One evening in Phlan: how Pool of Radiance works

A dwarf in Pool of Radiance should get a point of Constitution for his race, and he never does. One evening in Phlan, traced through every part of the engine.

13 min read Pool of Radiancegame enginesGold Box

The same dwarf's scores twice: as the game shipped (Constitution 15, Charisma 11) and, staged with one byte changed in memory, as the code was written (Constitution 16, Charisma 10)

Here's a dwarf fighter, freshly rolled in Pool of Radiance: Constitution 15, Charisma 11, 7 hit points. And here's the same dwarf, rolled with the same dice, the way the code was written to work: Constitution 16, Charisma 10, 8 hit points. The second sheet is staged. We ran the original game in our emulator and changed one byte in memory, a loop counter, just before the first ability roll. The game itself will never roll you that sheet.

Pool of Radiance has racial adjustments for dwarves, elves and halflings: a point up or down, added to each of the six rolls of a score before the best one is kept. The line that applies them is case RaceIndex of. But RaceIndex isn't the race you picked. It's the counter of the loop that filled the race menu, and once that loop is done it is always 7. Race 7 is human, and there is no case for human, so nothing changes.1

Pascal
  for RaceIndex := 1 to RaceHuman do      { the race menu: RaceIndex ends at 7 }
  ...
        AbilityRoll := RollDice(AbilityDiceCount, AbilityDiceSides);
        case RaceIndex of                 { the race picked is in Race, not here }
          RaceDwarf:
            case AbilityIndex of
              ConstitutionIndex: Inc(AbilityRoll);
              CharismaIndex: Dec(AbilityRoll);
            end;
          RaceElf: ...
          RaceHalfling: ...
          RaceHalfOrc: ...
        end;

We watched it happen in the emulator: all 36 rolls of a dwarf's six scores ran with RaceIndex at 7 and the race at 1, dwarf.2 So no rolled dwarf ever has the Constitution of 19 that his race's table allows, and no rolled elf ever has a Dexterity of 19. Three six-sided dice give 18 at most, and only the racial point reaches 19. (The Modify screen can still raise a score to the race's maximum by hand.) In the version of the game we decompiled, nobody ever got their racial adjustment.

The race table's limits, dwarf Constitution 12 to 19 and elf Dexterity 7 to 19, on a scale from 3, with the 19 that no roll reaches

Every episode in the playlist

A decompiled game, part by part

We can say that with certainty because Pool of Radiance has been decompiled: turned from machine code back into source code in Turbo Pascal, and that source compiles back into the original program, byte for byte. The first article on this site tells how we did it, the quirks article counted down ten things the game never told you, and the CoCo 3 article told how we ported it to a 1986 computer.

This one starts a series about the engine itself, one part at a time. It's the tour: one evening in Phlan, followed through every part of the engine in the order a player meets them, with a map of those parts, each covered in a later episode.

Typing START

At the DOS prompt you type START. The main program is 65,231 bytes, packed with Microsoft's EXEPACK, so the first thing it does is unpack itself.3

The game is written in Turbo Pascal, in units, Pascal's version of modules. Eleven of the game's units are in START.EXE, along with four of Borland's (System, Crt, Dos and Overlay). Another 35 live in GAME.OVR. Those are overlays: code that's only loaded when it's needed.

When the code calls a routine in an overlay that isn't in memory, the call lands on a small stub, which passes it on to Borland's overlay manager. The manager reads the unit from disk into a buffer of 100,352 bytes and then makes the call. That buffer holds only about half of the 197,641 bytes of overlay code, so units come and go as you play. We counted it on a recorded session in our emulator: load a save, walk a few steps, open the map and a character sheet. In that time, 15 units had to be read from disk a second time.4

The overlay buffer against the overlay code, and the 15 units the recorded session read from disk twice

Before any of that, 48 unit initialisations run, each unit's start-up code, one after another. One of them reads POOL.CFG, five lines: the video card, the sound, two folders and one more flag. Then the main program runs, and it's tiny:

Pascal
begin
  StartGame;
  if ParamStr(1) <> 'STING' then
  begin
    ShowTitleScreen;
    CheckCodeWheel;
  end;
  RunCharacterMenu;
  SetWallDescriptors(11, 0, 7, 6);
  RunWilderness;
  QuitGame;
end.

Start the game, show the title, check the code wheel, run the character menu, set up the walls, run the adventure, quit. The test after StartGame is the STING back door from the quirks article.

Data, the title and the code wheel

Next, StartGame sets up the game's memory and loads its first data. Almost everything Pool of Radiance knows, maps, scripts, wall graphics, pictures, monsters and the font, lives in 113 archive files called DAX. A DAX file starts with a table of contents: two bytes for the table's size, then nine bytes an entry, an id, where the block starts, and its unpacked and packed sizes. The blocks are packed with run length encoding: a small code byte means copy the next few bytes as they are, and a large one means repeat the next byte.5

The first 29 bytes of ECL2.DAX: the table's size, 27, then three 9-byte entries, coloured by field

At start-up the game loads the font, 177 characters of 8 by 8 pixels, then the tiles, the combat sprites and the table of item types. Then it seeds its random number generator from the clock.

Then come the title picture and the code wheel, the copy protection that came in the box. The game picks a random number from 0 to 12, which picks the question and the runes you have to line up on the wheel. Which question you get depends on that clock seed and on how fast your machine got through the title screen, a story for episode 13. There are only thirteen answers, such as DRAGON, KNIGHT and WYVERN, and they are the very first bytes of the game's data. A wrong answer gets you a new question, and the third wrong answer quits the game.6

The training hall

Past the wheel is the training hall. With no party yet, the menu offers Create, Add, Load and Exit. Once you pick a character, Drop, Modify, View and the rest show up, and Train, in a hall that trains your class.

A character is a 285-byte record: name, ability scores, race, class, hit points, spells, money and experience. Monsters use the very same 285-byte record. Each ability score is the best of six rolls of three six-sided dice, then adjusted for age, clamped to the race's limits and raised to the class minimum. Training costs 1,000 gold and gets you one level a visit.7

One step in New Phlan

Now we're in New Phlan. Press the up arrow and follow that one key. The game reads it through the BIOS, the PC's built-in routines, and it lands in the movement code. Before the party moves, the area's script gets a look at the step, and it can stop you.

An area is a 16 by 16 grid of cells, each with its walls, its doors and an event number. If the way ahead is open, the party moves, a footstep plays, and the game clock moves one minute; a step while searching costs ten. You can watch it on the status line under the party list: in our recording, 15,4 W 10:50 becomes 14,4 W 10:51 after one step.8

The status line under the party list, beside the 3D view, before and after one step, and the game clock's wheels

The 3D view isn't really 3D. It's an 11 by 11 grid of tiles, each 8 by 8 pixels. A wall is 156 tiles cut into ten pieces: near, middle and far, ahead and to the side. The game paints the farthest row first and the nearest last, so close walls cover the ones behind them. All of it goes into a staging buffer first, and only the rows that changed are copied to the screen. And there are three graphics cards to support, CGA, EGA and the Tandy 1000, so every routine that draws pixels has three paths inside it.9

The game's 3D view of New Phlan, painted far to near, and the ten pieces of a wall sized by their tiles

The script machine

With the move done, the area's script runs again, and this is the heart of the game. Pool of Radiance has a little machine inside it that runs byte code: numbered commands, each followed by the values it works on, about sixty kinds of them. The scripts live in files called ECL, so we call the language that too. In an area, every encounter, every conversation, every trap and every shop door is a script, not engine code.

A script has five entry points: one for each step, one for looking at the cell you arrive on, two for camping, and one that runs first. The arrival entry usually reads the event number of the cell you're on and jumps through a table, an ONGOTO, to that cell's handler.

Text is packed four letters into three bytes, six bits each. Six bits is only 64 codes, with no room for lower case, which is why every message in a script is in capitals. And the script sits in the same memory its commands read and write, so a script can rewrite itself.

In the slums, several orcs are arguing over some papers. The script stores 99 in the value the morale check reads, adds two groups of monsters, and starts the fight:10

Output
9E2A PRINTCLR  'SEVERAL ORCS ARE ARGUING OVER SOME PAPERS.'
9E57 STORE     99, [6DC6]
9E5E ADDMON    13, 1, 4
9E65 ADDMON    4, 3, 4
9E6C COMBAT

Battle

The battle gets a map of its own, 50 by 25 squares. In towns and dungeons it's built from the walls around the party; in the wilderness it's open ground, sometimes with a river and bridges. Each round, everyone rolls initiative, a six-sided die plus a bonus for Dexterity, and the highest goes first. Your fighter swings, and the game rolls a twenty-sided die. A one always misses.

Before that roll counts, the game runs lists of hooks: small handlers called at that moment, by kind. Bless adds one to the roll, and the dwarf's bonus against orcs adds one more. An elf's resistance to charm runs in another list, when a charm is put on her. It works like an event system, in a game this old, and the combat code never names any of them. So the racial abilities do work. Only the score adjustments never did.11

A d20 roll of 14, an example, with Bless and the dwarf's bonus against orcs each adding one through the attacker's hooks, and the elf's charm resistance in the hooks of a new affect

The monsters' turn is a ladder of decisions: check morale, use a magic item, finish a spell, turn undead, cast a spell, use the best item, then move and attack. And morale is a footrace. A hurt monster that is at least twice as fast as your fastest runs away. One that isn't, if its Intelligence is above 5, surrenders.12

Spoils, camp and the save file

When you win, you get experience from each monster's record, plus more for the money it carried. Hired companions take a share, a story for the combat episodes. The loot is the monsters' money and gear, plus whatever treasure the script adds. Money comes in seven kinds, from copper up to gems and jewelry, and a shop buys your things back at half price. At the Temple, Cure Light Wounds costs 100 gold, and Raise Dead costs 5,500 gold and a point of Constitution.13

At camp, a magic-user can study Sleep, but the spell is only pending until the rest: for Sleep, four hours and fifteen minutes. We set eight hours. The rest moves the clock in five-minute steps until it's done, or until something interrupts it; ours was interrupted two hours in. The clock is an odometer whose wheels roll over at different counts: minutes at 60, hours at 24, days at 30, and the next wheel at 12. The rest menu names the first three. The last two look like months and years, but the game never labels them. The area's script decides how often a rest may be interrupted, and the odds each time.14

A saved game is 13,137 bytes, and more than half of it is the area's script; why it's in there is a story for episode 12. Each character goes into files of its own: the 285-byte record, its items and its spell effects.15

Part of a saved game Bytes
Tile set 1
Three blocks of game variables 2,048 + 2,048 + 1,024
The area's running script 7,680
Position, view kind, view mode, member count 5 + 1 + 1 + 1
Members' file names 328
Total 13,137

The whole map

So that's one evening, and it touched every part of the engine, every box on the map.

The map of the engine, every part lit

Every one of them gets an episode, with the code on screen and a quirk or two that's been hiding in there for more than thirty years. The next one starts with the first box on the map: how two files and 48 initialisations become a game, and how we proved that our rebuild is the original. The source and the tools behind this article are in the project's repository.

Notes and sources

  1. CreateCharacter, src/OVL16.PAS: the race menu loop at line 484, the chosen race stored at line 510 (Race := Choice), the adjustments at lines 716 to 737, and the routine's own note, QUIRK ovl16:1236, at lines 358 to 360. The listing above is abridged from lines 484 to 495 and 712 to 740, and its two comments are ours. The race's limits are RaceAbilityLimits (DS:3DA3, src/POOLVARS.PAS line 2844): dwarf Constitution 12 to 19, elf Dexterity 7 to 19. ↩︎

  2. Our emulator runs the shipped program; a hook on RollDice read the caller's frame at every ability roll (36 rolls, every one with RaceIndex 7 and the race 1). The staged sheet is the same run with RaceIndex set to the race before the first roll: the dice are identical, only Constitution, Charisma and the hit points change. Hit points rise because Constitution 16 gives one more than 15 (ConstitutionHitPointAdjustment, src/OVL16.PAS line 1985). The capture scripts are not in the public repository. ↩︎

  3. START.EXE is 65,231 bytes on disk and 71,152 unpacked; GAME.OVR holds 35 units and 197,641 bytes of code (docs/design/WHITEPAPER.md, sections 2.1 and 3.1 to 3.3). The main program is src/POOL.PAS, lines 57 to 68. ↩︎

  4. The buffer is OvrSetBuf($18800), src/RES08.PAS line 68. The count comes from a file trace of the recorded session walk-explore: after start-up loads every overlay once, units 3, 7, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 32 and 34 were read again. ↩︎

  5. tools/re/dax.py reads the table and unpacks the blocks; the game's own decoder is in src/RES05.PAS. The font is block 201 of 8X8D1, loaded by LoadGameFont (src/RES06.PAS). ↩︎

  6. CheckCodeWheel, src/OVL02.PAS: Question := Random(WheelEntryCount), 13 entries, on each of three attempts, then QuitGame. The answers are the records CodeWheelRecords at DS:0002 (src/POOLVARS.PAS, lines 804 to 827 and 2680). ↩︎

  7. The record is CharacterSize = $11D (285), src/OVL16.PAS line 31; the rolls are in CreateCharacter (lines 712 to 835); TrainCost = 1000 (line 1201). The menu's choices are RunCharacterMenu (lines 143 to 216): Train shows only when the hall's script sets the classes it trains. ↩︎

  8. A step is AdvanceGameClock(1, 1), one unit of the minutes digit, and a searching step AdvanceGameClock(1, 2), one unit of the tens of minutes (src/OVL14.PAS lines 292 to 295). The rest menu's clock has the same digits and prints them under "daYs Hours Mins" (ShowRestTime, src/OVL20.PAS). ↩︎

  9. DrawWallView, src/OVL29.PAS; the ten pieces start at tiles 0, 2, 6, 10, 22, 38, 54, 110, 132 and 154 of 156. The staging buffer and the copy of changed rows are in src/RES07.PAS (FlushPictureChanges). ↩︎

  10. The slums script is block 20 of ECL2, listed with tools/maps/ecldis.py ECL2 20, abridged: the full block runs from 9E22 to 9E6C; [6DC6] is the word CheckMorale reads (src/OVL09.PAS line 734). The text packing is DecodeString and SixBitChar (ovl07). ↩︎

  11. RollToHit, src/OVL24.PAS lines 408 to 428: a natural one returns before the hooks run. Bless is affect $01, whose handler adds one to the roll (src/OVL12.PAS lines 373 to 381); the dwarf's bonus is affect $1A; the elf's resistance is affect $6B, run when a new affect is put on her. ↩︎

  12. QuickTurn and CheckMorale, src/OVL09.PAS lines 63 to 130 and 692 to 750. No die is rolled for morale. ↩︎

  13. EndBattle, src/OVL05.PAS; the shop's offer is Value div 2 (src/OVL19.PAS line 839); the Temple's prices are constants in src/OVL04.PAS (lines 29 and 33), and Raise Dead lowers Constitution (line 266). ↩︎

  14. The study time is 4 hours (6 for a spell above level 2) plus 15 minutes a spell level (src/OVL15.PAS lines 50 to 55); a rest step is five minutes and the clock's radixes are ClockRadix (10, 10, 6, 24, 30, 12, 256; src/POOLVARS.PAS line 1890). The interrupted rest is the recorded session camp-rest-combat: eight hours set, interrupted with six left, the clock from 10:50 to 12:50. ↩︎

  15. SaveGame, src/OVL17.PAS lines 739 to 757; each character's files are written by SaveCharacter in the same unit. ↩︎

Related