grav

view src/sim.cc @ 1:3d541da6e48c

lalalala
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 23 May 2014 18:27:42 +0300
parents 68db0e456733
children
line source
1 #include <GL/glut.h>
2 #include "sim.h"
4 Particle::Particle()
5 {
6 mass = 1.0;
7 }
9 void Particle::add_force(const Vector3 &force)
10 {
11 accel += force;
12 }
14 void Particle::step(float dt)
15 {
16 Vector3 npos = pos + vel * dt;
18 vel += accel * dt;
19 accel.x = accel.y = accel.z = 0.0;
21 prev_pos = pos;
22 pos = npos;
23 }
26 // ---- SimWorld ----
27 SimWorld::SimWorld()
28 {
29 set_world_bounds(1000.0f);
30 }
32 void SimWorld::set_world_bounds(float rad)
33 {
34 radius_sq = rad * rad;
35 }
37 void SimWorld::add_particle(const Particle &p)
38 {
39 particles.push_back(p);
40 }
42 void SimWorld::step(float dt)
43 {
44 for(size_t i=0; i<particles.size(); i++) {
45 for(size_t j=0; j<particles.size(); j++) {
46 if(i == j) continue;
48 // calculate amount of force applied by particle[j] to particle[i]
49 Vector3 gdir = particles[j].pos - particles[i].pos;
50 float len = gdir.length();
51 if(len > 0.0) {
52 gdir /= len;
53 particles[i].add_force(gdir * particles[j].mass / (len * len));
54 }
55 }
56 }
58 std::vector<Particle>::iterator it = particles.begin();
59 while(it != particles.end()) {
60 Particle *p = &*it;
61 p->step(dt);
63 if(p->pos.length_sq() > radius_sq) {
64 it = particles.erase(it);
65 } else {
66 ++it;
67 }
68 }
69 }
71 void SimWorld::draw() const
72 {
73 glBlendFunc(GL_ONE, GL_ONE);
74 glEnable(GL_BLEND);
76 glColor3f(0.5, 0.6, 0.7);
78 for(size_t i=0; i<particles.size(); i++) {
79 const Particle *p = &particles[i];
81 glPushMatrix();
82 glTranslatef(p->pos.x, p->pos.y, p->pos.z);
83 glutSolidSphere(p->mass * 0.1, 12, 6);
84 glPopMatrix();
86 glBegin(GL_LINES);
87 glNormal3f(0, 0, 1);
88 glVertex3f(p->pos.x, p->pos.y, p->pos.z);
89 glVertex3f(p->prev_pos.x, p->prev_pos.y, p->prev_pos.z);
90 glEnd();
91 }
93 glDisable(GL_BLEND);
94 }