Elffuss BraidHub

utopia-ia/elffuss-code public

7c24e7b60e19 · 31.9 KiBRawPermalink
1// Vista «Mente de Elffuss» — el pensamiento subyacente del cerebro CEO en un
2// mundo 3D de fantasía psicodélica trance, con la CIUDAD real del proyecto
3// (motor VibeCodeViewer) flotando por debajo.
4// · cada línea/tool-call que llega nace como una ESTRELLA de texto (color por
5// PERFIL, tamaño/tipografía según lo que ocurre) que se desvanece sola.
6// · los perfiles (nombre, foco, color) se editan desde ⚙ — el usuario los crea
7// a su gusto.
8// · «≡ historial»: panel con TODO lo que ha llegado, sin recortar.
9// · cuando lee/escribe un fichero real, un haz baja hasta él en la ciudad.
10// · overlay PERSISTENTE (música/animación no reinician al salir y volver).
11import * as THREE from 'three';
12import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
13import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
14import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
15import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
16import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
17import * as ceo from './ceo.js';
18import * as db from './db.js';
19import { renderMarkdown } from './md.js';
20import { t } from './i18n.js';
21
22const SOUNDCLOUD = 'https://soundcloud.com/dekel-official/dekel-baoba-festival-2023';
23const CEO_COLOR = '#ff4d8d';
24
25let open = false, built = false, raf = null;
26let overlay, S, widget, onOpenFile = () => {}, onExecute = () => {};
27// Ciudad de fondo (vista real del workspace) y semilla de pensamientos previos:
28// AMBOS opcionales e inyectados por la app anfitriona — Code tiene un motor
29// VibeCodeViewer sobre su proyecto único; Claw (v1) no lo ofrece y la Mente
30// funciona igual de bien sin ciudad de fondo.
31let loadThoughts = async () => []; // () => [{path, md}]
32let buildCityFn = null; // (scene) => {cityWrap, cityCity, cityModel} | null
33export function init({ loadThoughts: lt, buildCity: bc } = {}) {
34 if (lt) loadThoughts = lt;
35 if (bc) buildCityFn = bc;
36}
37let anchorMap = new Map(); // id de perfil (+ 'ceo') → Vector3 (anclas del mundo)
38const anchors = []; // { el, pos } — solo etiquetas de propuestas forjadas
39let nodesGroup, thoughtNodes = [];
40let starGroup, stars = []; // estrellas de pensamiento efímeras
41const lineBuf = new Map(); // canal → texto acumulado hasta la línea completa
42const streamed = new Map(); // canal → ¿llegaron tokens? (evita duplicar el texto final)
43let cityWrap = null, cityCity = null, cityModel = null;
44let beams = [], fileActivity = [];
45
46export function isOpen() { return open; }
47export function setOpenFile(fn) { onOpenFile = fn; }
48export function setExecuteProposal(fn) { onExecute = fn; }
49
50const escHtml = s => String(s).replace(/[<>&]/g, c => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c]));
51const profileOf = channel => channel === 'ceo'
52 ? { id: 'ceo', name: 'CEO', color: CEO_COLOR }
53 : ceo.getProfiles().find(p => p.id === channel) || { id: channel, name: channel, color: '#7c5cff' };
54
55// ── música con Widget API (persistente: pausa al salir, reanuda al volver) ──
56function mountMusic(root) {
57 const wrap = document.createElement('div');
58 wrap.className = 'mind-music';
59 const url = 'https://w.soundcloud.com/player/?url=' + encodeURIComponent(SOUNDCLOUD) +
60 '&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&visual=false&color=%23ff4d8d';
61 wrap.innerHTML = '<iframe id="mind-sc" title="música" width="100%" height="120" frameborder="no" allow="autoplay; encrypted-media" src="' + url + '"></iframe>' +
62 '<div class="mind-music-cap">▶ Dekel · Baoba Festival — modo trance</div>';
63 root.appendChild(wrap);
64 const iframe = wrap.querySelector('#mind-sc');
65 const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* aún no */ } };
66 if (window.SC && window.SC.Widget) initWidget();
67 else { const s = document.createElement('script'); s.src = 'https://w.soundcloud.com/player/api.js'; s.onload = initWidget; document.head.appendChild(s); }
68}
69
70// ══ ESTRELLAS de pensamiento: cada línea/tool-call nace, brilla y se apaga ══
71function makeTextSprite(text, color, { fontSize = 16, bold = false, glow = 10 } = {}) {
72 const pad = 8;
73 const probe = document.createElement('canvas').getContext('2d');
74 probe.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`;
75 const w = Math.ceil(probe.measureText(text).width) + pad * 2;
76 const h = fontSize + pad * 2;
77 const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
78 const g = cv.getContext('2d');
79 g.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`;
80 g.textBaseline = 'middle';
81 g.shadowColor = color; g.shadowBlur = glow;
82 g.fillStyle = color;
83 g.fillText(text, pad, h / 2 + 1);
84 const tex = new THREE.CanvasTexture(cv);
85 const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });
86 const sprite = new THREE.Sprite(mat);
87 const scale = 0.09;
88 sprite.scale.set(w * scale, h * scale, 1);
89 return sprite;
90}
91
92// kind: 'line' (charla normal) · 'tool' (tool-call) · 'event' (ciclo/estado) · 'built' (propuesta forjada)
93const KIND_STYLE = {
94 line: { fontSize: 13, bold: false, glow: 8, life: 6, jitter: 15 },
95 tool: { fontSize: 17, bold: true, glow: 16, life: 9, jitter: 9 },
96 event: { fontSize: 20, bold: true, glow: 14, life: 7, jitter: 6 },
97 built: { fontSize: 26, bold: true, glow: 22, life: 13, jitter: 4 },
98};
99function spawnStar(channel, text, kind = 'line') {
100 if (!starGroup || !text) return;
101 const prof = profileOf(channel);
102 const st = KIND_STYLE[kind] || KIND_STYLE.line;
103 const anchor = anchorMap.get(prof.id) || new THREE.Vector3(0, 20, 0);
104 const j = st.jitter;
105 const label = kind === 'tool' ? '⟐ ' + text : kind === 'event' ? '★ ' + text : kind === 'built' ? '✦ ' + text : text;
106 const sprite = makeTextSprite(label.slice(0, kind === 'line' ? 52 : 72), prof.color, st);
107 sprite.position.copy(anchor).add(new THREE.Vector3((Math.random() - 0.5) * j, (Math.random() - 0.5) * j * 0.6, (Math.random() - 0.5) * j));
108 sprite.material.opacity = 0;
109 starGroup.add(sprite);
110 stars.push({ obj: sprite, born: elapsed, life: st.life, seed: Math.random() * 1000, up: kind === 'built' ? 0.5 : 0.22 });
111 if (stars.length > 160) { const old = stars.shift(); starGroup.remove(old.obj); old.obj.material.map.dispose(); old.obj.material.dispose(); }
112}
113
114// ── historial COMPLETO (todo lo que llega, sin recortar) — PERSISTENTE: antes
115// vivía solo en el DOM/memoria y una recarga de página lo borraba entero.
116const LOG_CAP = 500;
117let logHistory = []; // [{channel, text}] — se guarda en IndexedDB
118let logSaveTimer = null;
119function saveLogSoon() {
120 clearTimeout(logSaveTimer);
121 logSaveTimer = setTimeout(() => db.set('kv', 'mindLog', logHistory).catch(() => {}), 400);
122}
123function renderLogRow(channel, text) {
124 const body = document.getElementById('mind-log-body');
125 if (!body) return;
126 const prof = profileOf(channel);
127 const row = document.createElement('div');
128 row.className = 'ml-row';
129 row.innerHTML = `<span class="ml-dot" style="background:${prof.color}"></span><b style="color:${prof.color}">${escHtml(prof.name)}</b> <span class="ml-t">${escHtml(text)}</span>`;
130 body.appendChild(row);
131 while (body.children.length > LOG_CAP) body.removeChild(body.firstChild);
132 body.scrollTop = body.scrollHeight;
133}
134function logLine(channel, text) {
135 logHistory.push({ channel, text });
136 if (logHistory.length > LOG_CAP) logHistory = logHistory.slice(-LOG_CAP);
137 saveLogSoon();
138 renderLogRow(channel, text);
139}
140async function loadPersistedLog() {
141 try {
142 const saved = await db.get('kv', 'mindLog');
143 if (!Array.isArray(saved) || !saved.length) return;
144 logHistory = saved;
145 for (const { channel, text } of saved) renderLogRow(channel, text);
146 } catch { /* aún no hay historial guardado */ }
147}
148
149function flushLine(channel, force = false) {
150 const buf = (lineBuf.get(channel) || '').trim();
151 if (!buf && !force) return;
152 if (buf) { spawnStar(channel, buf, 'line'); logLine(channel, buf); }
153 lineBuf.set(channel, '');
154}
155
156// alimenta estrellas + historial + haces sobre la ciudad (ceo.js → aquí)
157export function pushThought(channel, ev) {
158 if (!open) return;
159 if (channel === 'sys') { logLine('ceo', ev.text); return; }
160 if (channel === 'ceo') {
161 if (ev.type === 'cycle') { logLine('ceo', '● ' + ev.text); spawnStar('ceo', ev.text, 'event'); }
162 else if (ev.type === 'survey') { logLine('ceo', ev.text); }
163 else if (ev.type === 'reprogram') { logLine('ceo', '⚙ ' + ev.text); spawnStar('ceo', ev.text, 'event'); if (ev.profiles) rebuildWorld(); }
164 else if (ev.type === 'paused') { logLine('ceo', ev.text); spawnStar('ceo', ev.text, 'event'); }
165 else if (ev.type === 'built') { logLine('ceo', '✦ ' + ev.text); spawnStar('ceo', ev.text, 'built'); addThoughtNode(ev); }
166 else logLine('ceo', ev.text || '');
167 return;
168 }
169 if (ev.type === 'open') { lineBuf.set(channel, ''); streamed.set(channel, false); }
170 else if (ev.type === 'token') {
171 streamed.set(channel, true);
172 lineBuf.set(channel, (lineBuf.get(channel) || '') + ev.text);
173 const buf = lineBuf.get(channel);
174 if (/\n/.test(ev.text) || buf.length > 90) flushLine(channel);
175 } else if (ev.type === 'tool') {
176 flushLine(channel);
177 spawnStar(channel, ev.text, 'tool');
178 logLine(channel, '⟐ ' + ev.text);
179 if (ev.path) fileBeam(ev.path, /escrib/i.test(ev.text) ? 'write' : 'read');
180 } else if (ev.type === 'tool_result') {
181 // el RESULTADO real de la tool (lo que de verdad se leyó/escribió/ejecutó),
182 // enlazado justo debajo de su tool-call — no solo el nombre de la acción.
183 const t = '→ ' + (ev.text || '(sin salida)');
184 spawnStar(channel, t, 'line');
185 logLine(channel, t);
186 } else if (ev.type === 'done') {
187 flushLine(channel, true);
188 // el proveedor puede devolver el texto final SIN pasar por tokens (sin
189 // streaming) → si no vimos ningún token, esto es lo único que lo muestra.
190 if (ev.text && !streamed.get(channel)) { spawnStar(channel, ev.text, 'line'); logLine(channel, ev.text); }
191 }
192}
193
194// ── nodos de pensamiento clicables (cada .md forjado = un punto brillante) ──
195function addThoughtNode({ path, md, text }) {
196 if (!nodesGroup) return;
197 const i = thoughtNodes.length;
198 const a = i * 2.399963; // ángulo áureo
199 const r = 30 + i * 5;
200 const mesh = new THREE.Mesh(
201 new THREE.IcosahedronGeometry(3.2, 0),
202 new THREE.MeshBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false }));
203 mesh.position.set(Math.cos(a) * r, 6 + Math.sin(i * 0.7) * 10, Math.sin(a) * r);
204 mesh.userData = { path, md, text };
205 nodesGroup.add(mesh);
206 thoughtNodes.push(mesh);
207 const lab = document.createElement('div');
208 lab.className = 'mind-node-label';
209 lab.textContent = (path || 'pensamiento').split('/').pop();
210 // clicable ella misma — antes SOLO el raycast contra la diminuta malla 3D
211 // abría el panel, fácil de fallar; la etiqueta es el blanco visible real.
212 lab.addEventListener('click', () => selectThoughtNode(mesh));
213 document.getElementById('mind-anchors').appendChild(lab);
214 anchors.push({ el: lab, pos: mesh.position });
215 mesh.userData.label = lab;
216}
217
218async function loadExistingThoughts() {
219 try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* aún no hay */ }
220}
221
222// selección de un nodo de propuesta — desde la malla 3D (raycast) o su etiqueta
223function selectThoughtNode(mesh) { showThoughtPanel(mesh); focusOn(mesh.position, 26); }
224
225function showThoughtPanel(node) {
226 const root = document.getElementById('mind-panel');
227 const md = node.userData.md || node.userData.text || '(sin contenido)';
228 const path = node.userData.path || 'pensamiento';
229 root.innerHTML = `<div class="mp-head">${escHtml(path)}<button id="mp-x">✕</button></div>` +
230 `<div class="mp-body">${renderMarkdown(md)}</div>` +
231 `<div class="mp-actions">` +
232 `<button id="mp-exec" class="mp-exec">▶ Ejecutar esta propuesta</button>` +
233 (node.userData.path ? `<button id="mp-open" class="mp-open">Abrir en el editor</button>` : '') +
234 `</div>`;
235 root.classList.add('show');
236 root.querySelector('#mp-x').onclick = () => root.classList.remove('show');
237 root.querySelector('#mp-exec').onclick = () => { onExecute(md); root.classList.remove('show'); };
238 const openBtn = root.querySelector('#mp-open');
239 if (openBtn) openBtn.onclick = () => { onOpenFile(node.userData.path); root.classList.remove('show'); };
240}
241
242// ══ perfiles: anclas 3D + leyenda (recalculadas al abrir o al reprogramar) ══
243function computeAnchors() {
244 const map = new Map();
245 map.set('ceo', new THREE.Vector3(0, 46, 0));
246 const profs = ceo.getProfiles();
247 const n = Math.max(profs.length, 1);
248 profs.forEach((p, i) => {
249 const a = (i / n) * Math.PI * 2;
250 map.set(p.id, new THREE.Vector3(Math.cos(a) * 70, 8 + (i % 2) * 20, Math.sin(a) * 70));
251 });
252 return map;
253}
254function renderLegend() {
255 const el = document.getElementById('mind-legend');
256 if (!el) return;
257 const profs = ceo.getProfiles();
258 el.innerHTML = `<div class="ml-item" data-id="ceo"><span class="ml-sw" style="background:${CEO_COLOR}"></span>CEO</div>` +
259 profs.map(p => `<div class="ml-item" data-id="${p.id}"><span class="ml-sw" style="background:${p.color}"></span>${escHtml(p.name)}</div>`).join('');
260 el.querySelectorAll('.ml-item').forEach(row => {
261 row.onclick = () => { const pos = anchorMap.get(row.dataset.id); if (pos) focusOn(pos, 46); };
262 });
263}
264// vuelo suave de la cámara hacia un punto — así «clic en algo → la cámara se centra»
265let flyTo = null;
266function focusOn(pos, distance = 40) {
267 if (!S) return;
268 const dir = new THREE.Vector3().subVectors(S.camera.position, S.controls.target);
269 if (dir.lengthSq() < 0.001) dir.set(0, 0.3, 1);
270 dir.normalize().multiplyScalar(distance);
271 flyTo = { fromPos: S.camera.position.clone(), toPos: pos.clone().add(dir), fromTarget: S.controls.target.clone(), toTarget: pos.clone(), t0: elapsed, dur: 1.1 };
272}
273const easeInOut = k => k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2;
274function rebuildWorld() { anchorMap = computeAnchors(); renderLegend(); }
275
276// ── panel ⚙: reprograma misión, carpeta-alma y PERFILES (editables) ──────
277function wireConfig(root) {
278 const btn = root.querySelector('#mind-config');
279 const cfg = root.querySelector('#mind-cfg');
280 const profRowHtml = p => `<div class="cfg-prof" data-id="${escHtml(p.id || '')}">
281 <input type="color" class="cp-color" value="${p.color || '#7c5cff'}">
282 <input type="text" class="cp-name" value="${escHtml(p.name || '')}" placeholder="Nombre">
283 <input type="text" class="cp-focus" value="${escHtml(p.focus || '')}" placeholder="En qué se centra">
284 <button class="cp-del" title="quitar">✕</button></div>`;
285 const notifState = () => (!('Notification' in window)) ? { txt: 'no soportadas por este navegador', can: false }
286 : Notification.permission === 'granted' ? { txt: '✓ concedidas — avisaré cuando encuentre algo bueno', can: false }
287 : Notification.permission === 'denied' ? { txt: '✕ bloqueadas — actívalas en los ajustes del sitio del navegador', can: false }
288 : { txt: 'aún no pedidas', can: true };
289 const draw = () => {
290 const profs = ceo.getProfiles();
291 const ns = notifState();
292 cfg.innerHTML =
293 '<div class="cfg-head">⚙ Reprogramar el cerebro<button id="cfg-x">✕</button></div>' +
294 '<div class="cfg-notif">🔔 Notificaciones del navegador: ' + escHtml(ns.txt) + (ns.can ? ' <button id="cfg-notif-ask" class="cfg-notif-btn">Activar</button>' : '') + '</div>' +
295 '<label>Misión (qué quieres que haga por su cuenta)</label>' +
296 '<textarea id="cfg-mission" rows="3">' + escHtml(ceo.getMission()) + '</textarea>' +
297 '<label>Carpeta-alma (dentro del proyecto)</label>' +
298 '<input id="cfg-dir" value="' + escHtml(ceo.getSoulDir()) + '">' +
299 '<label>Perfiles — cada uno piensa en paralelo, con el color de su estrella</label>' +
300 '<div id="cfg-profiles">' + profs.map(profRowHtml).join('') + '</div>' +
301 '<button id="cfg-add-prof" class="cfg-add">+ nuevo perfil</button>' +
302 '<div class="cfg-actions"><button id="cfg-think-now" class="cfg-ghost">Pensar ahora</button>' +
303 '<button id="cfg-save" class="cfg-save">Reprogramar</button></div>' +
304 '<div class="cfg-note">La elfa trabajará según esto cuando estés ocioso y volcará todo en esa carpeta.</div>';
305 cfg.querySelector('#cfg-x').onclick = () => cfg.classList.remove('show');
306 cfg.querySelector('#cfg-notif-ask')?.addEventListener('click', () => { Notification.requestPermission().then(draw); });
307 cfg.querySelector('#cfg-add-prof').onclick = () => {
308 cfg.querySelector('#cfg-profiles').insertAdjacentHTML('beforeend', profRowHtml({ color: '#ff9f45', name: '', focus: '' }));
309 wireRows();
310 };
311 cfg.querySelector('#cfg-think-now').onclick = () => { ceo.forceCycle(); cfg.classList.remove('show'); };
312 cfg.querySelector('#cfg-save').onclick = () => {
313 // preserva el id original de cada perfil (si no, cada guardado los
314 // regeneraría desde el nombre y los ciclos en curso perderían el hilo)
315 const rows = [...cfg.querySelectorAll('.cfg-prof')].map(r => ({
316 id: r.dataset.id || undefined,
317 color: r.querySelector('.cp-color').value,
318 name: r.querySelector('.cp-name').value.trim(),
319 focus: r.querySelector('.cp-focus').value.trim(),
320 }));
321 ceo.setMission(cfg.querySelector('#cfg-mission').value);
322 ceo.setSoulDir(cfg.querySelector('#cfg-dir').value);
323 ceo.setProfiles(rows);
324 if (!ceo.isEnabled()) ceo.enable();
325 cfg.classList.remove('show');
326 };
327 wireRows();
328 function wireRows() { cfg.querySelectorAll('.cp-del').forEach(b => { b.onclick = () => b.closest('.cfg-prof').remove(); }); }
329 };
330 btn.onclick = () => { if (cfg.classList.contains('show')) cfg.classList.remove('show'); else { draw(); cfg.classList.add('show'); } };
331}
332function wireHistory(root) {
333 const btn = root.querySelector('#mind-history'), panel = root.querySelector('#mind-log');
334 btn.onclick = () => panel.classList.toggle('show');
335 panel.querySelector('#ml-x').onclick = () => panel.classList.remove('show');
336}
337
338// play/stop del cerebro, visible dentro de la Mente. La elección la persiste
339// ceo.js (misma clave que usa el clic en la elfa) → sobrevive a recargar.
340function wirePlayStop(root) {
341 const btn = root.querySelector('#mind-playstop');
342 const paint = () => {
343 const on = ceo.isEnabled();
344 btn.textContent = on ? '⏸ pausar cerebro' : '▶ reanudar cerebro';
345 btn.classList.toggle('paused', !on);
346 };
347 btn.onclick = () => { if (ceo.isEnabled()) ceo.disable(); else ceo.enable(); paint(); };
348 paint();
349}
350
351// ══ ciudad de fondo (motor de la app anfitriona, por debajo del mundo) ══════
352async function buildBackgroundCity(scene) {
353 if (!buildCityFn) return;
354 try {
355 const city = await buildCityFn(scene);
356 if (!city) return;
357 cityWrap = city.cityWrap; cityCity = city.cityCity; cityModel = city.cityModel;
358 } catch { /* sigue sin ciudad de fondo */ }
359}
360// haz de luz que baja hasta el fichero real en la ciudad + resalta su celda
361function fileBeam(path, kind) {
362 if (!cityModel || !cityCity || !S) return;
363 const rel = String(path).replace(/^\.?\//, '');
364 const f = cityModel.fileByRel.get(rel);
365 if (!f) return;
366 const local = new THREE.Vector3(f.box.cx, f.box.cy, f.box.cz);
367 const world = cityWrap.localToWorld(local.clone());
368 const top = world.clone(); top.y += 50;
369 const geo = new THREE.BufferGeometry().setFromPoints([top, world]);
370 const mat = new THREE.LineBasicMaterial({ color: kind === 'write' ? 0xff4d8d : 0x49e8ff, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false });
371 const line = new THREE.Line(geo, mat);
372 S.scene.add(line);
373 beams.push({ obj: line, born: elapsed, life: 1.4 });
374 fileActivity.push({ id: f.id, born: elapsed, life: 2.2 });
375}
376
377// ── mundo psicodélico ───────────────────────────────────────────────────────
378function buildScene(canvas, W, H) {
379 const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
380 renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
381 renderer.setSize(W, H, false);
382 renderer.toneMapping = THREE.ACESFilmicToneMapping;
383 const scene = new THREE.Scene();
384 const camera = new THREE.PerspectiveCamera(60, W / H, 0.1, 2000);
385 camera.position.set(0, 40, 150);
386 const controls = new OrbitControls(camera, canvas);
387 controls.enableDamping = true; controls.dampingFactor = 0.06; controls.autoRotate = false;
388 controls.enablePan = false; controls.minDistance = 60; controls.maxDistance = 420;
389
390 const N = 14000;
391 const pos = new Float32Array(N * 3), rad = new Float32Array(N);
392 let s = 987654321; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
393 for (let i = 0; i < N; i++) {
394 const arm = Math.floor(rnd() * 4);
395 const r = Math.pow(rnd(), 0.6) * 120 + 6;
396 const a = arm * (Math.PI / 2) + r * 0.03 + (rnd() - 0.5) * 0.5;
397 const y = (rnd() - 0.5) * (14 - r * 0.06);
398 pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = y; pos[i * 3 + 2] = Math.sin(a) * r; rad[i] = r;
399 }
400 const geo = new THREE.BufferGeometry();
401 geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
402 geo.setAttribute('aRad', new THREE.BufferAttribute(rad, 1));
403 const mat = new THREE.ShaderMaterial({
404 uniforms: { uTime: { value: 0 }, uBass: { value: 0 }, uMid: { value: 0 } },
405 transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
406 vertexShader: `uniform float uTime, uBass, uMid; attribute float aRad; varying vec3 vC;
407 vec3 hsv(float h){ vec3 k=vec3(1.,2./3.,1./3.); vec3 p=abs(fract(h+k)*6.-3.); return clamp(p-1.,0.,1.);}
408 float hash(vec3 p){ p=fract(p*0.3183099+0.1); p*=17.0; return fract(p.x*p.y*p.z*(p.x+p.y+p.z)); }
409 float vnoise(vec3 x){ vec3 i=floor(x),f=fract(x); f=f*f*(3.0-2.0*f);
410 return mix(mix(mix(hash(i+vec3(0,0,0)),hash(i+vec3(1,0,0)),f.x),mix(hash(i+vec3(0,1,0)),hash(i+vec3(1,1,0)),f.x),f.y),
411 mix(mix(hash(i+vec3(0,0,1)),hash(i+vec3(1,0,1)),f.x),mix(hash(i+vec3(0,1,1)),hash(i+vec3(1,1,1)),f.x),f.y),f.z); }
412 float fbm(vec3 p){ float a=0.5,s=0.0; for(int i=0;i<4;i++){ s+=a*vnoise(p); p*=2.02; a*=0.5;} return s; }
413 void main(){
414 vec3 pos=position;
415 float n=fbm(pos*0.03 + vec3(0.0,uTime*0.18,0.0));
416 pos += normalize(pos+0.001) * (n-0.5) * (5.0 + uMid*4.0 + uBass*7.0);
417 float sw = uTime*0.14 + aRad*0.015 + uBass*0.18;
418 float cs=cos(sw), sn=sin(sw);
419 pos.xz = mat2(cs,-sn,sn,cs) * pos.xz;
420 pos *= (1.0 + uBass*0.05);
421 float h=fract(aRad*0.004+uTime*0.03+n*0.12); vC=hsv(h)*(1.3-aRad*0.004)*(0.95+uMid*0.18+uBass*0.12);
422 vec4 mv=modelViewMatrix*vec4(pos,1.0); gl_PointSize=(2.2+60.0/-mv.z)*(1.0+uBass*0.18); gl_Position=projectionMatrix*mv; }`,
423 fragmentShader: `varying vec3 vC; void main(){ vec2 d=gl_PointCoord-0.5; float m=smoothstep(0.5,0.0,length(d)); gl_FragColor=vec4(vC*2.0,m); }`,
424 });
425 const galaxy = new THREE.Points(geo, mat); scene.add(galaxy);
426 const core = new THREE.LineSegments(new THREE.WireframeGeometry(new THREE.IcosahedronGeometry(18, 1)),
427 new THREE.LineBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false }));
428 scene.add(core);
429 const rings = [];
430 for (let i = 0; i < 24; i++) {
431 const ring = new THREE.Mesh(new THREE.TorusGeometry(22, 0.5, 8, 80),
432 new THREE.MeshBasicMaterial({ color: 0x7c5cff, transparent: true, opacity: 0.45, blending: THREE.AdditiveBlending, depthWrite: false }));
433 ring.rotation.x = Math.PI / 2; ring.position.y = -70 + i * 6; ring.userData.i = i;
434 scene.add(ring); rings.push(ring);
435 }
436 nodesGroup = new THREE.Group(); scene.add(nodesGroup);
437 starGroup = new THREE.Group(); scene.add(starGroup);
438 const composer = new EffectComposer(renderer);
439 composer.setSize(W, H); composer.addPass(new RenderPass(scene, camera));
440 const bloom = new UnrealBloomPass(new THREE.Vector2(W, H), 1.1, 0.5, 0.2);
441 composer.addPass(bloom); composer.addPass(new OutputPass());
442 return { renderer, scene, camera, controls, composer, bloom, mat, galaxy, core, rings };
443}
444
445export async function openMind() {
446 if (open) return;
447 open = true;
448 if (built) { overlay.style.display = ''; try { widget?.play(); } catch {} startLoop(); return; }
449
450 overlay = document.createElement('div');
451 overlay.id = 'mind-overlay';
452 overlay.innerHTML =
453 '<canvas id="mind-canvas"></canvas>' +
454 `<div id="mind-title">${t('mindTitle')}</div>` +
455 '<div id="mind-legend"></div>' +
456 '<button id="mind-playstop" title="pausar/reanudar el cerebro"></button>' +
457 '<button id="mind-config" title="reprogramar el cerebro">⚙ cerebro</button>' +
458 '<button id="mind-history" title="ver todo lo que ha llegado">≡ historial</button>' +
459 '<button id="mind-close" title="salir">✕ salir</button>' +
460 '<div id="mind-anchors"></div><div id="mind-panel"></div><div id="mind-cfg"></div>' +
461 '<div id="mind-log"><div class="ml-head">Historial completo<button id="ml-x">✕</button></div><div id="mind-log-body"></div></div>';
462 document.body.appendChild(overlay);
463 wireConfig(overlay); wireHistory(overlay); wirePlayStop(overlay);
464 mountMusic(overlay);
465 anchors.length = 0; thoughtNodes = []; stars = []; lineBuf.clear();
466 rebuildWorld();
467
468 const canvas = overlay.querySelector('#mind-canvas');
469 S = buildScene(canvas, window.innerWidth, window.innerHeight);
470 buildBackgroundCity(S.scene);
471 await loadExistingThoughts();
472 await loadPersistedLog(); // el historial de «≡ historial» sobrevive a recargas
473
474 const ray = new THREE.Raycaster(), ptr = new THREE.Vector2();
475 let downXY = null;
476 canvas.addEventListener('pointerdown', e => { downXY = [e.clientX, e.clientY]; });
477 canvas.addEventListener('pointerup', e => {
478 if (!downXY) return; const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]); downXY = null;
479 if (moved > 5 || !thoughtNodes.length) return;
480 ptr.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);
481 ray.setFromCamera(ptr, S.camera);
482 const hit = ray.intersectObjects(thoughtNodes)[0];
483 if (hit) selectThoughtNode(hit.object);
484 });
485
486 const onResize = () => {
487 const w = window.innerWidth, h = window.innerHeight;
488 S.renderer.setSize(w, h, false); S.composer.setSize(w, h); S.bloom.resolution.set(w, h);
489 S.camera.aspect = w / h; S.camera.updateProjectionMatrix();
490 };
491 window.addEventListener('resize', onResize); S.onResize = onResize;
492 overlay.querySelector('#mind-close').addEventListener('click', closeMind);
493 S.onKey = e => { if (e.key === 'Escape') closeMind(); };
494 document.addEventListener('keydown', S.onKey);
495 built = true;
496 startLoop();
497}
498
499// Etiquetas de propuestas: se proyectan del mundo 3D a la pantalla, así que
500// con muchas acumuladas acaban solapándose ilegibles según el ángulo de
501// cámara. Aquí: cap a las más cercanas y reparto anti-solape (empuja hacia
502// abajo la que choca con otra ya colocada), para que se apilen separadas.
503const MAX_LABELS = 14, LABEL_W = 90, LABEL_H = 20;
504function projectAnchors() {
505 const w = window.innerWidth, h = window.innerHeight, v = new THREE.Vector3();
506 const projected = [];
507 for (const a of anchors) {
508 v.copy(a.pos).project(S.camera);
509 if (v.z > 1) { a.el.style.display = 'none'; continue; } // detrás de la cámara
510 projected.push({ a, x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, depth: v.z });
511 }
512 projected.sort((p1, p2) => p1.depth - p2.depth); // las más cercanas a la cámara, prioridad
513 projected.forEach((p, i) => { p.a.el.style.display = i < MAX_LABELS ? '' : 'none'; });
514 const visible = projected.slice(0, MAX_LABELS).sort((p1, p2) => p1.x - p2.x || p1.y - p2.y);
515 const placed = [];
516 for (const p of visible) {
517 let y = p.y;
518 for (const q of placed) if (Math.abs(q.x - p.x) < LABEL_W && Math.abs(q.y - y) < LABEL_H) y = q.y + LABEL_H;
519 placed.push({ x: p.x, y });
520 p.a.el.style.left = p.x + 'px'; p.a.el.style.top = y + 'px';
521 p.a.el.style.transform = 'translate(-50%,-50%)';
522 }
523}
524const wob = (t, seed, freq = 0.1) => Math.sin(t * freq + seed) * 0.6 + Math.sin(t * freq * 0.43 + seed * 2.1) * 0.3 + Math.sin(t * freq * 0.19 + seed * 4.7) * 0.1;
525
526let elapsed = 0, lastMs = 0, smBass = 0, smMid = 0;
527function startLoop() {
528 if (raf) return;
529 const loop = (ms) => {
530 raf = requestAnimationFrame(loop);
531 const dt = lastMs ? (ms - lastMs) / 1000 : 0;
532 elapsed += dt; lastMs = ms;
533 const t = elapsed;
534 const beat = 60 / 138;
535 const bp = (t % beat) / beat;
536 const bassRaw = Math.pow(1 - bp, 3);
537 const midRaw = 0.5 + 0.5 * Math.sin(t * 6.0);
538 smBass += (bassRaw - smBass) * 0.05;
539 smMid += (midRaw - smMid) * 0.06;
540 S.mat.uniforms.uTime.value = t;
541 S.mat.uniforms.uBass.value = smBass;
542 S.mat.uniforms.uMid.value = smMid;
543 S.galaxy.rotation.y = t * 0.05;
544 S.galaxy.rotation.x = wob(t, 1.7, 0.05) * 0.15;
545 S.galaxy.rotation.z = wob(t, 5.2, 0.04) * 0.1;
546 S.galaxy.scale.setScalar(1 + smBass * 0.02);
547 const pulse = 1 + smBass * 0.05 + Math.sin(t * 0.9) * 0.03;
548 S.core.scale.setScalar(pulse); S.core.rotation.y = t * 0.16; S.core.rotation.x = t * 0.09;
549 S.core.position.x = wob(t, 3.1, 0.11) * 6; S.core.position.z = wob(t, 9.4, 0.09) * 6;
550 S.core.material.color.setHSL((t * 0.04) % 1, 0.9, 0.6);
551 for (const r of S.rings) {
552 r.position.y += 0.14 + smBass * 0.12;
553 if (r.position.y > 74) r.position.y -= 144;
554 r.position.x = wob(t, r.userData.i * 1.3 + 1, 0.08) * 3;
555 r.scale.setScalar(1 + smBass * 0.12 + Math.sin(t * 0.8 + r.userData.i) * 0.04);
556 r.material.opacity = 0.2 + smBass * 0.16;
557 r.material.color.setHSL((t * 0.05 + r.userData.i * 0.03) % 1, 0.85, 0.6);
558 }
559 for (let i = 0; i < thoughtNodes.length; i++) { const n = thoughtNodes[i]; n.rotation.y = t + i; n.scale.setScalar(1 + Math.sin(t * 2 + i) * 0.14); }
560 // estrellas: nacen (fade-in), viven, se apagan solas y se reciclan
561 for (let i = stars.length - 1; i >= 0; i--) {
562 const st = stars[i], age = t - st.born;
563 if (age > st.life) { starGroup.remove(st.obj); st.obj.material.map.dispose(); st.obj.material.dispose(); stars.splice(i, 1); continue; }
564 const fadeIn = Math.min(1, age / 0.5), fadeOut = Math.min(1, (st.life - age) / (st.life * 0.35));
565 st.obj.material.opacity = Math.min(fadeIn, fadeOut);
566 st.obj.position.y += st.up * dt;
567 st.obj.position.x += Math.sin(t * 0.6 + st.seed) * 0.3 * dt;
568 }
569 // haces sobre la ciudad + celdas de fichero resaltadas por actividad
570 for (let i = beams.length - 1; i >= 0; i--) {
571 const b = beams[i], age = t - b.born;
572 if (age > b.life) { S.scene.remove(b.obj); b.obj.geometry.dispose(); b.obj.material.dispose(); beams.splice(i, 1); continue; }
573 b.obj.material.opacity = 0.9 * Math.max(0, 1 - age / b.life);
574 }
575 if (cityCity) for (let i = fileActivity.length - 1; i >= 0; i--) {
576 const a = fileActivity[i], age = t - a.born;
577 if (age > a.life) { cityCity.paintFile(a.id, 0); fileActivity.splice(i, 1); continue; }
578 cityCity.paintFile(a.id, Math.max(0, 1 - age / a.life));
579 }
580 if (flyTo) {
581 const k = Math.min(1, (t - flyTo.t0) / flyTo.dur), e = easeInOut(k);
582 S.camera.position.lerpVectors(flyTo.fromPos, flyTo.toPos, e);
583 S.controls.target.lerpVectors(flyTo.fromTarget, flyTo.toTarget, e);
584 if (k >= 1) flyTo = null;
585 }
586 S.controls.update();
587 projectAnchors();
588 S.composer.render();
589 };
590 loop(performance.now());
591}
592
593export function closeMind() {
594 open = false;
595 if (raf) { cancelAnimationFrame(raf); raf = null; }
596 lastMs = 0;
597 try { widget?.pause(); } catch {}
598 if (overlay) overlay.style.display = 'none';
599}
600
601// para tests/depuración
602export function _debug() {
603 return {
604 starCount: stars.length, hasCity: !!cityCity, profileCount: ceo.getProfiles().length,
605 beamCount: beams.length, fileActivityCount: fileActivity.length,
606 cameraPos: S ? [S.camera.position.x, S.camera.position.y, S.camera.position.z] : null,
607 flying: !!flyTo,
608 };
609}
610export function _debugFocusOn(id) { const p = anchorMap.get(id); if (p) focusOn(p, 46); }