Elffuss BraidHub

kikocis/VibeCodeViewer public

Stabilize rendering and add visual diagnostics
Changeset4116077e169baaa8b3573ef295929b349ad2ae9ca3a4450952484dff71f31274
AuthorSendery <sendery@gmail.com> · 2026-06-19 07:36 +02:00
CommitterSendery <sendery@gmail.com> · 2026-06-19 07:36 +02:00
Parents26f65a4fb4c5

Browse the files at this changeset

10 files changed

modified README.md +97 −7
@@ -2,8 +2,8 @@
22
33 Ciudad procedural de **edificios de cristal** (Three.js) que visualiza un
44 repositorio de código como una metrópolis estilo *hacker noventero*: wireframes
5-cian nítidos, suelo de placa de circuito impreso y bloom selectivo solo en lo
6-que se resalta — nada de neblina permanente.
5+cian nítidos, suelo de placa de circuito impreso y controles visuales para
6+subir el dramatismo sin depender del postprocesado HDR.
77
88 ## Mapeo repo → ciudad
99
@@ -38,11 +38,14 @@
3838
3939 ## Receta anti-difuminado
4040
41-1. Aristas finas con **colores HDR** en un único `LineSegments` (rangos de
42- color por nodo): el bloom (umbral 0.85) solo se dispara en lo resaltado.
41+1. Aristas finas en un único `LineSegments` (rangos de color por nodo), con
42+ color y opacidad ajustables desde **Settings**.
4343 2. Cristal **fresnel** de opacidad mínima (α ≈ 0.02 en el centro de la cara).
4444 3. Cero volúmenes aditivos permanentes: los rellenos solo existen mientras un
4545 nivel está encendido (pool de 10 cajas reutilizables).
46+4. Render directo por defecto: el antiguo composer HDR/bloom queda como modo
47+ experimental (`?bloom=1`) porque algunos drivers producen rectángulos
48+ negros screen-space al orbitar.
4649
4750 ## Extras
4851
@@ -64,6 +67,11 @@
6467 late suavemente.
6568 - **Sugerencias de búsqueda**: mientras escribes, todos los ficheros que
6669 casan parpadean en la ciudad y se resaltan en las fachadas de sus edificios.
70+- **Settings**: panel modal bajo `Reset Vista` con presets visuales y sliders
71+ persistentes para exposición, brillo, contraste, saturación, aristas,
72+ celdas, cristal, fachadas, rótulos, suelo y niebla. Incluye un toggle
73+ explícito para probar **Bloom HDR**; al cambiarlo recarga con/sin
74+ `?bloom=1`.
6775
6876 ## Modos de coloreado
6977
@@ -134,6 +142,48 @@
134142 los sótanos; opaco escribe profundidad y los **oculta de verdad** (desde
135143 debajo, en modo vuelo, se siguen viendo).
136144
145+## Ajustes visuales y bloom
146+
147+El botón **Settings** abre un panel con cuatro presets:
148+
149+- **Seguro**: valores base, render directo.
150+- **Neón**: más saturación y brillo, recomendado para recuperar impacto sin
151+ pasar por bloom.
152+- **Cine**: más contraste, niebla algo más densa y suelo menos dominante.
153+- **Intenso**: mayor exposición y potencia de aristas/celdas; es el preset más
154+ agresivo probado sin artefactos negros.
155+
156+Los sliders se aplican en caliente y se guardan en `localStorage` bajo
157+`vcc.visualSettings.v1`. El HUD indica si estás en `render directo` o en
158+`bloom ×N`.
159+
160+`?bloom=1` activa el pipeline `EffectComposer` + `UnrealBloomPass`. Se conserva
161+para experimentación, pero no es el modo por defecto: en algunas GPUs/drivers
162+ese render target HDR genera cuadros negros alineados a pantalla durante la
163+órbita. Para volver al modo estable, quita `bloom` de la URL o desmarca
164+**Bloom HDR** en Settings.
165+
166+## Diagnóstico GPU
167+
168+La detección se basa en el renderer WebGL real que entrega el navegador
169+(`WEBGL_debug_renderer_info` cuando está disponible). En Windows/WSLg o capas
170+virtualizadas puede aparecer como `D3D12 virtual`, `Mesa` o `Microsoft` aunque
171+el host tenga una NVIDIA; en ese caso la app lo trata como hardware acelerado,
172+pero no puede inventar la marca si WebGL la oculta.
173+
174+El arranque escribe en consola algo como:
175+
176+```text
177+[gpu] NVIDIA · nivel alta · renderer "ANGLE (...)" · vendor "..."
178+```
179+
180+Overrides útiles para depurar:
181+
182+- `?gpu=nvidia` fuerza etiqueta/perfil NVIDIA cuando el host sí tiene NVIDIA
183+ pero el navegador solo reporta una capa virtual.
184+- `?msaa=N` y `?pr=N` fuerzan multisampling de render target y pixel ratio.
185+- `?bloom=1` activa el composer HDR experimental.
186+
137187 ## Teclado en el árbol
138188
139189 Con el árbol enfocado (clic sobre él): `↑`/`↓` mueven el cursor, `→`
@@ -201,6 +251,41 @@
201251 node scan.mjs /otra/ruta # o cualquier otro árbol
202252 ```
203253
254+## Verificación visual automatizada
255+
256+Hay tres herramientas para grabar órbitas y detectar regresiones de cuadros
257+negros:
258+
259+```bash
260+# 1. Levanta la app y un Chromium con DevTools remoto.
261+./serve.sh 8137
262+chromium-browser --headless --disable-gpu-sandbox --no-sandbox \
263+ --remote-debugging-port=9223 --window-size=2048,1152 about:blank
264+
265+# 2. Captura una órbita con un tema/preset.
266+node tools/capture-orbit.mjs \
267+ --url=http://localhost:8137/ \
268+ --out=/tmp/vcc-orbit \
269+ --frames=120 --width=2048 --height=1152 --port=9223 --theme=matrix \
270+ --visuals='{"exposure":1.24,"brightness":1.08,"contrast":1.28,"saturate":1.65,"lines":1.22,"files":1.35,"glass":1.16,"facades":1.12,"labels":1.45,"ground":1.08,"fog":0.92}'
271+
272+# 3. Genera un vídeo opcional.
273+ffmpeg -y -framerate 30 -i /tmp/vcc-orbit/frame-%04d.png \
274+ -pix_fmt yuv420p /tmp/vcc-orbit.mp4
275+
276+# 4. Detecta cuadros negros en una órbita.
277+python3 tools/detect-black-rects.py /tmp/vcc-orbit
278+
279+# 5. Detecta el caso de una captura suelta, más sensible a ventanas negras.
280+python3 tools/detect-black-rects.py --scan-windows captura.png
281+
282+# 6. Compara un candidato contra un baseline estable.
283+python3 tools/compare-black-regressions.py /tmp/candidato /tmp/baseline
284+```
285+
286+`tools/detect-black-rects.py` usa Pillow/NumPy en lugar de OpenCV para no
287+añadir dependencias nuevas. Devuelve código 1 cuando encuentra frames malos.
288+
204289 ## Modo test: `./serve.sh --test N M [K]`
205290
206291 Genera un `src/data.js` sintético y determinista (`tools/gentest.mjs`) para
@@ -261,8 +346,9 @@
261346 | `W A S D` / ratón | mover · mirar (en vuelo) |
262347 | `Space`/`E` · `C`/`Q` | subir · bajar · `Shift` turbo |
263348 | `1` `2` `3` | Reset Vista · Vista Aérea · Vista Altura Edificios |
349+| `L` · `G` | leyenda · suelo opaco |
264350 | `X` · `/` | limpiar selección · enfocar el buscador |
265-| `Esc` | salir del vuelo / cerrar buscador |
351+| `Esc` | salir del vuelo / cerrar buscador / cerrar Settings |
266352
267353 ## Estructura
268354
@@ -274,7 +360,11 @@
274360 model.js jerarquía + layout (cajas anidadas, empaquetado urbano)
275361 builder.js escena: aristas HDR, cristal fresnel, fachadas, suelo PCB
276362 controls.js órbita + vuelo libre + vuelos de cámara
277- ui.js árbol lateral, buscador, ruta, stats
278- main.js selección jerárquica, raycast, bucle de render
363+ ui.js árbol lateral, buscador, ruta, stats, Settings
364+ main.js selección jerárquica, raycast, render y ajustes visuales
365+tools/
366+ capture-orbit.mjs captura órbitas vía Chrome DevTools Protocol
367+ detect-black-rects.py detector de cuadros negros en frames/capturas
368+ compare-black-regressions.py compara órbitas contra baseline visual
279369 vendor/ Three.js r160 + addons (offline)
280370 ```
modified index.html +30 −0
@@ -31,6 +31,7 @@
3131 <button id="btn-aerial">Vista Aérea</button>
3232 <button id="btn-skyline">Vista Altura Edificios</button>
3333 <button id="btn-reset">Reset Vista</button>
34+ <button id="btn-settings" onclick="window.VCCOpenSettings?.()">Settings</button>
3435 <button id="btn-legend">Leyenda</button>
3536 <button id="btn-ground">Suelo Opaco</button>
3637 <select id="theme-select" title="Tema de color"></select>
@@ -71,6 +72,35 @@
7172
7273 <div id="crosshair">+</div>
7374
75+ <div id="settings-modal" aria-hidden="true">
76+ <div id="settings-panel" role="dialog" aria-modal="true" aria-labelledby="settings-title">
77+ <div class="settings-head">
78+ <div id="settings-title" class="title">Settings</div>
79+ <button id="settings-close" title="Cerrar" onclick="window.VCCCloseSettings?.()">×</button>
80+ </div>
81+ <div id="settings-presets"></div>
82+ <div id="settings-controls"></div>
83+ <div class="settings-foot">
84+ <label class="check-row"><input id="setting-bloom" type="checkbox"> Bloom HDR</label>
85+ <button id="settings-reset">Reset Settings</button>
86+ </div>
87+ </div>
88+ </div>
89+
7490 <script type="module" src="src/main.js"></script>
91+ <script>
92+ window.VCCOpenSettings = () => {
93+ const modal = document.getElementById('settings-modal');
94+ if (!modal) return;
95+ modal.classList.add('show');
96+ modal.setAttribute('aria-hidden', 'false');
97+ };
98+ window.VCCCloseSettings = () => {
99+ const modal = document.getElementById('settings-modal');
100+ if (!modal) return;
101+ modal.classList.remove('show');
102+ modal.setAttribute('aria-hidden', 'true');
103+ };
104+ </script>
75105 </body>
76106 </html>
modified src/builder.js +64 −13
@@ -7,6 +7,16 @@
77 import * as THREE from 'three';
88
99 function lerp3(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; }
10+function configureCanvasTexture(tx) {
11+ tx.colorSpace = THREE.SRGBColorSpace;
12+ tx.anisotropy = 8;
13+ // Las texturas son texto fino sobre fondo transparente. Sin mipmaps, los
14+ // píxeles transparentes no se mezclan con negro al orbitar y solaparse.
15+ tx.generateMipmaps = false;
16+ tx.minFilter = THREE.LinearFilter;
17+ tx.magFilter = THREE.LinearFilter;
18+ return tx;
19+}
1020
1121 // 12 aristas de una caja → 24 vértices
1222 const EDGE_PAIRS = [
@@ -165,14 +175,14 @@
165175 const cv = document.createElement('canvas');
166176 cv.width = W; cv.height = H;
167177 building.facadeCanvas = cv;
168- const tx = new THREE.CanvasTexture(cv);
169- tx.colorSpace = THREE.SRGBColorSpace;
170- tx.anisotropy = 8;
178+ const tx = configureCanvasTexture(new THREE.CanvasTexture(cv));
171179 building.facadeTexture = tx;
172180 drawFacade(building, null, theme);
173181 const mat = new THREE.MeshBasicMaterial({
174- map: tx, transparent: true, depthWrite: false, side: THREE.FrontSide,
182+ map: tx, transparent: true, alphaTest: 0.025, depthWrite: false, side: THREE.FrontSide,
183+ blending: theme.light ? THREE.NormalBlending : THREE.AdditiveBlending,
175184 });
185+ mat.userData.vccKind = 'facade';
176186 const E = 0.14;
177187 const faces = [
178188 { w: b.sx, pos: [b.cx, b.cy, b.cz + b.sz / 2 + E], rot: 0 },
@@ -211,9 +221,7 @@
211221 g.globalAlpha = 0.92;
212222 g.shadowColor = color; g.shadowBlur = 16;
213223 g.fillText(text, pad + 80, y);
214- const tx = new THREE.CanvasTexture(cv);
215- tx.colorSpace = THREE.SRGBColorSpace;
216- tx.anisotropy = 8;
224+ const tx = configureCanvasTexture(new THREE.CanvasTexture(cv));
217225 return { tx, aspect: cv.width / cv.height };
218226 }
219227
@@ -227,10 +235,11 @@
227235 const mesh = new THREE.Mesh(
228236 new THREE.PlaneGeometry(w, w / aspect),
229237 new THREE.MeshBasicMaterial({
230- map: tx, transparent: true, depthWrite: false,
238+ map: tx, transparent: true, alphaTest: 0.025, depthWrite: false,
231239 blending: theme.light ? THREE.NormalBlending : THREE.AdditiveBlending,
232240 }),
233241 );
242+ mesh.material.userData.vccKind = 'label';
234243 if (flat) mesh.rotation.x = -Math.PI / 2;
235244 mesh.position.set(...pos);
236245 mesh.renderOrder = 4;
@@ -341,8 +350,10 @@
341350 const lineGeo = new THREE.BufferGeometry();
342351 lineGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
343352 lineGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
353+ lineGeo.computeBoundingSphere();
344354 // opacidad adaptativa: cuantas más cajas, más tenue cada arista
345355 const lineOpacity = Math.min(0.95, Math.max(0.4, Math.sqrt(4000 / Math.max(boxNodes.length, 1))));
356+ const lineBaseOpacity = lineOpacity;
346357 const lines = new THREE.LineSegments(lineGeo, new THREE.LineBasicMaterial({
347358 vertexColors: true, transparent: true, opacity: lineOpacity,
348359 blending: BLEND, depthWrite: false,
@@ -359,6 +370,7 @@
359370 const shells = [];
360371 for (const b of model.buildings) {
361372 const mat = glassMaterial(theme, cityDim, b.onlyBasement ? 1 : 0);
373+ mat.userData.baseDim = cityDim;
362374 const mesh = new THREE.Mesh(new THREE.BoxGeometry(b.box.sx, b.box.sy, b.box.sz), mat);
363375 mesh.position.set(b.box.cx, b.box.cy, b.box.cz);
364376 mesh.renderOrder = 1;
@@ -391,6 +403,7 @@
391403 m.setPosition(n.box.cx, n.box.cy - n.box.sy / 2, n.box.cz);
392404 slabs.setMatrixAt(i, m);
393405 });
406+ slabs.computeBoundingSphere();
394407 slabs.renderOrder = 1;
395408 group.add(slabs);
396409 }
@@ -400,6 +413,7 @@
400413 const fileMat = new THREE.MeshBasicMaterial({
401414 transparent: true, opacity: 0.9, depthWrite: false, blending: BLEND,
402415 });
416+ const fileBaseOpacity = fileMat.opacity;
403417 const filesMesh = new THREE.InstancedMesh(fileGeo, fileMat, model.files.length);
404418 {
405419 const m = new THREE.Matrix4();
@@ -411,6 +425,7 @@
411425 filesMesh.setColorAt(f.id, c.setRGB(...FILE_BASE));
412426 }
413427 filesMesh.instanceColor.needsUpdate = true;
428+ filesMesh.computeBoundingSphere();
414429 }
415430 filesMesh.renderOrder = 2;
416431 group.add(filesMesh);
@@ -588,26 +603,62 @@
588603 const legend = buildLegend(model, byArea, theme);
589604 group.add(legend);
590605
606+ let groundOpaque = false;
607+ const groundBaseOpacity = 0.8;
608+ let visualSettings = {};
609+ function setVisuals(v = {}) {
610+ visualSettings = { ...visualSettings, ...v };
611+ const linesMul = visualSettings.lines ?? 1;
612+ const filesMul = visualSettings.files ?? 1;
613+ const glassMul = visualSettings.glass ?? 1;
614+ const facadeMul = visualSettings.facades ?? 1;
615+ const labelMul = visualSettings.labels ?? 1;
616+ const groundMul = visualSettings.ground ?? 1;
617+
618+ lines.material.opacity = Math.min(1, lineBaseOpacity * linesMul);
619+ fileMat.opacity = Math.min(1, fileBaseOpacity * filesMul);
620+ if (!groundOpaque) ground.material.opacity = Math.min(1, groundBaseOpacity * groundMul);
621+
622+ for (const shell of shells) {
623+ const mat = shell.material;
624+ mat.uniforms.uDim.value = (mat.userData.baseDim ?? cityDim) * glassMul;
625+ }
626+ group.traverse((o) => {
627+ const mats = Array.isArray(o.material) ? o.material : [o.material];
628+ for (const mat of mats) {
629+ if (mat?.userData?.vccKind === 'facade') mat.opacity = Math.min(1, facadeMul);
630+ if (mat?.userData?.vccKind === 'label') mat.opacity = Math.min(1, labelMul);
631+ }
632+ });
633+ }
634+
591635 function dispose() {
592636 scene.remove(group);
637+ const geometries = new Set();
638+ const materials = new Set();
593639 group.traverse((o) => {
594- o.geometry?.dispose?.();
640+ if (o.geometry) geometries.add(o.geometry);
595641 for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
596- m?.map?.dispose?.();
597- m?.dispose?.();
642+ if (m) materials.add(m);
598643 }
599644 });
645+ for (const g of geometries) g.dispose();
646+ for (const m of materials) {
647+ m.map?.dispose?.();
648+ m.dispose();
649+ }
600650 }
601651
602652 return {
603653 group, lines, shells, filesMesh, ground, legend,
604- paintNode, paintFile, clearGlows, fillBoxes, dispose, setModeColors, setBlastBeams, tickBeams,
654+ paintNode, paintFile, clearGlows, fillBoxes, dispose, setModeColors, setBlastBeams, tickBeams, setVisuals,
605655 setLegend: (v) => { legend.visible = v; },
606656 // suelo opaco/translúcido. Opaco = escribe profundidad y se dibuja en la
607657 // pasada de opacos: oculta de verdad los sótanos (ficheros ignorados)
608658 setGroundOpaque: (v) => {
659+ groundOpaque = v;
609660 const m = ground.material;
610- m.opacity = v ? 1 : 0.8;
661+ m.opacity = v ? 1 : Math.min(1, groundBaseOpacity * (visualSettings.ground ?? 1));
611662 m.transparent = !v;
612663 m.depthWrite = v;
613664 m.needsUpdate = true;
modified src/gpu.js +50 −17
@@ -1,9 +1,14 @@
11 // Detección de la aceleración gráfica real del navegador.
22 // Lee el renderer sin máscara de WebGL (WEBGL_debug_renderer_info) y
33 // clasifica el hardware en niveles para adaptar la calidad del render:
4-// - alta: GPU discreta NVIDIA/AMD/Intel Arc o Apple Silicon (Metal)
5-// - media: integradas u origen desconocido (valores actuales del proyecto)
4+// - alta: GPU discreta NVIDIA/AMD/Intel Arc, Apple Silicon, D3D12/Mesa HW
5+// - media: integradas u origen desconocido
66 // - software: SwiftShader/llvmpipe → sin MSAA y resolución nativa 1:1
7+//
8+// El composer usa render targets HDR. En varios drivers produce artefactos
9+// rectangulares negros screen-space al orbitar, incluso sin MSAA. Por eso el
10+// render directo es el camino por defecto y bloom queda como opt-in con
11+// ?bloom=1 para depuración visual.
712
813 export function detectGPU(gl) {
914 let renderer = '', vendor = '';
@@ -14,36 +19,63 @@
1419 } catch { /* contexto perdido o cabeceras bloqueadas */ }
1520 const low = `${renderer} ${vendor}`.toLowerCase();
1621
17- const isSoftware = /swiftshader|llvmpipe|softpipe|software|basic render/.test(low);
18- const isNvidia = /nvidia|geforce|quadro|\brtx\b|\bgtx\b/.test(low);
22+ const isSoftware = /swiftshader|llvmpipe|softpipe|software|basic render|warp/.test(low);
23+ let isNvidia = /nvidia|geforce|quadro|\brtx\b|\bgtx\b/.test(low);
1924 // macOS: ANGLE sobre Metal reporta "Apple M1/M2/…" o el genérico "Apple GPU"
20- const isApple = /apple m\d|apple gpu|angle.*metal/.test(low)
25+ let isApple = /apple m\d|apple gpu|angle.*metal/.test(low)
2126 || (/apple/.test(low) && /mac/i.test(navigator.platform ?? ''));
22- const isAmd = /\bamd\b|radeon/.test(low);
23- const isIntelArc = /intel.*arc/.test(low);
27+ let isAmd = /\bamd\b|radeon/.test(low);
28+ let isIntelArc = /intel.*arc/.test(low);
29+ const isD3D12 = /d3d12|direct3d\s*12|dx12/.test(low);
30+ const isD3D11 = /d3d11|direct3d\s*11|dx11/.test(low);
31+ const isMesa = /mesa|zink|vulkan/.test(low);
32+ const isVirtual = /microsoft|wsl|virtual|parallels|vmware|virgl/.test(low);
33+ const isHardwareBridge = !isSoftware && (isD3D12 || isD3D11 || isMesa);
2434
2535 let tier = 'media';
2636 if (isSoftware) tier = 'software';
27- else if (isNvidia || isApple || isAmd || isIntelArc) tier = 'alta';
37+ else if (isNvidia || isApple || isAmd || isIntelArc || isHardwareBridge) tier = 'alta';
38+
39+ let brand = 'desconocida';
40+ if (isNvidia) brand = 'NVIDIA';
41+ else if (isAmd) brand = 'AMD';
42+ else if (isIntelArc) brand = 'Intel Arc';
43+ else if (isApple) brand = 'Apple';
44+ else if (isD3D12) brand = isVirtual ? 'D3D12 virtual' : 'D3D12';
45+ else if (isD3D11) brand = isVirtual ? 'D3D11 virtual' : 'D3D11';
46+ else if (isMesa) brand = isVirtual ? 'Mesa virtual' : 'Mesa';
47+ else if (tier === 'alta') brand = 'discreta';
2848
2949 let maxSamples = 4;
3050 try { maxSamples = gl.getParameter(gl.MAX_SAMPLES) ?? 4; } catch { /* WebGL1 */ }
3151
32- // MSAA ×8 + HalfFloat + pixelRatio 3 corrompía el render en algunas GPUs
33- // discretas (regiones negras y geometría estirada según el ángulo de
34- // cámara: el driver no aguanta render targets multisample tan grandes).
35- // Techo conservador conocido-bueno: ×4 y ratio ≤2; el render software
36- // baja a 1:1 sin multisampling. Overrides para depurar: ?msaa=N&pr=N
52+ // Overrides para depurar: ?gpu=nvidia|amd|apple|arc|discreta|software&msaa=N&pr=N&bloom=1
3753 const params = new URLSearchParams(window.location?.search ?? '');
38- const ovMsaa = params.get('msaa'), ovPr = params.get('pr');
54+ const ovGpu = (params.get('gpu') || '').toLowerCase();
55+ const ovMsaa = params.get('msaa'), ovPr = params.get('pr'), ovBloom = params.get('bloom');
56+ if (ovGpu) {
57+ isNvidia = /nvidia|geforce|rtx|gtx/.test(ovGpu);
58+ isAmd = /amd|radeon/.test(ovGpu);
59+ isApple = /apple|metal/.test(ovGpu);
60+ isIntelArc = /arc/.test(ovGpu);
61+ if (isNvidia) brand = 'NVIDIA';
62+ else if (isAmd) brand = 'AMD';
63+ else if (isIntelArc) brand = 'Intel Arc';
64+ else if (isApple) brand = 'Apple';
65+ else if (/software|swiftshader|llvmpipe/.test(ovGpu)) brand = 'software';
66+ else brand = 'discreta';
67+ tier = /software|swiftshader|llvmpipe/.test(ovGpu) ? 'software' : /media|integrada/.test(ovGpu) ? 'media' : 'alta';
68+ }
3969
4070 const profile = {
4171 name: renderer || 'GPU desconocida',
42- tier, isNvidia, isApple,
72+ vendor: vendor || 'Proveedor desconocido',
73+ tier, brand, isNvidia, isApple, isAmd, isIntelArc, isD3D12, isD3D11, isMesa, isVirtual,
74+ override: ovGpu || '',
4375 webgpu: 'gpu' in navigator,
4476 pixelRatioCap: tier === 'software' ? 1 : 2,
45- msaaSamples: tier === 'software' ? 0 : Math.min(4, maxSamples),
46- bloom: tier !== 'software',
77+ msaaSamples: 0,
78+ bloom: false,
4779 };
4880 if (ovMsaa !== null && ovMsaa !== '') {
4981 profile.msaaSamples = Math.max(0, Math.min(+ovMsaa || 0, maxSamples));
@@ -51,5 +83,6 @@
5183 if (ovPr !== null && ovPr !== '') {
5284 profile.pixelRatioCap = Math.max(0.5, Math.min(+ovPr || 1, 4));
5385 }
86+ if (ovBloom !== null) profile.bloom = ovBloom !== '0';
5487 return profile;
5588 }
modified src/main.js +110 −23
@@ -14,40 +14,81 @@
1414 import { detectGPU } from './gpu.js';
1515 import { THEMES } from './themes.js';
1616
17+const VISUAL_STORAGE_KEY = 'vcc.visualSettings.v1';
18+const DEFAULT_VISUAL_SETTINGS = {
19+ exposure: 1.05,
20+ brightness: 1,
21+ contrast: 1,
22+ saturate: 1,
23+ lines: 1,
24+ files: 1,
25+ glass: 1,
26+ facades: 1,
27+ labels: 1,
28+ ground: 1,
29+ fog: 1,
30+};
31+
32+function loadVisualSettings() {
33+ try {
34+ return { ...DEFAULT_VISUAL_SETTINGS, ...JSON.parse(localStorage.getItem(VISUAL_STORAGE_KEY) || '{}') };
35+ } catch {
36+ return { ...DEFAULT_VISUAL_SETTINGS };
37+ }
38+}
39+
40+let visualSettings = loadVisualSettings();
41+
1742 // ── base persistente (renderer, cámara, composer) ─────────────────────────
1843 // powerPreference fuerza la GPU discreta en portátiles con doble gráfica
1944 const canvas = document.getElementById('view');
2045 const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
2146 const gpu = detectGPU(renderer.getContext());
22-console.info(`[gpu] ${gpu.name} · nivel ${gpu.tier} · MSAA ×${gpu.msaaSamples} · pixelRatio ≤${gpu.pixelRatioCap}${gpu.webgpu ? ' · WebGPU disponible' : ''}`);
47+console.info(`[gpu] ${gpu.brand} · nivel ${gpu.tier} · renderer "${gpu.name}" · vendor "${gpu.vendor}" · bloom ${gpu.bloom ? 'on' : 'off'} · MSAA RT ×${gpu.msaaSamples} · pixelRatio ≤${gpu.pixelRatioCap}${gpu.override ? ` · override ${gpu.override}` : ''}${gpu.webgpu ? ' · WebGPU disponible' : ''}`);
2348 renderer.setPixelRatio(Math.min(window.devicePixelRatio, gpu.pixelRatioCap));
2449 renderer.toneMapping = THREE.ACESFilmicToneMapping;
25-renderer.toneMappingExposure = 1.05;
50+renderer.toneMappingExposure = visualSettings.exposure;
51+renderer.setClearColor(0x020309, 1);
2652
2753 const scene = new THREE.Scene();
2854 scene.background = new THREE.Color(0x020309);
2955 const camera = new THREE.PerspectiveCamera(55, 1, 0.1, 1000);
3056
31-// el antialias del canvas no aplica al renderizar vía composer: sin MSAA
32-// en el render target, las aristas de 1px parpadean con el bloom al mover
33-// la cámara (aliasing temporal). HalfFloat para conservar los colores HDR.
34-// Las muestras se adaptan a la GPU detectada (×8 en discretas/Apple Silicon,
35-// 0 en render software).
36-const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(1, 1, {
37- type: THREE.HalfFloatType,
38- samples: gpu.msaaSamples,
39-}));
40-composer.addPass(new RenderPass(scene, camera));
41-const bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), 0.65, 0.25, 0.85);
42-bloom.enabled = gpu.bloom;
43-composer.addPass(bloom);
44-composer.addPass(new OutputPass());
57+function createRenderPipeline() {
58+ if (!gpu.bloom) {
59+ return {
60+ bloom: { strength: 0, threshold: 1, resolution: new THREE.Vector2(1, 1) },
61+ resize: () => {},
62+ render: () => renderer.render(scene, camera),
63+ };
64+ }
65+
66+ const target = new THREE.WebGLRenderTarget(1, 1, {
67+ type: THREE.HalfFloatType,
68+ samples: gpu.msaaSamples,
69+ });
70+ target.texture.name = 'VCC.composer';
71+ const composer = new EffectComposer(renderer, target);
72+ composer.addPass(new RenderPass(scene, camera));
73+ const bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), 0.65, 0.25, 0.85);
74+ composer.addPass(bloom);
75+ composer.addPass(new OutputPass());
76+ return {
77+ bloom,
78+ resize: (w, h) => {
79+ composer.setSize(w, h);
80+ bloom.resolution.set(w, h);
81+ },
82+ render: () => composer.render(),
83+ };
84+}
85+const pipeline = createRenderPipeline();
86+const bloom = pipeline.bloom;
4587
4688 function resize() {
4789 const w = window.innerWidth, h = window.innerHeight;
4890 renderer.setSize(w, h, false);
49- composer.setSize(w, h);
50- bloom.resolution.set(w, h);
91+ pipeline.resize(w, h);
5192 camera.aspect = w / h;
5293 camera.updateProjectionMatrix();
5394 }
@@ -59,6 +100,33 @@
59100 let groundSolid = false;
60101 let colorMode = 'basic';
61102 let themeName = 'hacker';
103+let fogBaseDensity = 0;
104+
105+function applyVisualSettings(next, { persist = true } = {}) {
106+ visualSettings = next === null
107+ ? { ...DEFAULT_VISUAL_SETTINGS }
108+ : { ...visualSettings, ...next };
109+ for (const k of Object.keys(DEFAULT_VISUAL_SETTINGS)) {
110+ visualSettings[k] = Number.isFinite(+visualSettings[k]) ? +visualSettings[k] : DEFAULT_VISUAL_SETTINGS[k];
111+ }
112+ renderer.toneMappingExposure = visualSettings.exposure;
113+ canvas.style.filter = [
114+ `brightness(${visualSettings.brightness})`,
115+ `contrast(${visualSettings.contrast})`,
116+ `saturate(${visualSettings.saturate})`,
117+ ].join(' ');
118+ if (scene.fog && fogBaseDensity) scene.fog.density = fogBaseDensity * visualSettings.fog;
119+ city?.setVisuals?.(visualSettings);
120+ if (persist) localStorage.setItem(VISUAL_STORAGE_KEY, JSON.stringify(visualSettings));
121+ return { ...visualSettings };
122+}
123+
124+function setBloomMode(enabled) {
125+ const url = new URL(location.href);
126+ if (enabled) url.searchParams.set('bloom', '1');
127+ else url.searchParams.delete('bloom');
128+ location.assign(url);
129+}
62130
63131 // aplica la parte "barata" del tema: escena, bloom y variables CSS de la UI
64132 function setSceneTheme(t) {
@@ -79,6 +147,7 @@
79147 city = buildCity(scene, model, t);
80148 city.setLegend(legendOn);
81149 city.setGroundOpaque(groundSolid);
150+ city.setVisuals(visualSettings);
82151 }
83152
84153 function boot(packedTree, meta) {
@@ -94,7 +163,8 @@
94163
95164 model = buildModel(packedTree, meta);
96165 const extent = Math.max(model.city.box.sx, model.city.box.sz);
97- scene.fog = new THREE.FogExp2(THEMES[themeName].fog, 0.62 / extent);
166+ fogBaseDensity = 0.62 / extent;
167+ scene.fog = new THREE.FogExp2(THEMES[themeName].fog, fogBaseDensity * visualSettings.fog);
98168 camera.far = extent * 14;
99169 camera.updateProjectionMatrix();
100170
@@ -107,7 +177,7 @@
107177 ui.setModeAvailable('blast',
108178 Object.keys(model.linksOut).length > 0 || Object.keys(model.symOut).length > 0);
109179 applyColorMode('basic');
110- window.VCC = { model, city, nav, camera, selectFile, selectNode, clearSelection, applyColorMode, applyTheme };
180+ window.VCC = { model, city, nav, camera, selectFile, selectNode, clearSelection, applyColorMode, applyTheme, applyVisualSettings };
111181 }
112182
113183 // cambia de tema reconstruyendo solo la ciudad (modelo y cámara intactos)
@@ -315,6 +385,7 @@
315385
316386 canvas.addEventListener('pointermove', (e) => {
317387 pointer.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);
388+ hoverDirty = true;
318389 });
319390
320391 function pick() {
@@ -325,8 +396,13 @@
325396 return { fileHit, shellHit };
326397 }
327398
328-function updateHover() {
399+let hoverDirty = true;
400+let lastHoverAt = 0;
401+function updateHover(now) {
329402 if (selectedFile) return;
403+ if (!nav.fly.active && !hoverDirty && now - lastHoverAt < 50) return;
404+ hoverDirty = false;
405+ lastHoverAt = now;
330406 // solo carcasas: raycast contra cientos de miles de celdas por frame no escala
331407 if (nav.fly.active) raycaster.setFromCamera(new THREE.Vector2(0, 0), camera);
332408 else raycaster.setFromCamera(pointer, camera);
@@ -413,6 +489,11 @@
413489 onToggleLegend: (on) => { legendOn = on; city.setLegend(on); },
414490 onToggleGround: (solid) => { groundSolid = solid; city.setGroundOpaque(solid); },
415491 onTheme: (name) => applyTheme(name),
492+ getVisualSettings: () => ({ ...visualSettings }),
493+ onVisualSettings: (settings) => applyVisualSettings(settings),
494+ onVisualPreset: (settings) => applyVisualSettings(settings),
495+ onBloomMode: (enabled) => setBloomMode(enabled),
496+ isBloomEnabled: () => gpu.bloom,
416497 onMode: (mode) => applyColorMode(mode),
417498 onPickFolder: () => loadScan(pickAndScanFolder),
418499 onReopenFolder: () => loadScan(reopenLastFolder),
@@ -425,14 +506,20 @@
425506 // ── arranque + bucle ──────────────────────────────────────────────────────
426507 boot(REPO_TREE, REPO_META);
427508 resize();
509+applyVisualSettings(visualSettings, { persist: false });
428510
429511 let last = performance.now();
430512 let fpsAcc = 0, fpsN = 0;
431513 function frame(now) {
514+ if (document.hidden) {
515+ last = now;
516+ requestAnimationFrame(frame);
517+ return;
518+ }
432519 const dt = Math.min(0.05, (now - last) / 1000);
433520 last = now;
434521 nav.update(dt);
435- updateHover();
522+ updateHover(now);
436523
437524 // pulse de los barrios encendidos
438525 for (const p of pulsers) {
@@ -446,7 +533,7 @@
446533 // pulsos de datos por los haces del modo Blast
447534 city.tickBeams(now);
448535
449- composer.render();
536+ pipeline.render();
450537 fpsAcc += dt; fpsN++;
451538 if (fpsAcc >= 0.5) {
452539 ui.setStats(Math.round(fpsN / fpsAcc));
modified src/styles.css +112 −11
@@ -15,14 +15,18 @@
1515 font-family: "JetBrains Mono", "Cascadia Code", "Fira Code", monospace;
1616 color: var(--text);
1717 font-size: 13px;
18+ text-rendering: geometricPrecision;
1819 }
1920
20-#view { position: fixed; inset: 0; width: 100%; height: 100%; display: block; }
21+#view {
22+ position: fixed; inset: 0; width: 100%; height: 100%; display: block;
23+ background: #020309;
24+}
2125
2226 .title {
2327 color: var(--cyan);
2428 font-size: 11px;
25- letter-spacing: 0.18em;
29+ letter-spacing: 0;
2630 text-transform: uppercase;
2731 margin-bottom: 8px;
2832 }
@@ -50,7 +54,7 @@
5054 padding: 8px 18px;
5155 cursor: pointer;
5256 text-align: left;
53- backdrop-filter: blur(4px);
57+ backdrop-filter: blur(10px) saturate(1.25);
5458 transition: border-color 0.15s, color 0.15s, box-shadow 0.15s;
5559 }
5660 #view-buttons button:hover {
@@ -60,6 +64,7 @@
6064 }
6165 #view-buttons button.off { color: rgba(140, 195, 210, 0.4); border-style: dashed; }
6266 #view-buttons button:disabled { color: rgba(140, 195, 210, 0.5); cursor: progress; }
67+#view-buttons #btn-settings { border-color: rgba(46, 230, 255, 0.35); }
6368 #view-buttons select {
6469 font: inherit;
6570 color: var(--text);
@@ -68,7 +73,7 @@
6873 border-radius: 4px;
6974 padding: 8px 12px;
7075 cursor: pointer;
71- backdrop-filter: blur(4px);
76+ backdrop-filter: blur(10px) saturate(1.25);
7277 }
7378 #view-buttons select:hover { border-color: var(--cyan); }
7479 #view-buttons select option { background: #04121a; color: var(--text); }
@@ -83,7 +88,8 @@
8388 border: 1px solid var(--panel-border);
8489 border-radius: 6px;
8590 overflow: hidden;
86- backdrop-filter: blur(4px);
91+ backdrop-filter: blur(10px) saturate(1.25);
92+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
8793 }
8894 #mode-switch button {
8995 font: inherit;
@@ -93,7 +99,7 @@
9399 border-right: 1px solid var(--panel-border);
94100 padding: 8px 20px;
95101 cursor: pointer;
96- letter-spacing: 0.06em;
102+ letter-spacing: 0;
97103 }
98104 #mode-switch button:last-child { border-right: none; }
99105 #mode-switch button:focus { outline: none; }
@@ -122,7 +128,7 @@
122128 border: 1px solid var(--panel-border);
123129 border-radius: 6px;
124130 padding: 10px 14px;
125- backdrop-filter: blur(4px);
131+ backdrop-filter: blur(10px) saturate(1.25);
126132 font-size: 11.5px;
127133 max-height: 38vh; overflow-y: auto;
128134 }
@@ -157,7 +163,8 @@
157163 border: 1px solid var(--panel-border);
158164 border-radius: 6px;
159165 padding: 12px;
160- backdrop-filter: blur(4px);
166+ backdrop-filter: blur(10px) saturate(1.25);
167+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
161168 }
162169 #search-input {
163170 width: 100%;
@@ -193,7 +200,8 @@
193200 border: 1px solid var(--panel-border);
194201 border-radius: 6px;
195202 padding: 12px 0 6px;
196- backdrop-filter: blur(4px);
203+ backdrop-filter: blur(10px) saturate(1.25);
204+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.18);
197205 }
198206 #tree-panel .title { padding: 0 12px; }
199207 #tree { overflow-y: auto; flex: 1; }
@@ -234,7 +242,7 @@
234242 border: 1px solid var(--panel-border);
235243 border-radius: 6px;
236244 padding: 9px 14px;
237- backdrop-filter: blur(4px);
245+ backdrop-filter: blur(10px) saturate(1.25);
238246 overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
239247 }
240248 #pathbar .sep { color: rgba(46, 230, 255, 0.4); margin: 0 4px; }
@@ -255,12 +263,105 @@
255263 border: 1px solid var(--panel-border);
256264 border-radius: 6px;
257265 padding: 12px 14px;
258- backdrop-filter: blur(4px);
266+ backdrop-filter: blur(10px) saturate(1.25);
259267 font-size: 11.5px;
260268 }
261269 #help td { padding: 1.5px 0; color: rgba(170, 220, 235, 0.75); }
262270 #help td:first-child { color: var(--cyan); padding-right: 14px; }
263271
272+/* ── settings ─────────────────────────────────────────── */
273+#settings-modal {
274+ position: fixed; inset: 0;
275+ display: none;
276+ align-items: center; justify-content: center;
277+ background: rgba(0, 0, 0, 0.28);
278+ z-index: 20;
279+}
280+#settings-modal.show { display: flex; }
281+#settings-panel {
282+ width: min(560px, calc(100vw - 32px));
283+ max-height: min(760px, calc(100vh - 32px));
284+ overflow: auto;
285+ background: var(--panel-bg);
286+ border: 1px solid var(--panel-border);
287+ border-radius: 6px;
288+ padding: 16px;
289+ backdrop-filter: blur(14px) saturate(1.35);
290+ box-shadow: 0 20px 80px rgba(0, 0, 0, 0.42);
291+}
292+.settings-head {
293+ display: flex; align-items: center; justify-content: space-between;
294+ margin-bottom: 10px;
295+}
296+#settings-close {
297+ width: 28px; height: 28px;
298+ border: 1px solid var(--panel-border);
299+ border-radius: 4px;
300+ color: var(--text);
301+ background: transparent;
302+ font: inherit;
303+ cursor: pointer;
304+}
305+#settings-presets {
306+ display: grid;
307+ grid-template-columns: repeat(4, minmax(0, 1fr));
308+ gap: 8px;
309+ margin-bottom: 12px;
310+}
311+#settings-presets button,
312+#settings-reset {
313+ font: inherit;
314+ color: var(--text);
315+ background: rgba(8, 22, 32, 0.62);
316+ border: 1px solid var(--panel-border);
317+ border-radius: 4px;
318+ padding: 8px 10px;
319+ cursor: pointer;
320+}
321+#settings-controls {
322+ display: grid;
323+ grid-template-columns: 1fr 1fr;
324+ gap: 10px 16px;
325+}
326+.setting-row {
327+ display: grid;
328+ grid-template-columns: 92px 1fr 42px;
329+ align-items: center;
330+ gap: 8px;
331+ color: var(--text);
332+}
333+.setting-row input[type="range"] {
334+ width: 100%;
335+ accent-color: var(--cyan);
336+}
337+.setting-row output {
338+ color: rgba(170, 220, 235, 0.72);
339+ text-align: right;
340+ font-size: 11px;
341+}
342+.settings-foot {
343+ display: flex; align-items: center; justify-content: space-between;
344+ gap: 12px;
345+ margin-top: 14px;
346+ padding-top: 12px;
347+ border-top: 1px solid var(--panel-border);
348+}
349+.check-row {
350+ display: inline-flex; align-items: center; gap: 8px;
351+ color: var(--text);
352+}
353+.check-row input { accent-color: var(--cyan); }
354+body.light #settings-presets button,
355+body.light #settings-reset {
356+ background: rgba(255, 255, 255, 0.72);
357+ color: #143a40;
358+}
359+
360+@media (max-width: 720px) {
361+ #settings-controls { grid-template-columns: 1fr; }
362+ #settings-presets { grid-template-columns: repeat(2, minmax(0, 1fr)); }
363+}
364+
264365 /* ── modo vuelo ────────────────────────────────────────── */
265366 #crosshair {
266367 position: fixed; left: 50%; top: 50%;
modified src/ui.js +91 −5
@@ -217,11 +217,12 @@
217217 if (!t.includes('*') && !t.includes('?')) {
218218 return (f) => f.path.toLowerCase().includes(t);
219219 }
220+ const globstar = '__DOUBLE_STAR__';
220221 const body = t
221222 .replace(/[.+^${}()|[\]\\]/g, '\\$&')
222- .replace(/\*\*/g, '')
223+ .replace(/\*\*/g, globstar)
223224 .replace(/\*/g, '[^/]*')
224- .replace(//g, '.*')
225+ .replace(new RegExp(globstar, 'g'), '.*')
225226 .replace(/\?/g, '[^/]');
226227 // ancla a final de nombre/ruta y a límite de segmento: «*.js» casa con
227228 // cualquier fichero .js, «src/*.css» con los css directos de un src/
@@ -288,6 +289,7 @@
288289 $('btn-aerial').addEventListener('click', () => cb.onView?.('aerial'));
289290 $('btn-skyline').addEventListener('click', () => cb.onView?.('skyline'));
290291 $('btn-reset').addEventListener('click', () => cb.onView?.('reset'));
292+ $('btn-settings').addEventListener('click', () => openSettings());
291293 const legendBtn = $('btn-legend');
292294 let legendOn = true;
293295 legendBtn.addEventListener('click', () => {
@@ -322,6 +324,89 @@
322324 }
323325 themeSel.addEventListener('change', () => { cb.onTheme?.(themeSel.value); themeSel.blur(); });
324326
327+ // ── panel de ajustes visuales ──────────────────────────────────────
328+ const settingsModal = $('settings-modal');
329+ const settingsControls = $('settings-controls');
330+ const settingsPresets = $('settings-presets');
331+ const bloomBox = $('setting-bloom');
332+ const settingsClose = $('settings-close');
333+ const settingsReset = $('settings-reset');
334+ const sliderDefs = [
335+ ['exposure', 'Exposición', 0.65, 1.8, 0.01],
336+ ['brightness', 'Brillo', 0.75, 1.45, 0.01],
337+ ['contrast', 'Contraste', 0.8, 1.8, 0.01],
338+ ['saturate', 'Saturación', 0.6, 2.4, 0.01],
339+ ['lines', 'Aristas', 0.45, 2.2, 0.01],
340+ ['files', 'Celdas', 0.45, 2.4, 0.01],
341+ ['glass', 'Cristal', 0.35, 2.2, 0.01],
342+ ['facades', 'Fachadas', 0.2, 1.8, 0.01],
343+ ['labels', 'Rótulos', 0.2, 2.4, 0.01],
344+ ['ground', 'Suelo', 0.25, 1.5, 0.01],
345+ ['fog', 'Niebla', 0.35, 1.8, 0.01],
346+ ];
347+ const presets = {
348+ Seguro: null,
349+ Neón: { exposure: 1.24, brightness: 1.08, contrast: 1.28, saturate: 1.65, lines: 1.22, files: 1.35, glass: 1.16, facades: 1.12, labels: 1.45, ground: 1.08, fog: 0.92 },
350+ Cine: { exposure: 1.12, brightness: 0.98, contrast: 1.45, saturate: 1.28, lines: 1.05, files: 1.18, glass: 0.95, facades: 1.05, labels: 1.25, ground: 0.82, fog: 1.22 },
351+ Intenso: { exposure: 1.34, brightness: 1.12, contrast: 1.55, saturate: 2.0, lines: 1.55, files: 1.75, glass: 1.35, facades: 1.35, labels: 1.85, ground: 1.18, fog: 0.78 },
352+ };
353+ const settingInputs = new Map();
354+
355+ function syncSettings(v) {
356+ for (const [key] of sliderDefs) {
357+ const input = settingInputs.get(key);
358+ const value = v?.[key];
359+ if (input && value !== undefined) {
360+ input.value = value;
361+ input.nextElementSibling.textContent = Number(value).toFixed(2);
362+ }
363+ }
364+ bloomBox.checked = cb.isBloomEnabled?.() ?? false;
365+ }
366+
367+ for (const [name, values] of Object.entries(presets)) {
368+ const btn = document.createElement('button');
369+ btn.type = 'button';
370+ btn.textContent = name;
371+ btn.addEventListener('click', () => {
372+ const next = cb.onVisualPreset?.(values);
373+ syncSettings(next);
374+ });
375+ settingsPresets.appendChild(btn);
376+ }
377+
378+ for (const [key, label, min, max, step] of sliderDefs) {
379+ const row = document.createElement('label');
380+ row.className = 'setting-row';
381+ row.innerHTML = `<span>${label}</span><input type="range" min="${min}" max="${max}" step="${step}"><output></output>`;
382+ const input = row.querySelector('input');
383+ const output = row.querySelector('output');
384+ input.addEventListener('input', () => {
385+ output.textContent = Number(input.value).toFixed(2);
386+ cb.onVisualSettings?.({ [key]: Number(input.value) });
387+ });
388+ settingInputs.set(key, input);
389+ settingsControls.appendChild(row);
390+ }
391+ bloomBox.addEventListener('change', () => cb.onBloomMode?.(bloomBox.checked));
392+ settingsReset.addEventListener('click', () => syncSettings(cb.onVisualPreset?.(null)));
393+ settingsClose.addEventListener('click', closeSettings);
394+ settingsModal.addEventListener('click', (e) => { if (e.target === settingsModal) closeSettings(); });
395+ document.addEventListener('keydown', (e) => {
396+ if (e.key === 'Escape' && settingsModal.classList.contains('show')) closeSettings();
397+ });
398+ function openSettings() {
399+ syncSettings(cb.getVisualSettings?.());
400+ settingsModal.classList.add('show');
401+ settingsModal.setAttribute('aria-hidden', 'false');
402+ }
403+ function closeSettings() {
404+ settingsModal.classList.remove('show');
405+ settingsModal.setAttribute('aria-hidden', 'true');
406+ }
407+ window.VCCOpenSettings = openSettings;
408+ window.VCCCloseSettings = closeSettings;
409+
325410 // ── selector de modo de coloreado ───────────────────────────────────
326411 const modeBtns = [...document.querySelectorAll('#mode-switch button')];
327412 for (const btn of modeBtns) {
@@ -372,9 +457,10 @@
372457 let gpuLabel = '';
373458 function setGpu(gpu) {
374459 if (!gpu) { gpuLabel = ''; return; }
375- if (gpu.tier === 'software') gpuLabel = ' · render software';
376- else if (gpu.tier === 'alta') gpuLabel = ` · GPU ${gpu.isNvidia ? 'NVIDIA' : gpu.isApple ? 'Apple' : 'discreta'} ×${gpu.msaaSamples}`;
377- else gpuLabel = '';
460+ const mode = gpu.bloom ? `bloom ×${gpu.msaaSamples}` : 'render directo';
461+ if (gpu.tier === 'software') gpuLabel = ` · render software · ${mode}`;
462+ else if (gpu.tier === 'alta') gpuLabel = ` · GPU ${gpu.brand || 'discreta'} · ${mode}`;
463+ else gpuLabel = ` · ${mode}`;
378464 }
379465 // progreso del análisis perezoso del modo Blast (lotes en segundo plano)
380466 let analysisLabel = '';
added tools/capture-orbit.mjs +95 −0
@@ -0,0 +1,95 @@
1+#!/usr/bin/env node
2+import { mkdirSync, writeFileSync } from 'node:fs';
3+import { join } from 'node:path';
4+
5+const args = new Map();
6+for (let i = 2; i < process.argv.length; i++) {
7+ const raw = process.argv[i];
8+ const eq = raw.indexOf('=');
9+ const k = eq === -1 ? raw : raw.slice(0, eq);
10+ const v = eq === -1 ? '1' : raw.slice(eq + 1);
11+ args.set(k.replace(/^--/, ''), v);
12+}
13+
14+const url = args.get('url') ?? 'http://localhost:8137/?theme=matrix&bloom=1';
15+const outDir = args.get('out') ?? '/tmp/vcc-orbit';
16+const frames = Number(args.get('frames') ?? 120);
17+const width = Number(args.get('width') ?? 2048);
18+const height = Number(args.get('height') ?? 1152);
19+const port = Number(args.get('port') ?? 9222);
20+const radius = Number(args.get('radius') ?? 0.82);
21+const elevation = Number(args.get('elevation') ?? 0.34);
22+const theme = args.get('theme') ?? 'matrix';
23+const visuals = args.get('visuals') ? JSON.parse(args.get('visuals')) : null;
24+
25+mkdirSync(outDir, { recursive: true });
26+
27+async function json(url, init) {
28+ const r = await fetch(url, init);
29+ if (!r.ok) throw new Error(`${r.status} ${r.statusText}: ${await r.text()}`);
30+ return r.json();
31+}
32+
33+const target = await json(`http://127.0.0.1:${port}/json/new?${encodeURIComponent(url)}`, { method: 'PUT' });
34+const ws = new WebSocket(target.webSocketDebuggerUrl);
35+let nextId = 0;
36+const pending = new Map();
37+
38+ws.addEventListener('message', (ev) => {
39+ const msg = JSON.parse(ev.data);
40+ if (!msg.id || !pending.has(msg.id)) return;
41+ const { resolve, reject } = pending.get(msg.id);
42+ pending.delete(msg.id);
43+ msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result);
44+});
45+
46+await new Promise((resolve) => ws.addEventListener('open', resolve, { once: true }));
47+
48+function send(method, params = {}) {
49+ return new Promise((resolve, reject) => {
50+ const id = ++nextId;
51+ pending.set(id, { resolve, reject });
52+ ws.send(JSON.stringify({ id, method, params }));
53+ });
54+}
55+
56+await send('Page.enable');
57+await send('Runtime.enable');
58+await send('Emulation.setDeviceMetricsOverride', {
59+ width, height, deviceScaleFactor: 1, mobile: false,
60+});
61+
62+await new Promise((resolve) => setTimeout(resolve, 1800));
63+await send('Runtime.evaluate', {
64+ expression: `window.VCC?.applyTheme?.(${JSON.stringify(theme)})`,
65+});
66+if (visuals) {
67+ await send('Runtime.evaluate', {
68+ expression: `window.VCC?.applyVisualSettings?.(${JSON.stringify(visuals)}, { persist: false })`,
69+ });
70+}
71+await new Promise((resolve) => setTimeout(resolve, 300));
72+
73+for (let i = 0; i < frames; i++) {
74+ const angle = i * Math.PI * 2 / frames;
75+ await send('Runtime.evaluate', {
76+ expression: `(() => {
77+ const { camera, model, nav } = window.VCC;
78+ const b = model.city.box;
79+ const e = Math.max(b.sx, b.sz);
80+ const r = e * ${radius};
81+ const cx = b.cx, cz = b.cz, cy = Math.max(8, e * 0.16);
82+ camera.position.set(cx + Math.cos(${angle}) * r, e * ${elevation}, cz + Math.sin(${angle}) * r);
83+ nav.orbit.target.set(cx, cy, cz);
84+ camera.lookAt(nav.orbit.target);
85+ nav.orbit.update();
86+ return true;
87+ })()`,
88+ });
89+ await new Promise((resolve) => setTimeout(resolve, 45));
90+ const shot = await send('Page.captureScreenshot', { format: 'png', fromSurface: true });
91+ writeFileSync(join(outDir, `frame-${String(i).padStart(4, '0')}.png`), Buffer.from(shot.data, 'base64'));
92+ if ((i + 1) % 20 === 0 || i + 1 === frames) console.log(`captured ${i + 1}/${frames}`);
93+}
94+
95+ws.close();
added tools/compare-black-regressions.py +92 −0
@@ -0,0 +1,92 @@
1+#!/usr/bin/env python3
2+import argparse
3+import json
4+from pathlib import Path
5+
6+import numpy as np
7+from PIL import Image, ImageDraw
8+
9+
10+def components(mask):
11+ h, w = mask.shape
12+ seen = np.zeros_like(mask, dtype=bool)
13+ out = []
14+ for y0, x0 in np.argwhere(mask & ~seen):
15+ if seen[y0, x0]:
16+ continue
17+ stack = [(int(y0), int(x0))]
18+ seen[y0, x0] = True
19+ area = 0
20+ minx = maxx = int(x0)
21+ miny = maxy = int(y0)
22+ while stack:
23+ y, x = stack.pop()
24+ area += 1
25+ minx = min(minx, x); maxx = max(maxx, x)
26+ miny = min(miny, y); maxy = max(maxy, y)
27+ for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):
28+ if 0 <= ny < h and 0 <= nx < w and mask[ny, nx] and not seen[ny, nx]:
29+ seen[ny, nx] = True
30+ stack.append((ny, nx))
31+ out.append((area, minx, miny, maxx + 1, maxy + 1))
32+ return out
33+
34+
35+def main():
36+ p = argparse.ArgumentParser()
37+ p.add_argument("candidate_dir")
38+ p.add_argument("baseline_dir")
39+ p.add_argument("--overlay-dir")
40+ p.add_argument("--min-area-ratio", type=float, default=0.018)
41+ args = p.parse_args()
42+
43+ cand_files = sorted(Path(args.candidate_dir).glob("*.png"))
44+ base_files = sorted(Path(args.baseline_dir).glob("*.png"))
45+ if len(cand_files) != len(base_files):
46+ raise SystemExit(f"frame count mismatch: {len(cand_files)} vs {len(base_files)}")
47+
48+ overlay_dir = Path(args.overlay_dir) if args.overlay_dir else None
49+ if overlay_dir:
50+ overlay_dir.mkdir(parents=True, exist_ok=True)
51+
52+ bad = []
53+ for cf, bf in zip(cand_files, base_files):
54+ cand = np.asarray(Image.open(cf).convert("RGB"), dtype=np.int16)
55+ base = np.asarray(Image.open(bf).convert("RGB"), dtype=np.int16)
56+ h, w = cand.shape[:2]
57+ cand_l = cand[:, :, 0] * 0.2126 + cand[:, :, 1] * 0.7152 + cand[:, :, 2] * 0.0722
58+ base_l = base[:, :, 0] * 0.2126 + base[:, :, 1] * 0.7152 + base[:, :, 2] * 0.0722
59+ mask = (cand_l < 18) & (base_l > 42) & ((base_l - cand_l) > 35)
60+ mask[: int(h * 0.09), :] = False
61+ mask[int(h * 0.92) :, :] = False
62+ mask[:, : int(w * 0.08)] = False
63+ mask[:, int(w * 0.92) :] = False
64+
65+ hits = []
66+ for area, x1, y1, x2, y2 in components(mask):
67+ bw, bh = x2 - x1, y2 - y1
68+ area_ratio = area / (w * h)
69+ rect_fill = area / max(1, bw * bh)
70+ if area_ratio >= args.min_area_ratio and bw >= w * 0.12 and bh >= h * 0.12 and rect_fill > 0.55:
71+ hits.append({
72+ "bbox": [x1, y1, x2, y2],
73+ "area_ratio": round(area_ratio, 4),
74+ "fill": round(rect_fill, 4),
75+ })
76+ if hits:
77+ item = {"file": str(cf), "baseline": str(bf), "hits": hits}
78+ bad.append(item)
79+ print(json.dumps(item, ensure_ascii=False))
80+ if overlay_dir:
81+ overlay = Image.open(cf).convert("RGB")
82+ d = ImageDraw.Draw(overlay)
83+ for hit in hits:
84+ d.rectangle(hit["bbox"], outline=(255, 0, 0), width=5)
85+ overlay.save(overlay_dir / f"{cf.stem}-regression.png")
86+
87+ print(json.dumps({"frames": len(cand_files), "bad_frames": len(bad)}, ensure_ascii=False))
88+ raise SystemExit(1 if bad else 0)
89+
90+
91+if __name__ == "__main__":
92+ main()
added tools/detect-black-rects.py +208 −0
@@ -0,0 +1,208 @@
1+#!/usr/bin/env python3
2+import argparse
3+import json
4+from pathlib import Path
5+
6+import numpy as np
7+from PIL import Image, ImageDraw
8+
9+
10+def components(mask):
11+ h, w = mask.shape
12+ seen = np.zeros_like(mask, dtype=bool)
13+ comps = []
14+ for y0, x0 in np.argwhere(mask & ~seen):
15+ if seen[y0, x0]:
16+ continue
17+ stack = [(int(y0), int(x0))]
18+ seen[y0, x0] = True
19+ minx = maxx = int(x0)
20+ miny = maxy = int(y0)
21+ area = 0
22+ while stack:
23+ y, x = stack.pop()
24+ area += 1
25+ minx = min(minx, x)
26+ maxx = max(maxx, x)
27+ miny = min(miny, y)
28+ maxy = max(maxy, y)
29+ for ny in (y - 1, y, y + 1):
30+ for nx in (x - 1, x, x + 1):
31+ if ny == y and nx == x:
32+ continue
33+ if 0 <= ny < h and 0 <= nx < w and mask[ny, nx] and not seen[ny, nx]:
34+ seen[ny, nx] = True
35+ stack.append((ny, nx))
36+ comps.append((area, minx, miny, maxx + 1, maxy + 1))
37+ return comps
38+
39+
40+def rect_sum(ii, x1, y1, x2, y2):
41+ return ii[y2, x2] - ii[y1, x2] - ii[y2, x1] + ii[y1, x1]
42+
43+
44+def downsample(mask, factor):
45+ h, w = mask.shape
46+ h2 = h // factor
47+ w2 = w // factor
48+ trimmed = mask[: h2 * factor, : w2 * factor]
49+ return trimmed.reshape(h2, factor, w2, factor).mean(axis=(1, 3)) > 0.98
50+
51+
52+def detect(path, out_dir=None, threshold=35, scan_windows=False):
53+ img = Image.open(path).convert("RGB")
54+ arr = np.asarray(img)
55+ h, w = arr.shape[:2]
56+
57+ luminance = arr[:, :, 0] * 0.2126 + arr[:, :, 1] * 0.7152 + arr[:, :, 2] * 0.0722
58+ dark = luminance <= threshold
59+
60+ # Ignore fixed HUD bands enough to keep the detector focused on the WebGL scene.
61+ hud = np.zeros((h, w), dtype=bool)
62+ hud[: int(h * 0.09), :] = True
63+ hud[int(h * 0.92) :, :] = True
64+ hud[:, : int(w * 0.08)] = True
65+ hud[:, int(w * 0.92) :] = True
66+ scene_dark = dark & ~hud
67+
68+ dark_i = np.pad(scene_dark.astype(np.float32).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
69+ lum_i = np.pad(luminance.astype(np.float64).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
70+ lum2_i = np.pad((luminance.astype(np.float64) ** 2).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
71+ window_hits = []
72+ if scan_windows:
73+ for wf, hf in ((0.26, 0.22), (0.34, 0.26), (0.42, 0.30)):
74+ bw = int(w * wf)
75+ bh = int(h * hf)
76+ step = max(24, min(bw, bh) // 7)
77+ for y1 in range(int(h * 0.16), int(h * 0.82) - bh, step):
78+ y2 = y1 + bh
79+ if y2 < h * 0.48:
80+ continue
81+ for x1 in range(int(w * 0.08), int(w * 0.92) - bw, step):
82+ x2 = x1 + bw
83+ area = bw * bh
84+ dark_ratio = rect_sum(dark_i, x1, y1, x2, y2) / area
85+ if dark_ratio < 0.985:
86+ continue
87+ mean = rect_sum(lum_i, x1, y1, x2, y2) / area
88+ mean2 = rect_sum(lum2_i, x1, y1, x2, y2) / area
89+ std = max(0.0, mean2 - mean * mean) ** 0.5
90+ if mean <= threshold * 0.55 and std <= threshold * 0.65:
91+ window_hits.append({
92+ "bbox": [int(x1), int(y1), int(x2), int(y2)],
93+ "area_ratio": round(area / (w * h), 4),
94+ "dark_ratio": round(float(dark_ratio), 4),
95+ "kind": "dark_window",
96+ })
97+ break
98+ if window_hits:
99+ break
100+ if window_hits:
101+ break
102+
103+ coarse = downsample(scene_dark, 8)
104+ hits = []
105+ for area, x1, y1, x2, y2 in components(coarse):
106+ x1 *= 8
107+ y1 *= 8
108+ x2 *= 8
109+ y2 *= 8
110+ bw = x2 - x1
111+ bh = y2 - y1
112+ full_area = bw * bh
113+ if full_area < w * h * 0.035:
114+ continue
115+ if bw < w * 0.12 or bh < h * 0.12:
116+ continue
117+ fill = scene_dark[y1:min(y2, h), x1:min(x2, w)].mean()
118+ if fill < 0.97:
119+ continue
120+ hits.append({
121+ "bbox": [x1, y1, min(x2, w), min(y2, h)],
122+ "area_ratio": round(full_area / (w * h), 4),
123+ "fill": round(float(fill), 4),
124+ })
125+
126+ edge_hits = []
127+ win = 18
128+ for y in range(int(h * 0.14), int(h * 0.92) - win):
129+ above = scene_dark[max(0, y - win):y, :].mean(axis=0) > 0.92
130+ below = scene_dark[y:y + win, :].mean(axis=0) < 0.45
131+ edge = above & below
132+ x = 0
133+ while x < w:
134+ if not edge[x]:
135+ x += 1
136+ continue
137+ x1 = x
138+ while x < w and edge[x]:
139+ x += 1
140+ x2 = x
141+ bw = x2 - x1
142+ if bw < w * 0.18 or bw > w * 0.82:
143+ continue
144+ if x1 < w * 0.08 or x2 > w * 0.92:
145+ continue
146+ top = y
147+ while top > int(h * 0.06) and scene_dark[top - 1, x1:x2].mean() > 0.88:
148+ top -= 1
149+ bh = y - top
150+ if bh < h * 0.18:
151+ continue
152+ edge_hits.append({
153+ "bbox": [int(x1), int(top), int(x2), int(y)],
154+ "area_ratio": round((bw * bh) / (w * h), 4),
155+ "kind": "lower_edge",
156+ })
157+
158+ if out_dir and hits:
159+ out = Path(out_dir)
160+ out.mkdir(parents=True, exist_ok=True)
161+ overlay = img.copy()
162+ d = ImageDraw.Draw(overlay)
163+ for hit in hits:
164+ d.rectangle(hit["bbox"], outline=(255, 0, 0), width=5)
165+ overlay.save(out / f"{Path(path).stem}-black-rect.png")
166+
167+ all_hits = window_hits + hits + edge_hits
168+ if out_dir and edge_hits:
169+ out = Path(out_dir)
170+ out.mkdir(parents=True, exist_ok=True)
171+ overlay = img.copy()
172+ d = ImageDraw.Draw(overlay)
173+ for hit in all_hits:
174+ d.rectangle(hit["bbox"], outline=(255, 0, 0), width=5)
175+ overlay.save(out / f"{Path(path).stem}-black-rect.png")
176+
177+ return {"file": str(path), "hits": all_hits}
178+
179+
180+def main():
181+ p = argparse.ArgumentParser()
182+ p.add_argument("paths", nargs="+")
183+ p.add_argument("--overlay-dir")
184+ p.add_argument("--threshold", type=int, default=35)
185+ p.add_argument("--scan-windows", action="store_true")
186+ args = p.parse_args()
187+
188+ all_results = []
189+ failed = False
190+ for raw in args.paths:
191+ path = Path(raw)
192+ files = sorted(path.glob("*.png")) if path.is_dir() else [path]
193+ for f in files:
194+ result = detect(f, args.overlay_dir, args.threshold, args.scan_windows)
195+ if result["hits"]:
196+ failed = True
197+ print(json.dumps(result, ensure_ascii=False))
198+ all_results.append(result)
199+ summary = {
200+ "frames": len(all_results),
201+ "bad_frames": sum(1 for r in all_results if r["hits"]),
202+ }
203+ print(json.dumps(summary, ensure_ascii=False))
204+ raise SystemExit(1 if failed else 0)
205+
206+
207+if __name__ == "__main__":
208+ main()