Towards An Entity-Component-System Framework for the Atari 2600#

It’s hard to think of a more “bare metal” programming experience than the Atari 2600.

You’ve got to fit everything into 128 bytes of RAM, 2 KB of ROM, and about 20,000 CPU cycles per video frame.

Such an environment is fun for making short demos, but it becomes difficult to scale up to a full game.

Isn’t it just a matter of stitching all of the components together? Yes, but doing so is a non-trivial exercise, which makes rapid prototyping exhausting.

There have been attempts to design high-level languages that make this experience easier. But the Atari 2600 has several constraints which make this suboptimal:

RAM is limited#

The Atari 2600 only has 128 bytes of RAM (unless the cartridge expands this) which must be carefully managed. For a moderately complex game, these bytes must be shared between components – for example, the title screen and game. You might also have to share temporary variables between multiple subsystems in the same frame, e.g. the scoreboard, display kernel, and music system.

Most assemblers have no way to analyze code and allocate RAM in this manner, so memory must be allocated manually.

In a C program, you might handle this problem by defining local variables on the stack. The 6502 doesn’t have stack-relative addressing, so accessing these variables would be slow and also tie up a register. Also, the Atari 2600 shares its stack with the very small amount of user RAM, so overflow would be a constant threat.

Kernels require exact timing#

The core of an Atari 2600 game is the display kernel, which is a block of code that paints each scanline – drawing the sprites, playfield, missiles, ball, and so forth.

Due to timing constraints, you can’t have a one-size-fits-all kernel that updates every register, so you must craft each kernel according to what’s being drawn. They usually have to be written in machine code or assembler.

Most games have composite kernels, for example in a shoot-em-up the scoreboard, enemy sprites, and player sprites might be separate kernels.

Some of the kernel’s work must be done in the cycles before or after the frame is drawn. This means you have to use more RAM to store temporary values. For example, the scoreboard kernel has to store a pointer to each digit’s bitmap data so it can quickly access them at display time.

The 6502 likes byte arrays#

The 6502 is optimized for arrays of 8 bit values. Often we have to store arrays of larger values, for example 16-bit pointers. In C, there’s no way to automatically split these into two 8-bit arrays.

It also gets more difficult if your game objects don’t have a homogenous set of properties. For example, what if your enemy sprites have a custom color, but your player sprites don’t? You have to choose between wasting RAM on unused array elements, or having a complex system where arrays can be different sizes for different combinations of properties. We’ve chosen the latter approach, because the ECS compiler can compute the array offsets.

The 6502 has alignment requirements#

On the 6502, data and code is sometimes subject to alignment constraints. If a branch or indexed lookup crosses a 256-byte boundary, an extra cycle is incurred. This is especially important when programming cycle-exact kernel code for the Atari 2600.

What’s wrong with assembler?#

How about assembly code libraries? These are useful, but the optimization requirements of the Atari 2600 often call for aggressive inlining, which calls for macros. These can only take you so far in the typical assembler – which is why we want kind of a super-macro library that is tuned to 6502 programming.

Modern ECS Frameworks#

Modern gamedev tools like Unity 3D use an ECS (Entity-Component-System) framework. The basic idea is that there are three types of objects:

  • Entities – The “things” in your program. Each is made up of various components.

  • Components – The data associated with your entities. Each component contains zero or more properties (or fields) of various data types.

  • System – The “code”. Each system is a bundle of logic which operates on entities and their components. It can emit and consume events.

For example, a Player entity might have the Sprite, Position, and Velocity components. A Physics system might move all entites with both Position and Velocity components, while the Graphics system draws entities with both Sprite and Position components.

Instead of calling functions or methods, the ECS approach relies on events. The code in a system is triggered by events, and can emit events.

For example, a CollisionDetector system may emit collision events, which are processed by a CollisionHandler system that updates the objects’ positions accordingly.

Advantages of ECS#

  • Modular design – You can add and remove components and systems without changing existing code. This encourages small composable systems rather than complex object hierarchies.

  • Separation of data and logic – You aren’t limited by object hierarchies. For example, enemies might have both X and Y coordinates, while the player might only move left and right, and thus need only an X-coordinate.

  • Optimized data access – You can separate data into arrays, which on modern CPUs can improve caching behavior. On the 6502, this allows us to use the indexed addressing modes.

  • Automatic initialization – You can declare initialization values for entities, and default values for components, which can be automatically copied into entities.

  • Automatic binding – When you include a system, it can query which components it needs, and it can place hooks into the event tree. Often, no additional code is needed to instantiate a system.

  • Serialization – The ECS framework can easily serialize entities to disk or stream them over a network. (Except on the Atari 2600, which has no storage medium nor network interface.)

Disadvantages of ECS#

  • It’s opinionated – You have to learn a new way of thinking about your program.

  • It’s not as flexible as C – Some things like nested data structures don’t translate well.

  • It can be harder to debug – The control flow tends to meander through many systems, and it can be difficult to follow.

Asset conversion#

The Atari 2600 has specialized formats for sprites and playfields which vary depending on the display kernel used. The data might also be page-aligned, which means it cannot cross a page boundary. The data might be stored backwards, and even the pointer to the data might have to be offset in either direction. Often these considerations are managed manually, with macros, or an external tool.

The ECS Design#

Design Goals#

  • Reasonable defaults

  • Automatic entity selection

  • Built-in examples

  • Cross-cutting code

  • Cross-platform (6502)

Components#

A component defines zero or more properties, which can be variable or constant. It has one of the following types:

  • Numeric – An integer range that can be either signed or unsigned. If the value extends beyond 8 bits, it is stored in multiple arrays.

  • Enum – A handy mapping of strings to numerics.

  • Array – An array of numeric or reference types. This is stored as 16-bit pointers.

  • Reference – A 8-bit reference to another entity.

Entities#

An entity holds a collection of components. The exact set of components is called the entity’s archetype.

An entity’s component can be defined as an uninitizalized variable, initialized variable, or constant value. Constants cannot be mixed with variables in a given set of entities.

Systems#

All of the code is contained in systems. A system operates on a subset of entites, or all entities. It has a collection of event handlers. An event handler listens for an event name. It might also have a query which narrows the entity set further.

An entity query selects the entities that will be in use by an event handler.

  • once – Don’t select entities, just run the routine once per event.

  • select – Selects one or more entities, but does not iterate, you have to write your own loop.

  • with – Selects exactly one entity, throws an error otherwise.

  • if – Same as ‘with’ except allows for zero entities, skipping the event.

  • foreach – Selects zero or more entities, iterating over them with an index register.

  • join – Selects zero or more entities indirectly via reference, using a loop with two index registers.

A system also can have locals – temporary variables that are used within the lifetime of the system. These are allocated globally using a bin-packing algorithm.

In this ECS, event handlers are like smart macros. They are expanded whenever an event is emitted with a matching name and intersecting entity set.

Events are executed in the order that systems are declared, then in the order they are declared in a given system. They are sort of like pointcuts.

There is a little bit of smarts to coalesce duplicate event handlers, calling them with a JSR instruction instead of expanding them inline.

Code Substitions#

Code substitions are bracked by {{ }} and contain either a command or symbol shortcut.

Scopes#

Scopes contain entities, and instantiate one or more systems.

Example Systems#

Let’s dive right into an example, starting with the vcslib standard library.

A scope is a nestable collection of entities, systems, and components. To create a top-level scope for testing purposes, we use the demo keyword:

demo Main

The using keyword instantiates systems inside of our scope:

  using FrameLoop, ResetConsole
  using StandardKernel, JoyButton

FrameLoop and ResetConsole define a basic frame loop that monitors the reset switch. StandardKernel draws a basic static kernel, while JoyButton monitors a player’s button.

Most systems depend on entities to get their data. The JoyButton system needs an entity with a Player component, so we define one:

  entity [Player]
  end

Note that it doesn’t define any data – the Player component has no fields. The presence of exactly one entity tagged with the Player component tells the system that we only need to read one joystick button. If we had two entities with Player components, it’d read two joystick buttons.

A KernelSection draws a section of the screen with a given height. We’ll define our first kernel section:

  entity [KernelSection,BGColor]
    const lines = 2
    const bgcolor = $18
  end

Note that this entity has two components. The KernelSection component has a lines field, which we define as a constant. We also include BGColor which we also define as a constant. This draws exactly 2 scanlines with color $18.

(Actually it draws three – the first KernelSection emits an additional scanline beforehand to set up attributes.)

We can define more entities with different attributes, for example:

  entity Trees [KernelSection,BGColor,PFColor,Playfield]
    const lines = 50
    const bgcolor = $14
    const pf = 0x112244
  end

This entity has a Playfield component and accepts a 20-bit integer. These will be stored in three 8-bit arrays.

We also gave this entity a PFColor component, but didn’t define a value. This will create a varable in RAM by default.

Note we also gave this entity a name, Trees. We will reference it later in an event handler.

Init#

The main_init event is invoked first. It’s boilerplate code that defines the main structure of the program, includes header files, defines constants and the 6502 vector area. The CPU reset routine invokes the CLEAN_START macro to initialize RAM, and then emits the start event.

system Init
  on main_init do once
---
.include "vcs-ca65.h"
.macpack longbranch
.define PAL 0
.segment "STARTUP"
__NMI:
__Reset:
__BRK:
    CLEAN_START
{{!start}}	; start main routine
.segment "VECTORS"
ZeroByte:  .byte $00
Return:    .byte $60
VecNMI:
VecReset:  .word __Reset
VecBRK:    .word __BRK
.code
---
end

FrameLoop#

The FrameLoop system handles the start event after initialization. It handles drawing a valid video frame every 60 seconds (for NTSC).

This system draws a blank video frame by default. It emits events that other systems can hook into at different parts of the drawing cycle:

system FrameLoop
  on start do once 
---
    {{emit preframeloop}}
@NextFrame:
    FRAME_END
    {{emit prevsync}}
    FRAME_START
    {{emit preframe}}
    {{emit prekernel}}
    KERNEL_START
    {{emit kernel}}
    KERNEL_END
    {{emit postkernel}}
    {{emit postframe}}
    jmp @NextFrame    ; loop to next frame
---
    on postframe do once
---
    lsr SWCHB	      ; test Game Reset switch
    bcs @NoStart
    {{emit resetswitch}}
@NoStart:
---
end

For example, a display kernel might hook into the prekernel event to do some precomputation, then hook into the kernel event to draw the kernel. Offscreen game logic might hook into either preframe or postframe.

During the postframe event it might emit a resetswitch event if the system is reset, which allows jumping to another scene without rolling the display. Or you can just include the ResetConsole system, which does a full reset.

JoyButton#

For each Player, emits the joybutton event if the player’s button is pressed.

system JoyButton
    on postframe do foreach [Player]
---
    lda {{index INPT4}}	;read button input
    bmi @NotPressed
    {{emit joybutton}}
@NotPressed:
---
end

This uses the {{index}} command, which converts its argument into an indexed operand using whatever register is used to index the current entity set. If the set only contains a single entity, it’ll expand into an absolute address. So in this example, it’ll expand into either lda INPT4,x or lda INPT4.

Joystick#

For each Player, emits joyright/joyleft/joydown/joyup events depending on how the player’s stick is moved.

This system uses the locals keyword which defines one or more temporary variables.

system Joystick
    locals 1

The first event loads the joystick register into the temporary variable:

    on postframe do once
---
    lda SWCHA
    sta {{$0}}
---

This byte contains 8 flags, 4 for each joystick. A game may have either one or two players, so we use foreach to iterate over each Player entity with a limit of two entites:

    on postframe do foreach [Player] limit 2
---
    asl {{$0}}
.ifdef EVENT__joyright
    bcs @SkipMoveRight
    {{!joyright}}
@SkipMoveRight:
.endif
    ...
---
end

SetHorizPos#

This is a critical routine that must fit into 22 bytes without crossing a page boundary. Because it’s critical, it’s never inlined.

It’s similar to the SetHorizPos routine in the book, and is called from other systems.

StandardKernel#

A basic display kernel that is used for simple, static kernels. Each entity with a KernelSection component is displayed top-to-bottom.

Emits the following events

  • kernelsetup - before each section and also once before first section. Sets up registers if BGColor/PFColor/Playfield is present.

  • prescanline - before WSYNC for each scanline

  • wsync - every time WSYNC should be called

  • scanline - after WSYNC for each scanline

SimpleCollision#

Handles collisions between a sprite and the playfield that have a SimpleCollidable component. The last X/Y position is stored, and if a collision happens the object is reverted to the last position.

FrameCounter#

Counts frames using the FrameCount component. Emits frame4 every 4 frames, frame8 every 8 frames, frame16 every 16 frames, frame256 every 256 frames. Code is omitted if no event handlers are present, using the EVENT__xxx #ifdef.

Code Fragments#

  system Local
    on joybutton do with [#Trees] ---
      inc {{set pfcolor}}
    ---
  end

This defines a local system (local to the scope) that responds to the joybutton event. When a button is pressed, it selects the Trees entity and increments its pfcolor variable.

The {{ }} expands expressions as text in the assembly code, kind of like a super-macro.

Here we say {{set pfcolor}} which evaluates to the operand used to set a given memory location. For this single variable, it expands to this:

    inc PFColor_pfcolor_b0

The {{set}} expression is used when values are modified. It will fail if the value is a constant, while {{get}} will simply emit a constant or an indexed entry into a lookup table.

Current Limitations#

We don’t have the ability to add/remove components at runtime, everything must be static. The best we can do is a flag that enables/disables a component.

Register allocation is not tracked, event handlers must be mindful of this.

Timing constraints are not tracked, so you can easily make a project which overflows scanlines or emits too many scanlines.

It’s kind of hard to debug, since your control flow goes all over the place, and you might have multiple inlined versions of the same event handler. However this is somewhat an IDE/assembler tooling issue.

We’d like to have an expression language that is less verbose than 6502 assembler.

The ordering of systems affects the ordering of events, and is important. We might want a “before/after” syntax to enforce ordering.

You gotta leave comments to explain ordering, register usage, and a couple other things.

It’d be better to write our own built-in assembler. Too many syntax errors which are hard to debug with nested tools.

We need a way to reset objects to the default value.

Packing/unpacking bitfields would be a good feature.

The whole compiler is buggy and awful and should be rewritten using formal methods.

Is it easier than writing from scratch? Hard to say. I think it’s easier, and maybe more fun.

The goal is to have doc generator for each system – literate code.

What is the call graph? We need to build an event tree and then do a topological sort.

Can scopes call sub-scopes, or can they call parents? Bank-switching needs figuring out. And so does initialization.

Scopes#

Scopes are a way to organize entity sets and their corresponding systems. Scopes can be nested. A scope has a lifetime, and its entities are initialized when it is created.

An example scope graph:

  • Main - main scope, contains common systems

    • Title - contains the title screen

    • Game - contains the score, lives, etc.

      • Intro - contains the intro sequence

      • Level - contains the gameplay systems

      • Gameover - contains the gameover sequence

The problem with nested scopes is that we can’t add/remove event handlers without rewriting code. So we’ll need a boolean for “active/inactive scope”, or we need to duplicate code.

Bank Switching#

Code and ROM banks are assigned automagically. Constant data must be kept with the code that uses it. Same deal with critical code. So we need to start by binpacking strongly-bound code/data. Ideally we want bank switching only to occur at the top levels. Maybe we manually assign banks to top-level scopes.

Segments#

We need to be able to define segments, which are contiguous blocks of memory. Segments are used for ROM, RAM, and code. Segments are assigned to banks. Segments are assigned to scopes. Segments are assigned to systems. Segments are assigned to entities. etc. Banks are segments, right?

Comments