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