Difference between revisions of "Sega MegaDrive"

From SizeCoding
Jump to: navigation, search
(Finish adding introductory info about the hardware and info sizecoders should know about TMSS, interrupts, setting up the console, etc)
(fix typos)
 
Line 250: Line 250:
 
==== Sprites ====
 
==== Sprites ====
  
Sprites are freely moving objects independent from the 2 background planes. They can be configured to be any size ranging from 1x1 tile to 4x4 tiles (8x8 px tiles, to 8x8 to 32x32 px). Any combination of width and height as long as it's within the 1x1 to 4x4 limit is allowed.
+
Sprites are freely moving objects independent from the 2 background planes. They can be configured to be any size ranging from 1x1 tile to 4x4 tiles (8x8 px tiles, so 8x8 to 32x32 px). Any combination of width and height as long as it's within the 1x1 to 4x4 limit is allowed.
  
 
Sprites reside in VRAM as a sort of display list. Every sprite field has x,y position information, tile index for where to find the first tile of the sprite in VRAM, horizontal and vertical flipping, which palette (PAL 0, 1, 2, or 3) to use and finally the "link" value. The link value is used to tell the VDP which sprite in the Sprite Attribute Table (SAT) to process next. The VDP will always start processing the first sprite slot found in the SAT, then it reads the link value for the next sprite and jumps to its slot. Sprite processing ends when the VDP finds a sprite with a link value of 0.
 
Sprites reside in VRAM as a sort of display list. Every sprite field has x,y position information, tile index for where to find the first tile of the sprite in VRAM, horizontal and vertical flipping, which palette (PAL 0, 1, 2, or 3) to use and finally the "link" value. The link value is used to tell the VDP which sprite in the Sprite Attribute Table (SAT) to process next. The VDP will always start processing the first sprite slot found in the SAT, then it reads the link value for the next sprite and jumps to its slot. Sprite processing ends when the VDP finds a sprite with a link value of 0.
Line 277: Line 277:
 
* From the VDP registers
 
* From the VDP registers
  
It's impossible to get an interrupt on startup unless you enable it from both sides, because even if interrupts were to be enabled though VDP registers, the 68k always initializes to IPL level 7 on startup, so all interrupts are ignored.
+
It's impossible to get an interrupt on startup unless you enable it from both sides, because even if interrupts were to be enabled through VDP registers, the 68k always initializes to IPL level 7 on startup, so all interrupts are ignored.
  
 
To implement raster effects without interrupts, you can poll the VDP's HVCOUNT port ($C00008). You can get an approximate of what line the VDP is currently rendering there.
 
To implement raster effects without interrupts, you can poll the VDP's HVCOUNT port ($C00008). You can get an approximate of what line the VDP is currently rendering there.

Latest revision as of 09:32, 20 December 2025

SEGA MegaDrive / Genesis

The SEGA MegaDrive / Genesis is a 16-bit videogame console released by SEGA in 1989.


It features:

  • 320x224 screen resolution by default, read "Screen Resolutions" for more information.
  • 4x 16 color palettes.
  • Tile based display chip with 2 scrolling tilemaps.
  • Full plane or 16 pixel column independent vertical scroll.
  • Full plane, 8 pixel row or scanline independent horizontal scroll.
  • 80 sprites per frame in H40 mode, 64 sprites in H32 mode. Read "Screen Resolutions" for more information.
  • 20 sprites per scanline in H40 mode, 16 sprites in H32 mode.
  • 64K of dedicated Video Memory (VRAM)
  • YM2612 FM Sound Chip + SN76489 PSG Sound Chip (Integrated in the VDP)

Setting up

Cartridges have a ROM header that can normally be ditched entirely, since it's only used by emulators to display information about the cartridge or choose correct emulation settings / peripherals. This is not true for all console revisions, though; one part of the header is mandatory for systems equiped with the TradeMark Security System. Read "ROM Header" and "TMSS" for more information.

CPU Vector table

This must be the very first thing in the ROM. On power up or reset the CPU initializes the stack pointer held at address $000000 and jumps to the reset vector held at address $000004. The rest of the vectors can be discarded competely, since they are only used for exception handling and video interrupts (more information about interrupts can be found in the "VDP" section). If a cartridge doesn't want to process a particular interrupt, or wants to ignore it, standard procedure is to set that vector to a dummy handler that simply returns from the exception (RTE). For our purposes, if only the stack pointer and reset vector will be used, we can use the remaining address space used by the vector table as executable code space.

Below are examples that illustrate how the vector table is conventionally set up and how we might want to do it.

	; Example 1: Standard procedure, where all vectors are initialized to something.
	; If a particular vector is not to be used, a "null" or "dummy" handler is put.
	dc.l   0x00FFE000			; Initial stack pointer value
	dc.l   CPU_EntryPoint		; Start of program
	dc.l   CPU_Exception		; Bus error
	dc.l   CPU_Exception		; Address error
	dc.l   CPU_Exception		; Illegal instruction
	dc.l   CPU_Exception		; Division by zero
	dc.l   CPU_Exception		; CHK CPU_Exception
	dc.l   CPU_Exception		; TRAPV CPU_Exception
	dc.l   CPU_Exception		; Privilege violation
	dc.l   INT_Null				; TRACE exception
	dc.l   INT_Null				; Line-A emulator
	dc.l   INT_Null				; Line-F emulator
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Spurious exception
	dc.l   INT_Null				; IRQ level 1
	dc.l   INT_Null				; IRQ level 2
	dc.l   INT_Null				; IRQ level 3
	dc.l   INT_HInterrupt		; IRQ level 4 (horizontal retrace interrupt)
	dc.l   INT_Null  			; IRQ level 5
	dc.l   INT_VInterrupt		; IRQ level 6 (vertical retrace interrupt)
	dc.l   INT_Null				; IRQ level 7
	dc.l   INT_Null				; TRAP #00 exception
	dc.l   INT_Null				; TRAP #01 exception
	dc.l   INT_Null				; TRAP #02 exception
	dc.l   INT_Null				; TRAP #03 exception
	dc.l   INT_Null				; TRAP #04 exception
	dc.l   INT_Null				; TRAP #05 exception
	dc.l   INT_Null				; TRAP #06 exception
	dc.l   INT_Null				; TRAP #07 exception
	dc.l   INT_Null				; TRAP #08 exception
	dc.l   INT_Null				; TRAP #09 exception
	dc.l   INT_Null				; TRAP #10 exception
	dc.l   INT_Null				; TRAP #11 exception
	dc.l   INT_Null				; TRAP #12 exception
	dc.l   INT_Null				; TRAP #13 exception
	dc.l   INT_Null				; TRAP #14 exception
	dc.l   INT_Null				; TRAP #15 exception
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)
	dc.l   INT_Null				; Unused (reserved)

	; Example 2: For sizecoding purposes, we only specify the initial stack pointer
	; and the reset vector, the rest of the space we can use as executable code space.
	; In theory this should work, in non TMSS systems. In practice TMSS compatibility should
	; be taken into account (read "TMSS" for more information) and some emulators might not like this.
	dc.l   0x00FFE000			; Initial stack pointer value
	dc.l   CPU_EntryPoint		; Start of program
CPU_EntryPoint:
	<our demo>
	bra.s	CPU_EntryPoint

This vector table is then followed by the ROM header at 0x100

ROM Header

The ROM Header is a data structure located at 0x000100 that specifies some metadata about the ROM; like the original and localized titles of the game, author and copyright, cart serial number, region, some information about which peripherals the game will use, Save RAM mapping ranges, ROM mapping ranges, and most importantly, the system type. If you want to read the full structure of the ROM Header, head to https://plutiedev.com/rom-header

Mega Drive systems prior to probably the Mega Drive 1 VA5 or VA4 can boot cartridges that contain absolutely no ROM Header, as these consoles simply ignore it. You could stop there and just ditch the ROM Header entirely, but later Mega Drive 1's, Mega Drive 2's and Mega Drive 3's all come equipped with a trademark challenge-response type protection scheme that makes this not that simple. This is called the TradeMark Security System, or TMSS.

TMSS

TMSS is an onboard 16KB ROM that gets mapped to the cartridge's address space when the cosole first turns on. The protection scheme has two stages:

  • First, and skipping a few minor details, TMSS uploads some code to RAM, jumps to said code and then unmaps itself and maps the cartridge into the address space. The RAM code then scans the cartridge's ROM Header for the system type. All it wants is to find the string "SEGA" or " SEGA" (to account for a typo, maybe?), if the SEGA string is found at address 0x000100, TMSS proceeds to the second stage, if not, it unmaps the cartridge and maps itself back, exits that RAM routine and locks up the system.

TMSS then maps itself back, uploads some palettes to CRAM, uploads tiles and a simple tilemap to VRAM and runs a timer. This is to show the following message on screen:

   PRODUCED BY OR
 UNDER LICENSE FROM
SEGA ENTERPRISES LTD.
  • In the second stage, when the timer runs out, TMSS disables display by reseting the VDP's MODE2 register, but it doesn't clear VRAM or CRAM, so a few colors and assets reside in video memory after control has been passed to the cartridge.

It then locks the VDP, maps the cartridge, initializes the cartridge's stack pointer and jumps to its reset vector. TMSS locks the VDP so the cartridge has to write the string "SEGA" at $A14000 before trying to access any video registers, otherwise the VDP won't assert /DTACK when the 68k tries to read or write to its ports, effectively locking up the console.


So, all you need to ensure your demo has full TMSS compatibility is have the string "SEGA" at 0x000100 and make your demo write "SEGA" at $A14000 before accessing any VDP port. Of course, this would make true 256 byte demos impossible, since you need those trailing 4 bytes for the "SEGA" string. What we can do is leverage ROM mirroring, and put the "SEGA" string where the stack vector would be. If we make a simple EEPROM cartridge and cut the address lines to the 256 byte range, TMSS would read 0x000100 as 0x000000.

There is a problem with emulators, however. Emulators usually load ROMs differently depending on the system type, but as we don't have one (we just care about the "SEGA" string) they will probably default to loading it as if it were a flat < 4MB cartridge. If emulators load ROMs in a flat 4MB buffer, the following parts of the address space that we expect to be mirrored might contain all zeros or garbage. To prevent this, the safest thing to do is to emulate a non TMSS system when running the demo on an emulator. BlastEm, for example, emulates non TMSS systems by default, but lets you choose.

Memory map

Start address 	End address 	Description 
$000000 		$3FFFFF 		Cartridge ROM/RAM 
$400000 		$7FFFFF 		Reserved (used by the Mega-CD and 32X)
$800000 		$9FFFFF 	    Reserved (used by the 32X)
$840000 		$85FFFF 	    32X frame buffer 	
$860000 		$87FFFF 	    32X frame buffer overwrite mode 
$880000 		$8FFFFF 	    32X cartridge ROM (first 512kB bank only)
$900000 	    $9FFFFF 	    32X cartridge bankswitched ROM (any 512kB bank, controlled by 32X registers)
$A00000 	    $A0FFFF 	    Z80 memory space
$A10000 	    $A10001 	    Version register
$A10002 	    $A10003 	    Controller 1 data
$A10004 	    $A10005 	    Controller 2 data
$A10006 	    $A10007 	    Expansion port data
$A10008 	    $A10009 	    Controller 1 control
$A1000A 	    $A1000B 	    Controller 2 control
$A1000C 	    $A1000D 	    Expansion port control
$A1000E 	    $A1000F 	    Controller 1 serial transmit
$A10010 	    $A10011 	    Controller 1 serial receive
$A10012 	    $A10013 	    Controller 1 serial control
$A10014 	    $A10015 	    Controller 2 serial transmit
$A10016 	    $A10017 	    Controller 2 serial receive
$A10018 	    $A10019 	    Controller 2 serial control
$A1001A 	    $A1001B 	    Expansion port serial transmit
$A1001C 	    $A1001D 	    Expansion port serial receive
$A1001E 	    $A1001F 	    Expansion port serial control
$A10020 	    $A10FFF 	    Reserved
$A11000 	                    Memory mode register
$A11002 	    $A110FF 	    Reserved
$A11100 	    $A11101 	    Z80 bus request
$A11102 	    $A111FF 	    Reserved
$A11200 	    $A11201 	    Z80 reset
$A11202 	    $A12FFF 	    Reserved
$A13000 	    $A130FF 	    TIME registers; used to send signals to the cartridge
$A130EC 	    $A130EF 	    "MARS" when 32X is attached
$A130F1 	                    SRAM access register
$A130F3 	                    Bank register for address $80000-$FFFFF
$A130F5 	                    Bank register for address $100000-$17FFFF
$A130F7 	                    Bank register for address $180000-$1FFFFF
$A130F9 	                    Bank register for address $200000-$27FFFF
$A130FB 	                    Bank register for address $280000-$2FFFFF
$A130FD 	                    Bank register for address $300000-$37FFFF
$A130FF 	                    Bank register for address $380000-$3FFFFF
$A14000 	    $A14003 	    TMSS "SEGA"
$A14101 	                    TMSS/cartridge register
$A14102 	    $BFFFFF 	    Reserved
$C00000 	    $C00001 	    VDP data port
$C00002 	    $C00003 	    VDP data port (mirror)
$C00004 	    $C00005 	    VDP control port
$C00006 	    $C00007 	    VDP control port (mirror)
$C00008 	    $C00009 	    VDP H/V counter
$C0000A 	    $C0000F 	    VDP H/V counter (mirror)
$C00011 	                    PSG output
$C00013 	    $C00017 	    PSG output (mirror)
$C0001C 	    $C0001D 	    Debug register
$C0001E 	    $C0001F 	    Debug register (mirror)
$C00020 	    $FEFFFF 	    Reserved
$FF0000 	    $FFFFFF 	    68000 RAM

Startup

Here it's described what things you should do first in your ROM, and the state to expect from the console when it first turns on.

In a TMSS system, when control is passed to the cartridge, both horizontal and vertical interrupts will be disabled from the VDP side, DMA will be disabled, there will be leftover graphics and colors from the TMSS screen and display rendering will be turned off. In a non TMSS system state is pretty much random, main memory and video memory won't be initialized and the VDP could be in virtually any random state. Make sure to also read the "Interrupts" section in "VDP" below.

To ensure predictable state on any console, you should first write "SEGA" at $A14000 to unlock the VDP, test the VDP control port to make it return to a known state and enable display rendering. Some of the steps (like the hardware version check before writing "SEGA") and testing VDP control could be removed, but bugs might arise in some console revisions.

A simple ROM that sets a background color and assumes ROM mirroring:

        dc.l    "SEGA"
        dc.l    start

start:
        ; Test hardware rev. Skipping this and blindly writing to $A14000
        ; regardless of the console revision could work, but not guaranteed
        move.w  $A10000, ccr
        bcc.s   @skip_tmss
        move.l  sp, ($A14000)           ; Unlock VDP with "SEGA". sp contains "SEGA"
@skip_tmss:
        lea     ($C00004), a0
        ; Stop VDP / Return VDP to known state. Skipping this could
        ; result in the VDP processing whatever was previously in its FIFO after a reset
        tst.w   (a0)
                                        
        move.l  #$80048F00, (a0)        ; Set bit 2 of MODE1, and set Auto Increment to 0
        move.l  #$8144C000, (a0)        ; Set bit 2 of MODE2, enable display, and point data port to CRAM
        move.w  #$0F00, -4(a0)          ; Write blue at color index 0 of CRAM
        bra.s   *

VDP

The Video Display Processor (VDP) is at the heart of graphics (and some sound) features of the Mega Drive. At first glance it might seem like a modest tile based video controller but it has tricks up its sleeve. It is assumed that you are familiar with VDP registers. If not, this resource is very handy: https://plutiedev.com/vdp-registers

You should also know what ports to use and how to write to these various registers: https://plutiedev.com/vdp-setup

Screen Resolutions

The VDP always initializes to a 320x224 pixel resolution, but on PAL systems a higher vertical resolution of 240 pixels is selectable through the MODE2 register. Bit 3 selects either V28 (224px) or V30 (240px) vertical resolutions.

Available on all systems regardless of region is the possibility of choosing a narrower horizontal resolution of 256 pixels as well. This is done through the MODE4 register, where if bits 7 and 0 are both clear, H32 mode or 256 pixel horizontal resolution is selected. If both bits are set instead, the standard H40 mode or 320 pixel horizontal resolution is selected.

Very important thing about H32

The native horizontal resolution of the VDP is 320 pixels, as we've said, how does it achieve a 256 pixel horizontal resolution in H32 mode, then? By underclocking its pixel clock.

This means that when you select a horizontal resolution of 256 pixels the VDP runs slower, since a lot of its internal logic is dependent on the pixel clock. One very important result that you'll have to face if you select this mode is that the maximum sprite amount per frame will be reduced from 80 (in H40) to 64 (in H32). Coincidentally, the maximum sprite amount per scanline will also be reduced from 20 to 16. This is simply because the VDP will run at a slower pixel clock and it won't be fast enough to fetch all the sprites it's capable of rendering during every blanking period.

Sprites

Sprites are freely moving objects independent from the 2 background planes. They can be configured to be any size ranging from 1x1 tile to 4x4 tiles (8x8 px tiles, so 8x8 to 32x32 px). Any combination of width and height as long as it's within the 1x1 to 4x4 limit is allowed.

Sprites reside in VRAM as a sort of display list. Every sprite field has x,y position information, tile index for where to find the first tile of the sprite in VRAM, horizontal and vertical flipping, which palette (PAL 0, 1, 2, or 3) to use and finally the "link" value. The link value is used to tell the VDP which sprite in the Sprite Attribute Table (SAT) to process next. The VDP will always start processing the first sprite slot found in the SAT, then it reads the link value for the next sprite and jumps to its slot. Sprite processing ends when the VDP finds a sprite with a link value of 0.

Sprites can be multiplexed (i.e. change their possition and attributes mid frame) to surpass the maximum amount of sprites per frame. Beware that the VDP caches some of the sprite attributes, however. For every sprite fetch it caches the Y coordinate and size of the sprite. The cache is flushed by writing to the Sprite Attribute Table in VRAM, but not if the table's address is swapped mid frame, so if you have two Sprite Attribute Tables and just swap from one to the other mid frame to change sprite behavior on the fly you'll end up with half the data from the previous table affecting your new sprites.

More information about sprite definition and caching can be found here: https://plutiedev.com/sprites

Background planes

The VDP can generate 2 planes of tile based backgrounds. Each tile in the tilemap(s) can reference a different 16 color palette, and each background plane can be independently scrolled in a few different ways:

  • Each plane can be scrolled completely. Or scrolled in "full plane".
  • Each plane can be scrolled per individual vertical column. Each column is 16 pixels in width. This is done by writing to VSRAM (vertical scroll RAM). Each word is a different scroll position for each column on each plane.
  • Each plane can be scrolled per individual horizontal row of 8 pixels in height. Think of it as scrolling "one row of tiles". This is done by writing to HSCROLL, a horizontal scroll table similar to VSRAM but held in VRAM.
  • Each plane can be scrolled per individual horizontal line. Yes, you can do scanline independent scrolling without interrupts. This is also through the HSCROLL table.

Both planes can be either 32x32, 32x64, 64x32, 64x64, 128x64 or 64x128 tiles in size. You cannot select different sizes for each plane. If you select 32x32, both planes will be 32x32 tiles in size.

Interrupts

This is important for sizecoding purposes. The VDP generates horizontal interrupts, vertical interrupts and "external" interrupts. External interrupts are for lightguns and such peripherals.

Interrupts are enabled from two sides:

  • From the interrupt mask set in the 68k
  • From the VDP registers

It's impossible to get an interrupt on startup unless you enable it from both sides, because even if interrupts were to be enabled through VDP registers, the 68k always initializes to IPL level 7 on startup, so all interrupts are ignored.

To implement raster effects without interrupts, you can poll the VDP's HVCOUNT port ($C00008). You can get an approximate of what line the VDP is currently rendering there.

To get VBlank state you can poll the VDP's status register (reading from VDP control, or $C00004) and check the VBlank flag.

Additional Resources