| 1 | // Modelo: convierte el árbol del repo en una ciudad con cajas anidadas. |
| 2 | // Jerarquía: ciudad → distrito → edificio → planta → apartamento → habitación |
| 3 | // → archivador → cajón → fichero (los ficheros pueden vivir en |
| 4 | // cualquier nivel: se les reserva un hueco en su contenedor). |
| 5 | // Cuando un subárbol es demasiado profundo/poblado para un solo edificio, |
| 6 | // se interpone una «urbanización»: una plota dentro del distrito que agrupa |
| 7 | // procedualmente a sus subcarpetas como edificios (recursivo), de modo que |
| 8 | // la profundidad sobrante se despliega por la ciudad en vez de comprimirse. |
| 9 | // Los ficheros ignorados (.gitignore y equivalentes) se separan en un |
| 10 | // sótano espejado bajo el plano de circuitos. |
| 11 | import { makeOwnerResolver } from './ownership.js'; |
| 12 | |
| 13 | export const ROLES = ['ciudad', 'distrito', 'edificio', 'planta', 'apartamento', 'habitacion', 'archivador', 'cajon']; |
| 14 | const ROLE_AXIS = { planta: 'y', apartamento: 'x', habitacion: 'z', archivador: 'x', cajon: 'y' }; |
| 15 | |
| 16 | const STREET = 14; // separación entre distritos |
| 17 | const ALLEY = 4; // separación entre edificios |
| 18 | const URB_PAD = 3; // margen interior de una urbanización |
| 19 | // un edificio absorbe 5 niveles (planta→…→cajón); más allá, urbanización |
| 20 | const URB_DEPTH = 5; |
| 21 | const URB_MIN_FILES = 200; |
| 22 | const URB_MAX_FILES = 2000; // aun siendo poco profundo, esto no cabe en uno |
| 23 | const GROUND_Y = 0; |
| 24 | |
| 25 | let nextNode = 0; |
| 26 | let nextFile = 0; |
| 27 | |
| 28 | function hash01(str) { |
| 29 | let h = 2166136261; |
| 30 | for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } |
| 31 | return ((h >>> 0) % 1000) / 1000; |
| 32 | } |
| 33 | |
| 34 | function unpack(packed) { |
| 35 | const [name, dirs, leaf] = packed; |
| 36 | const node = { name, dirs: dirs.map(unpack), leaf: leaf.map(([n, s, ig]) => ({ name: n, size: s, ignored: !!ig })) }; |
| 37 | node.files = node.leaf.length + node.dirs.reduce((a, d) => a + d.files, 0); |
| 38 | node.size = node.leaf.reduce((a, f) => a + f.size, 0) + node.dirs.reduce((a, d) => a + d.size, 0); |
| 39 | return node; |
| 40 | } |
| 41 | |
| 42 | function recount(node) { |
| 43 | node.files = node.leaf.length + node.dirs.reduce((a, d) => a + d.files, 0); |
| 44 | node.size = node.leaf.reduce((a, f) => a + f.size, 0) + node.dirs.reduce((a, d) => a + d.size, 0); |
| 45 | return node; |
| 46 | } |
| 47 | |
| 48 | // separa un subárbol en parte visible y parte ignorada (sótano) |
| 49 | function splitSrc(src) { |
| 50 | const kept = { name: src.name, dirs: [], leaf: src.leaf.filter(f => !f.ignored) }; |
| 51 | const ign = { name: src.name, dirs: [], leaf: src.leaf.filter(f => f.ignored) }; |
| 52 | for (const d of src.dirs) { |
| 53 | const s = splitSrc(d); |
| 54 | if (s.kept.files) kept.dirs.push(s.kept); |
| 55 | if (s.ign.files) ign.dirs.push(s.ign); |
| 56 | } |
| 57 | return { kept: recount(kept), ign: recount(ign) }; |
| 58 | } |
| 59 | |
| 60 | function makeNode(model, name, role, parent, { virtual = false } = {}) { |
| 61 | const node = { |
| 62 | id: nextNode++, name, role, parent, children: [], fileIds: [], |
| 63 | virtual, box: null, building: null, |
| 64 | path: parent ? (virtual ? parent.path : `${parent.path}/${name}`) : name, |
| 65 | }; |
| 66 | if (parent) parent.children.push(node); |
| 67 | model.nodes.push(node); |
| 68 | return node; |
| 69 | } |
| 70 | |
| 71 | function addFiles(model, node, leaf) { |
| 72 | for (const f of leaf) { |
| 73 | const file = { |
| 74 | id: nextFile++, name: f.name, size: f.size, node, |
| 75 | path: `${node.path}/${f.name}`, box: null, |
| 76 | }; |
| 77 | node.fileIds.push(file.id); |
| 78 | model.files.push(file); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // ── dimensiones de edificio ─────────────────────────────────────────────── |
| 83 | function buildingDims(src) { |
| 84 | const kb = src.size / 1024; |
| 85 | const side = Math.min(22, Math.max(6, 4 + Math.log2(1 + kb) * 1.5)); |
| 86 | const j = hash01(src.name); |
| 87 | const w = side * (0.85 + 0.3 * j); |
| 88 | const d = side * (0.85 + 0.3 * (1 - j)); |
| 89 | const floors = Math.max(1, src.dirs.length + (src.leaf.length ? 1 : 0)); |
| 90 | const h = Math.max(6, Math.max(floors * 3.0, 6 + src.files * 1.8)); |
| 91 | return { w, d, h: Math.min(h, 80) }; |
| 92 | } |
| 93 | |
| 94 | // ── reparto de un eje en franjas ponderadas ─────────────────────────────── |
| 95 | function splitAxis(box, axis, weights, inset) { |
| 96 | const total = weights.reduce((a, b) => a + b, 0); |
| 97 | const span = box['s' + axis]; |
| 98 | const start = box['c' + axis] - span / 2; |
| 99 | const gap = Math.min(inset, span * 0.04); |
| 100 | const usable = span - gap * (weights.length + 1); |
| 101 | const out = []; |
| 102 | let cursor = start + gap; |
| 103 | for (const w of weights) { |
| 104 | const s = usable * (w / total); |
| 105 | out.push({ ...box, ['c' + axis]: cursor + s / 2, ['s' + axis]: s }); |
| 106 | cursor += s + gap; |
| 107 | } |
| 108 | return out; |
| 109 | } |
| 110 | |
| 111 | function shrink(box, f) { |
| 112 | return { ...box, sx: box.sx * f, sy: box.sy * f, sz: box.sz * f }; |
| 113 | } |
| 114 | |
| 115 | // ── celdas de fichero dentro de su contenedor ───────────────────────────── |
| 116 | function placeFiles(model, node, box, files) { |
| 117 | const n = files.length; |
| 118 | if (!n) return; |
| 119 | if (node.role === 'cajon') { |
| 120 | // carpetas colgantes: láminas verticales en fila |
| 121 | const slabs = splitAxis({ ...box, sy: box.sy * 0.72, cy: box.cy - box.sy * 0.1 }, 'x', |
| 122 | files.map(() => 1), 0.05); |
| 123 | files.forEach((fid, i) => { |
| 124 | const s = slabs[i]; |
| 125 | model.files[fid].box = { ...s, sx: Math.min(s.sx * 0.55, 0.5), sz: s.sz * 0.78 }; |
| 126 | }); |
| 127 | return; |
| 128 | } |
| 129 | // rejilla de cubos apoyada en el suelo del contenedor |
| 130 | const aspect = box.sx / box.sz || 1; |
| 131 | const cols = Math.max(1, Math.round(Math.sqrt(n * aspect))); |
| 132 | const rows = Math.ceil(n / cols); |
| 133 | const cw = box.sx / cols, cd = box.sz / rows; |
| 134 | const base = Math.min(cw, cd, box.sy) * 0.5; |
| 135 | files.forEach((fid, i) => { |
| 136 | const f = model.files[fid]; |
| 137 | const col = i % cols, row = Math.floor(i / cols); |
| 138 | const k = 0.65 + 0.45 * Math.min(1, Math.log2(2 + f.size / 1024) / 8); |
| 139 | const s = Math.max(0.25, base * k); |
| 140 | f.box = { |
| 141 | cx: box.cx - box.sx / 2 + cw * (col + 0.5), |
| 142 | cz: box.cz - box.sz / 2 + cd * (row + 0.5), |
| 143 | cy: box.cy - box.sy / 2 + s / 2 + 0.05, |
| 144 | sx: s, sy: s, sz: s, |
| 145 | }; |
| 146 | }); |
| 147 | } |
| 148 | |
| 149 | // ── subdivisión recursiva del interior del edificio ─────────────────────── |
| 150 | // flipY: en los sótanos las plantas crecen hacia abajo (dirección inversa) |
| 151 | function layoutInterior(model, node, src, box, role, flipY = false) { |
| 152 | node.box = box; |
| 153 | const dirs = src.dirs; |
| 154 | const hasFiles = src.leaf.length > 0; |
| 155 | addFiles(model, node, src.leaf); |
| 156 | |
| 157 | if (!dirs.length) { |
| 158 | placeFiles(model, node, shrink(box, 0.9), node.fileIds); |
| 159 | return; |
| 160 | } |
| 161 | const childRole = ROLES[Math.min(ROLES.indexOf(role) + 1, ROLES.length - 1)]; |
| 162 | const axis = ROLE_AXIS[childRole] ?? 'y'; |
| 163 | const weights = dirs.map(d => 1 + Math.sqrt(d.files)); |
| 164 | if (hasFiles) weights.push(0.8 + Math.sqrt(src.leaf.length) * 0.7); |
| 165 | const slices = splitAxis(box, axis, weights, 0.5); |
| 166 | if (flipY && axis === 'y') slices.reverse(); |
| 167 | dirs.forEach((d, i) => { |
| 168 | const child = makeNode(model, d.name, childRole, node); |
| 169 | child.building = node.building; |
| 170 | layoutInterior(model, child, d, shrink(slices[i], 0.94), childRole, flipY); |
| 171 | }); |
| 172 | if (hasFiles) placeFiles(model, node, shrink(slices[slices.length - 1], 0.9), node.fileIds); |
| 173 | } |
| 174 | |
| 175 | // ── empaquetado en rejilla (edificios en distrito, distritos en ciudad) ─── |
| 176 | function packGrid(items, gap) { |
| 177 | // items: { w, d } → coloca en filas; devuelve posiciones y tamaño del plot |
| 178 | const area = items.reduce((a, it) => a + (it.w + gap) * (it.d + gap), 0); |
| 179 | const targetW = Math.max(Math.sqrt(area) * 1.15, ...items.map(it => it.w + gap)); |
| 180 | let x = 0, z = 0, rowD = 0, plotW = 0; |
| 181 | const pos = []; |
| 182 | for (const it of items) { |
| 183 | if (x > 0 && x + it.w > targetW) { x = 0; z += rowD + gap; rowD = 0; } |
| 184 | pos.push({ x: x + it.w / 2, z: z + it.d / 2 }); |
| 185 | x += it.w + gap; |
| 186 | rowD = Math.max(rowD, it.d); |
| 187 | plotW = Math.max(plotW, x - gap); |
| 188 | } |
| 189 | return { pos, w: plotW, d: z + rowD }; |
| 190 | } |
| 191 | |
| 192 | function subtreeDepth(src) { |
| 193 | let d = 0; |
| 194 | for (const s of src.dirs) d = Math.max(d, 1 + subtreeDepth(s)); |
| 195 | return d; |
| 196 | } |
| 197 | |
| 198 | // ¿demasiado profundo y poblado para un solo edificio? → urbanización |
| 199 | function needsUrb(src) { |
| 200 | if (src.virtual || !src.dirs.length) return false; |
| 201 | if (src.files > URB_MAX_FILES) return true; |
| 202 | return src.files > URB_MIN_FILES && subtreeDepth(src) > URB_DEPTH; |
| 203 | } |
| 204 | |
| 205 | function fileBlockSrc(leaf) { |
| 206 | return { name: '(ficheros)', dirs: [], leaf, files: leaf.length, size: leaf.reduce((a, f) => a + f.size, 0), virtual: true }; |
| 207 | } |
| 208 | |
| 209 | // un «bloque» es lo que ocupa una parcela: un edificio o una urbanización. |
| 210 | // Devuelve { w, d, place(cx, cz) } para el empaquetado en rejilla. |
| 211 | function buildBlock(model, parent, src) { |
| 212 | if (needsUrb(src)) return buildUrb(model, parent, src); |
| 213 | const split = splitSrc(src); |
| 214 | const b = makeNode(model, src.name, 'edificio', parent, { virtual: !!src.virtual }); |
| 215 | b.building = b; |
| 216 | b.dims = buildingDims(split.kept.files ? split.kept : src); |
| 217 | // sin nada en superficie y todo en el sótano: búnker bajo y más opaco |
| 218 | // que señala que la información está bajo el suelo |
| 219 | if (!split.kept.files && split.ign.files) { |
| 220 | b.onlyBasement = true; |
| 221 | b.dims.h = 3; |
| 222 | } |
| 223 | b.srcKept = split.kept; |
| 224 | b.srcIgn = split.ign; |
| 225 | model.buildings.push(b); |
| 226 | return { w: b.dims.w, d: b.dims.d, place: (cx, cz) => placeBuilding(model, b, cx, cz) }; |
| 227 | } |
| 228 | |
| 229 | function buildUrb(model, parent, src) { |
| 230 | const urb = makeNode(model, src.name, 'urbanizacion', parent); |
| 231 | const childSrcs = [...src.dirs]; |
| 232 | if (src.leaf.length) childSrcs.push(fileBlockSrc(src.leaf)); |
| 233 | const blocks = childSrcs.map(s => buildBlock(model, urb, s)); |
| 234 | const grid = packGrid(blocks, ALLEY); |
| 235 | const w = grid.w + URB_PAD * 2, d = grid.d + URB_PAD * 2; |
| 236 | model.urbs.push(urb); |
| 237 | return { |
| 238 | w, d, |
| 239 | place: (cx, cz) => { |
| 240 | urb.box = { cx, cy: GROUND_Y + 0.26, cz, sx: w, sy: 0.14, sz: d }; |
| 241 | const ox = cx - w / 2 + URB_PAD, oz = cz - d / 2 + URB_PAD; |
| 242 | blocks.forEach((blk, i) => blk.place(ox + grid.pos[i].x, oz + grid.pos[i].z)); |
| 243 | }, |
| 244 | }; |
| 245 | } |
| 246 | |
| 247 | function placeBuilding(model, b, cx, cz) { |
| 248 | const { w, d, h } = b.dims; |
| 249 | layoutInterior(model, b, b.srcKept, { cx, cz, cy: GROUND_Y + h / 2, sx: w, sy: h, sz: d }, 'edificio'); |
| 250 | // sótano: los ficheros ignorados crecen hacia abajo, mismo patrón invertido |
| 251 | if (b.srcIgn.files) { |
| 252 | const hb = Math.min(60, Math.max(5, Math.max( |
| 253 | (b.srcIgn.dirs.length + (b.srcIgn.leaf.length ? 1 : 0)) * 3.0, |
| 254 | 5 + b.srcIgn.files * 1.6, |
| 255 | ))); |
| 256 | const bb = makeNode(model, b.name, 'edificio', b.parent, { virtual: b.virtual }); |
| 257 | bb.building = bb; |
| 258 | bb.isBasement = true; |
| 259 | model.buildings.push(bb); |
| 260 | layoutInterior(model, bb, b.srcIgn, |
| 261 | { cx, cz, cy: GROUND_Y - 0.7 - hb / 2, sx: w, sy: hb, sz: d }, 'edificio', true); |
| 262 | } |
| 263 | delete b.srcKept; delete b.srcIgn; |
| 264 | } |
| 265 | |
| 266 | function buildDistrict(model, city, srcDir, files) { |
| 267 | const district = makeNode(model, srcDir ? srcDir.name : '(raíz)', 'distrito', city, { virtual: !srcDir }); |
| 268 | const blockSrcs = []; |
| 269 | if (srcDir) { |
| 270 | for (const d of srcDir.dirs) blockSrcs.push(d); |
| 271 | if (srcDir.leaf.length) blockSrcs.push(fileBlockSrc(srcDir.leaf)); |
| 272 | } else { |
| 273 | blockSrcs.push(fileBlockSrc(files)); |
| 274 | } |
| 275 | const blocks = blockSrcs.map(s => buildBlock(model, district, s)); |
| 276 | const grid = packGrid(blocks, ALLEY); |
| 277 | district.plot = { w: grid.w + ALLEY * 2, d: grid.d + ALLEY * 2 }; |
| 278 | district.blocks = blocks; |
| 279 | district.grid = grid; |
| 280 | model.districts.push(district); |
| 281 | return district; |
| 282 | } |
| 283 | |
| 284 | export function buildModel(packedTree, meta = null) { |
| 285 | nextNode = 0; nextFile = 0; |
| 286 | const model = { nodes: [], files: [], buildings: [], districts: [], urbs: [], city: null }; |
| 287 | const root = unpack(packedTree); |
| 288 | const city = makeNode(model, root.name, 'ciudad', null); |
| 289 | model.city = city; |
| 290 | |
| 291 | for (const d of root.dirs) buildDistrict(model, city, d, []); |
| 292 | if (root.leaf.length) buildDistrict(model, city, null, root.leaf); |
| 293 | |
| 294 | // colocar distritos en la ciudad |
| 295 | const plots = model.districts.map(di => ({ w: di.plot.w, d: di.plot.d })); |
| 296 | const cityGrid = packGrid(plots, STREET); |
| 297 | const ox = -cityGrid.w / 2, oz = -cityGrid.d / 2; |
| 298 | model.districts.forEach((di, i) => { |
| 299 | const p = cityGrid.pos[i]; |
| 300 | const px = ox + p.x, pz = oz + p.z; |
| 301 | di.box = { cx: px, cy: GROUND_Y + 0.12, cz: pz, sx: di.plot.w, sy: 0.24, sz: di.plot.d }; |
| 302 | const bx = px - di.plot.w / 2 + ALLEY, bz = pz - di.plot.d / 2 + ALLEY; |
| 303 | di.blocks.forEach((blk, j) => blk.place(bx + di.grid.pos[j].x, bz + di.grid.pos[j].z)); |
| 304 | delete di.blocks; delete di.grid; |
| 305 | }); |
| 306 | city.box = { cx: 0, cy: 0, cz: 0, sx: cityGrid.w + STREET * 2, sy: 1, sz: cityGrid.d + STREET * 2 }; |
| 307 | |
| 308 | // cadena de ancestros por fichero (para la iluminación jerárquica) |
| 309 | // + metadatos git y code ownership por fichero |
| 310 | const rootPrefix = city.name + '/'; |
| 311 | const resolveOwner = makeOwnerResolver(meta?.owners); |
| 312 | const ownerIndex = new Map(); |
| 313 | for (const f of model.files) { |
| 314 | const chain = []; |
| 315 | for (let n = f.node; n; n = n.parent) chain.push(n); |
| 316 | f.chain = chain; // del contenedor inmediato hacia la ciudad |
| 317 | f.rel = f.path.startsWith(rootPrefix) ? f.path.slice(rootPrefix.length) : f.path; |
| 318 | const g = meta?.git?.[f.rel]; |
| 319 | f.git = g ? { st: g[0], a: g[1], d: g[2] } : null; |
| 320 | const owner = resolveOwner(f.rel); |
| 321 | if (owner != null) { |
| 322 | if (!ownerIndex.has(owner)) ownerIndex.set(owner, ownerIndex.size); |
| 323 | f.owner = ownerIndex.get(owner); |
| 324 | } else { |
| 325 | f.owner = null; |
| 326 | } |
| 327 | } |
| 328 | model.owners = [...ownerIndex.keys()]; |
| 329 | model.hasGit = !!meta?.git; |
| 330 | |
| 331 | applyCodeMeta(model, meta?.links, meta?.codeIndex); |
| 332 | model.fileByRel = new Map(model.files.map(f => [f.rel, f])); |
| 333 | model.dirByRel = new Map(); |
| 334 | for (const n of model.nodes) { |
| 335 | if (n.role === 'ciudad' || n.virtual || n.isBasement || n.building?.isBasement) continue; |
| 336 | const rel = n.path.startsWith(rootPrefix) ? n.path.slice(rootPrefix.length) : n.path; |
| 337 | if (!model.dirByRel.has(rel)) model.dirByRel.set(rel, n); |
| 338 | } |
| 339 | return model; |
| 340 | } |
| 341 | |
| 342 | // enlaces de código (modo Blast): adyacencia saliente y entrante. Es una |
| 343 | // función aparte porque el análisis perezoso los refresca por lotes sobre |
| 344 | // el modelo ya construido, sin reconstruir la ciudad. |
| 345 | export function applyCodeMeta(model, links, codeIndex) { |
| 346 | model.linksOut = links ?? {}; |
| 347 | model.linksIn = {}; |
| 348 | for (const [src, toks] of Object.entries(model.linksOut)) { |
| 349 | for (const tok of toks) { |
| 350 | if (tok.startsWith('F:')) (model.linksIn[tok.slice(2)] ??= []).push(src); |
| 351 | } |
| 352 | } |
| 353 | // índice de símbolos (funciones/clases/tipos): aristas "src usa sym de target" |
| 354 | model.defs = codeIndex?.defs ?? {}; |
| 355 | model.symOut = codeIndex?.symLinks ?? {}; |
| 356 | model.symIn = {}; |
| 357 | for (const [src, edges] of Object.entries(model.symOut)) { |
| 358 | for (const [target, sym] of edges) (model.symIn[target] ??= []).push([src, sym]); |
| 359 | } |
| 360 | } |