Things change…

July 29th, 2010 No comments

Again ages since I last wrote on this blog. The reason I'm not writing anymore is on January 2010 I left for a sort of around the world trip.
I'm currently in Bolivia after having been in Brazil, Argentina and Chile.

I'll resume this site the day I'll stop somewhere and start experimenting with technology again, in the meanwhile, if you're interested in my travel stories you can found them at my travel blog

Marco

Categories: Uncategorized Tags:

June 12th, 2009 No comments

Wow. It was ages since the latest update.
Things have changed (and when they don't ?), I was starting to get pretty low on money so I had to look for a job.
I'm working now as a contractor in a nice place close to Marseille doing embedded ui development.

That doesn't mean I'm abandoning the game but just that I'll make a pause. I will restart at some point, maybe with a different game. The time spent working on this game taught me how difficult it is to work alone at a big project. I should have probably chosen something simpler for a start but I was really moving my first steps in this world so I underestimated the effort. I learnt a big deal though so I still consider it a success, this experience will be very valuable once I'll get back again to videogame development !

Categories: Bore the readers Tags:

Game Development Chronicles: Episode #2

February 24th, 2009 No comments

More than a month has passed since the previous update, I was too busy to write an entry in the blog. I can definitely say now that writing a game is hard, but writing it without a correct methodology (and previous experience) is even harder.

I spent lot of time working on tools and frameworks when instead I should had spent more time working on a prototype; just working on a demo made me realize much better what I need to do to reach the end and what tools I need.

I also learnt not to use a physics engine. Why ? Because it's much easier to simulate physics without using a physics engine than simulating "arcadeness" using it. When your characters need an almost real behaviour, don't use a physics engine !
It's easy to decide, there's only one question you have to ask yourself if you are in doubt about using a physics engine or not. The questions is: am I building a simulation ? If your answer is yes, then you better not reinvent the wheel and choose a physics engine. There are several out there but I can comment only on ODE since it's what I used. But if your answer is not then it's probably going to be easier to roll out your own custom physics engine, specialised for your game.

Another important lesson I learned during the latest month was to write the tools using the technologies that I know the most. I'm writing a track editor that I would like to include within the game to allow users to create their own track. I still can't write anything else than basic text and lines using the GUI system offered by the 3D engine I'm using, and this restrain my freedom to explore the best interface to adopt. Although it is true that one day or another I'll have to master this API, at least now I have a working track editor written in PyQT that I have quickly written and that allows to me create track and progress with the game.

But the biggest lesson I've learned is to write prototypes, as soon as possible. For the next months I'm going to stick to a Prototype-Driven-Development methodology. A quick search on Internet didn't reveal a specific definition, but to me it means shaping the final software thanks to the continuous improvement and re-factoring of prototypes. The biggest advantage of using this approach is that it make you realise exactly what your game needs in order to work, and that allows you to shape your framework around your game, always trying to keep it as generic as possible though, if it's a framework you're probably going to reuse it for another game.

I've completed the first prototype last week and I'll complete the next two hopefully in the middle of March, then I'll finally be able to post some screenshots so keep staying tuned!

PyQT playground: image gallery with zoom

January 28th, 2009 2 comments

In this article I'm going to create a small PyQT based application that displays images in a grid and that zoom the image hovered by the mouse.

This is how the final application looks like:

PyQT Image Gallery Screenshot

The first class we need is an ImageGallery, which is a mere QDialog using a QGridLayout.

class ImageGallery(QDialog):
 
    def __init__(self, parent=None):
        super(QDialog, self).__init__(parent)
        self.setWindowTitle("Image Gallery")
        self.setLayout(QGridLayout(self))
 
    def populate(self, pics, size, imagesPerRow=4,
                 flags=Qt.KeepAspectRatioByExpanding):
        row = col = 0
        for pic in pics:
            label = ImageLabel("")
            pixmap = QPixmap(pic)
            pixmap = pixmap.scaled(size, flags)
            label.setPixmap(pixmap)
            self.layout().addWidget(label, row, col)
            col +=1
            if col % imagesPerRow == 0:
                row += 1
                col = 0

The code is very simple, the class has only one public method, populate, which iterates over the images passed in the argument pics, create a QPixmap for each of them, and add them to the layout.

The interesting bit is the line where I create the label:

label = ImageLabel("")

This line creates a new instance of the ImageLabel, which is listed here below:

class ImageLabel(QLabel):
    """ This widget displays an ImagePopup when the mouse enters its region """
    def enterEvent(self, event):
        self.p = ImagePopup(self)
        self.p.show()
        event.accept()

The ImageLabel is a normal QLabel except that I redefined the enterEvent in order to show an ImagePopup when the mouse enters the label.

Finally, the ImagePopup class, responsible for the creation of the zoomed popup image.

class ImagePopup(QLabel):
    """
    The ImagePopup class is a QLabel that displays a popup, zoomed image
    on top of another label.
    """
    def __init__(self, parent):
        super(QLabel, self).__init__(parent)
 
        # set pixmap and size, which is the double of the original pixmap
        thumb = parent.pixmap()
        imageSize = thumb.size()
        imageSize.setWidth(imageSize.width()*2)
        imageSize.setHeight(imageSize.height()*2)
        self.setPixmap(thumb.scaled(imageSize,Qt.KeepAspectRatioByExpanding))
 
        # center the zoomed image on the thumb
        position = self.cursor().pos()
        position.setX(position.x() - thumb.size().width())
        position.setY(position.y() - thumb.size().height())
        self.move(position)
 
        # FramelessWindowHint may not work on some window managers on Linux
        # so I force also the flag X11BypassWindowManagerHint
        self.setWindowFlags(Qt.Popup | Qt.WindowStaysOnTopHint
                            | Qt.FramelessWindowHint
                            | Qt.X11BypassWindowManagerHint)
 
    def leaveEvent(self, event):
        """ When the mouse leave this widget, destroy it. """
        self.destroy()

That's it, it's very simple as you can see. You can download the python code or a zip file containing the code and the images.

Thanks for reading.

Categories: Uncategorized Tags:

Not so easy: updating a Python dictionary

January 23rd, 2009 No comments


Here's a problem that looks very easy but that it took me more time than I thought to solve.

Consider the following function prototype:

def updateDictValue(dictionary, keyPath, newValue)

dictionary is a normal Python dict, keyPath is a string referring to a key inside dictionary and newValue is the new value which should be put at the key correspondent to keyPath.

An example:

dictionary = {"a": {"b": {"c": {"d": 3}}}}
keypath = "a.b.c.d"
newValue = 4

Now write the body of the function so that at the end of the execution dictionary is

{"a": {"b": {"c": {"d": 4}}}}


My not so pretty solution is here:

def updateDictValue(dictionary, keyPath, newValue):
    tokens = keyPath.split(".")
    if len(tokens) > 1:
        prev = dictionary[tokens[0]]
        for token in tokens[1:]:
            if token == tokens[-1]:
                prev[token] = newValue
            else:
                 prev = prev.get(token)
        return dictionary
    else:
        dictionary[keyPath] = newValue
        return dictionary
 


At the beginning I simply thought using eval but you can't assign a value inside the eval expression so that won't work, and even if you could, how do you specify the correct type ? You're limited to the types offered by the string formatting options in Python (%s, %d etc...).

Now that I've posted here I'm sure I'm going to implement it faster next time but I'm curios about other ways of solving this problem. Any ideas ?

Categories: Programming Tags: ,

Game Development Chronicles: Episode #1

January 17th, 2009 No comments

About a month has passed since I started working at my game. I had a couple of interruptions along the way, I've been in Lisbon for almost a month to work on a data visualisation software for the SMOS mission, then I went home for a week at Christmas.

Not to mention two big losses, the hard disk of my beloved 12'' Powerbook failed, and my other laptop, a Fujitsu-Siemens Amilo laptop I bought 6 years ago died. The same day.

Dead...

...

But apart from these distractions I'm working hard at the world editor. There are many challenges I didn't foresee before starting, the most interesting one being the design of the application, particularly the way to decouple the various systems, input , rendering, physics, logic and more.

I've basically rewritten the editor two times and a half. The first time I concentrated on learning the Panda3D and ODE API and implementing some basic functionalities into the editor, like objects picking, camera, input detection and integrating the physic engine. As soon as I was confident enough with the libraries I've rewritten most of the application to follow the architecture described in the fantastic book Game Code Complete. After the rewrite I had more functionalities and 400 lines of code less. Unfortunately it wasn't so easy to get it right, and I struggled even more when I decided to make the application almost entirely data driven. In fact once I had almost finished to redesign I stumbled upon some articles about data-driven game systems and entity systems and I rewrote about a third of the code to follow these approaches.

I didn't build an entity system, but I designed the entities in the game basically as a collection of properties. I found several advantages with this approach, mainly:

  • Very simple class hierarchy, almost flat. I found that this is the biggest advantage. Having struggled in the past with complex hierarchies I'm happy to use this approach now.
  • Serialisation/deserialisation very easy. I just dump the current properties of the in-game objects using the same format I use to load them.
  • Easier modification of the object properties from within the editor. No need to call a different method for each property of the object to modify (setSpeed, setPosition, setMaterial etc...) except the one to actually modify the property.

Not everything is going so well unfortunately. I still have troubles with Panda3D input management when integrating the window within a wx frame; I found the wx library much worse then GTK in terms of API, and debugging is very difficult as most of the times the application just crash without any output message. The advantage over GTK is that it is more cross-platform. As I still haven't written lot of GUI code and considering that QT has just become LGPL, I may consider switching again...

I guess that's all for the first episode, this post is becoming too long, next update in a couple of weeks !

Categories: Game Chronicles Tags:

Indenting XML documents with gEdit

December 6th, 2008 1 comment

gedit is a pretty cool text editor for the GNOME desktop environment.

The problem is that sometimes I found myself using it to edit XML documents but there is no way to pretty print them.

I found yesterday a quick solution to this problem thanks to the External Tools support in gedit and a small utility called xmlindent.

Once you have installed xmlindent click on Tools->External tools, and on the dialog enter the following informations:

External tools dialog

Of course you can customize the options as you wish, the displayed configuration just indents the whole document and replace the unindented one.

To use it just click External Tools -> xmlindent.

Categories: Uncategorized Tags:

Embedding Mplayer in a PyGTK application

February 16th, 2008 5 comments

Recently I wanted to extract the sound track from a MP4 file.
You actually need a single command-line to do that, either using Mplayer or GStreamer.
It's amazing what you can do with GStreamer pipelines, but unfortunately I ran into several problems trying to play H.264 video files with AAC audio (the files are produced by a Sanyo camera and make Totem crash after about few seconds...) so I gave up and I took a look at MPlayer. After all I really didn't need all the GStreamer functionalities.
A single line actually does the job:

mplayer -ao pcm:file=$OUTPUT_FILE $INPUT_FILE

Couldn't be easier.

Nevertheless, I wanted to command the extraction from a GUI as it makes it more user friendly for people that don't deal with shells everyday. Additionally, I didn't want the MPlayer window to popup, I actually wanted to embed Mplayer inside my application.

Again, it turns out that a single line does the job:

mplayer -ao pcm:file=$OUTPUT_FILE -wid $WINDOW_XID

The -wid option tells Mplayer to connect to the window represented by the ID $WINDOW_XID.
This ID is actually the identifier given by the X Server to the window.
We'll see later how to retrieve it.

With this setup, the video is shown in the application, the problem is that there is no indication about the progress. What I wanted was to periodically ask to MPlayer the status of the playback, and displaying it in a progress bar. Checking the MPlayer's man page I discovered that it can be controlled by putting it into a slave mode and by sending him the commands through a named pipe. Bingo !

To start the mplayer in slave mode, I modified the command line to look like this:

mplayer -ao pcm:file=$OUTPUT_FILE -wid $WINDOW_XID -slave -idle \n
-input file=$FIFO

where FIFO is the absolute path of the named pipe where the commands are sent
(for a complete list of commands, type mplayer -input cmdlist).

On the Python side, you have to embed the video in a GtkDrawingArea.
The documentation for this component just says:
The GtkDrawingArea widget is used for creating custom user interface elements.
It's essentially a blank widget; you can draw on widget->window

It is actually everything I need, as the only thing required to do is to get the X ID of the window and pass it to Mplayer. You do it like this:

xid = canvas.window.xid # where canvas is an instance of GtkDrawingArea

We have almost everything required to start Mplayer, the only missing thing is the FIFO.
In Python, you create a FIFO using

os.mkfifo("path_to_fifo")

The full code to start Mplayer in another process would then be:

command = "mplayer -ao pcm:file=%s -wid %i -slave -idle \n
-input file=%s" % (outputFile,xid,fifo)
command = command.split().append("input_video_file.mp4")
subprocess.Popen(command, stdout=logfile, stderr=logfile)

I added the input file after the call to split because if there are whitespaces in the filename or in a parent directory, then the filename would break down in multiple tokens with the call to split.

Now that MPlayer has started, we have to tell him what to do. To do that, we write to the pipe:

mplayerClient = open(FIFO,"w")
mplayerClient.write("play\n") # commands must ends with a newline

(Actually, I still haven't get MPlayer to not start automatically the playback, even if I'm using the -idle option. Please post a comment if you can shed a light on the subject...)

At this point the application is showing the video, but as we said before, we also want to update a progress bar to show the progress, and to do that we've to repeatedly ask the status to Mplayer.

The easiest way to do that, since I was using Gtk, is to use the gobject.timeout_add call, like this:

# call the myUpdateFunction each UPDATE_INTERVAL milliseconds
gobject.timeout_add(UPDATE_INTERVAL, myUpdateFunction)

and myUpdateFunction is defined as:

def myUpdateFunction():
    keepGoing = True
    mplayerClient.write("get_percent_pos\n")
    mplayerClient.flush() # really important, or commands won't be always sent !
    line = logfile.readline()
    if line and line.startswith("ANS_PERCENT_POSITION"):
    # +1 because progress starts from 0, it would end to 99 otherwise
        progress = int(line[line.index('=')+1:-1]) + 1
        progressBar.set_text("%s %%" % progress)
        progressBar.update(progress/100.0)
    else:
        keepGoing = False
 
return keepGoing

That's it, progressBar is a normal GtkProgressBar object and logfile is where I previously redirected Mplayer stdout and stderr.

The above code won't actually works out of the box as there are some corner cases you have to deal with, for example it can happen that the update function is called before MPlayer starts to play the video (which should actually happen with the -idle option, but I couldn't get it to work). In that case line would be an empty string and the playback will immediately stop as myUpdateFunction will return False.

You can find the complete but fairly hackish code here:
AudioExtractor.zip

AudioExtractor

The program also pops up a dialog asking you if you want to burn the file with Serpentine or save it to a different location. I can't guarantee it will work for you as I've been written it mostly as an educational tool.

Categories: Uncategorized Tags: