Free stuff

This page contains little stuff that might be useful for you - either as a reference or just to copy paste in your own code. There are also a few interesting finds I made while working on my own projects so make sure to read them all!

Index

Low latency thread communication - C++

I've been working on threading concurrency for some time now. I even had the privilege to give a course to programmers on concurrency in c++ not too long ago. I would have like to make the powerpoint available but since it's Ludia's property, I'll have to make another one. The good thing is that I'll be able to add more stuff in it - especially regarding low latency thread communication stuff. Until then though, I'm going to make a little list of good references (I used some of them in my presentation).

References

top

Network Messaging - C++, RakNet

This is a network messaging system. Since RakNet's decoding is not really scalable, I decided to change the design. It's quite easy to use and easy to add more messages. The only thing not included in the sources are the processors for the one receiving the message.

Here's how you use it:

  • Add sources to your project (assuming you have already included RakNet's sources - I'm currently using RakNet_PC-4.068).
  • Add new message classes to the folder "common/Network/Messaging/Messages/". They register themselves to the Factory through the macro REGISTER_TO_FACTORY(classname). Don't forget to add the id to the MessageIds.h file. (see examples)
  • Each module running an instance of the class has to define it's own processors in its own codebase (since response to message is not common to both).
  • Associate the processors with the msg ids:
Common::MessageProcessors _MsgProcessor;
                
// associate your processor with msg id 
_MsgProcessor.RegisterProcessor(Common::MSGID_LOGIN, new MessageProcessorLogin());
                
// check RakNet's tutorial for more details on this code  
for (pPacket  =_pPeer->Receive(); pPacket; _pPeer->DeallocatePacket(pPacket), pPacket = _pPeer->Receive()) 
    _MsgProcessor.ProcessMessage(_pPeer, pPacket); // process the messages
                
  • Here's what a message processor would look like:
class MessageProcessorLogin : public Common::IMessageProcessor
{
public:
	virtual void Process(Common::WeakPtr pPeer, RakNet::SystemAddress address, Common::SharedPtr pMsg)
	{
		Common::WeakPtr pMsgLogin( dynamic_cast(pMsg.Ptr()) );
		assert( pMsgLogin.IsValid() );

		Common::Log::log_info("LOGIN: %s - %s.\n", pMsgLogin->GetUsername().c_str(), pMsgLogin->GetPassword().c_str());

		Common::ScopePtr pMsgResult( new Common::MessageLoginResult(true) );
		pMsgResult->Send(pPeer, address);
	}
};
                    

Source

Messaging.zip

top

Tray icon handler class - C++, Windows

I've made this little class to manage the tray icon minimize/maximize, you can check it out and even reuse it! =)

Source

TrayIconHandler.zip

top

Circular buffer, fast multi-thread communication - C++

I've just finished implementing a fast communication class called CircularBuffer. A circular buffer is used to communicate data between two threads (processes if the memory is shared). It is quite fast since there are no mutexes or anything like that. As long as the reads and writes are fast enough, the data transfer is quite fast. If the reads are not frequent enough though, Writes are going to fail so you may need to create a bigger buffer (also known as back pressure).

Source

CircularBuffer.zip

Common::CircularBuffer buffer;
uint32_t nSizeRead = 0;
uint8_t *pData1 = new uint8_t[10];
uint8_t *pData2 = new uint8_t[2];
uint8_t *pData3 = new uint8_t[10];
buffer.Set(pData1, 10);
if( buffer.Write(pData2, 1) ) ...
if( buffer.Read(pData3, 10, nSizeRead) ) ...
buffer.Reset();
delete[] pData1;
delete[] pData2;
delete[] pData3;

top

Keyboard and mouse interception

I've been researching how to intercept the keyboard and the mouse so that I can use my app in the other app and from my understanding, it won't be as easy as I first thought. Most apps can be intercepted using SetWindowsHook function (since most use the windows message system for inputs), but in my case, the applications I'm intercepting are using DirectInput and apis like that. For instance, if I connect to a DirectX game, it may use DirectInput, XInput or even the messaging system. So the only solution is to either hack into the kernel (that's kinda complicated) or hack into all the different libraries. From my understanding, steam is doing exactly that so it seems to be my best bet.

http://snipd.net/dll-injection-in-c

http://stackoverflow.com/questions/8821895/sending-key-presses-with-interception

http://www.codeproject.com/Articles/194729/Keyboard-Hooking-In-Kernel

A link to an interception library that requires offline installation (I don't really like that part but it seems to work pretty well):

http://oblita.com/Interception

Also, this is quite an interesting article regarding misuse of this technology.

(...)Keyloggers_How_they_work_and_how_to_detect_them_Part_1

(...)Keyloggers_Implementing_keyloggers_in_Windows_Part_Two

top

SmartPtr, C++

Everytime I start a little project, I end up needing to create a new smart pointer class. I usually use the one provided in boost, but it's big for small projects so I ended up making my own.

Sources

SmartPtr.zip

top

Logger - C++

Need a light logger for your application? I based myself on one that Unity is using in the master server code (open source don't worry). It's quite modified though.

Sources

Log.zip

top

Neural Net with backpropagation - C++

Neural net to be reused in any app. Contain Save() and Load() methods so that user can train it in another application and load it afterwards in the client.

Sources

NeuralNet.zip

top

Design patterns in game development

There are a lot of resources talking about design patterns specifically used in game development (I tried to be as unique as I could so as to not repeat what are in those references). But a pattern is rarely specific to game development and game development don't prevent anyone from using any of the patterns. So which patterns should I talk about then? Well I'll first try talking about those patterns I personally use when programming myself.. and since I am a game programmer, it will relate to your work as a game programmer. I'll follow with a list of example in games based on the list of design patterns on wikipedia.

Singleton

Who has never used the singleton? Singleton is especially useful to make a class available from anywhere in the code. In other words, it is a disguised global variable. Lots of people have those because of that. Personally, I think they are quite useful because it eases the programming. Why make things complicated when it can be easy? Isn't that the whole point of software development? Well, to be fair, let's look at the disadvantages related to the use of singletons.

  • Initialization - because of the way singletons are designed, it's kinda hard to know when the actual object is going to be created. Now think about if that singleton depends on something else.. it will need to be initialized after something else and destroyed before it! So we need to explicitely ensure that by either making a weird call somewhere in the code and making sure it gets destroyed properly before the other - but how do we destroy a singleton unless it's a pointer? User then has to make a Create and Destroy method for it and .... so on and so on.
  • Evolution of the design - since a singleton enforces the single intantiation of the class, it constrains the evolution of the application.

References:

http://www.coderanch.com/how-to/java/SingletonPattern

http://dancing-devil.blogspot.ca/2011/05/what-to-remember-while-using-singleton.html

Factory

Factories are "always" used in games. Be it to instantiate game objects or graphics api implementation and platforms implementation (see irrlicht engine for a good example of that). What's great is that it lets you program with some abstraction of the platform or graphics API (opengl vs directx). There lots of other use for that though.. for instance, you could have a network decoder that instantiate using an ID from the decoded data, etc. This is a mandatory pattern since it makes it all easier to work with and in some way enforce good programming practices.

Object pool

Object pools are usually used for textures, meshes, particles in a particle engine, threads pool, etc. Anyone who tried making their own game engine has made one for sure. Just think about a particle system to make rain. If the system had to reserver and delete memory everytime, it would make the system quite slow. Thanks to the pool though, it's just a matter of repositionning the rain drops.

Flyweight

"A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects." The concept is similar as an object pool - better memory usage - but in this case, the pattern makes it possible to use less memory instead of minimizing the amount of news and deletes. In this case though, it's on multive active objects. A good way to enforce good usage of that pattern is to use smart pointers that can be shared between objects. This way, you can't delete the shared object unless no one is still using it. For instance, this pattern is useful when creating shaders (sharing view/projection/etc matrices). This pattern is extensively used in Java for strings.

Wiki list

  • Abstract factory: Different implementations of factories. A good example of that would be materials in a graphics engine that supports multiple graphics API (ie: each has its own shaders, etc). So you could have a factory with createMaterialRock() that gets implemented differently depending on the platform.
  • Builder: Especially useful when related to composite pattern (ie: a game object composed of a graphics and audio representation). So a game object could be created
  • Factory method: Usually done by reimplementing a parent's virtual method. A good example would be an intelligent character class that reimplements the createControlAI() method that gives an input command object (ie: ai badass, ai crazy etc) of the button from its parent class.
  • Lazy initialization: Lots of places that is implemented. A simple exemple would be the way Leadwerks engine first implemented its materials. So everytime the game loaded an object with a new type of meterial, it would start to lag..
  • Multiton: Quite similar to the singleton pattern since it also enforces a class to be instantiated only once. The only difference is that it prevents someone to use it globally like the singleton. This is more of a way to protect from not knowing you can't instantiate an object again.. so it would be possible to apply it to a factory for instance (that keeps count of the memory usage). A second one wuld mess up with the calculations.
  • Object pool: Object pools are usually used for textures, meshes, particles in a particle engine, threads pool, etc. Anyone who tried making their own game engine has has one for sure.
  • Prototype: This one is used in many places! But it's especially useful in a messaging system. For instance, in an world editor, the user clones the selected tree mesh to have the same one a few pixels away.
  • Resource Acquisition Is Initialization: Mostly related to the language itself but a good example is the way to encapsulate mutexes (to make sure that the mutex locks on creation and released on destruction).
  • Singleton: Disguised global variable...
  • Adapter/Wrapper/Translator: Any cross platform graphics engine uses this quite of design over the graphics API. It adapts all calls to opengl or direct in the class.
  • Bridge: The bridge pattern is often implemented using an adaptor pattern. So the pattern can also refer to the way crossplaforms engines deal with graphics API.
  • Composite: This one is almost always used to represent the game objects (composed of a graphical representation, audio or physical.
  • Decorator: GUI! A button decorated by the toggle button to add functionality for instance.
  • Facade: Any graphical engine using the opengl or directx api is a facade.
  • Flyweight: A shared smart pointer is a way to share the same object with many. A sprite renderer is exactly that as well. You pass the image with some coordinates and it renders it using all its internal resources.
  • Front controller: Some guis are made this way - like the login scene that takes care of sessions for all the other pages.
  • Module: Everything in a game relates to a module - be it the sound module, the graphics, module, the physical module, etc. It's a way to organize the code.
  • Proxy: It's an interface to something else. For instance, the NetworkConnection class proxies the connection between a game server and the game. A better exemple would be the reference counting pointer used in any smart pointer class.
  • Blackboard: This one is kinda risky to use. A database could be considered a blackboard or even global variables.
  • Chain of responsibility: A messaging system between the server and the client uses that pattern to decode messages from one of the other.
  • Command: DirectX 11 implements the safe thread rendering this way. I also did the same in my pacman game available in the portfolio archive.
  • Interpreter: Some games like facade uses an interpreter to know what the player writes down and react properly.
  • Iterator: Anyone who used STL know who to use an iterator (vector, map, list, etc)
  • Mediator: Physics engines, Scene management designs like the octree, the bsp tree, etc.
  • Memento: Any save system from a game is exactly that to some degree (character's position for instance).
  • Null object: If you know the irrlicht game engine, you'll see that the default graphics api implementation is the null one - it doesn't do anything. It's used to revert to a useless objects that always compiles and "work" independantly of the system's state.
  • Observer or Publish/Subscribe: Physics engine use this pattern when a collision happens - it only tells it to those that want to know about it. The JMonkey engine 2 uses that a lot to tell other systems when it finished loading, etc.
  • Servant: A database used to hold player data (in League of Legends for instance).
  • Specification: Knowing if the game can activate specific quests that depends on previous quests.
  • State: State Machines! In other words, most of the artificial intelligence in games are made using a state pattern. GUI for button states is the same, etc.
  • Strategy: Often used in a graphics engine to render list of triangles. Discriminating factors are usually the presense of normals or other components of the vertex.
  • Template: Default game objects is a good example. The default object could just render a semi-transparent box and when child classes inherit from that class, they can redefine what gets rendered, the ai, the interactions, etc. The Sims games did some pretty good things with that design.
  • Visitor: Quite useful in scene editors when multiple file formats exists. Basically, a class encapsulating the different encoding would visit the class that it wants to save or load.
  • Active object: Used in multi-threading code. Useful when an object needs to be run on multiple threads (graphics, loading, etc). For instance, a game object would need to be run on the loading thread first then on the graphics thread (if graphics engine not thread-safe).
  • Balking: Kinda of a weird pattern (considered as an anti-pattern by some). In a way, it's like throwing exceptions when a child object doesn't support something the parent class gives access to. It could be useful when developping new features for different platforms (for instance, file system on android and other devices) so the unit test would catch the unimplemented features.
  • Binding properties: User interfaces API uses that a lot (ie: binding a specific control event to something in code, etc).
  • Double checked locking paterns: Can be used when having a singleton instantiation can be done on more than one thread (ie: a logger).
  • Event-based asynchronous:
  • Guarded suspension:
  • Lock:
  • Messaging:
  • Monitor
  • Reactor:
  • Write lock:
  • Scheduler:
  • Thread pool:
  • Thread-specific storage:

http://gamedev.stackexchange.com/questions/4157/what-are-some-programming-design-patterns-that-are-useful-in-game-development

http://gameprogrammingpatterns.com/

http://exciton.cs.rice.edu/research/sigcse02/DP4Games.pdf

top

Interview question: How do you program?

Each programmer has his own way of ...

Read More

Interview question: What do you expect from a supervisor

That's usually ...

Read More

Social

  • LinkedIn
  • adam _ galarneau (at) yahoo . com