Under the hood

Getting started

This repository does not carry the cartridge. It carries what you need to regenerate everything from your own copy and check that what it says is true.

What you need

The four steps

make comprueba     # is your ROM this one
make               # listing, reassembly, sanity checks and tests
make imagenes      # draws the scenery, the sprites and the screens
make vram          # checks those pictures against openMSX's VRAM

make is the one that matters. It chains four things:

  1. listado traces the flow from the entry points declared in src/twinbee.entries and generates src/twinbee.asm with the comments from src/twinbee.notes.
  2. verify reassembles that listing with pasmo and compares the sha256 with your ROM's. If they differ, the disassembly is worthless and it stops there.
  3. sanity checks what the reassembly cannot catch: that no area declared as data comes out as code, that no entry point falls inside a data block, and that not one byte is left unassigned.
  4. test runs the 21 checks in tests/.

How the listing is organised

The listing is generated; it is not hand-edited. What is edited is src/twinbee.notes, and out of it come the labels, the line comments, the block headers and the boundaries of every data area. Each D directive declares a range with a name and with the measurement it comes from: no boundary is set by eye.

src/twinbee.entries   entry points the tracer cannot deduce, each with its
                      reason: INIT, the interrupt hook, the routine the
                      Game Master calls, the four dispatch tables and the
                      address the code pushes as a return address
src/twinbee.nocode    ranges that are data even though the tracer reaches
                      them. Empty here: it was not needed
src/twinbee.notes     the annotations
src/twinbee.asm       the generated listing, 11,500 lines

What each number means

make sanity prints the budget: 14,406 bytes of code and 18,362 bytes of data, which add up to the 32,768 of the cartridge with zero left over. make densidad prints the other two: 1,000 named blocks and 41.4 % of the instructions carrying a line comment, with no routine below 10 %.

None of those figures is typed in by hand anywhere: tests/test_listado.py recomputes them from the listing and fails if they drop.

Checking the pictures

make imagenes draws the scenery, the tile sheets and the sprites from the ROM bytes, running in Python the very same decompressor the Z80 runs. make vram boots the cartridge in openMSX five times -one per stage-, dumps the 16 KB of VRAM at the exact instant the scenery finishes loading and compares it byte for byte against what Python built. Today it comes out at zero.

The cartridge

32,768 bytes, mapped into pages 1 and 2 of the MSX, that is 0x4000 to 0xBFFF. Not a MegaROM: no bank switching anywhere.

sha256  02bdce8ceafe6af05a45b61a689e78807551df663afd152090f7cd9cac827dd4

Two headers, not one

0x4000 carries the standard "AB" header, with INIT at 0x40B1 and STATEMENT, DEVICE and TEXT all zero. That is the one the BIOS reads.

0x4010 carries a second one, "CD" 07 40, and this cartridge never reads it: it is there for the one plugged in next door. It is the header of the Konami Game Master, the house cheat cartridge, and the layout of the bytes that follow is not guesswork - it comes from hand-running the Game Master's own reader. That reader copies 21 bytes from 0x4012, takes the catalogue number and then walks a flags byte at 0x4014: one rra per field, and a bit at zero means the field is present.

With flags 0x08 -only bit 3 set- the fields come out like this, and the last one ends exactly at 0x4025, one byte before code resumes:

offset field
0x4015 0xE000 and 0x04: the scene variable, and the scene where cheats apply
0x4018 0xE076 and 0x05: the stage variable, and how many stages: five
0x401B 0xE070: the lives
0x401D 0xE06C: the high score
0x401F 0xE068: the score
0x4021 0xE002: the mode bits
0x4023 0x4103: a routine of this cartridge, which the Game Master calls across slots to set a stage up

The field that is missing -bit 3- is the pointer to the block of game data the Game Master knows how to save to and load from disk. Twin Bee declares none.

The hidden mark

The last nine useful bytes of the cartridge, at 0xBFF7:

ba b7 9a ac 81 91 06 40 aa

Nobody in this cartridge reads them. It is the signature Konami left at the end of its ROMs: the title in katakana, the 0x06 length, the 07 40 of RC-740 and the 0xAA that closes it. This was discovered by Manuel Pazos, and without his work these bytes would be padding.

And its last six bytes are exactly the ones Nemesis (RC-742) goes hunting for through slots 0, 0x80, 0x84, 0x88 and 0x8C: that is how Nemesis knows whether Twin Bee is plugged in next door.

Video

The register table lives at 0x47F1 and is written from register 7 down to 0 -ld c,8, then dec c- so it reads backwards from how it is stored:

register value what it means
R0 0x02 SCREEN 2
R1 0xE2 16 KB, screen and interrupt on, 16x16 sprites
R2 0x0E name table at 0x3800
R3 0x7F colour at 0x0000, and the rest is a mask
R4 0x07 patterns at 0x2000
R5 0x76 sprite attributes at 0x3B00
R6 0x03 sprite patterns at 0x1800
R7 0xE4 ink 14 on background 4, the blue of the sea

R3 and R4 are the trap of SCREEN 2: they are not addresses, they are a base and a mask. Read as addresses they put the tables in the wrong place, the shapes come out right and the colours come out in stripes. Here they land the other way round from the usual: patterns above, colour below.

Memory map

0x4000 - 0x4025   the two headers
0x4025 - 0x4103   the framework: interrupt hook, dispatchers, INIT
0x4103 - 0x4172   the routine the Game Master calls, and the scene dispatch
0x4182 - 0x4535   the eight scenes
0x4535 - 0x4652   the score, in BCD
0x4652 - 0x47F9   the decompressor and the VRAM routines
0x47F9 - 0x48B4   the joysticks
0x48B4 - 0x4D1E   the intro and the title screen, with their scripts
0x4D1E - 0x518C   the sound player
0x518C - 0x5D20   the tunes
0x5D20 - 0x6CD1   the game: ships, shots, bombs, bells and clouds
0x6CD1 - 0x6F8F   the scenery: scroll, map script and stretches
0x6F8F - 0x8E8F   the 248 row blocks
0x8E8F - 0x994A   sprite patterns
0x994A - 0xA14B   scenery patterns and colour
0xA14B - 0xAD25   collisions and waves
0xAD25 - 0xBFF7   the enemy engine, the trigonometry and the boss
0xBFF7 - 0xC000   the hidden mark

The RAM

The game clears 0xE000 to 0xF0FF on boot and puts the stack at the top of it. Some landmarks:

0xE000  the scene, and 0xE001 the step inside it
0xE003  the frame counter, which half the cartridge looks at
0xE007  what the joystick reads, and 0xE009 what has just been pressed
0xE010  the three sound channels, 0x13 bytes each
0xE076  the stage, and 0xE07D the number you see, in BCD
0xE0A0  the two ships
0xE100  the shots
0xE160  the fourteen enemies, 0x20 bytes each
0xE320  the boss
0xE400  the map, decompressed
0xEB00  the join table, brought back from VRAM
0xEC40  the screen buffer, 768 bytes
0xEF80  the sprite buffer, 32 sprites

The code

Everything hangs off the interrupt

INIT (0x40B1) does four things and nothing else: it works out which slot the cartridge is in and enables page 2, it installs a jp to 0x402E at the H.KEYI hook, it clears the RAM, and it falls into a jr $ at 0x40F9.

From there on the whole game runs inside the interrupt. cada_cuadro (0x402E) is the top of it: the sound first, then a latch so a frame cannot enter twice, then the joysticks and the scene.

This is the framework the Konami cartridges of 1986 share: Knightmare (RC-739) and The Goonies (RC-734) carry the same one, down to two ld that write to the cartridge's own ROM at the same relative offsets and go nowhere.

The dispatcher of two instructions

reparte_por_tabla:
    pop hl              ; the return address IS the table
    call palabra_de_tabla
    ex de,hl
    jp (hl)

The table sits right behind the call, in the code. A call reparte_por_tabla followed by eight words is a switch of eight cases, and the ret of whichever routine it lands on returns to whoever called the caller. There are four of these in the cartridge, and between them they dispatch the eight scenes, the forty enemy behaviours, the five bosses and the five boss shots.

The scenes, and why the first one is last

(0xE000) is the scene and (0xE001) the step inside it. The scene dispatch picks one of eight routines, and inside each one the steps are chained with djnz:

escena_0_la_presentacion:
    djnz L_4195          ; step 0 and steps 2 up, further down
    ...                  ; step 1

With B at one the first djnz does not jump and falls into the first branch; with two it jumps once; and with zero the djnz leaves B at 0xFF and jumps as well. So step 0 -the one that sets the screen up- ends up at the end of the chain. That is why in this listing the preparation of each scene reads last and not first.

The decompressor

Everything this cartridge puts into VRAM goes through 0x4716. The format, read instruction by instruction at 0x471F:

byte meaning
0x00 end of block
< 0x80 run: the next byte, that many times
0x80 change destination: the next two bytes are the new VRAM address, and the filter is switched off
> 0x80 literals: the next n & 0x7F bytes, as they are

And every byte that comes out goes through the filter at 0x4786, which looks at register C:

sube_espejado (0x4695) enters with C=1 and sube_tal_cual (0x4699) with C=0; both repeat the same block three times, stepping 0x800 in VRAM, which are the three banks of SCREEN 2.

The sprites are half-stored

sube_patrones_de_sprite (0x4743) reads sixteen bytes -half a sprite- and writes them followed by the same sixteen flipped. A 16x16 sprite pattern is 32 bytes, the first sixteen being the left half; so half stored plus half computed is a sprite whose right side mirrors its left. That is why every enemy, every ship and every bell in Twin Bee is symmetric.

VRAM as a workbench

The decompressor only knows how to write to VRAM. So when the game needs a compressed table in RAM -the 81 values that decide how the two ships join hands- it decompresses it into 0x3B80, an unused gap in the sprite attribute table, and brings it back to 0xEB00 with LDIRMV. The video memory doubles as a workbench.

The scenery

A row of the screen is a block of 32 tiles, and the map is the list of those blocks:

  1. descomprime_el_mapa (0x460C) walks the script at 0x6D74. Each byte indexes the stretch table at 0x6E01, and the stretch it picks -a list of row codes ending in 0xFF- is copied straight into 0xE400.
  2. la_fila_numero (0x6D62) turns a row code into an address with five add hl,hl, that is index times 32, plus 0x6F8F.
  3. monta_las_veinticuatro_filas (0x6D08) copies twenty-four of them into the screen buffer with thirty-two consecutive ldi each.

The arithmetic closes by itself: between 0x6F8F and 0x8E8F there are 0x1F00 bytes, exactly 248 rows, and the highest code the stretches use is 0xF7 = 247.

Sprites take turns

The TMS9918 draws four sprites per line and drops the rest. sube_los_sprites (0x46CE) keeps the first four fixed -the ships and their shots- and uploads the other twenty-eight in an order that rotates: (0xE00F) advances 0x10 a frame and wraps at 0x1E, and the step inside the loop is 0x44. No enemy is skipped two frames running.

The enemies

Fourteen slots of 0x20 bytes from 0xE160, always laid out the same way:

(ix+0)      the drawing
(ix+1)      the class: the index into the forty-pointer table
(ix+2,3)    vertical speed, with its fractional part
(ix+4,5)    horizontal speed
(ix+6,7)    vertical position
(ix+8,9)    horizontal position
(ix+10,11)  sprite pattern and colour
(ix+14)     the wait between shots
(ix+16)     the frame counter
(ix+19)     the heading, on a 256-degree circle

Classes 0xFF and 0xFE are reserved -the first switches the slot off, the second means it is dying- and that is why 0xAD42 and 0xAD51 do two inc a before dispatching.

The trigonometry

One quadrant of cosine, 65 values at 0xB950, and out of it come the sine, the cosine and all four quadrants: seno_y_coseno (0xB921) indexes it with the angle and fixes the sign from the quadrant, and gets the sine out of the same table by entering at 0x40 - k.

The other way round -from a pair of distances to an angle- is angulo_hacia_la_nave (0xB850): it divides with eight bits of fraction and walks the eight tangents at 0xB991 from largest to smallest, eight degrees per step.

The sound

Three tone channels plus noise, all driven from the interrupt by el_reproductor (0x4E48). A request carries the tune in the low six bits and the priority in the top two: if what is already playing outranks it, the request is dropped.

Each tune is a script the interpreter at 0x4F06 walks: 0xFE jumps, 0xFF and above end it, a byte whose high nibble is 2 changes the instrument and the note length, a 1 sets the PSG envelope, and anything else is a note -volume in the high nibble, octave in the low one, with the note code in the byte after it-. The periods come from twelve semitones at 0x510E, and the octaves are made by doubling with add hl,hl.

In the emulator

Static analysis only takes you so far. Three of the things on the findings page were settled by booting the cartridge in openMSX and looking.

Checking the pictures against the VRAM

make vram

This boots the cartridge five times -one per stage-, dumps the 16 KB of VRAM at the exact instant the scenery finishes loading, and compares it byte for byte against what tools/pantallas.py, tools/mapas.py and tools/sprites.py build in Python from the ROM.

The instant matters. The dump is taken at 0x5FEC, the instruction right after call 0x9177:

The stage is imposed with a breakpoint at 0x994A, just before that routine reads (0xE076). Nothing is faked: one byte of the starting state is changed, which is what a player reaching that stage would do.

Today it comes out at:

titulo: 0 bytes distintos de 16384
fase 1: 0 casillas distintas de 900, y 0 bytes de sprite distintos de 2048
... (the same for the other four)

Where the load chain came from

make cargas

The scenery tiles of stages 2, 3 and 4 do not fill the whole sheet: the top tiles are not loaded by the stage and what shows there is whatever the title screen left behind. Guessing that costs an afternoon of looking for a load that does not exist.

tools/omsx_cargas.tcl settles it by putting a breakpoint on every door of the decompressor -0x4695, 0x4699, 0x469B, 0x4711, 0x4716, 0x4743 and 0x46AD- and writing down, in order, what registers it enters with. Out comes the whole chain: intro → title → stage, with every block, its destination and its filter. tools/pantallas.py reproduces that chain, which is why the check closes at zero.

That same log is what showed that the FILVRM at 0x4BEC fills one bank and not three - and that difference is exactly what made stage 4's colour come out wrong.

Reading a table the ROM does not carry

The prize table at 0xEB88 is written into RAM by hand, so there is nothing to read in the cartridge. A breakpoint at 0xA214 and a dump of those 32 bytes gives it:

00 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00
04 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00

Five prizes in thirty-two slots. And a write watchpoint over that range gives who puts them there: 0x5D41, 0x5D45, 0x5D49 and 0x5D4D, inside empieza_la_partida.

The traps of Tcl, already paid for

The scripts here respect three things this series learned the hard way: no brackets inside a format, binary files opened with -translation binary, and debug read_block instead of debug save_to_file, which does not exist.

Code shared with other Konami cartridges

This disassembly has been compared, instruction by instruction, with every other Konami one in the series. A block counts when the same instructions, at least six of them from a label to its ret or its unconditional jump, are in both cartridges; the addresses are left aside, because they change from one cartridge to the next. Of the other 57, 39 have at least one block in common with this one; these are the ones that share the most:

Cartridge Blocks Instructions For example (here = there)
Penguin Adventure 24 279 pon_el_mezclador (0x4E0F) = pon_la_mezcla
Nemesis / Gradius 18 188 pon_el_mezclador (0x4E0F) = pon_la_mezcla
Knightmare 16 165 cada_cuadro (0x402E)
Konami’s Soccer 14 135 parpadea_la_eleccion (0x4C11) = parpadea_el_cursor_del_menu
Yie Ar Kung-Fu II 14 122 baja_un_paso (0x4B0A)
Hyper Sports 3 12 127 cada_cuadro (0x402E) = manejador_de_interrupcion
The Goonies 11 97 baja_un_paso (0x4B0A)
Konami's Ping Pong 11 98 baja_un_paso (0x4B0A) = sube_el_rotulo
Q*bert 11 114 pon_el_mezclador (0x4E0F)
Road Fighter 10 98 parpadea_la_eleccion (0x4C11)

The whole matrix, the 58 cartridges against each other, is on The routines in the series database, along with the method and the program that measures it.