So, I rewrote my game in C3
If you are wondering, I wrote this myself with my own two hands. Writing is a nice way to organize my thoughts, I should do it more.
Over the past few months I’ve been working on rewriting Traction Point in C3. All the Zig code in the game has been replaced with C3, and the modding SDK will follow when the next playtest version is released. Why, you ask? Well, ever since I made it possible to hot-reload the game code, it has become an integral part of my workflow for developing the game. Want to tweak a UI element? Make the change and hot-reload the code while the game is running, and it shows up. An animation needing a longer ease-in? Hot-reload and you will see it in seconds. Need a temporary print in the code to isolate a bug in the state of the game? Hot-reload.
The problem with Zig is that building code on Windows is sloooow. These days Zig has a self-hosted backend which compiles code relatively quickly, at least in debug mode, but unfortunately it’s not yet available on Windows. They even added a form of incremental-compilation, but it doesn’t remove the long LLVM linking times. To give you an idea of what I am talking about, a full build of the Traction Point debug configuration, at a little over 100k LoC of Zig, takes around 24s. Changing a single line and rebuilding, with a warm cache, takes over 15s. C3 compiles the full game, without caching, in about 3s. I’ve seen it be as fast as 2.6s. Now, this is podracing! It will probably get a bit slower before the game is done, as more code is added, but I am sure you can see the benefits here.
What is C3 anyway?
C3 is not as widely known as other modern systems programming languages, but it fits the project perfectly. I wanted a language that could act almost as a drop-in replacement for Zig. That meant the memory model needed to be the same (no GC, no RAII), it needed to compile to WASM (for mod support), it needed to be fast (obviously, we are making a game here), and it needed to compile quickly. Preferrably it also would be somewhat easy for other people to pick up, and while I am personally quite fond of the Zig syntax, going with a C-derived language like C3 makes a lot of sense for attracting modders in the future.
Q: But what about Odin, Rust, Jai or HotNewLanguage™?
A: Yes, some of those might have fit the bill too, but I went with C3.
For my purposes, Zig and C3 were similar enough that almost all of the concepts used in the code could be ported over one-to-one, and I could do an almost mechanical translation of the code, which I think was the only way this port was ever going to happen. Let’s see what the new code looks like, by grabbing a few pieces from a random game component:
struct WireRendererComponent @Component("means.WireRendererComponent")
{
GameObjectComponent context;
RenderObject renderObject;
CurvePath3D curvePath;
uint pointCount;
// Exposed properties:
WireRendererGeometryMode geometryMode @Exposed(WireRendererGeometryMode.CURVE_PATH_3D);
AllocString curveDataBlockName @Exposed("");
uint curveSampleResolution @Exposed(16);
AllocString point0Object @Exposed("");
AllocString point1Object @Exposed("");
AllocString materialRef @ExposedResourceRef(ResourceTypeID.MATERIAL, "");
}
// ...
fn void WireRendererComponent.createVisualCurvePath(&self)
{
RendererPtr renderer = self.context.getRenderer();
SceneNodePtr parentNode = {};
bool createDedicatedNode = false;
GameObjectPtr gameObject = self.context.getGameObject();
self.pointCount = self.curveSampleResolution;
MeshGeometryPtr geometry = mesh_geometry::newGeometry();
defer geometry.deinit();
MeshGeometryLodLevelPtr lod0 = geometry.addLodLevel();
MeshGeometrySubMeshPtr subMesh = lod0.addSubMesh(VERTEX_FORMAT_TYPE);
self.generateIndicesCurvePath(subMesh);
self.generateGeometryCurvePath(subMesh);
MeshSource meshSource =
{
.kind = MeshSourceKind.MESH_GEOMETRY_IMMUTABLE,
.meshGeometry = geometry
};
self.renderObject.init(
renderer,
RenderObjectInstanceType.IMMOVABLE,
meshSource,
self.materialRef.str(),
parentNode,
createDedicatedNode,
gameObject);
}C3 supports annotations, both built-in and user-specified, and we are using a few above. Tagging a struct with @Component now makes the game engine treat it as a game object component. Exposed properties, ie. fields you want to show up in the level editor inspector, are just normal fields with @Exposed (or one of its variants) at the end, and the engine handles the rest. Overall, the code is pretty similar to C#, or even C++. The most obvious new thing is probably the fn at the start of the function signature.
You can see that C3 supports defer just like Zig, so much of the lifetime management and scoping was just a straight copy-paste. In fact, much of the code inside createVisualCurvePath() is literally the same as it is in Zig. C3 is also similar to Zig in the sense that it is explicit about many things. There is no RAII, but C3 offers temporary memory pools as a built-in thing, which is nice. Also, you can overload operators for things like math types, so we can do stuff like this:
// If we have turned to roughly face the target point, or turned almost 180 degrees, we are done.
Vec3 vehicleToTarget = (self.targetPoint - currentPosition).normalized();
bool reverseTurnComplete = vehicleToTarget.dot(currentForwardDir) > THRESHOLD || angleDiff < -THRESHOLD;How was the porting done?
To be honest, I can’t imagine a better codebase than Traction Point for doing a rewrite like this. Some of you might remember that we already took a look at C3 almost a year ago during a live stream. I’d been experimenting with making it possible to mod the game in different languages by compiling the mods to WASM and running them in a WebAssembly runtime. Thanks to this, one could already do some basic things in C3 back then, and it served as an excellent starting point for the porting work.
The first order of business was to expand the modding SDK for C3 enough to build and run the flying scout example mod. I can’t stress enough what a luxury it is to be able to continue running the game, while porting more and more of it to a new language, and testing that new functionality in a mod. I was able to port almost all of the game engine’s APIs over to C3 while keeping the Zig version running. Only when the most tricky binding issues were resolved did I start porting the actual game code over to C3.
The Traction Point game code is a dll loaded by the game engine, which itself is written in C++. Because of this, I needed to start by replicating the entire dll interface to the game engine in C3, since otherwise the engine would reject the dll outright. However, once the API was in place I could simply take one system at a time and port it over from Zig. I even did some of it live on stream! I gave myself a hard limit though: The game data could not be touched in any way, but needed to work with both versions until I was sure the C3 port would work out. In the end, it wasn’t really a problem. The biggest issues were related to json parsing, of all things, and had to do with how Zig’s and C3’s std lib json libraries handled default values for missing data.
We need to go faster!
Okay, so with C3 we can compile a development build of the game into native code in a few seconds. But what if we want to compile it even quicker? What if we have a tool that generates C3 code on the fly as you are using it, and we want the running logic to update more or less immediately, not after a few seconds? This is exactly how my particle editor works. In the image below you can see the particle editor being used to author a fire effect using a graph of nodes.
Each node in the graph contributes a small piece of C3 code which, when put together, make up the effect at runtime. You can see the code change in realtime (on the left) when you edit the graph. You don’t normally view the code at all, you just look at the graph, but it’s handy to be able to view it to see what is happening under the hood.
Now consider what needs to happen if we want to compile the code as it changes to get an updated effect in the preview window. First of all we’ll need to compile it to a dynamic library, ie. a .dll (or .so, .dylib) so that we can unload it, rebuild it and reload it while the app is running. This can get gnarly (eg. it’s easy to have the library locked by a second running instance) but it can be done. The bigger problem is the multi-second compilation that needs to take place between each modification.
Some of you might be thinking, why compile the effects to code at all? Why not just have an interpreter that executes the node graph? And yes, I support that too. The runtime performance is not as good as when compiling a graph to code though, where everything can be inlined and unused logic can be stripped out completely. This is kinda similar to “blueprint nativization” in UE4.
So, with this in mind I set out to build something that would allow us to hot-reload C3 logic very rapidly during the development phase, while still maintaining excellent runtime performance for the shipped game. I am calling it SL3 (Scripting Language on C3) and it is a strict subset of C3 which runs either as bytecode or natively, using the same interface to the host application. You can compile to bytecode and run on a register-based virtual machine for maximum iteration speed, and then compile to a native dll (using the official C3 compiler) to generate blazingly fast runtime logic. The SL3 compiler supports bundling together multiple bytecode modules and passing the code to the C3 compiler to build a single dll, to avoid having to load hundreds of dlls at runtime.
SL3 being a “strict subset” of C3 means that not all C3 code is valid SL3, but all SL3 code is valid C3. Some of the more advanced C3 functionality, like contracts, semantic macros etc. are not supported in SL3 (yet). Also, memory management and access is somewhat limited in order to sandbox SL3 code from the rest of the app.
It is still early days for the system and I have a long list of things I want to implement, but it is already very usable. And while the VM could be faster, it runs all of the particle effects created for the game so far, at 60fps with room to spare. On my pretty humble development machine, you can even run the demo mission with all effects running on the VM, and you barely notice any difference from the native version.
To give you an idea of what writing SL3 looks like, here’s the SL3 code for one of the simpler nodes, the one which kills a particle:
// Merlin.Nodes.Particle.KillParticleNode
module kill_particle;
import solmu;
import merlin;
import sl3::host;
const int INPIN_IN = 0;
fn void pins() @HostCall
{
solmu::declareInput(INPIN_IN, solmu::TYPE_EXECUTION);
}
fn int update(solmu::Context ctx, int entryPin)
{
merlin::kill(ctx); // This kills the particle we are currently simulating.
return solmu::STOP;
}The code declares a single input pin in the pins() function. The update() function runs when the node executes, and it typically gets inlined away in the native version. In SL3, functions tagged with the @HostCall attribute can be called from the host application. This isn’t how pins() is normally called (instead it’s called from within the SL3 module itself) but tagging it with @HostCall means that outside code can call it to query information about the node type.
For now, SL3 is only used for the particle effects, but it could be expanded enough to be a valid general-purpose scripting language in the future. Taking the SL3 code and generating shader source code from it, for running the particle simulation on the GPU, would also be a very interesting thing to do in the future.
If you want to talk more about C3 or gamedev in general, try out the playtest of the game, or otherwise just hang out feel free to join the Madrigal Games Discord server. We also have a YouTube channel with lots of videos and devlogs. The live streams have moved to a new YouTube channel so check it out if you want to follow along in real-time.
