Wednesday, November 20, 2019

Seeker missiles revisited

If you follow me on twitter, you saw back in February that I was attempting to get enemy-seeking missiles working correctly. At the time, I felt like I got all the bugs worked out, and they were good to go. But now that I'm at the point in content-creation of the game that the player actually GETS the seeker missiles, I'm not quite satisfied with how they behave, so it's time to revisit them.

The thing about seeker missiles (or any sort of "move an entity directly toward another entity at a set speed) behavior is that it's not as simple to get right on the 6502. (at least if you care at all about performance and would like to get more than 1 frame per second in your game).

The reason why is because of trigonometry.

There are two parts to making good enemy-seeking missiles. First is to select which enemy to target (usually the closest, although you might have a priority system instead to that they always target the most dangerous enemy or something. For this post, I'll assume we're targeting the closest enemy)

The way you'd do this on modern hardware is by first finding the closest enemy by using the Pythagorean theorem -- distance is the square root of x2 * y2. You can even omit the square root if you only care about finding the closest -- just find the sum of squares of the x and y distances for each enemy, and the closest is the smallest.

Unfortunately, arbitrary multiplication is slow on the 6502. Without a multiply instruction, you're stuck adding in a loop, (or bit shifts for multiplications times a power of 2). If the x distance is 74, that means adding 74 to itself 74 times in a loop.

That would look something like this (squaring a single 8-bit value into a 16-bit value):

  ldx val        ;3 cycles
  lda #0         ;2
  sta result     ;3
  sta result+1   ;3  (11 cycles for loop setup)
  lda result   ;3 
  clc          ;2
  adc val      ;3
  sta result   ;3
  lda result+1 ;3
  adc #0       ;2
  sta result+1 ;3
  dex          ;2
  bpl :-       ;3  (24 per each time through loop)

  ;11 + (24 * 74) = 1787 cycles 

I scribbled that down without checking it, so it may be off by 1 or something, but it's something like 6% of a frame just to do that single 74*74 calculation. Good luck trying to also do y2, then computing this for each possible enemy. So we need a better way.

To be honest, I haven't found a perfect solution for this. Luckily, for this part of the problem, we don't really have to be exact. If the missile targets an enemy that's not exactly the closest, I don't really care.  So for this first step, I just compare x + y instead of x2 * y2. Sure, that overestimates how far away enemies are that are more diagonal from the missile, but ... I don't care.

The more interesting part is the second half of the problem. Doing the math to determine the X and Y components of movement to move the missile toward the target.

The easiest solution is just to move at full speed horizontally until your x component matches the target, and also move at full speed vertically until your y component matches the target.  The problems with this are obvious though: the missile moves too quickly in a straight diagonal, until it gets even with the target in one dimension, then moves straight until it hits it.  This is a fairly obviously ugly movement.  It's fine in some cases, particularly if the entity is moving fast enough that you don't really pay attention to the movement itself.  I used this method in Super Homebrew War when a player gets the "swap everyone's location" power.  I didn't have the programmer time or rom space for something more complicated, so I just went with this. The swapping all happens so quickly that you don't really notice that it's ugly.

Another solution would be to use to a constant TIME instead of constant VELOCITY.  If you assume that the missile will always take approximately a second to reach the target, you can divide the x distance into 64 pieces (dividing by 64 is fast with bit shifts), and divide the y distance into 64, and move each by that amount every frame.  That will produce a nice even movement, BUT the speed will change based on the total distance traveled. A missile will take the same amount of time to reach enemy A as enemy B, which may be undesired.
The REAL solution involves trigonometry, which is hard on the 6502. You find the angle (the arctan of y / x). Then to find each frame's x and y components of movement, you use cos(angle) * vel = x.  (or sin to find y).  It's simple high school trigonometry. Easy if you have a calculator or a modern processor. Not as easy on the 6502.

But for Halcyon, I want things to look nice and polished, so I wasn't happy with either of the two previous solutions. So trigonometry it is.

For the arctan, I found a pre-written routine that does a pretty good fast estimation of arctan that was written by one Johan Forslöf. I don't pretend to understand the math behind it (he claims it simply "uses logarithmic division to get the y/x ratio and integrates the power function into the atan table"), but it does what I need it to do.

For sin and cos, the trick (like many things on the 6502) is just to use pre-computed tables. If you assume that the angle is a 1-byte value, then there are only 255 possible sin values you have to compute. So you can compute them ahead of time (using a python script or something similar), and just put them into your rom as a lookup table. The cartridge rom that I'm using for Halcyon has plenty of rom space, so a 255-byte table is no big deal.  Then to compute the sin, you just look up the precomputed value for any angle. Table lookups are one of the things that the 6502 does best, so this is nice and fast:

ldx angle      ;3
lda sinTable,x ;4 (7 cycles total)

For cosine, you can take advantage of the fact that cosine is just sine rotated by one quadrant, so you add (or is it subtract? I never remember) 64 from your angle and use the same table.

So with these tricks, you can have a pretty nicely functioning enemy-seeking missile, without using too much CPU time.

Now if I could only figure out why it's not working, and my missile is just bouncing along in a goofy-looking sine wave pattern.

Tuesday, November 12, 2019

Scrolling glitch

For an 8-way scrolling engine with 4 nametables (ie 4 in-memory screens for the camera to pan across), it's easy to end up with a lot of small glitches in the background. Scrolling diagonally across the seam of screens, it's easy to get some of the PPU memory address math wrong, and end up writing to the wrong spot on the screen. But it might only happen when the screen is aligned exactly wrong, so it can take awhile to find and fix all the glitches.

The gray outline shows what's actually on screen. The rest is video memory that's not shown.

Over the past couple of years of working on this project, I've gradually worked through what I thought was every single scroll glitch, and fixed them. Mesen, the NES emulator that I use, has some wonderful features for debugging this sort of thing. You can play through the game, and when you notice a rare, hard-to-reproduce bug like this, you can save your game history, then go back and replay the whole history through the debugger, stepping through what you did, rewinding if you went too far, and watching updates as they happen. It's amazing.

Despite all this, there's one scrolling glitch that, until tonight, I've never been able to reliably reproduce enough to find and fix. It only seems to happen in one particular room, and then, only rarely, even if I do the exact same movement when I enter the room.

The room that gave me all the trouble. Depending on some random numbers, you can end up with 7 enemies going at once, which has the potential to slow things down.

Luckily, tonight I caught the glitch in the emulator!  I went to quickly hit the "save history" button, and I accidentally pressed "reload save state" and jumped back to some previous point in the game, and lost it.   ARRGH!

But, I had the good fortune of being able to reproduce it again fairly soon after, and this time I managed to save the history, and replayed it over and and over and over again.

It didn't make any sense -- as I was scrolling diagonally through the room, it would just skip updating the background for a single frame. So instead of writing new tiles at the edge of the screen, garbage tiles would just scroll in instead. I couldn't figure out why it was skipping an update.

After about the 30th time I replayed it, though, I noticed something. My frame counter was jumping from $1d to $1f when I advanced a single frame. That's not right! 

To make a long story short (too late), I tie some of my scroll logic to the frame counter (to alternate between a few types of updates). In the rare case that too much is happening in a single frame, you can end up with that dreaded NES slowdown, which means that you hit vblank before you finish your frame's logic (ie you get 2 screen draws per logical frame, cutting your game to 30fps instead of 60).  During the screen draw interrupt (NMI) is when I advance my frame timer. 
You can use a grayscale bit in the video settings as a poor-man's profiler. The gray shows how much of my CPU time I'm using this frame.

So this one single room has enough enemies to very occasionally cause a slowdown (usually only for 1 or 2 frames so I never even notice), BUT during those slowdowns, my frame timer advances twice per logical frame. So my scrolling updater (which depends on that timer) fails.

It was an easy fix once I realized what was happening -- I now just use a separate counter for the background updates, and only increment it after actually doing an background update. It wastes a byte of ram, but this is the NES, which has a whopping 2k of ram! What's a wasted byte?

So now, for maybe the 100th time, my git commit message said "Fixed what was hopefully the last scroll glitch."  Maybe I'm actually right this time?

Monday, November 11, 2019

Who needs enemies?

One of the things I keep thinking as I'm building content in Halcyon is "does this room really need any enemies?"  I mean, the fun of the game is supposed to be about exploration. Enemies just slow that down, right?  Or maybe it's just that I'm being lazy and don't want to figure out what enemies to put into a room. Do I need to mix it up for each room, or is it ok to have a few rooms in a row with really similar enemies?  Will the players find this room to be boring, too similar to the last room? 

I have no idea.  But regardless, it sure is tempting to leave a lot of rooms empty.

Tuesday, November 5, 2019

Enemy names

I realized that I'm not all that creative when it comes to enemy names. For my enemy code, each enemy has a textual name that it's referred to in labels, in the map editor, etc.

Here's a handful of the names so far:

  • flapper
  • hopper
  • walker
  • gunner
  • diver
  • zapper
  • spitter
And then some that are even more boring:
  • blob
  • boss1
  • boss2
  • boss3
  • barrier
  • fish
Good thing these names are all secret....

Saturday, November 2, 2019

What sort of game is this anyway?

I've said before that I'm making a Metroidvania. A kind of mash-up of Metroid and Blaster Master in this case.  But these days, that Metroidvania label (as well as "rogue-like") gets attached to almost everything under the sun. Dead Cells, a procedurally generated level-based action platformer routinely gets labeled as both a roguelike and a metroidvania (while I would say it is neither).  Even among things that actually could accurately be described as Metroidvanias, there's a huge range of variety in what that can mean, and what sort of thing a game really is. So this post is my attempt to answer the question: "What sort of metroidvania is Halcyon?"

To answer that, there's a number of different aspects that are worth discussing: non-linearity, challenge, and reward structures. Let's dive in.


The first question is how linear is the game? At the far non-linear side of the spectrum are games with a big open world where you can really go anywhere in any order you want. The recent NES homebrew game Lizard by Brad Smith is a good example of this, as is Super Pitfall. There's a big giant world, and it's yours to explore. You can really do things in just about any order you want.

You can go any way you want in Super Pitfall, but mostly you just die. A lot.

Then there are games that have a little more linearity to them: the original Metroid is a good example. You can't really progress until you find the missiles and bombs. But when it comes down to it, you can go kill Ridley or Kraid in either order, without ever finding a number of the other powerups.  There may be a recommended order to do things, but you're not always doing everything in the same order.  (The original Legend of Zelda was very similar in it's non-linearity. There was an order to the dungeons, and some of them required items from other dungeons. But there's not much preventing you from doing some of them out of order(and we did so when we were first exploring the game as kids....if you got stuck on level 6, you went on to try level 7 instead).

Next up are games that are slightly more linear, like Super Metroid. Advanced players know how to exploit the game and can do things out of order, but the average player will end up doing things in mostly the same order every time. Sure, there's plenty to explore, and plenty of secret passages that you may or may not find. But the general order ("find this powerup to open the way to the next section. Find another and then you can go back through that other section") is generally the same for each player. (assuming they aren't purposely going back and trying to break the game sequence).

Despite the awesome Metroidvania-style map, Circle of the Moon was a huge disappointment to me. Each colored section was a distinct "level" that you had to play through in order.

At the far linear end of the Metroidvania genre are games like Castlevania: Circle of the Moon. Although it's one big world, it's divided into clear level-like areas. You beat the boss of the first to get an item that lets you explore the next. Beat that next level, and you get rewarded with the power that lets you explore the 3rd section. And so forth. These are the least interesting to me: although they pretend to be big contiguous-world metroidvanias, they're really not much different than a linear level-based game.

Where does Halcyon fit into this spectrum? I'm attempting to place it somewhere between Metroid and Super Metroid. I'd like the player to have a little bit more freedom in the order of things than Super Metroid, but I found Metroid to be a little too painful in terms of a beginning player not having any idea of where to go. A few parts of Halcyon will require you to go get powerup X right now to continue, but there will be other parts of the game where you can decide which way you want to go, with a number of different areas to explore and routes to take.

As a side tangent -- the world in Halcyon is a euclidean contiguous world. There are no warps between worlds or front/back (like Goonies 2) or weird non-euclidean layouts like Blaster Master. It (like Metroid) is just one large mappable world.


I've made some hard games in the past. My friends who have played my original Robo-Ninja for Android may have had some unkind words about me at times. Robo-Ninja (also a metroidvania) was designed to be HARD. The world wasn't big or complicated, but each room was a challenge.

Robo-Ninja -- possibly the world's first tap-to-jump metroidvania?

When I'm talking about a difficulty spectrum here, I'm talking not about how big or confusing the world is, but how difficult the enemies, obstacles, and other "platformer skill" elements are. The original Metroid was a pretty tough game, particularly at the beginning when you didn't have many energy tanks). Lizard is HARD -- you die A LOT. Blaster Master had a weird difficulty curve -- some levels were really easy, but some levels (and bosses) made you want to punch the screen.

The game was fun and easy-going until you had to fight THIS GUY.

Super Metroid, on the other hand, wasn't a very hard game. There were a couple parts that were tricky, but you really didn't die all that much. The fun of the game was exploring and figuring out where to go, and looking for secrets. The enemies were mostly just there to keep you on your toes.

Symphony of the Night was also like that. Other than that one boss (I don't remember his name, but I'm sure if you played it, you know who I mean), it was a fairly easy game, mechanically. The joy of the game wasn't in the finesse of fighting and jumping.

Unlike Robo-Ninja, this time I'm going easy. Halcyon is (hopefully) going to be more like Super Metroid or Symphony of the Night in this regard. If I can get the difficulty set the way I want, you might die a couple times, just enough to keep you interested and careful. But the combat isn't supposed to be hard. Anybody with moderate video game skill should be able to take their time and explore and enjoy the game.


One of the things that I want from Halcyon is for exploration to feel rewarding. Super Pitfall had a giant world with lots of areas to explore, but it was just a vast mostly-empty world. There was nothing that made you feel rewarded when you went this way vs that way. You'd explore a route and die, without having found anything interesting. You'd try a different route and die. You never seemed to make any sort of progress.

Lizard also had a fairly brutal reward system (in my opinion). There were coins scattered around the world, but you had no idea what they were for, and you'd lose them if you died. If you explored a lot, you could find a new power (a new lizard costume), but you didn't get to keep it. Even defeating a boss just mostly felt confusing to me.  These were all purposeful design decisions that Brad made (as opposed to just poorly-designed flaws), but playing it helped me figure out what sort of feeling of reward I wanted to put into Halcyon.

This screenshot from Lizard sums up how I felt most of the time.

First, I wanted a map screen that would be permanently revealed as you explored. (Like Super Metroid, Symphony of the Night, or many other newer games). With a revealed map, you always feel like you're making progress. Even if you get fairly lost, and don't discover where to go, your adventurous route is marked on your map. There's some internal feeling of reward in uncovering the map. You did something permanent. You got here once and you know how to get here again.

Second, I wanted a lot of powerups scattered throughout the world. Heart containers in Zelda and missile packs in Metroid were great -- they could distribute them freely all over the place, giving you lots of minor rewards throughout the game. I love Super Metroid's method of putting a minor reward behind some secret passage. The real thrill was finding the secret passage, but they gave you a permanent upgrade as a reward once you found it. To make this happen, I have a number of types of powerups in Halcyon, so that I can hand them out like candy. There are a few major ability powerups (which are the keys to unlocking content and progressing), but there are also new alternate weapons, max health increases, weapon power increases, energy increases, etc.  If it was ONLY health increases, I think they would quickly become boring and lose their sense of reward. So my goal is to have all sorts of types of things to find to keep it feeling rewarding.

A tiny sliver of Halcyon's minimap

Hopefully my describing where Halcyon fits in along each axis will help provide a better picture of "just what is this game all about, anyway?" But just a few more bullet points might be helpful:

- There's a little bit of story/plot, but not much. If all goes to plan, and
  we can get the details ironed out, there will be an opening story sequence, a tiny bit of plot along the way, and and ending story. But this won't be a story-driven game. You won't be talking to lots of people, getting clues in towns, or interacting with a lot of characters and dialog.

- Like Blaster Master, there will be a dynamic of getting in and out of your
  vehicle to explore different areas that are better handled on foot or in-vehicle. Unlike Blaster Master, there are no overhead sequences. The world is one single contiguous side-scrolling map.

- There will be secret passages and hidden items. More Metroid than Blaster
  master in this regard. Some will be pretty obvious. Others might be rather difficult to find. (dare I say obtuse?) My goal (if I pull it off well, which I may not) is that all of the secret passages necessary to win the game will be fairly intuitive to find, while many of the optional routes or powerups will be better hidden.

 If you have any questions, I'd love to hear from you! Pester me on Twitter or email at

Thursday, October 24, 2019

Asset Pipeline

One of the biggest tasks in marking a video game with a significant amount of content is managing your asset pipeline. What is an asset pipeline? It's the process of getting assets (graphics, music, maps, dialog scripts, or any other sort of content) into the game. In smaller games, you can usually get by without much of a pipeline. If there's not much content, you can usually find a way to manually shoehorn it into your game. Or even manually hack or hardcode the data into the game. But with more content, that quickly becomes unmanageable.

Modern platforms like unity have a lot of built-in editors and tooling that manage a lot of the pipeline for you, and the more powerful target platforms (ie your PC) can afford to work with a lot more options of data formats. But on old systems like the NES, it can be a lot of work getting your assets into a format that is usable and efficient.

For example, most Atari games store their sprite graphics upside-down in ROM. This lets you save a few cycles in your rendering kernel (because on the 6502 counting down to 0 is faster than counting up to an arbitrary number, so you count backwards when rendering most things). You can manually enter your sprite graphics backwards by hand, or you can draw your graphics in a user-friendly tool, and let it take care of turning them upside-down.

For the NES, there's a huge range of ways that people manage the asset pipeline. I know folks who design things on paper, then manually enter hex data into their editor.  I know a guy who built an editor entirely as a NES game itself so that you can just press save in the editor, and everything is ready in a NES-friendly format.

My philosophy is this: I want all my assets to be saved in the most easy-to-edit and user-friendly format. That way I can work with them easily during development. Then I want the build process to automatically convert them all into the right format for the game when I compile. I specifically DON'T want to deal with a separate export step during editing -- that usually ends up with a situation where you forget to save or export something, and your exported version differs from the original asset, and you aren't sure which is correct. Instead, I want the original asset to always be the authoritative version. So any conversion or export steps must be automatically done at build time.

So, let's get into examples. Text data is probably the simplest pipeline. I have a number of dialog boxes in the game. I want to be able to write my dialog text in any text editor, and save it as a text file that's tracked in git. So I have a separate text file for each dialog script.

One text file for each dialog

At build time, my makefile runs a python script to convert each of these into the format that my game wants: It converts each character to the value of the graphic tile id that displays that character. It converts special control characters (like line-breaks, special non-ascii glyphs like button icons, etc) to the correct codes. Then it generates symbol tables of both the address of that script, and the text length of the script. So if I want to change any text, I only have to change the text file and recompile, and I'm good to go.

Now, let's get into the more substantial example: backgrounds, metatiles, and map data.

NES background graphics are made of 8x8 pixel tiles of 3 colors plus a solid background color. Different palettes can be applied to those 3 tiles (with all sorts of rules that I won't get into here), but at the core, NES graphics can be represented by a 4-color image.  Frankengraphics (the artist I'm working with) likes to use a program called NES Screen Tool for making the graphics.  Screen Tool generally saves data in a NES-native graphics format, which most people really like. This goes against my core philosophy though, as it's a hard-to-use format. You can't see a preview of the graphics in your operating system's window manager, or pop open any old graphics tool and make quick changes. It doesn't help that Screen Tool is windows-only, and feels REALLY buggy and janky running in WINE on Linux. So when I get graphics from her, I immediately load them into Screen Tool once, and export them to 4-color indexed png format.  During the build process, I have a python script that goes back and converts the png format to the NES-native graphic format (as well as generates address symbols based on the file name) This has the added benefit of making it easier to have arbitrarily-sized chunks of graphic data that I can refer to directly.

NES Screen Tool.  A lot of people swear by this thing.

Then, Halcyon makes maps out of 32x32 pixel "metatiles" -- logical map tiles built out of 16 graphic tiles. So I need a way to define those.  Since there aren't standard ways of representing metatiles (and since each engine has its own requirements for what data is bundled with metatiles), I decided to use a format that's both human readable and easy to program against: json. I built a simple (ugly) graphical editor for building metatiles out of graphics tiles. It edits json files, so standard tools (text diffs, git merges, etc) can easily work with the output of my metatile editor.  In my engine, metatiles contain 16 graphical tiles, as well as collision and palette data for the 4 quadrants of the metatile. These are also saved with the json file.  At build time (do you see the pattern here?) a python script converts these json files to striped arrays of binary data (and will also put them into various rom banks to ensure that I don't overflow the amount of space I have in any given bank).  The other resulting file is a temporary graphical file that re-assembles the actual graphical tiles into the metatiles, which I use for designing maps. This graphics file is never used in the final build -- it's only a convenience to make map design easier.

Speaking of janky, my metatile editor is JANK-O-RIFFIC. But it gets the job done.

So now, on to maps. While there's not one single standard file format or tool for maps, there is a well-known open source program that I'm a big fan of: Tiled. Tiled is a general purpose tile-map editor. It's fairly flexible and configurable, and the author is a really friendly guy who's very invested in making it a well-run open source project.  Tiled saves and loads maps in a simple easy-to-read text format (either based on xml or json), which is perfect for my philosophy of assets.

So I load a tileset graphics file into Tiled and build my maps, saving them in Tiled's native format. At build time, a python script processes all of my map files, and converts them all to the right format for Halcyon. (which is a big array of properties about each map, with pointers to arrays of the actual map data, and arrays of enemy spawn information). Then the script builds a giant index of all my maps, and makes a big lookup table that lets me find the address of a room based on its X,Y coordinates.

Tiled is the best thing ever.

Now that I've talked about HOW I do the asset pipeline for levels, it's worth giving a few more reasons for WHY I do it this way. I mentioned a few above, but I like to repeat myself, so:

- Editing is MUCH easier when you use text formats as much as possible, and
  standard well-known formats for non-text

- Version control (ie git) is a lot more useful with text files, as you can
  easily see a diff of what changed

- Building from the original source asset at compile-time prevents the "out of
  sync" problems you can get with manual exports

- Using a script at build time lets you change the engine's expected format
  without having to touch each of your assets again. For example, at one point I made an optimization in my sprite rendering that required sprites to be stored offset by 32 pixels. To accommodate this, I only had to change my build script without touching each sprite definition. Or if I go back and decide to add compression on graphics, I can do it without having to manually handle each graphics file.

- Using a script lets you automatically build secondary derived assets from
  your assets.  For example, I automatically generate a minimap based on my actual maps without having to manually build a minimap to match the actual map. I also automatically build some reference notes for myself -- a text file that includes notes about the location of every powerup and the id's that I've assigned to them. I love not having to manage that notes file by hand.

  I could talk about all the other types of assets (enemy definitions -- which I've blogged about previously, music, palettes, etc), but I'd start to sound pretty redundant I think. I just do my best to folow the guiding philosophy: store in the most editor-friendly format, and convert everything at build time. Manual exports are NOT allowed.

Thursday, August 29, 2019

Scrolling Camera Tweaks

One of the subtle things that can really impact how a scrolling platformer feels is how the camera works. Does the character stay centered, or does the camera feel a bit looser? If it's loose, when does it scroll, and how quickly?  There are tons of articles out there about this, and they can describe it much better than I can, but it's a decision you have to make when designing a scrolling game.

In Halcyon, when moving horizontally, the camera tries to "stay ahead" of the player, by scrolling quickly until most of the screen is ahead of the direction the player is facing. That gives you plenty of time to think about upcoming obstacles and enemies.

This works really nicely for most of the game.

Until it doesn't.

One scenario that happens in Halcyon is that you will get out of the tank, use your grenades to destroy some walls, then get back into the tank. To work around limitations of the NES, destroyable walls regenerate when they go off the screen. This leads to situations like this, where you turn around to get back into your tank, and the destroyed wall immediately goes offscreen as the camera hurries to move ahead of you.

This is a tricky situation. Basically, I want my scrolling to work differently in this subjective situation. But how to define that and codify it into something that actually does what I want?

Tonight's attempt is some simple hackery:  Add a 4-second timer after destroying any block. During those 4 seconds, the camera won't scroll horizontally unless you get a lot closer to the screen edge in the direction you're wanting to scroll. 

This works great for the scenario in question:

The real question will be whether it causes annoying behavior in other parts of gameplay. That will remain to be seen....

Thursday, August 1, 2019

Crazy crashing bug

Normally after I test on an emulator for awhile, I eventually throw the game onto hardware, and get frustrated at it not working.

THIS TIME, however, I ran into something new. The game was working on my primary-use emulator, Mesen (which is accurate, easy to use, has a wonderful debugger, and an author who is always adding new features). It worked fine on hardware. But this week I was away from my computer a bit, and wanted to do some testing, so I threw it on my phone (which is using the quite common emulator, fceux).  And on my phone, it now won't run AT ALL.

fceux is a pretty good emulator. Not quite as 100% accurate as Mesen, but usually good enough.  What could cause the game to crash on it but not Mesen or real hardware?

As I usually do when I get stumped with a hard-to-debug issue, I did a git bisect. Git bisect is the one feature of git that, for a single-developer project, makes it better than subversion. It helps you quickly run through past changes, and find the one specific change you made that causes a behavior to happen. I won't go into detail here about it, but if you haven't used it, you're missing out.

Anyway, I did a git bisect, and discovered that the breaking change was just adding a new room to my game. No new code, no new features.  With some experimentation, it turned out that adding ANY new room would break it. Which sounds like maybe I was pushing something over a bank boundary in my rom.  So I dug up my assemblers map file, and no. Nothing was being pushed out of place.

So what could it be? fceux has a debugger, but for some reason, I can't understand how to use it. Did I really need to learn its debugger just for this?

Well, because the problem happened somewhere on startup, the next thing to try (before learning the new debugger) was to insert a bit of code that would turn the screen blue and then infinitely loop. I'd add that at my first line of code, compile and test.  It turned the screen blue on fceux, as it should. Which meant I was getting that far in my code.  For the next few hours, I moved that snippet of code forward and back, trying to find the exact function call that was crashing.

The result?  It turns out I was calling the update function of the music engine (ggsound) before ever calling the initialization function of the library.  Ok, that's bad.  But why would it work on hardware and Mesen but not fceux?  Suddenly it occurred to me.  Mesen and hardware start up with mostly random values in ram.  Fceux starts with zeros. I'm sure that some branch somewhere in the music engine branches on zero, and breaks.  The chance of that piece of memory being 0 in Mesen or hardware are just 1 in 256. So I never saw it crash on those platforms.

That said, I still have no idea why it didn't happen until I added one more room to the game. Probably some dark voodoo. I don't want to know.

Saturday, July 20, 2019

Prep for testing

My goal is to have the first area of the game ready for a few folks to sanity check and test for me soon. The goal of this first round of testing is just to make sure I'm not completely off-track. Does it actually run properly for other humans? Is it playable? Is the difficulty completely out of wack? What about the controls?

That means that before I hand it over to folks I need to add just enough polish on everything that it's not a frustrating experience. There are tons of things that aren't done, but that's ok. It just needs to be enough that you get to experience the game properly.

I've been playing through the first area a few times to make sure if feels ok to play to me. It's not very big -- only about 20 different rooms. But that's enough to take a few minutes exploring. And enough to get frustrated by if it doesn't play well. I've already had to change a few rooms that ended up being annoyingly hard.

The other thing that I spent some time on was getting saving/loading working. I fully expect my testers to die a couple times, even this early. I don't want them to have to start completely over every time they die, which means getting game saves working. I have another blog post I need to write about how flash saves work on the mapper I'm using. But I had that part working. What I didn't have working was everything that interacts with actually saving: What happens when you die? How do you load a saved game? How do you start over instead of continuing from your saved game? Does everything get loaded properly when you resume (answer: NO)

I think I finally have all that debugged and working. Tonight was the final piece of it: adding a simple UI for letting the player choose to Start or Continue. Which means title/menu work. Which always takes significantly longer than you expect, and is really boring. Yeehaw.

I'm almost there though. Time to do some more playthroughs.

Now it's a fairly short list of things that I hoped to have in this demo but are missing, and probably won't make it to this first testing round:
  • Super NES controller support (there's a lot of "hold down + A" type things in the game. If the player has a SNES to NES controller adapter, they can use dedicated buttons for those)
  • New Enemy Graphics (I'm using tons of placeholders)
  • The ability to shoot upward at an angle once you find the tank
  • Fix buggy behavior with the health-hungry blob enemy

Friday, July 19, 2019

Pseudo-fixed bank

I wrote about bank switching a few years ago when working on Atari Anguna. The idea being that the 6502 (or worse, the 6507 which is the variant of 6502 in the Atari) can only address a certain amount of ROM memory, so larger cartridges use multiple "banks" where you can switch which bank of ROM you're using. Nintendo cartridges used the same technique, so bank switching is important on both consoles.

Many variants of cartridge hardware (commonly known as mappers) divide ROM space into 2 (or more) sections. One that always stays active, and a second section that you can switch. This is a lot easier than switching the entire ROM space at once, as you can control things from the fixed bank, and just load data or call routines from the swappable banks as needed.

The mapper that I'm using for Halcyon (GTROM) doesn't have a fixed bank. Like Atari Anguna, it swaps out the entire bank all at once. Which means that you have to have special code to call a routine in a different bank. You put a stub of code (commonly called a trampoline) in the same place in both banks (or in RAM, which doesn't get swapped). You call that stub, it changes banks, then calls the new routine.

That's worked well for me so far on Halcyon. But now I've realized I have about 15 subroutines that I call a lot and from all sorts of different banks. I decided it would be faster (both in terms of writing code, and in execution) to avoid trampolines for those, and instead, duplicate just those routines into every bank that uses them.

Unfortunately, cc65 (the compiler/assembler suite I'm using) doesn't have direct support for duplicating routines multiple times in different places. So instead I'm doing some ugly hacks.

First, I compile the whole project once, leaving blank space in the places where the code should be duplicated to. One of the linker outputs is a nice map file, which tells the address of every piece of code in the final assembled output. So I have a python script that analyzes the map file, and extracts the portion of compiled binary that should be duplicated in other banks. It writes this to a file, and compiles everything again, this time injecting that extracted binary into each place that it needs to be duplicated.

This worked perfectly until last night when I started getting weird crashes calling code in this duplicated pseudo-fixed bank. Why was it crashing?  After an hour of angry debugging, I discovered the issue:  My python script had an off-by-one error. It was omitting the last byte of the pseudo-fixed bank.  Which means I had half an instruction dangling without the other half. That would do it.

Sunday, July 14, 2019

First Boss

I feel like I'm finally making real progress. Using some placeholder graphics from the ever-amazing surt, I've got the first boss fight finished. This boss is the main obstacle in your way from finding the tank vehicle, so you have to fight it on foot.

In Halcyon, bosses are mostly just another instance of a regular enemy, just harder. There were a few differences which I'll talk about in a minute, but interestingly, those differences aren't what took me the most time with this fight. Really, the things that took the longest were bugs in my main enemy-handling code that only revealed themselves while developing the boss fight:
  • The boss shoots missiles. The system for spawning a bullet for a boss had a bug based on the sign of the vertical offset.  Meaning if you spawned a bullet above an enemy's reference point, it failed. (every bullet I had spawned until this point was shot downward from an enemy, so I never noticed)
  • The edge-of-screen clipping was broken on the left side of the screen. Other enemies were narrow enough that I didn't notice, but enemies would disappear once about halfway off the left edge.
  • My enemy animation system was broken for animations that had multiple different repeating sections
This guy's look might change entirely once Frankengraphics gets ahold of him.
I'm also not sure about the vertical placement of the enemy health bar. We'll see.

Once I got those things worked out, developing the things specific to bosses was pretty quick:
  • I wanted a boss HP meter so you had some idea of how the fight was going. I thought this might take a while to develop, but I was able to reuse the code from the player's HP meter without much work, so this only took about 10 minutes to get working!
  • Bosses need a way to stay dead once you kill them. I already had the engine infrastructure in place to persist important global game state, so I just needed to add hooks before spawning the boss, and after killing it, to read and write that game state.
  • I added another entity, a type of gate, that blocks a pathway until all other enemies on the screen have been killed. This could be generally useful in other screens where I want to force a fight, but was important to make you actually stay and fight the boss.
The two things that I'm still missing are special boss music (which should be easy, but I just need new music), and a larger and more interesting explosion for bosses.

That said, other bosses in the game might require something more complicated -- larger bosses might be made from background tiles, and require some sort of background-scrolling magic to animate them. We'll cross that bridge when we come to it.

It's almost time for another round of testing, to see what's completely broken, or if the challenge level is acceptable. If you're reading this, and are interested in helping test the game, send me a message!

Thursday, July 11, 2019

Defining enemies

Enemies are the type of data-driven thing in video games that are fun to think about, in terms of tooling and development.  They have lots of stats (health, size, damage they do, etc), and a lot of different behaviors attached (What function runs to update them? Does anything special happen when they take damage? What about when they deal damage? Or when they die?)

There are tons of solutions for how to handle this. But one of my soap-boxes is that game data should be defined in a textual format, and be easy to edit (either by editing the text format, or with an easy UI tool).

For Halcyon, I decided to use a YAML format for enemy definitions. YAML is a data definition language, similar to XML or JSON. If you read about it, there's all sorts of reasons people say you shouldn't use it. But it has one important thing going for it: it's really easy to read and write. Which is what I need for this game.

- name:        topgunner
  hp:          4
  width:       16
  height:      16
  dmg:         1
  on-collide:  NORMAL
  on-offscreen: KILL
  update:      enemyb_topgunnerUpdate
  animation:   anim_topgunner
  frames:      frames_topgunner
  init:        enemyb_topgunnerInit

- name:        topgunnerBullet
  hp:          4
  width:       4
  height:      4
  dmg:         1
  on-collide:  NORMAL
  on-offscreen: KILL
  on-shoot:    NONE
  update:      enemyb_8wayBulletUpdate
  animation:   anim_shooterBullet
  frames:      frames_shooterBullet
  flags:       BULLET

I define my enemies in a YAML format, specifying both their numeric stats, the name of some animation data to display them, as well as various routines and properties to define their behavior. My build script then converts this YAML at compile-time into an assembly language file that defines arrays of data to represent each enemy.  Symbol names (like enemyb_8wayBulletUpdate) get injected right into the generated assembly code, and the linker knows how to translate those into the addresses of the functions that they refer to.

Sunday, July 7, 2019

Big and Tall

One of the things that can use up a lot of your CPU time on the NES is metasprite rendering.  Each hardware sprite is 8x8 pixels (or optionally 8x16). Complicated characters are then made up of a bunch of different sprites together, which is often referred to as a metasprite

Rendering a metasprite isn't complicated -- you push X, Y, tile, and color values into the right spot for the first sprite, then read the next sprite, adjust X and Y appropriately, and repeat.  The problem is twofold. First, it's just a lot of instructions on the 6502 to read, add, and write the sprites, when there's a lot going on onscreen.  Second, you have to deal with clipping.

Sprites can be positioned from pixel 0 to 256 horizontally, which is represented in a single byte. If you wrap around from 256 to 0, the sprite will appear on the left side. So for a large metasprite that's near the edge of the screen, you have two options.  First is to hide the object entirely if any of the sprites go off the edge. This is faster, but looks bad -- the character pops onto or off of the screen. A lot of old nes games do that, and you get used to it as a player, but it looks cheesy.  The second is do check each single sprite as you're computing its position. If a sprite's X value wraps around from 256 to 0 (or vice versa), you omit drawing that sprite. That gives a much better appearance of smoothly scrolling off the edge of the screen.  Unfortunately, it's that much more math you're doing for each sprite in the game.  Since enemies are often made of at least 4 sprites, and often 8 or more, that can become cumbersome very quickly.

In Halcyon, I wasn't happy with the popping-off-the-edge solution, so I opted for taking the time to check each sprite. To try to keep it easier on the CPU time, I have a number of ugly optimizations that make the wrapping/clipping checks a bit faster.  Unfortunately, one side effect of those optimizations is that my metasprites can only be 32 pixels wide or tall.

That was fine until this week, when I wanted to make a tall barrier that opens when you defeat a boss.  It needed to be more than 32 pixels tall.

That ugly thing in the middle is an "enemy" wall that can raise/lower depending on what other enemies are alive. The graphics are just placeholders.

That was tonight's challenge -- how to work around my optimizations and allow larger enemies?

The answer ended up being fairly simple: I still limit each metasprite to 32x32 pixels, but I allow a metasprite to specify a new base position and start a new metasprite from there.  So really, a metasprite can be more of a meta-metasprite, being made of a few different metasprites at different offsets.

Ugly?  You bet.  But it works.

Friday, June 21, 2019

Stairs and a hoppy guy

One thing that Frankengraphics (the artist I'm working with) suggested was adding 8-pixel tall blocks that the character could run/drive up without jumping. Sort of like ramps, only without the continuous nature. I've been putting it off, because ramps are weird.

I finally decided to tackle it in the last few days. And it turned out that the discrete nature of the steps, combined with how I've handled collisions so far, made them really easy.  As in 30 minutes of work, and they just worked.

Next I decided I needed some hoppy bouncy enemies. Because erratically bouncing enemies are always a giant pain to fight, which is a good thing. My hoppy enemy took a bit longer than I thought to get it working right (a couple of hours for this guy, way longer than my stairs!), but I finally have it working mostly right.  Except that it needs art.  I'm using a random placeholder for now, so it mostly looks like a bouncing cheeseburger.

Saturday, June 15, 2019

Level Design in Earnest

Well, with moving platforms done, I decided I'm fair enough along that it's time to start doing "real" level design. I've got a bunch of maps that I've designed for demo purposes, so you can play through a bit of how the world will play, and I can test out how transitions work.  But they were never intended to be the real map.

So I've wiped out all that, and started now on the "real game."  And after a couple years of fiddling about with the engine, it's really refreshing churning out a few maps. 

Spoiler alert!

I've realized a few things:
  1. I'm bad at making interesting maps.  I have these big rooms, and it's hard to fill them with things that will actually be fun. I'm trying though.
  2. I don't have to go very far before I run into features that I need to add into the engine.  I hit the first save room quickly, a few days ago, and remembered that I hadn't implemented game saves. I got that added, then immediately started on a room with some 8-px steps (which the main character is supposed to be able to run up without jumping). Of course, I haven't actually implemented the running up stairs yet.  Time to do that I guess.
  3. Nothing reveals bugs like real content.  Just tonight, I plopped an enemy (the eyeball creepy crawly guy that I've used all over the place in the demo rooms) into my map, and he's broken.  WHY, computer, WHY!?
Exhibit A, in which I decide that I hate computers.

Friday, June 7, 2019

Moving platforms working

Ok, another lunch hour devoted to the platforms, and they're working!  My idea of how to make them ended up working perfectly.

I ended up wasting about 45 minutes though due to a stupid optimization. Instead of checking collisions against the full world coordinates of the player and platform (which are 2 bytes instead of 1, thus requiring quite a bit more instructions for the collision check), I was just caching and comparing their on-screen rendered coordinates (which is just 1 byte).  That works well EXCEPT for the fact that the player's render coordinates are calculated AFTER the collision check, meaning they're one frame behind.  For a lot of things, that one frame might not matter, but here it caused the player to keep getting stuck in the platforms.

Once I removed my silly optimization, things worked great!  Although I need to make some minor changes to the camera code. Right now the camera only scrolls horizontally when the player moves naturally, but not when the platform pushes the player.  Meaning currently a platform can drag you offscreen. That needs to change.

The nice thing about this addition is all the ways it can be used in gameplay: moving platforms, moving walls that get in your way, enemies that can be frozen and climbed, barriers that can get moved by a switch or trigger, etc.

Tuesday, June 4, 2019

Catching up, and Halcyon moving platforms.

Hmm. I haven't posted here in almost a year. I got thinking about my progress on Halcyon, and decided it was time to actually get back to writing about what I'm doing here.

I realized I didn't say a thing here about Super Homebrew War, my 4-player nes brawl, using characters from other well-known NES homebrew games, which scored 2nd place in this year's NESdev competition. 

Nor did I mention that I got inspired to try my hand at Dreamcast development. Like last year's port of Robo-Ninja Climb to the 2600, I decided to once again take my NES code, and try porting it directly to the Dreamcast. As usual, it took slightly longer than I hoped, but I now have a Dreamcast version of Robo-Ninja Climb finished.
The nice thing about Dreamcast homebrew is that you can test on hardware for the low price of a CD-ROM!

Now I'm back on to working on my metroidvania, Halcyon.  Tonight's challenge is obstacles/platforms that aren't part of the background, and thus can move around.  Like ramps, moving platforms are always slightly trickier than you'd think they should be.

After a few false starts, my current theory of how they'll work is like this:

  • Moving platforms are actually just an enemy instance, with a modified collision routine.  
  • During the enemy platform's update routine, I'll do a collision check: If the player collides with the platform, I'll move the player by the same amount that the platform moved. (which lets the platform push the player around)
  • During the player's movement, it will look for any enemies flagged as platforms, and handle collision results against them just like collisions against background tiles.
  • During the enemy's movement/collision checks, the collision box of the platform will be adjusted to be a tiny bit larger than during the player's collision checks, so that the platform will "grab" the player and move it if the player is riding on top
Believe it or not, but that moving thing above the tank is a platform.

I spent the evening writing the first half of this (the enemy update phase, which can move the player around).  Hopefully tomorrow or soon I'll get to the 2nd half (the player's adjusted collision routine), and we'll see if my theory works out.

Seeker missiles revisited

If you follow me on twitter, you saw back in February that I was attempting to get enemy-seeking missiles working correctly. At the time, I...