| 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 mindLog from './mind-log.js'; |
| 19 | import { abrirModal } from './modal.js'; |
| 20 | import { renderMarkdown } from './md.js'; |
| 21 | import { t } from './i18n.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 | let etiquetaAbrir = null; // texto del botón que abre el fichero de una propuesta |
| 29 | let cerrarModal = null; // devuelve el foco y la página de detrás (modal.js) |
| 30 | let musicaPuesta = false; // la música es opcional: solo suena si la pides |
| 31 | let pintarPlayStop = () => {}; |
| 32 | let logMontado = false; |
| 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 | // Dónde escribe el cerebro, dicho con el nombre de verdad: «dentro del proyecto» |
| 40 | // es cosa de Code; en Claw es la primera carpeta autorizada. () => Promise<texto> |
| 41 | let etiquetaAlma = async () => t('mindSoulDir'); |
| 42 | // Por qué no puede pensar ahora mismo (sin modelo, sin carpeta…), o null. |
| 43 | let motivoNoPensar = async () => null; |
| 44 | export function init({ loadThoughts: lt, buildCity: bc, etiquetaAlma: ea, motivoNoPensar: mn } = {}) { |
| 45 | if (lt) loadThoughts = lt; |
| 46 | if (bc) buildCityFn = bc; |
| 47 | if (ea) etiquetaAlma = ea; |
| 48 | if (mn) motivoNoPensar = mn; |
| 49 | } |
| 50 | let anchorMap = new Map(); // id de perfil (+ 'ceo') → Vector3 (anclas del mundo) |
| 51 | const anchors = []; // { el, pos } — solo etiquetas de propuestas forjadas |
| 52 | let nodesGroup, thoughtNodes = []; |
| 53 | let starGroup, stars = []; // estrellas de pensamiento efímeras |
| 54 | let cityWrap = null, cityCity = null, cityModel = null; |
| 55 | let beams = [], fileActivity = []; |
| 56 | |
| 57 | export function isOpen() { return open; } |
| 58 | // `etiqueta`: cómo se llama el botón en ESTA app. «Abrir en el editor» es de |
| 59 | // Code; Claw no tiene editor y lee el fichero en el chat. |
| 60 | export function setOpenFile(fn, { etiqueta = null } = {}) { onOpenFile = fn; etiquetaAbrir = etiqueta; } |
| 61 | // `fn(md)` devuelve false si no la ejecutó (p. ej. sin modelo): el panel de la |
| 62 | // propuesta se queda abierto en vez de cerrarse como si hubiera arrancado. |
| 63 | export function setExecuteProposal(fn) { onExecute = fn; } |
| 64 | // En Básico el panel de la propuesta no enseña «Ejecutar» (lo esconde el CSS con |
| 65 | // body.modo-basico) sino que hace falta un modelo, con un botón que lleva a |
| 66 | // elegirlo: lo que haga ese botón lo pone la app anfitriona. |
| 67 | let onElegirModelo = null; |
| 68 | export function setElegirModelo(fn) { onElegirModelo = fn; } |
| 69 | // Lo que hace la app anfitriona al cerrarse la Mente (Claw devuelve la URL a la |
| 70 | // pestaña de debajo: ver kernel.js). |
| 71 | let onCerrar = () => {}; |
| 72 | export function alCerrar(fn) { onCerrar = typeof fn === 'function' ? fn : () => {}; } |
| 73 | |
| 74 | const escHtml = s => String(s).replace(/[<>&"]/g, c => ({ '<': '<', '>': '>', '&': '&', '"': '"' }[c])); |
| 75 | const profileOf = channel => channel === 'ceo' |
| 76 | ? { id: 'ceo', name: 'CEO', color: CEO_COLOR } |
| 77 | : ceo.getProfiles().find(p => p.id === channel) || { id: channel, name: channel, color: '#7c5cff' }; |
| 78 | |
| 79 | // ── música: SOLO si la pides ──────────────────────────────────────────────── |
| 80 | // Antes, abrir la Mente incrustaba el reproductor de SoundCloud con autoplay y |
| 81 | // cargaba su api.js: una página de un tercero contactada sin pedirlo, en una |
| 82 | // app que promete que nada sale de tu máquina. Ahora hay un botón; hasta que lo |
| 83 | // pulsas no se carga nada de fuera, y hay un enlace normal a la pista. |
| 84 | function wireMusic(root) { |
| 85 | const btn = root.querySelector('#mind-music-btn'); |
| 86 | const pintar = () => { |
| 87 | btn.textContent = musicaPuesta ? t('mindMusicOff') : t('mindMusicOn'); |
| 88 | btn.setAttribute('aria-pressed', musicaPuesta ? 'true' : 'false'); |
| 89 | }; |
| 90 | btn.onclick = () => { |
| 91 | musicaPuesta = !musicaPuesta; |
| 92 | if (musicaPuesta) mountMusic(root); else unmountMusic(root); |
| 93 | pintar(); |
| 94 | }; |
| 95 | pintar(); |
| 96 | } |
| 97 | function mountMusic(root) { |
| 98 | if (root.querySelector('.mind-music')) return; |
| 99 | const wrap = document.createElement('div'); |
| 100 | wrap.className = 'mind-music'; |
| 101 | const url = 'https://w.soundcloud.com/player/?url=' + encodeURIComponent(SOUNDCLOUD) + |
| 102 | '&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&visual=false&color=%23ff4d8d'; |
| 103 | wrap.innerHTML = '<iframe id="mind-sc" title="' + escHtml(t('mindMusicT')) + '" width="100%" height="120" frameborder="no" allow="autoplay; encrypted-media" src="' + url + '"></iframe>' + |
| 104 | '<div class="mind-music-cap">▶ Dekel · Baoba Festival — <a href="' + SOUNDCLOUD + '" target="_blank" rel="noopener noreferrer">SoundCloud ↗</a></div>'; |
| 105 | root.appendChild(wrap); |
| 106 | const iframe = wrap.querySelector('#mind-sc'); |
| 107 | const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* aún no */ } }; |
| 108 | if (window.SC && window.SC.Widget) initWidget(); |
| 109 | else { const s = document.createElement('script'); s.src = 'https://w.soundcloud.com/player/api.js'; s.onload = initWidget; document.head.appendChild(s); } |
| 110 | } |
| 111 | function unmountMusic(root) { |
| 112 | try { widget?.pause(); } catch { /* — */ } |
| 113 | widget = null; |
| 114 | root.querySelector('.mind-music')?.remove(); |
| 115 | } |
| 116 | |
| 117 | // ══ ESTRELLAS de pensamiento: cada línea/tool-call nace, brilla y se apaga ══ |
| 118 | function makeTextSprite(text, color, { fontSize = 16, bold = false, glow = 10 } = {}) { |
| 119 | const pad = 8; |
| 120 | const probe = document.createElement('canvas').getContext('2d'); |
| 121 | probe.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`; |
| 122 | const w = Math.ceil(probe.measureText(text).width) + pad * 2; |
| 123 | const h = fontSize + pad * 2; |
| 124 | const cv = document.createElement('canvas'); cv.width = w; cv.height = h; |
| 125 | const g = cv.getContext('2d'); |
| 126 | g.font = `${bold ? 700 : 500} ${fontSize}px ui-monospace, Menlo, monospace`; |
| 127 | g.textBaseline = 'middle'; |
| 128 | g.shadowColor = color; g.shadowBlur = glow; |
| 129 | g.fillStyle = color; |
| 130 | g.fillText(text, pad, h / 2 + 1); |
| 131 | const tex = new THREE.CanvasTexture(cv); |
| 132 | const mat = new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }); |
| 133 | const sprite = new THREE.Sprite(mat); |
| 134 | const scale = 0.09; |
| 135 | sprite.scale.set(w * scale, h * scale, 1); |
| 136 | return sprite; |
| 137 | } |
| 138 | |
| 139 | // kind: 'line' (charla normal) · 'tool' (tool-call) · 'event' (ciclo/estado) · 'built' (propuesta forjada) |
| 140 | const KIND_STYLE = { |
| 141 | line: { fontSize: 13, bold: false, glow: 8, life: 6, jitter: 15 }, |
| 142 | tool: { fontSize: 17, bold: true, glow: 16, life: 9, jitter: 9 }, |
| 143 | event: { fontSize: 20, bold: true, glow: 14, life: 7, jitter: 6 }, |
| 144 | built: { fontSize: 26, bold: true, glow: 22, life: 13, jitter: 4 }, |
| 145 | }; |
| 146 | function spawnStar(channel, text, kind = 'line') { |
| 147 | if (!starGroup || !text) return; |
| 148 | const prof = profileOf(channel); |
| 149 | const st = KIND_STYLE[kind] || KIND_STYLE.line; |
| 150 | const anchor = anchorMap.get(prof.id) || new THREE.Vector3(0, 20, 0); |
| 151 | const j = st.jitter; |
| 152 | const label = kind === 'tool' ? '⟐ ' + text : kind === 'event' ? '★ ' + text : kind === 'built' ? '✦ ' + text : text; |
| 153 | const sprite = makeTextSprite(label.slice(0, kind === 'line' ? 52 : 72), prof.color, st); |
| 154 | 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)); |
| 155 | sprite.material.opacity = 0; |
| 156 | starGroup.add(sprite); |
| 157 | stars.push({ obj: sprite, born: elapsed, life: st.life, seed: Math.random() * 1000, up: kind === 'built' ? 0.5 : 0.22 }); |
| 158 | if (stars.length > 160) { const old = stars.shift(); starGroup.remove(old.obj); old.obj.material.map.dispose(); old.obj.material.dispose(); } |
| 159 | } |
| 160 | |
| 161 | // ── historial COMPLETO (todo lo que llega, sin recortar) ──────────────────── |
| 162 | // Lo lleva mind-log.js, con la Mente abierta o cerrada; aquí solo se pinta. |
| 163 | const LOG_CAP = 500; |
| 164 | function renderLogRow({ channel, text, path }) { |
| 165 | const body = document.getElementById('mind-log-body'); |
| 166 | if (!body) return; |
| 167 | const prof = profileOf(channel); |
| 168 | const row = document.createElement('div'); |
| 169 | row.className = 'ml-row'; |
| 170 | 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>`; |
| 171 | // Una propuesta guardada se puede abrir desde su línea (antes la ruta era |
| 172 | // texto suelto). |
| 173 | if (path) { |
| 174 | const b = document.createElement('button'); |
| 175 | b.type = 'button'; |
| 176 | b.className = 'ml-open'; |
| 177 | b.textContent = t('mindOpenProposal'); |
| 178 | b.title = path; |
| 179 | b.onclick = () => mostrarPropuesta(path); |
| 180 | row.appendChild(b); |
| 181 | } |
| 182 | body.appendChild(row); |
| 183 | while (body.children.length > LOG_CAP) body.removeChild(body.firstChild); |
| 184 | body.scrollTop = body.scrollHeight; |
| 185 | } |
| 186 | mindLog.suscribir(l => { |
| 187 | if (logMontado) renderLogRow(l); |
| 188 | if (open && l.estrella) spawnStar(l.channel, l.estrella[1], l.estrella[0]); |
| 189 | }); |
| 190 | |
| 191 | // Último «no puedo» del cerebro (sin modelo, otra pestaña lo lleva…): el panel |
| 192 | // ⚙ lo enseña cuando «Pensar ahora» no arranca, en vez de cerrarse sin más. |
| 193 | let ultimoAviso = ''; |
| 194 | |
| 195 | // ceo.js → aquí. El historial se apunta SIEMPRE (mind-log.js); lo que solo se |
| 196 | // dibuja —nodos, haces, perfiles— necesita el mundo montado. |
| 197 | export function pushThought(channel, ev) { |
| 198 | if (!ev) return; |
| 199 | mindLog.registrar(channel, ev); |
| 200 | if (channel === 'sys') { pintarPlayStop(); return; } |
| 201 | if (channel === 'ceo' && ev.type === 'paused') ultimoAviso = ev.text || ''; |
| 202 | if (channel === 'ceo' && ev.type === 'built') forjadaAhora = true; |
| 203 | if (!built) return; |
| 204 | if (channel === 'ceo') { |
| 205 | if (ev.type === 'reprogram' && ev.profiles) rebuildWorld(); |
| 206 | else if (ev.type === 'built') addThoughtNode(ev); |
| 207 | return; |
| 208 | } |
| 209 | if (open && ev.type === 'tool' && ev.path) fileBeam(ev.path, /escrib/i.test(ev.text) ? 'write' : 'read'); |
| 210 | } |
| 211 | |
| 212 | // ── nodos de pensamiento clicables (cada .md forjado = un punto brillante) ── |
| 213 | function addThoughtNode({ path, md, text }) { |
| 214 | if (!nodesGroup) return; |
| 215 | const i = thoughtNodes.length; |
| 216 | const a = i * 2.399963; // ángulo áureo |
| 217 | const r = 30 + i * 5; |
| 218 | const mesh = new THREE.Mesh( |
| 219 | new THREE.IcosahedronGeometry(3.2, 0), |
| 220 | new THREE.MeshBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false })); |
| 221 | mesh.position.set(Math.cos(a) * r, 6 + Math.sin(i * 0.7) * 10, Math.sin(a) * r); |
| 222 | mesh.userData = { path, md, text }; |
| 223 | nodesGroup.add(mesh); |
| 224 | thoughtNodes.push(mesh); |
| 225 | // Un <button>: se alcanza con el teclado y es clicable ENTERO. Antes era un |
| 226 | // div con pointer-events:none (heredado de su capa): su clic no llegaba nunca |
| 227 | // y solo funcionaba atinar a la malla 3D que hubiera debajo. |
| 228 | const lab = document.createElement('button'); |
| 229 | lab.type = 'button'; |
| 230 | lab.className = 'mind-node-label'; |
| 231 | lab.textContent = (path || t('mindThought')).split('/').pop(); |
| 232 | lab.title = path || ''; |
| 233 | lab.addEventListener('click', () => selectThoughtNode(mesh)); |
| 234 | document.getElementById('mind-anchors').appendChild(lab); |
| 235 | anchors.push({ el: lab, pos: mesh.position }); |
| 236 | mesh.userData.label = lab; |
| 237 | } |
| 238 | |
| 239 | async function loadExistingThoughts() { |
| 240 | try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* aún no hay */ } |
| 241 | } |
| 242 | |
| 243 | // selección de un nodo de propuesta — desde la malla 3D (raycast) o su etiqueta |
| 244 | function selectThoughtNode(mesh) { showThoughtPanel(mesh); focusOn(mesh.position, 26); } |
| 245 | |
| 246 | // Abrir una propuesta por su ruta (#/mente/<ruta>, una notificación, el |
| 247 | // historial). Si su nodo no está —se guardó con la Mente sin montar y no estaba |
| 248 | // en la carpeta al abrirla—, se enseña lo que se sepa de ella. |
| 249 | export function mostrarPropuesta(path) { |
| 250 | if (!built || !path) return false; |
| 251 | const node = thoughtNodes.find(n => n.userData.path === path); |
| 252 | if (node) { selectThoughtNode(node); return true; } |
| 253 | return false; |
| 254 | } |
| 255 | |
| 256 | function showThoughtPanel(node) { |
| 257 | const root = document.getElementById('mind-panel'); |
| 258 | const md = node.userData.md || node.userData.text || '(sin contenido)'; |
| 259 | const path = node.userData.path || t('mindThought'); |
| 260 | root.innerHTML = `<div class="mp-head"><span class="mp-path"></span><button id="mp-x" type="button">✕</button></div>` + |
| 261 | `<div class="mp-body">${renderMarkdown(md)}</div>` + |
| 262 | `<div class="mp-actions">` + |
| 263 | `<button id="mp-exec" type="button" class="mp-exec">${escHtml(t('mindRunProposal'))}</button>` + |
| 264 | (onElegirModelo ? `<div class="proposal-needs-model mp-needs-model">${escHtml(t('proposalNeedsModelShort'))} <button id="mp-pick" type="button">${escHtml(t('pickModel'))}</button></div>` : '') + |
| 265 | (node.userData.path ? `<button id="mp-open" type="button" class="mp-open">${escHtml(etiquetaAbrir || t('mindOpenEditor'))}</button>` : '') + |
| 266 | `</div>`; |
| 267 | root.querySelector('.mp-path').textContent = path; |
| 268 | root.setAttribute('role', 'region'); |
| 269 | root.setAttribute('aria-label', path); |
| 270 | root.classList.add('show'); |
| 271 | const x = root.querySelector('#mp-x'); |
| 272 | x.setAttribute('aria-label', t('close')); |
| 273 | x.onclick = () => root.classList.remove('show'); |
| 274 | root.querySelector('#mp-exec').onclick = () => { if (onExecute(md) !== false) root.classList.remove('show'); }; |
| 275 | const openBtn = root.querySelector('#mp-open'); |
| 276 | if (openBtn) openBtn.onclick = () => { onOpenFile(node.userData.path); root.classList.remove('show'); }; |
| 277 | const pick = root.querySelector('#mp-pick'); |
| 278 | if (pick) pick.onclick = () => onElegirModelo?.(); |
| 279 | // El foco, al primer botón que se vea («Ejecutar», o «Elegir modelo» en Básico). |
| 280 | const primero = ['#mp-exec', '#mp-pick', '#mp-open'].map(s => root.querySelector(s)).find(b => b && b.getClientRects().length); |
| 281 | primero?.focus({ preventScroll: true }); |
| 282 | } |
| 283 | |
| 284 | // ══ perfiles: anclas 3D + leyenda (recalculadas al abrir o al reprogramar) ══ |
| 285 | function computeAnchors() { |
| 286 | const map = new Map(); |
| 287 | map.set('ceo', new THREE.Vector3(0, 46, 0)); |
| 288 | const profs = ceo.getProfiles(); |
| 289 | const n = Math.max(profs.length, 1); |
| 290 | profs.forEach((p, i) => { |
| 291 | const a = (i / n) * Math.PI * 2; |
| 292 | map.set(p.id, new THREE.Vector3(Math.cos(a) * 70, 8 + (i % 2) * 20, Math.sin(a) * 70)); |
| 293 | }); |
| 294 | return map; |
| 295 | } |
| 296 | function renderLegend() { |
| 297 | const el = document.getElementById('mind-legend'); |
| 298 | if (!el) return; |
| 299 | const profs = ceo.getProfiles(); |
| 300 | // Botones (antes divs sin rol ni foco): con el teclado también se vuela a un perfil. |
| 301 | el.innerHTML = `<button type="button" class="ml-item" data-id="ceo"><span class="ml-sw" style="background:${CEO_COLOR}"></span>CEO</button>` + |
| 302 | profs.map(p => `<button type="button" class="ml-item" data-id="${escHtml(p.id)}"><span class="ml-sw" style="background:${escHtml(p.color)}"></span>${escHtml(p.name)}</button>`).join(''); |
| 303 | el.setAttribute('aria-label', t('mindProfiles')); |
| 304 | el.querySelectorAll('.ml-item').forEach(row => { |
| 305 | row.title = t('mindFlyTo', { name: row.textContent }); |
| 306 | row.onclick = () => { const pos = anchorMap.get(row.dataset.id); if (pos) focusOn(pos, 46); }; |
| 307 | }); |
| 308 | } |
| 309 | // vuelo suave de la cámara hacia un punto — así «clic en algo → la cámara se centra» |
| 310 | let flyTo = null; |
| 311 | function focusOn(pos, distance = 40) { |
| 312 | if (!S) return; |
| 313 | const dir = new THREE.Vector3().subVectors(S.camera.position, S.controls.target); |
| 314 | if (dir.lengthSq() < 0.001) dir.set(0, 0.3, 1); |
| 315 | dir.normalize().multiplyScalar(distance); |
| 316 | flyTo = { fromPos: S.camera.position.clone(), toPos: pos.clone().add(dir), fromTarget: S.controls.target.clone(), toTarget: pos.clone(), t0: elapsed, dur: 1.1 }; |
| 317 | } |
| 318 | const easeInOut = k => k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; |
| 319 | function rebuildWorld() { anchorMap = computeAnchors(); renderLegend(); } |
| 320 | |
| 321 | // ── panel ⚙: reprograma misión, carpeta-alma y PERFILES (editables) ────── |
| 322 | // «Pensar ahora» puede tardar minutos con un modelo de verdad: su estado vive |
| 323 | // fuera del panel, que se redibuja cada vez que se abre. |
| 324 | let pensando = false, estadoPensar = '', forjadaAhora = false; |
| 325 | function wireConfig(root) { |
| 326 | const btn = root.querySelector('#mind-config'); |
| 327 | const cfg = root.querySelector('#mind-cfg'); |
| 328 | const profRowHtml = p => { |
| 329 | const n = escHtml(p.name || t('mindNewProfile')); |
| 330 | return `<div class="cfg-prof" data-id="${escHtml(p.id || '')}"> |
| 331 | <input type="color" class="cp-color" value="${escHtml(p.color || '#7c5cff')}" aria-label="${escHtml(t('mindProfColor', { name: p.name || t('mindNewProfile') }))}"> |
| 332 | <input type="text" class="cp-name" value="${escHtml(p.name || '')}" placeholder="${escHtml(t('mindProfName'))}" aria-label="${escHtml(t('mindProfName'))}"> |
| 333 | <input type="text" class="cp-focus" value="${escHtml(p.focus || '')}" placeholder="${escHtml(t('mindProfFocus'))}" aria-label="${escHtml(t('mindProfFocusL', { name: n }))}"> |
| 334 | <button type="button" class="cp-del" title="${escHtml(t('mindProfDel'))}" aria-label="${escHtml(t('mindProfDel'))}">✕</button></div>`; |
| 335 | }; |
| 336 | const notifState = () => (!('Notification' in window)) ? { txt: t('mindNotifNo'), can: false } |
| 337 | : Notification.permission === 'granted' ? { txt: t('mindNotifOk'), can: false } |
| 338 | : Notification.permission === 'denied' ? { txt: t('mindNotifBlocked'), can: false } |
| 339 | : { txt: t('mindNotifAsk'), can: true }; |
| 340 | const draw = () => { |
| 341 | const profs = ceo.getProfiles(); |
| 342 | const ns = notifState(); |
| 343 | cfg.setAttribute('role', 'region'); |
| 344 | cfg.setAttribute('aria-label', t('mindCfgTitle')); |
| 345 | cfg.innerHTML = |
| 346 | '<div class="cfg-head">' + escHtml(t('mindCfgTitle')) + '<button id="cfg-x" type="button">✕</button></div>' + |
| 347 | '<div class="cfg-notif">' + escHtml(t('mindNotif')) + ' ' + escHtml(ns.txt) + (ns.can ? ' <button id="cfg-notif-ask" type="button" class="cfg-notif-btn">' + escHtml(t('mindNotifBtn')) + '</button>' : '') + '</div>' + |
| 348 | '<label for="cfg-mission">' + escHtml(t('mindMission')) + '</label>' + |
| 349 | '<textarea id="cfg-mission" rows="3">' + escHtml(ceo.getMission()) + '</textarea>' + |
| 350 | '<label for="cfg-dir" id="cfg-dir-label">' + escHtml(t('mindSoulDir')) + '</label>' + |
| 351 | '<input id="cfg-dir" value="' + escHtml(ceo.getSoulDir()) + '">' + |
| 352 | '<label>' + escHtml(t('mindProfilesL')) + '</label>' + |
| 353 | '<div id="cfg-profiles">' + profs.map(profRowHtml).join('') + '</div>' + |
| 354 | '<button id="cfg-add-prof" type="button" class="cfg-add">' + escHtml(t('mindAddProfile')) + '</button>' + |
| 355 | '<div class="cfg-actions"><button id="cfg-think-now" type="button" class="cfg-ghost">' + escHtml(t('mindThinkNow')) + '</button>' + |
| 356 | '<button id="cfg-save" type="button" class="cfg-save">' + escHtml(t('mindReprogram')) + '</button></div>' + |
| 357 | '<div id="cfg-status" class="cfg-status" role="status" aria-live="polite"></div>' + |
| 358 | '<div class="cfg-note">' + escHtml(t('mindCfgNote')) + '</div>'; |
| 359 | const x = cfg.querySelector('#cfg-x'); |
| 360 | x.setAttribute('aria-label', t('close')); |
| 361 | // El foco vuelve a ⚙ (antes se quedaba en <body>, dentro de la Mente modal). |
| 362 | x.onclick = () => { cfg.classList.remove('show'); root.querySelector('#mind-config')?.focus(); }; |
| 363 | // Dónde escribe de verdad (en Claw, la primera carpeta autorizada). |
| 364 | Promise.resolve().then(() => etiquetaAlma()).then(txt => { |
| 365 | const l = cfg.querySelector('#cfg-dir-label'); if (l && txt) l.textContent = txt; |
| 366 | }).catch(() => {}); |
| 367 | cfg.querySelector('#cfg-notif-ask')?.addEventListener('click', () => { Notification.requestPermission().then(draw); }); |
| 368 | cfg.querySelector('#cfg-add-prof').onclick = () => { |
| 369 | cfg.querySelector('#cfg-profiles').insertAdjacentHTML('beforeend', profRowHtml({ color: '#ff9f45', name: '', focus: '' })); |
| 370 | wireRows(); |
| 371 | cfg.querySelector('#cfg-profiles .cfg-prof:last-child .cp-name')?.focus(); |
| 372 | }; |
| 373 | const estado = cfg.querySelector('#cfg-status'); |
| 374 | estado.textContent = estadoPensar; |
| 375 | const think = cfg.querySelector('#cfg-think-now'); |
| 376 | think.disabled = pensando; |
| 377 | // «Pensar ahora» ya no cierra el panel a ciegas: dice si no puede (sin |
| 378 | // modelo, sin carpeta) y, si puede, que está pensando y cómo acaba. |
| 379 | think.onclick = async () => { |
| 380 | const motivo = await motivoNoPensar(); |
| 381 | const st = () => cfg.querySelector('#cfg-status'); |
| 382 | if (motivo) { estadoPensar = motivo; if (st()) st().textContent = motivo; return; } |
| 383 | pensando = true; think.disabled = true; forjadaAhora = false; ultimoAviso = ''; |
| 384 | estadoPensar = t('mindThinking'); |
| 385 | if (st()) st().textContent = estadoPensar; |
| 386 | let ok = false; |
| 387 | try { ok = await ceo.forceCycle(); } catch { ok = false; } |
| 388 | pensando = false; |
| 389 | estadoPensar = ok && forjadaAhora ? t('mindThoughtDone') : (ultimoAviso || t('mindCantThink')); |
| 390 | if (st()) st().textContent = estadoPensar; |
| 391 | const b = cfg.querySelector('#cfg-think-now'); if (b) b.disabled = false; |
| 392 | }; |
| 393 | cfg.querySelector('#cfg-save').onclick = () => { |
| 394 | // preserva el id original de cada perfil (si no, cada guardado los |
| 395 | // regeneraría desde el nombre y los ciclos en curso perderían el hilo) |
| 396 | const rows = [...cfg.querySelectorAll('.cfg-prof')].map(r => ({ |
| 397 | id: r.dataset.id || undefined, |
| 398 | color: r.querySelector('.cp-color').value, |
| 399 | name: r.querySelector('.cp-name').value.trim(), |
| 400 | focus: r.querySelector('.cp-focus').value.trim(), |
| 401 | })); |
| 402 | ceo.setMission(cfg.querySelector('#cfg-mission').value); |
| 403 | ceo.setSoulDir(cfg.querySelector('#cfg-dir').value); |
| 404 | ceo.setProfiles(rows); |
| 405 | // Reprogramar NO enciende el cerebro: antes reactivaba en silencio uno |
| 406 | // que habías pausado, y el botón seguía diciendo «reanudar». |
| 407 | pintarPlayStop(); |
| 408 | cfg.classList.remove('show'); |
| 409 | root.querySelector('#mind-config')?.focus(); |
| 410 | }; |
| 411 | wireRows(); |
| 412 | function wireRows() { cfg.querySelectorAll('.cp-del').forEach(b => { b.onclick = () => b.closest('.cfg-prof').remove(); }); } |
| 413 | }; |
| 414 | btn.setAttribute('aria-expanded', 'false'); |
| 415 | btn.setAttribute('aria-controls', 'mind-cfg'); |
| 416 | const abrir = () => { draw(); cfg.classList.add('show'); btn.setAttribute('aria-expanded', 'true'); cfg.querySelector('#cfg-mission')?.focus(); }; |
| 417 | const cerrar = () => { cfg.classList.remove('show'); btn.setAttribute('aria-expanded', 'false'); }; |
| 418 | btn.onclick = () => (cfg.classList.contains('show') ? cerrar() : abrir()); |
| 419 | new MutationObserver(() => btn.setAttribute('aria-expanded', cfg.classList.contains('show') ? 'true' : 'false')) |
| 420 | .observe(cfg, { attributes: true, attributeFilter: ['class'] }); |
| 421 | } |
| 422 | function wireHistory(root) { |
| 423 | const btn = root.querySelector('#mind-history'), panel = root.querySelector('#mind-log'); |
| 424 | btn.setAttribute('aria-controls', 'mind-log'); |
| 425 | const sync = () => btn.setAttribute('aria-expanded', panel.classList.contains('show') ? 'true' : 'false'); |
| 426 | btn.onclick = () => { panel.classList.toggle('show'); sync(); }; |
| 427 | const x = panel.querySelector('#ml-x'); |
| 428 | x.setAttribute('aria-label', t('close')); |
| 429 | x.onclick = () => { panel.classList.remove('show'); sync(); btn.focus(); }; |
| 430 | new MutationObserver(sync).observe(panel, { attributes: true, attributeFilter: ['class'] }); |
| 431 | sync(); |
| 432 | } |
| 433 | |
| 434 | // play/stop del cerebro, visible dentro de la Mente. La elección la persiste |
| 435 | // ceo.js (misma clave que usa el clic en la elfa) → sobrevive a recargar. |
| 436 | // |
| 437 | // Pausar a mitad de un ciclo no es instantáneo: el ciclo se aborta, pero tiene |
| 438 | // que soltar el modelo. Mientras tanto se dice «pausando…» y no «pausado» |
| 439 | // —decir lo segundo con el modelo aún ocupado era mentir— y se repinta solo |
| 440 | // hasta que el ciclo ha terminado de verdad (ceo.isRunning() en false). |
| 441 | // |
| 442 | // Es EL interruptor del cerebro autónomo: abrir la Mente ya no lo enciende (lo |
| 443 | // hacía la primera vez, para siempre, sin decirlo). Se repinta con cada cambio |
| 444 | // de estado que anuncie ceo.js (pushThought 'sys') y al volver a abrir la |
| 445 | // Mente: antes solo con su propio clic, y tras «Reprogramar» decía lo contrario |
| 446 | // de lo que pasaba. |
| 447 | function wirePlayStop(root) { |
| 448 | const btn = root.querySelector('#mind-playstop'); |
| 449 | let repinta = null; |
| 450 | const paint = () => { |
| 451 | const on = ceo.isEnabled(); |
| 452 | const pausando = !on && ceo.isRunning(); |
| 453 | btn.textContent = on ? t('mindPause') : pausando ? t('mindPausing') |
| 454 | : (ceo.hasDecided?.() ? t('mindResume') : t('mindStart')); |
| 455 | btn.title = t('mindBrainExplain'); |
| 456 | btn.classList.toggle('paused', !on); |
| 457 | btn.classList.toggle('pausing', pausando); |
| 458 | clearTimeout(repinta); |
| 459 | if (pausando) repinta = setTimeout(paint, 250); |
| 460 | }; |
| 461 | btn.onclick = () => { if (ceo.isEnabled()) ceo.disable(); else ceo.enable(); paint(); }; |
| 462 | pintarPlayStop = paint; |
| 463 | paint(); |
| 464 | } |
| 465 | |
| 466 | // ══ ciudad de fondo (motor de la app anfitriona, por debajo del mundo) ══════ |
| 467 | async function buildBackgroundCity(scene) { |
| 468 | if (!buildCityFn) return; |
| 469 | try { |
| 470 | const city = await buildCityFn(scene); |
| 471 | if (!city) return; |
| 472 | cityWrap = city.cityWrap; cityCity = city.cityCity; cityModel = city.cityModel; |
| 473 | } catch { /* sigue sin ciudad de fondo */ } |
| 474 | } |
| 475 | // haz de luz que baja hasta el fichero real en la ciudad + resalta su celda |
| 476 | function fileBeam(path, kind) { |
| 477 | if (!cityModel || !cityCity || !S) return; |
| 478 | const rel = String(path).replace(/^\.?\//, ''); |
| 479 | const f = cityModel.fileByRel.get(rel); |
| 480 | if (!f) return; |
| 481 | const local = new THREE.Vector3(f.box.cx, f.box.cy, f.box.cz); |
| 482 | const world = cityWrap.localToWorld(local.clone()); |
| 483 | const top = world.clone(); top.y += 50; |
| 484 | const geo = new THREE.BufferGeometry().setFromPoints([top, world]); |
| 485 | const mat = new THREE.LineBasicMaterial({ color: kind === 'write' ? 0xff4d8d : 0x49e8ff, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false }); |
| 486 | const line = new THREE.Line(geo, mat); |
| 487 | S.scene.add(line); |
| 488 | beams.push({ obj: line, born: elapsed, life: 1.4 }); |
| 489 | fileActivity.push({ id: f.id, born: elapsed, life: 2.2 }); |
| 490 | } |
| 491 | |
| 492 | // ── mundo psicodélico ─────────────────────────────────────────────────────── |
| 493 | function buildScene(canvas, W, H) { |
| 494 | const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true }); |
| 495 | renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); |
| 496 | renderer.setSize(W, H, false); |
| 497 | renderer.toneMapping = THREE.ACESFilmicToneMapping; |
| 498 | const scene = new THREE.Scene(); |
| 499 | const camera = new THREE.PerspectiveCamera(60, W / H, 0.1, 2000); |
| 500 | camera.position.set(0, 40, 150); |
| 501 | const controls = new OrbitControls(camera, canvas); |
| 502 | controls.enableDamping = true; controls.dampingFactor = 0.06; controls.autoRotate = false; |
| 503 | controls.enablePan = false; controls.minDistance = 60; controls.maxDistance = 420; |
| 504 | |
| 505 | const N = 14000; |
| 506 | const pos = new Float32Array(N * 3), rad = new Float32Array(N); |
| 507 | let s = 987654321; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647; |
| 508 | for (let i = 0; i < N; i++) { |
| 509 | const arm = Math.floor(rnd() * 4); |
| 510 | const r = Math.pow(rnd(), 0.6) * 120 + 6; |
| 511 | const a = arm * (Math.PI / 2) + r * 0.03 + (rnd() - 0.5) * 0.5; |
| 512 | const y = (rnd() - 0.5) * (14 - r * 0.06); |
| 513 | pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = y; pos[i * 3 + 2] = Math.sin(a) * r; rad[i] = r; |
| 514 | } |
| 515 | const geo = new THREE.BufferGeometry(); |
| 516 | geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); |
| 517 | geo.setAttribute('aRad', new THREE.BufferAttribute(rad, 1)); |
| 518 | const mat = new THREE.ShaderMaterial({ |
| 519 | uniforms: { uTime: { value: 0 }, uBass: { value: 0 }, uMid: { value: 0 } }, |
| 520 | transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, |
| 521 | vertexShader: `uniform float uTime, uBass, uMid; attribute float aRad; varying vec3 vC; |
| 522 | 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.);} |
| 523 | 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)); } |
| 524 | float vnoise(vec3 x){ vec3 i=floor(x),f=fract(x); f=f*f*(3.0-2.0*f); |
| 525 | 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), |
| 526 | 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); } |
| 527 | 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; } |
| 528 | void main(){ |
| 529 | vec3 pos=position; |
| 530 | float n=fbm(pos*0.03 + vec3(0.0,uTime*0.18,0.0)); |
| 531 | pos += normalize(pos+0.001) * (n-0.5) * (5.0 + uMid*4.0 + uBass*7.0); |
| 532 | float sw = uTime*0.14 + aRad*0.015 + uBass*0.18; |
| 533 | float cs=cos(sw), sn=sin(sw); |
| 534 | pos.xz = mat2(cs,-sn,sn,cs) * pos.xz; |
| 535 | pos *= (1.0 + uBass*0.05); |
| 536 | 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); |
| 537 | vec4 mv=modelViewMatrix*vec4(pos,1.0); gl_PointSize=(2.2+60.0/-mv.z)*(1.0+uBass*0.18); gl_Position=projectionMatrix*mv; }`, |
| 538 | 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); }`, |
| 539 | }); |
| 540 | const galaxy = new THREE.Points(geo, mat); scene.add(galaxy); |
| 541 | const core = new THREE.LineSegments(new THREE.WireframeGeometry(new THREE.IcosahedronGeometry(18, 1)), |
| 542 | new THREE.LineBasicMaterial({ color: 0xff4d8d, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false })); |
| 543 | scene.add(core); |
| 544 | const rings = []; |
| 545 | for (let i = 0; i < 24; i++) { |
| 546 | const ring = new THREE.Mesh(new THREE.TorusGeometry(22, 0.5, 8, 80), |
| 547 | new THREE.MeshBasicMaterial({ color: 0x7c5cff, transparent: true, opacity: 0.45, blending: THREE.AdditiveBlending, depthWrite: false })); |
| 548 | ring.rotation.x = Math.PI / 2; ring.position.y = -70 + i * 6; ring.userData.i = i; |
| 549 | scene.add(ring); rings.push(ring); |
| 550 | } |
| 551 | nodesGroup = new THREE.Group(); scene.add(nodesGroup); |
| 552 | starGroup = new THREE.Group(); scene.add(starGroup); |
| 553 | const composer = new EffectComposer(renderer); |
| 554 | composer.setSize(W, H); composer.addPass(new RenderPass(scene, camera)); |
| 555 | const bloom = new UnrealBloomPass(new THREE.Vector2(W, H), 1.1, 0.5, 0.2); |
| 556 | composer.addPass(bloom); composer.addPass(new OutputPass()); |
| 557 | return { renderer, scene, camera, controls, composer, bloom, mat, galaxy, core, rings }; |
| 558 | } |
| 559 | |
| 560 | // La Mente es una capa MODAL: lo de detrás queda inerte mientras está abierta |
| 561 | // (modal.js), el foco entra en ella y al salir vuelve a donde estaba (el botón |
| 562 | // 🧠). Antes Tab recorría la página tapada y el foco se quedaba detrás. |
| 563 | export async function openMind() { |
| 564 | if (open) return; |
| 565 | open = true; |
| 566 | if (built) { |
| 567 | overlay.style.display = ''; |
| 568 | if (musicaPuesta) { try { widget?.play(); } catch { /* — */ } } |
| 569 | cerrarModal = abrirModal(overlay, { foco: '#mind-close', dejar: ['toasts'] }); |
| 570 | pintarPlayStop(); |
| 571 | startLoop(); |
| 572 | return; |
| 573 | } |
| 574 | |
| 575 | overlay = document.createElement('div'); |
| 576 | overlay.id = 'mind-overlay'; |
| 577 | overlay.setAttribute('role', 'dialog'); |
| 578 | overlay.setAttribute('aria-modal', 'true'); |
| 579 | overlay.setAttribute('aria-label', t('mindAria')); |
| 580 | overlay.setAttribute('aria-describedby', 'mind-explica'); |
| 581 | overlay.innerHTML = |
| 582 | '<canvas id="mind-canvas" aria-hidden="true"></canvas>' + |
| 583 | `<div id="mind-title">${escHtml(t('mindTitle'))}<span id="mind-explica">${escHtml(t('mindExplain'))}</span></div>` + |
| 584 | '<div id="mind-legend" role="group"></div>' + |
| 585 | '<button id="mind-playstop" type="button"></button>' + |
| 586 | `<button id="mind-config" type="button" title="${escHtml(t('mindCfgTitle'))}">${escHtml(t('mindCfgBtn'))}</button>` + |
| 587 | `<button id="mind-history" type="button" title="${escHtml(t('mindHistoryT'))}">${escHtml(t('mindHistoryBtn'))}</button>` + |
| 588 | `<button id="mind-close" type="button" title="${escHtml(t('mindCloseT'))}">${escHtml(t('mindCloseBtn'))}</button>` + |
| 589 | '<button id="mind-music-btn" type="button" class="mind-music-btn"></button>' + |
| 590 | '<div id="mind-anchors"></div><div id="mind-panel"></div><div id="mind-cfg"></div>' + |
| 591 | `<div id="mind-log" role="region" aria-label="${escHtml(t('mindHistoryTitle'))}"><div class="ml-head">${escHtml(t('mindHistoryTitle'))}<button id="ml-x" type="button">✕</button></div><div id="mind-log-body" role="log"></div></div>`; |
| 592 | document.body.appendChild(overlay); |
| 593 | cerrarModal = abrirModal(overlay, { foco: '#mind-close', dejar: ['toasts'] }); |
| 594 | wireConfig(overlay); wireHistory(overlay); wirePlayStop(overlay); wireMusic(overlay); |
| 595 | anchors.length = 0; thoughtNodes = []; stars = []; |
| 596 | rebuildWorld(); |
| 597 | |
| 598 | const canvas = overlay.querySelector('#mind-canvas'); |
| 599 | S = buildScene(canvas, window.innerWidth, window.innerHeight); |
| 600 | buildBackgroundCity(S.scene); |
| 601 | await loadExistingThoughts(); |
| 602 | // El historial: lo guardado más lo que llegó con la Mente cerrada (mind-log.js). |
| 603 | await mindLog.cargar(); |
| 604 | for (const l of mindLog.todas()) renderLogRow(l); |
| 605 | logMontado = true; |
| 606 | |
| 607 | const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(); |
| 608 | let downXY = null; |
| 609 | canvas.addEventListener('pointerdown', e => { downXY = [e.clientX, e.clientY]; }); |
| 610 | canvas.addEventListener('pointerup', e => { |
| 611 | if (!downXY) return; const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]); downXY = null; |
| 612 | if (moved > 5 || !thoughtNodes.length) return; |
| 613 | ptr.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1); |
| 614 | ray.setFromCamera(ptr, S.camera); |
| 615 | const hit = ray.intersectObjects(thoughtNodes)[0]; |
| 616 | if (hit) selectThoughtNode(hit.object); |
| 617 | }); |
| 618 | |
| 619 | const onResize = () => { |
| 620 | const w = window.innerWidth, h = window.innerHeight; |
| 621 | S.renderer.setSize(w, h, false); S.composer.setSize(w, h); S.bloom.resolution.set(w, h); |
| 622 | S.camera.aspect = w / h; S.camera.updateProjectionMatrix(); |
| 623 | }; |
| 624 | window.addEventListener('resize', onResize); S.onResize = onResize; |
| 625 | overlay.querySelector('#mind-close').addEventListener('click', closeMind); |
| 626 | // Escape cierra lo de más arriba: un panel abierto antes que la Mente entera. |
| 627 | // Con un permiso pendiente (un <dialog>), Escape es suyo. |
| 628 | S.onKey = e => { |
| 629 | if (e.key !== 'Escape' || !open) return; |
| 630 | if (document.querySelector('dialog[open]')) return; |
| 631 | const capa = ['#mind-cfg', '#mind-panel', '#mind-log'].map(s => overlay.querySelector(s)).find(el => el?.classList.contains('show')); |
| 632 | if (capa) { capa.classList.remove('show'); overlay.querySelector('#mind-close')?.focus(); return; } |
| 633 | closeMind(); |
| 634 | }; |
| 635 | document.addEventListener('keydown', S.onKey); |
| 636 | built = true; |
| 637 | startLoop(); |
| 638 | } |
| 639 | |
| 640 | // Etiquetas de propuestas: se proyectan del mundo 3D a la pantalla, así que |
| 641 | // con muchas acumuladas acaban solapándose ilegibles según el ángulo de |
| 642 | // cámara. Aquí: cap a las más cercanas y reparto anti-solape (empuja hacia |
| 643 | // abajo la que choca con otra ya colocada), para que se apilen separadas. |
| 644 | const MAX_LABELS = 14, LABEL_W = 90, LABEL_H = 20; |
| 645 | function projectAnchors() { |
| 646 | const w = window.innerWidth, h = window.innerHeight, v = new THREE.Vector3(); |
| 647 | const projected = []; |
| 648 | for (const a of anchors) { |
| 649 | v.copy(a.pos).project(S.camera); |
| 650 | if (v.z > 1) { a.el.style.display = 'none'; continue; } // detrás de la cámara |
| 651 | projected.push({ a, x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, depth: v.z }); |
| 652 | } |
| 653 | projected.sort((p1, p2) => p1.depth - p2.depth); // las más cercanas a la cámara, prioridad |
| 654 | projected.forEach((p, i) => { p.a.el.style.display = i < MAX_LABELS ? '' : 'none'; }); |
| 655 | const visible = projected.slice(0, MAX_LABELS).sort((p1, p2) => p1.x - p2.x || p1.y - p2.y); |
| 656 | const placed = []; |
| 657 | for (const p of visible) { |
| 658 | let y = p.y; |
| 659 | 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; |
| 660 | placed.push({ x: p.x, y }); |
| 661 | p.a.el.style.left = p.x + 'px'; p.a.el.style.top = y + 'px'; |
| 662 | p.a.el.style.transform = 'translate(-50%,-50%)'; |
| 663 | } |
| 664 | } |
| 665 | 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; |
| 666 | |
| 667 | let elapsed = 0, lastMs = 0, smBass = 0, smMid = 0; |
| 668 | function startLoop() { |
| 669 | if (raf) return; |
| 670 | const loop = (ms) => { |
| 671 | raf = requestAnimationFrame(loop); |
| 672 | const dt = lastMs ? (ms - lastMs) / 1000 : 0; |
| 673 | elapsed += dt; lastMs = ms; |
| 674 | const t = elapsed; |
| 675 | const beat = 60 / 138; |
| 676 | const bp = (t % beat) / beat; |
| 677 | const bassRaw = Math.pow(1 - bp, 3); |
| 678 | const midRaw = 0.5 + 0.5 * Math.sin(t * 6.0); |
| 679 | smBass += (bassRaw - smBass) * 0.05; |
| 680 | smMid += (midRaw - smMid) * 0.06; |
| 681 | S.mat.uniforms.uTime.value = t; |
| 682 | S.mat.uniforms.uBass.value = smBass; |
| 683 | S.mat.uniforms.uMid.value = smMid; |
| 684 | S.galaxy.rotation.y = t * 0.05; |
| 685 | S.galaxy.rotation.x = wob(t, 1.7, 0.05) * 0.15; |
| 686 | S.galaxy.rotation.z = wob(t, 5.2, 0.04) * 0.1; |
| 687 | S.galaxy.scale.setScalar(1 + smBass * 0.02); |
| 688 | const pulse = 1 + smBass * 0.05 + Math.sin(t * 0.9) * 0.03; |
| 689 | S.core.scale.setScalar(pulse); S.core.rotation.y = t * 0.16; S.core.rotation.x = t * 0.09; |
| 690 | S.core.position.x = wob(t, 3.1, 0.11) * 6; S.core.position.z = wob(t, 9.4, 0.09) * 6; |
| 691 | S.core.material.color.setHSL((t * 0.04) % 1, 0.9, 0.6); |
| 692 | for (const r of S.rings) { |
| 693 | r.position.y += 0.14 + smBass * 0.12; |
| 694 | if (r.position.y > 74) r.position.y -= 144; |
| 695 | r.position.x = wob(t, r.userData.i * 1.3 + 1, 0.08) * 3; |
| 696 | r.scale.setScalar(1 + smBass * 0.12 + Math.sin(t * 0.8 + r.userData.i) * 0.04); |
| 697 | r.material.opacity = 0.2 + smBass * 0.16; |
| 698 | r.material.color.setHSL((t * 0.05 + r.userData.i * 0.03) % 1, 0.85, 0.6); |
| 699 | } |
| 700 | 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); } |
| 701 | // estrellas: nacen (fade-in), viven, se apagan solas y se reciclan |
| 702 | for (let i = stars.length - 1; i >= 0; i--) { |
| 703 | const st = stars[i], age = t - st.born; |
| 704 | if (age > st.life) { starGroup.remove(st.obj); st.obj.material.map.dispose(); st.obj.material.dispose(); stars.splice(i, 1); continue; } |
| 705 | const fadeIn = Math.min(1, age / 0.5), fadeOut = Math.min(1, (st.life - age) / (st.life * 0.35)); |
| 706 | st.obj.material.opacity = Math.min(fadeIn, fadeOut); |
| 707 | st.obj.position.y += st.up * dt; |
| 708 | st.obj.position.x += Math.sin(t * 0.6 + st.seed) * 0.3 * dt; |
| 709 | } |
| 710 | // haces sobre la ciudad + celdas de fichero resaltadas por actividad |
| 711 | for (let i = beams.length - 1; i >= 0; i--) { |
| 712 | const b = beams[i], age = t - b.born; |
| 713 | if (age > b.life) { S.scene.remove(b.obj); b.obj.geometry.dispose(); b.obj.material.dispose(); beams.splice(i, 1); continue; } |
| 714 | b.obj.material.opacity = 0.9 * Math.max(0, 1 - age / b.life); |
| 715 | } |
| 716 | if (cityCity) for (let i = fileActivity.length - 1; i >= 0; i--) { |
| 717 | const a = fileActivity[i], age = t - a.born; |
| 718 | if (age > a.life) { cityCity.paintFile(a.id, 0); fileActivity.splice(i, 1); continue; } |
| 719 | cityCity.paintFile(a.id, Math.max(0, 1 - age / a.life)); |
| 720 | } |
| 721 | if (flyTo) { |
| 722 | const k = Math.min(1, (t - flyTo.t0) / flyTo.dur), e = easeInOut(k); |
| 723 | S.camera.position.lerpVectors(flyTo.fromPos, flyTo.toPos, e); |
| 724 | S.controls.target.lerpVectors(flyTo.fromTarget, flyTo.toTarget, e); |
| 725 | if (k >= 1) flyTo = null; |
| 726 | } |
| 727 | S.controls.update(); |
| 728 | projectAnchors(); |
| 729 | S.composer.render(); |
| 730 | }; |
| 731 | loop(performance.now()); |
| 732 | } |
| 733 | |
| 734 | export function closeMind() { |
| 735 | open = false; |
| 736 | if (raf) { cancelAnimationFrame(raf); raf = null; } |
| 737 | lastMs = 0; |
| 738 | try { widget?.pause(); } catch {} |
| 739 | if (overlay) overlay.style.display = 'none'; |
| 740 | cerrarModal?.(); |
| 741 | cerrarModal = null; |
| 742 | try { onCerrar(); } catch { /* lo de la app anfitriona no impide cerrar */ } |
| 743 | } |
| 744 | |
| 745 | // para tests/depuración |
| 746 | export function _debug() { |
| 747 | return { |
| 748 | starCount: stars.length, hasCity: !!cityCity, profileCount: ceo.getProfiles().length, |
| 749 | beamCount: beams.length, fileActivityCount: fileActivity.length, |
| 750 | cameraPos: S ? [S.camera.position.x, S.camera.position.y, S.camera.position.z] : null, |
| 751 | flying: !!flyTo, |
| 752 | }; |
| 753 | } |
| 754 | export function _debugFocusOn(id) { const p = anchorMap.get(id); if (p) focusOn(p, 46); } |