oldcode Archive

Introduction to SMEG

Introducing SMEG

In this post I’m going to introduce the SMEG adventure game system that I’m creating to build my ZX Spectrum point and click adventure.

What is SMEG?

SMEG stands for Scriptable MachinE for adventure Games, a very tenuous play on words that pays homage to Lucas Arts’ SCUMM and one of my favourite TV shows, Red Dwarf.

Rather than just being a fun acronym, it nicely describes the approach and the architecture of the system.

An overview of SCUMM

Why are you talking about SCUMM? I’m here to learn about SMEG!

To understand SMEG, it is worth getting familiar with SCUMM and what it was about.

Let’s start at Wikipedia for a hand. The original version of SCUMM was created by the legendary Ron Gilbert for the game Maniac Mansion.

It’s entire purpose was to provide an abstraction from the machine and the content, allowing people to use commands like walk bob to door instead of having to know that the character bob was memory location $6A00, the door object was at position 130,90 and the walk command involved playing animation, path finding and moving the character between frames.

As mentioned in the Wikipedia article, the system is somewhere between a game engine and a programming language. They exist in a symbiosis that’s balanced around the creation of point and click adventure games.

For a system that was designed and built in 1987, it was very advanced - and is still a very elegant way of approaching the adventure game genre. The idea still persists today in the form of Adventure Game Studio and other similar tools.

Ask me about SMEG

SMEG is my attempt at creating such a system for the ZX Spectrum. It started out as me messing about and making a simple crude Monkey Island-esque demo for the Speccy and it has morphed and blown up into my making SMEG (along with a companion game demo).

I didn’t start intending to build a SCUMM style system, moreover it started creating itself based on the complexity and requirements of building the content in Z80 assembler.

Previously, everything was hard-coded into the demo and I found that adding a new dialog, a new character, a new object, etc became quite a tedious and error prone task. The more items I added, it made it harder and harder to change the data structures and code that used those without breaking things.

A very clear example that stands out to me was adding something as simple as a status flag to the “stage object” structure caused a load of subtle bugs and even crashes when the code worked on that data. Remember that in Z80 assembler we have no type checking, and often accessing the data can mean incrementing the HL register, or some other offset-based lookups. Things broke a lot and I found that I was spending more time fixing existing things after a change that I stopped adding new things for a while.

The SMEG “engine”

SMEG Screenshot

The SMEG engine is currently designed around several core concepts:

  • Stage - A “room”, comprising of actors and props. The background of the room is defined as a tilemap.
  • Actor - A walking, talking being
  • Prop - An interactable object on the stage. It may or not be visible
  • Ego - the player’s actor
  • Inventory - A collection of objects in the ‘pocket’ of the Ego
  • Verbs & Sentences - Verbs are the ‘actions’ that the Ego can perform (Look, Walk, Take, Talk). These are combined with Nouns (such as Actors, Props, Inventory objects) to do something.
  • Dialog - Conversation system
  • Script - A virtual machine that ticks away and schedules the next sentence for execution.

The SMEG engine handles the drawing of the room, the sprites and all of the cursor interactions with the world. The beating heart of the system is a very simple bytecode-based virtual machine that runs the script actions, such as an actor saying a dialog line or walking to a position.

The “verbs” I have chosen are the standard 9 that is used by most SCUMM games, but in reality they may drop to 6, with things like “Use”, “Pull”, “Push” being largely the same, for example.

Verbs are important as they’re the basis for the “things you can do” in the world.

SMEG overview

SMEG Overview

The SMEG System has three phases a project goes through to turn into the end “game” that you can run on your Spectrum.

  1. Content Creation
  2. Content Build
  3. Compilation

These phases are as it is now, and are very likely to change as time goes on - especially the final stage. More on that later.

Content Creation

Content creation is the “fun” part, where I can build scenes, write scripts and generally build the stuff you see and interact with.

Making a room

I’ve adopted the open source map editor Tiled to build the rooms. It’s really easy to use and has a format that is easy to parse and process by my tools.

As you can see in the screenshot above, the room background is made up of a tilemap, with Tiled’s object system providing the basis for how you specify objects and their scripts in the room.

I have a convention-based approach of assigning the verbs to the objects, using the Tiled object property system to hold a lot of the data.

As you can see in the screenshot, there is a rudimentary scripting language (SMEG Script) that lets you direct what happens when a sentence is run.

    walkTo <actor> <position>
    pickUp <actor> <object>
    speech {
        line <actor> <text>

The language is currently based around Tcl, but will likely move more towards a simple C syntax as I feel most comfortable with that.

Anything that lives beyond the scope of a room lives in a SMEG Project file, a simple json file that has information about the actors, the sprites and the rooms.

Dialog and speech currently lives in the Tiled map files, but it is very likely that they’ll move into a separate set of files soon - mostly because it feels the wrong way to be authoring them.

Content Build

The content “build” stage is what takes all of the content files and turns it into something that the SMEG engine can actually use. This stage is captured by a single custom tool called the SMEG Build Tool.

This is a .NET Core project that presently, at least, is a crude Z80 code generator. In essence, this was the utility I created to make it easier for me to get content into the game, without having to write the Z80 structures.

Originally a single-pass emitter, it has gradually moved into requiring two passes over the assets, mostly because it can then perform lookups and validation on those objects.

This is handy as it allows me to move a lot of the validation away from the runtime (where it would be slow) and into this tool - where I can do it much more easily and across the entire project.

The SMEG Build Tool is also the SMEG Script compiler that turns the human readable instructions into bytecode that the SMEG VM can execute.

The Z80 emitted by this tool contains everything the game needs; the sprites, the dialog, the bytecode, the object definitions, the tile maps - everything.


The content file emitted is compiled with the engine source by SJAsmPlus into the final SNA/TAP file loadable by the Spectrum.

The reason for them both being compiled together is historical; the code and the content were originally together. The SMEG Build made it easier for me to work on the content, but I still needed to see the assembler to help with debugging.

One thing that I will be moving away from is the content being compiled with the engine. There’s many benefits to this; namely that I can compress rooms to get more into the Spectrum’s limited memory and to allow multiload content, effectively allowing for much bigger games. This is all something that needs to be looked at, but it is really the best direction to be taking.

This likely means that the final compilation stage will turn into one of ‘mastering’, taking the compiled engine code and game data and laying them out in a form that can be loaded by the Spectrum.

The Future

Everything is still very early, but it feels like the foundations are taking shape. I’m building a game demo with SMEG and using that to drive the features and pipelines. I’m not really setting out with a goal in mind, just happy to let things evolve and then refine them as we go on.

When I’m at the stage of being “happy” with where things are, likely near the release of the game demo, I am planning to open source all of this for others to enhance and make their own content with. Open sourcing it now just isn’t the right time, especially as everything’s changing and in flux. The code is also pretty nasty, too :)


Some questions I have been asked, that I will answer here:

Which Spectrum models are you aiming for?

I’m currently working with 48K, because I’ve not added 128K support to my development emulator (neccy). I’d love to keep things within reach of the 48K models, but I’m not against changing this to 128K only if it becomes too constrained.

Are you targeting the NEXT/ULA Plus/etc?

Not yet. I don’t have either of these systems and trying to target them will mean forking the code - for the NEXT it means that much of the display code will need reworking. I would very much love to target the NEXT in the future, but first I’m focussed on the original model Spectrum.

What about Kempston Mouse support?

Will probably add this, but I don’t have a real mouse to test it on.

What about music support?

Likely to be added in the future. I may need some help here.

Why a new engine instead of porting SCUMM VM?

I wanted to make my own game for the ZX Spectrum, I never really set out to build a SCUMM like system, it just evolved that way.

When are you going to open source this?

When I’m ready.

When can I play the SMEG game demo?

When it’s ready.

Will there be a port for the C64/Acorn BBC/etc?

No idea. I’d love to consider something like this in the future, but right now everything is designed specifically for the Spectrum, so it may not ever mean content is “portable”.

Making a game for the ZX Spectrum in 2020

Making a game for the ZX Spectrum in 2020

One of the aims for me creating my Spectrum emulator neccy (short for not a speccy) was so I could learn the ins-and-outs of the Spectrum - something I never did when I was using this machine back in the 80’s.

“What better way to learn it”, I thought, “than to create an emulator?". As it stands, writing an emulator for a 35+ year old machine is really only part of the puzzle. I liken it to understanding all of the notes and function of an instrument but then being absolutely clueless when it comes to playing a tune.

I am a person who learns through having a challenge; I simply can’t sit and read tutorials and copy/paste examples and expect any of it to stick. I have to have something that I believe in, something to motivate me. I also have to be thrown in at the absolute deep end and have to figure it out.

Armbands included

One thing about coding for an old machine in 2020 is that there are still folks out there who are programming for, blogging about and playing games on such systems. I dipped my toe into the retro gaming waters on Twitter and found a whole host of helpful folks and resources.

Whilst one may be in the deep end of programming for the Spectrum, there’s definitely some armbands to help you say afloat. Two such resources have come from Dean Belfield and Jonathan Cauldwell, both of whom were coders for the Spectrum back in the day and are still active today.

One thing I will say, however, is that much of the information out there already pretty much starts on/near the “end state” for Spectrum development, immediately talking about sprite shifters, pre-shifted sprites - self-modifying scroll routines, often with very few visuals. It’s all very cool stuff and hugely impressive - but it’s several steps ahead of where I am in my own personal journey. As such, there’s a gap in the market for the very basic detail on some of the techniques. Maybe one day I’ll feel motivated to type up my notes that I’ve been making whilst I’ve learned from the masters.

Peer Pressure

Anyway - I had to decide on a project. What was I going to make?

Pong? That should be ok as a starter project right?

How about Tetris? I even started it!

Falling block

Everything changed one evening during a little bit of banter with a couple of retro folks on Twitter.

At the time, I was mucking about with a really simple Point & Click Adventure game engine in C-like C++ using the olcPixelGameEngine.

olc Powered Point & Click

I was part way through creating a simple SCUMM-like scripting VM and had some of the basic interactions in place.

And then I chimed into a Twitter thread.

A healthy dose of peer pressure from @SpectrumNez and @BreakIntoProgram and it pretty much gave me one of those irritating ideas that I couldn’t shake.

So you’re making a Point & Click game - for the Spectrum?

I’m not sure where it’ll end up, but yes - it seems that way.

It took a relatively short space of time to get a basic joystick-powered “verb” menu up.

Verb Menu

I was seeing progress - and I had a purpose, let’s keep going!

Once I had verbs, I needed something to do with them. So I put together a simple inventory.

Inventory Menu

This made me think about how to handle all the controls and areas of the screen. We don’t have a mouse on the Spectrum, so I decided to make this joystick-controlled. You can move between the verbs, then press fire to action it - from there the intention is that you can switch between the inventory and the “stage”.

All of this may change in favour of the floating “crosshair” type cursor, but for now I’m happy with how this works.

Now I could select verbs and navigate the inventory, I decided it was worth thinking about how verbs and inventory items interact.

At this stage, I have a simple item description:

    item_table: [ list of item offsets ]
    item_1: {
        verb_table: [ ... ]
    item_2: {....}

Using this, I could start putting dialog descriptions with the items associated with a “Look At” verb.

In Z80 it looks like this:

	.db 8,"Powder"		; item label
	.db 1			    ; action_count
	.db VERB_LOOK		; actions[action_count]
	.dw dialog_powder_look

I’m using two types of strings in the demo at the moment; one which is zero terminated, the other which is length prefixed. The length prefixed ones let me jump past the strings very quickly, but this is only effective if they’re inlined. In future I may scrap this for pointers to zero-terminated strings. But it’s fine for now.

Inventory Item Descriptions

It’s all very rudimentary but it’s quite nice to be able to start interacting with the system. It’s also brought together a few things; displaying text, timers and basic user interaction.

With that in place, I’ve spent some time learning how Sprites work on the Spectrum. In short, they’re annoying - and thanks to @BreakIntoProgram it’s made understanding things a lot easier. One day I’ll have a go at writing my own step-by-step technical breakdown on the subject, mostly scribing my notes into a blog for you to digest.

With some rough code to handle sprites in place, I needed something to actually show. Using AESprite, I cobbled together a 16x48 character that (depending how hard you squint) may or may not resemble a certain iconic pirate who visited a place surrounded by water that is inhabited by primates. Don’t worry, I’ll change it.

Talking sprite

What next?

Seeing the animated sprite saying a dialog line made it all feel very “real”, inspiring me to continue with the demo.

The way I see it, there’s three logical places forward:

  1. Implement a dialog system and a conversation between two on-screen characters
  2. Implement player interaction with the stage; pick up item, use item.
  3. Implement the ability to move your character around the “stage” area, swapping between screens.

There’s probably more, but those three points feel like the next natural steps - so that’s what I’ll do!

With this in mind, I need to start thinking about a way to structure this game data better; we need a system that can describe scenes, items, characters and their various interactions. SCUMM did a good job of this; perhaps it’s a model I can explore along with more modern ideas.

Either way, I need to be mindful of the constraints in place when developing for the Spectrum.

I think the next few days I’ll scribble down a very small plot for a demo that involves a few different things. It won’t be a full game, but it’ll be enough of a demo to decide where we go from there.

neccy - Toy 48k Emulator Feb 2020 roundup

Hello again, neccy!

It’s been a while since I posted about neccy, my toy 48k ZX Spectrum emulator. It’s probably a good idea to remind ourselves where we were.

My next milestone is to get Sinclair BASIC working. After that, who knows - I’ll probably try and go for sound and then onto trying to run a game.

It’s a long journey ahead.

And here’s how it looked:

The Copyright Message

And this is what things look like today

neccy @ Feb 2020

A lot has changed since I last talked about this project!

Sinclair BASIC

One of the things I got working pretty soon after the last post was Sinclair BASIC. I had a few bugs in the Z80 emulation that caused basic to go wonky. The main thing that I got snagged on was that the offset to the IX/IY register is signed. I was treating it as unsigned, so in my emulation the offset was always positive.

I also had issues in the IO Read routines; I was assuming that no input was a zero byte (0x00), but in the Spectrum the value for unset is 0xFF. Somewhat counter-intuitive to those that are used to a 0 bit being “unset” and a 1 bit being “set”. It makes sense when you get closer to the hardware.

Speaking of hardware, I bought The ZX Spectrum ULA by Chris Smith - it’s a fantastic deconstruction of the ZX Spectrum hardware and has been invaluable for understanding many of the internal details of the system.

With all that working, Sinclair BASIC was up and running!

One thing that stood out immediately, however, was that the keyboard mapping is so very different to how modern computers work. This is true on the 128K Spectrum, but on the 48K model it’s even more extreme. BASIC commands are entered using a sequence of modifiers and keys that emit a full command.

As a result, programming on the spectrum using my laptop feels very cumbersome.

There’s a few QOL things I could do, such as supporting macros that would emulate the key sequences for backspace, but I haven’t done those yet.

It’s worth noting that pretty much all emulators suffer from this, as it’s down to the underlying system and not the emulators themselves. Either way, my career as a Sinclair BASIC programmer is very slow off the ground!

SNA loading & Z80 speed

Soon after getting BASIC up and running, I fel confident and added the ability to load a SNA file. These files are pretty simple, being essentially a copy of the registers and a dump of the RAM.

I was elated to see that Horace Goes Skiing just worked. There were no issues to speak of and I could play the game (badly) on my keyboard.

Horace on neccy

Shortly after, I got the CPU emulation running at full speed. I am running at exactly 3.5Mhz, so not quite the speed of a real speccy, but its good enough.

This threw up a few timing issues that caused me to implement clock timings properly. On the Z80, an instruction takes several cycles (T-States) to execute, for neccy I execute the full instruction at the first state and then basically do nothing for the rest. This is far from being perfect, but it’s enough for now. At some point in time I want to go back and emulate the Z80 with cycle accuracy, but that’s another story/project.

Using the SNA loading and improved timings I started trying to load some games. Pretty much all of them crashed, had glitches or relied on Z80 instructions I’d not implemented yet. I got so far as getting JetPac running, but was unplayable due to bugs.

I also added Kempston Joystick emulation at this stage as it was easy to do and allowed me to play games using my cursor keys.

Sound’s awful

It’s true, neccy does sound awful. It’s also true that I’ve had an awful time trying to get sound working.

As a bit of fun, I thought I’d add support for the 48K’s “beeper”, a one-bit audio signal. Easy, right?

neccy beeper signal

I began by following javidx9’s audio synth series on YouTube and plugging in the extension to the olcPixelGameEngine. It was at this point that I realised I know nothing about audio programming. Every sound that came out of the sound code was nothing but pop and crackles. It sounded terrible.

The audio extension to the olcPixelGameEngine calls my code back at a regular interval (I was using 22050Hz), essentially asking for a sample value at this point (-1.0f to +1.0f). I tried various things but nothing I did resulting in anything that even resembled the audio I was expecting.

Days passed with various aborted attempts at getting it to work and I just gave up and moved onto something else.

Goodbye olcPixelGameEngine

… well, sort of.

At this point I decided to move away from olcPixelGameEngine in favour of SDL2. There was one, sepcific reason to this, and it’s because I wanted to use dear ImGui. My hand-rolled GUI looked super retro and had a charm to it, but I kept finding it frustrating to work with when doing something new. I decided that I needed a new GUI system, and I didn’t want to write one.

I had a brief look at geting dear ImGui working with the olcPixelGameEngine but I decided that SDL2 would be better for me and would allow me to use SDL’s audio capabilities as well.

The thing with olcPixelGameEngine is that I really like the simplicity of it. It’s easy to work with; the abstractions over the various bits you need to do are intuitive and easy to work with - so I wanted to keep it.

What I ended up doing was to remove the olcPixelGameEngine implementation code, but maintain its interfaces - or at least the bits I was using. I ended up with a lightweight SDL2 SDLPixelGameEngine; I even kept the olc namespaces.

Unfortunately I lost a lot of the useful bits of code from PGE, such as the text output to a sprite, but I was going to move onto using dear ImGui so it wasn’t a huge loss.

dear ImGui

Armed with an SDL2 powered codebase, I was free to integrate dear ImGui into my code. A couple of issues cropped up, mostly around integrating the rendering systems but I managed to work around those pretty easily in the end.

The particular issue I had was having the neccy display render into a dear ImGui window. I was rendering to an SDL_Surface and had to figure out how to get dear ImGui to show it. In the end, I had to make sure the the SDL_Surface was associated with an OpenGL texture and hat I was refreshing that texture when things changed. After that, I could use ImGui::Image to show it.

Moving to dear ImGui gave me immediate benefits. I could have separate (movable) windows for all the things I needed debug displays of. The Z80 state, the disassembly window, the audio (beeper) signal and a bunch of other stuff.

dear neccy

Suddenly, adding a new debug window because effortless and made working on the emulator fun (again).

A huge boost came in the way that the author of dear ImGui had already built and released a memory viewer/editor for the library. It took minutes to integrate and offered me something far better than I had.

Z80 bugs everywhere

My Z80 had a boatload of bugs in it, here’s some examples of games that are buggy.

Buggy Manic Miner on neccy

Buggy Jetpac on neccy

Jetpac was bugged up; it’s there - but not quite. Lots of issues.

Buggy Kong on neccy

I really needed to iron out these bugs, so my attention turned to zexdoc/zexall.

zexdoc (and zexall) is a program that you run on Z80 powered machine. It essentially runs a ‘family’ of instructions and generates a Crc32 of the output (registers, flags & whatnot). At the end of each family it compares the result to a known Crc32 obtained from a real Z80-based computer. I needed to run zexdoc, but all I could find were TAP files of it for a spectrum and the original CP/M-based program.

TAP loading

As naive as I was, I opted for the TAP version of zexdoc (more on this later).

I set about figuring out how TAP files worked. Luckily, it’s quite simple and well documented.

Loading from TAP format is essentially simulating the pulse signals that a real tape would play to the Spectrum’s audio input. The loading is performed by the ROM itself.


Just loading the TAP format teased out several Z80 bugs. Finally, I got zexdoc running and… lots of tests failed.

zexdoc errors

zexdoc / zexall

zexdoc takes ages to run, so I added the ability to overclock the emulator. This proved handy as it let me run things faster, getting to the errors quicker.

Now began what I can only refer to as a slow grind. Finding errors and fixing them, one by one. Some errors literally made no sense. I looked at specs, undocumented opcode details, even other emulator source and couldn’t find what was wrong in some of the basic instructions.

Finally, I gave in and ran zexdoc on Fuse and found out we had the same set of errors!

Fuse zexdoc errors

I was both pleased but frustrated. I still had bugs - games still had issues, so where were they? I couldn’t rely on zexdoc to help me anymore, as many of the tests ‘failed’ but ‘passed’ in that they matched an established emulator. I needed a way to see the wood for the trees.

floooh to the rescue

I found a blog post by a chap called Andre Weissflog, that explained how he got zexdoc running in his rust Z80 emulation. Rather than using the Spectrum version of zexdoc, he was using the original CP/M version. Luckily for us, zexdoc relies on two CP/M OS calls - and these are very simple text output calls that we can trap and use to grab the output.

Better yet, the CP/M version of zexdoc run on the ‘naked’ Z80 and need nothing but an attached amount of emulated RAM. I was able to get a test up and running without having to simulate anything else of the Spectrum - no ULA, no screen output, nothing. As I didn’t care about timings either, I could make my CPU run at max speed, even skipping the emulated clock ‘wait’ timings I had to put in to get things running at comparable cycle timings to a real Z80.

Armed with this, I was able to rip through and fix a raft of Z80 bugs pretty quickly. It even forced me to implement a bunch of undocumented Z80 instructions and handle the flags correctly (including bit 3 and 5, the X/Y flag).

Current state of the Z80

I’ve fixed all but one failing zexdoc test:

ld <bcdexya>,<bcdexya>........  ERROR **** crc expected:478ba36b found:8088c9d9

zexall fails 5 tests:

bit n,(<ix,iy>+1).............  ERROR **** crc expected:83534ee1 found:9581a6ba
bit n,<b,c,d,e,h,l,(hl),a>....  ERROR **** crc expected:5e020e98 found:e6624aeb
ld <bcdexya>,<bcdexya>........  ERROR **** crc expected:478ba36b found:8088c9d9
ldd<r> (2)....................  ERROR **** crc expected:39dd3de1 found:405ca1c1
ldi<r> (1)....................  ERROR **** crc expected:f782b0d1 found:f531e964

I have spent hours - no, days - hunting down the ld bug and have had no joy. Out of them all, that’s the one that’s killing me most.

Current state of neccy

Games like Jetpac play now (even though I suck at it):

I suck at Jetpac

Many games, such as Uridium and Return of the Jedi either outright crash or never get past a specific point, like something doesn’t happen that they game expects.

Uridium crashes

I think that the issues are either in the Z80 itself (the ld bug?) or are down to expectations on hardware timings that I simply don’t handle yet.

For example, my emulation does all the Z80 work in one tick and lies dormant for the rest; as a result lots of data movement around the bus happens instantly instead of over a series of cycles. I don’t emulate the memory contention of the ULA in the ‘slow RAM’. I don’t emulate the ULA fetching bytes of screen RAM. I don’t emulate any floating bus values that many games use for timing to screen syncs. I’m convinced that my interrupt handling has bugs or quirks. My beeper audio is better, but still has issues because I still have variable frame times. I haven’t even looked at 128K stuff, like banked RAM or AY sound chips. Hell, I don’t even support TZX yet.

I still have a lot to do on this project.

With that in mind I decided to take a break from neccy for a bit. It was mostly down to complete burnout trying to trace the Z80 bugs. The ld bug in particular became days of grind that ended up in an all out death crawl - it completely killed the joy of working on this project. At least, for a bit it did.

Real hardware

Fortunately at the time of this Z80 emulation fatigue, a good friend of mine turned up one day with two Spectrums he found in his loft. He knew about my emulator project and asked if I wanted them - of course!

With this, I decided to get them restored by the fantastic Mutant Caterpillar - Ian & Alex did a fantastic job on the restoration, even doing the various magic mods that allows the Spectrums to work better with modern TVS. I bought a Zipstick and a divmmc future to enable loading from SD cards.

Now I can play Uridum!

Next steps

One of the reasons for me starting neccy was to have a pop at an emulator; but the other - more personal reason is that I wanted to have a go at making games for a system I owned when I was a kid. That was true back when I started it, and it’s even more true now.

I’ve been following Dean Belfield’s recent Spectrum coding and he’s really inspired me to have a go.

The next steps for me are exploring the various options for coding on a 30 year old computer in 2020.

See you next time. I’ll try not to leave it so long ;)

Hello, neccy

Hello, neccy!

It’s been a (long) while since I blogged. I thought I’d break the silence by talking about a fun little project I started.

I was working on a 2d physics based game and was getting frustrated by my own lack of maths knowledge. One night I watched One Lone Coder’s video series on building a NES emulator and it triggered a something of a nostalgia vibe in me.

Growing up, we never had a game console - instead my folks bought a ZX Spectrum +3. Although I was about 8 at the time, having a strange typewriter hooked up to the TV was fascinating to me. I eventually learned Sinclair BASIC and my programming life was kicked off.

The OLC NES emulator videos sparked off a very silly little idea - “I’m going to write a spectrum emulator!".

Not a Speccy

I needed a name for my new git repository - “Not a Speccy”, thus “neccy” was born.

First Shot

I’m coding neccy in C++ and am using the olcPixelGameEngine for the basic framework. I picked it as it seemed to be a nice little single header library and it alls all the tedious “new project” guff out of the way. I’ve not felt the need to move from it yet, so I will likely stick with it until something changes. Thanks to David (javidx9) for this little library, it has been very helpful.

Writing a Spectrum emulator naturally involves emulating the CPU, a Zilog Z80 processor. For an 8-bit processor there are actually quite a few instructions - especially if you try and emulate all the undocumented ones.

My emulation of the Z80 has been re-written 3 times so far on this project. I first tried to code-generate it from C#, which ended up in a bit of a disaster. The second variant I threw away as I was making too many assumptions and tried to over-generalise the ALU logic. This current version is “ok”, but needs some cleanup.

My emulation is very crude at present. I’m not simulating the various T & M states in the CPU, instead choosing to do all the fetch, decode and operation code at once and doing nothing for the rest of the cycles. In future this may change, but it’ll do for now.

Emulation is tough

If I’d realised how tough it was to write an emulator, I probably wouldn’t have started the project. However now I have, I’m pretty hooked on it.

For starters, you have to learn a lot about the machine you’re emulating. You have to understand the guts of the CPU, the memory maps used, how the screen is rendered, the various IO port mappings to handle peripherals; then there’s all the timings and everything else to get stuff working.

When I started the project, I realised I’d need to visualise what was going on. So the very first thing I ended up writing was actually a memory viewer and disassembler.


From here, I can see the state of the CPU and look at the program that is being executed. I started out writing my own little test assembler routines, but realised very quickly I needed something “real”. From here, I started to try and run the 48k Spectrum ROM.

I picked the 48k ROM as it’d be simpler than the later 128k models of the Spectrum, which had memory paging and better sound - if I ever get this thing “working” I’d probably try and progress to the 128k model Spectrum - but let’s not run before we can walk.

Running the ROM

I ended up deciding to implement the parts of the emulator as I went; adding the instructions as I needed them in order to run the ROM.

The this point I realised that I had to start actually understanding the programs I was running, which meant actually being able to read the disassembly of the ROM itself. Thankfully Skoolkit has a great 48K ROM disassembly, which has helped immensely.

When got to the point of the ROM that was clearing the screen, I decided to figure out how the Spectrum video memory worked.

This was “fun”, but resources like Break into Program and Overtaken by Events were a huge help.

Eventually, I was able to load a scr format file of my favourite game, Uridium.

Uridium Loading Screen

This was a very exciting milestone in the journey and the first time that I felt I was doing something right.

Dark Days

After this I had the next milestone in sight - I wanted to see the iconic copyright message text.

It turns out this was actually a while off; mostly due to lots and lots of little bugs and glitches in my Z80 emulation. Little things catch you out here - not setting the flags correctly, not treating 16 bit numbers with the correct endianness (which caused a stack stomp) forgetting that jump relative instructions need a signed operand and the one that took me far to long to figure out, a bug where I was treating LD BC,(NN) like LD BC,NN. Essentially operating on a pointer value instead of following the indirection.

Finally after lots of swearing and frustration I got to the milestone I set.

The Copyright Message

Current Status

I’m currently implementing the Keyboard IO with the aim that I can try and use Sinclair BASIC for the first time.

As you can see though, there’s a few glitches…

Input Glitches

One thing about writing an emulator is that it’s a case of fixing issue after issue, glitch after glitch… It’s frustrating at times (ok most of the time), but very satisfying when stuff starts to work.

My next milestone is to get Sinclair BASIC working. After that, who knows - I’ll probably try and go for sound and then onto trying to run a game.

It’s a long journey ahead.

OldCode (Manta-X) July 2017 Roundup

July 2017 Roundup

Wow, it’s been a month already? I’ve not written an update for a while, but it doesn’t mean that activity has stopped on the OldCode / Manta-X project.

Name Change

The last thing I did in July was to change the “internal” branding (namespaces, project names, etc) from “Manta-X” to “OldCode”.

Manta-X was always a code name, and one from the original days of the project (pre-rediscovery & updates, I may add). As a result, it feels ‘old’ in a way that I can’t really relate to anymore. I no longer remember the original premise or idea of the game, and there’s very little left that resembles the excavated piece.

I’ve come to associate this project as being “Old Code”, even though it’s now very different to it was when I unearthed it.

July Recap

Let’s go through the changelog and recap on the main areas of work last month…

Bye Bye 3D

At the start of the month I followed up on my promise and swapped over completely to a sprite-based approach using SDL_Texture. As a result, almost everything ‘3D’ was removed from the game. Models, vertices, OpenGL, the lot.

It took 8 checkins over 2 days to remove 3D and swap to sprites. Not bad, really.

Math Types

I changed how I do my basic ‘Vector’ stuff; removing the other Vertex class and adding templated Vector2<T>, Vector3<T> and Rectangle<T> classes. These are much simpler to work with and can be int or float-based (or any other type, really).

I also trashed my Matrix class as it wasn’t used; when I need matrix maths I’ll create a new one.


Now I’m committed to SDL2, I removed the Win32 filesystem I added to replace PhysFS and replaced it with one based on SDL_RWops. It was crazily simple to do.


I created an eventing system as a standalone git repo hosted (privately, for now) on bitbucket. I integrated this into OldCode and hooked up basic GameObjectSpawned events. It was nice as it let me immediately start decoupling code that was interested in entity spawning.

Level Loading

A big change I made was to make the game initialize entirely from data using a json-based level file. This was great as it allowed me to remove some hard coded stuff from the C++ code.

A result of doing this meant that I re-introduced a archetype or class based system that allowed an entity type to be specified in a json file and then spawned from the class type.

Game Services

I started to bring in the notion of game ‘services’ to work with entities that have specific components. This allowed me to move logic out of components and into services, meaning that my components are now totally data-only.

A result of this is that I now how a generic Ticker system that ticks things that are registered with it.

Game Services aren’t really generic yet, but I can see them evolving that way.

GameObject System

A huge change I made was to remove std::shared_ptr use in my GameObjects. I now have a GameObjectHandle that is basically a weak reference handle to an object. The handle is exchanged for a GameObject by the GameObjectService. By the handle being weak, I can basically despawn stuff and have handles invalidate automatically. The implementation of this is a post in its own right.

Dynamic Spawning

As a result of all this stuff, I changed the way spawning of GameObjects works; objects are created and then spawned - at which point they’re renderable, updatable, etc. Crucially, they can also be despawned now - which means they’re removed from any systems that care about entities. If an object is despawned, any handles pointing to it become invalid, meaning that systems that are interested in them have to discard the handle. Of course, they receive a GameObjectDespawnedEvent to give them an instant notification of this.

Because I can now spawn and despawn entities, I added WeaponFire, which is the player firing bullets. They travel until they exit the level bounds and despawn.

Next Month

That sums up the stuff I did in July (and the start of August). My next goals are:

  • Get collisions implemented. This would let me detect weapon collisions with enemies (and the player) and react to that. The beginnings of a real game will drop out of this.
  • Unit tests. I’ve gone on too long without automated testing and have made some stupid mistakes that tests would pick up. So I’m going to integrate my upptest project and add unit tests around the core systems.
  • Add multiple enemies. Let’s start making a game, not a tech demo.

Until next time.

Manta-X: 2d or bust!

Why 3D is bad for me

The goal of this project was always to make a game. Specifically, to make a top-down, side scrolling shump type of game. The previous old code entries talked about ripping out superflous stuff and pulling the project back to the essence of what 2004 me was trying to achieve.

I started looking into modernizing the codebase to a newer version of OpenGL, one that moves away from immediate mode and into the realm of shaders. I created a new branch called opengl-upd and set to work, ripping out the current stuff and adding in magical things that I was basically learning as I went from a ‘modern’ OpenGL tutorial.

It turns out that for me, someone who hasn’t touched graphics programming of any kind since the late 2000’s the leap is huge. Rendering was broken for a very long time in that branch. Getting a triangle up took a while and I eventually got the (untextured) models loaded and showing - however the camera system was totally screwed.

As part of this update, I realised I’d broken one of my core tenants in this project - that of refactoring - keeping the existing stuff working as I evolved the code. The old rendering system just wasn’t compatible with the newer code so I had a black screen for a long time - something which wasn’t desirable.

Sitting back and reflecting on this I realised that I was spending a lot of time learning OpenGL and not actually progressing with the original goal of having a working game. This was compounded by my lack of 3d tools knowledge (MilkShape 3D is defunct now) and I realised I’d have to learn Blender and other tools. It got me thinking, if I was doing all this - I could just quit and use Unreal or Unity as it has all the 3D features I’d want, for free.

Stripping it back

With this in mind I decided to abandon the OpenGL update branch and go back to something more basic. I want to get some simple game built here, not mess about with tech and tools forever.

Not only am I abandoning ‘modern’ OpenGL, but I’m going to abandon OpenGL entirely in favour of a sprite-based system using SDL2.

Swapping over to sprites allows me to crudely draw my own graphics and render them up relatively quickly, allowing me to focus on building out the game itself instead of worrying about graphics tech.

Implementation Plan

The goal here is to be able to rip out the 3D stuff and swap to sprites without breaking what’s there - thankfully there’s actually very little there right now.

I could approach this in two ways; the first would be to have a combined approach, whereby sprites are rendered alongside the 3D stuff. The second would be to keep them completely separate. I decided that for my own sanity, I’m going to keep the concepts totally separate - I’ll keep the 3d stuff running until the sprite systems are at parity, then I can remove the 3d stuff entirely.

To do this, I’ve implemented a runtime toggle - basically when the game starts up it reads a configuration file and runs in OpenGL mode or SDL (Sprite) mode.

Based on this mode, we now instance either a GLRenderWindow or a SDLRenderWindow. Both of which are entirely separate and deal with their own types of rendering.

We still have a problem, however. A lot of the old code that was ported over to the component system means that components are responsible for rendering themselves. So the Camera, Model and even the Collision components have some OpenGL code in them. This code is easily lifted and shifted into a specific Renderer system for the type of stuff we’re doing. It also means that the rendering code becomes consolidated in one place and that components lose their awareness of how they get rendered. This is a good thing.

Next up, we need a set of classes and components to mirror the current 3D components. These will be:

  • Sprite - To hold the sprite info (equivalent to Model)
  • SpriteManager - Equivalent to ModelManager, allows loading of sprites from config
  • SpriteComponent - Associates a Sprite to a GameObject
  • Camera2Component - A 2D camera component
  • SpriteRenderer - Renders sprites

Time to get cracking on all this. Hopefully I’ll have something to show soon.

gmc - Hacking a toy VM

gmc: Hacking a toy VM

If anyone remembers me from back in the “old code” days (circa 2006), there was a scripting language I used to use called GameMonkey Script. It was a lua-like language that was designed to be more familiar to C++ programmers. Back in the day, I used to contribute minor changes to the core language itself as well as write about it on GameDev.net.

GameMonkey itself is long dead, having been put into a maintence-only mode by one of the original authors (see Greg’s Github and abandoned completely by Matt, the other author. Lua has since hit version 5 and left it behind in terms of raw performance and adoption in the game industry.

However for me, GameMonkey (herein referred to as GM) was the project that kick-started my interest in virtual machines, compilers and other such things that certain programmers get a kick out of. I’ve previously implemented a version of the GM Virtual Machine in C# greenbeanscript and have many long lost projects where I’ve created some small VM to play around with things.

Newer languages such as Rust, Go and even Typescript have intrigued me with how they’ve approached syntax and other language design questions. As a result, I felt the stirrings to mess around in this space again after a long haitus.

First goals

Rather than do as some people would and jump right into LLVM, language theory and other such gubbins, I decided to take things slowly and get my head around building a basic VM and assembler. I largely see this work as throwaway, so I’m free to make mistakes and not feel so bad about it.

So for the first goals, it’d be creating a VM that can run the psedudocode program:

int add(int a, int b)
    return a + b

int a = 100
int b = 200
int c = add(a, b)
  1. Primitive types
  2. Static typing
  3. Local Variables
  4. Function definitions
  5. Function calls with parameters
  6. Return values
  7. Bytecode formats

So for now, I’m going to support only the int type only. I need to decide on how to manage variables, hold script functions and deal with passing of arguments to them.

Bytecode Format

I decided to think about bytecode first as this generally dicates the type of patterns you use up front; specifically whether your VM is stack-based or register-based.

The original GameMonkey script was stack-based; which meant that the majority of the bytecode instructions were simple and took their operands from the stack and pushed their results back to the stack.

For example, adding a = 1 and 2 would be something like:

push 1
push 2
add             // 2 values popped from stack, result pushed back
setlocal @a     // local variable a set from top of stack

Whereas a register-based VM (such as Lua 5) would encode the operands into their instructions itself.

add 1, 2 -> @a

Register-based VMs typically have larger bytecode ‘scripts’ as their instructions are larger (typically 32/64 bits instead of 8), however you can see from the simple example above that in register-based machines, each instruction tends to do more “work”, meaning that the VM spends lets time in the interpreter and so can be much faster.

One of my original thoughts was to speculate about converting the original GameMonkey from being stack-based to being register-based to see the impact; but as that largely meant rewriting the codegen and VM, I decided against it at this point in time (although it would be cool to do that).

As a result of this, I’ve decided that my toy VM will be register-based.

With this decision made, I looked at some descriptions on how Lua does it. I actually like Lua’s implementation here as it makes sense. We’re a VM, so we don’t have to map VM registers onto hardware registers - as a result, they’re basically part of the stackframe.


The stackframe layout for the toy (register-based) VM would be something like this:

0: Parameters [pN]
pN: Constants [kN]
kN: Variable registers [rN]
rN: Top of working stack

With the simple pseudo script of:

int a = 100
int b = 200
int c = a + b

We’d end up with a stackframe that looked something like this:

    [No params]
k0: int -> 100
k1: int -> 200
r0: int -> a
r1: int -> b
r2: int -> c

We can therefore assign variable registers from the constant table such as:

loadk k0 r0     ; load value from k0 (100) into variable register r0
loadk k1 r1

The add instruction would take the two source registers and the destination, eg:

add r0 r1 r2    ; add r0 and r1, store in r2


Now I have a couple of instructions and a general idea how registers work, I think it’d be a good idea for the first parser to be an assembler. The reason for this is that it would speed up my iteration time on scripts and force me with a data-driven way to initialise things like functions and such. The first pass would likely start in code, but I’d like to write the assembler early to dust off my parsing skills before it comes to think about a language.

With this in mind, we could specify the above program as something like this:

.func _main
.params 0
.consts 2
.const 0 int 100
.const 1 int 200
.locals 3
.local 0 int
.local 1 int
.local 2 int

loadk 0 0
loadk 1 1
add 0 1 2
ret 0

It’s not the most readable of syntax, so perhaps we could consider some sort of symbol table in the assembler:

.func _main
.var a int
.var b int
.var c int

loadk 100 a
loadk 200 b
add a b c
ret 0

The consts are now inlined, with the assembler being required to keep track of the parsed constants and assign them to a prototype for the function. Variables are referenced by identifier now, requiring a symbol table to be created.

Seems like creating this assembler would be a logical first step.

Now the question is do I write this in C++ or C99?

Until next time!

Introduction to GameMonkey Script: Part 1 Introduction to GameMonkey Script: Part 2 Continuing GameMonkey Script: Advanced Use

Updating Manta-X (Part 3)

Updating Tech

Whilst I have have stripped out a lot of cruft and slowly begun bringing the project up to date, remember that a lot of the technologies we’re currently based on are very old - even after the update from a couple of years ago when I brought in SDL 1.2, TinyXml 2 and Visual Studio 2012.

I decided that whilst things are fairly simple, I should upgrade some of the foundations - it’ll be easier to do it now before things get more complex.


The first thing I wanted to do was get onto SDL2 as it is the current branch that replaces the old 1.2 branch. The biggest reason for me doing this is that at some point, I’d like to upgrade to OpenGL 3 and that they’ve improved a lot of things, including controller support.

First thing to do was to look at the really handy SDL2 migration guide and get an overview of the main changes. For me, it was mostly around creating the window and handling keyboard input.

I tackled it head on:

  • Downloaded SDL2 version 2.0.4 to deps
  • Updated premake to reference it instead of 1.2 (folder paths, link objects)
  • Compile
  • Fix resulting errors

The errors were exactly as the SDL2 Migration guide suggested. The window creation & OpenGL context stuff was slightly different, which meant changing the RenderWindow. Keyboard input needed to use scancode - so that got changed in KeyStates and PlayerControllerComponent. Once I’d changed a few minor things to handle these changes I was up and running on SDL2 without any side effects. And that was it. The upgrade was committed in a single CL that migrated to SDL2 and removed SDL1.2 entirely.

Visual Studio 2015

Visual Studio 2012 is good, however the toolset supports a very limited version of C++11. There’s a bunch of stuff in the C++11 standard that I like plus I generally perfer to be on a fairly recent compiler version where possible. As a result, I wanted to upgrade to Visual Studio 2015.

Turns out that my prior changes of upgrading to SDL2 and using premake made this as trivial as updating my premake.bat file to pass the argument vs2015 instead of vs2012. And that was literally it. Clean, build, run - it all went through without a single issue.


I used to be a huge fan of XML. Nowadays I don’t touch it if I have a choice. Like all the cool kids out there, I use JSON. I use it professionally and it’s a lot more familiar to me on a hand-authoring and parsing point of view. A couple of months ago, I wrote a JSON Parser for fun to practice my TDD skills. It turns out that this exercise will be useful.

Being that I wanted to transfer a lot of the component initialization code to be data-driven, I decided to start this work by using my JSON library.

Over several commits, I gradually migrated away from XML to JSON, loading components from a JSON file. The cumulated in me removing TinyXML from the build. Like everything, premake has made this sort of thing very easy so far. I’ll write more about the migration to JSON in another post.

If you’re not using it - go use premake now. It’s excellent.

Old Tech - Next Gen

There’s a bunch of old technology in this project still.


I’m using a really old-skool, immediate mode OpenGL renderer. This style of renderer was old-hat back in 2004 and in 2016 it’s prehistoric. I want to upgrade to using shaders, vertex buffers and all that. The thing is, I don’t know anything about it. I’m going have to learn it - this project would be a nice way of learning this stuff as it’s small and could be done pretty quickly. I’ll be looking at this in the future as it’s something that interests me.


I ripped out my own texturing and image loading system as it wasn’t used. I had a basic (uncompressed) TGA loader and that was it. I’m sure that when I need it, there will be a bunch of libraries out there to use. I’m confident that’s not going to be a concern.


The 3d assets in this game are created in Milkshape3d and loaded from the source format. They’re low-poly and untextured - I’m happy with low-poly although this was 2004 low-poly, not 2016 low-poly!

The real problem is that there hasn’t been an update to Milkshape3d since 2009. That’s 7 years ago. It’s abandonware. I could keep using this tool or I could migrate to another tool. Having asked on Twitter, the three main recommendations are:

  • Blender
  • Wings3d
  • Maya LT

They’re all viable (although Maya is a a harder justification due to cost), but the biggest blocker is the tool itself and time. Modern tools seem to have a super-complicated interface compared to Milkshape3d. All of these will take a lot of time to learn to achieve stuff as basic as I have now. However, if I ever wanted to add more content to the game, I’m going to have to decide whether to battle on with a dead tool or to dedicate time to a newer tool.

When it comes to deciding on the tool, the export format will be important - this will basically be my import format, or something I use to derive it. I’m pretty confident that I won’t need to roll my own importer and that assimp or similar libraries will help.


The game currently loads raw source assets without processing. Currently the “conversion” to game format is done at load time. For now, this is acceptable - however at some point in the futre, I’ll likely need to build in a conversion pipeline. I’ll do this when I need to - definitely bottom of the pile for now.

Build Improvements

I’m a HUGE advocate of testing and continuous integration. One huge gap right now is that my only test strategy is to run the game and manually verify the results. This is not a scalable approach. As I add new features and the code gets more complex, things will break. Things will break. And I won’t know about them until it’s too late. Adding a level of testing (unit tests & integration tests) will help here. I’ve been using my own test framework upptest for various other projects, so it’d be easy to add this here.

The next thing that would be useful would be to hook up a system such as Visual Studio Online or Travis CI to ensure that the project builds on a machine that isn’t my laptop. It’d also help for initial non-Visual Studio compilation verification (eg: clang). Again, this could be easy to set up now whilst things are simple - it’s worth considering if I indend to treat this as a proper project.

Wrapping up

There’s a whole bunch of other tech improvements or decisions I can make, however I’m defintely not make them now. I’ll tackle each problem as it comes, making the choice using the information I know at the time.

The next post up, I’ll be talking about how I ripped out the XML ShipClass system in favour of a JSON-based component initialization approach.

Until next time!

Updating Manta-X (Part 2)


Last time around we devolved the hierarchy into a component-based model. I wanted to clean that up a bit to make creating and accessing components a bit simpler.

At this point I’m not interested in exploring ‘pure’ entity-component models or arriving at a super-optmized solution, I’ll just implement something that makes working on the current system a bit more convenient whilst not closing off any future avenues.

Here’s the current GameObject class:

class GameObject final
    Vertex3	position;
    Vertex3 rotation;

    std::unique_ptr<class CollisionComponent> collisionComponent;
    std::unique_ptr<class ModelComponent> modelComponent;
    std::unique_ptr<class ShipComponent> shipComponent;
    std::unique_ptr<class CameraComponent> cameraComponent;
    std::unique_ptr<class ControllerComponent> controllerComponent;

My goal here is to remove the specialized std::unique_ptr and replace with a std::vector with some creation and accessor methods. In order to do this, I needed to create a lightweight baseclass for components - GameObjectComponent. At this point, it was just en empty struct.

GameObject then became:

class GameObject final
    Vertex3	position;
    Vertex3 rotation;

    std::unique_ptr<class CollisionComponent> collisionComponent;
    std::unique_ptr<class ModelComponent> modelComponent;
    std::unique_ptr<class ShipComponent> shipComponent;
    std::unique_ptr<class CameraComponent> cameraComponent;
    std::unique_ptr<class ControllerComponent> controllerComponent;

    std::vector<std::unique_ptr<GameObjectComponent>> components;

In true refactoring spirit, I tackled the problem one component at a time, adding things to the GameObject and GameObjectComponent as I went. The first thing that was required after adding the second component was that I needed to be able to determine the component type. I added this to the base component:

struct GameObjectComponent
    virtual ~GameObjectComponent() {}

    virtual int componentType() const = 0;

I added the getComponent method to GameObject:

GameObjectComponent* getComponent(int componentType) const;

I ended up adding a quick macro to implement this method and define a static const int ComponentType member; this allowed me to then retrieve a component by class type (eg: getComponent<ModelComponent>()).

template<class TComponent>
TComponent* getComponent() const
    return reinterpret_cast<TComponent*>(getComponent(TComponent::ComponentType));

Gradually refactoring things out, I discovered that some components needed to access others via their parent object - so I ended up putting a GameObject member on the base component. As well as accessor methods, I created some creation methods on GameObject to allow me to add components byt type:

template<class TComponent>
TComponent* addComponent()
    if (getComponent<TComponent>()) return nullptr;
    auto* cmpt = new TComponent(this);
    return cmpt;

template<class TComponent, typename TArg1>
TComponent* addComponent(TArg1&& arg1)
    if (getComponent<TComponent>()) return nullptr;
    auto* cmpt = new TComponent(this, arg1);
    return cmpt;

I’m still on VS2012 so I don’t have all the C++11 features available - as a result, I can’t use variadic templates.

At this point in time, I’m wondering whether this current component design is going to cut it. It’s not very data-oriented and is really a slightly more devolved version of the inheritance structure that was present. Having to put the back-pointer to the owning GameObject was telling that the design isn’t quite right - components still refer to each other directly whereby it should likely be a manager or system class that is dealing with these inter-dependencies. Additionally, sharing components between GameObjects may be something I want to do.

But right now it’s fine for my purposes so it’ll stick around until I need to change it.

Adding a Bad-guy

I wanted to test this out by adding a new feature - an enemy ship. The first new feature in 12 years!

This basically meant duplicating the code that creates the player and changing the rotation and position. When I start up the game, I see the enemy in the level, facing the player. Because they both have a PlayerControllerComponent they both move in response to my input. However, I realised that as I moved forwards, the enemy moved backwards. Essentially, the rotation of the enemy wasn’t being taken account of. In fixing this I’ve been wondering about whether to treat these objects as 3d space transforms, or screen-space 2d transforms. This is 2d game using 3d assets. There will be pseduo-3d in here in the forms of layering, so it’s more of a 2.5d game. Rotating an object will mean that the directions are relative to the object, not the screen. So I put in a simple “facing” concept to handle this. Now, the up/down is still in screenspace, but forwards/backwads is relative to the facing of the ship. Still not ideal, but it’ll do for now until I have something more concrete.

With all this fixed up, I removed the PlayerControllerComponent from the bad guy and now he just sits there like a duck waiting to be shot at.

At this point I’m really not happy with the code that initializes the game objects, so I wanted to make the system a little more data-driven (eg: loading data from file, not code).

First up though, there’s some cleanup work to tackle.

Until next time!

Updating Manta-X

Old Code, New Code

The last 8 posts have focussed on the past, bringing an old dog back to life. Now it’s time to look to the future. We’re no longer stripping things away, we’re now in the process of refactoring, modernising and - Horus forbid - adding new features.

The process of iteratively refactoring something is a skill you seem to pick up with experience. I clearly didn’t have this skill 12 years ago, as I left the game in a broken state, with a bunch of things ripped out and not working. Refactoring isn’t about razing it to the ground and building it back up again, it’s about deliberately evolving a codebase over many many small steps whilst keeping the thing working. Sure, you may introduce some ugliness during the process, but you’re doing it knowingly, with the end goal in mind. Anyone who’s interested in this technique should read Martin Fowler’s Refactoring book.

Project Structure

I always find that dealing with C++ in Visual Studio is a royal pain in the ass. Adding new classes is never quite as fast as you’d like. It didn’t help that I had a whacky src and include split.

I decided to port the project over to Premake5 to allow me to better iterate on the build system. Premake is good because it’ll generate my VS files for me at any time and it’s often a lot easier to work in premake than trying to configure the build in Visual Studio’s property editor.

I have two build projects - the game itself and TinyXml. It took me about 30 minutes to get this working with Premake, ensuring I was linking to everything correctly and using the right runtime libs.

With premake in place, I can now rapidly add new files or change folder locations for things. So the very first thing I did was to merge all the code from include into src, tweak my premake file and regenerate. It all worked perfectly.

Devolving GameObject’s Hierarchy

The Entity/GameObject system in the codebase is based on inheritance. If you remember the last post, I’d removed a bunch of junk from the GameObject hierarchy (including Entity), but I want to make things more composable.

There’s only two GameObject types at the moment - the GameCamera and the GameShip (player).

Here’s a summary of the current state:

      /            \
     |              |
GameCamera      ModelEntity     <--- ICollidable

Over the last few years, I’ve been using component based architectures for game objects. This concept isn’t new and I’m not going to talk about the benefits of them in length except to say that assembling lots of smaller components makes creating behaviours and working with objects a lot simpler than trying to wrangle an ever increasing inheritance graph.


The first thing to do here is to introduce a break and remove the ICollidable from ModelEntity. I do this by refactoring the code into a CollisionComponent over several small steps.

  1. Create CollisionComponent that inherits ICollidable
  2. Add member to GameObject which holds CollisionComponent
  3. Move all references over to the new CollisionComponent instead of assuming they’re inherited members
  4. Remove the inherited ICollidable from ModelEntity
  5. Collapse the ICollidable code into the CollisionComponent

With that process, we retained the exact same functionality throughout whilst migrating to something more structurally sound.

The inheritance graph now looks like:

        GameObject      <>--- CollisionComponent
      /            \
     |              |
GameCamera      ModelEntity

The CollisionComponent is reusable in that it will let me attach it to any future game objects.

The GameObject class now looks like this:

class GameObject
    Vertex3	position;
    Vertex3 rotation;

    std::unique_ptr<class CollisionComponent> collisionComponent;


Next up is to take care of ModelEntity, collapsing it down into a ModelComponent. Its job will be to render the model.

The process is pretty much the same as it was for the CollisionComponent - take a series of small steps towards the goal.

  1. Created ModelComponent that inherits ModelEntity
  2. Add member to GameObject which holds ModelComponent
  3. Move all references over to the new ModelComponent
  4. Make GameShip inherit GameObject instead of ModelEntity
  5. Collapse the ModelEntity code into the ModelComponent

The inheritance graph now looks like:

        GameObject      <>--- ModelComponent
      /            \
     |              |
GameCamera      GameShip

And the GameObject class is now:

class GameObject
    Vertex3	position;
    Vertex3 rotation;

    std::unique_ptr<class CollisionComponent> collisionComponent;
    std::unique_ptr<class ModelComponent> modelComponent;

GameShip & GameCamera

The next thing is to apply the same refactoring process to GameShip, creating the ShipComponent and to GameCamera, creating the CameraComponent.

I now have no specialized GameObjects, so I mark the class as final.

class GameObject final
    Vertex3	position;
    Vertex3 rotation;

    std::unique_ptr<class CollisionComponent> collisionComponent;
    std::unique_ptr<class ModelComponent> modelComponent;
    std::unique_ptr<class ShipComponent> shipComponent;
    std::unique_ptr<class CameraComponent> cameraComponent;

Player Input

The final thing to do was to relocate the current logic that takes player input from the place it currently lives (the Game class) and create a new component, ControllerComponent which does exactly the same job. I’m not too keen on the name but can’t think of anything better yet. InputComponent perhaps?

The job of this component is to inspect the controller (in this case, keyboard) and create an action to poke at the ShipComponent. If I had an AI ship, I could create a similar component that would control the ship in the same way.

Here’s our GameObject:

class GameObject final
    Vertex3	position;
    Vertex3 rotation;

    std::unique_ptr<class CollisionComponent> collisionComponent;
    std::unique_ptr<class ModelComponent> modelComponent;
    std::unique_ptr<class ShipComponent> shipComponent;
    std::unique_ptr<class CameraComponent> cameraComponent;
    std::unique_ptr<class ControllerComponent> controllerComponent;

You’ll notice that there’s a bunch of members on here that only apply to some objects. Obviously adding new components will mean bloating this class out further. I’ll take a look at this next time.

Until then!

Manta-X Code (Part 7)

Entity System

One thing that has bugged me on this whole project is that crappy entity messaging system. Now that things are simpler, leaner, I feel happy enough to get rid of it.

Removing it was fairly simple; the only 4 messages used now are Update and PreRender, Render and PostRender. Realistically, the way they’re used right now is that I have Update and Render. So I decided to collapse these down.

cloc 2120

Having dug through the entity system and fix a couple of bugs that fell out of removing the messaging system, I’ve realised that the game is simple enough to not even use the Entity class at all. I don’t have this deep object graph and if I needed it, I’d likely do it in a different way.

So, controverisally, I deleted it.

If you remember one of the earlier posts, the object graph looked like this:

  Entity        <--- IMMO
GameObject      <--- ICollidable

Now it looks like this:

ModelEntity     <--- ICollidable

GameObject is basically the Entity class now.

I could probably collapse GameShip into ModelEntity, but I’m ok with how it is.

I moved ICollidable to the model - the only reason it’s even around is because the bounding box is being rendered and I didn’t want to remove that ‘feature’. If anything, it show how broken the hierarchy was in the first place. It’s still broken, but if I were to fix it, I’d write a basic component system instead.

Some final cleaning up of more junk, I’m left staring at the cloc.

cloc 1998

Less than 2000. From a starting point of almost 6000.

Journey’s End

I’m pretty much done with the cleanup of this old code. There’s nothing really I can do to it to strip it back and keep the same features.

And with that, we’re at the end of our old code journey. There’s a bunch of stuff I could do to this, but it’d be new code from there on, written in response of a new feature or requirement.

I’m going to sit back and consider what to do next. Do I use this as a test bed to reboot the project? Do I put it back in the box and leave it for another 12 years? I just don’t know at this point.

I have really enjoyed the ride - the insight into one’s own past and constrasting it with the current version of me.

I’ve enjoyed writing about this experience as much as the exploration itself. I hope you’ve enjoyed reading.

Old code is dead. Long live old code.

Manta-X Code (Part 6)

You Didn’t Need It

You Ain’t Gonna Need It is pretty much a guiding principle of mine in more recent years. The concept of ‘future coding’ is very easy to fall into. You anticipate a need for something so you try and cater for it early; kind of like risk mitigtion. The problem with all of this is that things change. The age old philosophy that Change is the only constant in life cannot be avoided. You find new ways of doing something, an assumption you made turned out to be wrong, a new feature is required, an old one is thrown away - all this stuff has happened during the years I’ve been a profressional programmer and they will continue to happen long after I’ve hung my keyboard.

My mindset, however, wasn’t always like this. I used to believe it was the job of a software engineer to anticipate all of these things and create something that was generic for all of time. Future coding was a core concept and it’s very evident in this old codebase.

With this project I’ve got the unique opportunity to revisit the past and see of the future coding decisions I made. We are in the future right now and none of those decisions and ideas have stood the test of time. There is very little to be ‘proud’ of in this codebase, except that maybe something is visible and moving around the screen. It’s rough, but it’s a rudimentary 3d game whereby I load raw assets and display them in response to a user’s input. These days, that’s an achievement given you could accomplish the same thing in 10 minutes with Unity or Unreal.

Minimum Viable Product

THe MVP is a concept you hear a lot about in the agile circles. It’s essentially about creating the bare minimum you need to in order to achieve a goal.

With this in mind, I’ve decided that I’m going to set my current goal on stripping back everything that doesn’t contribute to the current active featureset of the game. All the stuff that was there in spirit but commented out because it doesn’t work, or is missing will go.

The current featureset is therefore:

  • Load model
  • Load ship data
  • Render model on screen
  • Model has a bounding box (I’m keeping it because it’s visible)
  • Move model in response to keyboard input
  • ‘Animate’ model on movement

If it’s not in that list, it’s not in the live codepath. If it’s not visible or materially contributing to the current features, it will be removed. If it’s an over-abstraction of a concept, it will be removed.

If you’re skeptical about lean development principles, look away now - I’m not taking any prisoners. Perfectly ‘good’ code will be removed.

Out with the old

Some stats before we begin:

cloc    | Complie time
4168    | 00:00:56.54


First up, the finite state machine that is a baseclass for the entity class. It’s a strange decision to have made anyway, especially considering it’s not actually used anywhere. Chopped.

cloc 4012

Particle System

I came across this when I was cleaning out the smart pointer system. It’s total trash. Essentially a CPU particle system that treats particle as an object. And each particle is allocated on the heap. Each particle used to be an IMMO. The only way this could have been any worse would have been to have treated each particle as an entity.

Removing it was trivial. I deleted the whole src\fx and include\fx directories and compiled. Nothing changed. It is completed unreferenced.

cloc 3635

That’s 500 lines of shitty code gone. I’m glad that this whole system is consigned to the garbage heap.


The log system is initialized and never written to. Not on error, nothing. It’s completely unused. The code is garbage; it’s an unbuffered log that writes directly to the filesystem.

It’s going. And with it, the Singleton class, as that’s the only use of the singleton.

cloc 3484


The game runs at 700 fps; when I need to profile I will. The profiler system was removed. Wasn’t used - don’t need it at this point.

cloc 3236


My nice speedy optimization of hashing strings into ints for blah blah blah. Didn’t need it.

cloc 3180

Weapon Fire

The whole system for firing weapons isn’t hooked up. If you remember from a previous post, the weapon system didn’t seem to have survived the migration to this current codebase from an older one, so it was commented out and referenced missing classes.

I’ve deleted the whole thing, including pulling out any references to it in comments or update loops.

cloc 3098


File containing random utilities that aren’t used. Deleted. The Quad class. Deleted.


The Game class has a concept of a IGameState stack - states can be pushed to and popped from the stack, triggering enter or leave logic. The problem is that there is only one GameState, which is the PlayState. As a result, the stack isn’t required.

Furthermore, after removing the stubbed methods that are called on this state, the only one that actually did anything was the updateState method. Looking at this code, it does nothing that can’t be done inside the Game::update method, it’s a pointless abstraction. So I refactored the logic from PlayState into Game and deleted it.

cloc 2914


As it stands right now, we load a couple of textures into the game and do nothing with them. The models aren’t textured; there’s no particles and no UI. As a result, the whole texture and image system can be stripped out completely without affecting anything. If I need this in the future, I would likely do it in a different way - using stb or SDL for image loading and likely using shaders in the rendering pipeline.

As a result, I removed the entire texture and image loading system. Turns out that the rendering system didn’t even handle textures anyway - there was no OpenGL code to remove.

cloc 2655

Removing Dead Code

There’s a bunch of code that deals with ‘managing’ objects. Loading them, retrieving them, removing them. The problem is that this isn’t called anywhere, so it’s dead and can go.

I had a Timer class that wasn’t used anywhere. Gone.

The Entity class has a bunch of dead code. Message handlers that are wired up but do nothing. Gone.

Remember I talked about the entity id “freelist” concept that was in here? The code was bugged and it’d end up picking the next id anyway. That whole thing can go.

What followed is just a general cleanup of methods that never got called, or if they did, were completely empty. Interestingly, a bunch of the cleanup code can be removed because I’m handling lifetime of objects correctly now.

Wrapping up

Here’s the stats after the cleanup exercise:

cloc    | Complie time
2284    | 00:00:29.46

I’ve almost halved the lines of code and reduced the compile time by a further 25 seconds.

What’s more, the ‘game’ is exactly as functional as it was before. Sure, we’ve lost a bunch of systems and engine type code, but it was all doing absolutely nothing. It had no point in existing other than to take up compile time.

What’s fun is comparing where we were at the start of this series with where we are now:

        | Start         | Now         | Difference
cloc    | 5863          | 2284        | -3579
Compile | 00:03:00.35   | 00:00:29.46 | -00:02:31

I’ve removed over 3500 lines of code and shaved 2 minutes and 31 seconds from the compile time, whilst retaining the same playable version of the game.

Makes you think, huh?

There’s a couple of small, mechanical things I want to clean up before I think about what to do next. But that’s for another post.

Manta-X Code (Part 5)

Unfinished Business

It’s been fairly cathartic to go back and clean some of this code up - almost feels like some unfinished business. Still not sure if I want to continue working on it, but I thought I’d at least cull some of the garbage in here to unmuddy the water a bit.

Let’s take away the easy stuff. All those classes that aren’t used or do nothing I’d want to take forward.

GUI Gone

First up, the GUI subsytem. It looks like I was building out a GUI system - it wasn’t hooked up to anything except an empty “editor game state” (or the code was commented out). The GUI system can handle bitmap font display, text labels and ‘windows’. I looked at the code and decided to remove it. The whole thing. If I need a GUI in the future (probably), there will be better solutions than this half finished thing - dear ImGui is one such system that I could pretty much drop into place when I need it.

That’s quite a lot of code to remove. Past-me would have kept it around because of that reason - current me thinks YAGNI and points out that it’s still in the git hitsory if I need it (I won’t).


The Entity subsystem had the DTIClass (from Game Programming Gems 2) and PropertySet stuff to provide a runtime type information and metaclass system. It was probably here for automating script binding and data loading. Well it’s not used, so it’s going.

I could pretty much delete this stuff straight up without affecting anything. Gone.

Path Navigation

I was building some rudimentary node-based path navigation system that’s not hooked up or used. By the looks of it, it wasn’t going to work anyway. Gone.


I had an exception handling system in here that seemed to track the callstack of methods to the site of the exception. Well none were thrown anyway and this looks like it is just going to be problematic. Gone.

Goodbye, IMMO

I thought I’d tackle the old nemesis, the IMMO & MMOPtr combo. The IMMO system is basically a simple reference counted pointer system that tracks all ‘managed’ objects in a global list (eg: if you inherit the IMMO base). The reference counter is incremented/decremented by the scoping of the MMOPtr object. Each frame, we ‘clean’ up the dead list by iterating it and deleting any objects.

There’s a couple of sets of problems with this system. The first is that the IMMO system itself has a few mechanical flaws:

  • global static list of objects
  • cleaning all dead on each frame
  • no custom allocation strategies (heap or gtfo)
  • and more fundamentally, an IMMO cannot be a stack object

The ‘easy’ route to fixing this would be a blanket find/replace of the IMMO system with something like std::shared_ptr.

However, the second set of problems is common to all smart pointer style systems (including std::shared_ptr):

  • easy to create circular reference groups of objects
  • easy to disregard object ownership and lifetime concerns

That second point is a huge one. You’ll recognise it when you see public method signatures that pass around std::shared_ptr for everything. What you’re essentially saying here is “I don’t know who owns this anymore” and as a result, an object’s lifetime becomes less deterministic.

In languages such as C# this is fine as the garbage collector is sophisticated and the memory is managed - C# was designed around this very concept. In C++, and in games specifically, this can become a problem.

The use of the IMMO system in Manta-X is a huge abuse of this type of pointer. Almost every method signature has an MMOPtr reference which means that every object in the game has this problem. Therefore a blanket replacement of the IMMO system with std::shared_ptr may address some of the mechanical problems with IMMO, it does not solve the architectural issues of the codebase. Instead, removing IMMO means going through each system, one at a time and making decisions about ownership and lifetime and changing it to reflect this.

So that’s what I did.

Removing IMMO

Over the course of 10 or so commits, I went through and extricated the IMMO system from the codebase. Here’s the order, from first to last:

  • GameState
  • Image Loading
  • Texture System
  • Model System
  • Ship ‘class’ system
  • Particle system (I discovered that this whole system was total junk)
  • GameData (analogous to UE4’s GameInstance)
  • Entity System
  • Remnants
  • IMMO deleted

What was very clear was that the use of IMMO in the majority of these systems was replaced by holding onto a std::unique_ptr and doling out a raw pointer to anything that needed it. In the future, this may get replaced in some systems with a handle, but right here, right now, this works.

Cleaning up

In removing IMMO, I ended up poking around almost everything in the project. As a result, I’ve decided that the next goal for me is to remove everything in the code that isn’t been exercised by the current running state. So if it’s not part of a live codepath, it’s going.

After this cleanup, cloc is 4168 (down from 5990) and compile times:

Time Elapsed 00:00:56.54

That’s down from 00:01:13:00.

Until next time.

Manta-X Code (Part 4)

Up and Running

Now that the code compiles quicker, my iteration times will be faster in this codebase. The first thing I want to do now is get the game “running” and “playable” to the point that it was. I won’t add any new features, but just try and plumb together whatever’s there.


First thing to do is get the render loop running. The game currently uses OpenGL and used to use GLFW for windowing. The last time I touched this code, I brought in SDL, commenting out stuff to do with GLFW. The first thing to do is to start pulling all that stuff back in.

It was missing:

  • SDL_Init (heh)
  • SDL Event pumping
  • SDL Video mode setup

After uncommenting the creation and update of the render window, we finally have something displayed!

That screen is the last thing I saw before I closed my IDE on the project all those years ago. It’s like looking back in time and seeing the face of someone you once knew.

I can’t remember what I was doing at the time, but that’s it.

At this point, input is all disabled. This is fine, I’ll add it later.

I remember having at least a background in there and some enemy ship. Time to go and find how to turn all that back on.

//		MMPtr<BackgroundNode>	bkgNode = new BackgroundNode( MMPtr<Texture>(bkg) );
//		bkgNode->initSceneNode();

//		MMPtr<StarFieldNode>	stars = new StarFieldNode( 50, MMPtr<Texture>(particleTexture) );
//		stars->initSceneNode();

After prodding it for a bit, it looks like the code to turn back on no longer exists. BackgroundNode and StarFieldNode don’t exist. They did exist looking at the huge weight of evidence in the place they would have been hooked up.

And then it dawns on me that perhaps this codebase was in a transitionary state from an older one. This was meant to be the improved version. I can only imagine the trash that was there before. Back then I didn’t use version control software, so my codebases always got trashed in situ, with no backups. I often used to ‘fork’ by starting a new project and copying files over, changing them to fit the new ideas.

The older game with these features looks to be completely lost in time (unless I can find another archive).

The only way to go back and add these features is to write them again. sadface.


I can at least attempt to get the input working, to at least say I have something working. This should be a straight swap of GLFW’s handling with SDL’s key events.

Or so I thought.

Looks like there’s two layers of input handling here. One via GLFW (commented out), the other using DirectInput 8. I’m going to assume that the DX version is the canonical one that needs porting to SDL.

Ripping out the DX8 code was pretty quick as it was self contained. I run the code and start pressing the keys and… nothing. Nothing happens.

Turns out there’s an error in the code that calculates the frame tick, essentially meaning that the game update doesn’t get ticked at all. I replaced this with the SDL_GetTicks function and we’re away!

The ship is moving around with the arrow keys - rolling slightly when it moves up or down the screen.

I press the spacebar to fire the weapon and… nothing. Again.

int GameShip::fireWeapon()
    if (m_fireTimer <= 0)
    //	SmallLaserFire *p = new SmallLaserFire();

    //	p->position = this->position;
    //	p->position.x += 20.0f;
    //	p->velocity.x = 150.0f;
    //	m_level->addWeaponFire( MMPtr< IWeaponFire >( p ) );
        m_fireTimer = 0.25f;

    return 0;

And guess which class doesn’t exist? Screw you, past me.

lol comments

Some of the stuff in the code amused me highly - mostly the use of comments to document functions. Check out this gem from the Game.cpp file:

// Method:		isRunning
// Returns the current run status of the game. If this is
// false then update should not be called
// Access:		public
// Prototype:	bool isRunning()
// Parameters:	None
// Returns:		bool
// History:		20/06/2004 - Created
bool Game::isRunning()

That’s from the cpp file, not the header where you’d expect. That just gets this:

// Method:		isRunning
// Returns the running status of the game
bool isRunning();

Seriously - that stuff is worse than useles…

Past-me was a Jerk

When I took this investigation on, I didn’t really know what I’d find. I’ve unearthed a lot of really bad code, with “comment out stuff” being the modus operandi for source control. There’s at least 3 or 4 layers of legacy in this code - you can tell by the technologies and style (hell, some of the comments refer to a completely different namespace).

At one point in the past, this thing was playable and now it’s not even that. This code is either the start of a new ‘improved’ fork of the game or perhaps an old one that was ripped to pieces during an ‘upgrade’.

What bugs me the most about this code isn’t that the code is bad (that was expected), but that in ‘upgrading’ the code I threw away the useful bits (eg: the game) and implemented a bunch of crap that isn’t needed or doesn’t contribute anything to the game. I literally threw away the product to sit in the wrapping paper. And it’s not even good wrapping. It’s the brown paper and string type-stuff.

Perhaps that’s the benefit of experience talking, but I do things fundamentally differently now. When I refactor, I do it iteratively and keep the old thing working. You can’t afford to just ditch the old and have code that is fundamentally broken for months (or 12 years). Unless something is no longer required, I don’t factor out old behaviours or logic during the upgrades. That’s just idiocy - something which I had in spades.

I want to go back in time and tell past-me to make better decisions around how to go about building stuff.

Next Steps

This has been a fun journey so far and I’m really not sure where to go next. It was my intention to get this game up and running and then perhaps start working on it. I’ve got it running to the extent that it ever will and now need to decide what to do next. Working on this has exposed some basic architectural flaws that would need working through (literally, everything is fucked). It may be a fun refactoring project to move this to a better architecture and keep the nugget of the ‘game’ there (‘game’ being a huge airquote). I can at least delete the commented out junk code to see what there actually is left. Or I could just close the door on this and come back to it in another 12 years.

I’ll have a think about it.

Manta-X Code (Part 3)

Improving Compilation Time

Compile times on this 6094 loc project is much slower that it should be.

A full rebuild (including TinyXml):

Time Elapsed 00:03:00.35

There’s a bunch of reasons, but one of them is poor header discipline.

The all-emcompassing header

In every header file (and therefore every cpp file), there is #include "StdHeaders.h" at the top.

This StdHeaders.h file is some stupid include file that has a bunch of “common” junk in it. This is:

  • SDL headers
  • OpenGL headers
  • Windows headers
  • Tiny XML headers
  • A load of standard library headers
  • Singleton.h
  • IMMO.h
  • …and more!

So a whole bunch of crap in every file, regardless if it’s needed or not.

The first thing to do is just jump in and delete this damn file, then fix any compilation errors.

This took about an hour of removing all references to this header and including the right headers in the files. Note, I’m currently not forward declaring anything - I’ll do that in the next pass.

Compile time now:

Time Elapsed 00:01:53.19

We’ve shaved just over a minute off the compile time by cleaning up the “god header”, cloc says that at 6056 we’ve also shaved off some code.

The thing to look at next is to start removing unnecessary includes from the headers themselves.

Forward declarations & Unnecessary includes

The easy win here is to tackle the rendering system. It seems all of these files like to directly (or indirectly) include Reader.h, which in turn includes windows.h, gl/gl.h and gl/glu.h - rather large files to be bringing in every time.

Removing Render.h including only what is needed in just the texture rendering code improves the compile time somewhat:

Time Elapsed 00:01:25.33

That’s almost 30 seconds faster.

Clearing out some more in the model system:

Time Elapsed 00:01:18.18

And some more in the Entity system:

Time Elapsed 00:01:15.47

And pretty much everything else:

Time Elapsed 00:01:12.81

Using proper header discipline reduced the compile times of this ~6000 loc project by more than half.

It goes to show that best practices are there for a reason.

In cleaning out the code, I removed some unreferenced headers (that wouldn’t compile) - so cloc is now at 5990. Ideally, I’d not be counting the TinyXml build time in this at all - so perhaps that’s another avenue.

Next Time

Next time, I’ll go about actually getting this thing rendering again. The code is all there, but commented out. Not sure why, possibly due to the transition to SDL.

Manta-X Code (Part 2)

Removing PhysicsFS

I wanted to get the game running so I thought I’d go and remove the PhysicsFS dependency. I didn’t really need it at this point and can’t be bothered with another 3rd party library for the sake of it.

Turns out it was used in 3 classes:

    ModelManager (for loading Milkshape3d models)
    ShipClassManager (for loading XML data about the ships)
    TGAImage (for loading texture data)

Each of these essentially did the same series of operations:

  1. Check the file existed
  2. Allocate a buffer
  3. Read contents into the buffer
  4. Close file
  5. Do stuff with the buffer

As a side node, back then I was doing a lot of heap allocation and looking over the code, it was very easy for these buffers to be leaked when an error occurs. Now I’ll just use a std::unique_ptr until I can come up with a better allocation strategy.

I quickly hit the fact that my FileReader class I talked about before wasn’t implemented. I seemed to do a lot of this stuff back then, have code started and just not used or finished sigh. Anyway, it was farily trivial to implement a Win32 version of the FileReader and replace the PhysicsFS code. I’m not injecting the dependency still, so the classes are currently just creating their own FileReader and going from there.

The problem with removing PhysicsFS is that I added the dist\data directory to my search path using PhysicsFS. I wrapped up the file name in an immutable FilePath object which starts out as the root data directory. Now, instead of passing raw strings around to file load routines, I pass the path object. Seems to work ok.

With that all done, I can remove PhysicsFS (sorry Icculus!).

Current cloc 6092, that’s up by 200 lines or so. Not too bad considering I removed a huge dependency.

Also, the game compiles and starts now… but doesn’t run.


So digging into the file loading was pretty useful as it exposed me to how the manta.xml file is loaded. At first glance, this appeared to be a file thet describes the properties of the player.

The player’s ship is an instance of the GameShip class, which has the following inheritance hierarchy:

  Entity        <--- IMMO
GameObject      <--- ICollidable

Every entity in the game has a finite state machine - wtf? As expected, they all base on that awful IMMO object.

So what is an Entity? It looks like it’s a graph of other entities (like Unity) - they have parents and children.

Entity Messaging

Entities also have a messaging system built into them. It’s not a game wide messaging system, looks like it’s specifically for entities.

    // Message handling interface
    IEntityMessageFunctor *RegisterMessageHandler( long pMsgId, IEntityMessageFunctor *pHandler);
    IEntityMessageFunctor *GetMessageHandler( long pMsgId );
    int HandleEntityMessage( sEntityMessageInfo *msg );
    void SendMessageToChildren( sEntityMessageInfo *msg );

The signature of of RegisterMessageHandler is weird, but looking at the implementation it essentially returns you the old handler for a message, replacing it with the one you just registered.

long pMsgId is badly named (looks like a pointer) and is essentially a constant defined in an enum:

enum EntityMessages


I guess it’s a long instead of an enum EntityMessages to avoid including headers? I doubt it, as I had a huge header include issue anyway. Perhaps just another bad decision. There’s plenty here.

The IEntityMessageFunctor is essentially a message handler with the following definition:

class IEntityMessageFunctor
    virtual int operator()(sEntityMessageInfo *msg) = 0;  // call using operator
    virtual int Call(sEntityMessageInfo *msg) = 0;        // call using function

This has a couple of obvious flaws in that handlers can mutate messages. I’m going to assume that they’re all heap allocated and the same instance is shared. Will have to confirm. Not sure why the message handler defines the call operator, probably thought it was cool back then. It’s obviously pointless.

I was wondering why I had a special baseclass for the messages, assuming that perhaps I just did some downcasting in the handler based on the message type… but no. Something weird.

The definition of the sEntityMessageInfo is:

struct sEntityMessageInfo
    sEntityMessageInfo( long pMsg, Entity *pFrom, bool pRelay );

    long msg;
    Entity *from;
    bool relay;		// Relay to children?

    std::vector<sEntityMessageParam>	params;

WTF. Looks like the sender provides a flag to determine if the message is passed to the receiver’s children (how would it know?). Also, what the hell is sEntityMessageParam?!

I take a look and… yeah.

struct sEntityMessageParam
    enum msgType

    msgType Type;

        std::string		*m_string;
        size_t			m_long;
        int				m_int;
        bool			m_bool;
        float			m_float;
        void			*m_user;
    } Data;


It’s a variant type. Why? Why? WHY?!

I presume there was some legit reason, although right now I can’t comprehend what it might be. Perhaps scripting? shrug

I just noticed that every entity subscribes to a bunch of messages on construction, regardless if they consume them:

    Erase(); _allocateID();
    RegisterMessageHandler( ENT_MSG_CREATE, new TEntityMessageFunctor<Entity>(this, &Entity::OnCreate) );
    RegisterMessageHandler( ENT_MSG_DESTROY, new TEntityMessageFunctor<Entity>(this, &Entity::OnDestroy) );
    RegisterMessageHandler( ENT_MSG_SHUTDOWN, new TEntityMessageFunctor<Entity>(this, &Entity::OnShutdown) );
    RegisterMessageHandler( ENT_MSG_UPDATE, new TEntityMessageFunctor<Entity>(this, &Entity::OnUpdate) );
    RegisterMessageHandler( ENT_MSG_ATTACHED, new TEntityMessageFunctor<Entity>(this, &Entity::OnAttached) );
    RegisterMessageHandler( ENT_MSG_DETACHED, new TEntityMessageFunctor<Entity>(this, &Entity::OnDetached) );

Also, it looks like the next entityId (returned by _allocateID()) is a static… and that there’s a freelist of ids:



The weird thing is that Entity also seems to have the concept of rendering in it:

virtual int OnPreRender( sEntityMessageInfo *msg );
virtual int OnRender( sEntityMessageInfo *msg );
virtual int OnPostRender( sEntityMessageInfo *msg );

But the implemenations do nothing.

It’s a symptom of the inheritance structure that is in place. I’d assume I’d be adding all sorts of gubbins to this Entity if we continued.

Entity has both a position and rotation property, with a comment saying that they’re relative to the parent. When I look down the hierarchy, I also notice that GameObject has a postion and rotation which seems to be used. Essentially, I have no idea what the stuff on the base entity does - if anything.

Wrap up

Looking into this Entity code has been somewhat frustrating. There’s a lot of trash in here and a lot of stuff that doesn’t do anything. The first thing I’d look at doing is ripping out the message handling stuff and putting something a little cleaner in there - Ok a lot cleaner. After that, start breaking this idiotic hierarchy into components.

The first goal, however, is to get something rendering. The game runs but doesn’t show anything.

Manta-X Code

Manta-X: Toe in the code

Last post I talked about the overall folder and asset composition of a very old game codebase I found of mine (from 2004).

It looks like when I got it compiling back in 2014, I’d ported it to Visual Studio 2013, however the IDE is now crashing so I will use 2012 for now.

After more time than it should have taken, I configured cloc to skip the deps and dist folders, we have the following counts:

Language                     files          blank        comment           code
C++                             54           1396            623           3742
C/C++ Header                    70           1077            209           2121
SUM:                           124           2473            832           5863

In short, just under 6000 lines of code excluding comments and whitespace. We really don’t have much here - much less than I expected to find. My memory is that this project was much bigger than it actually is, perhaps it’s because this is likley a “reboot” of an even older version that’s lost in time.

Time to dig in and see what we find.

Coding style

The coding style I used in this project is represented fairly well by FileReader.h


#include "StdHeaders.h"

#include <fstream>

namespace MantaX
    class FileReader : public IMMO
        virtual ~FileReader();

        int openFile(const char *filename);
        int closeFile();
        int seekFile(unsigned int pos);
        unsigned int tellFile();

        unsigned int fileLen();
        virtual int readFile(char *buf, unsigned int len);
        std::ifstream	m_fin;


Let’s break it down:

  • Not using #pragma once (this was 2004, I guess)
  • StdHeaders.h is a huge catch-all header file with lots of stuff in it
  • Everything is in the MantaX root namespace
  • Class names are PascalCase (thankfully, I wasn’t using the C-prefix that was popular back then)
  • IMMO - more on this later…
  • Method names are pascalCase, parameters are pascalCase
  • I obviously wasn’t aware of const-correctness
  • Class member variables have the m_ prefix.
  • Public / Protected / Private ordering
  • Using standard file handling (I wonder why there’s a dependency on Physics FS?)

So the codebase is looking like it has a Java-like style, not terrible but obviously a few issues.

One of the biggest problems I see straight off is the split of src and include. This isn’t down a public/private boundary, but just a straight up “headers go in the include folder and source goes in the src folder”. This is a pain in the ass to work with and if I were to do anything with this code for real, I’d defintely go about chucking it all under a single src folder.


Anyone who visited GameDev.net back in 2004 would remember Richard Fine’s (in)famous Enginuity series. This codebase has a bunch of stuff inspired by that series in here.

We have:

  • IMMO / MMOPointer - a basic refcounted smartpointer/memory manager system
  • Singleton - The dreaded singleton - let’s hope it’s not everywhere…
  • Profiler - I had performance profiling in a 6000 loc codebase. Ok then…

Curiously, I wasn’t using the “task” system or anything else from Enginuity at this point.

Likely I’ll find more concepts from this series when I go digging around further.


There’s a handcrafted Vertex2d, Vertex3d and Matrix4x4 class there. There’s some other single structures like Quad sitting around. Just enough basic maths to render 3d “sprites” I guess :)

There’s also some stuff like Triangle and Mesh and Model which looks like it’ll be awful :)


Something of an oddity is that I have a few container classes that basically wrap the standard containers. I have Map which is a thin wrapper over std::map and then HashMap, which looks like it is a std::map<int, T> where items are inserted with string keys that go through a crude hash to calculate the key. I’ll have to dig around to see where this is used.

The HashMap code has methods like this:

void insert( std::string key, T data);
T find( std::string key );

String copying, anyone? Ironic as this is likely a performance optimization. I guess that profiling system wasn’t used much :)


One strange thing I found in the code from this cursory glance in the files is a reference to DTIClass and Property/PropertySet. It’s very likely I was considering reflection here, possibly as a way of serializing the Xml? Ah, this is where one of the uses of HashMap comes in. I’ve been very interested in reflection and other such things at runtime for a long time, so it’s not surprising that an old codebase from 2004 features some of it.

Wrap Up

This quick look over the code is already revealing. There is a lot of stuff that’s low level or not particularly focussed on the act of making the game. Perhaps this is because I’ve always been more interested in engines and systems programming and not the aspect of visuals or gameplay.

When I first found this codebase, I was wondering if there was anything I could use or even perhaps if I could pick up where I left off. That’s already looking doubtful, but I’ll keep looking over this code.

In the next post, I’ll take a look at the entity system.


Manta-X Archaeology

Manta-X: Uncovering a relic

I’ve been digging around in my visualstudio.com projects and came across Manta-X Game. This was a real blast from the past for me - a game dev project that I was working on back in 2004.

The goal of Manta-X was to essentially recreate the Andrew Braybrook C64 classic Uridium for the PC. I remember the ambition was to have 3d graphics instead of sprites, so I was using OpenGL. 2004 is a long time ago now and technology was very different back then. I also have no idea how far along the game got - what features it has or whether it’s even playable at all.

As a bit of fun, I’m going to explore my old codebase and blog about it. I’ll dig through the past and see how my old brain went about things and ask myself whether I’d still do things the same way now. I have been programming for a long time (long before 2004) and so my knowledge and professional development experience in the intervening 12 years has shaped my skills. This will be a fun exercise - I can remember literally nothing about the code or structure of the project at this point in time, so perhaps a few surprises will crop up :)

This is not the first time I stumbled across Manta-X; in 2012 I found it on an old hard drive and threw it up to visualstudio.com. In 2014 I found and got it compiling again, swapping out GLFW for SDL 1.2 and bringing in the latest versions of PhysicsFS and TinyXml (the versions I used were no longer around).

Today I pulled down the code from the TFS repository into git using git-tf (thanks to Chris Kirby’s blog) and uploaded it to bitbucket. Now I can start exploring and changing things.

Digging in

The first thing to note is the folder structure:


build contains the intermediate build files deps is where the third party libraries live. Currently physfs 2.0.3, SDL 1.2.15 and tinyxml 1.2.4. dist contains the built binaries and my game assets. doc contains a bunch of random text files, ideas, todo lists and other junk that was probably useful 12 years ago, but is totally meaningless to me now. include and src is where the code lives. Back then I kept .h and .cpp files separately. The visual studio solution and project files live in the root directory.


I thought it’d be interesting to explore the dist\data folder to see what assets I had. It turns out not many - a handful of tga files, Milkshape 3d models and xml specifications for entities and GUI layouts. Interestingly, I was loading up raw, loose assets and had no packaging process. The lack of assets is very telling too - the game obviously isn’t very far along. A couple of enemy models, the player model and a handful of basic textures.

I opened up the file entities\manta.xml and found this.

<?xml version="1.0" encoding="utf-8"?>
<model id="manta" file="manta">

    <feature xpos="" ypos="" zpos="" type="WEAPONMOUNT" />
    <feature xpos="" ypos="" zpos="" type="WEAPONMOUNT" />
    <feature xpos="0.0" ypos="0.0" zpos="9.0" type="ENGINEFLARE" />

        <point xpos="-10.0" ypos="-5.0" zpos="-8.5" type="MIN" />
        <point xpos="10.0" ypos="5.0" zpos="8.5" type="MAX" />
    <motion direction="LEFT" velocity="100.0" maxtilt="15.0" />
    <motion direction="RIGHT" velocity="100.0" maxtilt="15.0" />
    <motion direction="THRUST" velocity="100.0" maxtilt="0" />
    <motion direction="BRAKE" velocity="100.0" maxtilt="0" />

    <setting name="AUTO_TILT_CENTER" value="1" />


Of course, it means very little to me now - especially the magic “AUTO_TILT_CENTER” setting :) I was also clearly specifying the entity as a whole, rather than using a more component based model. I bet that looking in the code I find an inheritance graph for entities that starts with a class called Entity and ends with Manta, likely with some abstraction of Ship somewhere in the middle.

There’s a scripts\startup.gm file with the contents:

// Load models for game
Game.Models.Load( "manta", "models/manta.ms3d" );

// Create a player ship using the 'manta' model
player = Game.CreatePlayerShip( "manta" );

player.y_rot = 90.0f;
player.x_pos = -50.0f;

Looks like I was using the GameMonkey Script system to implement the “game”. Quite why there’s a split between xml configuration and script for similar reasons is unknown to me - there probably isn’t a sensible reason!

The textures folder is also very telling about the state of the game. There’s a nice background texture, a particle texture, a bitmap font and… that’s it. The models have no textures at all!

The lack of an audio folder confirms that not adding audio to my projects goes back a long way :)

Currently the game compiles but doesn’t run due to missing dlls (SDL runtime and physfs.dll). In my next post I’ll focus on getting the game running and then dig into the code and start exploring.

Until next time!