| 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). |
| 11 | import * as THREE from 'three'; |
| 12 | import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; |
| 13 | import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; |
| 14 | import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; |
| 15 | import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; |
| 16 | import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; |
| 17 | import * as ceo from './ceo.js'; |
| 18 | import * as db from './db.js'; |
| 19 | import { renderMarkdown } from './md.js'; |
| 20 | import { t } from './i18n.js'; |
| 21 | import { abrirModal } from './modal.js'; |
| 22 | |
| 23 | const SOUNDCLOUD = 'https://soundcloud.com/dekel-official/dekel-baoba-festival-2023'; |
| 24 | const CEO_COLOR = '#ff4d8d'; |
| 25 | |
| 26 | let open = false, built = false, raf = null; |
| 27 | let overlay, S, widget, onOpenFile = () => {}, onExecute = () => {}; |
| 28 | // La Mente es MODAL (role=dialog, aria-modal): mientras está abierta el IDE de |
| 29 | // detrás queda inerte, el foco entra en ella y al cerrarla vuelve a quien la |
| 30 | // abrió. Antes solo lo declaraba: Tab seguía detrás de la capa —el árbol, la |
| 31 | // pestaña, Monaco— y cada Tab más sangraba el fichero abierto sin verlo. |
| 32 | let cerrarModal = null; |
| 33 | // Ciudad de fondo (vista real del workspace) y semilla de pensamientos previos: |
| 34 | // AMBOS opcionales e inyectados por la app anfitriona — Code tiene un motor |
| 35 | // VibeCodeViewer sobre su proyecto único; Claw (v1) no lo ofrece y la Mente |
| 36 | // funciona igual de bien sin ciudad de fondo. |
| 37 | let loadThoughts = async () => []; // () => [{path, md}] |
| 38 | let buildCityFn = null; // (scene) => {cityWrap, cityCity, cityModel} | null |
| 39 | export function init({ loadThoughts: lt, buildCity: bc } = {}) { |
| 40 | if (lt) loadThoughts = lt; |
| 41 | if (bc) buildCityFn = bc; |
| 42 | } |
| 43 | let anchorMap = new Map(); // id de perfil (+ 'ceo') → Vector3 (anclas del mundo) |
| 44 | const anchors = []; // { el, pos } — solo etiquetas de propuestas forjadas |
| 45 | let nodesGroup, thoughtNodes = []; |
| 46 | let starGroup, stars = []; // estrellas de pensamiento efímeras |
| 47 | const lineBuf = new Map(); // canal → texto acumulado hasta la línea completa |
| 48 | const streamed = new Map(); // canal → ¿llegaron tokens? (evita duplicar el texto final) |
| 49 | let cityWrap = null, cityCity = null, cityModel = null; |
| 50 | let beams = [], fileActivity = []; |
| 51 | |
| 52 | export function isOpen() { return open; } |
| 53 | export function setOpenFile(fn) { onOpenFile = fn; } |
| 54 | export function setExecuteProposal(fn) { onExecute = fn; } |
| 55 | |
| 56 | // También las comillas: estos textos van dentro de atributos (value, title, |
| 57 | // aria-label) y un nombre de perfil con «"» rompía el atributo. |
| 58 | const escHtml = s => String(s).replace(/[<>&"']/g, c => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c])); |
| 59 | const profileOf = channel => channel === 'ceo' |
| 60 | ? { id: 'ceo', name: 'CEO', color: CEO_COLOR } |
| 61 | : ceo.getProfiles().find(p => p.id === channel) || { id: channel, name: channel, color: '#7c5cff' }; |
| 62 | |
| 63 | // ── música: SOLO si la pides ──────────────────────────────────────────────── |
| 64 | // Antes se cargaba un reproductor de SoundCloud con autoplay cada vez que |
| 65 | // abrías la Mente: una petición a un tercero en una app que promete que nada |
| 66 | // sale de tu máquina, y sonido sin haberlo pedido. Ahora hay un botón; el |
| 67 | // reproductor (con su propio control) solo existe mientras lo quieras, y «■ |
| 68 | // Quitar música» lo elimina del todo. |
| 69 | let musicOn = false, musicWrap = null; |
| 70 | function mountMusic(root) { |
| 71 | musicWrap = document.createElement('div'); |
| 72 | musicWrap.className = 'mind-music'; |
| 73 | root.appendChild(musicWrap); |
| 74 | paintMusic(); |
| 75 | } |
| 76 | function paintMusic() { |
| 77 | if (!musicWrap) return; |
| 78 | musicWrap.replaceChildren(); |
| 79 | const btn = document.createElement('button'); |
| 80 | btn.type = 'button'; |
| 81 | btn.className = 'mind-music-btn'; |
| 82 | btn.style.cssText = 'display:block;width:100%;background:rgba(10,6,24,.8);border:none;color:#ffd7e6;padding:7px 12px;font:inherit;font-size:.74rem;cursor:pointer;text-align:center'; |
| 83 | if (!musicOn) { |
| 84 | // Sin reproductor, la caja es solo el botón (sin el marco grande). |
| 85 | musicWrap.style.cssText = 'width:auto;border-radius:999px'; |
| 86 | btn.textContent = t('mindMusic'); |
| 87 | btn.title = t('mindMusicTitle'); |
| 88 | btn.onclick = () => { musicOn = true; paintMusic(); }; |
| 89 | musicWrap.appendChild(btn); |
| 90 | return; |
| 91 | } |
| 92 | musicWrap.style.cssText = ''; |
| 93 | const url = 'https://w.soundcloud.com/player/?url=' + encodeURIComponent(SOUNDCLOUD) + |
| 94 | '&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&visual=false&color=%23ff4d8d'; |
| 95 | const iframe = document.createElement('iframe'); |
| 96 | iframe.id = 'mind-sc'; iframe.title = t('mindMusicPlayer'); iframe.width = '100%'; iframe.height = '120'; |
| 97 | iframe.setAttribute('frameborder', 'no'); iframe.allow = 'autoplay; encrypted-media'; iframe.src = url; |
| 98 | const cap = document.createElement('div'); cap.className = 'mind-music-cap'; cap.textContent = '▶ Dekel · Baoba Festival — modo trance'; |
| 99 | btn.textContent = t('mindMusicOff'); |
| 100 | btn.onclick = () => { musicOn = false; widget = null; paintMusic(); }; |
| 101 | musicWrap.append(iframe, cap, btn); |
| 102 | const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* aún no */ } }; |
| 103 | if (window.SC && window.SC.Widget) initWidget(); |
| 104 | else { const sc = document.createElement('script'); sc.src = 'https://w.soundcloud.com/player/api.js'; sc.onload = initWidget; document.head.appendChild(sc); } |
| 105 | } |
| 106 | |
| 107 | // ══ ESTRELLAS de pensamiento: cada línea/tool-call nace, brilla y se apaga ══ |
| 108 | function makeTextSprite(text, color, { fontSize = 16, bold = false, glow = 10 } = {}) { |
| 109 | const pad = 8; |
| 110 | const probe = document.createElement('canvas').getContext('2d'); |
| 111 | probe.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`; |
| 112 | const w = Math.ceil(probe.measureText(text).width) + pad * 2; |
| 113 | const h = fontSize + pad * 2; |
| 114 | const cv = document.createElement('canvas'); cv.width = w; cv.height = h; |
| 115 | const g = cv.getContext('2d'); |
| 116 | g.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`; |
| 117 | g.textBaseline = 'middle'; |
| 118 | g.shadowColor = color; g.shadowBlur = glow; |
| 119 | g.fillStyle = color; |
| 120 | g.fillText(text, pad, h / 2 + 1); |
| 121 | const tex = new THREE.CanvasTexture(cv); |
| 122 | const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }); |
| 123 | const sprite = new THREE.Sprite(mat); |
| 124 | const scale = 0.09; |
| 125 | sprite.scale.set(w * scale, h * scale, 1); |
| 126 | return sprite; |
| 127 | } |
| 128 | |
| 129 | // kind: 'line' (charla normal) · 'tool' (tool-call) · 'event' (ciclo/estado) · 'built' (propuesta forjada) |
| 130 | const KIND_STYLE = { |
| 131 | line: { fontSize: 13, bold: false, glow: 8, life: 6, jitter: 15 }, |
| 132 | tool: { fontSize: 17, bold: true, glow: 16, life: 9, jitter: 9 }, |
| 133 | event: { fontSize: 20, bold: true, glow: 14, life: 7, jitter: 6 }, |
| 134 | built: { fontSize: 26, bold: true, glow: 22, life: 13, jitter: 4 }, |
| 135 | }; |
| 136 | function spawnStar(channel, text, kind = 'line') { |
| 137 | if (!starGroup || !text) return; |
| 138 | const prof = profileOf(channel); |
| 139 | const st = KIND_STYLE[kind] || KIND_STYLE.line; |
| 140 | const anchor = anchorMap.get(prof.id) || new THREE.Vector3(0, 20, 0); |
| 141 | const j = st.jitter; |
| 142 | const label = kind === 'tool' ? '⟐ ' + text : kind === 'event' ? '★ ' + text : kind === 'built' ? '✦ ' + text : text; |
| 143 | const sprite = makeTextSprite(label.slice(0, kind === 'line' ? 52 : 72), prof.color, st); |
| 144 | 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)); |
| 145 | sprite.material.opacity = 0; |
| 146 | starGroup.add(sprite); |
| 147 | stars.push({ obj: sprite, born: elapsed, life: st.life, seed: Math.random() * 1000, up: kind === 'built' ? 0.5 : 0.22 }); |
| 148 | if (stars.length > 160) { const old = stars.shift(); starGroup.remove(old.obj); old.obj.material.map.dispose(); old.obj.material.dispose(); } |
| 149 | } |
| 150 | |
| 151 | // ── historial COMPLETO (todo lo que llega, sin recortar) — PERSISTENTE: antes |
| 152 | // vivía solo en el DOM/memoria y una recarga de página lo borraba entero. |
| 153 | const LOG_CAP = 500; |
| 154 | let logHistory = []; // [{channel, text}] — se guarda en IndexedDB |
| 155 | let logSaveTimer = null; |
| 156 | function saveLogSoon() { |
| 157 | clearTimeout(logSaveTimer); |
| 158 | logSaveTimer = setTimeout(() => db.set('kv', 'mindLog', logHistory).catch(() => {}), 400); |
| 159 | } |
| 160 | function renderLogRow(channel, text) { |
| 161 | const body = document.getElementById('mind-log-body'); |
| 162 | if (!body) return; |
| 163 | const prof = profileOf(channel); |
| 164 | const row = document.createElement('div'); |
| 165 | row.className = 'ml-row'; |
| 166 | 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>`; |
| 167 | body.appendChild(row); |
| 168 | while (body.children.length > LOG_CAP) body.removeChild(body.firstChild); |
| 169 | body.scrollTop = body.scrollHeight; |
| 170 | } |
| 171 | function logLine(channel, text) { |
| 172 | logHistory.push({ channel, text }); |
| 173 | if (logHistory.length > LOG_CAP) logHistory = logHistory.slice(-LOG_CAP); |
| 174 | saveLogSoon(); |
| 175 | renderLogRow(channel, text); |
| 176 | } |
| 177 | async function loadPersistedLog() { |
| 178 | try { |
| 179 | const saved = await db.get('kv', 'mindLog'); |
| 180 | if (!Array.isArray(saved) || !saved.length) return; |
| 181 | logHistory = saved; |
| 182 | for (const { channel, text } of saved) renderLogRow(channel, text); |
| 183 | } catch { /* aún no hay historial guardado */ } |
| 184 | } |
| 185 | |
| 186 | function flushLine(channel, force = false) { |
| 187 | const buf = (lineBuf.get(channel) || '').trim(); |
| 188 | if (!buf && !force) return; |
| 189 | if (buf) { spawnStar(channel, buf, 'line'); logLine(channel, buf); } |
| 190 | lineBuf.set(channel, ''); |
| 191 | } |
| 192 | |
| 193 | // alimenta estrellas + historial + haces sobre la ciudad (ceo.js → aquí) |
| 194 | export function pushThought(channel, ev) { |
| 195 | if (!open) return; |
| 196 | if (channel === 'sys') { logLine('ceo', ev.text); return; } |
| 197 | if (channel === 'ceo') { |
| 198 | if (ev.type === 'cycle') { logLine('ceo', '● ' + ev.text); spawnStar('ceo', ev.text, 'event'); } |
| 199 | else if (ev.type === 'survey') { logLine('ceo', ev.text); } |
| 200 | else if (ev.type === 'reprogram') { logLine('ceo', '⚙ ' + ev.text); spawnStar('ceo', ev.text, 'event'); if (ev.profiles) rebuildWorld(); } |
| 201 | else if (ev.type === 'paused') { logLine('ceo', ev.text); spawnStar('ceo', ev.text, 'event'); } |
| 202 | else if (ev.type === 'built') { logLine('ceo', '✦ ' + ev.text); spawnStar('ceo', ev.text, 'built'); addThoughtNode(ev); } |
| 203 | else logLine('ceo', ev.text || ''); |
| 204 | return; |
| 205 | } |
| 206 | if (ev.type === 'open') { lineBuf.set(channel, ''); streamed.set(channel, false); } |
| 207 | else if (ev.type === 'token') { |
| 208 | streamed.set(channel, true); |
| 209 | lineBuf.set(channel, (lineBuf.get(channel) || '') + ev.text); |
| 210 | const buf = lineBuf.get(channel); |
| 211 | if (/\n/.test(ev.text) || buf.length > 90) flushLine(channel); |
| 212 | } else if (ev.type === 'tool') { |
| 213 | flushLine(channel); |
| 214 | spawnStar(channel, ev.text, 'tool'); |
| 215 | logLine(channel, '⟐ ' + ev.text); |
| 216 | if (ev.path) fileBeam(ev.path, /escrib/i.test(ev.text) ? 'write' : 'read'); |
| 217 | } else if (ev.type === 'tool_result') { |
| 218 | // el RESULTADO real de la tool (lo que de verdad se leyó/escribió/ejecutó), |
| 219 | // enlazado justo debajo de su tool-call — no solo el nombre de la acción. |
| 220 | const t = '→ ' + (ev.text || '(sin salida)'); |
| 221 | spawnStar(channel, t, 'line'); |
| 222 | logLine(channel, t); |
| 223 | } else if (ev.type === 'done') { |
| 224 | flushLine(channel, true); |
| 225 | // el proveedor puede devolver el texto final SIN pasar por tokens (sin |
| 226 | // streaming) → si no vimos ningún token, esto es lo único que lo muestra. |
| 227 | if (ev.text && !streamed.get(channel)) { spawnStar(channel, ev.text, 'line'); logLine(channel, ev.text); } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // ── nodos de pensamiento clicables (cada .md forjado = un punto brillante) ── |
| 232 | function addThoughtNode({ path, md, text }) { |
| 233 | if (!nodesGroup) return; |
| 234 | const i = thoughtNodes.length; |
| 235 | const a = i * 2.399963; // ángulo áureo |
| 236 | const r = 30 + i * 5; |
| 237 | const mesh = new THREE.Mesh( |
| 238 | new THREE.IcosahedronGeometry(3.2, 0), |
| 239 | new THREE.MeshBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false })); |
| 240 | mesh.position.set(Math.cos(a) * r, 6 + Math.sin(i * 0.7) * 10, Math.sin(a) * r); |
| 241 | mesh.userData = { path, md, text }; |
| 242 | nodesGroup.add(mesh); |
| 243 | thoughtNodes.push(mesh); |
| 244 | // Un BOTÓN, y con pointer-events propios: la hoja de estilos pone |
| 245 | // `pointer-events:none` a las etiquetas y a su contenedor (para que el ratón |
| 246 | // pase al lienzo y se pueda girar la cámara), así que el clic nunca llegaba a |
| 247 | // la etiqueta y solo un raycast con suerte sobre la diminuta malla abría el |
| 248 | // panel. El contenedor sigue sin capturar; la etiqueta sí, y con el teclado. |
| 249 | const lab = document.createElement('button'); |
| 250 | lab.type = 'button'; |
| 251 | lab.className = 'mind-node-label'; |
| 252 | lab.style.pointerEvents = 'auto'; |
| 253 | lab.style.cursor = 'pointer'; |
| 254 | lab.style.fontFamily = 'inherit'; |
| 255 | const nombre = (path || t('mindThought')).split('/').pop(); |
| 256 | lab.textContent = nombre; |
| 257 | lab.setAttribute('aria-label', t('mindOpenProposal', { name: nombre })); |
| 258 | lab.addEventListener('click', () => selectThoughtNode(mesh)); |
| 259 | document.getElementById('mind-anchors').appendChild(lab); |
| 260 | anchors.push({ el: lab, pos: mesh.position }); |
| 261 | mesh.userData.label = lab; |
| 262 | } |
| 263 | |
| 264 | async function loadExistingThoughts() { |
| 265 | try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* aún no hay */ } |
| 266 | } |
| 267 | |
| 268 | // selección de un nodo de propuesta — desde la malla 3D (raycast) o su etiqueta |
| 269 | function selectThoughtNode(mesh) { showThoughtPanel(mesh); focusOn(mesh.position, 26); } |
| 270 | |
| 271 | // Abrir un fichero DESDE la Mente: primero se cierra la Mente. Antes la |
| 272 | // pestaña se abría detrás de esta capa, que lo tapa todo, y parecía que el |
| 273 | // botón no hacía nada. |
| 274 | // «Abrir en el editor»: el foco va al editor (lo pone la app anfitriona al |
| 275 | // abrir el fichero), no de vuelta a la elfa. |
| 276 | function openInEditor(path) { |
| 277 | document.getElementById('mind-panel')?.classList.remove('show'); |
| 278 | closeMind({ devolverFoco: false }); |
| 279 | onOpenFile(path); |
| 280 | } |
| 281 | // Las rutas `entre comillas invertidas` de una propuesta se pueden abrir. |
| 282 | const PATH_RE = /^[\w.-]+(\/[\w.-]+)*\.[a-z0-9]{1,10}$/i; |
| 283 | function linkifyPaths(root) { |
| 284 | root.querySelectorAll('code').forEach(el => { |
| 285 | const p = el.textContent.trim(); |
| 286 | if (!PATH_RE.test(p) || /[{}()<>]/.test(p) || el.closest('pre')) return; |
| 287 | const a = document.createElement('a'); |
| 288 | a.href = '#'; |
| 289 | a.textContent = p; |
| 290 | a.title = t('mindOpenPath', { path: p }); |
| 291 | a.style.cssText = 'color:inherit;text-decoration:underline dotted'; |
| 292 | a.onclick = e => { e.preventDefault(); openInEditor(p); }; |
| 293 | el.replaceChildren(a); |
| 294 | }); |
| 295 | } |
| 296 | |
| 297 | function showThoughtPanel(node) { |
| 298 | const root = document.getElementById('mind-panel'); |
| 299 | const md = node.userData.md || node.userData.text || t('mindEmpty'); |
| 300 | const path = node.userData.path || t('mindThought'); |
| 301 | root.setAttribute('role', 'dialog'); |
| 302 | root.setAttribute('aria-label', path); |
| 303 | root.innerHTML = `<div class="mp-head">${escHtml(path)}<button id="mp-x" aria-label="${escHtml(t('close'))}">✕</button></div>` + |
| 304 | `<div class="mp-body">${renderMarkdown(md)}</div>` + |
| 305 | `<div class="mp-actions">` + |
| 306 | `<button id="mp-exec" class="mp-exec">${escHtml(t('mindExec'))}</button>` + |
| 307 | (node.userData.path ? `<button id="mp-open" class="mp-open">${escHtml(t('mindOpenEditor'))}</button>` : '') + |
| 308 | `</div>`; |
| 309 | root.classList.add('show'); |
| 310 | linkifyPaths(root.querySelector('.mp-body')); |
| 311 | root.querySelector('#mp-x').onclick = () => root.classList.remove('show'); |
| 312 | root.querySelector('#mp-exec').onclick = () => { onExecute(md); root.classList.remove('show'); }; |
| 313 | const openBtn = root.querySelector('#mp-open'); |
| 314 | if (openBtn) openBtn.onclick = () => openInEditor(node.userData.path); |
| 315 | root.querySelector('#mp-exec').focus(); |
| 316 | } |
| 317 | |
| 318 | // ══ perfiles: anclas 3D + leyenda (recalculadas al abrir o al reprogramar) ══ |
| 319 | function computeAnchors() { |
| 320 | const map = new Map(); |
| 321 | map.set('ceo', new THREE.Vector3(0, 46, 0)); |
| 322 | const profs = ceo.getProfiles(); |
| 323 | const n = Math.max(profs.length, 1); |
| 324 | profs.forEach((p, i) => { |
| 325 | const a = (i / n) * Math.PI * 2; |
| 326 | map.set(p.id, new THREE.Vector3(Math.cos(a) * 70, 8 + (i % 2) * 20, Math.sin(a) * 70)); |
| 327 | }); |
| 328 | return map; |
| 329 | } |
| 330 | // Botones (antes <div>: solo con ratón). Llevan la cámara a ese perfil. |
| 331 | function renderLegend() { |
| 332 | const el = document.getElementById('mind-legend'); |
| 333 | if (!el) return; |
| 334 | const profs = ceo.getProfiles(); |
| 335 | const reset = 'background:none;border:none;font:inherit;color:inherit;text-align:left;width:100%'; |
| 336 | el.innerHTML = `<button type="button" class="ml-item" data-id="ceo" style="${reset}"><span class="ml-sw" style="background:${CEO_COLOR}"></span>CEO</button>` + |
| 337 | profs.map(p => `<button type="button" class="ml-item" data-id="${escHtml(p.id)}" style="${reset}"><span class="ml-sw" style="background:${escHtml(p.color)}"></span>${escHtml(p.name)}</button>`).join(''); |
| 338 | el.querySelectorAll('.ml-item').forEach(row => { |
| 339 | row.title = t('mindFlyTo', { name: row.textContent }); |
| 340 | row.onclick = () => { const pos = anchorMap.get(row.dataset.id); if (pos) focusOn(pos, 46); }; |
| 341 | }); |
| 342 | } |
| 343 | // vuelo suave de la cámara hacia un punto — así «clic en algo → la cámara se centra» |
| 344 | let flyTo = null; |
| 345 | function focusOn(pos, distance = 40) { |
| 346 | if (!S) return; |
| 347 | const dir = new THREE.Vector3().subVectors(S.camera.position, S.controls.target); |
| 348 | if (dir.lengthSq() < 0.001) dir.set(0, 0.3, 1); |
| 349 | dir.normalize().multiplyScalar(distance); |
| 350 | flyTo = { fromPos: S.camera.position.clone(), toPos: pos.clone().add(dir), fromTarget: S.controls.target.clone(), toTarget: pos.clone(), t0: elapsed, dur: 1.1 }; |
| 351 | } |
| 352 | const easeInOut = k => k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; |
| 353 | function rebuildWorld() { anchorMap = computeAnchors(); renderLegend(); } |
| 354 | |
| 355 | // ── panel ⚙: reprograma misión, carpeta-alma y PERFILES (editables) ────── |
| 356 | function wireConfig(root) { |
| 357 | const btn = root.querySelector('#mind-config'); |
| 358 | const cfg = root.querySelector('#mind-cfg'); |
| 359 | cfg.setAttribute('role', 'dialog'); |
| 360 | cfg.setAttribute('aria-labelledby', 'cfg-title'); |
| 361 | const profRowHtml = p => `<div class="cfg-prof" data-id="${escHtml(p.id || '')}"> |
| 362 | <input type="color" class="cp-color" value="${escHtml(p.color || '#7c5cff')}" aria-label="${escHtml(t('cfgColor'))}"> |
| 363 | <input type="text" class="cp-name" value="${escHtml(p.name || '')}" placeholder="${escHtml(t('cfgName'))}" aria-label="${escHtml(t('cfgName'))}"> |
| 364 | <input type="text" class="cp-focus" value="${escHtml(p.focus || '')}" placeholder="${escHtml(t('cfgFocus'))}" aria-label="${escHtml(t('cfgFocus'))}"> |
| 365 | <button class="cp-del" title="${escHtml(t('cfgRemove'))}" aria-label="${escHtml(t('cfgRemove'))}">✕</button></div>`; |
| 366 | const notifState = () => (!('Notification' in window)) ? { txt: t('cfgNotifUnsupported'), can: false } |
| 367 | : Notification.permission === 'granted' ? { txt: t('cfgNotifGranted'), can: false } |
| 368 | : Notification.permission === 'denied' ? { txt: t('cfgNotifDenied'), can: false } |
| 369 | : { txt: t('cfgNotifDefault'), can: true }; |
| 370 | const draw = () => { |
| 371 | const profs = ceo.getProfiles(); |
| 372 | const ns = notifState(); |
| 373 | // Etiquetas ASOCIADAS a sus campos (for/id): antes un lector de pantalla |
| 374 | // solo oía el placeholder, o nada. |
| 375 | cfg.innerHTML = |
| 376 | `<div class="cfg-head"><span id="cfg-title">${escHtml(t('cfgTitle'))}</span><button id="cfg-x" aria-label="${escHtml(t('close'))}">✕</button></div>` + |
| 377 | `<div class="cfg-notif">${escHtml(t('cfgNotif'))} ${escHtml(ns.txt)}` + (ns.can ? ` <button id="cfg-notif-ask" class="cfg-notif-btn">${escHtml(t('cfgNotifAsk'))}</button>` : '') + '</div>' + |
| 378 | `<label for="cfg-mission">${escHtml(t('cfgMission'))}</label>` + |
| 379 | '<textarea id="cfg-mission" rows="3">' + escHtml(ceo.getMission()) + '</textarea>' + |
| 380 | `<label for="cfg-dir">${escHtml(t('cfgDir'))}</label>` + |
| 381 | '<input id="cfg-dir" value="' + escHtml(ceo.getSoulDir()) + '">' + |
| 382 | `<label id="cfg-prof-lbl">${escHtml(t('cfgProfiles'))}</label>` + |
| 383 | '<div id="cfg-profiles" role="group" aria-labelledby="cfg-prof-lbl">' + profs.map(profRowHtml).join('') + '</div>' + |
| 384 | `<button id="cfg-add-prof" class="cfg-add">${escHtml(t('cfgAddProf'))}</button>` + |
| 385 | `<div class="cfg-actions"><button id="cfg-think-now" class="cfg-ghost">${escHtml(t('cfgThink'))}</button>` + |
| 386 | `<button id="cfg-save" class="cfg-save">${escHtml(t('cfgSave'))}</button></div>` + |
| 387 | `<div class="cfg-note" id="cfg-note" role="status">${escHtml(t('cfgNote'))}</div>`; |
| 388 | cfg.querySelector('#cfg-x').onclick = () => cfg.classList.remove('show'); |
| 389 | cfg.querySelector('#cfg-notif-ask')?.addEventListener('click', () => { Notification.requestPermission().then(draw); }); |
| 390 | cfg.querySelector('#cfg-add-prof').onclick = () => { |
| 391 | cfg.querySelector('#cfg-profiles').insertAdjacentHTML('beforeend', profRowHtml({ color: '#ff9f45', name: '', focus: '' })); |
| 392 | wireRows(); |
| 393 | }; |
| 394 | // «Pensar ahora» sin modelo de verdad (modo básico) o sin proyecto: se dice |
| 395 | // aquí mismo en vez de cerrar el panel como si hubiera empezado. |
| 396 | cfg.querySelector('#cfg-think-now').onclick = async () => { |
| 397 | const motivo = await ceo.whyNotThink(); |
| 398 | if (motivo) { cfg.querySelector('#cfg-note').textContent = '⚠️ ' + t('cfgCant_' + motivo); return; } |
| 399 | ceo.forceCycle(); |
| 400 | cfg.classList.remove('show'); |
| 401 | }; |
| 402 | cfg.querySelector('#cfg-save').onclick = () => { |
| 403 | // preserva el id original de cada perfil (si no, cada guardado los |
| 404 | // regeneraría desde el nombre y los ciclos en curso perderían el hilo) |
| 405 | const rows = [...cfg.querySelectorAll('.cfg-prof')].map(r => ({ |
| 406 | id: r.dataset.id || undefined, |
| 407 | color: r.querySelector('.cp-color').value, |
| 408 | name: r.querySelector('.cp-name').value.trim(), |
| 409 | focus: r.querySelector('.cp-focus').value.trim(), |
| 410 | })); |
| 411 | ceo.setMission(cfg.querySelector('#cfg-mission').value); |
| 412 | ceo.setSoulDir(cfg.querySelector('#cfg-dir').value); |
| 413 | ceo.setProfiles(rows); |
| 414 | // Reprogramar NO enciende el cerebro: solo ▶ lo hace. Antes lo encendía |
| 415 | // (y lo dejaba guardado), también en modo Básico y también si lo habías |
| 416 | // pausado a propósito, sin que el botón dijera nada de encender. |
| 417 | paintPlay(); |
| 418 | cfg.classList.remove('show'); |
| 419 | root.querySelector('#mind-config')?.focus(); |
| 420 | }; |
| 421 | wireRows(); |
| 422 | function wireRows() { cfg.querySelectorAll('.cp-del').forEach(b => { b.onclick = () => b.closest('.cfg-prof').remove(); }); } |
| 423 | }; |
| 424 | btn.onclick = () => { |
| 425 | if (cfg.classList.contains('show')) { cfg.classList.remove('show'); return; } |
| 426 | draw(); cfg.classList.add('show'); |
| 427 | cfg.querySelector('#cfg-mission')?.focus(); |
| 428 | }; |
| 429 | } |
| 430 | function wireHistory(root) { |
| 431 | const btn = root.querySelector('#mind-history'), panel = root.querySelector('#mind-log'); |
| 432 | btn.onclick = () => panel.classList.toggle('show'); |
| 433 | panel.querySelector('#ml-x').onclick = () => panel.classList.remove('show'); |
| 434 | } |
| 435 | |
| 436 | // play/stop del cerebro, visible dentro de la Mente. La elección la persiste |
| 437 | // ceo.js → sobrevive a recargar. Abrir la Mente YA NO enciende el cerebro: se |
| 438 | // enciende aquí, a propósito, y el botón dice qué hace («activar» la primera |
| 439 | // vez, «reanudar» si lo pausaste). |
| 440 | let paintPlay = () => {}; |
| 441 | function wirePlayStop(root) { |
| 442 | const btn = root.querySelector('#mind-playstop'); |
| 443 | paintPlay = () => { |
| 444 | const on = ceo.isEnabled(); |
| 445 | btn.textContent = on ? t('mindPause') : (ceo.hasDecided() ? t('mindResume') : t('mindActivate')); |
| 446 | btn.title = on ? t('mindPauseTitle') : t('mindActivateTitle', { dir: ceo.getSoulDir() }); |
| 447 | btn.setAttribute('aria-pressed', on ? 'true' : 'false'); |
| 448 | btn.classList.toggle('paused', !on); |
| 449 | }; |
| 450 | btn.onclick = () => { if (ceo.isEnabled()) ceo.disable(); else ceo.enable(); paintPlay(); }; |
| 451 | paintPlay(); |
| 452 | } |
| 453 | |
| 454 | // ══ ciudad de fondo (motor de la app anfitriona, por debajo del mundo) ══════ |
| 455 | async function buildBackgroundCity(scene) { |
| 456 | if (!buildCityFn) return; |
| 457 | try { |
| 458 | const city = await buildCityFn(scene); |
| 459 | if (!city) return; |
| 460 | cityWrap = city.cityWrap; cityCity = city.cityCity; cityModel = city.cityModel; |
| 461 | } catch { /* sigue sin ciudad de fondo */ } |
| 462 | } |
| 463 | // haz de luz que baja hasta el fichero real en la ciudad + resalta su celda |
| 464 | function fileBeam(path, kind) { |
| 465 | if (!cityModel || !cityCity || !S) return; |
| 466 | const rel = String(path).replace(/^\.?\//, ''); |
| 467 | const f = cityModel.fileByRel.get(rel); |
| 468 | if (!f) return; |
| 469 | const local = new THREE.Vector3(f.box.cx, f.box.cy, f.box.cz); |
| 470 | const world = cityWrap.localToWorld(local.clone()); |
| 471 | const top = world.clone(); top.y += 50; |
| 472 | const geo = new THREE.BufferGeometry().setFromPoints([top, world]); |
| 473 | const mat = new THREE.LineBasicMaterial({ color: kind === 'write' ? 0xff4d8d : 0x49e8ff, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false }); |
| 474 | const line = new THREE.Line(geo, mat); |
| 475 | S.scene.add(line); |
| 476 | beams.push({ obj: line, born: elapsed, life: 1.4 }); |
| 477 | fileActivity.push({ id: f.id, born: elapsed, life: 2.2 }); |
| 478 | } |
| 479 | |
| 480 | // ── mundo psicodélico ─────────────────────────────────────────────────────── |
| 481 | function buildScene(canvas, W, H) { |
| 482 | const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true }); |
| 483 | renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); |
| 484 | renderer.setSize(W, H, false); |
| 485 | renderer.toneMapping = THREE.ACESFilmicToneMapping; |
| 486 | const scene = new THREE.Scene(); |
| 487 | const camera = new THREE.PerspectiveCamera(60, W / H, 0.1, 2000); |
| 488 | camera.position.set(0, 40, 150); |
| 489 | const controls = new OrbitControls(camera, canvas); |
| 490 | controls.enableDamping = true; controls.dampingFactor = 0.06; controls.autoRotate = false; |
| 491 | controls.enablePan = false; controls.minDistance = 60; controls.maxDistance = 420; |
| 492 | |
| 493 | const N = 14000; |
| 494 | const pos = new Float32Array(N * 3), rad = new Float32Array(N); |
| 495 | let s = 987654321; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647; |
| 496 | for (let i = 0; i < N; i++) { |
| 497 | const arm = Math.floor(rnd() * 4); |
| 498 | const r = Math.pow(rnd(), 0.6) * 120 + 6; |
| 499 | const a = arm * (Math.PI / 2) + r * 0.03 + (rnd() - 0.5) * 0.5; |
| 500 | const y = (rnd() - 0.5) * (14 - r * 0.06); |
| 501 | pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = y; pos[i * 3 + 2] = Math.sin(a) * r; rad[i] = r; |
| 502 | } |
| 503 | const geo = new THREE.BufferGeometry(); |
| 504 | geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); |
| 505 | geo.setAttribute('aRad', new THREE.BufferAttribute(rad, 1)); |
| 506 | const mat = new THREE.ShaderMaterial({ |
| 507 | uniforms: { uTime: { value: 0 }, uBass: { value: 0 }, uMid: { value: 0 } }, |
| 508 | transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, |
| 509 | vertexShader: `uniform float uTime, uBass, uMid; attribute float aRad; varying vec3 vC; |
| 510 | 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.);} |
| 511 | 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)); } |
| 512 | float vnoise(vec3 x){ vec3 i=floor(x),f=fract(x); f=f*f*(3.0-2.0*f); |
| 513 | 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), |
| 514 | 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); } |
| 515 | 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; } |
| 516 | void main(){ |
| 517 | vec3 pos=position; |
| 518 | float n=fbm(pos*0.03 + vec3(0.0,uTime*0.18,0.0)); |
| 519 | pos += normalize(pos+0.001) * (n-0.5) * (5.0 + uMid*4.0 + uBass*7.0); |
| 520 | float sw = uTime*0.14 + aRad*0.015 + uBass*0.18; |
| 521 | float cs=cos(sw), sn=sin(sw); |
| 522 | pos.xz = mat2(cs,-sn,sn,cs) * pos.xz; |
| 523 | pos *= (1.0 + uBass*0.05); |
| 524 | 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); |
| 525 | vec4 mv=modelViewMatrix*vec4(pos,1.0); gl_PointSize=(2.2+60.0/-mv.z)*(1.0+uBass*0.18); gl_Position=projectionMatrix*mv; }`, |
| 526 | 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); }`, |
| 527 | }); |
| 528 | const galaxy = new THREE.Points(geo, mat); scene.add(galaxy); |
| 529 | const core = new THREE.LineSegments(new THREE.WireframeGeometry(new THREE.IcosahedronGeometry(18, 1)), |
| 530 | new THREE.LineBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false })); |
| 531 | scene.add(core); |
| 532 | const rings = []; |
| 533 | for (let i = 0; i < 24; i++) { |
| 534 | const ring = new THREE.Mesh(new THREE.TorusGeometry(22, 0.5, 8, 80), |
| 535 | new THREE.MeshBasicMaterial({ color: 0x7c5cff, transparent: true, opacity: 0.45, blending: THREE.AdditiveBlending, depthWrite: false })); |
| 536 | ring.rotation.x = Math.PI / 2; ring.position.y = -70 + i * 6; ring.userData.i = i; |
| 537 | scene.add(ring); rings.push(ring); |
| 538 | } |
| 539 | nodesGroup = new THREE.Group(); scene.add(nodesGroup); |
| 540 | starGroup = new THREE.Group(); scene.add(starGroup); |
| 541 | const composer = new EffectComposer(renderer); |
| 542 | composer.setSize(W, H); composer.addPass(new RenderPass(scene, camera)); |
| 543 | const bloom = new UnrealBloomPass(new THREE.Vector2(W, H), 1.1, 0.5, 0.2); |
| 544 | composer.addPass(bloom); composer.addPass(new OutputPass()); |
| 545 | return { renderer, scene, camera, controls, composer, bloom, mat, galaxy, core, rings }; |
| 546 | } |
| 547 | |
| 548 | export async function openMind() { |
| 549 | if (open) return; |
| 550 | open = true; |
| 551 | if (built) { |
| 552 | overlay.style.display = ''; |
| 553 | cerrarModal = abrirModal(overlay, { foco: '#mind-close' }); |
| 554 | if (musicOn) { try { widget?.play(); } catch {} } |
| 555 | paintPlay(); startLoop(); return; |
| 556 | } |
| 557 | |
| 558 | overlay = document.createElement('div'); |
| 559 | overlay.id = 'mind-overlay'; |
| 560 | overlay.setAttribute('role', 'dialog'); |
| 561 | overlay.setAttribute('aria-modal', 'true'); |
| 562 | overlay.setAttribute('aria-label', t('mindTitle')); |
| 563 | overlay.innerHTML = |
| 564 | '<canvas id="mind-canvas" aria-hidden="true"></canvas>' + |
| 565 | `<div id="mind-title">${t('mindTitle')}</div>` + |
| 566 | `<div id="mind-legend" role="group" aria-label="${escHtml(t('mindLegend'))}"></div>` + |
| 567 | '<button id="mind-playstop"></button>' + |
| 568 | `<button id="mind-config" title="${escHtml(t('mindConfigTitle'))}">${escHtml(t('mindConfig'))}</button>` + |
| 569 | `<button id="mind-history" title="${escHtml(t('mindHistoryTitle'))}">${escHtml(t('mindHistory'))}</button>` + |
| 570 | `<button id="mind-close" title="${escHtml(t('mindCloseTitle'))}">${escHtml(t('mindClose'))}</button>` + |
| 571 | '<div id="mind-anchors"></div><div id="mind-panel"></div><div id="mind-cfg"></div>' + |
| 572 | `<div id="mind-log"><div class="ml-head">${escHtml(t('mindLogTitle'))}<button id="ml-x" aria-label="${escHtml(t('close'))}">✕</button></div><div id="mind-log-body" role="log"></div></div>`; |
| 573 | document.body.appendChild(overlay); |
| 574 | cerrarModal = abrirModal(overlay, { foco: '#mind-close' }); |
| 575 | wireConfig(overlay); wireHistory(overlay); wirePlayStop(overlay); |
| 576 | mountMusic(overlay); |
| 577 | anchors.length = 0; thoughtNodes = []; stars = []; lineBuf.clear(); |
| 578 | rebuildWorld(); |
| 579 | |
| 580 | const canvas = overlay.querySelector('#mind-canvas'); |
| 581 | S = buildScene(canvas, window.innerWidth, window.innerHeight); |
| 582 | buildBackgroundCity(S.scene); |
| 583 | await loadExistingThoughts(); |
| 584 | await loadPersistedLog(); // el historial de «≡ historial» sobrevive a recargas |
| 585 | |
| 586 | const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(); |
| 587 | let downXY = null; |
| 588 | canvas.addEventListener('pointerdown', e => { downXY = [e.clientX, e.clientY]; }); |
| 589 | canvas.addEventListener('pointerup', e => { |
| 590 | if (!downXY) return; const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]); downXY = null; |
| 591 | if (moved > 5 || !thoughtNodes.length) return; |
| 592 | ptr.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1); |
| 593 | ray.setFromCamera(ptr, S.camera); |
| 594 | const hit = ray.intersectObjects(thoughtNodes)[0]; |
| 595 | if (hit) selectThoughtNode(hit.object); |
| 596 | }); |
| 597 | |
| 598 | const onResize = () => { |
| 599 | const w = window.innerWidth, h = window.innerHeight; |
| 600 | S.renderer.setSize(w, h, false); S.composer.setSize(w, h); S.bloom.resolution.set(w, h); |
| 601 | S.camera.aspect = w / h; S.camera.updateProjectionMatrix(); |
| 602 | }; |
| 603 | window.addEventListener('resize', onResize); S.onResize = onResize; |
| 604 | overlay.querySelector('#mind-close').addEventListener('click', () => closeMind()); |
| 605 | S.onKey = e => { if (e.key === 'Escape') closeMind(); }; |
| 606 | document.addEventListener('keydown', S.onKey); |
| 607 | built = true; |
| 608 | startLoop(); |
| 609 | } |
| 610 | |
| 611 | // Etiquetas de propuestas: se proyectan del mundo 3D a la pantalla, así que |
| 612 | // con muchas acumuladas acaban solapándose ilegibles según el ángulo de |
| 613 | // cámara. Aquí: cap a las más cercanas y reparto anti-solape (empuja hacia |
| 614 | // abajo la que choca con otra ya colocada), para que se apilen separadas. |
| 615 | const MAX_LABELS = 14, LABEL_W = 90, LABEL_H = 20; |
| 616 | function projectAnchors() { |
| 617 | const w = window.innerWidth, h = window.innerHeight, v = new THREE.Vector3(); |
| 618 | const projected = []; |
| 619 | for (const a of anchors) { |
| 620 | v.copy(a.pos).project(S.camera); |
| 621 | if (v.z > 1) { a.el.style.display = 'none'; continue; } // detrás de la cámara |
| 622 | projected.push({ a, x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, depth: v.z }); |
| 623 | } |
| 624 | projected.sort((p1, p2) => p1.depth - p2.depth); // las más cercanas a la cámara, prioridad |
| 625 | projected.forEach((p, i) => { p.a.el.style.display = i < MAX_LABELS ? '' : 'none'; }); |
| 626 | const visible = projected.slice(0, MAX_LABELS).sort((p1, p2) => p1.x - p2.x || p1.y - p2.y); |
| 627 | const placed = []; |
| 628 | for (const p of visible) { |
| 629 | let y = p.y; |
| 630 | 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; |
| 631 | placed.push({ x: p.x, y }); |
| 632 | p.a.el.style.left = p.x + 'px'; p.a.el.style.top = y + 'px'; |
| 633 | p.a.el.style.transform = 'translate(-50%,-50%)'; |
| 634 | } |
| 635 | } |
| 636 | const 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; |
| 637 | |
| 638 | let elapsed = 0, lastMs = 0, smBass = 0, smMid = 0; |
| 639 | function startLoop() { |
| 640 | if (raf) return; |
| 641 | const loop = (ms) => { |
| 642 | raf = requestAnimationFrame(loop); |
| 643 | const dt = lastMs ? (ms - lastMs) / 1000 : 0; |
| 644 | elapsed += dt; lastMs = ms; |
| 645 | const t = elapsed; |
| 646 | const beat = 60 / 138; |
| 647 | const bp = (t % beat) / beat; |
| 648 | const bassRaw = Math.pow(1 - bp, 3); |
| 649 | const midRaw = 0.5 + 0.5 * Math.sin(t * 6.0); |
| 650 | smBass += (bassRaw - smBass) * 0.05; |
| 651 | smMid += (midRaw - smMid) * 0.06; |
| 652 | S.mat.uniforms.uTime.value = t; |
| 653 | S.mat.uniforms.uBass.value = smBass; |
| 654 | S.mat.uniforms.uMid.value = smMid; |
| 655 | S.galaxy.rotation.y = t * 0.05; |
| 656 | S.galaxy.rotation.x = wob(t, 1.7, 0.05) * 0.15; |
| 657 | S.galaxy.rotation.z = wob(t, 5.2, 0.04) * 0.1; |
| 658 | S.galaxy.scale.setScalar(1 + smBass * 0.02); |
| 659 | const pulse = 1 + smBass * 0.05 + Math.sin(t * 0.9) * 0.03; |
| 660 | S.core.scale.setScalar(pulse); S.core.rotation.y = t * 0.16; S.core.rotation.x = t * 0.09; |
| 661 | S.core.position.x = wob(t, 3.1, 0.11) * 6; S.core.position.z = wob(t, 9.4, 0.09) * 6; |
| 662 | S.core.material.color.setHSL((t * 0.04) % 1, 0.9, 0.6); |
| 663 | for (const r of S.rings) { |
| 664 | r.position.y += 0.14 + smBass * 0.12; |
| 665 | if (r.position.y > 74) r.position.y -= 144; |
| 666 | r.position.x = wob(t, r.userData.i * 1.3 + 1, 0.08) * 3; |
| 667 | r.scale.setScalar(1 + smBass * 0.12 + Math.sin(t * 0.8 + r.userData.i) * 0.04); |
| 668 | r.material.opacity = 0.2 + smBass * 0.16; |
| 669 | r.material.color.setHSL((t * 0.05 + r.userData.i * 0.03) % 1, 0.85, 0.6); |
| 670 | } |
| 671 | 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); } |
| 672 | // estrellas: nacen (fade-in), viven, se apagan solas y se reciclan |
| 673 | for (let i = stars.length - 1; i >= 0; i--) { |
| 674 | const st = stars[i], age = t - st.born; |
| 675 | if (age > st.life) { starGroup.remove(st.obj); st.obj.material.map.dispose(); st.obj.material.dispose(); stars.splice(i, 1); continue; } |
| 676 | const fadeIn = Math.min(1, age / 0.5), fadeOut = Math.min(1, (st.life - age) / (st.life * 0.35)); |
| 677 | st.obj.material.opacity = Math.min(fadeIn, fadeOut); |
| 678 | st.obj.position.y += st.up * dt; |
| 679 | st.obj.position.x += Math.sin(t * 0.6 + st.seed) * 0.3 * dt; |
| 680 | } |
| 681 | // haces sobre la ciudad + celdas de fichero resaltadas por actividad |
| 682 | for (let i = beams.length - 1; i >= 0; i--) { |
| 683 | const b = beams[i], age = t - b.born; |
| 684 | if (age > b.life) { S.scene.remove(b.obj); b.obj.geometry.dispose(); b.obj.material.dispose(); beams.splice(i, 1); continue; } |
| 685 | b.obj.material.opacity = 0.9 * Math.max(0, 1 - age / b.life); |
| 686 | } |
| 687 | if (cityCity) for (let i = fileActivity.length - 1; i >= 0; i--) { |
| 688 | const a = fileActivity[i], age = t - a.born; |
| 689 | if (age > a.life) { cityCity.paintFile(a.id, 0); fileActivity.splice(i, 1); continue; } |
| 690 | cityCity.paintFile(a.id, Math.max(0, 1 - age / a.life)); |
| 691 | } |
| 692 | if (flyTo) { |
| 693 | const k = Math.min(1, (t - flyTo.t0) / flyTo.dur), e = easeInOut(k); |
| 694 | S.camera.position.lerpVectors(flyTo.fromPos, flyTo.toPos, e); |
| 695 | S.controls.target.lerpVectors(flyTo.fromTarget, flyTo.toTarget, e); |
| 696 | if (k >= 1) flyTo = null; |
| 697 | } |
| 698 | S.controls.update(); |
| 699 | projectAnchors(); |
| 700 | S.composer.render(); |
| 701 | }; |
| 702 | loop(performance.now()); |
| 703 | } |
| 704 | |
| 705 | // `devolverFoco: false` cuando quien cierra lleva el foco a otro sitio (el editor). |
| 706 | export function closeMind({ devolverFoco = true } = {}) { |
| 707 | open = false; |
| 708 | if (raf) { cancelAnimationFrame(raf); raf = null; } |
| 709 | lastMs = 0; |
| 710 | try { widget?.pause(); } catch {} |
| 711 | if (overlay) overlay.style.display = 'none'; |
| 712 | cerrarModal?.({ devolverFoco: devolverFoco !== false }); |
| 713 | cerrarModal = null; |
| 714 | } |
| 715 | |
| 716 | // para tests/depuración |
| 717 | export function _debug() { |
| 718 | return { |
| 719 | starCount: stars.length, hasCity: !!cityCity, profileCount: ceo.getProfiles().length, |
| 720 | beamCount: beams.length, fileActivityCount: fileActivity.length, |
| 721 | cameraPos: S ? [S.camera.position.x, S.camera.position.y, S.camera.position.z] : null, |
| 722 | flying: !!flyTo, |
| 723 | }; |
| 724 | } |
| 725 | export function _debugFocusOn(id) { const p = anchorMap.get(id); if (p) focusOn(p, 46); } |