A game engine for top-down 2D RPG games.
rpg
game-engine
raylib
c99
1#include <keraforge.h>
2#include <raylib.h>
3#include <stdlib.h>
4#include <string.h>
5#include <math.h>
6
7struct _kf_tiles kf_tiles = {0};
8
9struct kf_world *kf_world_new(u32 width, u32 height, kf_tileid_t fill)
10{
11 const size_t len = sizeof(kf_tileid_t) * width * height;
12 struct kf_world *world = malloc(sizeof(struct kf_world) + len);
13 world->revision = 0;
14 world->width = width;
15 world->height = height;
16 memset(world->map, fill, len);
17 return world;
18}
19
20size_t kf_world_getsize(struct kf_world *world)
21{
22 return sizeof(struct kf_world) + sizeof(kf_tileid_t)*world->width*world->height;
23}
24
25kf_tileid_t *kf_world_gettile(struct kf_world *world, u32 x, u32 y)
26{
27 return &world->map[y*world->width + x];
28}
29
30void kf_world_draw(struct kf_world *world, Camera2D camera)
31{
32 const Vector2 start = GetScreenToWorld2D((Vector2){0, 0}, camera);
33 const Vector2 end = GetScreenToWorld2D((Vector2){GetScreenWidth(), GetScreenHeight()}, camera);
34 const u32 sx = fmax(0, floorf(start.x / KF_TILE_SIZE_PX));
35 const u32 sy = fmax(0, floorf(start.y / KF_TILE_SIZE_PX));
36 const u32 ex = fmin(world->width, ceilf(end.x / KF_TILE_SIZE_PX));
37 const u32 ey = fmin(world->height, ceilf(end.y / KF_TILE_SIZE_PX));
38 const size_t down = world->width - ex + sx; /* number of indexes to add to reach the next tile down */
39 kf_tileid_t *tile = kf_world_gettile(world, sx, sy);
40 u32 x;
41 for (u32 y = sy ; y < ey ; y++)
42 {
43 for (x = sx ; x < ex ; x++)
44 {
45 DrawRectangle(
46 (int)x * KF_TILE_SIZE_PX,
47 (int)y * KF_TILE_SIZE_PX,
48 KF_TILE_SIZE_PX,
49 KF_TILE_SIZE_PX,
50 kf_tiles.color[*tile]
51 );
52 tile++; /* shift tile pointer to the right */
53 }
54 tile += down; /* shift tile pointer down */
55 }
56}