import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { Particles } from './particles.js';
import { BlocksView, BLOCK_COLORS } from './blocks3d.js';
import { SentinelsView, ROLE_COLORS } from './sentinels3d.js';
import qrcode from './vendor/qrcode.mjs';
// Telefono o tablet: 3D alleggerito (un neurone ogni LITE_STRIDE) per restare fluido.
const LITE = matchMedia('(max-width: 900px)').matches || /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent);
const LITE_STRIDE = 8;
const $ = (id) => document.getElementById(id);
const fmt = (n) => n.toLocaleString('it-IT');
const REGION_COLORS = ['#5ce1e6', '#7b8cff', '#c77dff', '#ff6fb5', '#ffb347', '#9be15d',
'#4dabf7', '#ff8c69', '#63e6be', '#e599f7', '#ffd43b', '#b2f2bb'];
const GLOW_CAP = 40000; // neuroni accesi contemporaneamente al massimo
const MARK_CAP = 20000; // neuroni modificati evidenziati
const S = {
nLayer: 0, nFF: 0,
atlas: null,
regionOfLayer: [],
basePos: null,
ws: null,
generating: false,
aiMsg: null,
factors: new Map(), // chiave L*nFF+idx -> fattore
eeg: new Float32Array(0),
eegMax: new Float32Array(0),
selected: null, // {L, idx}
focusRegion: -1,
tokCount: 0, tokStart: 0,
blocks: [], // blocchi dal motore
blockProgress: new Map(), // id -> messaggio di elaborazione in corso
editing: new Set(), // blocchi di cui si sta cambiando la funzione
focusBlock: -1,
regions: [], // macroaree con le modifiche dell'utente
regionBusy: new Map(), // id area -> id blocco in elaborazione (0 = in coda)
ui: null,
doctor: null, // stato dell'autodiagnosi e diario
memory: null, // memoria a gruppi di neuroni
memFocus: -1, // ricordo evidenziato nel 3D // modifica aperta: {kind: 'region'|'block', id, mode: 'rename'|'use'|'delete'|'function'}
synapses: null, // ultime sinapsi calcolate per il neurone selezionato
msgCount: 0,
};
// ---------------------------------------------------------------- scena
const canvas = $('scene');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(LITE ? 1 : Math.min(devicePixelRatio, 2));
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);
camera.position.set(0, 5, 16);
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
controls.autoRotate = true;
controls.autoRotateSpeed = 0.35;
let idleTimer;
controls.addEventListener('start', () => { controls.autoRotate = false; clearTimeout(idleTimer); });
controls.addEventListener('end', () => { idleTimer = setTimeout(() => (controls.autoRotate = true), 20000); });
function glowSprite() {
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d');
const grad = g.createRadialGradient(32, 32, 0, 32, 32, 32);
grad.addColorStop(0, 'rgba(255,255,255,1)');
grad.addColorStop(0.25, 'rgba(255,255,255,0.55)');
grad.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = grad;
g.fillRect(0, 0, 64, 64);
return new THREE.CanvasTexture(c);
}
const sprite = glowSprite();
function pointsLayer(cap, material) {
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage));
geo.setAttribute('color', new THREE.BufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage));
geo.setDrawRange(0, 0);
const pts = new THREE.Points(geo, material);
pts.frustumCulled = false;
scene.add(pts);
return pts;
}
let base = null; // tutti i neuroni
const glow = pointsLayer(GLOW_CAP, new THREE.PointsMaterial({
size: 0.11, map: sprite, vertexColors: true, transparent: true,
blending: THREE.AdditiveBlending, depthWrite: false }));
const marks = pointsLayer(MARK_CAP, new THREE.PointsMaterial({
size: 0.14, map: sprite, vertexColors: true, transparent: true, depthWrite: false, depthTest: false }));
marks.renderOrder = 2; // sempre visibili, sopra l'attività
const pick = pointsLayer(1, new THREE.PointsMaterial({
size: 0.45, map: sprite, color: 0xffffff, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }));
const posOf = (l, j) => {
const k = (l * S.nFF + j) * 3;
return [S.basePos[k], S.basePos[k + 1], S.basePos[k + 2]];
};
const particles = new Particles(scene, sprite);
const blocksView = new BlocksView(scene, sprite, posOf);
const sentinelsView = new SentinelsView(scene, sprite, posOf);
let sentinelsKey = '';
function syncSentinels(force) {
const d = S.doctor;
const key = d ? JSON.stringify([d.network_on, d.groups.map((g) => [g.index, g.region, g.first, g.last, g.enabled])]) : '';
if (!force && key === sentinelsKey) return;
sentinelsKey = key;
sentinelsView.sync(d?.groups, S.nLayer, S.nFF, !!(d && d.network_on && S.basePos));
}
const EXCITE = new THREE.Color('#bff6ff'), INHIBIT = new THREE.Color('#ff5c7a');
let synLines = null; // fili delle sinapsi del neurone selezionato
// Esercitazione di infezione: neuroni infetti in verde tossico.
const INFECT_GREEN = new THREE.Color('#7cff4f'), CURED_WHITE = new THREE.Color('#e8fbff');
const infGlow = pointsLayer(4000, new THREE.PointsMaterial({
size: 0.12, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false }));
infGlow.renderOrder = 3;
const BKEY = 16777216; // chiavi dei neuroni dei blocchi: BKEY + id * 1024 + indice
function onInfection(ev) {
if (!S.basePos) return;
const nff = ev.neurons_per_layer;
const at = (key) => {
if (key < BKEY) return posOf(Math.floor(key / nff), key % nff);
const v = blocksView.views.get(Math.floor((key - BKEY) / 1024)), k = (key - BKEY) % 1024;
return v && k < v.block.neurons ? [v.pos[k * 3], v.pos[k * 3 + 1], v.pos[k * 3 + 2]] : null;
};
const p = infGlow.geometry.attributes.position.array, c = infGlow.geometry.attributes.color.array;
let n = 0;
for (const key of ev.list) {
const a = at(key);
if (!a || n >= 4000) continue;
p[n * 3] = a[0]; p[n * 3 + 1] = a[1]; p[n * 3 + 2] = a[2];
c[n * 3] = INFECT_GREEN.r; c[n * 3 + 1] = INFECT_GREEN.g; c[n * 3 + 2] = INFECT_GREEN.b;
n++;
}
infGlow.geometry.attributes.position.needsUpdate = true;
infGlow.geometry.attributes.color.needsUpdate = true;
infGlow.geometry.setDrawRange(0, n);
for (const [from, to] of ev.new) { const a = at(from), b = at(to); if (a && b) particles.spawn(a, b, INFECT_GREEN, 1, 0.7); } // contagio lungo la sinapsi
for (const key of ev.cured) { const a = at(key); if (a) particles.spawn(a, [a[0], a[1] + 0.5, a[2]], CURED_WHITE, 1, 0.9); } // guarito
const bar = $('infection-bar');
bar.hidden = !ev.on && !ev.healed;
bar.classList.toggle('cured', !ev.on);
$('inf-cure').hidden = !ev.on;
$('inf-text').textContent = ev.on
? `Infezione: ${fmt(ev.infected)} neuroni infetti · ${fmt(ev.healed)} guariti · ${Math.round(ev.seconds)} s${ev.detected ? '' : ' · incubazione, i presidi non se ne sono ancora accorti'}`
: `Infezione debellata: ${fmt(ev.healed)} neuroni guariti (massimo ${fmt(ev.peak)} infetti insieme)`;
if (!ev.on) setTimeout(() => { if (!S.infOn) bar.hidden = true; }, 15000);
S.infOn = ev.on;
}
$('inf-cure').onclick = () => send({ cmd: 'infect_cure' });
$('btn-infect').onclick = () => { if (S.selected) send({ cmd: 'infect', layer: S.selected.L, idx: S.selected.idx }); };
const MEM_GOLD = new THREE.Color('#ffd166');
const memGlow = pointsLayer(128 * 64, new THREE.PointsMaterial({
size: 0.07, map: sprite, vertexColors: true, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false }));
memGlow.renderOrder = 3;
let memGlowUntil = 0, memGlowPersist = false;
// Accende tutti i neuroni dei gruppi indicati (128 per gruppo).
function showMemoryGroups(groups, persist) {
if (!S.basePos || !S.memory) return;
const per = S.memory.per_layer, gs = S.memory.group_neurons;
const p = memGlow.geometry.attributes.position.array, c = memGlow.geometry.attributes.color.array;
let n = 0;
for (const g of groups.slice(0, 64)) {
const l = Math.floor(g / per), q = g % per;
for (let j = q * gs; j < (q + 1) * gs && j < S.nFF; j++) {
const k = (l * S.nFF + j) * 3;
p[n * 3] = S.basePos[k]; p[n * 3 + 1] = S.basePos[k + 1]; p[n * 3 + 2] = S.basePos[k + 2];
c[n * 3] = MEM_GOLD.r; c[n * 3 + 1] = MEM_GOLD.g; c[n * 3 + 2] = MEM_GOLD.b;
n++;
}
}
memGlow.geometry.attributes.position.needsUpdate = true;
memGlow.geometry.attributes.color.needsUpdate = true;
memGlow.geometry.setDrawRange(0, n);
memGlow.material.opacity = 1;
memGlowPersist = persist;
memGlowUntil = performance.now() + 4000;
}
const regionColor = (r) => new THREE.Color(REGION_COLORS[((r % REGION_COLORS.length) + REGION_COLORS.length) % REGION_COLORS.length]);
// Disposizione: gli strati scorrono lungo x (dall'ingresso all'uscita), ogni strato è una sezione
// ellittica del "cervello"; le macroaree sono separate da un piccolo solco, gli emisferi da una fessura.
function buildBrain() {
const { nLayer: L, nFF: F } = S;
const total = L * F;
const pos = new Float32Array(total * 3);
const col = new Float32Array(total * 3);
const span = 12, gap = 0.32;
const nReg = S.atlas ? S.atlas.regions.length : 1;
const golden = Math.PI * (3 - Math.sqrt(5));
const gray = new THREE.Color(0.24, 0.26, 0.29);
const tmp = new THREE.Color();
let seed = 12345;
const rand = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
for (let l = 0; l < L; l++) {
const r = S.regionOfLayer[l] ?? 0;
const x = -span / 2 + (l / (L - 1)) * span + (r - (nReg - 1) / 2) * gap;
const t = (l + 0.5) / L;
const radius = 0.55 + 2.4 * Math.pow(Math.sin(Math.PI * (0.06 + 0.88 * t)), 0.55);
const state = S.regions[r]?.state;
tmp.copy(gray).lerp(regionColor(r), r === S.focusRegion ? 0.55 : state === 'modificata' ? 0.45 : 0.2);
if (S.focusRegion >= 0 && r !== S.focusRegion) tmp.multiplyScalar(0.45);
if (state === 'eliminata') tmp.multiplyScalar(0.35); // specializzazione spenta
if (state === 'eliminata_tutta') tmp.setRGB(0.07, 0.07, 0.08); // area spenta del tutto
for (let j = 0; j < F; j++) {
const i = l * F + j;
const rr = radius * Math.sqrt((j + 0.5) / F);
const th = j * golden;
let z = rr * Math.cos(th);
z += Math.sign(z) * 0.18; // fessura tra gli emisferi
pos[i * 3] = x + (rand() - 0.5) * (span / (L - 1));
pos[i * 3 + 1] = rr * Math.sin(th) * 0.8;
pos[i * 3 + 2] = z;
const shade = 0.75 + rand() * 0.5;
col[i * 3] = tmp.r * shade; col[i * 3 + 1] = tmp.g * shade; col[i * 3 + 2] = tmp.b * shade;
}
}
S.basePos = pos;
if (base) { scene.remove(base); base.geometry.dispose(); }
// sul telefono si disegna un neurone ogni LITE_STRIDE; le posizioni di tutti restano per attività e selezione
let dpos = pos, dcol = col;
S.displayKey = null;
if (LITE) {
const n = Math.ceil(total / LITE_STRIDE);
dpos = new Float32Array(n * 3); dcol = new Float32Array(n * 3);
S.displayKey = new Int32Array(n);
for (let k = 0, i = 0; i < total; i += LITE_STRIDE, k++) {
S.displayKey[k] = i;
dpos.set(pos.subarray(i * 3, i * 3 + 3), k * 3);
dcol.set(col.subarray(i * 3, i * 3 + 3), k * 3);
}
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(dpos, 3));
geo.setAttribute('color', new THREE.BufferAttribute(dcol, 3));
geo.computeBoundingSphere();
base = new THREE.Points(geo, new THREE.PointsMaterial({
size: LITE ? 0.022 : 0.011, vertexColors: true, transparent: true, opacity: 0.6, depthWrite: false }));
scene.add(base);
glowReset();
renderMarks();
renderPick();
particles.clear();
blocksView.sync(S.blocks, true);
syncSentinels(true);
drawSynapses();
$('st-neurons').textContent = fmt(total);
}
// ---------------------------------------------------------------- neuroni accesi
const glowSlot = new Map(); // chiave -> slot
const glowKey = new Int32Array(GLOW_CAP);
const glowInt = new Float32Array(GLOW_CAP);
let glowN = 0;
function glowReset() { glowSlot.clear(); glowN = 0; glow.geometry.setDrawRange(0, 0); }
function light(l, j, v) {
const key = l * S.nFF + j;
let s = glowSlot.get(key);
if (s === undefined) {
if (glowN >= GLOW_CAP) return;
s = glowN++;
glowSlot.set(key, s);
glowKey[s] = key;
glowInt[s] = 0;
const p = glow.geometry.attributes.position.array;
p[s * 3] = S.basePos[key * 3]; p[s * 3 + 1] = S.basePos[key * 3 + 1]; p[s * 3 + 2] = S.basePos[key * 3 + 2];
glow.geometry.attributes.position.needsUpdate = true;
}
glowInt[s] = Math.max(glowInt[s], v);
}
function glowUpdate(dt) {
const decay = Math.pow(0.015, dt); // ~0.25 s di persistenza: si vede il flusso, non una nebbia
const p = glow.geometry.attributes.position.array;
const c = glow.geometry.attributes.color.array;
let moved = false;
for (let s = 0; s < glowN; s++) {
glowInt[s] *= decay;
if (glowInt[s] < 0.04) { // spento: sposta l'ultimo al suo posto
glowSlot.delete(glowKey[s]);
const last = --glowN;
if (s !== last) {
glowKey[s] = glowKey[last]; glowInt[s] = glowInt[last];
glowSlot.set(glowKey[s], s);
p[s * 3] = p[last * 3]; p[s * 3 + 1] = p[last * 3 + 1]; p[s * 3 + 2] = p[last * 3 + 2];
moved = true;
}
s--;
continue;
}
const v = glowInt[s];
const rc = regionColor(S.regionOfLayer[Math.floor(glowKey[s] / S.nFF)] ?? 0);
const w = v * v * v * 0.7; // i più intensi virano al bianco
c[s * 3] = rc.r * v + w; c[s * 3 + 1] = rc.g * v + w; c[s * 3 + 2] = rc.b * v + w;
}
if (moved) glow.geometry.attributes.position.needsUpdate = true;
glow.geometry.attributes.color.needsUpdate = true;
glow.geometry.setDrawRange(0, glowN);
$('st-active').textContent = fmt(glowN);
}
// ---------------------------------------------------------------- neuroni modificati e selezione
const markColor = (f) => (f === 0 ? new THREE.Color('#ff5c7a') : f > 1 ? new THREE.Color('#5ce1e6') : new THREE.Color('#ffb347'));
function renderMarks() {
if (!S.basePos) return;
const p = marks.geometry.attributes.position.array;
const c = marks.geometry.attributes.color.array;
let n = 0;
for (const [key, f] of S.factors) {
if (n >= MARK_CAP) break;
const col = markColor(f);
p[n * 3] = S.basePos[key * 3]; p[n * 3 + 1] = S.basePos[key * 3 + 1]; p[n * 3 + 2] = S.basePos[key * 3 + 2];
c[n * 3] = col.r; c[n * 3 + 1] = col.g; c[n * 3 + 2] = col.b;
n++;
}
marks.geometry.attributes.position.needsUpdate = true;
marks.geometry.attributes.color.needsUpdate = true;
marks.geometry.setDrawRange(0, n);
}
function renderPick() {
const sel = S.selected;
if (!sel || !S.basePos) { pick.geometry.setDrawRange(0, 0); return; }
const key = sel.L * S.nFF + sel.idx;
const p = pick.geometry.attributes.position.array;
p[0] = S.basePos[key * 3]; p[1] = S.basePos[key * 3 + 1]; p[2] = S.basePos[key * 3 + 2];
pick.geometry.attributes.position.needsUpdate = true;
pick.geometry.setDrawRange(0, 1);
}
const raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 0.05;
let downAt = null;
canvas.addEventListener('pointerdown', (e) => (downAt = [e.clientX, e.clientY]));
canvas.addEventListener('pointerup', (e) => {
if (!downAt || !base || Math.hypot(e.clientX - downAt[0], e.clientY - downAt[1]) > 4) return;
const r = canvas.getBoundingClientRect();
raycaster.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera);
const shit = raycaster.intersectObjects(sentinelsView.pickables)[0];
if (shit) { showTab('blocks'); document.getElementById('diagnosis')?.scrollIntoView({ behavior: 'smooth' }); return; }
const bhit = raycaster.intersectObjects(blocksView.pickables)[0];
const hit = raycaster.intersectObject(base)[0];
if (bhit && (!hit || bhit.distance <= hit.distance)) {
S.blockNeuron = { id: bhit.object.userData.blockId, k: bhit.index };
openBlock(bhit.object.userData.blockId);
return;
}
if (!hit) return;
const key = S.displayKey ? S.displayKey[hit.index] : hit.index;
select(Math.floor(key / S.nFF), key % S.nFF);
});
function regionName(l) {
const r = S.regionOfLayer[l];
return S.atlas && r !== undefined ? S.atlas.regions[r].name : '—';
}
function describeFactor(f) {
if (f === undefined || f === 1) return 'normale';
if (f === 0) return 'spento';
if (f < 0) return `invertito (×${f})`;
return f > 1 ? `amplificato ×${f}` : `ridotto ×${f}`;
}
function select(l, j) {
S.selected = { L: l, idx: j };
S.synapses = null;
$('syn-list').replaceChildren();
$('btn-syn').textContent = 'Mostra le sinapsi';
drawSynapses();
$('inspector').hidden = false;
$('insp-title').textContent = `Neurone ${fmt(j)}`;
$('insp-sub').textContent = `strato ${l} · ${regionName(l)}`;
refreshInspector();
renderPick();
}
function refreshInspector() {
const sel = S.selected;
if (!sel) return;
const key = sel.L * S.nFF + sel.idx;
$('insp-state').textContent = describeFactor(S.factors.get(key));
const s = glowSlot.get(key);
$('insp-act').textContent = s === undefined ? 'a riposo' : `${Math.round(glowInt[s] * 100)}% del massimo dello strato`;
// ogni neurone ha un indirizzo e sa dove si trova il suo pezzo di memoria sul disco
$('insp-addr').textContent = `n. ${fmt(key)}`;
if (S.memory) {
const per = S.memory.per_layer, gs = S.memory.group_neurons, q = Math.floor(sel.idx / gs), g = sel.L * per + q;
const owner = S.memory.memories.find((m) => m.groups.includes(g));
$('insp-group').textContent = `n. ${fmt(g)} (${gs} neuroni, ${S.memory.slot_bits} bit)${owner ? ` · custodisce «${owner.title}»` : ' · libero'}`;
$('insp-disk').textContent = `memoria/strato_${String(sel.L).padStart(2, '0')}.bin, byte ${q * (S.memory.slot_bits / 8)}–${(q + 1) * (S.memory.slot_bits / 8) - 1}`;
}
}
$('insp-close').onclick = () => { S.selected = null; S.synapses = null; $('inspector').hidden = true; renderPick(); drawSynapses(); };
// ---------------------------------------------------------------- sinapsi del neurone selezionato
$('btn-syn').onclick = () => {
if (!S.selected) return;
$('btn-syn').textContent = 'Calcolo dai pesi del modello…';
send({ cmd: 'synapses', layer: S.selected.L, idx: S.selected.idx });
};
function onSynapses(ev) {
if (!S.selected || ev.layer !== S.selected.L || ev.idx !== S.selected.idx) return;
S.synapses = ev;
$('btn-syn').textContent = `Ricalcola (${ev.seconds.toFixed(2)} s)`;
const list = $('syn-list');
list.replaceChildren();
const section = (title, items, dirIn) => {
const box = document.createElement('div');
box.innerHTML = `
${title}
`;
for (const [l, j, w] of items.slice(0, 6)) {
const b = document.createElement('button');
b.innerHTML = `strato ${l} · neurone ${fmt(j)}${w >= 0 ? '+' : ''}${w.toFixed(3)}`;
b.title = (w >= 0 ? 'eccitatoria' : 'inibitoria') + ' — clicca per andare a quel neurone';
b.onclick = () => select(l, j);
box.append(b);
}
list.append(box);
};
section('Riceve da (strato precedente)', ev.in, true);
section('Invia a (strato successivo)', ev.out, false);
drawSynapses();
// un'ondata di messaggi lungo le sinapsi appena scoperte
const me = posOf(ev.layer, ev.idx);
const maxw = Math.max(1e-9, ...ev.in.map((x) => Math.abs(x[2])), ...ev.out.map((x) => Math.abs(x[2])));
for (const [l, j, w] of ev.in) particles.spawn(posOf(l, j), me, w >= 0 ? EXCITE : INHIBIT, Math.abs(w) / maxw, 1.1);
for (const [l, j, w] of ev.out) particles.spawn(me, posOf(l, j), w >= 0 ? EXCITE : INHIBIT, Math.abs(w) / maxw, 1.1);
}
function drawSynapses() {
if (synLines) { scene.remove(synLines); synLines.geometry.dispose(); synLines.material.dispose(); synLines = null; }
const ev = S.synapses;
if (!ev || !S.basePos) return;
const me = posOf(ev.layer, ev.idx);
const pos = [], col = [];
const maxw = Math.max(1e-9, ...ev.in.map((x) => Math.abs(x[2])), ...ev.out.map((x) => Math.abs(x[2])));
const add = (a, b, w) => {
const c = (w >= 0 ? EXCITE : INHIBIT).clone().multiplyScalar(0.25 + 0.75 * Math.abs(w) / maxw);
pos.push(...a, ...b);
col.push(c.r, c.g, c.b, c.r, c.g, c.b);
};
for (const [l, j, w] of ev.in) add(posOf(l, j), me, w);
for (const [l, j, w] of ev.out) add(me, posOf(l, j), w);
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setAttribute('color', new THREE.Float32BufferAttribute(col, 3));
synLines = new THREE.LineSegments(g, new THREE.LineBasicMaterial({
vertexColors: true, transparent: true, opacity: 0.85, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false }));
synLines.renderOrder = 2;
scene.add(synLines);
}
document.querySelectorAll('#inspector [data-factor]').forEach((b) => (b.onclick = () => {
if (!S.selected) return;
send({ cmd: 'neurons', layer: S.selected.L, idx: [S.selected.idx], factor: Number(b.dataset.factor) });
}));
document.querySelectorAll('#inspector [data-top]').forEach((b) => (b.onclick = () => {
if (!S.selected) return;
send({ cmd: 'neurons', layer: S.selected.L, top: Number(b.dataset.top), factor: Number(b.dataset.topfactor) });
}));
$('btn-undo').onclick = () => send({ cmd: 'undo' });
$('btn-reset').onclick = () => { if (confirm('Riportare tutti i neuroni allo stato originale? Non si può annullare.')) send({ cmd: 'reset' }); };
$('btn-remap').onclick = () => { showBoot('Rimappatura del cervello in corso…'); send({ cmd: 'remap' }); };
// ---------------------------------------------------------------- attività per strato (EEG)
const eeg = $('eeg');
function drawEEG() {
const dpr = Math.min(devicePixelRatio, 2);
const w = eeg.clientWidth, h = eeg.clientHeight;
if (eeg.width !== w * dpr) { eeg.width = w * dpr; eeg.height = h * dpr; }
const g = eeg.getContext('2d');
g.setTransform(dpr, 0, 0, dpr, 0, 0);
g.clearRect(0, 0, w, h);
const L = S.nLayer;
if (!L) return;
const bw = w / L;
for (let l = 0; l < L; l++) {
const v = S.eegMax[l] > 0 ? S.eeg[l] / S.eegMax[l] : 0;
const bh = Math.max(1, v * (h - 12));
g.fillStyle = REGION_COLORS[(S.regionOfLayer[l] ?? 0) % REGION_COLORS.length];
g.globalAlpha = 0.25 + 0.75 * v;
g.fillRect(l * bw + 1, h - 12 - bh, Math.max(1, bw - 2), bh);
}
g.globalAlpha = 1;
g.fillStyle = '#7d8a9c';
g.font = '10px Consolas, monospace';
g.fillText('strato 0', 0, h - 1);
g.textAlign = 'right';
g.fillText(`strato ${L - 1}`, w, h - 1);
}
// ---------------------------------------------------------------- frame di attività
// header: u8 'A', u8 versione, u16 strati, u16 k, u16 0, u32 seq; per strato: f32 media, u16 idx[k], f32 val[k]
function onFrame(buf) {
const dv = new DataView(buf);
if (dv.getUint8(0) === 80) return playVoice(buf); // 'P': la voce di Neuronal nella chiamata
if (!S.basePos || dv.getUint8(1) !== 1) return;
const kind = dv.getUint8(0);
if (kind === 83) return onMessages(dv); // 'S'
if (kind === 67) return onBlockFrame(dv); // 'C'
if (kind === 68) return sentinelsView.onFrame(dv); // 'D'
if (kind !== 65) return; // 'A'
const L = dv.getUint16(2, true), k = dv.getUint16(4, true);
const per = 4 + 6 * k;
for (let l = 0; l < L; l++) {
const o = 12 + l * per;
const mean = dv.getFloat32(o, true);
S.eeg[l] = S.eeg[l] * 0.5 + mean * 0.5;
S.eegMax[l] = Math.max(S.eegMax[l] * 0.999, S.eeg[l]);
const top = Math.abs(dv.getFloat32(o + 4 + 2 * k, true)) || 1;
for (let t = 0; t < k; t++) {
const idx = dv.getUint16(o + 4 + 2 * t, true);
const v = Math.abs(dv.getFloat32(o + 4 + 2 * k + 4 * t, true)) / top;
if (v > 0.3) light(l, idx, v); // solo i neuroni davvero dominanti nello strato
}
}
}
// Messaggi tra neuroni lungo sinapsi reali: u16 n, u32 seq; per messaggio u16 strato, u16 da, u16 a, i16 forza
function onMessages(dv) {
const n = dv.getUint16(2, true);
for (let k = 0; k < n; k++) {
const o = 8 + k * 8;
const l = dv.getUint16(o, true), i = dv.getUint16(o + 2, true), j = dv.getUint16(o + 4, true);
const f = dv.getInt16(o + 6, true) / 32767;
if (l + 1 >= S.nLayer) continue;
particles.spawn(posOf(l, i), posOf(l + 1, j), f >= 0 ? EXCITE : INHIBIT, Math.abs(f), 0.55);
S.msgCount++;
}
}
// Attivazione dei neuroni dei blocchi: u16 blocchi, u32 seq; per blocco u16 id, u16 n, f32 att[n]
function onBlockFrame(dv) {
const nb = dv.getUint16(2, true);
let o = 8;
for (let b = 0; b < nb; b++) {
const id = dv.getUint16(o, true), n = dv.getUint16(o + 2, true);
o += 4;
const vals = new Float32Array(n);
for (let k = 0; k < n; k++) vals[k] = dv.getFloat32(o + 4 * k, true);
o += 4 * n;
blocksView.setActivations(id, vals);
}
}
// ---------------------------------------------------------------- blocchi
$('new-block').onsubmit = (e) => {
e.preventDefault();
const n = Number($('nb-n').value);
if (!(n >= 1 && n <= 512)) return;
send({ cmd: 'block_create', neurons: n, name: $('nb-name').value.trim() });
$('nb-name').value = '';
};
function openBlock(id) {
S.focusBlock = id;
showTab('blocks');
renderBlocks();
const c = blocksView.focus(id);
if (c) controls.target.set(c[0], c[1] * 0.5, 0);
document.querySelector(`.block[data-id="${id}"]`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
const STATE_LABEL = {
normale: 'originale',
modificata: 'nuovo utilizzo',
eliminata: 'eliminata · specializzazione spenta',
eliminata_tutta: 'eliminata completamente',
};
const isUi = (kind, id, mode) => S.ui && S.ui.kind === kind && S.ui.id === id && (!mode || S.ui.mode === mode);
const openUi = (kind, id, mode) => { S.ui = isUi(kind, id, mode) ? null : { kind, id, mode }; renderBlocks(); };
// Controlli comuni di un blocco applicato: acceso, intensità, prova di Neuronal, esempi.
function blockControls(b) {
return `
Si attiva nel ${Math.round(b.pos_rate * 100)}% degli esempi della funzione e nel ${Math.round(b.neg_rate * 100)}% dei testi neutri
· ${fmt(b.neurons)} neuroni negli strati ${b.first}–${b.last}
Come lo usa Neuronal
${esc(b.effect)}
Esempi elaborati da Neuronal (${b.examples.length})
${b.examples.map((x) => `
${esc(x)}
`).join('')}
`;
}
function renameForm(name) {
return `
`;
}
function examplesField() {
return `Aggiungi esempi tuoi (facoltativo, uno per riga)`;
}
const readExamples = (li) => (li.querySelector('[data-act="examples"]')?.value || '').split('\n').map((x) => x.trim()).filter(Boolean);
function wireBlockControls(li, b) {
li.querySelector('[data-act="enabled"]')?.addEventListener('change', (e) => send({ cmd: 'block_set', id: b.id, enabled: e.target.checked }));
const g = li.querySelector('[data-act="gain"]');
if (g) {
g.oninput = () => (g.nextElementSibling.textContent = '×' + Number(g.value).toFixed(1));
g.onchange = () => send({ cmd: 'block_set', id: b.id, gain: Number(g.value) });
}
li.querySelector('[data-act="infect"]')?.addEventListener('click', () => {
const k = S.blockNeuron?.id === b.id ? S.blockNeuron.k : Math.floor(Math.random() * b.neurons);
send({ cmd: 'infect', block: b.id, k });
});
}
const HEALTH = {
ok: ['live', 'in salute'], controllo: ['busy', 'si sta controllando…'], riparato: ['live', 'riparato da solo'],
problema: ['danger', 'problema non risolto'], riavvio: ['busy', 'si sta riavviando'], spento: ['', 'autodiagnosi spenta'],
};
// "Sospeso da Neuronal" con la possibilità di riattivare comunque.
function autoNote(reason, kind, id) {
return `
Neuronal: ${esc(reason)}
`;
}
function wireForce(el) {
el.querySelectorAll('[data-force]').forEach((b) => (b.onclick = () => {
if (confirm('Riattivare comunque? Neuronal aveva rilevato che gli impediva di funzionare bene. Rispetterà la tua scelta fino al prossimo riavvio.'))
send({ cmd: 'doctor_force', kind: b.dataset.force, id: Number(b.dataset.id) });
}));
}
const ROLE_LABELS = [['analisi', 'analisi'], ['controllo', 'controllo'], ['sicurezza', 'sicurezza'], ['riparazione', 'riparazione'], ['coordinamento', 'nucleo']];
const when = (t) => (t ? new Date(t * 1000).toLocaleString('it-IT', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: '2-digit' }) : 'mai');
function renderDiagnosisCard() {
const li = document.createElement('li');
li.className = 'block diag';
const d = S.doctor;
if (!d) { li.textContent = 'Rete della Diagnosi: in attesa del motore…'; return li; }
const [cls, label] = HEALTH[d.status] || ['', d.status];
const legend = ROLE_LABELS.map(([r, l]) => `${l}`).join('');
let html = `
Rete della Diagnosi${Math.max(0, d.groups.length - 1)} presidi + nucleo
${label}
Presidi di neuroni sentinella distribuiti dentro ogni macroarea e coordinati da un nucleo centrale.
Ogni presidio analizza l'attività dei suoi strati, controlla che la sua area funzioni, verifica la sicurezza dei suoi pesi
e ripara o ricostruisce quando serve.
${legend}
${d.last_check ? `ultimo controllo ${when(d.last_check)}` : ''}
`;
if (d.network_on) {
html += '
';
for (const g of d.groups) {
const st = !g.enabled ? 'spento' : g.alarm ? 'allarme'
: g.repairing ? 'in riparazione' : 'di guardia';
const area = g.region === 0 ? 'coordina tutti i presidi' : `strati ${g.first}–${g.last}${g.ratio >= 0 ? ` · risposta ${Math.round(g.ratio * 100)}%` : ''}`;
html += `
${esc(g.name)} ${st}${area}
${esc(g.report)}
`;
}
html += '
';
html += `
Sicurezza dei pesi: ${esc(d.security || 'non ancora controllata')} ${d.security_t ? `(${when(d.security_t)})` : ''}
${d.security_running ? ' · controllo in corso…' : ''}
Punto di ripristino sano: ${when(d.snapshot)}
`;
}
// tutto quello che la rete ha sospeso o attenuato
const notes = [];
if (d.interventions_suspended) notes.push(autoNote('ha sospeso i tuoi interventi manuali sui neuroni (non cancellati).', 'interventions', 0));
for (const r of S.regions) if (r.auto_off || r.auto_state !== 'normale' || r.auto_keep_old) notes.push(autoNote(r.auto_reason, 'region', r.id));
for (const b of S.blocks) if (b.auto_off || b.auto_gain > 0) notes.push(autoNote(b.auto_reason, 'block', b.id));
if (notes.length) html += `
${notes.join('')}
`;
const journal = (d.journal || []).slice().reverse();
if (journal.length) {
const line = (e) => `
${esc(e.text)}
`;
html += `
${journal.slice(0, 5).map(line).join('')}
`;
if (journal.length > 5) html += `Diario completo (${journal.length})
${journal.slice(5).map(line).join('')}
`;
}
if (d.network_on) html += `
`;
li.innerHTML = html;
li.querySelector('[data-act="network"]').onchange = (e) => {
if (!e.target.checked && !confirm('Spegnere la Rete della Diagnosi? Neuronal smetterà di controllarsi, proteggersi e ripararsi da solo.')) { e.target.checked = true; return; }
send({ cmd: e.target.checked ? 'network_on' : 'network_off' });
};
li.querySelectorAll('[data-group]').forEach((el) => (el.onchange = () => send({ cmd: 'sentinel_set', index: Number(el.dataset.group), enabled: el.checked })));
li.querySelector('[data-act="check"]')?.addEventListener('click', () => send({ cmd: 'doctor' }));
li.querySelector('[data-act="security"]')?.addEventListener('click', () => send({ cmd: 'security_check' }));
li.querySelector('[data-act="rebuild"]')?.addEventListener('click', () => {
if (confirm(`Ricostruire tutto com'era all'ultimo punto sano (${when(d.snapshot)})? Blocchi e macroaree torneranno a quello stato e il motore si riavvierà.`))
send({ cmd: 'reconstruct' });
});
wireForce(li);
return li;
}
function renderRegionCard(r, i) {
const li = document.createElement('li');
li.className = 'block' + (i === S.focusRegion ? ' focus' : '');
const blk = r.block ? S.blocks.find((b) => b.id === r.block) : null;
const busyBlock = S.regionBusy.get(r.id);
const busy = busyBlock !== undefined ? (S.blockProgress.get(busyBlock) || 'In coda: Neuronal inizierà appena libero…') : null;
const renamed = r.name !== r.original_name;
let html = `
${esc(r.name)}strati ${r.first}–${r.last}
${STATE_LABEL[r.state] || ''}${renamed ? `
nome originale: ${esc(r.original_name)}
` : ''}
${esc(r.function)}
`;
if (r.auto_off || r.auto_state !== 'normale' || r.auto_keep_old) html += autoNote(r.auto_reason, 'region', r.id);
if (r.state === 'modificata') {
html += `
${r.replace ? 'Sostituisce' : 'Si aggiunge a'} la funzione originale: «${esc(r.original_function)}»
`;
if (blk && blk.applied) html += blockControls(blk);
} else {
html += `
${fmt(r.selective)} neuroni specializzati
`;
}
if (busy) html += `
${esc(busy)}
`;
else if (isUi('region', r.id, 'rename')) html += renameForm(r.name);
else if (isUi('region', r.id, 'use')) {
html += `
Se sostituisce, i ${fmt(r.selective)} neuroni specializzati dell'area vengono attenuati al 30%; altrimenti la nuova funzione si aggiunge.
${examplesField()}
`;
} else if (isUi('region', r.id, 'delete')) {
html += `
Eliminare «${esc(r.name)}»?
Solo la specializzazione: si spengono i suoi ${fmt(r.selective)} neuroni specializzati. Neuronal continua a funzionare ma perde questa capacità.
Completamente: si spengono tutti i ${fmt((r.last - r.first + 1) * S.nFF)} neuroni dell'area. Nelle prove Neuronal ha cominciato a sbagliare o è rimasto muto.
Puoi sempre ripristinarla.
`;
} else {
html += '
';
html += '';
html += '';
if (!r.state.startsWith('eliminata')) html += '';
if (r.state !== 'normale' || renamed) html += '';
html += '