| 322 | /* ── Local optimization (gentle, anchor-preserving) ───────────── */ |
| 323 | |
| 324 | void cbm_layout_local_optimize(cbm_layout_body_t *b, int n, const int *es, const int *ed, int ne) { |
| 325 | /* Scale iteration effort down for very large graphs: each iteration is |
| 326 | * O(n log n) octree work, and past ~100k bodies the anchor layout already |
| 327 | * dominates the visible structure — fewer refinement passes keep huge |
| 328 | * budgets responsive instead of multiplying minutes of compute. */ |
| 329 | int iterations = LOCAL_ITERATIONS; |
| 330 | if (n > 500000) { |
| 331 | iterations = 10; |
| 332 | } else if (n > 100000) { |
| 333 | iterations = 20; |
| 334 | } |
| 335 | for (int iter = 0; iter < iterations; iter++) { |
| 336 | for (int i = 0; i < n; i++) { |
| 337 | b[i].fx = 0; |
| 338 | b[i].fy = 0; |
| 339 | b[i].fz = 0; |
| 340 | } |
| 341 | |
| 342 | /* Bounding box */ |
| 343 | float mnx = 1e9f, mny = 1e9f, mnz = 1e9f, mxx = -1e9f, mxy = -1e9f, mxz = -1e9f; |
| 344 | for (int i = 0; i < n; i++) { |
| 345 | if (b[i].x < mnx) |
| 346 | mnx = b[i].x; |
| 347 | if (b[i].y < mny) |
| 348 | mny = b[i].y; |
| 349 | if (b[i].z < mnz) |
| 350 | mnz = b[i].z; |
| 351 | if (b[i].x > mxx) |
| 352 | mxx = b[i].x; |
| 353 | if (b[i].y > mxy) |
| 354 | mxy = b[i].y; |
| 355 | if (b[i].z > mxz) |
| 356 | mxz = b[i].z; |
| 357 | } |
| 358 | float half = fmaxf(fmaxf(mxx - mnx, mxy - mny), mxz - mnz) * 0.5f + 1.0f; |
| 359 | |
| 360 | /* Repulsion (Barnes-Hut) */ |
| 361 | octree_node_t *root = |
| 362 | octree_new((mnx + mxx) * 0.5f, (mny + mxy) * 0.5f, (mnz + mxz) * 0.5f, half); |
| 363 | if (!root) |
| 364 | break; |
| 365 | for (int i = 0; i < n; i++) |
| 366 | octree_insert(root, i, b[i].x, b[i].y, b[i].z, b[i].mass, 0); |
| 367 | for (int i = 0; i < n; i++) |
| 368 | octree_repulse(root, b[i].x, b[i].y, b[i].z, b[i].mass, i, LOCAL_REPULSION, &b[i].fx, |
| 369 | &b[i].fy, &b[i].fz); |
| 370 | octree_free(root); |
| 371 | |
| 372 | /* Attraction (edges) */ |
| 373 | for (int e = 0; e < ne; e++) { |
| 374 | int s = es[e], t = ed[e]; |
| 375 | if (s < 0 || s >= n || t < 0 || t >= n) |
| 376 | continue; |
| 377 | float dx = b[t].x - b[s].x, dy = b[t].y - b[s].y, dz = b[t].z - b[s].z; |
| 378 | b[s].fx += dx * LOCAL_ATTRACTION; |
| 379 | b[s].fy += dy * LOCAL_ATTRACTION; |
| 380 | b[s].fz += dz * LOCAL_ATTRACTION; |
| 381 | b[t].fx -= dx * LOCAL_ATTRACTION; |
no test coverage detected