Development/Tutorials/Physical Simulation: Difference between revisions
No edit summary |
(Marked this version for translation) |
||
Line 2: | Line 2: | ||
<translate> | <translate> | ||
==Introduction== | ==Introduction== <!--T:1--> | ||
<!--T:2--> | |||
Often in engineering you want to animate things, and KDE has a great method for doing this. I found''' KDevelop''' particular helpful due to the auto-completion. However, this tutorial also gives you the vi/emacs/randomEditor version. | Often in engineering you want to animate things, and KDE has a great method for doing this. I found''' KDevelop''' particular helpful due to the auto-completion. However, this tutorial also gives you the vi/emacs/randomEditor version. | ||
<!--T:3--> | |||
Since the code will become relatively long for a tutorial, the tutorial is split into sections. At the end of each section, the program will produce something. | Since the code will become relatively long for a tutorial, the tutorial is split into sections. At the end of each section, the program will produce something. | ||
<!--T:4--> | |||
In this tutorial you will learn how to: | In this tutorial you will learn how to: | ||
* get two or more widgets in one window | * get two or more widgets in one window | ||
Line 16: | Line 19: | ||
<!--T:5--> | |||
[[image:introtokdetutorialBouncingBall.png|400px|center]] | [[image:introtokdetutorialBouncingBall.png|400px|center]] | ||
==Setup== | ==Setup== <!--T:6--> | ||
<!--T:7--> | |||
;In '''KDevelop:''' | ;In '''KDevelop:''' | ||
:<menuchoice>Project->New from Template -> Qt4 CMake Gui application with name "FallingBall" -> Next -> Finish.</menuchoice> | :<menuchoice>Project->New from Template -> Qt4 CMake Gui application with name "FallingBall" -> Next -> Finish.</menuchoice> | ||
Open CMakeLists.txt by double clicking on it. | Open CMakeLists.txt by double clicking on it. | ||
<!--T:8--> | |||
;In a Text Editor: | ;In a Text Editor: | ||
:Make directory and create a <tt>CMakeLists.txt</tt> file, which cmake requires to find dependencies and compile the program. | :Make directory and create a <tt>CMakeLists.txt</tt> file, which cmake requires to find dependencies and compile the program. | ||
<!--T:9--> | |||
<syntaxhighlight lang="cmake"> | <syntaxhighlight lang="cmake"> | ||
project (FallingBall) | project (FallingBall) | ||
Line 32: | Line 39: | ||
include_directories(${KDE4_INCLUDES}) | include_directories(${KDE4_INCLUDES}) | ||
<!--T:10--> | |||
set(FallingBall_SRCS | set(FallingBall_SRCS | ||
main.cpp | main.cpp | ||
Line 37: | Line 45: | ||
) | ) | ||
<!--T:11--> | |||
kde4_add_executable(FallingBall ${FallingBall_SRCS}) | kde4_add_executable(FallingBall ${FallingBall_SRCS}) | ||
target_link_libraries(FallingBall ${KDE4_KDEUI_LIBS}) | target_link_libraries(FallingBall ${KDE4_KDEUI_LIBS}) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:12--> | |||
The first line gives a name to the project, and the second ensures that the klibs are installed; while the third sets the header files appropriately. The "set" line is the most important. We have to put in all the ".cpp" files that we use in here. For now, just add the main.cpp and the FallingBall.cpp. Others will join later. Finally, define the executable and link all files. | The first line gives a name to the project, and the second ensures that the klibs are installed; while the third sets the header files appropriately. The "set" line is the most important. We have to put in all the ".cpp" files that we use in here. For now, just add the main.cpp and the FallingBall.cpp. Others will join later. Finally, define the executable and link all files. | ||
==Basic structure== | ==Basic structure== <!--T:13--> | ||
<!--T:14--> | |||
Now lets start with main.cpp: | Now lets start with main.cpp: | ||
<!--T:15--> | |||
This is just the starter point of the application, which starts the main window. | This is just the starter point of the application, which starts the main window. | ||
<!--T:16--> | |||
Include conventional headers, which allow to create a KDE application, a nice AboutBox and handle command line arguments. | Include conventional headers, which allow to create a KDE application, a nice AboutBox and handle command line arguments. | ||
<!--T:17--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#include <KApplication> | #include <KApplication> | ||
Line 56: | Line 70: | ||
#include <KCmdLineArgs> | #include <KCmdLineArgs> | ||
<!--T:18--> | |||
//Include the header of the new main window. | //Include the header of the new main window. | ||
#include "FallingBall.h" | #include "FallingBall.h" | ||
<!--T:19--> | |||
int main (int argc, char *argv[]) | int main (int argc, char *argv[]) | ||
{ | { | ||
Line 68: | Line 84: | ||
KCmdLineArgs::init( argc, argv, &aboutData ); | KCmdLineArgs::init( argc, argv, &aboutData ); | ||
KApplication app; | <!--T:20--> | ||
KApplication app; | |||
FallingBall* mainWindow = new FallingBall(); | FallingBall* mainWindow = new FallingBall(); | ||
mainWindow->show(); | mainWindow->show(); | ||
Line 75: | Line 92: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:21--> | |||
The header files should be self-explanatory. Of special interest is the second part. We create a new application by the name of "app". Then we create a new main window from the type FallingBall. The central things will happen in this class, hence mainWindow. After creation, we show the mainWindow and execute the app, which waits for user interactions, does the repainting, ... | The header files should be self-explanatory. Of special interest is the second part. We create a new application by the name of "app". Then we create a new main window from the type FallingBall. The central things will happen in this class, hence mainWindow. After creation, we show the mainWindow and execute the app, which waits for user interactions, does the repainting, ... | ||
<!--T:22--> | |||
Now lets come to FallingBall.h. The header for the main program. | Now lets come to FallingBall.h. The header for the main program. | ||
<!--T:23--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#ifndef FallingBall_H | #ifndef FallingBall_H | ||
#define FallingBall_H | #define FallingBall_H | ||
<!--T:24--> | |||
#include <KXmlGuiWindow> | #include <KXmlGuiWindow> | ||
#include <QTimer> | #include <QTimer> | ||
#include <KPlotWidget> | #include <KPlotWidget> | ||
<!--T:25--> | |||
class FallingBall : public KXmlGuiWindow | class FallingBall : public KXmlGuiWindow | ||
{ | { | ||
Line 92: | Line 114: | ||
FallingBall(QWidget *parent=0); | FallingBall(QWidget *parent=0); | ||
private: | <!--T:26--> | ||
private: | |||
QWidget *master; | QWidget *master; | ||
KPlotWidget *xyPlot; | KPlotWidget *xyPlot; | ||
}; | }; | ||
<!--T:27--> | |||
#endif // FallingBall_H | #endif // FallingBall_H | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:28--> | |||
This file will be expanded later on. Lets keep it simple for now, such that we can test the current version and are not bugged down in many interrelated bugs. | This file will be expanded later on. Lets keep it simple for now, such that we can test the current version and are not bugged down in many interrelated bugs. | ||
<!--T:29--> | |||
The KXmlGuiWindow allows us fancy application. The Qtimer is required for the motion of the ball and the KPlotWidget shows us the graph of the data. This main window is a child of the KXmlGuiWindow. and has a constructor with a default value of 0, which implies it is the main window. We also add one QWidget, which will allow us to position multiple things on the main window. Also we add already the KPlotWidget, since this widget is debugged and working nicely. | The KXmlGuiWindow allows us fancy application. The Qtimer is required for the motion of the ball and the KPlotWidget shows us the graph of the data. This main window is a child of the KXmlGuiWindow. and has a constructor with a default value of 0, which implies it is the main window. We also add one QWidget, which will allow us to position multiple things on the main window. Also we add already the KPlotWidget, since this widget is debugged and working nicely. | ||
<!--T:30--> | |||
Now lets come to the main window: FallingBall.cpp: | Now lets come to the main window: FallingBall.cpp: | ||
<!--T:31--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#include "FallingBall.h" | #include "FallingBall.h" | ||
#include <QHBoxLayout> | #include <QHBoxLayout> | ||
<!--T:32--> | |||
FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent) | FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent) | ||
{ | { | ||
Line 122: | Line 151: | ||
QTimer *timer = new QTimer(this); | <!--T:33--> | ||
QTimer *timer = new QTimer(this); | |||
timer->start(100); | timer->start(100); | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:34--> | |||
We include the appropriate header and the QHBoxLayout, which allows us to place multiple widgets in the main window. We create a new master QWidget, which will hold the picture of the falling ball and the graph. Then, we create an instance of the KPlotWidget. We define a new layout to place the things on the master. Here we choose horizontal layout but vertical and grid layout exist. Which can be further divided. Therefore, almost endless possibilities. | We include the appropriate header and the QHBoxLayout, which allows us to place multiple widgets in the main window. We create a new master QWidget, which will hold the picture of the falling ball and the graph. Then, we create an instance of the KPlotWidget. We define a new layout to place the things on the master. Here we choose horizontal layout but vertical and grid layout exist. Which can be further divided. Therefore, almost endless possibilities. | ||
<!--T:35--> | |||
We add the xyPlot widget to the layout for now. With only one well tested widget, we can test our code. | We add the xyPlot widget to the layout for now. With only one well tested widget, we can test our code. | ||
<!--T:36--> | |||
Next we assign the layout to the master widget. We can only assign layouts to widgets, even empty once. This main window is not a QWidget, hence we cannot assign a layout to it. | Next we assign the layout to the master widget. We can only assign layouts to widgets, even empty once. This main window is not a QWidget, hence we cannot assign a layout to it. | ||
<!--T:37--> | |||
After the master is setup, we can tell the compiler that this master should be the central widget and setup the GUI, which does some administrative stuff. | After the master is setup, we can tell the compiler that this master should be the central widget and setup the GUI, which does some administrative stuff. | ||
<!--T:38--> | |||
Finally, we define a new timer which will support the animation and we set the refresh rate to 100 milliseconds. | Finally, we define a new timer which will support the animation and we set the refresh rate to 100 milliseconds. | ||
<!--T:39--> | |||
Now we should be able to start the application. | Now we should be able to start the application. | ||
<!--T:40--> | |||
Now lets test this minimal program: | Now lets test this minimal program: | ||
<!--T:41--> | |||
;In KDevelop: | ;In KDevelop: | ||
*Compile with F8 | *Compile with F8 | ||
Line 149: | Line 187: | ||
*F9 | *F9 | ||
<!--T:42--> | |||
;In Editor: <code>cmake . && make && ./FallingBall</code> | ;In Editor: <code>cmake . && make && ./FallingBall</code> | ||
==Adding physics== | ==Adding physics== <!--T:43--> | ||
<!--T:44--> | |||
Now lets create the ball logic, which calculates the position,... . No drawing is done here, that will be done in the ball widget later. Always remember, use small (but meaningful) building blocks. That way you can test them and find problems fast. | Now lets create the ball logic, which calculates the position,... . No drawing is done here, that will be done in the ball widget later. Always remember, use small (but meaningful) building blocks. That way you can test them and find problems fast. | ||
<!--T:45--> | |||
;BallLogic.h | ;BallLogic.h | ||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
Line 160: | Line 201: | ||
#define _BALL_LOGIC_H_ | #define _BALL_LOGIC_H_ | ||
<!--T:46--> | |||
#include <QWidget> | #include <QWidget> | ||
<!--T:47--> | |||
class BallLogic : public QWidget { | class BallLogic : public QWidget { | ||
Q_OBJECT | Q_OBJECT | ||
<!--T:48--> | |||
public: | public: | ||
BallLogic(double dTime=0.1); | BallLogic(double dTime=0.1); | ||
Line 170: | Line 214: | ||
double getTime(); | double getTime(); | ||
<!--T:49--> | |||
private: | private: | ||
double position; | double position; | ||
Line 176: | Line 221: | ||
double time,dTime; | double time,dTime; | ||
<!--T:50--> | |||
public slots: | public slots: | ||
void nextTimeStep(); | void nextTimeStep(); | ||
}; | }; | ||
<!--T:51--> | |||
#endif | #endif | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:52--> | |||
This might seem strange: if we just want to put the logic in here, no drawing, why would we need a QWidget? Answer, the logic includes the next time step, which is a so called slot. We discuss the slots later. Only this much here. Since we want to have a "slot" we require to inherit from QWidget, which has slots. This slot must be public, i.e. we want to access it from outside this class. | This might seem strange: if we just want to put the logic in here, no drawing, why would we need a QWidget? Answer, the logic includes the next time step, which is a so called slot. We discuss the slots later. Only this much here. Since we want to have a "slot" we require to inherit from QWidget, which has slots. This slot must be public, i.e. we want to access it from outside this class. | ||
<!--T:53--> | |||
The Q_OBJECT is a macro, which will setup some default things. | The Q_OBJECT is a macro, which will setup some default things. | ||
<!--T:54--> | |||
The constructor requires a time step in seconds while the getPosition returns the current position. The private variables are self explanatory. | The constructor requires a time step in seconds while the getPosition returns the current position. The private variables are self explanatory. | ||
<!--T:55--> | |||
Now lets go into the ball logic code BallLogic.cpp: | Now lets go into the ball logic code BallLogic.cpp: | ||
<!--T:56--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#include "BallLogic.h" | #include "BallLogic.h" | ||
<!--T:57--> | |||
BallLogic::BallLogic(double dTime) { | BallLogic::BallLogic(double dTime) { | ||
this->dTime = dTime; | this->dTime = dTime; | ||
Line 203: | Line 256: | ||
} | } | ||
<!--T:58--> | |||
double BallLogic::getPosition() { | double BallLogic::getPosition() { | ||
return position; | return position; | ||
} | } | ||
<!--T:59--> | |||
double BallLogic::getTime() { | double BallLogic::getTime() { | ||
return time; | return time; | ||
} | } | ||
<!--T:60--> | |||
void BallLogic::nextTimeStep() { | void BallLogic::nextTimeStep() { | ||
time += dTime; | time += dTime; | ||
Line 219: | Line 275: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:61--> | |||
The constructor sets the time step of this class and defines the acceleration constant, together with some starting conditions: we start at pixel, with zero velocity at time zero. | The constructor sets the time step of this class and defines the acceleration constant, together with some starting conditions: we start at pixel, with zero velocity at time zero. | ||
The getPosition method returns the current position and the next time step does the calculation. If the current position and velocity are negative, the ball is hitting the floor and has to bounce back. (Omitting the velocity condition might result in a strange behavior.) Bouncing back implies a reversal of the velocity. The new velocity and position are calculated according to Newtonian mechanics. Check the corresponding Wikipedia if you like. | The getPosition method returns the current position and the next time step does the calculation. If the current position and velocity are negative, the ball is hitting the floor and has to bounce back. (Omitting the velocity condition might result in a strange behavior.) Bouncing back implies a reversal of the velocity. The new velocity and position are calculated according to Newtonian mechanics. Check the corresponding Wikipedia if you like. | ||
<!--T:62--> | |||
Now lets test it again. Frequent testing is the path to success. First add the new BallLogic.cpp to the CMakeLists.txt! Then, if you use KDevelop "F8" and "F9". Else use make and execute the application. | Now lets test it again. Frequent testing is the path to success. First add the new BallLogic.cpp to the CMakeLists.txt! Then, if you use KDevelop "F8" and "F9". Else use make and execute the application. | ||
==Adding drawing functions== | ==Adding drawing functions== <!--T:63--> | ||
<!--T:64--> | |||
After the logic is done, now it is time to do the drawing. First the header file. | After the logic is done, now it is time to do the drawing. First the header file. | ||
<!--T:65--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#ifndef _BALL_GRAPH_H_ | #ifndef _BALL_GRAPH_H_ | ||
#define _BALL_GRAPH_H_ | #define _BALL_GRAPH_H_ | ||
<!--T:66--> | |||
#include <QWidget> | #include <QWidget> | ||
#include <KPlotWidget> | #include <KPlotWidget> | ||
Line 238: | Line 299: | ||
#include <QtGui> | #include <QtGui> | ||
<!--T:67--> | |||
#include "BallLogic.h" | #include "BallLogic.h" | ||
<!--T:68--> | |||
class BallGraph : public QWidget { | class BallGraph : public QWidget { | ||
Q_OBJECT | Q_OBJECT | ||
<!--T:69--> | |||
public: | public: | ||
BallGraph(BallLogic *logic, KPlotWidget *xyPlot, QWidget *parent = 0); | BallGraph(BallLogic *logic, KPlotWidget *xyPlot, QWidget *parent = 0); | ||
Line 248: | Line 312: | ||
QSize sizeHint() const; | QSize sizeHint() const; | ||
<!--T:70--> | |||
protected: | protected: | ||
BallLogic *logic; | BallLogic *logic; | ||
Line 255: | Line 320: | ||
double radius; | double radius; | ||
<!--T:71--> | |||
public slots: | public slots: | ||
void nextAnimationFrame(); | void nextAnimationFrame(); | ||
}; | }; | ||
<!--T:72--> | |||
#endif | #endif | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:73--> | |||
Our ball drawing widget will inherit from QWidget, which is an feasible background. As such it requires again the Q_OBJECT macro, see before. | Our ball drawing widget will inherit from QWidget, which is an feasible background. As such it requires again the Q_OBJECT macro, see before. | ||
<!--T:74--> | |||
Now we come to a small detail. Our drawing widget needs to have a pointer to the xy-plot widget such that it can post data there. Moreover, the drawing widget requires a pointer to the ball logic, such that it can inquire about the position of the ball at the current time. All three widgets need to talk to each other, therefore a pointer is required which allows for communication, xyPlot. | Now we come to a small detail. Our drawing widget needs to have a pointer to the xy-plot widget such that it can post data there. Moreover, the drawing widget requires a pointer to the ball logic, such that it can inquire about the position of the ball at the current time. All three widgets need to talk to each other, therefore a pointer is required which allows for communication, xyPlot. | ||
<!--T:75--> | |||
To allow for usage of the xy-plot (KPlotWidget) three header files are included. The second defines the data structure, which can be plotted. This data structure is again a pointer called xyData. | To allow for usage of the xy-plot (KPlotWidget) three header files are included. The second defines the data structure, which can be plotted. This data structure is again a pointer called xyData. | ||
<!--T:76--> | |||
The radius defines the radius of the ball, and paintEvent and nextAnimationFrame allow for drawing of the next time frame. The paintEvent, which does the drawing, is called whenever the update() method is called. The nextAnimationFrame only calls all the update methods. (The update method is inherited from QWidget). | The radius defines the radius of the ball, and paintEvent and nextAnimationFrame allow for drawing of the next time frame. The paintEvent, which does the drawing, is called whenever the update() method is called. The nextAnimationFrame only calls all the update methods. (The update method is inherited from QWidget). | ||
<!--T:77--> | |||
minimumSizeHint and sizeHint specify the minimum and suggested size of this widget. Remember, this widget is only the drawing widget on the right hand side. They could be different, but lazy people as me set them equal. | minimumSizeHint and sizeHint specify the minimum and suggested size of this widget. Remember, this widget is only the drawing widget on the right hand side. They could be different, but lazy people as me set them equal. | ||
<!--T:78--> | |||
Now, on to the BallGraph.cpp | Now, on to the BallGraph.cpp | ||
<!--T:79--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#include "BallGraph.h" | #include "BallGraph.h" | ||
<!--T:80--> | |||
BallGraph::BallGraph(BallLogic* logic, KPlotWidget* xyPlot, QWidget* parent): QWidget(parent) { | BallGraph::BallGraph(BallLogic* logic, KPlotWidget* xyPlot, QWidget* parent): QWidget(parent) { | ||
this->logic = logic; | this->logic = logic; | ||
radius = 20; | radius = 20; | ||
setBackgroundRole(QPalette::Base); //Background color: this nice gradient of gray | <!--T:81--> | ||
setBackgroundRole(QPalette::Base); //Background color: this nice gradient of gray | |||
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //allow for expanding of the widget, aka use the minimumSizeHint and sizeHint | setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //allow for expanding of the widget, aka use the minimumSizeHint and sizeHint | ||
// For xy plot using KplotWidget | <!--T:82--> | ||
// For xy plot using KplotWidget | |||
this->xyPlot = xyPlot; //set pointer | this->xyPlot = xyPlot; //set pointer | ||
xyPlot->setMinimumSize( 600, 600 ); //set minimum size in pixel | xyPlot->setMinimumSize( 600, 600 ); //set minimum size in pixel | ||
Line 296: | Line 373: | ||
} | } | ||
<!--T:83--> | |||
QSize BallGraph::minimumSizeHint() const { | QSize BallGraph::minimumSizeHint() const { | ||
return QSize(200, 600); | return QSize(200, 600); | ||
Line 303: | Line 381: | ||
} | } | ||
<!--T:84--> | |||
void BallGraph::nextAnimationFrame() { | void BallGraph::nextAnimationFrame() { | ||
double time=logic->getTime(); | double time=logic->getTime(); | ||
Line 311: | Line 390: | ||
} | } | ||
<!--T:85--> | |||
void BallGraph::paintEvent(QPaintEvent* event) { | void BallGraph::paintEvent(QPaintEvent* event) { | ||
double position=logic->getPosition(); | double position=logic->getPosition(); | ||
Line 323: | Line 403: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:86--> | |||
The constructor connects the pointers of the ball logic and the KplotWidget to the current class and sets the radius. The remainder of the constructor is explained with the comments. | The constructor connects the pointers of the ball logic and the KplotWidget to the current class and sets the radius. The remainder of the constructor is explained with the comments. | ||
<!--T:87--> | |||
The minimumSizeHint and sizeHint were discussed before. | The minimumSizeHint and sizeHint were discussed before. | ||
<!--T:88--> | |||
During each animation time step, the current physical time and ball position is queried from the ball logic class. This data is added to the data stream, which will be plotted in the xy-Plot using KPlotWidget. | During each animation time step, the current physical time and ball position is queried from the ball logic class. This data is added to the data stream, which will be plotted in the xy-Plot using KPlotWidget. | ||
<!--T:89--> | |||
The pointer is used to call the update method. Finally, the update, aka drawing, method of this class is called. | The pointer is used to call the update method. Finally, the update, aka drawing, method of this class is called. | ||
<!--T:90--> | |||
During the drawing in paint event, first the current position of the ball in inquired using the pointer. Then we use a painter, to draw on this ball drawing widget. | During the drawing in paint event, first the current position of the ball in inquired using the pointer. Then we use a painter, to draw on this ball drawing widget. | ||
Clearly, everybody wants to use Antialiasing. | Clearly, everybody wants to use Antialiasing. | ||
<!--T:91--> | |||
Then we draw the ball using a red color and a 4 pixel wide pen. We draw an ellipse with the given boundary box. First the bottom left coordinate of the bounding rectangle is given. Be aware, the computer screens have the zero position at the top left corner, not as most people would expect at the bottom left corner. Therefore, we need to calculate the y-positions by some negative signs. | Then we draw the ball using a red color and a 4 pixel wide pen. We draw an ellipse with the given boundary box. First the bottom left coordinate of the bounding rectangle is given. Be aware, the computer screens have the zero position at the top left corner, not as most people would expect at the bottom left corner. Therefore, we need to calculate the y-positions by some negative signs. | ||
<!--T:92--> | |||
The total window height is 600, drawing the floor requires 25, therefore, 575-position gives the bottom coordinate. The ball has twice the radius diameter. Since the y-coordinates count from the top side, we have to use a minus again. | The total window height is 600, drawing the floor requires 25, therefore, 575-position gives the bottom coordinate. The ball has twice the radius diameter. Since the y-coordinates count from the top side, we have to use a minus again. | ||
<!--T:93--> | |||
Finally we draw the floor in dark gray with a filled rectangle of given dimensions: 180 wide and 20 pixel high while the bottom left corner has the given coordinates. | Finally we draw the floor in dark gray with a filled rectangle of given dimensions: 180 wide and 20 pixel high while the bottom left corner has the given coordinates. | ||
==Assembling== | ==Assembling== <!--T:94--> | ||
<!--T:95--> | |||
Now we need to wire everything together in FallingBall.cpp and FallingBall.h | Now we need to wire everything together in FallingBall.cpp and FallingBall.h | ||
First lets do the header file, which should look like this now: | First lets do the header file, which should look like this now: | ||
<!--T:96--> | |||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
#ifndef FallingBall_H | #ifndef FallingBall_H | ||
#define FallingBall_H | #define FallingBall_H | ||
<!--T:97--> | |||
#include <KXmlGuiWindow> | #include <KXmlGuiWindow> | ||
#include <QTimer> | #include <QTimer> | ||
Line 355: | Line 446: | ||
#include "BallLogic.h" | #include "BallLogic.h" | ||
<!--T:98--> | |||
class FallingBall : public KXmlGuiWindow | class FallingBall : public KXmlGuiWindow | ||
{ | { | ||
Line 360: | Line 452: | ||
FallingBall(QWidget *parent=0); | FallingBall(QWidget *parent=0); | ||
private: | <!--T:99--> | ||
private: | |||
QWidget *master; | QWidget *master; | ||
BallLogic *logic; | BallLogic *logic; | ||
Line 367: | Line 460: | ||
}; | }; | ||
<!--T:100--> | |||
#endif // FallingBall_H | #endif // FallingBall_H | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 372: | Line 466: | ||
<!--T:101--> | |||
Now to the wiring in the FallingBall.cpp: | Now to the wiring in the FallingBall.cpp: | ||
<syntaxhighlight lang="cpp-qt"> | <syntaxhighlight lang="cpp-qt"> | ||
Line 377: | Line 472: | ||
#include <QHBoxLayout> | #include <QHBoxLayout> | ||
<!--T:102--> | |||
FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent) | FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent) | ||
{ | { | ||
Line 391: | Line 487: | ||
QTimer *timer = new QTimer(this); | <!--T:103--> | ||
QTimer *timer = new QTimer(this); | |||
connect(timer, SIGNAL(timeout()), | connect(timer, SIGNAL(timeout()), | ||
logic, SLOT( nextTimeStep() ) ); | logic, SLOT( nextTimeStep() ) ); | ||
Line 401: | Line 498: | ||
Mostly, it is the same as before, now we only define the pointers for the xy-plot and the ball-logic and give those pointers to the constructor of the ball-drawing widget. We add the drawing widget to the layout. The widgets are added from the left to the right: the first goes left, the second goes to the right of that and so on. | Mostly, it is the same as before, now we only define the pointers for the xy-plot and the ball-logic and give those pointers to the constructor of the ball-drawing widget. We add the drawing widget to the layout. The widgets are added from the left to the right: the first goes left, the second goes to the right of that and so on. | ||
<!--T:104--> | |||
Finally, we start the animation with some connect action. First we connect the signal / event of the timer reaching the timeout (after 100ms), to the logic -> next time step. I envision this as a signal comes from a source (timer) and reaches a destination (ball logic) at a given slot. This event triggers the nextTimeStep method defined in the BallLogic class. | Finally, we start the animation with some connect action. First we connect the signal / event of the timer reaching the timeout (after 100ms), to the logic -> next time step. I envision this as a signal comes from a source (timer) and reaches a destination (ball logic) at a given slot. This event triggers the nextTimeStep method defined in the BallLogic class. | ||
<!--T:105--> | |||
Similarly whenever the 100ms are passed, the ballGraph gets a signal to add a new data point to the xy-Data and draw it using the update method of KPlotWidget and then update itself, draw the new ball and floor. | Similarly whenever the 100ms are passed, the ballGraph gets a signal to add a new data point to the xy-Data and draw it using the update method of KPlotWidget and then update itself, draw the new ball and floor. | ||
<!--T:106--> | |||
With the updated CMakeLists.txt: we are done. | With the updated CMakeLists.txt: we are done. | ||
<syntaxhighlight lang="cmake"> | <syntaxhighlight lang="cmake"> | ||
Line 415: | Line 515: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<!--T:107--> | |||
If you made no mistake, you should get a application that looks similar to the one on the top. | If you made no mistake, you should get a application that looks similar to the one on the top. | ||
==Extensions== | ==Extensions== <!--T:108--> | ||
<!--T:109--> | |||
{{Tip|3=Challenge 1|1=Extend the program by plotting the velocity in the xy-graph along with the position.}} | {{Tip|3=Challenge 1|1=Extend the program by plotting the velocity in the xy-graph along with the position.}} | ||
{{Info|3=Challenge 2|1=If you look at the graph it becomes obvious that the bouncing is damped. Why? Where would you have to change things, to remove the damping? One "else" is sufficient.}} | {{Info|3=Challenge 2|1=If you look at the graph it becomes obvious that the bouncing is damped. Why? Where would you have to change things, to remove the damping? One "else" is sufficient.}} | ||
<!--T:110--> | |||
[[Category:Programming]] | [[Category:Programming]] | ||
[[Category:Tutorial]] | [[Category:Tutorial]] | ||
</translate> | </translate> |
Revision as of 20:22, 20 March 2012
Introduction
Often in engineering you want to animate things, and KDE has a great method for doing this. I found KDevelop particular helpful due to the auto-completion. However, this tutorial also gives you the vi/emacs/randomEditor version.
Since the code will become relatively long for a tutorial, the tutorial is split into sections. At the end of each section, the program will produce something.
In this tutorial you will learn how to:
- get two or more widgets in one window
- plot data in an xy-plot
- draw something on a widget
- animate something engineering / physics based. What is easier than a bouncing ball
- use KDevelop if you choose to so (the inside help system and link to the KDE and QT help are great)
Setup
- In KDevelop:
Open CMakeLists.txt by double clicking on it.
- In a Text Editor
- Make directory and create a CMakeLists.txt file, which cmake requires to find dependencies and compile the program.
project (FallingBall)
find_package(KDE4 REQUIRED)
include_directories(${KDE4_INCLUDES})
set(FallingBall_SRCS
main.cpp
FallingBall.cpp
)
kde4_add_executable(FallingBall ${FallingBall_SRCS})
target_link_libraries(FallingBall ${KDE4_KDEUI_LIBS})
The first line gives a name to the project, and the second ensures that the klibs are installed; while the third sets the header files appropriately. The "set" line is the most important. We have to put in all the ".cpp" files that we use in here. For now, just add the main.cpp and the FallingBall.cpp. Others will join later. Finally, define the executable and link all files.
Basic structure
Now lets start with main.cpp:
This is just the starter point of the application, which starts the main window.
Include conventional headers, which allow to create a KDE application, a nice AboutBox and handle command line arguments.
#include <KApplication>
#include <KAboutData>
#include <KCmdLineArgs>
//Include the header of the new main window.
#include "FallingBall.h"
int main (int argc, char *argv[])
{
KAboutData aboutData( "FallingBall", 0,
ki18n("FallingBall"), "1.0",
ki18n("This is some random text"),
KAboutData::License_GPL,
ki18n("Copyright (c) 2012 Your name") );
KCmdLineArgs::init( argc, argv, &aboutData );
KApplication app;
FallingBall* mainWindow = new FallingBall();
mainWindow->show();
return app.exec();
}
The header files should be self-explanatory. Of special interest is the second part. We create a new application by the name of "app". Then we create a new main window from the type FallingBall. The central things will happen in this class, hence mainWindow. After creation, we show the mainWindow and execute the app, which waits for user interactions, does the repainting, ...
Now lets come to FallingBall.h. The header for the main program.
#ifndef FallingBall_H
#define FallingBall_H
#include <KXmlGuiWindow>
#include <QTimer>
#include <KPlotWidget>
class FallingBall : public KXmlGuiWindow
{
public:
FallingBall(QWidget *parent=0);
private:
QWidget *master;
KPlotWidget *xyPlot;
};
#endif // FallingBall_H
This file will be expanded later on. Lets keep it simple for now, such that we can test the current version and are not bugged down in many interrelated bugs.
The KXmlGuiWindow allows us fancy application. The Qtimer is required for the motion of the ball and the KPlotWidget shows us the graph of the data. This main window is a child of the KXmlGuiWindow. and has a constructor with a default value of 0, which implies it is the main window. We also add one QWidget, which will allow us to position multiple things on the main window. Also we add already the KPlotWidget, since this widget is debugged and working nicely.
Now lets come to the main window: FallingBall.cpp:
#include "FallingBall.h"
#include <QHBoxLayout>
FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent)
{
master = new QWidget();
xyPlot = new KPlotWidget();
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(xyPlot);
master->setLayout(layout);
setCentralWidget(master);
setupGUI();
QTimer *timer = new QTimer(this);
timer->start(100);
}
We include the appropriate header and the QHBoxLayout, which allows us to place multiple widgets in the main window. We create a new master QWidget, which will hold the picture of the falling ball and the graph. Then, we create an instance of the KPlotWidget. We define a new layout to place the things on the master. Here we choose horizontal layout but vertical and grid layout exist. Which can be further divided. Therefore, almost endless possibilities.
We add the xyPlot widget to the layout for now. With only one well tested widget, we can test our code.
Next we assign the layout to the master widget. We can only assign layouts to widgets, even empty once. This main window is not a QWidget, hence we cannot assign a layout to it.
After the master is setup, we can tell the compiler that this master should be the central widget and setup the GUI, which does some administrative stuff.
Finally, we define a new timer which will support the animation and we set the refresh rate to 100 milliseconds.
Now we should be able to start the application.
Now lets test this minimal program:
- In KDevelop
- Compile with F8
- setup the execution by Run->Configure Launches. Click on the Name "Falling Ball" and add "+" a launch to it.
- configure the launch by clicking on the Project Target: FallingBall/FallingBall
- and OK. From now on you can just hit ... (If you have multiple open projects, you must switch between different launches by choosing the project under "Run-Current Launch Configuration)
- F9
- In Editor
cmake . && make && ./FallingBall
Adding physics
Now lets create the ball logic, which calculates the position,... . No drawing is done here, that will be done in the ball widget later. Always remember, use small (but meaningful) building blocks. That way you can test them and find problems fast.
- BallLogic.h
#ifndef _BALL_LOGIC_H_
#define _BALL_LOGIC_H_
#include <QWidget>
class BallLogic : public QWidget {
Q_OBJECT
public:
BallLogic(double dTime=0.1);
double getPosition();
double getTime();
private:
double position;
double velocity;
double acceleration;
double time,dTime;
public slots:
void nextTimeStep();
};
#endif
This might seem strange: if we just want to put the logic in here, no drawing, why would we need a QWidget? Answer, the logic includes the next time step, which is a so called slot. We discuss the slots later. Only this much here. Since we want to have a "slot" we require to inherit from QWidget, which has slots. This slot must be public, i.e. we want to access it from outside this class.
The Q_OBJECT is a macro, which will setup some default things.
The constructor requires a time step in seconds while the getPosition returns the current position. The private variables are self explanatory.
Now lets go into the ball logic code BallLogic.cpp:
#include "BallLogic.h"
BallLogic::BallLogic(double dTime) {
this->dTime = dTime;
acceleration = -9.81;
velocity = 0;
position = 590;
time=0;
}
double BallLogic::getPosition() {
return position;
}
double BallLogic::getTime() {
return time;
}
void BallLogic::nextTimeStep() {
time += dTime;
if(position<=0 && velocity<0) velocity=-velocity;
velocity += acceleration*dTime;
position += velocity*dTime+0.5*acceleration*dTime*dTime;
}
The constructor sets the time step of this class and defines the acceleration constant, together with some starting conditions: we start at pixel, with zero velocity at time zero. The getPosition method returns the current position and the next time step does the calculation. If the current position and velocity are negative, the ball is hitting the floor and has to bounce back. (Omitting the velocity condition might result in a strange behavior.) Bouncing back implies a reversal of the velocity. The new velocity and position are calculated according to Newtonian mechanics. Check the corresponding Wikipedia if you like.
Now lets test it again. Frequent testing is the path to success. First add the new BallLogic.cpp to the CMakeLists.txt! Then, if you use KDevelop "F8" and "F9". Else use make and execute the application.
Adding drawing functions
After the logic is done, now it is time to do the drawing. First the header file.
#ifndef _BALL_GRAPH_H_
#define _BALL_GRAPH_H_
#include <QWidget>
#include <KPlotWidget>
#include <KPlotObject>
#include <KPlotAxis>
#include <QtGui>
#include "BallLogic.h"
class BallGraph : public QWidget {
Q_OBJECT
public:
BallGraph(BallLogic *logic, KPlotWidget *xyPlot, QWidget *parent = 0);
QSize minimumSizeHint() const;
QSize sizeHint() const;
protected:
BallLogic *logic;
KPlotWidget *xyPlot;
KPlotObject *xyData;
void paintEvent(QPaintEvent *event);
double radius;
public slots:
void nextAnimationFrame();
};
#endif
Our ball drawing widget will inherit from QWidget, which is an feasible background. As such it requires again the Q_OBJECT macro, see before.
Now we come to a small detail. Our drawing widget needs to have a pointer to the xy-plot widget such that it can post data there. Moreover, the drawing widget requires a pointer to the ball logic, such that it can inquire about the position of the ball at the current time. All three widgets need to talk to each other, therefore a pointer is required which allows for communication, xyPlot.
To allow for usage of the xy-plot (KPlotWidget) three header files are included. The second defines the data structure, which can be plotted. This data structure is again a pointer called xyData.
The radius defines the radius of the ball, and paintEvent and nextAnimationFrame allow for drawing of the next time frame. The paintEvent, which does the drawing, is called whenever the update() method is called. The nextAnimationFrame only calls all the update methods. (The update method is inherited from QWidget).
minimumSizeHint and sizeHint specify the minimum and suggested size of this widget. Remember, this widget is only the drawing widget on the right hand side. They could be different, but lazy people as me set them equal.
Now, on to the BallGraph.cpp
#include "BallGraph.h"
BallGraph::BallGraph(BallLogic* logic, KPlotWidget* xyPlot, QWidget* parent): QWidget(parent) {
this->logic = logic;
radius = 20;
setBackgroundRole(QPalette::Base); //Background color: this nice gradient of gray
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //allow for expanding of the widget, aka use the minimumSizeHint and sizeHint
// For xy plot using KplotWidget
this->xyPlot = xyPlot; //set pointer
xyPlot->setMinimumSize( 600, 600 ); //set minimum size in pixel
xyData = new KPlotObject( Qt::red, KPlotObject::Lines, 2 ); //the data lines are drawn in red with thickness 2
xyPlot->setLimits(0, 100, 0, 600); //the data limits are 0 to 100 in the x-direction and 0 to 600 in the y-direction (initially we start at point 590)
xyPlot->addPlotObject(xyData); //assign the data pointer to the graph. From now on, if the data pointer contains data, it is plotted in the graph
xyPlot->setBackgroundColor( QColor(240, 240, 240) ); //background: light shade of gray
xyPlot->setForegroundColor( Qt::black ); //foreground: black
xyPlot->axis( KPlotWidget::BottomAxis )->setLabel("Time [s]"); //set x-axis labeling
xyPlot->axis( KPlotWidget::LeftAxis )->setLabel("Position [m]"); //set y-axis labeling
}
QSize BallGraph::minimumSizeHint() const {
return QSize(200, 600);
}
QSize BallGraph::sizeHint() const {
return QSize(200, 600);
}
void BallGraph::nextAnimationFrame() {
double time=logic->getTime();
double position=logic->getPosition();
xyData->addPoint(time, position);
xyPlot->update();
update();
}
void BallGraph::paintEvent(QPaintEvent* event) {
double position=logic->getPosition();
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
//draw ball
painter.setPen(QPen(Qt::red, 4));
painter.drawEllipse(95, 575-position, 2*radius, -2*radius);
//draw floor
painter.fillRect( 10, 595, 180, -20 , QColor(40, 40, 40) );
}
The constructor connects the pointers of the ball logic and the KplotWidget to the current class and sets the radius. The remainder of the constructor is explained with the comments.
The minimumSizeHint and sizeHint were discussed before.
During each animation time step, the current physical time and ball position is queried from the ball logic class. This data is added to the data stream, which will be plotted in the xy-Plot using KPlotWidget.
The pointer is used to call the update method. Finally, the update, aka drawing, method of this class is called.
During the drawing in paint event, first the current position of the ball in inquired using the pointer. Then we use a painter, to draw on this ball drawing widget. Clearly, everybody wants to use Antialiasing.
Then we draw the ball using a red color and a 4 pixel wide pen. We draw an ellipse with the given boundary box. First the bottom left coordinate of the bounding rectangle is given. Be aware, the computer screens have the zero position at the top left corner, not as most people would expect at the bottom left corner. Therefore, we need to calculate the y-positions by some negative signs.
The total window height is 600, drawing the floor requires 25, therefore, 575-position gives the bottom coordinate. The ball has twice the radius diameter. Since the y-coordinates count from the top side, we have to use a minus again.
Finally we draw the floor in dark gray with a filled rectangle of given dimensions: 180 wide and 20 pixel high while the bottom left corner has the given coordinates.
Assembling
Now we need to wire everything together in FallingBall.cpp and FallingBall.h First lets do the header file, which should look like this now:
#ifndef FallingBall_H
#define FallingBall_H
#include <KXmlGuiWindow>
#include <QTimer>
#include <KPlotWidget>
#include "BallGraph.h"
#include "BallLogic.h"
class FallingBall : public KXmlGuiWindow
{
public:
FallingBall(QWidget *parent=0);
private:
QWidget *master;
BallLogic *logic;
KPlotWidget *xyPlot;
BallGraph *ballGraph;
};
#endif // FallingBall_H
We include the header files for the logic and the graph and add two pointers for the two widgets in the private section.
Now to the wiring in the FallingBall.cpp:
#include "FallingBall.h"
#include <QHBoxLayout>
FallingBall::FallingBall(QWidget *parent) : KXmlGuiWindow(parent)
{
master = new QWidget();
xyPlot = new KPlotWidget();
logic = new BallLogic();
ballGraph = new BallGraph(logic, xyPlot);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(ballGraph);
layout->addWidget(xyPlot);
master->setLayout(layout);
setCentralWidget(master);
setupGUI();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),
logic, SLOT( nextTimeStep() ) );
connect(timer, SIGNAL(timeout()),
ballGraph, SLOT(nextAnimationFrame()));
timer->start(100);
}
Mostly, it is the same as before, now we only define the pointers for the xy-plot and the ball-logic and give those pointers to the constructor of the ball-drawing widget. We add the drawing widget to the layout. The widgets are added from the left to the right: the first goes left, the second goes to the right of that and so on.
Finally, we start the animation with some connect action. First we connect the signal / event of the timer reaching the timeout (after 100ms), to the logic -> next time step. I envision this as a signal comes from a source (timer) and reaches a destination (ball logic) at a given slot. This event triggers the nextTimeStep method defined in the BallLogic class.
Similarly whenever the 100ms are passed, the ballGraph gets a signal to add a new data point to the xy-Data and draw it using the update method of KPlotWidget and then update itself, draw the new ball and floor.
With the updated CMakeLists.txt: we are done.
set(FallingBall_SRCS
main.cpp
FallingBall.cpp
BallLogic.cpp
BallGraph.cpp
)
If you made no mistake, you should get a application that looks similar to the one on the top.