Using TeXStudio with SVGs

I’ve been working on a book for some time using Microsoft Word. Once it got to a few hundred pages, MS Word started to become unusable. I remember some people at work use LaTeX on Windows/Linux. At home, I’m mostly a Mac user. I installed TeXStudio and started to learn the basics.

Soon, I wanted to add images to my document. I found some clues to include SVG files.

\usepackage{svg}

\begin{figure}
\includesvg{./TeX_files/test.svg}
\end{figure}

I was getting errors and warnings when trying to build and view the document. I spent hours trying to find how to get it to work. I found a note, https://latex.ti.bfh.ch/doc_installation/native/osx.html, showing I needed to add a symbolic link. I needed a link from /usr/local/bin/inkscape to the location of my Inkscape install. I followed the directions, but it didn’t work. However, on Mac, applications are typically packages, and the link needs to be to the application inside the package.

sudo su -
ln -s /Applications/Inkscape.app/Contents/MacOS/inkscape /usr/local/bin/inkscape

After getting the link made, I could build a PDF from TeXStudio without even restarting the app…. now I need to learn more about scaling images and tables.

Commander X16 Timing loop in Assembly

With the holiday season on me, I decided it was time to do more Commander X16 programming. I downloaded the latest X16 emulator, release 46, from the project website https://www.commanderx16.com. I’ve wanted to work on a game for a while but realised I needed to experiment with timing. Timing is required to give a game a constant timing feel and help ensure graphics and sound work nicely.

I knew from reading about the old Commodore 64 that it used Jiffies for measuring time. A jiffy is 1/60 of a second. I found a YouTube tutorial https://www.youtube.com/watch?v=kz7cPGulqlM&list=PLPSrOWYluVLIJ1n-TsVb-BESL1tkSTRI_&index=17, which appeared to show to me that it should work. After coding and calling the kernal function, I used the debugger but couldn’t see any values changing in the emulators’ memory. Then I realised I was starting the x16emu without the real-time clock started. Tried a few more times without luck. I started looking at the documentation kernal function clock_get_time more closely, which I should have done earlier. There was a pretty clear note there, jiffies field was unsupported and would always have a value of zero. Seconds, minutes etc should work fine.

I turned to the Commander X16 discord channel and asked a question in the #asm-dev channel. I was not expecting a reply for some time. User MooingLemur had the answer for me in about 2 minutes flat. The solution was to use the old Commodore Kernal function RDTIM that the X16 Kernal had inherited.

A bit more googling, and I quickly had it working. My code wasn’t pretty, but it worked. I wanted to include some feedback to show the clock / show the code running. I now wanted to convert the binary jiffy count into a hexadecimal number and display it. Some more googling and I found an example in a Compute magazine from May 1983 https://www.atarimagazines.com/compute/issue36/060_MACHINE_LANGUAGE.php

I decided to clean up the code and write a quick example of how I got this all working. The example code is available in github here, https://github.com/JustinBaldock/X16-guides/tree/master/2023-12-Timing

I’m trying to have organised code so my timing-demo.asm file includes links to several files.

.include "kernal.inc"
.include "variables.inc"
.include "petsciiCodes.inc"

The kernal.inc is a file declaring kernal functions and variables. The file variables.inc is where I have declared the address of GAME_TIMER and the contents of TEST_MESSAGE_1. Lastly the file petsciiCodes.inc has the hexadecimal values of various Petscii Codes for displaying to the screen.

The main function is pretty simple. I call my wait function which only returns once 1/60 of a second has passed. I then write a message to the screen so I can see something happening. Then it jumps back to the start and repeats the process.

; ----------
; main
; ----------
main:
; this is the main game loop
@gameLoop:
; wait until 1/60 second has passed since last time
jsr waitTimerInterrupt
; once it returns we do our logic

; print a message to screen
jsr testMessage
; jump back to start of main loop
jmp @gameLoop

@end:
; do some end game things
; exit the game
rts

The function waitTimerInterrupt simply uses a kernal function to put the current jiffy into the A register. It compares it to the value in GAME_TIMER and will loop until time has passed. Once the time has changed it updates the value in GAME_TIMER and returns to the main function.

; ----------
; function - wait for timer interrupt
; ----------
; This function uses the variable GAME_TIMER
; The variable GAME_TIMER should be initialized during program start
; Using the function KERNAL_RDTIM and saving reg A into GAME_TIMER
waitTimerInterrupt:
@start:
; none
@loop:
jsr KERNAL_RDTIM
cmp GAME_TIMER ; Compare current jiffy in A to previous jiffy in GAME_TIMER
beq @loop ; If not different then loop
@end:
sta GAME_TIMER ; update our timing variable
rts

The function testMessage is also pretty simple. It will use kernal function to write out a message to the screen, then it calls a function to print the current GAME

; ----------
; display test message
; ----------
testMessage:
@start:
;
@loopStart:
ldx #0
@loopDisplayMessage:
lda TEST_MESSAGE_1,x
beq @loopEnd
jsr KERNAL_CHROUT
inx
bra @loopDisplayMessage
@loopEnd:
; print out the game_timer has hex
jsr printGameTimer
lda #RETURN
jsr KERNAL_CHROUT
ldx #0
rts

The most complex piece of code in this program is the function to print the current GAME_TIMER variable as a hexadecimal number on screen.

; ----------
; function - print game_timer as hex
; ----------
printGameTimer:
lda GAME_TIMER
; logical shift right to get just the high four bits
lsr A
lsr A
lsr A
lsr A
jsr @hexDigit ; process the first digit
lda GAME_TIMER
and #$0F ; use and to mask off the high bits and extract the low four bits
jsr @hexDigit ; process the second digit
rts
@hexDigit:
cmp #$0A ; is digit alphabetic?
bcc @skip ; if 0-9 then skip
adc #$06 ; otherwise add seven
@skip:
adc #$30 ; convert to petscii
jsr KERNAL_CHROUT ; print it out
rts

I hope this post is useful to other people learning to program the Commander X16 in 6502 assembly.

Disassembling Spy Hunter Part 2

The exploration has continued. I started to explore the functions. Trying to figure out what was happening I spent more time looking at the C64 memory map. I was able to find three functions which were being called by the Interrupt. I could see functions saving values to the SID and VIC 2 registers. Others were saving values to Zero Page and others were writting values in other spots of memory. All of these addresses were outside of the cartridge image. This is a 16k cartridge, $8000-$BFFF. I needed to find some way of adding in extra memory addressess, eg $D000-$D3FE.

Finding the ‘Display Memory Map’ window was very useful. This allowed me to add in extra memory ranges. I added in all the known memory ranges that I thought would be useful; VIC2, SID, CIA#1, CIA#2, Hardware Vectors. It also appeared that the program was saving some variables around $4D00-$4DFE.

Ghidra Memory Map Window

Ghidra has a useful feature were it displays references which access memory addresses. It is very use to see which functions were writing or reading an address.

VIC2 memory registers

Progress then started to stall. I was trying to find the games sprites and text characters without luck. Only two of the VIC2 sprite registers were being accessed. That didn’t seem correct. I was expecting game data to be copied from the ROM over in to ram where the VIC2 could then access it. But nothing in the ROM looked what I expected.

I changed tac and decided I needed to do some dynamic reverse engineering. I found and downloaded Infiltrator 1.0. I couldn’t use infiltrator directly with the cartridge file. I loaded up the game in VICE and took a snapshot. I was then able to load the snapshot in Infiltrator and use the sprite tool. Very quickly I found the cars.

Infiltrator Spy Hunter Sprites

Clearly the sprites start at $5400. However using Ghidra I couldn’t find a function that was writing to that memory address. I kept on exploring in Infiltrator and then found the location of the screen memory and the main char set.

Infiltrator Spy Hunter Screen and Charset

Finding this vexed me. In Ghidra I couldn’t find the function which was writing the data to screen memory $7800-$7BE7 or the charset to $7000-$77FF. There has to be code someplace doing this!

Looking on youtube I saw a video presented by Shallan, “Lets Dissect a Commodore 64 Game! – Episode 1 – Thrust” where he was using a tool called C64 Debugger v0.64.2. I went and found it and installed it. Starting to use this piece of software I could watch and the game play see memory being accessed and written to. I could clearly see the SID being used to create the music. I could see sprites X and Y being changed.

C64 Debugger Spy Hunter Sound and Sprites

While watching the game play out I saw code / functions flashing by my eyes. Something then popped out to me. I could catch moments of code executing that where not in my cartridge range $8000-$BFFF.

C64 Debugger Spy Hunter Executing

There is code running down in $1E95 which appears to be moving tile data in memory. Data is being read in from around $7DF5 down to $7A1D. It looks like all the data is being offset back $3D8, 984 bytes.

Clearly I have a lot more work to go in figuring this out. I am starting to think I’ve actually picked a rather difficult starting game.

Disassembling Spy Hunter Part 1

I have been wanting to learn programming assembly on the Commodore 64 for some time. I want to have a go at writing my own scrolling shooting action space game. I thought I might be able to learn by pulling something apart. I found a few C64 games had been reverse engineered. So I looked at a range of classic games. I found the 1983 game Spy Hunter and I thought it might be an excellent place to start.

Spy Hunter is an arcade game from 1983 developed by Bally Midway. Check out the Wikipedia article for details. I remember playing the Commodore 64 version for hours as a child. It was fast, slick, and one of the early games on the platform. Being one of the earlier games on the platform, I’m hoping there aren’t any of the funky programming tricks used.

The game is not large. In fact, only 16 Kb in size. I decided that the cartridge version of the game might be the way to go. It was less likely to have any copy protection software tricks being a cartridge. The CRT cartridge image format is best defined by the VICE emulator help. I found a site where I could download the CRT image file. 

I have been meaning to become more familiar with Ghidra. It is an open-source reverse engineering tool created by the NSA. I had read someplace it supported all sorts of CPUs and languages. I wasn’t disappointed.

I downloaded and installed Ghida and a Java JRE for my Mac and started to have a play. I created a new project. I had to figure out how to add my CRT file. From the file menu, I selected ‘Import File’ and loaded the Spy Hunter CRT file. I used the ‘Raw Binary’ format and selected ‘6502’ for language. When I opened the file, it started the addressing from 0x0000, which I didn’t think was correct. I did some searching and found a good article on how the cartridges work. The base address of the software appeared to be 0x8000. Clicking on ‘Options’ I was able to change the base address. The only problem was the entire raw file was imported, all of the CRT rom file data as well. This wasn’t useful since everything was off, which is very important with assembly. Instead of trimming the CRT I looked at the data and worked out the starting address I needed. I selected the base address $7FB0.

Ghidra wanted to display text in ASCII and I could see some strings. However I knew text would actually be encoded as PETSCII. I needed to work out how to create my own data type. I then learned I could create an enum data type in the data type manager. I then entered in most of the PETSCII codes. I could then select data and assign it the PETSCII data type which then displayed the strings. I was then able to find the ‘CBM80’ cartridge signature at $8004 to $8008 as expected.

Now time to start disassembling this file. $8000 is a pointer to the start of the program, 27 80, being little endian the address is actually $8027. Going to $8027 I selected the byte, right clicked and selected ‘disassemble’. Things started to appear, variables, functions and labelled started to appear. I then started to look at memory locations being read to and writen to. These I was able to lookup in the C64 memory map. Knowing which control registers were being adjusted I could start to work out what was happening.

I ended up getting rather involved and before I knew it several hours had passed. I had not really decoded much at all but I enjoyed the process. I completely forgot to worry about version control or anything. The following night I started to write this blog post and I setup github repo. I’m hoping to have some fun and for others to learn from what I’ve managed.

Porting Akalabeth to Commander X16

Recently I decided I was going to try and port the old game Akalabeth: World of Doom (1979) by Richard Garriott to the Commander X16.

It took some time for me to realise that the basic code lines in the program were rather long. Much longer than the 80 characters allowed in Commodore Basic. It appears that Applesoft BASIC (a port of Microsoft BASIC) had a line character limit of 238 characters! Much large then the X16 or C64. This created a problems as I had to split IF…THEN statements from one line to three or four. This used up extra bytes and introduced several bugs.

Applesoft had a few extra statements which X16 Basic doesn’t have. Some of the graphical drawing commands work differently as well. I added plenty of REM statements and character spacing soI could see what was happening.

After much adjusting, I had converted all of the HPLOT commands to LINE or PSET. When I tried to load it into the X16 emulator, I started to see a lot of “?OUT OF MEMORY ERROR” errors on the screen. This confused me… Akalabeth was initially designed on an Apple II+, which had a maximum of 64k memory; machines often had 48k.

I checked the file I had created, it was 50,952 bytes. Well outside the BASIC memory space of 38,653. I then compared it to the source material file, which was only 36,141 bytes. I had added a lot of formatting to space out the code, I had split long lines into smaller ones, I had added extra character to the line numbers so I had extra room to move. Each of these little changes added extra bytes. Bytes I didn’t notice until the file was rather large.

AppleSoft has a function called VTAB, which lets the programmer send the cursor to a particular line. With some help from the X16 forum, I was able to create a little helper function. This would poke the desired line number into memory. Then it would call the Kernal function PLOT.

62000 REM FUNCTION VTAB
62010 POKE $030D,VTAB
62020 SYS $FFF0
62030 RETURN

I used Notepad++ and the Github desktop client. I would write a bit, run it in the X16 R38 emulator and commit the code change in Github. I ended up with over 60 commits while I worked on this.

Overall the process took me two weeks, doing a bit here and there. Mostly fixing bugs which I had introduced by having to split large lines. The last few days were mostly about cosmetics. I added some status information to the top of the screen. Then I started to add some colour to the line drawings. i.e. Making the skeleton’s eyes red. Making the rat brown with yellow eyes, etc.

Overall it was a nice little challenge. The end result left about 124 bytes of Basic memory free. I know it would be optimised more by removing comments etc but I don’t want to affect readability. I hope other people can look at the code and find it useful. I have put all of the code up on GitHub and on the Commander X16 site.

Commander X16 website https://www.commanderx16.com/forum/index.php?/files/file/217-akalabeth/

Github
https://github.com/JustinBaldock/X16-Akalabeth/

VMware Player error on Linux

Recently I decided I needed to spend more time on Linux. I am using a Dell Latitude 7480 with 16GB RAM and a 500GB SSD. I installed Linux then I tried to install the latest version of VMware player 16.0.2.

VMware Player Installing

The installation would say it was “successful”, but there would be a bunch of errors.

VMware installation errors

When I started VMware Player, it behaved as expected—prompting for licence agreements etc.

VMware Player Licence Agreements

I created a virtual machine and tried to start it. I then received the following error. “Could not open /dev/-vmmon: No such file or directory. Please make sure that the kernel module ‘vmmon’ is loaded.”

This error would make me curse for hours! I followed various guides telling me to install different packages, gcc, essentials, etc. Then, I saw posts telling me I was using the wrong Linux. Initially, I had installed Ubuntu 21.04. Instead I tried Ubuntu 20.04 LTS, with similar results. It appeared something was wrong with VMware and the Kernal.

After much testing without success, I managed to get lucky. I was in the laptop UEFI/BIOS settings and thought to change “Secure Boot -> Secure Boot Enable” and set it to “Disabled” I was grasping at straws. However, after rebooting, I could now start virtual machines without error! VMware Player is currently working for me. I hope other people who experience this error find this blog post before burning too much time.

Problems with my AnyCubic 3D Printer

Earlier in the year, my AnyCubic Kossle Linear Plus failed. The LCD would power up, but the display would be blank. I also could not access it via USB. Thinking it was the Trigorilla logic board that had failed, I ordered a new board. Once it arrived, I had the same problem.

I then made a rookie mistake. I checked the power supply and found that it displayed 28v instead of 12v. I then spent some time troubleshooting my power supply. It was only when talking with my father that I triple checked it with him looking over my should. He pointed out that when measuring for 12 DC, I should have my multimeter sent to DC instead of AC. It was embarrassing but a good reminder. When you see strange results, double-check your tools and techniques.

Knowing my power supply was good, I just needed to check why I couldn’t access the control boards via USB. I assumed the firmware had become corrupted or blank or something similarly strange was going on. I spend hours searching/googling and reading on the internet without any luck.

Checking out the Trigorilla, I could see what appeared to be an ISP connector, and the documentation confirmed it. I have a little USB ISP Programmer from Jay Car. https://www.jaycar.com.au/isp-programmer-for-arduino-and-avr/p/XC4627, and I thought it was time to start playing with it.

XC4627 – ISP Programmer for Arduino and AVR

Usually, I would use my Mac, but I needed Windows because of the range of tools to work with the logic boards. Also, all the forums and blogs people were using either Windows or Linux. I was using the software AVRDUDES from https://blog.zakkemble.net/avrdudess-a-gui-for-avrdude/, in particular, the portable executable https://blog.zakkemble.net/download/AVRDUDESS-2.13-portable.zip

I haven’t used the original AnyCubic Kossel firmware in years. I have switched to the Marlin 2.0 firmware. Still being a relative 3d printer newbie, I did not roll my own. I followed the instructions created by Lukas Pomykal on his website, https://www.lpomykal.cz/kossel-marlin-firmware/ . This made a file “Marlin.ini.with_bootloader.mega.hex”. This hex file is the firmware I would be uploading to the printer.

Using the USB ISP programmer was a time sink. I had compiled the firmware using Arduino IDE, and I had a hex file ready. Every time I tried to upload, I would get a cryptic error and warning messages from avrdude. “Warning. Cannot set sck period. Please check for usbasp firmware update” or “Verification failure, first mismatch at byte 0x0000 0x08 != 0x0C”

avrdudess verification error

I thought I had the latest firmware on the USB ISP but decided to make sure. I have a copy of the device created by Thomas Fischl, https://www.fischl.de/usbasp/ . I downloaded the newest firmware and went searching for how to perform the update. I used my Arduino Uno with the ‘ArduinoISP’ sketch. 

Once the update completed successfully, I tried to do the firmware update again, with the same result, “Verification failure”.

I then decided to ignore the USB ISP and use my Arduino with the ISP sketch. I selected programmer = ‘Atmel AVR ISP’, Port (-P) = ‘COM4’, Baud rate (-b) = ‘19200’, selected the Marlin.ini.with_bootloader.mega.hex file. I connected the 6 pins as per the below table.

Arduino UnoISPTrigorilla
D13SCK3
D12MISO1
D11MOSI4
D10RESET5
+5vVCC2
GNDGND6
Wiring connections

Then I held my breath and hit the ‘Program’ button. Success! “261406 bytes of flash verified”

Feeling victorious, I returned the Trigorilla board to the 3d printer and re-wired everything. The LCD screen appeared precisely as it was supposed to!

Success … ?

I made the mistake of getting too excited. I knew I needed to recalibrate the printer and started the process. I attached the levelling probe and found my troubles were not over. The printer head began to move in odd ways, up toward the printer’s top instead of down towards the print bed.

The printers behaviour perplexed me for over a day. I was chatting with my son, and I remembered that the Kossel has two different probe options! I reopened the firmware source and found the section about test probes. I followed the instructions and referenced the images and found that, indeed, the firmware was configured with a different probe than what I had. I made the change, then recompiled the firmware and re-flashed it.

Finally, after way too long, my printer was working again and, at the moment, appears to be working 100%. I’ve published this hoping that other people find it helpful with troubleshooting their Kossel/AnyCubic printer.

Commodore SD2IEC

When using a SD2IEC and a 1541 floppy drive together it is possible to have a device id conflict. The SD2IEC defaults to device#8. The 1541 floppy drive defaults to device#8 as well.

To change the device id on the SD2IEC, power on the C64 but not the 1541. Then open a connection to the SD2IEC

OPEN 15,8,15

Then send a command to change the device controller ID.

PRINT#15,”U0>”+CHR$(9)

The SD2IEC should now be using ID 9. To test, load the directory.

LOAD”$”,9

Now power on the 1541 floppy drive. It should startup and work as device#8 as normal.

LOAD”$”,8

Commodore 1541 Floppy drive commands

Getting back in to playing with my old Commodore 64 and 1541 floppy drive. I had to relearn how to use the floppy drive. Just a simple task such as formatting a floppy disk took me a little while to find the commands. So to make it easier for myself I thought I would list a bunch of the commands that I would be using now in the future.

Format a disk (NEW)
OPEN 1,8,15,"N0:Diskname,ID": CLOSE 1
or
OPEN 1,8,15: PRINT#1,"N0:Diskname,ID": CLOSE 1
The disk name has a maximum of 16 chars and the ID requires 2 chars.

Initialize drive (INITIALIZE)
e.g. to detect a disk change
OPEN 1,8,15,"I0":CLOSE 1

Validate a disk (VALIDATE)
Checks and fixes the disk’s meta-data structures (directory, block availability map, etc.)
OPEN 1,8,15,"V0": CLOSE 1

Copy files (COPY)
OPEN 1,8,15,"C0:NewFile=OldFile": CLOSE 1

Copy disk (COPY)
OPEN 1,8,15,"C0=C1": CLOSE 1
Copy the whole disk on a double drive from drive 1 to drive 0.

Concatenate files (COMBINE)
OPEN 1,8,15,"C0:NewFile=OldFile1,OldFile2,...": CLOSE 1
The command string is limited to 40 chars in length!

Rename a file (RENAME)
OPEN 1,8,15,"R0:New_Name=Old_Name":CLOSE 1
The command string is limited to 40 chars in length!

Delete a file (SCRATCH)
OPEN 1,8,15,"S0:filename": CLOSE 1
Wildcards such as * (matches all the remaining chars) or ? (matches one char) are supported.For example: OPEN 1,8,15,"S0:*":CLOSE 1 all files of a disk will be deleted (“scratched”).With comma (,) more than one file or wildcard mask can be given and multiple matching files actually could be subject of the deletion.

Overwrite a file (REPLACE)
SAVE"@0:filename",8
or
OPEN 1,8,15,"@0:filename,S,W": CLOSE 1.
The REPLACE command is especially prone to triggering the above mentioned bug on the original 1541 (fixed in the 1541C and the 1541-II) – it may fail with some regularity and one could lose all data on a disk. Unless the user knows for certain that the drive in question will not be an original 1541, the better way is to first to use SCRATCH and after that the BASIC command SAVE.

Commander X16 BASIC Tiles

I continue to learn more about the Commander X16 retro platform and programming in BASIC. I want to make games for the platform, so I needed to come to grips with how VERA handles tiles.

Currently, I’m using VMWare Fusion on my Mac with a Windows 10 VM for doing my retro development. I’m using X16 emulator R38 ,NotePad++ ,Tiled ,HxD ,TexturePacker ,MOSpeed and Vera Graphics Converter.

I started with a few false starts, and then I found a tile tutorial on 8-bit coding, which started me off. However, I needed something more. I was struggling with several different things, workflow and debugging how to get the tile graphics into the system and look ok, how to edit tilemaps and get that data into the X16. What is happening in VERA memory? Argg, their program works why doesn’t mine. So, now I have worked some things out I decided I should share what I learnt. 

I started by finding a nice 256 colour tileset, and I created what I thought was a basic 64 x 64 tilemap in Tiled. I then spent time learning how to export data out of Tiled as BASIC DATA statements. At this point I realised maybe I had made a mistake, just the data statements for the graphics and map were almost 30k. Also, I wasn’t having much luck with displaying anything. I was getting graphic snow/static. I just couldn’t see into VERA to work out what was happening. I spent time looking at the emulator debugger documentation, and I just couldn’t see what I needed. I had a look at the debugger.c code out of curiosity and found CMD_DUMP_VERA='v'
This was it! This lets me view VERA memory. Start the X16 emulator with the -debug switch.
C:\x16emu_win-r38>x16emu.exe -bas TUTORIAL-TILES.BAS -debug
Then activate the debugger by pressing F12. Once in the debugger press v and type the memory address in VERA to view. Awesome. 

X16 Emulator started with -debug and viewing VERA memory at $4000.

I still wasn’t having much luck. I stumbled upon a forum post which reminded me about the VLOAD command. I hadn’t looked at it before since at the time the documentation just listed TODO. A good reminder that the X16 team were working faster on the code then the documentation. I had some problems using VLOAD with data that crossed from Bank 0 to Bank 1. So I just made sure my data fit in either Bank 0 or Bank 1. 

For this tutorial, I am trying something more significant than my initial successful program. In Tiled I created a 256 x 32 tiled map of 16×16 tiles. Giving a scroll area of 4096 x 512, suitable for a side scroller like Mario. With the X16 in 320×240 mode, this would provide close to 26 screens worth of map for a level. I created an elementary map. I then used Johan Kårlin tool for tiled, which let me export the map data. The map data takes up just over 16k. I used a subset of a graphic tileset from Open Game Art. I used what I thought was a small sample, which ended up being 416 tiles. I then used VERA Graphics Converter to turn the png file into 16×16 tiles at 4 bit per pixel and exported the binary data file, which was 53kb! Clearly, when I do create a game, I will have to make sure I only included used tiles.

Tiled – Clearly, I need to develop my level creation skills.

Looking at VERA and its registers and memory, we can see that VERA can handle two layers. By default, it uses layer 1 for text. I was thinking of using layer 1 for a HUD/score/user information etc. So we will enable layer 0 and put the tiles there. But how to handle that? VERA has 128kb of memory, and my tile graphics were going to take 52kb, and the map was going to take 16kb. 

AddressNameBit 7 – BIT 6 – bit 5 – Bit 4 – Bit 3 – Bit 2 – Bit 1 – Bit 0
$9F29DC_VIDEO (DCSEL=0)Current Field (Bit 7) Sprites Enable (Bit 6) Layer1 Enable (Bit 5) Layer0 Enable (Bit 4) Unused (Bit 3) Chroma Disable (Bit 2) Output Mode (Bit 1-0)
$9F2DL0_CONFIGMap Height (Bit 7-6) Map Width (Bit 5-4) T256C (Bit 3) Bitmap Mode (Bit 2) Color Depth (Bit 1-0)
$9F2EL0_MAPBASEMap Base Address Bits 16-9 (Bit 7-0)
$9F2FL0_TILEBASETile Base Address Bit 16-11 (Bit 7-2) Tile Height (Bit 1) Tile Width (Bit 0)
$9F30L0_HSCROLL_LH-Scroll Bits 7-0 (Bit 7-0)
$9F31L0_HSCROLL_HUnused (Bit 7-4) H-Scroll Bits 11-8 (Bit 3-0)
$9F32L0_VSCROLL_LV-Scroll Bits 7-0 (Bit 7-0)
$9F33L0_VSCROLL_HUnused (Bit 7-4) V-Scroll Bits 11-8 (Bit 3-0)
$9F34L1_CONFIGMap Height (Bit 7-6) Map Width (Bit 5-4) T256C (Bit 3) Bitmap Mode (Bit 2) Color Depth (Bit 1-0)
$9F35L1_MAPBASEMap Base Address Bits 16-9 (Bit 7-0)
$9F36L1_TILEBASETile Base Address Bit 16-11 (Bit 7-2) Tile Height (Bit 1) Tile Width (Bit 0)
$9F37L1_HSCROLL_LH-Scroll Bits 7-0 (Bit 7-0)
$9F38L1_HSCROLL_HUnused (Bit 7-4) H-Scroll Bits 11-8 (Bit 3-0)
$9F39L1_VSCROLL_LV-Scroll Bits 7-0 (Bit 7-0)
$9F3AL1_VSCROLL_HUnused (Bit 7-4) V-Scroll Bits 11-8 (Bit 3-0)
Subset of VERA Registers for Layer 0 and 1

I will start the structure of this program with a simple main program and a number of subroutines which perform tasks. The first task is setting up the SCREEN in 320×240 mode.

Now we will need to enable layer 0. Doing so is relatively straight forward. We simply poke the right bit of memory. Looking at the table above we can see to enable layer 0 we just need to set bit 4 of $9F29 to be 1. I like to use binary when POKEing value so I set exactly the right bits. I want both layer 0 and 1 and enabled and the default output mode. For this, I will POKE $9F29, %00110001.

Now we have to do several pokes to configure Layer 0 in VERA. $9F2D is fairly straight forward. We will ignore T256C and Bitmap mode. We only have two bits for height and two bits for width. A binary value needs to be set.

decimalBinaryHeight / Width
00032 tiles
10164 tiles
210128 tiles
311256 tiles
VERA Layer Height and Width options

The last two bits in $9F2D are color depth. This value changes how VERA expects the colour data to be encoded. 8-Bit Coding has a tutorial which goes into more depth.

Color Depth valueDescription
01 bpp
12 bpp
24 bpp
38 bpp
VERA Layer Color Depth options

The next register took a little bit for me to understand. $9F2E. Initial I had thought it just took a 16-bit address for VERA memory and remove the eight least significate bits. But that didn’t work. It wasn’t until I started to think a bit more. 16-bit address only allows 64k. VERA has 128k of memory. To cover all 128k of memory the binary range is 0 0000 0000 0000 0000 – 1 1111 1111 1111 1111. The 17-bit is selecting which 64k bank is being used, bank 0 or bank 1. So this register actually needs the high 8-bits from a 17bit address. I found the Windows Calculator very handy for this. The example here is setting the tilemap base at $4000 in VERA. $4000 in binary is 0100 0000 0000 0000. If I poke 0100 0000 into the VERA register, it will not work correctly. If I change it so it is a 17bit address 0 0100 0000 0000 0000 and then I take the high 8-bits, I poke in 0010 0000 VERA should work correctly.

Windows Calculator in Programmer mode.

Once I understood the addressing issue, I found working with $9F2F easier. Instead of having the high 8-bits of the tile graphic location, it takes the high 6-bits. The last two bits set the height and width of the tiles. The height and width can be 8 or 16 pixels. Giving us a total of four different tile sizes; 8×8, 8×16, 16×8, 16×16. The example here is setting the tile graphics base at $10000 in VERA with 16×16 tiles. The 17-bit address is 1 0000 0000 0000 0000. I take the high 6-bits from the address. The tiles will be 16 x 16, so the height and width bits will be both be 1. So I poke in the binary value 1000 00 11.

Binary valueTile height / width
08 pixels
116 pixels
VERA Tile dimensions

If we started the program with what we have done at the moment, we would not see anything. Only the default blue background, the white text of layer 1 will be visible. VERA handles color 0 as transparent. Color 0 is normally black. We will use the COLOR command to set the foreground color to white (1) and background color to black (0). Then we will clear the screen using CLS and PRINT some instructions. That will be the end of the first subroutine, so we can then RETURN to the main program.

So far the code looks like this;
100 GOSUB 10000: REM SETUP DISPLAY
110 END
10000 REM SETUP DISPLAY
10010 SCREEN $00: REM SETUP SCREEN MODE 320X240
10020 REM CONFIGURE LAYER 0 AND DISPLAY TILES
10030 POKE $9F29, %00110001: REM TURN ON LAYER 0,1 AND VGA OUTPUT
10040 POKE $9F2D, %00110010: REM MAP 32 X 256, T256C, BITMAP MODE, COLOR DEPTH
10050 POKE $9F2E, %00100000: REM MAP BASE AT $4000
10060 POKE $9F2F, %10000011: REM SET TILE BASE AT $10000 AND H=16 W=16
10070 REM CONFIGURE LAYER 1 AND DISPLAY INSTRUCTIONS
10080 COLOR 1,0
10090 CLS
10100 PRINT "MOVE VIEW USING WASD. Q TO QUIT"
10110 RETURN

Now I need to load the tilemap data and tile graphic data straight into VERAs memory. We will use the VLOAD command. Now currently there isn’t any documentation for this, and I think there might be a bug in it as well. The data loaded should either fit entirely in bank 0 or bank 1 of VERA. If I try and load a large block of data starting in bank 0 and expecting it to continue into bank 1, I have a problem. I will investigate further, but I think VLOAD works with this syntax;
VLOAD "filename",device,<VERA memory bank>, <VERA memory address>
For this example, I have two files. TILEMAP-256X32.BIN and TILE-GFX.BIN. I then use sub-routines to load each of the files into VERA. The tilemap base is at $4000 in bank 0, so the command should look like VLOAD "TILEMAP-256X32.BIN",0,$4000. The tile graphic data is at $10000, so address $0000 in bank 1. The command will look like VLOAD "TILE-GFX.BIN",1,$0000

So far the code looks like this;
100 GOSUB 10000: REM SETUP DISPLAY
110 GOSUB 20000: REM SETUP TILE MAP
120 GOSUB 30000: REM SETUP TILE GRAPHICS
130 END

10000 REM SETUP DISPLAY
10010 SCREEN $00: REM SETUP SCREEN MODE 320X240
10020 REM CONFIGURE LAYER 0 AND DISPLAY TILES
10030 POKE $9F29, %00110001: REM TURN ON LAYER 0,1 AND VGA OUTPUT
10040 POKE $9F2D, %00110010: REM MAP 32 X 256, T256C, BITMAP MODE, COLOR DEPTH
10050 POKE $9F2E, %00100000: REM MAP BASE AT $4000
10060 POKE $9F2F, %10000011: REM SET TILE BASE AT $10000 AND H=16 W=16
10070 REM CONFIGURE LAYER 1 AND DISPLAY INSTRUCTIONS
10080 COLOR 1,0
10090 CLS
10100 PRINT "MOVE VIEW USING WASD. Q TO QUIT"
10110 RETURN

20000 REM SETUP TILE MAP
20010 VLOAD "TILEMAP-256X32.BIN",8,0,$4000
20020 RETURN

30000 REM SETUP TILE GRAPHICS
30020 VLOAD "TILE-GFX.BIN",8,1,$0000
30030 RETURN

To see how it is going I copied the two data files and the BASIC file into the X16 emulator directory and ran;
C:\x16emu_win-r38>x16emu.exe -bas TUTORIAL-TILES.BAS -debug
To see how it appeared…. and success!

Success – Tilemap and graphic data loaded and displayed.

Now I want the program to take keyboard input and move the view around so we can explore the entire map. The maximum layer area that VERA can handle is 4096 pixels, starting at 0 and going to 4095. However, we can only poke up to a value of 255! 0 to 4095 is a 12-bit address, 0000 0000 0000 to 1111 1111 1111. When we look at the VERA registers, we see that the horizontal scroll is $9F30 for the low 8-bits and $9F31 for the high 4-bits. Unlike assembly, you just can’t grab the high, or low 8-bits using < or > and manipulate data as easily. (I would like to be wrong here so if you know otherwise please leave a comment). So we need to create a few variables to handle data. I’m going to make two variables to keep track of the tile horizontal and vertical location, TH and TV. Then to convert those numbers into values, these we can poke into VERA. I will create HL and HH for the horizontal low and high values. As well as a VL and VH variable for vertical low and high values. I will also create a variable to store the movement speed, MV.

I will create another subroutine to handle moving the screen view around the layer. Then I will GET the keyboard input and store it in variable K$. Inside the loop, it will check which key was pressed and call a subroutine to move the view either left/right/up/down. Then it will loop back to GET the keyboard input again.

So far the code looks like this;
100 GOSUB 10000: REM SETUP DISPLAY
110 GOSUB 20000: REM SETUP TILE MAP
120 GOSUB 30000: REM SETUP TILE GRAPHICS
130 GOSUB 1000: REM THE MAIN LOOP
140 END

1000 REM MAIN LOOP
1010 LET TH=0: TV=0: REM TILE HORIZONTAL AND VERTICAL LOCATION 0-4095
1020 LET HH=0: HL=0: VH=0: VL=0: REM HIGH AND LOW VALUES FOR HOR AND VER
1030 LET MV=2: REM SET DEFAULT MOVEMENT SPEED
1040 GET K$: REM READ IN KEYPRESSES
1050 IF K$="A" THEN GOSUB 1100: REM MOVE LEFT
1060 IF K$="D" THEN GOSUB 1200: REM MOVE RIGHT
1070 IF K$="W" THEN GOSUB 1300: REM MOVE UP
1080 IF K$="S" THEN GOSUB 1400: REM MOVE DOWN
1090 IF K$="Q" THEN RETURN: REM EXIT SUBROUTINE
1095 GOTO 1040: REM LOOP BACK TO GET KEYBOARD INPUT

We create a subroutine for each of the movements. The program will also check bounds. When moving left, we should not have a value of less than 0. When moving to the right, we have to adjust a little. The screen view is 320 pixels wide. We don’t want to move the screen view all the way to 4095; otherwise, the layer will wrap around, and we will be looking at layer pixels 0-319. So we limit the movement to 3776, which is layer width (4096) – screen view width (320). When moving up, we should not have a value of less than 0. When moving down, we have to adjust a little again. The screen view is 240 pixels high. We have a layer vertical size of 512, so we will limit movement to 272, which is layer height (512) – screen view height (240). We then call the subroutine for calculating the values which will be POKEd into VERA. Then call the subroutine for updating VERA.

1100 REM MOVE VIEW LEFT
1110 IF TH = 0 THEN RETURN
1120 TH=TH-MV
1130 GOSUB 1700: REM CALCULATE 8BIT
1140 GOSUB 1900: REM UPDATE SCROLL
1150 RETURN

1200 REM MOVE VIEW RIGHT
1210 IF TH = 3776 THEN RETURN: REM LAYER WIDTH - SCREEN VIEW WIDTH
1220 TH=TH+MV
1230 GOSUB 1700: REM CALCULATE 8BIT
1240 GOSUB 1900: REM UPDATE SCROLL
1250 RETURN

1300 REM MOVE UP
1310 IF TV = 0 THEN RETURN
1320 TV=TV-MV
1330 GOSUB 1800: REM CALCULATE 8BIT
1340 GOSUB 1900: REM UPDATE SCROLL
1350 RETURN

1400 REM MOVE DOWN
1410 IF TV = 272 THEN RETURN: REM 512-240
1420 TV=TV+MV
1430 GOSUB 1800: REM CALCULATE 8BIT
1440 GOSUB 1900: REM UPDATE SCROLL
1450 RETURN

Now we need to calculate the 8-bit values which will get POKEd into VERA. The X16 handles numbers in 8-bit chunks, 0-255. VERA allows scroll values from 0 to 4095, 0000 0000 0000 – 1111 1111 1111. VERA has $9F30 for the low 8 bits and $9F31 for the hight 4-bits. We think of this process as some basic division maths. The 4-bit high value is the horizontal location divided by 255, and the 8-bit low value is the remainder of that division. We have to so a few steps. I use the HH variable to store the horizontal high value, which is the INTeger result of TH (Tile Horizontal location) divided by 255. By using the INT function, we only get the quotient and no remainder (float value, decimal numbers) The HL variable stores the result of the TH – number of times 255 went into it, giving me an integer less than 255. We do the process again for the vertical. Once each of these sub-routines has completed return to the code which called them.

1700 REM CALCULATE HORITZONAL HIGH AND LOW VALUES TO POKE IN TO LAYER SCROLL
1710 HH = INT(TH / 255)
1720 HL = TH - (HH * 255)
1730 RETURN

1800 REM CALCULATE VERTICAL HIGH AND LOW VALUES TO POKE IN TO LAYER SCROLL
1810 VH = INT(TV / 255)
1820 VL = TV - (VH * 255)
1830 RETURN

Finally the subroutine for updating VERA. We just POKE the horizontal and vertical values into the VERA scroll registers for layer 0.

1900 REM UPDATE VERA FOR NEW LAYER SCROLL
1910 POKE $9F30,HL
1920 POKE $9F31,HH
1930 POKE $9F32,VL
1940 POKE $9F33,VH
1950 RETURN

With my BASIC code, I’ve tried to use as many comments as possible. I’m also using empty lines to help break up my code. I’m sure my code is not efficient or as fast as it could be. All the code, Tiled map file, binary and graphics are available from the Github repo.

So now the completed code looks like this;
100 GOSUB 10000: REM SETUP DISPLAY
110 GOSUB 20000: REM SETUP TILE MAP
120 GOSUB 30000: REM SETUP TILE GRAPHICS
130 GOSUB 1000: REM THE MAIN LOOP
140 END

1000 REM MAIN LOOP
1010 LET TH=0: TV=0: REM TILE HORIZONTAL AND VERTICAL LOCATION 0-4095
1020 LET HH=0: HL=0: VH=0: VL=0: REM HIGH AND LOW VALUES FOR HOR AND VER
1030 LET MV=2: REM SET DEFAULT MOVEMENT SPEED
1040 GET K$: REM READ IN KEYPRESSES
1050 IF K$="A" THEN GOSUB 1100: REM MOVE LEFT
1060 IF K$="D" THEN GOSUB 1200: REM MOVE RIGHT
1070 IF K$="W" THEN GOSUB 1300: REM MOVE UP
1080 IF K$="S" THEN GOSUB 1400: REM MOVE DOWN
1090 IF K$="Q" THEN RETURN: REM EXIT SUBROUTINE
1095 GOTO 1040: REM LOOP BACK TO GET KEYBOARD INPUT

1100 REM MOVE VIEW LEFT
1110 IF TH = 0 THEN RETURN
1120 TH=TH-MV
1130 GOSUB 1700: REM CALCULATE 8BIT
1140 GOSUB 1900: REM UPDATE SCROLL
1150 RETURN

1200 REM MOVE VIEW RIGHT
1210 IF TH = 3776 THEN RETURN: REM LAYER WIDTH - SCREEN VIEW WIDTH
1220 TH=TH+MV
1230 GOSUB 1700: REM CALCULATE 8BIT
1240 GOSUB 1900: REM UPDATE SCROLL
1250 RETURN

1300 REM MOVE UP
1310 IF TV = 0 THEN RETURN
1320 TV=TV-MV
1330 GOSUB 1800: REM CALCULATE 8BIT
1340 GOSUB 1900: REM UPDATE SCROLL
1350 RETURN

1400 REM MOVE DOWN
1410 IF TV = 272 THEN RETURN: REM 512-240
1420 TV=TV+MV
1430 GOSUB 1800: REM CALCULATE 8BIT
1440 GOSUB 1900: REM UPDATE SCROLL
1450 RETURN

1700 REM CALCULATE HORITZONAL HIGH AND LOW VALUES TO POKE IN TO LAYER SCROLL
1710 HH = INT(TH / 255)
1720 HL = TH - (HH * 255)
1730 RETURN

1800 REM CALCULATE VERTICAL HIGH AND LOW VALUES TO POKE IN TO LAYER SCROLL
1810 VH = INT(TV / 255)
1820 VL = TV - (VH * 255)
1830 RETURN

1900 REM UPDATE VERA FOR NEW LAYER SCROLL
1910 POKE $9F30,HL
1920 POKE $9F31,HH
1930 POKE $9F32,VL
1940 POKE $9F33,VH
1950 RETURN

10000 REM SETUP DISPLAY
10010 SCREEN $00: REM SETUP SCREEN MODE 320X240
10020 REM CONFIGURE LAYER 0 AND DISPLAY TILES
10030 POKE $9F29, %00110001: REM TURN ON LAYER 0,1 AND VGA OUTPUT
10040 POKE $9F2D, %00110010: REM MAP 32 X 256, T256C, BITMAP MODE, COLOR DEPTH
10050 POKE $9F2E, %00100000: REM MAP BASE AT $4000
10060 POKE $9F2F, %10000011: REM SET TILE BASE AT $10000 AND H=16 W=16
10070 REM CONFIGURE LAYER 1 AND DISPLAY INSTRUCTIONS
10080 COLOR 1,0
10090 CLS
10100 PRINT "MOVE VIEW USING WASD. Q TO QUIT"
10110 RETURN

20000 REM SETUP TILE MAP
20010 VLOAD "TILEMAP-256X32.BIN",8,0,$4000
20020 RETURN

30000 REM SETUP TILE GRAPHICS
30020 VLOAD "TILE-GFX.BIN",8,1,$0000
30030 RETURN

Combined with the data files, we get a nice little demo of X16 tiles and BASIC.

X16 – Tile demo in BASIC