Application Development with Qt Creator Second Edition

Application Development with Qt Creator Second Edition” is the 3rd book I reviewed for Packt Publishing. Although it’s the second edition, the contents of the book are greatly varied from its predecessor.

First off, it has more chapters compare to the first edition, bringing more contents to the readers especially topics related to Qt Quick. The book also included some pretty fun projects for readers to work on such as media player and simple paint program.

The book also covers some of the fundamental and important topics such as localization, software optimization, and debugging which are needed to develop industry-standard applications.

Let’s take a look at the chapter outline:

Chapter 1
Getting Started with Qt Creator, shows you how to download and install Qt Creator as well as edit simple applications to test your installation.

Chapter 2
Building Applications with Qt Creator, shows you how to compile, run, and debug your application using Qt Creator. You will learn how Qt Creator integrates with both the GNU debugger and the Microsoft console debugger to provide breakpoints, memory inspection, and other debugging help.

Chapter 3
Designing Your Application with Qt Designer, shows you how to use the drag-and-drop GUI designer that is a part of Qt Creator to build both Qt Widget-based applications and Qt Quick applications.

Chapter 4
Qt Foundations, takes you through the foundations of software development using Qt and also covers its support for platform-agnostic application development.

Chapter 5
Developing Applications with Qt Widgets, shows you how to build applications using Qt Widgets that look and act like native desktop applications on the platform of your choice.

Chapter 6
Drawing with Qt, shows the various ways you can move beyond the built-in controls in Qt and make your own drawing on the screen and other drawable entities such as image files in PNG or JPEG.

Chapter 7
Doing More with Qt Quick, expands on what you learned about Qt Quick in the introductory chapters.

Chapter 8
Multimedia and Qt Quick, introduces you to Qt Quick’s support for multimedia, such as audio and video playback as well as how to use a camera if it is connected.

Chapter 9
Sensors and Qt Quick, shows you how to use the various sensors on many of the devices available today using Qt Quick.

Chapter 10
Localizing Your Application with Qt Linguist, shows you how to manage resource strings for different locales, letting you build your application with different languages in different locales.

Chapter 11
Optimizing Performance with Qt Creator, shows you how to use Qt Creator to examine your Qt Quick application’s runtime performance, as well as how to perform the memory profiling of your application with Valgrind, an open source diagnostic tool.

Chapter 12
Developing Mobile Applications with Qt Creator, gives you a glimpse of the exciting arena of mobile software development and shows you how you can use what you’ve learned in this book about Qt and Qt Creator to write applications for platforms such as Google Android.

Chapter 13
Qt Tips and Tricks, is packed with tricks for using Qt and Qt Creator that will help you use the Qt framework and the Qt Creator IDE efficiently.

You can get the book from here.

Call Javascript Functions from C/C++

If you have ever wondered how to control QWebView’s contents using C/C++, it’s actually pretty easy to accomplish using Qt. All you need to do is to write a Javascript function in your HTML page that does whatever that you need, and evaluate the Javascript function from C/C++.

For example, you wrote a Javascript function in your HTML page, like so:






Then, in C/C++ you can simply call:

myWebView->page()->mainFrame()->evaluateJavaScript("MyFunction();");

That’s all! Once you called evaluateJavaScript() function, Qt will handle the rest for you.

If you want to learn how to call C/C++ functions from Javascript, read this.

Call C/C++ Functions from Javascript

It’s possible to call a C/C++ functions from Javascript through web view. At the moment it will only work in Qt Form and doesn’t work well in QML yet. This will probably change in the future versions.

The first thing you need to do is to add your Qt object to the web view as a Javascript object. Then, connect the main frame’s javaScriptWindowObjectCleared() signal to a custom function which adds your Qt object to Javascript:

connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addMyObjectToJavascript()));

This step is very important because you don’t want to lose your object when the page is refreshed. This will ensure that the web view re-adds your object if the page ever gets refreshed.

Next, define the function that gets called when the page is loaded or refreshed:

void MainWindow::addMyObjectToJavascript()
{
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("mainWindow", this);
}

In this example, I added the main window to the web view. You can add anything to the web view as long as it’s a class that inherits from QObject.

Before you start calling your C/C++ function from Javascript, you have to make sure the C/C++ function is set to invokable in your header file:

Q_INVOKABLE void doSomething();

Now, you can call the function from Javascript by simply calling:

mainWindow.doSomething();

It’s all that simple.

You can also call Javascript functions from C/C++. Click here to learn how.

Malaysian Game Educators Summit 2014

Recently, it was a great honor for me to be recommended and invited to the Malaysian Game Educators Summit 2014 as one of the seminar conductors.

The event was carried out at the Knowledge Workers Development Centre (KDC), Cyberjaya on the 4th of December 2014. I was given a 1½ hours session to demonstrate the workflow and capability of Unity Engine.

Among the attendees were lecturers from well-known universities and higher education institutes such as University of Malaya, Sunway University, Multimedia University (MMU), University of Nottingham, Asia Pacific University of Technology & Innovation (APU), Universiti Teknologi MARA (UiTM), and so on and so forth.

One of the challenges I faced during the hands on session was the limited amount of time given versus the vast amount of information that I would like to deliver during the session. I had to compress the information, cut out some of the less important details, and deliver it in a comical and humorous way so that the attendees would feel interested to the subject.

Almost 2 hours later, the training session ended with success, although I wish I had more time to explain some of the more technical questions and had more interactions with the attendees.

I wish I will be given more chances to participate in events like this in the near future. That’s all for now, ciao.

Basic Random Number for Games

Random number is one of the most fundamental and important elements in video game programming. It’s being used in many different aspects such as AI (artificial intelligence), procedural content generation, unit stat, and so on which makes your game less predictable and thus increases the level of replayability of your game.

I first learned to use random numbers in one of my earliest game projects (circa 2006), a simple scissors-paper-stone game made in Macromedia Flash 8 (now known as Adobe Flash):

Random numbers were used for its AI, which basically a set of numbers ranging from 0 to 2, like so:

A random number will be generated at the beginning of each round to determine the AI’s selection and then an animation will be played according to the result. Winning or losing for each round will be determined by comparing the number generated by the AI with the number selected by player.

For example:

Player AI Result
0 (scissors) 1 (paper) Player wins
2 (stone) 0 (scissors) Player wins
1 (paper) 2 (stone) AI wins

This simple logic can be used in most games with minor iterations. Below I have included code snippets for random number generation in several different scripting languages so that you can copy and paste refer to it when needed. All it does is generates a pseudo random number between 0 to 2 with time seed. Happy coding!

C/C++:

#include 
#include 

int main()
{
    srand((unsigned)time(0)); //srand() only needs to call once
    int result;
    result = rand()%3; //this will generate a number between 0 to 2
   return 0;
}

Unity script:

var result : int = Random.Range(0, 2);

Action script:

function randRange(min:Number, max:Number):Number
{
    var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
    return randomNum;
}
var result:Number = randRange(0, 2);

Python:

random.randint(1, 2)

Lastly, please allow me to share with you a comic about random numbers, illustrated by Scott Adams.

OGRE Hello World!

In this tutorial, I will teach you how to create an empty window with OGRE graphics engine and C/C++ language. Unlike any other tutorials that you can find on the internet, this tutorial does not rely on ExampleApplication.h and therefore you will be able to learn OGRE completely from scratch.

At the end of this tutorial, you will be able to create an empty window similar to this:

It’s actually not that complicated to code from scratch, just take a look at the full source code below and you will realize that it’s actually pretty simple to understand even for beginners.

#include 
using namespace Ogre;

int main()
{
    Root *root = new Root("plugins.cfg", "mygame.cfg", "mygame.log");
    root->showConfigDialog();

    root->initialise(true, "My Game");
    RenderWindow *window = root->getAutoCreatedWindow();

    SceneManager *smgr = root->createSceneManager(ST_GENERIC, "SceneManager");

    Camera *cam = smgr->createCamera("MainCamera");

    Viewport *vp = window->addViewport(cam);
    vp->setBackgroundColour(ColourValue(0.3, 0.6, 0.9));

    root->startRendering();

    return 0;
}

Pretty simple isn’t it? I will now explain what the code does part-by-part. First of all, you have to include OGRE’s main header file “Ogre.h” into your project so that you can access its classes and functions for later use:

#include 
using namespace Ogre;

You can also predefine its namespaces (but not a must) to make your code shorter. For example, instead of calling Ogre::Root *root = new Ogre::Root(), we can use Root *root = new Root() instead, which is much shorter and clean.

After that, create a Root class at the beginning of your main function, like so:

Root *root = new Root("plugins.cfg", "mygame.cfg", "mygame.log");

As you can see, Root requires 3 parameters during initialization: the first one being the config file that defines what plugins to load before starting the program; the second parameter is your game’s rendering config file that defines the resolution, aspect ratio, color depth, and so on which will also be loaded before your game is launched; and the last parameter is the name of the log file that will be generated whenever an error happens and it will tell you what problem had occurred.

After that we will be calling:

root->showConfigDialog();

which displays a config dialog before launching your game. The dialog window looks like this:

It lets the players change display settings before the game starts, which is quite handy especially for debugging purposes during development stages.

Next, we will initialize the Root class and define the window title by doing so:

root->initialise(true, "My Game");
RenderWindow *window = root->getAutoCreatedWindow();

We will then call root->getAutoCreatedWindow() to return the newly created render window and stores it to the a pointer called window. Please note that Ogre uses UK English, therefore you should use initialise instead of initialize.

Next, we will create a scene manager that manages your game’s scene graph (i.e. all the 3D objects in your scene) and save it to a pointer called smgr:

SceneManager *smgr = root->createSceneManager(ST_GENERIC, "SceneManager");

There are two parameters for creating a scene manager. The first parameter defines the type of scene graph you’re about to create. There are multiple types of scene managers you can choose from, such as:

  1. ST_GENERIC – Generic scene manager
  2. ST_EXTERIOR_CLOSE – Old terrain scene manager
  3. ST_EXTERIOR_FAR – Nature scene manager
  4. ST_EXTERIOR_REAL_FAR – Paging scene manager
  5. ST_INTERIOR – BSP scene manager

which each of them serves a very different and specific purpose. In this example, we use ST_GENERIC which is the generic type that works well in most cases. The second parameter simply lets you set a name for your scene manager, in this case, we called it “SceneManager”.

Next, we have the code below:

Camera *cam = smgr->createCamera("MainCamera");

Viewport *vp = window->addViewport(cam);
vp->setBackgroundColour(ColourValue(0.3, 0.6, 0.9));

which simply does the following, in ascending order:

  1. Create a camera and call it “MainCamera”.
  2. Ask the rendering window to link the newly created camera to its viewport.
  3. Set a background color for the viewport which will be used to flush the back buffer.

After everything has been setup correctly, we will now render the scene by calling startRendering() which is quite self-explanatory:

root->startRendering();

and viola! You have now successfully created an empty rendering window that runs on OGRE. That’s all for this tutorial, have fun!

Irrlicht Hello World!

In this tutorial, you will learn to write a simple “Hello World!” application to test whether your project has been set up correctly. At the end of this tutorial, you should be able to get this result:

Pretty cool right?

Before we start, let’s download the badass-looking beast model created by Psionic by clicking the image below:

After you’ve downloaded the zip file, extract everything to your project directory. Make sure “beast.b3d” and “beast1.jpg” are both at the same folder as your executable (.exe).

Now, let’s start writing some code!

First of all, you need to include the main Irrlicht header to your script:

#include 

After that, predefine all the irrlicht namespaces, like so:

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

If you don’t add in the codes above, you will need to call the namespaces manually everytime you use its child classes. Without predefining it, you need to call irr::scene::ISceneNode *node instead of ISceneNode *node, for example, which makes your code much longer and harder to read.

After that, define the main function:

int main(){

Note: If you don’t know what is a main function, you probably need to stop reading this tutorial, go ahead and pick up some basic C/C++ knowledge, and come back again after that.

Now, we will create an Irrlicht device and set the window caption by calling:

IrrlichtDevice *device = createDevice(EDT_OPENGL, dimension2d(512,512), 32, false, false, false, 0);
device->setWindowCaption(L"Irrlicht Hello World Tutorial");

Let me explain a bit here. At the first line, we created an IrrlichtDevice pointer and named it as device. Then, we called createDevice() function to ask Irrlicht to create the rendering device based on 7 parameters which we have filled in. The parameters are explained below, in ascending order:

deviceType: Type of device. There are currently 5 options for us to choose from. As you can see, we’ve chosen OpenGL as the rendering device in this example.

  1. OpenGL – EDT_OPENGL
  2. DirectX 8 – EDT_DIRECT3D8
  3. DirectX 9 – EDT_DIRECT3D9
  4. Software – EDT_SOFTWARE
  5. Software 2 – EDT_BURNINGSVIDEO

windowSize: Size of the window. In this example, we set it as 512×512.
bits: Number of bits per pixel when running full screen mode (which will be ignored in windowed mode). It should be either 16 or 32.
fullscreen: Whether or not we enable full screen mode.
stencilbuffer: Specify if we want to use stencil buffer for drawing shadows.
vsync: Enable/disable vsync mode. Only useful when running full screen.
eventReceiver: An object which receives events. We set it as 0 because we are not going to use this parameter in this example.

Then, we will create a video driver, scene manager and GUI environment respectively by calling:

IVideoDriver *driver = device->getVideoDriver();
ISceneManager *smgr = device->getSceneManager();
IGUIEnvironment *guienv = device->getGUIEnvironment();

After that, we display a line of static text on the screen:

guienv->addStaticText(L"Hello World! You are now running Irrlicht Engine!", rect(10,10,200,22), true);

For the code above, we were calling the function addStaticText() which derives from the GUI environment class named guienv. There are 3 parameters for that particular functions: The first parameter is the text that you want to display on the screen. The second parameter is the size and location of the rectangular container where your text will be placed in. See the image below to help you understand more about text container and how you adjust the parameters. The third parameter is to specify whether we want the border line of the container to be shown.

Now, the most exciting part: We will now place the beast model into the scene!

IAnimatedMesh *mesh = smgr->getMesh("beast.b3d");
IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh);

if (node)
{
    node->setMaterialFlag(EMF_LIGHTING, false);
    ITexture *texture = driver->getTexture("beast1.png");
    node->setMaterialTexture(0, texture);
    node->setFrameLoop(1, 25);
    node->setRotation(vector3df(0, 180, 0));
}

At the first line, we loaded the mesh “beast.b3d” which you downloaded at the beginning. Please remember to place the file in the same directory as your executable binary file (.exe). Then, at the second line, we created a scene node, which stores information of your mesh, such as location, scale, attributes, materials, and so on. You can create many different individual node which uses the same mesh.

From the fourth line onwards, it means that if the animated scene node was successfully created, we will then:

  1. Disable lighting affecting the beast.
  2. Load a texture file called “beast1.png” from the directory.
  3. Apply the texture to the beast on the first UV layer. You can apply different textures on different layers, but we don’t need to do that for now.
  4. Load the animation from frame 1 to frame 25, and keep looping it.
  5. Rotate the node by 180 degree along the Y-axis.

After placing the beast, we need a camera to render the scene:

ICameraSceneNode *camera = smgr->addCameraSceneNode(0, vector3df(-100, 100, 150), vector3df(0, 5, 20));

There are 3 parameters used by the camera. The first one is the id number for that particular camera node, the second parameter is the camera location and third parameter is the viewing target of the camera.

Then, we will start running the main loop. Everything will be rendered to the screen at this point including all the objects in the scene and even the user interface.

while(device->run())
{
    driver->beginScene(true, true, SColor(255, 100, 101, 140));
    smgr->drawAll();
    guienv->drawAll();
    driver->endScene();
}
device->drop();
return 0;}

There are 3 parameters in the function beginScene(): The first one is to enable/disable back buffer, second parameter is to enable/disable z-buffer and the third parameter is the color used to clear the screen. Please remember that everything must be drawn between beginScene() and endScene() functions.

You can now build your project and that’s all for this tutorial. For those who are lazy, the whole script is shown below:

#include 

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;

int main()
{
    IrrlichtDevice *device = createDevice(EDT_OPENGL, dimension2d(512,512), 32, false, false, false, 0);
    device->setWindowCaption(L"Irrlicht Hello World Tutorial");

    IVideoDriver *driver = device->getVideoDriver();
    ISceneManager *smgr = device->getScenemanager();
    IGUIEnvironment *guienv = device->getGUIEnvironment();

    guienv->addStaticText(L"Hello World! You are now running Irrlicht Engine!", rect(10,10,200,22), true);

    IAnimatedMesh *mesh = smgr->getMesh("beast.b3d");
    IAnimatedMeshSceneNode *node = smgr->addAnimatedMeshSceneNode(mesh);

    if (node)
    {
        node->setMaterialFlag(EMF_LIGHTING, false);
        ITexture *texture = driver->getTexture("beast1.png");
        node->setFrameLoop(1, 25);
        node->setMaterialTexture(0, texture);
        node->setRotation(vector3df(0, 180, 0));

    }

    ICameraSceneNode *camera = smgr->addCameraSceneNode(0, vector3df(-100, 100, 150), vector3df(0, 5, 20));

    while(device->run())
    {
        driver->beginScene(true, true, SColor(255, 100, 101, 140));
        smgr->drawAll();
        guienv->drawAll();
        driver->endScene();
    }
    device->drop();
    return 0;
}

If an error appears when you’re launching your program, it’s most probably because you didn’t copy the important irrlicht DLL file into your project directory. The DLL file needs to be placed in the same folder as your executable file (.exe).

If you want to remove the ugly console window, open up the project properties window, and change your project from console application to GUI application.

Have fun!

Setting Up Irrlicht Project

In this tutorial, I will guide you step-by-step on how to set up Irrlicht Engine on Code::Blocks so that you can start writing your first 3D game in C/C++ language. Before we start, please make sure that you have installed or downloaded the following programs:

Irrlicht Engine
Code::Blocks with MinGW

Once you have installed Code::Blocks, launch the program and create a new project by calling File->New->Project, like so:

We are not going to use a template for now, so we’ll create an empty project instead:

Now that you have created an empty project, you need to create your first empty source file by going to File->New->Empty file

A window will pop out and ask you whether you want to add the file to your project. Click “Yes” and proceed to save it to your project directory. Make sure that the file type is “C/C++ files”:

Another window will pop out and ask you which target should the file belongs to. In this example, we will tick both options. Occasionally you would want a source file to be included in just a single target but that happens quite rarely.

After that, your file will appear under the “Sources” folder. Double click your source file you just saved (i.e. main.cpp) and it will get launched at the right hand panel.

Now that you have successfully created a working project in Code::Blocks, you need to link your compiler with the Irrlicht Engine so that you can access to its API. In order to do that, go to Project->Build options:

A window will then pop out. Click your project name instead of just “Debug” or “Release” because we are going to adjust the settings that affect both targets. Please do not simply change the project settings unless you know what you are doing. You might not be able to compile your app if you mess the settings up.

In this example, we will change 2 things: the “Linker settings” and “Search directories”. First, go to the “Linker settings” tab and click the “Add” button. A window will pop out and ask you which library file should be included to your project. Normally the library file is located at [irrlicht dir]\lib\Win32-gcc\libIrrlicht.a if you’re running Windows. [irrlicht dir] is the directory where you installed/extracted the Irrlicht Engine.

Now that you have added the library file to your compiler, you will need to link some of the Irrlicht directories to the compiler as well so that it can access to its header files. Click the “Search directories” tab and select the “Add” button under “Compiler” child tab. Add the particular folder which contains all the Irrlicht header files which usually located at [irrlicht dir]\include:

Press the “OK” button and you’re done!