Design Patterns – The Command Pattern

Again, I am not gonna bother trying to find relevant images for this stuff, so have a nice picture of Wipeout Omega Collection that came out last week. Wipeout is my favourite Anti-Grav racer, sorry F-zero, I grew up with the PlayStation ūüôā .

Anyway, lets have a look at the Command Pattern. I have been reading up on the Command Pattern recently, and it seems pretty popular with it being Robert Nystrom’s favorite pattern! (He is the author of Game Programming Patterns. It is a good book, I would recommend it! He also has it all up for free on his website).

Unfortunately, as Mr Nystrom says, the Command pattern as an annoyingly obtuse description:

“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”

Seriously, it would be nice not to here a technical definition of something in a language other than nerd once in a while. In English, Commands are an object-oriented replacement for callbacks. It allows you to encapsulate actions into objects with the main objective being to provide the means to decouple the client from receiver.

Does that kind of make sense? OK, well either way let’s look at an example or two.

In the real world, say you were at Maccy D’s after a night out. You want a large portion of C-Nugz with a Cheezy B for the road (or a Large Chicken Nugget meal with an extra cheeseburger. They are only like an extra quid, so why the hell not?). Let’s say it is old school maccys where there is someone taking your order. You (the Client) ask the guy (the Invoker) for your meal of goodness (the Command). The guy plugs that in and a request is made to the Chef(the Receiver) to create it. Do you see what is going on? The Client gives an Invoker a Command that is then past on to the Reciever that actually knows how to deal with the Command.

Let’s look at it in more game dev terminology. I am going to write some C#, because C# is awesome (C++ is alright too, but C# is easier to just get stuff done ūüėČ )

Let’s say I am making that really popular Side Scrolling Shooter on Vita known as Storm Ship Shiro. We will likely want to put in a way to remap the controls (something I admittedly didn’t do back in the day…). First I am going to make an abstract class called Command.

public abstract class Command
{
    public abstract void Execute()
}

The main part of the game I may want to remap is Firing the main Weapon. Firing the Weapon is a Command so what do you think I am gonna do? Make a class that inherits from this Command.

public sealed class FireWeapon : Command
{
    public override void Execute()
    {
        //Fire logic goes here
    }
}

Cool so we have our command, what is our Client. Well in this case that is more “conceptual”. You could say our player is the Client. Our Invoker however could be our Input System that has the following code:

Command onButtonA;
public void SetButtonACommand(Command command)
{
    onButtonA = command;
}
//A load of code...

if (Input.GetButtonDown(Button.A))
{
    onButtonA.Execute();
}

If we plug in the following:

InputManager.SetButtonACommand(_playerShip.FireWeapon);

Then we have mapped that to Button A.

In this case the Client is the player, the Invoker is the Input System, Firing the Weapon is the Command and the Reciever is the Player’s ship.

If we check our simplified definition:

“Allows you to encapsulate¬†actions in objects with the key idea being to provide the means to decouple client from reciever”

That is exactly what this Input system is doing.

Cool huh?

There are many other examples of how the Command pattern is used, one is Undoing and Redoing actions. Say you had a Tactics style game where you could see the outcome of your move. You move your character and then tell him to attack. You didn’t like that last action you performed. So you decided to return to just the move and then use an Item. The client here is still player but the Invoker is a core game system that has a load of commands for every action a character can do. The receiver¬†then is the character themselves.

The command pattern is pretty cool, have a look at it!

Design Patterns – Intro

Image result for persona 5

As usual, I couldn’t find a decent picture, so I just put up one of Persona 5. I am still playing it, it is really good. Pick it up!

Recently I have been going through all my knowledge and figuring out where my core knowledge gaps are. After doing a few tests, etc, I found one of these was design patterns. I have used them a lot in the past, but there are still a few that I am not super comfortable with, so as with most things, I thought I would revise them by doing blog posts about them. Makes sense right?

Firstly, why are design patterns important?

I have worked with a number of code bases, both good and bad. Some code is built in an extremely nice way, other bits are hacked together willy nilly just writing code and not really thinking about the architecture to solve the problem. I myself have done both at some point or another, for a variety of reasons that I may go into in a later post. Design patterns CAN help with this, but there are some caveats.

Let me go on a bit of a tangent a bit. In 2017, games are often not a fire and forget bit of software. They are living breathing things which we can later update and make better. We have platforms like Steam, PS4, Xbox One and Switch which allow us to patch our games unlike the days of PS1 and PS2. We also have games that require lots of Live Operations and will require us to revisit code to add features or extend existing ones. We will essentially need to make changes and design patterns are one way that can kind of help us write code in anticipation that we are one day going to have to make these changes. They are no silver bullet, but they can help towards this.

But hang on, why is that the case? Well let’s look at the definition or what a design pattern is.

According to Wikipedia – “a software design pattern is a general reusable solution to a commonly occurring problem within a give context in software design.”

Let’s say you get to a code base ¬†and you need to make a change to a feature that you are not super familiar with. This feature is meaty, but luckily as you peruse through it you can see some familiar patterns and the classes, etc seem to be named in familiar ways. You realize that someone has used a design pattern and you can use your knowledge of the design pattern to get stuck in. The amount of time taken in understanding the code has decreased and the amount of time needed to make your change. This is because they are defined as reusable solutions to commonly occurring¬†problems. Yes you will still need to learn what the code is actually doing, but¬†as it is a solution to a problem that has cropped up before, their usage is communicating to you what the goal of this system was and it’s intention. Similarly, as it is a familiar solution to a commonly solved problem, the code is likely to be more readable and thus also easier to maintain, which is good as someone else comes back and revisits it again.

You have been given a feature on the game to do. It is pretty big and you need to architect a system. You come up with a system that fits within a design pattern. By doing this, you can easily explain to other developers how exactly you are going to implement a feature. You can talk about how you are going to use a Factory to handle all your object creation, or an Observer to handle when to trigger an event. It gives developers a common vocabulary to talk about and can be used as a good starting point in a discussion whether or not that it is a good way of implementing the solution to the problem you are trying to solve.

Here is a final example. Say you are writing a feature, and it sounds very similar to something that already exists. You look up the code for this old feature and find the underlying system is written in a nice reusable manner as it followed a specific design pattern. This is awesome as it means you won;t have to write a tonne of common code to solve your issue.

So let’s look at the key points at why Design Patterns are important:

  • They make code more¬†readable
  • They make code easier to maintain
  • They can make it easier to communicate your intentions to other developers
  • They allow for code re-use and less code

Sounds great, right. There are a fair few good reasons why you should use a design pattern, but there are caveats. Like I mentioned briefly before, they are not the silver bullet. And can cause problems.

  • They can make the code more complex – some of them patterns use a lot of indirection and less experienced members of your team may have a harder time following them
  • You need to know when to use them –¬†There are always dangers of using the wrong pattern and also using them just for the sake of it. Regardless of how senior you are, when developing a big feature and want to use a design pattern, chat it through with another developer. Otherwise it will make life harder rather than easier
  • Some can hurt game performance –¬†patterns can make your code more flexible and easier to reuse, but this can in some cases come with a cost to performance. They can rely on features that have a greater runtime cost. There needs to be a balance here. Although you are writing more flexible and potentially easier to understand code,a re you shooting yourself in the foot when it comes to performance?
  • They can be abused –¬†Google the Singleton pattern and you will find a lot of discussion around its abuse.
  • You can code yourself into a corner –¬†This is a very specific case I have found when it comes to dealing with live games. Originally, you used a certain design pattern to create a feature based on the design. However the game is out in the wild and analytics are revealing that players are having a hard time with it, don’t enjoy it or it just doesn’t work as a concept. The game is a living breathing thing and you have to adapt it. The change you have been given is not that big conceptually, so you go to the code base. However, because you built the code in such a specific way, it is actually going to take a long time to unpick parts of it and put in this change. You essentially coded yourself into a corner.

So yeah, Pros and Cons. The main points here are:

  • Design patterns are powerful and can help make your code better,¬†when thinking about using¬†them, research them and discuss your solution with others to evaluate the pros and cons.
  • Don’t be the “Small Boy with a design¬†pattern” and use them for the sake of it

Awesome! Next we will be looking at some of the Command Pattern!

Unity Shader Tutorial: An intro to Compute Shaders

Are you ready to turn this up to 11?¬†We are going to look at some real “Triple A” business now. The world of compute shaders. So what are these mysterious ¬†creatures that you probably don’t know exist in Unity?

To be honest, I had completely forgot they were there and I was looking at a fur tutorial (that doesn’t actually seem to work by the way and was also a really dirty way of doing it ) and then remembered my mate had said you could probably do grass and fur in one. I think he actually meant geometry shaders, but compute shaders peeked my interest.

However, after digging around the net it turns out that info surrounding them when it comes to Unity seems quite scarce.

Let’s start from the top!

What is a compute shader, and why should I care?

In Microsoft’s fancy terms, “a compute shader is a programmable shader ¬†stage that expands Microsoft Direct3D11 beyond graphics programming” and “a compute shader provides high-speed general purpose computing and takes advantage of the large numbers of parallel processors on the GPU”.

In simple terms, a compute shader is a program that runs on the graphics card that does stuff outside of the normal rendering pipeline.

So you are probably thinking “OK, I kind of get it, you can run some logic and put some work onto the graphics card, but why would I want to do that?” Well these shaders are really good at maths and parallelization, i.e. they are really good at performing tasks where you are doing a lot of the same thing. In other words, they are really good at tasks that involve applying the same set of calcualtions to every element in a given data set.

This is probably a kind of crappy exlanation, so lets wind the clock back a bit to when I was just gracing the planet with my presence. The 90s. It was a beautiful time with games like Doom, Final Fantasy 7, The Legend of Zelda: Ocarina of Time, Crash Bandicoot, Tekken 3… do I need to go on? Essentially lots of 3D games and PCs started going out with graphics cards. Stuff like this bad boy.

What a rush indeed! Getting that sweet 6MB of power all up in your grill. Anyway OpenGL and DirectX appeared¬†and the magic of the programmable pipeline emerged. Developers just send geometry down to the graphics card and OpenGL/Direct X would figure it out. However, the pipeline was pretty rigid, and thus to make more interesting effects and push the boundaries it had to became more flexible. This led onto shaders, where devs could write their own programs to perform certain parts of the pipeline and make things look like the wizard’s tits.

This the opened up a lot of possibilities and this new system mean that the new pipline could deal with a lot of different types of algorithms and now the GPU can do stuff like crazy multi-threaded physics, etc.

What this means now is we can do crazy stuff like Nvidia’s Hair works.

You on board now? If not, just know it is cool and you feel like a Game Development Maverick when you do it.

Basically, you can potentially harness the GPU to do none graphicsy stuff if you so desire and gain MOAR POWER.

Sod it, lets jump in!

That’s the attitude I want!

Before you start though you need a WINDOWS machine. Macs don’t have it. And to be honest they are kinda crappy for big boy game development like this anyway ūüėõ

Create a compute shader in Unity.

The first thing you will notice is that this is not CG. This is a Direct X 11 style HLSL bad boy. Yeah fasten your seat belts boys and girls.

// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain

// Create a RenderTexture with enableRandomWrite flag and set it
// with cs.SetTexture
RWTexture2D<float4> Result;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
     // TODO: insert actual code here!

     Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0);
}

So the above is what you get if you just create one from scratch.

The #pragma kernel CSMain is the first thing we see in our shader. Kind of like the other shaders, this is us telling the program where our entry point is, in this case CSMain. A compute shader can have many a function and you can call a specific funciton from a script. More on that later.

The next bit is a RWTexture2D<float4> Result

Again, like our other shaders, this is just a variable declaration. However, as we aren’t using mesh data, we have to say what the shader will read and write to. In this case we have a RWTexture2D a read/write texture 2d object that the program is gonna use. Take a look at MSDN for reference:

https://msdn.microsoft.com/en-gb/library/windows/desktop/ff471505(v=vs.85).aspx

Finally, the last super different thing is the numthreads which is the the number of thread groups that are spawned by our shader. GPUs love the parallel processing business and create threads that run simultaneously.  This line is specifying the dimensions of the thread groups. These specify how the threads that are created are organised and in this case we are saying that we want to create 64 threads. Take a look at msdn for refrence:

https://msdn.microsoft.com/en-us/library/windows/desktop/ff471442(v=vs.85).aspx

The size of your thread groups will be determined by a lot of factors and probably most notably your target hardware. For example, the PS4 may have  a different optimum size compared to the Xbox One.

The rest is kind of bog standard code. The kernel function determines what pixel it should be working on based on the uint3 ID of the thread running the function and writes some data to the result buffer.

Cool. We have our first compute shader! But how do we actually run this warlock? It doesn’t run on mesh data so we can’t attach it to a mesh. We need to grab it from a script.

But hold up, before we start lets change up our script that Unity spat out and make the compute shader do something different.

// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain

RWStructuredBuffer<int> buffer1;
 
[numthreads(4,1,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    buffer1[id.x] = mul(id.x, 2.0);
}

You can see we switched out the texture for a structured buffer. This is just an array of data consisting of a single data type, in this case it is an int. In the code you can see we are just taking the id of the thread and multiplying it by 2.

Cool lets write a new script.

using UnityEngine;
using System.Collections;

public class RunComputeShader : MonoBehaviour
{
    [SerializeField]
    private ComputeShader _shader;

    void Start()
    {
       ComputeBuffer buffer = new ComputeBuffer(4, sizeof(int));

       _shader.SetBuffer(0, "buffer1", buffer);

       _shader.Dispatch(0, 1, 1, 1);

        int[] data = new int[4];

        buffer.GetData(data);

        for (int i = 0; i < 4; i++)
        {
             Debug.Log(data[i]);
        }

         buffer.Release();
     }
}

Firstly we are creating a compute buffer the size of an int, a buffer that ComputeShader programs use to store arbitrary data and then we are using the SetBuffer to tell the shader to dump data in there. We use the dispatch function to run our shader and then grab the work the shader has done.

If you set up the above you should see in the debug window it print out some numbers. Yeah it did that on the Graphics card.

Alright fine, it wasn’t the most crazy thing in the world, but it is just showing you that work other than just rendering pretty images can be done.

Round up

This is a post to show you compute shaders are there. I am not saying go out and use them everywhere.¬†The GPU can be used to do some cool multi threaded tasks, however a word to the wise. The tasks that the GPU can do are going to be limited and you really have to look at the problem you are trying to solve before you go down this path. If your game is gonna be super pretty in, you porbably want to be maxing out the gpu on that first before offloading stuff the cpu can do onto it. If your GPU is jsut idling though… maybe on like some lower poly strategy game, etc then maybe consider offloading some of the logic to the GPU using a compute shader.

Well until next time!