Compare commits

...

10 Commits

Author SHA1 Message Date
49f45423d1 Port to entt 2025-06-09 10:49:59 +02:00
a69fc7d2b0 Sound effects 2025-06-01 18:44:19 +02:00
f9336dcbd8 Stop game at 0 2025-06-01 12:52:06 +02:00
d019c761bf Add render module 2025-06-01 12:44:38 +02:00
e2a2d6efdf Refactor audio system 2025-06-01 12:34:45 +02:00
81f4d6157e Use C++ random device 2025-06-01 12:34:45 +02:00
ae5733ae62 Spawning system refactor 2025-06-01 11:54:46 +02:00
6eb5046523 Add spiders 2025-06-01 11:19:42 +02:00
b18543e04e Fall faster fruits 2025-06-01 11:19:24 +02:00
0c99e625ba Add score text 2025-06-01 11:19:24 +02:00
20 changed files with 522 additions and 253 deletions

View File

@@ -6,16 +6,42 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Option to switch real platform vs. SDL implementation...
include(FetchContent)
FetchContent_Declare(
SDL3
URL https://github.com/libsdl-org/SDL/releases/download/release-3.2.14/SDL3-3.2.14.tar.gz
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(SDL3)
FetchContent_Declare(
SDL3_ttf
URL https://github.com/libsdl-org/SDL_ttf/releases/download/release-3.2.2/SDL3_ttf-3.2.2.tar.gz
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(SDL3_ttf)
FetchContent_Declare(
entt
URL https://github.com/skypjack/entt/archive/refs/tags/v3.15.0.tar.gz
OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(entt)
find_package(entt CONFIG REQUIRED)
find_package(SDL3 CONFIG REQUIRED)
find_package(flecs CONFIG REQUIRED)
find_package(SDL3_ttf CONFIG REQUIRED)
find_package(spdlog CONFIG REQUIRED)
add_executable(HansTheGatherer
src/main.cpp
src/audio.cpp
src/assets.cpp
src/level.cpp
src/physics.cpp
src/render.cpp
)
target_link_libraries(HansTheGatherer SDL3::SDL3 flecs::flecs spdlog::spdlog)
target_link_libraries(HansTheGatherer SDL3::SDL3 SDL3_ttf::SDL3_ttf EnTT spdlog::spdlog)
set_property(TARGET HansTheGatherer PROPERTY CXX_STANDARD 20)

2
NOTICE
View File

@@ -6,3 +6,5 @@ Assets used by this project:
URL: https://trashboat93.itch.io/jungle-background-parallax
- "Jamaican Sunrise - Reggae" by DavidKBD
URL: https://davidkbd.itch.io/tropical-dreams-spring-and-summer-music-pack
- "SPIDER ENEMY PIXEL ART" by camacebra
URL: https://camacebra.itch.io/spider-pixel-art-pack-16x16

Binary file not shown.

BIN
assets/images/spiders.bmp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

BIN
assets/sounds/hit.wav Normal file

Binary file not shown.

BIN
assets/sounds/pickup.wav Normal file

Binary file not shown.

View File

@@ -13,6 +13,10 @@ static constexpr uint8_t FRUITS_DATA[] = {
#embed "../assets/images/fruits.bmp"
};
static constexpr uint8_t SPIDERS_DATA[] = {
#embed "../assets/images/spiders.bmp"
};
static constexpr uint8_t BASKET_DATA[] = {
#embed "../assets/images/basket.bmp"
};
@@ -21,6 +25,18 @@ static constexpr uint8_t BACKGROUND_MUSIC_DATA[] = {
#embed "../assets/sounds/JamaicanSunrise.wav"
};
static constexpr uint8_t PICKUP_SOUND_DATA[] = {
#embed "../assets/sounds/pickup.wav"
};
static constexpr uint8_t HIT_SOUND_DATA[] = {
#embed "../assets/sounds/hit.wav"
};
static constexpr uint8_t DEFAULT_FONT_DATA[] = {
#embed "../assets/fonts/OpenTTD-Sans.ttf"
};
SDL_Texture* load_texture(uint8_t const* data, size_t size, SDL_Renderer* renderer)
{
auto* iostream = SDL_IOFromConstMem(data, size);
@@ -53,9 +69,21 @@ AudioAsset load_audio(uint8_t const* data, size_t size)
return audio_asset;
}
AssetModule::AssetModule(flecs::world& world)
FontAsset load_font(uint8_t const* data, size_t size)
{
auto* renderer = world.get<SdlHandles>()->renderer;
FontAsset font_asset;
auto* iostream = SDL_IOFromConstMem(data, size);
auto* ttf = TTF_OpenFontIO(iostream, false, 20);
font_asset.font = ttf;
return font_asset;
}
AssetModule::AssetModule(entt::registry& registry)
{
auto renderer = registry.ctx().get<SdlHandles>().renderer;
auto* background = load_texture(BACKGROUND_DATA, sizeof(BACKGROUND_DATA), renderer);
TextureAtlasLayout background_layout = {.width = 866, .height = 510, .rows = 1, .columns = 1};
@@ -63,14 +91,25 @@ AssetModule::AssetModule(flecs::world& world)
auto* fruits = load_texture(FRUITS_DATA, sizeof(FRUITS_DATA), renderer);
TextureAtlasLayout fruits_layout = {.width = 16, .height = 16, .rows = 6, .columns = 38};
auto* spiders = load_texture(SPIDERS_DATA, sizeof(SPIDERS_DATA), renderer);
TextureAtlasLayout spiders_layout = {.width = 16, .height = 16, .rows = 2, .columns = 4};
auto* basket = load_texture(BASKET_DATA, sizeof(BASKET_DATA), renderer);
TextureAtlasLayout basket_layout = {.width = 16, .height = 16, .rows = 1, .columns = 1};
world.set<TextureAssets>(TextureAssets{
registry.ctx().emplace<TextureAssets>(TextureAssets{
.background = Texture{.sdl_texture = background, .texture_atlas_layout = background_layout},
.fruits = Texture{.sdl_texture = fruits, .texture_atlas_layout = fruits_layout},
.spiders = Texture{.sdl_texture = spiders, .texture_atlas_layout = spiders_layout},
.basket = Texture{.sdl_texture = basket, .texture_atlas_layout = basket_layout}});
auto background_music = load_audio(BACKGROUND_MUSIC_DATA, sizeof(BACKGROUND_MUSIC_DATA));
world.set<AudioAssets>(AudioAssets{.background_music = background_music});
auto pickup_sound = load_audio(PICKUP_SOUND_DATA, sizeof(PICKUP_SOUND_DATA));
auto hit_sound = load_audio(HIT_SOUND_DATA, sizeof(HIT_SOUND_DATA));
registry.ctx().emplace<AudioAssets>(AudioAssets{.background_music = background_music,
.pickup_sound = pickup_sound,
.hit_sound = hit_sound});
auto font = load_font(DEFAULT_FONT_DATA, sizeof(DEFAULT_FONT_DATA));
registry.ctx().emplace<FontAssets>(FontAssets{.default_font = font});
}

View File

@@ -3,7 +3,8 @@
#include "audio.hpp"
#include <SDL3/SDL.h>
#include <flecs.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <entt/entt.hpp>
struct TextureAtlasLayout
{
@@ -23,15 +24,28 @@ struct TextureAssets
{
Texture background;
Texture fruits;
Texture spiders;
Texture basket;
};
struct AudioAssets
{
AudioAsset background_music;
AudioAsset pickup_sound;
AudioAsset hit_sound;
};
struct FontAsset
{
TTF_Font* font;
};
struct FontAssets
{
FontAsset default_font;
};
struct AssetModule
{
AssetModule(flecs::world& world);
AssetModule(entt::registry& registry);
};

31
src/audio.cpp Normal file
View File

@@ -0,0 +1,31 @@
#include "audio.hpp"
#include "assets.hpp"
AudioModule::AudioModule(entt::registry& registry)
{
auto const& audio_assets = registry.ctx().get<AudioAssets>();
auto* music_stream = SDL_OpenAudioDeviceStream(
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_assets.background_music.spec, NULL, NULL);
auto* sound_stream = SDL_OpenAudioDeviceStream(
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_assets.pickup_sound.spec, NULL, NULL);
SDL_ResumeAudioStreamDevice(music_stream);
SDL_ResumeAudioStreamDevice(sound_stream);
registry.ctx().emplace<AudioStreams>(
AudioStreams{.music_stream = music_stream, .sound_stream = sound_stream});
}
void AudioModule::FeedAudioStreams(entt::registry& registry)
{
auto audio_streams = registry.ctx().get<AudioStreams>();
auto audio_assets = registry.ctx().get<AudioAssets>();
if (SDL_GetAudioStreamQueued(audio_streams.music_stream) <
static_cast<int>(audio_assets.background_music.buffer_length))
{
SDL_PutAudioStreamData(audio_streams.music_stream,
audio_assets.background_music.buffer,
audio_assets.background_music.buffer_length);
}
}

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h>
#include <cstdint>
#include <entt/entt.hpp>
struct AudioAsset
{
@@ -9,3 +10,15 @@ struct AudioAsset
uint8_t* buffer;
uint32_t buffer_length;
};
struct AudioStreams
{
SDL_AudioStream* music_stream;
SDL_AudioStream* sound_stream;
};
struct AudioModule
{
AudioModule(entt::registry& registry);
static void FeedAudioStreams(entt::registry& registry);
};

View File

@@ -1,6 +1,8 @@
#pragma once
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <random>
static constexpr int WINDOW_WIDTH = 400;
static constexpr int WINDOW_HEIGHT = 240;
@@ -9,10 +11,13 @@ struct SdlHandles
{
SDL_Window* window;
SDL_Renderer* renderer;
TTF_TextEngine* text_engine;
};
struct Game
{
uint32_t ticks;
uint32_t score;
int32_t time;
int32_t score;
std::default_random_engine random_engine;
};

125
src/level.cpp Normal file
View File

@@ -0,0 +1,125 @@
#include "level.hpp"
#include "input.hpp"
#include <spdlog/spdlog.h>
void LevelModule::MoveBasket(entt::registry& registry)
{
auto const& input = registry.ctx().get<ButtonInput>();
auto basket_view = registry.view<Position, Size const, Sprite const, Basket>();
for (auto [entity, pos, size, sprite] : basket_view.each())
{
if (input.pressed.contains(SDLK_LEFT))
{
pos.x -= 5;
}
if (input.pressed.contains(SDLK_RIGHT))
{
pos.x += 5;
}
pos.x = pos.x < 0 ? 0 : pos.x;
pos.x = pos.x > WINDOW_WIDTH - size.w ? WINDOW_WIDTH - size.w : pos.x;
}
}
void LevelModule::SpawnFruits(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
auto const& texture_assets = registry.ctx().get<TextureAssets>();
std::bernoulli_distribution spider_dist(0.25);
bool spider = spider_dist(game.random_engine);
std::binomial_distribution<> velocity_dist(3, 0.5);
int vel = velocity_dist(game.random_engine) + 1;
if ((game.ticks % 50) == 0)
{
auto item = registry.create();
std::uniform_int_distribution<> xpos_dist(32, WINDOW_WIDTH - 32);
int xpos = xpos_dist(game.random_engine);
if (!spider)
{
std::uniform_int_distribution<> index_dist(0, 228 - 1);
uint16_t index = index_dist(game.random_engine);
registry.emplace<Fruit>(item);
registry.emplace<WorldPosition>(item);
registry.emplace<Position>(item, Position{.x = xpos, .y = -16});
registry.emplace<Velocity>(item, Velocity{.x = 0, .y = vel});
registry.emplace<Sprite>(
item, Sprite{.texture = &texture_assets.fruits, .texture_atlas_index = index});
registry.emplace<Size>(item, Size{.w = 32, .h = 32});
}
else
{
std::uniform_int_distribution<> index_dist(0, 8 - 1);
uint16_t index = index_dist(game.random_engine);
registry.emplace<Spider>(item);
registry.emplace<WorldPosition>(item);
registry.emplace<Position>(item, Position{.x = xpos, .y = -16});
registry.emplace<Velocity>(item, Velocity{.x = 0, .y = vel});
registry.emplace<Sprite>(
item, Sprite{.texture = &texture_assets.spiders, .texture_atlas_index = index});
registry.emplace<Size>(item, Size{.w = 32, .h = 32});
}
auto collision_box = registry.create();
registry.emplace<Parent>(collision_box, item);
registry.emplace<WorldPosition>(collision_box);
registry.emplace<Position>(collision_box, Position{.x = 0, .y = 0});
registry.emplace<Size>(collision_box, Size{.w = 32, .h = 32});
registry.emplace<CollisionBox>(collision_box, item);
}
}
void LevelModule::CollectFruit(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
auto const& audio_streams = registry.ctx().get<AudioStreams>();
auto const& audio_assets = registry.ctx().get<AudioAssets>();
auto view = registry.view<Position, Fruit, Collided>();
for (auto [entity, pos] : view.each())
{
game.score += 10;
pos.x += 1000;
// registry.destroy(entity);
SDL_PutAudioStreamData(audio_streams.sound_stream,
audio_assets.pickup_sound.buffer,
audio_assets.pickup_sound.buffer_length);
}
}
void LevelModule::CollectSpider(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
auto const& audio_streams = registry.ctx().get<AudioStreams>();
auto const& audio_assets = registry.ctx().get<AudioAssets>();
auto view = registry.view<Position, Spider, Collided>();
for (auto [entity, pos] : view.each())
{
game.score -= 50;
pos.x += 1000;
// registry.destroy(entity);
SDL_PutAudioStreamData(audio_streams.sound_stream,
audio_assets.hit_sound.buffer,
audio_assets.hit_sound.buffer_length);
};
}
void LevelModule::DespawnItems(entt::registry& registry)
{
auto view = registry.view<WorldPosition const, Item>();
for (auto [entity, pos] : view.each())
{
if (pos.y >= WINDOW_HEIGHT)
registry.destroy(entity);
}
}

View File

@@ -1,118 +1,70 @@
#pragma once
#include "definitions.hpp"
#include "input.hpp"
#include "physics.hpp"
#include "sprite.hpp"
#include <flecs.h>
#include <entt/entt.hpp>
#include <spdlog/spdlog.h>
struct Background
{
};
struct Fruit
{
};
struct Spider
{
};
struct Item
{
};
struct Basket
{
};
struct BasketCollisionBox
{
};
struct LevelModule
{
LevelModule(flecs::world& world)
LevelModule(entt::registry& registry)
{
auto const* texture_assets = world.get<TextureAssets>();
auto const* texture_assets = &registry.ctx().get<TextureAssets>();
world.entity("Background")
.set<Position>(Position{.x = 0, .y = 0})
.set<Sprite>(Sprite{.texture = &texture_assets->background, .texture_atlas_index = 0})
.set<Size>(Size{.w = WINDOW_WIDTH, .h = WINDOW_HEIGHT});
auto background = registry.create();
registry.emplace<Position>(background, Position{.x = 0, .y = 0});
registry.emplace<Sprite>(
background, Sprite{.texture = &texture_assets->background, .texture_atlas_index = 0});
registry.emplace<Size>(background, Size{.w = WINDOW_WIDTH, .h = WINDOW_HEIGHT});
registry.emplace<Background>(background);
auto basket =
world.entity("Basket")
.add<WorldPosition>()
.set<Position>(Position{.x = WINDOW_WIDTH / 2 - 32, .y = WINDOW_HEIGHT - 32})
.set<Sprite>(Sprite{.texture = &texture_assets->basket, .texture_atlas_index = 0})
.set<Size>(Size{.w = 64, .h = 32})
.add<Basket>();
auto basket = registry.create();
registry.emplace<WorldPosition>(basket);
registry.emplace<Position>(basket,
Position{.x = WINDOW_WIDTH / 2 - 32, .y = WINDOW_HEIGHT - 32});
registry.emplace<Sprite>(
basket, Sprite{.texture = &texture_assets->basket, .texture_atlas_index = 0});
registry.emplace<Size>(basket, Size{.w = 64, .h = 32});
registry.emplace<Basket>(basket);
world.entity()
.child_of(basket)
.add<WorldPosition>()
.set<Position>(Position{.x = 0, .y = 0})
.set<Size>(Size{.w = 64, .h = 32})
.add<CollisionBox>();
world.system<Game const, TextureAssets const>("SpawnFruits")
.term_at(0)
.singleton()
.term_at(1)
.singleton()
.each(
[](flecs::iter& it,
size_t index,
Game const& game,
TextureAssets const& texture_assets)
{
if ((game.ticks % 100) == 0)
{
auto fruit =
it.world()
.entity()
.add<Fruit>()
.add<WorldPosition>()
.set<Position>(Position{
.x = static_cast<int>(game.ticks % WINDOW_WIDTH), .y = -16})
.set<Velocity>(Velocity{.x = 0, .y = 1})
.set<Sprite>(Sprite{.texture = &texture_assets.fruits,
.texture_atlas_index =
static_cast<uint16_t>(game.ticks % 228)})
.set<Size>(Size{.w = 32, .h = 32});
it.world()
.entity("CollisionBox")
.child_of(fruit)
.add<WorldPosition>()
.set<Position>(Position{.x = 0, .y = 0})
.set<Size>(Size{.w = 32, .h = 32})
.add<CollisionBox>();
}
});
// world.system<WorldPosition const, Fruit>("DespawnFruits")
// .kind(flecs::OnValidate)
// .each(
// [](flecs::entity e, WorldPosition const& pos, Fruit)
// {
// if (pos.y >= WINDOW_HEIGHT)
// e.destruct();
// });
world.system<Game, Fruit, Collided>("CollectItem")
.term_at(0)
.singleton()
.each([](flecs::entity e, Game& game, Fruit, Collided) { game.score += 10; });
world.system<ButtonInput const, Position, Size const, Sprite const, Basket>("MoveBasket")
.term_at(0)
.singleton()
.each(
[](ButtonInput const& input,
Position& pos,
Size const& size,
Sprite const& sprite,
Basket)
{
if (input.pressed.contains(SDLK_LEFT))
{
pos.x -= 5;
}
if (input.pressed.contains(SDLK_RIGHT))
{
pos.x += 5;
}
pos.x = pos.x < 0 ? 0 : pos.x;
pos.x = pos.x > WINDOW_WIDTH - size.w ? WINDOW_WIDTH - size.w : pos.x;
});
auto basket_cb = registry.create();
registry.emplace<WorldPosition>(basket_cb);
registry.emplace<Position>(basket_cb, Position{.x = 0, .y = 16});
registry.emplace<Size>(basket_cb, Size{.w = 64, .h = 16});
registry.emplace<CollisionBox>(basket_cb);
registry.emplace<Parent>(basket_cb, basket);
registry.emplace<BasketCollisionBox>(basket_cb);
}
};
static void MoveBasket(entt::registry& registry);
static void SpawnFruits(entt::registry& registry);
static void CollectFruit(entt::registry &registry);
static void CollectSpider(entt::registry &registry);
static void DespawnItems(entt::registry &registry);
};

View File

@@ -3,17 +3,29 @@
#include "input.hpp"
#include "level.hpp"
#include "physics.hpp"
#include "sprite.hpp"
#include "render.hpp"
#include <SDL3/SDL.h>
#include <SDL3/SDL_error.h>
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_iostream.h>
#include <SDL3/SDL_render.h>
#include <SDL3/SDL_video.h>
#include <flecs.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <entt/entt.hpp>
#include <spdlog/spdlog.h>
void increment_ticks(entt::registry& registry)
{
auto& game = registry.ctx().get<Game>();
// auto& translate_system = registry.ctx().get<TranslateSystem>();
game.ticks += 1;
if (game.ticks % 60 == 0)
{
game.time = std::max(0, game.time - 1);
}
// if (game.time == 0)
// translate_system.translate_system.disable();
}
int main()
{
spdlog::info("Initialize SDL...");
@@ -26,6 +38,8 @@ int main()
std::terminate();
}
TTF_Init();
auto* window = SDL_CreateWindow("HansTheGatherer", WINDOW_WIDTH, WINDOW_HEIGHT, 0);
if (window == nullptr)
{
@@ -38,63 +52,25 @@ int main()
spdlog::critical("Failed to create SDL renderer!\nCause: {}", SDL_GetError());
}
flecs::world world;
auto* text_engine = TTF_CreateRendererTextEngine(renderer);
world.set<Game>(Game{.ticks = 0});
world.set<ButtonInput>(ButtonInput{});
world.set<SdlHandles>(SdlHandles{.window = window, .renderer = renderer});
entt::registry registry;
world.import <AssetModule>();
world.import <PhysicsModule>();
world.import <LevelModule>();
registry.ctx().emplace<Game>(Game{.ticks = 0, .time = 60, .score = 0, .random_engine = {}});
registry.ctx().emplace<ButtonInput>(ButtonInput{});
auto sdl_handles = registry.ctx().emplace<SdlHandles>(
SdlHandles{.window = window, .renderer = renderer, .text_engine = text_engine});
world.system<Game>("IncrementTicks")
.term_at(0)
.singleton()
.each([](Game& game_ticks) { game_ticks.ticks += 1; });
world.system<SdlHandles const, Position const, Size const, Sprite const>("RenderSprites")
.kind(flecs::PreUpdate)
.term_at(0)
.singleton()
.each(
[](SdlHandles const& sdl_handles,
Position const& pos,
Size const& size,
Sprite const& sprite)
{
TextureAtlasLayout layout = sprite.texture->texture_atlas_layout;
uint8_t row = sprite.texture_atlas_index / layout.columns;
uint8_t column = sprite.texture_atlas_index % layout.columns;
SDL_FRect srcrect{static_cast<float>(column * layout.width),
static_cast<float>(row * layout.height),
static_cast<float>(layout.width),
static_cast<float>(layout.height)};
SDL_FRect dstrect{static_cast<float>(pos.x),
static_cast<float>(pos.y),
static_cast<float>(size.w),
static_cast<float>(size.h)};
SDL_RenderTexture(
sdl_handles.renderer, sprite.texture->sdl_texture, &srcrect, &dstrect);
});
auto* audio_assets = world.get<AudioAssets>();
auto* stream = SDL_OpenAudioDeviceStream(
SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_assets->background_music.spec, NULL, NULL);
if (!stream)
{
SDL_Log("Couldn't create audio stream: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
SDL_ResumeAudioStreamDevice(stream);
AssetModule asset_module(registry);
AudioModule audio_module(registry);
RenderModule render_module(registry);
PhysicsModule physics_module(registry);
LevelModule level_module(registry);
bool exit_gameloop = false;
while (!exit_gameloop)
{
auto* input = world.get_mut<ButtonInput>();
auto* input = &registry.ctx().get<ButtonInput>();
// Clear just pressed/released
input->just_pressed.clear();
@@ -128,18 +104,24 @@ int main()
}
}
// Game Logic
if (SDL_GetAudioStreamQueued(stream) < (int)audio_assets->background_music.buffer_length)
{
SDL_PutAudioStreamData(stream,
audio_assets->background_music.buffer,
audio_assets->background_music.buffer_length);
}
AudioModule::FeedAudioStreams(registry);
increment_ticks(registry);
LevelModule::MoveBasket(registry);
LevelModule::SpawnFruits(registry);
LevelModule::CollectFruit(registry);
LevelModule::CollectSpider(registry);
// LevelModule::DespawnItems(registry);
// Render
SDL_RenderClear(renderer);
world.progress();
SDL_RenderPresent(renderer);
PhysicsModule::TranslatePhysicsObject(registry);
PhysicsModule::PropagatePosition(registry);
PhysicsModule::RemoveCollisionMarker(registry);
PhysicsModule::CollisionCheck(registry);
SDL_RenderClear(sdl_handles.renderer);
RenderModule::RenderSprites(registry);
RenderModule::RenderScore(registry);
SDL_RenderPresent(sdl_handles.renderer);
}
SDL_DestroyRenderer(renderer);

View File

@@ -3,78 +3,68 @@
#include <spdlog/spdlog.h>
PhysicsModule::PhysicsModule(flecs::world& world)
void PhysicsModule::TranslatePhysicsObject(entt::registry& registry)
{
world.system<Position, Velocity const>("TranslatePhysicsObject")
.each(
[](Position& pos, Velocity const& vel)
auto view = registry.view<Position, Velocity const>();
for (auto [entity, pos, vel] : view.each())
{
pos.x += vel.x;
pos.y += vel.y;
}
}
void PhysicsModule::PropagatePosition(entt::registry& registry)
{
auto root_transform_view = registry.view<Position const, WorldPosition>(entt::exclude<Parent>);
auto transform_view = registry.view<Position const, WorldPosition, Parent const>();
for (auto [entity, pos, world_pos] : root_transform_view.each())
{
world_pos.x = pos.x;
world_pos.y = pos.y;
}
for (auto [entity, pos, world_pos, parent] : transform_view.each())
{
auto parent_pos = registry.get<WorldPosition const>(parent.parent);
world_pos.x = parent_pos.x + pos.x;
world_pos.y = parent_pos.y + pos.y;
}
}
void PhysicsModule::RemoveCollisionMarker(entt::registry& registry)
{
auto view = registry.view<Collided const>();
for (auto [entity] : view.each())
{
registry.remove<Collided>(entity);
}
}
void PhysicsModule::CollisionCheck(entt::registry& registry)
{
auto view = registry.view<WorldPosition const, Size const, Parent const, CollisionBox>(
entt::exclude<BasketCollisionBox>);
auto basket_cb_view = registry.view<WorldPosition const, Size const, BasketCollisionBox>();
for (auto [e, world_pos, size, parent] : view.each())
{
auto fruit = parent.parent;
for (auto [basket, basket_world_pos, basket_size] : basket_cb_view.each())
{
if (basket_world_pos.x + basket_size.w >= world_pos.x &&
basket_world_pos.x <= world_pos.x + size.w &&
basket_world_pos.y + basket_size.h >= world_pos.y &&
basket_world_pos.y <= world_pos.y + size.h)
{
pos.x += vel.x;
pos.y += vel.y;
});
registry.emplace<Collided>(fruit);
}
}
}
}
// Introduce phase that runs after OnUpdate but before OnValidate
flecs::entity propagate_phase = world.entity().add(flecs::Phase).depends_on(flecs::OnUpdate);
world.system<WorldPosition, Position const>("PropagatePosition")
.kind(propagate_phase)
.each(
[](flecs::entity e, WorldPosition& world_pos, Position const& local_pos)
{
if (e.parent() != flecs::entity::null() && e.parent().has<WorldPosition>())
return;
world_pos.x = local_pos.x;
world_pos.y = local_pos.y;
std::function<void(flecs::entity, WorldPosition const&)> propagate_to_children;
propagate_to_children = [&](flecs::entity parent, WorldPosition const& parent_pos)
{
parent.children(
[=](flecs::entity child)
{
auto local_pos = child.get<Position>();
auto world_pos = child.get_mut<WorldPosition>();
world_pos->x = parent_pos.x + local_pos->x;
world_pos->y = parent_pos.y + local_pos->y;
propagate_to_children(child, *world_pos);
});
};
propagate_to_children(e, world_pos);
});
auto basket_query = world.query<Basket>();
world.system<WorldPosition const, Size const, CollisionBox>("CollisionCheck")
.kind(flecs::OnValidate)
.each(
[basket_query](
flecs::entity e, WorldPosition const& world_pos, Size const& size, CollisionBox)
{
if (e.parent().has<Basket>())
return;
auto fruit = e.parent();
auto basket = basket_query.first();
basket.children(
[fruit, world_pos, size](flecs::entity basket_child)
{
if (!basket_child.has<CollisionBox>())
return;
auto basket_child_pos = basket_child.get<WorldPosition>();
auto basket_child_size = basket_child.get<Size>();
if (basket_child_pos->x + basket_child_size->w >= world_pos.x &&
basket_child_pos->x <= world_pos.x + size.w &&
basket_child_pos->y + basket_child_size->h >= world_pos.y &&
basket_child_pos->y <= world_pos.y + size.h)
{
fruit.add<Collided>();
}
});
});
PhysicsModule::PhysicsModule(entt::registry& registry)
{
}

View File

@@ -1,6 +1,6 @@
#pragma once
#include <flecs.h>
#include <entt/entt.hpp>
struct WorldPosition
{
@@ -26,6 +26,16 @@ struct Size
int h;
};
struct Parent
{
entt::entity parent;
};
struct Children
{
std::vector<entt::entity> children;
};
struct CollisionBox
{
};
@@ -36,5 +46,10 @@ struct Collided
struct PhysicsModule
{
PhysicsModule(flecs::world& world);
PhysicsModule(entt::registry& registry);
static void TranslatePhysicsObject(entt::registry& registry);
static void PropagatePosition(entt::registry& registry);
static void RemoveCollisionMarker(entt::registry& registry);
static void CollisionCheck(entt::registry& registry);
};

72
src/render.cpp Normal file
View File

@@ -0,0 +1,72 @@
#include "render.hpp"
#include "definitions.hpp"
#include "level.hpp"
#include "physics.hpp"
#include "sprite.hpp"
#include <format>
RenderModule::RenderModule(entt::registry& registry)
{
}
void RenderModule::RenderSprites(entt::registry& registry)
{
auto const& sdl_handles = registry.ctx().get<SdlHandles>();
auto const& game = registry.ctx().get<Game>();
auto sprites_view =
registry.view<Position const, Size const, Sprite const>(entt::exclude<Background>);
auto background_view = registry.view<Position const, Size const, Sprite const, Background>();
for (auto [entity, pos, size, sprite] : background_view.each())
{
TextureAtlasLayout layout = sprite.texture->texture_atlas_layout;
uint8_t row = sprite.texture_atlas_index / layout.columns;
uint8_t column = sprite.texture_atlas_index % layout.columns;
SDL_FRect srcrect{static_cast<float>(column * layout.width),
static_cast<float>(row * layout.height),
static_cast<float>(layout.width),
static_cast<float>(layout.height)};
SDL_FRect dstrect{static_cast<float>(pos.x),
static_cast<float>(pos.y),
static_cast<float>(size.w),
static_cast<float>(size.h)};
SDL_RenderTexture(sdl_handles.renderer, sprite.texture->sdl_texture, &srcrect, &dstrect);
}
for (auto [entity, pos, size, sprite] : sprites_view.each())
{
TextureAtlasLayout layout = sprite.texture->texture_atlas_layout;
uint8_t row = sprite.texture_atlas_index / layout.columns;
uint8_t column = sprite.texture_atlas_index % layout.columns;
SDL_FRect srcrect{static_cast<float>(column * layout.width),
static_cast<float>(row * layout.height),
static_cast<float>(layout.width),
static_cast<float>(layout.height)};
SDL_FRect dstrect{static_cast<float>(pos.x),
static_cast<float>(pos.y),
static_cast<float>(size.w),
static_cast<float>(size.h)};
SDL_RenderTexture(sdl_handles.renderer, sprite.texture->sdl_texture, &srcrect, &dstrect);
}
}
void RenderModule::RenderScore(entt::registry& registry)
{
auto const& sdl_handles = registry.ctx().get<SdlHandles>();
auto const& game = registry.ctx().get<Game>();
auto const& font_assets = registry.ctx().get<FontAssets>();
auto score_string = std::format("Score: {}\nTime: {}", game.score, game.time);
auto text = TTF_CreateText(sdl_handles.text_engine,
font_assets.default_font.font,
score_string.c_str(),
score_string.length());
TTF_DrawRendererText(text, 0.0, 0.0);
TTF_DestroyText(text);
}

11
src/render.hpp Normal file
View File

@@ -0,0 +1,11 @@
#pragma once
#include <entt/entt.hpp>
struct RenderModule
{
RenderModule(entt::registry& registry);
static void RenderSprites(entt::registry& registry);
static void RenderScore(entt::registry& registry);
};

View File

@@ -1,8 +0,0 @@
{
"dependencies": [
"spdlog",
"sdl3",
"spdlog",
"flecs"
]
}