RBDL bugfix release 2.3.2

August 29, 2014

some very fine people found some bugs in RBDL which made me release another bugfix release. If you are using RBDL version 2.3.0 or 2.3.1 make sure to update as soon as possible.

You can find the newest version here: https://bitbucket.org/rbdl/rbdl/overview

Direct downloads here: https://bitbucket.org/rbdl/rbdl/downloads

And here the list of changes: 29 August 2014: New version 2.3.2:

Tags

Custom Types in LuaTables++ Done Right

October 22, 2013

Even though I am qute happy with LuaTables++ I figured storing and retrieval of custom types could be made even nicer. In my previous post I presented how one could add a custom type (i.e. a C++ struct or class) such that it can be assigned to values in Lua. It still required knowledge of the Lua C-API and would furthermore have made assignment of nested values more cumbersome. It now dawned to me that I could re-use facilities in LuaTables++ to circumvent both points.

For a struct of the form:

struct CustomType {
    string name;
    double age;
    bool drunken;
    double position[3];
};

especially setting the values of the double position[3] array would require creation of a new table which can be a bit cumbersome if one is not familiar with Lua’s stack. However this kind of functionality is already included in LuaTables++. Using the new API one can now implement the LuaTableNode::getDefault<CustomType>(const CustomType &value) function as:

template<>
CustomType LuaTableNode::getDefault<CustomType>(const CustomType &default_value) {
    CustomType result = default_value;

    if (exists()) {
        LuaTable custom_table = stackQueryTable();

        result.name = custom_table["name"].get<std::string>();
        result.age = custom_table["age"];
        result.drunken = custom_table["drunken"];
        result.position[0] = custom_table["position"][1];
        result.position[1] = custom_table["position"][2];
        result.position[2] = custom_table["position"][3];
    }

    stackRestore();

    return result;
}

and similarly the LuaTableNode::set<CustomType>(const CustomType &value) as:

template<>
void LuaTableNode::set<CustomType>(const CustomType &value) {
    LuaTable custom_table = stackCreateLuaTable();

    // set the fields of the custom type
    custom_table["name"] = value.name;
    custom_table["age"] = value.age;
    custom_table["drunken"] = value.drunken;
    custom_table["position"][1] = value.position[0];
    custom_table["position"][2] = value.position[1];
    custom_table["position"][3] = value.position[2];

    // restore the stack
    stackRestore();
}

One has to keep in mind that Lua starts its indices at 1 instead of 0. But apart from that I guess it should now be quite easy to add any kind of structs or classes even with complex member variables. If you have a suggestion to make it even simpler, let me know!

Tags

Using Lua Scripts as Config Files from C++

October 16, 2013

tl;dr: LuaTables++ is a library that allows you to access values from Lua scripts in an easy manner. Custom types (i.e. structs or classes) can be easily added so that storing and retrieval to and from Lua is super simple. Serialization to strings is included. Code available here (MIT license). Handling of custom classes / structs is explained here.

Introduction

For my visualization tool MeshUp I am using jsoncpp to store the configurations files. However it dawned to me that it should be easy to implement a library that allows to store and retrieve values from Lua scripts similarly easy as jsoncpp. As Lua has a nicer syntax than JSON this would allow me to store the configuration as Lua scripts and thus getting all the scripting capabilities there as well.

Overview

The last few days I spent some time to pimp the my LuaTables (which I mentioned here) library to make it more intuitive to use from C++ and I ended up something very nice. It even deserves a renaming to LuaTables++. First, an example:

-- agentsettings.lua
person = {
    name = "James Bond",
    age = 42.,
    drunken = true,
    address = {
        country = "United Kingdom"
    }
}

return person

Can be accessed using LuaTables++ using:

LuaTable ltable = LuaTable::fromFile("myfile.lua")

std::string name = ltable["name"];
double age = ltable["age"];
bool drunken = ltable["drunken"];
std::string country = ltable["address"]["country"];

Similarly you can set values:

ltable["drunken"] = false;

And also convert the table back to a string, e.g. to save the configuration back to a file:

std::string config_string = ltable.serialize();

Custom Types

Update: I have found a much better solution on how to handle custom types with LuaTables++.

This was very nice, but it gets better: LuaTables++ uses some templating magic inside which can be used to add reading and writing for structured data. E.g. to add the following custom type:

struct CustomType {
    CustomType() :
        name ("unnamed"),
        age (-1.),
        drunken (false) {}

    string name;
    double age;
    bool drunken;
};

one has to implement two functions:

Here the function for converting from LuaTables++ to the C++ CustomType:

template<> CustomType LuaTableNode::getDefault<CustomType>(const CustomType &default_value) {
    CustomType result = default_value;

    if (stackQueryValue()) {
        lua_getfield (luaTable->L, -1, "name");
        result.name = lua_tostring (luaTable->L, -1);
        lua_pop (luaTable->L, 1);

        lua_getfield (luaTable->L, -1, "age");
        result.age = lua_tonumber (luaTable->L, -1);
        lua_pop (luaTable->L, 1);

        lua_getfield (luaTable->L, -1, "drunken");
        result.drunken = lua_toboolean (luaTable->L, -1);
        lua_pop (luaTable->L, 1);
    }

    stackRestore();

    return result;
}

And here the function to store a C++ CustomType to LuaTables++:

template<> void LuaTableNode::set<CustomType>(const CustomType &value) {
    stackCreateValue();

    // create new table for the CustomType
    lua_newtable(luaTable->L);  // parent, CustomTable

    // set the fields of the custom type
    lua_pushstring (luaTable->L, "name");
    lua_pushstring (luaTable->L, value.name.c_str());
    lua_settable (luaTable->L, -3);

    lua_pushstring (luaTable->L, "age");
    lua_pushnumber (luaTable->L, value.age);
    lua_settable (luaTable->L, -3);

    lua_pushstring (luaTable->L, "drunken");
    lua_pushboolean (luaTable->L, value.drunken);
    lua_settable (luaTable->L, -3);

    // add table of CustomType to the parent
    stackPushKey(); // parent, CustomTable, key
    lua_pushvalue(luaTable->L, -2); // parent, CustomTable, key, CustomTable
    lua_settable(luaTable->L, -4);

    // restore the stack
    stackRestore();
}

Once this is done, one can directly store and retrieve any CustomType to Lua:

// Create a new Custom Type
CustomType agent007;
agent007.name = "James Bond";
agent007.age = 42.;
agent007.drunken = true;

// Store it in LuaTables++
ltable["agents"][123] = agent007;

// Retrieve it from LuaTables++
CustomType other_agent = ltable["agents"][123];

One nice thing about this is, that once you have implemented the set() and getDefault() functions you automatically can serialize and de-serialize CustomTypes. Yeeeehaaaa!

Code

LuaTables++ is available from https://bitbucket.org/MartinFelis/luatables only depends on the STL and Lua, which should be easy to fulfill. It is licensed under the MIT license (same as Lua).

Fun Fact: Around the same time Elias Daler implemented something similar to retrieve values from a Lua script http://eliasdaler.wordpress.com/2013/10/11/lua_cpp_binder/. His article also contains a brief introduction how the internals work.

Tags

Switching between Lua and LuaJIT using CMake

August 26, 2013

The more I work with Lua, the more I get addicted to it. Lua itself is a formidable language and additionally it is (somewhat) fun to write wrappers to C/C++ code.

Lua itself is fast, but it can be made even faster by using LuaJIT, which is one of the fastest scripting language implementations available. The nice thing about LuaJIT is, that it is both API and ABI compatible to the standard Lua 5.1 implementation. This means that you simply need to link against the LuaJIT library instead of the Lua library and you get increased performance for free*!

For most of my C/C++ code I am using CMake as a build tool, which is does its job most of the time, albeit its language and syntax is rather cumbersome (especially compared to Lua). There is premake, a build system using Lua, which looks very interesting, however right now I have too little time to move my stuff over to it.

CMake comes with scripts to find Lua 5.0 and 5.1 but not to find LuaJIT. So I wrote my own FindLua.cmake script that searches for Lua 5.1 or LuaJIT depending on the value of the variable LUA_USE_LUAJIT option. Adjusting this variable allows easy switching between the standard Lua and LuaJIT.

CMake caches most of its variables and therefore you cannot change the type of Lua implementation using the CMake GUI. To alleviate this you can use the following lines, that ensure the invalidation of the cached CMake variables and nice and snappy switching between the implementations from the CMake GUI:

OPTION (LUA_USE_LUAJIT "Use LuaJIT instead of default Lua" OFF)
UNSET(Lua_FOUND CACHE)
UNSET(LUA_INCLUDE_DIR CACHE)
UNSET(LUA_LIBRARY CACHE)
FIND_PACKAGE (Lua REQUIRED)

Here is full FindLua.cmake script:

# Copyright (c) 2013 Martin Felis &lt;martin@fysx.org&gt;
# License: Public Domain (Unlicense: http://unlicense.org/)
#
# Try to find Lua or LuaJIT depending on the variable LUA_USE_LUAJIT.
# Sets the following variables:
#   Lua_FOUND
#   LUA_INCLUDE_DIR
#   LUA_LIBRARY
#
# Use it in a CMakeLists.txt script as:
#
#   OPTION (LUA_USE_LUAJIT "Use LuaJIT instead of default Lua" OFF)
#   UNSET(Lua_FOUND CACHE)
#   UNSET(LUA_INCLUDE_DIR CACHE)
#   UNSET(LUA_LIBRARY CACHE)
#   FIND_PACKAGE (Lua REQUIRED)
 
SET (Lua_FOUND FALSE)
 
SET (LUA_INTERPRETER_TYPE "")
 
IF (LUA_USE_LUAJIT)
    SET (LUA_INTERPRETER_TYPE "LuaJIT")
    SET (LUA_LIBRARY_NAME luajit-5.1)
    SET (LUA_INCLUDE_DIRS /usr/include/luajit-2.0 /usr/local/include/luajit-2.0)
ELSE (LUA_USE_LUAJIT)
    SET (LUA_INTERPRETER_TYPE "Lua")
    SET (LUA_LIBRARY_NAME lua5.1)
    SET (LUA_INCLUDE_DIRS /usr/include/lua5.1 /usr/local/include/lua5.1)
ENDIF(LUA_USE_LUAJIT)
 
FIND_PATH (LUA_INCLUDE_DIR lua.h ${LUA_INCLUDE_DIRS} )
FIND_LIBRARY (LUA_LIBRARY NAMES ${LUA_LIBRARY_NAME} PATHS /usr/lib /usr/local/lib)
 
IF (LUA_INCLUDE_DIR AND LUA_LIBRARY)
    SET (Lua_FOUND TRUE)
ENDIF (LUA_INCLUDE_DIR AND LUA_LIBRARY)
 
IF (Lua_FOUND)
    IF (NOT Lua_FIND_QUIETLY)
        MESSAGE(STATUS "Found ${LUA_INTERPRETER_TYPE} library: ${LUA_LIBRARY}")
    ENDIF (NOT Lua_FIND_QUIETLY)
ELSE (Lua_FOUND)
   IF (Lua_FIND_REQUIRED)
       MESSAGE(FATAL_ERROR "Could not find ${LUA_INTERPRETER_TYPE}")
   ENDIF (Lua_FIND_REQUIRED)
ENDIF (Lua_FOUND)
 
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lua  DEFAULT_MSG LUA_LIBRARY LUA_INCLUDE_DIR)
 
MARK_AS_ADVANCED ( LUA_INCLUDE_DIR LUA_LIBRARY)

* the only “downside” of using LuaJIT instead of Lua that I faced so far is that you have ensure all your wrappers actually return an integer. Otherwise LuaJIT crashes when it calls a wrapped function. But you should return an from a integer function anyways, so it just encourages better code.

Tags

Rigid Body Dynamics Library

December 7, 2011

Hi there…

some time ago, I posted a video about my C++ implementation of the Articulated Body Algorithm (ABA), one of the best available algorithms available to perform forward dynamics computations on kinematic tree structures (if this sounds weird, replace “forward dynamics computations” by “physics simulations” and “kinematic tree structures” by “human-like figures” and you might be able to get a clue what you can do with it).

I mostly use it for my scientific work, which is funded by the Heidelberg Graduate School of Mathematical  and Computational Methods for the Sciences. I spent quite some time in programming it and making sure it does what it should (91 tests!).

Some highlights:

So far I am very happy with it and thought that maybe other can benefit from it as well.

Therefore I decided to publish it under an open-source license, namely the very permissive zlib license (which is also used by Bullet), which should allow pretty much anyone to do what he/she/it wants with it. However comments, suggestions or acknowledgements are still very welcome.

You can grab it at:

https://bitbucket.org/MartinFelis/rigidbodydynamicslibrary

It does feel a little weird to let it out into the wild, but I hope it is of use for anyone.

Martin

Quest for a GUI (or Simple GUIs for Games)

September 13, 2010

This post describes my quest for a simple graphical user interface for my Asteroids clone.

What has happened so far

In my Asteroids clone I had an extremely simple GUI in which one had to press specific keys in the main menu. Return started the game, ‘h’ showed the highscore and ‘q’ quit. When starting the game, the player was presented with a screen where he/she/it could enter a name, after pressing the return key the actual game would start. I encapsulated the drawing and the input processing in the class Overlay and had for each state (MainMenu, ShowHighscore, EnterPlayername) different subtypes of the Overlay class. This all worked okay for this very simple UI, however I wanted to have a proper menu where one could use the arrow keys and maybe even the mouse. For this, my previous approach would have to be hacked up that I wanted to avoid as I found having these multiple Overlay classes tedious. So there was a need for a proper GUI.

Related Work

The popular general-purpose GUI library Qt (read: “cute”) impressed me a lot, as it allows one to display Qt widgets within OpenGL as is demonstrated in this post. As Qt is well supported on major OS’ this was a big plus. Additionally Qt has a lot of tools for GUI creation and whatnot, however for my simple purpose this all would have been an overkill, as I merely need just a few buttons and maybe some text input. Still, the capabilities of the library were very impressive. The site http://labs.trolltech.com also has a lot of entries which talk about how to do OpenGL with Qt.

I needed a simple approach that would be able to render widgets within OpenGL if possible open-source. From earlier game GUI research I had a short look on libraries like CEGUI, clanlib, seemed too complicated for my simple purpose. GLUI is a little older however seems to work but did not look as intended for game user interfaces. There are a few more, such as GLAM and libUFO, that I had a short look at, however they also did not seem to be actively maintained for quite some time. GLGooey is also a bit dated however seemed quite nice concerning the programming interface. There are much more but nothing entirely catched me.

In the commercial world Scaleform, that uses Flash, seemed very interesting and powerful, however as no pricing was listed on their page it seemed doubtful it would be a price I would be willing to pay for my simple purpose. Additionally for a small amateur project this would not be the right choice as I want to mainly program a game, not design a super fancy user interface. Awesomium is used by Wolfire Games for the user interface and allows one to use HTML, Javascript and CSS for the Userinterface. Nice! However also costs money that would be too much for my purpose. (Note: Over on http://www.pathogenstudios.com they use Berkelium which is supposed to be similar to Awesomium and open-source, I just found when I already had my own solution for the GUI problem…).

Retained mode GUI

In a classical “retained mode GUI” (a.k.a. RMGUI) one creates Widgets, connects events such as “OnButtonPress”, “OnMouseHover”, “OnTextEnter” with callback functions that are processed whenever the events occur. This is also sometimes called event-driven. The created widgets are registered with some WidgetManager that checks whether the events have happened (e.g. checks whether the mouse is over a button and if it detects it was clicked, it reports a “OnButtonPress” event by calling the associated callback function). In the Qt library they created the Signal-Slot-mechanism just for that purpose.

As with everything, there is a catch. Implementing such a system is not straight forward. It usually results in quite a number of classes and one has to wire up all the callbacks to the events. Additionally for each action that should be performed by a button one needs a callback function. Qt does all this in a very convenient way, however implementing their Signal-Slot-mechanism would be too much for what I want to do.

The reasons why I don’t like this approach are that I don’t want to implement a whole widget managing system and additionally I would end up with a lot of small callbacks for the buttons in the menu. In the main menu most of them would only set the game state from MainMenu to ShowHighscore, eg. SetMainMenuState() and SetShowHighscoreState().

Immediate Mode GUI

I don’t know how I got there, but I read somewhere about “immediate mode GUIs” (a.k.a. IMGUIs). One of the main proponents is Casey Muratory from Molly Rocket. There is a video where he gives an introduction to IMGUIs. I had a short look at the first minutes of the video a few months ago, but then got distracted and forgot about it. A few weeks ago, however I stumbled over the tutorial of Jari Komppa. It gives a nice and clear introduction what the idea of IMGUIs are and how they work, along with sample code that uses the SDL and OpenGL, that convinced me my quest is over.

Basically one does not create widgets and connect them with callback functions, instead one only calls functions that perform the drawing and check simultaneously whether certain events have happened. As logic for differs for each widget type one has for each widget type one function. For widgets like buttons or a text edit this function would return true if the button was pressed or the text was changed, respectively.

When drawing your UI this results in code of the form (example for a button):

if (IMGUI_button (StartButtonId, "Start", x, y, w, h)) {
	SetGameState (GameStateEnterPlayerName);
}

The only thing here that might arise questions is the StartButtonId. This can be any value other than 0 and must not collide with the Id of another widget that should be visible on the screen.

From the programmers point of view, a text edit could look like this:

char *name_value = GetPlayerName(name_value);
if (IMGUI_textedit (TextEditId, name_value, 32, x, y, w, h)) {
    SetPlayerName(name_value);
}

That’s it! This simple line displays and allows modification of the player name!

You have to pass a pointer (or in C++ maybe a reference) of the string that should be displayed and modified, the maximum length of the string and the position and size of the edit widget. There is still some code that needs to be called at the beginning and the end of the frame, but this is everything you need to do for the widget.

A huge advantage of this is, that for a programmer it is very easy to read. Also it is very easy to build interfaces for the most common menus, including settings screen with sliders, text edits, checkboxes and whatnot. Even for handling input of the mouse and keyboard simultaneously it is the same code!

But also IMGUIs have their flaws (of course!). They require a high framerate as there is always a 1 frame latency (e.g. for text entries). However if you redraw your screen anyways (as I am currently doing it) this should be okay.

IMGUI vs RMGUI

One might ask, why not everyone is using this approach. There is also a quite long discussion about IMGUI vs. RMGUI over on GameDev (http://www.gamedev.net/community/forums/topic.asp?topic_id=545995). Most criticisms are:

Efficiency is not a problem for me, as neither my game nor my current GUI even remotely scratch on the hardware limits. Of course it is very simple, but I won’t optimize here before it is necessary.

My current GUI designer is actually very happy with the IMGUI approach. However my GUI designer also knows how to program, so I might be in a very prestigious position, but this might be alleviated that I *am* my GUI designer.

“Paradigms used by IMGUIs is anachronistic”? Well … so what? This doesn’t mean I have to do everything in a anachronistic way. Additionally the IMGUI plays very well together with a MVC for which the state of the UI is stored in the Controller and the drawing is performed in the View. (Okay, this might be put a little too optimistic, as the drawing functions do modify the UI state, however in this case a tighter coupling between the View and the Controller is okay in my opinion).

Conclusion

So in total IMGUIs might not be perfect for everyone, but should you be an amateur game programmer and want to add a GUI with keyboard and mouse support, I highly recommend giving it a shot! IMGUIs are very easy to implement and should you really need something more sophisticated, you can still switch to something else. But I guess you probably won’t. Some poeple are actually very happy with this approach of GUI programming, see here: http://blogs.unity3d.com/2009/08/17/doing-a-talk-at-gdc-europe-tomorrow/.

I plan to write up a small sample library under a liberal open-source library that can be modified to your needs. You will read about it somewhere on this blog.

Further Reading

Tags

Blinking Cursors

July 16, 2010

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!

Tags

Premature code and binary LEAKED*!

April 9, 2010

The worst possible happened: the source code an even a buggy windows version version of my asteroids clone leaked to the internet! It took me quite long to finally get it run under windows and now that hard work simply pops up in the internet… I don’t know what to say. I fear it is probably an evil German hacker, just like in the 2003 leak of the Half-life 2 source. Tough times, I’d say…

Apart from that I am actually quite happy to get it finally run on windows. On the way there I ran into quite a few obstacles. I tried to use portable tools and libraries (CMake, freetype, OpenGL, SDL, libpng, boost), however getting them compiled and correctly linked in Visual Studio Express 2008 took quite some time. I also used a few precompiler #defines that were not supported by the Microsoft compiler (e.g. used __func__ instead of __FUNCTION__). There also was a critical bug that would make my game crash under Windows but not under GNU/Linux which was caused of improper initialization of a variable. The biggest hassle in the end was however getting it compiled so that it can be run on a computer on which it wasn’t compiled as there are some dependancies on the redistributable runtime libraries of Visual C++. I hope this is solved in the uploaded binary.

When you look at the asteroids.rc file you can mess around with some variables of the game (such as ship acceleration, maximum speed, etc.) and also set the controls the way you like it (so far only keyboard). Oh and there is also a very basic console (to access it press F8) with which you can run simple commands such as the ones in the asteroids.rc file.

For those who want to have a look at it here are the official links to the “leaked” versions ;D:

Known issues so far:

explosion of an innocent ship

(buggy) explosion of an innocent ship

*too bad 1st of april has been already 9 days ago

Tags