Porting: OpenGL and Shaders

Getting a new graphics API running in an existing game engine is somewhat painful – there’s always some kind of issue or architectural oversight that doesn’t meld well with new APIs. But the game engine for Banished is written in such a way to abstract all the graphics functionality behind a common API, so porting it isn’t as awful as it could be. The game can already switch between DirectX 9 and 11 at runtime, so adding OpenGL to the mix shouldn’t be too bad.

However, there’s a critical mass of code required to get even the simplest graphics to display.

Vertex Buffers need to be implemented to store mesh data, as do Index Buffers. Vertex Layouts need to be defined to tell the GPU how to read that mesh data. Constant Buffers are needed to send uniform constant data to the GPU for use in pixel and vertex shaders. Render State needs an implementation – it tells the GPU how to blend new geometry into the scene (transparent, solid, etc), how to update depth and stencil buffers, and how each triangle gets rasterized. Vertex Shaders are needed to transform mesh data into something that’s a triangle on screen, and Pixel Shaders are needed to read textures, performing lighting, and output the final color for each pixel.

All that just to get a simple triangle on the screen.

Once that triangle is displayed, textures need to be supported – there’s 2D Textures, Cubemaps, compressed formats, mipmaps, copying textures, and scaling of images – lots of code there. Then Render Targets need to be implemented to be able to render off screen buffers and render shadow maps.

Only then will the renderer be complete. Once I get all that code done, the game should just render properly with OpenGL. It’s all common code at the level of drawing a building, the terrain, UI, or anything else.

It’s only about 80K of code, but getting it all right takes some debugging time.

OpenGL has a few items that DirectX doesn’t – like Vertex Array Objects and Shader Programs that pre link vertex and pixel shaders. Not a big deal, but these are things my engine wasn’t designed around, so there are a few hoops to jump through.

All this implementation is fairly mechanical – with a good OpenGL reference none of this is terrible – but I’ve been struggling with how to implement one particular item, and that’s vertex shader and pixel shaders.

At its simplest, a shader is a short program that tells the GPU how to deal with mesh data, or how to color a pixel. Each API (DirectX 9, 11, OpenGL) tend to have they’re own way of specifying these programs. For each API, a slightly different version of the same program is required.

For example, here’s a simple vertex program written for DirectX 9, HLSL for Shader Model 2.0/3.0. (I didn’t actually compile any of these… so forgive minor errors)

uniform float4x4 g_localToView; void main(in float4 iposition : POSITION, in float4 icolor : COLOR0, in float2 itexture : TEXCOORD0, out float4 oposition : POSITION, out float4 ocolor : COLOR0, out float2 otexcoord : TEXCOORD0) { oposition = mul(g_localToView, iposition); otexcoord = itexture; ocolor = icolor; }

Here’s the same vertex program, written for DirectX 11 – HLSL 4/5 – fairly similar, but there are some differences. There are more differences in more complex cases, such as texture sampling and dealing with input and output registers.

cbuffer globals { float4x4 g_localToView; } void main(in float4 iposition : POSITION, in float4 icolor : COLOR0, in float2 itexture : TEXCOORD0, out float4 oposition : SV_Position, out float4 ocolor : COLOR0, out float2 otexcoord : TEXCOORD0) { oposition = mul(g_localToView, iposition); otexcoord = itexture; ocolor = icolor; }

Now, the OpenGL GLSL 3.3 version:

uniform Globals { mat4 localToView; } globals; in vec4 iposition; in vec4 icolor; in vec2 itexture; out vec4 ocolor; out vec2 otexcoord; void main(void) { gl_Position = globals.localToView * iposition; otexcoord = itexture; ocolor = icolor; }

Currently, the game engine supports just DirectX 9 and 11 – and those shaders are close enough to be able to switch between them using some generated code for the constants and some macros to account for language differences. It’s probably possible to do the same with GLSL, but I’m not keen to do so.

I’m generally not a coder that worries about future proofing code – I write what I need now, and refactor when needed. But I already refactored my shaders when I added DirectX 11 code, and I’m doing it again now for OpenGL’s GLSL language.

If one day I want to include support for other hardware that has programmable GPUs, more versions of these programs are required. Banished already has 50-60 different shaders, so for each new platform supported, there’s the same programs to implement over and over. There’s already other shading languages out there that I’m not currently targeting, but may do so in the future – There are differences for OpenGL ES, OpenGL 2, OpenGL 4, Vulkan, Xbox 360, Xbox One, PS3, PS4, AMD Mantle, and DirectX 12. There’s probably more I don’t know about.

There are a few solutions to this:

Option 1. Just deal with multiple versions.

This is really not ideal. What’s frustrating here is during development, these shaders are often in flux – and updating many programs that do the same thing is error prone and a bit wasteful of time. This would be like writing Banished in C on OSX and C++ on Windows. It’s not as much code, but you get the idea. Not much point to implementing the same thing different ways when the result is identical. Worse is that since I use the PC for development, I’d probably get lazy, only update the PC shaders, and then when I want to test on another platform, would have to spend all day updating shaders in other languages.

Option 2. Use macros, find/replace, and partially generated code to account for language differences.

This is the option that is currently in use. It works, but it’s not future proof. The more languages that are supported, the more macros are used, and the messier the code gets to look at. If you’ve spent time modding Banished and looked at the shaders, you’ll notice all the crap around the actual body text of the shaders to make them compatible just with DX9/11. There’s also a lot of #ifdef/#else/#endif code sections to account for differences between the two. It’s messy. I can get this to work for OpenGL, but it still requires at least one more refactoring of all the shaders.

Option 3. Use an existing tool, like HLSL2GLSL

This is a good option. There are some tools to convert from HLSL to GLSL, but they don’t support as many languages as I’d like. It could work for the OpenGL version of Banished, but that’s about it. I could probably modify the tool to output other languages, but I really don’t like messing with other people’s code. (Yup, I’m one of those coders…) Additionally I’d prefer the language I use not be pure HLSL of some specific version. I’d like a language that would be updated to support new hardware features. Nvidia provided the Cg language for a while, which targeted many platforms, but development has been discontinued, so it’s a no go for future proofing.

Option 4. Design a new shading language that can be read in and then output any language.

To me, this is the best option, but one I’ve been trying to decide if it’s worth the effort. I basically would have to write a compiler. It’s not a small undertaking, but it has advantages. There are things I never really liked about HLSL, and I’m finding I don’t like GLSL that much either. Both languages are very C like, but they don’t need to be – I’d rather see a language that is designed around the hardware rather than looking like the code that everything else is written in with special syntax just to bind certain variables to hardware features. My own language would give the freedom to implement just the features I need, and add features as they are needed. I’ve been thinking about my ideal shading language for a while (being a graphics programmer and all) but never really saw a need for it. With my own language, my engine would become API agnostic. I’ve got my own graphics layer anyway, that hides the platform specific details, so having a shading language to match would make sense. Plus, never having had written a compiler, it’s one of those programming tasks that my fingers are begging to implement. To do this, a fairly feature complete compiler with proper parsing, semantic checking, type checks, symbol tables, full error messages, and more would be required. It’s a big project.

Option 5 – OpenGL Only

I could just limit the engine to using OpenGL. However this is more restrictive than I’d like. It would support Windows, OSX, and Linux, but in the future it would limit me to only working on OpenGL systems. Granted, it’s a pretty large set of systems, but I don’t see any reason to do this since I already have DirectX implementations working and a framework for supporting multiple graphics APIs and hardware. I’d like to make console games again one day, and OpenGL tends to either not be available on them, or it isn’t the base graphics library which gives full GPU control.

Option 6 – Node Graph or Alternate Representation

Shaders could be built using an alternate representation, like the node graph material editor in Unreal and some other game engines. The idea is to use small blocks each with their own snippet of code, and link them together visually. For each target language, a different code snippet would be used per node. This type of system can be a great tool for prototyping features and allows non-coders to generate shaders. It’s fairly hard to generate invalid code. It also allows for multiple types of outputs to any shading language. However, this type of tool takes a bit of code to implement, quite a bit of UI. There’s still a significant code generation step, and hand coding of each node in the graph for each language. In an environment without a large number of artists, this may also be overkill in terms of toolset. The game engine that Banished runs on only has text inputs without any visual tools, so adding this type of tool probably doesn’t make a whole lot of sense.

Decision?

I’m writing a compiler. It’s the most flexible solution, so that’s what I’ve been working on the past two months (well, a few other things too, including some other tools, and going to GDC)

I’ve been thinking about this language issue for a long time, designing and changing the syntax, and making sure I can extend it to geometry shaders (and other hardware features) at some point. I’ve also been looking at the feature set that all current shading languages are providing and making sure I can provide the full feature set I need for the games I make and the hardware I’m targeting.

While it’s been a slower road to getting done, I’m pretty sure at this point my own language that does just what it needs and has a clean syntax is the best thing.

I still have to do one more refactor of all the shaders in the game – but as that’s required anyway regardless of what I do to make OpenGL work. If I end up porting Banished to some other platform with a different graphics API, I’ll be able to just write a new output for the compiler. The next game I make will just be portable to any system.

At this point I’ve got most of the compiler written. It reads in my syntax and can output GLSL 3.2, HLSL 2/3, and 4/5 and I’ve converted enough shaders that the UI terrain, and buildings show up in game.

As a side motive, I’m excited to be writing a compiler – it makes me start thinking that the next game I make could possibly have a scripting language for game code – but that’s a ways off.