| 247 | *cz = n->oz + ((o & 4) ? q : -q); |
| 248 | } |
| 249 | static void octree_insert(octree_node_t *n, int idx, float x, float y, float z, float mass, |
| 250 | int depth) { |
| 251 | if (n->total_mass == 0.0f && n->body_index == -1) { |
| 252 | n->body_index = idx; |
| 253 | n->body_mass = mass; |
| 254 | n->cx = x; |
| 255 | n->cy = y; |
| 256 | n->cz = z; |
| 257 | n->total_mass = mass; |
| 258 | return; |
| 259 | } |
| 260 | /* OOM guard: when bodies share (or nearly share) a position, subdivision |
| 261 | * never separates them, so half_size shrinks toward zero and we allocate |
| 262 | * octree cells without bound — the runaway that exhausted memory on large |
| 263 | * graphs. Once we hit the depth/size floor, stop splitting and fold the body |
| 264 | * into this cell as an aggregate (mass-weighted centroid). */ |
| 265 | if (depth >= OCTREE_MAX_DEPTH || n->half_size < OCTREE_MIN_HALF) { |
| 266 | float nm = n->total_mass + mass; |
| 267 | n->cx = (n->cx * n->total_mass + x * mass) / nm; |
| 268 | n->cy = (n->cy * n->total_mass + y * mass) / nm; |
| 269 | n->cz = (n->cz * n->total_mass + z * mass) / nm; |
| 270 | n->total_mass = nm; |
| 271 | n->body_index = -1; |
| 272 | return; |
| 273 | } |
| 274 | if (n->body_index >= 0) { |
| 275 | int oi = n->body_index; |
| 276 | float ox = n->cx, oy = n->cy, oz = n->cz, om = n->body_mass; |
| 277 | n->body_index = -1; |
| 278 | int o = octant(n, ox, oy, oz); |
| 279 | if (!n->children[o]) { |
| 280 | float a, b, c; |
| 281 | child_center(n, o, &a, &b, &c); |
| 282 | n->children[o] = octree_new(a, b, c, n->half_size * 0.5f); |
| 283 | } |
| 284 | if (n->children[o]) |
| 285 | octree_insert(n->children[o], oi, ox, oy, oz, om, depth + 1); |
| 286 | } |
| 287 | float nm = n->total_mass + mass; |
| 288 | n->cx = (n->cx * n->total_mass + x * mass) / nm; |
| 289 | n->cy = (n->cy * n->total_mass + y * mass) / nm; |
| 290 | n->cz = (n->cz * n->total_mass + z * mass) / nm; |
| 291 | n->total_mass = nm; |
| 292 | int o = octant(n, x, y, z); |
| 293 | if (!n->children[o]) { |
| 294 | float a, b, c; |
| 295 | child_center(n, o, &a, &b, &c); |
| 296 | n->children[o] = octree_new(a, b, c, n->half_size * 0.5f); |
| 297 | } |
| 298 | if (n->children[o]) |
| 299 | octree_insert(n->children[o], idx, x, y, z, mass, depth + 1); |
| 300 | } |
| 301 | static void octree_repulse(octree_node_t *n, float px, float py, float pz, float mm, int si, |
| 302 | float kr, float *fx, float *fy, float *fz) { |
| 303 | if (!n || n->total_mass == 0.0f || n->body_index == si) |
no test coverage detected