Tag Archives: programming

MeshUp!

Last week I started working on a small, yet powerful visualization tool for animations or more generally spoken for any multi-body simulations. It is based on skeletal animation and magic and is called MeshUp!.

The frames for the skeleton are defined in a JSON file (thanks to jsoncpp this was relatively easy to implement). In the same file meshes can be attached to the frames (e.g. some random monkey head to the “Head” frame, etc.) and are then moved with the head bone.

The meshes themselves are Wavefront OBJ files that can be exported by nearly every 3d content creation package. I wrote the importer in about 2 hours which surprised me. I feared that to be a lot more of a hassle.

Furthermore it finally made me play around with Quaternions a bit more. Turns out that they are not as hard and are actually quite efficient. Before that I used some matrix calculations for the rotations but with the Quaternions I basically have the same usage but about 10% performance gain (not that it would matter, but it surprised me a little). The biggest problems I had, was that in my computer animation reference book a formula for a conversion had a typo. Thanks to test driven development this was easy to debug and will not occur in the future! Yay!

Oh, also it is coordinate system agnostic. Meaning you can use whatever angle convention you like! ZYX Euler? Sure! YZX Euler? Why not? Just define the proper coordinate system and rotation order in the model file and that’s it!

I published MeshUp! at bitbucket account. You can download the source at:

https://bitbucket.org/MartinFelis/meshup

So far I havent’t decided on a license. Any suggestions?

 

Android Programming – First Try

Today I felt a bit daring and thought I’d try programming for android.

Here is the result: the NerdRomanceHelper.apk.

Here is a screenshot:

I’ve tried it, it works!

Custom Shaders and Material in Horde3D

To simplify scene management and visual effects I looked at various open-source graphic engines that I might use. I briefly looked at the usual suspects such as Ogre3D and Irrlicht until I found Horde3D, which convinced me by its simple looking API and the compiled library was much smaller than of the others. It also seemed to feature various capabilities that might be interesting (scene graph, shadow mapping) or nice to have things (picking, blur, hdr, etc.).

However being an old-school OpenGL programmer, that mostly draws simple geometries such as cubes, spheres, and similar, it is not quite the way I am used to do stuff. Furthermore, the shaders in the examples seemed much more advanced than I need for now, so I am currently trying to make things more basic. Eventually I want to use the scene graph to do some procedural animation and that I am going to do with these simple geometries. Using more sophisticated models created with blender should not be too hard once I got it running.

So far I incorporated Horde3D to my code and using assets from the example to get some experience with Horde3D and implemented a simple shader. As I had the OpenGL Superbible laying around I thought it would be nice to implement the good old Ambient-Diffuse-Specular lighting model (so far only on a per-vertex basis).

Here are some screenshots of the different steps I took:

Now I can easily specify the material in the XML-files that Horde3D is using. Also, I learned a great deal about Horde3D.

Hopefully I’ll soon be able to draw simple procedurally generated geometries and can then start to look at the animations.

Scala + LWJGL = Running Program

scala + lwjglI thought I would try to get the Lightweight Java Game Library (LWJGL) running in Scala as both are really hip nowadays. Turns out that there is not much available on teh internets that works. Most of them use the “Simple Build Tool” (sbt) which I did not find simple at all. Also they have a new version 0.10.x which is incompatible to the Scala+LWJGL examples which use sbt version 0.7.x. Yay!

Anyhow, I used the Scala code from http://lwjgl.org/forum/index.php?topic=3416.0 and finally managed to get it run without any “simple” tools or other dependencies. Here is how:

  1. Download the current LWJGL release (as of writing: 2.7.1). This should give you a zip file with a few jars, dlls and so files.
  2. Download and install Scala from http://www.scala-lang.org/ (as of writing: 2.9.1)
  3. Create the folders “lwjglproject/lib” and “lwjglproject/src”
  4. Extract all .jars to “lwjglproject/lib”. When using Windows do so with the dlls, on Linux put the .so files there and Mac users probably don’t have to do anything (that’s what I’m always being told)
  5. Create a source file “lwjglproject/src/lwjgl.scala” with contents from the example (also available further down)
  6. Compile the code with
    scalac -classpath ./lib/lwjgl.jar src/lwjgl.scala

    this should  give you some .class files

  7. Run the example by executing
    scala -classpath lib/lwjgl.jar -Djava.library.path=./lib Main
  8. Enjoy

Oh, and if you want to run the program directly with java to have to specify the path to scala-library.jar and add the (current) “lwjglproject” path to the classpath:

java -classpath .:lib/lwjgl.jar:/lib/scala-library.jar -Djava.library.path=./lib Main

Here is the code for the example:

import org.lwjgl._
import opengl.{Display,GL11,DisplayMode}
import GL11._
import input._
import math._
 
object Main{
	val GAME_TITLE = "My Game"
	val FRAMERATE = 60
	val width = 640
	val height = 480
 
	val player = new Player(0,0,0);
 
	var finished = false
	var angle = 0.0f
	var rotation = 0.0f
 
	def main(args:Array[String]){
		var fullscreen = false
		for(arg <- args){
			arg match{
				case "-fullscreen" =>
					fullscreen = true
			}
		}
 
		init(fullscreen)
		run
	}
 
	def init(fullscreen:Boolean){
 
		println("init Display")
		Display.setTitle(GAME_TITLE)
		Display.setFullscreen(fullscreen)
		Display.setVSyncEnabled(true)
		Display.setDisplayMode(new DisplayMode(width,height))
		Display.create
 
		println("init gl")
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_LIGHTING)
		glEnable(GL_LIGHT0)
		adjustcam
	}
 
	def adjustcam(){
		val v = Display.getDisplayMode.getWidth.toFloat/Display.getDisplayMode.getHeight.toFloat
		printf("v:%f",v)
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity
		glFrustum(-v,v,-1,1,1,100)
		glMatrixMode(GL_MODELVIEW)
	}
 
	def cleanup(){
		Display.destroy
	}
 
	def run(){
		while(!finished){
			Display.update
 
			logic
			render
 
			Display.sync(FRAMERATE)
		}
	}
 
	def logic(){
	    // in scala we can locally import all methods from Keyboard.
	    import Keyboard._
 
		if(isKeyDown(KEY_ESCAPE))
			finished = true
		if(Display.isCloseRequested)
			finished = true
 
		// rx and rx store our keyboard input as direction  
		var ry = 0
		var rx = 0
 
		// keys are IKJL for up down left right
 
		if(isKeyDown(KEY_I))
			ry += 1
		if(isKeyDown(KEY_K))
			ry -= 1
		if(isKeyDown(KEY_J))
			rx -= 1
		if(isKeyDown(KEY_L))
			rx += 1
 
		// this makes the direction relative to the camera position
		// it is a simple rotation matrix you may know from linear algebra
		val ax = rx*cos(-rotation.toRadians)-ry*sin(-rotation.toRadians)
		val ay = rx*sin(-rotation.toRadians)+ry*cos(-rotation.toRadians)
 
		player.x += 0.1f*ax.toFloat
		player.y += 0.1f*ay.toFloat
 
		// this rotates our camera around the center
		angle += 2.0f % 360
		rotation += 0.2f
	}
 
	def renderGrid(size : Int){
	    // this creates the nice looking background.
		glDisable(GL_LIGHTING)
		glBegin(GL_LINES)
		for(i <- -size to size){
			glVertex2i(i,-size)
			glVertex2i(i, size)
			glVertex2i(-size,i)
			glVertex2i( size,i)
		}
		glEnd
		glEnable(GL_LIGHTING)
	}
 
	def render(){
		glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glLoadIdentity
 
		glTranslatef(0,0,-20)
		glRotatef(-70,1,0,0)
		glRotatef(rotation,0,0,1)
 
		glPushMatrix
		player.applyPos
		//rotate the player just for fun
		glRotatef(angle, 0, 0, 1.0f)
		player.draw
		glPopMatrix
 
		//without background, motion is not visible
		// a green grid is nice and retro
		glColor3f(0,1,0)
		renderGrid(10000)
	}
}
 
class Player(nx:Float,ny:Float,nz:Float){
	var x:Float = nx
	var y:Float = ny
	var z:Float = nz
 
	def applyPos {
	    glTranslatef(x,y,z)
	}
 
	def draw = {
		glColor3f(1, 0, 0)
		glBegin(GL_TRIANGLE_FAN)
		glNormal3d( 0, 0, 1);	glVertex3d(0,0,0.5)
		glNormal3d(-1,-1, 1);	glVertex2d(-0.5, -0.5)
		glNormal3d( 1,-1, 1);	glVertex2d(0.5, -0.5)
		glNormal3d( 1, 1, 1);	glVertex2d(0.5, 0.5)
		glNormal3d(-1, 1, 1);	glVertex2d(-0.5, 0.5)
		glNormal3d(-1,-1, 1);	glVertex2d(-0.5, -0.5)
		glEnd
	}
}

Articulated Body Algorithm – first video

During the last month I was working on an implementation of Roy Featherstones “Articulated Body Algorithm” which is one of the most efficient algorithms for simulating the dynamics of articulated figures. It has an asymptotic complexity of O(n) with n being the numbers of degrees of freedom. Here is a first video of a simple OpenGL visualization I hacked together yesterday:

I used Featherstones book “Rigid Body Dynamics Algorithms” which I highly recommend to anyone undertaking this task(*). Additionally I used Featherstones Matlab Code of his algorithm that is available from his site at http://users.cecs.anu.edu.au/~roy/spatial/index.html to verify my results. I also used The HuMAnS Toolbox to double check my implementation. Furthermore I used exhaustive unit testing (algorithm + library: ~2600 lines of code, automated tests: ~1500 lines of code) to make sure I don’t brake things too much or at least have some feedback what I am currently breaking. Thanks to UnitTest++ this was nice and easy.

Now what is remarkable about this video is that it is the first time I see my implementation in live action. Before that I only knew from my tests and the comparisons that it is correct. It is comparable to flying blindly through fog only by using your instruments and trying to land. Luckily this bird has landed! … actually using “luckily” here is rather odd… let’s go with: WICKED!

(Even though the instruments said it is all right it is very nice when the sun comes out suddenly and you have landed very well and are already at the correct parking position.)

*Some things to note about the book:

The book is also very useful for other well-known algorithms used in robotics and mechanics, such as the Composite Rigid Body Algorithm or the Newton Euler Algorithm, as this book is very clear and complete. It also discusses other topics such as system with closed (kinematic) loops, impacts and other stuff. Additionally there is a detailed section about efficiency and how to implement the algorithms. For every major algorithm there is always the mathematical expressions next to the actual pseudo code for clarity – nice!

Spatial Algebra

But The Best Thing Ever™ in his book is the spatial algebra he uses to formulate rigid multi body problems. It is a very sleek way to overcome the hassle of using two types of equations: one for linear motions and forces (translations, etc.) and another one for rotational motions and forces. Instead of the two 3D equations he uses one 6D equation that is further grained with Screw Theory. It takes some time to get the point of it all, but it absolutely pays off once one understands the elegance of it.

There is also a very good 2 part tutorial written by Featherstone concerning spatial algebra, which is published at the Robotics and Automation Magazine in the two recent issues which you might get through here:

Update: link to the September issue of RAM pointed to the December issue, now fixed.
Update 2: my code a.k.a. Rigid Body Dynamics Library is now available at http://bitbucket.org/MartinFelis/rigidbodydynamicslibrary

Asteroids Beta 1 (update)

Wahoo!!! It looks like I am getting somewhere with my Asteroids clone. It took me much longer than expected that far, but I do think I learned a lot on the way. Initially I started it because I realized my game programming demons that prevented me from actually writing a game. Instead I was only talking to myself that I would program game X at some point and programmed smaller things with which I could delve in the illusion of programming games.

However you don’t make a game unless you make a game. And that’s what I did – although I have to confess something: the game is not yet finished. There are two remaining tasks that I want to work on before I would dare to call it a completed game. These tasks are testing and additional levels.

Things still todo…

I guess the experienced game designer/programmer might smile at this point, especially at the latter part, as levels are probably one of the trickiest things to do. They have to make the player at first curious, then be challenging, but not too hard, and not too easy, oh and not boring. However I do not plan to make this game perfect and therefore I am not going to make more than, say 20 levels. So far there are 5 levels with more or less increasing difficulty except the 5th which is a bit of a steeper step. The game mechanics will stay the same for future levels and there won’t be crazy new game elements, because I do not want to finish a game and not go on an endless journey of ideas.

Right now I need to do some testing (done by YOU* !) to find problems that I haven’t found yet. I am starting to not see issues because I am already too much in the technical viewpoint and got used to a play style that probably circumvents all issues that other people might have. Therefore I need some non-biased feedback from people without knowledge about the details. I already showed the game to a few people and had the chance to watch them play and I am fairly satisfied so far.

Now cut to the chase!

You can download the windows version from here:

I tested it under Windows 7 (64bit), Windows Vista (32bit), and Windows XP (32bit). I do my development under linux, but creating packages for that is a bit annoying. If someone wants to run it under linux, I will gladly send you the code and help you make it run.

Update: there is now also a Debian/Ubuntu (64bit) package available here:

Here are some screenshots, to get an impression how the game looks:

A few words to the style…

I tried to keep the style more simple and not do fancy OpenGL stuff. This has two reasons: first I am so far not much of an OpenGL guru and shader ninja, and second for a game like this a more ‘classical’ style fits very well. I tried to use filtered sprites, but that made the game look like strangely cheap. I hope the following picture conveys this somehow:

Also together with the font I am using it all looks a little more retro style. I do believe that it is more important to find a fitting style than to have graphical excesses (however I totally do not mind them, rather the opposite). But for a lone-wolf production like this I have to take what I can make myself and so far I am very satisfied.

Some Credits

Here is a non-exhaustive list of libraries that I am using for the game (in no particular order):

  • SDL for OS abstraction
  • SDL_mixer for sound playback (which allows me to use ogg files quite nicely)
  • OpenGL for graphics
  • OGLFT for font rendering
  • boost (shared pointers and filesystem abstraction)
  • libpng for loading textures
  • Visual Studio Express C++ 2008 to create windows binaries
  • CMake as a build system
  • Mercurial as version control system
  • Audacity for modifying sounds
  • Gimp for everything that is 2D and consists of pixels

The music I am using is from DJAD and is called Space Exploration. Other than that I am using various sounds from http://freesound.org that I have customized (I still have to make a proper list for the credits).

All right. So much for now.

Have a nice day!

(* all right, there are not too many people passing around here that might be inclined to test it, but I still thought I’d make it clear that you are cordially invited to test and give some comments.)

Blinking Cursors

When having some sort of keyboard input it is always helpful to have a blinking cursor, so that the user knows where he/she/it is typing. This is usually shown by a blinking pipe ‘|’ or underscore ‘_’ symbol. In my current asteroids I didn’t bother with the blinking and simply appended a static underscore to the current input. However I was just reading a nice post about immediate GUIs at http://sol.gfxile.net/imgui/ch01.html (very interesting way of programming a game user interface!), which also had a very nice trick to have a blinking mouse cursor with pretty much no effort. You find it in chapter 7 of that tutorial.

The trick is:

std::string name_output (mPlayerNameInput);
if ((SDL_GetTicks() >> 8) & 1)
	name_output += "_";
DrawGLString(xpos, ypos, name_output.c_str());

SDL_GetTicks() is the time function of the SDL library and simply returns the number of milliseconds passed since the initialization of the SDL library. By shifting the value of the function to the right by 8, the resulting expression in line 2 alternates now between true and false each 256 milliseconds. If you want the blinking every half seconds, shift it by 9 bits.

Awesome!

Asteroids: first flying rocks

As I mentioned in my previous post, I decided to get a rather simple game done instead of dreaming of bigger ones. So far I think I was quite successful. I tried to reuse most of the code I already had and it was very helpful to modify my existing code towards a very clear playable game.

The game itself is already playable and I have a basic menu and basic gamelogic (you have 3 lives and once you die you’ll see the game over screen) and I can load and save levels. At first I thought of using 3d models by using the cal3d library which I already use in my research project, however I reminded myself of keeping things simple and created some nice sprites. I added PNG support by using libpng to be able to load sprites with transparency and also added simple animation of sprites. In the background the stars are moving sideways to give a slight 3d effect (looks very nice!).

What is still missing is sound and I need a few more animations (ship exploding, asteroid exploding). Additionally I do not yet count any points and some non-asteroid (maybe some powerups) would be nice to add more fun to the game.

Enough prose – here are some screenshots:

the menu

asteroids in action

game over screen

My game development demons

It’s been now a long time, since I decided to write a certain game and talked a lot about it with friends. However I must confess, now after a few years, I still haven’t managed to finish a game. I wrote a lot of code and both bugs and documentation is so far not the problem. Instead there are a couple of demons that  slow down the process that I would like to introduce to you (you probably know them already):

Efficiency Demon: This one is always in the back of my head. It tries to convince me not to use virtual functions as they are somewhat slower than normal function calls. However this approach makes things a lot more complicated and I spent time to circumvent the usage of “the single most important feature of C++” by using probably less efficient detours. Additionally following strictly the rule: first make it run, then optimize would encourage me to take a deeper look in profilers, which would be definitely a knowledge I wish to possess. There are a couple of nice quotes to this one on the Wikipedia page on program optimization – I guess I am not the only one having this demon.

Engine Demon: Instead of tackling simply completing the game logic/event managing/input handling part, I try to generalize what I just coded and put it into a part that I call “engine”. This “engine” is some kind of container of reusable code that I will most certainly need in the future. The catch is just: I do not yet know what exactly I will be needing in the future. Actually neither whether I need the generalized case nor the specialized I wrote in the first place. There is a very well written article (write-games-not-engines) from Josh Petrie which talks about this one. This demon is sometimes called Premature Generalization.

Beauty Demon: The Beauty Demon is related to the Engine Demon. It makes you want to clean up your mess (a.k.a. code). You just hacked in some features and now you want to polish it a little. So you polish. Then you realize you should add documentation. So you add it (and look at the beautiful caller graphs that Doxygen creates automatically for you). Then you realize that you could create of this feature set a library against which you can link dynamically – oh yeah, this is great, because then you can do this for all the other games you will write and reuse it. Oh, and the build system it got a little messy. How about … Yeah, you get it. You do a lot of things which are actually very useful. However they do not complete your game.

Just-that-feature-and-then-I’m-done Demon: I coded hard. The prototype works. And I am very happy. So I relax and think: Awesome, I’ll be done soon with the whole game and I can finish the rest tomorrow. There is a huge difference between a prototype and putting it into your game. I had a few nice parts, such as an event system and entity management system and so on which worked very well on them selves. But when I actually tried to make a simple game with it, I had to rewrite a lot of it and it was a lot harder than I expected. So unless the code is not in your game don’t think anything is done! (Please note that this is not an argument against writing prototypes – they are very important because you realize what the actual problem is and what kind of difficulties you run into!)

A long time ago, I read this very inspiring article ‘How do I make games?’ A Path to Game Development.When I look back, I must admit, I skipped quite a few steps suggested there. So last week I started to abuse my “engine” to create an Asteroids clone. So far controlling the ship, destroying asteroids and getting killed works, but there are still some areas untouched (menu, game-over screen, etc.). It took me a lot longer than I expected and I currently have a lot of quirks on making things work.

So far it is not efficient, not an engine, not beautiful and there is still a lot of work to be done. But I’ll stay on that rocky road and bring it home.

Thought game development is fun? It is – but getting it done is actually quite hard!

About the View in a Model-View-Controller

I recently bought the third edition of the book “Game Coding Complete” from Mike McShaffry (a.k.a. MrMike) et al. which has been very delightful to read so far. I have been reading a few chapters which gave me a new way of looking at game architecture and other things that I was convinced that I already understood them quite well.

One of them is the famously known Design Pattern: the Model-View-Controller. To me, the Model always was the data that is being modified, the Controller takes care of the input (mouse, keyboard, maybe network, …) sent to the application and the View simply displays the data. If you want to improve graphics – you work on the View. You want to update keybindings in your input system – you’ll modify the Controller. Also the Controller keeps track of the player id that tells us which entity is being controlled by the player. Need a new type of vehicle / weapon? – Go to your Model (and of course, add code to the Controller and View to reflect them).

So far so good.

However in this book Mike gives an overview of a game architecture consisting of three basic parts: the Application Layer, the Game Logic and multiple Game Views. The Application layer hides the platform specific from the game and the Game Logic resembles what is going on in the game. The Game Views represent the game from different perspectives e.g. for a human player or a AI agent.

Game Architecture after Mike McShaffry

At first my head tried to map them onto a Model-View-Controller which failed as they resemble completely different things. Especially the description of the Game View gave me a different way of looking at the View in a Model-View-Controller. The Game View does not only display what is going on in the game, instead it also takes care of the input handling. More specific: the Game Views receive all the input events (key presses, etc.) and communicate with the Game Logic over events.

At first this seems a bit awkward concerning to what I wrote further up concerning the View, but giving the view the ability to receive input and send events has some nice properties. For example it might be “easier” to add a split-screen mechanic as each player has its own Game View (remember: we have multiple Game Views!) and also its own keybindings. Also one could imagine having a GameEditView which has completely different abilities than e.g. a HumanGameView. This gives the View more power as it also contains not only the way how you look at things but also how you interact.

Maybe I got it all mixed up, however I think it one shouldn’t be too strict on saying input is clearly handled in the Controller or that the job of a View is drawing only.