first commit
[blok] / physicsscene.cpp
1 #include "physicsscene.h"
2 #include <QDebug>
3
4
5 #include "athread.h"
6
7 PhysicsScene::PhysicsScene(QObject *parent) :
8         QGraphicsScene(parent)
9 {
10     mGravity= b2Vec2(0.0f,10.0f);
11     createWorld();
12     mTimer = new QTimer;
13     mTimer->setInterval(20);
14     mTime = QTime::currentTime();
15     connect(mTimer,SIGNAL(timeout()),this,SLOT(mainLoop()));
16     mFps = 20;
17
18     aThread * accelerometer = new aThread(this);
19     connect(accelerometer,SIGNAL(deviceOrientation(QString,QString,QString)),this,SLOT(moveXYZ(QString,QString,QString)));
20
21
22     accelerometer->start(QThread::NormalPriority);
23 }
24 PhysicsScene::~PhysicsScene()
25 {
26
27     delete mWorld;
28 }
29
30 void PhysicsScene::createWorld()
31 {
32
33     b2AABB worldAABB;
34     worldAABB.lowerBound.Set(-100.0f, -100.0f);
35     worldAABB.upperBound.Set(100.0f, 100.0f);
36     bool doSleep = false;
37     mWorld = new b2World(worldAABB, mGravity, doSleep);
38
39 }
40 void PhysicsScene::addPhysicsItem(BoxItem * item)
41 {
42     addItem(item);
43     item->setup(mWorld);
44     mBoxList.append(item);
45 }
46 void PhysicsScene::removePhysicsItem(BoxItem * item)
47 {
48     mBoxList.removeOne(item);
49     mWorld->DestroyBody(item->body());
50     removeItem(item);
51
52 }
53
54 void PhysicsScene::computeSimulation(int32 iterations)
55 {
56
57     double R = mFps/1000;
58
59     float32 timeStep = R;
60     mWorld->Step(timeStep, iterations);
61
62     b2Body* node = mWorld->GetBodyList();
63     while (node)
64     {
65         b2Body* b = node;
66         node = node->GetNext();
67
68         if ( b->GetUserData()!=NULL)
69         {
70             //            qDebug()<<"positionx:"<<b->GetPosition().x;
71             //            q#include <phonon/MediaObject>
72 //qDebug()<<"positiony:"<<b->GetPosition().y;
73
74
75             BoxItem* item = (BoxItem*)b->GetUserData();
76             if (!item->needRemoveFromWorld())
77                 item->updatePhysics();
78
79             else
80             {
81                 mWorld->DestroyBody(item->body());
82             }
83
84         }
85     }
86 }
87
88 void PhysicsScene::keyPressEvent(QKeyEvent *event)
89 {
90     qDebug()<<"key press";
91
92     computeSimulation();
93
94 }
95
96 void PhysicsScene::mainLoop()
97 {
98     mFps = mTime.elapsed();
99     mTime = QTime::currentTime();
100
101     computeSimulation();
102
103
104 }
105
106 void PhysicsScene::start()
107 {
108     mTimer->start();
109 }
110
111 void PhysicsScene::stop()
112 {
113
114
115
116
117
118     mTimer->stop();
119
120 }
121
122 void PhysicsScene::moveXYZ(QString x, QString y, QString z)
123 {
124 #if defined(Q_WS_MAEMO_5)
125
126
127
128
129
130         mWorld->SetGravity(b2Vec2(-x.toDouble()/10, -y.toDouble() / 10));
131
132 #endif
133
134     }
135
136
137