Skip to content

Commit d175df9

Browse files
Fixed Bugs
1 parent b91c3e8 commit d175df9

1 file changed

Lines changed: 40 additions & 15 deletions

File tree

src/gravity/step.h

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,53 @@ inline void Step(std::vector<Particle>& p, real dt) {
1111
real theta = 0.5;
1212
real half = dt * real(0.5);
1313

14+
auto buildTree = [&](Octree*& root) {
15+
// Compute bounding box
16+
real minx=+1e30, miny=+1e30, minz=+1e30;
17+
real maxx=-1e30, maxy=-1e30, maxz=-1e30;
18+
19+
for (auto& a : p) {
20+
minx = std::min(minx, a.x);
21+
miny = std::min(miny, a.y);
22+
minz = std::min(minz, a.z);
23+
maxx = std::max(maxx, a.x);
24+
maxy = std::max(maxy, a.y);
25+
maxz = std::max(maxz, a.z);
26+
}
27+
28+
real cx = (minx + maxx) * 0.5;
29+
real cy = (miny + maxy) * 0.5;
30+
real cz = (minz + maxz) * 0.5;
31+
real size = std::max({maxx-minx, maxy-miny, maxz-minz}) * 0.5;
32+
33+
if (size <= 0) size = 1; // safety
34+
35+
root = new Octree(cx, cy, cz, size);
36+
37+
for (auto& a : p)
38+
root->insert(&a);
39+
40+
root->computeMass();
41+
};
42+
1443
// =========================
1544
// First Kick (dt/2)
1645
// =========================
1746
{
18-
Octree root(0,0,0, 1e9);
19-
20-
for (auto& a : p) {
21-
root.insert(&a);
22-
}
23-
root.computeMass();
47+
Octree* root = nullptr;
48+
buildTree(root);
2449

2550
#pragma omp parallel for schedule(static)
2651
for (int i = 0; i < (int)p.size(); i++) {
2752
real ax = 0, ay = 0, az = 0;
28-
bhAccel(&root, p[i], theta, ax, ay, az);
53+
bhAccel(root, p[i], theta, ax, ay, az);
2954

3055
p[i].vx += ax * half;
3156
p[i].vy += ay * half;
3257
p[i].vz += az * half;
3358
}
59+
60+
delete root;
3461
}
3562

3663
// =========================
@@ -47,21 +74,19 @@ inline void Step(std::vector<Particle>& p, real dt) {
4774
// Second Kick (dt/2)
4875
// =========================
4976
{
50-
Octree root(0,0,0, 1e9);
51-
52-
for (auto& a : p) {
53-
root.insert(&a);
54-
}
55-
root.computeMass();
77+
Octree* root = nullptr;
78+
buildTree(root);
5679

5780
#pragma omp parallel for schedule(static)
5881
for (int i = 0; i < (int)p.size(); i++) {
5982
real ax = 0, ay = 0, az = 0;
60-
bhAccel(&root, p[i], theta, ax, ay, az);
83+
bhAccel(root, p[i], theta, ax, ay, az);
6184

6285
p[i].vx += ax * half;
6386
p[i].vy += ay * half;
6487
p[i].vz += az * half;
6588
}
89+
90+
delete root;
6691
}
67-
}
92+
}

0 commit comments

Comments
 (0)