sprstk/examples/basic.cpp

129 lines
2.4 KiB
C++

#include <sprstk/sprstk.h>
#include <cmath>
namespace
{
struct Tile
{
struct Type
{
virtual unsigned int layers() const = 0;
bool operator==(const Type& other) const { return this == &other; }
};
Tile();
const Type& type;
unsigned int layers() const { return type.layers(); }
bool operator==(const Tile& other) { return type == other.type; }
};
namespace Tiles
{
struct FloorTileType : public Tile::Type
{
virtual unsigned int layers() const override
{
return 1;
}
} Floor;
struct WallTileType : public Tile::Type
{
virtual unsigned int layers() const override
{
return 31;
}
} Wall;
}
Tile::Tile() :
type(Tiles::Wall)
{}
struct AppState
{
static constexpr int MAP_SIZE = 256;
Tile tiles[MAP_SIZE * MAP_SIZE];
struct
{
int x;
int y;
} player;
Tile& tile_at(int x, int y)
{
static Tile dummy;
x += MAP_SIZE / 2;
y += MAP_SIZE / 2;
if (x < 0 || x >= MAP_SIZE || y < 0 || y >= MAP_SIZE) { return dummy; }
return tiles[x + y * MAP_SIZE];
}
};
void init(sprstk* instance, AppState* userdata)
{
sprstk_set_scale(instance, 8.0f);
sprstk_palette palette;
for (int i = 0; i < 32; i++) { int val = i * 2 + 0x10; val <<= 24; palette.colors[i] = val | 0xFFFFFF; }
sprstk_set_palette(instance, 0, &palette);
for (int i = 0; i < 32; i++) { palette.colors[i] = 0xFF00FF00; }
sprstk_set_palette(instance, 1, &palette);
sprstk_load_sprites(instance, "resources/atlas.png", 8);
}
void update(sprstk* instance, float dt, AppState* userdata)
{
sprstk_clear(instance);
constexpr int SIZE = 4;
for (int i = -SIZE; i <= SIZE; i++)
{
for (int j = -SIZE; j <= SIZE; j++)
{
if (i == 0 && j == 0) { continue; }
Tile& tile = userdata->tile_at(userdata->player.x + i, userdata->player.y + j);
sprstk_put(instance, {
.position = { i, j },
.layers = tile.layers(),
.layer_order_offset = 0,
.palette_index = 0,
.layer_modifiers = { i / 32.0f, j / 32.0f, 1 / 64.0f },
.sprite = { 0, 0 },
});
}
}
sprstk_tile_info info = {};
info.position = { 0, 0 };
info.sprite = { 1, 0 };
info.palette_index = 1;
sprstk_put(instance, info);
}
}
int main()
{
AppState userdata;
sprstk* instance = sprstk_new({ .init = (sprstk_init_fn)init, .update = (sprstk_update_fn)update }, &userdata);
sprstk_run(instance);
sprstk_del(instance);
}