PVR Spritesheets

From dreamcast.wiki
Revision as of 22:51, 10 January 2020 by Unknown user (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Author: Bogglez

About this tutorial

In this tutorial you will learn:

  • Generating a spritesheet from a directory full of single images automatically.
  • Converting the spritesheet into a PVR paletted texture automatically.
  • Loading the spritesheet into the PVR for drawing.
  • Setting up the palette for drawing.
  • Drawing a user interface (with a dynamic health bar).
  • Drawing animated characters.
  • Using the PVR's sprite drawing mode (instead of polygons)

This will be the end result:

Spritesheet tutorial.gif

Required software

Before you can get started, you will need to install two tools.

TexturePacker

The first tool you need is TexturePacker. It packs single images together into one big spritesheet, so you don't need to do this manually. We will make it do it for us using Make.

TexturePacker has some Pro features, but this tutorial limits itself to its free features.

This image should give you an idea about this tools's usefulness:

Spritesheet tutorial texturepacker.png

It will also create text files of the following format:

mage_combat6, 244, 103, 122, 103, 0, 0, 0, 0
mage_combat7, 366, 103, 122, 103, 0, 0, 0, 0
mage_idle0, 0, 206, 79, 93, 0, 0, 0, 0
mage_idle1, 79, 206, 79, 94, 0, 0, 0, 0
mage_idle2, 158, 206, 82, 94, 0, 0, 0, 0
mage_idle3, 240, 206, 85, 94, 0, 0, 0, 0

The example code will parse this information to find out where each sprite within the spritesheet is.

texconv

The next tool you need is texconv by tvspelsfreak.

texconv is an alternative to KOS' vqenc for converting images such as PNG into texture formats supported by the Dreamcast's PVR graphics chip. It doesn't create KMG files, instead it creates its own DTEX format, but provides other nice features. For this tutorial paletted textures are essential.

Another feature that is used is its preview feature. It will basically convert the converted texture back to PNG so you can check the quality of the conversion.

texconv has a dependency on Qt5, so install that first.

On Debian-based systems this will get you running:

sudo apt install qt5-default qtbase5-dev
git clone https://github.com/tvspelsfreak/texconv
cd texconv
qmake
make

You can then use ./texconv. I suggest you put it somewhere in your PATH for convenient global access.

texconv offers the following options (options used in this tutorial are marked as bold):

Usage: ./texconv [options]
Texture formats:
 BUMPMAP  PAL4BPP  ARGB4444  YUV422  ARGB1555  RGB565  PAL8BPP
Options:
 -h, --help                Displays this help.
 -i, --in <filename>       Input file(s). (REQUIRED)
 -o, --out <filename>      Output file. (REQUIRED)
 -f, --format <format>     Texture format. (REQUIRED)
 -m, --mipmap              Generate/allow mipmaps.
 -c, --compress            Output a compressed texture.
 -s, --stride              Output a stride texture.
 -p, --preview <filename>  Generate a texture preview.
 -v, --verbose             Extra printouts.
 -n, --nearest             Use nearest-neighbor filtering for scaling mipmaps.
 -b, --bilinear            Use bilinear filtering for scaling mipmaps.
 --vqcodeusage <filename>  Output an image that visualizes compression code
                           usage.

Downloading and running the example code

After installing the required software, you can download the example source code for this tutorial.

Unzip the archive and open the directory kos_spritesheet_tutorial. You will find the following directory and file structure:

  • assets: Raw art assets that will be turned into spritesheets and converted to Dreamcast PVR textures.
  • build: Contains temporary files. For example build/ui_sheet.png will contain all art assets from assets/spritesheets/ui/*.
  • main.c: Loading, parsing and drawing code.
  • Makefile: Build system. Also calls TexturePacker and texconv to create the spritesheets automatically upong changing anything.
  • readme.txt: License for the used artwork.
  • romdisk: Contains the files that will be available at runtime of the game.

After typing make, you should get the following output:

kos-cc -std=c11 -c main.c -o main.o

Generating spritesheet build/stage1_actors_sheet.png from assets/spritesheets/stage1_actors
TexturePacker --sheet build/stage1_actors_sheet.png \
       --format gideros --data romdisk/stage1_actors_sheet.txt \
       --size-constraints POT --max-width 1024 --max-height 1024 \
       --pack-mode Best --disable-rotation --trim-mode None \
       --trim-sprite-names \
       --algorithm Basic --png-opt-level 0 --extrude 0 --disable-auto-alias \
       assets/spritesheets/stage1_actors
Resulting sprite sheet is 512x1024
Writing sprite sheet to build/stage1_actors_sheet.png
Writing romdisk/stage1_actors_sheet.txt

Converting romdisk/stage1_actors_sheet.dtex < build/stage1_actors_sheet.png
texconv -i build/stage1_actors_sheet.png -o romdisk/stage1_actors_sheet.dtex -f PAL8BPP -p build/stage1_actors_preview.png

Generating spritesheet build/ui_sheet.png from assets/spritesheets/ui
TexturePacker --sheet build/ui_sheet.png \
       --format gideros --data romdisk/ui_sheet.txt \
       --size-constraints POT --max-width 1024 --max-height 1024 \
       --pack-mode Best --disable-rotation --trim-mode None \
       --trim-sprite-names \
       --algorithm Basic --png-opt-level 0 --extrude 0 --disable-auto-alias \
       assets/spritesheets/ui
Resulting sprite sheet is 512x128
Writing sprite sheet to build/ui_sheet.png
Writing romdisk/ui_sheet.txt

Converting romdisk/ui_sheet.dtex < build/ui_sheet.png
texconv -i build/ui_sheet.png -o romdisk/ui_sheet.dtex -f PAL8BPP -p build/ui_preview.png

/opt/toolchains/dc/kos/utils/genromfs/genromfs -f romdisk.img -d romdisk -v
0    rom 56ef0c99         [0xffffffff, 0xffffffff] 37777777777, sz     0, at 0x0     
1    .                    [0x802     , 0x566411  ] 0040755, sz     0, at 0x20    
1    ..                   [0x802     , 0x56639f  ] 0040755, sz     0, at 0x40     [link to 0x20    ]
1    ui_sheet.dtex.pal    [0x802     , 0x5654fa  ] 0100644, sz  1032, at 0x60    
1    ui_sheet.txt         [0x802     , 0x5654f7  ] 0100644, sz   392, at 0x4a0   
1    stage1_actors_sheet.dtex [0x802     , 0x5654f3  ] 0100644, sz 524304, at 0x650   
1    stage1_actors_sheet.dtex.pal [0x802     , 0x5654f4  ] 0100644, sz   104, at 0x80690 
1    stage1_actors_sheet.txt [0x802     , 0x5654f2  ] 0100644, sz  1818, at 0x80730 
1    ui_sheet.dtex        [0x802     , 0x5654f8  ] 0100644, sz 65552, at 0x80e80 
/opt/toolchains/dc/kos/utils/bin2o/bin2o romdisk.img romdisk romdisk.o

kos-cc -o spritesheet.elf main.o romdisk.o -lkmg -lkosutils -lm

The executable will be called spritesheet.elf and can be run in an emulator or on your Dreamcast.

Explanation

The Makefile and main.c are heavily commented, so I will only refer to the most important bits here.

Makefile

If any of these rules confuse you, compare them to the output of the make command above and things should become clear.

The Makefile target spritesheet.elf (the executable of the game) depends on romdisk.o, which depends on romdisk.img.

All the converted spritesheets, their palettes, and the sprite geometry info will be stored in this romdisk, therefore romdisk.img must depend on those files. We don't care about the raw art assets, however, since they're not used at runtime.

To achieve this in Make, the name of all spritesheets needs to be generated first, i.e. assets/spritesheets/foo/*.png assets/spritesheets/bar/*.png needs to turn into foo bar

SPRITESHEET_NAMES := $(notdir $(wildcard assets/spritesheets/*))

Now romdisk.img should depend on romdisk/foo_sheet.dtex and romdisk/bar_sheet.dtex. But texconv will save the palette file separately, so we add romdisk/foo_sheet.dtex.pal etc.

SPRITESHEET_RESULT_FILES := $(patsubst %,romdisk/%_sheet.dtex,$(SPRITESHEET_NAMES))
romdisk.img: $(SPRITESHEET_RESULT_FILES) $(addsuffix .pal,$(SPRITESHEET_RESULT_FILES))
	$(KOS_GENROMFS) -f romdisk.img -d romdisk -v

Next Make needs to know how to generate the dtex and dtex.pal files from the corresponding PNG using texconv.

romdisk/%_sheet.dtex romdisk/%_sheet.dtex.pal: build/%_sheet.png
	$(info Converting $@ < $<)
	texconv -i $< -o $@ -f PAL8BPP -p build/$*_preview.png

This rule requires that the sprites have been assembled as build/foo_sheet.png before (using TexturePacker), so that file becomes a dependency.

Notice how the texture format is set to PAL8BPP, allowing for 256 different colors in the palette. PAL4BPP is also a possibility. texconv assumes 32 bit colors in the palette. It implicitly creates the .dtex.pal file.

Also take a look at the build/foo_preview.png file to see whether you suffered quality loss during the conversion. This will happen if your input image has more than 256 colors in this case.

Lastly TexturePacker is called to turn all images in the directory assets/spritesheets/foo/ into build/foo_sheet.png and generate romdisk/foo_sheet.txt with the sprite geometry information. The txt file is stored in romdisk/ because we will parse it during runtime in order to draw the sprites. build/foo_sheet.png is just the temporary file to create the Dreamcast PVR texture romdisk/foo_sheet.dtex (and .pal).

TexturePacker is instructed to create power-of-two textures (e.g. 64x256) of maximum dimensions 1024x1024, because of the PVR graphics chip's limitations.

The options in the last line are necessary to disable pro-version features (otherwise TexturePacker will turn some sprites red).

build/%_sheet.png: assets/spritesheets/%
	$(info Generating spritesheet $@ from $^)
	TexturePacker --sheet $@ \
		--format gideros --data romdisk/$*_sheet.txt \
		--size-constraints POT --max-width 1024 --max-height 1024 \
		--pack-mode Best --disable-rotation --trim-mode None \
		--trim-sprite-names \
		--algorithm Basic --png-opt-level 0 --extrude 0 --disable-auto-alias \
		$^

The code

I'll explain the code top-down, to give you a high level view. So assume that the mentioned helper functions have already been written, they will be explained later.

The main loop

The main loop is very basic:

struct spritesheet stage1_actors_sheet, ui_sheet;
int main(int argc, char *argv[]) {
	int result = 0;
	if(init()) {
		puts("Cannot init");
		result = 1;
		goto cleanup;
	}
	for(;;) {
		draw();
	}
cleanup:
	spritesheet_free(&stage1_actors_sheet);
	spritesheet_free(&ui_sheet);
	return result;
}

Two spritesheets are loaded within init() as global variables. Then draw() will draw some sprites on the screen repeatedly. In the end some clean-up code is called (here only if init() fails).

The drawing routine

This is the draw() function.

First it needs to wait for the PVR graphics chip to be ready for drawing:

static void draw() {
	pvr_wait_ready(); /* Await v-blank */
	pvr_scene_begin();

Next, the PVR is told to expect a punchthru polygon list. This will allow you to send geometry that can have translucency per pixel (visible or not, not half, unlike transparency).

If you want to send opaque or transparent polygons too, you need to do that before this code. This function implicitly closes the preceding polygon lists for the duration of this frame.

	pvr_list_begin(PVR_LIST_PT_POLY);

Now we set up the palettes for this frame. We tell the PVR chip what colors the textures refer to (try mixing them up for fun!). Here, draw() uses my helper function setup_palette():

void setup_palette(uint32_t const * colors, uint16_t count, uint8_t palette_number);
	// in draw()
	uint8_t const ui_palette_number = 0;
	uint8_t const stage1_actors_palette_number = 1;
	setup_palette(ui_sheet.palette, ui_sheet.color_count, ui_palette_number);
	setup_palette(stage1_actors_sheet.palette, stage1_actors_sheet.color_count, stage1_actors_palette_number);

Now the actual sprite drawing happens. We draw a little user interface and some animated characters using my helper function draw_sprite():

void draw_sprite(struct spritesheet const * const sheet, char const * const name, float x, float y, uint8_t palette_number);

The arguments are

  • a spritesheet struct with parsed information,
  • the name of the sprite inside of it that should be drawn (e.g. healthbar_left in romdisk/ui_sheet.txt)
  • x, y coordinates on screen (y goes downwards)
  • The number of the palette to use. Palettes on the Dreamcast persist throughout a frame, so you cannot just switch the palette after drawing a texture. If you want to use multiple paletted textures with different palettes, you will have to put their palette into a different part of the global palette. The global palette has 1024 entries, 8-bit paletted textures use 256 entries each.

The KOS function timer_ms_gettime64() is used for animation of the characters depending on how much time has elapsed.

	/* Draw UI */
	draw_sprite(&ui_sheet, "stage_announce", 174, 100, ui_palette_number);

	/* Health bar background */
	draw_sprite(&ui_sheet, "barbg_left",  10, 10, 0);
	for(int x = 0; x < 100; ++x)
		draw_sprite(&ui_sheet, "barbg_mid", 15+x, 10, 0);
	draw_sprite(&ui_sheet, "barbg_right", 115, 10, 0);
	/* Draw animated health bar inside */
	float const s = sin(0.001f * timer_ms_gettime64());
	uint8_t health_count = 15 + 70 * s*s;
	draw_sprite(&ui_sheet, "healthbar_left", 16, 18, 0);
	for(int x = 0; x < health_count; ++x)
		draw_sprite(&ui_sheet, "healthbar_mid", 16+5 + x, 18, 0);
	draw_sprite(&ui_sheet, "healthbar_right",   16+5 + health_count, 18, 0);
	/* Draw animated enemies */
	uint8_t sprite_number = (unsigned)(0.01f * timer_ms_gettime64()) % 8;
	char sprite_name[32];
	snprintf(sprite_name, sizeof(sprite_name), "mage_combat%u", sprite_number);
	sprite_name[31] = 0;
	draw_sprite(&stage1_actors_sheet, sprite_name, 100, 300, stage1_actors_palette_number);

	snprintf(sprite_name, sizeof(sprite_name), "mage_shadowform%u", sprite_number);
	sprite_name[31] = 0;
	draw_sprite(&stage1_actors_sheet, sprite_name, 250, 300, stage1_actors_palette_number);

	snprintf(sprite_name, sizeof(sprite_name), "mage_idle%u", sprite_number);
	sprite_name[31] = 0;
	draw_sprite(&stage1_actors_sheet, sprite_name, 350, 300, stage1_actors_palette_number);

After this the scene is drawn, so the PVR needs to be told to present the result:

	pvr_scene_finish();
}

Spritesheet Loader

The loading code can be found in

int spritesheet_load(
	struct spritesheet * const spritesheet, /* Where to store the loaded information */
	char const * const image_filename,      /* foo.dtex     */
	char const * const palette_filename,    /* foo.dtex.pal */
	char const * const sheet_filename);     /* foo.txt      */

This function reads the foo.dtex texture and loads it into video memory. To allocate video memory you should use the KOS function pvr_mem_malloc(). It will also load the corresponding palette file into memory. The DTEX and DPAL file formats are documented in texconv's readme.

Lastly this function parses the sprite geometry information from the accompanying .txt file that TexturePacker created. The amount of lines in the file tells us the amount of sprites in the spritesheet.

It is parsed in the following way:

	struct sprite * sprite = sprites;
	for(uint16_t i = 0; i < sprite_count && !feof(sheet_file); ++i) {
		int scanned = fscanf(sheet_file, "%[^,], %hu, %hu, %hu, %hu, 0, 0, 0, 0\n", sprite->name, &sprite->x, &sprite->y, &sprite->width, &sprite->height);
		printf("scanned %d parameters: %s %d %d %d %d\n", scanned, sprite->name, sprite->x, sprite->y, sprite->width, sprite->height);
		if(scanned != 5) {
			result = 10;
			goto cleanup;
		}
		++sprite;
	}

%[^,] is a quite underused format in scanf. It means a string without ,.

So all this does is read a name that can be used in draw_sprite(), as well as x and y offset and width and height of the sprite.

Speciyfing the Palette

This is done in setup_palette() and is very simple. Just keep in mind that multiple textures' palettes share the global palette memory. So some housekeeping needs to be performed to avoid overwriting palette memory that's used by other textures. You can also give a texture a different palette to create some amazing palette animations.

We leave the first 256 entries to what we'll call palette 0 and the next 256 to palette 1.

void setup_palette(uint32_t const * colors, uint16_t count, uint8_t palette_number) {
	pvr_set_pal_format(PVR_PAL_ARGB8888);
	for(uint16_t i = 0; i < count; ++i)
		pvr_set_pal_entry(i + 256 * palette_number, colors[i]);
}

Drawing sprites

This is done in draw_sprite() and is used as seen before in draw().

void draw_sprite(struct spritesheet const * const sheet, char const * const name, float x, float y, uint8_t palette_number) {

Remember that the palette must have been set up before, so this function is told which part of the global palette memory is being used.

First we look up the information about the particular sprite called name we are tasked to draw. You might want to do this using a hashmap, I did a simple array walk.

	/* Find sprite by name */
	uint16_t const sprite_count = sheet->sprite_count;
	struct sprite const * const sprites = sheet->sprites;
	struct sprite const * sprite = NULL;
	for(uint16_t i = 0; i < sprite_count; ++i) {
		if(!strcmp(sprites[i].name, name)) {
			sprite = &sprites[i];
			break;
		}
	}

	if(sprite == NULL) {
		printf("There is no sprite named '%s' in this spritesheet.\n", name);
		return;
	}

This gives us a pointer to a struct of the following form:

struct sprite {
	char name[32];
	uint16_t x, y, width, height;
};

We'll be using this information to calculate the proper UV-coordinates. The whole texture of the entire spritesheet has coordinates on the horizontal axis in the range U=[0.0, 1.0] and the vertical axis V=[0.0, 1.0]. Therefore we can determine the UV-coordinates of this particular tile by the following calculation:

	float x0 = x; /* function arguments: where to draw the sprite on screen */
	float y0 = y;
	float x1 = x + sprite->width;
	float y1 = y + sprite->height;
	float z = 1;

	float u0 =  sprite->x                   / (float)sheet->width; /* Relative coordinates, [0.0,1.0] range */
	float v0 =  sprite->y                   / (float)sheet->height;
	float u1 = (sprite->x + sprite->width)  / (float)sheet->width;
	float v1 = (sprite->y + sprite->height) / (float)sheet->height;

As a little extra, I will not use polygons to draw the sprites. We'll be using the Dreamcast's special sprite drawing mode. In sprite drawing mode, you specify the minimum and maximum values of the rectangle and its texture coordinates, instead of specifying each point. This works because sprites cannot be rotated. These sprites also cannot have a color. This makes them super efficient (for bullet hell games etc.), but you will need to use 3D polygons for 3D effects.

Define which palette, texture and polyon list are to be used (punchthru for alpha masking here). Filtering is disabled because sprites are displayed 1:1.

	pvr_sprite_cxt_t sprite_context; /* This is just a convenience function for creating the following. */
	pvr_sprite_hdr_t sprite_header;  /* This is sent to the PVR before geometry is sent. */
	pvr_sprite_cxt_txr(&sprite_context, PVR_LIST_PT_POLY, PVR_TXRFMT_PAL8BPP | PVR_TXRFMT_8BPP_PAL(palette_number), sheet->width, sheet->height, sheet->texture, PVR_FILTER_NONE);
	pvr_sprite_compile(&sprite_header, &sprite_context);

	pvr_prim(&sprite_header, sizeof(sprite_header)); /* Send header to PVR */

	pvr_sprite_txr_t vert = {
		.flags = PVR_CMD_VERTEX_EOL,
		.ax = x0, .ay = y0, .az = z,
 		.bx = x1, .by = y0, .bz = z,
 		.cx = x1, .cy = y1, .cz = z,
 		.dx = x0, .dy = y1,
		.auv = PVR_PACK_16BIT_UV(u0, v0),
		.buv = PVR_PACK_16BIT_UV(u1, v0),
		.cuv = PVR_PACK_16BIT_UV(u1, v1),
	};
	pvr_prim(&vert, sizeof(vert));
}

As you see it took only 2 calls to pvr_prim() to send a sprite. That said, pvr_prim() is not an efficient way of sending geometry to the PVR graphics chip.

If you want to make a bullet hell game with a serious amount of sprites, you should look into store queues to transfer whole arrays of sprites. The header only needs to be set once before drawing sprites too.

PVR Sprite Draw Mode Caveat

While the triangle strip drawing mode of the PVR uses 32 bit floating point values for the texture coordinates, the sprite draw mode requires you to use 16 bit floating point values. If you don't position your sprites carefully, you will therefore see the following problem (note the distortion in the right character's animation):

Spritesheet tutorial demo sprite.gif

To fix this you will either need to position the sprites so that 16 bit floats can represent the texture coordinate properly, or you can use polygon drawing mode instead. I implemented this in the tutorial as well and polygon drawing mode is used by default.