« Posts under Programming

Global Game Jam 2012 Wrap-Up

The 2012 Global Game Jam is over and it was another year of awesome games in the Raleigh-Durham – North Carolina area.  This week I wanted to put the spotlight on all the games lovingly crafted by our crack squad of jammers – especially mine, Low Power! :D

The Theme

theme

The Ouroboros – but no explanation was given.  We just showed the jammers the image and it was up to them to interprete it.

LOTR Body Snatching

Rock, Paper, Scissors with body snatching!
Avoid or possess enemies to stay alive and win.

Low Power

In order to survive Low Power you must consume yourself (like the Ouroboros) to survive.  You control a robot whose battery is constantly draining but there are valuable energy cores scattered throughout the level that will sustain your life.  There are all kinds of dangerous environmental hazards that unless you enable your sensors/abilities (lights, shield, ground sensor, microphone) you’ll never survive.  However enabling the different systems will drain your battery even faster!

Parasite

You are a Parasite that leeches off battle ships. Enemies will constantly come in formations to destroy the ship you are occupying. Using the possessed ship, you must defeat your enemies! However, as you leech your ship it slowly dies, you will constantly need to take control of and leech of another ship. With out a ship for protection you are helpless!

Planes on a Snake

A rift in spacetime has resulted in a large number of World War II era planes getting stuck on the world snake.  Join the frequent fliers club of Ouroboros Airlines, racking up points while taking advantage of the torus nature of your new environment.

Roller Snake: The Quest for Chili Dogs

Control “Hardy the Hoop Snake, Jr., III, IV, and V” in his quest to eat as many chili dogs as possible while winding through ‘Catastrophe Canyon’

Snake Run

You are the snake’s guardian, you must ensure that balance is maintained.  Let enough creatures be eaten by the snake to ensure he doesn’t starve, but not enough that he frenzies and destroys everything.  All the while outrunning him!

Making Your Files Merge Friendly

Merging is a fact of life for most of us.  Eventually two users touch the same files and a conflict must be resolved.  For programmers merging is a daily activity, but what about the content creators?

If two artists touch the same level, have your tools programmers made enough of an effort to make merging possible and if possible as painless as can be?

Here’s a handy checklist,

1 – Use XML/JSON (or some other text based file format)

It’s slower, it’s bigger but it’s going to make merging possible.  If your level files are binary blobs merging without a custom tool just isn’t going to be possible.  Using XML or JSON are the simplest text based alternatives because there are already many libraries for reading and writing them.

2 – For XML – Give Each Attribute a Line

If you’re using XML, you should make sure to write out the files such that every element and every attribute receives its own line.  If you don’t do this it will make conflicts a lot more likely if two users touch the same object.

If you’re using JSON, having each attribute on its own line is the norm unless the library is attempting to keep the text compact.

Here’s a quick example, note that after separating the attributes the merge tool handles the conflict correctly while it fails to do so when they are on the same line.

nonewline
Figure 1 – Attributes all on the same line

newline
Figure 2 – Attributes on different lines

If you’re using .Net this can be achieved very easily by changing the default XmlWriterSettings with the NewLineOnAttribute property set to true.

C#
var settings = new XmlWriterSettings()
{
    NewLineOnAttributes = true
};
 
using (XmlWriter writer = XmlWriter.Create(filestream, settings))
{
    // Write out document...
}

3 – Maintain Order

Always write out the order of the data the same.  This one is pretty easy, the only real pitfall is to make sure your data structure and undo/redo system are working correctly.  For example, if you happen to store your objects in a list and someone removes and object at the front, but when it’s undone it’s inserted at the end of the list (Even if the UI doesn’t reflect this) this could affect your output order.

4 – Don’t Add New Objects At The End

When you go to save the entities don’t write them out in the order they were created.  This will definitely result in a merge conflict.  Because it ensures that if two users edit the file and both add an entity they’ll both show up in the same location and confuse the merge tool.

One thing you could do is to sort them based on a GUID that is stored as part of the objects data.  Sorting based on GUID ensures a lower probability of collisions occurring when two users both add objects.

Alternatively a sorting based on a string containing the machine name of the original creator of the object is another idea.  It would ensure every user touching the file would be inserting to their own section of the file instead of everyone inserting to the tail.

Robust Inside and Outside Solid Voxelization

complete_polygonal_scene_voxelization

While wrapping up my post for generating simplified occluders for Hierarchical Z-Buffer Occlusion Culling, I was pointed to a paper called Complete Polygonal Scene Voxelization.  Afterwards I found time to read it thoroughly and implement it as a replacement for my existing ray casting based solid voxelization method.

The problem with the solid voxelization technique I was using previously was that it used ray casting; making it impossible to perform solid voxelization unless the mesh is watertight in addition to having no anomalies like intersecting geometry.

However, that restriction makes it an unrealistic solution in the real world because game art typically has holes in the locations players never see; such as the bottom cap on a building, which is rarely modeled.

The New Solution

The Complete Polygonal Scene Voxelization paper’s solution to voxelizing a scene is pretty clever; It applies a heuristic model to the problem of determining the inside/outside status of each voxel or octree cell.  Allowing it to overcome the problem of holes and intersecting geometry making it suitable as a real world solution.

How It Works

bunny_octree_3

You can download the paper and read it for yourself, but let me go ahead and summarize the algorithm for brevity’s sake so that the rest of the article makes sense.

The algorithm takes place in 3 stages:

  1. Create Octree
  2. Find Seed Cell
  3. Propagate Seed Cell

Create Octree

First you create an octree around the mesh that continues to subdivide each cell until either the cell no longer intersects with any triangle or a maximum depth is reached.  A typical maximum octree depth that will work for most meshes is 5.  If the mesh has some exceptionally thin walls that you want the cells to be small enough to fill you may need to go as high as 7 or 8.

I was having some problems with the GPU AABB/Triangle overlap test I used for voxelization in the Hierarchical Z-Buffer Occlusion Culling article and so I ended up porting the Möller implementation of AABB/Triangle overlap test to C# and just used it instead.

Also if you ever need to lookup how an intersection is performed I highly recommend the gigantic matrix of intersections over at realtimerendering.com.  It was a handy resource since I don’t keep the algorithm for AABB/Triangle overlap stored in my brain.

After you’ve created the octree we need to process each cell that wasn’t intersecting with a triangle to determine if it is inside or outside.

Find Seed Cell

Before we can determine if a cell is inside or outside the mesh we need to find a seed cell.  The seed cell is sort of the ground truth example cell that we use to propagate its status to the other cells that it can see.  The seed cell’s status is determined by rendering a cube map centered inside the cell with the near plane placed at the cell edge.

When rendering each side of the cube map, you render the scene such that all front facing polygons are blue and all back facing polygons are red.  You then read back each cube map surface from the GPU and determine the percentage of red and blue pixels seen at each face.

If at least 4 sides of the cube map contain red pixels, the cell is determined to be inside the mesh.

The paper says that NO red pixels can be seen for a seed cell to be determined to be outside however I found this problematic since occasionally a red pixel can be seen just through tiny rendering artifacts.

So I feel a better solution is one like the following:

C#
MIN_INSIDE_FACES = 4;
MIN_INSIDE_PERCENTAGE = 0.03f;
 
int cubemap_sides_seeing_inside = 0;
 
for (int i = 0; i < 6; i++)
{
    RenderCubeMapSide(i);
    float backfacePercentage = CalculateBackfacePercentage(i);
 
    if (backfacePercentage > MIN_INSIDE_PERCENTAGE)
        cubemap_sides_seeing_inside++;
}
 
if (cubemap_sides_seeing_inside >= MIN_INSIDE_FACES || cubemap_sides_seeing_inside == 0)
{
    if (cubemap_sides_seeing_inside >= MIN_INSIDE_FACES)
        cell.Status = CellStatus.Inside;
    else // cubemap_sides_seeing_inside == 0
        cell.Status = CellStatus.Outside;
 
    // Propagate cell status...
}
else
{
    // Unable to solve status exactly.
}

Where you don’t count a face as inside unless at least 3% of the total red and blue pixels are red.  The percentage is just something I picked out of thin air, it feels like a number small enough to be easily overcome by any truly inside cube face, but high enough to allow me to ignore tiny artifacts.

Propagate Seed Cell

The last step is to propagate the seed cell’s status to other cells.  After classifying a seed cell you need to test every unknown cell against each the depth map and frustum of each cube map surface.

You’re performing a test to see if any of the 8 corners of the octree cell when projected into the camera space of each cube face are closer than the depth value at that pixel.  If it is, then then the entire octree cell likely visible.

If the cell is visible from the seed cell, then in all likelihood the cell has the same status as the seed cell.  However because having holes means 2 seed cells (one inside and one outside) can potentially see the same cell you want several seed cells to confirm the status of a cell before committing to it.

So once you’ve determined a cell is visible from the seed cell you’ll increment a counter on the cell for that status.  Once one of the statuses reaches a threshold, like for example 16 you’ll change the status of the cell from Unknown to whatever status counter overcame the threshold and no longer process that cell.

It should be noted that only seed cells propagate their status.  Cells that you propagate to do not propagate their own status.

Repeat

After you’ve found a seed cell and propagated its status you’ll continue to repeat finding a seed cell and propagating the seed cell until all cells have a status of inside, outside or intersecting.  You can rarely end up with some cells whose status simply can’t be determined so make sure your code can handle that scenario and not loop forever.

Improvements

While implementing the paper I made some additional improvements to the proposed solution.  I sped up the process by taking advantage of hardware improvements to render the scene using a single pass.  I also improved the conservativeness of the algorithm in situations where you’re using square voxels. When a mesh is wider than it is tall in those sitations there will be padding below the mesh; if the bottom of the mesh is uncapped it can lead to inside cells ‘leaking’ their status outside.

Single Pass Rendering

The paper was published back in 2002 and due to limitations at the time the simplest method of rendering front faces one color and back faces another was to render the scene twice and flip the winding order and the color of the triangles being rendered.  However this method is slower than just using a simple pixel shader to change the color of front/back faces.

In OpenGL you can use gl_FrontFacing and in DirectX 11 you can use SV_IsFrontFace.

GLSL
void main()
{
     gl_FragColor = gl_FrontFacing ? vec4(0,0,1,1) : vec4(1,0,0,1);
}

Intersect Mesh Bounds and Clip To Bounds

One problem I found is that when a mesh (like a building) is uncapped at its base but is wider than it is tall there will be several cells below the base of the mesh.  Cells that will have the status of inside spread to them, even though a human could easily see those cells are outside.

So one improvement I ended up adding is that when testing for triangle intersection, you should also test against intersection against the mesh bounds.  Additionally you immediately mark a cell as Outside if is outside the mesh bounds, since it simply is not possible for that cell to be inside the mesh, but don’t treat that cell like it’s a seed cell; just mark it as outside and move on.

I needed some real game art to properly test the solution so I exported a roof structure from the Necropolis map from UDK’s UTGame sample.  Here you can really see the difference it makes to clip to the bounds of the mesh.  Note how many additional voxel/octree cells (purple lines) are determined to be ‘inside’ because of how many backfaces (red triangles) they can see.

udk_necropolis_roof_not_fixed
Figure 1 – Roof Inner Voxelization Not Bounded (Before)

udk_necropolis_roof_fixed
Figure 2 – Roof Inner Voxelization Bounded (After)

Future Improvements

When the cube map for each seed cell is processed it’s read back from the GPU and each pixel is checked on the CPU.  This is wildly inefficient when all we care about is the percentage of red to blue pixels on each face.

So that processing can be moved to OpenCL to improve the performance significantly.  I would prefer to have all cells be seed cells since that makes it easier to define the rules of what cells are inside vs. outside.  Allowing the cells to propagate has a higher potential to cause problems I suspect on meshes with very nasty artifacts.  Giving each cell the ability to individually determine their status will be more stable and more predictable.

Currently my cube map rendering is performed in 6 passes.  Shifting over to a single pass method using the geometry shader will likely add additional speed improvements, but I don’t know for sure.

If I move enough of the processing to the GPU it may allow me to make more cells seed cells (perhaps all?) and still maintain an acceptable performance footprint for tool time usage.  For offline usage though this method is already very acceptable (a few seconds for an average mesh and a maximum depth of 5) even with all the CPU read-backs I’m performing.

Sample Code

I’m still working on an improved version of the Generating Occluders for Hierarchical Z-Buffer Occlusion Culling sample.  So the code is a bit tied up at the moment.  However the next post I do on generating the occluders will contain it, which should be soon.

Robust Inside and Outside Solid Voxelization @ altdevblogaday.com

Published Achievement Unlocked!

image

The September 2011 issue of Game Developer Magazine contains an article of mine!  They asked me to write an article for the “Inner Product” section summarizing the Hi-Z GPU Culling algorithm as well as the related research I started working on to automatically generate occluders for the runtime.

My copy hasn’t yet arrived in the mail so I don’t know how the final version turned out, but the last draft I saw after the good folks at GD Mag spruced up the language in my article was looking really good.

It was a lot of work putting the article together, more than I actually thought going into it.  Especially since I already had 3 blog entries to pull from.  However, you find yourself second guessing everything you write because it’s not like a blog entry that you can go back and edit if there’s a mistake.

It also becomes a bit more of a challenge to summarize things that you simply can’t add a link to and tell the reader, go read this.  Also, not being able to just insert a huge chunk of code makes explaining something simple often a lot harder to explain in words.  Hopefully you’re good at making diagrams in those situations.

It was an interesting experience.  Really glad I got the opportunity to contribute an article.

SWIG: Casting Revisited

A while back I wrote SWIG and a Miss, which is a post about several of the problems I’ve encountered with SWIG. At that time I didn’t have a solution for dealing with down casting – the process of casting from a base class to a more derived class.

I ended up coming up with a solution that I thought would be good to do a post on, since there doesn’t seem to be much out there on SWIG and these types of problems.

Some Background

For those unfamiliar with why it’s difficult, let me explain. When your API returns a native pointer to be wrapped, of lets say class Foo, and your function returns Foo* but the instance it returns is actually the more derived version Bar. Sadly SWIG has no way of knowing this, so the object it creates in C# would be a C# Foo class. Therefore, if you tried to cast the C# Foo to the more derived C# Bar you’d be unable to because as far as .Net is concerned the instance of Foo is just a Foo and nothing more.

Alright now that you understand the problem, lets talk about how we can solve it.

How We Can Solve It

The solution to the problem can be solved in essentially 3 ways,

1 // Walk Away

Simply don’t do anything that would require it. Don’t expose classes that users will ever need to downcast to for any reason. If this option is available to you, take it. This however means that your base class needs to support all the functionality a user will ever need, something not always possible or desirable. But if you can, do it, because once you get to script land, down casting becomes a expensive process.

2 // Manual Cast Wrapper

Write or generate C++ functions for every downcast that you would like to perform and SWIG those functions. This would allow you to take object Foo as a parameter, returns Bar, does the dynamic cast in C++ and returns the pointer to Bar.

This option is manpower intensive and is truly brute forcing a solution. It also causes potential holes where nasty aliasing occurs and can become a real problem if the source object is ever deleted. Imagine an API with a factory function that returns object Foo, but Foo is actually Bar due to the way the factory works. You need to access a Bar specific only function on the object so you downcast Foo to Bar.

Now in C++ these objects are the same object, but SWIG doesn’t know this, so two completely different C# objects are created one wrapping the native pointer to Foo, and one wrapping the native pointer to Bar. If the SWIG layer was properly authored, the factory function notes that the object returned was created with new memory and thus SWIG is responsible for deleting the object.

So we call our Bar specific function and we decide to hang onto Bar and we let Foo on the stack pass out of scope, because why hang onto it, it’s the same object as Bar…right? But Foo was responsible for managing the memory for the common native object they both point to. So the underlying native object is destroyed when the garbage collector runs next after Foo is no longer referenced and now our Bar object points to totally bogus memory.

3 // Custom Solution

The solution I ended up coming up with requires you to have a custom RTTI system that allows you to check if an object is a specific type by name.

The first step is to extend the C# wrapper for your base class with RTTI information. If you don’t have a base RTTI object this will be a bit harder. The reason we have a new m_castedSource member variable is to solve the aliasing problem. After the cast we can store the source here so that we never have to worry about the garbage collector accidentally cleaning up memory we’re still using.

C#
%typemap(cscode) YourBaseRTTIObject
%{
    internal YourBaseRTTIObject m_castedSource;
 
    public bool IsKindOf<T>()
    {
        // Use your C++ RTTI system to test if this wrapped C# object's
        // native object is a 'typeof(T).Name'
    }
%}

The next step is to create a function that can create the C# method needed to factory the C# object. We could use reflection, but that method is slow and we can do a far better job by emitting IL at runtime to specifically initialize one type and just cache those created methods.

C#
private static Dictionary<Type, Func<IntPtr, bool, object>> constructorCache =
    new Dictionary<Type, Func<IntPtr, bool, object>>();
 
private static Func<IntPtr, bool, object> CreateConstructorDelegate<T>()
{
    // We need to first grab the reflection information for the more derrived type we're casting to.
    // SWIG has protected constructors we'll be able to call that take 2 parameters, the native pointer
    // to the type and whether or not SWIG owns the memory
    ConstructorInfo ctor = typeof(T).GetConstructor(
        BindingFlags.Instance | BindingFlags.NonPublic, null,
        CallingConventions.HasThis, new Type[] { typeof(IntPtr), typeof(bool) }, null);
 
    // Lets emit some IL that will allow us to construct our type much
    // faster than using reflection.
    DynamicMethod dm = new DynamicMethod("Create", typeof(object),
        new Type[] { typeof(IntPtr), typeof(bool) }, typeof(T), true);
    ILGenerator il = dm.GetILGenerator();
    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldarg_1);
    il.Emit(OpCodes.Newobj, ctor);
    il.Emit(OpCodes.Ret);
 
    // Create the delegate for the dynamic method, which will further improve the calling speed.
    return (Func<IntPtr, bool, object>)dm.CreateDelegate(typeof(Func<IntPtr, bool, object>));
}

After that we need to add a function that can perform the down cast. This is just a matter of checking if the object is actually the desired casting type. If it is we get or create the factory delegate for the type. We construct the new wrapper object and hand it the pointer for the type. (NOTE: This is only viable if the new type isn’t offset in the vtable, as would be the case with multiple inheritance).

C#
public static T CastTo<t>(YourBaseRTTIObject self) where T : YourBaseRTTIObject
{
    if (self == null)
        return null;
 
    // Check if the object is actually the type we're trying to cast to.
    if (self.IsKindOf<t>())
    {
        Type type = typeof(T);
 
        // Check if we've already cached the factory function.
        Func<IntPtr, bool, object> factory;
        if (!constructorCache.TryGetValue(type, out factory))
        {
            factory = CreateConstructorDelegate<t>();
            constructorCache.Add(type, factory);
        }
 
        // Call the factory function and set the casted source to the
        // current object.
        T castedObject = (T)factory(YourBaseRTTIObject.getCPtr(self).Handle, false);
        castedObject.m_castedSource = self;
 
        return castedObject;
    }
    return null;
}