come with me, on the way I'll explain.
Posts tagged C
Tiled TMX Map Loader for Pygame
Dec 19th
I’m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It’s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my set of free pixelart tiles.

A map done with Tiled is stored in a file with TMX extension. It’s just a XML file, easy to understand.
As I’m creating a map loader for my owns purposes, the procedure I’m doing here works we need some simplifications. I’m handling orthogonal maps only. I’m not supporting tile properties as well. I also don’t want to handle base64 and zlib encoding in this version, so in the Tiled editor, go at the menu Edit → Preferences and in the Saving tab unmark the options “Use binary encoding” and “Compress Layer Data (gzip)”, like this:

When saving a map it will produce a TMX file like this:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE map SYSTEM "http://mapeditor.org/dtd/1.0/map.dtd"> <map version="1.0" orientation="orthogonal" width="10" height="10" tilewidth="32" tileheight="32"> <properties> <property name="Author" value="Silveira Neto"/> <property name="Year" value="2009"/> </properties> <tileset name="mytiles" firstgid="1" tilewidth="32" tileheight="32"> <image source="free_tileset_version_10.png"/> </tileset> <layer name="grass" width="10" height="10"> <data> <tile gid="261"/> <tile gid="260"/> ... <tile gid="160"/> <tile gid="0"/> </data> </layer> </map>
For processing it on Python I’m using the event oriented SAX approach for XML. So I create a ContentHandler that handles events the start and end of XML elements. In the first element, map, I know enough to create a Pygame surface with the correct size. I’m also storing the map properties so I can use it later for add some logics or effects on the map. After that we create a instance of the Tileset class from where we will get the each tile by an gid number. Each layer has it’s a bunch of gids in the correct order. So it’s enough information to mount and draw a map.
# Author: Silveira Neto # License: GPLv3 import sys, pygame from pygame.locals import * from pygame import Rect from xml import sax class Tileset: def __init__(self, file, tile_width, tile_height): image = pygame.image.load(file).convert_alpha() if not image: print "Error creating new Tileset: file %s not found" % file self.tile_width = tile_width self.tile_height = tile_height self.tiles = [] for line in xrange(image.get_height()/self.tile_height): for column in xrange(image.get_width()/self.tile_width): pos = Rect( column*self.tile_width, line*self.tile_height, self.tile_width, self.tile_height ) self.tiles.append(image.subsurface(pos)) def get_tile(self, gid): return self.tiles[gid] class TMXHandler(sax.ContentHandler): def __init__(self): self.width = 0 self.height = 0 self.tile_width = 0 self.tile_height = 0 self.columns = 0 self.lines = 0 self.properties = {} self.image = None self.tileset = None def startElement(self, name, attrs): # get most general map informations and create a surface if name == 'map': self.columns = int(attrs.get('width', None)) self.lines = int(attrs.get('height', None)) self.tile_width = int(attrs.get('tilewidth', None)) self.tile_height = int(attrs.get('tileheight', None)) self.width = self.columns * self.tile_width self.height = self.lines * self.tile_height self.image = pygame.Surface([self.width, self.height]).convert() # create a tileset elif name=="image": source = attrs.get('source', None) self.tileset = Tileset(source, self.tile_width, self.tile_height) # store additional properties. elif name == 'property': self.properties[attrs.get('name', None)] = attrs.get('value', None) # starting counting elif name == 'layer': self.line = 0 self.column = 0 # get information of each tile and put on the surface using the tileset elif name == 'tile': gid = int(attrs.get('gid', None)) - 1 if gid <0: gid = 0 tile = self.tileset.get_tile(gid) pos = (self.column*self.tile_width, self.line*self.tile_height) self.image.blit(tile, pos) self.column += 1 if(self.column>=self.columns): self.column = 0 self.line += 1 # just for debugging def endDocument(self): print self.width, self.height, self.tile_width, self.tile_height print self.properties print self.image def main(): if(len(sys.argv)!=2): print 'Usage:\n\t{0} filename'.format(sys.argv[0]) sys.exit(2) pygame.init() screen = pygame.display.set_mode((800, 480)) parser = sax.make_parser() tmxhandler = TMXHandler() parser.setContentHandler(tmxhandler) parser.parse(sys.argv[1]) while 1: for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return screen.fill((255,255,255)) screen.blit(tmxhandler.image, (0,0)) pygame.display.flip() pygame.time.delay(1000/60) if __name__ == "__main__": main()
Here is the result for opening a four layers map file:
That’s it. You can get this code and adapt for your game because next versions will be a lot more coupled for my own purposes and not so general.
Download:
maploader.tar.bz2 It’s the Netbeans 6.7 (Python EA 2) project file but that can be opened or used with another IDE or without one. Also contains the village.tmx map and the tileset.
OpenCV: adding two images
Dec 8th
This is a very simple example of how to open two images and display them added.
I got two pictures at project Commons from Wikimedia that were highlighted on Featured Pictures. I did a crop on both to have the same size, as I’m trying to make this example as simple as possible.
The first one is a photo of our Milky Way, taken at Paranal Observatory by Stéphane Guisard.

The second one is a California surfer inside wave, taken by Mila Zinkova.

In this simple OpenCV code below, we open the images, create a new one to display the result and use cvAdd to add them. We do not save the result or handle more than the ordinary case of two images with the same size.
#include <stdio.h> #include <cv.h> #include <highgui.h> int main( int argc, char **argv ){ IplImage *surfer, *milkyway, *result; int key = 0; CvSize size; /* load images, check, get size (both should have the same) */ surfer = cvLoadImage("surfer.jpg", CV_LOAD_IMAGE_COLOR); milkyway = cvLoadImage("milkyway.jpg", CV_LOAD_IMAGE_COLOR); if((!surfer)||(!milkyway)){ printf("Could not open one or more images."); exit -1; } size = cvGetSize(surfer); /* create a empty image, same size, depth and channels of others */ result = cvCreateImage(size, surfer->depth, surfer->nChannels); cvZero(result); /* result = surfer + milkyway (NULL mask)*/ cvAdd(surfer, milkyway, result, NULL); /* create a window, display the result, wait for a key */ cvNamedWindow("example", CV_WINDOW_AUTOSIZE); cvShowImage("example", result); cvWaitKey(0); /* free memory and get out */ cvDestroyWindow("example"); cvReleaseImage(&surfer); cvReleaseImage(&milkyway); cvReleaseImage(&result); return 0; } /* gcc add.c -o add `pkg-config opencv --libs --cflags` */
Compile it (on a well configured OpenCV development environment) and run it:
gcc add.c -o add `pkg-config opencv –libs –cflags`
./add
The result got pretty cool, a milky way surfer.

Simple Face Detection Player
Dec 1st
Here’s a simple video player that also performs facial detection thought the Open Computer Vision Library.
Here’s a code developed using codes from nashruddin.com and samples from OpenCV, including the haar classifier xml. More detailed explanation on the theory about how the OpenCV face detection algorithm works can be found here.
The code:
#include <highgui.h> #include <stdio.h> #include <cv.h> CvHaarClassifierCascade *cascade; CvMemStorage *storage; int main(int argc, char *argv[]) { CvCapture *video = NULL; IplImage *frame = NULL; int delay = 0, key, i=0; char *window_name = "Video"; char *cascadefile = "haarcascade_frontalface_alt.xml"; /* check for video file passed by command line */ if (argc>1) { video = cvCaptureFromFile(argv[1]); } else { printf("Usage: %s VIDEO_FILE\n", argv[0]); return 1; } /* check file was correctly opened */ if (!video) { printf("Unable to open \"%s\"\n", argv[1]); return 1; } /* load the classifier */ cascade = ( CvHaarClassifierCascade* )cvLoad( cascadefile, 0, 0, 0 ); if(!cascade){ printf("Error loading the classifier."); return 1; } /* setup the memory buffer for the face detector */ storage = cvCreateMemStorage( 0 ); if(!storage){ printf("Error creating the memory storage."); return 1; } /* create a video window, auto size */ cvNamedWindow(window_name, CV_WINDOW_AUTOSIZE); /* get a frame. Necessary for use the cvGetCaptureProperty */ frame = cvQueryFrame(video); /* calculate the delay between each frame and display video's FPS */ printf("%2.2f FPS\n", cvGetCaptureProperty(video, CV_CAP_PROP_FPS)); delay = (int) (1000/cvGetCaptureProperty(video, CV_CAP_PROP_FPS)); while (frame) { /* show loaded frame */ cvShowImage(window_name, frame); /* wait delay and check for the quit key */ key = cvWaitKey(delay); if(key=='q') break; /* load and check next frame*/ frame = cvQueryFrame(video); if(!frame) { printf("error loading frame.\n"); return 1; } /* detect faces */ CvSeq *faces = cvHaarDetectObjects( frame, /* image to detect objects in */ cascade, /* haar classifier cascade */ storage, /* resultant sequence of the object candidate rectangles */ 1.1, /* increse window by 10% between the subsequent scans*/ 3, /* 3 neighbors makes up an object */ 0 /* flags CV_HAAR_DO_CANNY_PRUNNING */, cvSize( 40, 40 ) ); /* for each face found, draw a red box */ for( i = 0 ; i < ( faces ? faces->total : 0 ) ; i++ ) { CvRect *r = ( CvRect* )cvGetSeqElem( faces, i ); cvRectangle( frame, cvPoint( r->x, r->y ), cvPoint( r->x + r->width, r->y + r->height ), CV_RGB( 255, 0, 0 ), 1, 8, 0 ); } } }
Yeah, I know the code needs a few adjustments. ¬¬
To compile it in a well configured OpenCV development environment:
gcc faceplayer.c -o faceplayer `pkg-config opencv ‑‑libs ‑‑cflags`
To run it you have to put in the same directory of the binary the XML classifier (haarcascade_frontalface_alt.xml) that comes with OpenCV sources at OpenCV-2.0.0/data/haarcascades/. And so:
./faceplayer video.avi
The results I got so far is that it works well for faces but sometimes its also detects more than faces. And here a video of it working live.
A example of good result:

A example of bad result:

Maybe with some adjustments it could performs even better. But was really easy to create it using OpenCV.
C Gaussian Elimination Implementation
Dec 9th
A simple gaussian elimination implemented in C.
To simplify, I hard coded the linear system
| 10 x1 | + 2 x2 | + 3 x3 | + 4 x4 | = 5 | |
| 6 x1 | + 17 x2 | + 8 x3 | + 9 x4 | = 10 | |
| 11 x1 | + 12 x2 | + 23 x3 | + 14 x4 | = 15 | |
| 16 x1 | + 17 x2 | + 18 x3 | + 29 x4 | = 20 |
into the AB float matrix.
/* * Description: Solve a hard coded linear system by gaussian elimination * Author: Silveira Neto * License: Public Domain */ #include <stdio.h> #include <stdlib.h> #define ROWS 4 #define COLS 5 /** * Linear System, Ax = B * * 10*x1 + 2*x2 + 3*x3 + 4*x4 = 5 * 6*x1 + 17*x2 + 8*x3 + 9*x4 = 10 * 11*x1 + 12*x2 + 23*x3 + 14*x4 = 15 * 16*x1 + 17*x2 + 18*x3 + 29*x4 = 20 */ float AB[ROWS][COLS] = { {10, 2, 3, 4, 5}, { 6, 17, 8, 9, 10}, {11, 12, 23, 14, 15}, {16, 17, 18, 29, 20} }; /* Answer x from Ax=B */ float X[ROWS] = {0,0,0,0}; int main(int argc, char** argv) { int row, col, i; /* gaussian elimination */ for (col=0; col<COLS-1; col++) { for (row=0; row<ROWS; line++){ float pivot = AB[row][col]/AB[col][col]; if(row!=col) { for(i=0; i<COLS; i++) { AB[row][i] = AB[row][i] - pivot * AB[col][i]; } } } } /* X = B/A and show X */ for(row=0; row<ROWS; line++) { X[row] = AB[row][ROWS] / AB[row][row]; printf("%3.5f ", X[row]); } printf("n"); return (EXIT_SUCCESS); }
Before the gaugassian elimination, AB is
10 2 3 4 5 6 17 8 9 10 11 12 23 14 15 16 17 18 29 20
and after it is
10.00000 0.00000 0.00000 0.00000 2.82486 0.00000 15.80000 0.00000 0.00000 3.92768 0.00000 0.00000 15.85443 0.00000 3.85164 0.00000 0.00000 0.00000 14.13174 3.35329
that corresponds to
| 10 x1 | = 2.82486 | ||||
| 15.80000 x2 | = 3.92768 | ||||
| 15.85443 x3 | = 3.85164 | ||||
| 14.13174 x4 | = 3.35329 |
The solution vector is X = (x1, x2, x3, x4). We get it by X=B/A.
The program output, X, is
0.28249 0.24859 0.24294 0.23729
Benchmarking:
I’m this serial implementation over one node of our cluster, a machine with 4 processors (Intel Xeon 1.8 Ghz) and 1Gb RAM memory. I tried random systems from 1000 to 5000 variables and got the average time.

JavaFX, rectangular collision detection
Oct 30th
In a game I wrote some years ago we handled simple rectangular collisions. Given the points:

We did:
// returning 0 means collision int collision(int ax, int ay, int bx, int by, int cx, int cy, int dx, int dy){ return ((ax > dx)||(bx < cx)||(ay > dy)||(by < cy)); }
I’ll show here a little demo about how implement simple rectangular collisions on JavaFX.
First I created a movable rectangle using the same idea of draggable nodes I already had posted before.
import javafx.input.MouseEvent; import javafx.scene.geometry.Rectangle; public class MovableRectangle extends Rectangle { private attribute startX = 0.0; private attribute startY = 0.0; public attribute onMove = function(e:MouseEvent):Void {} override attribute onMousePressed = function(e:MouseEvent):Void { startX = e.getDragX()-translateX; startY = e.getDragY()-translateY; onMove(e); } override attribute onMouseDragged = function(e:MouseEvent):Void { translateX = e.getDragX()-startX; translateY = e.getDragY()-startY; onMove(e); } }
In the main code I some important things:
- colide, a color that represents the collision effect. White means no collision and gray means collision.
- rec1 and rec2, the two rectangles that can collide.
- checkcollision() the function that checks and handles a possible collision.
Here is the main code:
import javafx.application.Frame; import javafx.application.Stage; import javafx.scene.geometry.Rectangle; import javafx.scene.paint.Color; import javafx.input.MouseEvent; var colide = Color.WHITE; function checkcollision():Void { if ( (rec1.getBoundsX() > rec2.getBoundsX() + rec2.getWidth()) or (rec1.getBoundsX() + rec1.getWidth() < rec2.getBoundsX()) or (rec1.getBoundsY() > rec2.getBoundsY() + rec2.getHeight()) or (rec1.getBoundsY() + rec1.getHeight() < rec2.getBoundsY()) ) { colide = Color.WHITE } else { colide = Color.LIGHTGRAY } } var rec1: MovableRectangle = MovableRectangle { x: 10, y: 10, width: 50, height: 60, fill: Color.RED onMove: function(e:MouseEvent):Void { checkcollision() } } var rec2: MovableRectangle = MovableRectangle { x: 100, y: 100, width: 70, height: 30, fill: Color.BLUE onMove: function(MouseEvent):Void { checkcollision() } } Frame { title: "Rectangular Collisions", width: 300, height: 300 closeAction: function() { java.lang.System.exit( 0 ); } visible: true stage: Stage { fill: bind colide content: [rec1, rec2] } }
Try it via Java Web Start:

Some considerations:
- You can use rectangular collisions to create bounding boxes to handle collisions in more complex shapes or sprites. Is a common approach in 2d games to avoid more expensive calculations.
- There are space for optimizations.
- In this case I’m using only two objects. Some problems raises when I have N objects to handle.
More generally, we can code:
function collission(ax, ay, bx, by, cx, cy, dx, dy): Boolean { return not ((ax > dx)or(bx < cx)or(ay > dy)or(by < cy)); } function hitnode(a: Node, b:Node): Boolean{ return (collission( a.getBoundsX(), a.getBoundsY(), a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(), b.getX(), b.getY(), b.getX() + b.getWidth(), b.getY() + b.getHeight() )); }
This way we can pass just two bounding boxes to hitnode and easily check collision of a node against a list of bounding boxes nodes.
Using the same approach I also wrote this function to test if a Node is inside another Node:
function inside (ax, ay, bx, by, cx, cy, dx, dy):Boolean{ return ((ax > cx) and (bx < dx) and (ay > cy) and (by < dy)); } function insidenode(a:Node,b:Node):Boolean{ return (inside( a.getBoundsX(), a.getBoundsY(), a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(), b.getBoundsX(), b.getBoundsY(), b.getBoundsX() + b.getWidth(), b.getBoundsY() + b.getHeight() )); }
Soon I’ll post game examples showing how to use this method and others collission detection methods.
Downloads:
- The original video, javafx_rectangular_collision_detection.ogg
- NetBeans 6.1 Project with sources, javafx_rec_col.tar.gz. Needs JavaFX module installed.













