coeng

view src/sim.cc @ 8:8cce82794f90

seems to work nicely
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 15 Feb 2015 05:14:20 +0200
parents af24cfbdf9b6
children
line source
1 #include <algorithm>
2 #include "sim.h"
4 SimWorld::SimWorld()
5 : gravity(0, -9, 0)
6 {
7 damping = 0.005;
8 }
10 void SimWorld::add_object(GObject *obj)
11 {
12 CoRigid *co = COCAST(CoRigid, obj->get_component("rigid"));
13 if(co) {
14 add_rigid_body(co);
15 } else {
16 fprintf(stderr, "SimWorld::add_object: trying to add object without rigid body component\n");
17 }
18 }
20 void SimWorld::add_rigid_body(CoRigid *co)
21 {
22 if(std::find(rigid.begin(), rigid.end(), co) == rigid.end()) {
23 rigid.push_back(co);
24 co->world = this;
25 }
26 }
28 void SimWorld::remove_object(GObject *obj)
29 {
30 CoRigid *co = COCAST(CoRigid, obj->get_component("rigid"));
31 if(co) {
32 remove_rigid_body(co);
33 } else {
34 fprintf(stderr, "SimWorld::remove_object: failed to remove object without rigid body component\n");
35 }
36 }
38 void SimWorld::remove_rigid_body(CoRigid *co)
39 {
40 std::list<CoRigid*>::iterator it = std::find(rigid.begin(), rigid.end(), co);
41 if(it != rigid.end()) {
42 rigid.erase(it);
43 } else {
44 fprintf(stderr, "SimWorld::remove_rigid_body: failed to remove missing rigid body\n");
45 }
46 }
48 void SimWorld::set_damping(float damping)
49 {
50 this->damping = damping;
51 }
53 float SimWorld::get_damping() const
54 {
55 return damping;
56 }
58 void SimWorld::set_gravity(const Vector3 &v)
59 {
60 gravity = v;
61 }
63 const Vector3 &SimWorld::get_gravity() const
64 {
65 return gravity;
66 }
68 bool SimWorld::collide(const GObject *obj, HitPoint *hit) const
69 {
70 CoCollider *co = COCAST(CoCollider, obj->get_component("collider"));
71 if(co) {
72 return collide(co, hit);
73 }
74 return false; // no collisions if it doesn't have a collider component
75 }
77 bool SimWorld::collide(const CoCollider *col, HitPoint *hit) const
78 {
79 if(!col->shape) {
80 return false;
81 }
83 // TODO do something better
84 std::list<CoRigid*>::const_iterator it = rigid.begin();
85 while(it != rigid.end()) {
86 const CoRigid *r = *it++;
87 const GObject *obj2 = r->get_object();
88 if(!obj2 || obj2 == col->get_object()) {
89 continue;
90 }
92 const CoCollider *col2 = COCAST(CoCollider, obj2->get_component("collider"));
93 if(!col2 || !col2->shape) {
94 continue;
95 }
97 if(col->shape->collide(col2->shape, hit)) {
98 return true;
99 }
100 }
101 return false;
102 }