Jump to content

  • Log In with Google      Sign In   
  • Create Account

Pixel → Tile → World

Code snippet for typesafe void* userdata

Posted by , in Code snippets 28 July 2013 - - - - - - · 1,292 views
Just tossed this piece of code together - it wraps void* points with asserts() to ensure you are getting the same type that you originally set.
Normally I shy away from void* pointers as I feel like they are indicators of bad design, but sometimes you need to use them, and when you do, they might as well be type-safe.

This is kinda a lightweight alternative to boost::any, but not designed by a peer-reviewed team of professionals who also have seats on the C++ standards committee. Posted Image

Requires C++11's typeid(), and RTTI enabled.
#include <typeinfo>
#include <vector>
#include <cassert>
//Quick macro to replace my real Assert() function, just for this file.
#define Assert(condition, message) assert(condition && message)
//Holds any type of user-given pointer that can be cast to void, and does run-time checks on the type of the data when retrieving it.
//Ownership is *not* taken. It is the original owner's responsibillity to ensure the lifetime of the object when
//someone tries to retrieve the pointer later. The Userdata class itself never de-references the pointer.
class Userdata
    Userdata() = default;
        template<typename UserType>
        Userdata(UserType *data)
        //Sets a user-spe
        template<typename UserType>
        void Set(UserType *data)
                //Save the pointer (cast to void*), and the type's RTTI information, so we can validate on retrieval.
                this->type_info = &typeid(UserType);
                this->userdata = data;
        template<typename UserType>
        UserType *Get()
                //Validate that we've actually set *anything*.
                Assert(this->type_info, "We never set any data, so we can't retrieve any.");
                //Validate that we are getting the same type that we initially set.
                Assert((*this->type_info) == typeid(UserType), "The types don't match - we can't retrieve the userdata safely.");
                return static_cast<UserType*>(this->userdata);
        void Reset()
                this->type_info = nullptr;
                this->userdata = nullptr;
        //A pointer to the global compiler-specific (but standardized) type_info for this type (the type that Userdata's void* points to).
        //C++11 guarantees that "The lifetime of the object referred to by [typeid()'s return value] extends to the end of the program." (N3337 5.2.8)
        const std::type_info *type_info = nullptr; 
        //A pointer to the user-defined data.
        void *userdata = nullptr;
//Manages a FILO stack of void pointers in a type-safe way.
//This class does not take any ownership of the data pointed to.
class UserdataStack
        UserdataStack() = default;
        ~UserdataStack() = default;
        template<typename UserType>
        void Push(UserType *userdata)
        template<typename UserType>
        UserType *Get()
                Assert(!this->stack.empty(), "The stack is empty - we can't retrieve any userdata.");
                return this->stack.back().Get<UserType>();
        void Pop()
    //Pops the stack, and returns the pointer previously pointed to.
    template<typename UserType>
        UserType *Take()
                UserType *data = this->Get<UserType>();
                return data;
        void Clear()
        std::vector<Userdata> stack;
Compilable code on Ideone.com

Note: By design, the Userdata/UserdataStack classes don't take ownership of the data. I guess that's another difference than with boost::any - though you could always just pass boost::any some pointers.

Tiny bit of art, some programming talk

Posted by , in AdventureFar, Pixel art, Code snippets 21 July 2013 - - - - - - · 1,105 views
Here's a few pieces of art I made for my game, in between programming.

Stone fence
Attached Image

I just finished this a few minutes ago - it took about an hour.

Attached Image

I guess about a week ago? Maybe two.


Didn't get anything done today - rather lazy. Still have a few hours left in the day, so I'm going to crack back into the code for a bit more work.

Yesterday and the day before I made great progress finally figuring out a good resource-management system for my game. This is after a week or two of false-starts, and several concepts drawn on paper over the past few months. The end result isn't anything special - but all my prior attempts were either too limiting in capability, or else too generalized to be useful. I've gotten it mostly working already, and yesterday I started connecting it up to the old area-drawing code that I haven't seen in several months. I'm happy with the area-drawing code - it's still stable and clean - but the tile-drawing and image-sharing code that I was replacing just was too clunky.

One bit of code I'm somewhat proud of is a new serializing system I wrote up to replace my old one. The new one is more reusable and a pleasure to use, though there is one annoying thing I'd like to fix later.

The new serializer is heavily template-based for great flexibility, observe:
struct MyStruct
	std::tuple<std::pair<std::string, int>, float, std::vector<std::string> > tupleOfPairsAndVectorsOfStrings;
	float otherStuff;

//Template specialization for serializing 'MyStruct'.
size_t Serialize<MyStruct>(Serializer &serializer, MyStruct &tileDetails, size_t pos)
	//Automaticly calls the overload for floats.
	pos = Serialize(serializer, tileDetails.otherStuff, pos);
	//Automaticly calls the overload for tuples, which in-turn calls the overload for each tuple's member,
	//which in this case calls the overload for std::pair<> which then calls the overload for std::string and int,
	//and also calls the overload for std::vector, which calls on each element the overload for std::string.
	pos = Serialize(serializer, tileDetails.tupleOfPairsAndVectorsOfStrings, pos);
	//Sound slow? Not when you remember template functions are resolved at compile-time. =P
        //It shouldn't be any slower than most other serializing methods.
	return pos;

class Foo
	//Calling Serialize() on class 'Foo' automaticly detects that Foo has a Foo::Serialize() function, and calls that instead.
	size_t Serialize(Serializer &serializer, size_t pos)
		//Calls the Serialize() function for vectors... which automaticly detects the type of element in the vector,
		//and calls Serialize<ElementType>() for each element in that vector.
		return Serialize(serializer, this->arrayOfStructs, pos);
	std::vector<MyStruct> arrayOfStructs;
While not intentional, I think it's also loads faster than my old class, which is a nice plus. I haven't profiled it yet to see.

Better still, I don't have to code almost-identical read and write serializing functions for classes - just one function, that reads OR writes, using the same code. Serialize() depending on the nature of the Serializer passed in, reads or writes using the same functions. And without a bunch branching statements - it redirects to the read or write function using a function pointer.

Using a function-pointer also allows me to redirect to Safe or Fast read functions at run time (or for individual pieces of code), depending on the requirements of the program. If I want to, I could later also add Encrypted read/write functions, or Compressed read/write functions, without changing any existing code, but by just adding the new functions to the Serializer class that handles the incoming bytes.

Easing along, one step at a time

Posted by , in Code snippets 02 March 2013 - - - - - - · 2,416 views
interpolation, easing, tweening
I just finished adding some of the standard Ease equations to my code base for use in Of Stranger Flames.
In discussion about the equations, it was requested for me to share the code here. This is not a tutorial, I don't have enough familiarity with the subject (or with math in general) to explain how every equation works. I'm just posting what I added to my own code, so others can use it if they want to.

The equations are mostly from Robert Penner's eases, which are under the BSD license. His code seems to be the ones that are used by most software, such as the jQuery, Flash, and other libraries.

Most Ease equations have the function signature:
void equation(currentTime, start, distance, totalTime);
I personally like having my eases in start at 0.0, end at 1.0, and have a 'duration' of 1.0, and then I scale the input and output as desired, instead of having the equation scale it. It just makes it easier for me to understand.

That said, all my functions have the format:
void equation(position);
...with 'position' being from 0.0 to 1.0.

Because Eases come in various forms (You can ease IN, OUT, IN and OUT, or OUT and IN), I made sure all the ease equations were in EaseIn form, and I created a few functions to convert the input and output to the other forms as desired.

Here's the conversion code:
http://ideone.com/6rc0Zk (Posted as links, because all my code kept getting unformatted when hitting 'publish')

EaseFunction is: "typedef std::function<float(float)> EaseFunction;", which nicely permits the use of things like lambdas and functors as well as the regular ease functions. If you don't have C++11, you can just typedef it as: "typedef float(*EaseFunction)(float);" or whatever the correct C-style function-pointer syntax is.

Some of the ease equations have a few extra parameters, like ElasticEase and BackEase, so I provided some C++11 templates to convert the functions to std::functions that meet the function signature shared by the other functions. It's just a wrapper around std::bind for convenience. (I'm big on convenience! Posted Image)

You don't have to use C++11 to use the equations! Just the helper functions above.

I also use this function for scaling the output:

Actually, mine looks like this:
...but that depends on a 'FloatRange' helper class I made, whereas the previous one has no dependencies.

I actually made two ScaledEase overloads, one for my Point class, and one for my Color class. I haven't tested those out yet. Posted Image

I also made a Easer class, that handles most of everything inside of it. This is more for when you want persistent ease data wrapped nicely, and this class would be a member-variable of another class.


That also uses FloatRange, but can be easily adjusted to just use 'float begin' and 'float end' instead.

The Ease Equations
And here are a few additional ones I keep inline

The next page has graphs generated to test/demonstrate the output.

Recent Entries

Recent Comments

Latest Visitors