(Single-Threaded) Latent Functions in C++

I’ve been recently considering conversion of one object oriented Unreal Script like language code into C++ to improve its run-time performance. And while most of the features of the language seemed easy to transform from one to another there was one that wasn’t trivial to do: latent functions.

Now, just to make sure: by latent functions here I mean functions that might take a long time to finish and this is not because they’re heavy functions but because they might need to wait for something. The best example of such function is Sleep().

My goal was to support execution of multiple such functions on a single thread without having to block i.e. whenever the function needs to wait for something it should get paused and it should be possible to resume it later at any time. Pseudo-code sample:

int MyFunction( float a )
{
    [...]               // Some code
    Sleep( 1 second );  // Wait 1 second
    [...]               // Some code
    Sleep( 2 seconds ); // Wait 2 seconds
    [...]               // Some code
}

[...]

call.Call( MyFunction, 10.0f ); // Call MyFunction with a == 10.0f
while ( !call.IsDone() ) // While not finished
{
    call.Advance();      // Keep resuming
    [...]                // Other code
}
result = call.GetResult(); // Done! Now get the result

What I ended up with is a very small library that makes implementing latent functions in C++ a bit easier to write (and read!). My implementation is based on an idea described in Coroutines in C but goes beyond what’s presented there in that it:

  • allows for arbitrarily nested latent function calls
  • doesn’t require programmer to access parameters or local variables via context struct (makes the code look a lot more like ‘normal’ code)
  • fully supports canceling latent call without memory leaks; this is achieved by storing individual parameters and local variables along with their destructor functions

But the main trick stays the same and is the fact that individual ‘case’ blocks can be placed anywhere inside of the ‘switch’ block which allows us to jump pretty much anywhere in the function body – almost like goto instruction. In particular, using this language feature, we can jump to where we left off previously and resume code execution.

The only major limitation of this implementation, and one I’d love to be able to solve but I’m afraid there’s no solution for it in pure C++, is that one can’t place latent function calls returning non-void value inside of an expression, e.g. inside an ‘if’ condition. This is because it’s impossible to use switch-case (or goto) to jump to inside of an expression.

Check out LatentLib on github and let me know what you think. But please keep in mind that it hasn’t been implemented with high performance in mind (separate dynamic memory allocation per variable and stack frame) but more so to present the general concept.

Posted in game engine, general programming, scripting languages | Tagged , | 2 Comments

Rainbow Hero – my new indie game

After some very long and slow, mostly after hours, development I have finally released my new puzzle game – Rainbow Hero:

The game is an old-school type of game as far as mechanics with some painterly stylized graphics and a fairy tale style audio.

     game7game8     game4

One of my primary gameplay inspirations for Rainbow Hero was Stone Age – a game released for PC DOS in 1992. I remember when I played it with my father on my old good Intel 486. Years later, I played it again with my wife. Both times it was a lot of fun. Clever, often seemingly impossible, puzzles and lots of cool ideas.

stone-age_1  stone-age_11

Another inspiration was Lasermania – game released in 1990 for Amiga. I liked the general idea of reflecting lasers but I considered the game prohibitive as far as difficulty level. Even though I am a patient kind of gamer and I love solving puzzles, I got stuck on some of the very first levels and didn’t want to continue.

VXPzeTt    lasermania_l09_s

There’s a couple more inspirations including general pushover mechanic as well as some totally original ones. I’ve always loved playing puzzle games and I guess with Rainbow Hero it is my attempt at gathering together some of the most interesting puzzles that could be applied to grid based levels and putting them together into a game.

Sokoban    02_sokoban-1988_29

One of the cool things that I am particularly happy with is time rewind feature that simply lets you go back in time – either when you get stuck or just want to try different approach. This isn’t anything new – games such as Braid use this a lot (and not just for purely time rewind) – but it makes the game a lot more player friendly.

game10

Time rewind in action

In fact, it was pretty straightforward to do code wise. All I had to do was to store game state for each frame. Then, with ‘rewind’ button pressed, the game gets continually restored from past states. A little bit of work went into optimizing memory usage, so that the game state is small enough I can safely store hours of gameplay.

If you’re into serious puzzle solving Rainbow Hero might be the game for you. It is already available on Steam and directly via game website. And if you happen to play the game I’d love hear what you have to say about it.

Posted in general programming, indie game development, puzzle game | 1 Comment

Preventing players from getting stuck in puzzle games

I’ve been developing my puzzle game Rainbow Hero (to be released soon on PC) for a while now and while doing so I designed a lot of puzzle levels. It was fun but it was also great opportunity for me to learn about good and bad ways to design puzzles.

wizard

Rainbow Hero artwork.

Now I’ve just came across an article that talks specifically about that. If you’re into designing puzzles you should totally give it a go: How Are Puzzle Games Designed?. It’s great read and I couldn’t agree more with anything there but I’d like to add a couple of my own tips on one particular topic of how to prevent players from getting stuck (and as a result stop playing the game).

It is very challenging to make a puzzle game that would appeal to many players – both casual and hardcore ones. Making puzzles too easy or too difficult might easily break the game for many. But there’s some ways that can make the game fun for casual players without lowering difficulty level too much thus offering challenge for hardcore players as well.

Here’s my tips:

1) Provide alternative puzzles. Don’t let your game unlock exactly one puzzle after completing another. Make it unlock 2 or more so as to always give a choice to the player. There might be other ways to it but the main idea stays the same – never leave the player with one (or too few) puzzles left.

2) Don’t require player to solve all puzzles in order to solve “the big puzzle” (be it game chapter/world or some other part of the game).

I bet you, as a developer, would much prefer to have lots of players who completed the game even if that means solving only 50% of all puzzles rather than have lots of players who got stuck after completing 10% of the game and never played it again.

3) If the game makes it possible to get into non-obviously unrecoverable states (totally easy in a game such as e.g. sokoban) provide undo or time rewind option. Actually provide it even if it’s obviously unrecoverable because the player might have made a tiny mistake (e.g. pressed the wrong button) and would otherwise have to replay the whole level and start solving the puzzle from scratch.

433022-braid-xbox-360-screenshot-your-basic-power-is-the-ability

Time rewind in action in Braid.

Some puzzle games, such as Braid or Time Ducks, have even made time rewind feature their core mechanic.

Posted in indie game development, puzzle game | Tagged | Leave a comment

Tiny2D – my open source 2D game engine

Today I have finally managed to open source my after hours project called Tiny2D.

It’s development started roughly 4 months ago as I decided to resurrect an old puzzle game I did 5 years ago but never got to finish it. I wanted to port it quickly to new engine (previously used my own tech) that would work well on desktop and mobile platforms and I wanted to improve some of the things too.

Also, having done a couple of 2D game prototypes recently I really wanted something easy to use. Something that would translate my gameplay ideas into working game with as little effort as possible. Minimum code, maximum effect.

And now, here it is – Tiny2D is the fruit of my work, mostly developed while my wife was putting my baby to sleep. It is very simple to use and – as the name suggests – tiny library.

Currently Tiny2D only supports Windows and Android but since it’s using SDL under the hood (and implementing Tiny2D on top of other libs – e.g. Marmalade – would be trivial) it should be easily portable to other platforms such as Linux, MacOS or iOS.

Here’s current list of features:
* Textures (png, jpg and more)
* Materials with Techniques and (GLSL) Shaders
* Animated Sprites
* Particle Effects
* Render Targets
* Several built-in Post-Processing Filters
* Asynchronous Resource Loading
* Virtual Resolution Rendering
* True Type Fonts
* Audio (wav, ogg, mp3 and more)
* Input (keyboard, mouse, touchpad)
* Files
* XML
* Localization
* Multithreaded Job System
* Timer
* Random Numbers

For more details head over to Tiny2D project homepage or check it out on GitHub.

Curious why I made yet another 2D game engine?

a) Because I haven’t found any 2D game engine with as simple, yet powerful, interface. I consider Unity or Marmalade too complex for rapid prototyping, DragonFireSDK far too limited (btw, here is my comparison of Marmalade, DragonFireSDK and Unity) and I prefer C++ from Lua, so LÖVE is out of question too. Sure, there’s many other game engines, but I haven’t found one that would fully satisfy my needs.

b) For fun. After all I really enjoy coding :)

Posted in Uncategorized | 5 Comments

Binding C++ with Lua, Squirrel, Game Monkey and Ocaml

This isn’t anything new I did recently but I thought it’s worth putting up on my blog anyway. I was once interested how easy it is to implement binding between C++ and several popular, mostly scripting, languages.

If you search on the internet there’s heaps of libraries that make the process of binding of various scripting languages with C++ easier – check out this for lua or this for Squirrel binding options.

So, why did I make another one? The first reason was I wanted to learn more about scripting languages and the second one was I wanted the same interface for use with all languages.

C++ library

The result of all that is my MultiScript library that:

  • allows script code to access C++ classes and functions and
  • allows C++ code to access script functions

The library has a very simple C++ interface with 4 different implementations for the following languages:

The interface itself consists of:

  • ScriptContext – responsible for maintaining script execution context; registers classes and functions
  • ScriptStack – used to handle function calls including pushing and popping values on stack
  • ScriptObject – base C++ class for objects to be visible from script
  • ClassDesc, FunctionDesc etc. – helper structs used to describe classes and functions to be registered

The library comes with a simple test project that runs test programs for all languages and prints out their output along with some statistics. The source code of all these languages is included.

Ocaml

Ocaml binding implementation deserves separate paragraph or two as it wasn’t as straightforward as I had hoped originally and I ended up modifying source code of the Ocaml VM (virtual machine) so I could easily load-from-string and run multiple times a chunk of Ocaml code as well as dynamically register C++ functions with Ocaml runtime. Apparently Ocaml VM wasn’t meant to be used as an embedded scripting language the way Lua is.

Binding C++ classes would most likely require a lot more work to get done, so I gave up on that. All of the modifications are clearly marked with “msawitus” in the comments.

In order to be able to run Ocaml tests you have to install Ocaml binary distribution from Inria download site. It is necessary to compile (not execute) Ocaml code.

Summary

Implementation for both Lua and Squirrel are very similar – after all Squirrel is heavily based on Lua. Getting my head around Lua concepts required a little bit of effort at first but it was straightforward after all. Game Monkey binding was straightforward to do from the very beginning, even without docs and Ocaml was a bit of trial and error experimentation.

I should also point out that this was just an experimental project and it’s nowhere near production quality code. But it’s probably worth looking at if you’re wondering which scripting language to choose for your next project.

Project source code is hosted here.

Posted in Uncategorized | 2 Comments

Naive #include Optimizer for C++

Here’s my simple and really basic utility written in C# that optimizes Visual Studio project by removing redundant #include lines where possible. Why having redundant #includes is so bad? The answer is simple – it can severely slow down the compilation process.

Download: Source and Binary

Example usage:

NaiveIncludeOptimizer.exe “C:/Program Files (x86)/Microsoft Visual Studio 11.0/Common7/IDE/devenv.exe” “C:/my_project/my_project.sln” “Debug” “C:/my_project/src”

Example output:

Optimizing Main.cpp...
    Redundant #include External.h
    Redundant #include Misc.h
Optimizing Misc.cpp...
    Redundant #include Common.h
    Redundant #include API.h
    Redundant #include Defines.h
DONE!

The way it works is very brute force (hence the “Naive” in the name) meaning it tests every #include individually to see if the solution would still build if it was removed. So, yes, that means larger projects may even take days to process! But in the end it does work (mostly – see below when it doesn’t).

Be careful because it does modify the source code. But while doing so, it always creates a backup copy. Bonus feature is that it is capable of resuming from where it stopped last time.

Also, please note that it only optimizes .cpp files. Optimizing .h files would obviously take a lot longer!

I should also point out that the proper way of doing this would be implementing full blown C++ preprocessor that would include:

* removing redundant #includes

* adding forward declares where possible

* making sure that the actual code generated does not change (my solution may result in some undesired program “optimizations” – e.g. by removing #include “my_new_operators.h” the definition of your new/delete operators might change but the project would still build successfully)

It’s obviously a lot more work but fortunately that’s exactly how Google’s Include-What-You-Use is meant to work. I haven’t tried it but it looks neat.

Posted in c++, general programming | Leave a comment

The end of my indie game devevelopment adventure

As of today some of my games on some of the platforms are no longer available and the reason I pulled them is simply because they don’t make enough profit.

Monstaaa! is not available anymore on any of the platforms. In fact I have just recently sold the IP to other developer. Hopefully they bring the second life to the game!

Meanwhile, Puzzled Rabbit for Android, Blackberry PlayBookXBLIG and PC is still available.

iphone0

Apparently indie game development, in particular on mobile platforms, is really tough these days. The way I see things is that iOS / Android gold rush is gone and it’s now incredibly difficult to compete when you’re a small developer because in order to succeed you not only need an exceptionally good, original and polished game but you also need to be visible on the market. And that takes a lot of hard work, talent and some luck too.

Finally I have to say that I am really glad I tried indie game development as I would otherwise not fully understand why it is so difficult and would probably regret not having tried it. I have also learned a lot and had a really good time while it lasted. If you want to learn more about my 10 month long indie adventure have a look at my past blog posts and try to learn something from it.

iOS and Android game development on Windows

Monstaaa! for iOS – the first announcement

Monstaaa! development summary – part 1

Monstaaa! development summary – part 2

How I sold 22 copies of my game in 3 weeks on Android

Posted in Uncategorized | 5 Comments