This tutorial covers SNES sprites (OBJ layer) including OAM management and animation.
SNES Sprite Basics
The OBJ layer shows up to 128 sprites of 16 colours, each one of two sizes chosen for all sprites at once, with palettes in the upper half of CGRAM. The size combinations, the per-line limits and the palettes are in The PPU: sprites; each sprite's four bytes and two bits of OAM are in SNES OAM (Object Attribute Memory).
Using OpenSNES Sprite Functions
Initialize OAM
}
int main(void)
Definition main.c:73
void consoleInit(void)
Initialize SNES hardware.
void setScreenOn(void)
Enable screen display.
#define REG_TM
Main screen designation (W).
Definition registers.h:187
#define TM_OBJ
Definition registers.h:447
OpenSNES common-case master header.
void oamInit(u16 size, u16 name_base)
Initialize the sprite (OAM) system.
#define OAM_DEFAULT_SIZE
Default sprite size mode — small=8×8 / large=16×16.
Definition sprite.h:211
#define OAM_DEFAULT_TILE_BASE
Default sprite tile base — 0 = tiles at VRAM word $0000.
Definition sprite.h:213
Setting a Sprite
oamSet(0, 100, 80, 0, 0, 0, 0);
oamSet(1, 120, 80, 0, 1, 0, 0);
void oamSet(u16 id, u16 x, u16 y, u16 tile, u16 palette, u16 priority, u16 flags)
Set sprite properties.
To move a sprite that is already set, change only its position: oamSetXY(id, x, y), or oamSetX(id, x) when only X changes (a horizontal shooter's scroll, a sprite sliding along a rail). Tile, palette and flags stay as oamSet() left them.
Updating OAM
while (1) {
}
static s16 player_y
Kit's hitbox, top-left corner, Y.
Definition main.c:78
static s16 player_x
Kit's hitbox, top-left corner, in screen coordinates.
Definition main.c:76
void WaitForVBlank(void)
Wait for next VBlank period.
void oamUpdate(void)
Copy OAM buffer to hardware.
Hiding Sprites
void oamClear(void)
Clear all sprites.
void oamHide(u16 id)
Park a sprite off screen.
Re-initialising is not how you hide sprites — oamInit() reconfigures OBJSEL. Call oamHide(id) per sprite, or oamClear() to hide them all.
The name_base argument is a page number, not a VRAM address
oamInit(size, name_base) takes name_base as a page number 0-7, not a VRAM address. Each page is $2000 word addresses (16 KB), so tiles DMA'd to word $4000 need base 2. The value is masked to 3 bits: passing a VRAM address — the natural mistake, since every other VRAM parameter in the SDK takes one — silently yields a wrong base (0x6000 & 7 is 0) and the sprites render whatever tiles sit at word 0, with no diagnostic. Use the OBJ_NAME_BASE(addr) macro to convert, so the intent survives the call:
#define OBJ_NAME_BASE(vram_word_addr)
Convert a VRAM word address into an OBJ name base (0-7).
Definition sprite.h:257
#define OBJ_SIZE8_L16
Sprite size indices (for oamInit, oamInitGfxSet).
Definition sprite.h:52
Loading Sprite Tiles
Sprite tiles go in VRAM (location set by REG_OBJSEL):
const u8 sprite_tile[32] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
void load_sprite_tiles(void) {
for (
i = 0;
i < 32;
i += 2) {
}
}
static u8 i
Definition main.c:144
#define REG_VMADDH
VRAM address high (W).
Definition registers.h:124
#define REG_VMAIN
VRAM address increment mode (W).
Definition registers.h:112
#define REG_VMADDL
VRAM address low (W).
Definition registers.h:121
#define REG_VMDATAL
VRAM data write low (W).
Definition registers.h:127
#define REG_OBJSEL
Object (sprite) size and base (W).
Definition registers.h:52
#define REG_VMDATAH
VRAM data write high (W).
Definition registers.h:130
unsigned short u16
16-bit unsigned integer (0 to 65535)
Definition types.h:53
unsigned char u8
8-bit unsigned integer (0 to 255)
Definition types.h:47
Converting a sheet: size must match the sprite size
A 16x16 OBJ does not read four consecutive tiles. It reads n, n+1, n+16, n+17 — the second row comes from 16 tiles later, because the hardware treats the sheet as 16 tiles (128 px) wide. Same idea for 32x32 (n, n+1, n+2, n+3, n+16 …) and 64x64.
opensnes-sprite — sheets, metasprites and Aseprite clips produces exactly that layout when you tell it the sprite size, in the settings file beside the sheet:
# res/sprite32.png.toml (examples/sprites/simple_sprite)
tool = "opensnes-sprite"
[sheet]
size = 32 # a sheet of 32x32 sprites (8, 16, 32 or 64)
colors = 16 # one OBJ palette
The build runs opensnes-sprite sheet on it and writes sprite32.pic, sprite32.pal and sprite32.inc, which declares sprite32_tiles, sprite32_pal (each with _end) and a GfxAsset:
#include "res/sprite32.inc"
dmaCopyVram(sprite32_tiles, 0x2100, sprite32_tiles_end - sprite32_tiles);
void dmaCopyVram(const u8 *source, u16 vramAddr, u16 size)
Copy data to VRAM (PVSnesLib compatible).
void dmaCopyCGram(const u8 *source, u16 startColor, u16 size)
Copy palette data to CGRAM (PVSnesLib compatible).
#define PALETTE_16_SIZE
Size of one 16-color palette in bytes (16 colors x 2 bytes per BGR555).
Definition sprite.h:84
#define OBJ_CGRAM_BASE
CGRAM base offset for sprite palettes (sprites use colors 128-255).
Definition sprite.h:78
With size = 16 the converter cuts the image into 16x16 blocks and emits each one as the four tiles the hardware expects, whatever the sheet's width or height.
The trap: converting a sheet of 16x16 frames with size = 8. It succeeds, produces the right number of tiles, and the sprite renders — wrong. The top half is one frame and the bottom half is whatever tile happened to land 16 slots later, which depends on the PNG's width. A sheet 16 tiles wide happens to work; make it 18 tiles wide by adding a frame and every sprite in the game breaks at once, with no diagnostic.
The rule is one line: size is the sprite's size, not the tile size.
The converter cannot catch the mistake — with size = 8 it has no way to know you meant 16x16 sprites. It does warn when the image is not an exact multiple of the block size, since the last row or column of blocks would then be built from pixels that are not in the image. opensnes-sprite inspect res/hero.png --size 16 prints the block count and the VRAM cost before you convert.
Sprite Palettes
Sprite palettes start at CGRAM colour 128 (OBJ_CGRAM_BASE):
void load_sprite_palette(void) {
}
#define REG_CGADD
CGRAM address (W).
Definition registers.h:154
#define REG_CGDATA
CGRAM data write (W).
Definition registers.h:157
Animation
Frame-based Animation
Cycling a sprite's tile on a timer, and the anim module that does it from data, are in Animation Tutorial.
Movement with Animation
void update_player(
u16 pad) {
facing_right = 0;
}
facing_right = 1;
}
}
#define OBJ_FLIPX
Metasprite horizontal flip flag.
Definition sprite.h:666
Sprite Sizes
oamInit(size, name_base) sets OBJSEL: size is one of OBJ_SIZE8_L16 … OBJ_SIZE32_L64, the small and large size every sprite chooses between, and oamSetSize(id, 1) gives a sprite the large one. The table of size combinations is in The PPU: sprites.
#define OBJ_SIZE16_L32
Definition sprite.h:55
Example: Two Players
examples/input/controller reads both pads (padHeld(0), padHeld(1)); give each its own OAM entry and palette to move two sprites independently.
A scrolling game's sprites: oamPlaceWorld
A game whose background scrolls keeps its actors in world coordinates, and every frame has to turn each one into an OAM entry: subtract the camera, decide whether it is on screen, write it or hide it. Written as a loop in C around oamSet() and oamHide(), that is where the frame goes. oamPlaceWorld() is that loop, once, in assembly:
#define ACTORS 18
static s16 actor_x[ACTORS], actor_y[ACTORS];
static u8 actor_tile[ACTORS], actor_attr[ACTORS];
static u8 actor_seen[ACTORS];
actor_x, actor_y, actor_tile, actor_attr, actor_seen,
0,
ACTORS,
32
};
for (
i = 0;
i < ACTORS;
i++) {
if (!actor_seen[
i])
continue;
}
signed short s16
16-bit signed integer (-32768 to 32767)
Definition types.h:50
void oamSetSize(u16 id, u16 large)
Set sprite size (large/small).
void oamPlaceWorld(const OamWorldBatch *batch, u16 cam_x, u16 cam_y)
Place a batch of world-space sprites: camera, culling, OAM, in one call.
u16 cam_y
Definition main.c:91
u16 cam_x
Probe oracles: the camera, the shards placed this frame, the resident in the front slot.
Definition main.c:90
A batch of sprites in world coordinates, for oamPlaceWorld().
Definition sprite.h:408
What it does for each sprite, and what it leaves to you:
- Culling is by the sprite's size, on both axes. A 32x32 sprite at x = -31 is drawn, with its ninth x bit set; one pixel further it is hidden, the way oamHide() hides.
- cam_y is the y you give bgSetScroll(). A sprite and the background it stands on take the same camera value (see OAM: a sprite's y needs no correction).
- Structure of arrays. One array per property is what this CPU indexes cheaply, and each array can live where it suits: positions in RAM, tile numbers in a const table if they never change.
- One size per batch, unless you give big. A game with 32x32 heroes and 16x16 coins that do not overlap makes two calls; the second batch can point into the same arrays (actor_x + 18). When the two sizes must share one drawing order, see "Two sizes in one order" below.
- A sprite the game wants hidden although it is on screen (its graphics are not loaded yet, say) is one oamHide(id) after the call.
Measured (devtools/libbench, rows worldc and world: 19 sprites, 13 on screen, a moving camera; the table in docs/PERF.md): 23,767 master cycles a frame with oamPlaceWorld(), 53,409 for the same loop in C writing oamMemory[] directly — the cheapest way to write it in C.
Sorted by depth: order
Of two sprites, the one with the lower OAM id is drawn in front, whatever their priority bits: those only place a sprite against the backgrounds (SNESdev wiki, Sprites: "sprites
with lower index within OAM always appear on top of sprites with a higher
index"; the order array below assumes priority rotation is off, which is the library's setting). A game seen from above sorts its actors by y every frame so that the one lower on the screen hides the one behind it — and the sorted order is an order of OAM slots, while everything else in the game (state, animation, target) is indexed by the actor. Without help the game keeps a second, sorted copy of x, y, tile and attr and refills it each frame.
Give the batch an order array instead: slot first_id + i shows actor order[i]. The arrays stay indexed by the actor and never move; the sort permutes one byte per actor.
static u8 by_depth[ACTORS];
actor_x, actor_y, actor_tile, actor_attr, actor_seen,
0, ACTORS, 32,
by_depth
};
sortByDepth(by_depth);
- visible[] stays indexed by the actor: actor_seen[n] still answers "is actor n on screen", whichever slot shows it.
- The size bit belongs to the slot, as before: every slot of a batch has the batch's size, so a sort changes nothing there (with big, below, the call writes it from the actor the slot shows).
- An order byte that is not under count hides its slot and reads no array.
- Cost (rows world and worldo): about 240 master cycles more a sprite than the unsorted call, 36,400 a frame for the same 19 sprites; the C loop with the same indirection costs 136,700 with PVSnesLib's compiler.
Two sizes in one order: big
A sort by depth mixes sizes: a 16x16 shot passes in front of or behind a 32x32 character depending on where each stands. Two batches of one size each would put all the small sprites in OAM before (or after) all the large ones, which is not the sorted order. Give the batch a big array, one byte per actor (indexed by the actor, like tile): 0 is small, size pixels; any other value is large, size_big pixels — the two sizes chosen with oamInit() (OBJ_SIZE16_L32 below).
static u8 actor_big[ACTORS];
actor_x, actor_y, actor_tile, actor_attr, actor_seen,
0, ACTORS,
16,
by_depth,
actor_big,
32
};
- Each actor is culled at its own size: a large one at x = -31 is drawn, a small one there is hidden.
- The call writes the size bit of every slot of the batch: set for a placed large actor, clear for a placed small one and for every hidden slot (a hidden entry is small). Do not call oamSetSize() for those slots. Without big, the size bits are not touched, as before.
- A batch written without the field (8 or 9 initialisers) has big 0: one size, the call costs what it did.
- The screen test is the screen's, 256 x 224. A play area smaller than the screen (a status bar under it) is not a bound the call knows: a sprite over the bar is placed, and a game that must not show or count it hides it after the call with oamHide(), the slot read from the game's own order.
- Cost (devtools/placebench, rows mix, SlowROM): about 1,090 master cycles a placed small sprite, 1,200 a large one and 770 a hidden one in a large batch without order (the one-size call: 939 and 588), about 100 more each with order; about 6,800 a call of one sprite (a batch with big always takes the path of the large batches: give a lone sprite its own one-size batch). The one-size call pays about 110 master cycles a call for the test of big, nothing a sprite.
Many alike objects: oamSetBatch
Bullets, particles, a swarm: N objects that move the same way and are drawn the same way. The movement is the game's code; the emission, four OAM bytes and a ninth x bit a sprite, is a loop that oamSetBatch() runs in assembly over the game's arrays. It is an opt-in module: add sprite_batch to LIB_MODULES.
static u16 bx
Definition main.c:147
static u16 by
Definition main.c:147
void oamSetBatch(const OamBatch *batch)
Write the OAM entries of N sprites from parallel arrays, in one call.
A batch of sprites in screen coordinates, for oamSetBatch().
Definition sprite.h:1005
tile and attr are optional: objects that never change picture are set once with oamSet() and passed as 0, and only x, y and the ninth x bit are written. Give tile, attr, or both, for what changes. The size bit is never touched (oamSetSize()).
It pays when the arrays already exist: a game that moves and masks each object in its own loop, and would build the x and y arrays only to hand them over, measured 1.4 % worse than writing the entries in that loop.
Cost, measured on luna with 32 and 64 identical objects (slow ROM; the update loop of the game, about 1,870 master cycles an object, is not in these figures): x and y only, 741 master cycles an object against 2,256 for oamSetXYFast() in a loop; with tile and attribute, 1,098 against 3,250 for oamSetFast(). With the update loop of the scene added, 4,112 to 2,602 and 5,099 to 2,959 master cycles an object.
Performance Tips
- Minimize oamUpdate() calls - Only call once per frame
- Use sprite pooling - Reuse sprite slots instead of creating/destroying
- Check sprite limits - the per-line limits are in The PPU: sprites
- Batch similar sprites - Group sprites using same tiles/palettes
Next Steps