Maniacal: Under the Hood

In the first post on Maniacal, I talked about testing my reimplementation of the engine behind Maniac Mansion: what “correct” means when there’s a second implementation to compare against, and how an agent player that reads a walkthrough won the game twenty-one times. In the second, I sat in the other chair and used the library as a stranger would. This post goes underneath both. It’s about how the thing actually works, and about the instruments I built to look inside it.

As with the Laser Vault version of this post, there are two audiences. If you’re a tester who likes reading code, this is the technical track from the first post, with the code showing. If you’re simply curious how a game from 1987 can run on a computer from today without anything pretending to be a Commodore 64 or a 386 PC running DOS 5, I’ve tried to make every piece of it followable without a background in C#, C++ or even the game itself.

All the code in this post is from the project, which is open source, or from the throwaway probes I describe along the way.

What an Interpreter Actually Is

The Laser Vault post started with what an emulator is: software that pretends to be a circuit board, so the game’s original machine code can run on it unchanged. Maniacal isn’t that. Nothing in it pretends to be a 6502 processor or an IBM PC. And yet the game’s original code still runs unchanged. How?

The answer is that Maniac Mansion was never really written for a processor. Ron Gilbert and Aric Wilmunder wrote it in a language of their own, SCUMM, and the game is a collection of scripts in that language, compiled into bytecode. Each release of the game shipped with an interpreter for that bytecode, written for its machine: one for the C64, one for DOS, and later ones for the NES, the Atari ST and the Amiga. The scripts didn’t know which machine they were on. All they knew was the SCUMM machine: a set of instructions, a few hundred variables, a handful of running scripts, rooms full of objects, actors walking around in them.

What all that means is that a game like this is two things:

  • Data: rooms (each a background picture, a mask, walkable areas and objects), costumes (how the actors look and animate), sounds, and the scripts themselves.
  • An interpreter: the program that loads the data, runs the scripts, draws the rooms and actors, plays the sounds and turns the player’s clicks into sentences like “open front door.”

The data is the game. The interpreter is the machine it runs on, and it’s what I rebuilt. If every script instruction does what the original interpreter did, with the same timing, drawing what it drew, then the game has no way of knowing it isn’t in 1987. That’s the same promise as an emulator’s, made one level higher. Instead of “every byte at every address,” it’s “every instruction, every variable, every step.”

Here’s the catch, and it’s the reason this post exists. There’s no specification of SCUMM. Lucasfilm never published one. What we do have is ScummVM, a reimplementation built by people who spent years working out what the original interpreters did. For the C64, we have my commented reconstruction of the original engine itself, which is part of the repo. So I wasn’t implementing a specification. I was implementing an implementation, and checking it against the original where I could. Everything in this post sits somewhere on that line.

ScummVM organizes its SCUMM code as a chain of classes, one per engine version, each inheriting from the next: version 0 from 2, 2 from 3, up to version 5 and the base class. Most of what Maniac Mansion runs on lives in those later classes, mixed in with code for games a decade newer: 256 colors, digital music, video. That was a little confusing to me, so Maniacal doesn’t port that chain. It has one flat engine with the version (0, 1 or 2) as data, and from each of ScummVM’s functions it takes only the branches this one particular game reaches.

“Port only what this game reaches” is a scoping rule, but it’s also a testing rule. Every branch I ported is a branch some release of Maniac Mansion actually runs, which means every branch can be tested with real data. A branch nothing reaches is code nobody can check.

Getting at the Data

Before an interpreter can do anything, it has to read the game’s files. And Maniac Mansion, like many games, came on various kinds of media: floppies for the C64, DOS, the Atari ST and the Amiga, and a cartridge for the NES. In each of them the data lives differently.

The DOS releases are the simplest. The game is a folder of files called 00.LFL to 53.LFL: the index in the first, and one room per file after that, with its scripts, costumes and sounds. Every byte is stored XOR-ed with FF, which is the gentlest encryption imaginable. Basically, every bit in each byte is flipped (1 becomes 0, and 0 becomes 1). Here’s what I came up with:

Again, XOR with FF flips every bit, and flipping every bit twice gets you back where you started. This mechanism clearly wasn’t there to stop a determined reader. It was there to stop a curious one; one who might open the file in a text editor and see the game’s dialog.

Now, the interesting decision is what to do about the other releases. The C64 version is two disk images. The NES version is a cartridge dump. The Atari ST is a disk image in a real file system, and the Amiga is two more in a different one. The obvious approach is a reader for each format, each feeding the engine in its own way. The approach Maniacal takes is stranger and (at least arguably) better: every release is made to look like the DOS release. Every container presents itself as a folder of NN.LFL files, XOR-encoded, and there’s only one reader of room files in the whole project.

Okay, but what does that mean for something like the C64. Its disks don’t have files the way DOS does. The index is at a known place on the first disk, and it says, for each room, which disk, track and sector the room starts at. The room is then a run of resources, one after another, each starting with its length. Here’s how I handled that:

Look at what it does with each byte it reads: it XORs it with FF. But, and here’s the key point, the C64’s disks were never encrypted in the first place! My code encrypts them, on purpose, so that the room file it builds is exactly the kind of file the DOS reader expects. It’s a translation layer that speaks DOS, so nothing downstream has to know there ever was a C64 involved.

The Padding loop is there because a length of FFFF on the disk isn’t a length. It’s filler before the real one. That’s one of those facts nobody would guess and ScummVM’s code knew, which means it was, in that instance, a helpful reference.

The NES goes further. The cartridge has no rooms as such, just program data with the game’s resources scattered through it, and their places differ between the seven versions of the cartridge that were sold in different countries. ScummVM has a table of every resource’s place and length in each of them. Maniacal takes that table from ScummVM’s source with a generator (more on those in a moment), and uses it to build the DOS-style room files, plus an index. The index it builds from the American cartridge is ScummVM’s, byte for byte: 2,082 bytes, the same MD5. That’s a test with a very clean oracle. Either the bytes match or they don’t.

The Atari ST and the Amiga are the opposite case. Their disks hold real files, with real names, 00.LFL and so on, in real file systems: FAT12 on the ST, the same one DOS floppies used, and the Amiga’s own. ScummVM expects you to copy the files off the disk images before it will play them. Maniacal reads the file systems where they are, so the disk images themselves are the game folder.

This is the pattern I would most want to steal for any system that takes many kinds of input: make every input look like the one you understand best, as early as possible. One reader of room files, tested against six releases, is worth far more than six readers each tested against one.

Tables Ported, Not Typed

A great deal of what an interpreter knows isn’t code. It’s tables. Which handler runs for each of the 256 opcodes. The MD5 of every known release’s files so it can recognize them. The game’s built-in fonts. The color palettes of the C64, the EGA and the NES. The frequency tables of the PC speaker and the PCjr. The places of every resource in seven NES cartridges. The C64’s verb names. Its actors’ colors.

ScummVM has all of those, in C++ source files. The easy thing would have been for me to just copy them over. But, early on, I made a rule: no table gets copied by hand. Every one is produced by a small Python script in the repository’s tools folder, which reads ScummVM’s source and writes a C# file. Here’s the core of the one for the opcodes:

It finds ScummVM’s function that sets up the opcode table, pulls out every OPCODE(0x.., name) line, and refuses to go on unless it found exactly 256 of them. What it writes looks like this:

Notice those names. Some start with o2_, and some with o5_. That’s ScummVM’s class chain showing through: version 2’s table borrows handlers from version 5 wherever they’re the same. And notice that Maniacal keeps ScummVM’s names for them, exactly. That was deliberate too. When I, or someone else, sits down to read Maniacal‘s handler for o2_doSentence, I can open ScummVM’s file and search for the same name. The names are a cross-reference that never goes stale.

Now, you might ask: Why go to this much trouble for tables? Because a table typed by hand is a hand-typed bug waiting to happen, and an especially quiet one. A wrong entry in a frequency table doesn’t crash anything. It makes one note slightly flat. A wrong MD5 makes one release unrecognized, which you’ll only find if you happen to own that release. Granted, a generated table can be wrong too, but only in the way the generator is wrong. That’s mitigated by the fact that the generator checks itself: 256 opcodes, or stop.

There’s another benefit as well. Some of these tables aren’t really ScummVM’s at all. The SID chip’s combined waveforms, which you’ll see later, are tables sampled from real chips by the author of reSID, the emulator ScummVM uses. The generator carries them across untouched. Nobody on the ScummVM project ever had to type four thousand numbers measured off a chip from 1982, and I didn’t have to either (from which I am very thankful).

Facts copied by hand drift silently. Facts generated from their source can be regenerated, diffed and checked. If you find yourself pasting a table from another project, write the twenty lines that read it instead, and make them refuse to run if the table isn’t the shape you expect. This applies to any data structures, not just tables.

Reading the Scripts

The scripts are the heart of the game, so the script engine is the heart of the interpreter. Given that, let me tell you a little about how it works.

A script is a list of instructions. Each one starts with an opcode byte that says what to do, followed by its operands: numbers, variable numbers, text, a place to jump. Maniacal has a decoder that turns bytes into instructions, and that decoder is used in two places: by the engine to run the scripts, and by the inspector to list them. That’s important. The listings you can read are made by the exact same code that runs the game, so a listing can’t disagree with what the engine does.

Up to eighty scripts can be running at once, each in a slot of its own. But they don’t run in parallel. Each step of the game, the engine goes through the slots, and each running script runs until it gives up its turn. This is my implementation of that:

That’s cooperative multitasking, the way operating systems worked before they learned to interrupt programs. A script yields with an instruction called breakHere, or by waiting, or by ending. A script that never yields would hang the whole game, because nothing else would ever run.

Which is why that budget is there. ScummVM doesn’t have it. The original interpreters didn’t either. If the scripts are right and the interpreter is right, no script ever runs a hundred thousand instructions without yielding. But if the interpreter did have a bug, say a jump that goes to the wrong place and makes a loop, the game would freeze. A frozen test is the least informative failure there is. With the budget, the same bug fails at once and says which script did it.

An infinite loop is a bug that hides its own location. If your system can loop forever, give it a budget it should never reach, and make it say where it was when it ran out. It costs nothing when the code is right, and it turns a hang into a stack trace when it isn’t.

Each instruction then goes to a big switch on the handler’s name. Here are a few, including the one that waits:

Two things from the first post’s heuristics are right there in the code. The jump is taken when the condition is false: isEqual means “carry on if these are equal, and jump past the next part if they’re not,” which is how an if statement compiles. And the delay is stored upside down, as FFFFFF less the number of ticks. This means a script that waits five minutes holds the number 16,759,215. The comment saying so is the only place in the code that explains those numbers.

The Slot That Gave Itself Away

The first post told the story of the door to the dungeon that closes on itself: on DOS, the door’s script closes the door behind the kid by starting a sentence at once, and the rest of the script never runs, so the kid stays in the cellar. ScummVM leaves him there too. Here’s the code that does it:

A script asks for a sentence to be carried out straight away. Before starting the object’s script for it, the engine looks for a script of that object already running with the same flags, and if there is one, the new script takes over its slot. The script that asked is the door’s own script. So the door’s script replaces itself, and everything after the request is gone. ScummVM does exactly this, line for line.

That one line above, FindObjectSlot, would be very easy to “simplify.” A new script in a free slot is cleaner, safer and more obvious. It would also make the dungeon door work, which would make Maniacal different from the original, and from ScummVM, in a way that would never fail a test. The comment above it is there so that nobody, including me, ever tidies it away.

A Freeze Only the Demo Could See

Here’s a script bug that was mine, and it’s a good one because of who found it.

Cutscenes in SCUMM freeze the other scripts while they play: the house’s timers stop, Edna (the crazy wife of Dr. Fred) stays where she is. When a script starts another script that has a cutscene in it, the question is whether the first script carries on afterwards. In ScummVM’s code, it does, unless its freeze count was raised. And in versions 0 to 2, the freeze never raises the count. It only sets a flag bit on each frozen slot. Maniacal‘s port checked the flag bit instead of the count, so a script that started a cutscene stayed frozen when it should have carried on.

In the full game, you would never see it. The boot script, which starts the game’s opening, sat one instruction from its end and never finished. It held a slot it didn’t need, out of eighty, and nothing noticed. Every walkthrough test passed. Every comparison matched.

Then the 1988 DOS demo came along. The demo runs itself, scene after scene, with quotes from reviews in between (“Game of the Year,” says Analog Science Fiction Magazine). Its script 9 starts a cutscene and then, afterwards, starts another script, 173, which shows those quotes. With the bug, script 9 never carried on after the cutscene, and the quotes never came. The demo stood still where they should have begun.

That’s the lesson from the Laser Vault post again: the strictest program is the one that finds your bug. The full game was tolerant of a script that never finished. The demo, which was nothing but a script that must finish, wasn’t. Run every program you have, not just the important one.

Letting the Game Say What It Means

Here’s a smaller example, but it’s my favorite example of a principle that runs through the whole project: when the game has an answer, take the game’s answer.

Objects in Maniac Mansion have verb tables. The front door’s says what to do for verb 1, verb 2, verb 11 and so on. The library could tell you those numbers. What it couldn’t tell you, until recently, was what they’re called: that verb 1 is “Open” and verb 11 is “Use.” That’s on the screen, in the verb area, but not in any table in the interpreter. The obvious thing would have been to type a list. It’s only fifteen verbs. How hard can it be, right?

Except that the releases don’t agree! The NES has no “Fix,” “Unlock” or “What is,” and calls two of its verbs “Go To” and “Get.” The C64’s verbs are built into its engine. And there are numbers in the verb tables that aren’t verbs at all. A typed list would be right for some releases, wrong for others, and right for all of them only until somebody found a release I hadn’t thought of.

So where do the names on the screen come from? From a script. Every release but the C64 sets up its verbs in global script 164. Here it is, as Maniacal‘s own tool lists it from the 1988 release:

The first four lines are a loop that clears the verb area. Then each verbOps makes a verb: its number, where it goes on the screen, and its name, padded with @ signs to a fixed width. You can even see a decision in it: “New kid” is only made when variable 175 is zero, which is why that verb isn’t always on the screen.

And here’s what that script draws, on the driveway in the same release. The numbers after each verb’s own number are its column and row: Push, Pull and Give in column 0, Open, Close and Read in column 7, and so on across:

So my inspector logic decodes this script, with the same decoder the engine uses, and picks out the instructions that make a verb:

That’s probably a little confusing looking. That pattern says: a verbOps whose first operand is a number from 1 to 254, and whose last is text. A first operand of 0 deletes a verb (that’s the clearing loop), and FF only moves one, so neither is a verb being made. The names come out exactly as each release shows them, the NES’s “Go To” included, and the C64, whose verbs are in its engine, uses ScummVM’s table of them.

Then I have a test that checks the answer against what the player sees. It plays each release to the driveway and compares the names with the words in the verb area on the screen. And it checks the leftovers: every number in any object’s verb table that has no name must be one the player can’t pick. That turned up 16, which locks a door; 253, which scripts use to run an object’s code behind the scenes; and 255, which means “any verb this object has no code for.” None of them is a verb. All of them now say so in my documentation. Documentation I wish I had at the start!

The game is its own best documentation, if you can read it. Before typing a table of facts about a program, check whether the program already has them, in a form you can decode. Its answer will be right for every version, including the ones you haven’t seen.

Drawing

Rooms in Maniac Mansion are drawn in strips eight pixels wide, and every release encodes its strips differently. Actors are drawn from costumes, and costumes are where the releases differ most. I’ll stay with the costumes, because they produced the best bug.

A costume is a set of pictures, called cels, for each of an actor’s limbs: head, body, legs. An animation says which cel each limb shows, frame by frame. The interpreter draws them one after another, each placed relative to the one before.

And there’s a saving: a costume usually only has pictures of an actor facing right. To face left, the interpreter draws the right-facing cel mirrored.

The cels are compressed, and the two DOS releases compress them differently. The 1988 release’s cels are stored a column at a time, each column one pixel wide, as runs of a color. The 1987 release uses the C64’s format, where each column is eight pixels wide, and each byte is a row of four double-width pixels. That’s a detail of how the bytes are packed. It shouldn’t affect where the picture goes on the screen.

Except it does, and here’s how I found out. Late in the project, I compared the 1987 DOS demo with ScummVM 2026.4.0, capture by capture. Everything matched to the pixel, but for two moments. In one, the meteor that opens the game was a movement step away from where ScummVM had it. In the other, just after a save was loaded, Syd and Razor (two of the kids you can play) were a strip apart from ScummVM’s. Two differences, in two unrelated places. They looked like two bugs.

They were, as it turns out, one bug. The meteor flies facing left. Syd and Razor, at that moment, are facing Dave, which is to their left. Every difference was a left-facing figure. And once the kids turned to face the front, the screens agreed again, which is why the second difference lasted only a second or two.

Here’s the moment just after the load, with the same part of the screen from three places: Maniacal before the fix, ScummVM, and Maniacal after it. The dashed line is at the same place in each, where Syd’s face starts in ScummVM’s picture:

Before the fix, 1,727 pixels in that box differ from ScummVM’s. After it, none do. Both of the kids facing left are seven pixels too far left. Dave, facing right, is in the same place in all three.

Here’s the fix, the line that places a cel:

When ScummVM draws a mirrored cel, it starts at the right edge and steps left a column at a time. For a one-pixel column, the column is where the step lands. But for an eight-pixel column, ScummVM’s C64 decoder still fills each column from its left edge rightwards, eight pixels from where the step landed. So the whole mirrored picture ends up seven pixels further right than the one-pixel arithmetic says. Maniacal had used the one-pixel arithmetic for both formats.

There’s a twist that makes this bug story worth telling. The first post mentioned a different mirroring bug, in the 1988 release: a left-facing kid drawn one column out of place, which ScummVM 2.7.0 drew one column out of place too. That one was found by moving to a newer ScummVM, which had fixed it. This current bug was found by the same newer ScummVM, in the other release. Two bugs, in the same line of code, one for each column width. As you can see above, the line now has a comment of five lines for one of code, and a test for each DOS release that draws figures facing left and right and checks that one is exactly the mirror of the other, shifted by the right amount: seven pixels for 1987, none for 1988.

When several differences appear at once, look for what they have in common before fixing any of them. Here, “a meteor in the wrong place” and “two kids in the wrong place after a load” had nothing in common but the direction they faced, and that was the whole bug.

Headless and Deterministic

The Laser Vault post had a heartbeat: a processor’s clock cycles, all of which were counted. Maniacal‘s heartbeat is coarser. The game runs in steps. Each step is one pass of the original interpreter’s main loop, and here’s what one looks like, trimmed a bit:

Variables first, then time: the waiting scripts count down. Then the player’s input. Then every running script gets its turn. Then the actors walk, the camera moves, and the screen is drawn. Each comment names the ScummVM function the part comes from, so the step can be read side by side with ScummVM’s loop.

That first line, the one about sound, is the one the second post’s case study turned on. The C64 demo’s menu waits in a loop while variable 8 says a sound is running. A save doesn’t hold the sound, so a game loaded mid-tune finds variable 8 at zero on its first step, and moves on. It’s right there, at the top of every step.

Look at what’s missing from that method, though: the clock. Time += StepLength is the only notion of time in it, and it’s a number the step adds to, not one it reads. Nothing in the engine asks the computer what time it is. The game’s random numbers come from a generator with a fixed seed. This means that the same game files and the same clicks on the same steps give the same game, every time, on every machine. That’s the property the first post called the most useful in the project, and now you can see where it lives.

The command-line player I provide with Maniacal exposes it directly. –run plays without a window, as fast as the computer will go, with clicks and keys at chosen steps, and writes a screenshot or a recording at the end:

That’s 900 steps, a click at step 400, Escape at step 600, and the screen and the sound at the end. A minute of the game takes a fraction of a second. And because it’s deterministic, that command makes the same PNG every time. Pinning its hash is a regression test, and that’s what many of the tests are: a run, a hash, and a comment saying when the result was last checked by eye.

Same lesson as Laser Vault, from a different machine: make time a number. If nothing reads the wall clock, every run is a test, and a test of a whole game can take less time than a test of one function in a slower design.

This here, by the way, is probably one of the best, but also most involved, examples that show what it’s like for testers who are engaging in game testing and not just “playing it as a user would.” I’m sure most testers reading this can extrapolate that to non-game applications.

Comparing Against ScummVM

The first post described the comparison with ScummVM: save at a moment, load it in both, compare the screens, and account for every pixel that differs. Here’s how that works underneath, because it has a wrinkle the first post skipped.

The saves are the easy part. Maniacal writes ScummVM’s own save format, so a save from either loads in the other. Matching a save’s screen is a matter of loading it in both and capturing both windows.

Matching a moment is harder. Say I want to compare the 1987 demo’s first hundred seconds. ScummVM runs in real time. I can capture its window every four seconds, but the captures are timed from when I started capturing, not from when the game started, and a busy computer delays both. Maniacal runs in steps, and in this release a step is about a ninth of a second, its length set by the game’s own scripts. No step of mine lands exactly where a capture did.

So the comparison can’t ask “is my screen at 4.13 seconds the same as ScummVM’s?” The answer would usually be no, for reasons that have nothing to do with bugs. Instead, a small program I called the matcher asks a better question: which of my steps matches this capture best, and how well?

It plays the game headless and compares every step’s screen with every capture, keeping the best match for each. At the end it prints, for each capture, the best step, the game time of that step, how far that is from the capture’s time, and how many pixels still differ, and where:

Those are real lines, from a run against the 1987 demo’s captures as I write this. All 24 captures, a hundred seconds of the demo, match a step to the pixel.

That turns one question into two separate ones. Does Maniacal draw what ScummVM draws? That’s the pixel count, and the answer should be zero. Does it draw it at the same time? That’s the time difference, and it should be steady. Here it mostly sits at about two seconds, which is how much earlier I started capturing than the game started playing. A bug in drawing shows in the first number. A bug in timing shows in the second. And a capture whose best match still has pixels left over is a lead with an address, because the matcher prints the box they fall in.

Worth noting that before the mirroring fix in the last section, one capture still had 30 pixels left over in a corner, and that box pointed straight at the meteor.

The time difference needs reading with care, though. Look at captures 20 and 24. Both match step 162, so the second one’s difference jumps to six seconds. That isn’t the game falling behind. The screen simply didn’t change for four seconds, so the first step showing it wins every capture of it. The time difference only means something when the picture is moving. That’s another thing an instrument can tell you that isn’t true, unless you know how it was built.

Two small things in that loop are decisions, and they’re worth naming. The > 24 is a tolerance: a pixel counts as different only if its color is more than a little off. ScummVM’s window and Maniacal‘s palette can disagree by a step or two in a color channel without either being wrong, and without a tolerance every pixel of a room would “differ.” And the fromRow and toRow let the comparison look at the room alone or at the verb area alone, so a cursor sitting in the verb area doesn’t hide a real difference in the room. Each of those is an exclusion, and like the two bytes left out of Laser Vault‘s checksum, each needs to be something I can explain.

When two systems run on different clocks, don’t compare them at the same time. Find each one’s best match and report both how well it matched and when. “Same picture, slightly later” and “different picture” are different bugs, and a comparison that can’t tell them apart will find neither.

Sound

Sound was the part of Maniacal with the most variety. Every release makes its sound differently:

  • The DOS releases play tunes and effects through the PC speaker or, on a PCjr or Tandy, through a three-voice sound chip.
  • The C64 has the SID, MOS Technology’s famous 6581 sound chip, with three voices, waveforms, envelopes and an analog filter.
  • The NES has its own sound chip, with two pulse voices, a triangle and noise.
  • The Atari ST plays the 1988 DOS release’s sounds, as ScummVM does.
  • The Amiga plays its own sampled sounds, in stereo.

The SID is the hardest of those, and it’s where Maniacal comes closest to being an emulator after all. The C64’s music doesn’t exist as music anywhere in the game data. It exists as a sound driver, ported from the C64 engine’s own, writing values into the SID’s registers sixty times a second, the way the original program did. To hear it, you need a SID. So Maniacal has one: a port of the reSID emulation that ScummVM uses, clocked cycle by cycle. Here’s how one voice decides what it sounds like:

Each voice has a 24-bit counter, the accumulator, that goes up by the voice’s frequency every cycle and wraps around. The basic waveforms are just different ways of reading it. The sawtooth is its top twelve bits, rising and falling back. The pulse is “on” while the counter is above a set width and “off” below it. The triangle is the sawtooth folded in half.

Then come the lines with tables in them. A program can turn on two waveforms at once, and on a real 6581, what comes out isn’t any tidy combination of them. It’s whatever the chip’s circuitry did when two waveform generators drove the same lines. Nobody can derive that. It was measured: the author of reSID sampled the combined waveforms off real chips, and those are the tables. Maniacal‘s generator carries them over from ScummVM’s source untouched. And noise combined with anything else gives nothing at all, because that’s what a real 6581 gives.

How do you test a sound chip? The same way as the screen: against ScummVM. I recorded ScummVM’s output to a file, from the same save, using SDL’s disk audio driver, and compared it with Maniacal‘s. For the C64, one sound came out the same sample for sample, and a later one, started at a different point of the chip’s frame, correlated at 0.998. For the Amiga, which mixes its sampled sounds into stereo with integer arithmetic, the match was exact: ScummVM’s output, sample for sample, on both channels, at one fixed offset, for every second from 20 to 57 of the intro.

“Sounds right” is a judgement. “Sample for sample at one offset” is a measurement. Wherever you can turn a judgement into a measurement, do, and keep the judgement too, because it’s how you know the measurement is measuring the right thing. I listened to every one of those sounds before I compared any of them.

Probes: Instruments You Throw Away

The matcher from earlier never went into the repository. Neither did most of the instruments I used. As with Laser Vault, the repository holds the product, and the probes lived in a scratch folder: small programs, a few dozen lines each, that answered one question and were done.

Here’s one, nearly whole: the probe for the C64 demo’s round trip, the case study from the second post. It plays the demo, lets it get back to its menu, saves, loads the save into a fresh game, and then prints both games side by side, step by step:

Twenty steps, two games, one line each. Within a few lines of output, one game was in room 45, the menu, and the other in room 33, the title. That’s the moment the question changed from “is the save losing something?” to “what does the menu wait for?”, and the answer, from there, was in the scripts.

Notice that this probe uses nothing but the public API: ManiacMansion.Open, Play, Save, Load, Step. That’s the second post’s playground paying off from the other direction. Once the API was easy enough for a stranger, it was easy enough for a probe, and a probe that takes five minutes to write gets written.

Not every probe was so polite. The matcher needed to play the NES cartridge before the library would open it (at that stage, it refused the NES by name, because the NES wasn’t finished). So the matcher reached past the refusal with reflection, building the internal reader by hand. That’s exactly the sort of thing the playground’s rules forbid, and exactly right for a probe. A probe isn’t a test of the API. It’s a microscope, and you point a microscope wherever you need to.

Some probes weren’t programs at all. When I wanted to know whether Maniacal played on Linux, I didn’t build anything. I wrote a few shell scripts to install .NET inside WSL, clone the repository, run the tests and the package checks, and open the player in a window. The tests passed and the package checks printed numbers identical to those on Windows. The window opened empty, which turned out to be WSL’s graphics bridge failing to share memory, not the player; restarting WSL fixed it, and the game played with sound. That was a probe too: a question, an answer, and a folder of scripts that will never be needed again.

A probe’s value is in the question it answers, not the code it’s made of. Write it as quickly as you can, break whatever rules you need to inside it, and throw it away when it’s done. If you find yourself writing the same probe twice, that’s when it becomes a tool and goes in the repository.

Heuristics for Building a Testable Interpreter

As with Laser Vault, if you take nothing else from this post, take these. Most of them reach well past interpreters.

  • Make every input look like the one you know best. Six containers turned into one kind of file means one reader, tested six ways.
  • Generate tables from their source. A generator can be rerun, diffed and made to check itself. A pasted table can only drift.
  • Keep the reference’s names. When your function is called what the original’s is called, every line has a cross-reference built in.
  • Use the same decoder for running and reading. A listing made by the code that runs the program can’t disagree with what the program does.
  • Give loops a budget. A bug that hangs tells you nothing. The same bug failing at once with the script’s number tells you where to look.
  • Comment the strange lines hardest. The line that reuses a script’s slot, and the one that places a mirrored cel, look wrong and are right. Those are the ones somebody will “fix.”
  • Ask the program before you type its facts. The verb names were in script 164 all along, right for every release.
  • Make time a number. A deterministic step loop turns every run into a test.
  • Match moments, not times. When two systems run on different clocks, find the best match and report both how good it is and when it was.
  • Look for what differences share. Two unrelated-looking differences that both face left are one bug.
  • Run every program you have. The demo found a freeze that the full game hid.

Exit Mansion

When I started Maniacal, I thought the hard part would be the scripts. There are hundreds of them, in three dialects across six machines, and a single wrong instruction could strand a kid on a ladder or lock a door forever. They turned out to be the most orderly part of the whole thing. The decoder is the same for every release. The handlers have ScummVM’s names. Every script that exists is decoded in a test.

The hard part was the places where the original programs knew something nobody wrote down: a length of FFFF that isn’t a length, a column filled rightwards while the picture runs left, a freeze that sets a flag instead of a count, a chip whose combined waveforms could only be measured. Some of those I learned from ScummVM’s code, which had learned them the hard way. Some, ScummVM had wrong too, until it didn’t.

And for all of them, as with Laser Vault, the game itself was the final test. A collection of scripts from 1987, which knows nothing about C#, or ScummVM, or me. It never says what’s wrong. It just puts a meteor seven pixels from where it should be, and waits for somebody to build enough instruments to understand why.

What Next?

Well, this ends our trip to the mansion. In the next post, I’ll cover what was likely my largest project to date, and this will involve us going to a fantasy land. Stay tuned!

Share

This article was written by Jeff Nyman

Anything I put here is an approximation of the truth. You're getting a particular view of myself ... and it's the view I'm choosing to present to you. If you've never met me before in person, please realize I'm not the same in person as I am in writing. That's because I can only put part of myself down into words. If you have met me before in person then I'd ask you to consider that the view you've formed that way and the view you come to by reading what I say here may, in fact, both be true. I'd advise that you not automatically discard either viewpoint when they conflict or accept either as truth when they agree.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.