Writing stuff in Assembly for Sega Genesis #3

In this post I will describe how to display an image from tiles on the Sega Genesis emulator using assembler.
The splash picture of Demens Deum in Exodus emulator will look like this:

The process of outputting a PNG image using tiles is done in steps:

  1. Reducing the image to fit the Sega screen
  2. Convert PNG to assembler data-code, with division into colors and tiles
  3. Loading the color picker into CRAM
  4. Loading tiles / patterns into VRAM
  5. Loading tile indices at Plane A / B addresses in VRAM

You can reduce the image to fit Sega’s screen using your favorite graphics editor, for example Blender.

Convert PNG

To convert images, you can use the ImaGenesis tool, to work under wine you need Visual Basic 6 libraries, they can be installed using winetricks (winetricks vb6run), or RICHTX32.OCX can be downloaded from the Internet and put into the application folder for correct operation. < / p>

In ImaGenesis, you need to select a 4-bit chroma, export colors and tiles in two assembly files. Next, in the file with colors, you need to put each color in a word (2 bytes), for this you use the dc.w opcode.

For example CRAM splash screen:

 Colors: 
  dc.w $0000 
  dc.w $0000 
  dc.w $0222 
  dc.w $000A 
  dc.w $0226 
  dc.w $000C 
  dc.w $0220 
  dc.w $08AA 
  dc.w $0446 
  dc.w $0EEE 
  dc.w $0244 
  dc.w $0668 
  dc.w $0688 
  dc.w $08AC 
  dc.w $0200 
  dc.w $0000 

Leave the tile file as it is, it already contains the correct format for loading. An example of a part of a tile file:

 Tiles: 
	dc.l	$11111111	; Tile #0 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111	; Tile #1 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 
	dc.l	$11111111 

As you can see from the example above, the tiles are an 8×8 grid of CRAM color palette indices.

Colors in CRAM

Loading into CRAM is performed by setting the color load command at a specific CRAM address to the vdp control port. The command format is described in the Sega Genesis Software Manual (1989), I just add that it is enough to add to the address 0x20000 to go to the next color.

Next, you need to load the color into the data port (vdp data); The easiest way to understand loading is with the example below:

VDPCRAMFillLoop: 
    lea Colors,a0 ; pointer to Colors label 
    move.l #15,d7; colors counter 
VDPCRAMFillLoopStep: 
    move.l  d0,vdp_control_port ;  
    move.w  (a0)+,d1; 
    move.w  d1,(vdp_data_port); 
    add.l #$20000,d0 ; increment CRAM address 
    dbra d7,VDPCRAMFillLoopStep 

Tiles in VRAM

Next comes the loading of tiles / patterns into VRAM. To do this, select an address in VRAM, for example 0x00000000. By analogy with CRAM, we address the VDP control port with a command to write to VRAM and a starting address.

After that, you can upload longwords to VRAM, compared to CRAM, you do not need to specify an address for each longword, since there is a VRAM auto-increment mode. You can enable it using the register flag VDP 0x0F (dc.b $ 02)

TilesVRAM: 
  lea Tiles,a0 
  move.l #$40200000,vdp_control_port; write to VRAM command 
  move.w #6136,d0 ; (767 tiles * 8 rows) counter 
TilesVRAMLoop: 
  move.l (a0)+,vdp_data_port; 
  dbra d0,TilesVRAMLoop 

Tile indices in Plane A / B

Now we have to fill the screen with tiles by their index. For this, VRAM is filled at the Plane A / B address, which is put in the VDP registers (0x02, 0x04). For more information about tricky addressing, see Sega’s manual, in my example the VRAM address is 0xC000, let’s unload the indexes there.

Your picture will fill the VRAM off-screen space anyway, so after rendering the screen space, your render should stop rendering and resume when the cursor moves to a new line. There are many ways to implement this set, I used the simplest version of counting on two registers of the image width counter, the cursor position counter.

Example code:

 FillBackground: 
  move.w #0,d0     ; column index 
  move.w #1,d1     ; tile index 
  move.l #$40000003,(vdp_control_port) ; initial drawing location 
  move.l #2500,d7     ; how many tiles to draw (entire screen ~2500) 

imageWidth = 31 
screenWidth = 64 

FillBackgroundStep: 
  cmp.w	#imageWidth,d0 
  ble.w	FillBackgroundStepFill 
FillBackgroundStep2: 
  cmp.w	#imageWidth,d0 
  bgt.w	FillBackgroundStepSkip 
FillBackgroundStep3: 
  add #1,d0 
  cmp.w	#screenWidth,d0 
  bge.w	FillBackgroundStepNewRow 
FillBackgroundStep4: 
  dbra d7,FillBackgroundStep    ; loop to next tile 

Stuck: 
  nop 
  jmp Stuck 

FillBackgroundStepNewRow: 
  move.w #0,d0 
  jmp FillBackgroundStep4 
FillBackgroundStepFill: 
  move.w d1,(vdp_data_port)    ; copy the pattern to VPD 
  add #1,d1 
  jmp FillBackgroundStep2 
FillBackgroundStepSkip: 
  move.w #0,(vdp_data_port)    ; copy the pattern to VPD 
  jmp FillBackgroundStep3 

After that, it remains only to collect rum using vasm, launching the simulator, and see the picture.

Debug

Not everything will work out right away, so I would like to recommend the following Exodus emulator tools:

  1. m68k processor debugger
  2. Changing the number of cycles of the m68k processor (for slow-mo mode in debugger)
  3. Viewers CRAM, VRAM, Plane A / B
  4. Carefully read the documentation for m68k, used opcodes (not everything is as obvious as it seems at first glance)
  5. See examples of code / game disassembly on github
  6. Implement processor execution sabrutines, process them

Pointers to processor execution sabrutines are put in the title of the rum, there is also a project on GitHub with an interactive runtime debugger for Sega, called genesis-debugger.

Use all available tools, nice old school coding and may Blast Processing come with you!

Links

https://gitlab.com/demensdeum/segagenesissamples/-/tree/main/6Image/vasm
http://devster.monkeeh.com/sega/imagenesis/
https://github.com/flamewing/genesis-debugger

Sources

https://www.chibiakumas.com/68000/helloworld .php # LessonH5
https://huguesjohnson.com/programming/genesis/tiles-sprites/

Writing stuff in Assembly for Sega Genesis #2

In this post I will describe how to load colors into Sega’s palette in assembler.
The final result in the Exodus emulator will look like this:

To make the process easier, find a pdf on the Internet called Genesis Software Manual (1989) , it describes the whole process in great detail, in fact, this note is a commentary on the original manual.

In order to write colors to the VDP chip of the Sega emulator, you need to do the following things:

  • Disable TMSS protection system
  • Write correct parameters to VDP registers
  • Write the desired colors to CRAM

For the assembly, we will use vasmm68k_mot and our favorite text editor, for example echo. The assembly is carried out by the command:

 vasmm68k_mot -Fbin minimal.asm -o minimal.gen 

VDP Ports

The VDP chip communicates with the M68K through two ports in RAM – the control port and the data port.
Essentially:

  1. VDP registers can be set through the control port.
  2. Also, the control port is a pointer to that part of the VDP (VRAM, CRAM, VSRAM etc.) through which data is transmitted through the data port

Interesting information: Sega retained compatibility with Master System games, as indicated by MODE 4 from the developer’s manual, in it VDP switches to Master System mode.

Let’s declare ports of control and data:

 vdp_control_port = $ C00004
vdp_data_port = $ C00000 

Disable TMSS protection system

Protection against unlicensed games TMSS has several unlocking options, for example, it is required that the string “SEGA” be in the A1 address register before accessing the VDP.


MOVE.B A1, D0; We get the version of the hardware with the number from A1 to register D0
ANDI.B 0x0F, D0; We take the last bits by the mask so as not to break anything
BEQ.B SkipTmss; If the version is 0, most likely it is a Japanese woman or an emulator without TMSS enabled, then go to the SkipTmss sabrutina
MOVE.L "SEGA" A1; Or write the string SEGA to A1

Write correct parameters to VDP registers

Why set the correct parameters in the VDP registers at all? The idea is that VDP can do a lot, so before rendering, you need to initialize it with the necessary features, otherwise it just won’t understand what they want from it.

Each register is responsible for a specific setting / mode of operation. The Segov manual contains all the bits / flags for each of the 24 registers, a description of the registers themselves.

Let’s take ready-made parameters with comments from the bigevilcorporation blog:

 VDPRegisters:

VDPReg0: dc.b $ 14; 0: H interrupt on, palettes on
VDPReg1: dc.b $ 74; 1: V interrupt on, display on, DMA on, Genesis mode on
VDPReg2: dc.b $ 30; 2: Pattern table for Scroll Plane A at VRAM $ C000
                    ; (bits 3-5 = bits 13-15)
VDPReg3: dc.b $ 00; 3: Pattern table for Window Plane at VRAM $ 0000
                    ; (disabled) (bits 1-5 = bits 11-15)
VDPReg4: dc.b $ 07; 4: Pattern table for Scroll Plane B at VRAM $ E000
                    ; (bits 0-2 = bits 11-15)
VDPReg5: dc.b $ 78; 5: Sprite table at VRAM $ F000 (bits 0-6 = bits 9-15)
VDPReg6: dc.b $ 00; 6: Unused
VDPReg7: dc.b $ 00; 7: Background color - bits 0-3 = color,
                    ; bits 4-5 = palette
VDPReg8: dc.b $ 00; 8: Unused
VDPReg9: dc.b $ 00; 9: Unused
VDPRegA: dc.b $ FF; 10: Frequency of Horiz. interrupt in Rasters
                    ; (number of lines traveled by the beam)
VDPRegB: dc.b $ 00; 11: External interrupts off, V scroll fullscreen,
                    ; H scroll fullscreen
VDPRegC: dc.b $ 81; 12: Shadows and highlights off, interlace off,
                    ; H40 mode (320 x 224 screen res)
VDPRegD: dc.b $ 3F; 13: Horiz. scroll table at VRAM $ FC00 (bits 0-5)
VDPRegE: dc.b $ 00; 14: Unused
VDPRegF: dc.b $ 02; 15: Autoincrement 2 bytes
VDPReg10: dc.b $ 01; 16: Vert. scroll 32, Horiz. scroll 64
VDPReg11: dc.b $ 00; 17: Window Plane X pos 0 left
                    ; (pos in bits 0-4, left / right in bit 7)
VDPReg12: dc.b $ 00; 18: Window Plane Y pos 0 up
                    ; (pos in bits 0-4, up / down in bit 7)
VDPReg13: dc.b $ FF; 19: DMA length lo byte
VDPReg14: dc.b $ FF; 20: DMA length hi byte
VDPReg15: dc.b $ 00; 21: DMA source address lo byte
VDPReg16: dc.b $ 00; 22: DMA source address mid byte
VDPReg17: dc.b $ 80; 23: DMA source address hi byte,
                    ; memory-to-VRAM mode (bits 6-7)

Ok, now let’s go to the control port and write all the flags to the VDP registers:


PrepareToFillVDPRegisters:
    move.l # VDPRegisters, a0; We write the address of the parameter table in A1
    move.l # $ 18, d0; Cycle counter - 24 = 18 (HEX) in D0
    move.l # $ 00008000, d1; Preparing a command to write to the VDP register at index 0, according to the manual - 1000 0000 0000 0000 (BIN) = 8000 (HEX)

FillInitialStateForVDPRegistersLoop:
    move.b (a0) +, d1; We write in D1 the total value of the VDP register from the parameter table, for sending to the VDP control port
    move.w d1, vdp_control_port; We send the final command + value from D1 to the VDP control port
    add.w # $ 0100, d1; Raise the VDP register index by 1 (binary addition +1 to the index according to Sega's manual)
    dbra d0, FillInitialStateForVDPRegistersLoop; Decrease the register counter, continue the loop if necessary 

The most difficult thing is to read the manual and understand in what format the data is fed to the control port, experienced developers will figure it out right away, but inexperienced ones … They will think a little and understand that the syntax for writing registers is as follows:

0B100 (5 bits – register index) (8 bits / byte – value)

0B1000001001000101 – write to the VDP register 2 (00010), the value of the flags 01000101.

Write the desired colors to CRAM

Next, we go to write two colors into the color memory CRAM (Color RAM). To do this, write to the control port a command to access the color at index 0 in CRAM and send the color to the date port. Everyone!

Example:

 VDPControlPortEnableCRAMWriteAccessGreenColorAtIndex0:
    move.l # $ C0000000, vdp_control_port; Access to color at index 0 in CRAM through the control port
    move.w # 228, d0; Color in D0
    move.w d0, vdp_data_port; Sending color to data port

After building and running in the emulator in Exodus, you should have the screen filled with color 228.

Let’s fill with another color, last byte 127.

 VDPControlPortEnableCRAMWriteAccessGreenColorAtIndex127:
  move.l # $ C07f0000, vdp_control_port; Access to color by byte 127 in CRAM through the control port
  move.w # 69, d0; Color in D0
  move.w d0, vdp_data_port; Sending color to data port

Links

https://gitlab.com/demensdeum/segagenesissamples
https://www.exodusemulator.com/
http://sun.hasenbraten.de/vasm/
https://tomeko.net/online_tools/bin_to_32bit_hex.php?lang= en

Sources

https://namelessalgorithm.com/genesis/blog/genesis/
https://plutiedev.com/vdp-commands
https://huguesjohnson.com/programming/genesis/palettes/ < br />
https://www.chibiakumas.com/68000/helloworld.php# LessonH5
https: / /blog.bigevilcorporation.co.uk/2012/03/09/sega-megadrive-3-awaking-the-beast/

Writing stuff in Assembly for Sega Genesis #1

The first article dedicated to writing games for the classic Sega Genesis console in Motorola 68000 Assembler.

Let’s write the simplest endless loop for Sega. For this we need: an assembler, an emulator with a disassembler, a favorite text editor, a basic understanding of the structure of the Sega rom.

For development, I use my own Gen68KryBaby assembler/disassembler:

https://gitlab.com/demensdeum/gen68krybaby/

The tool is developed in Python 3, for assembly, a file with the extension .asm or .gen68KryBabyDisasm is supplied to the input, the output is a file with the extension .gen68KryBabyAsm.bin, which can be run in the emulator or on a real console (carefully, step away, the console may explode!)

Roms disassembling is also supported, for this you need to put a rom file to the input, without the .asm or .gen68KryBabyDisasm extensions. Opcode support will increase or decrease depending on my interest in the topic, the participation of contributors.

Structure

The Sega rom header occupies the first 512 bytes. It contains information about the game, name, supported peripherals, check sum, and other system flags. I suppose that without a title, the prefix will not even look at the rom, thinking that it is incorrect, like “what are you giving me here?”

After the header comes the Reset subroutine, from which the m68K processor starts its work. Well, it’s just a small matter – to find the opcodes, namely, the execution of nothing (!) And the transition to the subroutine at the address in memory. Googling, you can find the NOP opcode that does nothing and the JSR opcode that performs an unconditional jump to the argument address, that is, it just moves the carriage to where we ask for it, without any whims.

Putting It All Together

One of the games in the Beta version was the donor of the title for the rom, at the moment it is recorded in the form of hex data.

 ROM HEADER:

 00 ff 2b 52 00 00 02 00 00 00 49 90 00 00 49 90 00 00 49 90 00 ... etc. 

The program code so-but is a declaration of the Reset / EntryPoint subroutine in 512 (0x200) bytes, NOP, carriage return to 0x00000200, so we get an infinite loop.

Assembly code of Subroutine Reset / EntryPoint:

 SUBROUTINE_EntryPoint:
    NOP
    NOP
    NOP
    NOP
    NOP
    JSR 0x00000200

Complete example along with rom title:

https://gitlab.com/demensdeum/segagenesissamples/-/blob/main/1InfiniteLoop/1infiniteloop.asm

Next, assembly:

 python3 gen68krybaby.py 1infiniteloop.asm 

Run rom 1infiniteloop.asm.gen68KryBabyAsm.bin in debugger mode of Exodus / Gens emulator, see that m68K correctly reads NOP, and endlessly jumps to EntryPoint at 0x200 on JSR

Sonic should be showing V here, but he left for Wacken .

Links

https://gitlab.com/demensdeum/gen68krybaby/

https://gitlab.com/demensdeum/segagenesissamples

https://www.exodusemulator.com/downloads/release-archive

Sources

ROM Hacking Demo – Genesis and SNES games in 480i < / p>

http://68k.hax.com/

https://www.chibiakumas.com/68000/genesis.php

https://plutiedev.com/rom-header

https: //blog.bigevilcorporation.co.uk/2012/02/28/sega-megadrive-1-getting-started/

https : //opensource.apple.com/source/cctools/cctools-836/as/m68k-opcode.h.auto.html

Flame Steel Engine Runner

I present to your attention Flame Steel Engine Runner – a platform for running multimedia applications based on the Flame Steel Engine toolkit. Supported platforms are Windows, MacOS, Linux, Android, iOS, HTML 5. The focus of application code development has shifted towards scripting – at the moment JavaScript support has been added using TinyJS, the toolkit itself and the engine will continue to be developed in languages ​​close to hardware (C, C ++, Rust, etc.)
Flame Steel Engine Runner Demo
On the page below, you can spin the cube, write JavaScript code, upload models, sounds, music, code using the Upload files button, and start from the main.js file using the Run button.
https://demensdeum.com/demos/FlameSteelEngineRunner/

KleyMoment – glue for script files tool

I present to you a utility for pasting script files – KleyMoment, also a reverse utility for pasting files back. The utility can be used to merge JavaScript files into one.
The tool is implemented in Python 3, has the simplest command line interface of the form:

python3 KleyMoment.py extension Files directory Containing Files output File

For example, recursively gluing js files from the scripts directory to the output.js file

python3 KleyMoment.py js scripts output.js

Also a utility for pasting files back AntiKleyMoment, accepts a glued file as input, for example:

python3 AntiKleyMoment.py output.js

Repository:
https://gitlab.com/demensdeum/kleymoment /

Space Jaguar Action RPG 0.0.4

First Space Jaguar Action RPG prototype for Webassembly:

https://demensdeum.com/demos/SpaceJaguarActionRPG004/

https://demensdeum.com/demos/SpaceJaguarActionRPG004_NOTIMEOUT/

Prepare for long loading (53mb) without any indication.

Space Jaguar Action RPG – space pirate simulator. Features available right now:

  • fly around
  • die
  • eat
  • sleep
  • recruit people
  • look at unstoppable flow of time

Can’t walk in 3D scenes right now, due to bad optimization for web version. It will available in next versions.

Game engine source code, scripts are available under MIT license. All comments and feedback are welcome:

https://gitlab.com/demensdeum/space-jaguar-action-rpg

Linux version screenshots:

How I didn’t hit the guy on the pole or the story of amazing ingenuity

In this post I will write about the importance of architectural decisions in development, application support, in a team development environment.

Self-Operating Napkin – Rube Goldberg

During my youth, I worked on an app for ordering a taxi. In the program, you could choose a pickup point, a drop point, calculate the cost of the trip, the type of tariff, and, in fact, order a taxi. I got the application at the last stage of the pre-launch, after adding several fixes, the application was released in the AppStore. Already at that stage, the whole team understood that it was implemented very poorly, design patterns were not used, all components of the system were tightly connected, in general, it could be written into one large continuous class (God object), nothing would have changed, so how classes mixed their boundaries of responsibility and, in their mass, overlapped each other in a dead cohesion. Later, the management decided to write the application from scratch, using the correct architecture, which was done and the final product was implemented by several dozen B2B clients.

However, I will describe a curious incident from past architecture, from which I sometimes wake up in a cold sweat in the middle of the night, or suddenly remember in the middle of the day and start laughing hysterically. The thing is that I could not hit the guy on the pole the first time, and this brought down most of the application, but first things first.

It was an ordinary working day, one of the customers received a task to slightly modify the application design – it is banal to move a few pixels up the icon in the center of the screen on the pickup address selection screen. Well, having professionally evaluated the task in 10 minutes, I raised the icon 20 pixels up, suspecting nothing at all, I decided to check the taxi order.

What? Does the app no ​​longer show the order button? How did it happen?

I could not believe my eyes, after raising the icon by 20 pixels, the application stopped showing the continue ordering button. Rolling back the change, I saw the button again. Something was wrong here. After spending 20 minutes in the debugger, I got a little tired of unwinding spaghetti from calls to overlapping classes, but I found that * moving the picture really changes the logic of the application *

It was all about the icon in the center – the man on the pole, when he moved the map, he jumped to animate the camera movement, this animation was followed by the disappearance of the button below. Apparently the program thought that the man shifted by 20 pixels was in a jump, so, according to internal logic, it hid the confirmation button.

How can this happen? Does * the state * of the screen depend not on the pattern of the state machine, but on the * representation * of the guy’s position on the pole?

Everything turned out to be so, every time the map was drawn, the application * visually pick * in the middle of the screen and checked what was there, if there was a man on a pole, then this means that the animation of the map shift was over and the button had to be shown. In the case when the man is not there, it means that the map is shifting, and the button must be hidden.

In the example above, everything is fine, firstly, this is an example of the Goldberg Machine (abstruse machines), secondly, an example of the developer’s unwillingness to somehow interact with other developers in the team (try to figure it out without me), thirdly, you can list all the problems by SOLID, patterns (code smell), MVC violation, and more.

Try not to do this, develop in all possible directions, help your colleagues in their work. Happy new year everyone)

Links

https://en.wikipedia.org/wiki/Rube_Goldberg_machine

https://en.wikipedia.org/wiki/SOLID

https://refactoring.guru/refactoring/smells

https://en.wikipedia.org/wiki/Model-view-controller

https://refactoring.guru/design-patterns/state

Guess Band

In this post I will describe how to work with the fasttext text classifier.

Fasttext is a machine learning library for text classification. Let’s try to teach her to identify a metal band by the name of the song. For this, we use supervised learning using a dataset.

Let’s create a dataset of songs with group names:

__label__metallica the house jack built
__label__metallica fuel
__label__metallica escape
__label__black_sabbath gypsy
__label__black_sabbath snowblind
__label__black_sabbath am i going insane
__label__anthrax anthrax
__label__anthrax i'm alive
__label__anthrax antisocial
[etc.] 

Training sample format:

{__label__class} {example from class} 

Let’s train fasttext and save the model:

model = fasttext.train_supervised ("train.txt")
model.save_model ("model.bin")

Let’s load the trained model and ask to identify the group by the song name:

model = fasttext.load_model ("model.bin")
predictResult = model.predict ("Bleed")
print (predictResult) 

As a result, we will get a list of classes that this example looks like, indicating the level of similarity by a number, in our case, the similarity of the Bleed song name to one of the dataset groups.
In order for the fasttext model to be able to work with a dataset that goes beyond the boundaries of the training sample, the autotune mode is used using a validation file (test file). During autotune, fasttext selects the optimal model hyperparameters, validating the result on a sample from the test file. The autotune time is limited by the user independently by passing the autotuneDuration argument.
An example of creating a model using a test file:

model = fasttext.train_supervised ("train.txt", autotuneValidationFile = "test.txt", autotuneDuration = 10000) 

Sources

https://fasttext.cc
https://gosha20777.github.io / tutorial / 2018/04/12 / fasttext-for-windows

Source code

https://gitlab.com/demensdeum/ MachineLearning / – / tree / master / 6bandClassifier