From 07adbf48e0781cd8c95983c1871a84b6160ee5bf Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Thu, 14 Nov 2024 13:57:13 +0100 Subject: implement asset + more WIP audio system --- src/example/asset_manager.cpp | 22 +++++++++++----------- src/example/audio_internal.cpp | 16 ++++++++++++---- src/example/particles.cpp | 5 +++-- src/example/rendering.cpp | 6 +++--- 4 files changed, 29 insertions(+), 20 deletions(-) (limited to 'src/example') diff --git a/src/example/asset_manager.cpp b/src/example/asset_manager.cpp index cf64f89..a2ca8c3 100644 --- a/src/example/asset_manager.cpp +++ b/src/example/asset_manager.cpp @@ -8,7 +8,7 @@ int main() { // this needs to be called before the asset manager otherwise the destructor // of sdl is not in the right order - { Texture test("../asset/texture/img.png"); } + { Texture test("asset/texture/img.png"); } // FIXME: make it so the issue described by the above comment is not possible // (i.e. the order in which internal classes are instantiated should not // impact the way the engine works). @@ -18,20 +18,20 @@ int main() { { // TODO: [design] the Sound class can't be directly included by the user as // it includes SoLoud headers. - auto bgm = mgr.cache("../mwe/audio/bgm.ogg"); - auto sfx1 = mgr.cache("../mwe/audio/sfx1.wav"); - auto sfx2 = mgr.cache("../mwe/audio/sfx2.wav"); + auto bgm = mgr.cache("mwe/audio/bgm.ogg"); + auto sfx1 = mgr.cache("mwe/audio/sfx1.wav"); + auto sfx2 = mgr.cache("mwe/audio/sfx2.wav"); - auto img = mgr.cache("../asset/texture/img.png"); - auto img1 = mgr.cache("../asset/texture/second.png"); + auto img = mgr.cache("asset/texture/img.png"); + auto img1 = mgr.cache("asset/texture/second.png"); } { - auto bgm = mgr.cache("../mwe/audio/bgm.ogg"); - auto sfx1 = mgr.cache("../mwe/audio/sfx1.wav"); - auto sfx2 = mgr.cache("../mwe/audio/sfx2.wav"); + auto bgm = mgr.cache("mwe/audio/bgm.ogg"); + auto sfx1 = mgr.cache("mwe/audio/sfx1.wav"); + auto sfx2 = mgr.cache("mwe/audio/sfx2.wav"); - auto img = mgr.cache("../asset/texture/img.png"); - auto img1 = mgr.cache("../asset/texture/second.png"); + auto img = mgr.cache("asset/texture/img.png"); + auto img1 = mgr.cache("asset/texture/second.png"); } } diff --git a/src/example/audio_internal.cpp b/src/example/audio_internal.cpp index ff55a59..9b60e6b 100644 --- a/src/example/audio_internal.cpp +++ b/src/example/audio_internal.cpp @@ -4,7 +4,9 @@ */ #include +#include #include +#include #include #include @@ -24,12 +26,18 @@ int _ = []() { }(); int main() { + SoundContext ctx{}; + Sound sound{ctx}; // Load a background track (Ogg Vorbis) - auto bgm = Sound("../mwe/audio/bgm.ogg"); + auto _bgm = sound.clone(Asset{"mwe/audio/bgm.ogg"}); + Sound & bgm = *dynamic_cast(_bgm.get()); // Load three short samples (WAV) - auto sfx1 = Sound("../mwe/audio/sfx1.wav"); - auto sfx2 = Sound("../mwe/audio/sfx2.wav"); - auto sfx3 = Sound("../mwe/audio/sfx3.wav"); + auto _sfx1 = sound.clone(Asset{"mwe/audio/sfx1.wav"}); + Sound & sfx1 = *dynamic_cast(_sfx1.get()); + auto _sfx2 = sound.clone(Asset{"mwe/audio/sfx2.wav"}); + Sound & sfx2 = *dynamic_cast(_sfx2.get()); + auto _sfx3 = sound.clone(Asset{"mwe/audio/sfx3.wav"}); + Sound & sfx3 = *dynamic_cast(_sfx3.get()); // Start the background track bgm.play(); diff --git a/src/example/particles.cpp b/src/example/particles.cpp index 6eab046..b65671a 100644 --- a/src/example/particles.cpp +++ b/src/example/particles.cpp @@ -14,10 +14,11 @@ using namespace crepe; using namespace std; int main(int argc, char * argv[]) { - GameObject game_object(0, "", "", Vector2{0, 0}, 0, 0); + ComponentManager mgr; + GameObject game_object = mgr.new_object("", "", Vector2{0, 0}, 0, 0); Color color(0, 0, 0, 0); Sprite test_sprite = game_object.add_component( - make_shared("../asset/texture/img.png"), color, + make_shared("asset/texture/img.png"), color, FlipSettings{true, true}); game_object.add_component(ParticleEmitter::Data{ .position = {0, 0}, diff --git a/src/example/rendering.cpp b/src/example/rendering.cpp index abd11b1..2157bdc 100644 --- a/src/example/rendering.cpp +++ b/src/example/rendering.cpp @@ -31,21 +31,21 @@ int main() { { Color color(0, 0, 0, 0); obj.add_component( - make_shared("../asset/texture/img.png"), color, + make_shared("asset/texture/img.png"), color, FlipSettings{false, false}); obj.add_component(Color::get_red()); } { Color color(0, 0, 0, 0); obj1.add_component( - make_shared("../asset/texture/second.png"), color, + make_shared("asset/texture/second.png"), color, FlipSettings{true, true}); } /* { Color color(0, 0, 0, 0); - auto img = mgr.cache("../asset/texture/second.png"); + auto img = mgr.cache("asset/texture/second.png"); obj2.add_component(img, color, FlipSettings{true, true}); } */ -- cgit v1.2.3 From c59d460f12e1393e0ddbaaa1c6f5522eb12f8ff9 Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Fri, 29 Nov 2024 16:23:52 +0100 Subject: more utility classes for Audio system --- src/crepe/api/AudioSource.h | 11 ++----- src/crepe/facade/Sound.h | 4 +++ src/crepe/system/AudioSystem.cpp | 17 +++++++++-- src/crepe/system/AudioSystem.h | 21 +++++++++++++ src/crepe/util/CMakeLists.txt | 3 ++ src/crepe/util/Private.cpp | 29 ++++++++++++++++++ src/crepe/util/Private.h | 34 +++++++++++++++++++++ src/crepe/util/Private.hpp | 31 +++++++++++++++++++ src/example/CMakeLists.txt | 1 - src/example/asset_manager.cpp | 36 ---------------------- src/test/AudioTest.cpp | 5 ++- src/test/CMakeLists.txt | 1 + src/test/PrivateTest.cpp | 66 ++++++++++++++++++++++++++++++++++++++++ 13 files changed, 210 insertions(+), 49 deletions(-) create mode 100644 src/crepe/util/Private.cpp create mode 100644 src/crepe/util/Private.h create mode 100644 src/crepe/util/Private.hpp delete mode 100644 src/example/asset_manager.cpp create mode 100644 src/test/PrivateTest.cpp (limited to 'src/example') diff --git a/src/crepe/api/AudioSource.h b/src/crepe/api/AudioSource.h index 0950129..9d76f0b 100644 --- a/src/crepe/api/AudioSource.h +++ b/src/crepe/api/AudioSource.h @@ -2,6 +2,7 @@ #include "../Component.h" #include "../types.h" +#include "../util/Private.h" #include "GameObject.h" #include "Asset.h" @@ -47,14 +48,8 @@ private: bool rewind = false; private: - //! Value of \c active after last system update - bool last_active = false; - //! Value of \c playing after last system update - bool last_playing = false; - //! Value of \c volume after last system update - float last_volume = 1.0; - //! Value of \c loop after last system update - bool last_loop = false; + //! AudioSystem::ComponentPrivate + Private private_data; }; } // namespace crepe diff --git a/src/crepe/facade/Sound.h b/src/crepe/facade/Sound.h index b0b80f8..f33ee58 100644 --- a/src/crepe/facade/Sound.h +++ b/src/crepe/facade/Sound.h @@ -9,6 +9,10 @@ namespace crepe { class SoundContext; +struct SoundHandle { + SoLoud::handle handle; +}; + /** * \brief Sound resource facade * diff --git a/src/crepe/system/AudioSystem.cpp b/src/crepe/system/AudioSystem.cpp index 97cf966..0f943be 100644 --- a/src/crepe/system/AudioSystem.cpp +++ b/src/crepe/system/AudioSystem.cpp @@ -1,6 +1,5 @@ #include "AudioSystem.h" -#include "../api/AudioSource.h" #include "../manager/ComponentManager.h" #include "../manager/ResourceManager.h" #include "../types.h" @@ -13,12 +12,24 @@ void AudioSystem::update() { ResourceManager & resource_manager = this->mediator.resource_manager; RefVector components = component_manager.get_components_by_type(); - for (auto component_ref : components) { - AudioSource & component = component_ref.get(); + for (AudioSource & component : components) { if (!component.active) continue; Sound & sound = resource_manager.get(component.source); + if (component.private_data.empty()) + component.private_data.set(); + auto & data = component.private_data.get(); // TODO: lots of state diffing + + + this->update_private(component, data); } } +void AudioSystem::update_private(const AudioSource & component, ComponentPrivate & data) { + data.last_active = component.active; + data.last_loop = component.loop; + data.last_playing = component.playing; + data.last_volume = component.volume; +} + diff --git a/src/crepe/system/AudioSystem.h b/src/crepe/system/AudioSystem.h index e037f51..7f41fda 100644 --- a/src/crepe/system/AudioSystem.h +++ b/src/crepe/system/AudioSystem.h @@ -1,6 +1,7 @@ #pragma once #include "../facade/SoundContext.h" +#include "../api/AudioSource.h" #include "System.h" @@ -11,6 +12,26 @@ public: using System::System; void update() override; +private: + /** + * \brief Private data stored by AudioSystem on AudioSource component + */ + struct ComponentPrivate { + //! This sample's voice handle + SoLoud::handle handle; + + //! Value of \c active after last system update + bool last_active = false; + //! Value of \c playing after last system update + bool last_playing = false; + //! Value of \c volume after last system update + float last_volume = 1.0; + //! Value of \c loop after last system update + bool last_loop = false; + }; + + void update_private(const AudioSource & component, ComponentPrivate & data); + private: SoundContext context {}; }; diff --git a/src/crepe/util/CMakeLists.txt b/src/crepe/util/CMakeLists.txt index 94ed906..f49d851 100644 --- a/src/crepe/util/CMakeLists.txt +++ b/src/crepe/util/CMakeLists.txt @@ -1,6 +1,7 @@ target_sources(crepe PUBLIC LogColor.cpp Log.cpp + Private.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES @@ -11,5 +12,7 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES Proxy.hpp OptionalRef.h OptionalRef.hpp + Private.h + Private.hpp ) diff --git a/src/crepe/util/Private.cpp b/src/crepe/util/Private.cpp new file mode 100644 index 0000000..c5b5b30 --- /dev/null +++ b/src/crepe/util/Private.cpp @@ -0,0 +1,29 @@ +#include "Private.h" + +using namespace crepe; + +bool Private::empty() const noexcept { + return this->instance == nullptr; +} + +Private::~Private() { + if (this->instance == nullptr) return; + this->destructor(this->instance); +} + +Private::Private(Private && other) { + *this = std::move(other); +} + +Private & Private::operator=(Private && other) { + // TODO: ideally this function checks for self-assignment + this->instance = other.instance; + this->destructor = other.destructor; + this->type = other.type; + + other.instance = nullptr; + other.destructor = [](void*){}; + + return *this; +} + diff --git a/src/crepe/util/Private.h b/src/crepe/util/Private.h new file mode 100644 index 0000000..fc3728f --- /dev/null +++ b/src/crepe/util/Private.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +namespace crepe { + +class Private { +public: + Private() = default; + ~Private(); + Private(Private &&); + Private & operator=(Private &&); + Private(const Private &) = delete; + Private & operator=(const Private &) = delete; + + template + T & get(); + + template + void set(Args &&... args); + + bool empty() const noexcept; + +private: + std::function destructor; + std::type_index type = typeid(void); + void * instance = nullptr; +}; + +} + +#include "Private.hpp" + diff --git a/src/crepe/util/Private.hpp b/src/crepe/util/Private.hpp new file mode 100644 index 0000000..30c8146 --- /dev/null +++ b/src/crepe/util/Private.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +#include "Private.h" + +namespace crepe { + +template +void Private::set(Args &&... args) { + T * instance = new T(std::forward(args)...); + this->instance = static_cast(instance); + this->destructor = [](void * instance) { + delete static_cast(instance); + }; + this->type = typeid(T); +} + +template +T & Private::get() { + using namespace std; + if (this->empty()) + throw out_of_range("Private: get() called on empty object"); + type_index requested_type = typeid(T); + if (this->type != requested_type) + throw logic_error(format("Private: get() called with [T = {}] (actual is [T = {}])", requested_type.name(), this->type.name())); + return *static_cast(this->instance); +} + +} diff --git a/src/example/CMakeLists.txt b/src/example/CMakeLists.txt index 560e2bc..9c3c550 100644 --- a/src/example/CMakeLists.txt +++ b/src/example/CMakeLists.txt @@ -16,7 +16,6 @@ function(add_example target_name) add_dependencies(examples ${target_name}) endfunction() -add_example(asset_manager) add_example(savemgr) add_example(rendering_particle) add_example(gameloop) diff --git a/src/example/asset_manager.cpp b/src/example/asset_manager.cpp deleted file mode 100644 index 660b318..0000000 --- a/src/example/asset_manager.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include -#include - -using namespace crepe; - -int main() { - - // this needs to be called before the asset manager otherwise the destructor of sdl is not in - // the right order - { Texture test("asset/texture/img.png"); } - // FIXME: make it so the issue described by the above comment is not possible (i.e. the order - // in which internal classes are instantiated should not impact the way the engine works). - - auto & mgr = AssetManager::get_instance(); - - { - // TODO: [design] the Sound class can't be directly included by the user as it includes - // SoLoud headers. - auto bgm = mgr.cache("mwe/audio/bgm.ogg"); - auto sfx1 = mgr.cache("mwe/audio/sfx1.wav"); - auto sfx2 = mgr.cache("mwe/audio/sfx2.wav"); - - auto img = mgr.cache("asset/texture/img.png"); - auto img1 = mgr.cache("asset/texture/second.png"); - } - - { - auto bgm = mgr.cache("mwe/audio/bgm.ogg"); - auto sfx1 = mgr.cache("mwe/audio/sfx1.wav"); - auto sfx2 = mgr.cache("mwe/audio/sfx2.wav"); - - auto img = mgr.cache("asset/texture/img.png"); - auto img1 = mgr.cache("asset/texture/second.png"); - } -} diff --git a/src/test/AudioTest.cpp b/src/test/AudioTest.cpp index afd2672..3be5afa 100644 --- a/src/test/AudioTest.cpp +++ b/src/test/AudioTest.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -13,15 +14,17 @@ class AudioTest : public Test { Mediator mediator; public: ComponentManager component_manager{mediator}; + ResourceManager resource_manager{mediator}; AudioSystem system {mediator}; void SetUp() override { auto & mgr = this->component_manager; GameObject entity = mgr.new_object("name"); - entity.add_component("mwe/audio/sfx1.wav"); + AudioSource & audio_source = entity.add_component("mwe/audio/sfx1.wav"); } }; TEST_F(AudioTest, Default) { + system.update(); } diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index 4174926..8c4b855 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -16,4 +16,5 @@ target_sources(test_main PUBLIC Vector2Test.cpp ScriptEventTest.cpp ScriptSceneTest.cpp + PrivateTest.cpp ) diff --git a/src/test/PrivateTest.cpp b/src/test/PrivateTest.cpp new file mode 100644 index 0000000..f0d2b1a --- /dev/null +++ b/src/test/PrivateTest.cpp @@ -0,0 +1,66 @@ +#include + +#include + +using namespace std; +using namespace crepe; +using namespace testing; + +class PrivateTest : public Test { +public: + static unsigned constructors; + static unsigned destructors; + + void SetUp() override { + PrivateTest::constructors = 0; + PrivateTest::destructors = 0; + } + + class TestClass { + public: + TestClass() { PrivateTest::constructors++; } + ~TestClass() { PrivateTest::destructors++; } + }; + class Unrelated {}; +}; +unsigned PrivateTest::constructors; +unsigned PrivateTest::destructors; + +TEST_F(PrivateTest, Empty) { + { + Private foo; + } + + EXPECT_EQ(PrivateTest::constructors, 0); + EXPECT_EQ(PrivateTest::destructors, 0); +} + +TEST_F(PrivateTest, WithObject) { + { + Private foo; + foo.set(); + + EXPECT_EQ(PrivateTest::constructors, 1); + EXPECT_EQ(PrivateTest::destructors, 0); + } + + EXPECT_EQ(PrivateTest::constructors, 1); + EXPECT_EQ(PrivateTest::destructors, 1); +} + +TEST_F(PrivateTest, EmptyException) { + Private foo; + EXPECT_THROW(foo.get(), std::out_of_range); + + foo.set(); + EXPECT_NO_THROW(foo.get()); +} + +TEST_F(PrivateTest, IncorrectTypeException) { + Private foo; + foo.set(); + + EXPECT_THROW(foo.get(), std::logic_error); + EXPECT_NO_THROW(foo.get()); +} + -- cgit v1.2.3 From 7ae597ac9268e031927f94dd89c20ab6c034f5de Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Fri, 29 Nov 2024 21:20:48 +0100 Subject: working floating point black bars --- src/crepe/api/Config.h | 2 +- src/crepe/api/Sprite.cpp | 2 +- src/crepe/api/Sprite.h | 4 +-- src/crepe/facade/SDLContext.cpp | 71 ++++++++++++++++++++++++-------------- src/example/rendering_particle.cpp | 7 ++-- 5 files changed, 55 insertions(+), 31 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h index 225e9b9..200a3b0 100644 --- a/src/crepe/api/Config.h +++ b/src/crepe/api/Config.h @@ -67,7 +67,7 @@ public: //! default window settings struct { //TODO make this constexpr because this will never change - ivec2 default_size = {1080, 720}; + ivec2 default_size = {1280, 720}; std::string window_title = "Jetpack joyride clone"; } window_settings; diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index 8647794..1d57b53 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -11,7 +11,7 @@ using namespace std; using namespace crepe; Sprite::Sprite(game_object_id_t id, Texture & image, const Color & color, - const FlipSettings & flip, int sort_layer, int order_layer, int height) + const FlipSettings & flip, int sort_layer, int order_layer, float height) : Component(id), color(color), flip(flip), diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index a0e90a0..5a7a1d9 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -41,7 +41,7 @@ public: * \param height the height of the image in game units */ Sprite(game_object_id_t id, Texture & image, const Color & color, - const FlipSettings & flip, int sort_layer, int order_layer, int height); + const FlipSettings & flip, int sort_layer, int order_layer, float height); /** * \brief Destroys the Sprite instance. @@ -63,7 +63,7 @@ public: const int order_in_layer; //! height in world units - const int height; + const float height; /** * \aspect_ratio ratio of the img so that scaling will not become weird diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 9f60285..56ba61a 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -94,7 +95,7 @@ void SDLContext::handle_events(bool & running) { } void SDLContext::clear_screen() { - SDL_SetRenderDrawColor(this->game_renderer.get(), 0, 0, 0, 255); + SDL_SetRenderDrawColor(this->game_renderer.get(), 255, 255, 255, 255); SDL_RenderClear(this->game_renderer.get()); } void SDLContext::present_screen() { SDL_RenderPresent(this->game_renderer.get()); } @@ -110,17 +111,19 @@ SDL_Rect SDLContext::get_src_rect(const Sprite & sprite) const { SDL_Rect SDLContext::get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, const vec2 & cam_pos, const double & img_scale) const { - int width = sprite.height * sprite.aspect_ratio; - int height = sprite.height; + double width = sprite.height * sprite.aspect_ratio; + double height = sprite.height; width *= img_scale * cam.zoom; height *= img_scale * cam.zoom; return SDL_Rect{ - .x = static_cast((pos.x - cam_pos.x + (cam.viewport_size.x / 2) - width / 2)), - .y = static_cast((pos.y - cam_pos.y + (cam.viewport_size.y / 2) - height / 2)), - .w = width, - .h = height, + .x + = static_cast(round(pos.x - cam_pos.x + (cam.viewport_size.x / 2) - width / 2)), + .y + = static_cast(round(pos.y - cam_pos.y + (cam.viewport_size.y / 2) - height / 2)), + .w = static_cast(width), + .h = static_cast(height), }; } @@ -134,6 +137,8 @@ void SDLContext::draw(const RenderContext & ctx) { SDL_Rect dstrect = this->get_dst_rect(ctx.sprite, ctx.pos, ctx.cam, ctx.cam_pos, ctx.scale); + cout << dstrect.x << " " << dstrect.y << " " << dstrect.w << " " << dstrect.h << endl; + SDL_RenderCopyEx(this->game_renderer.get(), ctx.sprite.sprite_image.texture.get(), &srcrect, &dstrect, ctx.angle, NULL, render_flip); } @@ -147,30 +152,44 @@ void SDLContext::set_camera(const Camera & cam) { SDL_SetWindowSize(this->game_window.get(), cam.screen.x, cam.screen.y); } - double screen_aspect = cam.screen.x / cam.screen.y; + double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; double viewport_aspect = cam.viewport_size.x / cam.viewport_size.y; - SDL_Rect view; + cout << screen_aspect << " " << viewport_aspect << endl; + SDL_FRect black_bars[2]; // calculate black bars if (screen_aspect > viewport_aspect) { - // letterboxing - view.h = cam.screen.y / cam.zoom; - view.w = cam.screen.y * viewport_aspect; - view.x = (cam.screen.x - view.w) / 2; - view.y = 0; - } else { // pillarboxing - view.h = cam.screen.x / viewport_aspect; - view.w = cam.screen.x / cam.zoom; - view.x = 0; - view.y = (cam.screen.y - view.h) / 2; + cout << "pillarboxing" << endl; + float render_scale = cam.screen.y / cam.viewport_size.y; + float adj_width = cam.viewport_size.x * render_scale; + float bar_width = (cam.screen.x - adj_width) / 2; + black_bars[0] = {0, 0, bar_width, (float)cam.screen.y}; + black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float)cam.screen.y}; + cout << render_scale << " " << adj_width << " " << bar_width << " " << cam.screen.y + << " " << cam.viewport_size.y << endl; + } else { + // letterboxing + cout << "letterboxing" << endl; + float render_scale = cam.screen.y / cam.viewport_size.y; + float adj_width = cam.viewport_size.x * render_scale; + float bar_height = (cam.screen.x - adj_width) / 2; + black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; + black_bars[1] = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height}; + cout << render_scale << " " << adj_width << " " << bar_height << " " << cam.screen.y + << " " << cam.viewport_size.y << endl; } - // set drawing area - SDL_RenderSetViewport(this->game_renderer.get(), &view); - SDL_RenderSetLogicalSize(this->game_renderer.get(), static_cast(cam.viewport_size.x), - static_cast(cam.viewport_size.y)); + for (int i = 0; i < 2; ++i) { + cout << black_bars[i].x << " " << black_bars[i].y << " " << black_bars[i].w << " " + << black_bars[i].h << endl; + } + + SDL_SetRenderDrawColor(this->game_renderer.get(), 0, 0, 0, 255); + SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[0]); + SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[1]); + /* // set bg color SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, cam.bg_color.g, cam.bg_color.b, cam.bg_color.a); @@ -178,11 +197,13 @@ void SDLContext::set_camera(const Camera & cam) { SDL_Rect bg = { .x = 0, .y = 0, - .w = static_cast(cam.viewport_size.x), - .h = static_cast(cam.viewport_size.y), + .w = (int)cam.viewport_size.x, + .h = (int)cam.viewport_size.y, }; // fill bg color SDL_RenderFillRect(this->game_renderer.get(), &bg); + + */ } uint64_t SDLContext::get_ticks() const { return SDL_GetTicks64(); } diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 3a12144..5896c81 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -31,12 +31,15 @@ int main(int argc, char * argv[]) { Color color(255, 255, 255, 255); auto img = Texture("asset/texture/test_ap43.png"); + + /* Sprite & test_sprite = game_object.add_component( img, color, Sprite::FlipSettings{true, true}, 1, 1, 500); //game_object.add_component(test_sprite, 4, 1, 0).active = true; game_object.add_component(test_sprite, 1, 1, 0).active = true; + */ /* auto & test = game_object.add_component(ParticleEmitter::Data{ .position = {0, 0}, @@ -59,8 +62,8 @@ int main(int argc, char * argv[]) { }); */ - auto & cam = game_object.add_component(Color::WHITE, ivec2{1080, 720}, - vec2{2000, 2000}, 1.0f); + auto & cam = game_object.add_component(Color::WHITE, ivec2{1600, 900}, + vec2{800,800}, 1.0f); /* game_object -- cgit v1.2.3 From 4159c7187e17d6318e33d8a0c014ba042ae8261b Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Sat, 30 Nov 2024 15:22:17 +0100 Subject: first version of new viewport floats without the use of sdl functions --- src/crepe/api/Sprite.h | 2 +- src/crepe/facade/SDLContext.cpp | 60 +++++++++++++++++++++++--------------- src/crepe/facade/SDLContext.h | 2 +- src/example/rendering_particle.cpp | 9 +++--- 4 files changed, 42 insertions(+), 31 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index 5a7a1d9..7d9c14b 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -71,7 +71,7 @@ public: * cannot be const because if Animator component is addded then ratio becomes scuffed and * does it need to be calculated again in the Animator */ - double aspect_ratio; + float aspect_ratio; private: //! Reads the mask of sprite diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 56ba61a..0ba1db4 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -108,22 +108,30 @@ SDL_Rect SDLContext::get_src_rect(const Sprite & sprite) const { .h = sprite.mask.h, }; } -SDL_Rect SDLContext::get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, + +vec2 bar_size; +vec2 scale; + +SDL_FRect SDLContext::get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, const vec2 & cam_pos, const double & img_scale) const { - double width = sprite.height * sprite.aspect_ratio; - double height = sprite.height; - width *= img_scale * cam.zoom; - height *= img_scale * cam.zoom; + vec2 size = { (sprite.height * sprite.aspect_ratio), sprite.height}; + + size *= scale * img_scale * cam.zoom ; - return SDL_Rect{ - .x - = static_cast(round(pos.x - cam_pos.x + (cam.viewport_size.x / 2) - width / 2)), - .y - = static_cast(round(pos.y - cam_pos.y + (cam.viewport_size.y / 2) - height / 2)), - .w = static_cast(width), - .h = static_cast(height), + vec2 screen_pos = (pos - cam_pos + cam.viewport_size / 2) * scale - size / 2 + bar_size; + + cout << size.x << " " << size.y << endl; + cout << pos.x << " " << pos.y << endl; + cout << scale.x << " " << scale.y << endl; + cout << screen_pos.x << " " << screen_pos.y << endl; + + return SDL_FRect{ + .x = screen_pos.x, + .y = screen_pos.y, + .w = size.x, + .h = size.y, }; } @@ -134,12 +142,12 @@ void SDLContext::draw(const RenderContext & ctx) { | (SDL_FLIP_VERTICAL * ctx.sprite.flip.flip_y)); SDL_Rect srcrect = this->get_src_rect(ctx.sprite); - SDL_Rect dstrect + SDL_FRect dstrect = this->get_dst_rect(ctx.sprite, ctx.pos, ctx.cam, ctx.cam_pos, ctx.scale); cout << dstrect.x << " " << dstrect.y << " " << dstrect.w << " " << dstrect.h << endl; - SDL_RenderCopyEx(this->game_renderer.get(), ctx.sprite.sprite_image.texture.get(), + SDL_RenderCopyExF(this->game_renderer.get(), ctx.sprite.sprite_image.texture.get(), &srcrect, &dstrect, ctx.angle, NULL, render_flip); } @@ -155,7 +163,7 @@ void SDLContext::set_camera(const Camera & cam) { double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; double viewport_aspect = cam.viewport_size.x / cam.viewport_size.y; - cout << screen_aspect << " " << viewport_aspect << endl; + SDL_FRect black_bars[2]; // calculate black bars if (screen_aspect > viewport_aspect) { @@ -164,22 +172,26 @@ void SDLContext::set_camera(const Camera & cam) { float render_scale = cam.screen.y / cam.viewport_size.y; float adj_width = cam.viewport_size.x * render_scale; float bar_width = (cam.screen.x - adj_width) / 2; - black_bars[0] = {0, 0, bar_width, (float)cam.screen.y}; - black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float)cam.screen.y}; - cout << render_scale << " " << adj_width << " " << bar_width << " " << cam.screen.y - << " " << cam.viewport_size.y << endl; + black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; + black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; + + bar_size = {bar_width,0}; + scale.x = scale.y = cam.screen.y / cam.viewport_size.y; } else { // letterboxing cout << "letterboxing" << endl; - float render_scale = cam.screen.y / cam.viewport_size.y; - float adj_width = cam.viewport_size.x * render_scale; - float bar_height = (cam.screen.x - adj_width) / 2; + float render_scale = cam.screen.x / cam.viewport_size.x; + float adj_height = cam.viewport_size.y * render_scale; + float bar_height = (cam.screen.y - adj_height) / 2; black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; black_bars[1] = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height}; - cout << render_scale << " " << adj_width << " " << bar_height << " " << cam.screen.y - << " " << cam.viewport_size.y << endl; + + bar_size = {0,bar_height}; + scale.x = scale.y = render_scale; } + cout << "BARS" << endl; + for (int i = 0; i < 2; ++i) { cout << black_bars[i].x << " " << black_bars[i].y << " " << black_bars[i].w << " " << black_bars[i].h << endl; diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index 6030a6e..ead0c72 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -158,7 +158,7 @@ private: * \param img_scale the image multiplier for increasing img size * \return sdl rectangle to draw a dst image to draw on the screen */ - SDL_Rect get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, + SDL_FRect get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, const vec2 & cam_pos, const double & img_scale) const; private: diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 5896c81..f5b9ab3 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -32,14 +32,12 @@ int main(int argc, char * argv[]) { auto img = Texture("asset/texture/test_ap43.png"); - /* Sprite & test_sprite = game_object.add_component( - img, color, Sprite::FlipSettings{true, true}, 1, 1, 500); + img, color, Sprite::FlipSettings{true, true}, 1, 1, 3000); //game_object.add_component(test_sprite, 4, 1, 0).active = true; game_object.add_component(test_sprite, 1, 1, 0).active = true; - */ /* auto & test = game_object.add_component(ParticleEmitter::Data{ .position = {0, 0}, @@ -62,8 +60,9 @@ int main(int argc, char * argv[]) { }); */ - auto & cam = game_object.add_component(Color::WHITE, ivec2{1600, 900}, - vec2{800,800}, 1.0f); + auto & cam = game_object.add_component(Color::WHITE, ivec2{1280, 720}, + vec2{8000,6000}, 1.0f); + cam.offset.x = 4000; /* game_object -- cgit v1.2.3 From ad4f8acfb252b8be3a3fbb74ed97b32e498a26a4 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Sat, 30 Nov 2024 15:43:36 +0100 Subject: zoomed viewport --- src/crepe/facade/SDLContext.cpp | 14 +++++++------- src/example/rendering_particle.cpp | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) (limited to 'src/example') diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 0ba1db4..6d79c73 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -118,9 +118,9 @@ SDL_FRect SDLContext::get_dst_rect(const Sprite & sprite, const vec2 & pos, cons vec2 size = { (sprite.height * sprite.aspect_ratio), sprite.height}; - size *= scale * img_scale * cam.zoom ; + size *= scale * img_scale; - vec2 screen_pos = (pos - cam_pos + cam.viewport_size / 2) * scale - size / 2 + bar_size; + vec2 screen_pos = (pos - cam_pos + (cam.viewport_size / cam.zoom ) / 2) * scale - size / 2 + bar_size; cout << size.x << " " << size.y << endl; cout << pos.x << " " << pos.y << endl; @@ -161,7 +161,7 @@ void SDLContext::set_camera(const Camera & cam) { } double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; - double viewport_aspect = cam.viewport_size.x / cam.viewport_size.y; + double viewport_aspect = (cam.viewport_size.x / cam.zoom ) / (cam.viewport_size.y / cam.zoom); SDL_FRect black_bars[2]; @@ -169,18 +169,18 @@ void SDLContext::set_camera(const Camera & cam) { if (screen_aspect > viewport_aspect) { // pillarboxing cout << "pillarboxing" << endl; - float render_scale = cam.screen.y / cam.viewport_size.y; - float adj_width = cam.viewport_size.x * render_scale; + float render_scale = cam.screen.y / (cam.viewport_size.y / cam.zoom); + float adj_width = (cam.viewport_size.x / cam.zoom )* render_scale; float bar_width = (cam.screen.x - adj_width) / 2; black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; bar_size = {bar_width,0}; - scale.x = scale.y = cam.screen.y / cam.viewport_size.y; + scale.x = scale.y = render_scale; } else { // letterboxing cout << "letterboxing" << endl; - float render_scale = cam.screen.x / cam.viewport_size.x; + float render_scale = cam.screen.x / (cam.viewport_size.x * cam.zoom); float adj_height = cam.viewport_size.y * render_scale; float bar_height = (cam.screen.y - adj_height) / 2; black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index f5b9ab3..b4bfeb2 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -33,7 +33,7 @@ int main(int argc, char * argv[]) { auto img = Texture("asset/texture/test_ap43.png"); Sprite & test_sprite = game_object.add_component( - img, color, Sprite::FlipSettings{true, true}, 1, 1, 3000); + img, color, Sprite::FlipSettings{true, true}, 1, 1, 300); //game_object.add_component(test_sprite, 4, 1, 0).active = true; game_object.add_component(test_sprite, 1, 1, 0).active = true; @@ -61,8 +61,8 @@ int main(int argc, char * argv[]) { */ auto & cam = game_object.add_component(Color::WHITE, ivec2{1280, 720}, - vec2{8000,6000}, 1.0f); - cam.offset.x = 4000; + vec2{400,300}, 0.5f); + cam.offset.x = 0; /* game_object -- cgit v1.2.3 From 1520cb55ad714583c3903f2988b0fdc38ede9c18 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Sat, 30 Nov 2024 16:44:47 +0100 Subject: cleaner camera implementation --- src/crepe/facade/SDLContext.cpp | 101 ++++++++++++++++--------------------- src/crepe/facade/SDLContext.h | 26 ++++++++-- src/crepe/system/RenderSystem.cpp | 10 ++-- src/crepe/system/RenderSystem.h | 5 +- src/example/rendering_particle.cpp | 8 +-- 5 files changed, 74 insertions(+), 76 deletions(-) (limited to 'src/example') diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 6d79c73..1f729b2 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -94,11 +94,13 @@ void SDLContext::handle_events(bool & running) { */ } -void SDLContext::clear_screen() { - SDL_SetRenderDrawColor(this->game_renderer.get(), 255, 255, 255, 255); - SDL_RenderClear(this->game_renderer.get()); +void SDLContext::clear_screen() { SDL_RenderClear(this->game_renderer.get()); } +void SDLContext::present_screen() { + SDL_SetRenderDrawColor(this->game_renderer.get(), 0, 0, 0, 255); + SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[0]); + SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[1]); + SDL_RenderPresent(this->game_renderer.get()); } -void SDLContext::present_screen() { SDL_RenderPresent(this->game_renderer.get()); } SDL_Rect SDLContext::get_src_rect(const Sprite & sprite) const { return SDL_Rect{ @@ -109,23 +111,16 @@ SDL_Rect SDLContext::get_src_rect(const Sprite & sprite) const { }; } -vec2 bar_size; -vec2 scale; +SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { -SDL_FRect SDLContext::get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, - const vec2 & cam_pos, const double & img_scale) const { + vec2 size = {(ctx.sprite.height * ctx.sprite.aspect_ratio), ctx.sprite.height}; + const CameraValues & cam = ctx.cam; - vec2 size = { (sprite.height * sprite.aspect_ratio), sprite.height}; - - size *= scale * img_scale; + size *= cam.render_scale * ctx.img_scale; - vec2 screen_pos = (pos - cam_pos + (cam.viewport_size / cam.zoom ) / 2) * scale - size / 2 + bar_size; - - cout << size.x << " " << size.y << endl; - cout << pos.x << " " << pos.y << endl; - cout << scale.x << " " << scale.y << endl; - cout << screen_pos.x << " " << screen_pos.y << endl; + vec2 screen_pos = (ctx.pos - cam.cam_pos + (cam.zoomed_viewport) / 2) * cam.render_scale + - size / 2 + cam.bar_size; return SDL_FRect{ .x = screen_pos.x, @@ -142,16 +137,18 @@ void SDLContext::draw(const RenderContext & ctx) { | (SDL_FLIP_VERTICAL * ctx.sprite.flip.flip_y)); SDL_Rect srcrect = this->get_src_rect(ctx.sprite); - SDL_FRect dstrect - = this->get_dst_rect(ctx.sprite, ctx.pos, ctx.cam, ctx.cam_pos, ctx.scale); - - cout << dstrect.x << " " << dstrect.y << " " << dstrect.w << " " << dstrect.h << endl; + SDL_FRect dstrect = this->get_dst_rect(SDLContext::DstRect{ + .sprite = ctx.sprite, + .cam = ctx.cam, + .pos = ctx.pos, + .img_scale = ctx.scale, + }); SDL_RenderCopyExF(this->game_renderer.get(), ctx.sprite.sprite_image.texture.get(), - &srcrect, &dstrect, ctx.angle, NULL, render_flip); + &srcrect, &dstrect, ctx.angle, NULL, render_flip); } -void SDLContext::set_camera(const Camera & cam) { +void SDLContext::set_camera(const Camera & cam, CameraValues & ctx) { // resize window int w, h; @@ -160,62 +157,50 @@ void SDLContext::set_camera(const Camera & cam) { SDL_SetWindowSize(this->game_window.get(), cam.screen.x, cam.screen.y); } - double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; - double viewport_aspect = (cam.viewport_size.x / cam.zoom ) / (cam.viewport_size.y / cam.zoom); + vec2 & zoomed_viewport = ctx.zoomed_viewport; + vec2 & bar_size = ctx.bar_size; + vec2 & render_scale = ctx.render_scale; + zoomed_viewport = cam.viewport_size * cam.zoom; + double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; + double viewport_aspect = zoomed_viewport.x / zoomed_viewport.y; - SDL_FRect black_bars[2]; - // calculate black bars + // calculate black bars if (screen_aspect > viewport_aspect) { // pillarboxing - cout << "pillarboxing" << endl; - float render_scale = cam.screen.y / (cam.viewport_size.y / cam.zoom); - float adj_width = (cam.viewport_size.x / cam.zoom )* render_scale; + float scale = cam.screen.y / zoomed_viewport.y; + float adj_width = zoomed_viewport.x * scale; float bar_width = (cam.screen.x - adj_width) / 2; - black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; - black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; + this->black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; + this->black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; - bar_size = {bar_width,0}; - scale.x = scale.y = render_scale; + bar_size = {bar_width, 0}; + render_scale.x = render_scale.y = scale; } else { // letterboxing - cout << "letterboxing" << endl; - float render_scale = cam.screen.x / (cam.viewport_size.x * cam.zoom); - float adj_height = cam.viewport_size.y * render_scale; + float scale = cam.screen.x / (cam.viewport_size.x * cam.zoom); + float adj_height = cam.viewport_size.y * scale; float bar_height = (cam.screen.y - adj_height) / 2; - black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; - black_bars[1] = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height}; - - bar_size = {0,bar_height}; - scale.x = scale.y = render_scale; - } + this->black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; + this->black_bars[1] + = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height}; - cout << "BARS" << endl; - - for (int i = 0; i < 2; ++i) { - cout << black_bars[i].x << " " << black_bars[i].y << " " << black_bars[i].w << " " - << black_bars[i].h << endl; + bar_size = {0, bar_height}; + render_scale.x = render_scale.y = scale; } - SDL_SetRenderDrawColor(this->game_renderer.get(), 0, 0, 0, 255); - SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[0]); - SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[1]); - - /* - // set bg color SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, cam.bg_color.g, cam.bg_color.b, cam.bg_color.a); SDL_Rect bg = { .x = 0, .y = 0, - .w = (int)cam.viewport_size.x, - .h = (int)cam.viewport_size.y, + .w = cam.screen.x, + .h = cam.screen.y, }; + // fill bg color SDL_RenderFillRect(this->game_renderer.get(), &bg); - - */ } uint64_t SDLContext::get_ticks() const { return SDL_GetTicks64(); } diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index ead0c72..285eee2 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -29,15 +29,23 @@ typedef SDL_Keycode CREPE_KEYCODES; */ class SDLContext { public: + //! data that the camera component cannot hold + struct CameraValues { + vec2 zoomed_viewport; + vec2 render_scale; + vec2 bar_size; + vec2 cam_pos; + }; + struct RenderContext { const Sprite & sprite; - const Camera & cam; - const vec2 & cam_pos; + const CameraValues & cam; const vec2 & pos; const double & angle; const double & scale; }; + public: /** * \brief Gets the singleton instance of SDLContext. @@ -137,9 +145,15 @@ private: * \brief sets the background of the camera (will be adjusted in future PR) * \param camera Reference to the Camera object. */ - void set_camera(const Camera & camera); + void set_camera(const Camera & camera, CameraValues & ctx); private: + struct DstRect { + const Sprite & sprite; + const CameraValues & cam; + const vec2 & pos; + const double & img_scale; + }; /** * \brief calculates the sqaure size of the image * @@ -158,8 +172,7 @@ private: * \param img_scale the image multiplier for increasing img size * \return sdl rectangle to draw a dst image to draw on the screen */ - SDL_FRect get_dst_rect(const Sprite & sprite, const vec2 & pos, const Camera & cam, - const vec2 & cam_pos, const double & img_scale) const; + SDL_FRect get_dst_rect(const DstRect & ctx) const; private: //! sdl Window @@ -167,6 +180,9 @@ private: //! renderer for the crepe engine std::unique_ptr> game_renderer; + + //! black bars rectangle to draw + SDL_FRect black_bars[2]; }; } // namespace crepe diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index c196bb1..944ac86 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -32,8 +32,8 @@ const Camera & RenderSystem::update_camera() { if (!cam.active) continue; const Transform & transform = mgr.get_components_by_id(cam.game_object_id).front().get(); - this->context.set_camera(cam); - this->cam_pos = transform.position + cam.offset; + this->context.set_camera(cam, this->cam_ctx); + this->cam_ctx.cam_pos = transform.position + cam.offset; return cam; } throw std::runtime_error("No active cameras in current scene"); @@ -79,8 +79,7 @@ bool RenderSystem::render_particle(const Sprite & sprite, const Camera & cam, this->context.draw(SDLContext::RenderContext{ .sprite = sprite, - .cam = cam, - .cam_pos = this->cam_pos, + .cam = this->cam_ctx, .pos = p.position, .angle = p.angle, .scale = scale, @@ -93,8 +92,7 @@ void RenderSystem::render_normal(const Sprite & sprite, const Camera & cam, const Transform & tm) { this->context.draw(SDLContext::RenderContext{ .sprite = sprite, - .cam = cam, - .cam_pos = this->cam_pos, + .cam = this->cam_ctx, .pos = tm.position, .angle = tm.rotation, .scale = tm.scale, diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h index e70831e..9ff015e 100644 --- a/src/crepe/system/RenderSystem.h +++ b/src/crepe/system/RenderSystem.h @@ -76,9 +76,8 @@ private: private: SDLContext & context = SDLContext::get_instance(); - - //! camera postion in the current scene - vec2 cam_pos; + + SDLContext::CameraValues cam_ctx; }; } // namespace crepe diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index b4bfeb2..9dcaa49 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -33,7 +33,7 @@ int main(int argc, char * argv[]) { auto img = Texture("asset/texture/test_ap43.png"); Sprite & test_sprite = game_object.add_component( - img, color, Sprite::FlipSettings{true, true}, 1, 1, 300); + img, color, Sprite::FlipSettings{true, true}, 1, 1, 1.95); //game_object.add_component(test_sprite, 4, 1, 0).active = true; game_object.add_component(test_sprite, 1, 1, 0).active = true; @@ -60,9 +60,9 @@ int main(int argc, char * argv[]) { }); */ - auto & cam = game_object.add_component(Color::WHITE, ivec2{1280, 720}, - vec2{400,300}, 0.5f); - cam.offset.x = 0; + auto & cam = game_object.add_component(Color::RED, ivec2{1280, 720}, + vec2{2.59,1.95}, 2.0); + cam.offset.x = 1; /* game_object -- cgit v1.2.3 From 6ae0b9038e432869b506cbdfe2779e97d3732d87 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Sat, 30 Nov 2024 21:02:27 +0100 Subject: improved animator --- src/crepe/api/Animator.cpp | 1 - src/crepe/api/Animator.h | 32 +++++++++++++------ src/crepe/api/LoopManager.cpp | 6 +++- src/crepe/api/Sprite.cpp | 5 +-- src/crepe/api/Sprite.h | 8 ++--- src/crepe/facade/SDLContext.cpp | 6 +++- src/crepe/system/AnimatorSystem.cpp | 26 ++++++++++----- src/crepe/system/AnimatorSystem.h | 7 +++-- src/example/rendering_particle.cpp | 63 +++++++++++++++++++------------------ 9 files changed, 93 insertions(+), 61 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index 45f67f6..7fe49ee 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -18,7 +18,6 @@ Animator::Animator(game_object_id_t id, Sprite & ss, int row, int col, int col_a this->spritesheet.mask.w /= row; this->spritesheet.mask.x = 0; this->spritesheet.mask.y = col_animator * this->spritesheet.mask.h; - this->active = false; // need to do this for to get the aspect ratio for a single clipping in the spritesheet this->spritesheet.aspect_ratio diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 6c506aa..ede450a 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -17,11 +17,6 @@ class SDLContext; */ class Animator : public Component { -public: - //TODO: need to implement this - void loop(); - void stop(); - public: /** * \brief Constructs an Animator object that will control animations for a sprite sheet. @@ -57,15 +52,32 @@ private: //! The current row being animated. int curr_row = 0; - //TODO: Is this necessary? - //int fps; + //! should the animation loop + bool looping = false; + + //! starting frame for cycling + int cycle_start = 0; + + //! end frame for cycling (-1 --> use last frame) + int cycle_end = -1; + + //! frames per second for animation + int fps = 1; + + int offset_x = 0; + +public: + void loop() { this->looping = true; } + void play() {this->active = true;} + void pause() {this->active = false;} + void stop() {this->active = false; this->curr_col = 0; this->curr_row = 0;} + void set_fps(int fps) {this->fps = fps;} + void set_cycle_range(int start, int end) {this->cycle_start = start, this->cycle_end = end;} + void set_anim(int col) {this->curr_row = 0; this->curr_col = col; } private: //! AnimatorSystem adjust the private member parameters of Animator; friend class AnimatorSystem; - - //! SDLContext reads the Animator member var's - friend class SDLContext; }; } // namespace crepe // diff --git a/src/crepe/api/LoopManager.cpp b/src/crepe/api/LoopManager.cpp index 7edf4d1..88ca704 100644 --- a/src/crepe/api/LoopManager.cpp +++ b/src/crepe/api/LoopManager.cpp @@ -58,6 +58,7 @@ void LoopManager::setup() { this->game_running = true; LoopTimer::get_instance().start(); LoopTimer::get_instance().set_fps(200); + this->scene_manager.load_next_scene(); } void LoopManager::render() { @@ -66,4 +67,7 @@ void LoopManager::render() { } } -void LoopManager::update() { LoopTimer & timer = LoopTimer::get_instance(); } +void LoopManager::update() { + LoopTimer & timer = LoopTimer::get_instance(); + this->get_system().update(); +} diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index 1d57b53..29e415f 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -6,19 +6,20 @@ #include "Component.h" #include "Sprite.h" #include "Texture.h" +#include "types.h" using namespace std; using namespace crepe; Sprite::Sprite(game_object_id_t id, Texture & image, const Color & color, - const FlipSettings & flip, int sort_layer, int order_layer, float height) + const FlipSettings & flip, int sort_layer, int order_layer, const vec2 & size) : Component(id), color(color), flip(flip), sprite_image(std::move(image)), sorting_in_layer(sort_layer), order_in_layer(order_layer), - height(height) { + size(size) { dbg_trace(); diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index 7d9c14b..f04f70c 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -1,11 +1,10 @@ #pragma once -#include - #include "../Component.h" #include "Color.h" #include "Texture.h" +#include "types.h" namespace crepe { @@ -41,7 +40,7 @@ public: * \param height the height of the image in game units */ Sprite(game_object_id_t id, Texture & image, const Color & color, - const FlipSettings & flip, int sort_layer, int order_layer, float height); + const FlipSettings & flip, int sort_layer, int order_layer, const vec2 & size); /** * \brief Destroys the Sprite instance. @@ -62,8 +61,7 @@ public: //! Order within the sorting layer const int order_in_layer; - //! height in world units - const float height; + vec2 size; /** * \aspect_ratio ratio of the img so that scaling will not become weird diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 1f729b2..f0a21d5 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -113,7 +113,11 @@ SDL_Rect SDLContext::get_src_rect(const Sprite & sprite) const { SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { - vec2 size = {(ctx.sprite.height * ctx.sprite.aspect_ratio), ctx.sprite.height}; + + vec2 size = { + ctx.sprite.size.x == 0 && ctx.sprite.size.y != 0 ? ctx.sprite.size.y * ctx.sprite.aspect_ratio : ctx.sprite.size.x, + ctx.sprite.size.y == 0 && ctx.sprite.size.x != 0 ? ctx.sprite.size.x / ctx.sprite.aspect_ratio : ctx.sprite.size.y + }; const CameraValues & cam = ctx.cam; diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index 4c40940..6a84150 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -1,7 +1,6 @@ -#include + #include "api/Animator.h" -#include "facade/SDLContext.h" #include "AnimatorSystem.h" #include "ComponentManager.h" @@ -13,12 +12,25 @@ void AnimatorSystem::update() { RefVector animations = mgr.get_components_by_type(); - uint64_t tick = SDLContext::get_instance().get_ticks(); + double elapsed_time = this->timer.get_current_time(); + for (Animator & a : animations) { if (!a.active) continue; - // (10 frames per second) - a.curr_row = (tick / 100) % a.row; - a.spritesheet.mask.x = (a.curr_row * a.spritesheet.mask.w) + a.curr_col; - a.spritesheet.mask = a.spritesheet.mask; + + double frame_duration = 1.0f / a.fps; + + int cycle_end = (a.cycle_end == -1) ? a.row : cycle_end; + int total_frames = cycle_end - a.cycle_start; + + + int curr_frame = static_cast(elapsed_time / frame_duration) % total_frames; + + a.curr_row = a.cycle_start + curr_frame; + a.spritesheet.mask.x = std::clamp((a.curr_row * a.spritesheet.mask.w - a.offset_x), 0, a.spritesheet.mask.w); + a.spritesheet.mask.y = (a.curr_col * a.spritesheet.mask.h); + + if (!a.looping && curr_frame == total_frames) { + a.active = false; + } } } diff --git a/src/crepe/system/AnimatorSystem.h b/src/crepe/system/AnimatorSystem.h index f8179a9..e8a5158 100644 --- a/src/crepe/system/AnimatorSystem.h +++ b/src/crepe/system/AnimatorSystem.h @@ -1,9 +1,7 @@ #pragma once #include "System.h" - -//TODO: -// control if flip works with animation system +#include "api/LoopTimer.h" namespace crepe { @@ -26,6 +24,9 @@ public: * looping). */ void update() override; + +private: + LoopTimer & timer = LoopTimer::get_instance(); }; } // namespace crepe diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 9dcaa49..026c9ce 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -1,5 +1,7 @@ #include "api/Animator.h" #include "api/Camera.h" +#include "api/LoopManager.h" +#include "api/LoopTimer.h" #include "system/AnimatorSystem.h" #include "system/ParticleSystem.h" #include @@ -16,29 +18,10 @@ #include #include -#include - using namespace crepe; using namespace std; -int main(int argc, char * argv[]) { - ComponentManager mgr; - GameObject game_object = mgr.new_object("", "", vec2{0, 0}, 0, 1); - RenderSystem sys{mgr}; - ParticleSystem psys{mgr}; - AnimatorSystem asys{mgr}; - - Color color(255, 255, 255, 255); - - auto img = Texture("asset/texture/test_ap43.png"); - - Sprite & test_sprite = game_object.add_component( - img, color, Sprite::FlipSettings{true, true}, 1, 1, 1.95); - - //game_object.add_component(test_sprite, 4, 1, 0).active = true; - game_object.add_component(test_sprite, 1, 1, 0).active = true; - - /* +/* auto & test = game_object.add_component(ParticleEmitter::Data{ .position = {0, 0}, .max_particles = 10, @@ -60,9 +43,35 @@ int main(int argc, char * argv[]) { }); */ - auto & cam = game_object.add_component(Color::RED, ivec2{1280, 720}, - vec2{2.59,1.95}, 2.0); - cam.offset.x = 1; +class TestScene : public Scene { +public: + using Scene::Scene; + + void load_scene() { + ComponentManager & mgr = this->component_manager; + GameObject game_object = mgr.new_object("", "", vec2{0, 0}, 0, 1); + + Color color(255, 255, 255, 255); + + auto img = Texture("asset/spritesheet/spritesheet_test.png"); + + Sprite & test_sprite = game_object.add_component( + img, color, Sprite::FlipSettings{true, true}, 1, 1, vec2{1, 1}); + + //game_object.add_component(test_sprite, 4, 1, 0).active = true; + game_object.add_component(test_sprite, 4, 1, 0).active = true; + + auto & cam = game_object.add_component(Color::RED, ivec2{1280, 720}, + vec2{2.59, 1.95}, 2.0); + } + + string get_name() const { return "TestScene"; }; +}; + +int main(int argc, char * argv[]) { + LoopManager engine; + engine.add_scene(); + engine.start(); /* game_object @@ -73,13 +82,5 @@ int main(int argc, char * argv[]) { = 6; */ - auto start = std::chrono::steady_clock::now(); - while (std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) { - psys.update(); - asys.update(); - sys.update(); - SDL_Delay(10); - } - return 0; } -- cgit v1.2.3 From 135af8b0e0eaf8a5a5b7e1a42bfb20bb14ec97e5 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Mon, 2 Dec 2024 18:51:47 +0100 Subject: tmp commit --- src/crepe/api/Animator.h | 2 +- src/crepe/api/Sprite.h | 4 ++-- src/crepe/system/AnimatorSystem.cpp | 9 +++++---- src/example/rendering_particle.cpp | 11 +++++------ 4 files changed, 13 insertions(+), 13 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 188f193..511d6ef 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -89,7 +89,7 @@ public: ~Animator(); // dbg_trace -private: +public: //! A reference to the Sprite sheet containing. Sprite & spritesheet; diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index 96b57e1..354f663 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -74,10 +74,10 @@ public: vec2 size; //! independent sprite angle. rotating clockwise direction in degrees - double angle_offset; + double angle_offset = 0; //! independent sprite scale multiplier - double scale; + double scale = 1; /** * \aspect_ratio ratio of the img so that scaling will not become weird diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index ee00728..1650b3d 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -4,6 +4,7 @@ #include "AnimatorSystem.h" #include "ComponentManager.h" +#include using namespace crepe; @@ -25,11 +26,11 @@ void AnimatorSystem::update() { int curr_frame = static_cast(elapsed_time / frame_duration) % total_frames; a.curr_row = a.cycle_start + curr_frame; - a.spritesheet.mask.x = std::clamp((a.curr_row * a.spritesheet.mask.w - a.offset_x), 0, - a.spritesheet.mask.w); + a.spritesheet.mask.x = a.curr_row * a.spritesheet.mask.w; a.spritesheet.mask.y = (a.curr_col * a.spritesheet.mask.h); - - if (!a.looping && curr_frame == total_frames) { + + std::cout << curr_frame << " " << total_frames << std::endl; + if (!a.looping && curr_frame == 0) { a.active = false; } } diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 026c9ce..5a50d27 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -53,16 +53,15 @@ public: Color color(255, 255, 255, 255); - auto img = Texture("asset/spritesheet/spritesheet_test.png"); + auto img = Texture("asset/spritesheet/pokemon_spritesheet.png"); Sprite & test_sprite = game_object.add_component( - img, color, Sprite::FlipSettings{true, true}, 1, 1, vec2{1, 1}); + img, color, Sprite::FlipSettings{false, false}, 1, 1, vec2{100, 100}); - //game_object.add_component(test_sprite, 4, 1, 0).active = true; - game_object.add_component(test_sprite, 4, 1, 0).active = true; + auto & anim = game_object.add_component(test_sprite, 4, 4, 0); - auto & cam = game_object.add_component(Color::RED, ivec2{1280, 720}, - vec2{2.59, 1.95}, 2.0); + auto & cam = game_object.add_component(Color::, ivec2{720, 1280}, + vec2{400, 400}, 1.0); } string get_name() const { return "TestScene"; }; -- cgit v1.2.3 From a84ca09e97d466643f022acfffcf4c6a77f42052 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Mon, 2 Dec 2024 20:02:14 +0100 Subject: making struct constructors --- src/crepe/api/Animator.cpp | 34 ++++++------- src/crepe/api/Animator.h | 66 +++++++++++++------------ src/crepe/api/Camera.cpp | 11 +---- src/crepe/api/Camera.h | 37 +++++++------- src/crepe/api/Sprite.cpp | 17 +++---- src/crepe/api/Sprite.h | 98 +++++++++++++++++-------------------- src/crepe/facade/SDLContext.cpp | 25 +++++----- src/crepe/system/AnimatorSystem.cpp | 17 ++++--- src/crepe/system/RenderSystem.cpp | 5 +- src/example/rendering_particle.cpp | 19 +++++-- 10 files changed, 166 insertions(+), 163 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index 0b7e86d..ce824e6 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -7,37 +7,37 @@ using namespace crepe; -Animator::Animator(game_object_id_t id, Sprite & ss, int row, int col, int col_animator) +Animator::Animator(game_object_id_t id, const Animator::Data & ctx) : Component(id), - spritesheet(ss), - row(row), - col(col) { + data(ctx) +{ dbg_trace(); - this->spritesheet.mask.h /= col; - this->spritesheet.mask.w /= row; - this->spritesheet.mask.x = 0; - this->spritesheet.mask.y = col_animator * this->spritesheet.mask.h; + this->data.spritesheet.mask.h /= this->data.col; + this->data.spritesheet.mask.w /= this->data.row; + this->data.spritesheet.mask.x = 0; + this->data.spritesheet.mask.y = this->data.col * this->data.spritesheet.mask.h; // need to do this for to get the aspect ratio for a single clipping in the spritesheet - this->spritesheet.aspect_ratio - = static_cast(this->spritesheet.mask.w) / this->spritesheet.mask.h; + Sprite & ss = this->data.spritesheet; + ss.data.aspect_ratio + = static_cast(this->data.spritesheet.mask.w) / this->data.spritesheet.mask.h; } Animator::~Animator() { dbg_trace(); } -void Animator::loop() { this->looping = true; } +void Animator::loop() { this->data.looping = true; } void Animator::play() { this->active = true; } void Animator::pause() { this->active = false; } void Animator::stop() { this->active = false; - this->curr_col = 0; - this->curr_row = 0; + this->data.curr_col = 0; + this->data.curr_row = 0; } -void Animator::set_fps(int fps) { this->fps = fps; } +void Animator::set_fps(int fps) { this->data.fps = fps; } void Animator::set_cycle_range(int start, int end) { - this->cycle_start = start, this->cycle_end = end; + this->data.cycle_start = start, this->data.cycle_end = end; } void Animator::set_anim(int col) { - this->curr_row = 0; - this->curr_col = col; + this->data.curr_row = 0; + this->data.curr_col = col; } diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 511d6ef..194a9cf 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -16,6 +16,39 @@ class SDLContext; * sheet. It can be used to play animations, loop them, or stop them. */ class Animator : public Component { +public: + struct Data { + //! A reference to the Sprite sheet containing. + Sprite & spritesheet; + + //! The maximum number of columns in the sprite sheet. + const int col; + + //! The maximum number of rows in the sprite sheet. + const int row; + + //! frames per second for animation + int fps; + + //! The current col being animated. + int curr_col; + + //! The current row being animated. + int curr_row = 0; + + //! should the animation loop + bool looping = false; + + //! starting frame for cycling + int cycle_start = 0; + + //! end frame for cycling (-1 --> use last frame) + int cycle_end = -1; + + + //! offset in pixels. + int offset_x = 0; + }; public: /** @@ -85,40 +118,11 @@ public: * This constructor sets up the Animator with the given parameters, and initializes the * animation system. */ - Animator(uint32_t id, Sprite & spritesheet, int row, int col, int col_animate); - + Animator(uint32_t id, const Animator::Data & ctx); ~Animator(); // dbg_trace public: - //! A reference to the Sprite sheet containing. - Sprite & spritesheet; - - //! The maximum number of columns in the sprite sheet. - const int col; - - //! The maximum number of rows in the sprite sheet. - const int row; - - //! The current col being animated. - int curr_col = 0; - - //! The current row being animated. - int curr_row = 0; - - //! should the animation loop - bool looping = false; - - //! starting frame for cycling - int cycle_start = 0; - - //! end frame for cycling (-1 --> use last frame) - int cycle_end = -1; - - //! frames per second for animation - int fps = 1; - - //! offset in pixels. - int offset_x = 0; + Animator::Data data; private: //! AnimatorSystem adjust the private member parameters of Animator; diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp index 39d8ab0..27bcb35 100644 --- a/src/crepe/api/Camera.cpp +++ b/src/crepe/api/Camera.cpp @@ -2,19 +2,12 @@ #include "util/Log.h" #include "Camera.h" -#include "Color.h" #include "Component.h" using namespace crepe; -Camera::Camera(game_object_id_t id, const Color & bg_color, const ivec2 & screen, - const vec2 & viewport_size, const double & zoom, const vec2 & offset) - : Component(id), - bg_color(bg_color), - offset(offset), - screen(screen), - viewport_size(viewport_size), - zoom(zoom) { +Camera::Camera(game_object_id_t id, const Data & ctx) : Component(id), data(ctx) { + dbg_trace(); } diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h index 2d8fa48..e466d36 100644 --- a/src/crepe/api/Camera.h +++ b/src/crepe/api/Camera.h @@ -14,32 +14,35 @@ namespace crepe { * position, and zoom level. It controls what part of the game world is visible on the screen. */ class Camera : public Component { +public: + struct Data { + //! Background color of the camera view. + const Color bg_color; + + //! screen the display size in pixels ( output resolution ) + const ivec2 screen; + + //! viewport is the area of the world visible through the camera (in world units) + const vec2 viewport_size; + + //! Zoom level of the camera view. + double zoom; + + //! offset postion from the game object transform component + vec2 offset; + }; public: /** * \brief Constructs a Camera with the specified ID and background color. * \param id Unique identifier for the camera component. - * \param bg_color Background color for the camera view. + * \param ctx the camera component data */ - Camera(game_object_id_t id, const Color & bg_color, const ivec2 & screen, - const vec2 & viewport_size, const double & zoom, const vec2 & offset = {0, 0}); + Camera(game_object_id_t id, const Data & ctx); ~Camera(); // dbg_trace only public: - //! Background color of the camera view. - const Color bg_color; - - //! offset postion from the game object transform component - vec2 offset; - - //! screen the display size in pixels ( output resolution ) - const ivec2 screen; - - //! viewport is the area of the world visible through the camera (in world units) - const vec2 viewport_size; - - //! Zoom level of the camera view. - const double zoom; + Camera::Data data; public: /** diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index 29e415f..fe495a1 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -11,21 +11,16 @@ using namespace std; using namespace crepe; -Sprite::Sprite(game_object_id_t id, Texture & image, const Color & color, - const FlipSettings & flip, int sort_layer, int order_layer, const vec2 & size) +Sprite::Sprite(game_object_id_t id, Texture & texture, const Sprite::Data & ctx) : Component(id), - color(color), - flip(flip), - sprite_image(std::move(image)), - sorting_in_layer(sort_layer), - order_in_layer(order_layer), - size(size) { + texture(std::move(texture)), + data(ctx) { dbg_trace(); - this->mask.w = sprite_image.get_width(); - this->mask.h = sprite_image.get_height(); - this->aspect_ratio = static_cast(this->mask.w) / this->mask.h; + this->mask.w = this->texture.get_width(); + this->mask.h = this->texture.get_height(); + this->data.aspect_ratio = static_cast(this->mask.w) / this->mask.h; } Sprite::~Sprite() { dbg_trace(); } diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index 354f663..aef6a8d 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -19,73 +19,67 @@ class AnimatorSystem; * flip settings, and is managed in layers with defined sorting orders. */ class Sprite : public Component { - public: struct FlipSettings { bool flip_x = false; bool flip_y = false; }; + struct Data { + //! Color tint of the sprite + Color color; + + //! Flip settings for the sprite + FlipSettings flip; + + //! Layer sorting level of the sprite + const int sorting_in_layer; + + //! Order within the sorting layer + const int order_in_layer; + + /** + * \size width and height of the sprite in game units + * + * if height is filled in and not width it will multiply width by aspect_ratio. + * if width is filled in and not height it will multiply height by aspect_ratio. + * if neither is filled it will not show sprite because size will be zero + * if both are filled will it use the width and height without making sure the aspect_ratio + * is correct + */ + vec2 size; + + //! independent sprite angle. rotating clockwise direction in degrees + double angle_offset = 0; + + //! independent sprite scale multiplier + double scale = 1; + + /** + * \aspect_ratio ratio of the img so that scaling will not become weird + * + * cannot be const because if Animator component is addded then ratio becomes scuffed and + * does it need to be calculated again in the Animator + */ + float aspect_ratio; + }; + public: - // TODO: Loek comment in github #27 will be looked another time - // about shared_ptr Texture /** * \brief Constructs a Sprite with specified parameters. * \param game_id Unique identifier for the game object this sprite belongs to. - * \param image Shared pointer to the texture for this sprite. - * \param color Color tint applied to the sprite. - * \param flip Flip settings for horizontal and vertical orientation. - * \param order_layer decides the sorting in layer of the sprite. - * \param sort_layer decides the order in layer of the sprite. - * \param height the height of the image in game units - */ - Sprite(game_object_id_t id, Texture & image, const Color & color, - const FlipSettings & flip, int sort_layer, int order_layer, const vec2 & size); - - /** - * \brief Destroys the Sprite instance. + * \param texture asset of the image + * \param ctx all the sprite data */ + //TODO: texture is outside the Sprite::Data because of the deleted copy constructer. eventually + // texture will go into data when it becomes asset + Sprite(game_object_id_t id, Texture & texture, const Data & ctx); ~Sprite(); //! Texture used for the sprite - const Texture sprite_image; - - //! Color tint of the sprite - Color color; - - //! Flip settings for the sprite - FlipSettings flip; - - //! Layer sorting level of the sprite - const int sorting_in_layer; + const Texture texture; - //! Order within the sorting layer - const int order_in_layer; - - /** - * \size width and height of the sprite in game units - * - * if height is filled in and not width it will multiply width by aspect_ratio. - * if width is filled in and not height it will multiply height by aspect_ratio. - * if neither is filled it will not show sprite because size will be zero - * if both are filled will it use the width and height without making sure the aspect_ratio - * is correct - */ - vec2 size; - - //! independent sprite angle. rotating clockwise direction in degrees - double angle_offset = 0; - - //! independent sprite scale multiplier - double scale = 1; - - /** - * \aspect_ratio ratio of the img so that scaling will not become weird - * - * cannot be const because if Animator component is addded then ratio becomes scuffed and - * does it need to be calculated again in the Animator - */ - float aspect_ratio; + Data data; private: //! Reads the mask of sprite diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index bba26a3..ab3fa45 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -112,17 +112,15 @@ SDL_Rect SDLContext::get_src_rect(const Sprite & sprite) const { SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { - // this might not work all the time because of float checking zero -_- - vec2 size = {ctx.sprite.size.x == 0 && ctx.sprite.size.y != 0 - ? ctx.sprite.size.y * ctx.sprite.aspect_ratio - : ctx.sprite.size.x, - ctx.sprite.size.y == 0 && ctx.sprite.size.x != 0 - ? ctx.sprite.size.x / ctx.sprite.aspect_ratio - : ctx.sprite.size.y}; + const Sprite::Data & data = ctx.sprite.data; + + vec2 size = { + data.size.x == 0 && data.size.y != 0 ? data.size.y * data.aspect_ratio : data.size.x, + data.size.y == 0 && data.size.x != 0 ? data.size.x / data.aspect_ratio : data.size.y}; const CameraValues & cam = ctx.cam; - size *= cam.render_scale * ctx.img_scale * ctx.sprite.scale; + size *= cam.render_scale * ctx.img_scale * data.scale; vec2 screen_pos = (ctx.pos - cam.cam_pos + (cam.zoomed_viewport) / 2) * cam.render_scale - size / 2 + cam.bar_size; @@ -137,9 +135,10 @@ SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { void SDLContext::draw(const RenderContext & ctx) { + const Sprite::Data & data = ctx.sprite.data; SDL_RendererFlip render_flip - = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * ctx.sprite.flip.flip_x) - | (SDL_FLIP_VERTICAL * ctx.sprite.flip.flip_y)); + = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * data.flip.flip_x) + | (SDL_FLIP_VERTICAL * data.flip.flip_y)); SDL_Rect srcrect = this->get_src_rect(ctx.sprite); SDL_FRect dstrect = this->get_dst_rect(SDLContext::DstRect{ @@ -149,10 +148,10 @@ void SDLContext::draw(const RenderContext & ctx) { .img_scale = ctx.scale, }); - double angle = ctx.angle + ctx.sprite.angle_offset; + double angle = ctx.angle + data.angle_offset; - SDL_RenderCopyExF(this->game_renderer.get(), ctx.sprite.sprite_image.texture.get(), - &srcrect, &dstrect, angle, NULL, render_flip); + SDL_RenderCopyExF(this->game_renderer.get(), ctx.sprite.texture.texture.get(), &srcrect, + &dstrect, angle, NULL, render_flip); } void SDLContext::set_camera(const Camera & cam, CameraValues & ctx) { diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index 1650b3d..b1f23d1 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -17,20 +17,21 @@ void AnimatorSystem::update() { for (Animator & a : animations) { if (!a.active) continue; + + Animator::Data & ctx = a.data; + double frame_duration = 1.0f / ctx.fps; - double frame_duration = 1.0f / a.fps; - - int cycle_end = (a.cycle_end == -1) ? a.row : cycle_end; - int total_frames = cycle_end - a.cycle_start; + int cycle_end = (ctx.cycle_end == -1) ? ctx.row : cycle_end; + int total_frames = cycle_end - ctx.cycle_start; int curr_frame = static_cast(elapsed_time / frame_duration) % total_frames; - a.curr_row = a.cycle_start + curr_frame; - a.spritesheet.mask.x = a.curr_row * a.spritesheet.mask.w; - a.spritesheet.mask.y = (a.curr_col * a.spritesheet.mask.h); + ctx.curr_row = ctx.cycle_start + curr_frame; + ctx.spritesheet.mask.x = ctx.curr_row * ctx.spritesheet.mask.w; + ctx.spritesheet.mask.y = (ctx.curr_col * ctx.spritesheet.mask.h); std::cout << curr_frame << " " << total_frames << std::endl; - if (!a.looping && curr_frame == 0) { + if (!ctx.looping && curr_frame == 0) { a.active = false; } } diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 944ac86..08f254f 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -40,8 +40,9 @@ const Camera & RenderSystem::update_camera() { } bool sorting_comparison(const Sprite & a, const Sprite & b) { - if (a.sorting_in_layer < b.sorting_in_layer) return true; - if (a.sorting_in_layer == b.sorting_in_layer) return a.order_in_layer < b.order_in_layer; + if (a.data.sorting_in_layer < b.data.sorting_in_layer) return true; + if (a.data.sorting_in_layer == b.data.sorting_in_layer) + return a.data.order_in_layer < b.data.order_in_layer; return false; } diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 5a50d27..4fd4071 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -56,11 +56,24 @@ public: auto img = Texture("asset/spritesheet/pokemon_spritesheet.png"); Sprite & test_sprite = game_object.add_component( - img, color, Sprite::FlipSettings{false, false}, 1, 1, vec2{100, 100}); + img, Sprite::Data{ + .color = color, + .flip = Sprite::FlipSettings{false, false}, + .sorting_in_layer = 2, + .order_in_layer = 2, + .size = {0, 100}, + .angle_offset = 0, + .scale = 1, + }); - auto & anim = game_object.add_component(test_sprite, 4, 4, 0); + auto & anim = game_object.add_component(Animator::Data{ + .spritesheet = test_sprite, + .col = 4, + .row = 4, + .fps = 10, + }); - auto & cam = game_object.add_component(Color::, ivec2{720, 1280}, + auto & cam = game_object.add_component(Color::WHITE, ivec2{720, 1280}, vec2{400, 400}, 1.0); } -- cgit v1.2.3 From 0a1739de21e5ab270cb45efb6fc0aed092d81227 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Mon, 2 Dec 2024 21:00:54 +0100 Subject: added all the contructor strutcts for animator,sprite and camera --- src/crepe/api/Animator.cpp | 15 +++++++++++++-- src/crepe/api/Animator.h | 8 ++------ src/crepe/api/Camera.cpp | 1 - src/crepe/facade/SDLContext.cpp | 35 ++++++++++++++++++----------------- src/crepe/facade/SDLContext.h | 2 +- src/crepe/system/AnimatorSystem.cpp | 6 ++---- src/crepe/system/RenderSystem.cpp | 2 +- src/example/rendering_particle.cpp | 14 +++++++++++--- 8 files changed, 48 insertions(+), 35 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index ce824e6..1234967 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -9,8 +9,7 @@ using namespace crepe; Animator::Animator(game_object_id_t id, const Animator::Data & ctx) : Component(id), - data(ctx) -{ + data(ctx) { dbg_trace(); this->data.spritesheet.mask.h /= this->data.col; @@ -23,21 +22,33 @@ Animator::Animator(game_object_id_t id, const Animator::Data & ctx) ss.data.aspect_ratio = static_cast(this->data.spritesheet.mask.w) / this->data.spritesheet.mask.h; } + Animator::~Animator() { dbg_trace(); } void Animator::loop() { this->data.looping = true; } + void Animator::play() { this->active = true; } + void Animator::pause() { this->active = false; } + void Animator::stop() { this->active = false; this->data.curr_col = 0; this->data.curr_row = 0; } void Animator::set_fps(int fps) { this->data.fps = fps; } + void Animator::set_cycle_range(int start, int end) { this->data.cycle_start = start, this->data.cycle_end = end; } + void Animator::set_anim(int col) { this->data.curr_row = 0; this->data.curr_col = col; } + +void Animator::next_anim() { + Animator::Data & ctx = this->data; + ctx.curr_row = ctx.curr_row++ % ctx.row; + ctx.spritesheet.mask.x = ctx.curr_row * ctx.spritesheet.mask.w; +} diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 194a9cf..36bc9f4 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -47,6 +47,7 @@ public: //! offset in pixels. + // TODO implement int offset_x = 0; }; @@ -108,12 +109,7 @@ public: * \brief Constructs an Animator object that will control animations for a sprite sheet. * * \param id The unique identifier for the component, typically assigned automatically. - * \param spritesheet A reference to the Sprite object which holds the sprite sheet for - * animation. - * \param row The maximum number of rows in the sprite sheet. - * \param col The maximum number of columns in the sprite sheet. - * \param col_animate The specific col index of the sprite sheet to animate. This allows - * selecting which col to animate from multiple col in the sheet. + * \param ctx animator data * * This constructor sets up the Animator with the given parameters, and initializes the * animation system. diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp index 27bcb35..ff41710 100644 --- a/src/crepe/api/Camera.cpp +++ b/src/crepe/api/Camera.cpp @@ -7,7 +7,6 @@ using namespace crepe; Camera::Camera(game_object_id_t id, const Data & ctx) : Component(id), data(ctx) { - dbg_trace(); } diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index ab3fa45..32461f2 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -156,53 +156,54 @@ void SDLContext::draw(const RenderContext & ctx) { void SDLContext::set_camera(const Camera & cam, CameraValues & ctx) { + const Camera::Data & cam_data = cam.data; // resize window int w, h; SDL_GetWindowSize(this->game_window.get(), &w, &h); - if (w != cam.screen.x || h != cam.screen.y) { - SDL_SetWindowSize(this->game_window.get(), cam.screen.x, cam.screen.y); + if (w != cam_data.screen.x || h != cam_data.screen.y) { + SDL_SetWindowSize(this->game_window.get(), cam_data.screen.x, cam_data.screen.y); } vec2 & zoomed_viewport = ctx.zoomed_viewport; vec2 & bar_size = ctx.bar_size; vec2 & render_scale = ctx.render_scale; - zoomed_viewport = cam.viewport_size * cam.zoom; - double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; + zoomed_viewport = cam_data.viewport_size * cam_data.zoom; + double screen_aspect = static_cast(cam_data.screen.x) / cam_data.screen.y; double viewport_aspect = zoomed_viewport.x / zoomed_viewport.y; // calculate black bars if (screen_aspect > viewport_aspect) { // pillarboxing - float scale = cam.screen.y / zoomed_viewport.y; + float scale = cam_data.screen.y / zoomed_viewport.y; float adj_width = zoomed_viewport.x * scale; - float bar_width = (cam.screen.x - adj_width) / 2; - this->black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; - this->black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; + float bar_width = (cam_data.screen.x - adj_width) / 2; + this->black_bars[0] = {0, 0, bar_width, (float) cam_data.screen.y}; + this->black_bars[1] = {(cam_data.screen.x - bar_width), 0, bar_width, (float) cam_data.screen.y}; bar_size = {bar_width, 0}; render_scale.x = render_scale.y = scale; } else { // letterboxing - float scale = cam.screen.x / (cam.viewport_size.x * cam.zoom); - float adj_height = cam.viewport_size.y * scale; - float bar_height = (cam.screen.y - adj_height) / 2; - this->black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; + float scale = cam_data.screen.x / (cam_data.viewport_size.x * cam_data.zoom); + float adj_height = cam_data.viewport_size.y * scale; + float bar_height = (cam_data.screen.y - adj_height) / 2; + this->black_bars[0] = {0, 0, (float) cam_data.screen.x, bar_height}; this->black_bars[1] - = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height}; + = {0, (cam_data.screen.y - bar_height), (float) cam_data.screen.x, bar_height}; bar_size = {0, bar_height}; render_scale.x = render_scale.y = scale; } - SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r, cam.bg_color.g, - cam.bg_color.b, cam.bg_color.a); + SDL_SetRenderDrawColor(this->game_renderer.get(), cam_data.bg_color.r, cam_data.bg_color.g, + cam_data.bg_color.b, cam_data.bg_color.a); SDL_Rect bg = { .x = 0, .y = 0, - .w = cam.screen.x, - .h = cam.screen.y, + .w = cam_data.screen.x, + .h = cam_data.screen.y, }; // fill bg color diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index 0a6fce6..a0d1da8 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -128,7 +128,7 @@ private: /** * \brief Draws a sprite to the screen using the specified transform and camera. - * \param RenderCtx Reference to rendering data to draw + * \param RenderContext Reference to rendering data to draw */ void draw(const RenderContext & ctx); diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index b1f23d1..ff8d2ce 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -4,7 +4,6 @@ #include "AnimatorSystem.h" #include "ComponentManager.h" -#include using namespace crepe; @@ -21,7 +20,7 @@ void AnimatorSystem::update() { Animator::Data & ctx = a.data; double frame_duration = 1.0f / ctx.fps; - int cycle_end = (ctx.cycle_end == -1) ? ctx.row : cycle_end; + int cycle_end = (ctx.cycle_end == -1) ? ctx.row : ctx.cycle_end; int total_frames = cycle_end - ctx.cycle_start; int curr_frame = static_cast(elapsed_time / frame_duration) % total_frames; @@ -30,8 +29,7 @@ void AnimatorSystem::update() { ctx.spritesheet.mask.x = ctx.curr_row * ctx.spritesheet.mask.w; ctx.spritesheet.mask.y = (ctx.curr_col * ctx.spritesheet.mask.h); - std::cout << curr_frame << " " << total_frames << std::endl; - if (!ctx.looping && curr_frame == 0) { + if (!ctx.looping && curr_frame == total_frames - 1) { a.active = false; } } diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 08f254f..1bf5f65 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -33,7 +33,7 @@ const Camera & RenderSystem::update_camera() { const Transform & transform = mgr.get_components_by_id(cam.game_object_id).front().get(); this->context.set_camera(cam, this->cam_ctx); - this->cam_ctx.cam_pos = transform.position + cam.offset; + this->cam_ctx.cam_pos = transform.position + cam.data.offset; return cam; } throw std::runtime_error("No active cameras in current scene"); diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 4fd4071..f84eb94 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -70,11 +70,19 @@ public: .spritesheet = test_sprite, .col = 4, .row = 4, - .fps = 10, + .fps = 1, + .looping = true, + .cycle_start = 1, + .cycle_end = 3, }); + anim.set_anim(2); - auto & cam = game_object.add_component(Color::WHITE, ivec2{720, 1280}, - vec2{400, 400}, 1.0); + auto & cam = game_object.add_component(Camera::Data{ + .bg_color = Color::WHITE, + .screen = ivec2{720, 1280}, + .viewport_size = vec2{400, 400}, + .zoom = 1.0, + }); } string get_name() const { return "TestScene"; }; -- cgit v1.2.3 From 683ae28b81a66f18bbadbe7ae70eb8ddd952c293 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Tue, 3 Dec 2024 10:40:37 +0100 Subject: fixed the one cycle aimatorsystem where it did not do the last frame_for the full duration --- src/crepe/system/AnimatorSystem.cpp | 4 +++- src/example/rendering_particle.cpp | 6 ++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src/example') diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index 9cf8ba5..e9cdd4c 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -20,6 +20,8 @@ void AnimatorSystem::update() { Animator::Data & ctx = a.data; double frame_duration = 1.0f / ctx.fps; + int last_frame = ctx.curr_row; + int cycle_end = (ctx.cycle_end == -1) ? ctx.row : ctx.cycle_end; int total_frames = cycle_end - ctx.cycle_start; @@ -29,7 +31,7 @@ void AnimatorSystem::update() { ctx.spritesheet.mask.x = ctx.curr_row * ctx.spritesheet.mask.w; ctx.spritesheet.mask.y = (ctx.curr_col * ctx.spritesheet.mask.h); - if (!ctx.looping && curr_frame == total_frames - 1) { + if (!ctx.looping && curr_frame == ctx.cycle_start && last_frame == total_frames - 1) { a.active = false; } } diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index f84eb94..e18c7b7 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -71,15 +71,13 @@ public: .col = 4, .row = 4, .fps = 1, - .looping = true, - .cycle_start = 1, - .cycle_end = 3, + .looping = false, }); anim.set_anim(2); auto & cam = game_object.add_component(Camera::Data{ .bg_color = Color::WHITE, - .screen = ivec2{720, 1280}, + .screen = ivec2{1280, 720}, .viewport_size = vec2{400, 400}, .zoom = 1.0, }); -- cgit v1.2.3 From a11824956b478e356fa684c9d88b980aa22cb19a Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Wed, 4 Dec 2024 10:56:53 +0100 Subject: implemented feedback, cameraValues need better name? --- src/crepe/api/Animator.cpp | 29 ++++++++++++---------- src/crepe/api/Animator.h | 22 +++++++++-------- src/crepe/api/Camera.cpp | 7 +++++- src/crepe/api/Camera.h | 19 ++++++++------- src/crepe/api/Sprite.cpp | 2 +- src/crepe/api/Sprite.h | 25 ++++++++++--------- src/crepe/facade/SDLContext.cpp | 48 ++++++++++++++++++++----------------- src/crepe/facade/SDLContext.h | 2 +- src/crepe/system/AnimatorSystem.cpp | 6 ++--- src/crepe/system/RenderSystem.cpp | 19 +++++++-------- src/crepe/system/RenderSystem.h | 8 +++---- src/example/rendering_particle.cpp | 14 +++-------- 12 files changed, 103 insertions(+), 98 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index 1234967..dc99fd4 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -7,20 +7,23 @@ using namespace crepe; -Animator::Animator(game_object_id_t id, const Animator::Data & ctx) +Animator::Animator(uint32_t id, Sprite & ss, int max_row, int max_col, + const Animator::Data & ctx) : Component(id), + spritesheet(ss), + row(max_row), + col(max_col), data(ctx) { dbg_trace(); - this->data.spritesheet.mask.h /= this->data.col; - this->data.spritesheet.mask.w /= this->data.row; - this->data.spritesheet.mask.x = 0; - this->data.spritesheet.mask.y = this->data.col * this->data.spritesheet.mask.h; + this->spritesheet.mask.h /= this->col; + this->spritesheet.mask.w /= this->row; + this->spritesheet.mask.x = this->data.curr_row * this->spritesheet.mask.w; + this->spritesheet.mask.y = this->data.curr_col * this->spritesheet.mask.h; // need to do this for to get the aspect ratio for a single clipping in the spritesheet - Sprite & ss = this->data.spritesheet; - ss.data.aspect_ratio - = static_cast(this->data.spritesheet.mask.w) / this->data.spritesheet.mask.h; + this->spritesheet.aspect_ratio + = static_cast(this->spritesheet.mask.w) / this->spritesheet.mask.h; } Animator::~Animator() { dbg_trace(); } @@ -43,12 +46,14 @@ void Animator::set_cycle_range(int start, int end) { } void Animator::set_anim(int col) { - this->data.curr_row = 0; - this->data.curr_col = col; + Animator::Data & ctx = this->data; + this->spritesheet.mask.x = ctx.curr_row = 0; + ctx.curr_col = col; + this->spritesheet.mask.y = ctx.curr_col * this->spritesheet.mask.h; } void Animator::next_anim() { Animator::Data & ctx = this->data; - ctx.curr_row = ctx.curr_row++ % ctx.row; - ctx.spritesheet.mask.x = ctx.curr_row * ctx.spritesheet.mask.w; + ctx.curr_row = ctx.curr_row++ % this->row; + this->spritesheet.mask.x = ctx.curr_row * this->spritesheet.mask.w; } diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 74abd5e..1fe2b6f 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -18,20 +18,13 @@ class SDLContext; class Animator : public Component { public: struct Data { - //! A reference to the Sprite sheet containing. - Sprite & spritesheet; - //! The maximum number of columns in the sprite sheet. - const int col; - - //! The maximum number of rows in the sprite sheet. - const int row; //! frames per second for animation - int fps; + int fps = 1; //! The current col being animated. - int curr_col; + int curr_col = 0; //! The current row being animated. int curr_row = 0; @@ -113,10 +106,19 @@ public: * This constructor sets up the Animator with the given parameters, and initializes the * animation system. */ - Animator(uint32_t id, const Animator::Data & ctx); + Animator(uint32_t id, Sprite & ss, int max_row, int max_col, const Animator::Data & ctx); ~Animator(); // dbg_trace public: + //! A reference to the Sprite sheet containing. + Sprite & spritesheet; + + //! The maximum number of columns in the sprite sheet. + const int col; + + //! The maximum number of rows in the sprite sheet. + const int row; + Animator::Data data; private: diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp index ff41710..b042c35 100644 --- a/src/crepe/api/Camera.cpp +++ b/src/crepe/api/Camera.cpp @@ -6,7 +6,12 @@ using namespace crepe; -Camera::Camera(game_object_id_t id, const Data & ctx) : Component(id), data(ctx) { +Camera::Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size, + const Data & ctx) + : Component(id), + screen(screen), + viewport_size(viewport_size), + data(ctx) { dbg_trace(); } diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h index e466d36..f626379 100644 --- a/src/crepe/api/Camera.h +++ b/src/crepe/api/Camera.h @@ -17,16 +17,10 @@ class Camera : public Component { public: struct Data { //! Background color of the camera view. - const Color bg_color; - - //! screen the display size in pixels ( output resolution ) - const ivec2 screen; - - //! viewport is the area of the world visible through the camera (in world units) - const vec2 viewport_size; + const Color bg_color = Color::WHITE; //! Zoom level of the camera view. - double zoom; + double zoom = 1; //! offset postion from the game object transform component vec2 offset; @@ -38,12 +32,19 @@ public: * \param id Unique identifier for the camera component. * \param ctx the camera component data */ - Camera(game_object_id_t id, const Data & ctx); + Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size, + const Data & ctx); ~Camera(); // dbg_trace only public: Camera::Data data; + //! screen the display size in pixels ( output resolution ) + const ivec2 screen; + + //! viewport is the area of the world visible through the camera (in world units) + const vec2 viewport_size; + public: /** * \brief Gets the maximum number of camera instances allowed. diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index fe495a1..3a1acac 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -20,7 +20,7 @@ Sprite::Sprite(game_object_id_t id, Texture & texture, const Sprite::Data & ctx) this->mask.w = this->texture.get_width(); this->mask.h = this->texture.get_height(); - this->data.aspect_ratio = static_cast(this->mask.w) / this->mask.h; + this->aspect_ratio = static_cast(this->mask.w) / this->mask.h; } Sprite::~Sprite() { dbg_trace(); } diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index aef6a8d..d82ae8d 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -27,16 +27,16 @@ public: struct Data { //! Color tint of the sprite - Color color; + Color color = Color::WHITE; //! Flip settings for the sprite FlipSettings flip; //! Layer sorting level of the sprite - const int sorting_in_layer; + const int sorting_in_layer = 0; //! Order within the sorting layer - const int order_in_layer; + const int order_in_layer = 0; /** * \size width and height of the sprite in game units @@ -53,15 +53,8 @@ public: double angle_offset = 0; //! independent sprite scale multiplier - double scale = 1; + double scale_offset = 1; - /** - * \aspect_ratio ratio of the img so that scaling will not become weird - * - * cannot be const because if Animator component is addded then ratio becomes scuffed and - * does it need to be calculated again in the Animator - */ - float aspect_ratio; }; public: @@ -71,8 +64,6 @@ public: * \param texture asset of the image * \param ctx all the sprite data */ - //TODO: texture is outside the Sprite::Data because of the deleted copy constructer. eventually - // texture will go into data when it becomes asset Sprite(game_object_id_t id, Texture & texture, const Data & ctx); ~Sprite(); @@ -82,6 +73,14 @@ public: Data data; private: + /** + * \aspect_ratio ratio of the img so that scaling will not become weird + * + * cannot be const because if Animator component is addded then ratio becomes scuffed and + * does it need to be calculated again in the Animator + */ + float aspect_ratio; + //! Reads the mask of sprite friend class SDLContext; diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 391aa78..d3a15d9 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -115,12 +115,12 @@ SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { const Sprite::Data & data = ctx.sprite.data; vec2 size = { - data.size.x == 0 && data.size.y != 0 ? data.size.y * data.aspect_ratio : data.size.x, - data.size.y == 0 && data.size.x != 0 ? data.size.x / data.aspect_ratio : data.size.y}; + data.size.x == 0 && data.size.y != 0 ? data.size.y * ctx.sprite.aspect_ratio : data.size.x, + data.size.y == 0 && data.size.x != 0 ? data.size.x / ctx.sprite.aspect_ratio : data.size.y}; const CameraValues & cam = ctx.cam; - size *= cam.render_scale * ctx.img_scale * data.scale; + size *= cam.render_scale * ctx.img_scale * data.scale_offset; vec2 screen_pos = (ctx.pos - cam.cam_pos + (cam.zoomed_viewport) / 2) * cam.render_scale - size / 2 + cam.bar_size; @@ -154,44 +154,45 @@ void SDLContext::draw(const RenderContext & ctx) { &dstrect, angle, NULL, render_flip); } -void SDLContext::set_camera(const Camera & cam, CameraValues & ctx) { +SDLContext::CameraValues SDLContext::set_camera(const Camera & cam) { const Camera::Data & cam_data = cam.data; + CameraValues ret_cam; // resize window int w, h; SDL_GetWindowSize(this->game_window.get(), &w, &h); - if (w != cam_data.screen.x || h != cam_data.screen.y) { - SDL_SetWindowSize(this->game_window.get(), cam_data.screen.x, cam_data.screen.y); + if (w != cam.screen.x || h != cam.screen.y) { + SDL_SetWindowSize(this->game_window.get(), cam.screen.x, cam.screen.y); } - vec2 & zoomed_viewport = ctx.zoomed_viewport; - vec2 & bar_size = ctx.bar_size; - vec2 & render_scale = ctx.render_scale; + vec2 & zoomed_viewport = ret_cam.zoomed_viewport; + vec2 & bar_size = ret_cam.bar_size; + vec2 & render_scale = ret_cam.render_scale; - zoomed_viewport = cam_data.viewport_size * cam_data.zoom; - double screen_aspect = static_cast(cam_data.screen.x) / cam_data.screen.y; + zoomed_viewport = cam.viewport_size * cam_data.zoom; + double screen_aspect = static_cast(cam.screen.x) / cam.screen.y; double viewport_aspect = zoomed_viewport.x / zoomed_viewport.y; // calculate black bars if (screen_aspect > viewport_aspect) { // pillarboxing - float scale = cam_data.screen.y / zoomed_viewport.y; + float scale = cam.screen.y / zoomed_viewport.y; float adj_width = zoomed_viewport.x * scale; - float bar_width = (cam_data.screen.x - adj_width) / 2; - this->black_bars[0] = {0, 0, bar_width, (float) cam_data.screen.y}; + float bar_width = (cam.screen.x - adj_width) / 2; + this->black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; this->black_bars[1] - = {(cam_data.screen.x - bar_width), 0, bar_width, (float) cam_data.screen.y}; + = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; bar_size = {bar_width, 0}; render_scale.x = render_scale.y = scale; } else { // letterboxing - float scale = cam_data.screen.x / (cam_data.viewport_size.x * cam_data.zoom); - float adj_height = cam_data.viewport_size.y * scale; - float bar_height = (cam_data.screen.y - adj_height) / 2; - this->black_bars[0] = {0, 0, (float) cam_data.screen.x, bar_height}; + float scale = cam.screen.x / (cam.viewport_size.x * cam_data.zoom); + float adj_height = cam.viewport_size.y * scale; + float bar_height = (cam.screen.y - adj_height) / 2; + this->black_bars[0] = {0, 0, (float) cam.screen.x, bar_height}; this->black_bars[1] - = {0, (cam_data.screen.y - bar_height), (float) cam_data.screen.x, bar_height}; + = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height}; bar_size = {0, bar_height}; render_scale.x = render_scale.y = scale; @@ -203,12 +204,15 @@ void SDLContext::set_camera(const Camera & cam, CameraValues & ctx) { SDL_Rect bg = { .x = 0, .y = 0, - .w = cam_data.screen.x, - .h = cam_data.screen.y, + .w = cam.screen.x, + .h = cam.screen.y, }; // fill bg color SDL_RenderFillRect(this->game_renderer.get(), &bg); + + + return ret_cam; } uint64_t SDLContext::get_ticks() const { return SDL_GetTicks64(); } diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index a0d1da8..d662bee 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -142,7 +142,7 @@ private: * \brief sets the background of the camera (will be adjusted in future PR) * \param camera Reference to the Camera object. */ - void set_camera(const Camera & camera, CameraValues & ctx); + CameraValues set_camera(const Camera & camera); private: struct DstRect { diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp index e9cdd4c..a2ae529 100644 --- a/src/crepe/system/AnimatorSystem.cpp +++ b/src/crepe/system/AnimatorSystem.cpp @@ -22,14 +22,14 @@ void AnimatorSystem::update() { int last_frame = ctx.curr_row; - int cycle_end = (ctx.cycle_end == -1) ? ctx.row : ctx.cycle_end; + int cycle_end = (ctx.cycle_end == -1) ? a.row : ctx.cycle_end; int total_frames = cycle_end - ctx.cycle_start; int curr_frame = static_cast(elapsed_time / frame_duration) % total_frames; ctx.curr_row = ctx.cycle_start + curr_frame; - ctx.spritesheet.mask.x = ctx.curr_row * ctx.spritesheet.mask.w; - ctx.spritesheet.mask.y = (ctx.curr_col * ctx.spritesheet.mask.h); + a.spritesheet.mask.x = ctx.curr_row * a.spritesheet.mask.w; + a.spritesheet.mask.y = (ctx.curr_col * a.spritesheet.mask.h); if (!ctx.looping && curr_frame == ctx.cycle_start && last_frame == total_frames - 1) { a.active = false; diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 1bf5f65..b5db45a 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -21,7 +21,7 @@ void RenderSystem::clear_screen() { this->context.clear_screen(); } void RenderSystem::present_screen() { this->context.present_screen(); } -const Camera & RenderSystem::update_camera() { +SDLContext::CameraValues RenderSystem::update_camera() { ComponentManager & mgr = this->component_manager; RefVector cameras = mgr.get_components_by_type(); @@ -32,9 +32,9 @@ const Camera & RenderSystem::update_camera() { if (!cam.active) continue; const Transform & transform = mgr.get_components_by_id(cam.game_object_id).front().get(); - this->context.set_camera(cam, this->cam_ctx); - this->cam_ctx.cam_pos = transform.position + cam.data.offset; - return cam; + SDLContext::CameraValues cam_val = this->context.set_camera(cam); + cam_val.cam_pos = transform.position + cam.data.offset; + return cam_val; } throw std::runtime_error("No active cameras in current scene"); } @@ -60,7 +60,7 @@ void RenderSystem::update() { this->present_screen(); } -bool RenderSystem::render_particle(const Sprite & sprite, const Camera & cam, +bool RenderSystem::render_particle(const Sprite & sprite, const SDLContext::CameraValues & cam, const double & scale) { ComponentManager & mgr = this->component_manager; @@ -80,7 +80,7 @@ bool RenderSystem::render_particle(const Sprite & sprite, const Camera & cam, this->context.draw(SDLContext::RenderContext{ .sprite = sprite, - .cam = this->cam_ctx, + .cam = cam, .pos = p.position, .angle = p.angle, .scale = scale, @@ -89,11 +89,10 @@ bool RenderSystem::render_particle(const Sprite & sprite, const Camera & cam, } return rendering_particles; } -void RenderSystem::render_normal(const Sprite & sprite, const Camera & cam, - const Transform & tm) { +void RenderSystem::render_normal(const Sprite & sprite, const SDLContext::CameraValues & cam, const Transform & tm) { this->context.draw(SDLContext::RenderContext{ .sprite = sprite, - .cam = this->cam_ctx, + .cam = cam, .pos = tm.position, .angle = tm.rotation, .scale = tm.scale, @@ -102,7 +101,7 @@ void RenderSystem::render_normal(const Sprite & sprite, const Camera & cam, void RenderSystem::render() { ComponentManager & mgr = this->component_manager; - const Camera & cam = this->update_camera(); + const SDLContext::CameraValues & cam = this->update_camera(); RefVector sprites = mgr.get_components_by_type(); RefVector sorted_sprites = this->sort(sprites); diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h index 249f3b8..e779047 100644 --- a/src/crepe/system/RenderSystem.h +++ b/src/crepe/system/RenderSystem.h @@ -37,7 +37,7 @@ private: void present_screen(); //! Updates the active camera used for rendering. - const Camera & update_camera(); + SDLContext::CameraValues update_camera(); //! Renders the whole screen void render(); @@ -49,7 +49,7 @@ private: * \param tm the Transform component for scale * \return true if particles have been rendered */ - bool render_particle(const Sprite & sprite, const Camera & cam, const double & scale); + bool render_particle(const Sprite & sprite, const SDLContext::CameraValues & cam, const double & scale); /** * \brief renders a sprite with a Transform component on the screen @@ -57,7 +57,7 @@ private: * \param sprite the sprite component that holds all the data * \param tm the Transform component that holds the position,rotation and scale */ - void render_normal(const Sprite & sprite, const Camera & cam, const Transform & tm); + void render_normal(const Sprite & sprite, const SDLContext::CameraValues & cam, const Transform & tm); /** * \brief sort a vector sprite objects with @@ -76,8 +76,6 @@ private: private: SDLContext & context = SDLContext::get_instance(); - - SDLContext::CameraValues cam_ctx; }; } // namespace crepe diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index e18c7b7..2e2552d 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -45,8 +45,6 @@ using namespace std; class TestScene : public Scene { public: - using Scene::Scene; - void load_scene() { ComponentManager & mgr = this->component_manager; GameObject game_object = mgr.new_object("", "", vec2{0, 0}, 0, 1); @@ -63,23 +61,17 @@ public: .order_in_layer = 2, .size = {0, 100}, .angle_offset = 0, - .scale = 1, }); - auto & anim = game_object.add_component(Animator::Data{ - .spritesheet = test_sprite, - .col = 4, - .row = 4, + auto & anim = game_object.add_component(test_sprite, 4, 4, Animator::Data{ .fps = 1, .looping = false, }); anim.set_anim(2); + anim.active = false; - auto & cam = game_object.add_component(Camera::Data{ + auto & cam = game_object.add_component(ivec2{1280,720}, vec2{400,400},Camera::Data{ .bg_color = Color::WHITE, - .screen = ivec2{1280, 720}, - .viewport_size = vec2{400, 400}, - .zoom = 1.0, }); } -- cgit v1.2.3 From 9cde6875186b335c75eafa6402f0957cd4252c76 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Wed, 4 Dec 2024 10:57:20 +0100 Subject: make format --- src/crepe/api/Animator.h | 1 - src/crepe/api/Sprite.h | 1 - src/crepe/facade/SDLContext.cpp | 11 +++++------ src/crepe/system/RenderSystem.cpp | 3 ++- src/crepe/system/RenderSystem.h | 6 ++++-- src/example/rendering_particle.cpp | 16 +++++++++------- 6 files changed, 20 insertions(+), 18 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index 1fe2b6f..dab6697 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -19,7 +19,6 @@ class Animator : public Component { public: struct Data { - //! frames per second for animation int fps = 1; diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index d82ae8d..a1230db 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -54,7 +54,6 @@ public: //! independent sprite scale multiplier double scale_offset = 1; - }; public: diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index d3a15d9..86969ed 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -114,9 +114,10 @@ SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { const Sprite::Data & data = ctx.sprite.data; - vec2 size = { - data.size.x == 0 && data.size.y != 0 ? data.size.y * ctx.sprite.aspect_ratio : data.size.x, - data.size.y == 0 && data.size.x != 0 ? data.size.x / ctx.sprite.aspect_ratio : data.size.y}; + vec2 size = {data.size.x == 0 && data.size.y != 0 ? data.size.y * ctx.sprite.aspect_ratio + : data.size.x, + data.size.y == 0 && data.size.x != 0 ? data.size.x / ctx.sprite.aspect_ratio + : data.size.y}; const CameraValues & cam = ctx.cam; @@ -180,8 +181,7 @@ SDLContext::CameraValues SDLContext::set_camera(const Camera & cam) { float adj_width = zoomed_viewport.x * scale; float bar_width = (cam.screen.x - adj_width) / 2; this->black_bars[0] = {0, 0, bar_width, (float) cam.screen.y}; - this->black_bars[1] - = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; + this->black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y}; bar_size = {bar_width, 0}; render_scale.x = render_scale.y = scale; @@ -211,7 +211,6 @@ SDLContext::CameraValues SDLContext::set_camera(const Camera & cam) { // fill bg color SDL_RenderFillRect(this->game_renderer.get(), &bg); - return ret_cam; } diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index b5db45a..4c618d8 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -89,7 +89,8 @@ bool RenderSystem::render_particle(const Sprite & sprite, const SDLContext::Came } return rendering_particles; } -void RenderSystem::render_normal(const Sprite & sprite, const SDLContext::CameraValues & cam, const Transform & tm) { +void RenderSystem::render_normal(const Sprite & sprite, const SDLContext::CameraValues & cam, + const Transform & tm) { this->context.draw(SDLContext::RenderContext{ .sprite = sprite, .cam = cam, diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h index e779047..9c306c5 100644 --- a/src/crepe/system/RenderSystem.h +++ b/src/crepe/system/RenderSystem.h @@ -49,7 +49,8 @@ private: * \param tm the Transform component for scale * \return true if particles have been rendered */ - bool render_particle(const Sprite & sprite, const SDLContext::CameraValues & cam, const double & scale); + bool render_particle(const Sprite & sprite, const SDLContext::CameraValues & cam, + const double & scale); /** * \brief renders a sprite with a Transform component on the screen @@ -57,7 +58,8 @@ private: * \param sprite the sprite component that holds all the data * \param tm the Transform component that holds the position,rotation and scale */ - void render_normal(const Sprite & sprite, const SDLContext::CameraValues & cam, const Transform & tm); + void render_normal(const Sprite & sprite, const SDLContext::CameraValues & cam, + const Transform & tm); /** * \brief sort a vector sprite objects with diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 2e2552d..07e43a1 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -63,16 +63,18 @@ public: .angle_offset = 0, }); - auto & anim = game_object.add_component(test_sprite, 4, 4, Animator::Data{ - .fps = 1, - .looping = false, - }); + auto & anim = game_object.add_component(test_sprite, 4, 4, + Animator::Data{ + .fps = 1, + .looping = false, + }); anim.set_anim(2); anim.active = false; - auto & cam = game_object.add_component(ivec2{1280,720}, vec2{400,400},Camera::Data{ - .bg_color = Color::WHITE, - }); + auto & cam = game_object.add_component(ivec2{1280, 720}, vec2{400, 400}, + Camera::Data{ + .bg_color = Color::WHITE, + }); } string get_name() const { return "TestScene"; }; -- cgit v1.2.3 From f6111b6df65047557239c827100454c188979c43 Mon Sep 17 00:00:00 2001 From: max-001 Date: Wed, 4 Dec 2024 11:45:50 +0100 Subject: Setup test for AI --- src/example/AITest.cpp | 32 ++++++++++++++++++++++++++++++++ src/example/CMakeLists.txt | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/example/AITest.cpp (limited to 'src/example') diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp new file mode 100644 index 0000000..ccf5a85 --- /dev/null +++ b/src/example/AITest.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace crepe; + +int main() { + ComponentManager mgr; + GameObject game_object1 = mgr.new_object("", "", vec2{0, 0}, 0, 1); + GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1); + + Texture img = Texture("asset/texture/test_ap43.png"); + game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); + + game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); + + RenderSystem sys{mgr}; + + auto start = std::chrono::steady_clock::now(); + while (std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) { + sys.update(); + SDL_Delay(10); + } + + return 0; +} diff --git a/src/example/CMakeLists.txt b/src/example/CMakeLists.txt index 560e2bc..ef770ae 100644 --- a/src/example/CMakeLists.txt +++ b/src/example/CMakeLists.txt @@ -20,4 +20,4 @@ add_example(asset_manager) add_example(savemgr) add_example(rendering_particle) add_example(gameloop) - +add_example(AITest) -- cgit v1.2.3 From 16444f19ae2c7c71a2be53ce6fd2e4d671aa8765 Mon Sep 17 00:00:00 2001 From: max-001 Date: Wed, 4 Dec 2024 12:15:05 +0100 Subject: Modified test and setup of AISystem --- src/crepe/api/LoopManager.cpp | 14 ++++++++++++- src/crepe/system/AISystem.cpp | 6 ++++++ src/crepe/system/AISystem.h | 14 +++++++++++++ src/crepe/system/CMakeLists.txt | 2 ++ src/example/AITest.cpp | 45 ++++++++++++++++++++++++----------------- 5 files changed, 62 insertions(+), 19 deletions(-) create mode 100644 src/crepe/system/AISystem.cpp create mode 100644 src/crepe/system/AISystem.h (limited to 'src/example') diff --git a/src/crepe/api/LoopManager.cpp b/src/crepe/api/LoopManager.cpp index 7edf4d1..cd602d8 100644 --- a/src/crepe/api/LoopManager.cpp +++ b/src/crepe/api/LoopManager.cpp @@ -1,5 +1,6 @@ #include "../facade/SDLContext.h" +#include "../system/AISystem.h" #include "../system/AnimatorSystem.h" #include "../system/CollisionSystem.h" #include "../system/ParticleSystem.h" @@ -20,6 +21,7 @@ LoopManager::LoopManager() { this->load_system(); this->load_system(); this->load_system(); + this->load_system(); } void LoopManager::process_input() { @@ -51,6 +53,11 @@ void LoopManager::loop() { this->render(); timer.enforce_frame_rate(); + + // Stop the game after 5 seconds, for testing purposes + if (timer.get_current_time() > 5) { + this->game_running = false; + } } } @@ -58,6 +65,7 @@ void LoopManager::setup() { this->game_running = true; LoopTimer::get_instance().start(); LoopTimer::get_instance().set_fps(200); + this->scene_manager.load_next_scene(); } void LoopManager::render() { @@ -66,4 +74,8 @@ void LoopManager::render() { } } -void LoopManager::update() { LoopTimer & timer = LoopTimer::get_instance(); } +void LoopManager::update() { + LoopTimer & timer = LoopTimer::get_instance(); + this->get_system().update(); + this->get_system().update(); +} diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp new file mode 100644 index 0000000..012f4fa --- /dev/null +++ b/src/crepe/system/AISystem.cpp @@ -0,0 +1,6 @@ +#include "AISystem.h" +#include + +using namespace crepe; + +void AISystem::update() { std::cout << "AI System update" << std::endl; } diff --git a/src/crepe/system/AISystem.h b/src/crepe/system/AISystem.h new file mode 100644 index 0000000..4138e01 --- /dev/null +++ b/src/crepe/system/AISystem.h @@ -0,0 +1,14 @@ +#pragma once + +#include "System.h" + +namespace crepe { + +class AISystem : public System { +public: + using System::System; + + void update() override; +}; + +} // namespace crepe diff --git a/src/crepe/system/CMakeLists.txt b/src/crepe/system/CMakeLists.txt index d658b25..ca89d4d 100644 --- a/src/crepe/system/CMakeLists.txt +++ b/src/crepe/system/CMakeLists.txt @@ -6,6 +6,7 @@ target_sources(crepe PUBLIC CollisionSystem.cpp RenderSystem.cpp AnimatorSystem.cpp + AISystem.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES @@ -15,4 +16,5 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES CollisionSystem.h RenderSystem.h AnimatorSystem.h + AISystem.h ) diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index ccf5a85..3998ff4 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -1,32 +1,41 @@ +#include +#include +#include #include #include -#include -#include -#include #include +#include +#include +#include +#include #include -#include -#include using namespace crepe; +using namespace std; -int main() { - ComponentManager mgr; - GameObject game_object1 = mgr.new_object("", "", vec2{0, 0}, 0, 1); - GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1); - - Texture img = Texture("asset/texture/test_ap43.png"); - game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); +class Scene1 : public Scene { +public: + void load_scene() override { + ComponentManager & mgr = this->component_manager; - game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); + GameObject game_object1 = mgr.new_object("", "", vec2{0, 0}, 0, 1); + GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1); - RenderSystem sys{mgr}; + Texture img = Texture("asset/texture/test_ap43.png"); + game_object1.add_component(img, Color::MAGENTA, + Sprite::FlipSettings{false, false}, 1, 1, 195); - auto start = std::chrono::steady_clock::now(); - while (std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) { - sys.update(); - SDL_Delay(10); + game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, + 1.0f); } + string get_name() const override { return "Scene1"; } +}; + +int main() { + LoopManager engine; + engine.add_scene(); + engine.start(); + return 0; } -- cgit v1.2.3 From ac87bfad20e1bcf1fd066a4eda231608fe12f504 Mon Sep 17 00:00:00 2001 From: max-001 Date: Wed, 4 Dec 2024 13:17:08 +0100 Subject: Added AI component --- src/crepe/api/AI.cpp | 11 +++++++++++ src/crepe/api/AI.h | 18 ++++++++++++++++++ src/crepe/api/CMakeLists.txt | 2 ++ src/example/AITest.cpp | 3 ++- 4 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/crepe/api/AI.cpp create mode 100644 src/crepe/api/AI.h (limited to 'src/example') diff --git a/src/crepe/api/AI.cpp b/src/crepe/api/AI.cpp new file mode 100644 index 0000000..6b63216 --- /dev/null +++ b/src/crepe/api/AI.cpp @@ -0,0 +1,11 @@ +#include "AI.h" + +namespace crepe { + +AI::AI(game_object_id_t id, double mass, double max_speed, double max_force) + : Component(id), + mass(mass), + max_speed(max_speed), + max_force(max_force) {} + +} // namespace crepe diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h new file mode 100644 index 0000000..b755439 --- /dev/null +++ b/src/crepe/api/AI.h @@ -0,0 +1,18 @@ +#pragma once + +#include "Component.h" +#include "types.h" + +namespace crepe { + +class AI : public Component { +public: + AI(game_object_id_t id, double mass, double max_speed, double max_force); + +public: + double mass; + double max_speed; + double max_force; +}; + +} // namespace crepe diff --git a/src/crepe/api/CMakeLists.txt b/src/crepe/api/CMakeLists.txt index 50c51ed..d42b459 100644 --- a/src/crepe/api/CMakeLists.txt +++ b/src/crepe/api/CMakeLists.txt @@ -23,6 +23,7 @@ target_sources(crepe PUBLIC Asset.cpp EventHandler.cpp Script.cpp + AI.cpp ) target_sources(crepe PUBLIC FILE_SET HEADERS FILES @@ -58,4 +59,5 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES LoopManager.h LoopTimer.h Asset.h + AI.h ) diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 3998ff4..1c4633f 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -8,7 +9,6 @@ #include #include #include -#include using namespace crepe; using namespace std; @@ -24,6 +24,7 @@ public: Texture img = Texture("asset/texture/test_ap43.png"); game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); + game_object1.add_component(1, 1, 1); game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); -- cgit v1.2.3 From 121387ba92a23d6f17b36331d25757abc899f7d2 Mon Sep 17 00:00:00 2001 From: max-001 Date: Wed, 4 Dec 2024 17:27:51 +0100 Subject: Implemeted seek behavior --- src/crepe/api/AI.h | 3 +++ src/crepe/system/AISystem.cpp | 45 +++++++++++++++++++++++++++++++++++++++++-- src/crepe/system/AISystem.h | 3 +++ src/example/AITest.cpp | 4 ++-- 4 files changed, 51 insertions(+), 4 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h index faeeba5..242ff89 100644 --- a/src/crepe/api/AI.h +++ b/src/crepe/api/AI.h @@ -51,6 +51,9 @@ public: float arrive_deceleration = 2.0f; private: + vec2 velocity; + friend class AISystem; + int flags = 0; }; diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index 12da3d9..9029f32 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -1,4 +1,7 @@ #include "../ComponentManager.h" +#include "api/LoopTimer.h" +#include "api/Transform.h" +#include "types.h" #include "AISystem.h" @@ -8,9 +11,19 @@ void AISystem::update() { ComponentManager & mgr = this->component_manager; RefVector ai_components = mgr.get_components_by_type(); + double dt = LoopTimer::get_instance().get_delta_time(); + for (AI & ai : ai_components) { vec2 force = this->calculate(ai); - //... + vec2 acceleration = force / ai.mass; + ai.velocity += acceleration * dt; + ai.velocity.truncate(ai.max_speed); + + // Update the position + RefVector transforms + = mgr.get_components_by_id(ai.game_object_id); + Transform & transform = transforms.front().get(); + transform.position += ai.velocity * dt; } } @@ -18,7 +31,11 @@ vec2 AISystem::calculate(AI & ai) { vec2 force; if (ai.on(AI::BehaviorType::SEEK)) { - // Seek the target + vec2 force_to_add = this->seek(ai); + + if (!this->accumulate_force(force, force_to_add)) { + return force; + } } if (ai.on(AI::BehaviorType::FLEE)) { // Flee from the target @@ -32,3 +49,27 @@ vec2 AISystem::calculate(AI & ai) { return force; } + +bool AISystem::accumulate_force(vec2 & running_total, vec2 force_to_add) { + double magnitude_remaining = running_total.length(); + double magnitude_to_add = force_to_add.length(); + + if (magnitude_remaining + magnitude_to_add > 0) { + running_total += force_to_add; + return true; + } + + return false; +} + +vec2 AISystem::seek(const AI & ai) { + ComponentManager & mgr = this->component_manager; + RefVector transforms = mgr.get_components_by_id(ai.game_object_id); + Transform & transform = transforms.front().get(); + + vec2 desired_velocity = ai.seek_target - transform.position; + desired_velocity.normalize(); + desired_velocity *= ai.max_speed; + + return desired_velocity - ai.velocity; +} diff --git a/src/crepe/system/AISystem.h b/src/crepe/system/AISystem.h index eb8d08c..5e94ccb 100644 --- a/src/crepe/system/AISystem.h +++ b/src/crepe/system/AISystem.h @@ -15,6 +15,9 @@ public: private: vec2 calculate(AI & ai); + bool accumulate_force(vec2 & running_total, vec2 force_to_add); + + vec2 seek(const AI & ai); }; } // namespace crepe diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 1c4633f..341e1de 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -18,13 +18,13 @@ public: void load_scene() override { ComponentManager & mgr = this->component_manager; - GameObject game_object1 = mgr.new_object("", "", vec2{0, 0}, 0, 1); + GameObject game_object1 = mgr.new_object("", "", vec2{250, 250}, 0, 1); GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1); Texture img = Texture("asset/texture/test_ap43.png"); game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); - game_object1.add_component(1, 1, 1); + game_object1.add_component(1, 200, 200).seek_on(); game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); -- cgit v1.2.3 From e617b4f002638e37dbe4d2ce13849728e7e82c78 Mon Sep 17 00:00:00 2001 From: max-001 Date: Thu, 5 Dec 2024 17:26:41 +0100 Subject: Used Mediator --- src/crepe/system/AISystem.cpp | 9 ++++++--- src/example/AITest.cpp | 6 ++++-- 2 files changed, 10 insertions(+), 5 deletions(-) (limited to 'src/example') diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index 9029f32..c67d5ea 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -1,6 +1,7 @@ -#include "../ComponentManager.h" +#include "manager/ComponentManager.h" #include "api/LoopTimer.h" #include "api/Transform.h" +#include "manager/Mediator.h" #include "types.h" #include "AISystem.h" @@ -8,7 +9,8 @@ using namespace crepe; void AISystem::update() { - ComponentManager & mgr = this->component_manager; + const Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; RefVector ai_components = mgr.get_components_by_type(); double dt = LoopTimer::get_instance().get_delta_time(); @@ -63,7 +65,8 @@ bool AISystem::accumulate_force(vec2 & running_total, vec2 force_to_add) { } vec2 AISystem::seek(const AI & ai) { - ComponentManager & mgr = this->component_manager; + const Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; RefVector transforms = mgr.get_components_by_id(ai.game_object_id); Transform & transform = transforms.front().get(); diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 341e1de..71aacb2 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -1,6 +1,7 @@ +#include #include #include -#include +#include #include #include #include @@ -16,7 +17,8 @@ using namespace std; class Scene1 : public Scene { public: void load_scene() override { - ComponentManager & mgr = this->component_manager; + Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; GameObject game_object1 = mgr.new_object("", "", vec2{250, 250}, 0, 1); GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1); -- cgit v1.2.3 From 6b45759e570bcaafc167e74ac46c8ffe05efa66e Mon Sep 17 00:00:00 2001 From: max-001 Date: Thu, 5 Dec 2024 18:28:15 +0100 Subject: Make format --- src/crepe/system/AISystem.cpp | 2 +- src/example/AITest.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src/example') diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index c67d5ea..3c61c78 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -1,6 +1,6 @@ -#include "manager/ComponentManager.h" #include "api/LoopTimer.h" #include "api/Transform.h" +#include "manager/ComponentManager.h" #include "manager/Mediator.h" #include "types.h" diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 71aacb2..841b195 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -1,7 +1,5 @@ -#include #include #include -#include #include #include #include @@ -10,6 +8,8 @@ #include #include #include +#include +#include using namespace crepe; using namespace std; -- cgit v1.2.3 From 93893dbe710d864d5865f361f9a8a8f8f85b94f6 Mon Sep 17 00:00:00 2001 From: max-001 Date: Fri, 6 Dec 2024 09:57:30 +0100 Subject: Make format --- mwe/events/include/event.h | 2 +- src/crepe/api/Rigidbody.h | 1 - src/crepe/api/Script.h | 2 +- src/crepe/system/CollisionSystem.cpp | 40 +++++++-------- src/crepe/system/CollisionSystem.h | 6 +-- src/example/game.cpp | 98 +++++++++++++++++------------------- src/test/CollisionTest.cpp | 6 +-- src/test/Profiling.cpp | 6 +-- 8 files changed, 76 insertions(+), 85 deletions(-) (limited to 'src/example') diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h index ee1bf52..e1b220b 100644 --- a/mwe/events/include/event.h +++ b/mwe/events/include/event.h @@ -148,7 +148,7 @@ private: }; class ShutDownEvent : public Event { public: - ShutDownEvent() : Event("ShutDownEvent") {}; + ShutDownEvent() : Event("ShutDownEvent"){}; REGISTER_EVENT_TYPE(ShutDownEvent) diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h index b0a24f7..722a665 100644 --- a/src/crepe/api/Rigidbody.h +++ b/src/crepe/api/Rigidbody.h @@ -7,7 +7,6 @@ #include "types.h" - namespace crepe { /** diff --git a/src/crepe/api/Script.h b/src/crepe/api/Script.h index 1474a09..fa83152 100644 --- a/src/crepe/api/Script.h +++ b/src/crepe/api/Script.h @@ -3,10 +3,10 @@ #include #include "../manager/EventManager.h" -#include "system/CollisionSystem.h" #include "../manager/Mediator.h" #include "../types.h" #include "../util/OptionalRef.h" +#include "system/CollisionSystem.h" namespace crepe { diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index f75d0ad..da9e3af 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -6,6 +6,8 @@ #include #include +#include "../manager/ComponentManager.h" +#include "../manager/EventManager.h" #include "api/BoxCollider.h" #include "api/CircleCollider.h" #include "api/Event.h" @@ -13,8 +15,6 @@ #include "api/Rigidbody.h" #include "api/Transform.h" #include "api/Vector2.h" -#include "../manager/ComponentManager.h" -#include "../manager/EventManager.h" #include "Collider.h" #include "CollisionSystem.h" @@ -27,17 +27,14 @@ void CollisionSystem::update() { std::vector all_colliders; game_object_id_t id = 0; ComponentManager & mgr = this->mediator.component_manager; - RefVector rigidbodies - = mgr.get_components_by_type(); + RefVector rigidbodies = mgr.get_components_by_type(); // Collisions can only happen on object with a rigidbody for (Rigidbody & rigidbody : rigidbodies) { if (!rigidbody.active) continue; id = rigidbody.game_object_id; - Transform & transform - = mgr.get_components_by_id(id).front().get(); + Transform & transform = mgr.get_components_by_id(id).front().get(); // Check if the boxcollider is active and has the same id as the rigidbody. - RefVector boxcolliders - = mgr.get_components_by_type(); + RefVector boxcolliders = mgr.get_components_by_type(); for (BoxCollider & boxcollider : boxcolliders) { if (boxcollider.game_object_id != id) continue; if (!boxcollider.active) continue; @@ -159,7 +156,7 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform, data2.rigidbody); resolution = this->get_circle_box_resolution(collider2, collider1, collider_pos2, - collider_pos1,true); + collider_pos1, true); break; } case CollisionInternalType::CIRCLE_CIRCLE: { @@ -185,7 +182,7 @@ CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform, data2.rigidbody); resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1, - collider_pos2,false); + collider_pos2, false); break; } } @@ -261,7 +258,6 @@ vec2 CollisionSystem::get_circle_circle_resolution(const CircleCollider & circle // Normalize the delta vector to get the collision direction vec2 collision_normal = delta / distance; - // Compute the resolution vector vec2 resolution = -collision_normal * penetration_depth; @@ -272,7 +268,8 @@ vec2 CollisionSystem::get_circle_circle_resolution(const CircleCollider & circle vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_collider, const BoxCollider & box_collider, const vec2 & circle_position, - const vec2 & box_position,bool inverse) const { + const vec2 & box_position, + bool inverse) const { vec2 delta = circle_position - box_position; // Compute half-dimensions of the box @@ -294,7 +291,7 @@ vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_co // Compute penetration depth float penetration_depth = circle_collider.radius - distance; - if(inverse) collision_normal = -collision_normal; + if (inverse) collision_normal = -collision_normal; // Compute the resolution vector vec2 resolution = collision_normal * penetration_depth; @@ -311,8 +308,7 @@ void CollisionSystem::determine_collision_handler(CollisionInfo & info) { // Call collision event for user CollisionEvent data(info); EventManager & emgr = this->mediator.event_manager; - emgr.trigger_event( - data, info.this_collider.game_object_id); + emgr.trigger_event(data, info.this_collider.game_object_id); } void CollisionSystem::static_collision_handler(CollisionInfo & info) { @@ -389,14 +385,14 @@ CollisionSystem::gather_collisions(std::vector & colliders) { bool CollisionSystem::have_common_layer(const std::set & layers1, const std::set & layers2) { - + // Check if any number is equal in the layers for (int num : layers1) { - if (layers2.contains(num)) { - // Common layer found - return true; - break; - } + if (layers2.contains(num)) { + // Common layer found + return true; + break; + } } // No common layer found return false; @@ -512,7 +508,7 @@ bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1, float distance_squared = distance_x * distance_x + distance_y * distance_y; // Compare distance squared with the square of the circle's radius - return distance_squared <= circle2.radius * circle2.radius-1; + return distance_squared <= circle2.radius * circle2.radius - 1; } bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1, diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h index b978dbb..eee582b 100644 --- a/src/crepe/system/CollisionSystem.h +++ b/src/crepe/system/CollisionSystem.h @@ -6,11 +6,11 @@ #include "api/BoxCollider.h" #include "api/CircleCollider.h" +#include "api/Event.h" #include "api/Metadata.h" #include "api/Rigidbody.h" #include "api/Transform.h" #include "api/Vector2.h" -#include "api/Event.h" #include "Collider.h" #include "System.h" @@ -183,8 +183,8 @@ private: */ vec2 get_circle_box_resolution(const CircleCollider & circle_collider, const BoxCollider & box_collider, - const vec2 & circle_position, - const vec2 & box_position,bool inverse) const; + const vec2 & circle_position, const vec2 & box_position, + bool inverse) const; /** * \brief Determines the appropriate collision handler for a collision. diff --git a/src/example/game.cpp b/src/example/game.cpp index be756bd..2b4e46f 100644 --- a/src/example/game.cpp +++ b/src/example/game.cpp @@ -1,6 +1,6 @@ #include "api/CircleCollider.h" -#include "manager/ComponentManager.h" #include "api/Scene.h" +#include "manager/ComponentManager.h" #include "manager/Mediator.h" #include #include @@ -28,66 +28,64 @@ class MyScript1 : public Script { bool keypressed(const KeyPressEvent & test) { Log::logf("Box script keypressed()"); switch (test.key) { - case Keycode::A: - { + case Keycode::A: { Transform & tf = this->get_component(); tf.position.x -= 1; break; } - case Keycode::W: - { + case Keycode::W: { Transform & tf = this->get_component(); tf.position.y -= 1; break; } - case Keycode::S: - { + case Keycode::S: { Transform & tf = this->get_component(); tf.position.y += 1; break; } - case Keycode::D: - { + case Keycode::D: { Transform & tf = this->get_component(); tf.position.x += 1; break; } - case Keycode::E: - { - if(flip){ + case Keycode::E: { + if (flip) { flip = false; this->get_component().active = true; this->get_components()[0].get().active = true; this->get_component().active = false; this->get_components()[1].get().active = false; - } - else { + } else { flip = true; this->get_component().active = false; this->get_components()[0].get().active = false; this->get_component().active = true; this->get_components()[1].get().active = true; } - - + //add collider switch break; } + case Keycode::Q: { + throw "Test"; + break; + } default: - break; + break; } return false; - } + } void init() { Log::logf("init"); - subscribe([this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); }); - subscribe([this](const KeyPressEvent & ev) -> bool { return this->keypressed(ev); }); + subscribe( + [this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); }); + subscribe( + [this](const KeyPressEvent & ev) -> bool { return this->keypressed(ev); }); } void update() { // Retrieve component from the same GameObject this script is on } - }; class MyScript2 : public Script { @@ -99,74 +97,68 @@ class MyScript2 : public Script { bool keypressed(const KeyPressEvent & test) { Log::logf("Box script keypressed()"); switch (test.key) { - case Keycode::LEFT: - { + case Keycode::LEFT: { Transform & tf = this->get_component(); tf.position.x -= 1; break; } - case Keycode::UP: - { + case Keycode::UP: { Transform & tf = this->get_component(); tf.position.y -= 1; break; } - case Keycode::DOWN: - { + case Keycode::DOWN: { Transform & tf = this->get_component(); tf.position.y += 1; break; } - case Keycode::RIGHT: - { + case Keycode::RIGHT: { Transform & tf = this->get_component(); tf.position.x += 1; break; } - case Keycode::PAUSE: - { - if(flip){ + case Keycode::PAUSE: { + if (flip) { flip = false; this->get_component().active = true; this->get_components()[0].get().active = true; this->get_component().active = false; this->get_components()[1].get().active = false; - } - else { + } else { flip = true; this->get_component().active = false; this->get_components()[0].get().active = false; this->get_component().active = true; this->get_components()[1].get().active = true; } - - + //add collider switch break; } default: - break; + break; } return false; - } + } void init() { Log::logf("init"); - subscribe([this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); }); - subscribe([this](const KeyPressEvent & ev) -> bool { return this->keypressed(ev); }); + subscribe( + [this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); }); + subscribe( + [this](const KeyPressEvent & ev) -> bool { return this->keypressed(ev); }); } void update() { // Retrieve component from the same GameObject this script is on } - }; class ConcreteScene1 : public Scene { public: using Scene::Scene; - + void load_scene() { - + Mediator & m = this->mediator; ComponentManager & mgr = m.component_manager; Color color(0, 0, 0, 255); @@ -195,7 +187,10 @@ public: vec2{world_collider, world_collider}); // Left world.add_component(vec2{screen_size_width / 2 + world_collider / 2, 0}, vec2{world_collider, world_collider}); // right - world.add_component(Color::WHITE, ivec2{static_cast(screen_size_width), static_cast(screen_size_height)}, vec2{screen_size_width, screen_size_height}, 1.0f); + world.add_component( + Color::WHITE, + ivec2{static_cast(screen_size_width), static_cast(screen_size_height)}, + vec2{screen_size_width, screen_size_height}, 1.0f); GameObject game_object1 = mgr.new_object( "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1); @@ -219,10 +214,10 @@ public: //add circle with cirlcecollider deactiveated game_object1.add_component(vec2{0, 0}, 10).active = false; auto img2 = Texture("asset/texture/circle.png"); - game_object1.add_component(img2, color, Sprite::FlipSettings{false, false}, 1, - 1, 20).active = false; - - + game_object1 + .add_component(img2, color, Sprite::FlipSettings{false, false}, 1, 1, 20) + .active + = false; GameObject game_object2 = mgr.new_object( "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1); @@ -246,9 +241,10 @@ public: //add circle with cirlcecollider deactiveated game_object2.add_component(vec2{0, 0}, 10).active = false; auto img4 = Texture("asset/texture/circle.png"); - game_object2.add_component(img4, color, Sprite::FlipSettings{false, false}, 1, - 1, 20).active = false; - + game_object2 + .add_component(img4, color, Sprite::FlipSettings{false, false}, 1, 1, 20) + .active + = false; } string get_name() const { return "scene1"; } diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp index a683b1f..dd45eb6 100644 --- a/src/test/CollisionTest.cpp +++ b/src/test/CollisionTest.cpp @@ -7,14 +7,14 @@ #define private public #define protected public -#include -#include #include -#include #include #include #include #include +#include +#include +#include #include #include #include diff --git a/src/test/Profiling.cpp b/src/test/Profiling.cpp index 91be769..f091d9d 100644 --- a/src/test/Profiling.cpp +++ b/src/test/Profiling.cpp @@ -9,14 +9,14 @@ #define private public #define protected public -#include #include -#include #include #include #include #include #include +#include +#include #include #include #include @@ -162,7 +162,7 @@ TEST_F(Profiling, Profiling_2) { .body_type = Rigidbody::BodyType::STATIC, }); gameobject.add_component(vec2{0, 0}, vec2{1, 1}); - + gameobject.add_component().set_script(); Color color(0, 0, 0, 0); auto img = Texture("asset/texture/green_square.png"); -- cgit v1.2.3 From 42ecf9c1d0e3ed1f37f99a24f31241b68f978b28 Mon Sep 17 00:00:00 2001 From: max-001 Date: Fri, 6 Dec 2024 10:14:33 +0100 Subject: Added script to shutdown game (by throwing an exception and not catching it) --- src/example/AITest.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'src/example') diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 841b195..91a529c 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -1,19 +1,33 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include -#include #include using namespace crepe; using namespace std; +class Script1 : public Script { + bool shutdown(const ShutDownEvent & event) { + // Very dirty way of shutting down the game + throw "ShutDownEvent"; + return true; + } + + void init() { + subscribe( + [this](const ShutDownEvent & ev) -> bool { return this->shutdown(ev); }); + } +}; + class Scene1 : public Scene { public: void load_scene() override { @@ -30,6 +44,7 @@ public: game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); + game_object2.add_component().set_script(); } string get_name() const override { return "Scene1"; } -- cgit v1.2.3 From 9c2cafd85ed7aa9a860ba25fbe2bd3ccc2439f29 Mon Sep 17 00:00:00 2001 From: max-001 Date: Fri, 6 Dec 2024 10:39:18 +0100 Subject: Using Rigidbody from now on --- src/crepe/api/AI.cpp | 6 +----- src/crepe/api/AI.h | 7 +------ src/crepe/system/AISystem.cpp | 22 +++++++++++----------- src/example/AITest.cpp | 6 +++++- 4 files changed, 18 insertions(+), 23 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/AI.cpp b/src/crepe/api/AI.cpp index 7f820a8..d785bb5 100644 --- a/src/crepe/api/AI.cpp +++ b/src/crepe/api/AI.cpp @@ -2,10 +2,6 @@ namespace crepe { -AI::AI(game_object_id_t id, float mass, float max_speed, float max_force) - : Component(id), - mass(mass), - max_speed(max_speed), - max_force(max_force) {} +AI::AI(game_object_id_t id, float max_force) : Component(id), max_force(max_force) {} } // namespace crepe diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h index 242ff89..046426d 100644 --- a/src/crepe/api/AI.h +++ b/src/crepe/api/AI.h @@ -16,7 +16,7 @@ public: }; public: - AI(game_object_id_t id, float mass, float max_speed, float max_force); + AI(game_object_id_t id, float max_force); bool on(BehaviorType behavior) const { return (flags & behavior) == behavior; } void seek_on() { flags |= SEEK; } @@ -37,8 +37,6 @@ public: } public: - float mass; - float max_speed; float max_force; // The target to seek or arrive at @@ -51,9 +49,6 @@ public: float arrive_deceleration = 2.0f; private: - vec2 velocity; - friend class AISystem; - int flags = 0; }; diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index 3c61c78..d496e12 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -1,4 +1,5 @@ #include "api/LoopTimer.h" +#include "api/Rigidbody.h" #include "api/Transform.h" #include "manager/ComponentManager.h" #include "manager/Mediator.h" @@ -16,16 +17,13 @@ void AISystem::update() { double dt = LoopTimer::get_instance().get_delta_time(); for (AI & ai : ai_components) { + RefVector rigidbodies + = mgr.get_components_by_id(ai.game_object_id); + Rigidbody & rigidbody = rigidbodies.front().get(); + vec2 force = this->calculate(ai); - vec2 acceleration = force / ai.mass; - ai.velocity += acceleration * dt; - ai.velocity.truncate(ai.max_speed); - - // Update the position - RefVector transforms - = mgr.get_components_by_id(ai.game_object_id); - Transform & transform = transforms.front().get(); - transform.position += ai.velocity * dt; + vec2 acceleration = force / rigidbody.data.mass; + rigidbody.data.linear_velocity += acceleration * dt; } } @@ -69,10 +67,12 @@ vec2 AISystem::seek(const AI & ai) { ComponentManager & mgr = mediator.component_manager; RefVector transforms = mgr.get_components_by_id(ai.game_object_id); Transform & transform = transforms.front().get(); + RefVector rigidbodies = mgr.get_components_by_id(ai.game_object_id); + Rigidbody & rigidbody = rigidbodies.front().get(); vec2 desired_velocity = ai.seek_target - transform.position; desired_velocity.normalize(); - desired_velocity *= ai.max_speed; + desired_velocity *= rigidbody.data.max_linear_velocity; - return desired_velocity - ai.velocity; + return desired_velocity - rigidbody.data.linear_velocity; } diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 91a529c..2b6a4d6 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -40,7 +41,10 @@ public: Texture img = Texture("asset/texture/test_ap43.png"); game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); - game_object1.add_component(1, 200, 200).seek_on(); + game_object1.add_component(200).seek_on(); + game_object1.add_component(Rigidbody::Data{ + .mass = 1.0f, .max_linear_velocity = {21, 21}, // sqrt(21^2 + 21^2) = 30 + }); game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); -- cgit v1.2.3 From 0c1cd46d22d9006ab46442c92bc7bd8858079ea8 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Fri, 6 Dec 2024 11:13:01 +0100 Subject: merged master --- src/crepe/facade/SDLContext.cpp | 4 +--- src/crepe/system/InputSystem.cpp | 4 ++-- src/doc/feature/animator_creation.dox | 0 src/example/rendering_particle.cpp | 28 +++++++--------------------- 4 files changed, 10 insertions(+), 26 deletions(-) create mode 100644 src/doc/feature/animator_creation.dox (limited to 'src/example') diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 72b4e42..0097070 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include @@ -19,7 +18,6 @@ #include "../api/Config.h" #include "../api/Sprite.h" #include "../api/Texture.h" -#include "../manager/EventManager.h" #include "../util/Log.h" #include "SDLContext.h" @@ -273,7 +271,7 @@ void SDLContext::draw(const RenderContext & ctx) { double angle = ctx.angle + data.angle_offset; - this->set_color_texture(ctx.sprite.sprite_image, ctx.sprite.color); + this->set_color_texture(ctx.sprite.texture, ctx.sprite.data.color); SDL_RenderCopyExF(this->game_renderer.get(), ctx.sprite.texture.texture.get(), &srcrect, &dstrect, angle, NULL, render_flip); } diff --git a/src/crepe/system/InputSystem.cpp b/src/crepe/system/InputSystem.cpp index 7cc8d30..56a40b7 100644 --- a/src/crepe/system/InputSystem.cpp +++ b/src/crepe/system/InputSystem.cpp @@ -25,9 +25,9 @@ void InputSystem::update() { = mgr.get_components_by_id(current_cam.game_object_id); Transform & cam_transform = transform_vec.front().get(); int camera_origin_x - = cam_transform.position.x + current_cam.offset.x - (current_cam.viewport_size.x / 2); + = cam_transform.position.x + current_cam.data.offset.x - (current_cam.viewport_size.x / 2); int camera_origin_y - = cam_transform.position.y + current_cam.offset.y - (current_cam.viewport_size.y / 2); + = cam_transform.position.y + current_cam.data.offset.y - (current_cam.viewport_size.y / 2); for (const SDLContext::EventData & event : event_list) { int world_mouse_x = event.mouse_position.x + camera_origin_x; diff --git a/src/doc/feature/animator_creation.dox b/src/doc/feature/animator_creation.dox new file mode 100644 index 0000000..e69de29 diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 07e43a1..9d6b537 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -1,21 +1,16 @@ -#include "api/Animator.h" -#include "api/Camera.h" -#include "api/LoopManager.h" -#include "api/LoopTimer.h" -#include "system/AnimatorSystem.h" -#include "system/ParticleSystem.h" -#include -#include - #include +#include +#include #include #include +#include #include #include #include #include #include -#include +#include +#include #include using namespace crepe; @@ -46,7 +41,8 @@ using namespace std; class TestScene : public Scene { public: void load_scene() { - ComponentManager & mgr = this->component_manager; + Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; GameObject game_object = mgr.new_object("", "", vec2{0, 0}, 0, 1); Color color(255, 255, 255, 255); @@ -84,15 +80,5 @@ int main(int argc, char * argv[]) { LoopManager engine; engine.add_scene(); engine.start(); - - /* - game_object - .add_component(make_shared("asset/texture/img.png"), color, - .add_component(make_shared("asset/texture/img.png"), color, - FlipSettings{false, false}) - .order_in_layer - = 6; - */ - return 0; } -- cgit v1.2.3 From 7ec1fcfcff0c01d204ccbf1bac9919ba610b8606 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Fri, 6 Dec 2024 15:42:25 +0100 Subject: implemented final max feedback --- src/crepe/api/Animator.cpp | 2 +- src/crepe/api/Animator.h | 26 ++++++++++++++------------ src/crepe/api/Camera.h | 2 +- src/crepe/api/Sprite.h | 12 +++++++++--- src/crepe/facade/SDLContext.cpp | 2 +- src/crepe/manager/Mediator.h | 2 ++ src/crepe/system/InputSystem.cpp | 4 ++-- src/crepe/system/RenderSystem.cpp | 2 +- src/crepe/system/RenderSystem.h | 3 +-- src/example/rendering_particle.cpp | 1 + 10 files changed, 33 insertions(+), 23 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp index dc99fd4..8b91859 100644 --- a/src/crepe/api/Animator.cpp +++ b/src/crepe/api/Animator.cpp @@ -7,7 +7,7 @@ using namespace crepe; -Animator::Animator(uint32_t id, Sprite & ss, int max_row, int max_col, +Animator::Animator(uint32_t id, Sprite & ss, unsigned int max_row, unsigned int max_col, const Animator::Data & ctx) : Component(id), spritesheet(ss), diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index dab6697..e0399a8 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -2,6 +2,8 @@ #include "Component.h" #include "Sprite.h" +#include "types.h" +#include namespace crepe { @@ -20,26 +22,26 @@ public: struct Data { //! frames per second for animation - int fps = 1; + unsigned int fps = 1; //! The current col being animated. - int curr_col = 0; + unsigned int curr_col = 0; //! The current row being animated. - int curr_row = 0; + unsigned int curr_row = 0; //! should the animation loop bool looping = false; //! starting frame for cycling - int cycle_start = 0; + unsigned int cycle_start = 0; //! end frame for cycling (-1 --> use last frame) int cycle_end = -1; //! offset in pixels. // TODO implement - int offset_x = 0; + unsigned int white_space = 0; }; public: @@ -100,12 +102,15 @@ public: * \brief Constructs an Animator object that will control animations for a sprite sheet. * * \param id The unique identifier for the component, typically assigned automatically. - * \param ctx animator data + * \param ss the reference to the spritesheet + * \param max_row maximum of rows inside the given spritesheet + * \param max_col maximum of columns inside the given spritesheet + * \param ctx extra animation data for more control * * This constructor sets up the Animator with the given parameters, and initializes the * animation system. */ - Animator(uint32_t id, Sprite & ss, int max_row, int max_col, const Animator::Data & ctx); + Animator(game_object_id_t id, Sprite & ss, unsigned int max_row, unsigned int max_col, const Animator::Data & ctx); ~Animator(); // dbg_trace public: @@ -113,16 +118,13 @@ public: Sprite & spritesheet; //! The maximum number of columns in the sprite sheet. - const int col; + const unsigned int col; //! The maximum number of rows in the sprite sheet. - const int row; + const unsigned int row; Animator::Data data; -private: - //! AnimatorSystem adjust the private member parameters of Animator; - friend class AnimatorSystem; }; } // namespace crepe // diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h index f626379..84ca9e1 100644 --- a/src/crepe/api/Camera.h +++ b/src/crepe/api/Camera.h @@ -23,7 +23,7 @@ public: double zoom = 1; //! offset postion from the game object transform component - vec2 offset; + vec2 postion_offset; }; public: diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index a1230db..0ccc296 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -20,11 +20,14 @@ class AnimatorSystem; */ class Sprite : public Component { public: + //! settings to flip the image struct FlipSettings { + //! horizantal flip bool flip_x = false; + //! vertical flip bool flip_y = false; }; - + struct Data { //! Color tint of the sprite Color color = Color::WHITE; @@ -50,10 +53,13 @@ public: vec2 size; //! independent sprite angle. rotating clockwise direction in degrees - double angle_offset = 0; + float angle_offset = 0; //! independent sprite scale multiplier - double scale_offset = 1; + float scale_offset = 1; + + //! independent sprite offset position + vec2 position_offset; }; public: diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 0097070..9533b8a 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -243,7 +243,7 @@ SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { size *= cam.render_scale * ctx.img_scale * data.scale_offset; - vec2 screen_pos = (ctx.pos - cam.cam_pos + (cam.zoomed_viewport) / 2) * cam.render_scale + vec2 screen_pos = (ctx.pos + data.position_offset - cam.cam_pos + (cam.zoomed_viewport) / 2) * cam.render_scale - size / 2 + cam.bar_size; return SDL_FRect{ diff --git a/src/crepe/manager/Mediator.h b/src/crepe/manager/Mediator.h index 71bd1c9..5b53bcc 100644 --- a/src/crepe/manager/Mediator.h +++ b/src/crepe/manager/Mediator.h @@ -5,6 +5,7 @@ // TODO: remove these singletons: #include "EventManager.h" #include "SaveManager.h" +#include "../facade/SDLContext.h" namespace crepe { @@ -28,6 +29,7 @@ struct Mediator { OptionalRef scene_manager; OptionalRef save_manager = SaveManager::get_instance(); OptionalRef event_manager = EventManager::get_instance(); + OptionalRef sdl_context = SDLContext::get_instance(); }; } // namespace crepe diff --git a/src/crepe/system/InputSystem.cpp b/src/crepe/system/InputSystem.cpp index 20da644..aaa8bdf 100644 --- a/src/crepe/system/InputSystem.cpp +++ b/src/crepe/system/InputSystem.cpp @@ -24,9 +24,9 @@ void InputSystem::update() { RefVector transform_vec = mgr.get_components_by_id(current_cam.game_object_id); Transform & cam_transform = transform_vec.front().get(); - int camera_origin_x = cam_transform.position.x + current_cam.data.offset.x + int camera_origin_x = cam_transform.position.x + current_cam.data.postion_offset.x - (current_cam.viewport_size.x / 2); - int camera_origin_y = cam_transform.position.y + current_cam.data.offset.y + int camera_origin_y = cam_transform.position.y + current_cam.data.postion_offset.y - (current_cam.viewport_size.y / 2); for (const SDLContext::EventData & event : event_list) { diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp index 111ad7d..0ba71ec 100644 --- a/src/crepe/system/RenderSystem.cpp +++ b/src/crepe/system/RenderSystem.cpp @@ -33,7 +33,7 @@ SDLContext::CameraValues RenderSystem::update_camera() { const Transform & transform = mgr.get_components_by_id(cam.game_object_id).front().get(); SDLContext::CameraValues cam_val = this->context.set_camera(cam); - cam_val.cam_pos = transform.position + cam.data.offset; + cam_val.cam_pos = transform.position + cam.data.postion_offset; return cam_val; } throw std::runtime_error("No active cameras in current scene"); diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h index eaf1213..91b386f 100644 --- a/src/crepe/system/RenderSystem.h +++ b/src/crepe/system/RenderSystem.h @@ -79,8 +79,7 @@ private: */ private: - // FIXME: retrieve sdlcontext via mediator after #PR57 - SDLContext & context = SDLContext::get_instance(); + SDLContext & context = this->mediator.sdl_context; }; } // namespace crepe diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 9d6b537..145bc5e 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -57,6 +57,7 @@ public: .order_in_layer = 2, .size = {0, 100}, .angle_offset = 0, + .position_offset = {100,0}, }); auto & anim = game_object.add_component(test_sprite, 4, 4, -- cgit v1.2.3 From 83ee80ea439fc6a9042307a25b214b3efcf28d91 Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Fri, 6 Dec 2024 15:42:52 +0100 Subject: make format --- src/crepe/api/Animator.h | 4 ++-- src/crepe/api/Sprite.h | 4 ++-- src/crepe/facade/SDLContext.cpp | 6 ++++-- src/crepe/manager/Mediator.h | 2 +- src/example/rendering_particle.cpp | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h index e0399a8..2a0a889 100644 --- a/src/crepe/api/Animator.h +++ b/src/crepe/api/Animator.h @@ -110,7 +110,8 @@ public: * This constructor sets up the Animator with the given parameters, and initializes the * animation system. */ - Animator(game_object_id_t id, Sprite & ss, unsigned int max_row, unsigned int max_col, const Animator::Data & ctx); + Animator(game_object_id_t id, Sprite & ss, unsigned int max_row, unsigned int max_col, + const Animator::Data & ctx); ~Animator(); // dbg_trace public: @@ -124,7 +125,6 @@ public: const unsigned int row; Animator::Data data; - }; } // namespace crepe // diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index 0ccc296..78ed7ad 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -27,7 +27,7 @@ public: //! vertical flip bool flip_y = false; }; - + struct Data { //! Color tint of the sprite Color color = Color::WHITE; @@ -58,7 +58,7 @@ public: //! independent sprite scale multiplier float scale_offset = 1; - //! independent sprite offset position + //! independent sprite offset position vec2 position_offset; }; diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 9533b8a..cf9f7d5 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -243,8 +243,10 @@ SDL_FRect SDLContext::get_dst_rect(const DstRect & ctx) const { size *= cam.render_scale * ctx.img_scale * data.scale_offset; - vec2 screen_pos = (ctx.pos + data.position_offset - cam.cam_pos + (cam.zoomed_viewport) / 2) * cam.render_scale - - size / 2 + cam.bar_size; + vec2 screen_pos + = (ctx.pos + data.position_offset - cam.cam_pos + (cam.zoomed_viewport) / 2) + * cam.render_scale + - size / 2 + cam.bar_size; return SDL_FRect{ .x = screen_pos.x, diff --git a/src/crepe/manager/Mediator.h b/src/crepe/manager/Mediator.h index 5b53bcc..f8517a3 100644 --- a/src/crepe/manager/Mediator.h +++ b/src/crepe/manager/Mediator.h @@ -3,9 +3,9 @@ #include "../util/OptionalRef.h" // TODO: remove these singletons: +#include "../facade/SDLContext.h" #include "EventManager.h" #include "SaveManager.h" -#include "../facade/SDLContext.h" namespace crepe { diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp index 145bc5e..29d475d 100644 --- a/src/example/rendering_particle.cpp +++ b/src/example/rendering_particle.cpp @@ -57,7 +57,7 @@ public: .order_in_layer = 2, .size = {0, 100}, .angle_offset = 0, - .position_offset = {100,0}, + .position_offset = {100, 0}, }); auto & anim = game_object.add_component(test_sprite, 4, 4, -- cgit v1.2.3 From 9eac8d31b25c234a21b1d188df17e77e71f48088 Mon Sep 17 00:00:00 2001 From: max-001 Date: Fri, 6 Dec 2024 16:21:40 +0100 Subject: Improved example --- src/crepe/system/CollisionSystem.cpp | 2 -- src/example/AITest.cpp | 17 ++++++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) (limited to 'src/example') diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp index 2a487fd..1282f7a 100644 --- a/src/crepe/system/CollisionSystem.cpp +++ b/src/crepe/system/CollisionSystem.cpp @@ -550,5 +550,3 @@ vec2 CollisionSystem::get_current_position(const vec2 & collider_offset, // Final positions considering scaling and rotation return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1)); } - - diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 2b6a4d6..144aef3 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -12,6 +12,7 @@ #include #include #include +#include using namespace crepe; using namespace std; @@ -23,9 +24,19 @@ class Script1 : public Script { return true; } + bool mousemove(const MouseMoveEvent & event) { + RefVector aivec = this->get_components(); + AI & ai = aivec.front().get(); + ai.seek_target + = vec2{static_cast(event.mouse_x), static_cast(event.mouse_y)}; + return true; + } + void init() { subscribe( [this](const ShutDownEvent & ev) -> bool { return this->shutdown(ev); }); + subscribe( + [this](const MouseMoveEvent & ev) -> bool { return this->mousemove(ev); }); } }; @@ -41,14 +52,14 @@ public: Texture img = Texture("asset/texture/test_ap43.png"); game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); - game_object1.add_component(200).seek_on(); + game_object1.add_component(30).seek_on(); game_object1.add_component(Rigidbody::Data{ - .mass = 1.0f, .max_linear_velocity = {21, 21}, // sqrt(21^2 + 21^2) = 30 + .mass = 0.5f, .max_linear_velocity = {21, 21}, // sqrt(21^2 + 21^2) = 30 }); + game_object1.add_component().set_script(); game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, 1.0f); - game_object2.add_component().set_script(); } string get_name() const override { return "Scene1"; } -- cgit v1.2.3 From 0d0943d23364d7110f0232e3564f4ea63af13db2 Mon Sep 17 00:00:00 2001 From: max-001 Date: Fri, 6 Dec 2024 16:41:51 +0100 Subject: Implemented flee and arrive behaviors --- src/crepe/api/AI.h | 4 +-- src/crepe/system/AISystem.cpp | 71 ++++++++++++++++++++++++++++++++++++++----- src/example/AITest.cpp | 6 ++-- 3 files changed, 69 insertions(+), 12 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h index 046426d..d4bd9d3 100644 --- a/src/crepe/api/AI.h +++ b/src/crepe/api/AI.h @@ -44,9 +44,9 @@ public: // The target to flee from vec2 flee_target; // The distance at which the entity will start to flee from the target - float square_flee_panic_distance = 100.0f * 100.0f; + float square_flee_panic_distance = 200.0f * 200.0f; // The deceleration rate for the arrive behavior (higher values will make the entity decelerate faster (less overshoot)) - float arrive_deceleration = 2.0f; + float arrive_deceleration = 40.0f; private: int flags = 0; diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index 4858000..ce3147f 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -1,11 +1,14 @@ +#include +#include + #include "api/LoopTimer.h" #include "api/Rigidbody.h" #include "api/Transform.h" #include "manager/ComponentManager.h" #include "manager/Mediator.h" -#include "types.h" #include "AISystem.h" +#include "types.h" using namespace crepe; @@ -30,21 +33,33 @@ void AISystem::update() { vec2 AISystem::calculate(AI & ai) { vec2 force; - if (ai.on(AI::BehaviorType::SEEK)) { - vec2 force_to_add = this->seek(ai); + if (ai.on(AI::BehaviorType::FLEE)) { + vec2 force_to_add = this->flee(ai); if (!this->accumulate_force(ai, force, force_to_add)) { return force; } } - if (ai.on(AI::BehaviorType::FLEE)) { - // Flee from the target - } if (ai.on(AI::BehaviorType::ARRIVE)) { - // Arrive at the target + vec2 force_to_add = this->arrive(ai); + + if (!this->accumulate_force(ai, force, force_to_add)) { + return force; + } + } + if (ai.on(AI::BehaviorType::SEEK)) { + vec2 force_to_add = this->seek(ai); + + if (!this->accumulate_force(ai, force, force_to_add)) { + return force; + } } if (ai.on(AI::BehaviorType::PATH_FOLLOW)) { - // Follow the path + /*vec2 force_to_add = this->path_follow(ai); + + if (!this->accumulate_force(ai, force, force_to_add)) { + return force; + }*/ } return force; @@ -83,3 +98,43 @@ vec2 AISystem::seek(const AI & ai) { return desired_velocity - rigidbody.data.linear_velocity; } + +vec2 AISystem::flee(const AI & ai) { + const Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; + RefVector transforms = mgr.get_components_by_id(ai.game_object_id); + Transform & transform = transforms.front().get(); + RefVector rigidbodies = mgr.get_components_by_id(ai.game_object_id); + Rigidbody & rigidbody = rigidbodies.front().get(); + + vec2 desired_velocity = transform.position - ai.flee_target; + if (desired_velocity.length_squared() > ai.square_flee_panic_distance) { + return vec2{0, 0}; + } + + desired_velocity.normalize(); + desired_velocity *= rigidbody.data.max_linear_velocity; + + return desired_velocity - rigidbody.data.linear_velocity; +} + +vec2 AISystem::arrive(const AI & ai) { + const Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; + RefVector transforms = mgr.get_components_by_id(ai.game_object_id); + Transform & transform = transforms.front().get(); + RefVector rigidbodies = mgr.get_components_by_id(ai.game_object_id); + Rigidbody & rigidbody = rigidbodies.front().get(); + + vec2 to_target = ai.seek_target - transform.position; + float distance = to_target.length(); + if (distance > 0.0f) { + float speed = distance / ai.arrive_deceleration; + speed = std::min(speed, rigidbody.data.max_linear_velocity.length()); + vec2 desired_velocity = to_target * (speed / distance); + + return desired_velocity - rigidbody.data.linear_velocity; + } + + return vec2{0, 0}; +} diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 144aef3..319d0fe 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -27,7 +27,7 @@ class Script1 : public Script { bool mousemove(const MouseMoveEvent & event) { RefVector aivec = this->get_components(); AI & ai = aivec.front().get(); - ai.seek_target + ai.flee_target = vec2{static_cast(event.mouse_x), static_cast(event.mouse_y)}; return true; } @@ -52,7 +52,9 @@ public: Texture img = Texture("asset/texture/test_ap43.png"); game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); - game_object1.add_component(30).seek_on(); + AI & ai = game_object1.add_component(30); + ai.arrive_on(); + ai.flee_on(); game_object1.add_component(Rigidbody::Data{ .mass = 0.5f, .max_linear_velocity = {21, 21}, // sqrt(21^2 + 21^2) = 30 }); -- cgit v1.2.3 From 33a072db28d71ba65e59f9491abd42dbf9695fc4 Mon Sep 17 00:00:00 2001 From: max-001 Date: Fri, 6 Dec 2024 17:14:00 +0100 Subject: Implemented path_follow --- src/crepe/api/AI.h | 14 ++++++++++++++ src/crepe/system/AISystem.cpp | 34 ++++++++++++++++++++++++++++++++-- src/crepe/system/AISystem.h | 2 +- src/example/AITest.cpp | 21 +++++++++++++-------- 4 files changed, 60 insertions(+), 11 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h index d4bd9d3..35b8998 100644 --- a/src/crepe/api/AI.h +++ b/src/crepe/api/AI.h @@ -36,6 +36,8 @@ public: if (on(PATH_FOLLOW)) flags ^= PATH_FOLLOW; } + void add_path_node(vec2 node) { path.push_back(node); } + public: float max_force; @@ -47,9 +49,21 @@ public: float square_flee_panic_distance = 200.0f * 200.0f; // The deceleration rate for the arrive behavior (higher values will make the entity decelerate faster (less overshoot)) float arrive_deceleration = 40.0f; + // The path to follow + std::vector path; + // The distance from the path node at which the entity will move to the next node + float path_node_distance = 400.0f; + // Looping behavior for the path + bool path_loop = true; private: + // The flags for the behaviors int flags = 0; + // The current path index + size_t path_index = 0; + + // The AISystem is the only class that can access the private members of AI + friend class AISystem; }; } // namespace crepe diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp index ce3147f..55dc14c 100644 --- a/src/crepe/system/AISystem.cpp +++ b/src/crepe/system/AISystem.cpp @@ -55,11 +55,11 @@ vec2 AISystem::calculate(AI & ai) { } } if (ai.on(AI::BehaviorType::PATH_FOLLOW)) { - /*vec2 force_to_add = this->path_follow(ai); + vec2 force_to_add = this->path_follow(ai); if (!this->accumulate_force(ai, force, force_to_add)) { return force; - }*/ + } } return force; @@ -138,3 +138,33 @@ vec2 AISystem::arrive(const AI & ai) { return vec2{0, 0}; } + +vec2 AISystem::path_follow(AI & ai) { + const Mediator & mediator = this->mediator; + ComponentManager & mgr = mediator.component_manager; + RefVector transforms = mgr.get_components_by_id(ai.game_object_id); + Transform & transform = transforms.front().get(); + RefVector rigidbodies = mgr.get_components_by_id(ai.game_object_id); + Rigidbody & rigidbody = rigidbodies.front().get(); + + if (ai.path.empty()) { + return vec2{0, 0}; + } + + vec2 to_target = ai.path.at(ai.path_index) - transform.position; + if (to_target.length_squared() > ai.path_node_distance * ai.path_node_distance) { + ai.seek_target = ai.path.at(ai.path_index); + } else { + ai.path_index++; + if (ai.path_index >= ai.path.size()) { + if (ai.path_loop) { + ai.path_index = 0; + } else { + ai.path_index = ai.path.size() - 1; + return this->arrive(ai); + } + } + } + + return this->seek(ai); +} diff --git a/src/crepe/system/AISystem.h b/src/crepe/system/AISystem.h index 18f1c61..27861d9 100644 --- a/src/crepe/system/AISystem.h +++ b/src/crepe/system/AISystem.h @@ -20,7 +20,7 @@ private: vec2 seek(const AI & ai); vec2 flee(const AI & ai); vec2 arrive(const AI & ai); - vec2 path_follow(const AI & ai); + vec2 path_follow(AI & ai); }; } // namespace crepe diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp index 319d0fe..d12a99a 100644 --- a/src/example/AITest.cpp +++ b/src/example/AITest.cpp @@ -25,10 +25,10 @@ class Script1 : public Script { } bool mousemove(const MouseMoveEvent & event) { - RefVector aivec = this->get_components(); + /*RefVector aivec = this->get_components(); AI & ai = aivec.front().get(); ai.flee_target - = vec2{static_cast(event.mouse_x), static_cast(event.mouse_y)}; + = vec2{static_cast(event.mouse_x), static_cast(event.mouse_y)};*/ return true; } @@ -46,21 +46,26 @@ public: Mediator & mediator = this->mediator; ComponentManager & mgr = mediator.component_manager; - GameObject game_object1 = mgr.new_object("", "", vec2{250, 250}, 0, 1); + GameObject game_object1 = mgr.new_object("", "", vec2{0, 0}, 0, 1); GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1); Texture img = Texture("asset/texture/test_ap43.png"); game_object1.add_component(img, Color::MAGENTA, Sprite::FlipSettings{false, false}, 1, 1, 195); - AI & ai = game_object1.add_component(30); - ai.arrive_on(); - ai.flee_on(); + AI & ai = game_object1.add_component(300); + // ai.arrive_on(); + // ai.flee_on(); + ai.path_follow_on(); + ai.add_path_node(vec2{1200, 1200}); + ai.add_path_node(vec2{-1200, 1200}); + ai.add_path_node(vec2{1200, -1200}); + ai.add_path_node(vec2{-1200, -1200}); game_object1.add_component(Rigidbody::Data{ - .mass = 0.5f, .max_linear_velocity = {21, 21}, // sqrt(21^2 + 21^2) = 30 + .mass = 0.5f, .max_linear_velocity = {50, 50}, // sqrt(21^2 + 21^2) = 30 }); game_object1.add_component().set_script(); - game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{1036, 780}, + game_object2.add_component(Color::WHITE, ivec2{1080, 720}, vec2{5000, 5000}, 1.0f); } -- cgit v1.2.3 From f19f37ae3eff84161f86e62a26fbd8b68f8f91a9 Mon Sep 17 00:00:00 2001 From: Loek Le Blansch Date: Sat, 7 Dec 2024 15:29:33 +0100 Subject: make SaveManager no longer a singleton --- src/crepe/manager/Mediator.h | 4 ++-- src/crepe/manager/SaveManager.cpp | 32 +++++++++++++--------------- src/crepe/manager/SaveManager.h | 27 ++++++++++-------------- src/example/CMakeLists.txt | 2 -- src/example/asset_manager.cpp | 36 -------------------------------- src/example/savemgr.cpp | 44 --------------------------------------- src/test/CMakeLists.txt | 1 + src/test/SaveManagerTest.cpp | 41 ++++++++++++++++++++++++++++++++++++ 8 files changed, 69 insertions(+), 118 deletions(-) delete mode 100644 src/example/asset_manager.cpp delete mode 100644 src/example/savemgr.cpp create mode 100644 src/test/SaveManagerTest.cpp (limited to 'src/example') diff --git a/src/crepe/manager/Mediator.h b/src/crepe/manager/Mediator.h index 8094d80..6507a74 100644 --- a/src/crepe/manager/Mediator.h +++ b/src/crepe/manager/Mediator.h @@ -5,13 +5,13 @@ // TODO: remove these singletons: #include "../facade/SDLContext.h" #include "EventManager.h" -#include "SaveManager.h" #include "api/LoopTimer.h" namespace crepe { class ComponentManager; class SceneManager; +class SaveManager; /** * Struct to pass references to classes that would otherwise need to be singletons down to @@ -28,7 +28,7 @@ class SceneManager; struct Mediator { OptionalRef component_manager; OptionalRef scene_manager; - OptionalRef save_manager = SaveManager::get_instance(); + OptionalRef save_manager; OptionalRef event_manager = EventManager::get_instance(); OptionalRef sdl_context = SDLContext::get_instance(); OptionalRef timer = LoopTimer::get_instance(); diff --git a/src/crepe/manager/SaveManager.cpp b/src/crepe/manager/SaveManager.cpp index d4ed1c1..292e8fd 100644 --- a/src/crepe/manager/SaveManager.cpp +++ b/src/crepe/manager/SaveManager.cpp @@ -1,13 +1,24 @@ #include "../ValueBroker.h" #include "../api/Config.h" #include "../facade/DB.h" -#include "../util/Log.h" #include "SaveManager.h" using namespace std; using namespace crepe; +SaveManager::SaveManager(Mediator & mediator) : Manager(mediator) { + mediator.save_manager = *this; +} + +DB & SaveManager::get_db() { + if (this->db == nullptr) { + Config & cfg = Config::get_instance(); + this->db = make_unique(cfg.savemgr.location); + } + return *this->db; +} + template <> string SaveManager::serialize(const string & value) const noexcept { return value; @@ -90,22 +101,6 @@ int32_t SaveManager::deserialize(const string & value) const noexcept { return deserialize(value); } -SaveManager::SaveManager() { dbg_trace(); } - -SaveManager & SaveManager::get_instance() { - dbg_trace(); - static SaveManager instance; - return instance; -} - -DB & SaveManager::get_db() { - Config & cfg = Config::get_instance(); - // TODO: make this path relative to XDG_DATA_HOME on Linux and whatever the - // default equivalent is on Windows using some third party library - static DB db(cfg.savemgr.location); - return db; -} - bool SaveManager::has(const string & key) { DB & db = this->get_db(); return db.has(key); @@ -155,7 +150,8 @@ ValueBroker SaveManager::get(const string & key) { return { [this, key](const T & target) { this->set(key, target); }, [this, key, value]() mutable -> const T & { - value = this->deserialize(this->get_db().get(key)); + DB & db = this->get_db(); + value = this->deserialize(db.get(key)); return value; }, }; diff --git a/src/crepe/manager/SaveManager.h b/src/crepe/manager/SaveManager.h index 3d8c852..d13a97a 100644 --- a/src/crepe/manager/SaveManager.h +++ b/src/crepe/manager/SaveManager.h @@ -4,6 +4,8 @@ #include "../ValueBroker.h" +#include "Manager.h" + namespace crepe { class DB; @@ -18,7 +20,7 @@ class DB; * * The underlying database is a key-value store. */ -class SaveManager { +class SaveManager : public Manager { public: /** * \brief Get a read/write reference to a value and initialize it if it does not yet exist @@ -63,8 +65,8 @@ public: */ bool has(const std::string & key); -private: - SaveManager(); +public: + SaveManager(Mediator & mediator); virtual ~SaveManager() = default; private: @@ -90,25 +92,18 @@ private: T deserialize(const std::string & value) const noexcept; public: - // singleton - static SaveManager & get_instance(); SaveManager(const SaveManager &) = delete; SaveManager(SaveManager &&) = delete; SaveManager & operator=(const SaveManager &) = delete; SaveManager & operator=(SaveManager &&) = delete; +protected: + //! Create or return DB + virtual DB & get_db(); + private: - /** - * \brief Create an instance of DB and return its reference - * - * \returns DB instance - * - * This function exists because DB is a facade class, which can't directly be used in the API - * without workarounds - * - * TODO: better solution - */ - static DB & get_db(); + //! Database + std::unique_ptr db = nullptr; }; } // namespace crepe diff --git a/src/example/CMakeLists.txt b/src/example/CMakeLists.txt index 8ef71bb..5a93b1f 100644 --- a/src/example/CMakeLists.txt +++ b/src/example/CMakeLists.txt @@ -16,8 +16,6 @@ function(add_example target_name) add_dependencies(examples ${target_name}) endfunction() -add_example(asset_manager) -add_example(savemgr) add_example(rendering_particle) add_example(game) add_example(button) diff --git a/src/example/asset_manager.cpp b/src/example/asset_manager.cpp deleted file mode 100644 index 917b547..0000000 --- a/src/example/asset_manager.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include -#include - -using namespace crepe; - -int main() { - - // this needs to be called before the asset manager otherwise the destructor of sdl is not in - // the right order - { Texture test("../asset/texture/img.png"); } - // FIXME: make it so the issue described by the above comment is not possible (i.e. the order - // in which internal classes are instantiated should not impact the way the engine works). - - auto & mgr = AssetManager::get_instance(); - - { - // TODO: [design] the Sound class can't be directly included by the user as it includes - // SoLoud headers. - auto bgm = mgr.cache("../mwe/audio/bgm.ogg"); - auto sfx1 = mgr.cache("../mwe/audio/sfx1.wav"); - auto sfx2 = mgr.cache("../mwe/audio/sfx2.wav"); - - auto img = mgr.cache("../asset/texture/img.png"); - auto img1 = mgr.cache("../asset/texture/second.png"); - } - - { - auto bgm = mgr.cache("../mwe/audio/bgm.ogg"); - auto sfx1 = mgr.cache("../mwe/audio/sfx1.wav"); - auto sfx2 = mgr.cache("../mwe/audio/sfx2.wav"); - - auto img = mgr.cache("../asset/texture/img.png"); - auto img1 = mgr.cache("../asset/texture/second.png"); - } -} diff --git a/src/example/savemgr.cpp b/src/example/savemgr.cpp deleted file mode 100644 index 65c4a34..0000000 --- a/src/example/savemgr.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/** \file - * - * Standalone example for usage of the save manager - */ - -#include -#include -#include -#include -#include - -using namespace crepe; - -// unrelated setup code -int _ = []() { - // make sure all log messages get printed - auto & cfg = Config::get_instance(); - cfg.log.level = Log::Level::TRACE; - - return 0; // satisfy compiler -}(); - -int main() { - const char * key = "mygame.test"; - - SaveManager & mgr = SaveManager::get_instance(); - - dbg_logf("has key = {}", mgr.has(key)); - ValueBroker prop = mgr.get(key, 0); - Proxy val = mgr.get(key, 0); - - dbg_logf("val = {}", mgr.get(key).get()); - prop.set(1); - dbg_logf("val = {}", mgr.get(key).get()); - val = 2; - dbg_logf("val = {}", mgr.get(key).get()); - mgr.set(key, 3); - dbg_logf("val = {}", mgr.get(key).get()); - - dbg_logf("has key = {}", mgr.has(key)); - assert(true == mgr.has(key)); - - return 0; -} diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt index c9cbac5..734e3ee 100644 --- a/src/test/CMakeLists.txt +++ b/src/test/CMakeLists.txt @@ -17,4 +17,5 @@ target_sources(test_main PUBLIC ScriptEventTest.cpp ScriptSceneTest.cpp Profiling.cpp + SaveManagerTest.cpp ) diff --git a/src/test/SaveManagerTest.cpp b/src/test/SaveManagerTest.cpp new file mode 100644 index 0000000..a1efc33 --- /dev/null +++ b/src/test/SaveManagerTest.cpp @@ -0,0 +1,41 @@ +#include + +#include +#include +#include + +using namespace std; +using namespace crepe; +using namespace testing; + +class SaveManagerTest : public Test { + Mediator m; + class TestSaveManager : public SaveManager { + using SaveManager::SaveManager; + + // in-memory database for testing + DB db{}; + virtual DB & get_db() override { return this->db; } + }; + +public: + TestSaveManager mgr{m}; +}; + +TEST_F(SaveManagerTest, ReadWrite) { + ASSERT_FALSE(mgr.has("foo")); + mgr.set("foo", "bar"); + ASSERT_TRUE(mgr.has("foo")); + + ValueBroker value = mgr.get("foo"); + EXPECT_EQ(value.get(), "bar"); +} + +TEST_F(SaveManagerTest, DefaultValue) { + ValueBroker value = mgr.get("foo", 3); + + ASSERT_EQ(value.get(), 3); + value.set(5); + ASSERT_EQ(value.get(), 5); +} + -- cgit v1.2.3 From 63bcd54e0e0ea64cfef5950568b4253d5dae5c1e Mon Sep 17 00:00:00 2001 From: heavydemon21 Date: Sun, 8 Dec 2024 14:29:25 +0100 Subject: removed singleton from SDLContext, problem now is cannot call functionalities in the constructor sprite and animator and texture because it can only be filled at rendersystem call --- src/crepe/api/Config.h | 2 +- src/crepe/api/LoopManager.h | 7 ++-- src/crepe/api/LoopTimer.cpp | 3 +- src/crepe/api/Sprite.cpp | 12 +++---- src/crepe/api/Sprite.h | 5 +-- src/crepe/api/Texture.cpp | 23 ++++--------- src/crepe/api/Texture.h | 15 ++++----- src/crepe/facade/SDLContext.cpp | 18 +++++----- src/crepe/facade/SDLContext.h | 62 +++++++++++++++-------------------- src/crepe/manager/EventManager.cpp | 2 ++ src/crepe/manager/Mediator.h | 4 +-- src/crepe/manager/ResourceManager.cpp | 2 +- src/crepe/manager/SceneManager.cpp | 3 ++ src/crepe/system/InputSystem.cpp | 6 +++- src/crepe/system/RenderSystem.cpp | 11 +++++++ src/example/rendering_particle.cpp | 9 +++-- 16 files changed, 95 insertions(+), 89 deletions(-) (limited to 'src/example') diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h index 6472270..73c9a4e 100644 --- a/src/crepe/api/Config.h +++ b/src/crepe/api/Config.h @@ -26,7 +26,7 @@ struct Config final { * * Only messages with equal or higher priority than this value will be logged. */ - Log::Level level = Log::Level::INFO; + Log::Level level = Log::Level::TRACE; /** * \brief Colored log output * diff --git a/src/crepe/api/LoopManager.h b/src/crepe/api/LoopManager.h index d8910a0..8a30602 100644 --- a/src/crepe/api/LoopManager.h +++ b/src/crepe/api/LoopManager.h @@ -8,6 +8,7 @@ #include "../system/System.h" #include "LoopTimer.h" +#include "manager/ResourceManager.h" namespace crepe { @@ -96,8 +97,10 @@ private: //! Scene manager instance SceneManager scene_manager{mediator}; - //! SDL context \todo no more singletons! - SDLContext & sdl_context = SDLContext::get_instance(); + SDLContext sdl_context {mediator}; + + ResourceManager res_man {mediator}; + //! Loop timer \todo no more singletons! LoopTimer & loop_timer = LoopTimer::get_instance(); diff --git a/src/crepe/api/LoopTimer.cpp b/src/crepe/api/LoopTimer.cpp index 15a0e3a..40fc94e 100644 --- a/src/crepe/api/LoopTimer.cpp +++ b/src/crepe/api/LoopTimer.cpp @@ -1,6 +1,5 @@ #include -#include "../facade/SDLContext.h" #include "../util/Log.h" #include "LoopTimer.h" @@ -67,7 +66,7 @@ void LoopTimer::enforce_frame_rate() { = std::chrono::duration_cast(this->frame_target_time - frame_duration); if (delay_time.count() > 0) { - SDLContext::get_instance().delay(delay_time.count()); + //SDLContext::get_instance().delay(delay_time.count()); } } diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp index cc0e20a..bae5ad9 100644 --- a/src/crepe/api/Sprite.cpp +++ b/src/crepe/api/Sprite.cpp @@ -2,25 +2,25 @@ #include #include "../util/Log.h" +#include "api/Asset.h" #include "Component.h" #include "Sprite.h" -#include "Texture.h" #include "types.h" using namespace std; using namespace crepe; -Sprite::Sprite(game_object_id_t id, Texture & texture, const Sprite::Data & data) +Sprite::Sprite(game_object_id_t id, const Asset & texture, const Sprite::Data & data) : Component(id), - texture(std::move(texture)), + source(texture), data(data) { dbg_trace(); - this->mask.w = this->texture.get_size().x; - this->mask.h = this->texture.get_size().y; - this->aspect_ratio = static_cast(this->mask.w) / this->mask.h; + //this->mask.w = this->texture.get_size().x; + //this->mask.h = this->texture.get_size().y; + //this->aspect_ratio = static_cast(this->mask.w) / this->mask.h; } Sprite::~Sprite() { dbg_trace(); } diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h index dbf41e4..ec120c0 100644 --- a/src/crepe/api/Sprite.h +++ b/src/crepe/api/Sprite.h @@ -4,6 +4,7 @@ #include "Color.h" #include "Texture.h" +#include "api/Asset.h" #include "types.h" namespace crepe { @@ -74,11 +75,11 @@ public: * \param texture asset of the image * \param ctx all the sprite data */ - Sprite(game_object_id_t id, Texture & texture, const Data & data); + Sprite(game_object_id_t id, const Asset & texture, const Data & data); ~Sprite(); //! Texture used for the sprite - const Texture texture; + const Asset source; Data data; diff --git a/src/crepe/api/Texture.cpp b/src/crepe/api/Texture.cpp index 2b56271..9d8e02d 100644 --- a/src/crepe/api/Texture.cpp +++ b/src/crepe/api/Texture.cpp @@ -1,16 +1,16 @@ -#include "../facade/SDLContext.h" #include "../util/Log.h" #include "Asset.h" +#include "Resource.h" #include "Texture.h" #include "types.h" +#include using namespace crepe; using namespace std; -Texture::Texture(const Asset & src) { +Texture::Texture(const Asset & src) : Resource(src) { dbg_trace(); - this->load(src); } Texture::~Texture() { @@ -18,21 +18,12 @@ Texture::~Texture() { this->texture.reset(); } -Texture::Texture(Texture && other) noexcept : texture(std::move(other.texture)) {} - -Texture & Texture::operator=(Texture && other) noexcept { - if (this != &other) { - texture = std::move(other.texture); - } - return *this; -} - -void Texture::load(const Asset & res) { - SDLContext & ctx = SDLContext::get_instance(); - this->texture = ctx.texture_from_path(res.get_path()); +void Texture::load(std::unique_ptr> texture) { + this->texture = std::move(texture); + this->loaded = true; } ivec2 Texture::get_size() const { if (this->texture == nullptr) return {}; - return SDLContext::get_instance().get_size(*this); + return {}; } diff --git a/src/crepe/api/Texture.h b/src/crepe/api/Texture.h index 1817910..f9c7919 100644 --- a/src/crepe/api/Texture.h +++ b/src/crepe/api/Texture.h @@ -8,6 +8,7 @@ #include #include "Asset.h" +#include "Resource.h" #include "types.h" namespace crepe { @@ -22,7 +23,7 @@ class Animator; * The Texture class is responsible for loading an image from a source and providing access to * its dimensions. Textures can be used for rendering. */ -class Texture { +class Texture : public Resource { public: /** @@ -35,12 +36,6 @@ public: * \brief Destroys the Texture instance, freeing associated resources. */ ~Texture(); - // FIXME: this constructor shouldn't be necessary because this class doesn't manage memory - - Texture(Texture && other) noexcept; - Texture & operator=(Texture && other) noexcept; - Texture(const Texture &) = delete; - Texture & operator=(const Texture &) = delete; /** * \brief Gets the width and height of the texture. @@ -53,12 +48,14 @@ private: * \brief Loads the texture from an Asset resource. * \param res Unique pointer to an Asset resource to load the texture from. */ - void load(const Asset & res); - + void load(std::unique_ptr> texture); + private: //! The texture of the class from the library std::unique_ptr> texture; + bool loaded = false; + //! Grants SDLContext access to private members. friend class SDLContext; diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp index 4cc2206..85257d6 100644 --- a/src/crepe/facade/SDLContext.cpp +++ b/src/crepe/facade/SDLContext.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -22,19 +23,16 @@ #include "../util/Log.h" #include "SDLContext.h" +#include "manager/Manager.h" +#include "manager/Mediator.h" #include "types.h" using namespace crepe; using namespace std; -SDLContext & SDLContext::get_instance() { - static SDLContext instance; - return instance; -} - -SDLContext::SDLContext() { +SDLContext::SDLContext(Mediator & mediator) : Manager(mediator){ dbg_trace(); - + mediator.sdl_context = *this; if (SDL_Init(SDL_INIT_VIDEO) != 0) { throw runtime_error(format("SDLContext: SDL_Init error: {}", SDL_GetError())); } @@ -261,6 +259,8 @@ SDL_FRect SDLContext::get_dst_rect(const DestinationRectangleData & ctx) const { void SDLContext::draw(const RenderContext & ctx) { + if (!ctx.texture.loaded) ctx.texture.load(this->texture_from_path(ctx.sprite.source.get_path())); + const Sprite::Data & data = ctx.sprite.data; SDL_RendererFlip render_flip = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * data.flip.flip_x) @@ -276,8 +276,8 @@ void SDLContext::draw(const RenderContext & ctx) { double angle = ctx.angle + data.angle_offset; - this->set_color_texture(ctx.sprite.texture, ctx.sprite.data.color); - SDL_RenderCopyExF(this->game_renderer.get(), ctx.sprite.texture.texture.get(), &srcrect, + this->set_color_texture(ctx.texture, ctx.sprite.data.color); + SDL_RenderCopyExF(this->game_renderer.get(), ctx.texture.texture.get(), &srcrect, &dstrect, angle, NULL, render_flip); } diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h index e232511..d95ebec 100644 --- a/src/crepe/facade/SDLContext.h +++ b/src/crepe/facade/SDLContext.h @@ -14,14 +14,16 @@ #include "api/Color.h" #include "api/KeyCodes.h" #include "api/Sprite.h" -#include "api/Texture.h" #include "api/Transform.h" + +#include "manager/Manager.h" +#include "manager/Mediator.h" #include "types.h" namespace crepe { -class LoopManager; -class InputSystem; +class Texture; + /** * \class SDLContext * \brief Facade for the SDL library @@ -29,7 +31,7 @@ class InputSystem; * SDLContext is a singleton that handles the SDL window and renderer, provides methods for * event handling, and rendering to the screen. It is never used directly by the user */ -class SDLContext { +class SDLContext : public Manager { public: //! data that the camera component cannot hold struct CameraValues { @@ -62,6 +64,7 @@ public: //! rendering data needed to render on screen struct RenderContext { const Sprite & sprite; + Texture & texture; const CameraValues & cam; const vec2 & pos; const double & angle; @@ -92,20 +95,27 @@ public: float scroll_delta = INFINITY; ivec2 rel_mouse_move = {-1, -1}; }; - /** - * \brief Gets the singleton instance of SDLContext. - * \return Reference to the SDLContext instance. - */ - static SDLContext & get_instance(); +public: SDLContext(const SDLContext &) = delete; SDLContext(SDLContext &&) = delete; SDLContext & operator=(const SDLContext &) = delete; SDLContext & operator=(SDLContext &&) = delete; -private: - //! will only use get_events - friend class InputSystem; +public: + /** + * \brief Constructs an SDLContext instance. + * Initializes SDL, creates a window and renderer. + */ + SDLContext(Mediator & mediator); + + /** + * \brief Destroys the SDLContext instance. + * Cleans up SDL resources, including the window and renderer. + */ + ~SDLContext(); + +public: /** * \brief Retrieves a list of all events from the SDL context. * @@ -139,9 +149,7 @@ private: */ MouseButton sdl_to_mousebutton(Uint8 sdl_button); -private: - //! Will only use delay - friend class LoopTimer; +public: /** * \brief Gets the current SDL ticks since the program started. * \return Current ticks in milliseconds as a constant uint64_t. @@ -157,23 +165,8 @@ private: */ void delay(int ms) const; -private: - /** - * \brief Constructs an SDLContext instance. - * Initializes SDL, creates a window and renderer. - */ - SDLContext(); - - /** - * \brief Destroys the SDLContext instance. - * Cleans up SDL resources, including the window and renderer. - */ - ~SDLContext(); - -private: - //! Will use the funtions: texture_from_path, get_width,get_height. - friend class Texture; +public: /** * \brief Loads a texture from a file path. * \param path Path to the image file. @@ -188,10 +181,7 @@ private: */ ivec2 get_size(const Texture & ctx); -private: - //! Will use draw,clear_screen, present_screen, camera. - friend class RenderSystem; - +public: /** * \brief Draws a sprite to the screen using the specified transform and camera. * \param RenderContext Reference to rendering data to draw @@ -210,7 +200,7 @@ private: */ CameraValues set_camera(const Camera & camera); -private: +public: //! the data needed to construct a sdl dst rectangle struct DestinationRectangleData { const Sprite & sprite; diff --git a/src/crepe/manager/EventManager.cpp b/src/crepe/manager/EventManager.cpp index 20f0dd3..17fe528 100644 --- a/src/crepe/manager/EventManager.cpp +++ b/src/crepe/manager/EventManager.cpp @@ -1,9 +1,11 @@ #include "EventManager.h" +#include "util/Log.h" using namespace crepe; using namespace std; EventManager & EventManager::get_instance() { + dbg_trace(); static EventManager instance; return instance; } diff --git a/src/crepe/manager/Mediator.h b/src/crepe/manager/Mediator.h index ba0b41f..6a9e113 100644 --- a/src/crepe/manager/Mediator.h +++ b/src/crepe/manager/Mediator.h @@ -3,7 +3,6 @@ #include "../util/OptionalRef.h" // TODO: remove these singletons: -#include "../facade/SDLContext.h" #include "EventManager.h" #include "SaveManager.h" #include "api/LoopTimer.h" @@ -13,6 +12,7 @@ namespace crepe { class ComponentManager; class SceneManager; class ResourceManager; +class SDLContext; /** * Struct to pass references to classes that would otherwise need to be singletons down to @@ -27,12 +27,12 @@ class ResourceManager; * \warning This class should never be directly accessible from the API */ struct Mediator { + OptionalRef sdl_context; OptionalRef component_manager; OptionalRef scene_manager; OptionalRef save_manager = SaveManager::get_instance(); OptionalRef event_manager = EventManager::get_instance(); OptionalRef resource_manager; - OptionalRef sdl_context = SDLContext::get_instance(); OptionalRef timer = LoopTimer::get_instance(); }; diff --git a/src/crepe/manager/ResourceManager.cpp b/src/crepe/manager/ResourceManager.cpp index 7c01808..a141a46 100644 --- a/src/crepe/manager/ResourceManager.cpp +++ b/src/crepe/manager/ResourceManager.cpp @@ -6,8 +6,8 @@ using namespace crepe; using namespace std; ResourceManager::ResourceManager(Mediator & mediator) : Manager(mediator) { - mediator.resource_manager = *this; dbg_trace(); + mediator.resource_manager = *this; } ResourceManager::~ResourceManager() { dbg_trace(); } diff --git a/src/crepe/manager/SceneManager.cpp b/src/crepe/manager/SceneManager.cpp index 50a9fbb..a788c51 100644 --- a/src/crepe/manager/SceneManager.cpp +++ b/src/crepe/manager/SceneManager.cpp @@ -4,10 +4,13 @@ #include "ComponentManager.h" #include "SceneManager.h" +#include "util/Log.h" + using namespace crepe; using namespace std; SceneManager::SceneManager(Mediator & mediator) : Manager(mediator) { + dbg_trace(); mediator.scene_manager = *this; } diff --git a/src/crepe/system/InputSystem.cpp b/src/crepe/system/InputSystem.cpp index aaa8bdf..b36ec09 100644 --- a/src/crepe/system/InputSystem.cpp +++ b/src/crepe/system/InputSystem.cpp @@ -1,15 +1,19 @@ #include "../api/Button.h" #include "../manager/ComponentManager.h" #include "../manager/EventManager.h" +#include "facade/SDLContext.h" +#include "util/Log.h" #include "InputSystem.h" using namespace crepe; void InputSystem::update() { + dbg_trace(); ComponentManager & mgr = this->mediator.component_manager; EventManager & event_mgr = this->mediator.event_manager; - std::vector event_list = SDLContext::get_instance().get_events(); + SDLContext & context = this->mediator.sdl_context; + std::vector event_list = context.get_events(); RefVector