Elffuss BraidHub

kikocis/VibeCodeViewer public

9becfbfdcf77 · 26.3 KiBRawPermalink
1// Construcción de la escena: ciudad de cristal nítida.
2// Receta anti-difuminado: aristas finas con colores HDR (el bloom solo se
3// dispara en lo resaltado), cristal con fresnel de opacidad mínima y nada
4// de volúmenes aditivos permanentes.
5// Toda la paleta viene del tema activo (src/themes.js); los temas claros
6// usan blending normal en lugar de aditivo.
7import * as THREE from 'three';
8
9function 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]; }
10function 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}
20
21// 12 aristas de una caja → 24 vértices
22const EDGE_PAIRS = [
23 [0, 1], [1, 3], [3, 2], [2, 0],
24 [4, 5], [5, 7], [7, 6], [6, 4],
25 [0, 4], [1, 5], [2, 6], [3, 7],
26];
27function corners(b) {
28 const x0 = b.cx - b.sx / 2, x1 = b.cx + b.sx / 2;
29 const y0 = b.cy - b.sy / 2, y1 = b.cy + b.sy / 2;
30 const z0 = b.cz - b.sz / 2, z1 = b.cz + b.sz / 2;
31 return [
32 [x0, y0, z0], [x1, y0, z0], [x0, y0, z1], [x1, y0, z1],
33 [x0, y1, z0], [x1, y1, z0], [x0, y1, z1], [x1, y1, z1],
34 ];
35}
36
37// ── suelo: placa de circuito impreso ──────────────────────────────────────
38function circuitTexture(theme) {
39 const T = theme.ground;
40 const S = 1024;
41 const cv = document.createElement('canvas');
42 cv.width = cv.height = S;
43 const g = cv.getContext('2d');
44 g.fillStyle = T.bg;
45 g.fillRect(0, 0, S, S);
46 g.strokeStyle = T.grid;
47 g.lineWidth = 1;
48 for (let i = 0; i <= S; i += 64) {
49 g.beginPath(); g.moveTo(i, 0); g.lineTo(i, S); g.stroke();
50 g.beginPath(); g.moveTo(0, i); g.lineTo(S, i); g.stroke();
51 }
52 const rnd = (() => { let s = 1234567; return () => (s = (s * 16807) % 2147483647) / 2147483647; })();
53 for (let i = 0; i < 260; i++) {
54 const isA = rnd() < 0.58;
55 const a = 0.18 + rnd() * 0.5;
56 const [tr, tg, tb] = isA ? T.traceA : T.traceB;
57 g.strokeStyle = `rgba(${tr}, ${tg}, ${tb}, ${isA ? a : a * 0.9})`;
58 g.lineWidth = rnd() < 0.12 ? 3 : 1.4;
59 let x = rnd() * S, y = rnd() * S;
60 g.beginPath(); g.moveTo(x, y);
61 const segs = 2 + Math.floor(rnd() * 4);
62 for (let sg = 0; sg < segs; sg++) {
63 const len = 24 + rnd() * 150;
64 if (rnd() < 0.5) x += rnd() < 0.5 ? len : -len; else y += rnd() < 0.5 ? len : -len;
65 g.lineTo(x, y);
66 }
67 g.stroke();
68 const [pr, pg, pb] = isA ? T.padA : T.padB;
69 g.fillStyle = `rgba(${pr}, ${pg}, ${pb}, ${a + 0.2})`;
70 const ps = 2 + rnd() * 3;
71 g.fillRect(x - ps / 2, y - ps / 2, ps, ps);
72 }
73 const tx = new THREE.CanvasTexture(cv);
74 tx.wrapS = tx.wrapT = THREE.RepeatWrapping;
75 tx.colorSpace = THREE.SRGBColorSpace;
76 tx.anisotropy = 8;
77 return tx;
78}
79
80// ── cristal con fresnel (bordes algo más vivos, centro casi invisible) ────
81function glassMaterial(theme, dim = 1, solid = 0) {
82 return new THREE.ShaderMaterial({
83 uniforms: {
84 uColor: { value: new THREE.Color(...theme.glass) },
85 uHi: { value: new THREE.Color(...theme.glassHi) },
86 uGlow: { value: 0 },
87 uDim: { value: dim },
88 uSolid: { value: solid },
89 },
90 vertexShader: /* glsl */`
91 varying vec3 vN, vV;
92 void main() {
93 vec4 mv = modelViewMatrix * vec4(position, 1.0);
94 vN = normalMatrix * normal;
95 vV = -mv.xyz;
96 gl_Position = projectionMatrix * mv;
97 }`,
98 fragmentShader: /* glsl */`
99 uniform vec3 uColor;
100 uniform vec3 uHi;
101 uniform float uGlow;
102 uniform float uDim;
103 uniform float uSolid;
104 varying vec3 vN, vV;
105 void main() {
106 float fr = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.6);
107 vec3 col = mix(uColor, uHi, uGlow);
108 float alpha = (0.022 + fr * 0.12 + uSolid * 0.12) * uDim + uGlow * 0.05;
109 gl_FragColor = vec4(col * ((0.5 + fr * 1.9) * uDim + uGlow), alpha);
110 }`,
111 transparent: true,
112 depthWrite: false,
113 side: THREE.DoubleSide,
114 });
115}
116
117// ── fachada: árbol de ficheros impreso sobre el cristal ───────────────────
118const FACADE_MAX_LINES = 150;
119
120function facadeLines(building) {
121 const lines = [];
122 let overflow = false;
123 (function walk(node, depth) {
124 if (lines.length > FACADE_MAX_LINES) { overflow = true; return; }
125 lines.push({ text: node.name + '/', depth, key: 'n' + node.id });
126 for (const c of node.children) walk(c, depth + 1);
127 for (const fid of node.fileIds) {
128 if (lines.length > FACADE_MAX_LINES) { overflow = true; return; }
129 const f = building.modelFiles[fid];
130 lines.push({ text: f.name, depth: depth + 1, key: 'f' + f.id });
131 }
132 })(building, 0);
133 if (overflow) lines.push({ text: '· · ·', depth: 1, key: '' });
134 return lines;
135}
136
137function drawFacade(building, highlight, theme) {
138 const cv = building.facadeCanvas;
139 if (!cv) return; // edificio sin fachada (recorte en ciudades enormes)
140 const g = cv.getContext('2d');
141 const W = cv.width, H = cv.height;
142 g.clearRect(0, 0, W, H);
143 const lines = building.facadeLineCache;
144 const fs = Math.max(9, Math.min(30, (H - 60) / (lines.length + 1)));
145 g.font = `${fs}px "JetBrains Mono", "Cascadia Code", monospace`;
146 g.textBaseline = 'top';
147 let y = 26;
148 for (const ln of lines) {
149 const x = 22 + ln.depth * fs * 1.1;
150 const hot = highlight && highlight.has(ln.key);
151 if (hot) {
152 g.shadowColor = theme.facade.hotGlow;
153 g.shadowBlur = 14;
154 g.fillStyle = theme.facade.hotBg;
155 g.fillRect(x - 6, y - 3, g.measureText(ln.text).width + 12, fs + 6);
156 g.fillStyle = theme.facade.hot;
157 } else {
158 g.shadowBlur = 0;
159 g.fillStyle = theme.facade.text;
160 }
161 g.fillText(ln.text, x, y);
162 y += fs * 1.18;
163 if (y > H - fs) break;
164 }
165 g.shadowBlur = 0;
166 building.facadeTexture.needsUpdate = true;
167}
168
169function buildFacade(building, model, group, theme) {
170 building.modelFiles = model.files;
171 building.facadeLineCache = facadeLines(building);
172 const b = building.box;
173 const H = 1024;
174 const W = Math.round(Math.min(2048, Math.max(256, H * (b.sx / b.sy))));
175 const cv = document.createElement('canvas');
176 cv.width = W; cv.height = H;
177 building.facadeCanvas = cv;
178 const tx = configureCanvasTexture(new THREE.CanvasTexture(cv));
179 building.facadeTexture = tx;
180 drawFacade(building, null, theme);
181 const mat = new THREE.MeshBasicMaterial({
182 map: tx, transparent: true, alphaTest: 0.025, depthWrite: false, side: THREE.FrontSide,
183 blending: theme.light ? THREE.NormalBlending : THREE.AdditiveBlending,
184 });
185 mat.userData.vccKind = 'facade';
186 const E = 0.14;
187 const faces = [
188 { w: b.sx, pos: [b.cx, b.cy, b.cz + b.sz / 2 + E], rot: 0 },
189 { w: b.sx, pos: [b.cx, b.cy, b.cz - b.sz / 2 - E], rot: Math.PI },
190 { w: b.sz, pos: [b.cx + b.sx / 2 + E, b.cy, b.cz], rot: Math.PI / 2 },
191 { w: b.sz, pos: [b.cx - b.sx / 2 - E, b.cy, b.cz], rot: -Math.PI / 2 },
192 ];
193 for (const f of faces) {
194 const plane = new THREE.Mesh(new THREE.PlaneGeometry(f.w, b.sy), mat);
195 plane.position.set(...f.pos);
196 plane.rotation.y = f.rot;
197 plane.renderOrder = 3;
198 group.add(plane);
199 }
200}
201
202// ── leyenda: nombres serigrafiados (suelo de distrito y tejado) ───────────
203function labelTexture(text, color) {
204 const fs = 96, pad = 40;
205 const probe = document.createElement('canvas').getContext('2d');
206 probe.font = `bold ${fs}px "JetBrains Mono", monospace`;
207 const tw = probe.measureText(text).width;
208 const cv = document.createElement('canvas');
209 cv.width = Math.ceil(tw + pad * 2 + 220);
210 cv.height = 190;
211 const g = cv.getContext('2d');
212 g.font = `bold ${fs}px "JetBrains Mono", monospace`;
213 g.textBaseline = 'middle';
214 // pista de circuito: línea con pads a ambos lados del texto
215 g.strokeStyle = color; g.globalAlpha = 0.65; g.lineWidth = 5;
216 const y = cv.height / 2;
217 g.beginPath(); g.moveTo(14, y); g.lineTo(pad + 60, y); g.stroke();
218 g.beginPath(); g.moveTo(pad + 100 + tw, y); g.lineTo(cv.width - 14, y); g.stroke();
219 g.fillStyle = color;
220 for (const px of [14, pad + 60, pad + 100 + tw, cv.width - 26]) g.fillRect(px - 7, y - 7, 14, 14);
221 g.globalAlpha = 0.92;
222 g.shadowColor = color; g.shadowBlur = 16;
223 g.fillText(text, pad + 80, y);
224 const tx = configureCanvasTexture(new THREE.CanvasTexture(cv));
225 return { tx, aspect: cv.width / cv.height };
226}
227
228const LEGEND_MAX_BUILDINGS = 400;
229
230function buildLegend(model, labeled, theme) {
231 const legend = new THREE.Group();
232 const add = (text, color, width, pos, flat) => {
233 const { tx, aspect } = labelTexture(text, color);
234 const w = Math.min(width, aspect * 8);
235 const mesh = new THREE.Mesh(
236 new THREE.PlaneGeometry(w, w / aspect),
237 new THREE.MeshBasicMaterial({
238 map: tx, transparent: true, alphaTest: 0.025, depthWrite: false,
239 blending: theme.light ? THREE.NormalBlending : THREE.AdditiveBlending,
240 }),
241 );
242 mesh.material.userData.vccKind = 'label';
243 if (flat) mesh.rotation.x = -Math.PI / 2;
244 mesh.position.set(...pos);
245 mesh.renderOrder = 4;
246 legend.add(mesh);
247 };
248 for (const di of model.districts) {
249 add(di.name, theme.labels.district, di.box.sx * 0.85,
250 [di.box.cx, 0.3, di.box.cz + di.box.sz / 2 - 2], true);
251 }
252 // urbanizaciones: mismo serigrafiado de suelo que los distritos, en tono
253 // intermedio; en monorepos se etiquetan las de mayor superficie
254 const urbs = [...model.urbs].sort((a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz);
255 for (const u of urbs.slice(0, LEGEND_MAX_BUILDINGS)) {
256 add(u.name, theme.labels.urb, u.box.sx * 0.8,
257 [u.box.cx, 0.32, u.box.cz + u.box.sz / 2 - 1.4], true);
258 }
259 for (const b of labeled.slice(0, LEGEND_MAX_BUILDINGS)) {
260 if (b.isBasement) continue; // su tejado es la calle: sin etiqueta
261 add(b.name, theme.labels.building, b.box.sx * 0.95,
262 [b.box.cx, b.box.cy + b.box.sy / 2 + 0.12, b.box.cz], true);
263 }
264 return legend;
265}
266
267// ── ciudad completa ───────────────────────────────────────────────────────
268export function buildCity(scene, model, theme) {
269 const group = new THREE.Group();
270 scene.add(group);
271 // paleta del tema; en temas claros el blending aditivo no funciona
272 const ROLE_COLOR = theme.roleColor;
273 const HI = theme.hi;
274 const FILE_BASE = theme.fileBase;
275 const FILE_HI = theme.fileHi;
276 const BLEND = theme.light ? THREE.NormalBlending : THREE.AdditiveBlending;
277
278 // suelo
279 const extent = Math.max(model.city.box.sx, model.city.box.sz);
280 const ground = new THREE.Mesh(
281 new THREE.PlaneGeometry(extent * 7, extent * 7),
282 // semitransparente y a doble cara: los sótanos (ficheros ignorados)
283 // se intuyen a través del plano de circuitos. depthWrite: false — era el
284 // único material que escribía profundidad y, con el rango near/far de la
285 // ciudad, las plotas y serigrafías a ras de suelo hacían z-fighting
286 // (parpadeo en franjas) al mover la cámara
287 new THREE.MeshBasicMaterial({
288 map: circuitTexture(theme), transparent: true, opacity: 0.8, side: THREE.DoubleSide,
289 depthWrite: false,
290 // separa el suelo en el z-buffer de plotas y serigrafías a ras de
291 // suelo (evita el z-fighting cuando el modo opaco activa depthWrite)
292 polygonOffset: true, polygonOffsetFactor: 2, polygonOffsetUnits: 2,
293 }),
294 );
295 ground.material.map.repeat.set(7, 7);
296 ground.rotation.x = -Math.PI / 2;
297 ground.position.y = -0.05;
298 group.add(ground);
299
300 // aristas de las cajas en un único buffer con rangos por nodo.
301 // LOD por presupuesto para monorepos: decenas de miles de wireframes
302 // aditivos se acumulan en blanco. Distritos y edificios siempre dibujan;
303 // del interior se conservan las cajas más grandes y menos profundas.
304 const LINE_BUDGET = 12000;
305 const ROLE_DEPTH = { distrito: 0, urbanizacion: 0, edificio: 0, planta: 1, apartamento: 2, habitacion: 3, archivador: 4, cajon: 5 };
306 const candidates = model.nodes.filter(n => n.role !== 'ciudad' && n.box);
307 let boxNodes = candidates;
308 if (candidates.length > LINE_BUDGET) {
309 const score = (n) => (n.role === 'distrito' || n.role === 'urbanizacion' || n.role === 'edificio')
310 ? Infinity
311 : Math.max(n.box.sx, n.box.sy, n.box.sz) - ROLE_DEPTH[n.role] * 3;
312 boxNodes = candidates.sort((a, b) => score(b) - score(a)).slice(0, LINE_BUDGET);
313 }
314 const positions = new Float32Array(boxNodes.length * 24 * 3);
315 const colors = new Float32Array(boxNodes.length * 24 * 3);
316 // brillo de arista normalizado por edificio: el interior de un edificio
317 // reparte un presupuesto de luz constante (mismo principio que las celdas)
318 const boxesPerBuilding = new Map();
319 for (const n of boxNodes) {
320 if (n.building && n.building !== n) {
321 boxesPerBuilding.set(n.building.id, (boxesPerBuilding.get(n.building.id) ?? 0) + 1);
322 }
323 }
324 // …y una atenuación global suave en ciudades con miles de edificios:
325 // uniforme (todos los edificios conservan el mismo aspecto entre sí),
326 // solo evita que la acumulación aditiva a vista de pájaro se queme
327 const cityDim = Math.min(1, Math.max(0.45, Math.sqrt(900 / Math.max(model.buildings.length, 1))));
328 for (const n of boxNodes) {
329 const local = (!n.building || n.building === n)
330 ? 1
331 : Math.min(1, Math.max(0.12, 30 / (boxesPerBuilding.get(n.building.id) ?? 1)));
332 // las plotas (distrito y urbanización) son solo perímetro: siempre nítidas
333 n.lineDim = (n.role === 'distrito' || n.role === 'urbanizacion') ? 1 : local * cityDim;
334 }
335
336 let v = 0;
337 for (const node of boxNodes) {
338 node.lineStart = v;
339 const cs = corners(node.box);
340 const base = (ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon).map(c => c * node.lineDim);
341 node.baseColor = base;
342 for (const [a, b] of EDGE_PAIRS) {
343 for (const p of [cs[a], cs[b]]) {
344 positions[v * 3] = p[0]; positions[v * 3 + 1] = p[1]; positions[v * 3 + 2] = p[2];
345 colors[v * 3] = base[0]; colors[v * 3 + 1] = base[1]; colors[v * 3 + 2] = base[2];
346 v++;
347 }
348 }
349 }
350 const lineGeo = new THREE.BufferGeometry();
351 lineGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
352 lineGeo.setAttribute('color', new THREE.BufferAttribute(colors, 3));
353 lineGeo.computeBoundingSphere();
354 // opacidad adaptativa: cuantas más cajas, más tenue cada arista
355 const lineOpacity = Math.min(0.95, Math.max(0.4, Math.sqrt(4000 / Math.max(boxNodes.length, 1))));
356 const lineBaseOpacity = lineOpacity;
357 const lines = new THREE.LineSegments(lineGeo, new THREE.LineBasicMaterial({
358 vertexColors: true, transparent: true, opacity: lineOpacity,
359 blending: BLEND, depthWrite: false,
360 }));
361 lines.renderOrder = 2;
362 group.add(lines);
363
364 // carcasas de cristal por edificio (también sirven para el raycast).
365 // En ciudades enormes las fachadas con texto se reservan a los edificios
366 // más grandes (una textura canvas por edificio no escala a miles).
367 const byArea = [...model.buildings].sort(
368 (a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz);
369 const facadeSet = new Set(byArea.slice(0, 250));
370 const shells = [];
371 for (const b of model.buildings) {
372 const mat = glassMaterial(theme, cityDim, b.onlyBasement ? 1 : 0);
373 mat.userData.baseDim = cityDim;
374 const mesh = new THREE.Mesh(new THREE.BoxGeometry(b.box.sx, b.box.sy, b.box.sz), mat);
375 mesh.position.set(b.box.cx, b.box.cy, b.box.cz);
376 mesh.renderOrder = 1;
377 mesh.userData.building = b;
378 b.shell = mesh;
379 shells.push(mesh);
380 group.add(mesh);
381 if (facadeSet.has(b)) buildFacade(b, model, group, theme);
382 }
383
384 // forjados de las plantas (losa fina, casi invisible); con tope en
385 // monorepos, priorizando las plantas de mayor superficie
386 let slabNodes = model.nodes.filter(n => n.role === 'planta');
387 if (slabNodes.length > 4000) {
388 slabNodes = slabNodes
389 .sort((a, b) => b.box.sx * b.box.sz - a.box.sx * a.box.sz)
390 .slice(0, 4000);
391 }
392 if (slabNodes.length) {
393 const slabGeo = new THREE.BoxGeometry(1, 1, 1);
394 const slabMat = new THREE.MeshBasicMaterial({
395 color: new THREE.Color(...theme.slab), transparent: true,
396 opacity: Math.min(0.045, 0.045 * Math.sqrt(1500 / slabNodes.length)),
397 depthWrite: false, blending: BLEND,
398 });
399 const slabs = new THREE.InstancedMesh(slabGeo, slabMat, slabNodes.length);
400 const m = new THREE.Matrix4();
401 slabNodes.forEach((n, i) => {
402 m.makeScale(n.box.sx, 0.12, n.box.sz);
403 m.setPosition(n.box.cx, n.box.cy - n.box.sy / 2, n.box.cz);
404 slabs.setMatrixAt(i, m);
405 });
406 slabs.computeBoundingSphere();
407 slabs.renderOrder = 1;
408 group.add(slabs);
409 }
410
411 // celdas de fichero (instanciadas)
412 const fileGeo = new THREE.BoxGeometry(1, 1, 1);
413 const fileMat = new THREE.MeshBasicMaterial({
414 transparent: true, opacity: 0.9, depthWrite: false, blending: BLEND,
415 });
416 const fileBaseOpacity = fileMat.opacity;
417 const filesMesh = new THREE.InstancedMesh(fileGeo, fileMat, model.files.length);
418 {
419 const m = new THREE.Matrix4();
420 const c = new THREE.Color();
421 for (const f of model.files) {
422 m.makeScale(f.box.sx, f.box.sy, f.box.sz);
423 m.setPosition(f.box.cx, f.box.cy, f.box.cz);
424 filesMesh.setMatrixAt(f.id, m);
425 filesMesh.setColorAt(f.id, c.setRGB(...FILE_BASE));
426 }
427 filesMesh.instanceColor.needsUpdate = true;
428 filesMesh.computeBoundingSphere();
429 }
430 filesMesh.renderOrder = 2;
431 group.add(filesMesh);
432
433 // cajas de relleno para los niveles encendidos (pool reutilizable)
434 const fillPool = [];
435 for (let i = 0; i < 10; i++) {
436 const mesh = new THREE.Mesh(
437 new THREE.BoxGeometry(1, 1, 1),
438 new THREE.MeshBasicMaterial({
439 color: new THREE.Color(...theme.fill), transparent: true, opacity: 0,
440 depthWrite: false, blending: BLEND,
441 }),
442 );
443 mesh.visible = false;
444 mesh.renderOrder = 2;
445 group.add(mesh);
446 fillPool.push(mesh);
447 }
448
449 // ── API de iluminación ──────────────────────────────────────────────
450 const touchedNodes = new Set();
451 const touchedFiles = new Set();
452 const colorAttr = lineGeo.getAttribute('color');
453 const tmpColor = new THREE.Color();
454 // atenuación normalizada por edificio: cada edificio reparte un presupuesto
455 // de luz constante entre sus celdas — así un rascacielos con 50k ficheros
456 // no se quema y uno con 20 sigue viéndose igual que antes
457 const filesPerBuilding = new Map();
458 for (const f of model.files) {
459 const b = f.node.building;
460 if (b) filesPerBuilding.set(b.id, (filesPerBuilding.get(b.id) ?? 0) + 1);
461 }
462 const dimOf = (f) => {
463 const n = filesPerBuilding.get(f.node.building?.id) ?? 1;
464 return Math.min(1, Math.max(0.05, 350 / n)) * cityDim;
465 };
466 // color base por fichero, reescribible por los modos de coloreado
467 const fileBase = model.files.map(f => FILE_BASE.map(c => c * dimOf(f)));
468
469 function paintNode(node, glow, hi = HI) {
470 // los nodos diminutos no tienen aristas (LOD): solo carcasa/relleno
471 if (node.lineStart !== undefined) {
472 const col = lerp3(node.baseColor, hi, Math.pow(glow, 1.35));
473 for (let i = node.lineStart; i < node.lineStart + 24; i++) {
474 colorAttr.array[i * 3] = col[0];
475 colorAttr.array[i * 3 + 1] = col[1];
476 colorAttr.array[i * 3 + 2] = col[2];
477 }
478 // subida parcial: en monorepos el buffer completo pesa decenas de MB
479 colorAttr.addUpdateRange(node.lineStart * 3, 72);
480 colorAttr.needsUpdate = true;
481 }
482 if (node.shell) node.shell.material.uniforms.uGlow.value = glow * 0.3;
483 if (glow > 0.01) touchedNodes.add(node); else touchedNodes.delete(node);
484 }
485
486 function paintFile(fileId, glow, hi = FILE_HI) {
487 const col = lerp3(fileBase[fileId], hi, glow);
488 filesMesh.setColorAt(fileId, tmpColor.setRGB(...col));
489 filesMesh.instanceColor.addUpdateRange(fileId * 3, 3);
490 filesMesh.instanceColor.needsUpdate = true;
491 if (glow > 0.01) touchedFiles.add(fileId); else touchedFiles.delete(fileId);
492 }
493
494 function clearGlows() {
495 for (const n of [...touchedNodes]) paintNode(n, 0);
496 for (const f of [...touchedFiles]) paintFile(f, 0);
497 for (const mesh of fillPool) mesh.visible = false;
498 }
499
500 // haces del modo Blast: del fichero seleccionado a sus relacionados,
501 // con pulsos viajando por la línea como paquetes de datos
502 let blastBeams = null;
503 function setBlastBeams(pairs) {
504 if (blastBeams) {
505 group.remove(blastBeams);
506 blastBeams.geometry.dispose();
507 blastBeams.material.dispose();
508 blastBeams = null;
509 }
510 if (!pairs?.length) return;
511 // pairs: { a, b, impact } — impact=true: b depende del seleccionado
512 // (consecuencias de un cambio); el pulso siempre viaja en el sentido de
513 // la propagación: hacia fuera en impactos, hacia dentro en dependencias
514 const pos = new Float32Array(pairs.length * 6);
515 const dist = new Float32Array(pairs.length * 2);
516 const dir = new Float32Array(pairs.length * 2);
517 pairs.forEach(({ a, b, impact }, i) => {
518 pos.set(a, i * 6);
519 pos.set(b, i * 6 + 3);
520 const len = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
521 dist[i * 2] = impact ? 0 : len;
522 dist[i * 2 + 1] = impact ? len : 0;
523 dir[i * 2] = dir[i * 2 + 1] = impact ? 1 : 0;
524 });
525 const geo = new THREE.BufferGeometry();
526 geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
527 geo.setAttribute('aDist', new THREE.BufferAttribute(dist, 1));
528 geo.setAttribute('aDir', new THREE.BufferAttribute(dir, 1));
529 blastBeams = new THREE.LineSegments(geo, new THREE.ShaderMaterial({
530 uniforms: {
531 uTime: { value: 0 },
532 uColor: { value: new THREE.Color(...theme.beam) },
533 uColorIn: { value: new THREE.Color(...(theme.beamIn ?? theme.beam)) },
534 },
535 vertexShader: /* glsl */`
536 attribute float aDist;
537 attribute float aDir;
538 varying float vD;
539 varying float vDir;
540 void main() {
541 vD = aDist;
542 vDir = aDir;
543 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
544 }`,
545 fragmentShader: /* glsl */`
546 uniform float uTime;
547 uniform vec3 uColor;
548 uniform vec3 uColorIn;
549 varying float vD;
550 varying float vDir;
551 void main() {
552 // tren de pulsos avanzando por la línea (cada ~8 unidades); la
553 // línea base se mantiene bien visible entre pulsos
554 float w = fract(vD * 0.125 - uTime * 1.4);
555 float pulse = exp(-pow((w - 0.2) * 6.0, 2.0));
556 vec3 col = mix(uColor, uColorIn, vDir);
557 gl_FragColor = vec4(col * (0.6 + pulse * 2.4), 0.5 + pulse * 0.5);
558 }`,
559 transparent: true,
560 blending: BLEND,
561 depthWrite: false,
562 }));
563 blastBeams.renderOrder = 3;
564 group.add(blastBeams);
565 }
566
567 function tickBeams(timeMs) {
568 if (blastBeams) blastBeams.material.uniforms.uTime.value = timeMs / 1000;
569 }
570
571 // modos de coloreado: reescribe los colores base de nodos y ficheros
572 // (fileColorFn/nodeColorFn → [r,g,b] o null para el color por defecto)
573 function setModeColors(fileColorFn, nodeColorFn) {
574 for (const node of boxNodes) {
575 const col = nodeColorFn?.(node) ?? (ROLE_COLOR[node.role] ?? ROLE_COLOR.cajon);
576 node.baseColor = col.map(c => c * (node.lineDim ?? 1));
577 paintNode(node, 0);
578 }
579 for (const f of model.files) {
580 const dim = dimOf(f);
581 const col = fileColorFn?.(f) ?? FILE_BASE;
582 fileBase[f.id] = col.map(c => c * dim);
583 paintFile(f.id, 0);
584 }
585 // se ha tocado todo: mejor una única subida completa que miles de rangos
586 colorAttr.clearUpdateRanges();
587 filesMesh.instanceColor.clearUpdateRanges();
588 }
589
590 function fillBoxes(boxesWithGlow) {
591 fillPool.forEach((mesh, i) => {
592 const entry = boxesWithGlow[i];
593 if (!entry) { mesh.visible = false; return; }
594 const { box, glow } = entry;
595 mesh.scale.set(box.sx, box.sy, box.sz);
596 mesh.position.set(box.cx, box.cy, box.cz);
597 mesh.material.opacity = 0.008 + glow * 0.045;
598 mesh.visible = true;
599 });
600 }
601
602 // leyenda serigrafiada (conmutable)
603 const legend = buildLegend(model, byArea, theme);
604 group.add(legend);
605
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
635 function dispose() {
636 scene.remove(group);
637 const geometries = new Set();
638 const materials = new Set();
639 group.traverse((o) => {
640 if (o.geometry) geometries.add(o.geometry);
641 for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
642 if (m) materials.add(m);
643 }
644 });
645 for (const g of geometries) g.dispose();
646 for (const m of materials) {
647 m.map?.dispose?.();
648 m.dispose();
649 }
650 }
651
652 return {
653 group, lines, shells, filesMesh, ground, legend,
654 paintNode, paintFile, clearGlows, fillBoxes, dispose, setModeColors, setBlastBeams, tickBeams, setVisuals,
655 setLegend: (v) => { legend.visible = v; },
656 // suelo opaco/translúcido. Opaco = escribe profundidad y se dibuja en la
657 // pasada de opacos: oculta de verdad los sótanos (ficheros ignorados)
658 setGroundOpaque: (v) => {
659 groundOpaque = v;
660 const m = ground.material;
661 m.opacity = v ? 1 : Math.min(1, groundBaseOpacity * (visualSettings.ground ?? 1));
662 m.transparent = !v;
663 m.depthWrite = v;
664 m.needsUpdate = true;
665 },
666 redrawFacade: (building, highlightKeys) => drawFacade(building, highlightKeys, theme),
667 };
668}