Monday, 17 February 2014

This blog has moved

This blog has moved to http://blog.noctua-software.com I finally decided to host my blog on my own machine. Please update your bookmark ;)

Tuesday, 2 July 2013

Object Oriented in C

I decided to write this post because a few people were surprised when I told them I make video games in C (and not in C++). What I am told is that since a video game usually requires an object oriented design, using C++ is more suitable to the task. I disagree with this common opinion: writing object oriented code in C is not only possible but, I might even argue, easier than in C++.

Before I enter into the matter, I need to say that I am not against C++. It does indeed have a few interesting features that C does not have. I decide not use C++ in my games because, from my experience, the risk of messing up the code with no way to go back once you realized it outweigh the relatively small convenience you get from it. Yet, some people manage to use C++ in a successful way, and I think that is usually because they enforce strict guideline about what features can be used.

So let's go back to video games. Usually the basic design of a game is to have a common class for all the game objects and then for each type of object (player, enemies, doors, decor, etc.) we create a sub-class. Each sub class reimplements a few methods like "iter", "render". We maintain a list of all the game objects and the engine is responsible for looping over them and calling "iter" and "render".

Of course at first glance C++ seems to be the perfect choice to implement this kind of design. We could have something like:

class Object {
public:
    virtual void iter(float dt);
    virtual void render();
private:
    Vec pos;
    // ...
};

class Player : public Object {
// ....
};

class EnemyA : public Object {
// ....
};

Then we could implement Player::iter to update the player position when we press a key, and EnemyA::iter to move the enemy the way we want it.

(Note that in practice it is not efficient to have such a "render" method, because the nature of modern GPU makes it better to batch the rendering of all the entities of a game, but this is not really important for my argument).

In C, there are several ways of implementing the same design, all making use of function pointers.

Since C++ user are rarely exposed to function pointer, lets quickly remind the somehow awkward syntax to define them:

static void my_func(int x) {printf("hello %d\n", x);}

// Here the variable func_ptr is pointing the the function my_func.
void (*func_ptr)(int x) = my_func;

So here is how we could do Object oriented in C: Each base object we create keep pointers to all the implementations of its methods, we then need to create a special constructor function for each type of objects, equivalent to the C++ constructor:

struct Object {
    void (*iter)(struct Object *this, float dt);
    void (*render)(struct Object *this);
    Vec pos;
};

static void player_iter(struct Object *this, float dt) { ... }
static voif player_render(struct Object *this) { ... }

Object *create_player()
{
    struct Object *ret = calloc(1, sizeof(*ret));
    ret->iter = player_iter;
    ret->render = player_render;
    return ret;
}

Calling a method of an object is simple, we just need to remember to pass the "this" argument as first parameter, since C won't do it for you.

Object *object = create_player();
object->iter(object, dt);

Of course we are wasting a lot of memory by storing those function pointer for each object. If this is an issue, we can use instead a single pointer to a "v-table" struct that we share among objects of the same type. But for the sake of simplicity I prefer to skip this for the moment. Also this structure offers the interesting possibility to dynamically change the methods of an active object. This can be used in game to simulate state changes. Let say your enemy has two possible states: patrolling, and attacking. If we were to use C++ it would be complicated to implement this using the language classes features. Here we could simply change the "iter" pointer of the object at any time during the game to make it behave differently:

void enemy_patrolling(Object *this, float dt)
{
    ...
    if (player_in_sight)
        this->iter = enemy_attacking;
}

void enemy_attacking(Object *this, float dt)
{
    ...
    if (end_attack)
        this->iter = enemy_patrolling;
}

Object *create_enemy()
{
    struct Object *ret = calloc(1, sizeof(*ret));
    ret->iter = enemy_patrolling; // Initial state.
    ...
    return ret;
}

One point I didn't cover is how to create specific attribute to the sub classes. I will talk about this in a next post.

Wednesday, 30 January 2013

Voxel Invaders ported to javascript using emscripten

We just released a javascript version of our game voxel invaders that can run on any browser with webgl support.

Turns out the port was pretty easy, and I didn't have to write a single line of javascript.

So how did we do it? Since our game was written entirely in C, we used emscripten to compile our source code directly to JavaScript. For those who don't know, emscripten is an LLVM backend that generates JavaScript code, so if a project is written in a language that can be compiled by clang, then it is in theory possible to make it run on a browser.

Of course there are a few restrictions, and in our cases we had to make some changes to the code before we could have it running properly on a browser:

  • Emscripten has no support for client side arrays in OpenGL. Even though it has a pretty good support for OpenGL ES2 via webgl, using client side arrays is not supported. This is not really a problem: we just used array buffer everywhere we had client side arrays.

  • Some standard C functions are missing. The one that really hit me was strsep that we used in the levels parsing code. In that case I just modified the code to use strtok_r instead. As a bonus, it turns out the code using strtok_r was actually cleaner than the original one.

  • Sound. When doing a portable game, sound is probably the most complicated part. For the graphics, using Opengl ES2 pretty much works on every possible platforms, but for the sounds, there is still no clear standard library that can be used everywhere. So, as we already had an openAL and an OpenSL ES backends for the desktop and android versions, we created an other sound backend using SDL_mixer for the javascript version. [By the way, I always find it funny that OpenSL ES -that has been done by the same company behind OpenGL- is such a complicated mess compared to OpenAL].

All in all, it wasn't that hard to port the game to JavaScript. The performances are probably not as good as it would have been if we had rewritten the game manually in javascript, but the amount of work done was negligible.

Sunday, 7 October 2012

Video Game in C: using X macros to define game data

As my brother and I recently released our last video game voxel invaders on android and symbian, I though I would share some of the technical details about it. For my the first post I will talk about a quite useful, although rarely used, C trick known as "X macros", and how we can use it to simplify game code.

The code is written in plain C, and the original design was very simple: all the elements of the game are stored in a structure (called obj_t in the code) that looks like that:

struct obj_t { 
    int type;
    float pos[3];
    float speed[3];
    sprite_t *sprite;
    // A lot of other attributes follow...
};

The important attribute of the structure is the first one: int type. This value allows us to differentiate all the kinds of objects in the game (in C++ I would have probably used subclassing instead). We can see it as a pointer to the object class, except that it is not a real pointer but an index on an array of a structure obj_info_t that contains all the information about a type of object (the game equivalent of a C++ class).

file objects.h:

struct obj_info_t {
   const char *sprite_file;
   float initial_speed[3];
   void (*on_hit)();
   // Lot of other attributes...
};

enum {
   PLAYER,
   ENEMY_A,
   ENEMY_B,
   // And so on...
   OBJ_COUNT
};

file objects.c:

obj_info_t obj_infos[] = {
    // PLAYER
    {
        "data/img1.png",  // sprite_file
        {0, 1, 0},        // initial speed
        NULL             // on hit
    },
    // ENEMY_A
    {
        "data/img2.png",  // sprite_file
        {1, 2, 2},        // initial speed
        enemy_a_on_hit    // on hit
    },
    // And so on..
};

By the way, this kind of design was mostly inspired by the code of the original doom game by John Carmack.

The first improvement we can do is to realize that since we are using C98, we can make the array declaration look better using designated initializers:

file objects.c:

obj_info_t obj_infos[] = {
    [PLAYER] = {
        .sprite_file = "data/img1.png",
        .initial_speed = {0, 1, 0},
    },
    [ENEMY_A] = {
        .sprite_file = "data/img2.png",
        .initial_speed = {1, 2, 2},
        .on_hit = enemy_a_on_hit,
    },
    // And so on.
};

See how the code already looks nice and simple. Although this is how our code looked like for a while, at some point we started to get annoyed by a problem with this pattern. The problem is that every time we define a new enemy, we need to modify too files: the file containing the object types enum, and the file containing the object infos array. Beside, since there is no way to separate the array or the enum into several files, those two files got bigger and bigger. This might not seem too bad, but really it is, specially when you have to find the definition of a given object in the thousand of lines of code containing the obj_infos array.

As I mentioned, the original doom engine also used this kind of pattern, and I think the way they overcame this problem was to use a special tool that would automatically generate the C code for both the enum and the array.

In our case I though writing a C generator tool would be overkill. That is where I realized that there is a simple way to have the C preprocessor generates those two parts (enum and global array) for us. Later when I searched for occurrences of this pattern online I found out this is known as "X macros", there is a very comprehensive article about it from Randy Meyers.

The idea behind C macros is to use a C preprocessor macro that, depending on the context, will expand to either the enum part, either the array initializer part.

In our simple case, it would be something like this:

file object_defs.h:

OBJ(PLAYER,
    .sprite_file = "data/img1.png",
    .initial_speed = {0, 1, -},
)

OBJ(ENEMY_A,
    .sprite_file = "data/img2/png",
    .initial_speed = {1, 2, 2},
    .on_hit = enemy_a_on_hit,
)

file object.h:

#define OBJ(name, ...) name,

enum {
    #include "object_defs.h"
}

file objects.c:

#define OBJ(name, ...) [name] = {__VA_ARGS__},

obj_info_t obj_infos[] = {
    #include "object_defs.h"
}

And so, thanks to this trick, we just need to modify the objects_def.h file to add or remove an object type. Both our enum and our global array will be automatically updated by the preprocessor at compile time. As a bonus, this makes it easy to split the object definitions into several files. For that we just need to #include all the needed files instead of just object_defs.h.

Sunday, 23 September 2012

Voxel Invaders : space invader + 3d voxels



This week we (noctua software) released our new video game for android phone: voxel invaders.
This is the sequel of our previous game Retrocosmos, and it follows the same principle (making a fun space invader game for touch screen devices).  Only this time we used 3d voxels (the equivalent of pixels in 3d) for all the graphics.

Voxels based games are starting to appear more and more and are particularly interesting for independent developers because it is much easier to generate a voxel model than a traditional 3d model.

Anyway back to the game:  this has been written almost entirely in C using android ndk, with just a few java code for some of the stuffs the ndk does not allow to do easily (like controlling the device vibrator). I wrote the engine from scratch, using opengl es 2 for the rendering, and some interesting C hacks using macro for the enemies behaviour state machines (maybe I'll do an other post on that an other time).  The good thing about that is that if the game is a success it will be quite easy to port it to other platforms like iOS or symbian.

From a marketing point of view, we did two versions of the game: a free demo and a full paid version.  We have little experience of this kind of approach so I might do a follow up an other time about how much money we made from that.

Here is a video of the gameplay:



Friday, 23 September 2011

Ascii art Tetris game

I was bored so I wrote this little online tetris game in ascii art.

I hope someone will have fun playing it.

Sunday, 10 July 2011

Voxpaint, an opensource 3d voxels painter

This is the first release of a small 3D voxels painter I had been working on recently.

For the moment it cannot do much, but I am planning to use to create some video game graphics.

The code is hosted on launchpad: https://launchpad.net/voxpaint

Check out the videos:




Tuesday, 28 June 2011

Compiling Qt mobility for Simulator on Windows

These days I am working on a Symbian application using Qt 4.7.3 and Qt mobility 1.2.0.

Since the last version of Qt SDK doesn't ship Qt mobility 1.2.0 for the simulator, I had to recompile it myself. Since it took me some time, I write a step by step how to to help people who are trying to do the same thing.

The only real problem is that the SDK for windows doesn't include all the headers files needed to compile the sources. So I copied them from my linux installation of the SDK.
  1. Make sure you have the latest version of Qt SDK. As I write it it is the version 1.1.2, including Qt 4.7.3 and Qt mobility 1.1.3. In my case the SDK is installed into c:\QtSDK.
  2. Get the sources of qt mobility for the simulator from its git repository. Note that it is not the same repository as for Symbian or desktop version.
  3. Two directories are missing in the the simulator source on windows:
    • c:\QtSDK\Simulator\Qt\mingw\include\private
    • c:\QtSDK\Simulator\Qt\mingw\include\QtGui\private
    So what I did is copied those directory from my linux partition where Qt SDK was installed (from the directory ./QtSDK/Simulator/Qt/gcc/include).
  4. In a windows console, set up the PATH to include all the needed tools. You need qmake from the Simulator SDK, perl, and makew32-make:

    set PATH=c:\QtSDK\Simulator\Qt\mingw\bin;%PATH%
    set PATH=c:\QtSDK\mingw\bin;%PATH%
    set PATH=c:\QtSDK\Symbian\tools\perl\bin\;%PATH%

  5. Run configure. In my case I didn't need the messaging module and since it requires dependencies I removed it from the list of modules using the -modules argument of the command:

    configure -modules "bearer contacts gallery location publishsubscribe multimedia systeminfo serviceframework sensors versit organizer feedback connectivity"

  6. Run the make command:

    mingw32-make

  7. Finally install everything:

    mingw32-make install
After this I was able to compile and run applications using qt mobility 1.2.0 on the simulator.

Monday, 2 May 2011

Gedit plugin to emulate emacs alt-q

Here is a small gedit plugin for all the people who are like me on an emacs rehab.

If there is one emacs feature I really miss when using gedit -which is by the way a great text editor- this is the alt-q command (fill-paragraph), that automatically reformats the current paragraph according to the margin width.

Monday, 21 February 2011

from org-mode to zim

In a previous post I shared my enthusiasm with org-mode, the great emacs module for keeping notes and getting things done.

At the time I was using org-mode for pretty much everything : taking notes, keeping my contacts list, monitoring the time spent working on different projects, etc.

But these days, even though I still think org-mode is one of the most powerful notes taking system out there, I don't use it anymore. Now I am using a mix of hamster and zim. Here is the list of reasons that made me switch from org-mode:


1. I don't use emacs anymore.


I am not going to start the old flame war about emacs vs other text editors, but the fact is that org-mode is only useful for people who know how to use emacs. I don't like to use too many different tools, I am already currently using gedit, netbeans and vim. Having to use emacs at the same time confuses me too much.

2. No integration with gnome


This is specially important for time tracking. I need to be able to see at every moment the task I am working on, and be able to change it in a few seconds. With org-mode I had to switch to the workspace where I run emacs, then enter several commands to see the current task and changing it. Very often when working on a task I would forget to start or stop the timers. In contrast, hamster always show very clearly in the gnome bar what I am doing and the time spent on the task. A simple click and I can stop the task and start a new one.

3. Too complicated (but this is related to the point 1)

Not really a problem for people who use emacs all the time, but when I use it only for org-mode, then I spent many time simply learning the commands. Getting Things Done is all about spending time doing things, not learning about how to do things.

4. Zim organization of files is much better for my needs


The most important thing that org-mode (and zim) got right is that all the data should be stored in plain text files that can be read and edited by any text editor. This way I can always access my notes no matter where. Now the problem with org-mode is that if it works very well with one file per project, it doesn't scale well for wiki style notes where you have many small text files linked to each other. Zim on the other hand make it super easy to have as many files as needed. Each file is automatically added into the ~/Notes directory, which is exactly what I want. On the left

So, here is the typical way I use zim and hamster :

Every morning after I turn on my computer (and I am done reading blogs and emails), I click on the hamster notification to start a new task. The timer always remind me of what I am supped to do, and this is a good physiological fence that prevent me from focusing on anything else that
the current task.

I keep a general Zim note for each project I am working on, that mostly look like a TODO file. Before I start to work I can read it and see what are the important things I should do.

If I suddenly have an idea or find a link that would be useful for a task that is not the one I am working on, I open zim (takes half a second) and add the idea/link in the relevant note.

When I find useful general informations, I add then into my personal wiki that is also managed by zim.

Every time hamster reminds me that I have been working for more that one hour on a task, I allow myself to make a pause, and eventually switch task.

At the end of the day I can review the total time I spent working during the day.

In the end my workflow is pretty much the same as before, but the overall experience is much better than it was with org-mode.

Now of course there are some things I wish I could get from zim / hamster

1. Tables
This is the killer feature of org-mode, and to be honest the only reason I still sometime turn on emacs these days. org-mode just make it super easy to edit tables.

2. Calendar integration
I would love to have gnome automatically parsing my notes for entry containing dates and adding them in the calendar. Once again org-mode had it almost right, except that they don't care about gnome or any other desktop. For them the working environment is emacs.

3. Better wiki syntax and text editing
Disclaimer : I am a fan of restructured text, and I wish that every wiki would use its syntax.
Being a programmer, I feel more comfortable working with mono-spaced font, with if possible a way to automatically format the lines to 80 characters. Currently zim don't allow to edit the notes directly in plain text, and I understand it is the better option for most people, but that is one of the cases where I think more choices would be good.

So should you use org-mode or zim / hamster or something else ?

My opinion: If you already use emacs a lot (and if you like it), then go for org-mode, you can do pretty much anything with it and it can be quite enjoyable to use.

If you don't like emacs, and use gnome, then go for zim/hamster. You can get 80/100 of what you get with org-mode, and you won't spend much time learning it.

Tuesday, 8 February 2011

Chatocracy released





Chatocracy is a website that allows people to have one to one conversations on the webcam. After each conversation you can rate the person you have been talking to ; the better ranking you get, the more people you can talk to.

My brother and me have been working on this for the last few weeks. It is still beta so if you encounter problems please report it.

url : http://www.chatocracy.com

Sunday, 28 February 2010

Laoshi release 0.1.0

I announce the first release of laoshi, my Chinese learning application. In this release I include four lessons for beginners. The code and files can be downloaded from the google code page.

Saturday, 20 February 2010

laoshi : A Chinese learning application


I had some free time recently so I created a small application to learn Chinese. The name "laoshi" is the pinyin for "老師" which means "teacher".

For the moment the application features :
  • A dictionary, using the database from cedict containing more than 90,000 entries.
  • A lessons viewer, with automatic dictionary lookup when we pass the mouse over the text.
  • A flash card player.
  • Two lessons that I wrote for beginners.
I wrote everything in python using gtk for the interface, so it should work on every platform. I don't provide any package yet, but people interested can check the code at google code.

Wednesday, 3 February 2010

Writing a resume using reStructuredText

reStructuredText (rst) is a simple markup language perfect for writing documentation. Altough it may not be as powerful as Latex, it is much simpler to use.

I decided to give a try at using rst to create my resume : here is the input file.

Now, thanks to this rst to pdf converter project (written in my favourite language), I can easily generate a nice pdf version of my resume. Here is the resulting pdf.

This approach has many advantages compared to my previous way of doing (using open office). I can easily update the document, change the style, and generate my resume not only in pdf, but also in html or almost any formats I want.

[edit] : as some people pointed out, the input file for my CV needs an extra file for the style. This file can be found here.

Thursday, 19 November 2009

monitor long compilation time

For people who like me like to keep logs of everything they do, this little script can be used to automatically add entries into a log file before and after running a long command.

It fits nicely into my org-mode system, I put the logs entries into an org file and they then appear into my agenda :

=====================================================================
#
!/bin/bash

# Automatically logs the task given as argument into my org log file.
# This is useful when running long compilations.

LOG_FILE=/home/guillaume/Org/Logs.org
CMD=$@

TMP_FILE=$(tempfile)
LABEL=$(pwd)

echo "* start: ($LABEL) $CMD <$(date +'%F %a %R')>" >> $LOG_FILE

STAT_FORMAT="\
- time :: %E
- retun status :: %x
"


trap ctrl_c INT

function ctrl_c() {
echo "* killed: ($LABEL) $CMD <$(date +'%F %a %R')>" >> $LOG_FILE

exit -1
}

/usr/bin/time -o $TMP_FILE -f "$STAT_FORMAT" $CMD

echo "* end: ($LABEL) $CMD <$(date +'%F %a %R')>" >> $LOG_FILE

cat $TMP_FILE >> $LOG_FILE
rm $TMP_FILE
=========================================================================

Friday, 7 August 2009

Check python coding style on the fly with emacs


A nice emacs trick : using flymake-mode and this python code styles PEP8 checker script written by Johann C. Rocholl, we can have automatic real time checking for standard python coding style.

To make this work I copied the script (pep8.py) in my PATH, and then I added this block of code in my .emac file :

(when (load "flymake" t)
(defun flymake-pylint-init ()
(let* ((temp-file (flymake-init-create-temp-buffer-copy
'flymake-create-temp-inplace))
(local-file (file-relative-name
temp-file
(file-name-directory buffer-file-name))))
(list "pep8.py" (list "--repeat" local-file))))

(add-to-list 'flymake-allowed-file-name-masks
'("\\.py\\'" flymake-pylint-init)))

After this I can just enable flymake mode when I edit a python file, and every coding style error will be highlighted on the fly.

Saturday, 13 June 2009

Fluid dynamics engine

After I read this paper I decided to try to write a small two dimensions fluid dynamics engine for video games. It is quite fun.

Now I need to see what I could use it for.

Sunday, 31 May 2009

Tichy 1.1.0 released

Yesterday I released tichy 1.1.0. In this new release a lot of internal refactoring, improvement of the style system, the text editor, the terminal, and the PIM applications. I also added some unit tests using py.tests.

See the release notes.

Tuesday, 5 May 2009

ditaa

Never used it nor planing to do so soon, but I like the idea a lot : ditaa.

Tichy's new style


Today I created a new style for tichy's widgets.

The way we can create widgets style is very simple : we create 32x32 sized png images for each frame. The image is cut so that each 8x8 sized corner will correspond to the associated widget frame corner, the top will be used to fill the top of the widget frame and so on (see the image.)

This is not very flexible because it only allows 8x8 corners size for all the widgets, but here simplicity beats flexibility.

My previous style was done using the gimp. This time I decided to use inkscape instead. Inskape is one of the best open source software I know. Perfect for this kind of job.

I went for a very bright style, so that we can read the phone screen even outside. I also decided to use no gradient or effect at all, this increases the feeling of simplicity that I want to have in Tichy.