My view on game development

Nine-patches and text rendering

I promised I’d post more often and I guess I’m keeping my promise by posting… twice a month!

For the past week-and-a-half I’ve been focusing on the interface of my game. Because I’m targeting such an old platform, I pretty much have to implement everything myself. But that’s okay, because it’s fun! Although I can’t use it directly, I’m using the Gameplay engine as inspiration and also blatantly steal the bits I like.

The reason I’m putting the focus on my interface is because it looks like this:

I can render text and some buttons, but that’s pretty much it. Moving on, I’ll have to put in some more engine work in order to support all the features I want. For example, I want to be able to load my entire interface from a text file and connect the events (button clicked, text entered, etc.) to my game logic. Additionally, I want the ability to specify a margin, border and padding for my controls. This is known as the box model and it comes from HTML. It’s really easy to explain too:

  • Everything element on the screen is put into a box.
  • Boxes are placed together as closely as possible without overlapping.
  • Boxes can be placed inside other boxes.
  • The distance between boxes is known as the margin.
  • The inside of the box is known as the content.
  • The edges around the box is known as the border.
  • The distance between the border and the content is known as the padding

Using these simple rules, you can build pretty much any interface you want!

The next thing on my wishlist was the nine-patch. This is a box with a border in which the corners don’t deform when you stretch the content area.

The most difficult part was figuring out how I was going to store all this information. Ultimately I looked at how gameplay does it and copied that. The result:

Terrible programming art aside, it works! Next up, I attacked the text rendering. It’s a small change, but I can now center the text horizontally and vertically:

I also cleaned up the rendering in general. I am now able to draw text with multiple lines (!) and the code is general enough to fit in the base “Engine” project instead of the Windows Mobile 6-specific renderer. Unfortunately, working for yourself means you have to be tough. So the old text rendering code is still in there, but will be removed “eventually”.

This post has gotten too damn long again. I’m doing so much exciting stuff, I need to talk about it more!

Three months of development

On January the 24th I made the first commit. I had decided to finally build a game on my favorite crazy platform: Windows Mobile 6.1.

Windows Mobile is exactly as the name applies: Windows for your phone. And it programs like that too. You create a window with “CreateWindow”, you can render using GDI, DirectDraw or Direct3D and sound is done using MMSYSTEM or DirectSound. Programming for this platform is a lot like programming for Windows.

However, it is a mobile platform. And it is old. My development device is a HP iPAQ PDA. Remember those? You’d lug them around to keep track of your day-by-day planning and they had wifi so you could check your e-mail. Eventually they would get replaced, first by Blackberries and finally by smartphones in general.

The device has, I estimate, a 300 MHz processor and 64 MB of RAM. It has a 240 x 320 pixel screen without multi-touch. You need to use a supplied pen to get it to actually register a click. And although it doesn’t sound like a beast of a machine, it’s enough to run Age of Empires II and a crappy version of Call of Duty.

So why pick this platform? Because it’s a challenge. I’ve been meaning to make something for it ever since I first got it. I have the skills, all I need now is persistence. Every day, before work, I launch Visual Studio and try to get something done. Last week I worked on level loading. I was using a hardcoded level definition that just didn’t cut it anymore. So I turned to my favorite serialization library: Protobuf.

It was a bit of a pain to setup, but it works! I can use protobuf-lite on Windows Mobile!

So naturally, after finishing the level loader, I converted my font loading to Protobuf too. And my sprites as well…

I got a bit carried away is all I’m sayin’.

My plan is to keep you posted by posting small updates every few days. I have a tendency to write gargantuan blog posts and those take a loooooong time to write. So by keeping it short I hope to increase frequency in posting. ;)

Serialization using Protobuf

For the past few months I’ve been working on a game I’d like to call “Alpha One”, but is still called “Duck Hunt” for now.

Exciting top-down action! Programmer graphics! Unfinished gameplay!

I’ve been working on it in the train, with a mindset of: just get it done. I’m not really bothering with architecture all that much, I just want a working prototype. And that mindset is necessary, because every day I only get an hour and a half, split in two, to work on it.

For the past month I’ve been working on storing the game state to disk. This due to the advice of @ivanassen, who worked on Tropico 4 (and a whole slew of other games). His advice was to start working on the subsystem that stores the game state to disk as soon as possible, because it touches everything.  If you like casino games is important that you look the best Bonuses to make easier for you win money.

What I’ve found is that he’s absolutely right.

So, what do I need to store to disk for Alpha One?

  • Background – My background is divided into layers, each layer containing items. These are static and won’t change throughout the game.
  • Camera’s – Right now I have only two camera’s: one for the game and one for the editor. But I would like to store their position and orientation in the game save as I might add more camera’s later.
  • Lights – I don’t have any right now, but I definitely will in the future.
  • Objects – Everything that’s moving and interacting. Right now I have only three classes: Player, Enemy and Bullet. And even that has proven to be a headache.

XML is terrible for a lot of things, this is one of them

My first idea for storing the game state was to simply write it to XML. This was before I really researched serialization in games. This is what that looked like:

<Level name="Generated">
        <Layer level="0">
            <Item name="Back">
                <Pivot>0.500000 0.500000</Pivot>
                <Position>0.000000 0.000000</Position>
        <Object type="Player" id="0" owner="-1">
            <Position>320.000000 240.000000</Position>
            <Velocity>0.000000 0.000000</Velocity>
        <Object type="Enemy" id="1" owner="-1">
            <Position>552.673096 360.225830</Position>
            <Velocity>0.000000 0.000000</Velocity>

The signal-to-noise ratio here is okay. It’s a lot of fluff around your actual data, but not very troublesome to actually parse. However, this is how I saved my BackgroundItem class to the file:

	bool BackgroundItem::Save(tinyxml2::XMLElement* a_Element)
		tinyxml2::XMLDocument* doc = a_Element->GetDocument();

		tb::String temp(1024);

		tinyxml2::XMLElement* ele_item = doc->NewElement("Item");
		ele_item->SetAttribute("name", m_Name.GetData());

		if (m_Sprite)
			tinyxml2::XMLElement* ele_item_sprite = doc->NewElement("Sprite");

			tinyxml2::XMLElement* ele_item_pivot = doc->NewElement("Pivot");
			temp.Format("%f %f", m_Pivot.x, m_Pivot.y);

		tinyxml2::XMLElement* ele_item_position = doc->NewElement("Position");
		temp.Format("%f %f", m_Position.x, m_Position.y);

		tinyxml2::XMLElement* ele_item_rotation = doc->NewElement("Rotation");
		temp.Format("%f", m_Rotation);

		tinyxml2::XMLElement* ele_item_scale = doc->NewElement("Scale");
		temp.Format("%f", m_Scale);


		return true;

It looks bad, it feels bad and it’s very cumbersome to add new variables to this definition. What doesn’t help is that everything uses strings, so I first have to convert my floats to a string before I can store them.

I was also starting to worry about security and performance. TinyXml2 is blazing fast, but my levels would grow in size very quickly. On top of that, storing your game state as plaintext is a bad idea. It’s practically begging to be messed with. However, I didn’t really look too much into these problems, my main concern was just getting it to store my game state to a file.

What I noticed, however, was that every time I made a relatively minor change to my XML, like putting the Object’s id in an attribute instead of a child node, I would have to change massive amounts of code. It was bothering me, but not enough to actually do something about it. But then I wanted to change my Camera’s position from a Vec3 (one value) to a JuicyVar>Vec3< (three values). And that was such a nightmare that I finally set down to research serialization.

So that’s how you serialize your data…

What I found was magnificent. Google has an open source project called Protocol Buffers (Protobuf for short) that they use internally for all their projects.

The basics come down to this: instead of describing what your data is, why not describe what your data looks like?

Alright, an example. This would be a position stored in XML:

<Position>0.0 100.0 -10.0</Position>

Now, this is what it looks like using a Protobuf definition:

position {
	x: 0.0
	y: 100.0
	z: -10.0

This looks much cleaner in my opinion. It only specifies the name of the field once and it labels the values.

This would be the code to parse the XML version:

tinyxml2::XMLElement* ele_pos = a_Element->FirstChildElement("Position");
if (ele_pos)
	sscanf(ele_pos->GetText(), "%f %f %f", &m_Position.x, &m_Position.y, &m_Position.z);

While this would be the code to parse the protobuf version:

if (a_Element.has_position())
	m_Position.x = a_Element.position().x();
	m_Position.y = a_Element.position().y();
	m_Position.z = a_Element.position().z();

That’s quite a difference! But how does it work?

The secret is in the sauce

Like I said, a .proto file is nothing but a definition of what your data looks like. Here would be the definition for the above data:

package PbGame;

message Vec3
	required float x = 1;
	required float y = 2;
	required float z = 3;

message Object
	optional Vec3 position = 1;

This .proto file is fed to protoc.exe, which converts the file to a header (.pb.h) and implementation ( Now you can include those generated files in your project and use them to parse the data.

Let’s shake our definition up a bit. I don’t want a static position, but a juicy one, which wiggles and wobbles to the target position over time. We’ll need a Vec3 as data, a Vec3 as target and a blend factor. First we’ll add a new message:

message JuicyVec3
	required Vec3 data = 1;
	required Vec3 target = 2;
	required float blend = 3;

Then we change the Object message:

message Object
	optional JuicyVec3 position = 1;

What does our parsing code look like now?

if (a_Object.has_position())
	tb::Vec3 data;
	tb::Vec3 target;
	float blend;
	data.x = a_Element.position().data().x();
	data.y = a_Element.position().data().y();
	data.z = a_Element.position().data().z();
	target.x = a_Element.position().target().x();
	target.y = a_Element.position().target().y();
	target.z = a_Element.position().target().z();
	blend = a_Element.position().blend();

Still looks pretty nice. Now let’s look in the XML corner:

tinyxml2::XMLElement* ele_pos = a_Object->FirstChildElement("Position");
if (ele_pos)
	tb::Vec3 data;
	tb::Vec3 target;
	float blend;

	sscanf(ele_pos->FirstChildElement("Data")->GetText(), "%f %f %f", &data.x, &data.y, &data.z);
	sscanf(ele_pos->FirstChildElement("Target")->GetText(), "%f %f %f", &target.x, &target.y, &target.z);
	sscanf(ele_pos->FirstChildElement("Blend")->GetText(), "%f", &blend);

Yeah… it eh… didn’t get better.

The main problem with XML is that it’s extremely brittle. If your data doesn’t match up with your definition, you’re pretty much screwed. You have to add a lot of checks to make sure that doesn’t happen. Checks I haven’t even added here.

With protobuffers, a lot of these common annoyances are smoothed away. If you use mutable_target() instead of target(), you are guaranteed to get a pointer to a PbGame::Vec3, even if the message doesn’t have one right now.

Another advantage is that protobuffers can be saved to and loaded from a binary file. That means that you have a text version of your data where you can make changes in and a binary version that you ship with, for speed and safety. This also means that they’re extremely useful for packing data to send over an internet connection. You don’t have to keep a record of what each byte stood for because that’s already in your .proto file!


I really, really like protobuffers. They took a while to get used to, but once they click, I suddenly had a shiny new hammer and everything starts to look like a nail. Now I just need to figure out what the downsides are. Also with my experience in games I recommend that if you like casino games, learn how to know if you can trust a no deposit online casino, to make your experience much better.

Friends don’t let friends generate icosahedrons

A while ago, I did a retake for a course on procedural programming. One of the assignments was to generate a textured sphere. You would be marked on getting the texturing right, but I got distracted and decided to try making an icosahedron instead. However, I also made a version that used a more traditional subdivision method: generate circles on a cylinder, and have the radius of the circles depend on the cosine of the distance on the cylinder’s height. Here are my spheres:

Looks pretty round right? However, let’s take a look at their wireframes:

Click on the image for a larger version.

From the thumbnail, the second version looks unchanged. But when you click on it, you’ll notice that the lines are so dense that it looks textured!

What’s the difference?

The sphere on the left (sphere 1) uses the traditional method of sphere generation. It has 31 subdivisions on the y-axis and 31 subdivisions on the z-axis of the half-sphere. This half-sphere is then mirrored to the bottom. It has a total of 3,844 faces.

In pseudocode:

for (y = 0; y < subdivisions_y; y++)
	y = cos(degrees_y) * radius_sphere;
	radius_y = sin(degrees_y) * radius_sphere;
	for (z = 0; z < subdivisions_z; x++)
		x = cos(degrees_z) * radius_y;
		z = sin(degrees_z) * radius_y

The sphere on the right (sphere 2) uses an icosahedron subdivision algorithm to generate a sphere. It has a recursive depth of 5 and generates 109,200 faces.

In pseudocode:

// first, generate the 20 triangles of an icosahedron
// then subdivide them:

triangle_curr = triangle_first;
for (int i = 0; i < 20; i++)
	subdivide_triangle(curr, recursive_depth);
	triangle_curr = triangle_next;

The icosahedron is an almost perfect sphere, but it comes at a high price. It uses a lot more faces to achieve the same effect.

But okay, that’s not really fair. Let’s scale down the quality considerably:

Sphere 1 uses 5 subdivisions on the y-axis and 5 subdivisions on the z-axis, for a total of 100 faces.

Sphere 2 uses 0 recursive subdivisions, for a total of 100 faces.

They use the same amount of faces, but in my opinion, the sphere on the left looks better. It looks less lumpy and a lot more round. Let’s take a look at the amount of faces per quality level.


  • Level 0 – 100 faces
  • Level 1 – 420 faces
  • Level 2 – 1,700 faces
  • Level 3 – 6,820 faces
  • Level 4 – 27,300 faces
  • Level 5 – 109,220 faces

Subdivided sphere:

  • YZ: 5 – 100 faces
  • YZ: 10 – 400 faces
  • YZ: 15 – 900 faces
  • YZ: 20 – 1,600 faces
  • YZ: 25 – 2,500 faces
  • YZ: 30 – 3,600 faces

It’s easy to see that the subdivided sphere gives you a lot more bang for your buck. The 30-subdivisions version is comparably in quality to the 5-level recursive icosahedron, but it uses only 3.2% of the faces!

Texturing problems

The truth is: you don’t *need* the precision an icosahedron will give you. Because they both hide a much harder problem: texturing a 2D plane on a 3D sphere. Here’s what the top looks like:

On the top-left, you can see the texture being used. Coincidentally, it’s also being generated procedurally. (Hey, it was a course on procedural generation, right?) It looks terrible, but this is as good as it’s going to get. I got top marks for my texture mapping, because most people don’t even get it this right.

Why is it such a problem to map a texture to a sphere? Well, xkcd explains it better than I can:

Image taken from

The way I solved it is by generating polar coordinates from normalized coordinates on the sphere to get the texture u and v. I won’t go into too much detail, because I don’t want to ruin the course material. But I do have a fix for the dateline issue, which took a very long time to figure out. When the texture goes around the sphere, you get to a face that has to wrap around from 1.0 to 0.0. If you don’t fix that, you will get an ugly band.

void ModelSphere::FixDateLine(tb::Vec2& a_Left, tb::Vec2& a_Right)
	float tt = 0.75f;
	float nn = 1.f - tt;

	if (tb::Math::Abs(a_Left.x - a_Right.x) > tt) 
		if (a_Left.x < nn) { a_Left.x += 1.f; }
		if (a_Right.x < nn) { a_Right.x += 1.f; }

It’s not a lot of code, but it isn’t explained properly anywhere else. The same code is used for both the icosahedron and the subdivided sphere, in case you were wondering.


Consider using cosine and sine to generate a sphere. It generates a lot less faces for the same amount of detail. For most games it will be “good enough”. Unless you’re generating planets that really, really need to be round all over its surface, you can get away with a subdivided sphere quite easily. Casino games have been getting very appear everywhere even in movies check this movies you forgot had a casino scene.

PostApocalypse DevDiary 2: Of Saves and Trading

This is part 2 of an on-going series. Start here if you don’t know what’s going on.

Hello readers!

Last week I spent most of my time working on a school assignment, but I still managed to find some time to cram in some new features into this fancy indie game I’m making.

But most of all, I spent time playing one of my favorite indie games of all time: Mount & Blade: Warband. So I want to start this blogpost with a critique of that game, as well I started with sport betting, I just checked the info of the professional  from Fantasy Punter, and I decided to be part of this.

What’s so bad about MB:W?

When looking for comments about it online, you’ll find a lot of people talking about the first person combat, and not a helluva lot of talk about the third-person world overview. Even though you’ll be spending close to 70% of your time in it!

The way it works is that you get an iconic representation of your party: a horse with a dude on it with a number representing its movement speed. All the other parties get the same treatment, so you can start fights by colliding with them.

However, that is just one way to get rich. You can also try your hand at trading, where you buy goods for cheap in a village or town and sell them in another town where the demand for that good is high. Of course you’ll have to factor in that some goods will lose value as they get eaten or start to rot, so to get rich you have to focus on the unspoilables like salt, velvet, tools and furs. But how do you know if the price you’re getting for an item is amazingly cheap or horrifyingly expensive?

You don’t. And it’s very problematic. In fact, I started a spreadsheet just to see what the average price of items was:

What is this, EVE online?

After a while, you start seeing patterns. For instance, if you see grain at

However, if you buy iron for <70, you can sell it for ~300 denars. A huge profit! And it would be nice if the game actually told you about these things. If it let you discover the workings of the local economy, to help you make a profit without bloodshed.

But enough about this hugely popular and successful game built by two people in an apartment. Let’s talk about new features in PostApocalypse!

Saving game state

This proved to be quite the headache. How do you store game state in a file? Well, remember how I talked about MVC last week? That model is very, very handy when you want store only the state of the game and not any additional fluff. You simply store the variables in the Data modules, because you don’t have to care about the rest!

But what should the save file structure look like? My first thought was to use an .ini like structure. And you should always start small before investing a lot of time an energy into a new system, so I started with saving and restoring the camera’s position and rotation:

Position=Vec3(123.5, 23.4, 677.0)
Orientation=Quat(0.0, 0.0, 0.0, 1.0)

This looks fine, but it has a problem. These guys can explain it much better: Engine Tech: Concurrent World Editing. They talk about the problems they had with their save file system and how they resolved it. The gist of it is that when you store floats as strings, you tend to lose precision real fast. Did you know that the floating point number “0.2” cannot be accurately represented in the floats we use in our floating point hardware? It’s true and it’s not a conspiracy! It’s just how the math works out.

The result of this is that it’s a bad idea to store floats as strings. So I looked at the article I linked earlier to see how they fixed it. Well, here’s what they do:

; position
    46.103531 : 42386a04
    108.079681 : 42d828cc
    8.694907 : 410b1e57

They store the float as both a string representation and they store it as a hexadecimal integer! That’s brilliant, because you can always read the hex correctly and convert it to a float.

But as I tried to implement this myself, I realized: why don’t I just make a binary file in the first place?

The tool I\’m using here is called 010 Editor. It\’s awesome.

That probably looks like a big ol’ pile of gobbledygook to you. As well it should! But after reverse-engineering a great many stupid file formats, I know what makes a great file format.

The savefile

The most important thing of any binary format is the header. This helps identify the type of file you’re dealing with, but also the type of data. I use a PNG-like block structure, where each block has its own header.

This is the structure used for that:

	struct SaveSectionHeader
	char name[4];
	dword version;
	dword length_in_bytes;

Keeping the header separate like that allows you to load the entire header in one go, without those pesky conditionals. The name variable is used to identify the block. Right now I have only two blocks: “PASV” (PostApocalypse SaVe file) and “CAMR” (Camera). The first block allows you to quickly identify that yes, this is a PostApocalypse save file and it also tells you how many blocks are going to follow.

The camera block simply has its data (position and rotation) dumped into the block as bytes.

And that’s it. :) Surprisingly easy to work with, reliable and extensible! The version variable might seem like overkill, but it will vital in allowing backwards-compatibility. Hopefully, by the time this game reaches completion, I will still be able to convert and load this savefile.

The Graphics User Interface

UI is one of those things that nobody ever enjoys doing, but is vital to what separates a mediocre game from a great game. Mount & Blade: Warband, that game I use to steal… I mean get inspired by? It has a terrible user interface. It tells you either too much:

Why not just tell me: 108 prisoners. Sure would save screen estate.

Or too little:

How many days can I survive on these food supplies? How much does each horse increase my movement speed? What the hell is encumbrance even for?

So I set out to improve upon that by designing a great UI from the start and integrating it with the rest of the game.

Firs things first: that silly font rendering I had had to go. Obviously it was Windows-specific and it would be a pain to port to other platforms. But I’ve used FreeType in the past and I could never get it to render quite right. Also, I don’t want to spend all of my time designing a system I don’t really care for, so let’s take an existing package.

I don’t want to use CEGUI, because last time I used it I produced code looking like this:

That RockScroll image on the right side really tells you all you need to know about the GUI code.

But I didn’t want to let my prejudices get in the way of progress, so I gave it a try anyway. And then I found out that you can’t really control anything. Don’t want to use XML to load scheme files? Too bad, the scheme loader uses private, not protected members. Want to use your own font render? Yeah, no, this one just works for us you know?

So I decided to look at alternatives. And I ended up with libRocket, the cute little engine that could.

Even its logo is adorable

Now I should explain my thought process regarding it:

  • Stage 1: Dismissal – “Using HTML and CSS to render UI’s? Come on, that’s overkill! Besides, I’ll bet it’s really slow.”
  • Stage 2: Testing the waters – “I bet the source is a real mess. No, actually it’s not. And I get to specify my own renderer? Sweet!”
  • Stage 3: Acceptance – “Listeners are awesome! Input is awesome! I love this library!”

That’s not to say I haven’t had problems with it. For instance, what if you want to know whether input should be handled by the game or by the UI? I still haven’t figured out a reliable way, but here’s what I came up with:

	void InterfaceManager::Update()

	Rocket::Core::Element* hover = m_Context->GetHoverElement();

	Rocket::Core::String tag_handled;
	if (hover)
		tag_handled = hover->GetTagName();
		tag_handled = m_Context->GetFocusElement()->GetTagName();

	m_HandledByGUI = true;
	if (tag_handled == "#root")
		m_HandledByGUI = false;

It seems kind of… clunky, to be honest. And then there’s the div hell web developers should be familiar with:

I just want that little X to the right of that dummy text. WHY MUST THIS BE SO DIFFICULT?

But overall: I really like it! Using HTML/CSS for UI makes a lot more sense than trying to get the same results using relative and absolute offsets like in CEGUI.

Next week

I’m hoping I can finally start getting some gameplay next week. I have the basic systems set up, now it’s a matter of getting more content.

And that may involve… me learning GIMP and Blender. D:

See you next time!

seo resell