Macro Lists For The Win – Side B

Example Code: Code_050713.zip

In the previous post I talked about how you can use macro lists to solve the problem of wanting to generate a bunch of code based on the same set of data. This was useful for doing things like defining a list of resources a player could accumulate, and then being able to generate code to store and manipulate each resource type. You only had to update the resource list to add a new resource and the rest of the code would almost magically generate itself.

What if you wanted the reverse though? What if you had a fixed set of code that you want to apply to a bunch of different sets of data? This post is going to show you a way to do that.

In the example code, we are going to make a way to define several lists of items, and expand each list into an enum that also has a ToString and FromString function associated with it.

Another usage case for this technique might be to define lists of data fields, and expand each list into a data structure that contains serialization and deserialization functions. This would allow you to make data structures that could be saved and loaded to disk, or to sent and received over a network connection, just by defining what data fields they contained.

I haven’t yet seen this technique in the wild, and it kind of makes me wonder why since they are just two sides of the same coin.

GameEnums.h

In the last post, our data was always the same and we just applied it to different code. To do this, we had the code in one .h and the data in another .h that would get included multiple times. This allowed us to define different pieces of code in one .h, then include the other .h file to apply the fixed data to each piece of code.

In this post, it’s going to be the exact opposite. Our code will always stay the same and we will apply it to different data so our data will be in one .h and the code will be in another .h that gets included multiple times.

Here’s GameEnums.h:

//////////////////////
//     EDamageType
//////////////////////
#define ENUMNAME DamageType
#define ENUMLIST 
	ENUMENTRY(Normal) 
	ENUMENTRY(Electricity) 
	ENUMENTRY(Fire) 
	ENUMENTRY(BluntForce)

#include "EnumBuilder.h"
//////////////////////
//     EDeathType
//////////////////////
#define ENUMNAME DeathType
#define ENUMLIST 
	ENUMENTRY(Normal) 
	ENUMENTRY(Electrocuted) 
	ENUMENTRY(Incinerated) 
	ENUMENTRY(Smashed)

#include "EnumBuilder.h"
//////////////////////
//     EFruit
//////////////////////
#define ENUMNAME Fruit
#define ENUMLIST 
	ENUMENTRY(Apple) 
	ENUMENTRY(Banana) 
	ENUMENTRY(Orange) 
	ENUMENTRY(Kiwi)

#include "EnumBuilder.h"
//////////////////////
//     EPlayers
//////////////////////
#define ENUMNAME Player
#define ENUMLIST 
	ENUMENTRY(1) 
	ENUMENTRY(2) 
	ENUMENTRY(3) 
	ENUMENTRY(4)

#include "EnumBuilder.h"

EnumBuilder.h

This header file is where the real magic is; it’s responsible for taking the previously defined ENUMNAME and ENUMLIST macros as input, and turning them into an enum and the string functions. Here it is:

#include  // for _stricmp, for the enum Fromstring function

// this EB_COMBINETEXT macro works in visual studio 2010.  No promises anywhere else.
// Check out the boost preprocessor library if this doesn't work for you.
// BOOST_PP_CAT provides the same functionality, but ought to work on all compilers!
#define EB_COMBINETEXT(a, b) EB_COMBINETEXT_INTERNAL(a, b)
#define EB_COMBINETEXT_INTERNAL(a, b) a ## b

// make the enum E
#define ENUMENTRY(EnumValue) EB_COMBINETEXT(e, EB_COMBINETEXT(ENUMNAME, EnumValue)),
enum EB_COMBINETEXT(E,ENUMNAME) {
	EB_COMBINETEXT(EB_COMBINETEXT(e, ENUMNAME), Unknown) = -1,
	ENUMLIST
	EB_COMBINETEXT(EB_COMBINETEXT(e, ENUMNAME), Count),
	EB_COMBINETEXT(EB_COMBINETEXT(e, ENUMNAME), First) = 0,
	EB_COMBINETEXT(EB_COMBINETEXT(e, ENUMNAME), Last) = EB_COMBINETEXT(EB_COMBINETEXT(e, ENUMNAME), Count) - 1
};
#undef ENUMENTRY

// make the EToString function
const char *EB_COMBINETEXT(EB_COMBINETEXT(E,ENUMNAME), ToString)(EB_COMBINETEXT(E,ENUMNAME) value)
{
	switch(value)
	{
		#define ENUMENTRY(EnumValue) 
			case EB_COMBINETEXT(e, EB_COMBINETEXT(ENUMNAME, EnumValue)): 
			return #EnumValue;
		ENUMLIST
		#undef ENUMENTRY
	}
	return "Unknown";
}

// make the EFromString function
EB_COMBINETEXT(E,ENUMNAME) EB_COMBINETEXT(EB_COMBINETEXT(E,ENUMNAME), FromString)(const char *value)
{
	#define ENUMENTRY(EnumValue) 
	if(!_stricmp(value,#EnumValue)) 
		return EB_COMBINETEXT(e, EB_COMBINETEXT(ENUMNAME, EnumValue));
	ENUMLIST
	#undef ENUMENTRY
	return EB_COMBINETEXT(EB_COMBINETEXT(e, ENUMNAME), Unknown);
}

// clean up
#undef EB_COMBINETEXT
#undef EB_COMBINETEXT_INTERNAL

// these were defined by the caller but clean them up for convinience
#undef ENUMNAME
#undef ENUMLIST

Main.cpp

Now, here’s how you can actually use this stuff!

#include "GameEnums.h"

int main(int argc, char* argv[])
{
	EDamageType damageType = eDamageTypeBluntForce;
	EDeathType deathType = EDeathTypeFromString("smashed");
	EFruit fruit = eFruitLast;
	EPlayer player = EPlayerFromString(EPlayerToString(ePlayer1));
	return 0;
}

Combining the files

As a quick aside, in both this and the last post, I separated the code and data files. This is probably how you would normally want to do things because it’ll usually be cleaner, but it isn’t required. Here’s a cool technique I came across today…

Here’s Macro.cpp:

#ifdef MACROHEADER
	// Put your header stuff here
#else
	// Put cpp type stuff here

	// Include the "header"
	#define MACROHEADER
	#include "Macro.cpp"
	#undef MACROHEADER
#endif

If you ever really just want to combine all your code and data into a single file and not muddy up a directory or project with more files, this technique can help you do that. IMO you really ought to just use separate files, but I wanted to share this for when there are exceptions to that rule (as there always seem to be for every rule!)

Being Data Driven

After my last post, a fellow game developer friend of mine pointed out..

I hope that one day we hurl C++ into a raging sea of fire.

I do like this technique, in theory at least, but whenever I feel like it’s the right solution, a voice in the back of my head yells that I’m digging too greedily and too deeply and should step back for a second and consider what design choices have lead me to this point.

And I think that usually that introspection ends up at the intersection of “we’re not data-driven enough but want to be” and “we decided to use C++ for our engine.”

— jsola

He does have a point. For instance, in the case of our resource list from last post, it would be better if you had some “source data”, such as an xml file, listing all the resources a player could have. The game should load that data in on startup and make a dynamic array, etc to handle those resources. When you had game actions that added or subtracted specific resources from a player, the details of which resources got modified, and by how much, should also be specified in data.

When you save or pack your data, or at runtime (as your situation calls for), it can verify that your data is well formed and makes sure that if a data field is meant to specify a resource type, that it actually corresponds to an actual resource type listed in the list of resources.

That is closer to the ideal situation when making a game – especially when making larger games with a lot of people.

But there are still some good usage cases for this kind of macro magic (and template metaprogramming as well). For instance, maybe you use macros to define your data schemas so that your application can be data driven in the first place – I’ve done that on several projects myself and have seen other well respected people do it as well. So, add these things to your toolbox I say, because you never know when you might need them!

Next Post…

The next post will be what i promised at the end of the last one. I’m going to talk about a way to define a list of lists and then be able to expand that list of lists in a single go, instead of having to do a file include for each list individually.

Example Code: Code_050713.zip

Macro Lists For The Win

Around 6 years ago I was introduced to a programming technique that really blew my mind. John, My boss at the time and the tech director at inXile, had written it as part of the code base for the commercial version of a game called Line Rider and I believe he said he first heard about the technique from a friend at Sony.

Since seeing it at inXile, I’ve seen the same technique or variations on it at several places including Monolith and Blizzard, and have had the opportunity to use it on quite a few occasions myself.

What is this technique? I’m not sure if it has an actual name but I refer to it as “Macro Lists” and it’s a good tool towards achieving the DRY principle (don’t repeat yourself – http://en.wikipedia.org/wiki/Don’t_repeat_yourself)

Macro lists are often useful when you find yourself copy / pasting code just to change a couple things, and have multiple places you need to update whenever you need to add a new entry into the mix.

For example, let’s say that you have a class to store how much of each resource that a player has and lets say you start out with two resources – gold and wood.

To implement this, you might write some code like this:

enum EResource
{
	eResourceGold,
	eResourceWood,
};

class CResourceHolder
{
public:
	CResourceHolder()
	{
		m_resources[eResourceGold] = 100.0f;
		m_resources[eResourceWood] = 0.0f;
	}

	float GetGold() const
		{ return m_resources[eResourceGold ]; }
	void SetGold(float amount)
		{ m_resources[eResourceGold ] = amount; }

	float GetWood() const
		{ return m_resources[eResourceWood]; }
	void SetWood(float amount)
		{ m_resources[eResourceWood] = amount; }
private:
	float m_resources[2];
};

That seems pretty reasonable right?

Now let’s say that you (or someone else who doesn’t know the code) wants to add another resource type. What do you need to do to add a new resource?

  1. Add a new enum value to the enum
  2. Initialize the new value in the array to zero
  3. Make a Get and Set function for the resource
  4. Increase the array size of m_resources to hold the new value

If #1 or #3 are forgotten, it will probably be really obvious and it’ll be fixed right away. If #2 or #4 are missed though, you are going to have some bugs that might potentially be very hard to track down because they won’t happen all the time, and they may only happen in release, or only when doing some very specific steps that don’t seem to have anything to do with the resource code.

Kind of a pain right? As the code gets more mature and more features are added, there will likely be other places that need to be updated too that will easily be forgotten. Also, when this sort of stuff comes up, people tend to copy/paste existing patterns and then change what needs to be changed – which can be really dangerous if people forget to change some of the values which need to be changed.

Luckily macro lists can help out here to ensure that it’s IMPOSSIBLE for you, or anyone else, to forget the steps of what to change. Macro lists make it impossible to forget because they do the work for you!

Check out this code to see what I mean. It took me a little bit to wrap my head around how this technique worked when I first saw it, so don’t get discouraged if you have trouble wrapping your head around it as well.

#define RESOURCE_LIST 
	RESOURCE_ENTRY(Gold, 100.0) 
	RESOURCE_ENTRY(Wood, 0)

// make the enum
#define RESOURCE_ENTRY(resource, startingValue) 
	eResource#resource,
enum EResource
{
	eResourceUnknown = -1,
	RESOURCE_LIST
	eResourceCount,
	eResourcefirst = 0
};
#undef RESOURCE_ENTRY

class CResourceHolder
{
public:
	CResourceHolder()
	{
		// initialize to starting values
		#define RESOURCE_ENTRY(resource, startingValue) 
			m_resources[eResource#resource] = startingValue;
		RESOURCE_LIST
		#undef RESOURCE_ENTRY
	}

// make a Get and Set for each resource
#define RESOURCE_ENTRY(resource, startingValue) 
	float Get#resource() const 
	{return m_resources[eResource#resource];} 
	void Set#resource(float amount) 
	{m_resources[eResource#resource] = amount;} 
RESOURCE_LIST
#undef RESOURCE_ENTRY

private:
	// ensure that our array is always the right size
	float m_resources[eResourceCount];
};

In the above code, the steps mentioned before happen automatically. When you want to add a resource, all you have to do is add an entry to the RESOURCE_LIST and it does the rest for you. You can’t forget any of the steps, and as people add new features, they can work with the macro list to make sure people in the future can add resources without having to worry about the details.

Include File Variation

If you used the above technique a lot in your code base, you could imagine that someone might name their macros the same things you named yours which could lead to a naming conflict.

Keeping the “global macro namespace” as clean as possible is a good practice to follow and there’s a variation of the macro list technique that doesn’t pollute the global macro namespace like the above.

Basically, you put your macro list in a header file, and then include that header file every place you would normally put a RESOURCE_LIST.

Here’s the same example broken up that way. First is ResourceList.h:

///////////////////////////////////
//	RESOURCE_ENTRY(ResourceName, StartingValue)
//
//	ResourceName - the name of the resource
//	StartingValue - what to start the resource at
//
RESOURCE_ENTRY(Gold, 100.0)
RESOURCE_ENTRY(Wood, 0)
///////////////////////////////////

And now here is CResourceHolder.h:

///////////////////////////////////
// make the enum
#define RESOURCE_ENTRY(resource, startingValue) 
	eResource#resource,
enum EResource
{
	eResourceUnknown = -1,
	#include "ResourceList.h"
	eResourceCount,
	eResourcefirst = 0
};
#undef RESOURCE_ENTRY

class CResourceHolder
{
public:
	CResourceHolder()
	{
		// initialize to starting values
		#define RESOURCE_ENTRY(resource, startingValue) 
			m_resources[eResource#resource] = startingValue;
		#include "ResourceList.h"
		#undef RESOURCE_ENTRY
	}

// make a Get and Set for each resource
#define RESOURCE_ENTRY(resource, startingValue) 
	float Get#resource() const 
	{return m_resources[eResource#resource];} 
	void Set#resource(float amount) 
	{m_resources[eResource#resource] = amount;}
#include "ResourceList.h"
#undef RESOURCE_ENTRY

private:
	// ensure that our array is always the right size
	float m_resources[eResourceCount];
};

The Downside of Macro Lists

So, while doing the above makes code a lot easier to maintain and less error prone, it comes at a cost.

Most notably is it can be really difficult to figure out what code the macros will expand to, and it can be difficult to alter the functionality of the macros. A way to lessen this problem is that you can tell most compilers to make a file that shows what your code looks like after the preprocessor is done with it. It can still be difficult even with this feature, but it does help a lot.

When you have compiler errors due to macros, because perhaps you forgot a parameter, or it’s the wrong type, the compiler errors can be pretty difficult to understand sometimes.

Another problem with macros is that I don’t know of any debuggers that will let you step through macro code, so in a lot of ways it’s a black box while you are debugging, which sucks if that code malfunctions. If you keep your functionality simple, straightfoward and format it cleanly, you ought not to hit many of these problems though.

Instead of using macro lists, some people prefer to put their data into something like an xml or json data file, and then as a custom build step, use XSLT or the like to convert that data into some code, just like the C++ preprocessor would. The benefit here is that you can see the resulting code and step through it while debugging, but of course the downside is it can be more difficult for someone else to get set up to be able to compile your code.

To Be Continued…

Macro lists are great, but what if you want your lists to have sublists? For instance, what if you wanted to define network messages for your game in a format like this, and have it automatically expand into full fledged classes to be able to ensure that message parsing and data serialization was always done in a consistent way to minimize bugs and maximize efficiency (less code to write and less testing to do)?

As you might have noticed, macro lists can take parameters to help them be flexible (like, the starting value of the resources… you could add more parameters if you wanted to), but, a macro list can’t contain another macro list. At least not how the above implementations work.

I’m going to show you how to tackle this problem in the next post, so stay tuned! (:

Permutation Programming Without Maintenance Nightmares

Example Code: TemplateSlots.cpp

When writing real time software, we sometimes hit situations where we have code that needs to be lightning fast, but also needs to be configurable to change how it behaves.

For instance, if you are writing something that renders 3d graphics (either traditional rasterized 3d graphics, or raytraced 3d graphics) you might be forced to put an if statement in a deep inner loop saying “is this object textured? Does this object have emissive lighting? If so, call the appropriate functions”.  Or, in the case of something like DSP / Audio processing, you might have an if statement saying “do we need to increase the amplitude of our samples?  if so do that”.

Depending on your use case, this can result in tens of thousands of checks per second or more, which can impact performance quite a bit.

This puts us in a pickle between two extremes:

  1. We can decide to live with the the checks to see which functionality is enabled.  The end result is code that is easy to maintain, but it comes at a cost in execution speed.
  2. We can hand craft each permutation of functionality needed, and call the correct function based on parameters in an outer loop. For example, in an outer loop, we call a function like “RenderPolygonNoTextureYesEmissive”.  This means that we copy / paste a lot of code and change small pieces of each function to act like it should for the specific permutation.  This results in form fitted code that can be a lot faster, but will be harder to maintain.

Someone might look at the above and say “#1 makes slower code that is easier to maintain?  Programmers need to stop being lazy and just go with #2 so that it’s faster at runtime”.  When code is easier to maintain though, it means that programmers can spend less time working on bugs and features in this code, freeing them up to work on other things, and also it means that there will be less bugs in the code to begin with.  Making code that’s easier to maintain is a decision that affects team productivity and the business as a whole, so it isn’t something we can very easily dismiss, even at the cost of runtime performance.

Quick aside: there are features in modern CPUs like branch prediction, as well as features in modern compilers / linkers / optimizers that can mitigate some of this stuff, but they can’t always, and if you rely on the behavior of a specific compiler or CPU, you’ll have code maintenance problems when you have to start supporting a different compiler or CPU.  Console and mobile processors are very different beasts than desktop processors for example, which can make relying on assumptions like this a big problem.

One common solution to the code permutation problem is to generate code for all the permutations needed to get the speed of solution #2, but have that code generated based on a few core pieces of code to get the maintainability of solution #1.   People can do this with clever macro usage, or even actually generate code using a custom build step while compiling.

In the graphics world, it’s fairly common that AAA game engines actually have a shader permutation compiler built into the engine to handle this exact problem.  The situation there is a little bit different because shaders aren’t written in C++, but it’s the same basic problem.

I’m going to show a variation to the code generation solution using templates, template parameters, and inline functions.

Before we get into it I want to note two important things:

  • All observations I make about function inlining and optimizations preformed by the compiler were made using Microsoft Visual Studio 2010 using the default settings for a release built console application.  Your mileage may vary!
  • The example code attached to this post works as a makeshift compressor and limiter.  That DSP code is just there as an example of using this technique and this should in no way be used as a lesson on how to write a compressor or limiter.  Many features are missing and major shortcuts have been taken to keep the code simple!

OOPS!

After posting this, a friend pointed out two things to me that I want to share…

  1. Apparently this technique is already well known and used. It’s called “traits” and it’s talked about in the book Modern C++ Design by Andrei Alexandrescu.
  2. The sample code doesn’t seem to compile in llvm or clang. I don’t have easy access to those guys so… sorry about that.

Inline Functions – The Silent Killer

Ok, I’m joking, inline functions aren’t the #1 cause of death for males between the age of 23 and 25.

When people talk about using inline functions, they always seem to only talk about how inline functions remove the overhead of the function call, setting up the stack for the local parameters, the cost of the return, and any object copies that might have happened for the parameters or return value.

A far less talked about feature of inline functions is that it promotes the function code to be a full sibling to the calling code in the eyes of the optimizer.

If your inlined function checks a boolean parameter to take different action whether it’s true or false, and you call that inlined function using a compile time constant for that parameter (ie just pass “true” , not a variable), that means that the optimizer has the opportunity to completely get rid of the branch of code that will never get executed and get rid of the if statement all together.  The optimizer just ditched the inner loop “if check” we talked about earlier that was happening tens of thousands of times a second.

If you call the same inlined function in another place, passing a boolean variable for the parameter, that other location will keep the if statement intact and will act as you would expect.

This is the first step in our battle against code permutations – inline functions can be used to write code once that shrink wraps itself to whatever your specific use cases may be!

This also gives the optimizer the ability to combine various pieces of  code together in clever ways, especially if you call multiple inline functions and it has more code to work with.

Not All Unicorns and Lollipops – Code Bloat and Cache Misses

Inline functions do come at a cost though and are not a magical solution to every problem.  Most notably, inline functions bloat the size of your compiled code.  For most people, code size on disk isn’t really a huge problem because hard drives are huge and loading an exe sized file into ram is not going to be a problem for normal cases.

The problem with increasing code size mainly comes up when dealing with the instruction cache.

Processors have built in cache memory that they can read and write to super quickly, but the cache memory can only hold so much data.  Whenever the processor needs to read something from RAM that isn’t in the cache, it has to load it from RAM into the cache, and then it can read it.  This is called a cache miss and can a major source of performance problems.  Desktop CPUs can get around this problem by doing other things while waiting for the data to come in (http://en.wikipedia.org/wiki/Out-of-order_execution), but other processors like consoles and mobile devices aren’t able to do that, so they just sit there stalled while waiting for the memory to come back.  Very slow!

To minimize cache misses, you should set up your code and data structures so that they don’t have to jump around in memory a lot, which can cause the CPU to have to load and unload the same peices of RAM into the cache needlessly.

Another thing you can do to minimize cache misses is to try to make your data as small as possible by storing less data or using smaller data types.  This way, the CPU is able to hold more meaningful data in it’s cache at a time, which means less RAM access needed.

These techniques also apply to your program itself inside the instruction cache.  If you have code that jumps around a lot (e.g. gotos that jump really far away for those that use gotos, or excessive function calls), that can cause the CPU to have to excessively load different parts of your program from RAM into it’s cache which can be a costly operation.   Also just like with data, if you keep your code smaller, the CPU will be able to hold more meaningful data in the cache at a time and have to hit RAM less.

Lastly, if you ever make a for or while loop that is too large to fit in the instruction cache, that means that you can get a cache miss each time you iterate through the loop!  Making functions inlined, especially if they are called multiple times inside of the loop, can cause the contents of a loop to become larger and cause this problem.

In the end though, if you’d like you can just mark your functions as inline and let the compiler decide if it would like to actually inline them or not since it’s just a hint.  A lot of the times the compiler ought to make decent choices for you, but of course you are free to go down into this rabbit hole as you want.  Since the compiler doesn’t actually understand your algorithm, you can certainly do better than it can in some situations and make better trade offs. In MSVC there is an option to disallow the compiler from going against your wishes for inlining a function if you want to go this route. Other compilers probably have similar options.

The Main Course – Templated Classes With Worker Slots

Now that you see how inline functions can be used to write custom fitting code permutations for you, you can use this to your advantage by having the class or function that does your work take a template parameter for each piece of configurable work that you would like it to do.

You might define a class like this:

template <class EmissiveLighter, class Texturer>
class CRenderer
{
public:
	static void Render(const CSomeDummyParams &params)
	{
		// render
		...
		// now apply emissive lighting and texture
		EmissiveLighter::ApplyEmissive(params);
		Texturer::ApplyTexture(params);
	}
};

Then, you might define “Slot Classes” like the below

//do nothing for emissive lighting and pay no runtime cost for using this
class EmissiveLighter_None
{
public:
	static inline void ApplyEmissive(const CSomeDummyParams &) {}
};

//apply the emissive color defined in the params struct
//Note, we are using templates but not interfaces so the parameter declarations can change to suit our needs
class EmissiveLighter_Params
{
public:
	static inline void ApplyEmissive(CSomeDummyParams &params)
	{
		params.m_outColor += params.m_emissive;
	}
};

Now, you can call the render function and supply what operations you want to use for each slot and it will generate the form fitted permutations for you.

// no emissive lighting, no texture
Render<
	EmissiveLighter_None,
	Texturer_None>
	::Render(params);

// emissive lighting from params, no texture
Render<
	EmissiveLighter_Params,
	Texturer_None>
	::Render(params);

// emissive lighting from params, texture from params
Render<
	EmissiveLighter_Params,
	Texturer_Params>
	::Render(params);

// emissive lighting from params, use procedural noise texture generator
Render<
	EmissiveLighter_Params,
	Texturer_ProceduralNoise>
	::Render(params);

Also, a quick note… templates also cause code bloat like inline functions do, because behind the scenes, it will create a different class for each permutation of template parameters that you actually use.  Just something to be wary of!

Why No Interface Classes?

You might be saying “you know, you could make an interface class with pure virtuals to make sure that your slot classes implemented the required functions in the required ways.  That would increase type safety and such”.

That is definitely true, but in this case I think there is actually good value in NOT making interface classes that the various slot classes derive from.

To see what I mean, check out the difference between the two emissive lighter classes i defined.  One takes the params parameter as a const reference, and the other takes it as a non const reference.  This lets you decide what you want to do with the parameters on an implementation by implementation basis.

This lets you give further optimization hints to the compiler, allowing you to define unused parameters as const refs.

It lets you further “shrink wrap” the code to suit your specific needs in each permutation, and you still get a lot of compile time protection when you use the type in a template.

Last Words

If you go this route, it definitely could make some issues more difficult to debug, especially if you stray from the straight and narrow usage. For instance, you might make the EmissiveLighter_Params set some value on the params that the Texturer_Params uses because Texturer_Params assumes that emissive will always use params too when texture params is used. If you switch the emissive to something else but leave the texturer alone, the texturer could stop working and it could be hard to realize why. My advice if using this technique is to make each slot class as isolated as possible and make as few assumptions as possible about other slots. Also make sure and name slot classes so that it’s very obvious what they do from the name and make sure they don’t do anything other than the name implies. If they do anything else, change the name to reflect that! Don’t worry about not being able to share calculations between slot classes to improve efficiency either… since they ought to all be inlined, the optimizer ought to be able to combine some of that and increase re-use for you when it’s appropriate.

When using this in the real world, you might have to come up with some sort of “multiplexer” function where you pass it your variable parameters and it will return a function pointer to the specific function you ought to use.  A function pointer points at the function in the specific template instantiation asked for, so getting a function pointer back would be enough to translate your parameters into the right template instantiation to use. I’m not sure of a way to do this other than a bunch of embeded switch statements but I’ll be thinking about it and report back or write a new article if I come up with an interesting way to do that. The main problem there comes in mapping run time dynamic values to compile time static values.

Since this technique is using template classes and/or template functions you might be able to do some interesting things with template specialization, partial template specialization and template parameter deduction.

For instance, you could introduce SSE calls if you have to process more than a specific amount of data, but just do simple loops if doing less than that.

I made some example code that goes into this stuff in some more depth and has a few interesting techniques I didn’t go over in the article.

The example source code makes frequent use of casting like “(DataType)0.5” but don’t worry, those ought to be compile time operations for all basic types and have no runtime cost (verified in my compiler anyways)

Example Code: TemplateSlots.cpp

Mechanical Computer Quest Part I

For years I’ve been wanting to make mechanical logic gates that i could put together into mechanical logic circuits. I want to do this mostly for novelty purposes, but I also think it could be leveraged into either an entertaining learning device, or some sort of game or puzzle.

Since I’m a software engineer, one of the main problems I’ve had is my inability to manifest my ideas in a physical way. Thanks to some modern technology, I think I might be able to partner up with my good buddy Eric and finally make this idea into a reality!

I’m sure some of the things I’m trying to figure out are solved problems, but I want to try and figure it out as much as I can before researching the right way to do it hehe.

Here is some basic background knowledge relating to what I’m trying to achieve, as well as my plans for moving forward.

Logic Gate Basics

Logic gates are the basic building blocks of logic circuits and computers. You can put them together in various ways to make lots of different things happen such as adding or multiplying numbers together, or comparing two numbers to see which is bigger.

The basic logic gates themselves take in either 1 or 2 inputs, and give one output. The inputs and outputs are binary where each one is either a one or a zero.

The 3 basic textbook logic gates are AND, OR and NOT.

AND: this takes in two inputs and gives one output. If both inputs are 1, it gives a 1 as output, else it gives a 0 as output.

0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1

OR: this takes in two inputs and gives one output. If either input is 1, it gives a 1 as output. If the inputs are both 0, it gives a 0 as output.

0 OR 0 = 0
0 OR 1 = 1
1 OR 0 = 1
1 OR 1 = 1

NOT: this takes in one input and gives one output. If you give it a 1, it gives out a 0. If you give it a 0, it gives out a 1.

NOT 0 = 1
NOT 1 = 0

If you are able to do these 3 things, and combine them together arbitrarily, that is considered “Turing Complete”. That basically means it’s capable of doing anything a computer can do, but check out this wikipedia page for more information http://en.wikipedia.org/wiki/Turing_completeness.

Mechanical Logic Gates

To make mechanical versions of these things I was thinking of having each logic gate a self contained object that had sticks for input and output. If a stick was pushed “up” it would be a 1, if a stick wasn’t pushed up, it would be a 0.

I then set out to make a wooden prototype of each gate to make sure I had the basic designs worked out.

NOT

To make a NOT gate, you would have a box with an input stick going into it and an output stick coming out of it. If you pushed the input stick up, the output stick would go down.

If you pulled the input stick back down, the output stick would go up again.

I made one of these out of wood by making a box with two sticks going into it, that inside were attached with a cross peice that could rotate but not move.

This way, when you push up the input stick, the crosspeice rotates and the output stick goes down. When you pull down the input stick, the reverse happens.

It worked fairly decently.

NotGate

OR

To make an OR gate, I made a box with two input sticks going in and one output stick coming out. I had the output stick attached to a cross peice that rested above the input sticks. This way, when you pushed either input stick up, the output stick would be pushed up.

One thing I didn’t like about this design was that it relied on gravity to reset the output after changing the input pins. I’d prefer the mechanical logic gates made as few assumptions about their environment as possible so that there are less points of failure. That way, the mechanical computer would work in space, or on it’s side, etc. A spring could be used, but springs wear out and that’s just another moving part that can fail.

It wasn’t 100% ideal but it worked “ok”.

OrGate

AND

To make an AND gate, if you push up one input pin, nothing should happen to the output pin and it should remain at zero. If you push up both input pins, the output pin should then push up.

The best way i could think of how to do this was to have the output pin rest on a slack string. The string should be slack just enough such that if you push up one input pin, it takes the slack out of the string and rests against the bottom of the output pin. If you push up the second pin, it should make the output pin raise up to the full output pin level.

Unfortunately I never got this working correctly – I’m really bad at making things, I told you! haha.

I wasn’t a fan of the string since it was a finicky, error prone part of the design that could easily fail.

Also, you would need to attach the string ends to the side of the box or something to make sure that as you raised both pins, you didn’t just re-introduce the slack in the string between the sticks. It sounds in my head like it would work, but again, unfortunately I’m a SOFTWARE engineer and this is not really my forte so I’m not sure hehe.

AndGate

Connecting Logic Gates, Metrics and Physical Requirements

So, assuming the mechanical logic gates actually work like they should, there are still some problems to solve, as well as some in general design requirements about how these gates need to work.

  1. Gate pins have to be able to connect to eachother somehow. An input pin needs to be able to connect to an output pin in a rigid way such that if one moves, the other one moves as well.  It would be nice if there was a way for the peices to easily snap together and easily be taken apart again. During normal use they should stay snapped though obviously!
  2. The difference between zero and one needs to be standardized. For instance, the difference between a pin being pushed out and pushed in could be one inch, and all logic gates and all logic gate configurations need to obey this measurement in both their input and output pins.  Some metric needs to be decided on when prototypes start getting designed.
  3. The different logic gates should be the same dimensions (or compatible dimensions) so that you dont end up with a situation where you are trying to connect two logic gates together but can’t because there is a gap between them.  We’ll have to figure out the metrics when prototypes start getting designed.
  4. If i have a gate which takes two inputs, changing one input value should not change the other input value. For example, if in the OR gate, the input pins were rigidly attached to the cross bar, pushing up a pin on either side would cause the other input pin to also change from 0 to 1.  Gates will have to be designed so that this is true.
  5. It would be nice if the gates were set up such that you could see their internals working. This is just for fun to be able to see the computations at work.  We’ll see if we can make this happen when making prototypes.
  6. The gates should be as simple as possible, and manufacturing should be simple. each gate should be made of similar basic building blocks with as simple design and as few moving parts as possible.  We’ll have to keep the design simple when making prototypes. I want to stay away from strings, springs, wheels etc. Nothing that wears out quickly or has any significant fail rate.
  7. When you push a pin up that results in a cascading change across several other gates, friction / resistance shouldn’t be so hard that it gets unreasonably hard to push a pin up, or cause damage to the gates themselves when they are used reasonably.  Hopefully this will be true if we use a light but strong material.
  8. It would be nice if gates liked to rest at whatever setting they were at (1 or 0), as opposed to easily sliding between values (0.8 for instance), or some gates having a tendancy to want to rest at zero instead of one.  I’m not sure if we are good enough engineers to make this happen haha… we may just have to say that these mechanical gates have to operate on their sides or something unfortunately…We’ll have to see!
  9. Changing the input pins should be action enough to change the output pins of each gate. What i mean is that if you had one of your OR inputs as a 1, making it so the output is 1, when you pull down the input pin back to 0, the output pin should also move back to 0, and not require any extra action, such as pushing down the output pin manually.  Just something to be thinking about in the design.

NOR and NAND Logic Gates

There are actually a couple other ways to make logic circuits besides using AND, OR and NOT.

There is something called a “Universal Gate”, which is just a logic gate that can be combined with itself in various ways to make the functionality of AND, OR and NOT (and thus others such as XOR, XNOR, and everything else).

The two universal gates are NOR and NAND. Here are the truth tables:

0 NOR 0 = 1
0 NOR 1 = 0
1 NOR 0 = 0
1 NOR 1 = 0

0 NAND 0 = 1
0 NAND 1 = 1
1 NAND 0 = 1
1 NAND 1 = 0

For more information on how these gates are universal, check out these Wikipedia pages!

http://en.wikipedia.org/wiki/NOR_logic

http://en.wikipedia.org/wiki/NAND_logic

While figuring out how to make a NOR or NAND mechanically would solve my problem of not having a working design for the AND gate, it goes against one of my design goals, which is to be able to give someone AND, OR and NOT building blocks to put together and so learn logic circuits physically the same way they are shown in text books and online.

One possibility would be to take NANDs or NORs and put them together to make AND, OR and NOT gates that came pre-assembled, but that goes against my design goal of keeping things as simple as possible with as few moving parts as possible. It would also add needless visual complexity to the computations, which might LOOK NEAT, but would just add confusion to what was going on.

I haven’t yet decided on a solution to these issues.

Manufacture

For manufacturing, I wanted to work with my friend Eric to get some 3d models made up and get them printed up into 3d objects by http://www.shapeways.com/.

I’m sure it’ll take multiple iterations to get it right, but this seems like a pretty nice solution.

After we have proven our idea on a small scale, maybe in the future we’ll be able to do something like get a kick starter project together to make some kind of mechanical logic gate set you can buy, or some sort of board or puzzle game.

Next Steps

For the next step, I want to think about our logic gate options a bit more, talk to Eric about them, and try and get some prototypes modeled and printed out.

I’ll post an update when we make some progress (: