SDL

Stuff I’ve learned #02

Some time has passed, and I’ve learned new stuff again:

  • Updating a single gem is not done with ‘bundle update <gemname>’ but in fact with ‘bundle update –source <gemname>’. See this post for more info on that.
  • Mailbox (iOS) is a really neat mail program. I really love this ‘remind me later’ stuff which keeps my mailbox clean and keeps me from writing these reminders myself in the Calendar app.
  • With CTRL-F2 you can get focus on the menu bar in any mac app. (more keyboard shortcuts here)
  • With JSONLint you can easily verify JSON.
  • In Ruby you can actually create a Hash using brackets with key, value order. Ie like: Hash[“myKey”, “value”, “myOtherKey”, “myOtherValue”]. The [] is a class method.
  • I am really happy that we spent time creating a ‘load dump from environment X into my dev environment’ so we can easily test migrations and fix lots of bugs beforehand (instead of having to solve issues while deploying to an environment).
  • When using ZShell and you want to issue a rake task you cannot pass parameters with [] (ie rake myjob[someparam] won’t work). You need to use single quotes around the jobname + its parameters. Ie: rake ‘myjob[someparam]’ works.
  • You can download free, legal, VM’s to test IE versions on different versions of Windows (here)
  • You can create your own events with SDL using User events., as is done here
  • The Global Day Coderetreat 2013 will be held at the 14th of December and we (at Zilverline) host one!

Thx to Sander for his tips about MailBox and ZShell.

D2TM Rewrite – Development Blog – Drawing stuff on the screen

In the previous post I have set up a raw architecture for the game. There is a Game class that has a function called execute, which allows basic stuff to happen:

- responding to events
– updating state
– and rendering state

In code it is:

while (running) {
	handleEvents();
	update();
	render();
}

The end result of the first phase was, well, a black window. Nothing to be excited about just yet…

One of the very basic needs is drawing on the screen. One way to get something on the screen is by using something called blitting. Blitting is basically taking a picture in memory (called in SDL a surface, or in Allegro a BITMAP) and then copy it onto another surface which functions as the screen.

We already have this screen SDL Surface defined in our Game class. It is not the actual (hardware) screen buffer. But, by doing SDL_Flip we can make this screen visible.

In essense this means the render function will be like this:

void Game::render() {
// draw some stuff on the screen
// flip screen at the end
SDL_Flip(screen); 
}

I want to be able to draw surfaces on the screen. SDL requires the usage of SDL_Rect‘s which allows you to draw pieces of surfaces. At this point I don’t want deal with these SDL_Rect’s directly. What i want is:

  draw (source surface, dest surface, int x, int y);

This is where I introduce a new class (again Single Responsibility Principle) that allows drawing on the screen and providing easy methods to do so. I call this the surfaceDrawer. At this point in time, its class definition looks like this:

#ifndef SURFACEDRAWER_H
#define SURFACEDRAWER_H

#include <SDL/SDL.h>

class SurfaceDrawer {

	public:
		void draw(SDL_Surface * from, SDL_Surface * dest, int x, int y);
		
	
};

#endif

The implementation looks like this:

#include "surfacedrawer.h"


void SurfaceDrawer::draw(SDL_Surface * from, SDL_Surface * dest, int x, int y) {
	if(from == NULL || dest == NULL) {
		return;
	}

	SDL_Rect rect;
	rect.x = x;
	rect.y = y;

	SDL_BlitSurface(from, NULL, dest, &rect);
}

This implementation is easy; the SDL_BlitSurface accepts:
– a from surface
– a from rectangle (ie, what to copy from the from surface?, NULL = everything)
– a destination surface
– a position given by a rect. (where to draw this? Starting with upperleft corner of from surface)

In this case, we provide NULL as 2nd argument, saying we want to copy the entire from surface. Then, the last parameter is the position where to draw it in the form of an SDL_Rect.

Next step is to actually use this function. One thing that we always need in an RTS is to draw the mouse. What we need is an SDL_Surface with a mouse bitmap loaded. I will be using:

Default mouse at 32x32 size, with purple background

Default mouse at 32x32 size, with purple background

Loading this image is done by using SDL_LoadBMP . We need to make sure that the surface we have loaded is in the same bit/color format as our screen. We can do that by using SDL_DisplayFormat. We don’t want to be bothered with this everytime, so we have to make some class responsible for loading resources into SDL_Surface’s which are suitable for drawing by the surfaceDrawer. For that I have introduced a surfaceDao class, which has the following class definition:

#ifndef SURFACEREPO
#define SURFACEREPO

// Data Access Object for fetching SDL Surfaces
#include <SDL/SDL.h>


class SurfaceDao {

	public:
		SDL_Surface * load(char * file);

};

#endif

SDL supports BMP formats out of the box. We need to use the SDL_Image library to get support for other formats. Using a DAO we can move all this format specific stuff out of our game into this single class later. For now I will be using BMP, as the main focus is drawing surfaces.

The implementation of the surfaceDao looks like this:

#include "surfacedao.h"

#include <iostream>

using namespace std;

SDL_Surface * SurfaceDao::load(char * file) {
	SDL_Surface * temp = NULL;
	SDL_Surface * result = NULL;

	if((temp = SDL_LoadBMP(file)) == NULL) {
		cout << "Failed to load [" << file << "]." << endl;
		return NULL;
	}

	result = SDL_DisplayFormat(temp);
	SDL_FreeSurface(temp);

	return result;
}

We load the BMP, when that is succesful, we convert it to the current display format. We have to free the temp surface using SDL_FreeSurface, to prevent memory leaks.

Now, in the Game class, this all comes together, first the class definition is expanded and gets (at the private section) the following code:

#ifndef GAME_H
#define GAME_H

#include <SDL/SDL.h>

#include "surfacedao.h"
#include "surfacedrawer.h"

class Game {

	.. snip ..

	private:
	.. snip ..		
		
		SDL_Surface * mouse;

	// Dependencies
		SurfaceDao surfaceDao;
		SurfaceDrawer surfaceDrawer;

};

#endif

As you can see, I already have prepared the SDL_Surface for the mouse. Now in the Game implementation, loading the mouse is using the surfaceDao:

int Game::init() {
	... snip ...

	// load resources
	mouse = surfaceDao.load("resources/images/MS_Normal.bmp");

	return 0;
}

In the render function I use the surfaceDrawer to draw the mouse at the current X and Y position of the mouse:


void Game::render() {
	int mouseX, mouseY;
	SDL_GetMouseState(&mouseX, &mouseY); 

	surfaceDrawer.draw(mouse, screen, mouseX, mouseY);

	// flip screen at the end
	SDL_Flip(screen); 
}

This all finally results into:

Drawing the mouse! Isn't that cute.

Drawing the mouse! Isn't that cute.

Finally, we have something to draw! yay! But we need to make this a little bit better first:
– remove the system cursor (you don’t see this on the picture, but when running this your system cursor is on top)
– make sure we don’t have a trail of the mouse, ie, clean the screen before drawing
– we also see the purple background of the mouse, we don’t want to draw that…

Lets fix these things:

Hide system cursor

int Game::init() {
	... snip ...
	SDL_ShowCursor(0); 

	// load resources
	... snip ...
}

Clean screen before drawing
Add function to the surfaceDrawer

class SurfaceDrawer {

	public:
		... snip ...
		void clearToColor(SDL_Surface * target, Uint32 color);

And implement this:

void SurfaceDrawer::clearToColor(SDL_Surface * target, Uint32 color) {
	if (target == NULL) return;
	SDL_FillRect (target, NULL, color); 	
}

Don’t draw the purple background
What we want is to skip a certain color when blitting a surface to another surface. We can do this by specifying a color key. This color will be skipped with drawing. The nice thing about the surfaceDrawer is that all have to do is add a function there to do this and change the call in Game to use the new function:

Add function to the surfaceDrawer

class SurfaceDrawer {

	public:
		... snip ...
		void drawTransparant(SDL_Surface * from, SDL_Surface * to, int x, int y);

One thing to note, in D2TM the assumption is that all colors with RGB: 255,0,255 (purple) will be skipped. That is the reason the surfaceDrawer does not have a color parameter. We could add this if it is needed later on.

Implementation:


void SurfaceDrawer::drawTransparant(SDL_Surface * from, SDL_Surface * dest, int x, int y) {
 	Uint32 colorkey = SDL_MapRGB(from->format, 255, 0, 255);
    SDL_SetColorKey(from, SDL_SRCCOLORKEY, colorkey);
    draw(from, dest, x, y);
    SDL_SetColorKey(from, 0, 0); 
}

The first line actually creates the purple color. The code is not that selfdescribing. Later on I will introduce a Colors class that basically says “give me purple”, and does the SDL_MapRGB in its implementation.

Of course, now in the Game we have to make a few adjustments.

void Game::render() {
	surfaceDrawer.clearToColor(screen, Colors::black(screen));

	int mouseX, mouseY;
	SDL_GetMouseState(&mouseX, &mouseY); 

	surfaceDrawer.drawTransparant(mouse, screen, mouseX, mouseY);

	// flip screen at the end
	SDL_Flip(screen); 
}

Two lines are added, first clear the screen to a specific color (black), and then for drawing the mouse we use the new drawTransparant function.

And after compiling, it looks like this:

Drawing a mouse, that leaves no 'trail', and skips the purple color

Drawing a mouse, that leaves no 'trail', and skips the purple color

Next blog post
Although we are able to draw stuff on the screen, it is far from efficient. If we want to draw a terrain we have up to 16 different surfaces for one terrain type (lets say, rocks). It is not doable to hold 16 different SDL_Surface’s and then draw the correct one. Besides, we also have spice, mountains, sand, hills, spicehills. So we need to do something clever. Thats where a tileset comes in. The next blog will be about that.

A side note about including SDL in every header file
One thing you’ll notice about my class definitions, is that I seem to include SDL all the time. Tutorials will say you’ll provide this at the top of your project in your main class (in this case it has to be main.cpp). Although I understand why (since the preprocessor will put the SDL code there, and will be accessible to all other files), it violates the SRP. In fact, you cannot compile a single CPP class anymore using SDL, since you do not refer to this.

As you can see in all my header files, there is a piece:

#ifndef SOMETHING
#define SOMETTHING
 // here is code
#endif

This basically says “whenever I have not yet defined SOMETHING include the piece of code, and define SOMETHING”. This allows us to include the same files over and over again, but we are sure the preprocessor only includes it once. This is needed because else your program will not compile due multiple definitions of the same class.

So now:
– I can compile any CPP file seperately (and, the big plus: I can use that for testing later on! :))
– I know what all my dependencies are, they are not somewhere else hidden

End of side-note

D2TM Rewrite – Development Blog – SDL initialization & initial game setup

In my previous post I have described a way to compile your project with a Maven style like project structure. Using that as basis I am busy rewriting my project Dune II – The Maker. This time I am using SDL.

Because I have started over I thought of writing blog posts about my progress. Blog posts will be about progress made, decisions taken, etc. This is by no means a real tutorial sequence, but you could follow the blog posts probably and make something out of it. Do note: In reality I am much further in development then my blog posts. The blog posts are based upon older revisions than HEAD. If you are interested in the most recent version you can get the source yourself.

In this blog post I will describe how I have started to setup the project. I already have a directory structure as described in my previous blog post.

My goal is to have a primitive architecture set up, I have used the first SDL tutorial as starting point.

The reason I went with a tutorial is that I wanted to be inspired by a different approach than I have done myself in the past. In fact, I have always just tried to do what I thought what was best. In this case I took the tutorial and from there I will change it how I think it should be. Its never bad to take a fresh look at things :)

The very first start was to create a Game class, it has the following class declaration:

#ifndef GAME_H
#define GAME_H

#include <SDL/SDL.h>   /* All SDL App's need this */

class Game {

	public:
		int execute();

	private:
		bool running;

		int init();
		void shutdown();

		void handleEvents();
		void update();
		void render();

		void onEvent(SDL_Event * event);

		SDL_Surface * screen;

};

#endif

The only function that needs to be exposed is the execute method. All other functions are used internally.
The SDL surface screen represents the main display (screen).

The Game class is implemented as follows:

#include "gamerules.h"
#include "game.h"

#include <iostream>

using namespace std;

int Game::init() {
	if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)) {
        	printf("Could not initialize SDL: %s.\n", SDL_GetError());
	        return -1;
	}

	screen = SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE);
	if ( screen == NULL ) {
		printf("Unable to set 640x480 video: %s\n", SDL_GetError());
		return -1;
	}

	return 0;
}

void Game::handleEvents() {
	SDL_Event event;
	while (SDL_PollEvent(&event)) {
		onEvent(&event);
	}
}

void Game::onEvent(SDL_Event * event) {
	if(event->type == SDL_QUIT) {
		running = false;
	}
}

void Game::update() {

}

void Game::render() {

}

void Game::shutdown() {
	SDL_Quit();
}

int Game::execute() {
	if (init() != 0) {
		return -1;
	}

	while (running) {
		handleEvents();
		update();
		render();
	}

	shutdown();

	return 0;
}

The execute function does basically everything. A game loop is in essence very simple. In fact the game is one big loop which does two things:
– update state
– show state

To update state, in this case we have separated two things:
– handle events (in SDL terminology, this means we handle input events. Which can have effect on the game state)
– update (here you actually update the game state)

That still remains updating game state, though a bit more split up. We could later split it into keyboard/mouse states. But, these things all are depended on the certain kind of game state you’re in. A main menu screen should react differently on mouse input than lets say the actual game playing. The current design has not given any direction yet what to do. We could have one big switch statement, but we could also do something better… I’ll come to that in a future blog post.

The init function basically sets up the application. I am not too happy about this in this stage, but for the initial setup it is good enough. I believe the factory pattern should be used for constructing a game object though, so I have already created a class for it. The reason is that i want to respect the Single Responsibility Principle. Constructing a Game object, which requires loading resources, setup SDL, etc, has nothing to do really with the basic Game object itself. In fact, as you will see in later blog posts, the Game object has the only responsibility and that’s calling all the right collaborator classes that make the game what it is.

Since I already know I will be using a factory class I already introduce one which for now does nothing spectacular:

Header:

#ifndef GAMEFACTORY_H
#define GAMEFACTORY_H

#include "game.h"

class GameFactory {

	public:
		Game create();

};

#endif

Implementation:

#include "gamefactory.h"

Game GameFactory::create() {
	Game game;

	// TODO: load resources for game, do SDL initialization, etc.

	return game;
}

Finally the main.cpp which has the entry point of the application:

#include "gamefactory.h"

int main(int argc, char **argv) {
	GameFactory gameFactory;
	Game game = gameFactory.create();
	return game.execute();
}

And thats it! The result is a game that is able to start, it has functions that declare several phases in the game and allows us to expand it further. Because of the factory we can also easily move initialization code out of the Game class.

If you would compile this, and run it, you would see:

A running application

As for developing applications, I believe a certain principle lies behind it. Most of it, you won’t really see. Often, with a few lines of code you can make a lot of stuff happen on the screen. But the actual work is ‘under water':

A (C++) makefile using a maven like directory structure

When you’re used to Java, you build your software using the comforting build-tools. Popular examples are Ant and Maven. Personally I love Maven.

When you’re writing an application in C++ it seems like a big step backwards build-tools wise. If you’re an Ant God you might feel a bit more comfortable with using Make. However, writing makefiles (the ‘equivalent’ of the Ant’s build.xml) are a more tough.

Since I am used to Maven, there are some tasks I want to perform, like:

- clean
– compile
– compile tests
– package

To start with. I have set up a little makefile that does this for me and for those who just want to get started, share the makefile with you. But what will you get? It won’t be exactly like Maven

It took a little while, and I bet it is far from perfect for real C++ developers who eat makefiles for breakfast. But I am happy with it for now.

The directory structure that needs to be in your project is like this (cpp vs mavenized):

CPP 					Mavenized
------------------------------------------
src\main 				src\main\java
src\main\resources 		src\main\resources
src\include\			none
src\test\ 				src\test\java
bin\main 				target\
bin\test 				target\test-classes
lib\ 					src\main\resources

When you run ‘make’ you will be doing all tasks. Meaning you will clean, compile everything (your ‘normal’ code and test code) and then copy any libraries, resources and binaries.

Caveats:
– I am compiling without using the -c flag, this simplifies a lot of stuff for me (it works). But, the larger your project the longer it will take to compile, since it will compile everything all the time. So even though you change one file, everything will be recompiled.
– You need to specify sub-dirs when you use them, when there are no files in those dirs the compilation fails (atleast using G++)

The makefile:

CC=g++
CFLAGS=-Wall

# MAIN properties
SRC=src/main
INCLUDE=src/include
BIN=bin/main
RESOURCES=src/main/resources
LIB=lib

# TEST properties
SRC_TEST=src/test
BIN_TEST=bin/test
RESOURCES_TEST=src/test/resources

all: clean compile compile-test copy-resources copy-libraries

bin: clean compile copy-resources copy-libraries

copy-libraries:
	cp $(LIB)/*.* $(BIN)

copy-resources:
	cp -R $(RESOURCES)/ $(BIN)

compile: clean-main prepare-main
	$(CC) $(SRC)/*.cpp $(SRC)/domain/*.cpp -I$(INCLUDE) -I$(INCLUDE)/domain -o $(BIN)/d2tm -lmingw32 -lSDLmain -lSDL $(CFLAGS)

compile-test: clean-test prepare-test
	$(CC) $(SRC_TEST)/*.cpp -I$(INCLUDE) -o $(BIN_TEST)/tests $(CFLAGS)

clean:	clean-main	clean-test

clean-main:
	rm -rf bin\main

prepare-main:
	mkdir bin\main

clean-test:
	rm -rf bin\test

prepare-test:
	mkdir bin\test

Want to see how it is used in a project? Look here.