aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.clang-format2
-rw-r--r--.editorconfig3
-rw-r--r--.gitmodules4
-rw-r--r--Doxyfile16
-rw-r--r--asset/texture/ERROR.pngbin0 -> 3581 bytes
-rwxr-xr-xasset/texture/circle.pngbin0 -> 509 bytes
-rw-r--r--asset/texture/img.pngbin92742 -> 11476 bytes
-rwxr-xr-xasset/texture/square.pngbin0 -> 162 bytes
-rw-r--r--asset/texture/test_ap43.pngbin0 -> 2394 bytes
-rw-r--r--contributing.md255
m---------lib/fontconfig0
-rw-r--r--makefile3
-rw-r--r--mwe/ecs-homemade/inc/ComponentManager.h6
-rw-r--r--mwe/ecs-homemade/inc/ComponentManager.hpp21
-rw-r--r--mwe/ecs-homemade/inc/GameObjectMax.hpp3
-rw-r--r--mwe/ecs-homemade/src/ComponentManager.cpp3
-rw-r--r--mwe/ecs-homemade/src/GameObjectMax.cpp3
-rw-r--r--mwe/ecs-homemade/src/main.cpp11
-rw-r--r--mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp3
-rw-r--r--mwe/ecs-memory-efficient/inc/GameObjectMax.hpp9
-rw-r--r--mwe/ecs-memory-efficient/src/ComponentManager.cpp9
-rw-r--r--mwe/ecs-memory-efficient/src/GameObjectMax.cpp3
-rw-r--r--mwe/ecs-memory-efficient/src/main.cpp8
-rw-r--r--mwe/events/include/customTypes.h11
-rw-r--r--mwe/events/include/event.h10
-rw-r--r--mwe/events/include/eventManager.h30
-rw-r--r--mwe/events/src/event.cpp35
-rw-r--r--mwe/events/src/eventManager.cpp41
-rw-r--r--mwe/events/src/iKeyListener.cpp8
-rw-r--r--mwe/events/src/iMouseListener.cpp17
-rw-r--r--mwe/events/src/inputSystem.cpp14
-rw-r--r--mwe/events/src/keyListenerTest.cpp4
-rw-r--r--mwe/events/src/loopManager.cpp21
-rw-r--r--mwe/events/src/main.cpp7
-rw-r--r--mwe/events/src/mouseListenerTest.cpp12
-rw-r--r--mwe/events/src/timer.cpp3
-rw-r--r--mwe/events/src/uiRenderer.cpp13
-rw-r--r--mwe/events/src/window.cpp9
-rw-r--r--mwe/events/versions/delayBased.cpp3
-rw-r--r--mwe/gameloop/include/gameObject.h4
-rw-r--r--mwe/gameloop/src/gameObject.cpp4
-rw-r--r--mwe/gameloop/src/loopManager.cpp11
-rw-r--r--mwe/gameloop/src/timer.cpp3
-rw-r--r--mwe/gameloop/src/window.cpp5
-rw-r--r--mwe/gameloop/versions/delayBased.cpp3
-rw-r--r--mwe/resource-manager/TextureMap.cpp10
-rw-r--r--mwe/resource-manager/main.cpp5
-rw-r--r--mwe/resource-manager/map_layer.cpp41
-rw-r--r--mwe/resource-manager/resource_converter.cpp3
-rw-r--r--mwe/resource-manager/spritesheet.cpp4
-rw-r--r--mwe/resource-manager/stb_image.h1501
-rw-r--r--mwe/resource-manager/tiledMap.cpp6
-rw-r--r--readme.md8
-rw-r--r--src/CMakeLists.txt5
-rw-r--r--src/crepe/CMakeLists.txt7
-rw-r--r--src/crepe/Collider.cpp2
-rw-r--r--src/crepe/Collider.h13
-rw-r--r--src/crepe/Component.h28
-rw-r--r--src/crepe/ComponentManager.cpp35
-rw-r--r--src/crepe/ComponentManager.h132
-rw-r--r--src/crepe/Exception.cpp8
-rw-r--r--src/crepe/Exception.h31
-rw-r--r--src/crepe/Exception.hpp12
-rw-r--r--src/crepe/Particle.cpp13
-rw-r--r--src/crepe/Particle.h35
-rw-r--r--src/crepe/Resource.cpp4
-rw-r--r--src/crepe/Resource.h24
-rw-r--r--src/crepe/ValueBroker.h7
-rw-r--r--src/crepe/api/AI.cpp89
-rw-r--r--src/crepe/api/AI.h128
-rw-r--r--src/crepe/api/Animator.cpp56
-rw-r--r--src/crepe/api/Animator.h111
-rw-r--r--src/crepe/api/Asset.cpp20
-rw-r--r--src/crepe/api/Asset.h34
-rw-r--r--src/crepe/api/AudioSource.cpp15
-rw-r--r--src/crepe/api/AudioSource.h57
-rw-r--r--src/crepe/api/BehaviorScript.cpp6
-rw-r--r--src/crepe/api/BehaviorScript.h51
-rw-r--r--src/crepe/api/BehaviorScript.hpp14
-rw-r--r--src/crepe/api/BoxCollider.cpp10
-rw-r--r--src/crepe/api/BoxCollider.h23
-rw-r--r--src/crepe/api/Button.cpp10
-rw-r--r--src/crepe/api/Button.h57
-rw-r--r--src/crepe/api/CMakeLists.txt34
-rw-r--r--src/crepe/api/Camera.cpp9
-rw-r--r--src/crepe/api/Camera.h58
-rw-r--r--src/crepe/api/CircleCollider.cpp8
-rw-r--r--src/crepe/api/CircleCollider.h17
-rw-r--r--src/crepe/api/Color.cpp37
-rw-r--r--src/crepe/api/Color.h49
-rw-r--r--src/crepe/api/Config.h64
-rw-r--r--src/crepe/api/Event.h162
-rw-r--r--src/crepe/api/EventHandler.cpp5
-rw-r--r--src/crepe/api/EventHandler.h96
-rw-r--r--src/crepe/api/EventHandler.hpp20
-rw-r--r--src/crepe/api/GameObject.cpp19
-rw-r--r--src/crepe/api/GameObject.h45
-rw-r--r--src/crepe/api/GameObject.hpp2
-rw-r--r--src/crepe/api/KeyCodes.h160
-rw-r--r--src/crepe/api/LoopManager.cpp84
-rw-r--r--src/crepe/api/LoopManager.h108
-rw-r--r--src/crepe/api/LoopManager.hpp16
-rw-r--r--src/crepe/api/LoopTimer.cpp86
-rw-r--r--src/crepe/api/LoopTimer.h147
-rw-r--r--src/crepe/api/Metadata.h9
-rw-r--r--src/crepe/api/ParticleEmitter.cpp6
-rw-r--r--src/crepe/api/ParticleEmitter.h71
-rw-r--r--src/crepe/api/ResourceManager.cpp41
-rw-r--r--src/crepe/api/ResourceManager.h69
-rw-r--r--src/crepe/api/Rigidbody.cpp6
-rw-r--r--src/crepe/api/Rigidbody.h158
-rw-r--r--src/crepe/api/Scene.cpp14
-rw-r--r--src/crepe/api/Scene.h79
-rw-r--r--src/crepe/api/Scene.hpp19
-rw-r--r--src/crepe/api/SceneManager.hpp21
-rw-r--r--src/crepe/api/Script.cpp37
-rw-r--r--src/crepe/api/Script.h205
-rw-r--r--src/crepe/api/Script.hpp67
-rw-r--r--src/crepe/api/Sprite.cpp18
-rw-r--r--src/crepe/api/Sprite.h130
-rw-r--r--src/crepe/api/Text.cpp12
-rw-r--r--src/crepe/api/Text.h66
-rw-r--r--src/crepe/api/Texture.cpp39
-rw-r--r--src/crepe/api/Texture.h77
-rw-r--r--src/crepe/api/Transform.cpp3
-rw-r--r--src/crepe/api/Transform.h25
-rw-r--r--src/crepe/api/UIObject.cpp8
-rw-r--r--src/crepe/api/UIObject.h25
-rw-r--r--src/crepe/api/Vector2.cpp43
-rw-r--r--src/crepe/api/Vector2.h79
-rw-r--r--src/crepe/api/Vector2.hpp166
-rw-r--r--src/crepe/facade/CMakeLists.txt6
-rw-r--r--src/crepe/facade/DB.cpp30
-rw-r--r--src/crepe/facade/DB.h17
-rw-r--r--src/crepe/facade/EventData.h54
-rw-r--r--src/crepe/facade/Font.cpp21
-rw-r--r--src/crepe/facade/Font.h42
-rw-r--r--src/crepe/facade/FontFacade.cpp43
-rw-r--r--src/crepe/facade/FontFacade.h34
-rw-r--r--src/crepe/facade/SDLContext.cpp457
-rw-r--r--src/crepe/facade/SDLContext.h360
-rw-r--r--src/crepe/facade/Sound.cpp48
-rw-r--r--src/crepe/facade/Sound.h71
-rw-r--r--src/crepe/facade/SoundContext.cpp25
-rw-r--r--src/crepe/facade/SoundContext.h58
-rw-r--r--src/crepe/facade/SoundHandle.h12
-rw-r--r--src/crepe/facade/Texture.cpp28
-rw-r--r--src/crepe/facade/Texture.h69
-rw-r--r--src/crepe/manager/CMakeLists.txt25
-rw-r--r--src/crepe/manager/ComponentManager.cpp74
-rw-r--r--src/crepe/manager/ComponentManager.h230
-rw-r--r--src/crepe/manager/ComponentManager.hpp (renamed from src/crepe/ComponentManager.hpp)110
-rw-r--r--src/crepe/manager/EventManager.cpp44
-rw-r--r--src/crepe/manager/EventManager.h148
-rw-r--r--src/crepe/manager/EventManager.hpp36
-rw-r--r--src/crepe/manager/LoopTimerManager.cpp91
-rw-r--r--src/crepe/manager/LoopTimerManager.h175
-rw-r--r--src/crepe/manager/Manager.cpp5
-rw-r--r--src/crepe/manager/Manager.h24
-rw-r--r--src/crepe/manager/Mediator.h37
-rw-r--r--src/crepe/manager/ResourceManager.cpp30
-rw-r--r--src/crepe/manager/ResourceManager.h78
-rw-r--r--src/crepe/manager/ResourceManager.hpp27
-rw-r--r--src/crepe/manager/SaveManager.cpp (renamed from src/crepe/api/SaveManager.cpp)91
-rw-r--r--src/crepe/manager/SaveManager.h (renamed from src/crepe/api/SaveManager.h)45
-rw-r--r--src/crepe/manager/SceneManager.cpp (renamed from src/crepe/api/SceneManager.cpp)21
-rw-r--r--src/crepe/manager/SceneManager.h (renamed from src/crepe/api/SceneManager.h)26
-rw-r--r--src/crepe/manager/SceneManager.hpp25
-rw-r--r--src/crepe/system/AISystem.cpp186
-rw-r--r--src/crepe/system/AISystem.h81
-rw-r--r--src/crepe/system/AnimatorSystem.cpp43
-rw-r--r--src/crepe/system/AnimatorSystem.h9
-rw-r--r--src/crepe/system/AudioSystem.cpp59
-rw-r--r--src/crepe/system/AudioSystem.h36
-rw-r--r--src/crepe/system/CMakeLists.txt4
-rw-r--r--src/crepe/system/CollisionSystem.cpp572
-rw-r--r--src/crepe/system/CollisionSystem.h298
-rw-r--r--src/crepe/system/InputSystem.cpp215
-rw-r--r--src/crepe/system/InputSystem.h99
-rw-r--r--src/crepe/system/ParticleSystem.cpp136
-rw-r--r--src/crepe/system/ParticleSystem.h61
-rw-r--r--src/crepe/system/PhysicsSystem.cpp140
-rw-r--r--src/crepe/system/PhysicsSystem.h8
-rw-r--r--src/crepe/system/RenderSystem.cpp155
-rw-r--r--src/crepe/system/RenderSystem.h64
-rw-r--r--src/crepe/system/ScriptSystem.cpp39
-rw-r--r--src/crepe/system/ScriptSystem.h13
-rw-r--r--src/crepe/system/System.cpp4
-rw-r--r--src/crepe/system/System.h11
-rw-r--r--src/crepe/types.h23
-rw-r--r--src/crepe/util/Log.cpp9
-rw-r--r--src/crepe/util/Log.h27
-rw-r--r--src/crepe/util/Log.hpp3
-rw-r--r--src/crepe/util/LogColor.cpp65
-rw-r--r--src/crepe/util/LogColor.h24
-rw-r--r--src/crepe/util/OptionalRef.h47
-rw-r--r--src/crepe/util/OptionalRef.hpp45
-rw-r--r--src/crepe/util/Proxy.h6
-rw-r--r--src/crepe/util/Proxy.hpp6
-rw-r--r--src/doc/feature/animator_creation.dox0
-rw-r--r--src/doc/feature/gameobject.dox18
-rw-r--r--src/doc/feature/proxy.dox43
-rw-r--r--src/doc/feature/savemgr.dox80
-rw-r--r--src/doc/feature/scene.dox72
-rw-r--r--src/doc/feature/script.dox62
-rw-r--r--src/doc/features.dox28
-rw-r--r--src/doc/index.dox17
-rw-r--r--src/doc/installing.dox9
-rw-r--r--src/doc/internal/component.dox41
-rw-r--r--src/doc/internal/resource.dox12
-rw-r--r--src/doc/internal/style.dox9
-rw-r--r--src/doc/internal/system.dox26
-rw-r--r--src/doc/internals.dox10
-rw-r--r--src/doc/layout.xml255
-rw-r--r--src/doc/style.css6
-rw-r--r--src/example/AITest.cpp90
-rw-r--r--src/example/CMakeLists.txt21
-rw-r--r--src/example/FontExample.cpp55
-rw-r--r--src/example/asset_manager.cpp37
-rw-r--r--src/example/audio_internal.cpp65
-rw-r--r--src/example/button.cpp41
-rw-r--r--src/example/components_internal.cpp55
-rw-r--r--src/example/db.cpp30
-rw-r--r--src/example/ecs.cpp60
-rw-r--r--src/example/game.cpp292
-rw-r--r--src/example/gameloop.cpp7
-rw-r--r--src/example/loadfont.cpp49
-rw-r--r--src/example/log.cpp28
-rw-r--r--src/example/particles.cpp44
-rw-r--r--src/example/physics.cpp24
-rw-r--r--src/example/proxy.cpp45
-rw-r--r--src/example/rendering.cpp57
-rw-r--r--src/example/rendering_particle.cpp73
-rw-r--r--src/example/savemgr.cpp44
-rw-r--r--src/example/scene_manager.cpp86
-rw-r--r--src/example/script.cpp49
-rw-r--r--src/makefile7
-rw-r--r--src/test/AssetTest.cpp20
-rw-r--r--src/test/AudioTest.cpp151
-rw-r--r--src/test/CMakeLists.txt18
-rw-r--r--src/test/CollisionTest.cpp391
-rw-r--r--src/test/DBTest.cpp37
-rw-r--r--src/test/ECSTest.cpp468
-rw-r--r--src/test/EventTest.cpp228
-rw-r--r--src/test/InputTest.cpp267
-rw-r--r--src/test/LoopManagerTest.cpp78
-rw-r--r--src/test/LoopTimerTest.cpp97
-rw-r--r--src/test/OptionalRefTest.cpp38
-rw-r--r--src/test/ParticleTest.cpp139
-rw-r--r--src/test/PhysicsTest.cpp78
-rw-r--r--src/test/Profiling.cpp249
-rw-r--r--src/test/RenderSystemTest.cpp186
-rw-r--r--src/test/ResourceManagerTest.cpp105
-rw-r--r--src/test/SaveManagerTest.cpp51
-rw-r--r--src/test/SceneManagerTest.cpp160
-rw-r--r--src/test/ScriptECSTest.cpp41
-rw-r--r--src/test/ScriptEventTest.cpp50
-rw-r--r--src/test/ScriptSaveManagerTest.cpp35
-rw-r--r--src/test/ScriptSceneTest.cpp30
-rw-r--r--src/test/ScriptTest.cpp105
-rw-r--r--src/test/ScriptTest.h34
-rw-r--r--src/test/ValueBrokerTest.cpp63
-rw-r--r--src/test/Vector2Test.cpp532
-rw-r--r--src/test/main.cpp11
264 files changed, 12417 insertions, 4361 deletions
diff --git a/.clang-format b/.clang-format
index 8ce4033..1ee37ec 100644
--- a/.clang-format
+++ b/.clang-format
@@ -4,7 +4,7 @@ AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
BasedOnStyle: LLVM
BreakBeforeBraces: Attach
-ColumnLimit: 80
+ColumnLimit: 95
EmptyLineBeforeAccessModifier: Always
IndentAccessModifiers: false
IndentCaseLabels: true
diff --git a/.editorconfig b/.editorconfig
index df2cf5e..65f5034 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -4,8 +4,11 @@ root = true
indent_style = tab
end_of_line = lf
insert_final_newline = true
+max_line_length = 95
[{*.{md,yml},.clang-*}]
indent_style = space
indent_size = 2
+[*.{md,dox}]
+max_line_length = 80
diff --git a/.gitmodules b/.gitmodules
index bd6e7f7..8155600 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -26,3 +26,7 @@
path = lib/whereami/lib
url = https://github.com/gpakosz/whereami
shallow = true
+[submodule "lib/fontconfig"]
+ path = lib/fontconfig
+ url = https://gitlab.freedesktop.org/fontconfig/fontconfig.git
+ shallow = true
diff --git a/Doxyfile b/Doxyfile
index 8ba90fc..07c86d1 100644
--- a/Doxyfile
+++ b/Doxyfile
@@ -14,12 +14,22 @@ RECURSIVE = YES
GENERATE_LATEX = NO
-USE_MDFILE_AS_MAINPAGE = ./readme.md
-HTML_INDEX_NUM_ENTRIES = 1 # collapse trees by default
+LAYOUT_FILE = src/doc/layout.xml
+TAB_SIZE = 2
+
+HTML_INDEX_NUM_ENTRIES = 999
+HTML_EXTRA_STYLESHEET = src/doc/style.css
+SHOW_HEADERFILE = NO
+
REPEAT_BRIEF = NO
-INTERNAL_DOCS = YES
EXTRACT_STATIC = YES
+HIDE_UNDOC_NAMESPACES = YES
+HIDE_UNDOC_CLASSES = YES
QUIET = YES
+WARNINGS = NO
+# set these to NO for user-only docs
+INTERNAL_DOCS = YES
+EXTRACT_PRIVATE = YES
diff --git a/asset/texture/ERROR.png b/asset/texture/ERROR.png
new file mode 100644
index 0000000..2af3548
--- /dev/null
+++ b/asset/texture/ERROR.png
Binary files differ
diff --git a/asset/texture/circle.png b/asset/texture/circle.png
new file mode 100755
index 0000000..0a92ac7
--- /dev/null
+++ b/asset/texture/circle.png
Binary files differ
diff --git a/asset/texture/img.png b/asset/texture/img.png
index 43b1eca..649a3f1 100644
--- a/asset/texture/img.png
+++ b/asset/texture/img.png
Binary files differ
diff --git a/asset/texture/square.png b/asset/texture/square.png
new file mode 100755
index 0000000..d07ec98
--- /dev/null
+++ b/asset/texture/square.png
Binary files differ
diff --git a/asset/texture/test_ap43.png b/asset/texture/test_ap43.png
new file mode 100644
index 0000000..e758ed7
--- /dev/null
+++ b/asset/texture/test_ap43.png
Binary files differ
diff --git a/contributing.md b/contributing.md
index 3090727..5555892 100644
--- a/contributing.md
+++ b/contributing.md
@@ -15,12 +15,19 @@ that you can click on to open them.
`name/feature` (i.e. `loek/dll-so-poc` or `jaro/class2`)
- The master branch is considered stable, and should always contain a
working/compiling version of the project
+- Pull requests for new code include either automated tests for the new code or
+ an explanation as to why the code can not (reliably) be tested
+- Non-bugfix pull requests must be approved by at least 2 reviewers before being
+ merged
+
+<!--
- TODO: tagging / versions
+-->
# Code style
- Formatting nitty-gritty is handled by clang-format/clang-tidy (run `make
- format` in the root folder of this repository to format all sources files)
+ format` or `make lint`)
- <details><summary>
ASCII only
</summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
@@ -491,6 +498,12 @@ that you can click on to open them.
</td></tr></table></details>
- <details><summary>
Ensure const-correctness
+
+ > [!IMPORTANT]
+ > C-style APIs that work on (possibly internal) references to structs can be
+ > called from const member functions in C++. If the compiler allows you to
+ > mark a function as `const` even though it has side effects, it should
+ > **not** be marked as `const`.
</summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
```cpp
@@ -622,15 +635,21 @@ that you can click on to open them.
</summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
```cpp
+ void Foo::bar() { }
+
void Foo::set_value(int value) {
this->value = value;
+ this->bar();
}
```
</td><td>
```cpp
+ void Foo::bar() { }
+
void Foo::set_value(int new_value) {
value = new_value;
+ bar();
}
```
</td></tr></table></details>
@@ -678,6 +697,162 @@ that you can click on to open them.
uint64_t foo();
```
</td></tr></table></details>
+- <details><summary>
+ Utilize standard exceptions where appropriate (those found in <code>&lt;stdexcept&gt;</code>)
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ ```cpp
+ #include <stdexcept>
+
+ // ...
+
+ if (foo == nullptr) {
+ throw std::runtime_error("What is wrong");
+ }
+ ```
+ </td><td>
+
+ ```cpp
+ if (foo == nullptr) {
+ std::cout << "What is wrong" << std::endl;
+ exit(1);
+ }
+ ```
+ </td></tr></table></details>
+- <details><summary>
+ Mention the name of the class when throwing an exception
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ ```cpp
+ Foo::bar() {
+ if (...)
+ throw std::runtime_error("Foo: big error!");
+ }
+ ```
+ </td><td>
+
+ ```cpp
+ Foo::bar() {
+ if (...)
+ throw std::runtime_error("big error!");
+ }
+ ```
+ </td></tr></table></details>
+- <details><summary>
+ Constructors of classes derived from <code>Component</code> should be
+ protected and <code>ComponentManager</code> should be declared as a friend
+ class.
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ ```cpp
+ class MyComponent : public Component {
+ protected:
+ MyComponent(...);
+ //! Only ComponentManager is allowed to create components
+ friend class ComponentManager;
+ };
+ ```
+ </td><td>
+
+ ```cpp
+ class MyComponent : public Component {
+ public:
+ MyComponent(...);
+ };
+ ```
+ </td></tr></table></details>
+- <details><summary>
+ C++ <code>std::format</code> should be used instead of C-style format specifiers
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ ```cpp
+ std::string message = std::format("Hello, {}", name);
+
+ dbg_logf("Here too: {}", 3);
+
+ throw std::runtime_error(std::format("Or here: {}", 5));
+ ```
+ </td><td>
+
+ ```cpp
+ char message[50];
+ sprintf(message, "Hello, %s", name);
+ ```
+ </td></tr></table></details>
+- <details><summary>
+ Argument names should be added in <code>.h</code> files (not only in
+ <code>.cpp</code> and <code>.hpp</code> files)
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ Foo.h:
+ ```cpp
+ void foo(int bar);
+ ```
+
+ Foo.cpp:
+ ```cpp
+ void foo(int bar) {
+ // ...
+ }
+ ```
+ </td><td>
+
+ Foo.h:
+ ```cpp
+ void foo(int);
+ ```
+
+ Foo.cpp:
+ ```cpp
+ void foo(int bar) {
+ // ...
+ }
+ ```
+ </td></tr></table></details>
+- Do not implement new classes as singletons
+- <details><summary>
+ Retrieving the first or last indices for iterators with a known or expected
+ size should be done using <code>.front()</code> or <code>.back()</code>
+ instead of by index
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ ```cpp
+ vector<int> foo = { 1, 2, 3 };
+ int bar = foo.first();
+ ```
+ </td><td>
+
+ ```cpp
+ vector<int> foo = { 1, 2, 3 };
+ int bar = foo[0];
+ ```
+ </td></tr></table></details>
+- <details><summary>
+ Always explicitly check against <code>NULL</code> (for C APIs) or
+ <code>nullptr</code> (for C++ APIs) when checking if a pointer is valid
+ </summary><table><tr><th>Good</th><th>Bad</th></tr><tr><td>
+
+ ```cpp
+ string foo = "Hello world";
+ if (foo.c_str() == nullptr)
+ // ...
+
+ void * bar = malloc();
+ if (bar == NULL)
+ // ...
+ ```
+ </td><td>
+
+ ```cpp
+ string foo = "Hello world";
+ if (!foo.c_str())
+ // ...
+
+ void * bar = malloc();
+ if (!bar)
+ // ...
+ ```
+ </td></tr></table></details>
## CMakeLists-specific
@@ -686,6 +861,32 @@ that you can click on to open them.
resolving merge conflicts when multiple sources were added by different
people to the same CMakeLists.txt easier.
+## GoogleTest-specific
+
+- Unit tests are not *required* to follow all code standards
+- <details><summary>
+ Private/protected members may be accessed using preprocessor tricks
+ </summary>
+
+ ```cpp
+ // include unrelated headers before
+
+ #define private public
+ #define protected public
+
+ // headers included after *will* be affected
+ ```
+ </details>
+- Each test source file defines tests within a single test suite (first
+ parameter of `TEST()` / `TEST_F()` macro)
+- Test source files match their suite name (or test fixture name in the case of
+ tests that use a fixture)
+- Tests that measure time or use delays must be [disabled][gtest-disable] (by
+ prepending `DISABLED_` to the suite or case name).
+
+ These tests will still be compiled, but will only run when the `test_main`
+ binary is run with the `--gtest_also_run_disabled_tests` flag.
+
# Structure
- Files are placed in the appropriate directory:
@@ -704,6 +905,8 @@ that you can click on to open them.
# Documentation
+[Doxygen commands](https://www.doxygen.nl/manual/commands.html)
+
- All documentation is written in U.S. English
- <details><summary>
Doxygen commands are used with a backslash instead of an at-sign.
@@ -789,6 +992,52 @@ that you can click on to open them.
Foo & operator=(Foo &&) = delete;
```
</td></tr></table></details>
+- Do not use markdown headings in Doxygen
+
+## Documenting features
+
+Engine features are small 'building blocks' that the user (game developer) may
+reference when building a game with the engine. Features do not necessarily map
+1-1 to engine components or systems. If a component or system has a single,
+distinct feature it should be named after that feature, not the component or
+system itself.
+
+The sources for these pages are located under `src/doc/feature/`, and have the
+following format:
+
+- A feature description which explains—
+ - the purpose and function of the feature (focus on what it enables or
+ achieves for the user)
+ - additional information about when to implement the feature, such as specific
+ use cases or scenarios
+- A list of 'see also' references to relevant classes and/or types
+- A **minimal** example to demonstrate how the feature is used. The example
+ should be written such that the following is clear to the reader:
+ - Which headers need to be included to utilize the feature
+ - *Why* the example works, not what is happening in the example
+ - Where is this code supposed to be called (e.g. inside scene/script
+ functions)
+ - Which restrictions should be kept in mind (e.g. copy/move semantics, max
+ component instances, speed considerations)
+
+Features should be documented as clear and concise as possible, so the following
+points should be kept in mind:
+
+- <details><summary>
+ If a page expands on an example from another page, directly reference the
+ other page using a cross-reference (`\ref`) in a `\note` block at the top of
+ the page.
+ </summary>
+
+ ```
+ \note This page builds on top of the example shown in \ref feature_script
+ ```
+ </details>
+- When explaining the usage of specific functions, qualify them such that
+ Doxygen is able to add a cross-reference or manually add a reference using the
+ `\ref` command.
+- Users will likely copy-paste examples as-is, so do this yourself to check if
+ the example code actually works!
# Libraries
@@ -796,4 +1045,8 @@ that you can click on to open them.
subdirectory
- When adding new submodules, please set the `shallow` option to `true` in the
[.gitmodules](./.gitmodules) file
+- When adding new libraries, please update the library version table in
+ [readme\.md](./readme.md)
+
+[gtest-disable]: https://google.github.io/googletest/advanced.html#temporarily-disabling-tests
diff --git a/lib/fontconfig b/lib/fontconfig
new file mode 160000
+Subproject 72b9a48f57de6204d99ce1c217b5609ee92ece9
diff --git a/makefile b/makefile
index dd7c587..c46e8a5 100644
--- a/makefile
+++ b/makefile
@@ -6,5 +6,6 @@ doxygen: Doxyfile FORCE
FMT += $(shell git ls-files '*.c' '*.cpp' '*.h' '*.hpp')
format: FORCE
clang-format -i $(FMT)
- $(MAKE) -C src $@
+lint: FORCE
+ $(MAKE) -C src $@
diff --git a/mwe/ecs-homemade/inc/ComponentManager.h b/mwe/ecs-homemade/inc/ComponentManager.h
index 0ba358e..99c108f 100644
--- a/mwe/ecs-homemade/inc/ComponentManager.h
+++ b/mwe/ecs-homemade/inc/ComponentManager.h
@@ -33,8 +33,7 @@ public:
//Get a vector<> of all components at specific type and id
template <typename T>
- std::vector<std::reference_wrapper<T>>
- GetComponentsByID(std::uint32_t id) const;
+ std::vector<std::reference_wrapper<T>> GetComponentsByID(std::uint32_t id) const;
//Get a vector<> of all components of a specific type
template <typename T>
std::vector<std::reference_wrapper<T>> GetComponentsByType() const;
@@ -50,8 +49,7 @@ private:
* The first std::vector<> stores another vector<>. This first vector<> is to bind the entity's id to a component.
* The second std::vector<> stores unique_ptrs. Each component can be gathered via an unique_ptr. This second vector<> allows multiple components of the same std::type_index for one entity (id).
*/
- std::unordered_map<std::type_index,
- std::vector<std::vector<std::unique_ptr<Component>>>>
+ std::unordered_map<std::type_index, std::vector<std::vector<std::unique_ptr<Component>>>>
mComponents;
};
diff --git a/mwe/ecs-homemade/inc/ComponentManager.hpp b/mwe/ecs-homemade/inc/ComponentManager.hpp
index 92db1d4..af9c3a1 100644
--- a/mwe/ecs-homemade/inc/ComponentManager.hpp
+++ b/mwe/ecs-homemade/inc/ComponentManager.hpp
@@ -7,8 +7,7 @@ T & ComponentManager::AddComponent(std::uint32_t id, Args &&... args) {
//Check if this component type is already in the unordered_map<>
if (mComponents.find(type) == mComponents.end()) {
//If not, create a new (empty) vector<> of vector<unique_ptr<Component>>
- mComponents[type]
- = std::vector<std::vector<std::unique_ptr<Component>>>();
+ mComponents[type] = std::vector<std::vector<std::unique_ptr<Component>>>();
}
//Resize the vector<> if the id is greater than the current size
@@ -18,8 +17,7 @@ T & ComponentManager::AddComponent(std::uint32_t id, Args &&... args) {
}
//Create a new component of type T using perfect forwarding and store its unique_ptr in the vector<>
- mComponents[type][id].push_back(
- std::make_unique<T>(std::forward<Args>(args)...));
+ mComponents[type][id].push_back(std::make_unique<T>(std::forward<Args>(args)...));
return static_cast<T &>(*mComponents[type][id].back().get());
}
@@ -68,15 +66,13 @@ ComponentManager::GetComponentsByID(std::uint32_t id) const {
if (mComponents.find(type) != mComponents.end()) {
//Get the correct vector<>
- const std::vector<std::vector<std::unique_ptr<Component>>> &
- componentArray
+ const std::vector<std::vector<std::unique_ptr<Component>>> & componentArray
= mComponents.at(type);
//Make sure that the id (that we are looking for) is within the boundaries of the vector<>
if (id < componentArray.size()) {
//Loop trough the whole vector<>
- for (const std::unique_ptr<Component> & componentPtr :
- componentArray[id]) {
+ for (const std::unique_ptr<Component> & componentPtr : componentArray[id]) {
//Cast the unique_ptr to a raw pointer
T * castedComponent = static_cast<T *>(componentPtr.get());
@@ -94,8 +90,7 @@ ComponentManager::GetComponentsByID(std::uint32_t id) const {
}
template <typename T>
-std::vector<std::reference_wrapper<T>>
-ComponentManager::GetComponentsByType() const {
+std::vector<std::reference_wrapper<T>> ComponentManager::GetComponentsByType() const {
//Determine the type of T (this is used as the key of the unordered_map<>)
std::type_index type = typeid(T);
@@ -107,13 +102,11 @@ ComponentManager::GetComponentsByType() const {
if (mComponents.find(type) != mComponents.end()) {
//Get the correct vector<>
- const std::vector<std::vector<std::unique_ptr<Component>>> &
- componentArray
+ const std::vector<std::vector<std::unique_ptr<Component>>> & componentArray
= mComponents.at(type);
//Loop through the whole vector<>
- for (const std::vector<std::unique_ptr<Component>> & component :
- componentArray) {
+ for (const std::vector<std::unique_ptr<Component>> & component : componentArray) {
//Loop trough the whole vector<>
for (const std::unique_ptr<Component> & componentPtr : component) {
//Cast the unique_ptr to a raw pointer
diff --git a/mwe/ecs-homemade/inc/GameObjectMax.hpp b/mwe/ecs-homemade/inc/GameObjectMax.hpp
index 2f433bb..92375bb 100644
--- a/mwe/ecs-homemade/inc/GameObjectMax.hpp
+++ b/mwe/ecs-homemade/inc/GameObjectMax.hpp
@@ -2,6 +2,5 @@
template <typename T, typename... Args>
T & GameObject::AddComponent(Args &&... args) {
- return ComponentManager::GetInstance().AddComponent<T>(
- mId, std::forward<Args>(args)...);
+ return ComponentManager::GetInstance().AddComponent<T>(mId, std::forward<Args>(args)...);
}
diff --git a/mwe/ecs-homemade/src/ComponentManager.cpp b/mwe/ecs-homemade/src/ComponentManager.cpp
index 536c152..33ba12e 100644
--- a/mwe/ecs-homemade/src/ComponentManager.cpp
+++ b/mwe/ecs-homemade/src/ComponentManager.cpp
@@ -12,8 +12,7 @@ void ComponentManager::DeleteAllComponentsOfId(std::uint32_t id) {
if (id
< componentArray
.size()) { //Make sure that the id (that we are looking for) is within the boundaries of the vector<>
- componentArray[id]
- .clear(); //Clear the components at this specific id
+ componentArray[id].clear(); //Clear the components at this specific id
}
}
}
diff --git a/mwe/ecs-homemade/src/GameObjectMax.cpp b/mwe/ecs-homemade/src/GameObjectMax.cpp
index 753c8e2..0516f68 100644
--- a/mwe/ecs-homemade/src/GameObjectMax.cpp
+++ b/mwe/ecs-homemade/src/GameObjectMax.cpp
@@ -2,8 +2,7 @@
#include "ComponentManager.h"
-GameObject::GameObject(std::uint32_t id, std::string name, std::string tag,
- int layer)
+GameObject::GameObject(std::uint32_t id, std::string name, std::string tag, int layer)
: mId(id),
mName(name),
mTag(tag),
diff --git a/mwe/ecs-homemade/src/main.cpp b/mwe/ecs-homemade/src/main.cpp
index 70c5d2c..85ab1f1 100644
--- a/mwe/ecs-homemade/src/main.cpp
+++ b/mwe/ecs-homemade/src/main.cpp
@@ -53,8 +53,7 @@ int main() {
}
std::vector<std::reference_wrapper<BehaviourScript>> scripts
- = ComponentManager::GetInstance()
- .GetComponentsByType<BehaviourScript>();
+ = ComponentManager::GetInstance().GetComponentsByType<BehaviourScript>();
for (BehaviourScript & script : scripts) {
//script.onStart();
//script.onUpdate();
@@ -66,10 +65,10 @@ int main() {
delete gameObject[i];
}
- auto Addtime = std::chrono::duration_cast<std::chrono::microseconds>(
- stopAdding - startAdding);
- auto LoopTime = std::chrono::duration_cast<std::chrono::microseconds>(
- stopLooping - stopAdding);
+ auto Addtime
+ = std::chrono::duration_cast<std::chrono::microseconds>(stopAdding - startAdding);
+ auto LoopTime
+ = std::chrono::duration_cast<std::chrono::microseconds>(stopLooping - stopAdding);
std::cout << "AddTime: " << Addtime.count() << " us" << std::endl;
std::cout << "LoopTime: " << LoopTime.count() << " us" << std::endl;
}
diff --git a/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp b/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp
index ff8fde4..fa95952 100644
--- a/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp
+++ b/mwe/ecs-memory-efficient/inc/ContiguousContainer.hpp
@@ -54,8 +54,7 @@ size_t ContiguousContainer<T>::getSize() const {
// Function that returns a vector of references to all stored objects
template <typename T>
-std::vector<std::reference_wrapper<T>>
-ContiguousContainer<T>::getAllReferences() {
+std::vector<std::reference_wrapper<T>> ContiguousContainer<T>::getAllReferences() {
std::vector<std::reference_wrapper<T>> references;
references.reserve(mSize); // Reserve space to avoid reallocation
for (size_t i = 0; i < mSize; ++i) {
diff --git a/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp b/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp
index be3ffa2..909b4be 100644
--- a/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp
+++ b/mwe/ecs-memory-efficient/inc/GameObjectMax.hpp
@@ -2,18 +2,15 @@
template <typename... Args>
void GameObject::addSpriteComponent(Args &&... args) {
- ComponentManager::GetInstance().addSpriteComponent(
- std::forward<Args>(args)...);
+ ComponentManager::GetInstance().addSpriteComponent(std::forward<Args>(args)...);
}
template <typename... Args>
void GameObject::addRigidbodyComponent(Args &&... args) {
- ComponentManager::GetInstance().addRigidbodyComponent(
- std::forward<Args>(args)...);
+ ComponentManager::GetInstance().addRigidbodyComponent(std::forward<Args>(args)...);
}
template <typename... Args>
void GameObject::addColiderComponent(Args &&... args) {
- ComponentManager::GetInstance().addColiderComponent(
- std::forward<Args>(args)...);
+ ComponentManager::GetInstance().addColiderComponent(std::forward<Args>(args)...);
}
diff --git a/mwe/ecs-memory-efficient/src/ComponentManager.cpp b/mwe/ecs-memory-efficient/src/ComponentManager.cpp
index 8c1fd23..e7a8866 100644
--- a/mwe/ecs-memory-efficient/src/ComponentManager.cpp
+++ b/mwe/ecs-memory-efficient/src/ComponentManager.cpp
@@ -6,17 +6,14 @@ ComponentManager & ComponentManager::GetInstance() { return mInstance; }
ComponentManager::ComponentManager() {}
-std::vector<std::reference_wrapper<Sprite>>
-ComponentManager::getAllSpriteReferences() {
+std::vector<std::reference_wrapper<Sprite>> ComponentManager::getAllSpriteReferences() {
return mSpriteContainer.getAllReferences();
}
-std::vector<std::reference_wrapper<Rigidbody>>
-ComponentManager::getAllRigidbodyReferences() {
+std::vector<std::reference_wrapper<Rigidbody>> ComponentManager::getAllRigidbodyReferences() {
return mRigidbodyContainer.getAllReferences();
}
-std::vector<std::reference_wrapper<Colider>>
-ComponentManager::getAllColiderReferences() {
+std::vector<std::reference_wrapper<Colider>> ComponentManager::getAllColiderReferences() {
return mColiderContainer.getAllReferences();
}
diff --git a/mwe/ecs-memory-efficient/src/GameObjectMax.cpp b/mwe/ecs-memory-efficient/src/GameObjectMax.cpp
index 753c8e2..0516f68 100644
--- a/mwe/ecs-memory-efficient/src/GameObjectMax.cpp
+++ b/mwe/ecs-memory-efficient/src/GameObjectMax.cpp
@@ -2,8 +2,7 @@
#include "ComponentManager.h"
-GameObject::GameObject(std::uint32_t id, std::string name, std::string tag,
- int layer)
+GameObject::GameObject(std::uint32_t id, std::string name, std::string tag, int layer)
: mId(id),
mName(name),
mTag(tag),
diff --git a/mwe/ecs-memory-efficient/src/main.cpp b/mwe/ecs-memory-efficient/src/main.cpp
index 9c6f2aa..b564b8c 100644
--- a/mwe/ecs-memory-efficient/src/main.cpp
+++ b/mwe/ecs-memory-efficient/src/main.cpp
@@ -50,10 +50,10 @@ int main() {
delete gameObject[i];
}
- auto Addtime = std::chrono::duration_cast<std::chrono::microseconds>(
- stopAdding - startAdding);
- auto LoopTime = std::chrono::duration_cast<std::chrono::microseconds>(
- stopLooping - stopAdding);
+ auto Addtime
+ = std::chrono::duration_cast<std::chrono::microseconds>(stopAdding - startAdding);
+ auto LoopTime
+ = std::chrono::duration_cast<std::chrono::microseconds>(stopLooping - stopAdding);
std::cout << "AddTime: " << Addtime.count() << " us" << std::endl;
std::cout << "LoopTime: " << LoopTime.count() << " us" << std::endl;
}
diff --git a/mwe/events/include/customTypes.h b/mwe/events/include/customTypes.h
index 415b989..5a7851b 100644
--- a/mwe/events/include/customTypes.h
+++ b/mwe/events/include/customTypes.h
@@ -5,14 +5,10 @@ struct Vector2 {
float y; // Y component of the vector
// Vector subtraction
- Vector2 operator-(const Vector2 & other) const {
- return {x - other.x, y - other.y};
- }
+ Vector2 operator-(const Vector2 & other) const { return {x - other.x, y - other.y}; }
// Vector addition
- Vector2 operator+(const Vector2 & other) const {
- return {x + other.x, y + other.y};
- }
+ Vector2 operator+(const Vector2 & other) const { return {x + other.x, y + other.y}; }
// Scalar multiplication
Vector2 operator*(float scalar) const { return {x * scalar, y * scalar}; }
@@ -31,8 +27,7 @@ struct Collision {
Vector2 contactNormal; // Normal vector at the contact point
// Constructor to initialize a Collision
- Collision(int idA, int idB, const Vector2 & point, const Vector2 & normal,
- float depth)
+ Collision(int idA, int idB, const Vector2 & point, const Vector2 & normal, float depth)
: objectIdA(idA),
objectIdB(idB),
contactPoint(point),
diff --git a/mwe/events/include/event.h b/mwe/events/include/event.h
index 16c75bf..ee1bf52 100644
--- a/mwe/events/include/event.h
+++ b/mwe/events/include/event.h
@@ -20,9 +20,7 @@ public: \
static std::uint32_t typeID = UUIDGenerator::getUniqueID(); \
return typeID; \
} \
- virtual std::uint32_t getEventType() const override { \
- return getStaticEventType(); \
- }
+ virtual std::uint32_t getEventType() const override { return getStaticEventType(); }
class Event {
public:
Event(std::string eventType);
@@ -32,16 +30,14 @@ public:
void addArgument(const std::string & key,
const std::variant<int, std::string, float> & value);
- std::variant<int, std::string, float>
- getArgument(const std::string & key) const;
+ std::variant<int, std::string, float> getArgument(const std::string & key) const;
std::string getType() const;
bool getHandled() const;
void markHandled();
private:
- std::unordered_map<std::string, std::variant<int, std::string, float>>
- eventData;
+ std::unordered_map<std::string, std::variant<int, std::string, float>> eventData;
bool isHandled = false;
};
diff --git a/mwe/events/include/eventManager.h b/mwe/events/include/eventManager.h
index 508a5e2..30e927f 100644
--- a/mwe/events/include/eventManager.h
+++ b/mwe/events/include/eventManager.h
@@ -18,11 +18,9 @@ public:
}
void shutdown();
- void subscribe(int eventType,
- std::unique_ptr<IEventHandlerWrapper> && handler,
+ void subscribe(int eventType, std::unique_ptr<IEventHandlerWrapper> && handler,
int eventId);
- void unsubscribe(int eventType, const std::string & handlerName,
- int eventId);
+ void unsubscribe(int eventType, const std::string & handlerName, int eventId);
void triggerEvent(const Event & event_, int eventId);
void queueEvent(std::unique_ptr<Event> && event_, int eventId);
void dispatchEvents();
@@ -30,11 +28,9 @@ public:
private:
EventManager() = default;
std::vector<std::pair<std::unique_ptr<Event>, int>> eventsQueue;
- std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>
- subscribers;
+ std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> subscribers;
std::unordered_map<
- int, std::unordered_map<
- int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>
+ int, std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>
subscribersByEventId;
};
@@ -42,18 +38,16 @@ template <typename EventType>
inline void subscribe(const EventHandler<EventType> & callback, int eventId = 0,
const bool unsubscribeOnSuccess = false) {
std::unique_ptr<IEventHandlerWrapper> handler
- = std::make_unique<EventHandlerWrapper<EventType>>(
- callback, unsubscribeOnSuccess);
- EventManager::getInstance().subscribe(EventType::getStaticEventType(),
- std::move(handler), eventId);
+ = std::make_unique<EventHandlerWrapper<EventType>>(callback, unsubscribeOnSuccess);
+ EventManager::getInstance().subscribe(EventType::getStaticEventType(), std::move(handler),
+ eventId);
}
template <typename EventType>
-inline void unsubscribe(const EventHandler<EventType> & callback,
- int eventId = 0) {
+inline void unsubscribe(const EventHandler<EventType> & callback, int eventId = 0) {
const std::string handlerName = callback.target_type().name();
- EventManager::getInstance().unsubscribe(EventType::getStaticEventType(),
- handlerName, eventId);
+ EventManager::getInstance().unsubscribe(EventType::getStaticEventType(), handlerName,
+ eventId);
}
inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) {
@@ -61,6 +55,6 @@ inline void triggerEvent(const Event & triggeredEvent, int eventId = 0) {
}
inline void queueEvent(std::unique_ptr<Event> && queuedEvent, int eventId = 0) {
- EventManager::getInstance().queueEvent(
- std::forward<std::unique_ptr<Event>>(queuedEvent), eventId);
+ EventManager::getInstance().queueEvent(std::forward<std::unique_ptr<Event>>(queuedEvent),
+ eventId);
}
diff --git a/mwe/events/src/event.cpp b/mwe/events/src/event.cpp
index 8ffa0b1..0040c73 100644
--- a/mwe/events/src/event.cpp
+++ b/mwe/events/src/event.cpp
@@ -8,14 +8,11 @@ void Event::addArgument(const std::string & key,
eventData[key] = value;
}
-std::variant<int, std::string, float>
-Event::getArgument(const std::string & key) const {
+std::variant<int, std::string, float> Event::getArgument(const std::string & key) const {
return eventData.at(key);
}
-std::string Event::getType() const {
- return std::get<std::string>(eventData.at("eventType"));
-}
+std::string Event::getType() const { return std::get<std::string>(eventData.at("eventType")); }
std::string Event::toString() const { return std::to_string(getEventType()); }
bool Event::getHandled() const { return isHandled; }
@@ -32,9 +29,7 @@ Keycode KeyPressedEvent::getKeyCode() const { return key; }
int KeyPressedEvent::getRepeatCount() const { return repeatCount; }
// KeyReleasedEvent class methods
-KeyReleasedEvent::KeyReleasedEvent(int keycode)
- : Event("KeyReleasedEvent"),
- key(keycode) {}
+KeyReleasedEvent::KeyReleasedEvent(int keycode) : Event("KeyReleasedEvent"), key(keycode) {}
Keycode KeyReleasedEvent::getKeyCode() const { return key; }
@@ -44,22 +39,16 @@ MousePressedEvent::MousePressedEvent(int mouseX, int mouseY)
mouseX(mouseX),
mouseY(mouseY) {}
-std::pair<int, int> MousePressedEvent::getMousePosition() const {
- return {mouseX, mouseY};
-}
+std::pair<int, int> MousePressedEvent::getMousePosition() const { return {mouseX, mouseY}; }
//Collision event
CollisionEvent::CollisionEvent(Collision collision)
: collisionData(collision),
Event("CollisionEvent") {}
-Collision CollisionEvent::getCollisionData() const {
- return this->collisionData;
-}
+Collision CollisionEvent::getCollisionData() const { return this->collisionData; }
-TextSubmitEvent::TextSubmitEvent(std::string text)
- : text(text),
- Event("TextSubmitEvent") {}
+TextSubmitEvent::TextSubmitEvent(std::string text) : text(text), Event("TextSubmitEvent") {}
std::string TextSubmitEvent::getText() const { return this->text; }
@@ -68,9 +57,7 @@ MouseReleasedEvent::MouseReleasedEvent(int x, int y, MouseButton button)
mouseY(y),
button(button),
Event("MouseReleased") {}
-std::pair<int, int> MouseReleasedEvent::getMousePosition() const {
- return {mouseX, mouseY};
-}
+std::pair<int, int> MouseReleasedEvent::getMousePosition() const { return {mouseX, mouseY}; }
MouseClickEvent::MouseClickEvent(int x, int y, MouseButton button)
: mouseX(x),
mouseY(y),
@@ -80,9 +67,5 @@ MouseMovedEvent::MouseMovedEvent(int x, int y)
: mouseX(x),
mouseY(y),
Event("MouseMovedEvent") {}
-std::pair<int, int> MouseClickEvent::getMousePosition() const {
- return {mouseX, mouseY};
-}
-std::pair<int, int> MouseMovedEvent::getMousePosition() const {
- return {mouseX, mouseY};
-}
+std::pair<int, int> MouseClickEvent::getMousePosition() const { return {mouseX, mouseY}; }
+std::pair<int, int> MouseMovedEvent::getMousePosition() const { return {mouseX, mouseY}; }
diff --git a/mwe/events/src/eventManager.cpp b/mwe/events/src/eventManager.cpp
index 34a093d..9e7d880 100644
--- a/mwe/events/src/eventManager.cpp
+++ b/mwe/events/src/eventManager.cpp
@@ -2,33 +2,27 @@
void EventManager::shutdown() { subscribers.clear(); }
-void EventManager::subscribe(int eventType,
- std::unique_ptr<IEventHandlerWrapper> && handler,
+void EventManager::subscribe(int eventType, std::unique_ptr<IEventHandlerWrapper> && handler,
int eventId) {
if (eventId) {
std::unordered_map<
- int, std::unordered_map<
- int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>::
+ int, std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>::
iterator subscribers
= subscribersByEventId.find(eventType);
if (subscribers != subscribersByEventId.end()) {
- std::unordered_map<
- int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> &
+ std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> &
handlersMap
= subscribers->second;
std::unordered_map<
- int,
- std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator
- handlers
+ int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator handlers
= handlersMap.find(eventId);
if (handlers != handlersMap.end()) {
handlers->second.emplace_back(std::move(handler));
return;
}
}
- subscribersByEventId[eventType][eventId].emplace_back(
- std::move(handler));
+ subscribersByEventId[eventType][eventId].emplace_back(std::move(handler));
} else {
auto & handlers = subscribers[eventType];
@@ -36,29 +30,23 @@ void EventManager::subscribe(int eventType,
}
}
-void EventManager::unsubscribe(int eventType, const std::string & handlerName,
- int eventId) {
+void EventManager::unsubscribe(int eventType, const std::string & handlerName, int eventId) {
if (eventId) {
std::unordered_map<
- int, std::unordered_map<
- int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>::
+ int, std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>>::
iterator subscriberList
= subscribersByEventId.find(eventType);
if (subscriberList != subscribersByEventId.end()) {
- std::unordered_map<
- int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> &
+ std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>> &
handlersMap
= subscriberList->second;
std::unordered_map<
- int,
- std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator
- handlers
+ int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator handlers
= handlersMap.find(eventId);
if (handlers != handlersMap.end()) {
std::vector<std::unique_ptr<IEventHandlerWrapper>> & callbacks
= handlers->second;
- for (std::vector<
- std::unique_ptr<IEventHandlerWrapper>>::iterator it
+ for (std::vector<std::unique_ptr<IEventHandlerWrapper>>::iterator it
= callbacks.begin();
it != callbacks.end(); ++it) {
if (it->get()->getType() == handlerName) {
@@ -69,13 +57,11 @@ void EventManager::unsubscribe(int eventType, const std::string & handlerName,
}
}
} else {
- std::unordered_map<
- int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator
+ std::unordered_map<int, std::vector<std::unique_ptr<IEventHandlerWrapper>>>::iterator
handlersIt
= subscribers.find(eventType);
if (handlersIt != subscribers.end()) {
- std::vector<std::unique_ptr<IEventHandlerWrapper>> & handlers
- = handlersIt->second;
+ std::vector<std::unique_ptr<IEventHandlerWrapper>> & handlers = handlersIt->second;
for (std::vector<std::unique_ptr<IEventHandlerWrapper>>::iterator it
= handlers.begin();
it != handlers.end(); ++it) {
@@ -90,8 +76,7 @@ void EventManager::unsubscribe(int eventType, const std::string & handlerName,
void EventManager::triggerEvent(const Event & event_, int eventId) {
if (eventId > 0) {
- auto handlersIt
- = subscribersByEventId[event_.getEventType()].find(eventId);
+ auto handlersIt = subscribersByEventId[event_.getEventType()].find(eventId);
if (handlersIt != subscribersByEventId[event_.getEventType()].end()) {
std::vector<std::unique_ptr<IEventHandlerWrapper>> & callbacks
= handlersIt->second;
diff --git a/mwe/events/src/iKeyListener.cpp b/mwe/events/src/iKeyListener.cpp
index 0235fab..d5d1d90 100644
--- a/mwe/events/src/iKeyListener.cpp
+++ b/mwe/events/src/iKeyListener.cpp
@@ -3,11 +3,9 @@
IKeyListener::~IKeyListener() { unsubscribeEvents(); }
void IKeyListener::subscribeEvents(int listenerId) {
- keyPressedHandler
- = [this](const KeyPressedEvent & event) { this->onKeyPressed(event); };
- keyReleasedHandler = [this](const KeyReleasedEvent & event) {
- this->onKeyReleased(event);
- };
+ keyPressedHandler = [this](const KeyPressedEvent & event) { this->onKeyPressed(event); };
+ keyReleasedHandler
+ = [this](const KeyReleasedEvent & event) { this->onKeyReleased(event); };
subscribe<KeyPressedEvent>(keyPressedHandler, listenerId);
subscribe<KeyReleasedEvent>(keyReleasedHandler, listenerId);
diff --git a/mwe/events/src/iMouseListener.cpp b/mwe/events/src/iMouseListener.cpp
index 69d8c9f..53e6f80 100644
--- a/mwe/events/src/iMouseListener.cpp
+++ b/mwe/events/src/iMouseListener.cpp
@@ -2,17 +2,12 @@
IMouseListener::~IMouseListener() { unsubscribeEvents(); }
void IMouseListener::subscribeEvents(int listenerId) {
- mouseClickHandler = [this](const MouseClickEvent & event) {
- this->onMouseClicked(event);
- };
- mousePressHandler = [this](const MousePressedEvent & event) {
- this->onMousePressed(event);
- };
- mouseReleaseHandler = [this](const MouseReleasedEvent & event) {
- this->onMouseReleased(event);
- };
- mouseMoveHandler
- = [this](const MouseMovedEvent & event) { this->onMouseMoved(event); };
+ mouseClickHandler = [this](const MouseClickEvent & event) { this->onMouseClicked(event); };
+ mousePressHandler
+ = [this](const MousePressedEvent & event) { this->onMousePressed(event); };
+ mouseReleaseHandler
+ = [this](const MouseReleasedEvent & event) { this->onMouseReleased(event); };
+ mouseMoveHandler = [this](const MouseMovedEvent & event) { this->onMouseMoved(event); };
subscribe<MouseClickEvent>(mouseClickHandler, listenerId);
subscribe<MousePressedEvent>(mousePressHandler, listenerId);
diff --git a/mwe/events/src/inputSystem.cpp b/mwe/events/src/inputSystem.cpp
index b87b12e..d740c9e 100644
--- a/mwe/events/src/inputSystem.cpp
+++ b/mwe/events/src/inputSystem.cpp
@@ -3,9 +3,7 @@
InputSystem::InputSystem() {}
void InputSystem::registerButton(Button * button) { buttons.push_back(button); }
-void InputSystem::registerTextInput(TextInput * input) {
- textInputs.push_back(input);
-}
+void InputSystem::registerTextInput(TextInput * input) { textInputs.push_back(input); }
void InputSystem::registerText(Text * label) { texts.push_back(label); }
void InputSystem::processInput() {
@@ -16,8 +14,7 @@ void InputSystem::processInput() {
triggerEvent(ShutDownEvent());
break;
case SDL_KEYDOWN:
- triggerEvent(
- KeyPressedEvent(getCustomKey(event.key.keysym.sym)));
+ triggerEvent(KeyPressedEvent(getCustomKey(event.key.keysym.sym)));
processKeyPress(event.key.keysym.sym);
break;
case SDL_TEXTINPUT:
@@ -37,15 +34,14 @@ void InputSystem::processInput() {
void InputSystem::processMouseClick(int mouseX, int mouseY) {
for (auto * button : buttons) {
- if (mouseX >= button->x && mouseX <= (button->x + button->width)
- && mouseY >= button->y && mouseY <= (button->y + button->height)) {
+ if (mouseX >= button->x && mouseX <= (button->x + button->width) && mouseY >= button->y
+ && mouseY <= (button->y + button->height)) {
button->onClick();
}
}
for (auto * textInput : textInputs) {
if (mouseX >= textInput->x && mouseX <= textInput->x + textInput->width
- && mouseY >= textInput->y
- && mouseY <= textInput->y + textInput->height) {
+ && mouseY >= textInput->y && mouseY <= textInput->y + textInput->height) {
textInput->isActive = true;
} else {
textInput->isActive = false;
diff --git a/mwe/events/src/keyListenerTest.cpp b/mwe/events/src/keyListenerTest.cpp
index 8446dfa..f45dffd 100644
--- a/mwe/events/src/keyListenerTest.cpp
+++ b/mwe/events/src/keyListenerTest.cpp
@@ -1,8 +1,6 @@
#include "keyListenerTest.h"
-KeyListenerTest::KeyListenerTest(int listenerId) {
- subscribeEvents(listenerId);
-}
+KeyListenerTest::KeyListenerTest(int listenerId) { subscribeEvents(listenerId); }
KeyListenerTest::~KeyListenerTest() { unsubscribeEvents(); }
diff --git a/mwe/events/src/loopManager.cpp b/mwe/events/src/loopManager.cpp
index 0b7d888..c58a5e7 100644
--- a/mwe/events/src/loopManager.cpp
+++ b/mwe/events/src/loopManager.cpp
@@ -1,8 +1,7 @@
#include "loopManager.h"
LoopManager::LoopManager() : inputSystem(std::make_unique<InputSystem>()) {
- shutdownHandler
- = [this](const ShutDownEvent & event) { this->onShutdown(event); };
+ shutdownHandler = [this](const ShutDownEvent & event) { this->onShutdown(event); };
subscribe(shutdownHandler);
}
void LoopManager::processInput() {
@@ -63,17 +62,15 @@ void LoopManager::setup() {
subscribe<KeyPressedEvent>(callback, false);
EventHandler<MousePressedEvent> mouseCallback = onMouse;
subscribe<MousePressedEvent>(mouseCallback, false);
- EventHandler<KeyPressedEvent> closeWindowCallback
- = [this](const KeyPressedEvent & e) {
- if (e.getKeyCode() == Escape) {
- this->setRunning(false);
- }
- };
+ EventHandler<KeyPressedEvent> closeWindowCallback = [this](const KeyPressedEvent & e) {
+ if (e.getKeyCode() == Escape) {
+ this->setRunning(false);
+ }
+ };
subscribe<KeyPressedEvent>(closeWindowCallback, false);
Button * testButton = new Button(200, 200);
testButton->color = {100, 0, 100};
- testButton->onClick
- = []() { std::cout << "Button was clicked" << std::endl; };
+ testButton->onClick = []() { std::cout << "Button was clicked" << std::endl; };
testButton->x = 200;
testButton->y = 200;
inputSystem->registerButton(testButton);
@@ -93,9 +90,7 @@ void LoopManager::render() {
window.renderUIObjects();
}
}
-void LoopManager::onShutdown(const ShutDownEvent & e) {
- this->gameRunning = false;
-}
+void LoopManager::onShutdown(const ShutDownEvent & e) { this->gameRunning = false; }
void LoopManager::update() {
//fprintf(stderr, "**********normal update********** \n");
LoopTimer & timer = LoopTimer::getInstance();
diff --git a/mwe/events/src/main.cpp b/mwe/events/src/main.cpp
index f4e7390..ad0fd69 100644
--- a/mwe/events/src/main.cpp
+++ b/mwe/events/src/main.cpp
@@ -25,8 +25,8 @@ private:
int playerID;
};
void onPlayerDamaged(const PlayerDamagedEvent & e) {
- std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage()
- << " damage." << std::endl;
+ std::cout << "Player " << e.getPlayerID() << " took " << e.getDamage() << " damage."
+ << std::endl;
}
void onKeyPressed1(const KeyPressedEvent & e) {
@@ -38,8 +38,7 @@ void onKeyPressed(const KeyPressedEvent & e) {
fprintf(stderr, "second function KeyCode %d\n", keyCode);
}
void CollisionHandler(const CollisionEvent & e) {
- std::cout << "collision betwee object id: "
- << e.getCollisionData().objectIdA
+ std::cout << "collision betwee object id: " << e.getCollisionData().objectIdA
<< " and id: " << e.getCollisionData().objectIdB << std::endl;
}
void testCollisionEvent() {
diff --git a/mwe/events/src/mouseListenerTest.cpp b/mwe/events/src/mouseListenerTest.cpp
index a2a7e6d..7b35f4e 100644
--- a/mwe/events/src/mouseListenerTest.cpp
+++ b/mwe/events/src/mouseListenerTest.cpp
@@ -1,8 +1,6 @@
#include "mouseListenerTest.h"
-MouseListenerTest::MouseListenerTest(int listenerId) {
- subscribeEvents(listenerId);
-}
+MouseListenerTest::MouseListenerTest(int listenerId) { subscribeEvents(listenerId); }
MouseListenerTest::~MouseListenerTest() { unsubscribeEvents(); }
@@ -12,13 +10,13 @@ void MouseListenerTest::onMouseClicked(const MouseClickEvent & event) {
}
void MouseListenerTest::onMousePressed(const MousePressedEvent & event) {
- std::cout << "Mouse button pressed at: (" << event.getMousePosition().first
- << ", " << event.getMousePosition().second << ")" << std::endl;
+ std::cout << "Mouse button pressed at: (" << event.getMousePosition().first << ", "
+ << event.getMousePosition().second << ")" << std::endl;
}
void MouseListenerTest::onMouseReleased(const MouseReleasedEvent & event) {
- std::cout << "Mouse button released at: (" << event.getMousePosition().first
- << ", " << event.getMousePosition().second << ")" << std::endl;
+ std::cout << "Mouse button released at: (" << event.getMousePosition().first << ", "
+ << event.getMousePosition().second << ")" << std::endl;
}
void MouseListenerTest::onMouseMoved(const MouseMovedEvent & event) {
diff --git a/mwe/events/src/timer.cpp b/mwe/events/src/timer.cpp
index 0b89bf5..0f8339f 100644
--- a/mwe/events/src/timer.cpp
+++ b/mwe/events/src/timer.cpp
@@ -45,8 +45,7 @@ void LoopTimer::enforceFrameRate() {
double frameDuration = (currentFrameTime - lastFrameTime) / 1000.0;
if (frameDuration < frameTargetTime) {
- uint32_t delayTime
- = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0);
+ uint32_t delayTime = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0);
SDL_Delay(delayTime);
}
}
diff --git a/mwe/events/src/uiRenderer.cpp b/mwe/events/src/uiRenderer.cpp
index 9fec272..ca8d284 100644
--- a/mwe/events/src/uiRenderer.cpp
+++ b/mwe/events/src/uiRenderer.cpp
@@ -24,21 +24,18 @@ void UIRenderer::renderButton(Button * button) {
// Private helper function to render a Text
void UIRenderer::renderText(Text * text) {
if (text->font != nullptr) {
- SDL_Color sdlColor
- = {text->color.red, text->color.green, text->color.blue, 255};
+ SDL_Color sdlColor = {text->color.red, text->color.green, text->color.blue, 255};
SDL_Surface * textSurface
= TTF_RenderText_Blended(text->font, text->text.c_str(), sdlColor);
if (!textSurface) {
- std::cerr << "Error creating text surface: " << TTF_GetError()
- << std::endl;
+ std::cerr << "Error creating text surface: " << TTF_GetError() << std::endl;
return;
}
- SDL_Texture * textTexture
- = SDL_CreateTextureFromSurface(renderer, textSurface);
+ SDL_Texture * textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
if (!textTexture) {
- std::cerr << "Error creating texture from surface: "
- << SDL_GetError() << std::endl;
+ std::cerr << "Error creating texture from surface: " << SDL_GetError()
+ << std::endl;
SDL_FreeSurface(textSurface);
return;
}
diff --git a/mwe/events/src/window.cpp b/mwe/events/src/window.cpp
index f482b7f..af2b627 100644
--- a/mwe/events/src/window.cpp
+++ b/mwe/events/src/window.cpp
@@ -11,9 +11,8 @@ bool WindowManager::initWindow() {
return false;
}
- window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED,
- SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
- SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
+ window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
+ SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (!window) {
std::cerr << "Error creating SDL Window.\n";
return false;
@@ -36,9 +35,7 @@ void WindowManager::destroyWindow() {
}
SDL_Renderer * WindowManager::getRenderer() { return renderer; }
-void WindowManager::addUIObject(UIObject * uiObject) {
- uiObjects.push_back(uiObject);
-}
+void WindowManager::addUIObject(UIObject * uiObject) { uiObjects.push_back(uiObject); }
void WindowManager::renderUIObjects() {
for (UIObject * obj : uiObjects) {
diff --git a/mwe/events/versions/delayBased.cpp b/mwe/events/versions/delayBased.cpp
index 253a03a..634de9c 100644
--- a/mwe/events/versions/delayBased.cpp
+++ b/mwe/events/versions/delayBased.cpp
@@ -32,8 +32,7 @@ void LoopManager::setup() {
LoopTimer::getInstance().setFPS(210);
for (int i = 0; i < 2; i++) {
- GameObject * square2
- = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0);
+ GameObject * square2 = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0);
objectList.push_back(square2);
}
}
diff --git a/mwe/gameloop/include/gameObject.h b/mwe/gameloop/include/gameObject.h
index abdc9b0..2764215 100644
--- a/mwe/gameloop/include/gameObject.h
+++ b/mwe/gameloop/include/gameObject.h
@@ -3,8 +3,8 @@
class GameObject {
public:
GameObject();
- GameObject(std::string name, float x, float y, float width, float height,
- float velX, float velY);
+ GameObject(std::string name, float x, float y, float width, float height, float velX,
+ float velY);
std::string getName() const;
float getX() const;
float getY() const;
diff --git a/mwe/gameloop/src/gameObject.cpp b/mwe/gameloop/src/gameObject.cpp
index b33dc78..809e25f 100644
--- a/mwe/gameloop/src/gameObject.cpp
+++ b/mwe/gameloop/src/gameObject.cpp
@@ -24,8 +24,8 @@ void GameObject::setVelX(float value) { velX = value; }
void GameObject::setVelY(float value) { velY = value; }
-GameObject::GameObject(std::string name, float x, float y, float width,
- float height, float velX, float velY)
+GameObject::GameObject(std::string name, float x, float y, float width, float height,
+ float velX, float velY)
: name(name),
x(x),
y(y),
diff --git a/mwe/gameloop/src/loopManager.cpp b/mwe/gameloop/src/loopManager.cpp
index 49d65fb..fb06995 100644
--- a/mwe/gameloop/src/loopManager.cpp
+++ b/mwe/gameloop/src/loopManager.cpp
@@ -18,11 +18,11 @@ void LoopManager::processInput() {
if (event.key.keysym.sym == SDLK_ESCAPE) {
gameRunning = false;
} else if (event.key.keysym.sym == SDLK_i) {
- LoopTimer::getInstance().setGameScale(
- LoopTimer::getInstance().getGameScale() + 0.1);
+ LoopTimer::getInstance().setGameScale(LoopTimer::getInstance().getGameScale()
+ + 0.1);
} else if (event.key.keysym.sym == SDLK_k) {
- LoopTimer::getInstance().setGameScale(
- LoopTimer::getInstance().getGameScale() - 0.1);
+ LoopTimer::getInstance().setGameScale(LoopTimer::getInstance().getGameScale()
+ - 0.1);
}
break;
@@ -57,8 +57,7 @@ void LoopManager::setup() {
LoopTimer::getInstance().setFPS(10);
this->gameRunning = true;
for (int i = 1; i < 3; i++) {
- GameObject * square
- = new GameObject("square2", i * 60, i * 60, 20, 20, 0, 0);
+ GameObject * square = new GameObject("square2", i * 60, i * 60, 20, 20, 0, 0);
objectList.push_back(square);
}
}
diff --git a/mwe/gameloop/src/timer.cpp b/mwe/gameloop/src/timer.cpp
index 97baef6..5ae1564 100644
--- a/mwe/gameloop/src/timer.cpp
+++ b/mwe/gameloop/src/timer.cpp
@@ -45,8 +45,7 @@ void LoopTimer::enforceFrameRate() {
double frameDuration = (currentFrameTime - lastFrameTime) / 1000.0;
if (frameDuration < frameTargetTime) {
- uint32_t delayTime
- = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0);
+ uint32_t delayTime = (uint32_t) ((frameTargetTime - frameDuration) * 1000.0);
SDL_Delay(delayTime);
}
}
diff --git a/mwe/gameloop/src/window.cpp b/mwe/gameloop/src/window.cpp
index dd1d98f..8f802e1 100644
--- a/mwe/gameloop/src/window.cpp
+++ b/mwe/gameloop/src/window.cpp
@@ -36,9 +36,8 @@ bool WindowManager::initWindow() {
fprintf(stderr, "Error inititalising SDL.\n");
return false;
}
- window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED,
- SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
- SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
+ window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
+ SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (!window) {
fprintf(stderr, "Error creating SDL Window. \n");
return false;
diff --git a/mwe/gameloop/versions/delayBased.cpp b/mwe/gameloop/versions/delayBased.cpp
index 253a03a..634de9c 100644
--- a/mwe/gameloop/versions/delayBased.cpp
+++ b/mwe/gameloop/versions/delayBased.cpp
@@ -32,8 +32,7 @@ void LoopManager::setup() {
LoopTimer::getInstance().setFPS(210);
for (int i = 0; i < 2; i++) {
- GameObject * square2
- = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0);
+ GameObject * square2 = new GameObject("square2", i * 40, i * 40, 20, 20, 0, 0);
objectList.push_back(square2);
}
}
diff --git a/mwe/resource-manager/TextureMap.cpp b/mwe/resource-manager/TextureMap.cpp
index d82975c..284f8a8 100644
--- a/mwe/resource-manager/TextureMap.cpp
+++ b/mwe/resource-manager/TextureMap.cpp
@@ -15,8 +15,7 @@ TextureMap::~TextureMap() {
}
//public
-bool TextureMap::loadFromFile(const std::string & path,
- SDL_Renderer * renderer) {
+bool TextureMap::loadFromFile(const std::string & path, SDL_Renderer * renderer) {
assert(renderer != nullptr);
assert(!path.empty());
@@ -34,12 +33,11 @@ bool TextureMap::loadFromFile(const std::string & path,
constexpr std::int32_t bmask = 0x00ff0000;
const std::int32_t amask = c == 4 ? 0xff000000 : 0;
- auto * surface = SDL_CreateRGBSurfaceFrom(data, x, y, c * 8, pitch,
- rmask, gmask, bmask, amask);
+ auto * surface
+ = SDL_CreateRGBSurfaceFrom(data, x, y, c * 8, pitch, rmask, gmask, bmask, amask);
if (!surface) {
- std::cerr << "Unable to create texture surface: " << SDL_GetError()
- << "\n";
+ std::cerr << "Unable to create texture surface: " << SDL_GetError() << "\n";
stbi_image_free(data);
return false;
}
diff --git a/mwe/resource-manager/main.cpp b/mwe/resource-manager/main.cpp
index b6416f6..1910af8 100644
--- a/mwe/resource-manager/main.cpp
+++ b/mwe/resource-manager/main.cpp
@@ -23,9 +23,8 @@ int main() {
SDL_Event event;
- SDL_Window * window
- = SDL_CreateWindow("Tessting resources", SDL_WINDOWPOS_UNDEFINED,
- SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
+ SDL_Window * window = SDL_CreateWindow("Tessting resources", SDL_WINDOWPOS_UNDEFINED,
+ SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
diff --git a/mwe/resource-manager/map_layer.cpp b/mwe/resource-manager/map_layer.cpp
index 6339707..17792a6 100644
--- a/mwe/resource-manager/map_layer.cpp
+++ b/mwe/resource-manager/map_layer.cpp
@@ -20,8 +20,7 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex,
const auto & tileSets = map.getTilesets();
const auto tintColour = layer.getTintColour();
- const SDL_Colour vertColour
- = {tintColour.r, tintColour.g, tintColour.b, tintColour.a};
+ const SDL_Colour vertColour = {tintColour.r, tintColour.g, tintColour.b, tintColour.a};
for (auto i = 0u; i < tileSets.size(); ++i) {
//check tile ID to see if it falls within the current tile set
@@ -40,8 +39,7 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex,
for (auto x = 0u; x < mapSize.x; ++x) {
const auto idx = y * mapSize.x + x;
if (idx < tileIDs.size() && tileIDs[idx].ID >= ts.getFirstGID()
- && tileIDs[idx].ID
- < (ts.getFirstGID() + ts.getTileCount())) {
+ && tileIDs[idx].ID < (ts.getFirstGID() + ts.getTileCount())) {
//tex coords
auto idIndex = (tileIDs[idx].ID - ts.getFirstGID());
float u = static_cast<float>(idIndex % tileCountX);
@@ -55,36 +53,24 @@ bool MapLayer::create(const tmx::Map & map, std::uint32_t layerIndex,
v /= textures[i]->getSize().y;
//vert pos
- const float tilePosX
- = static_cast<float>(x) * mapTileSize.x;
- const float tilePosY
- = (static_cast<float>(y) * mapTileSize.y);
+ const float tilePosX = static_cast<float>(x) * mapTileSize.x;
+ const float tilePosY = (static_cast<float>(y) * mapTileSize.y);
//push back to vert array
- SDL_Vertex vert
- = {{tilePosX, tilePosY}, vertColour, {u, v}};
+ SDL_Vertex vert = {{tilePosX, tilePosY}, vertColour, {u, v}};
verts.emplace_back(vert);
- vert = {{tilePosX + mapTileSize.x, tilePosY},
- vertColour,
- {u + uNorm, v}};
+ vert = {{tilePosX + mapTileSize.x, tilePosY}, vertColour, {u + uNorm, v}};
verts.emplace_back(vert);
- vert = {{tilePosX, tilePosY + mapTileSize.y},
- vertColour,
- {u, v + vNorm}};
+ vert = {{tilePosX, tilePosY + mapTileSize.y}, vertColour, {u, v + vNorm}};
verts.emplace_back(vert);
- vert = {{tilePosX, tilePosY + mapTileSize.y},
- vertColour,
- {u, v + vNorm}};
+ vert = {{tilePosX, tilePosY + mapTileSize.y}, vertColour, {u, v + vNorm}};
verts.emplace_back(vert);
- vert = {{tilePosX + mapTileSize.x, tilePosY},
- vertColour,
- {u + uNorm, v}};
+ vert = {{tilePosX + mapTileSize.x, tilePosY}, vertColour, {u + uNorm, v}};
verts.emplace_back(vert);
- vert
- = {{tilePosX + mapTileSize.x, tilePosY + mapTileSize.y},
- vertColour,
- {u + uNorm, v + vNorm}};
+ vert = {{tilePosX + mapTileSize.x, tilePosY + mapTileSize.y},
+ vertColour,
+ {u + uNorm, v + vNorm}};
verts.emplace_back(vert);
}
}
@@ -104,7 +90,6 @@ void MapLayer::draw(SDL_Renderer * renderer) const {
assert(renderer);
for (const auto & s : m_subsets) {
SDL_RenderGeometry(renderer, s.texture, s.vertexData.data(),
- static_cast<std::int32_t>(s.vertexData.size()),
- nullptr, 0);
+ static_cast<std::int32_t>(s.vertexData.size()), nullptr, 0);
}
}
diff --git a/mwe/resource-manager/resource_converter.cpp b/mwe/resource-manager/resource_converter.cpp
index 0477dc2..632f630 100644
--- a/mwe/resource-manager/resource_converter.cpp
+++ b/mwe/resource-manager/resource_converter.cpp
@@ -17,8 +17,7 @@ SDL_Surface * ResourceConverter::FromStringToImage(const Texture & resource) {
const std::string & content = resource.getContent();
SDL_RWops * rw = SDL_RWFromConstMem(content.data(), content.size());
if (!rw) {
- std::cerr << "Failed to create SDL_RWops: " << SDL_GetError()
- << std::endl;
+ std::cerr << "Failed to create SDL_RWops: " << SDL_GetError() << std::endl;
return nullptr;
}
diff --git a/mwe/resource-manager/spritesheet.cpp b/mwe/resource-manager/spritesheet.cpp
index a5881e5..9739e01 100644
--- a/mwe/resource-manager/spritesheet.cpp
+++ b/mwe/resource-manager/spritesheet.cpp
@@ -4,8 +4,6 @@
#include <string>
-SpriteSheet::SpriteSheet(const std::string & content) {
- this->m_content = content;
-}
+SpriteSheet::SpriteSheet(const std::string & content) { this->m_content = content; }
SpriteSheet::~SpriteSheet() {}
diff --git a/mwe/resource-manager/stb_image.h b/mwe/resource-manager/stb_image.h
index ce0cc10..3462f3a 100644
--- a/mwe/resource-manager/stb_image.h
+++ b/mwe/resource-manager/stb_image.h
@@ -410,9 +410,8 @@ typedef struct {
int (*read)(
void * user, char * data,
int size); // fill 'data' with 'size' bytes. return number of bytes actually read
- void (*skip)(
- void * user,
- int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
+ void (*skip)(void * user,
+ int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
int (*eof)(void * user); // returns nonzero if we are at end of file/data
} stbi_io_callbacks;
@@ -421,33 +420,28 @@ typedef struct {
// 8-bits-per-channel interface
//
-STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len,
- int * x, int * y,
- int * channels_in_file,
- int desired_channels);
-STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y,
- int * channels_in_file,
+STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * channels_in_file, int desired_channels);
+STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, void * user,
+ int * x, int * y, int * channels_in_file,
int desired_channels);
#ifndef STBI_NO_STDIO
-STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y,
- int * channels_in_file, int desired_channels);
-STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y,
- int * channels_in_file,
+STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, int * channels_in_file,
+ int desired_channels);
+STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * channels_in_file,
int desired_channels);
// for stbi_load_from_file, file pointer is left pointing immediately after image
#endif
#ifndef STBI_NO_GIF
-STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len,
- int ** delays, int * x, int * y,
- int * z, int * comp, int req_comp);
+STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int ** delays,
+ int * x, int * y, int * z, int * comp,
+ int req_comp);
#endif
#ifdef STBI_WINDOWS_UTF8
-STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen,
- const wchar_t * input);
+STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen, const wchar_t * input);
#endif
////////////////////////////////////
@@ -455,20 +449,16 @@ STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen,
// 16-bits-per-channel interface
//
-STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len,
- int * x, int * y,
- int * channels_in_file,
- int desired_channels);
-STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y,
- int * channels_in_file,
+STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * channels_in_file, int desired_channels);
+STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, void * user,
+ int * x, int * y, int * channels_in_file,
int desired_channels);
#ifndef STBI_NO_STDIO
-STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y,
- int * channels_in_file, int desired_channels);
-STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y,
- int * channels_in_file,
+STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * channels_in_file,
+ int desired_channels);
+STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y, int * channels_in_file,
int desired_channels);
#endif
@@ -477,19 +467,16 @@ STBIDEF stbi_us * stbi_load_from_file_16(FILE * f, int * x, int * y,
// float-per-channel interface
//
#ifndef STBI_NO_LINEAR
-STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x,
- int * y, int * channels_in_file,
- int desired_channels);
-STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y,
- int * channels_in_file,
+STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * channels_in_file, int desired_channels);
+STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x,
+ int * y, int * channels_in_file,
int desired_channels);
#ifndef STBI_NO_STDIO
-STBIDEF float * stbi_loadf(char const * filename, int * x, int * y,
- int * channels_in_file, int desired_channels);
-STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y,
- int * channels_in_file,
+STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * channels_in_file,
+ int desired_channels);
+STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * channels_in_file,
int desired_channels);
#endif
#endif
@@ -505,8 +492,7 @@ STBIDEF void stbi_ldr_to_hdr_scale(float scale);
#endif // STBI_NO_LINEAR
// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
-STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk,
- void * user);
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk, void * user);
STBIDEF int stbi_is_hdr_from_memory(stbi_uc const * buffer, int len);
#ifndef STBI_NO_STDIO
STBIDEF int stbi_is_hdr(char const * filename);
@@ -521,13 +507,12 @@ STBIDEF const char * stbi_failure_reason(void);
STBIDEF void stbi_image_free(void * retval_from_stbi_load);
// get image dimensions & components without fully decoding
-STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x,
- int * y, int * comp);
-STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y, int * comp);
+STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * comp);
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x,
+ int * y, int * comp);
STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const * buffer, int len);
-STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * clbk,
- void * user);
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * clbk, void * user);
#ifndef STBI_NO_STDIO
STBIDEF int stbi_info(char const * filename, int * x, int * y, int * comp);
@@ -539,8 +524,7 @@ STBIDEF int stbi_is_16_bit_from_file(FILE * f);
// for image formats that explicitly notate that they have premultiplied alpha,
// we just return the colors as stored in the file. set this flag to force
// unpremultiplication. results are undefined if the unpremultiply overflow.
-STBIDEF void
-stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
// indicate whether we should process iphone images back to canonical format,
// or just pass them through "as-is"
@@ -552,32 +536,23 @@ STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
// as above, but only applies to images loaded on the thread that calls the function
// this function is only available if your compiler supports thread-local variables;
// calling it will fail to link if your compiler doesn't
-STBIDEF void
-stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
-STBIDEF void
-stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
-STBIDEF void
-stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
// ZLIB client - used by PNG, available for other purposes
STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len,
- int initial_size,
- int * outlen);
-STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer,
- int len,
- int initial_size,
- int * outlen,
+ int initial_size, int * outlen);
+STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, int len,
+ int initial_size, int * outlen,
int parse_header);
-STBIDEF char * stbi_zlib_decode_malloc(const char * buffer, int len,
- int * outlen);
-STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen,
- const char * ibuffer, int ilen);
+STBIDEF char * stbi_zlib_decode_malloc(const char * buffer, int len, int * outlen);
+STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, const char * ibuffer, int ilen);
-STBIDEF char * stbi_zlib_decode_noheader_malloc(const char * buffer, int len,
- int * outlen);
-STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen,
- const char * ibuffer, int ilen);
+STBIDEF char * stbi_zlib_decode_noheader_malloc(const char * buffer, int len, int * outlen);
+STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer,
+ int ilen);
#ifdef __cplusplus
}
@@ -590,11 +565,10 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen,
#ifdef STB_IMAGE_IMPLEMENTATION
-#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) \
- || defined(STBI_ONLY_BMP) || defined(STBI_ONLY_TGA) \
- || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
- || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) \
- || defined(STBI_ONLY_PNM) || defined(STBI_ONLY_ZLIB)
+#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
+ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
+ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
+ || defined(STBI_ONLY_ZLIB)
#ifndef STBI_ONLY_JPEG
#define STBI_NO_JPEG
#endif
@@ -624,8 +598,7 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen,
#endif
#endif
-#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) \
- && !defined(STBI_NO_ZLIB)
+#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
#define STBI_NO_ZLIB
#endif
@@ -671,8 +644,7 @@ STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen,
#define STBI_THREAD_LOCAL __thread
#elif defined(_MSC_VER)
#define STBI_THREAD_LOCAL __declspec(thread)
-#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
- && !defined(__STDC_NO_THREADS__)
+#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
#define STBI_THREAD_LOCAL _Thread_local
#endif
@@ -755,8 +727,8 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1];
#define STBI_NO_SIMD
#endif
-#if defined(__MINGW32__) && defined(STBI__X86_TARGET) \
- && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
+#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) \
+ && !defined(STBI_NO_SIMD)
// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
//
// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
@@ -771,8 +743,7 @@ typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1];
#define STBI_NO_SIMD
#endif
-#if !defined(STBI_NO_SIMD) \
- && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
+#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
#define STBI_SSE2
#include <emmintrin.h>
@@ -868,8 +839,7 @@ typedef struct {
static void stbi__refill_buffer(stbi__context * s);
// initialize a memory-decode context
-static void stbi__start_mem(stbi__context * s, stbi_uc const * buffer,
- int len) {
+static void stbi__start_mem(stbi__context * s, stbi_uc const * buffer, int len) {
s->io.read = NULL;
s->read_from_callbacks = 0;
s->callback_already_read = 0;
@@ -878,8 +848,7 @@ static void stbi__start_mem(stbi__context * s, stbi_uc const * buffer,
}
// initialize a callback-based context
-static void stbi__start_callbacks(stbi__context * s, stbi_io_callbacks * c,
- void * user) {
+static void stbi__start_callbacks(stbi__context * s, stbi_io_callbacks * c, void * user) {
s->io = *c;
s->io_user_data = user;
s->buflen = sizeof(s->buffer_start);
@@ -941,68 +910,68 @@ typedef struct {
#ifndef STBI_NO_JPEG
static int stbi__jpeg_test(stbi__context * s);
-static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__jpeg_info(stbi__context * s, int * x, int * y, int * comp);
#endif
#ifndef STBI_NO_PNG
static int stbi__png_test(stbi__context * s);
-static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__png_info(stbi__context * s, int * x, int * y, int * comp);
static int stbi__png_is16(stbi__context * s);
#endif
#ifndef STBI_NO_BMP
static int stbi__bmp_test(stbi__context * s);
-static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__bmp_info(stbi__context * s, int * x, int * y, int * comp);
#endif
#ifndef STBI_NO_TGA
static int stbi__tga_test(stbi__context * s);
-static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp);
#endif
#ifndef STBI_NO_PSD
static int stbi__psd_test(stbi__context * s);
-static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri, int bpc);
+static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri, int bpc);
static int stbi__psd_info(stbi__context * s, int * x, int * y, int * comp);
static int stbi__psd_is16(stbi__context * s);
#endif
#ifndef STBI_NO_HDR
static int stbi__hdr_test(stbi__context * s);
-static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__hdr_info(stbi__context * s, int * x, int * y, int * comp);
#endif
#ifndef STBI_NO_PIC
static int stbi__pic_test(stbi__context * s);
-static void * stbi__pic_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static void * stbi__pic_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__pic_info(stbi__context * s, int * x, int * y, int * comp);
#endif
#ifndef STBI_NO_GIF
static int stbi__gif_test(stbi__context * s);
-static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
-static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x,
- int * y, int * z, int * comp, int req_comp);
+static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
+static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int * y, int * z,
+ int * comp, int req_comp);
static int stbi__gif_info(stbi__context * s, int * x, int * y, int * comp);
#endif
#ifndef STBI_NO_PNM
static int stbi__pnm_test(stbi__context * s);
-static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri);
+static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri);
static int stbi__pnm_info(stbi__context * s, int * x, int * y, int * comp);
static int stbi__pnm_is16(stbi__context * s);
#endif
@@ -1013,9 +982,7 @@ static
#endif
const char * stbi__g_failure_reason;
-STBIDEF const char * stbi_failure_reason(void) {
- return stbi__g_failure_reason;
-}
+STBIDEF const char * stbi_failure_reason(void) { return stbi__g_failure_reason; }
#ifndef STBI_NO_FAILURE_STRINGS
static int stbi__err(const char * str) {
@@ -1074,8 +1041,7 @@ static int stbi__mad3sizes_valid(int a, int b, int c, int add) {
#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) {
return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a * b, c)
- && stbi__mul2sizes_valid(a * b * c, d)
- && stbi__addsizes_valid(a * b * c * d, add);
+ && stbi__mul2sizes_valid(a * b * c, d) && stbi__addsizes_valid(a * b * c * d, add);
}
#endif
@@ -1102,8 +1068,7 @@ static void * stbi__malloc_mad4(int a, int b, int c, int d, int add) {
// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.
static int stbi__addints_valid(int a, int b) {
- if ((a >= 0) != (b >= 0))
- return 1; // a and b have different signs, so no overflow
+ if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow
if (a < 0 && b < 0)
return a
>= INT_MIN
@@ -1116,9 +1081,7 @@ static int stbi__mul2shorts_valid(int a, int b) {
if (b == 0 || b == -1)
return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow
if ((a >= 0) == (b >= 0))
- return a
- <= SHRT_MAX
- / b; // product is positive, so similar to mul2sizes_valid
+ return a <= SHRT_MAX / b; // product is positive, so similar to mul2sizes_valid
if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN
return a >= SHRT_MIN / b;
}
@@ -1136,8 +1099,7 @@ static int stbi__mul2shorts_valid(int a, int b) {
#endif
#define stbi__errpf(x, y) ((float *) (size_t) (stbi__err(x, y) ? NULL : NULL))
-#define stbi__errpuc(x, y) \
- ((unsigned char *) (size_t) (stbi__err(x, y) ? NULL : NULL))
+#define stbi__errpuc(x, y) ((unsigned char *) (size_t) (stbi__err(x, y) ? NULL : NULL))
STBIDEF void stbi_image_free(void * retval_from_stbi_load) {
STBI_FREE(retval_from_stbi_load);
@@ -1163,8 +1125,7 @@ STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) {
static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local,
stbi__vertically_flip_on_load_set;
-STBIDEF void
-stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) {
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) {
stbi__vertically_flip_on_load_local = flag_true_if_should_flip;
stbi__vertically_flip_on_load_set = 1;
}
@@ -1174,12 +1135,11 @@ stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) {
: stbi__vertically_flip_on_load_global)
#endif // STBI_THREAD_LOCAL
-static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri, int bpc) {
+static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri, int bpc) {
memset(ri, 0,
sizeof(*ri)); // make sure it's initialized if we add new fields
- ri->bits_per_channel
- = 8; // default is 8 so most paths don't have to be changed
+ ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed
ri->channel_order
= STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order
ri->num_channels = 0;
@@ -1196,8 +1156,7 @@ static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp,
if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri);
#endif
#ifndef STBI_NO_PSD
- if (stbi__psd_test(s))
- return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc);
+ if (stbi__psd_test(s)) return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc);
#else
STBI_NOTUSED(bpc);
#endif
@@ -1227,12 +1186,10 @@ static void * stbi__load_main(stbi__context * s, int * x, int * y, int * comp,
if (stbi__tga_test(s)) return stbi__tga_load(s, x, y, comp, req_comp, ri);
#endif
- return stbi__errpuc("unknown image type",
- "Image not of any known type, or corrupt");
+ return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
}
-static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h,
- int channels) {
+static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h, int channels) {
int i;
int img_len = w * h * channels;
stbi_uc * reduced;
@@ -1249,15 +1206,13 @@ static stbi_uc * stbi__convert_16_to_8(stbi__uint16 * orig, int w, int h,
return reduced;
}
-static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h,
- int channels) {
+static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h, int channels) {
int i;
int img_len = w * h * channels;
stbi__uint16 * enlarged;
enlarged = (stbi__uint16 *) stbi__malloc(img_len * 2);
- if (enlarged == NULL)
- return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+ if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
for (i = 0; i < img_len; ++i)
enlarged[i]
@@ -1269,8 +1224,7 @@ static stbi__uint16 * stbi__convert_8_to_16(stbi_uc * orig, int w, int h,
return enlarged;
}
-static void stbi__vertical_flip(void * image, int w, int h,
- int bytes_per_pixel) {
+static void stbi__vertical_flip(void * image, int w, int h, int bytes_per_pixel) {
int row;
size_t bytes_per_row = (size_t) w * bytes_per_pixel;
stbi_uc temp[2048];
@@ -1282,8 +1236,7 @@ static void stbi__vertical_flip(void * image, int w, int h,
// swap row0 with row1
size_t bytes_left = bytes_per_row;
while (bytes_left) {
- size_t bytes_copy
- = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
+ size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
memcpy(temp, row0, bytes_copy);
memcpy(row0, row1, bytes_copy);
memcpy(row1, temp, bytes_copy);
@@ -1308,10 +1261,8 @@ static void stbi__vertical_flip_slices(void * image, int w, int h, int z,
}
#endif
-static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s,
- int * x, int * y,
- int * comp,
- int req_comp) {
+static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s, int * x, int * y,
+ int * comp, int req_comp) {
stbi__result_info ri;
void * result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
@@ -1336,10 +1287,8 @@ static unsigned char * stbi__load_and_postprocess_8bit(stbi__context * s,
return (unsigned char *) result;
}
-static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s,
- int * x, int * y,
- int * comp,
- int req_comp) {
+static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s, int * x, int * y,
+ int * comp, int req_comp) {
stbi__result_info ri;
void * result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
@@ -1366,8 +1315,8 @@ static stbi__uint16 * stbi__load_and_postprocess_16bit(stbi__context * s,
}
#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)
-static void stbi__float_postprocess(float * result, int * x, int * y,
- int * comp, int req_comp) {
+static void stbi__float_postprocess(float * result, int * x, int * y, int * comp,
+ int req_comp) {
if (stbi__vertically_flip_on_load && result != NULL) {
int channels = req_comp ? req_comp : *comp;
stbi__vertical_flip(result, *x, *y, channels * sizeof(float));
@@ -1378,19 +1327,20 @@ static void stbi__float_postprocess(float * result, int * x, int * y,
#ifndef STBI_NO_STDIO
#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
-STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(
- unsigned int cp, unsigned long flags, const char * str, int cbmb,
- wchar_t * widestr, int cchwide);
+STBI_EXTERN
+__declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags,
+ const char * str, int cbmb,
+ wchar_t * widestr, int cchwide);
STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(
- unsigned int cp, unsigned long flags, const wchar_t * widestr, int cchwide,
- char * str, int cbmb, const char * defchar, int * used_default);
+ unsigned int cp, unsigned long flags, const wchar_t * widestr, int cchwide, char * str,
+ int cbmb, const char * defchar, int * used_default);
#endif
#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
STBIDEF int stbi_convert_wchar_to_utf8(char * buffer, size_t bufferlen,
const wchar_t * input) {
- return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer,
- (int) bufferlen, NULL, NULL);
+ return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL,
+ NULL);
}
#endif
@@ -1433,8 +1383,7 @@ STBIDEF stbi_uc * stbi_load(char const * filename, int * x, int * y, int * comp,
return result;
}
-STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp,
- int req_comp) {
+STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp, int req_comp) {
unsigned char * result;
stbi__context s;
stbi__start_file(&s, f);
@@ -1446,8 +1395,8 @@ STBIDEF stbi_uc * stbi_load_from_file(FILE * f, int * x, int * y, int * comp,
return result;
}
-STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y,
- int * comp, int req_comp) {
+STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y, int * comp,
+ int req_comp) {
stbi__uint16 * result;
stbi__context s;
stbi__start_file(&s, f);
@@ -1459,12 +1408,11 @@ STBIDEF stbi__uint16 * stbi_load_from_file_16(FILE * f, int * x, int * y,
return result;
}
-STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y,
- int * comp, int req_comp) {
+STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y, int * comp,
+ int req_comp) {
FILE * f = stbi__fopen(filename, "rb");
stbi__uint16 * result;
- if (!f)
- return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file");
+ if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file");
result = stbi_load_from_file_16(f, x, y, comp, req_comp);
fclose(f);
return result;
@@ -1472,52 +1420,44 @@ STBIDEF stbi_us * stbi_load_16(char const * filename, int * x, int * y,
#endif //!STBI_NO_STDIO
-STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len,
- int * x, int * y,
- int * channels_in_file,
- int desired_channels) {
+STBIDEF stbi_us * stbi_load_16_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * channels_in_file, int desired_channels) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
- return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file,
- desired_channels);
+ return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels);
}
-STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y,
- int * channels_in_file,
+STBIDEF stbi_us * stbi_load_16_from_callbacks(stbi_io_callbacks const * clbk, void * user,
+ int * x, int * y, int * channels_in_file,
int desired_channels) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
- return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file,
- desired_channels);
+ return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels);
}
-STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len,
- int * x, int * y, int * comp,
- int req_comp) {
+STBIDEF stbi_uc * stbi_load_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * comp, int req_comp) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
}
-STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y,
- int * comp, int req_comp) {
+STBIDEF stbi_uc * stbi_load_from_callbacks(stbi_io_callbacks const * clbk, void * user,
+ int * x, int * y, int * comp, int req_comp) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp);
}
#ifndef STBI_NO_GIF
-STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len,
- int ** delays, int * x, int * y,
- int * z, int * comp, int req_comp) {
+STBIDEF stbi_uc * stbi_load_gif_from_memory(stbi_uc const * buffer, int len, int ** delays,
+ int * x, int * y, int * z, int * comp,
+ int req_comp) {
unsigned char * result;
stbi__context s;
stbi__start_mem(&s, buffer, len);
- result = (unsigned char *) stbi__load_gif_main(&s, delays, x, y, z, comp,
- req_comp);
+ result = (unsigned char *) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);
if (stbi__vertically_flip_on_load) {
stbi__vertical_flip_slices(result, *x, *y, *z, *comp);
}
@@ -1539,30 +1479,26 @@ static float * stbi__loadf_main(stbi__context * s, int * x, int * y, int * comp,
}
#endif
data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);
- if (data)
- return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
- return stbi__errpf("unknown image type",
- "Image not of any known type, or corrupt");
+ if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
+ return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
}
-STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x,
- int * y, int * comp, int req_comp) {
+STBIDEF float * stbi_loadf_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * comp, int req_comp) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__loadf_main(&s, x, y, comp, req_comp);
}
-STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk,
- void * user, int * x, int * y,
- int * comp, int req_comp) {
+STBIDEF float * stbi_loadf_from_callbacks(stbi_io_callbacks const * clbk, void * user, int * x,
+ int * y, int * comp, int req_comp) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
return stbi__loadf_main(&s, x, y, comp, req_comp);
}
#ifndef STBI_NO_STDIO
-STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * comp,
- int req_comp) {
+STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * comp, int req_comp) {
float * result;
FILE * f = stbi__fopen(filename, "rb");
if (!f) return stbi__errpf("can't fopen", "Unable to open file");
@@ -1571,8 +1507,7 @@ STBIDEF float * stbi_loadf(char const * filename, int * x, int * y, int * comp,
return result;
}
-STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * comp,
- int req_comp) {
+STBIDEF float * stbi_loadf_from_file(FILE * f, int * x, int * y, int * comp, int req_comp) {
stbi__context s;
stbi__start_file(&s, f);
return stbi__loadf_main(&s, x, y, comp, req_comp);
@@ -1624,8 +1559,7 @@ STBIDEF int stbi_is_hdr_from_file(FILE * f) {
}
#endif // !STBI_NO_STDIO
-STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk,
- void * user) {
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const * clbk, void * user) {
#ifndef STBI_NO_HDR
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
@@ -1646,12 +1580,8 @@ STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f;
-STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) {
- stbi__h2l_gamma_i = 1 / gamma;
-}
-STBIDEF void stbi_hdr_to_ldr_scale(float scale) {
- stbi__h2l_scale_i = 1 / scale;
-}
+STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1 / gamma; }
+STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1 / scale; }
//////////////////////////////////////////////////////////////////////////////
//
@@ -1736,8 +1666,7 @@ static int stbi__getn(stbi__context * s, stbi_uc * buffer, int n) {
memcpy(buffer, s->img_buffer, blen);
- count = (s->io.read)(s->io_user_data, (char *) buffer + blen,
- n - blen);
+ count = (s->io.read)(s->io_user_data, (char *) buffer + blen, n - blen);
res = (count == (n - blen));
s->img_buffer = s->img_buffer_end;
return res;
@@ -1788,8 +1717,7 @@ static stbi__uint32 stbi__get32le(stbi__context * s) {
}
#endif
-#define STBI__BYTECAST(x) \
- ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
+#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) \
&& defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) \
@@ -1817,9 +1745,8 @@ static stbi_uc stbi__compute_y(int r, int g, int b) {
&& defined(STBI_NO_PNM)
// nothing
#else
-static unsigned char * stbi__convert_format(unsigned char * data, int img_n,
- int req_comp, unsigned int x,
- unsigned int y) {
+static unsigned char * stbi__convert_format(unsigned char * data, int img_n, int req_comp,
+ unsigned int x, unsigned int y) {
int i, j;
unsigned char * good;
@@ -1871,18 +1798,14 @@ static unsigned char * stbi__convert_format(unsigned char * data, int img_n,
dest[3] = 255;
}
break;
- STBI__CASE(3, 1) {
- dest[0] = stbi__compute_y(src[0], src[1], src[2]);
- }
+ STBI__CASE(3, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); }
break;
STBI__CASE(3, 2) {
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
dest[1] = 255;
}
break;
- STBI__CASE(4, 1) {
- dest[0] = stbi__compute_y(src[0], src[1], src[2]);
- }
+ STBI__CASE(4, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); }
break;
STBI__CASE(4, 2) {
dest[0] = stbi__compute_y(src[0], src[1], src[2]);
@@ -1899,8 +1822,7 @@ static unsigned char * stbi__convert_format(unsigned char * data, int img_n,
STBI_ASSERT(0);
STBI_FREE(data);
STBI_FREE(good);
- return stbi__errpuc("unsupported",
- "Unsupported format conversion");
+ return stbi__errpuc("unsupported", "Unsupported format conversion");
}
#undef STBI__CASE
}
@@ -1921,9 +1843,8 @@ static stbi__uint16 stbi__compute_y_16(int r, int g, int b) {
#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
// nothing
#else
-static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n,
- int req_comp, unsigned int x,
- unsigned int y) {
+static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n, int req_comp,
+ unsigned int x, unsigned int y) {
int i, j;
stbi__uint16 * good;
@@ -1975,18 +1896,14 @@ static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n,
dest[3] = 0xffff;
}
break;
- STBI__CASE(3, 1) {
- dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
- }
+ STBI__CASE(3, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); }
break;
STBI__CASE(3, 2) {
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
dest[1] = 0xffff;
}
break;
- STBI__CASE(4, 1) {
- dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
- }
+ STBI__CASE(4, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); }
break;
STBI__CASE(4, 2) {
dest[0] = stbi__compute_y_16(src[0], src[1], src[2]);
@@ -2003,8 +1920,8 @@ static stbi__uint16 * stbi__convert_format16(stbi__uint16 * data, int img_n,
STBI_ASSERT(0);
STBI_FREE(data);
STBI_FREE(good);
- return (stbi__uint16 *) stbi__errpuc(
- "unsupported", "Unsupported format conversion");
+ return (stbi__uint16 *) stbi__errpuc("unsupported",
+ "Unsupported format conversion");
}
#undef STBI__CASE
}
@@ -2029,9 +1946,8 @@ static float * stbi__ldr_to_hdr(stbi_uc * data, int x, int y, int comp) {
else n = comp - 1;
for (i = 0; i < x * y; ++i) {
for (k = 0; k < n; ++k) {
- output[i * comp + k]
- = (float) (pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma)
- * stbi__l2h_scale);
+ output[i * comp + k] = (float) (pow(data[i * comp + k] / 255.0f, stbi__l2h_gamma)
+ * stbi__l2h_scale);
}
}
if (n < comp) {
@@ -2060,10 +1976,9 @@ static stbi_uc * stbi__hdr_to_ldr(float * data, int x, int y, int comp) {
else n = comp - 1;
for (i = 0; i < x * y; ++i) {
for (k = 0; k < n; ++k) {
- float z = (float) pow(data[i * comp + k] * stbi__h2l_scale_i,
- stbi__h2l_gamma_i)
- * 255
- + 0.5f;
+ float z
+ = (float) pow(data[i * comp + k] * stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255
+ + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i * comp + k] = (stbi_uc) stbi__float2int(z);
@@ -2164,11 +2079,10 @@ typedef struct {
// kernels
void (*idct_block_kernel)(stbi_uc * out, int out_stride, short data[64]);
- void (*YCbCr_to_RGB_kernel)(stbi_uc * out, const stbi_uc * y,
- const stbi_uc * pcb, const stbi_uc * pcr,
- int count, int step);
- stbi_uc * (*resample_row_hv_2_kernel)(stbi_uc * out, stbi_uc * in_near,
- stbi_uc * in_far, int w, int hs);
+ void (*YCbCr_to_RGB_kernel)(stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb,
+ const stbi_uc * pcr, int count, int step);
+ stbi_uc * (*resample_row_hv_2_kernel)(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far,
+ int w, int hs);
} stbi__jpeg;
static int stbi__build_huffman(stbi__huffman * h, int * count) {
@@ -2191,8 +2105,7 @@ static int stbi__build_huffman(stbi__huffman * h, int * count) {
h->delta[j] = k - code;
if (h->size[k] == j) {
while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++);
- if (code - 1 >= (1u << j))
- return stbi__err("bad code lengths", "Corrupt JPEG");
+ if (code - 1 >= (1u << j)) return stbi__err("bad code lengths", "Corrupt JPEG");
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16 - j);
@@ -2230,14 +2143,12 @@ static void stbi__build_fast_ac(stbi__int16 * fast_ac, stbi__huffman * h) {
if (magbits && len + magbits <= FAST_BITS) {
// magnitude code followed by receive_extend code
- int k = ((i << len) & ((1 << FAST_BITS) - 1))
- >> (FAST_BITS - magbits);
+ int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
int m = 1 << (magbits - 1);
if (k < m) k += (~0U << magbits) + 1;
// if the result is small enough, we can fit it in fast_ac table
if (k >= -128 && k <= 127)
- fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16)
- + (len + magbits));
+ fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits));
}
}
}
@@ -2262,12 +2173,10 @@ static void stbi__grow_buffer_unsafe(stbi__jpeg * j) {
// (1 << n) - 1
static const stbi__uint32 stbi__bmask[17]
- = {0, 1, 3, 7, 15, 31, 63, 127, 255,
- 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535};
+ = {0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535};
// decode a jpeg huffman value from the bitstream
-stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j,
- stbi__huffman * h) {
+stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j, stbi__huffman * h) {
unsigned int temp;
int c, k;
@@ -2306,9 +2215,8 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j,
c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
if (c < 0 || c >= 256) // symbol id out of bounds!
return -1;
- STBI_ASSERT(
- (((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]])
- == h->code[c]);
+ STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]])
+ == h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
@@ -2317,9 +2225,8 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg * j,
}
// bias[n] = (-1<<n) + 1
-static const int stbi__jbias[16]
- = {0, -1, -3, -7, -15, -31, -63, -127,
- -255, -511, -1023, -2047, -4095, -8191, -16383, -32767};
+static const int stbi__jbias[16] = {0, -1, -3, -7, -15, -31, -63, -127,
+ -255, -511, -1023, -2047, -4095, -8191, -16383, -32767};
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
@@ -2366,17 +2273,15 @@ stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg * j) {
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static const stbi_uc stbi__jpeg_dezigzag[64 + 15]
- = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33,
- 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43,
- 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53,
- 60, 61, 54, 47, 55, 62, 63,
+ = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37,
+ 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
// decode one 64-entry block--
-static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64],
- stbi__huffman * hdc, stbi__huffman * hac,
- stbi__int16 * fac, int b,
+static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64], stbi__huffman * hdc,
+ stbi__huffman * hac, stbi__int16 * fac, int b,
stbi__uint16 * dequant) {
int diff, dc, k;
int t;
@@ -2409,9 +2314,8 @@ static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64],
k += (r >> 4) & 15; // run
s = r & 15; // combined length
if (s > j->code_bits)
- return stbi__err(
- "bad huffman code",
- "Combined length longer than code bits available");
+ return stbi__err("bad huffman code",
+ "Combined length longer than code bits available");
j->code_buffer <<= s;
j->code_bits -= s;
// decode into unzigzag'd location
@@ -2436,12 +2340,11 @@ static int stbi__jpeg_decode_block(stbi__jpeg * j, short data[64],
return 1;
}
-static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64],
- stbi__huffman * hdc, int b) {
+static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64], stbi__huffman * hdc,
+ int b) {
int diff, dc;
int t;
- if (j->spec_end != 0)
- return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
@@ -2449,8 +2352,7 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64],
// first scan for DC coefficient, must be first
memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now
t = stbi__jpeg_huff_decode(j, hdc);
- if (t < 0 || t > 15)
- return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
diff = t ? stbi__extend_receive(j, t) : 0;
if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff))
@@ -2469,12 +2371,10 @@ static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg * j, short data[64],
// @OPTIMIZE: store non-zigzagged during the decode passes,
// and only de-zigzag when dequantizing
-static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64],
- stbi__huffman * hac,
+static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64], stbi__huffman * hac,
stbi__int16 * fac) {
int k;
- if (j->spec_start == 0)
- return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
if (j->succ_high == 0) {
int shift = j->succ_low;
@@ -2495,17 +2395,15 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64],
k += (r >> 4) & 15; // run
s = r & 15; // combined length
if (s > j->code_bits)
- return stbi__err(
- "bad huffman code",
- "Combined length longer than code bits available");
+ return stbi__err("bad huffman code",
+ "Combined length longer than code bits available");
j->code_buffer <<= s;
j->code_bits -= s;
zig = stbi__jpeg_dezigzag[k++];
data[zig] = (short) ((r >> 8) * (1 << shift));
} else {
int rs = stbi__jpeg_huff_decode(j, hac);
- if (rs < 0)
- return stbi__err("bad huffman code", "Corrupt JPEG");
+ if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
@@ -2519,8 +2417,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64],
} else {
k += r;
zig = stbi__jpeg_dezigzag[k++];
- data[zig]
- = (short) (stbi__extend_receive(j, s) * (1 << shift));
+ data[zig] = (short) (stbi__extend_receive(j, s) * (1 << shift));
}
}
} while (k <= j->spec_end);
@@ -2547,8 +2444,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64],
int rs = stbi__jpeg_huff_decode(
j,
hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
- if (rs < 0)
- return stbi__err("bad huffman code", "Corrupt JPEG");
+ if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
@@ -2562,8 +2458,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg * j, short data[64],
// so we don't have to do anything special here
}
} else {
- if (s != 1)
- return stbi__err("bad huffman code", "Corrupt JPEG");
+ if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
// sign bit
if (stbi__jpeg_get_bit(j)) s = bit;
else s = -bit;
@@ -2651,15 +2546,14 @@ static void stbi__idct_block(stbi_uc * out, int out_stride, short data[64]) {
// columns
for (i = 0; i < 8; ++i, ++d, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
- if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0
- && d[48] == 0 && d[56] == 0) {
+ if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 && d[40] == 0 && d[48] == 0
+ && d[56] == 0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * 4;
- v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56]
- = dcterm;
+ v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56])
// constants scaled things up by 1<<12; let's bring them back
@@ -2729,10 +2623,8 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) {
// out = in << 12 (in 16-bit, out 32-bit)
#define dct_widen(out, in) \
- __m128i out##_l \
- = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
- __m128i out##_h \
- = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
+ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
+ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
// wide add
#define dct_wadd(out, a, b) \
@@ -2751,10 +2643,8 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) {
__m128i abiased_h = _mm_add_epi32(a##_h, bias); \
dct_wadd(sum, abiased, b); \
dct_wsub(dif, abiased, b); \
- out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), \
- _mm_srai_epi32(sum_h, s)); \
- out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), \
- _mm_srai_epi32(dif_h, s)); \
+ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
+ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
}
// 8-bit interleave step (for transposes)
@@ -2798,28 +2688,21 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) {
}
__m128i rot0_0
- = dct_const(stbi__f2f(0.5411961f),
- stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
- __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f),
- stbi__f2f(0.5411961f));
- __m128i rot1_0
- = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f),
- stbi__f2f(1.175875602f));
- __m128i rot1_1
- = dct_const(stbi__f2f(1.175875602f),
- stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
- __m128i rot2_0
- = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f),
- stbi__f2f(-1.961570560f));
- __m128i rot2_1
- = dct_const(stbi__f2f(-1.961570560f),
- stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f));
- __m128i rot3_0
- = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f),
- stbi__f2f(-0.390180644f));
- __m128i rot3_1
- = dct_const(stbi__f2f(-0.390180644f),
- stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f));
+ = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
+ __m128i rot0_1
+ = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f));
+ __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f),
+ stbi__f2f(1.175875602f));
+ __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f),
+ stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
+ __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f),
+ stbi__f2f(-1.961570560f));
+ __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f),
+ stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f));
+ __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f),
+ stbi__f2f(-0.390180644f));
+ __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f),
+ stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f));
// rounding biases in column/row passes, see stbi__idct_block for explanation.
__m128i bias_0 = _mm_set1_epi32(512);
@@ -3030,8 +2913,7 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) {
}
#define dct_trn32(x, y) \
{ \
- int32x4x2_t t \
- = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \
+ int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); \
x = vreinterpretq_s16_s32(t.val[0]); \
y = vreinterpretq_s16_s32(t.val[1]); \
}
@@ -3092,15 +2974,13 @@ static void stbi__idct_simd(stbi_uc * out, int out_stride, short data[64]) {
}
#define dct_trn8_16(x, y) \
{ \
- uint16x4x2_t t \
- = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \
+ uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); \
x = vreinterpret_u8_u16(t.val[0]); \
y = vreinterpret_u8_u16(t.val[1]); \
}
#define dct_trn8_32(x, y) \
{ \
- uint32x2x2_t t \
- = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \
+ uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); \
x = vreinterpret_u8_u32(t.val[0]); \
y = vreinterpret_u8_u32(t.val[1]); \
}
@@ -3211,14 +3091,13 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) {
for (j = 0; j < h; ++j) {
for (i = 0; i < w; ++i) {
int ha = z->img_comp[n].ha;
- if (!stbi__jpeg_decode_block(
- z, data, z->huff_dc + z->img_comp[n].hd,
- z->huff_ac + ha, z->fast_ac[ha], n,
- z->dequant[z->img_comp[n].tq]))
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd,
+ z->huff_ac + ha, z->fast_ac[ha], n,
+ z->dequant[z->img_comp[n].tq]))
return 0;
- z->idct_block_kernel(
- z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8,
- z->img_comp[n].w2, data);
+ z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8
+ + i * 8,
+ z->img_comp[n].w2, data);
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
@@ -3245,15 +3124,14 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) {
int x2 = (i * z->img_comp[n].h + x) * 8;
int y2 = (j * z->img_comp[n].v + y) * 8;
int ha = z->img_comp[n].ha;
- if (!stbi__jpeg_decode_block(
- z, data, z->huff_dc + z->img_comp[n].hd,
- z->huff_ac + ha, z->fast_ac[ha], n,
- z->dequant[z->img_comp[n].tq]))
+ if (!stbi__jpeg_decode_block(z, data,
+ z->huff_dc + z->img_comp[n].hd,
+ z->huff_ac + ha, z->fast_ac[ha],
+ n, z->dequant[z->img_comp[n].tq]))
return 0;
- z->idct_block_kernel(
- z->img_comp[n].data + z->img_comp[n].w2 * y2
- + x2,
- z->img_comp[n].w2, data);
+ z->idct_block_kernel(z->img_comp[n].data
+ + z->img_comp[n].w2 * y2 + x2,
+ z->img_comp[n].w2, data);
}
}
}
@@ -3280,16 +3158,16 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) {
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j) {
for (i = 0; i < w; ++i) {
- short * data = z->img_comp[n].coeff
- + 64 * (i + j * z->img_comp[n].coeff_w);
+ short * data
+ = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
if (z->spec_start == 0) {
if (!stbi__jpeg_decode_block_prog_dc(
z, data, &z->huff_dc[z->img_comp[n].hd], n))
return 0;
} else {
int ha = z->img_comp[n].ha;
- if (!stbi__jpeg_decode_block_prog_ac(
- z, data, &z->huff_ac[ha], z->fast_ac[ha]))
+ if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha],
+ z->fast_ac[ha]))
return 0;
}
// every data block is an MCU, so countdown the restart interval
@@ -3314,12 +3192,10 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg * z) {
for (x = 0; x < z->img_comp[n].h; ++x) {
int x2 = (i * z->img_comp[n].h + x);
int y2 = (j * z->img_comp[n].v + y);
- short * data
- = z->img_comp[n].coeff
- + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
+ short * data = z->img_comp[n].coeff
+ + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
if (!stbi__jpeg_decode_block_prog_dc(
- z, data, &z->huff_dc[z->img_comp[n].hd],
- n))
+ z, data, &z->huff_dc[z->img_comp[n].hd], n))
return 0;
}
}
@@ -3352,12 +3228,12 @@ static void stbi__jpeg_finish(stbi__jpeg * z) {
int h = (z->img_comp[n].y + 7) >> 3;
for (j = 0; j < h; ++j) {
for (i = 0; i < w; ++i) {
- short * data = z->img_comp[n].coeff
- + 64 * (i + j * z->img_comp[n].coeff_w);
+ short * data
+ = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
- z->idct_block_kernel(
- z->img_comp[n].data + z->img_comp[n].w2 * j * 8 + i * 8,
- z->img_comp[n].w2, data);
+ z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2 * j * 8
+ + i * 8,
+ z->img_comp[n].w2, data);
}
}
}
@@ -3371,8 +3247,7 @@ static int stbi__process_marker(stbi__jpeg * z, int m) {
return stbi__err("expected marker", "Corrupt JPEG");
case 0xDD: // DRI - specify restart interval
- if (stbi__get16be(z->s) != 4)
- return stbi__err("bad DRI len", "Corrupt JPEG");
+ if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len", "Corrupt JPEG");
z->restart_interval = stbi__get16be(z->s);
return 1;
@@ -3382,14 +3257,12 @@ static int stbi__process_marker(stbi__jpeg * z, int m) {
int q = stbi__get8(z->s);
int p = q >> 4, sixteen = (p != 0);
int t = q & 15, i;
- if (p != 0 && p != 1)
- return stbi__err("bad DQT type", "Corrupt JPEG");
+ if (p != 0 && p != 1) return stbi__err("bad DQT type", "Corrupt JPEG");
if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG");
for (i = 0; i < 64; ++i)
z->dequant[t][stbi__jpeg_dezigzag[i]]
- = (stbi__uint16) (sixteen ? stbi__get16be(z->s)
- : stbi__get8(z->s));
+ = (stbi__uint16) (sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));
L -= (sixteen ? 129 : 65);
}
return L == 0;
@@ -3402,8 +3275,7 @@ static int stbi__process_marker(stbi__jpeg * z, int m) {
int q = stbi__get8(z->s);
int tc = q >> 4;
int th = q & 15;
- if (tc > 1 || th > 3)
- return stbi__err("bad DHT header", "Corrupt JPEG");
+ if (tc > 1 || th > 3) return stbi__err("bad DHT header", "Corrupt JPEG");
for (i = 0; i < 16; ++i) {
sizes[i] = stbi__get8(z->s);
n += sizes[i];
@@ -3421,8 +3293,7 @@ static int stbi__process_marker(stbi__jpeg * z, int m) {
v = z->huff_ac[th].values;
}
for (i = 0; i < n; ++i) v[i] = stbi__get8(z->s);
- if (tc != 0)
- stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
+ if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
L -= n;
}
return L == 0;
@@ -3475,8 +3346,7 @@ static int stbi__process_scan_header(stbi__jpeg * z) {
z->scan_n = stbi__get8(z->s);
if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n)
return stbi__err("bad SOS component count", "Corrupt JPEG");
- if (Ls != 6 + 2 * z->scan_n)
- return stbi__err("bad SOS len", "Corrupt JPEG");
+ if (Ls != 6 + 2 * z->scan_n) return stbi__err("bad SOS len", "Corrupt JPEG");
for (i = 0; i < z->scan_n; ++i) {
int id = stbi__get8(z->s), which;
int q = stbi__get8(z->s);
@@ -3484,11 +3354,9 @@ static int stbi__process_scan_header(stbi__jpeg * z) {
if (z->img_comp[which].id == id) break;
if (which == z->s->img_n) return 0; // no match
z->img_comp[which].hd = q >> 4;
- if (z->img_comp[which].hd > 3)
- return stbi__err("bad DC huff", "Corrupt JPEG");
+ if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff", "Corrupt JPEG");
z->img_comp[which].ha = q & 15;
- if (z->img_comp[which].ha > 3)
- return stbi__err("bad AC huff", "Corrupt JPEG");
+ if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff", "Corrupt JPEG");
z->order[i] = which;
}
@@ -3500,9 +3368,8 @@ static int stbi__process_scan_header(stbi__jpeg * z) {
z->succ_high = (aa >> 4);
z->succ_low = (aa & 15);
if (z->progressive) {
- if (z->spec_start > 63 || z->spec_end > 63
- || z->spec_start > z->spec_end || z->succ_high > 13
- || z->succ_low > 13)
+ if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end
+ || z->succ_high > 13 || z->succ_low > 13)
return stbi__err("bad SOS", "Corrupt JPEG");
} else {
if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG");
@@ -3543,24 +3410,21 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) {
if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG
p = stbi__get8(s);
if (p != 8)
- return stbi__err(
- "only 8-bit",
- "JPEG format not supported: 8-bit only"); // JPEG baseline
+ return stbi__err("only 8-bit",
+ "JPEG format not supported: 8-bit only"); // JPEG baseline
s->img_y = stbi__get16be(s);
if (s->img_y == 0)
return stbi__err(
"no header height",
"JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
s->img_x = stbi__get16be(s);
- if (s->img_x == 0)
- return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires
+ if (s->img_x == 0) return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires
if (s->img_y > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS)
return stbi__err("too large", "Very large image (corrupt?)");
c = stbi__get8(s);
- if (c != 3 && c != 1 && c != 4)
- return stbi__err("bad component count", "Corrupt JPEG");
+ if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count", "Corrupt JPEG");
s->img_n = c;
for (i = 0; i < c; ++i) {
z->img_comp[i].data = NULL;
@@ -3598,10 +3462,8 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) {
// check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios
// and I've never seen a non-corrupted JPEG file actually use them
for (i = 0; i < s->img_n; ++i) {
- if (h_max % z->img_comp[i].h != 0)
- return stbi__err("bad H", "Corrupt JPEG");
- if (v_max % z->img_comp[i].v != 0)
- return stbi__err("bad V", "Corrupt JPEG");
+ if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H", "Corrupt JPEG");
+ if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V", "Corrupt JPEG");
}
// compute interleaved mcu info
@@ -3629,25 +3491,22 @@ static int stbi__process_frame_header(stbi__jpeg * z, int scan) {
z->img_comp[i].coeff = 0;
z->img_comp[i].raw_coeff = 0;
z->img_comp[i].linebuf = NULL;
- z->img_comp[i].raw_data
- = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
+ z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
if (z->img_comp[i].raw_data == NULL)
- return stbi__free_jpeg_components(
- z, i + 1, stbi__err("outofmem", "Out of memory"));
+ return stbi__free_jpeg_components(z, i + 1,
+ stbi__err("outofmem", "Out of memory"));
// align blocks for idct using mmx/sse
- z->img_comp[i].data
- = (stbi_uc *) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
+ z->img_comp[i].data = (stbi_uc *) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
if (z->progressive) {
// w2, h2 are multiples of 8 (see above)
z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
- z->img_comp[i].raw_coeff = stbi__malloc_mad3(
- z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
+ z->img_comp[i].raw_coeff
+ = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
if (z->img_comp[i].raw_coeff == NULL)
- return stbi__free_jpeg_components(
- z, i + 1, stbi__err("outofmem", "Out of memory"));
- z->img_comp[i].coeff
- = (short *) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
+ return stbi__free_jpeg_components(z, i + 1,
+ stbi__err("outofmem", "Out of memory"));
+ z->img_comp[i].coeff = (short *) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
}
}
@@ -3731,8 +3590,7 @@ static int stbi__decode_jpeg_image(stbi__jpeg * j) {
int Ld = stbi__get16be(j->s);
stbi__uint32 NL = stbi__get16be(j->s);
if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG");
- if (NL != j->s->img_y)
- return stbi__err("bad DNL height", "Corrupt JPEG");
+ if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG");
m = stbi__get_marker(j);
} else {
if (!stbi__process_marker(j, m)) return 1;
@@ -3745,13 +3603,13 @@ static int stbi__decode_jpeg_image(stbi__jpeg * j) {
// static jfif-centered resampling (across block boundaries)
-typedef stbi_uc * (*resample_row_func)(stbi_uc * out, stbi_uc * in0,
- stbi_uc * in1, int w, int hs);
+typedef stbi_uc * (*resample_row_func)(stbi_uc * out, stbi_uc * in0, stbi_uc * in1, int w,
+ int hs);
#define stbi__div4(x) ((stbi_uc) ((x) >> 2))
-static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near,
- stbi_uc * in_far, int w, int hs) {
+static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far, int w,
+ int hs) {
STBI_NOTUSED(out);
STBI_NOTUSED(in_far);
STBI_NOTUSED(w);
@@ -3759,8 +3617,8 @@ static stbi_uc * resample_row_1(stbi_uc * out, stbi_uc * in_near,
return in_near;
}
-static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near,
- stbi_uc * in_far, int w, int hs) {
+static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far,
+ int w, int hs) {
// need to generate two samples vertically for every one in input
int i;
STBI_NOTUSED(hs);
@@ -3768,8 +3626,8 @@ static stbi_uc * stbi__resample_row_v_2(stbi_uc * out, stbi_uc * in_near,
return out;
}
-static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near,
- stbi_uc * in_far, int w, int hs) {
+static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far,
+ int w, int hs) {
// need to generate two samples horizontally for every one in input
int i;
stbi_uc * input = in_near;
@@ -3798,8 +3656,8 @@ static stbi_uc * stbi__resample_row_h_2(stbi_uc * out, stbi_uc * in_near,
#define stbi__div16(x) ((stbi_uc) ((x) >> 4))
-static stbi_uc * stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near,
- stbi_uc * in_far, int w, int hs) {
+static stbi_uc * stbi__resample_row_hv_2(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far,
+ int w, int hs) {
// need to generate 2x2 samples for every one in input
int i, t0, t1;
if (w == 1) {
@@ -3858,8 +3716,7 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near,
__m128i prv0 = _mm_slli_si128(curr, 2);
__m128i nxt0 = _mm_srli_si128(curr, 2);
__m128i prev = _mm_insert_epi16(prv0, t1, 0);
- __m128i next
- = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7);
+ __m128i next = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7);
// horizontal filter, polyphase implementation since it's convenient:
// even pixels = 3*cur + prev = cur*4 + (prev - cur)
@@ -3899,8 +3756,7 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near,
int16x8_t prv0 = vextq_s16(curr, curr, 7);
int16x8_t nxt0 = vextq_s16(curr, curr, 1);
int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
- int16x8_t next
- = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7);
+ int16x8_t next = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7);
// horizontal filter, polyphase implementation since it's convenient:
// even pixels = 3*cur + prev = cur*4 + (prev - cur)
@@ -3941,8 +3797,8 @@ static stbi_uc * stbi__resample_row_hv_2_simd(stbi_uc * out, stbi_uc * in_near,
}
#endif
-static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near,
- stbi_uc * in_far, int w, int hs) {
+static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near, stbi_uc * in_far,
+ int w, int hs) {
// resample with nearest-neighbor
int i, j;
STBI_NOTUSED(in_far);
@@ -3954,9 +3810,8 @@ static stbi_uc * stbi__resample_row_generic(stbi_uc * out, stbi_uc * in_near,
// this is a reduced-precision calculation of YCbCr-to-RGB introduced
// to make sure the code produces the same results in both SIMD and scalar
#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8)
-static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y,
- const stbi_uc * pcb, const stbi_uc * pcr,
- int count, int step) {
+static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y, const stbi_uc * pcb,
+ const stbi_uc * pcr, int count, int step) {
int i;
for (i = 0; i < count; ++i) {
int y_fixed = (y[i] << 20) + (1 << 19); // rounding
@@ -3991,9 +3846,8 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc * out, const stbi_uc * y,
}
#if defined(STBI_SSE2) || defined(STBI_NEON)
-static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y,
- stbi_uc const * pcb, stbi_uc const * pcr,
- int count, int step) {
+static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y, stbi_uc const * pcb,
+ stbi_uc const * pcr, int count, int step) {
int i = 0;
#ifdef STBI_SSE2
@@ -4004,10 +3858,8 @@ static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y,
// this is a fairly straightforward implementation and not super-optimized.
__m128i signflip = _mm_set1_epi8(-0x80);
__m128i cr_const0 = _mm_set1_epi16((short) (1.40200f * 4096.0f + 0.5f));
- __m128i cr_const1
- = _mm_set1_epi16(-(short) (0.71414f * 4096.0f + 0.5f));
- __m128i cb_const0
- = _mm_set1_epi16(-(short) (0.34414f * 4096.0f + 0.5f));
+ __m128i cr_const1 = _mm_set1_epi16(-(short) (0.71414f * 4096.0f + 0.5f));
+ __m128i cb_const0 = _mm_set1_epi16(-(short) (0.34414f * 4096.0f + 0.5f));
__m128i cb_const1 = _mm_set1_epi16((short) (1.77200f * 4096.0f + 0.5f));
__m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);
__m128i xw = _mm_set1_epi16(255); // alpha channel
@@ -4074,10 +3926,8 @@ static void stbi__YCbCr_to_RGB_simd(stbi_uc * out, stbi_uc const * y,
uint8x8_t y_bytes = vld1_u8(y + i);
uint8x8_t cr_bytes = vld1_u8(pcr + i);
uint8x8_t cb_bytes = vld1_u8(pcb + i);
- int8x8_t cr_biased
- = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
- int8x8_t cb_biased
- = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
+ int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
+ int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
// expand to s16
int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
@@ -4181,14 +4031,13 @@ static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) {
return (stbi_uc) ((t + (t >> 8)) >> 8);
}
-static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
- int * comp, int req_comp) {
+static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y, int * comp,
+ int req_comp) {
int n, decode_n, is_rgb;
z->s->img_n = 0; // make stbi__cleanup_jpeg safe
// validate req_comp
- if (req_comp < 0 || req_comp > 4)
- return stbi__errpuc("bad req_comp", "Internal error");
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
// load a jpeg image from whichever source, but leave in YCbCr format
if (!stbi__decode_jpeg_image(z)) {
@@ -4199,8 +4048,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
// determine actual number of components to generate
n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1;
- is_rgb = z->s->img_n == 3
- && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
+ is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1;
else decode_n = z->s->img_n;
@@ -4240,12 +4088,9 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
r->line0 = r->line1 = z->img_comp[k].data;
if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
- else if (r->hs == 1 && r->vs == 2)
- r->resample = stbi__resample_row_v_2;
- else if (r->hs == 2 && r->vs == 1)
- r->resample = stbi__resample_row_h_2;
- else if (r->hs == 2 && r->vs == 2)
- r->resample = z->resample_row_hv_2_kernel;
+ else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
+ else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
+ else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;
else r->resample = stbi__resample_row_generic;
}
@@ -4262,14 +4107,12 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
for (k = 0; k < decode_n; ++k) {
stbi__resample * r = &res_comp[k];
int y_bot = r->ystep >= (r->vs >> 1);
- coutput[k] = r->resample(
- z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0,
- y_bot ? r->line0 : r->line1, r->w_lores, r->hs);
+ coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0,
+ y_bot ? r->line0 : r->line1, r->w_lores, r->hs);
if (++r->ystep >= r->vs) {
r->ystep = 0;
r->line0 = r->line1;
- if (++r->ypos < z->img_comp[k].y)
- r->line1 += z->img_comp[k].w2;
+ if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2;
}
}
if (n >= 3) {
@@ -4284,8 +4127,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
out += n;
}
} else {
- z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2],
- z->s->img_x, n);
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
}
} else if (z->s->img_n == 4) {
if (z->app14_color_transform == 0) { // CMYK
@@ -4298,8 +4140,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
out += n;
}
} else if (z->app14_color_transform == 2) { // YCCK
- z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2],
- z->s->img_x, n);
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
for (i = 0; i < z->s->img_x; ++i) {
stbi_uc m = coutput[3][i];
out[0] = stbi__blinn_8x8(255 - out[0], m);
@@ -4308,8 +4149,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
out += n;
}
} else { // YCbCr + alpha? Ignore the fourth channel for now
- z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2],
- z->s->img_x, n);
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
}
} else
for (i = 0; i < z->s->img_x; ++i) {
@@ -4321,12 +4161,12 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
if (is_rgb) {
if (n == 1)
for (i = 0; i < z->s->img_x; ++i)
- *out++ = stbi__compute_y(
- coutput[0][i], coutput[1][i], coutput[2][i]);
+ *out++
+ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
else {
for (i = 0; i < z->s->img_x; ++i, out += 2) {
- out[0] = stbi__compute_y(
- coutput[0][i], coutput[1][i], coutput[2][i]);
+ out[0]
+ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
out[1] = 255;
}
}
@@ -4342,8 +4182,7 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
}
} else if (z->s->img_n == 4 && z->app14_color_transform == 2) {
for (i = 0; i < z->s->img_x; ++i) {
- out[0] = stbi__blinn_8x8(255 - coutput[0][i],
- coutput[3][i]);
+ out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);
out[1] = 255;
out += n;
}
@@ -4362,16 +4201,13 @@ static stbi_uc * load_jpeg_image(stbi__jpeg * z, int * out_x, int * out_y,
stbi__cleanup_jpeg(z);
*out_x = z->s->img_x;
*out_y = z->s->img_y;
- if (comp)
- *comp = z->s->img_n >= 3
- ? 3
- : 1; // report original components, not output
+ if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output
return output;
}
}
-static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__jpeg_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
unsigned char * result;
stbi__jpeg * j = (stbi__jpeg *) stbi__malloc(sizeof(stbi__jpeg));
if (!j) return stbi__errpuc("outofmem", "Out of memory");
@@ -4460,8 +4296,7 @@ stbi_inline static int stbi__bit_reverse(int v, int bits) {
return stbi__bitreverse16(v) >> (16 - bits);
}
-static int stbi__zbuild_huffman(stbi__zhuffman * z, const stbi_uc * sizelist,
- int num) {
+static int stbi__zbuild_huffman(stbi__zhuffman * z, const stbi_uc * sizelist, int num) {
int i, k = 0;
int code, next_code[16], sizes[17];
@@ -4479,8 +4314,7 @@ static int stbi__zbuild_huffman(stbi__zhuffman * z, const stbi_uc * sizelist,
z->firstsymbol[i] = (stbi__uint16) k;
code = (code + sizes[i]);
if (sizes[i])
- if (code - 1 >= (1 << i))
- return stbi__err("bad codelengths", "Corrupt PNG");
+ if (code - 1 >= (1 << i)) return stbi__err("bad codelengths", "Corrupt PNG");
z->maxcode[i] = code << (16 - i); // preshift for inner loop
code <<= 1;
k += sizes[i];
@@ -4526,9 +4360,7 @@ typedef struct {
stbi__zhuffman z_length, z_distance;
} stbi__zbuf;
-stbi_inline static int stbi__zeof(stbi__zbuf * z) {
- return (z->zbuffer >= z->zbuffer_end);
-}
+stbi_inline static int stbi__zeof(stbi__zbuf * z) { return (z->zbuffer >= z->zbuffer_end); }
stbi_inline static stbi_uc stbi__zget8(stbi__zbuf * z) {
return stbi__zeof(z) ? 0 : *z->zbuffer++;
@@ -4565,15 +4397,13 @@ static int stbi__zhuffman_decode_slowpath(stbi__zbuf * a, stbi__zhuffman * z) {
// code size is s, so:
b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s];
if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!
- if (z->size[b] != s)
- return -1; // was originally an assert, but report failure instead.
+ if (z->size[b] != s) return -1; // was originally an assert, but report failure instead.
a->code_buffer >>= s;
a->num_bits -= s;
return z->value[b];
}
-stbi_inline static int stbi__zhuffman_decode(stbi__zbuf * a,
- stbi__zhuffman * z) {
+stbi_inline static int stbi__zhuffman_decode(stbi__zbuf * a, stbi__zhuffman * z) {
int b, s;
if (a->num_bits < 16) {
if (stbi__zeof(a)) {
@@ -4608,12 +4438,10 @@ static int stbi__zexpand(stbi__zbuf * z, char * zout,
char * q;
unsigned int cur, limit, old_limit;
z->zout = zout;
- if (!z->z_expandable)
- return stbi__err("output buffer limit", "Corrupt PNG");
+ if (!z->z_expandable) return stbi__err("output buffer limit", "Corrupt PNG");
cur = (unsigned int) (z->zout - z->zout_start);
limit = old_limit = (unsigned) (z->zout_end - z->zout_start);
- if (UINT_MAX - cur < (unsigned) n)
- return stbi__err("outofmem", "Out of memory");
+ if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory");
while (cur + n > limit) {
if (limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory");
limit *= 2;
@@ -4631,18 +4459,16 @@ static const int stbi__zlength_base[31]
= {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
-static const int stbi__zlength_extra[31]
- = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
- 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0};
+static const int stbi__zlength_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
+ 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0};
static const int stbi__zdist_base[32]
= {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
-static const int stbi__zdist_extra[32]
- = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6,
- 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
+static const int stbi__zdist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6,
+ 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
static int stbi__parse_huffman_block(stbi__zbuf * a) {
char * zout = a->zout;
@@ -4677,18 +4503,15 @@ static int stbi__parse_huffman_block(stbi__zbuf * a) {
"Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data
z -= 257;
len = stbi__zlength_base[z];
- if (stbi__zlength_extra[z])
- len += stbi__zreceive(a, stbi__zlength_extra[z]);
+ if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
z = stbi__zhuffman_decode(a, &a->z_distance);
if (z < 0 || z >= 30)
return stbi__err(
"bad huffman code",
"Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data
dist = stbi__zdist_base[z];
- if (stbi__zdist_extra[z])
- dist += stbi__zreceive(a, stbi__zdist_extra[z]);
- if (zout - a->zout_start < dist)
- return stbi__err("bad dist", "Corrupt PNG");
+ if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
+ if (zout - a->zout_start < dist) return stbi__err("bad dist", "Corrupt PNG");
if (len > a->zout_end - zout) {
if (!stbi__zexpand(a, zout, len)) return 0;
zout = a->zout;
@@ -4733,8 +4556,7 @@ static int stbi__compute_huffman_codes(stbi__zbuf * a) {
n = 0;
while (n < ntot) {
int c = stbi__zhuffman_decode(a, &z_codelength);
- if (c < 0 || c >= 19)
- return stbi__err("bad codelengths", "Corrupt PNG");
+ if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
if (c < 16) lencodes[n++] = (stbi_uc) c;
else {
stbi_uc fill = 0;
@@ -4749,8 +4571,7 @@ static int stbi__compute_huffman_codes(stbi__zbuf * a) {
} else {
return stbi__err("bad codelengths", "Corrupt PNG");
}
- if (ntot - n < c)
- return stbi__err("bad codelengths", "Corrupt PNG");
+ if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
memset(lencodes + n, fill, c);
n += c;
}
@@ -4768,8 +4589,7 @@ static int stbi__parse_uncompressed_block(stbi__zbuf * a) {
// drain the bit-packed data into header
k = 0;
while (a->num_bits > 0) {
- header[k++]
- = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
+ header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
a->code_buffer >>= 8;
a->num_bits -= 8;
}
@@ -4779,8 +4599,7 @@ static int stbi__parse_uncompressed_block(stbi__zbuf * a) {
len = header[1] * 256 + header[0];
nlen = header[3] * 256 + header[2];
if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG");
- if (a->zbuffer + len > a->zbuffer_end)
- return stbi__err("read past buffer", "Corrupt PNG");
+ if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer", "Corrupt PNG");
if (a->zout + len > a->zout_end)
if (!stbi__zexpand(a, a->zout, len)) return 0;
memcpy(a->zout, a->zbuffer, len);
@@ -4794,8 +4613,7 @@ static int stbi__parse_zlib_header(stbi__zbuf * a) {
int cm = cmf & 15;
/* int cinfo = cmf >> 4; */
int flg = stbi__zget8(a);
- if (stbi__zeof(a))
- return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec
+ if (stbi__zeof(a)) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec
if ((cmf * 256 + flg) % 31 != 0)
return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec
if (flg & 32)
@@ -4809,18 +4627,16 @@ static int stbi__parse_zlib_header(stbi__zbuf * a) {
}
static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS]
- = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
- 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7,
- 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8};
+ = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7,
+ 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8};
static const stbi_uc stbi__zdefault_distance[32]
= {5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
@@ -4854,11 +4670,9 @@ static int stbi__parse_zlib(stbi__zbuf * a, int parse_header) {
} else {
if (type == 1) {
// use fixed code lengths
- if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length,
- STBI__ZNSYMS))
+ if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, STBI__ZNSYMS))
return 0;
- if (!stbi__zbuild_huffman(&a->z_distance,
- stbi__zdefault_distance, 32))
+ if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32))
return 0;
} else {
if (!stbi__compute_huffman_codes(a)) return 0;
@@ -4869,8 +4683,7 @@ static int stbi__parse_zlib(stbi__zbuf * a, int parse_header) {
return 1;
}
-static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp,
- int parse_header) {
+static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp, int parse_header) {
a->zout_start = obuf;
a->zout = obuf;
a->zout_end = obuf + olen;
@@ -4880,8 +4693,7 @@ static int stbi__do_zlib(stbi__zbuf * a, char * obuf, int olen, int exp,
}
STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len,
- int initial_size,
- int * outlen) {
+ int initial_size, int * outlen) {
stbi__zbuf a;
char * p = (char *) stbi__malloc(initial_size);
if (p == NULL) return NULL;
@@ -4896,15 +4708,12 @@ STBIDEF char * stbi_zlib_decode_malloc_guesssize(const char * buffer, int len,
}
}
-STBIDEF char * stbi_zlib_decode_malloc(char const * buffer, int len,
- int * outlen) {
+STBIDEF char * stbi_zlib_decode_malloc(char const * buffer, int len, int * outlen) {
return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
}
-STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer,
- int len,
- int initial_size,
- int * outlen,
+STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer, int len,
+ int initial_size, int * outlen,
int parse_header) {
stbi__zbuf a;
char * p = (char *) stbi__malloc(initial_size);
@@ -4920,18 +4729,15 @@ STBIDEF char * stbi_zlib_decode_malloc_guesssize_headerflag(const char * buffer,
}
}
-STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen,
- char const * ibuffer, int ilen) {
+STBIDEF int stbi_zlib_decode_buffer(char * obuffer, int olen, char const * ibuffer, int ilen) {
stbi__zbuf a;
a.zbuffer = (stbi_uc *) ibuffer;
a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
- if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
- return (int) (a.zout - a.zout_start);
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start);
else return -1;
}
-STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len,
- int * outlen) {
+STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len, int * outlen) {
stbi__zbuf a;
char * p = (char *) stbi__malloc(16384);
if (p == NULL) return NULL;
@@ -4946,13 +4752,12 @@ STBIDEF char * stbi_zlib_decode_noheader_malloc(char const * buffer, int len,
}
}
-STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen,
- const char * ibuffer, int ilen) {
+STBIDEF int stbi_zlib_decode_noheader_buffer(char * obuffer, int olen, const char * ibuffer,
+ int ilen) {
stbi__zbuf a;
a.zbuffer = (stbi_uc *) ibuffer;
a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
- if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
- return (int) (a.zout - a.zout_start);
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start);
else return -1;
}
#endif
@@ -4984,8 +4789,7 @@ static int stbi__check_png_header(stbi__context * s) {
static const stbi_uc png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
int i;
for (i = 0; i < 8; ++i)
- if (stbi__get8(s) != png_sig[i])
- return stbi__err("bad png sig", "Not a PNG");
+ if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig", "Not a PNG");
return 1;
}
@@ -5022,14 +4826,13 @@ static int stbi__paeth(int a, int b, int c) {
return t1;
}
-static const stbi_uc stbi__depth_scale_table[9]
- = {0, 0xff, 0x55, 0, 0x11, 0, 0, 0, 0x01};
+static const stbi_uc stbi__depth_scale_table[9] = {0, 0xff, 0x55, 0, 0x11, 0, 0, 0, 0x01};
// adds an extra all-255 alpha channel
// dest == src is legal
// img_n must be 1 or 3
-static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src,
- stbi__uint32 x, int img_n) {
+static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src, stbi__uint32 x,
+ int img_n) {
int i;
// must process data backwards since we allow dest==src
if (img_n == 1) {
@@ -5049,9 +4852,8 @@ static void stbi__create_png_alpha_expand8(stbi_uc * dest, stbi_uc * src,
}
// create the png data from post-deflated data
-static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw,
- stbi__uint32 raw_len, int out_n,
- stbi__uint32 x, stbi__uint32 y, int depth,
+static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw, stbi__uint32 raw_len,
+ int out_n, stbi__uint32 x, stbi__uint32 y, int depth,
int color) {
int bytes = (depth == 16 ? 2 : 1);
stbi__context * s = a->s;
@@ -5067,8 +4869,8 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw,
int width = x;
STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1);
- a->out = (stbi_uc *) stbi__malloc_mad3(
- x, y, output_bytes, 0); // extra bytes to write off the end into
+ a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes,
+ 0); // extra bytes to write off the end into
if (!a->out) return stbi__err("outofmem", "Out of memory");
// note: error exits here don't need to clean up a->out individually,
@@ -5123,32 +4925,28 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw,
cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]);
break;
case STBI__F_up:
- for (k = 0; k < nk; ++k)
- cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
+ for (k = 0; k < nk; ++k) cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
break;
case STBI__F_avg:
for (k = 0; k < filter_bytes; ++k)
cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1));
for (k = filter_bytes; k < nk; ++k)
- cur[k] = STBI__BYTECAST(
- raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1));
+ cur[k]
+ = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1));
break;
case STBI__F_paeth:
for (k = 0; k < filter_bytes; ++k)
cur[k] = STBI__BYTECAST(
- raw[k]
- + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)
+ raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)
for (k = filter_bytes; k < nk; ++k)
- cur[k] = STBI__BYTECAST(
- raw[k]
- + stbi__paeth(cur[k - filter_bytes], prior[k],
- prior[k - filter_bytes]));
+ cur[k] = STBI__BYTECAST(raw[k]
+ + stbi__paeth(cur[k - filter_bytes], prior[k],
+ prior[k - filter_bytes]));
break;
case STBI__F_avg_first:
memcpy(cur, raw, filter_bytes);
for (k = filter_bytes; k < nk; ++k)
- cur[k]
- = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1));
+ cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1));
break;
}
@@ -5156,9 +4954,8 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw,
// expand decoded bits in cur to dest, also adding an extra alpha channel if desired
if (depth < 8) {
- stbi_uc scale = (color == 0)
- ? stbi__depth_scale_table[depth]
- : 1; // scale grayscale values to 0..255 range
+ stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth]
+ : 1; // scale grayscale values to 0..255 range
stbi_uc * in = cur;
stbi_uc * out = dest;
stbi_uc inb = 0;
@@ -5187,8 +4984,7 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw,
}
// insert alpha=255 values if desired
- if (img_n != out_n)
- stbi__create_png_alpha_expand8(dest, dest, x, img_n);
+ if (img_n != out_n) stbi__create_png_alpha_expand8(dest, dest, x, img_n);
} else if (depth == 8) {
if (img_n == out_n) memcpy(dest, cur, x * img_n);
else stbi__create_png_alpha_expand8(dest, cur, x, img_n);
@@ -5227,20 +5023,18 @@ static int stbi__create_png_image_raw(stbi__png * a, stbi_uc * raw,
}
static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data,
- stbi__uint32 image_data_len, int out_n,
- int depth, int color, int interlaced) {
+ stbi__uint32 image_data_len, int out_n, int depth, int color,
+ int interlaced) {
int bytes = (depth == 16 ? 2 : 1);
int out_bytes = out_n * bytes;
stbi_uc * final;
int p;
if (!interlaced)
- return stbi__create_png_image_raw(a, image_data, image_data_len, out_n,
- a->s->img_x, a->s->img_y, depth,
- color);
+ return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x,
+ a->s->img_y, depth, color);
// de-interlacing
- final
- = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
+ final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
if (!final) return stbi__err("outofmem", "Out of memory");
for (p = 0; p < 7; ++p) {
int xorig[] = {0, 4, 0, 2, 0, 1, 0};
@@ -5252,10 +5046,9 @@ static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data,
x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p];
y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p];
if (x && y) {
- stbi__uint32 img_len
- = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
- if (!stbi__create_png_image_raw(a, image_data, image_data_len,
- out_n, x, y, depth, color)) {
+ stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
+ if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth,
+ color)) {
STBI_FREE(final);
return 0;
}
@@ -5263,8 +5056,7 @@ static int stbi__create_png_image(stbi__png * a, stbi_uc * image_data,
for (i = 0; i < x; ++i) {
int out_y = j * yspc[p] + yorig[p];
int out_x = i * xspc[p] + xorig[p];
- memcpy(final + out_y * a->s->img_x * out_bytes
- + out_x * out_bytes,
+ memcpy(final + out_y * a->s->img_x * out_bytes + out_x * out_bytes,
a->out + (j * x + i) * out_bytes, out_bytes);
}
}
@@ -5301,8 +5093,7 @@ static int stbi__compute_transparency(stbi__png * z, stbi_uc tc[3], int out_n) {
return 1;
}
-static int stbi__compute_transparency16(stbi__png * z, stbi__uint16 tc[3],
- int out_n) {
+static int stbi__compute_transparency16(stbi__png * z, stbi__uint16 tc[3], int out_n) {
stbi__context * s = z->s;
stbi__uint32 i, pixel_count = s->img_x * s->img_y;
stbi__uint16 * p = (stbi__uint16 *) z->out;
@@ -5325,8 +5116,7 @@ static int stbi__compute_transparency16(stbi__png * z, stbi__uint16 tc[3],
return 1;
}
-static int stbi__expand_png_palette(stbi__png * a, stbi_uc * palette, int len,
- int pal_img_n) {
+static int stbi__expand_png_palette(stbi__png * a, stbi_uc * palette, int len, int pal_img_n) {
stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
stbi_uc *p, *temp_out, *orig = a->out;
@@ -5365,8 +5155,7 @@ static int stbi__expand_png_palette(stbi__png * a, stbi_uc * palette, int len,
static int stbi__unpremultiply_on_load_global = 0;
static int stbi__de_iphone_flag_global = 0;
-STBIDEF void
-stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) {
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) {
stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
}
@@ -5380,17 +5169,14 @@ STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) {
#else
static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local,
stbi__unpremultiply_on_load_set;
-static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local,
- stbi__de_iphone_flag_set;
+static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
-STBIDEF void
-stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) {
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) {
stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
stbi__unpremultiply_on_load_set = 1;
}
-STBIDEF void
-stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) {
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) {
stbi__de_iphone_flag_local = flag_true_if_should_convert;
stbi__de_iphone_flag_set = 1;
}
@@ -5399,8 +5185,7 @@ stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) {
(stbi__unpremultiply_on_load_set ? stbi__unpremultiply_on_load_local \
: stbi__unpremultiply_on_load_global)
#define stbi__de_iphone_flag \
- (stbi__de_iphone_flag_set ? stbi__de_iphone_flag_local \
- : stbi__de_iphone_flag_global)
+ (stbi__de_iphone_flag_set ? stbi__de_iphone_flag_local : stbi__de_iphone_flag_global)
#endif // STBI_THREAD_LOCAL
static void stbi__de_iphone(stbi__png * z) {
@@ -5446,8 +5231,7 @@ static void stbi__de_iphone(stbi__png * z) {
}
#define STBI__PNG_TYPE(a, b, c, d) \
- (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) \
- + (unsigned) (d))
+ (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d))
static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
stbi_uc palette[1024], pal_img_n = 0;
@@ -5476,43 +5260,34 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
int comp, filter;
if (!first) return stbi__err("multiple IHDR", "Corrupt PNG");
first = 0;
- if (c.length != 13)
- return stbi__err("bad IHDR len", "Corrupt PNG");
+ if (c.length != 13) return stbi__err("bad IHDR len", "Corrupt PNG");
s->img_x = stbi__get32be(s);
s->img_y = stbi__get32be(s);
if (s->img_y > STBI_MAX_DIMENSIONS)
- return stbi__err("too large",
- "Very large image (corrupt?)");
+ return stbi__err("too large", "Very large image (corrupt?)");
if (s->img_x > STBI_MAX_DIMENSIONS)
- return stbi__err("too large",
- "Very large image (corrupt?)");
+ return stbi__err("too large", "Very large image (corrupt?)");
z->depth = stbi__get8(s);
- if (z->depth != 1 && z->depth != 2 && z->depth != 4
- && z->depth != 8 && z->depth != 16)
+ if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8
+ && z->depth != 16)
return stbi__err("1/2/4/8/16-bit only",
"PNG not supported: 1/2/4/8/16-bit only");
color = stbi__get8(s);
if (color > 6) return stbi__err("bad ctype", "Corrupt PNG");
- if (color == 3 && z->depth == 16)
- return stbi__err("bad ctype", "Corrupt PNG");
+ if (color == 3 && z->depth == 16) return stbi__err("bad ctype", "Corrupt PNG");
if (color == 3) pal_img_n = 3;
- else if (color & 1)
- return stbi__err("bad ctype", "Corrupt PNG");
+ else if (color & 1) return stbi__err("bad ctype", "Corrupt PNG");
comp = stbi__get8(s);
if (comp) return stbi__err("bad comp method", "Corrupt PNG");
filter = stbi__get8(s);
- if (filter)
- return stbi__err("bad filter method", "Corrupt PNG");
+ if (filter) return stbi__err("bad filter method", "Corrupt PNG");
interlace = stbi__get8(s);
- if (interlace > 1)
- return stbi__err("bad interlace method", "Corrupt PNG");
- if (!s->img_x || !s->img_y)
- return stbi__err("0-pixel image", "Corrupt PNG");
+ if (interlace > 1) return stbi__err("bad interlace method", "Corrupt PNG");
+ if (!s->img_x || !s->img_y) return stbi__err("0-pixel image", "Corrupt PNG");
if (!pal_img_n) {
s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
if ((1 << 30) / s->img_x / s->img_n < s->img_y)
- return stbi__err("too large",
- "Image too large to decode");
+ return stbi__err("too large", "Image too large to decode");
} else {
// if paletted, then pal_n is our final components, and
// img_n is # components to decompress/filter.
@@ -5526,11 +5301,9 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
case STBI__PNG_TYPE('P', 'L', 'T', 'E'): {
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
- if (c.length > 256 * 3)
- return stbi__err("invalid PLTE", "Corrupt PNG");
+ if (c.length > 256 * 3) return stbi__err("invalid PLTE", "Corrupt PNG");
pal_len = c.length / 3;
- if (pal_len * 3 != c.length)
- return stbi__err("invalid PLTE", "Corrupt PNG");
+ if (pal_len * 3 != c.length) return stbi__err("invalid PLTE", "Corrupt PNG");
for (i = 0; i < pal_len; ++i) {
palette[i * 4 + 0] = stbi__get8(s);
palette[i * 4 + 1] = stbi__get8(s);
@@ -5542,23 +5315,18 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
case STBI__PNG_TYPE('t', 'R', 'N', 'S'): {
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
- if (z->idata)
- return stbi__err("tRNS after IDAT", "Corrupt PNG");
+ if (z->idata) return stbi__err("tRNS after IDAT", "Corrupt PNG");
if (pal_img_n) {
if (scan == STBI__SCAN_header) {
s->img_n = 4;
return 1;
}
- if (pal_len == 0)
- return stbi__err("tRNS before PLTE", "Corrupt PNG");
- if (c.length > pal_len)
- return stbi__err("bad tRNS len", "Corrupt PNG");
+ if (pal_len == 0) return stbi__err("tRNS before PLTE", "Corrupt PNG");
+ if (c.length > pal_len) return stbi__err("bad tRNS len", "Corrupt PNG");
pal_img_n = 4;
- for (i = 0; i < c.length; ++i)
- palette[i * 4 + 3] = stbi__get8(s);
+ for (i = 0; i < c.length; ++i) palette[i * 4 + 3] = stbi__get8(s);
} else {
- if (!(s->img_n & 1))
- return stbi__err("tRNS with alpha", "Corrupt PNG");
+ if (!(s->img_n & 1)) return stbi__err("tRNS with alpha", "Corrupt PNG");
if (c.length != (stbi__uint32) s->img_n * 2)
return stbi__err("bad tRNS len", "Corrupt PNG");
has_trans = 1;
@@ -5569,14 +5337,12 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
}
if (z->depth == 16) {
for (k = 0; k < s->img_n; ++k)
- tc16[k] = (stbi__uint16) stbi__get16be(
- s); // copy the values as-is
+ tc16[k] = (stbi__uint16) stbi__get16be(s); // copy the values as-is
} else {
for (k = 0; k < s->img_n; ++k)
- tc[k]
- = (stbi_uc) (stbi__get16be(s) & 255)
- * stbi__depth_scale_table
- [z->depth]; // non 8-bit images will be larger
+ tc[k] = (stbi_uc) (stbi__get16be(s) & 255)
+ * stbi__depth_scale_table
+ [z->depth]; // non 8-bit images will be larger
}
}
break;
@@ -5584,28 +5350,23 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
case STBI__PNG_TYPE('I', 'D', 'A', 'T'): {
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
- if (pal_img_n && !pal_len)
- return stbi__err("no PLTE", "Corrupt PNG");
+ if (pal_img_n && !pal_len) return stbi__err("no PLTE", "Corrupt PNG");
if (scan == STBI__SCAN_header) {
// header scan definitely stops at first IDAT
if (pal_img_n) s->img_n = pal_img_n;
return 1;
}
if (c.length > (1u << 30))
- return stbi__err("IDAT size limit",
- "IDAT section larger than 2^30 bytes");
+ return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");
if ((int) (ioff + c.length) < (int) ioff) return 0;
if (ioff + c.length > idata_limit) {
stbi__uint32 idata_limit_old = idata_limit;
stbi_uc * p;
- if (idata_limit == 0)
- idata_limit = c.length > 4096 ? c.length : 4096;
+ if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit) idata_limit *= 2;
STBI_NOTUSED(idata_limit_old);
- p = (stbi_uc *) STBI_REALLOC_SIZED(
- z->idata, idata_limit_old, idata_limit);
- if (p == NULL)
- return stbi__err("outofmem", "Out of memory");
+ p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit);
+ if (p == NULL) return stbi__err("outofmem", "Out of memory");
z->idata = p;
}
if (!stbi__getn(s, z->idata + ioff, c.length))
@@ -5618,48 +5379,36 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
stbi__uint32 raw_len, bpl;
if (first) return stbi__err("first not IHDR", "Corrupt PNG");
if (scan != STBI__SCAN_load) return 1;
- if (z->idata == NULL)
- return stbi__err("no IDAT", "Corrupt PNG");
+ if (z->idata == NULL) return stbi__err("no IDAT", "Corrupt PNG");
// initial guess for decoded data size to avoid unnecessary reallocs
- bpl = (s->img_x * z->depth + 7)
- / 8; // bytes per line, per component
+ bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
raw_len = bpl * s->img_y * s->img_n /* pixels */
+ s->img_y /* filter mode per row */;
- z->expanded
- = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag(
- (char *) z->idata, ioff, raw_len, (int *) &raw_len,
- !is_iphone);
+ z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag(
+ (char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
if (z->expanded == NULL) return 0; // zlib should set error
STBI_FREE(z->idata);
z->idata = NULL;
- if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n)
- || has_trans)
+ if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans)
s->img_out_n = s->img_n + 1;
else s->img_out_n = s->img_n;
- if (!stbi__create_png_image(z, z->expanded, raw_len,
- s->img_out_n, z->depth, color,
- interlace))
+ if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth,
+ color, interlace))
return 0;
if (has_trans) {
if (z->depth == 16) {
- if (!stbi__compute_transparency16(z, tc16,
- s->img_out_n))
- return 0;
+ if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
} else {
- if (!stbi__compute_transparency(z, tc, s->img_out_n))
- return 0;
+ if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
}
}
- if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
- stbi__de_iphone(z);
+ if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z);
if (pal_img_n) {
// pal_img_n == 3 or 4
s->img_n = pal_img_n; // record the actual colors we had
s->img_out_n = pal_img_n;
if (req_comp >= 3) s->img_out_n = req_comp;
- if (!stbi__expand_png_palette(z, palette, pal_len,
- s->img_out_n))
- return 0;
+ if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0;
} else if (has_trans) {
// non-paletted image with tRNS -> source image has (constant) alpha
++s->img_n;
@@ -5683,9 +5432,8 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
#endif
- return stbi__err(
- invalid_chunk,
- "PNG not supported: unknown PNG chunk type");
+ return stbi__err(invalid_chunk,
+ "PNG not supported: unknown PNG chunk type");
}
stbi__skip(s, c.length);
break;
@@ -5695,11 +5443,10 @@ static int stbi__parse_png_file(stbi__png * z, int scan, int req_comp) {
}
}
-static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n, int req_comp,
+ stbi__result_info * ri) {
void * result = NULL;
- if (req_comp < 0 || req_comp > 4)
- return stbi__errpuc("bad req_comp", "Internal error");
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
if (p->depth <= 8) ri->bits_per_channel = 8;
else if (p->depth == 16) ri->bits_per_channel = 16;
@@ -5710,13 +5457,11 @@ static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n,
p->out = NULL;
if (req_comp && req_comp != p->s->img_out_n) {
if (ri->bits_per_channel == 8)
- result = stbi__convert_format((unsigned char *) result,
- p->s->img_out_n, req_comp,
- p->s->img_x, p->s->img_y);
+ result = stbi__convert_format((unsigned char *) result, p->s->img_out_n,
+ req_comp, p->s->img_x, p->s->img_y);
else
- result = stbi__convert_format16((stbi__uint16 *) result,
- p->s->img_out_n, req_comp,
- p->s->img_x, p->s->img_y);
+ result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n,
+ req_comp, p->s->img_x, p->s->img_y);
p->s->img_out_n = req_comp;
if (result == NULL) return result;
}
@@ -5734,8 +5479,8 @@ static void * stbi__do_png(stbi__png * p, int * x, int * y, int * n,
return result;
}
-static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__png_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
stbi__png p;
p.s = s;
return stbi__do_png(&p, x, y, comp, req_comp, ri);
@@ -5926,8 +5671,8 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) {
"BMP type not supported: unsupported "
"compression"); // this includes PNG/JPEG modes
if (compress == 3 && info->bpp != 16 && info->bpp != 32)
- return stbi__errpuc(
- "bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel
+ return stbi__errpuc("bad BMP",
+ "bad BMP"); // bitfields requires 16 or 32 bits/pixel
stbi__get32le(s); // discard sizeof
stbi__get32le(s); // discard hres
stbi__get32le(s); // discard vres
@@ -5958,18 +5703,15 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) {
} else {
// V4/V5 header
int i;
- if (hsz != 108 && hsz != 124)
- return stbi__errpuc("bad BMP", "bad BMP");
+ if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP");
info->mr = stbi__get32le(s);
info->mg = stbi__get32le(s);
info->mb = stbi__get32le(s);
info->ma = stbi__get32le(s);
- if (compress
- != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
+ if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
stbi__bmp_set_mask_defaults(info, compress);
stbi__get32le(s); // discard color space
- for (i = 0; i < 12; ++i)
- stbi__get32le(s); // discard color space parameters
+ for (i = 0; i < 12; ++i) stbi__get32le(s); // discard color space parameters
if (hsz == 124) {
stbi__get32le(s); // discard rendering intent
stbi__get32le(s); // discard offset of profile data
@@ -5981,8 +5723,8 @@ static void * stbi__bmp_parse_header(stbi__context * s, stbi__bmp_data * info) {
return (void *) 1;
}
-static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
stbi_uc * out;
unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a;
stbi_uc pal[256][4];
@@ -5992,8 +5734,7 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
STBI_NOTUSED(ri);
info.all_a = 255;
- if (stbi__bmp_parse_header(s, &info) == NULL)
- return NULL; // error code already set
+ if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set
flip_vertically = ((int) s->img_y) > 0;
s->img_y = abs((int) s->img_y);
@@ -6012,17 +5753,14 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
if (info.hsz == 12) {
if (info.bpp < 24) psize = (info.offset - info.extra_read - 24) / 3;
} else {
- if (info.bpp < 16)
- psize = (info.offset - info.extra_read - info.hsz) >> 2;
+ if (info.bpp < 16) psize = (info.offset - info.extra_read - info.hsz) >> 2;
}
if (psize == 0) {
// accept some number of extra bytes after the header, but if the offset points either to before
// the header ends or implies a large amount of extra data, reject the file as malformed
int bytes_read_so_far
- = s->callback_already_read
- + (int) (s->img_buffer - s->img_buffer_original);
- int header_limit
- = 1024; // max we actually read is below 256 bytes currently.
+ = s->callback_already_read + (int) (s->img_buffer - s->img_buffer_original);
+ int header_limit = 1024; // max we actually read is below 256 bytes currently.
int extra_data_limit
= 256
* 4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.
@@ -6116,8 +5854,8 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
}
}
} else {
- int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0,
- gcount = 0, bcount = 0, acount = 0;
+ int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, gcount = 0, bcount = 0,
+ acount = 0;
int z = 0;
int easy = 0;
stbi__skip(s, info.offset - info.extra_read - info.hsz);
@@ -6128,9 +5866,7 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
if (info.bpp == 24) {
easy = 1;
} else if (info.bpp == 32) {
- if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000
- && ma == 0xff000000)
- easy = 2;
+ if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2;
}
if (!easy) {
if (!mr || !mg || !mb) {
@@ -6167,15 +5903,11 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
int bpp = info.bpp;
for (i = 0; i < (int) s->img_x; ++i) {
stbi__uint32 v
- = (bpp == 16 ? (stbi__uint32) stbi__get16le(s)
- : stbi__get32le(s));
+ = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));
unsigned int a;
- out[z++] = STBI__BYTECAST(
- stbi__shiftsigned(v & mr, rshift, rcount));
- out[z++] = STBI__BYTECAST(
- stbi__shiftsigned(v & mg, gshift, gcount));
- out[z++] = STBI__BYTECAST(
- stbi__shiftsigned(v & mb, bshift, bcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
all_a |= a;
if (target == 4) out[z++] = STBI__BYTECAST(a);
@@ -6204,8 +5936,7 @@ static void * stbi__bmp_load(stbi__context * s, int * x, int * y, int * comp,
if (req_comp && req_comp != target) {
out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
- if (out == NULL)
- return out; // stbi__convert_format frees input on failure
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
}
*x = s->img_x;
@@ -6240,8 +5971,7 @@ static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int * is_rgb16) {
}
static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) {
- int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel,
- tga_colormap_bpp;
+ int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;
int sz, tga_colormap_type;
stbi__get8(s); // discard Offset
tga_colormap_type = stbi__get8(s); // colormap type
@@ -6255,8 +5985,7 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) {
stbi__rewind(s);
return 0;
}
- stbi__skip(
- s, 4); // skip index of first colormap entry and number of entries
+ stbi__skip(s, 4); // skip index of first colormap entry and number of entries
sz = stbi__get8(s); // check bits per palette color entry
if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) {
stbi__rewind(s);
@@ -6265,8 +5994,8 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) {
stbi__skip(s, 4); // skip image x and y origin
tga_colormap_bpp = sz;
} else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE
- if ((tga_image_type != 2) && (tga_image_type != 3)
- && (tga_image_type != 10) && (tga_image_type != 11)) {
+ if ((tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10)
+ && (tga_image_type != 11)) {
stbi__rewind(s);
return 0; // only RGB or grey allowed, +/- RLE
}
@@ -6294,9 +6023,8 @@ static int stbi__tga_info(stbi__context * s, int * x, int * y, int * comp) {
}
tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);
} else {
- tga_comp = stbi__tga_get_comp(
- tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11),
- NULL);
+ tga_comp = stbi__tga_get_comp(tga_bits_per_pixel,
+ (tga_image_type == 3) || (tga_image_type == 11), NULL);
}
if (!tga_comp) {
stbi__rewind(s);
@@ -6316,13 +6044,10 @@ static int stbi__tga_test(stbi__context * s) {
if (tga_color_type > 1) goto errorEnd; // only RGB or indexed allowed
sz = stbi__get8(s); // image type
if (tga_color_type == 1) { // colormapped (paletted) image
- if (sz != 1 && sz != 9)
- goto errorEnd; // colortype 1 demands image type 1 or 9
- stbi__skip(
- s, 4); // skip index of first colormap entry and number of entries
+ if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9
+ stbi__skip(s, 4); // skip index of first colormap entry and number of entries
sz = stbi__get8(s); // check bits per palette color entry
- if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32))
- goto errorEnd;
+ if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd;
stbi__skip(s, 4); // skip image x and y origin
} else { // "normal" image w/o colormap
if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11))
@@ -6334,8 +6059,7 @@ static int stbi__tga_test(stbi__context * s) {
sz = stbi__get8(s); // bits per pixel
if ((tga_color_type == 1) && (sz != 8) && (sz != 16))
goto errorEnd; // for colormapped images, bpp is size of an index
- if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32))
- goto errorEnd;
+ if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd;
res = 1; // if we got this far, everything's good and we can return 1 instead of 0
@@ -6363,8 +6087,8 @@ static void stbi__tga_read_rgb16(stbi__context * s, stbi_uc * out) {
// so let's treat all 15 and 16bit TGAs as RGB with no alpha.
}
-static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
// read in the TGA header stuff
int tga_offset = stbi__get8(s);
int tga_indexed = stbi__get8(s);
@@ -6406,11 +6130,8 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
tga_inverted = 1 - ((tga_inverted >> 5) & 1);
// If I'm paletted, then I'll use the number of bits from the palette
- if (tga_indexed)
- tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
- else
- tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3),
- &tga_rgb16);
+ if (tga_indexed) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
+ else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);
if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency
return stbi__errpuc("bad format", "Can't find out TGA pixelformat");
@@ -6423,8 +6144,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))
return stbi__errpuc("too large", "Corrupt TGA");
- tga_data = (unsigned char *) stbi__malloc_mad3(tga_width, tga_height,
- tga_comp, 0);
+ tga_data = (unsigned char *) stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);
if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
// skip to the data's starting position (offset usually = 0)
@@ -6439,8 +6159,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
} else {
// do I need to load a palette?
if (tga_indexed) {
- if (tga_palette_len
- == 0) { /* you have to have at least one entry! */
+ if (tga_palette_len == 0) { /* you have to have at least one entry! */
STBI_FREE(tga_data);
return stbi__errpuc("bad palette", "Corrupt TGA");
}
@@ -6448,8 +6167,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
// any data to skip? (offset usually = 0)
stbi__skip(s, tga_palette_start);
// load the palette
- tga_palette = (unsigned char *) stbi__malloc_mad2(tga_palette_len,
- tga_comp, 0);
+ tga_palette = (unsigned char *) stbi__malloc_mad2(tga_palette_len, tga_comp, 0);
if (!tga_palette) {
STBI_FREE(tga_data);
return stbi__errpuc("outofmem", "Out of memory");
@@ -6461,8 +6179,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
stbi__tga_read_rgb16(s, pal_entry);
pal_entry += tga_comp;
}
- } else if (!stbi__getn(s, tga_palette,
- tga_palette_len * tga_comp)) {
+ } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) {
STBI_FREE(tga_data);
STBI_FREE(tga_palette);
return stbi__errpuc("bad palette", "Corrupt TGA");
@@ -6489,8 +6206,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
// load however much data we did have
if (tga_indexed) {
// read in index, then perform the lookup
- int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s)
- : stbi__get16le(s);
+ int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);
if (pal_idx >= tga_palette_len) {
// invalid index
pal_idx = 0;
@@ -6513,8 +6229,7 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
} // end of reading a pixel
// copy data
- for (j = 0; j < tga_comp; ++j)
- tga_data[i * tga_comp + j] = raw_data[j];
+ for (j = 0; j < tga_comp; ++j) tga_data[i * tga_comp + j] = raw_data[j];
// in case we're in RLE mode, keep counting down
--RLE_count;
@@ -6552,13 +6267,11 @@ static void * stbi__tga_load(stbi__context * s, int * x, int * y, int * comp,
// convert to target component count
if (req_comp && req_comp != tga_comp)
- tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width,
- tga_height);
+ tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
// the things I do to get rid of an error message, and yet keep
// Microsoft's C compilers happy... [8^(
- tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin
- = tga_y_origin = 0;
+ tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0;
STBI_NOTUSED(tga_palette_start);
// OK, done
return tga_data;
@@ -6575,8 +6288,7 @@ static int stbi__psd_test(stbi__context * s) {
return r;
}
-static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p,
- int pixelCount) {
+static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p, int pixelCount) {
int count, nleft, len;
count = 0;
@@ -6613,8 +6325,8 @@ static int stbi__psd_decode_rle(stbi__context * s, stbi_uc * p,
return 1;
}
-static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri, int bpc) {
+static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri, int bpc) {
int pixelCount;
int channelCount, compression;
int channel, i;
@@ -6629,8 +6341,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
// Check file type version.
if (stbi__get16be(s) != 1)
- return stbi__errpuc("wrong version",
- "Unsupported version of PSD image");
+ return stbi__errpuc("wrong version", "Unsupported version of PSD image");
// Skip 6 reserved bytes.
stbi__skip(s, 6);
@@ -6653,8 +6364,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
// Make sure the depth is 8 bits.
bitdepth = stbi__get16be(s);
if (bitdepth != 8 && bitdepth != 16)
- return stbi__errpuc("unsupported bit depth",
- "PSD bit depth is not 8 or 16 bit");
+ return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit");
// Make sure the color mode is RGB.
// Valid options are:
@@ -6667,8 +6377,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
// 8: Duotone
// 9: Lab color
if (stbi__get16be(s) != 3)
- return stbi__errpuc("wrong color format",
- "PSD is not in RGB color format");
+ return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
// Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
stbi__skip(s, stbi__get32be(s));
@@ -6685,12 +6394,10 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
// 1: RLE compressed
compression = stbi__get16be(s);
if (compression > 1)
- return stbi__errpuc("bad compression",
- "PSD has an unknown compression format");
+ return stbi__errpuc("bad compression", "PSD has an unknown compression format");
// Check size
- if (!stbi__mad3sizes_valid(4, w, h, 0))
- return stbi__errpuc("too large", "Corrupt PSD");
+ if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD");
// Create the destination image.
@@ -6726,8 +6433,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
p = out + channel;
if (channel >= channelCount) {
// Fill this channel with default data.
- for (i = 0; i < pixelCount; i++, p += 4)
- *p = (channel == 3 ? 255 : 0);
+ for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0);
} else {
// Read the RLE data.
if (!stbi__psd_decode_rle(s, p, pixelCount)) {
@@ -6765,8 +6471,7 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
for (i = 0; i < pixelCount; i++, p += 4)
*p = (stbi_uc) (stbi__get16be(s) >> 8);
} else {
- for (i = 0; i < pixelCount; i++, p += 4)
- *p = stbi__get8(s);
+ for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s);
}
}
}
@@ -6805,11 +6510,9 @@ static void * stbi__psd_load(stbi__context * s, int * x, int * y, int * comp,
// convert to desired output format
if (req_comp && req_comp != 4) {
if (ri->bits_per_channel == 16)
- out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4,
- req_comp, w, h);
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h);
else out = stbi__convert_format(out, 4, req_comp, w, h);
- if (out == NULL)
- return out; // stbi__convert_format frees input on failure
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
}
if (comp) *comp = 4;
@@ -6857,8 +6560,7 @@ static stbi_uc * stbi__readval(stbi__context * s, int channel, stbi_uc * dest) {
for (i = 0; i < 4; ++i, mask >>= 1) {
if (channel & mask) {
- if (stbi__at_eof(s))
- return stbi__errpuc("bad file", "PIC file too short");
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file", "PIC file too short");
dest[i] = stbi__get8(s);
}
}
@@ -6873,8 +6575,8 @@ static void stbi__copyval(int channel, stbi_uc * dest, const stbi_uc * src) {
if (channel & mask) dest[i] = src[i];
}
-static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
- int * comp, stbi_uc * result) {
+static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height, int * comp,
+ stbi_uc * result) {
int act_comp = 0, num_packets = 0, y, chained;
stbi__pic_packet packets[10];
@@ -6897,8 +6599,7 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
if (stbi__at_eof(s))
return stbi__errpuc("bad file", "file too short (reading packets)");
- if (packet->size != 8)
- return stbi__errpuc("bad format", "packet isn't 8bpp");
+ if (packet->size != 8) return stbi__errpuc("bad format", "packet isn't 8bpp");
} while (chained);
*comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
@@ -6912,8 +6613,7 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
switch (packet->type) {
default:
- return stbi__errpuc("bad format",
- "packet has bad compression type");
+ return stbi__errpuc("bad format", "packet has bad compression type");
case 0: { //uncompressed
int x;
@@ -6932,8 +6632,8 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
count = stbi__get8(s);
if (stbi__at_eof(s))
- return stbi__errpuc(
- "bad file", "file too short (pure read count)");
+ return stbi__errpuc("bad file",
+ "file too short (pure read count)");
if (count > left) count = (stbi_uc) left;
@@ -6950,9 +6650,8 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
while (left > 0) {
int count = stbi__get8(s), i;
if (stbi__at_eof(s))
- return stbi__errpuc(
- "bad file",
- "file too short (mixed read count)");
+ return stbi__errpuc("bad file",
+ "file too short (mixed read count)");
if (count >= 128) { // Repeated
stbi_uc value[4];
@@ -6960,23 +6659,19 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
if (count == 128) count = stbi__get16be(s);
else count -= 127;
if (count > left)
- return stbi__errpuc("bad file",
- "scanline overrun");
+ return stbi__errpuc("bad file", "scanline overrun");
- if (!stbi__readval(s, packet->channel, value))
- return 0;
+ if (!stbi__readval(s, packet->channel, value)) return 0;
for (i = 0; i < count; ++i, dest += 4)
stbi__copyval(packet->channel, dest, value);
} else { // Raw
++count;
if (count > left)
- return stbi__errpuc("bad file",
- "scanline overrun");
+ return stbi__errpuc("bad file", "scanline overrun");
for (i = 0; i < count; ++i, dest += 4)
- if (!stbi__readval(s, packet->channel, dest))
- return 0;
+ if (!stbi__readval(s, packet->channel, dest)) return 0;
}
left -= count;
}
@@ -6989,8 +6684,8 @@ static stbi_uc * stbi__pic_load_core(stbi__context * s, int width, int height,
return result;
}
-static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp, int req_comp,
+ stbi__result_info * ri) {
stbi_uc * result;
int i, x, y, internal_comp;
STBI_NOTUSED(ri);
@@ -7007,8 +6702,7 @@ static void * stbi__pic_load(stbi__context * s, int * px, int * py, int * comp,
if (x > STBI_MAX_DIMENSIONS)
return stbi__errpuc("too large", "Very large image (corrupt?)");
- if (stbi__at_eof(s))
- return stbi__errpuc("bad file", "file too short (pic header)");
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pic header)");
if (!stbi__mad3sizes_valid(x, y, 4, 0))
return stbi__errpuc("too large", "PIC image too large to decode");
@@ -7053,8 +6747,7 @@ typedef struct {
typedef struct {
int w, h;
stbi_uc * out; // output buffer (always 4 components)
- stbi_uc *
- background; // The current "background" as far as a gif is concerned
+ stbi_uc * background; // The current "background" as far as a gif is concerned
stbi_uc * history;
int flags, bgindex, ratio, transparent, eflags;
stbi_uc pal[256][4];
@@ -7087,8 +6780,8 @@ static int stbi__gif_test(stbi__context * s) {
return r;
}
-static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4],
- int num_entries, int transp) {
+static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4], int num_entries,
+ int transp) {
int i;
for (i = 0; i < num_entries; ++i) {
pal[i][2] = stbi__get8(s);
@@ -7098,16 +6791,14 @@ static void stbi__gif_parse_colortable(stbi__context * s, stbi_uc pal[256][4],
}
}
-static int stbi__gif_header(stbi__context * s, stbi__gif * g, int * comp,
- int is_info) {
+static int stbi__gif_header(stbi__context * s, stbi__gif * g, int * comp, int is_info) {
stbi_uc version;
if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F'
|| stbi__get8(s) != '8')
return stbi__err("not GIF", "Corrupt GIF");
version = stbi__get8(s);
- if (version != '7' && version != '9')
- return stbi__err("not GIF", "Corrupt GIF");
+ if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
stbi__g_failure_reason = "";
@@ -7124,13 +6815,11 @@ static int stbi__gif_header(stbi__context * s, stbi__gif * g, int * comp,
return stbi__err("too large", "Very large image (corrupt?)");
if (comp != 0)
- *comp
- = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
+ *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
if (is_info) return 1;
- if (g->flags & 0x80)
- stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1);
+ if (g->flags & 0x80) stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1);
return 1;
}
@@ -7155,8 +6844,7 @@ static void stbi__out_gif_code(stbi__gif * g, stbi__uint16 code) {
// recurse to decode the prefixes, since the linked-list is backwards,
// and working backwards through an interleaved image would be nasty
- if (g->codes[code].prefix >= 0)
- stbi__out_gif_code(g, g->codes[code].prefix);
+ if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix);
if (g->cur_y >= g->max_y) return;
@@ -7248,11 +6936,9 @@ static stbi_uc * stbi__process_gif_raster(stbi__context * s, stbi__gif * g) {
p->prefix = (stbi__int16) oldcode;
p->first = g->codes[oldcode].first;
- p->suffix
- = (code == avail) ? p->first : g->codes[code].first;
+ p->suffix = (code == avail) ? p->first : g->codes[code].first;
} else if (code == avail)
- return stbi__errpuc("illegal code in raster",
- "Corrupt GIF");
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
stbi__out_gif_code(g, (stbi__uint16) code);
@@ -7271,9 +6957,8 @@ static stbi_uc * stbi__process_gif_raster(stbi__context * s, stbi__gif * g) {
// this function is designed to support animated gifs, although stb_image doesn't support it
// two back is the image from two frames ago, used for a very specific disposal format
-static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g,
- int * comp, int req_comp,
- stbi_uc * two_back) {
+static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g, int * comp,
+ int req_comp, stbi_uc * two_back) {
int dispose;
int first_frame;
int pi;
@@ -7382,13 +7067,11 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g,
if (g->lflags & 0x80) {
stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7),
- g->eflags & 0x01 ? g->transparent
- : -1);
+ g->eflags & 0x01 ? g->transparent : -1);
g->color_table = (stbi_uc *) g->lpal;
} else if (g->flags & 0x80) {
g->color_table = (stbi_uc *) g->pal;
- } else
- return stbi__errpuc("missing color table", "Corrupt GIF");
+ } else return stbi__errpuc("missing color table", "Corrupt GIF");
o = stbi__process_gif_raster(s, g);
if (!o) return NULL;
@@ -7417,10 +7100,9 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g,
len = stbi__get8(s);
if (len == 4) {
g->eflags = stbi__get8(s);
- g->delay
- = 10
- * stbi__get16le(
- s); // delay - 1/100th of a second, saving as 1/1000ths.
+ g->delay = 10
+ * stbi__get16le(
+ s); // delay - 1/100th of a second, saving as 1/1000ths.
// unset old transparent
if (g->transparent >= 0) {
@@ -7448,8 +7130,7 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g,
}
case 0x3B: // gif stream termination code
- return (
- stbi_uc *) s; // using '1' causes warning on some compilers
+ return (stbi_uc *) s; // using '1' causes warning on some compilers
default:
return stbi__errpuc("unknown code", "Corrupt GIF");
@@ -7457,8 +7138,7 @@ static stbi_uc * stbi__gif_load_next(stbi__context * s, stbi__gif * g,
}
}
-static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out,
- int ** delays) {
+static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out, int ** delays) {
STBI_FREE(g->out);
STBI_FREE(g->history);
STBI_FREE(g->background);
@@ -7468,8 +7148,8 @@ static void * stbi__load_gif_main_outofmem(stbi__gif * g, stbi_uc * out,
return stbi__errpuc("outofmem", "Out of memory");
}
-static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x,
- int * y, int * z, int * comp, int req_comp) {
+static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x, int * y, int * z,
+ int * comp, int req_comp) {
if (stbi__gif_test(s)) {
int layers = 0;
stbi_uc * u = 0;
@@ -7499,34 +7179,28 @@ static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x,
stride = g.w * g.h * 4;
if (out) {
- void * tmp = (stbi_uc *) STBI_REALLOC_SIZED(
- out, out_size, layers * stride);
- if (!tmp)
- return stbi__load_gif_main_outofmem(&g, out, delays);
+ void * tmp
+ = (stbi_uc *) STBI_REALLOC_SIZED(out, out_size, layers * stride);
+ if (!tmp) return stbi__load_gif_main_outofmem(&g, out, delays);
else {
out = (stbi_uc *) tmp;
out_size = layers * stride;
}
if (delays) {
- int * new_delays = (int *) STBI_REALLOC_SIZED(
- *delays, delays_size, sizeof(int) * layers);
- if (!new_delays)
- return stbi__load_gif_main_outofmem(&g, out,
- delays);
+ int * new_delays = (int *) STBI_REALLOC_SIZED(*delays, delays_size,
+ sizeof(int) * layers);
+ if (!new_delays) return stbi__load_gif_main_outofmem(&g, out, delays);
*delays = new_delays;
delays_size = layers * sizeof(int);
}
} else {
out = (stbi_uc *) stbi__malloc(layers * stride);
- if (!out)
- return stbi__load_gif_main_outofmem(&g, out, delays);
+ if (!out) return stbi__load_gif_main_outofmem(&g, out, delays);
out_size = layers * stride;
if (delays) {
*delays = (int *) stbi__malloc(layers * sizeof(int));
- if (!*delays)
- return stbi__load_gif_main_outofmem(&g, out,
- delays);
+ if (!*delays) return stbi__load_gif_main_outofmem(&g, out, delays);
delays_size = layers * sizeof(int);
}
}
@@ -7557,8 +7231,8 @@ static void * stbi__load_gif_main(stbi__context * s, int ** delays, int * x,
}
}
-static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
stbi_uc * u = 0;
stbi__gif g;
memset(&g, 0, sizeof(g));
@@ -7572,8 +7246,7 @@ static void * stbi__gif_load(stbi__context * s, int * x, int * y, int * comp,
// moved conversion to after successful load so that the same
// can be done for multiple frames.
- if (req_comp && req_comp != 4)
- u = stbi__convert_format(u, 4, req_comp, g.w, g.h);
+ if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h);
} else if (g.out) {
// if there was an error and we allocated an image buffer, free it!
STBI_FREE(g.out);
@@ -7639,8 +7312,7 @@ static void stbi__hdr_convert(float * output, stbi_uc * input, int req_comp) {
float f1;
// Exponent
f1 = (float) ldexp(1.0f, input[3] - (int) (128 + 8));
- if (req_comp <= 2)
- output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
+ if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
else {
output[0] = input[0] * f1;
output[1] = input[1] * f1;
@@ -7664,8 +7336,8 @@ static void stbi__hdr_convert(float * output, stbi_uc * input, int req_comp) {
}
}
-static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
char buffer[STBI__HDR_BUFLEN];
char * token;
int valid = 0;
@@ -7680,8 +7352,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
// Check identifier
headerToken = stbi__hdr_gettoken(s, buffer);
- if (strcmp(headerToken, "#?RADIANCE") != 0
- && strcmp(headerToken, "#?RGBE") != 0)
+ if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0)
return stbi__errpf("not HDR", "Corrupt HDR image");
// Parse header
@@ -7691,8 +7362,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
}
- if (!valid)
- return stbi__errpf("unsupported format", "Unsupported HDR format");
+ if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
// Parse width and height
// can't use sscanf() if we're not using stdio!
@@ -7722,8 +7392,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
return stbi__errpf("too large", "HDR image is too large");
// Read data
- hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp,
- sizeof(float), 0);
+ hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);
if (!hdr_data) return stbi__errpf("outofmem", "Out of memory");
// Load image data
@@ -7735,9 +7404,8 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
stbi_uc rgbe[4];
main_decode_loop:
stbi__getn(s, rgbe, 4);
- stbi__hdr_convert(hdr_data + j * width * req_comp
- + i * req_comp,
- rgbe, req_comp);
+ stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe,
+ req_comp);
}
}
} else {
@@ -7767,8 +7435,7 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
if (len != width) {
STBI_FREE(hdr_data);
STBI_FREE(scanline);
- return stbi__errpf("invalid decoded scanline length",
- "corrupt HDR");
+ return stbi__errpf("invalid decoded scanline length", "corrupt HDR");
}
if (scanline == NULL) {
scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0);
@@ -7790,27 +7457,23 @@ static float * stbi__hdr_load(stbi__context * s, int * x, int * y, int * comp,
if ((count == 0) || (count > nleft)) {
STBI_FREE(hdr_data);
STBI_FREE(scanline);
- return stbi__errpf("corrupt",
- "bad RLE data in HDR");
+ return stbi__errpf("corrupt", "bad RLE data in HDR");
}
- for (z = 0; z < count; ++z)
- scanline[i++ * 4 + k] = value;
+ for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value;
} else {
// Dump
if ((count == 0) || (count > nleft)) {
STBI_FREE(hdr_data);
STBI_FREE(scanline);
- return stbi__errpf("corrupt",
- "bad RLE data in HDR");
+ return stbi__errpf("corrupt", "bad RLE data in HDR");
}
- for (z = 0; z < count; ++z)
- scanline[i++ * 4 + k] = stbi__get8(s);
+ for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s);
}
}
}
for (i = 0; i < width; ++i)
- stbi__hdr_convert(hdr_data + (j * width + i) * req_comp,
- scanline + i * 4, req_comp);
+ stbi__hdr_convert(hdr_data + (j * width + i) * req_comp, scanline + i * 4,
+ req_comp);
}
if (scanline) STBI_FREE(scanline);
}
@@ -8026,13 +7689,13 @@ static int stbi__pnm_test(stbi__context * s) {
return 1;
}
-static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp,
- int req_comp, stbi__result_info * ri) {
+static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp, int req_comp,
+ stbi__result_info * ri) {
stbi_uc * out;
STBI_NOTUSED(ri);
- ri->bits_per_channel = stbi__pnm_info(s, (int *) &s->img_x,
- (int *) &s->img_y, (int *) &s->img_n);
+ ri->bits_per_channel
+ = stbi__pnm_info(s, (int *) &s->img_x, (int *) &s->img_y, (int *) &s->img_n);
if (ri->bits_per_channel == 0) return 0;
if (s->img_y > STBI_MAX_DIMENSIONS)
@@ -8044,48 +7707,40 @@ static void * stbi__pnm_load(stbi__context * s, int * x, int * y, int * comp,
*y = s->img_y;
if (comp) *comp = s->img_n;
- if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y,
- ri->bits_per_channel / 8, 0))
+ if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))
return stbi__errpuc("too large", "PNM too large");
- out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y,
- ri->bits_per_channel / 8, 0);
+ out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8,
+ 0);
if (!out) return stbi__errpuc("outofmem", "Out of memory");
- if (!stbi__getn(s, out,
- s->img_n * s->img_x * s->img_y
- * (ri->bits_per_channel / 8))) {
+ if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) {
STBI_FREE(out);
return stbi__errpuc("bad PNM", "PNM file truncated");
}
if (req_comp && req_comp != s->img_n) {
if (ri->bits_per_channel == 16) {
- out = (stbi_uc *) stbi__convert_format16(
- (stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y);
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp,
+ s->img_x, s->img_y);
} else {
- out = stbi__convert_format(out, s->img_n, req_comp, s->img_x,
- s->img_y);
+ out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
}
- if (out == NULL)
- return out; // stbi__convert_format frees input on failure
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
}
return out;
}
static int stbi__pnm_isspace(char c) {
- return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f'
- || c == '\r';
+ return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
}
static void stbi__pnm_skip_whitespace(stbi__context * s, char * c) {
for (;;) {
- while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
- *c = (char) stbi__get8(s);
+ while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char) stbi__get8(s);
if (stbi__at_eof(s) || *c != '#') break;
- while (!stbi__at_eof(s) && *c != '\n' && *c != '\r')
- *c = (char) stbi__get8(s);
+ while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') *c = (char) stbi__get8(s);
}
}
@@ -8098,9 +7753,8 @@ static int stbi__pnm_getinteger(stbi__context * s, char * c) {
value = value * 10 + (*c - '0');
*c = (char) stbi__get8(s);
if ((value > 214748364) || (value == 214748364 && *c > '7'))
- return stbi__err(
- "integer parse overflow",
- "Parsing an integer in the PPM header overflowed a 32-bit int");
+ return stbi__err("integer parse overflow",
+ "Parsing an integer in the PPM header overflowed a 32-bit int");
}
return value;
@@ -8124,22 +7778,19 @@ static int stbi__pnm_info(stbi__context * s, int * x, int * y, int * comp) {
return 0;
}
- *comp = (t == '6') ? 3
- : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
+ *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
c = (char) stbi__get8(s);
stbi__pnm_skip_whitespace(s, &c);
*x = stbi__pnm_getinteger(s, &c); // read width
if (*x == 0)
- return stbi__err("invalid width",
- "PPM image header had zero or overflowing width");
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
stbi__pnm_skip_whitespace(s, &c);
*y = stbi__pnm_getinteger(s, &c); // read height
if (*y == 0)
- return stbi__err("invalid width",
- "PPM image header had zero or overflowing width");
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
stbi__pnm_skip_whitespace(s, &c);
maxv = stbi__pnm_getinteger(s, &c); // read max value
@@ -8193,8 +7844,7 @@ static int stbi__info_main(stbi__context * s, int * x, int * y, int * comp) {
#ifndef STBI_NO_TGA
if (stbi__tga_info(s, x, y, comp)) return 1;
#endif
- return stbi__err("unknown image type",
- "Image not of any known type, or corrupt");
+ return stbi__err("unknown image type", "Image not of any known type, or corrupt");
}
static int stbi__is_16_main(stbi__context * s) {
@@ -8252,15 +7902,15 @@ STBIDEF int stbi_is_16_bit_from_file(FILE * f) {
}
#endif // !STBI_NO_STDIO
-STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x,
- int * y, int * comp) {
+STBIDEF int stbi_info_from_memory(stbi_uc const * buffer, int len, int * x, int * y,
+ int * comp) {
stbi__context s;
stbi__start_mem(&s, buffer, len);
return stbi__info_main(&s, x, y, comp);
}
-STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * c, void * user,
- int * x, int * y, int * comp) {
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const * c, void * user, int * x,
+ int * y, int * comp) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
return stbi__info_main(&s, x, y, comp);
@@ -8272,8 +7922,7 @@ STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const * buffer, int len) {
return stbi__is_16_main(&s);
}
-STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * c,
- void * user) {
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const * c, void * user) {
stbi__context s;
stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
return stbi__is_16_main(&s);
diff --git a/mwe/resource-manager/tiledMap.cpp b/mwe/resource-manager/tiledMap.cpp
index 836929c..85fc30e 100644
--- a/mwe/resource-manager/tiledMap.cpp
+++ b/mwe/resource-manager/tiledMap.cpp
@@ -49,8 +49,7 @@ void TiledMap::SetMapTextures() {
for (const auto & ts : tileSets) {
m_MapTextures.emplace_back(new TextureMap);
- if (!m_MapTextures.back()->loadFromFile(ts.getImagePath(),
- m_Renderer)) {
+ if (!m_MapTextures.back()->loadFromFile(ts.getImagePath(), m_Renderer)) {
std::cerr << "Failed opening " << ts.getImagePath() << "\n";
}
}
@@ -63,8 +62,7 @@ void TiledMap::SetMapLayers() {
for (auto i = 0u; i < mapLayers.size(); ++i) {
if (mapLayers[i]->getType() == tmx::Layer::Type::Tile) {
m_RenderLayers.emplace_back(new MapLayer);
- m_RenderLayers.back()->create(this->m_TmxMap, i,
- this->m_MapTextures);
+ m_RenderLayers.back()->create(this->m_TmxMap, i, this->m_MapTextures);
}
}
}
diff --git a/readme.md b/readme.md
index c83853d..373c682 100644
--- a/readme.md
+++ b/readme.md
@@ -32,6 +32,8 @@ This project uses the following libraries
|`SoLoud`|(latest git `master` version)|
|Google Test (`GTest`)|1.15.2|
|Berkeley DB (`libdb`)|5.3.21|
+|Where Am I?|(latest git `master` version)
+|fontconfig|2.15.0|
> [!NOTE]
> Most of these libraries are likely available from your package manager if you
@@ -49,6 +51,11 @@ $ git submodule update --init --recursive --depth 1
Then, follow these steps for each library you want to install:
+> [!IMPORTANT]
+> A dollar sign prompt (`$`) indicates commands to be run as a regular user,
+> while a hashtag (`#`) is used to denote commands that must be run with
+> privileges (e.g. as root or using `sudo`).
+
1. Change into the library folder (run **one** of these):
```
$ cd lib/googletest
@@ -56,6 +63,7 @@ Then, follow these steps for each library you want to install:
$ cd lib/soloud/contrib
$ cd lib/sdl_image
$ cd lib/sdl_ttf
+ $ cd lib/whereami
```
2. Use CMake to configure the build, run the build and install (run **all** of
these):
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index c3f29da..696856c 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -9,10 +9,12 @@ project(crepe C CXX)
find_package(SDL2 REQUIRED)
find_package(SDL2_image REQUIRED)
+find_package(SDL2_ttf REQUIRED)
find_package(SoLoud REQUIRED)
find_package(GTest REQUIRED)
find_package(whereami REQUIRED)
find_library(BERKELEY_DB db)
+find_library(FONTCONFIG_LIB fontconfig)
add_library(crepe SHARED)
add_executable(test_main EXCLUDE_FROM_ALL)
@@ -24,9 +26,11 @@ target_include_directories(crepe
target_link_libraries(crepe
PRIVATE soloud
PUBLIC SDL2
+ PUBLIC SDL2_ttf
PUBLIC SDL2_image
PUBLIC ${BERKELEY_DB}
PUBLIC whereami
+ PUBLIC ${FONTCONFIG_LIB}
)
add_subdirectory(crepe)
@@ -40,5 +44,6 @@ install(
target_link_libraries(test_main
PRIVATE gtest
+ PRIVATE gmock
PUBLIC crepe
)
diff --git a/src/crepe/CMakeLists.txt b/src/crepe/CMakeLists.txt
index d72d4a0..6cbb9fe 100644
--- a/src/crepe/CMakeLists.txt
+++ b/src/crepe/CMakeLists.txt
@@ -1,26 +1,21 @@
target_sources(crepe PUBLIC
Particle.cpp
- ComponentManager.cpp
Component.cpp
Collider.cpp
- Exception.cpp
Resource.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
- ComponentManager.h
- ComponentManager.hpp
Component.h
Collider.h
ValueBroker.h
ValueBroker.hpp
- Exception.h
- Exception.hpp
Resource.h
)
add_subdirectory(api)
add_subdirectory(facade)
+add_subdirectory(manager)
add_subdirectory(system)
add_subdirectory(util)
diff --git a/src/crepe/Collider.cpp b/src/crepe/Collider.cpp
index 113ba61..77e11c8 100644
--- a/src/crepe/Collider.cpp
+++ b/src/crepe/Collider.cpp
@@ -1,3 +1,5 @@
#include "Collider.h"
using namespace crepe;
+
+Collider::Collider(game_object_id_t id, const vec2 & offset) : Component(id), offset(offset) {}
diff --git a/src/crepe/Collider.h b/src/crepe/Collider.h
index a1e9095..42ccfd4 100644
--- a/src/crepe/Collider.h
+++ b/src/crepe/Collider.h
@@ -1,14 +1,23 @@
#pragma once
#include "Component.h"
+#include "types.h"
namespace crepe {
class Collider : public Component {
public:
- using Component::Component;
+ Collider(game_object_id_t id, const vec2 & offset);
- int size;
+public:
+ /**
+ * \brief Offset of the collider relative to the rigidbody position.
+ *
+ * The `offset` defines the positional shift applied to the collider relative to the position of the rigidbody it is attached to.
+ * This allows the collider to be placed at a different position than the rigidbody.
+ *
+ */
+ vec2 offset;
};
} // namespace crepe
diff --git a/src/crepe/Component.h b/src/crepe/Component.h
index 12c10cb..eff5a58 100644
--- a/src/crepe/Component.h
+++ b/src/crepe/Component.h
@@ -8,15 +8,20 @@ class ComponentManager;
/**
* \brief Base class for all components
- *
- * This class is the base class for all components. It provides a common
- * interface for all components.
+ *
+ * This class is the base class for all components. It provides a common interface for all
+ * components.
*/
class Component {
public:
//! Whether the component is active
bool active = true;
- //! The id of the GameObject this component belongs to
+ /**
+ * \brief The id of the GameObject this component belongs to
+ *
+ * \note Only systems are supposed to use this member, but since friend
+ * relations aren't inherited this needs to be public.
+ */
const game_object_id_t game_object_id;
protected:
@@ -24,16 +29,23 @@ protected:
* \param id The id of the GameObject this component belongs to
*/
Component(game_object_id_t id);
- //! Only the ComponentManager can create components
+ //! Only ComponentManager can create components
friend class ComponentManager;
+ Component(const Component &) = delete;
+ Component(Component &&) = delete;
+ virtual Component & operator=(const Component &) = delete;
+ virtual Component & operator=(Component &&) = delete;
+
+public:
+ virtual ~Component() = default;
+
public:
/**
* \brief Get the maximum number of instances for this component
*
- * This method returns -1 by default, which means that there is no limit
- * for the number of instances. Concrete components can override this method
- * to set a limit.
+ * This method returns -1 by default, which means that there is no limit for the number of
+ * instances. Concrete components can override this method to set a limit.
*
* \return The maximum number of instances for this component
*/
diff --git a/src/crepe/ComponentManager.cpp b/src/crepe/ComponentManager.cpp
deleted file mode 100644
index 7af0380..0000000
--- a/src/crepe/ComponentManager.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-#include "api/GameObject.h"
-#include "util/Log.h"
-
-#include "ComponentManager.h"
-
-using namespace crepe;
-using namespace std;
-
-void ComponentManager::delete_all_components_of_id(game_object_id_t id) {
- // Loop through all the types (in the unordered_map<>)
- for (auto & [type, componentArray] : this->components) {
- // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
- if (id < componentArray.size()) {
- // Clear the components at this specific id
- componentArray[id].clear();
- }
- }
-}
-
-void ComponentManager::delete_all_components() {
- // Clear the whole unordered_map<>
- this->components.clear();
-}
-
-ComponentManager::ComponentManager() { dbg_trace(); }
-ComponentManager::~ComponentManager() { dbg_trace(); }
-
-GameObject ComponentManager::new_object(const string & name, const string & tag,
- const Vector2 & position,
- double rotation, double scale) {
- GameObject object{*this, this->next_id, name, tag,
- position, rotation, scale};
- this->next_id++;
- return object;
-}
diff --git a/src/crepe/ComponentManager.h b/src/crepe/ComponentManager.h
deleted file mode 100644
index 51c84a4..0000000
--- a/src/crepe/ComponentManager.h
+++ /dev/null
@@ -1,132 +0,0 @@
-#pragma once
-
-#include <forward_list>
-#include <memory>
-#include <typeindex>
-#include <unordered_map>
-#include <vector>
-
-#include "Component.h"
-#include "api/Vector2.h"
-
-namespace crepe {
-
-class GameObject;
-
-/**
- * \brief Manages all components
- *
- * This class manages all components. It provides methods to add, delete and get
- * components.
- */
-class ComponentManager {
-public:
- ComponentManager(); // dbg_trace
- ~ComponentManager(); // dbg_trace
-
-protected:
- /**
- * \brief Add a component to the ComponentManager
- *
- * This method adds a component to the ComponentManager. The component is
- * created with the given arguments and added to the ComponentManager.
- *
- * \tparam T The type of the component
- * \tparam Args The types of the arguments
- * \param id The id of the GameObject this component belongs to
- * \param args The arguments to create the component
- * \return The created component
- */
- template <typename T, typename... Args>
- T & add_component(game_object_id_t id, Args &&... args);
- //! GameObject is used as an interface to add components instead of the
- // component manager directly
- friend class GameObject;
-
-public:
- /**
- * \brief Delete all components of a specific type and id
- *
- * This method deletes all components of a specific type and id.
- *
- * \tparam T The type of the component
- * \param id The id of the GameObject this component belongs to
- */
- template <typename T>
- void delete_components_by_id(game_object_id_t id);
- /**
- * \brief Delete all components of a specific type
- *
- * This method deletes all components of a specific type.
- *
- * \tparam T The type of the component
- */
- template <typename T>
- void delete_components();
- /**
- * \brief Delete all components of a specific id
- *
- * This method deletes all components of a specific id.
- *
- * \param id The id of the GameObject this component belongs to
- */
- void delete_all_components_of_id(game_object_id_t id);
- /**
- * \brief Delete all components
- *
- * This method deletes all components.
- */
- void delete_all_components();
- /**
- * \brief Get all components of a specific type and id
- *
- * This method gets all components of a specific type and id.
- *
- * \tparam T The type of the component
- * \param id The id of the GameObject this component belongs to
- * \return A vector of all components of the specific type and id
- */
- template <typename T>
- std::vector<std::reference_wrapper<T>>
- get_components_by_id(game_object_id_t id) const;
- /**
- * \brief Get all components of a specific type
- *
- * This method gets all components of a specific type.
- *
- * \tparam T The type of the component
- * \return A vector of all components of the specific type
- */
- template <typename T>
- std::vector<std::reference_wrapper<T>> get_components_by_type() const;
-
- // TODO: doxygen
- GameObject new_object(const std::string & name,
- const std::string & tag = "",
- const Vector2 & position = {0, 0},
- double rotation = 0, double scale = 0);
-
-private:
- /**
- * \brief The components
- *
- * This unordered_map stores all components. The key is the type of the
- * component and the value is a vector of vectors of unique pointers to the
- * components.
- * Every component type has its own vector of vectors of unique pointers to
- * the components. The first vector is for the ids of the GameObjects and the
- * second vector is for the components (because a GameObject might have multiple
- * components).
- */
- std::unordered_map<std::type_index,
- std::vector<std::vector<std::unique_ptr<Component>>>>
- components;
-
- //! ID of next GameObject
- game_object_id_t next_id = 0;
- std::forward_list<std::unique_ptr<GameObject>> objects;
-};
-
-} // namespace crepe
-
-#include "ComponentManager.hpp"
diff --git a/src/crepe/Exception.cpp b/src/crepe/Exception.cpp
deleted file mode 100644
index 5a24e7e..0000000
--- a/src/crepe/Exception.cpp
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "Exception.h"
-
-using namespace crepe;
-using namespace std;
-
-const char * Exception::what() const noexcept { return error.c_str(); }
-
-Exception::Exception(const string & msg) { this->error = msg; }
diff --git a/src/crepe/Exception.h b/src/crepe/Exception.h
deleted file mode 100644
index 580fc16..0000000
--- a/src/crepe/Exception.h
+++ /dev/null
@@ -1,31 +0,0 @@
-#pragma once
-
-#include <exception>
-#include <format>
-#include <string>
-
-namespace crepe {
-
-//! Exception class
-class Exception : public std::exception {
-public:
- //! Exception with plain message
- Exception(const std::string & msg);
-
- //! Exception with \c std::format message
- template <class... Args>
- Exception(std::format_string<Args...> fmt, Args &&... args);
-
- //! Get formatted error message
- const char * what() const noexcept;
-
-protected:
- Exception() = default;
-
- //! Formatted error message
- std::string error;
-};
-
-} // namespace crepe
-
-#include "Exception.hpp"
diff --git a/src/crepe/Exception.hpp b/src/crepe/Exception.hpp
deleted file mode 100644
index 7c462a3..0000000
--- a/src/crepe/Exception.hpp
+++ /dev/null
@@ -1,12 +0,0 @@
-#pragma once
-
-#include "Exception.h"
-
-namespace crepe {
-
-template <class... Args>
-Exception::Exception(std::format_string<Args...> fmt, Args &&... args) {
- this->error = std::format(fmt, std::forward<Args>(args)...);
-}
-
-} // namespace crepe
diff --git a/src/crepe/Particle.cpp b/src/crepe/Particle.cpp
index 582edf4..b340826 100644
--- a/src/crepe/Particle.cpp
+++ b/src/crepe/Particle.cpp
@@ -2,8 +2,8 @@
using namespace crepe;
-void Particle::reset(uint32_t lifespan, const Vector2 & position,
- const Vector2 & velocity, double angle) {
+void Particle::reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity,
+ float angle) {
// Initialize the particle state
this->time_in_life = 0;
this->lifespan = lifespan;
@@ -15,16 +15,17 @@ void Particle::reset(uint32_t lifespan, const Vector2 & position,
this->force_over_time = {0, 0};
}
-void Particle::update() {
+void Particle::update(double dt) {
// Deactivate particle if it has exceeded its lifespan
- if (++time_in_life >= lifespan) {
+ time_in_life += dt;
+ if (time_in_life >= lifespan) {
this->active = false;
return;
}
// Update velocity based on accumulated force and update position
- this->velocity += force_over_time;
- this->position += velocity;
+ this->velocity += force_over_time * dt;
+ this->position += velocity * dt;
}
void Particle::stop_movement() {
diff --git a/src/crepe/Particle.h b/src/crepe/Particle.h
index 3eaebc3..ee0cd66 100644
--- a/src/crepe/Particle.h
+++ b/src/crepe/Particle.h
@@ -2,56 +2,55 @@
#include <cstdint>
-#include "api/Vector2.h"
+#include "types.h"
namespace crepe {
/**
* \brief Represents a particle in the particle emitter.
*
- * This class stores information about a single particle, including its position,
- * velocity, lifespan, and other properties. Particles can be updated over time
- * to simulate movement and can also be reset or stopped.
+ * This class stores information about a single particle, including its position, velocity,
+ * lifespan, and other properties. Particles can be updated over time to simulate movement and
+ * can also be reset or stopped.
*/
class Particle {
- // TODO: add friend particleSsytem and rendersystem. Unit test will fail.
-
public:
//! Position of the particle in 2D space.
- Vector2 position;
+ vec2 position;
//! Velocity vector indicating the speed and direction of the particle.
- Vector2 velocity;
+ vec2 velocity;
//! Accumulated force affecting the particle over time.
- Vector2 force_over_time;
+ vec2 force_over_time;
//! Total lifespan of the particle in milliseconds.
- uint32_t lifespan;
+ float lifespan;
//! Active state of the particle; true if it is in use, false otherwise.
bool active = false;
//! The time the particle has been alive, in milliseconds.
- uint32_t time_in_life = 0;
+ float time_in_life = 0;
//! The angle at which the particle is oriented or moving.
- double angle = 0;
+ float angle = 0;
/**
* \brief Resets the particle with new properties.
*
- * This method initializes the particle with a specific lifespan, position,
- * velocity, and angle, marking it as active and resetting its life counter.
+ * This method initializes the particle with a specific lifespan, position, velocity, and
+ * angle, marking it as active and resetting its life counter.
*
* \param lifespan The lifespan of the particle in amount of updates.
* \param position The starting position of the particle.
* \param velocity The initial velocity of the particle.
* \param angle The angle of the particle's trajectory or orientation.
*/
- void reset(uint32_t lifespan, const Vector2 & position,
- const Vector2 & velocity, double angle);
+ void reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity,
+ float angle);
/**
* \brief Updates the particle's state.
*
- * Advances the particle's position based on its velocity and applies accumulated forces.
+ * Advances the particle's position based on its velocity and applies accumulated forces.
* Deactivates the particle if its lifespan has expired.
+ * \param dt The amount of fixed delta time that has passed.
*/
- void update();
+ void update(double dt);
/**
* \brief Stops the particle's movement.
*
diff --git a/src/crepe/Resource.cpp b/src/crepe/Resource.cpp
index e254695..85913ed 100644
--- a/src/crepe/Resource.cpp
+++ b/src/crepe/Resource.cpp
@@ -1,6 +1,6 @@
#include "Resource.h"
+#include "manager/Mediator.h"
using namespace crepe;
-Resource::Resource(const Asset & asset) { }
-
+Resource::Resource(const Asset & asset, Mediator & mediator) {}
diff --git a/src/crepe/Resource.h b/src/crepe/Resource.h
index a0c8859..d65206b 100644
--- a/src/crepe/Resource.h
+++ b/src/crepe/Resource.h
@@ -4,23 +4,27 @@ namespace crepe {
class ResourceManager;
class Asset;
+class Mediator;
/**
- * Resource is an interface class used to represent a (deserialized) game
- * resource (e.g. textures, sounds).
+ * \brief Resource interface
+ *
+ * Resource is an interface class used to represent a (deserialized) game resource (e.g.
+ * textures, sounds). Resources are always created from \ref Asset "assets" by ResourceManager.
+ *
+ * The game programmer has the ability to use the ResourceManager to keep instances of concrete
+ * resources between scenes, preventing them from being reinstantiated during a scene
+ * transition.
*/
class Resource {
public:
- Resource(const Asset & src);
+ Resource(const Asset & src, Mediator & mediator);
virtual ~Resource() = default;
-private:
- /**
- * The resource manager uses \c clone to create new instances of the concrete
- * resource class. This may be used to inherit references to classes that
- * would otherwise need to be implemented as singletons.
- */
- friend class ResourceManager;
+ Resource(const Resource &) = delete;
+ Resource(Resource &&) = delete;
+ Resource & operator=(const Resource &) = delete;
+ Resource & operator=(Resource &&) = delete;
};
} // namespace crepe
diff --git a/src/crepe/ValueBroker.h b/src/crepe/ValueBroker.h
index d844d6a..673b660 100644
--- a/src/crepe/ValueBroker.h
+++ b/src/crepe/ValueBroker.h
@@ -7,10 +7,9 @@ namespace crepe {
/**
* \brief Give reference to value through custom set/get functions
*
- * This class can be used to abstract direct access to any arbitrary value
- * through a custom get and set function passed to its constructor. Consumers
- * of this type may want to wrap it in a \c Proxy so it behaves like a regular
- * variable.
+ * This class can be used to abstract direct access to any arbitrary value through a custom get
+ * and set function passed to its constructor. Consumers of this type may want to wrap it in a
+ * \c Proxy so it behaves like a regular variable.
*
* \tparam T Type of the underlying variable
*/
diff --git a/src/crepe/api/AI.cpp b/src/crepe/api/AI.cpp
new file mode 100644
index 0000000..2195249
--- /dev/null
+++ b/src/crepe/api/AI.cpp
@@ -0,0 +1,89 @@
+#include <stdexcept>
+#include <type_traits>
+
+#include "AI.h"
+#include "types.h"
+
+namespace crepe {
+
+AI::AI(game_object_id_t id, float max_force) : Component(id), max_force(max_force) {}
+
+void AI::make_circle_path(float radius, const vec2 & center, float start_angle,
+ bool clockwise) {
+ if (radius <= 0) {
+ throw std::runtime_error("Radius must be greater than 0");
+ }
+
+ // The step size is determined by the radius (step size is in radians)
+ float step = RADIUS_TO_STEP / radius;
+ // Force at least MIN_STEP steps (in case of a small radius)
+ if (step > 2 * M_PI / MIN_STEP) {
+ step = 2 * M_PI / MIN_STEP;
+ }
+ // The path node distance is determined by the step size and the radius
+ this->path_node_distance = radius * step * PATH_NODE_DISTANCE_FACTOR;
+
+ if (clockwise) {
+ for (float i = start_angle; i < 2 * M_PI + start_angle; i += step) {
+ path.push_back(vec2{static_cast<float>(center.x + radius * cos(i)),
+ static_cast<float>(center.y + radius * sin(i))});
+ }
+ } else {
+ for (float i = start_angle; i > start_angle - 2 * M_PI; i -= step) {
+ path.push_back(vec2{static_cast<float>(center.x + radius * cos(i)),
+ static_cast<float>(center.y + radius * sin(i))});
+ }
+ }
+}
+
+void AI::make_oval_path(float radius_x, float radius_y, const vec2 & center, float start_angle,
+ bool clockwise, float rotation) {
+ if (radius_x <= 0 && radius_y <= 0) {
+ throw std::runtime_error("Radius must be greater than 0");
+ }
+
+ float max_radius = std::max(radius_x, radius_y);
+ // The step size is determined by the radius (step size is in radians)
+ float step = RADIUS_TO_STEP / max_radius;
+ // Force at least MIN_STEP steps (in case of a small radius)
+ if (step > 2 * M_PI / MIN_STEP) {
+ step = 2 * M_PI / MIN_STEP;
+ }
+ // The path node distance is determined by the step size and the radius
+ this->path_node_distance = max_radius * step * PATH_NODE_DISTANCE_FACTOR;
+
+ std::function<vec2(vec2, vec2)> rotate_point = [rotation](vec2 point, vec2 center) {
+ float s = sin(rotation);
+ float c = cos(rotation);
+
+ // Translate point back to origin
+ point.x -= center.x;
+ point.y -= center.y;
+
+ // Rotate point
+ float xnew = point.x * c - point.y * s;
+ float ynew = point.x * s + point.y * c;
+
+ // Translate point back
+ point.x = xnew + center.x;
+ point.y = ynew + center.y;
+
+ return point;
+ };
+
+ if (clockwise) {
+ for (float i = start_angle; i < 2 * M_PI + start_angle; i += step) {
+ vec2 point = {static_cast<float>(center.x + radius_x * cos(i)),
+ static_cast<float>(center.y + radius_y * sin(i))};
+ path.push_back(rotate_point(point, center));
+ }
+ } else {
+ for (float i = start_angle; i > start_angle - 2 * M_PI; i -= step) {
+ vec2 point = {static_cast<float>(center.x + radius_x * cos(i)),
+ static_cast<float>(center.y + radius_y * sin(i))};
+ path.push_back(rotate_point(point, center));
+ }
+ }
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h
new file mode 100644
index 0000000..c780a91
--- /dev/null
+++ b/src/crepe/api/AI.h
@@ -0,0 +1,128 @@
+#pragma once
+
+#include "Component.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief The AI component is used to control the movement of an entity using AI.
+ *
+ * The AI component can be used to control the movement of an entity. The AI component can be used
+ * to implement different behaviors such as seeking, fleeing, arriving, and path following.
+ */
+class AI : public Component {
+public:
+ //! The different types of behaviors that can be used
+ enum BehaviorTypeMask {
+ SEEK = 0x00002,
+ FLEE = 0x00004,
+ ARRIVE = 0x00008,
+ PATH_FOLLOW = 0x00010,
+ };
+
+public:
+ /**
+ * \param id The id of the game object
+ * \param max_force The maximum force that can be applied to the entity
+ */
+ AI(game_object_id_t id, float max_force);
+
+ /**
+ * \brief Check if a behavior is on (aka activated)
+ *
+ * \param behavior The behavior to check
+ * \return true if the behavior is on, false otherwise
+ */
+ bool on(BehaviorTypeMask behavior) const { return (flags & behavior); }
+ //! Turn on the seek behavior
+ void seek_on() { flags |= SEEK; }
+ //! Turn off the seek behavior
+ void seek_off() { flags &= ~SEEK; }
+ //! Turn on the flee behavior
+ void flee_on() { flags |= FLEE; }
+ //! Turn off the flee behavior
+ void flee_off() { flags &= ~FLEE; }
+ //! Turn on the arrive behavior
+ void arrive_on() { flags |= ARRIVE; }
+ //! Turn off the arrive behavior
+ void arrive_off() { flags &= ~ARRIVE; }
+ //! Turn on the path follow behavior
+ void path_follow_on() { flags |= PATH_FOLLOW; }
+ //! Turn off the path follow behavior
+ void path_follow_off() { flags &= ~PATH_FOLLOW; }
+
+ /**
+ * \brief Add a path node (for the path following behavior)
+ *
+ * \note The path is not relative to the entity's position (it is an absolute path)
+ *
+ * \param node The path node to add
+ */
+ void add_path_node(const vec2 & node) { path.push_back(node); }
+ /**
+ * \brief Make a circle path (for the path following behavior)
+ *
+ * \note The path is not relative to the entity's position (it is an absolute path)
+ *
+ * \param radius The radius of the circle (in game units)
+ * \param center The center of the circle (in game units)
+ * \param start_angle The start angle of the circle (in radians)
+ * \param clockwise The direction of the circle
+ */
+ void make_circle_path(float radius, const vec2 & center = {0, 0}, float start_angle = 0,
+ bool clockwise = true);
+ /**
+ * \brief Make an oval path (for the path following behavior)
+ *
+ * \note The path is not relative to the entity's position (it is an absolute path)
+ *
+ * \param radius_x The x radius of the oval (in game units)
+ * \param radius_y The y radius of the oval (in game units)
+ * \param center The center of the oval (in game units)
+ * \param start_angle The start angle of the oval (in radians)
+ * \param clockwise The direction of the oval
+ * \param rotation The rotation of the oval (in radians)
+ */
+ void make_oval_path(float radius_x, float radius_y, const vec2 & center = {0, 0},
+ float start_angle = 0, bool clockwise = true, float rotation = 0);
+
+public:
+ //! The maximum force that can be applied to the entity (higher values will make the entity adjust faster)
+ float max_force;
+
+ //! The target to seek at
+ vec2 seek_target;
+ //! The target to arrive at
+ vec2 arrive_target;
+ //! 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 = 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 (for the path following behavior)
+ std::vector<vec2> path;
+ //! The distance from the path node at which the entity will move to the next node (automatically set by make_circle_path())
+ 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 should access the flags and path_index variables
+ friend class AISystem;
+
+ //! The minimum amount of steps for the path following behavior
+ static constexpr int MIN_STEP = 16;
+ //! The radius to step size ratio for the path following behavior
+ static constexpr float RADIUS_TO_STEP = 400.0f;
+ //! The path node distance factor for the path following behavior
+ static constexpr float PATH_NODE_DISTANCE_FACTOR = 0.75f;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp
index 54b2ec3..4ce4bf0 100644
--- a/src/crepe/api/Animator.cpp
+++ b/src/crepe/api/Animator.cpp
@@ -1,6 +1,4 @@
-#include <cstdint>
-
#include "util/Log.h"
#include "Animator.h"
@@ -9,19 +7,51 @@
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, Sprite & spritesheet, const ivec2 & single_frame_size,
+ const uvec2 & grid_size, const Animator::Data & data)
: Component(id),
- spritesheet(ss),
- row(row),
- col(col) {
+ spritesheet(spritesheet),
+ grid_size(grid_size),
+ data(data) {
dbg_trace();
- animator_rect = spritesheet.sprite_rect;
- animator_rect.h /= col;
- animator_rect.w /= row;
- animator_rect.x = 0;
- animator_rect.y = col_animator * animator_rect.h;
- this->active = false;
+ this->spritesheet.mask.w = single_frame_size.x;
+ this->spritesheet.mask.h = single_frame_size.y;
+ this->spritesheet.mask.x = 0;
+ this->spritesheet.mask.y = 0;
+
+ this->spritesheet.aspect_ratio
+ = static_cast<float>(single_frame_size.x) / single_frame_size.y;
}
+
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.col = 0;
+ this->data.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) {
+ Animator::Data & ctx = this->data;
+ this->spritesheet.mask.x = ctx.row = 0;
+ ctx.col = col;
+ this->spritesheet.mask.y = ctx.col * this->spritesheet.mask.h;
+}
+
+void Animator::next_anim() {
+ Animator::Data & ctx = this->data;
+ ctx.row = ctx.row++ % this->grid_size.x;
+ this->spritesheet.mask.x = ctx.row * this->spritesheet.mask.w;
+}
diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h
index 75b8139..5918800 100644
--- a/src/crepe/api/Animator.h
+++ b/src/crepe/api/Animator.h
@@ -1,6 +1,6 @@
#pragma once
-#include <cstdint>
+#include "../types.h"
#include "Component.h"
#include "Sprite.h"
@@ -11,67 +11,94 @@ class AnimatorSystem;
class SDLContext;
/**
- * \brief The Animator component is used to animate sprites by managing the movement
- * and frame changes within a sprite sheet.
+ * \brief The Animator component is used to animate sprites by managing the movement and frame
+ * changes within a sprite sheet.
*
- * This component allows for controlling sprite animation through rows and columns of a sprite sheet.
- * It can be used to play animations, loop them, or stop them.
+ * This component allows for controlling sprite animation through rows and columns of a sprite
+ * sheet. It can be used to play animations, loop them, or stop them.
*/
class Animator : public Component {
+public:
+ struct Data {
+ //! frames per second for animation
+ unsigned int fps = 1;
+ //! The current col being animated.
+ unsigned int col = 0;
+ //! The current row being animated.
+ unsigned int row = 0;
+ //! should the animation loop
+ bool looping = false;
+ //! starting frame for cycling
+ unsigned int cycle_start = 0;
+ //! end frame for cycling (-1 = use last frame)
+ int cycle_end = -1;
+ };
public:
- //TODO: need to implement this
+ //! Animator will repeat the animation
void loop();
+ //! starts the animation
+ void play();
+ //! pauses the animation
+ void pause();
+ /**
+ * \brief stops the animation
+ *
+ * sets the active on false and resets all the current rows and columns
+ */
void stop();
+ /**
+ * \brief set frames per second
+ *
+ * \param fps frames per second
+ */
+ void set_fps(int fps);
+ /**
+ * \brief set the range in the row
+ *
+ * \param start of row animation
+ * \param end of row animation
+ */
+ void set_cycle_range(int start, int end);
+ /**
+ * \brief select which column to animate from
+ *
+ * \param col animation column
+ */
+ void set_anim(int col);
+ //! will go to the next animaiton of current row
+ void next_anim();
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 spritesheet the reference to the spritesheet
+ * \param single_frame_size the width and height in pixels of a single frame inside the
+ * spritesheet
+ * \param grid_size the max rows and columns inside the given spritesheet
+ * \param data extra animation data for more control
*
- * This constructor sets up the Animator with the given parameters, and initializes the animation system.
+ * This constructor sets up the Animator with the given parameters, and initializes the
+ * animation system.
*/
- Animator(game_object_id_t id, Sprite & spritesheet, int row, int col,
- int col_animate);
-
+ Animator(game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size,
+ const uvec2 & grid_size, const Animator::Data & data);
~Animator(); // dbg_trace
- Animator(const Animator &) = delete;
- Animator(Animator &&) = delete;
- Animator & operator=(const Animator &) = delete;
- Animator & operator=(Animator &&) = delete;
+
+public:
+ Animator::Data data;
private:
- //! A reference to the Sprite sheet containing the animation frames.
+ //! 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 maximum number of rows and columns inside the spritesheet
+ const uvec2 grid_size;
- //! The current row being animated.
- int curr_row = 0;
-
- Rect animator_rect;
-
- //TODO: Is this necessary?
- //int fps;
-
-private:
- //! AnimatorSystem adjust the private member parameters of Animator;
- friend class AnimatorSystem;
-
- //! SDLContext reads the Animator member var's
- friend class SDLContext;
+ //! Uses the spritesheet
+ friend AnimatorSystem;
};
+
} // namespace crepe
-//
diff --git a/src/crepe/api/Asset.cpp b/src/crepe/api/Asset.cpp
index 5271cf7..e148367 100644
--- a/src/crepe/api/Asset.cpp
+++ b/src/crepe/api/Asset.cpp
@@ -2,34 +2,33 @@
#include <stdexcept>
#include <whereami.h>
-#include "Asset.h"
#include "api/Config.h"
+#include "Asset.h"
+
using namespace crepe;
using namespace std;
-Asset::Asset(const string & src) : src(find_asset(src)) { }
-Asset::Asset(const char * src) : src(find_asset(src)) { }
+Asset::Asset(const string & src) : src(find_asset(src)) {}
+Asset::Asset(const char * src) : src(find_asset(src)) {}
const string & Asset::get_path() const noexcept { return this->src; }
string Asset::find_asset(const string & src) const {
auto & cfg = Config::get_instance();
- auto & root_pattern = cfg.asset.root_pattern;
+ string & root_pattern = cfg.asset.root_pattern;
// if root_pattern is empty, find_asset must return all paths as-is
if (root_pattern.empty()) return src;
// absolute paths do not need to be resolved, only canonicalized
filesystem::path path = src;
- if (path.is_absolute())
- return filesystem::canonical(path);
+ if (path.is_absolute()) return filesystem::canonical(path);
// find directory matching root_pattern
filesystem::path root = this->whereami();
while (1) {
- if (filesystem::exists(root / root_pattern))
- break;
+ if (filesystem::exists(root / root_pattern)) break;
if (!root.has_parent_path())
throw runtime_error(format("Asset: Cannot find root pattern ({})", root_pattern));
root = root.parent_path();
@@ -48,11 +47,8 @@ string Asset::whereami() const noexcept {
return path;
}
-bool Asset::operator==(const Asset & other) const noexcept {
- return this->src == other.src;
-}
+bool Asset::operator==(const Asset & other) const noexcept { return this->src == other.src; }
size_t std::hash<const Asset>::operator()(const Asset & asset) const noexcept {
return std::hash<string>{}(asset.get_path());
};
-
diff --git a/src/crepe/api/Asset.h b/src/crepe/api/Asset.h
index 05dccba..bfd0ac7 100644
--- a/src/crepe/api/Asset.h
+++ b/src/crepe/api/Asset.h
@@ -1,7 +1,6 @@
#pragma once
#include <string>
-#include <unordered_map>
namespace crepe {
@@ -34,13 +33,29 @@ public:
* \param other Possibly different instance of \c Asset to test equality against
* \return True if \c this and \c other are equal
*/
- bool operator == (const Asset & other) const noexcept;
+ bool operator==(const Asset & other) const noexcept;
private:
//! path to asset
const std::string src;
private:
+ /**
+ * \brief Locate asset path, or throw exception if it cannot be found
+ *
+ * This function resolves asset locations relative to crepe::Config::root_pattern if it is
+ * set and \p src is a relative path. If \p src is an absolute path, it is canonicalized.
+ * This function only returns if the file can be found.
+ *
+ * \param src Arbitrary path to resource file
+ *
+ * \returns \p src if crepe::Config::root_pattern is empty
+ * \returns Canonical path to \p src
+ *
+ * \throws std::runtime_error if root_pattern cannot be found
+ * \throws std::filesystem::filesystem_error if the resolved path does not exist
+ * \throws std::filesystem::filesystem_error if the path cannot be canonicalized
+ */
std::string find_asset(const std::string & src) const;
/**
* \returns The path to the current executable
@@ -52,9 +67,18 @@ private:
namespace std {
-template<> struct hash<const crepe::Asset> {
+//! Hash helper struct
+template <>
+struct hash<const crepe::Asset> {
+ /**
+ * \brief Hash operator for crepe::Asset
+ *
+ * This function hashes a crepe::Asset instance, allowing it to be used as a key in an \c
+ * std::unordered_map.
+ *
+ * \returns Hash value
+ */
size_t operator()(const crepe::Asset & asset) const noexcept;
};
-}
-
+} // namespace std
diff --git a/src/crepe/api/AudioSource.cpp b/src/crepe/api/AudioSource.cpp
index 4baac9a..7b05cb1 100644
--- a/src/crepe/api/AudioSource.cpp
+++ b/src/crepe/api/AudioSource.cpp
@@ -3,18 +3,13 @@
using namespace crepe;
using namespace std;
-AudioSource::AudioSource(game_object_id_t id, const Asset & src) :
- Component(id),
- source(src)
-{ }
+AudioSource::AudioSource(game_object_id_t id, const Asset & src)
+ : Component(id),
+ source(src) {}
void AudioSource::play(bool looping) {
this->loop = looping;
- this->playing = true;
-}
-
-void AudioSource::stop() {
- this->playing = false;
- this->rewind = true;
+ this->oneshot_play = true;
}
+void AudioSource::stop() { this->oneshot_stop = true; }
diff --git a/src/crepe/api/AudioSource.h b/src/crepe/api/AudioSource.h
index 8a78927..b20e490 100644
--- a/src/crepe/api/AudioSource.h
+++ b/src/crepe/api/AudioSource.h
@@ -1,20 +1,35 @@
#pragma once
#include "../Component.h"
+#include "../facade/SoundHandle.h"
#include "../types.h"
#include "Asset.h"
+#include "GameObject.h"
namespace crepe {
+class AudioSystem;
+
//! Audio source component
class AudioSource : public Component {
-public:
+ //! AudioSource components are handled by AudioSystem
+ friend class AudioSystem;
+
+protected:
+ /**
+ * \param source Sound sample to load
+ */
AudioSource(game_object_id_t id, const Asset & source);
+ //! Only ComponentManager creates components
+ friend class ComponentManager;
+
+public:
+ // std::unique_ptr needs to be able to destoy this component
virtual ~AudioSource() = default;
public:
- //! Start or resume this audio source
+ //! Start this audio source
void play(bool looping = false);
//! Stop this audio source
void stop();
@@ -31,21 +46,29 @@ private:
//! This audio source's clip
const Asset source;
- //! If this source is playing audio
- bool playing = false;
- //! Rewind the sample location
- 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;
+ /**
+ * \name One-shot state variables
+ *
+ * These variables trigger function calls when set to true, and are unconditionally reset on
+ * every system update.
+ *
+ * \{
+ */
+ //! Play this sample
+ bool oneshot_play = false;
+ //! Stop this sample
+ bool oneshot_stop = false;
+ //! \}
+ /**
+ * \name State diffing variables
+ * \{
+ */
+ typeof(active) last_active = false;
+ typeof(volume) last_volume = volume;
+ typeof(loop) last_loop = loop;
+ //! \}
+ //! This source's voice handle
+ SoundHandle voice{};
};
} // namespace crepe
-
diff --git a/src/crepe/api/BehaviorScript.cpp b/src/crepe/api/BehaviorScript.cpp
index 7bbace0..d22afdf 100644
--- a/src/crepe/api/BehaviorScript.cpp
+++ b/src/crepe/api/BehaviorScript.cpp
@@ -4,12 +4,12 @@
using namespace crepe;
-BehaviorScript::BehaviorScript(game_object_id_t id, ComponentManager & mgr)
+BehaviorScript::BehaviorScript(game_object_id_t id, Mediator & mediator)
: Component(id),
- component_manager(mgr) {}
+ mediator(mediator) {}
template <>
BehaviorScript & GameObject::add_component<BehaviorScript>() {
ComponentManager & mgr = this->component_manager;
- return mgr.add_component<BehaviorScript>(this->id, mgr);
+ return mgr.add_component<BehaviorScript>(this->id, mgr.mediator);
}
diff --git a/src/crepe/api/BehaviorScript.h b/src/crepe/api/BehaviorScript.h
index 2982358..3909b96 100644
--- a/src/crepe/api/BehaviorScript.h
+++ b/src/crepe/api/BehaviorScript.h
@@ -3,6 +3,7 @@
#include <memory>
#include "../Component.h"
+
#include "GameObject.h"
namespace crepe {
@@ -14,54 +15,56 @@ class Script;
/**
* \brief Script component
*
- * This class acts as a (component) wrapper around an instance of (a class
- * derivatived from) \c Script. \c BehaviorScript is the only ECS component
- * that stores member function implementations as data.
+ * This class acts as a (component) wrapper around an instance of (a class derivatived from) \c
+ * Script. \c BehaviorScript is the only ECS component that stores member function
+ * implementations as data.
*/
class BehaviorScript : public Component {
protected:
- BehaviorScript(game_object_id_t id, ComponentManager & component_manager);
+ /**
+ * \param id Parent \c GameObject id
+ * \param mediator Mediator reference
+ *
+ * \note Calls to this constructor (should) always pass through \c GameObject::add_component,
+ * which has an exception for this specific component type. This was done so the user does
+ * not have to pass references used within \c Script to each \c BehaviorScript instance.
+ */
+ BehaviorScript(game_object_id_t id, Mediator & mediator);
//! Only ComponentManager is allowed to instantiate BehaviorScript
friend class ComponentManager;
public:
- ~BehaviorScript() = default;
-
-public:
/**
* \brief Set the concrete script of this component
*
* \tparam T Concrete script type (derived from \c crepe::Script)
+ * \tparam Args Arguments for concrete script constructor
+ *
+ * \param args Arguments for concrete script constructor (forwarded using perfect forwarding)
*
* \returns Reference to BehaviorScript component (`*this`)
*/
- template <class T>
- BehaviorScript & set_script();
+ template <class T, typename... Args>
+ BehaviorScript & set_script(Args &&... args);
protected:
- //! ScriptSystem needs direct access to the script instance
- friend class ScriptSystem;
- //! Flag to indicate if script->init() has been called already
- bool initialized = false;
//! Script instance
std::unique_ptr<Script> script = nullptr;
- //! Reference to component manager
- ComponentManager & component_manager;
+ //! ScriptSystem needs direct access to the script instance
+ friend class ScriptSystem;
-private:
- //! Script accesses the component manager directly via its parent
- // (BehaviorScript) reference
- friend class Script;
+protected:
+ //! Reference mediator
+ Mediator & mediator;
};
/**
* \brief Add a BehaviorScript component to this game object
*
- * The \c BehaviorScript class is the only exception to the ECS harmony, and
- * requires a reference to the component manager passed to its constructor in
- * order to function normally. This is because the \c BehaviorScript (and \c
- * Script) classes are the only component-related classes that store
- * implemented member functions as data.
+ * The \c BehaviorScript class is the only exception to the ECS harmony, and requires a
+ * reference to the component manager passed to its constructor in order to function normally.
+ * This is because the \c BehaviorScript (and \c Script) classes are the only component-related
+ * classes that store implemented member functions as data.
*/
template <>
BehaviorScript & GameObject::add_component<BehaviorScript>();
diff --git a/src/crepe/api/BehaviorScript.hpp b/src/crepe/api/BehaviorScript.hpp
index eec26da..b9bb1e2 100644
--- a/src/crepe/api/BehaviorScript.hpp
+++ b/src/crepe/api/BehaviorScript.hpp
@@ -9,14 +9,16 @@
namespace crepe {
-template <class T>
-BehaviorScript & BehaviorScript::set_script() {
+template <class T, typename... Args>
+BehaviorScript & BehaviorScript::set_script(Args &&... args) {
dbg_trace();
static_assert(std::is_base_of<Script, T>::value);
- Script * s = new T();
- s->parent_ref = this;
- s->component_manager_ref = &this->component_manager;
- this->script = std::unique_ptr<Script>(s);
+ this->script = std::unique_ptr<Script>(new T(std::forward<Args>(args)...));
+
+ this->script->game_object_id = this->game_object_id;
+ this->script->active = this->active;
+ this->script->mediator = this->mediator;
+
return *this;
}
diff --git a/src/crepe/api/BoxCollider.cpp b/src/crepe/api/BoxCollider.cpp
new file mode 100644
index 0000000..a893d41
--- /dev/null
+++ b/src/crepe/api/BoxCollider.cpp
@@ -0,0 +1,10 @@
+#include "BoxCollider.h"
+
+#include "../Collider.h"
+
+using namespace crepe;
+
+BoxCollider::BoxCollider(game_object_id_t game_object_id, const vec2 & dimensions,
+ const vec2 & offset)
+ : Collider(game_object_id, offset),
+ dimensions(dimensions) {}
diff --git a/src/crepe/api/BoxCollider.h b/src/crepe/api/BoxCollider.h
new file mode 100644
index 0000000..d643e7f
--- /dev/null
+++ b/src/crepe/api/BoxCollider.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include "../Collider.h"
+#include "Vector2.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief A class representing a box-shaped collider.
+ *
+ * This class is used for collision detection with other colliders (e.g., CircleCollider).
+ */
+class BoxCollider : public Collider {
+public:
+ BoxCollider(game_object_id_t game_object_id, const vec2 & dimensions,
+ const vec2 & offset = {0, 0});
+
+ //! Width and height of the box collider
+ vec2 dimensions;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Button.cpp b/src/crepe/api/Button.cpp
new file mode 100644
index 0000000..305922c
--- /dev/null
+++ b/src/crepe/api/Button.cpp
@@ -0,0 +1,10 @@
+#include "Button.h"
+
+namespace crepe {
+
+Button::Button(game_object_id_t id, const vec2 & dimensions, const vec2 & offset,
+ const std::function<void()> & on_click)
+ : UIObject(id, dimensions, offset),
+ on_click(on_click) {}
+
+} // namespace crepe
diff --git a/src/crepe/api/Button.h b/src/crepe/api/Button.h
new file mode 100644
index 0000000..08f5dec
--- /dev/null
+++ b/src/crepe/api/Button.h
@@ -0,0 +1,57 @@
+#pragma once
+
+#include <functional>
+
+#include "UIObject.h"
+
+namespace crepe {
+
+//! Represents a clickable UI button, derived from the UiObject class.
+class Button : public UIObject {
+public:
+ /**
+ * \brief Constructs a Button with the specified game object ID and dimensions.
+ *
+ * \param id The unique ID of the game object associated with this button.
+ * \param dimensions The width and height of the UIObject
+ * \param offset The offset relative this GameObjects Transform
+ * \param on_click callback function that will be invoked when the button is clicked.
+ */
+ Button(game_object_id_t id, const vec2 & dimensions, const vec2 & offset,
+ const std::function<void()> & on_click);
+
+ // TODO: create separate toggle button class
+ /**
+ * \brief The callback function to be executed when the button is clicked.
+ *
+ * This function is invoked whenever the button is clicked. It can be set to any
+ * function that matches the signature `void()`.
+ */
+ std::function<void()> on_click = nullptr;
+
+ /**
+ * \brief Callback function to be executed when the mouse enters the button's boundaries.
+ *
+ * This function is triggered when the mouse cursor moves over the button, allowing
+ * custom actions like visual effects, highlighting, or sound effects.
+ */
+ std::function<void()> on_mouse_enter = nullptr;
+
+ /**
+ * \brief Callback function to be executed when the mouse exits the button's boundaries.
+ *
+ * This function is triggered when the mouse cursor moves out of the button's area,
+ * allowing custom actions like resetting visual effects or playing exit-related effects.
+ */
+ std::function<void()> on_mouse_exit = nullptr;
+
+private:
+ //! friend relation for is_pressed and hover variables
+ friend class InputSystem;
+ //! Indicates whether the mouse is currently hovering over the button
+ bool hover = false;
+
+public:
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/CMakeLists.txt b/src/crepe/api/CMakeLists.txt
index b452f37..e8d6f92 100644
--- a/src/crepe/api/CMakeLists.txt
+++ b/src/crepe/api/CMakeLists.txt
@@ -1,26 +1,27 @@
target_sources(crepe PUBLIC
AudioSource.cpp
BehaviorScript.cpp
- Script.cpp
GameObject.cpp
Rigidbody.cpp
ParticleEmitter.cpp
Transform.cpp
Color.cpp
- Texture.cpp
- ResourceManager.cpp
Sprite.cpp
- SaveManager.cpp
Config.cpp
Metadata.cpp
- Scene.cpp
- SceneManager.cpp
- Vector2.cpp
Camera.cpp
Animator.cpp
+ BoxCollider.cpp
+ CircleCollider.cpp
LoopManager.cpp
- LoopTimer.cpp
Asset.cpp
+ EventHandler.cpp
+ Script.cpp
+ Button.cpp
+ UIObject.cpp
+ AI.cpp
+ Text.cpp
+ Scene.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
@@ -34,17 +35,22 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES
Rigidbody.h
Sprite.h
Vector2.h
+ Vector2.hpp
Color.h
- Texture.h
- ResourceManager.h
- SaveManager.h
Scene.h
+ Scene.hpp
Metadata.h
- SceneManager.h
- SceneManager.hpp
Camera.h
Animator.h
+ BoxCollider.h
+ CircleCollider.h
+ EventHandler.h
+ EventHandler.hpp
+ Event.h
LoopManager.h
- LoopTimer.h
Asset.h
+ Button.h
+ UIObject.h
+ AI.h
+ Text.h
)
diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp
index 5835bdd..179dc18 100644
--- a/src/crepe/api/Camera.cpp
+++ b/src/crepe/api/Camera.cpp
@@ -1,14 +1,17 @@
#include "util/Log.h"
#include "Camera.h"
-#include "Color.h"
#include "Component.h"
+#include "types.h"
using namespace crepe;
-Camera::Camera(game_object_id_t id, const Color & bg_color)
+Camera::Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size,
+ const Data & data)
: Component(id),
- bg_color(bg_color) {
+ screen(screen),
+ viewport_size(viewport_size),
+ data(data) {
dbg_trace();
}
diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h
index d8c08a6..54d9a73 100644
--- a/src/crepe/api/Camera.h
+++ b/src/crepe/api/Camera.h
@@ -1,9 +1,8 @@
#pragma once
-#include <cstdint>
-
#include "Color.h"
#include "Component.h"
+#include "types.h"
namespace crepe {
@@ -11,45 +10,58 @@ namespace crepe {
* \class Camera
* \brief Represents a camera component for rendering in the game.
*
- * The Camera class defines the view parameters, including background color,
- * aspect ratio, position, and zoom level. It controls what part of the game
- * world is visible on the screen.
+ * The Camera class defines the view parameters, including background color, aspect ratio,
+ * position, and zoom level. It controls what part of the game world is visible on the screen.
*/
class Camera : public Component {
+public:
+ struct Data {
+ /**
+ * \bg_color background color of the game
+ *
+ * This will make the background the same color as the given value.
+ */
+ const Color bg_color = Color::BLACK;
+
+ /**
+ * \zoom Zooming level of the game
+ *
+ * zoom = 1 --> no zoom.
+ * zoom < 1 --> zoom out
+ * zoom > 1 --> zoom in
+ */
+ double zoom = 1;
+
+ //! offset postion from the game object transform component
+ vec2 postion_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 screen is the actual screen size in pixels
+ * \param viewport_size is the view of the world in game units
+ * \param data the camera component data
*/
- Camera(game_object_id_t id, const Color & bg_color);
+ Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size,
+ const Camera::Data & data);
~Camera(); // dbg_trace only
public:
- //! Background color of the camera view.
- Color bg_color;
-
- //! Aspect ratio height for the camera.
- double aspect_height = 480;
-
- //! Aspect ratio width for the camera.
- double aspect_width = 640;
-
- //! X-coordinate of the camera position.
- double x = 0.0;
+ Camera::Data data;
- //! Y-coordinate of the camera position.
- double y = 0.0;
+ //! screen the display size in pixels ( output resolution )
+ const ivec2 screen;
- //! Zoom level of the camera view.
- double zoom = 1.0;
+ //! 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.
* \return Maximum instance count as an integer.
*/
- virtual int get_instances_max() const { return 10; }
+ virtual int get_instances_max() const { return 1; }
};
} // namespace crepe
diff --git a/src/crepe/api/CircleCollider.cpp b/src/crepe/api/CircleCollider.cpp
new file mode 100644
index 0000000..90ab5e7
--- /dev/null
+++ b/src/crepe/api/CircleCollider.cpp
@@ -0,0 +1,8 @@
+#include "CircleCollider.h"
+
+using namespace crepe;
+
+CircleCollider::CircleCollider(game_object_id_t game_object_id, float radius,
+ const vec2 & offset)
+ : Collider(game_object_id, offset),
+ radius(radius) {}
diff --git a/src/crepe/api/CircleCollider.h b/src/crepe/api/CircleCollider.h
index e77a592..22da836 100644
--- a/src/crepe/api/CircleCollider.h
+++ b/src/crepe/api/CircleCollider.h
@@ -1,14 +1,23 @@
#pragma once
+
+#include "Vector2.h"
+
#include "../Collider.h"
namespace crepe {
+/**
+ * \brief A class representing a circle-shaped collider.
+ *
+ * This class is used for collision detection with other colliders (e.g., BoxCollider).
+ */
class CircleCollider : public Collider {
public:
- CircleCollider(game_object_id_t game_object_id, int radius)
- : Collider(game_object_id),
- radius(radius) {}
- int radius;
+ CircleCollider(game_object_id_t game_object_id, float radius,
+ const vec2 & offset = {0, 0});
+
+ //! Radius of the circle collider.
+ float radius;
};
} // namespace crepe
diff --git a/src/crepe/api/Color.cpp b/src/crepe/api/Color.cpp
index 9e5f187..29bd77a 100644
--- a/src/crepe/api/Color.cpp
+++ b/src/crepe/api/Color.cpp
@@ -2,32 +2,11 @@
using namespace crepe;
-Color Color::white = Color(255, 255, 255, 0);
-Color Color::red = Color(255, 0, 0, 0);
-Color Color::green = Color(0, 255, 0, 0);
-Color Color::blue = Color(0, 0, 255, 0);
-Color Color::black = Color(0, 0, 0, 0);
-Color Color::cyan = Color(0, 255, 255, 0);
-Color Color::yellow = Color(255, 255, 0, 0);
-Color Color::magenta = Color(255, 0, 255, 0);
-
-Color::Color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
- this->a = alpha;
- this->r = red;
- this->g = green;
- this->b = blue;
-};
-
-const Color & Color::get_white() { return Color::white; };
-
-const Color & Color::get_red() { return Color::red; };
-const Color & Color::get_green() { return Color::green; };
-const Color & Color::get_blue() { return Color::blue; };
-
-const Color & Color::get_black() { return Color::black; };
-
-const Color & Color::get_cyan() { return Color::cyan; };
-
-const Color & Color::get_yellow() { return Color::yellow; };
-
-const Color & Color::get_magenta() { return Color::magenta; };
+const Color Color::WHITE{0xff, 0xff, 0xff};
+const Color Color::RED{0xff, 0x00, 0x00};
+const Color Color::GREEN{0x00, 0xff, 0x00};
+const Color Color::BLUE{0x00, 0x00, 0xff};
+const Color Color::BLACK{0x00, 0x00, 0x00};
+const Color Color::CYAN{0x00, 0xff, 0xff};
+const Color Color::YELLOW{0xff, 0xff, 0x00};
+const Color Color::MAGENTA{0xff, 0x00, 0xff};
diff --git a/src/crepe/api/Color.h b/src/crepe/api/Color.h
index aa47bf4..84edb5c 100644
--- a/src/crepe/api/Color.h
+++ b/src/crepe/api/Color.h
@@ -4,41 +4,20 @@
namespace crepe {
-// TODO: make Color a struct w/o constructors/destructors
-class Color {
-
- // FIXME: can't these colors be defined as a `static constexpr const Color`
- // instead?
-
-public:
- Color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha);
- static const Color & get_white();
- static const Color & get_red();
- static const Color & get_green();
- static const Color & get_blue();
- static const Color & get_cyan();
- static const Color & get_magenta();
- static const Color & get_yellow();
- static const Color & get_black();
-
-private:
- // TODO: why are these private!?
- uint8_t r;
- uint8_t g;
- uint8_t b;
- uint8_t a;
-
- static Color white;
- static Color red;
- static Color green;
- static Color blue;
- static Color cyan;
- static Color magenta;
- static Color yellow;
- static Color black;
-
-private:
- friend class SDLContext;
+struct Color {
+ uint8_t r = 0x00;
+ uint8_t g = 0x00;
+ uint8_t b = 0x00;
+ uint8_t a = 0xff;
+
+ static const Color WHITE;
+ static const Color RED;
+ static const Color GREEN;
+ static const Color BLUE;
+ static const Color CYAN;
+ static const Color MAGENTA;
+ static const Color YELLOW;
+ static const Color BLACK;
};
} // namespace crepe
diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h
index c3f9474..6b9e3ca 100644
--- a/src/crepe/api/Config.h
+++ b/src/crepe/api/Config.h
@@ -1,33 +1,30 @@
#pragma once
-#include "../util/Log.h"
+#include <string>
-namespace crepe {
+#include "../util/Log.h"
-class Config {
-private:
- Config() = default;
+#include "types.h"
-public:
- ~Config() = default;
+namespace crepe {
-public:
+/**
+ * \brief Global configuration interface
+ *
+ * This class stores engine default settings. Properties on this class are only supposed to be
+ * modified *before* execution is handed over from the game programmer to the engine (i.e. the
+ * main loop is started).
+ */
+struct Config final {
//! Retrieve handle to global Config instance
static Config & get_instance();
- // singleton
- Config(const Config &) = delete;
- Config(Config &&) = delete;
- Config & operator=(const Config &) = delete;
- Config & operator=(Config &&) = delete;
-public:
//! Logging-related settings
struct {
/**
* \brief Log level
*
- * Only messages with equal or higher severity than this value will be
- * logged.
+ * Only messages with equal or higher priority than this value will be logged.
*/
Log::Level level = Log::Level::INFO;
/**
@@ -43,8 +40,8 @@ public:
/**
* \brief Save file location
*
- * This location is used by the constructor of SaveManager, and should be
- * set before save manager functionality is attempted to be used.
+ * This location is used by the constructor of SaveManager, and should be set before save
+ * manager functionality is attempted to be used.
*/
std::string location = "save.crepe.db";
} savemgr;
@@ -56,9 +53,16 @@ public:
*
* Gravity value of game.
*/
- double gravity = 1;
+ float gravity = 10;
} physics;
+ //! default window settings
+ struct {
+ //! default screen size in pixels
+ ivec2 default_size = {1280, 720};
+ std::string window_title = "Jetpack joyride clone";
+ } window_settings;
+
//! Asset loading options
struct {
/**
@@ -72,6 +76,28 @@ public:
*/
std::string root_pattern = ".crepe-root";
} asset;
+ //! Default font options
+ struct {
+ /**
+ * \brief Default font size
+ *
+ * Using the SDL_ttf library the font size needs to be set when loading the font.
+ * This config option is the font size at which all fonts will be loaded initially.
+ *
+ */
+ unsigned int size = 16;
+ } font;
+ //! Configuration for click tolerance.
+ struct {
+ //! The maximum number of pixels the mouse can move between MouseDown and MouseUp events to be considered a click.
+ int click_tolerance = 5;
+ } input;
+
+ //! Audio system settings
+ struct {
+ //! Max amount of simultanious voices
+ unsigned int voices = 32;
+ } audio;
};
} // namespace crepe
diff --git a/src/crepe/api/Event.h b/src/crepe/api/Event.h
new file mode 100644
index 0000000..73bf461
--- /dev/null
+++ b/src/crepe/api/Event.h
@@ -0,0 +1,162 @@
+#pragma once
+// TODO discussing the location of these events
+
+#include <string>
+
+#include "api/KeyCodes.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief Base class for all event types in the system.
+ */
+class Event {};
+
+/**
+ * \brief Event triggered when a key is pressed.
+ */
+class KeyPressEvent : public Event {
+public:
+ //! false if first time press, true if key is repeated
+ bool repeat = false;
+
+ //! The key that was pressed.
+ Keycode key = Keycode::NONE;
+};
+
+/**
+ * \brief Event triggered when a key is released.
+ */
+class KeyReleaseEvent : public Event {
+public:
+ //! The key that was released.
+ Keycode key = Keycode::NONE;
+};
+
+/**
+ * \brief Event triggered when a mouse button is pressed.
+ */
+class MousePressEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+
+ //! The mouse button that was pressed.
+ MouseButton button = MouseButton::NONE;
+};
+
+/**
+ * \brief Event triggered when a mouse button is clicked (press and release).
+ */
+class MouseClickEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+
+ //! The mouse button that was clicked.
+ MouseButton button = MouseButton::NONE;
+};
+
+/**
+ * \brief Event triggered when a mouse button is released.
+ */
+class MouseReleaseEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+
+ //! The mouse button that was released.
+ MouseButton button = MouseButton::NONE;
+};
+
+/**
+ * \brief Event triggered when the mouse is moved.
+ */
+class MouseMoveEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+ //! The change in mouse position relative to the last position (in pixels).
+ ivec2 mouse_delta = {0, 0};
+};
+
+/**
+ * \brief Event triggered when the mouse is moved.
+ */
+class MouseScrollEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units) when the scroll happened.
+ vec2 mouse_pos = {0, 0};
+ //! scroll direction (-1 = down, 1 = up)
+ int scroll_direction = 0;
+ //! scroll amount in y axis (from and away from the person).
+ float scroll_delta = 0;
+};
+
+/**
+ * \brief Event triggered when text is submitted, e.g., from a text input.
+ */
+class TextSubmitEvent : public Event {
+public:
+ //! The submitted text.
+ std::string text = "";
+};
+
+/**
+ * \brief Event triggered to indicate the application is shutting down.
+ */
+class ShutDownEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window is overlapped by another window.
+ *
+ * When two windows overlap the bottom window gets distorted and that window has to be redrawn.
+ */
+class WindowExposeEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window is resized.
+ */
+class WindowResizeEvent : public Event {
+public:
+ //! new window dimensions
+ ivec2 dimensions = {0, 0};
+};
+
+/**
+ * \brief Event triggered to indicate the window is moved.
+ */
+class WindowMoveEvent : public Event {
+public:
+ //! The change in position relative to the last position (in pixels).
+ ivec2 delta_move = {0, 0};
+};
+
+/**
+ * \brief Event triggered to indicate the window is minimized.
+ */
+class WindowMinimizeEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window is maximized
+ */
+class WindowMaximizeEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window gained focus
+ *
+ * This event is triggered when the window receives focus, meaning it becomes the active window
+ * for user interaction.
+ */
+class WindowFocusGainEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window lost focus
+ *
+ * This event is triggered when the window loses focus, meaning it is no longer the active window
+ * for user interaction.
+ */
+class WindowFocusLostEvent : public Event {};
+
+} // namespace crepe
diff --git a/src/crepe/api/EventHandler.cpp b/src/crepe/api/EventHandler.cpp
new file mode 100644
index 0000000..4dc232f
--- /dev/null
+++ b/src/crepe/api/EventHandler.cpp
@@ -0,0 +1,5 @@
+#include "EventHandler.h"
+
+using namespace crepe;
+
+bool IEventHandlerWrapper::exec(const Event & e) { return this->call(e); }
diff --git a/src/crepe/api/EventHandler.h b/src/crepe/api/EventHandler.h
new file mode 100644
index 0000000..7bb501b
--- /dev/null
+++ b/src/crepe/api/EventHandler.h
@@ -0,0 +1,96 @@
+#pragma once
+
+#include <functional>
+#include <string>
+
+#include "Event.h"
+
+namespace crepe {
+/**
+ * \brief A type alias for an event handler function.
+ *
+ * The EventHandler is a std::function that takes an EventType reference and returns a boolean value
+ * indicating whether the event is handled.
+ *
+ * \tparam EventType The type of event this handler will handle.
+ *
+ * Returning \c false from an event handler results in the event being propogated to other listeners for the same event type, while returning \c true stops propogation altogether.
+ */
+template <typename EventType>
+using EventHandler = std::function<bool(const EventType & e)>;
+
+/**
+ * \class IEventHandlerWrapper
+ * \brief An abstract base class for event handler wrappers.
+ *
+ * This class provides the interface for handling events. Derived classes must implement the
+ * `call()` method to process events
+ */
+class IEventHandlerWrapper {
+public:
+ /**
+ * \brief Virtual destructor for IEventHandlerWrapper.
+ */
+ virtual ~IEventHandlerWrapper() = default;
+
+ /**
+ * \brief Executes the handler with the given event.
+ *
+ * This method calls the `call()` method of the derived class, passing the event to the handler.
+ *
+ * \param e The event to be processed.
+ * \return A boolean value indicating whether the event is handled.
+ */
+ bool exec(const Event & e);
+
+private:
+ /**
+ * \brief The method responsible for handling the event.
+ *
+ * This method is implemented by derived classes to process the event.
+ *
+ * \param e The event to be processed.
+ * \return A boolean value indicating whether the event is handled.
+ */
+ virtual bool call(const Event & e) = 0;
+};
+
+/**
+ * \class EventHandlerWrapper
+ * \brief A wrapper for event handler functions.
+ *
+ * This class wraps an event handler function of a specific event type. It implements the
+ * `call()` and `get_type()` methods to allow the handler to be executed and its type to be
+ * queried.
+ *
+ * \tparam EventType The type of event this handler will handle.
+ */
+template <typename EventType>
+class EventHandlerWrapper : public IEventHandlerWrapper {
+public:
+ /**
+ * \brief Constructs an EventHandlerWrapper with a given handler.
+ *
+ * The constructor takes an event handler function and stores it in the wrapper.
+ *
+ * \param handler The event handler function.
+ */
+ explicit EventHandlerWrapper(const EventHandler<EventType> & handler);
+
+private:
+ /**
+ * \brief Calls the stored event handler with the event.
+ *
+ * This method casts the event to the appropriate type and calls the handler.
+ *
+ * \param e The event to be handled.
+ * \return A boolean value indicating whether the event is handled.
+ */
+ bool call(const Event & e) override;
+ //! The event handler function.
+ EventHandler<EventType> handler;
+};
+
+} // namespace crepe
+
+#include "EventHandler.hpp"
diff --git a/src/crepe/api/EventHandler.hpp b/src/crepe/api/EventHandler.hpp
new file mode 100644
index 0000000..050e57e
--- /dev/null
+++ b/src/crepe/api/EventHandler.hpp
@@ -0,0 +1,20 @@
+#pragma once
+
+#include <typeindex>
+
+#include "EventHandler.h"
+
+namespace crepe {
+
+// Implementation of EventHandlerWrapper constructor
+template <typename EventType>
+EventHandlerWrapper<EventType>::EventHandlerWrapper(const EventHandler<EventType> & handler)
+ : handler(handler) {}
+
+// Implementation of EventHandlerWrapper::call
+template <typename EventType>
+bool EventHandlerWrapper<EventType>::call(const Event & e) {
+ return this->handler(static_cast<const EventType &>(e));
+}
+
+} //namespace crepe
diff --git a/src/crepe/api/GameObject.cpp b/src/crepe/api/GameObject.cpp
index 4f3c639..9ef4682 100644
--- a/src/crepe/api/GameObject.cpp
+++ b/src/crepe/api/GameObject.cpp
@@ -7,10 +7,9 @@
using namespace crepe;
using namespace std;
-GameObject::GameObject(ComponentManager & component_manager,
- game_object_id_t id, const std::string & name,
- const std::string & tag, const Vector2 & position,
- double rotation, double scale)
+GameObject::GameObject(ComponentManager & component_manager, game_object_id_t id,
+ const std::string & name, const std::string & tag,
+ const vec2 & position, double rotation, double scale)
: id(id),
component_manager(component_manager) {
@@ -24,12 +23,16 @@ void GameObject::set_parent(const GameObject & parent) {
ComponentManager & mgr = this->component_manager;
// Set parent on own Metadata component
- vector<reference_wrapper<Metadata>> this_metadata
- = mgr.get_components_by_id<Metadata>(this->id);
+ RefVector<Metadata> this_metadata = mgr.get_components_by_id<Metadata>(this->id);
this_metadata.at(0).get().parent = parent.id;
// Add own id to children list of parent's Metadata component
- vector<reference_wrapper<Metadata>> parent_metadata
- = mgr.get_components_by_id<Metadata>(parent.id);
+ RefVector<Metadata> parent_metadata = mgr.get_components_by_id<Metadata>(parent.id);
parent_metadata.at(0).get().children.push_back(this->id);
}
+
+void GameObject::set_persistent(bool persistent) {
+ ComponentManager & mgr = this->component_manager;
+
+ mgr.set_persistent(this->id, persistent);
+}
diff --git a/src/crepe/api/GameObject.h b/src/crepe/api/GameObject.h
index 73ff0b8..ff80f49 100644
--- a/src/crepe/api/GameObject.h
+++ b/src/crepe/api/GameObject.h
@@ -2,7 +2,6 @@
#include <string>
-#include "Vector2.h"
#include "types.h"
namespace crepe {
@@ -11,17 +10,16 @@ class ComponentManager;
/**
* \brief Represents a GameObject
- *
- * This class represents a GameObject. The GameObject class is only used
- * as an interface for the game programmer. The actual implementation is
- * done in the ComponentManager.
+ *
+ * This class represents a GameObject. The GameObject class is only used as an interface for
+ * the game programmer. The actual implementation is done in the ComponentManager.
*/
class GameObject {
private:
/**
- * This constructor creates a new GameObject. It creates a new
- * Transform and Metadata component and adds them to the ComponentManager.
- *
+ * This constructor creates a new GameObject. It creates a new Transform and Metadata
+ * component and adds them to the ComponentManager.
+ *
* \param component_manager Reference to component_manager
* \param id The id of the GameObject
* \param name The name of the GameObject
@@ -31,28 +29,28 @@ private:
* \param scale The scale of the GameObject
*/
GameObject(ComponentManager & component_manager, game_object_id_t id,
- const std::string & name, const std::string & tag,
- const Vector2 & position, double rotation, double scale);
+ const std::string & name, const std::string & tag, const vec2 & position,
+ double rotation, double scale);
//! ComponentManager instances GameObject
friend class ComponentManager;
public:
/**
* \brief Set the parent of this GameObject
- *
- * This method sets the parent of this GameObject. It sets the parent
- * in the Metadata component of this GameObject and adds this GameObject
- * to the children list of the parent GameObject.
- *
+ *
+ * This method sets the parent of this GameObject. It sets the parent in the Metadata
+ * component of this GameObject and adds this GameObject to the children list of the parent
+ * GameObject.
+ *
* \param parent The parent GameObject
*/
void set_parent(const GameObject & parent);
/**
* \brief Add a component to the GameObject
- *
- * This method adds a component to the GameObject. It forwards the
- * arguments to the ComponentManager.
- *
+ *
+ * This method adds a component to the GameObject. It forwards the arguments to the
+ * ComponentManager.
+ *
* \tparam T The type of the component
* \tparam Args The types of the arguments
* \param args The arguments to create the component
@@ -60,6 +58,15 @@ public:
*/
template <typename T, typename... Args>
T & add_component(Args &&... args);
+ /**
+ * \brief Components will not be deleted if this method is called
+ *
+ * This method sets the persistent flag of the GameObject to true. If the persistent
+ * flag is set to true, the GameObject will not be deleted when the scene is changed.
+ *
+ * \param persistent The persistent flag
+ */
+ void set_persistent(bool persistent = true);
public:
//! The id of the GameObject
diff --git a/src/crepe/api/GameObject.hpp b/src/crepe/api/GameObject.hpp
index 17b17d7..a6b45b0 100644
--- a/src/crepe/api/GameObject.hpp
+++ b/src/crepe/api/GameObject.hpp
@@ -1,6 +1,6 @@
#pragma once
-#include "../ComponentManager.h"
+#include "../manager/ComponentManager.h"
#include "GameObject.h"
diff --git a/src/crepe/api/KeyCodes.h b/src/crepe/api/KeyCodes.h
new file mode 100644
index 0000000..1b9573a
--- /dev/null
+++ b/src/crepe/api/KeyCodes.h
@@ -0,0 +1,160 @@
+#pragma once
+
+#include <unordered_map>
+
+namespace crepe {
+
+//! Enumeration for mouse button inputs, including standard and extended buttons.
+enum class MouseButton {
+ NONE = 0, //!< No mouse button input.
+ LEFT_MOUSE = 1, //!< Left mouse button.
+ RIGHT_MOUSE = 2, //!< Right mouse button.
+ MIDDLE_MOUSE = 3, //!< Middle mouse button (scroll wheel press).
+ X1_MOUSE = 4, //!< First extended mouse button.
+ X2_MOUSE = 5, //!< Second extended mouse button.
+ SCROLL_UP = 6, //!< Scroll wheel upward movement.
+ SCROLL_DOWN = 7, //!< Scroll wheel downward movement.
+};
+
+//! Enumeration for keyboard key inputs, including printable characters, function keys, and keypad keys.
+enum class Keycode {
+ NONE = 0, //!< No key input.
+ SPACE = 32, //!< Spacebar.
+ APOSTROPHE = 39, //!< Apostrophe (').
+ COMMA = 44, //!< Comma (,).
+ MINUS = 45, //!< Minus (-).
+ PERIOD = 46, //!< Period (.).
+ SLASH = 47, //!< Slash (/).
+ D0 = 48, //!< Digit 0.
+ D1 = 49, //!< Digit 1.
+ D2 = 50, //!< Digit 2.
+ D3 = 51, //!< Digit 3.
+ D4 = 52, //!< Digit 4.
+ D5 = 53, //!< Digit 5.
+ D6 = 54, //!< Digit 6.
+ D7 = 55, //!< Digit 7.
+ D8 = 56, //!< Digit 8.
+ D9 = 57, //!< Digit 9.
+ SEMICOLON = 59, //!< Semicolon (;).
+ EQUAL = 61, //!< Equal sign (=).
+ A = 65, //!< Key 'A'.
+ B = 66, //!< Key 'B'.
+ C = 67, //!< Key 'C'.
+ D = 68, //!< Key 'D'.
+ E = 69, //!< Key 'E'.
+ F = 70, //!< Key 'F'.
+ G = 71, //!< Key 'G'.
+ H = 72, //!< Key 'H'.
+ I = 73, //!< Key 'I'.
+ J = 74, //!< Key 'J'.
+ K = 75, //!< Key 'K'.
+ L = 76, //!< Key 'L'.
+ M = 77, //!< Key 'M'.
+ N = 78, //!< Key 'N'.
+ O = 79, //!< Key 'O'.
+ P = 80, //!< Key 'P'.
+ Q = 81, //!< Key 'Q'.
+ R = 82, //!< Key 'R'.
+ S = 83, //!< Key 'S'.
+ T = 84, //!< Key 'T'.
+ U = 85, //!< Key 'U'.
+ V = 86, //!< Key 'V'.
+ W = 87, //!< Key 'W'.
+ X = 88, //!< Key 'X'.
+ Y = 89, //!< Key 'Y'.
+ Z = 90, //!< Key 'Z'.
+ LEFT_BRACKET = 91, //!< Left bracket ([).
+ BACKSLASH = 92, //!< Backslash (\).
+ RIGHT_BRACKET = 93, //!< Right bracket (]).
+ GRAVE_ACCENT = 96, //!< Grave accent (`).
+ WORLD1 = 161, //!< Non-US key #1.
+ WORLD2 = 162, //!< Non-US key #2.
+ ESCAPE = 256, //!< Escape key.
+ ENTER = 257, //!< Enter key.
+ TAB = 258, //!< Tab key.
+ BACKSPACE = 259, //!< Backspace key.
+ INSERT = 260, //!< Insert key.
+ DELETE = 261, //!< Delete key.
+ RIGHT = 262, //!< Right arrow key.
+ LEFT = 263, //!< Left arrow key.
+ DOWN = 264, //!< Down arrow key.
+ UP = 265, //!< Up arrow key.
+ PAGE_UP = 266, //!< Page Up key.
+ PAGE_DOWN = 267, //!< Page Down key.
+ HOME = 268, //!< Home key.
+ END = 269, //!< End key.
+ CAPS_LOCK = 280, //!< Caps Lock key.
+ SCROLL_LOCK = 281, //!< Scroll Lock key.
+ NUM_LOCK = 282, //!< Num Lock key.
+ PRINT_SCREEN = 283, //!< Print Screen key.
+ PAUSE = 284, //!< Pause key.
+ /**
+ * \name Function keys (F1-F25).
+ * \{
+ */
+ F1 = 290,
+ F2 = 291,
+ F3 = 292,
+ F4 = 293,
+ F5 = 294,
+ F6 = 295,
+ F7 = 296,
+ F8 = 297,
+ F9 = 298,
+ F10 = 299,
+ F11 = 300,
+ F12 = 301,
+ F13 = 302,
+ F14 = 303,
+ F15 = 304,
+ F16 = 305,
+ F17 = 306,
+ F18 = 307,
+ F19 = 308,
+ F20 = 309,
+ F21 = 310,
+ F22 = 311,
+ F23 = 312,
+ F24 = 313,
+ F25 = 314,
+ /// \}
+ /**
+ * \name Keypad digits and operators.
+ * \{
+ */
+ KP0 = 320,
+ KP1 = 321,
+ KP2 = 322,
+ KP3 = 323,
+ KP4 = 324,
+ KP5 = 325,
+ KP6 = 326,
+ KP7 = 327,
+ KP8 = 328,
+ KP9 = 329,
+ KP_DECIMAL = 330,
+ KP_DIVIDE = 331,
+ KP_MULTIPLY = 332,
+ KP_SUBTRACT = 333,
+ KP_ADD = 334,
+ KP_ENTER = 335,
+ KP_EQUAL = 336,
+ /// \}
+ /**
+ * \name Modifier keys.
+ * \{
+ */
+ LEFT_SHIFT = 340,
+ LEFT_CONTROL = 341,
+ LEFT_ALT = 342,
+ LEFT_SUPER = 343,
+ RIGHT_SHIFT = 344,
+ RIGHT_CONTROL = 345,
+ RIGHT_ALT = 346,
+ RIGHT_SUPER = 347,
+ /// \}
+ MENU = 348, //!< Menu key.
+};
+//! Typedef for keyboard state.
+typedef std::unordered_map<Keycode, bool> keyboard_state_t;
+} // namespace crepe
diff --git a/src/crepe/api/LoopManager.cpp b/src/crepe/api/LoopManager.cpp
index f0788ab..7a78019 100644
--- a/src/crepe/api/LoopManager.cpp
+++ b/src/crepe/api/LoopManager.cpp
@@ -1,14 +1,18 @@
#include "../facade/SDLContext.h"
-
+#include "../manager/EventManager.h"
+#include "../manager/LoopTimerManager.h"
+#include "../system/AISystem.h"
#include "../system/AnimatorSystem.h"
+#include "../system/AudioSystem.h"
#include "../system/CollisionSystem.h"
+#include "../system/InputSystem.h"
#include "../system/ParticleSystem.h"
#include "../system/PhysicsSystem.h"
#include "../system/RenderSystem.h"
#include "../system/ScriptSystem.h"
+#include "../util/Log.h"
#include "LoopManager.h"
-#include "LoopTimer.h"
using namespace crepe;
using namespace std;
@@ -20,54 +24,64 @@ LoopManager::LoopManager() {
this->load_system<PhysicsSystem>();
this->load_system<RenderSystem>();
this->load_system<ScriptSystem>();
+ this->load_system<InputSystem>();
+ this->event_manager.subscribe<ShutDownEvent>(
+ [this](const ShutDownEvent & event) { return this->on_shutdown(event); });
+ this->load_system<AudioSystem>();
+ this->load_system<AISystem>();
}
-
-ComponentManager & LoopManager::get_component_manager() {
- return this->component_manager;
-}
-
-void LoopManager::process_input() {
- SDLContext::get_instance().handle_events(this->game_running);
-}
-
void LoopManager::start() {
this->setup();
this->loop();
}
-void LoopManager::set_running(bool running) { this->game_running = running; }
-void LoopManager::fixed_update() {}
+void LoopManager::setup() {
+ this->game_running = true;
+ this->loop_timer.start();
+ this->scene_manager.load_next_scene();
+}
void LoopManager::loop() {
- LoopTimer & timer = LoopTimer::get_instance();
- timer.start();
+ try {
+ while (game_running) {
+ this->loop_timer.update();
- while (game_running) {
- timer.update();
+ while (this->loop_timer.get_lag() >= this->loop_timer.get_fixed_delta_time()) {
+ this->fixed_update();
+ this->loop_timer.advance_fixed_elapsed_time();
+ }
- while (timer.get_lag() >= timer.get_fixed_delta_time()) {
- this->process_input();
- this->fixed_update();
- timer.advance_fixed_update();
+ this->frame_update();
+ this->loop_timer.enforce_frame_rate();
}
-
- this->update();
- this->render();
-
- timer.enforce_frame_rate();
+ } catch (const exception & e) {
+ Log::logf(Log::Level::ERROR, "Exception caught in main loop: {}", e.what());
+ this->event_manager.trigger_event<ShutDownEvent>(ShutDownEvent{});
}
}
-void LoopManager::setup() {
- this->game_running = true;
- LoopTimer::get_instance().start();
- LoopTimer::get_instance().set_fps(60);
+// will be called at a fixed interval
+void LoopManager::fixed_update() {
+ this->get_system<InputSystem>().update();
+ this->event_manager.dispatch_events();
+ this->get_system<ScriptSystem>().update();
+ this->get_system<ParticleSystem>().update();
+ this->get_system<AISystem>().update();
+ this->get_system<PhysicsSystem>().update();
+ this->get_system<CollisionSystem>().update();
+ this->get_system<AudioSystem>().update();
}
-void LoopManager::render() {
- if (this->game_running) {
- this->get_system<RenderSystem>().update();
- }
+// will be called every frame
+void LoopManager::frame_update() {
+ this->scene_manager.load_next_scene();
+ this->get_system<AnimatorSystem>().update();
+ //render
+ this->get_system<RenderSystem>().update();
}
-void LoopManager::update() { LoopTimer & timer = LoopTimer::get_instance(); }
+bool LoopManager::on_shutdown(const ShutDownEvent & e) {
+ this->game_running = false;
+ // propagate to possible user ShutDownEvent listeners
+ return false;
+}
diff --git a/src/crepe/api/LoopManager.h b/src/crepe/api/LoopManager.h
index 288dca2..124cd3a 100644
--- a/src/crepe/api/LoopManager.h
+++ b/src/crepe/api/LoopManager.h
@@ -2,15 +2,40 @@
#include <memory>
-#include "../ComponentManager.h"
+#include "../facade/SDLContext.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/EventManager.h"
+#include "../manager/LoopTimerManager.h"
+#include "../manager/Mediator.h"
+#include "../manager/ResourceManager.h"
+#include "../manager/SaveManager.h"
+#include "../manager/SceneManager.h"
#include "../system/System.h"
namespace crepe {
-
+/**
+ * \brief Main game loop manager
+ *
+ * This class is responsible for managing the game loop, including initialization and updating.
+ */
class LoopManager {
public:
- void start();
LoopManager();
+ /**
+ * \brief Start the gameloop
+ *
+ * This is the start of the engine where the setup is called and then the loop keeps running until the game stops running.
+ * The Game programmer needs to call this function to run the game. This should be done after creating and adding all scenes.
+ */
+ void start();
+
+ /**
+ * \brief Add a new concrete scene to the scene manager
+ *
+ * \tparam T Type of concrete scene
+ */
+ template <typename T>
+ void add_scene();
private:
/**
@@ -27,59 +52,70 @@ private:
void loop();
/**
- * \brief Function for handling input-related system calls.
+ * \brief Per-frame update.
*
- * Processes user inputs from keyboard and mouse.
+ * Updates the game state based on the elapsed time since the last frame.
*/
- void process_input();
+ virtual void frame_update();
/**
- * \brief Per-frame update.
+ * \brief Fixed update executed at a fixed rate.
*
- * Updates the game state based on the elapsed time since the last frame.
+ * This function updates physics and game logic based on LoopTimer's fixed_delta_time.
*/
- void update();
+ virtual void fixed_update();
+
+ //! Indicates whether the game is running.
+ bool game_running = false;
+private:
+ //! Global context
+ Mediator mediator;
/**
- * \brief Late update which is called after update().
+ * \brief Collection of System instances
*
- * This function can be used for final adjustments before rendering.
+ * This map holds System instances indexed by the system's class typeid. It is filled in the
+ * constructor of LoopManager using LoopManager::load_system.
*/
- void late_update();
+ std::unordered_map<std::type_index, std::unique_ptr<System>> systems;
+ //! SDLContext instance
+ SDLContext sdl_context{mediator};
+ //! Resource manager instance
+ ResourceManager resource_manager{mediator};
+
+ //! Component manager instance
+ ComponentManager component_manager{mediator};
+ //! Scene manager instance
+ SceneManager scene_manager{mediator};
+ //! LoopTimerManager instance
+ LoopTimerManager loop_timer{mediator};
+ //! EventManager instance
+ EventManager event_manager{mediator};
+ //! Save manager instance
+ SaveManager save_manager{mediator};
+
+private:
/**
- * \brief Fixed update executed at a fixed rate.
+ * \brief Callback function for ShutDownEvent
*
- * This function updates physics and game logic based on LoopTimer's fixed_delta_time.
+ * This function sets the game_running variable to false, stopping the gameloop and therefor quitting the game.
*/
- void fixed_update();
+ bool on_shutdown(const ShutDownEvent & e);
/**
- * \brief Set game running variable
- *
- * \param running running (false = game shutdown, true = game running)
+ * \brief Initialize a system
+ * \tparam T System type (must be derivative of \c System)
*/
- void set_running(bool running);
+ template <class T>
+ void load_system();
/**
- * \brief Function for executing render-related systems.
- *
- * Renders the current state of the game to the screen.
+ * \brief Retrieve a reference to ECS system
+ * \tparam T System type
+ * \returns Reference to system instance
+ * \throws std::runtime_error if the System is not initialized
*/
- void render();
-
- bool game_running = false;
-
-protected:
- ComponentManager & get_component_manager();
template <class T>
T & get_system();
-
-private:
- ComponentManager component_manager{};
- std::unordered_map<std::type_index, std::unique_ptr<System>> systems;
-
-private:
- template <class T>
- void load_system();
};
} // namespace crepe
diff --git a/src/crepe/api/LoopManager.hpp b/src/crepe/api/LoopManager.hpp
index 8fb9aa3..266758a 100644
--- a/src/crepe/api/LoopManager.hpp
+++ b/src/crepe/api/LoopManager.hpp
@@ -1,9 +1,9 @@
#pragma once
#include <cassert>
+#include <format>
#include <memory>
-#include "../Exception.h"
#include "../system/System.h"
#include "LoopManager.h"
@@ -11,6 +11,11 @@
namespace crepe {
template <class T>
+void LoopManager::add_scene() {
+ this->scene_manager.add_scene<T>();
+}
+
+template <class T>
T & LoopManager::get_system() {
using namespace std;
static_assert(is_base_of<System, T>::value,
@@ -18,7 +23,7 @@ T & LoopManager::get_system() {
const type_info & type = typeid(T);
if (!this->systems.contains(type))
- throw Exception("LoopManager: %s is not initialized", type.name());
+ throw runtime_error(format("LoopManager: {} is not initialized", type.name()));
System * system = this->systems.at(type).get();
T * concrete_system = dynamic_cast<T *>(system);
@@ -33,8 +38,11 @@ void LoopManager::load_system() {
static_assert(is_base_of<System, T>::value,
"load_system must recieve a derivative class of System");
- System * system = new T(this->component_manager);
- this->systems[typeid(T)] = unique_ptr<System>(system);
+ const type_info & type = typeid(T);
+ if (this->systems.contains(type))
+ throw runtime_error(format("LoopManager: {} is already initialized", type.name()));
+ System * system = new T(this->mediator);
+ this->systems[type] = unique_ptr<System>(system);
}
} // namespace crepe
diff --git a/src/crepe/api/LoopTimer.cpp b/src/crepe/api/LoopTimer.cpp
deleted file mode 100644
index b3aec22..0000000
--- a/src/crepe/api/LoopTimer.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-#include <chrono>
-
-#include "../facade/SDLContext.h"
-#include "../util/Log.h"
-
-#include "LoopTimer.h"
-
-using namespace crepe;
-
-LoopTimer::LoopTimer() { dbg_trace(); }
-
-LoopTimer & LoopTimer::get_instance() {
- static LoopTimer instance;
- return instance;
-}
-
-void LoopTimer::start() {
- this->last_frame_time = std::chrono::steady_clock::now();
- this->elapsed_time = std::chrono::milliseconds(0);
- this->elapsed_fixed_time = std::chrono::milliseconds(0);
- this->delta_time = std::chrono::milliseconds(0);
-}
-
-void LoopTimer::update() {
- auto current_frame_time = std::chrono::steady_clock::now();
- // Convert to duration in seconds for delta time
- this->delta_time
- = std::chrono::duration_cast<std::chrono::duration<double>>(
- current_frame_time - last_frame_time);
-
- if (this->delta_time > this->maximum_delta_time) {
- this->delta_time = this->maximum_delta_time;
- }
-
- this->delta_time *= this->game_scale;
- this->elapsed_time += this->delta_time;
- this->last_frame_time = current_frame_time;
-}
-
-double LoopTimer::get_delta_time() const { return this->delta_time.count(); }
-
-double LoopTimer::get_current_time() const {
- return this->elapsed_time.count();
-}
-
-void LoopTimer::advance_fixed_update() {
- this->elapsed_fixed_time += this->fixed_delta_time;
-}
-
-double LoopTimer::get_fixed_delta_time() const {
- return this->fixed_delta_time.count();
-}
-
-void LoopTimer::set_fps(int fps) {
- this->fps = fps;
- // target time per frame in seconds
- this->frame_target_time = std::chrono::seconds(1) / fps;
-}
-
-int LoopTimer::get_fps() const { return this->fps; }
-
-void LoopTimer::set_game_scale(double value) { this->game_scale = value; }
-
-double LoopTimer::get_game_scale() const { return this->game_scale; }
-void LoopTimer::enforce_frame_rate() {
- std::chrono::steady_clock::time_point current_frame_time
- = std::chrono::steady_clock::now();
- std::chrono::milliseconds frame_duration
- = std::chrono::duration_cast<std::chrono::milliseconds>(
- current_frame_time - this->last_frame_time);
-
- if (frame_duration < this->frame_target_time) {
- std::chrono::milliseconds delay_time
- = std::chrono::duration_cast<std::chrono::milliseconds>(
- this->frame_target_time - frame_duration);
- if (delay_time.count() > 0) {
- SDLContext::get_instance().delay(delay_time.count());
- }
- }
-
- this->last_frame_time = current_frame_time;
-}
-
-double LoopTimer::get_lag() const {
- return (this->elapsed_time - this->elapsed_fixed_time).count();
-}
diff --git a/src/crepe/api/LoopTimer.h b/src/crepe/api/LoopTimer.h
deleted file mode 100644
index 85687be..0000000
--- a/src/crepe/api/LoopTimer.h
+++ /dev/null
@@ -1,147 +0,0 @@
-#pragma once
-
-#include <chrono>
-#include <cstdint>
-
-namespace crepe {
-
-class LoopTimer {
-public:
- /**
- * \brief Get the singleton instance of LoopTimer.
- *
- * \return A reference to the LoopTimer instance.
- */
- static LoopTimer & get_instance();
-
- /**
- * \brief Get the current delta time for the current frame.
- *
- * \return Delta time in seconds since the last frame.
- */
- double get_delta_time() const;
-
- /**
- * \brief Get the current game time.
- *
- * \note The current game time may vary from real-world elapsed time.
- * It is the cumulative sum of each frame's delta time.
- *
- * \return Elapsed game time in seconds.
- */
- double get_current_time() const;
-
- /**
- * \brief Set the target frames per second (FPS).
- *
- * \param fps The desired frames rendered per second.
- */
- void set_fps(int fps);
-
- /**
- * \brief Get the current frames per second (FPS).
- *
- * \return Current FPS.
- */
- int get_fps() const;
-
- /**
- * \brief Get the current game scale.
- *
- * \return The current game scale, where 0 = paused, 1 = normal speed, and values > 1 speed up the game.
- */
- double get_game_scale() const;
-
- /**
- * \brief Set the game scale.
- *
- * \param game_scale The desired game scale (0 = pause, 1 = normal speed, > 1 = speed up).
- */
- void set_game_scale(double game_scale);
-
-private:
- friend class LoopManager;
-
- /**
- * \brief Start the loop timer.
- *
- * Initializes the timer to begin tracking frame times.
- */
- void start();
-
- /**
- * \brief Enforce the frame rate limit.
- *
- * Ensures that the game loop does not exceed the target FPS by delaying
- * frame updates as necessary.
- */
- void enforce_frame_rate();
-
- /**
- * \brief Get the fixed delta time for consistent updates.
- *
- * Fixed delta time is used for operations that require uniform time steps,
- * such as physics calculations.
- *
- * \return Fixed delta time in seconds.
- */
- double get_fixed_delta_time() const;
-
- /**
- * \brief Get the accumulated lag in the game loop.
- *
- * Lag represents the difference between the target frame time and the
- * actual frame time, useful for managing fixed update intervals.
- *
- * \return Accumulated lag in seconds.
- */
- double get_lag() const;
-
- /**
- * \brief Construct a new LoopTimer object.
- *
- * Private constructor for singleton pattern to restrict instantiation
- * outside the class.
- */
- LoopTimer();
-
- /**
- * \brief Update the timer to the current frame.
- *
- * Calculates and updates the delta time for the current frame and adds it to
- * the cumulative game time.
- */
- void update();
-
- /**
- * \brief Advance the game loop by a fixed update interval.
- *
- * This method progresses the game state by a consistent, fixed time step,
- * allowing for stable updates independent of frame rate fluctuations.
- */
- void advance_fixed_update();
-
-private:
- //! Current frames per second
- int fps = 50;
- //! Current game scale
- double game_scale = 1;
- //! Maximum delta time in seconds to avoid large jumps
- std::chrono::duration<double> maximum_delta_time{0.25};
- //! Delta time for the current frame in seconds
- std::chrono::duration<double> delta_time{0.0};
- //! Target time per frame in seconds
- std::chrono::duration<double> frame_target_time
- = std::chrono::seconds(1) / fps;
- //! Fixed delta time for fixed updates in seconds
- std::chrono::duration<double> fixed_delta_time
- = std::chrono::seconds(1) / 50;
- //! Total elapsed game time in seconds
- std::chrono::duration<double> elapsed_time{0.0};
- //! Total elapsed time for fixed updates in seconds
- std::chrono::duration<double> elapsed_fixed_time{0.0};
- //! Time of the last frame
- std::chrono::steady_clock::time_point last_frame_time;
-};
-
-} // namespace crepe
diff --git a/src/crepe/api/Metadata.h b/src/crepe/api/Metadata.h
index c61e006..f404703 100644
--- a/src/crepe/api/Metadata.h
+++ b/src/crepe/api/Metadata.h
@@ -9,9 +9,9 @@ namespace crepe {
/**
* \brief Metadata component
- *
- * This class represents the Metadata component. It stores the name, tag, parent
- * and children of a GameObject.
+ *
+ * This class represents the Metadata component. It stores the name, tag, parent and children
+ * of a GameObject.
*/
class Metadata : public Component {
public:
@@ -20,8 +20,7 @@ public:
* \param name The name of the GameObject
* \param tag The tag of the GameObject
*/
- Metadata(game_object_id_t id, const std::string & name,
- const std::string & tag);
+ Metadata(game_object_id_t id, const std::string & name, const std::string & tag);
/**
* \brief Get the maximum number of instances for this component
*
diff --git a/src/crepe/api/ParticleEmitter.cpp b/src/crepe/api/ParticleEmitter.cpp
index 35f960d..4f54bbd 100644
--- a/src/crepe/api/ParticleEmitter.cpp
+++ b/src/crepe/api/ParticleEmitter.cpp
@@ -1,12 +1,14 @@
#include "ParticleEmitter.h"
+#include "api/Sprite.h"
using namespace crepe;
-ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id,
+ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, const Sprite & sprite,
const Data & data)
: Component(game_object_id),
+ sprite(sprite),
data(data) {
for (size_t i = 0; i < this->data.max_particles; i++) {
- this->data.particles.emplace_back();
+ this->particles.emplace_back();
}
}
diff --git a/src/crepe/api/ParticleEmitter.h b/src/crepe/api/ParticleEmitter.h
index a9e872f..8ac2e72 100644
--- a/src/crepe/api/ParticleEmitter.h
+++ b/src/crepe/api/ParticleEmitter.h
@@ -1,10 +1,14 @@
#pragma once
+#include <cmath>
#include <vector>
+#include "system/ParticleSystem.h"
+#include "system/RenderSystem.h"
+
#include "Component.h"
#include "Particle.h"
-#include "Vector2.h"
+#include "types.h"
namespace crepe {
@@ -13,61 +17,60 @@ class Sprite;
/**
* \brief Data holder for particle emission parameters.
*
- * The ParticleEmitter class stores configuration data for particle properties,
- * defining the characteristics and boundaries of particle emissions.
+ * The ParticleEmitter class stores configuration data for particle properties, defining the
+ * characteristics and boundaries of particle emissions.
*/
class ParticleEmitter : public Component {
public:
/**
* \brief Defines the boundary within which particles are constrained.
*
- * This structure specifies the boundary's size and offset, as well as the
- * behavior of particles upon reaching the boundary limits.
+ * This structure specifies the boundary's size and offset, as well as the behavior of
+ * particles upon reaching the boundary limits.
*/
struct Boundary {
//! boundary width (midpoint is emitter location)
- double width = 0.0;
+ float width = INFINITY;
//! boundary height (midpoint is emitter location)
- double height = 0.0;
+ float height = INFINITY;
//! boundary offset from particle emitter location
- Vector2 offset;
+ vec2 offset;
//! reset on exit or stop velocity and set max postion
bool reset_on_exit = false;
};
+ //! sprite reference of displayed sprite
+ const Sprite & sprite;
+
/**
* \brief Holds parameters that control particle emission.
*
- * Contains settings for the emitter’s position, particle speed, angle, lifespan,
- * boundary, and the sprite used for rendering particles.
+ * Contains settings for the emitter’s position, particle speed, angle, lifespan, boundary,
+ * and the sprite used for rendering particles.
*/
struct Data {
- //! position of the emitter
- Vector2 position;
+ //! offset of the emitter relative to transform
+ vec2 offset;
//! maximum number of particles
- const unsigned int max_particles = 0;
- //! rate of particle emission per update (Lowest value = 0.001 any lower is ignored)
- double emission_rate = 0;
+ const unsigned int max_particles = 256;
+ //! rate of particle emission per second
+ float emission_rate = 50;
//! min speed of the particles
- double min_speed = 0;
+ float min_speed = 100;
//! min speed of the particles
- double max_speed = 0;
+ float max_speed = 100;
//! min angle of particle emission
- double min_angle = 0;
+ float min_angle = 0;
//! max angle of particle emission
- double max_angle = 0;
- //! begin Lifespan of particle (only visual)
- double begin_lifespan = 0.0;
- //! end Lifespan of particle
- double end_lifespan = 0.0;
+ float max_angle = 0;
+ //! begin Lifespan of particle in seconds (only visual)
+ float begin_lifespan = 0.0;
+ //! end Lifespan of particle in seconds
+ float end_lifespan = 10.0;
//! force over time (physics)
- Vector2 force_over_time;
+ vec2 force_over_time;
//! particle boundary
Boundary boundary;
- //! collection of particles
- std::vector<Particle> particles;
- //! sprite reference
- const Sprite & sprite;
};
public:
@@ -75,11 +78,21 @@ public:
* \param game_object_id Identifier for the game object using this emitter.
* \param data Configuration data defining particle properties.
*/
- ParticleEmitter(game_object_id_t game_object_id, const Data & data);
+ ParticleEmitter(game_object_id_t game_object_id, const Sprite & sprite, const Data & data);
public:
//! Configuration data for particle emission settings.
Data data;
+
+private:
+ //! Only ParticleSystem can move and read particles
+ friend ParticleSystem;
+ //! Only RenderSystem can read particles
+ friend RenderSystem;
+ //! Saves time left over from last update event.
+ float spawn_accumulator = 0;
+ //! collection of particles
+ std::vector<Particle> particles;
};
} // namespace crepe
diff --git a/src/crepe/api/ResourceManager.cpp b/src/crepe/api/ResourceManager.cpp
deleted file mode 100644
index 7877ed9..0000000
--- a/src/crepe/api/ResourceManager.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-#include <stdexcept>
-
-#include "util/Log.h"
-
-#include "ResourceManager.h"
-
-using namespace crepe;
-using namespace std;
-
-ResourceManager & ResourceManager::get_instance() {
- static ResourceManager instance;
- return instance;
-}
-
-ResourceManager::~ResourceManager() { dbg_trace(); }
-ResourceManager::ResourceManager() { dbg_trace(); }
-
-void ResourceManager::clear() {
- this->resources.clear();
-}
-
-template <typename T>
-T & ResourceManager::cache(const Asset & asset) {
- dbg_trace();
- static_assert(is_base_of<Resource, T>::value, "cache must recieve a derivative class of Resource");
-
- if (!this->resources.contains(asset))
- this->resources[asset] = make_unique<T>(asset);
-
- Resource * resource = this->resources.at(asset).get();
- T * concrete_resource = dynamic_cast<T *>(resource);
-
- if (concrete_resource == nullptr)
- throw runtime_error(format("ResourceManager: mismatch between requested type and actual type of resource ({})", asset.get_path()));
-
- return *concrete_resource;
-}
-
-#include "../facade/Sound.h"
-template Sound & ResourceManager::cache(const Asset &);
-
diff --git a/src/crepe/api/ResourceManager.h b/src/crepe/api/ResourceManager.h
deleted file mode 100644
index efdd5c5..0000000
--- a/src/crepe/api/ResourceManager.h
+++ /dev/null
@@ -1,69 +0,0 @@
-#pragma once
-
-#include <memory>
-#include <unordered_map>
-
-#include "Asset.h"
-#include "Resource.h"
-
-namespace crepe {
-
-class Sound;
-
-/**
- * \brief The ResourceManager is responsible for storing and managing assets over
- * multiple scenes.
- *
- * The ResourceManager ensures that assets are loaded once and can be accessed
- * across different scenes. It caches assets to avoid reloading them every time
- * a scene is loaded. Assets are retained in memory until the ResourceManager is
- * destroyed, at which point the cached assets are cleared.
- */
-class ResourceManager {
-
-private:
- //! A cache that holds all the assets, accessible by their file path, over multiple scenes.
- std::unordered_map<const Asset, std::unique_ptr<Resource>> resources;
-
-private:
- ResourceManager(); // dbg_trace
- virtual ~ResourceManager(); // dbg_trace
-
- ResourceManager(const ResourceManager &) = delete;
- ResourceManager(ResourceManager &&) = delete;
- ResourceManager & operator=(const ResourceManager &) = delete;
- ResourceManager & operator=(ResourceManager &&) = delete;
-
-public:
- /**
- * \brief Retrieves the singleton instance of the ResourceManager.
- *
- * \return A reference to the single instance of the ResourceManager.
- */
- static ResourceManager & get_instance();
-
-public:
- /**
- * \brief Caches an asset by loading it from the given file path.
- *
- * \param file_path The path to the asset file to load.
- * \param reload If true, the asset will be reloaded from the file, even if
- * it is already cached.
- * \tparam T The type of asset to cache (e.g., texture, sound, etc.).
- *
- * \return A reference to the resource
- *
- * This template function caches the asset at the given file path. If the
- * asset is already cached, the existing instance will be returned.
- * Otherwise, the concrete resource will be instantiated and added to the
- * cache.
- */
- template <typename T>
- T & cache(const Asset & asset);
-
- //! Clear the resource cache
- void clear();
-};
-
-} // namespace crepe
-
diff --git a/src/crepe/api/Rigidbody.cpp b/src/crepe/api/Rigidbody.cpp
index 6b87695..8213afb 100644
--- a/src/crepe/api/Rigidbody.cpp
+++ b/src/crepe/api/Rigidbody.cpp
@@ -6,10 +6,8 @@ crepe::Rigidbody::Rigidbody(game_object_id_t id, const Data & data)
: Component(id),
data(data) {}
-void crepe::Rigidbody::add_force_linear(const Vector2 & force) {
+void crepe::Rigidbody::add_force_linear(const vec2 & force) {
this->data.linear_velocity += force;
}
-void crepe::Rigidbody::add_force_angular(double force) {
- this->data.angular_velocity += force;
-}
+void crepe::Rigidbody::add_force_angular(float force) { this->data.angular_velocity += force; }
diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h
index 2e20288..6900295 100644
--- a/src/crepe/api/Rigidbody.h
+++ b/src/crepe/api/Rigidbody.h
@@ -1,24 +1,25 @@
#pragma once
-#include <cstdint>
+#include <cmath>
+#include <set>
#include "../Component.h"
-#include "Vector2.h"
+#include "types.h"
namespace crepe {
/**
* \brief Rigidbody class
- *
- * This class is used by the physics sytem and collision system.
- * It configures how to system interact with the gameobject for movement and collisions.
+ *
+ * This class is used by the physics sytem and collision system. It configures how to system
+ * interact with the gameobject for movement and collisions.
*/
class Rigidbody : public Component {
public:
/**
* \brief BodyType enum
- *
+ *
* This enum provides three bodytypes the physics sytem and collision system use.
*/
enum class BodyType {
@@ -31,54 +32,118 @@ public:
};
/**
* \brief PhysicsConstraints to constrain movement
- *
- * This struct configures the movement constraint for this object.
- * If a constraint is enabled the systems will not move the object.
+ *
+ * This struct configures the movement constraint for this object. If a constraint is enabled
+ * the systems will not move the object.
*/
struct PhysicsConstraints {
- //! X constraint
+ //! Prevent movement along X axis
bool x = false;
- //! Y constraint
+ //! Prevent movement along Y axis
bool y = false;
- //! rotation constraint
+ //! Prevent rotation
bool rotation = false;
};
public:
- /**
+ /**
* \brief struct for Rigidbody data
- *
+ *
* This struct holds the data for the Rigidbody.
*/
struct Data {
//! objects mass
- double mass = 0.0;
- //! gravtiy scale
- double gravity_scale = 0.0;
- //! Changes if physics apply
+ float mass = 1;
+ /**
+ * \brief Gravity scale factor.
+ *
+ * The `gravity_scale` controls how much gravity affects the object. It is a multiplier applied to the default
+ * gravity force, allowing for fine-grained control over how the object responds to gravity.
+ *
+ */
+ float gravity_scale = 0;
+
+ //! Defines the type of the physics body, which determines how the physics system interacts with the object.
BodyType body_type = BodyType::DYNAMIC;
- //! linear velocity of object
- Vector2 linear_velocity;
- //! maximum linear velocity of object
- Vector2 max_linear_velocity;
- //! linear damping of object
- Vector2 linear_damping;
- //! angular velocity of object
- double angular_velocity = 0.0;
- //! max angular velocity of object
- double max_angular_velocity = 0.0;
- //! angular damping of object
- double angular_damping = 0.0;
- //! movements constraints of object
+
+ /**
+ * \name Linear (positional) motion
+ *
+ * These variables define the linear motion (movement along the position) of an object.
+ * The linear velocity is applied to the object's position in each update of the PhysicsSystem.
+ * The motion is affected by the object's linear velocity, its maximum velocity, and a coefficient
+ * that can scale the velocity over time.
+ *
+ * \{
+ */
+ //! Linear velocity of the object (speed and direction).
+ vec2 linear_velocity;
+ //! Maximum linear velocity of the object. This limits the object's speed.
+ float max_linear_velocity = INFINITY;
+ //! Linear velocity coefficient. This scales the object's velocity for adjustment or damping.
+ vec2 linear_velocity_coefficient = {1, 1};
+ //! \}
+
+ /**
+ * \name Angular (rotational) motion
+ *
+ * These variables define the angular motion (rotation) of an object.
+ * The angular velocity determines how quickly the object rotates, while the maximum angular velocity
+ * sets a limit on the rotation speed. The angular velocity coefficient applies damping or scaling
+ * to the angular velocity, which can be used to simulate friction or other effects that slow down rotation.
+ *
+ * \{
+ */
+ //! Angular velocity of the object, representing the rate of rotation (in degrees).
+ float angular_velocity = 0;
+ //! Maximum angular velocity of the object. This limits the maximum rate of rotation.
+ float max_angular_velocity = INFINITY;
+ //! Angular velocity coefficient. This scales the object's angular velocity, typically used for damping.
+ float angular_velocity_coefficient = 1;
+ //! \}
+
+ /**
+ * \brief Movement constraints for an object.
+ *
+ * The `PhysicsConstraints` struct defines the constraints that restrict an object's movement
+ * in certain directions or prevent rotation. These constraints effect only the physics system
+ * to prevent the object from moving or rotating in specified ways.
+ *
+ */
PhysicsConstraints constraints;
- //! if gravity applies
- bool use_gravity = true;
- //! if object bounces
- bool bounce = false;
+
+ /**
+ * \brief Elasticity factor of the material (bounce factor).
+ *
+ * The `elasticity_coefficient` controls how much of the object's velocity is retained after a collision.
+ * It represents the material's ability to bounce or recover velocity upon impact. The coefficient is a value
+ * above 0.0.
+ *
+ */
+ float elastisity_coefficient = 0.0;
+
+ /**
+ * \brief Offset of all colliders relative to the object's transform position.
+ *
+ * The `offset` defines a positional shift applied to all colliders associated with the object, relative to the object's
+ * transform position. This allows for the colliders to be placed at a different position than the object's actual
+ * position, without modifying the object's transform itself.
+ *
+ */
+ vec2 offset;
+
+ /**
+ * \brief Defines the collision layers of a GameObject.
+ *
+ * The `collision_layers` specifies the layers that the GameObject will collide with.
+ * Each element represents a layer ID, and the GameObject will only detect
+ * collisions with other GameObjects that belong to these layers.
+ */
+ std::set<int> collision_layers = {0};
};
public:
- /**
+ /**
* \param game_object_id id of the gameobject the rigibody is added to.
* \param data struct to configure the rigidbody.
*/
@@ -87,18 +152,27 @@ public:
Data data;
public:
- /**
+ /**
* \brief add a linear force to the Rigidbody.
- *
+ *
* \param force Vector2 that is added to the linear force.
*/
- void add_force_linear(const Vector2 & force);
- /**
+ void add_force_linear(const vec2 & force);
+ /**
* \brief add a angular force to the Rigidbody.
- *
+ *
* \param force Vector2 that is added to the angular force.
*/
- void add_force_angular(double force);
+ void add_force_angular(float force);
+
+protected:
+ /**
+ * Ensures there is at most one Rigidbody component per entity.
+ * \return Always returns 1, indicating this constraint.
+ */
+ virtual int get_instances_max() const { return 1; }
+ //! ComponentManager instantiates all components
+ friend class ComponentManager;
};
} // namespace crepe
diff --git a/src/crepe/api/Scene.cpp b/src/crepe/api/Scene.cpp
index 88aa82d..ad729d2 100644
--- a/src/crepe/api/Scene.cpp
+++ b/src/crepe/api/Scene.cpp
@@ -2,6 +2,14 @@
using namespace crepe;
-Scene::Scene(ComponentManager & mgr, const std::string & name)
- : component_manager(mgr),
- name(name) {}
+SaveManager & Scene::get_save_manager() const { return mediator->save_manager; }
+
+GameObject Scene::new_object(const std::string & name, const std::string & tag,
+ const vec2 & position, double rotation, double scale) {
+ // Forward the call to ComponentManager's new_object method
+ return mediator->component_manager->new_object(name, tag, position, rotation, scale);
+}
+
+void Scene::set_persistent(const Asset & asset, bool persistent) {
+ mediator->resource_manager->set_persistent(asset, persistent);
+}
diff --git a/src/crepe/api/Scene.h b/src/crepe/api/Scene.h
index 334f306..dcca9d4 100644
--- a/src/crepe/api/Scene.h
+++ b/src/crepe/api/Scene.h
@@ -2,22 +2,93 @@
#include <string>
+#include "../manager/ComponentManager.h"
+#include "../manager/Mediator.h"
+#include "../manager/ResourceManager.h"
+#include "../util/Log.h"
+#include "../util/OptionalRef.h"
+
+#include "GameObject.h"
+
namespace crepe {
+class SceneManager;
class ComponentManager;
+class Asset;
+/**
+ * \brief Represents a Scene
+ *
+ * This class represents a Scene. The Scene class is only used as an interface for the game
+ * programmer.
+ */
class Scene {
+protected:
+ // NOTE: This must be the only constructor on Scene, see "Late references" below
+ Scene() = default;
+ //! SceneManager instances Scene
+ friend class SceneManager;
+
public:
- Scene(ComponentManager & mgr, const std::string & name);
virtual ~Scene() = default;
+public:
+ //! Load the scene
virtual void load_scene() = 0;
+ /**
+ * \brief Get the scene's name
+ * \return The scene's name
+ */
+ virtual std::string get_name() const = 0;
-public:
- const std::string name;
+ // TODO: Late references should ALWAYS be private! This is currently kept as-is so unit tests
+ // keep passing, but this reference should not be directly accessible by the user!!!
+
+private:
+ /**
+ * \name Late references
+ *
+ * These references are set by SceneManager immediately after calling the constructor of Scene.
+ *
+ * \note Scene must have a constructor without arguments so the game programmer doesn't need to
+ * manually add `using Scene::Scene` to their concrete scene class, if they want to add a
+ * constructor with arguments (e.g. for passing references to their own concrete Scene classes).
+ *
+ * \{
+ */
+ //! Mediator reference
+ OptionalRef<Mediator> mediator;
+ //! \}
protected:
- ComponentManager & component_manager;
+ /**
+ * \brief Retrieve the reference to the SaveManager instance
+ *
+ * \returns A reference to the SaveManager instance held by the Mediator.
+ */
+ SaveManager & get_save_manager() const;
+
+ //! \copydoc ComponentManager::new_object
+ GameObject new_object(const std::string & name, const std::string & tag = "",
+ const vec2 & position = {0, 0}, double rotation = 0,
+ double scale = 1);
+
+ //! \copydoc ResourceManager::set_persistent
+ void set_persistent(const Asset & asset, bool persistent);
+ /**
+ * \name Logging functions
+ * \see Log
+ * \{
+ */
+ //! \copydoc Log::logf
+ template <class... Args>
+ void logf(const Log::Level & level, std::format_string<Args...> fmt, Args &&... args);
+ //! \copydoc Log::logf
+ template <class... Args>
+ void logf(std::format_string<Args...> fmt, Args &&... args);
+ //! \}
};
} // namespace crepe
+
+#include "Scene.hpp"
diff --git a/src/crepe/api/Scene.hpp b/src/crepe/api/Scene.hpp
new file mode 100644
index 0000000..14635df
--- /dev/null
+++ b/src/crepe/api/Scene.hpp
@@ -0,0 +1,19 @@
+#pragma once
+
+#include "../util/Log.h"
+
+#include "Scene.h"
+
+namespace crepe {
+
+template <class... Args>
+void Scene::logf(const Log::Level & level, std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(level, fmt, std::forward<Args>(args)...);
+}
+
+template <class... Args>
+void Scene::logf(std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(fmt, std::forward<Args>(args)...);
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/SceneManager.hpp b/src/crepe/api/SceneManager.hpp
deleted file mode 100644
index 714f690..0000000
--- a/src/crepe/api/SceneManager.hpp
+++ /dev/null
@@ -1,21 +0,0 @@
-#pragma once
-
-#include "SceneManager.h"
-
-namespace crepe {
-
-template <typename T>
-void SceneManager::add_scene(const std::string & name) {
- using namespace std;
- static_assert(is_base_of<Scene, T>::value, "T must be derived from Scene");
-
- Scene * scene = new T(this->component_manager, name);
- this->scenes.emplace_back(unique_ptr<Scene>(scene));
-
- // The first scene added, is the one that will be loaded at the beginning
- if (next_scene.empty()) {
- next_scene = name;
- }
-}
-
-} // namespace crepe
diff --git a/src/crepe/api/Script.cpp b/src/crepe/api/Script.cpp
index 390cec7..583c04f 100644
--- a/src/crepe/api/Script.cpp
+++ b/src/crepe/api/Script.cpp
@@ -1,3 +1,40 @@
+#include <string>
+
+#include "../facade/SDLContext.h"
+#include "../manager/SceneManager.h"
#include "Script.h"
using namespace crepe;
+using namespace std;
+
+Script::~Script() {
+ EventManager & mgr = this->mediator->event_manager;
+ for (auto id : this->listeners) {
+ mgr.unsubscribe(id);
+ }
+}
+
+template <>
+void Script::subscribe(const EventHandler<CollisionEvent> & callback) {
+ this->subscribe_internal(callback, this->game_object_id);
+}
+
+void Script::set_next_scene(const string & name) {
+ SceneManager & mgr = this->mediator->scene_manager;
+ mgr.set_next_scene(name);
+}
+
+SaveManager & Script::get_save_manager() const { return this->mediator->save_manager; }
+
+const keyboard_state_t & Script::get_keyboard_state() const {
+ SDLContext & sdl_context = this->mediator->sdl_context;
+ return sdl_context.get_keyboard_state();
+}
+
+bool Script::get_key_state(Keycode key) const noexcept {
+ try {
+ return this->get_keyboard_state().at(key);
+ } catch (...) {
+ return false;
+ }
+}
diff --git a/src/crepe/api/Script.h b/src/crepe/api/Script.h
index 68a46d7..65306cd 100644
--- a/src/crepe/api/Script.h
+++ b/src/crepe/api/Script.h
@@ -2,6 +2,13 @@
#include <vector>
+#include "../api/KeyCodes.h"
+#include "../manager/EventManager.h"
+#include "../manager/Mediator.h"
+#include "../system/CollisionSystem.h"
+#include "../types.h"
+#include "../util/OptionalRef.h"
+
namespace crepe {
class ScriptSystem;
@@ -11,73 +18,217 @@ class ComponentManager;
/**
* \brief Script interface
*
- * This class is used as a base class for user-defined scripts that can be
- * added to game objects using the \c BehaviorScript component.
+ * This class is used as a base class for user-defined scripts that can be added to game
+ * objects using the \c BehaviorScript component.
+ *
+ * \note Additional *events* (like Unity's OnDisable and OnEnable) should be implemented as
+ * member or lambda methods in derivative user script classes and registered in \c init().
+ *
+ * \warning Concrete scripts are allowed do create a custom constructor, but the utility
+ * functions should not be called inside the constructor as they rely on late references that
+ * are only available after the constructor returns.
+ *
+ * \see feature_script
*/
class Script {
- //! ScriptSystem calls \c update()
- friend class crepe::ScriptSystem;
-
protected:
/**
- * \brief Script initialization function
+ * \name Interface functions
+ * \{
+ */
+ /**
+ * \brief Script initialization function (empty by default)
*
* This function is called during the ScriptSystem::update() routine *before*
- * Script::update() if it (a) has not yet been called and (b) the \c
- * BehaviorScript component holding this script instance is active.
+ * Script::update() if it (a) has not yet been called and (b) the \c BehaviorScript component
+ * holding this script instance is active.
*/
virtual void init() {}
/**
- * \brief Script update function
+ * \brief Script update function (empty by default)
*
- * This function is called during the ScriptSystem::update() routine if the
- * \c BehaviorScript component holding this script instance is active.
+ * This function is called during the ScriptSystem::update() routine if the \c BehaviorScript
+ * component holding this script instance is active.
*/
virtual void update() {}
- // NOTE: additional *events* (like unity's OnDisable and OnEnable) should be
- // implemented as member methods in derivative user script classes and
- // registered in init(), otherwise this class will balloon in size with each
- // added event.
+ //! \}
+
+ //! ScriptSystem calls \c init() and \c update()
+ friend class crepe::ScriptSystem;
protected:
/**
- * \brief Get single component of type \c T on this game object (utility)
+ * \name Utility functions
+ * \{
+ */
+
+ /**
+ * \brief Get single component of type \c T on this game object
*
* \tparam T Type of component
*
* \returns Reference to component
*
- * \throws nullptr if this game object does not have a component matching
- * type \c T
+ * \throws std::runtime_error if this game object does not have a component with type \c T
*/
template <typename T>
T & get_component() const;
+ // TODO: make get_component calls for component types that can have more than 1 instance
+ // cause compile-time errors
/**
- * \brief Get all components of type \c T on this game object (utility)
+ * \brief Get all components of type \c T on this game object
*
* \tparam T Type of component
*
* \returns List of component references
*/
template <typename T>
- std::vector<std::reference_wrapper<T>> get_components() const;
+ RefVector<T> get_components() const;
+
+ /**
+ * \copydoc ComponentManager::get_components_by_id
+ * \see ComponentManager::get_components_by_id
+ */
+ template <typename T>
+ RefVector<T> get_components_by_id(game_object_id_t id) const;
+ /**
+ * \copydoc ComponentManager::get_components_by_name
+ * \see ComponentManager::get_components_by_name
+ */
+ template <typename T>
+ RefVector<T> get_components_by_name(const std::string & name) const;
+ /**
+ * \copydoc ComponentManager::get_components_by_tag
+ * \see ComponentManager::get_components_by_tag
+ */
+ template <typename T>
+ RefVector<T> get_components_by_tag(const std::string & tag) const;
+
+ /**
+ * \brief Log a message using Log::logf
+ *
+ * \tparam Args Log::logf parameters
+ * \param args Log::logf parameters
+ */
+ template <typename... Args>
+ void logf(Args &&... args);
+
+ /**
+ * \brief Subscribe to an event with an explicit channel
+ * \see EventManager::subscribe
+ */
+ template <typename EventType>
+ void subscribe(const EventHandler<EventType> & callback, event_channel_t channel);
+ /**
+ * \brief Subscribe to an event on EventManager::CHANNEL_ALL
+ * \see EventManager::subscribe
+ */
+ template <typename EventType>
+ void subscribe(const EventHandler<EventType> & callback);
+
+ /**
+ * \brief Set the next scene using SceneManager
+ * \see SceneManager::set_next_scene
+ */
+ void set_next_scene(const std::string & name);
+
+ //! Retrieve SaveManager reference
+ SaveManager & get_save_manager() const;
+ /**
+ * \brief Utility function to retrieve the keyboard state
+ * \see SDLContext::get_keyboard_state
+ *
+ * \return current keyboard state map with Keycode as key and bool as value(true = pressed, false = not pressed)
+ *
+ */
+ const keyboard_state_t & get_keyboard_state() const;
+ /**
+ * \brief Utility function to retrieve a single key state.
+ * \see SDLContext::get_keyboard_state
+ *
+ * \return Keycode state (true if pressed, false if not pressed).
+ *
+ */
+ bool get_key_state(Keycode key) const noexcept;
+ //! \}
+
+private:
+ /**
+ * \brief Internal subscribe function
+ *
+ * This function exists so certain template specializations of Script::subscribe can be
+ * explicitly deleted, and does the following:
+ * - Wrap the user-provided callback in a check that tests if the parent BehaviorScript
+ * component is still active
+ * - Store the subscriber handle returned by the event manager so this listener is
+ * automatically unsubscribed at the end of this Script instance's life
+ *
+ * \tparam EventType concrete Event class
+ * \param callback User-provided callback function
+ * \param channel Event channel (may have been overridden by template specializations)
+ */
+ template <typename EventType>
+ void subscribe_internal(const EventHandler<EventType> & callback, event_channel_t channel);
protected:
- // NOTE: Script must have a constructor without arguments so the game
- // programmer doesn't need to manually add `using Script::Script` to their
- // concrete script class.
+ // NOTE: This must be the only constructor on Script, see "Late references" below
Script() = default;
//! Only \c BehaviorScript instantiates Script
friend class BehaviorScript;
+public:
+ // std::unique_ptr destroys script
+ virtual ~Script();
+
+private:
+ Script(const Script &) = delete;
+ Script(Script &&) = delete;
+ Script & operator=(const Script &) = delete;
+ Script & operator=(Script &&) = delete;
+
private:
- // These references are set by BehaviorScript immediately after calling the
- // constructor of Script.
- BehaviorScript * parent_ref = nullptr;
- ComponentManager * component_manager_ref = nullptr;
+ /**
+ * \name Late references
+ *
+ * These references are set by BehaviorScript immediately after calling the constructor of
+ * Script.
+ *
+ * \note Script must have a constructor without arguments so the game programmer doesn't need
+ * to manually add `using Script::Script` to their concrete script class if they want to
+ * implement a non-default constructor (e.g. for passing references to their own concrete
+ * Script classes).
+ *
+ * \{
+ */
+ //! Game object ID of game object parent BehaviorScript is attached to
+ game_object_id_t game_object_id;
+ //! Reference to parent component
+ OptionalRef<bool> active;
+ //! Mediator reference
+ OptionalRef<Mediator> mediator;
+ //! \}
+
+private:
+ //! Flag to indicate if \c init() has been called already
+ bool initialized = false;
+ //! List of subscribed events
+ std::vector<subscription_t> listeners;
};
+/**
+ * \brief Subscribe to CollisionEvent for the current GameObject
+ *
+ * This is a template specialization for Script::subscribe which automatically sets the event
+ * channel so the callback handler is only called for CollisionEvent events that apply to the
+ * current GameObject the parent BehaviorScript is attached to.
+ */
+template <>
+void Script::subscribe(const EventHandler<CollisionEvent> & callback);
+template <>
+void Script::subscribe(const EventHandler<CollisionEvent> & callback, event_channel_t)
+ = delete;
+
} // namespace crepe
#include "Script.hpp"
diff --git a/src/crepe/api/Script.hpp b/src/crepe/api/Script.hpp
index aceb38b..225a51c 100644
--- a/src/crepe/api/Script.hpp
+++ b/src/crepe/api/Script.hpp
@@ -1,7 +1,6 @@
#pragma once
-#include "../ComponentManager.h"
-#include "../Exception.h"
+#include "../manager/ComponentManager.h"
#include "BehaviorScript.h"
#include "Script.h"
@@ -10,21 +9,69 @@ namespace crepe {
template <typename T>
T & Script::get_component() const {
- std::vector<std::reference_wrapper<T>> all_components
- = this->get_components<T>();
+ using namespace std;
+ RefVector<T> all_components = this->get_components<T>();
if (all_components.size() < 1)
- throw Exception("Script: no component found with type = {}",
- typeid(T).name());
+ throw runtime_error(
+ format("Script: no component found with type = {}", typeid(T).name()));
return all_components.back().get();
}
template <typename T>
-std::vector<std::reference_wrapper<T>> Script::get_components() const {
- auto & parent = *this->parent_ref;
- auto & mgr = *this->component_manager_ref;
+RefVector<T> Script::get_components() const {
+ return this->get_components_by_id<T>(this->game_object_id);
+}
+
+template <typename... Args>
+void Script::logf(Args &&... args) {
+ Log::logf(std::forward<Args>(args)...);
+}
+
+template <typename EventType>
+void Script::subscribe_internal(const EventHandler<EventType> & callback,
+ event_channel_t channel) {
+ EventManager & mgr = this->mediator->event_manager;
+ subscription_t listener = mgr.subscribe<EventType>(
+ [this, callback](const EventType & data) -> bool {
+ bool & active = this->active;
+ if (!active) return false;
+ return callback(data);
+ },
+ channel);
+ this->listeners.push_back(listener);
+}
+
+template <typename EventType>
+void Script::subscribe(const EventHandler<EventType> & callback, event_channel_t channel) {
+ this->subscribe_internal(callback, channel);
+}
+
+template <typename EventType>
+void Script::subscribe(const EventHandler<EventType> & callback) {
+ this->subscribe_internal(callback, EventManager::CHANNEL_ALL);
+}
+
+template <typename T>
+RefVector<T> Script::get_components_by_id(game_object_id_t id) const {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+
+ return mgr.get_components_by_id<T>(id);
+}
+template <typename T>
+RefVector<T> Script::get_components_by_name(const std::string & name) const {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+
+ return mgr.get_components_by_name<T>(name);
+}
+template <typename T>
+RefVector<T> Script::get_components_by_tag(const std::string & tag) const {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
- return mgr.get_components_by_id<T>(parent.game_object_id);
+ return mgr.get_components_by_tag<T>(tag);
}
} // namespace crepe
diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp
index ac0079e..ba684ba 100644
--- a/src/crepe/api/Sprite.cpp
+++ b/src/crepe/api/Sprite.cpp
@@ -1,25 +1,21 @@
-#include <memory>
+#include <cmath>
#include "../util/Log.h"
-#include "facade/SDLContext.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, const shared_ptr<Texture> image,
- const Color & color, const FlipSettings & flip)
+Sprite::Sprite(game_object_id_t id, const Asset & texture, const Sprite::Data & data)
: Component(id),
- color(color),
- flip(flip),
- sprite_image(image) {
- dbg_trace();
+ source(texture),
+ data(data) {
- this->sprite_rect.w = sprite_image->get_width();
- this->sprite_rect.h = sprite_image->get_height();
+ dbg_trace();
}
Sprite::~Sprite() { dbg_trace(); }
diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h
index deb3f93..a2409c2 100644
--- a/src/crepe/api/Sprite.h
+++ b/src/crepe/api/Sprite.h
@@ -1,26 +1,13 @@
#pragma once
-#include <cstdint>
-#include <memory>
+#include "../Component.h"
+#include "api/Asset.h"
#include "Color.h"
-#include "Component.h"
-#include "Texture.h"
+#include "types.h"
namespace crepe {
-struct Rect {
- int w = 0;
- int h = 0;
- int x = 0;
- int y = 0;
-};
-
-struct FlipSettings {
- bool flip_x = false;
- bool flip_y = false;
-};
-
class SDLContext;
class Animator;
class AnimatorSystem;
@@ -28,61 +15,100 @@ class AnimatorSystem;
/**
* \brief Represents a renderable sprite component.
*
- * A renderable sprite that can be displayed in the game. It includes a texture,
- * color, and flip settings, and is managed in layers with defined sorting orders.
+ * A renderable sprite that can be displayed in the game. It includes a texture, color, and
+ * flip settings, and is managed in layers with defined sorting orders.
*/
class Sprite : public Component {
+public:
+ //! settings to flip the image
+ struct FlipSettings {
+ //! horizantal flip
+ bool flip_x = false;
+ //! vertical flip
+ bool flip_y = false;
+ };
+
+ //! Sprite data that does not have to be set in the constructor
+ struct Data {
+ /**
+ * \brief Sprite tint (multiplied)
+ *
+ * The sprite texture's pixels are multiplied by this color before being displayed
+ * (including alpha channel for transparency).
+ */
+ Color color = Color::WHITE;
+
+ //! Flip settings for the sprite
+ FlipSettings flip;
+
+ //! Layer sorting level of the sprite
+ const int sorting_in_layer = 0;
+
+ //! Order within the sorting layer
+ const int order_in_layer = 0;
+
+ /**
+ * \brief width and height of the sprite in game units
+ *
+ * - if exclusively width is specified, the height is calculated using the texture's aspect
+ * ratio
+ * - if exclusively height is specified, the width is calculated using the texture's aspect
+ * ratio
+ * - if both are specified the texture is streched to fit the specified size
+ */
+ vec2 size = {0, 0};
+
+ //! independent sprite angle. rotating clockwise direction in degrees
+ float angle_offset = 0;
+
+ //! independent sprite scale multiplier
+ float scale_offset = 1;
+
+ //! independent sprite offset position
+ vec2 position_offset;
+ };
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.
- */
- Sprite(game_object_id_t id, const std::shared_ptr<Texture> image,
- const Color & color, const FlipSettings & flip);
-
- /**
- * \brief Destroys the Sprite instance.
+ * \param texture asset of the image
+ * \param ctx all the sprite data
*/
+ Sprite(game_object_id_t id, const Asset & texture, const Data & data);
~Sprite();
//! Texture used for the sprite
- const std::shared_ptr<Texture> sprite_image;
- //! Color tint of the sprite
- Color color;
- //! Flip settings for the sprite
- FlipSettings flip;
- //! Layer sorting level of the sprite
- uint8_t sorting_in_layer = 0;
- //! Order within the sorting layer
- uint8_t order_in_layer = 0;
+ const Asset source;
-public:
- /**
- * \brief Gets the maximum number of instances allowed for this sprite.
- * \return Maximum instance count as an integer.
- *
- * For now is this number randomly picked. I think it will eventually be 1.
- */
- virtual int get_instances_max() const { return 10; }
+ Data data;
private:
- //! Reads the sprite_rect of sprite
+ //! Reads the mask of sprite
friend class SDLContext;
- //! Reads the all the variables plus the sprite_rect
+ //! Reads the all the variables plus the mask
friend class Animator;
- //! Reads the all the variables plus the sprite_rect
+ //! Reads the all the variables plus the mask
friend class AnimatorSystem;
- //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator object is present in GameObject
- Rect sprite_rect;
+ /**
+ * \aspect_ratio the ratio of the sprite image
+ *
+ * - this value will only be set by the \c Animator component for the ratio of the Animation
+ * - if \c Animator component is not added it will not use this ratio (because 0) and will use aspect_ratio of the Asset.
+ */
+ float aspect_ratio = 0;
+
+ struct Rect {
+ int w = 0;
+ int h = 0;
+ int x = 0;
+ int y = 0;
+ };
+ //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator
+ // object is present in GameObject. this is in sprite pixels
+ Rect mask;
};
} // namespace crepe
diff --git a/src/crepe/api/Text.cpp b/src/crepe/api/Text.cpp
new file mode 100644
index 0000000..54a4370
--- /dev/null
+++ b/src/crepe/api/Text.cpp
@@ -0,0 +1,12 @@
+#include "../facade/FontFacade.h"
+
+#include "Text.h"
+
+using namespace crepe;
+
+Text::Text(game_object_id_t id, const vec2 & dimensions, const vec2 & offset,
+ const std::string & font_family, const Data & data, const std::string & text)
+ : UIObject(id, dimensions, offset),
+ text(text),
+ data(data),
+ font_family(font_family) {}
diff --git a/src/crepe/api/Text.h b/src/crepe/api/Text.h
new file mode 100644
index 0000000..c30dc80
--- /dev/null
+++ b/src/crepe/api/Text.h
@@ -0,0 +1,66 @@
+#pragma once
+
+#include <optional>
+#include <string>
+
+#include "../Component.h"
+
+#include "Asset.h"
+#include "Color.h"
+#include "UIObject.h"
+
+namespace crepe {
+/**
+ * \brief Text UIObject component for displaying text
+ *
+ * This class can be used to display text on screen. By setting the font_family to a font already stored on the current device it will automatically be loaded in.
+ */
+class Text : public UIObject {
+public:
+ //! Text data that does not have to be set in the constructor
+ struct Data {
+ /**
+ * \brief fontsize for text rendering
+ *
+ * \note this is not the actual font size that is loaded in.
+ *
+ * Since SDL_TTF requires the font size when loading in the font it is not possible to switch the font size.
+ * The default font size that is loaded is set in the Config.
+ * Instead this value is used to upscale the font texture which can cause blurring or distorted text when upscaling or downscaling too much.
+ */
+ unsigned int font_size = 16;
+
+ //! Layer sorting level of the text
+ const int sorting_in_layer = 0;
+
+ //! Order within the sorting text
+ const int order_in_layer = 0;
+
+ //! Label text color.
+ Color text_color = Color::BLACK;
+ };
+
+public:
+ /**
+ *
+ * \param dimensions Width and height of the UIObject.
+ * \param offset Offset of the UIObject relative to its transform
+ * \param text The text to be displayed.
+ * \param font_family The font style name to be displayed.
+ * \param data Data struct containing extra text parameters.
+ * \param font Optional font asset that can be passed or left empty.
+ */
+ Text(game_object_id_t id, const vec2 & dimensions, const vec2 & offset,
+ const std::string & font_family, const Data & data, const std::string & text = "");
+
+ //! Label text.
+ std::string text = "";
+ //! font family name
+ std::string font_family = "";
+ //! Font asset variable if this is not set, it will use the font_family to create an asset.
+ std::optional<Asset> font;
+ //! Data instance
+ Data data;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Texture.cpp b/src/crepe/api/Texture.cpp
deleted file mode 100644
index 6a1e4d8..0000000
--- a/src/crepe/api/Texture.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-#include <SDL2/SDL_render.h>
-
-#include "../facade/SDLContext.h"
-#include "../util/Log.h"
-
-#include "Asset.h"
-#include "Texture.h"
-
-using namespace crepe;
-using namespace std;
-
-Texture::Texture(unique_ptr<Asset> res) {
- dbg_trace();
- this->load(std::move(res));
-}
-
-Texture::Texture(const char * src) {
- dbg_trace();
- this->load(make_unique<Asset>(src));
-}
-
-Texture::~Texture() {
- dbg_trace();
- this->texture.reset();
-}
-
-void Texture::load(unique_ptr<Asset> res) {
- SDLContext & ctx = SDLContext::get_instance();
- this->texture = std::move(ctx.texture_from_path(res->get_path()));
-}
-
-int Texture::get_width() const {
- if (this->texture == nullptr) return 0;
- return SDLContext::get_instance().get_width(*this);
-}
-int Texture::get_height() const {
- if (this->texture == nullptr) return 0;
- return SDLContext::get_instance().get_width(*this);
-}
diff --git a/src/crepe/api/Texture.h b/src/crepe/api/Texture.h
deleted file mode 100644
index b89bc17..0000000
--- a/src/crepe/api/Texture.h
+++ /dev/null
@@ -1,77 +0,0 @@
-#pragma once
-
-// FIXME: this header can't be included because this is an API header, and SDL2
-// development headers won't be bundled with crepe. Why is this facade in the
-// API namespace?
-
-#include <SDL2/SDL_render.h>
-#include <functional>
-#include <memory>
-
-#include "Asset.h"
-
-namespace crepe {
-
-class SDLContext;
-class Animator;
-
-/**
- * \class Texture
- * \brief Manages texture loading and properties.
- *
- * 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 {
-
-public:
- /**
- * \brief Constructs a Texture from a file path.
- * \param src Path to the image file to be loaded as a texture.
- */
- Texture(const char * src);
-
- /**
- * \brief Constructs a Texture from an Asset resource.
- * \param res Unique pointer to an Asset resource containing texture data.
- */
- Texture(std::unique_ptr<Asset> res);
-
- /**
- * \brief Destroys the Texture instance, freeing associated resources.
- */
- ~Texture();
- // FIXME: this constructor shouldn't be necessary because this class doesn't
- // manage memory
-
- /**
- * \brief Gets the width of the texture.
- * \return Width of the texture in pixels.
- */
- int get_width() const;
-
- /**
- * \brief Gets the height of the texture.
- * \return Height of the texture in pixels.
- */
- int get_height() const;
-
-private:
- /**
- * \brief Loads the texture from an Asset resource.
- * \param res Unique pointer to an Asset resource to load the texture from.
- */
- void load(std::unique_ptr<Asset> res);
-
-private:
- //! The texture of the class from the library
- std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> texture;
-
- //! Grants SDLContext access to private members.
- friend class SDLContext;
-
- //! Grants Animator access to private members.
- friend class Animator;
-};
-
-} // namespace crepe
diff --git a/src/crepe/api/Transform.cpp b/src/crepe/api/Transform.cpp
index e9108c4..a85b792 100644
--- a/src/crepe/api/Transform.cpp
+++ b/src/crepe/api/Transform.cpp
@@ -4,8 +4,7 @@
using namespace crepe;
-Transform::Transform(game_object_id_t id, const Vector2 & point,
- double rotation, double scale)
+Transform::Transform(game_object_id_t id, const vec2 & point, double rotation, double scale)
: Component(id),
position(point),
rotation(rotation),
diff --git a/src/crepe/api/Transform.h b/src/crepe/api/Transform.h
index 902dafa..7ee6d65 100644
--- a/src/crepe/api/Transform.h
+++ b/src/crepe/api/Transform.h
@@ -1,25 +1,24 @@
#pragma once
-#include "api/Vector2.h"
-
#include "Component.h"
+#include "types.h"
namespace crepe {
/**
* \brief Transform component
- *
- * This class represents the Transform component. It stores the position,
- * rotation and scale of a GameObject.
+ *
+ * This class represents the Transform component. It stores the position, rotation and scale of
+ * a GameObject.
*/
class Transform : public Component {
public:
//! Translation (shift)
- Vector2 position = {0, 0};
- //! Rotation, in degrees
- double rotation = 0;
+ vec2 position = {0, 0};
+ //! Rotation, in degrees clockwise
+ float rotation = 0;
//! Multiplication factor
- double scale = 0;
+ float scale = 0;
protected:
/**
@@ -28,9 +27,11 @@ protected:
* \param rotation The rotation of the GameObject
* \param scale The scale of the GameObject
*/
- Transform(game_object_id_t id, const Vector2 & point, double rotation = 0,
- double scale = 0);
- //! There is always exactly one transform component per entity
+ Transform(game_object_id_t id, const vec2 & point, double rotation, double scale);
+ /**
+ * There is always exactly one transform component per entity
+ * \return 1
+ */
virtual int get_instances_max() const { return 1; }
//! ComponentManager instantiates all components
friend class ComponentManager;
diff --git a/src/crepe/api/UIObject.cpp b/src/crepe/api/UIObject.cpp
new file mode 100644
index 0000000..d239b89
--- /dev/null
+++ b/src/crepe/api/UIObject.cpp
@@ -0,0 +1,8 @@
+#include "UIObject.h"
+
+using namespace crepe;
+
+UIObject::UIObject(game_object_id_t id, const vec2 & dimensions, const vec2 & offset)
+ : Component(id),
+ dimensions(dimensions),
+ offset(offset) {}
diff --git a/src/crepe/api/UIObject.h b/src/crepe/api/UIObject.h
new file mode 100644
index 0000000..f7f4fba
--- /dev/null
+++ b/src/crepe/api/UIObject.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include "../Component.h"
+
+namespace crepe {
+
+/**
+ * \brief Represents a UI object in the game, derived from the Component class.
+ */
+class UIObject : public Component {
+public:
+ /**
+ * \brief Constructs a UiObject with the specified game object ID.
+ * \param id The unique ID of the game object associated with this UI object.
+ * \param dimensions width and height of the UIObject
+ * \param offset Offset relative to the GameObject Transform
+ */
+ UIObject(game_object_id_t id, const vec2 & dimensions, const vec2 & offset);
+ //! Width and height of the UIObject
+ vec2 dimensions;
+ //! Position offset relative to this GameObjects Transform
+ vec2 offset;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Vector2.cpp b/src/crepe/api/Vector2.cpp
deleted file mode 100644
index 97b74ac..0000000
--- a/src/crepe/api/Vector2.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-#include "Vector2.h"
-
-using namespace crepe;
-
-Vector2 Vector2::operator-(const Vector2 & other) const {
- return {x - other.x, y - other.y};
-}
-
-Vector2 Vector2::operator+(const Vector2 & other) const {
- return {x + other.x, y + other.y};
-}
-
-Vector2 Vector2::operator*(double scalar) const {
- return {x * scalar, y * scalar};
-}
-
-Vector2 & Vector2::operator*=(const Vector2 & other) {
- x *= other.x;
- y *= other.y;
- return *this;
-}
-
-Vector2 & Vector2::operator+=(const Vector2 & other) {
- x += other.x;
- y += other.y;
- return *this;
-}
-
-Vector2 & Vector2::operator+=(double other) {
- x += other;
- y += other;
- return *this;
-}
-
-Vector2 Vector2::operator-() const { return {-x, -y}; }
-
-bool Vector2::operator==(const Vector2 & other) const {
- return x == other.x && y == other.y;
-}
-
-bool Vector2::operator!=(const Vector2 & other) const {
- return !(*this == other);
-}
diff --git a/src/crepe/api/Vector2.h b/src/crepe/api/Vector2.h
index 2fb6136..bf9d124 100644
--- a/src/crepe/api/Vector2.h
+++ b/src/crepe/api/Vector2.h
@@ -3,38 +3,95 @@
namespace crepe {
//! 2D vector
+template <class T>
struct Vector2 {
//! X component of the vector
- double x = 0;
+ T x = 0;
//! Y component of the vector
- double y = 0;
+ T y = 0;
//! Subtracts another vector from this vector and returns the result.
- Vector2 operator-(const Vector2 & other) const;
+ Vector2 operator-(const Vector2<T> & other) const;
+
+ //! Subtracts a scalar value from both components of this vector and returns the result.
+ Vector2 operator-(T scalar) const;
//! Adds another vector to this vector and returns the result.
- Vector2 operator+(const Vector2 & other) const;
+ Vector2 operator+(const Vector2<T> & other) const;
+
+ //! Adds a scalar value to both components of this vector and returns the result.
+ Vector2 operator+(T scalar) const;
+
+ //! Multiplies this vector by another vector element-wise and returns the result.
+ Vector2 operator*(const Vector2<T> & other) const;
//! Multiplies this vector by a scalar and returns the result.
- Vector2 operator*(double scalar) const;
+ Vector2 operator*(T scalar) const;
- //! Multiplies this vector by another vector element-wise and updates this vector.
- Vector2 & operator*=(const Vector2 & other);
+ //! Divides this vector by another vector element-wise and returns the result.
+ Vector2 operator/(const Vector2<T> & other) const;
+
+ //! Divides this vector by a scalar and returns the result.
+ Vector2 operator/(T scalar) const;
//! Adds another vector to this vector and updates this vector.
- Vector2 & operator+=(const Vector2 & other);
+ Vector2 & operator+=(const Vector2<T> & other);
//! Adds a scalar value to both components of this vector and updates this vector.
- Vector2 & operator+=(double other);
+ Vector2 & operator+=(T other);
+
+ //! Subtracts another vector from this vector and updates this vector.
+ Vector2 & operator-=(const Vector2<T> & other);
+
+ //! Subtracts a scalar value from both components of this vector and updates this vector.
+ Vector2 & operator-=(T other);
+
+ //! Multiplies this vector by another vector element-wise and updates this vector.
+ Vector2 & operator*=(const Vector2<T> & other);
+
+ //! Multiplies this vector by a scalar and updates this vector.
+ Vector2 & operator*=(T other);
+
+ //! Divides this vector by another vector element-wise and updates this vector.
+ Vector2 & operator/=(const Vector2<T> & other);
+
+ //! Divides this vector by a scalar and updates this vector.
+ Vector2 & operator/=(T other);
//! Returns the negation of this vector.
Vector2 operator-() const;
//! Checks if this vector is equal to another vector.
- bool operator==(const Vector2 & other) const;
+ bool operator==(const Vector2<T> & other) const;
//! Checks if this vector is not equal to another vector.
- bool operator!=(const Vector2 & other) const;
+ bool operator!=(const Vector2<T> & other) const;
+
+ //! Truncates the vector to a maximum length.
+ void truncate(T max);
+
+ //! Normalizes the vector (resulting in vector with a length of 1).
+ void normalize();
+
+ //! Returns the length of the vector.
+ T length() const;
+
+ //! Returns the squared length of the vector.
+ T length_squared() const;
+
+ //! Returns the dot product (inwendig product) of this vector and another vector.
+ T dot(const Vector2<T> & other) const;
+
+ //! Returns the distance between this vector and another vector.
+ T distance(const Vector2<T> & other) const;
+
+ //! Returns the squared distance between this vector and another vector.
+ T distance_squared(const Vector2<T> & other) const;
+
+ //! Returns the perpendicular vector to this vector.
+ Vector2 perpendicular() const;
};
} // namespace crepe
+
+#include "Vector2.hpp"
diff --git a/src/crepe/api/Vector2.hpp b/src/crepe/api/Vector2.hpp
new file mode 100644
index 0000000..ff53cb0
--- /dev/null
+++ b/src/crepe/api/Vector2.hpp
@@ -0,0 +1,166 @@
+#pragma once
+
+#include <cmath>
+
+#include "Vector2.h"
+
+namespace crepe {
+
+template <class T>
+Vector2<T> Vector2<T>::operator-(const Vector2<T> & other) const {
+ return {x - other.x, y - other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator-(T scalar) const {
+ return {x - scalar, y - scalar};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator+(const Vector2<T> & other) const {
+ return {x + other.x, y + other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator+(T scalar) const {
+ return {x + scalar, y + scalar};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator*(const Vector2<T> & other) const {
+ return {x * other.x, y * other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator*(T scalar) const {
+ return {x * scalar, y * scalar};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator/(const Vector2<T> & other) const {
+ return {x / other.x, y / other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator/(T scalar) const {
+ return {x / scalar, y / scalar};
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator+=(const Vector2<T> & other) {
+ x += other.x;
+ y += other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator+=(T other) {
+ x += other;
+ y += other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator-=(const Vector2<T> & other) {
+ x -= other.x;
+ y -= other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator-=(T other) {
+ x -= other;
+ y -= other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator*=(const Vector2<T> & other) {
+ x *= other.x;
+ y *= other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator*=(T other) {
+ x *= other;
+ y *= other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator/=(const Vector2<T> & other) {
+ x /= other.x;
+ y /= other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator/=(T other) {
+ x /= other;
+ y /= other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator-() const {
+ return {-x, -y};
+}
+
+template <class T>
+bool Vector2<T>::operator==(const Vector2<T> & other) const {
+ return x == other.x && y == other.y;
+}
+
+template <class T>
+bool Vector2<T>::operator!=(const Vector2<T> & other) const {
+ return !(*this == other);
+}
+
+template <class T>
+void Vector2<T>::truncate(T max) {
+ if (length() > max) {
+ normalize();
+ *this *= max;
+ }
+}
+
+template <class T>
+void Vector2<T>::normalize() {
+ T len = length();
+ if (len > 0) {
+ *this /= len;
+ }
+}
+
+template <class T>
+T Vector2<T>::length() const {
+ return std::sqrt(x * x + y * y);
+}
+
+template <class T>
+T Vector2<T>::length_squared() const {
+ return x * x + y * y;
+}
+
+template <class T>
+T Vector2<T>::dot(const Vector2<T> & other) const {
+ return x * other.x + y * other.y;
+}
+
+template <class T>
+T Vector2<T>::distance(const Vector2<T> & other) const {
+ return (*this - other).length();
+}
+
+template <class T>
+T Vector2<T>::distance_squared(const Vector2<T> & other) const {
+ return (*this - other).length_squared();
+}
+
+template <class T>
+Vector2<T> Vector2<T>::perpendicular() const {
+ return {-y, x};
+}
+
+} // namespace crepe
diff --git a/src/crepe/facade/CMakeLists.txt b/src/crepe/facade/CMakeLists.txt
index 4cc53bc..243ae46 100644
--- a/src/crepe/facade/CMakeLists.txt
+++ b/src/crepe/facade/CMakeLists.txt
@@ -1,14 +1,20 @@
target_sources(crepe PUBLIC
Sound.cpp
+ Texture.cpp
SoundContext.cpp
SDLContext.cpp
DB.cpp
+ FontFacade.cpp
+ Font.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
Sound.h
+ Texture.h
SoundContext.h
SDLContext.h
DB.h
+ FontFacade.h
+ Font.h
)
diff --git a/src/crepe/facade/DB.cpp b/src/crepe/facade/DB.cpp
index 80047a6..ae2d4bc 100644
--- a/src/crepe/facade/DB.cpp
+++ b/src/crepe/facade/DB.cpp
@@ -1,6 +1,5 @@
#include <cstring>
-#include "Exception.h"
#include "util/Log.h"
#include "DB.h"
@@ -15,19 +14,13 @@ DB::DB(const string & path) {
// init database struct
libdb::DB * db;
if ((ret = libdb::db_create(&db, NULL, 0)) != 0)
- throw Exception("db_create: {}", libdb::db_strerror(ret));
+ throw runtime_error(format("db_create: {}", libdb::db_strerror(ret)));
this->db = {db, [](libdb::DB * db) { db->close(db, 0); }};
// load or create database file
- ret = this->db->open(this->db.get(), NULL, path.c_str(), NULL,
- libdb::DB_BTREE, DB_CREATE, 0);
- if (ret != 0) throw Exception("db->open: {}", libdb::db_strerror(ret));
-
- // create cursor
- libdb::DBC * cursor;
- ret = this->db->cursor(this->db.get(), NULL, &cursor, 0);
- if (ret != 0) throw Exception("db->cursor: {}", libdb::db_strerror(ret));
- this->cursor = {cursor, [](libdb::DBC * cursor) { cursor->close(cursor); }};
+ const char * file = path.empty() ? NULL : path.c_str();
+ ret = this->db->open(this->db.get(), NULL, file, NULL, libdb::DB_BTREE, DB_CREATE, 0);
+ if (ret != 0) throw runtime_error(format("db->open: {}", libdb::db_strerror(ret)));
}
libdb::DBT DB::to_thing(const string & thing) const noexcept {
@@ -43,22 +36,25 @@ string DB::get(const string & key) {
libdb::DBT db_val;
memset(&db_val, 0, sizeof(libdb::DBT));
- int ret = this->cursor->get(this->cursor.get(), &db_key, &db_val, DB_FIRST);
- if (ret != 0) throw Exception("cursor->get: {}", libdb::db_strerror(ret));
- return {static_cast<char *>(db_val.data), db_val.size};
+ int ret = this->db->get(this->db.get(), NULL, &db_key, &db_val, 0);
+ if (ret == 0) return {static_cast<char *>(db_val.data), db_val.size};
+
+ string err = format("db->get: {}", libdb::db_strerror(ret));
+ if (ret == DB_NOTFOUND) throw out_of_range(err);
+ else throw runtime_error(err);
}
void DB::set(const string & key, const string & value) {
libdb::DBT db_key = this->to_thing(key);
libdb::DBT db_val = this->to_thing(value);
int ret = this->db->put(this->db.get(), NULL, &db_key, &db_val, 0);
- if (ret != 0) throw Exception("cursor->get: {}", libdb::db_strerror(ret));
+ if (ret != 0) throw runtime_error(format("db->get: {}", libdb::db_strerror(ret)));
}
-bool DB::has(const std::string & key) noexcept {
+bool DB::has(const std::string & key) {
try {
this->get(key);
- } catch (...) {
+ } catch (std::out_of_range &) {
return false;
}
return true;
diff --git a/src/crepe/facade/DB.h b/src/crepe/facade/DB.h
index 7c757a2..84cdf19 100644
--- a/src/crepe/facade/DB.h
+++ b/src/crepe/facade/DB.h
@@ -15,15 +15,17 @@ namespace crepe {
/**
* \brief Berkeley DB facade
*
- * Berkeley DB is a simple key-value database that stores arbitrary data as
- * both key and value. This facade uses STL strings as keys/values.
+ * Berkeley DB is a simple key-value database that stores arbitrary data as both key and value.
+ * This facade uses STL strings as keys/values.
*/
class DB {
public:
/**
* \param path The path of the database (created if nonexistant)
+ *
+ * \note If \p path is empty, the database is entirely in-memory
*/
- DB(const std::string & path);
+ DB(const std::string & path = "");
virtual ~DB() = default;
public:
@@ -34,7 +36,8 @@ public:
*
* \return The value
*
- * \throws Exception if value is not found in DB or other error occurs
+ * \throws std::out_of_range if value is not found in DB
+ * \throws std::runtime_error if other error occurs
*/
std::string get(const std::string & key);
/**
@@ -43,7 +46,7 @@ public:
* \param key The value key
* \param value The value to store
*
- * \throws Exception if an error occurs
+ * \throws std::runtime_error if an error occurs
*/
void set(const std::string & key, const std::string & value);
/**
@@ -53,13 +56,11 @@ public:
*
* \returns True if the key exists, or false if it does not
*/
- bool has(const std::string & key) noexcept;
+ bool has(const std::string & key);
private:
//! RAII wrapper around \c DB struct
std::unique_ptr<libdb::DB, std::function<void(libdb::DB *)>> db;
- //! RAII wrapper around \c DBC struct
- std::unique_ptr<libdb::DBC, std::function<void(libdb::DBC *)>> cursor;
private:
/**
diff --git a/src/crepe/facade/EventData.h b/src/crepe/facade/EventData.h
new file mode 100644
index 0000000..a7526b4
--- /dev/null
+++ b/src/crepe/facade/EventData.h
@@ -0,0 +1,54 @@
+#pragma once
+#include "../api/KeyCodes.h"
+#include "../types.h"
+namespace crepe {
+//! EventType enum for passing eventType
+enum EventType {
+ NONE = 0,
+ MOUSE_DOWN,
+ MOUSE_UP,
+ MOUSE_MOVE,
+ MOUSE_WHEEL,
+ KEY_UP,
+ KEY_DOWN,
+ SHUTDOWN,
+ WINDOW_MINIMIZE,
+ WINDOW_MAXIMIZE,
+ WINDOW_FOCUS_GAIN,
+ WINDOW_FOCUS_LOST,
+ WINDOW_MOVE,
+ WINDOW_RESIZE,
+ WINDOW_EXPOSE,
+};
+
+//! Struct for storing key data.
+struct KeyData {
+ Keycode key = Keycode::NONE;
+ bool key_repeat = false;
+};
+
+//! Struct for storing mouse data.
+struct MouseData {
+ MouseButton mouse_button = MouseButton::NONE;
+ ivec2 mouse_position = {-1, -1};
+ int scroll_direction = -1;
+ float scroll_delta = INFINITY;
+ ivec2 rel_mouse_move = {-1, -1};
+};
+
+//! Struct for storing window data.
+struct WindowData {
+ ivec2 move_delta;
+ ivec2 resize_dimension;
+};
+
+//! EventData struct for passing event data from facade
+struct EventData {
+ EventType event_type = EventType::NONE;
+ union {
+ KeyData key_data;
+ MouseData mouse_data;
+ WindowData window_data;
+ } data;
+};
+} // namespace crepe
diff --git a/src/crepe/facade/Font.cpp b/src/crepe/facade/Font.cpp
new file mode 100644
index 0000000..771002f
--- /dev/null
+++ b/src/crepe/facade/Font.cpp
@@ -0,0 +1,21 @@
+#include <SDL2/SDL_ttf.h>
+
+#include "../api/Asset.h"
+#include "../api/Config.h"
+
+#include "Font.h"
+
+using namespace std;
+using namespace crepe;
+
+Font::Font(const Asset & src, Mediator & mediator) : Resource(src, mediator) {
+ const Config & config = Config::get_instance();
+ const std::string FONT_PATH = src.get_path();
+ TTF_Font * loaded_font = TTF_OpenFont(FONT_PATH.c_str(), config.font.size);
+ if (loaded_font == NULL) {
+ throw runtime_error(format("Font: {} (path: {})", TTF_GetError(), FONT_PATH));
+ }
+ this->font = {loaded_font, [](TTF_Font * close_font) { TTF_CloseFont(close_font); }};
+}
+
+TTF_Font * Font::get_font() const { return this->font.get(); }
diff --git a/src/crepe/facade/Font.h b/src/crepe/facade/Font.h
new file mode 100644
index 0000000..b208d96
--- /dev/null
+++ b/src/crepe/facade/Font.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include <SDL2/SDL_ttf.h>
+#include <memory>
+
+#include "../Resource.h"
+#include "../api/Config.h"
+
+namespace crepe {
+
+class Asset;
+/**
+ * \brief Resource for managing font creation and destruction
+ *
+ * This class is a wrapper around an SDL_ttf font instance, encapsulating font loading and usage.
+ * It loads a font from an Asset and manages its lifecycle. The font is automatically unloaded
+ * when this object is destroyed.
+ */
+class Font : public Resource {
+
+public:
+ /**
+ * \param src The Asset containing the font file path and metadata to load the font.
+ * \param mediator The Mediator object used for managing the SDL context or related systems.
+ */
+ Font(const Asset & src, Mediator & mediator);
+ /**
+ * \brief Gets the underlying TTF_Font resource.
+ *
+ * This function returns the raw pointer to the SDL_ttf TTF_Font object that represents
+ * the loaded font. This can be used with SDL_ttf functions to render text.
+ *
+ * \return The raw TTF_Font object wrapped in a unique pointer.
+ */
+ TTF_Font * get_font() const;
+
+private:
+ //! The SDL_ttf font object with custom deleter.
+ std::unique_ptr<TTF_Font, std::function<void(TTF_Font *)>> font = nullptr;
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/FontFacade.cpp b/src/crepe/facade/FontFacade.cpp
new file mode 100644
index 0000000..87f95ab
--- /dev/null
+++ b/src/crepe/facade/FontFacade.cpp
@@ -0,0 +1,43 @@
+#include <fontconfig/fontconfig.h>
+#include <functional>
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+#include "FontFacade.h"
+
+using namespace std;
+using namespace crepe;
+
+FontFacade::FontFacade() {
+ if (!FcInit()) throw runtime_error("Failed to initialize Fontconfig.");
+}
+
+FontFacade::~FontFacade() { FcFini(); }
+
+Asset FontFacade::get_font_asset(const string & font_family) {
+ FcPattern * raw_pattern
+ = FcNameParse(reinterpret_cast<const FcChar8 *>(font_family.c_str()));
+ if (raw_pattern == NULL) throw runtime_error("Failed to create font pattern.");
+
+ unique_ptr<FcPattern, function<void(FcPattern *)>> pattern{
+ raw_pattern, [](FcPattern * p) { FcPatternDestroy(p); }};
+
+ FcConfig * config = FcConfigGetCurrent();
+ if (config == NULL) throw runtime_error("Failed to get current Fontconfig configuration.");
+
+ FcResult result;
+ FcPattern * raw_matched_pattern = FcFontMatch(config, pattern.get(), &result);
+ if (raw_matched_pattern == NULL) throw runtime_error("No matching font found.");
+
+ unique_ptr<FcPattern, function<void(FcPattern *)>> matched_pattern
+ = {raw_matched_pattern, [](FcPattern * p) { FcPatternDestroy(p); }};
+
+ FcChar8 * file_path = nullptr;
+ FcResult res = FcPatternGetString(matched_pattern.get(), FC_FILE, 0, &file_path);
+ if (res != FcResultMatch || file_path == NULL)
+ throw runtime_error("Failed to get font file path.");
+
+ string font_file_path = reinterpret_cast<const char *>(file_path);
+ return Asset(font_file_path);
+}
diff --git a/src/crepe/facade/FontFacade.h b/src/crepe/facade/FontFacade.h
new file mode 100644
index 0000000..9761070
--- /dev/null
+++ b/src/crepe/facade/FontFacade.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include <memory>
+
+#include "../api/Asset.h"
+
+namespace crepe {
+
+/**
+ *
+ * \brief Font facade class for converting font family names to absolute file paths
+ *
+ */
+class FontFacade {
+public:
+ FontFacade();
+ ~FontFacade();
+ FontFacade(const FontFacade & other) = delete;
+ FontFacade & operator=(const FontFacade & other) = delete;
+ FontFacade(FontFacade && other) noexcept = delete;
+ FontFacade & operator=(FontFacade && other) noexcept = delete;
+ /**
+ *
+ * \brief Facade function to convert a font_family into an asset.
+ *
+ * This function uses the FontConfig library to convert a font family name (Arial, Inter, Helvetica) and converts it to the font source path.
+ * This function returns a default font path if the font_family name doesnt exist or cant be found
+ * \param font_family Name of the font family name.
+ * \return Asset with filepath to the corresponding font.
+ */
+ Asset get_font_asset(const std::string & font_family);
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp
index 5527803..fffbe34 100644
--- a/src/crepe/facade/SDLContext.cpp
+++ b/src/crepe/facade/SDLContext.cpp
@@ -1,74 +1,69 @@
#include <SDL2/SDL.h>
+#include <SDL2/SDL_blendmode.h>
#include <SDL2/SDL_image.h>
+#include <SDL2/SDL_keycode.h>
+#include <SDL2/SDL_pixels.h>
#include <SDL2/SDL_rect.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_surface.h>
+#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_video.h>
+#include <array>
#include <cmath>
#include <cstddef>
+#include <cstdint>
#include <functional>
-#include <iostream>
#include <memory>
-#include <string>
-#include <utility>
+#include <stdexcept>
+#include "../api/Camera.h"
+#include "../api/Color.h"
+#include "../api/Config.h"
#include "../api/Sprite.h"
-#include "../api/Texture.h"
-#include "../api/Transform.h"
#include "../util/Log.h"
-#include "Exception.h"
+#include "manager/Mediator.h"
#include "SDLContext.h"
+#include "Texture.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) {
dbg_trace();
- // FIXME: read window defaults from config manager
-
- if (SDL_Init(SDL_INIT_VIDEO) < 0) {
- // FIXME: throw exception
- std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError()
- << std::endl;
- return;
+ if (TTF_Init() == -1) {
+ throw runtime_error(format("SDL_ttf initialization failed: {}", TTF_GetError()));
}
- SDL_Window * tmp_window = SDL_CreateWindow(
- "Crepe Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
- this->viewport.w, this->viewport.h, 0);
+ if (SDL_Init(SDL_INIT_VIDEO) != 0) {
+ throw runtime_error(format("SDLContext: SDL_Init error: {}", SDL_GetError()));
+ }
+
+ auto & cfg = Config::get_instance().window_settings;
+ SDL_Window * tmp_window
+ = SDL_CreateWindow(cfg.window_title.c_str(), SDL_WINDOWPOS_CENTERED,
+ SDL_WINDOWPOS_CENTERED, cfg.default_size.x, cfg.default_size.y, 0);
if (!tmp_window) {
- // FIXME: throw exception
- std::cerr << "Window could not be created! SDL_Error: "
- << SDL_GetError() << std::endl;
- return;
+ throw runtime_error(format("SDLContext: SDL_Window error: {}", SDL_GetError()));
}
- this->game_window
- = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }};
+ this->game_window = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }};
- SDL_Renderer * tmp_renderer = SDL_CreateRenderer(
- this->game_window.get(), -1, SDL_RENDERER_ACCELERATED);
+ SDL_Renderer * tmp_renderer
+ = SDL_CreateRenderer(this->game_window.get(), -1, SDL_RENDERER_ACCELERATED);
if (!tmp_renderer) {
- // FIXME: throw exception
- std::cerr << "Renderer could not be created! SDL_Error: "
- << SDL_GetError() << std::endl;
- SDL_DestroyWindow(this->game_window.get());
- return;
+ throw runtime_error(
+ format("SDLContext: SDL_CreateRenderer error: {}", SDL_GetError()));
}
- this->game_renderer = {tmp_renderer, [](SDL_Renderer * renderer) {
- SDL_DestroyRenderer(renderer);
- }};
+ this->game_renderer
+ = {tmp_renderer, [](SDL_Renderer * renderer) { SDL_DestroyRenderer(renderer); }};
int img_flags = IMG_INIT_PNG;
if (!(IMG_Init(img_flags) & img_flags)) {
- // FIXME: throw exception
- std::cout << "SDL_image could not initialize! SDL_image Error: "
- << IMG_GetError() << std::endl;
+ throw runtime_error("SDLContext: SDL_image could not initialize!");
}
+
+ mediator.sdl_context = *this;
}
SDLContext::~SDLContext() {
@@ -81,114 +76,344 @@ SDLContext::~SDLContext() {
// thread that SDL_Init() was called on? This has caused problems for me
// before.
IMG_Quit();
+ TTF_Quit();
SDL_Quit();
}
-void SDLContext::handle_events(bool & running) {
- //TODO: wouter i need events
- /*
- SDL_Event event;
- SDL_PollEvent(&event);
- switch (event.type) {
- case SDL_QUIT:
- running = false;
- break;
- case SDL_KEYDOWN:
- triggerEvent(KeyPressedEvent(getCustomKey(event.key.keysym.sym)));
- break;
- case SDL_MOUSEBUTTONDOWN:
- int x, y;
- SDL_GetMouseState(&x, &y);
- triggerEvent(MousePressedEvent(x, y));
- break;
+Keycode SDLContext::sdl_to_keycode(SDL_Scancode sdl_key) {
+ if (!lookup_table.contains(sdl_key)) return Keycode::NONE;
+ return lookup_table.at(sdl_key);
+}
+
+const keyboard_state_t & SDLContext::get_keyboard_state() {
+ SDL_PumpEvents();
+ const Uint8 * current_state = SDL_GetKeyboardState(nullptr);
+
+ for (int i = 0; i < SDL_NUM_SCANCODES; ++i) {
+
+ Keycode key = sdl_to_keycode(static_cast<SDL_Scancode>(i));
+ if (key != Keycode::NONE) {
+ this->keyboard_state[key] = current_state[i] != 0;
+ }
+ }
+ return this->keyboard_state;
+}
+
+MouseButton SDLContext::sdl_to_mousebutton(Uint8 sdl_button) {
+ static const std::array<MouseButton, 5> MOUSE_BUTTON_LOOKUP_TABLE = [] {
+ std::array<MouseButton, 5> table{};
+ table.fill(MouseButton::NONE);
+
+ table[SDL_BUTTON_LEFT] = MouseButton::LEFT_MOUSE;
+ table[SDL_BUTTON_RIGHT] = MouseButton::RIGHT_MOUSE;
+ table[SDL_BUTTON_MIDDLE] = MouseButton::MIDDLE_MOUSE;
+ table[SDL_BUTTON_X1] = MouseButton::X1_MOUSE;
+ table[SDL_BUTTON_X2] = MouseButton::X2_MOUSE;
+
+ return table;
+ }();
+
+ if (sdl_button >= MOUSE_BUTTON_LOOKUP_TABLE.size()) {
+ // Return NONE for invalid or unmapped button
+ return MouseButton::NONE;
}
- */
+
+ return MOUSE_BUTTON_LOOKUP_TABLE[sdl_button];
}
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::draw(const Sprite & sprite, const Transform & transform,
- const Camera & cam) {
+SDL_FRect SDLContext::get_dst_rect(const DestinationRectangleData & ctx) const {
- SDL_RendererFlip render_flip
- = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * sprite.flip.flip_x)
- | (SDL_FLIP_VERTICAL * sprite.flip.flip_y));
-
- double adjusted_x = (transform.position.x - cam.x) * cam.zoom;
- double adjusted_y = (transform.position.y - cam.y) * cam.zoom;
- double adjusted_w = sprite.sprite_rect.w * transform.scale * cam.zoom;
- double adjusted_h = sprite.sprite_rect.h * transform.scale * cam.zoom;
-
- SDL_Rect srcrect = {
- .x = sprite.sprite_rect.x,
- .y = sprite.sprite_rect.y,
- .w = sprite.sprite_rect.w,
- .h = sprite.sprite_rect.h,
- };
+ const Sprite::Data & data = ctx.sprite.data;
- SDL_Rect dstrect = {
- .x = static_cast<int>(adjusted_x),
- .y = static_cast<int>(adjusted_y),
- .w = static_cast<int>(adjusted_w),
- .h = static_cast<int>(adjusted_h),
- };
+ float aspect_ratio
+ = (ctx.sprite.aspect_ratio == 0) ? ctx.texture.get_ratio() : ctx.sprite.aspect_ratio;
+
+ vec2 size = data.size;
+ if (data.size.x == 0 && data.size.y != 0) {
+ size.x = data.size.y * aspect_ratio;
+ }
+ if (data.size.y == 0 && data.size.x != 0) {
+ size.y = data.size.x / aspect_ratio;
+ }
+ size *= cam_aux_data.render_scale * ctx.img_scale * data.scale_offset;
- SDL_RenderCopyEx(this->game_renderer.get(),
- sprite.sprite_image->texture.get(), &srcrect,
+ vec2 screen_pos = (ctx.pos + data.position_offset - cam_aux_data.cam_pos
+ + (cam_aux_data.zoomed_viewport) / 2)
+ * cam_aux_data.render_scale
+ - size / 2 + cam_aux_data.bar_size;
- &dstrect, transform.rotation, NULL, render_flip);
+ return SDL_FRect{
+ .x = screen_pos.x,
+ .y = screen_pos.y,
+ .w = size.x,
+ .h = size.y,
+ };
}
-void SDLContext::camera(const Camera & cam) {
- this->viewport.w = static_cast<int>(cam.aspect_width);
- this->viewport.h = static_cast<int>(cam.aspect_height);
- this->viewport.x = static_cast<int>(cam.x) - (SCREEN_WIDTH / 2);
- this->viewport.y = static_cast<int>(cam.y) - (SCREEN_HEIGHT / 2);
+void SDLContext::draw(const RenderContext & ctx) {
+ const Sprite::Data & data = ctx.sprite.data;
+ SDL_RendererFlip render_flip
+ = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * data.flip.flip_x)
+ | (SDL_FLIP_VERTICAL * data.flip.flip_y));
+
+ SDL_Rect srcrect;
+ SDL_Rect * srcrect_ptr = NULL;
+ if (ctx.sprite.mask.w != 0 || ctx.sprite.mask.h != 0) {
+ srcrect.w = ctx.sprite.mask.w;
+ srcrect.h = ctx.sprite.mask.h;
+ srcrect.x = ctx.sprite.mask.x;
+ srcrect.y = ctx.sprite.mask.y;
+ srcrect_ptr = &srcrect;
+ }
+
+ SDL_FRect dstrect = this->get_dst_rect(SDLContext::DestinationRectangleData{
+ .sprite = ctx.sprite,
+ .texture = ctx.texture,
+ .pos = ctx.pos,
+ .img_scale = ctx.scale,
+ });
- SDL_SetRenderDrawColor(this->game_renderer.get(), cam.bg_color.r,
- cam.bg_color.g, cam.bg_color.b, cam.bg_color.a);
+ double angle = ctx.angle + data.angle_offset;
+
+ this->set_color_texture(ctx.texture, ctx.sprite.data.color);
+ SDL_RenderCopyExF(this->game_renderer.get(), ctx.texture.get_img(), srcrect_ptr, &dstrect,
+ angle, NULL, render_flip);
}
-uint64_t SDLContext::get_ticks() const { return SDL_GetTicks64(); }
+void SDLContext::update_camera_view(const Camera & cam, const vec2 & new_pos) {
+
+ 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);
+ }
+
+ vec2 & zoomed_viewport = this->cam_aux_data.zoomed_viewport;
+ vec2 & bar_size = this->cam_aux_data.bar_size;
+ vec2 & render_scale = this->cam_aux_data.render_scale;
+ this->cam_aux_data.cam_pos = new_pos;
+
+ zoomed_viewport = cam.viewport_size * cam_data.zoom;
+ float screen_aspect = static_cast<float>(cam.screen.x) / cam.screen.y;
+ float 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 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};
+
+ bar_size = {bar_width, 0};
+ render_scale.x = render_scale.y = scale;
+ } else {
+ // letterboxing
+ 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.screen.y - bar_height), (float) cam.screen.x, bar_height};
+
+ bar_size = {0, bar_height};
+ render_scale.x = render_scale.y = scale;
+ }
+
+ 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,
+ };
+
+ // fill bg color
+ SDL_RenderFillRect(this->game_renderer.get(), &bg);
+}
std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>>
SDLContext::texture_from_path(const std::string & path) {
SDL_Surface * tmp = IMG_Load(path.c_str());
- if (tmp == nullptr) {
- tmp = IMG_Load("asset/texture/ERROR.png");
- }
+ if (tmp == nullptr)
+ throw runtime_error(format("SDLContext: IMG_Load error: {}", SDL_GetError()));
- std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>>
- img_surface;
- img_surface
- = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }};
+ std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>> img_surface;
+ img_surface = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }};
- SDL_Texture * tmp_texture = SDL_CreateTextureFromSurface(
- this->game_renderer.get(), img_surface.get());
+ SDL_Texture * tmp_texture
+ = SDL_CreateTextureFromSurface(this->game_renderer.get(), img_surface.get());
if (tmp_texture == nullptr) {
- throw Exception("Texture cannot be load from {}", path);
+ throw runtime_error(format("SDLContext: Texture cannot be load from {}", path));
}
- std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>>
- img_texture;
- img_texture = {tmp_texture,
- [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }};
+ std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> img_texture;
+ img_texture = {tmp_texture, [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }};
+ SDL_SetTextureBlendMode(img_texture.get(), SDL_BLENDMODE_BLEND);
return img_texture;
}
-int SDLContext::get_width(const Texture & ctx) const {
- int w;
- SDL_QueryTexture(ctx.texture.get(), NULL, NULL, &w, NULL);
- return w;
+
+ivec2 SDLContext::get_size(const Texture & ctx) {
+ ivec2 size;
+ SDL_QueryTexture(ctx.get_img(), NULL, NULL, &size.x, &size.y);
+ return size;
}
-int SDLContext::get_height(const Texture & ctx) const {
- int h;
- SDL_QueryTexture(ctx.texture.get(), NULL, NULL, NULL, &h);
- return h;
+
+std::vector<EventData> SDLContext::get_events() {
+ std::vector<EventData> event_list;
+ SDL_Event event;
+ const CameraAuxiliaryData & cam = this->cam_aux_data;
+ while (SDL_PollEvent(&event)) {
+ ivec2 mouse_pos;
+ mouse_pos.x = (event.button.x - cam.bar_size.x) / cam.render_scale.x;
+ mouse_pos.y = (event.button.y - cam.bar_size.y) / cam.render_scale.y;
+ switch (event.type) {
+ case SDL_QUIT:
+ event_list.push_back({.event_type = EventType::SHUTDOWN});
+ break;
+ case SDL_KEYDOWN:
+ event_list.push_back(EventData{
+ .event_type = EventType::KEY_DOWN,
+ .data = {
+ .key_data = {
+ .key = this->sdl_to_keycode(event.key.keysym.scancode),
+ .key_repeat = event.key.repeat != 0,
+ },
+ },
+ });
+ break;
+
+ case SDL_KEYUP:
+ event_list.push_back(EventData{
+ .event_type = EventType::KEY_UP,
+ .data = {
+ .key_data = {
+ .key = this->sdl_to_keycode(event.key.keysym.scancode),
+ .key_repeat = event.key.repeat != 0,
+ },
+ },
+ });
+ break;
+
+ case SDL_MOUSEBUTTONDOWN:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_DOWN,
+ .data = {
+ .mouse_data = {
+ .mouse_button = this->sdl_to_mousebutton(event.button.button),
+ .mouse_position = mouse_pos,
+ },
+ },
+ });
+ break;
+ case SDL_MOUSEBUTTONUP:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_UP,
+ .data = {
+ .mouse_data = {
+ .mouse_button = this->sdl_to_mousebutton(event.button.button),
+ .mouse_position = mouse_pos,
+ },
+ },
+ });
+ break;
+
+ case SDL_MOUSEMOTION:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_MOVE,
+ .data = {
+ .mouse_data = {
+ .mouse_position = mouse_pos,
+ .rel_mouse_move = {event.motion.xrel, event.motion.yrel},
+ },
+ },
+ });
+ break;
+
+ case SDL_MOUSEWHEEL:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_WHEEL,
+ .data = {
+ .mouse_data = {
+ .mouse_position = mouse_pos,
+ .scroll_direction = event.wheel.y < 0 ? -1 : 1,
+ .scroll_delta = event.wheel.preciseY,
+ },
+ },
+ });
+ break;
+ case SDL_WINDOWEVENT:
+ this->handle_window_event(event.window, event_list);
+ break;
+ }
+ }
+
+ return event_list;
+}
+
+void SDLContext::handle_window_event(const SDL_WindowEvent & window_event,
+ std::vector<EventData> & event_list) {
+ switch (window_event.event) {
+ case SDL_WINDOWEVENT_EXPOSED:
+ event_list.push_back(EventData{EventType::WINDOW_EXPOSE});
+ break;
+ case SDL_WINDOWEVENT_RESIZED:
+ event_list.push_back(EventData{
+ .event_type = EventType::WINDOW_RESIZE,
+ .data = {
+ .window_data = {
+ .resize_dimension = {window_event.data1, window_event.data2}
+ },
+ },
+ });
+ break;
+ case SDL_WINDOWEVENT_MOVED:
+ event_list.push_back(EventData{
+ .event_type = EventType::WINDOW_MOVE,
+ .data = {
+ .window_data = {
+ .move_delta = {window_event.data1, window_event.data2}
+ },
+ },
+ });
+ break;
+
+ case SDL_WINDOWEVENT_MINIMIZED:
+ event_list.push_back(EventData{EventType::WINDOW_MINIMIZE});
+ break;
+ case SDL_WINDOWEVENT_MAXIMIZED:
+ event_list.push_back(EventData{EventType::WINDOW_MAXIMIZE});
+ break;
+ case SDL_WINDOWEVENT_FOCUS_GAINED:
+ event_list.push_back(EventData{EventType::WINDOW_FOCUS_GAIN});
+ break;
+ case SDL_WINDOWEVENT_FOCUS_LOST:
+ event_list.push_back(EventData{EventType::WINDOW_FOCUS_LOST});
+ break;
+ }
+}
+
+void SDLContext::set_color_texture(const Texture & texture, const Color & color) {
+ SDL_SetTextureColorMod(texture.get_img(), color.r, color.g, color.b);
+ SDL_SetTextureAlphaMod(texture.get_img(), color.a);
+}
+
+Asset SDLContext::get_font_from_name(const std::string & font_family) {
+ return this->font_facade.get_font_asset(font_family);
}
-void SDLContext::delay(int ms) const { SDL_Delay(ms); }
diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h
index 536dec5..b687f87 100644
--- a/src/crepe/facade/SDLContext.h
+++ b/src/crepe/facade/SDLContext.h
@@ -1,38 +1,75 @@
#pragma once
+#include <SDL2/SDL.h>
#include <SDL2/SDL_keycode.h>
+#include <SDL2/SDL_rect.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_video.h>
+#include <cmath>
#include <functional>
#include <memory>
#include <string>
+#include <unordered_map>
-#include "../api/Sprite.h"
-#include "../api/Transform.h"
+#include "../types.h"
#include "api/Camera.h"
+#include "api/Color.h"
+#include "api/KeyCodes.h"
+#include "api/Sprite.h"
+#include "api/Transform.h"
+#include "types.h"
-// FIXME: this needs to be removed
-const int SCREEN_WIDTH = 640;
-const int SCREEN_HEIGHT = 480;
+#include "EventData.h"
+#include "FontFacade.h"
namespace crepe {
-
-// TODO: SDL_Keycode is defined in a header not distributed with crepe, which
-// means this typedef is unusable when crepe is packaged. Wouter will fix this
-// later.
-typedef SDL_Keycode CREPE_KEYCODES;
-
class Texture;
-class LoopManager;
+class Mediator;
/**
- * \class SDLContext
* \brief Facade for the SDL library
- *
- * 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
+ *
+ * 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 {
+public:
+ //! data that the camera component cannot hold
+ struct CameraAuxiliaryData {
+
+ //! zoomed in viewport in game_units
+ vec2 zoomed_viewport;
+
+ /**
+ * \brief scaling factor
+ *
+ * depending on the black bars type will the scaling be different.
+ * - letterboxing --> scaling on the y-as
+ * - pillarboxing --> scaling on the x-as
+ */
+ vec2 render_scale;
+
+ /**
+ * \brief size of calculated black bars
+ *
+ * depending on the black bars type will the size be different
+ * - lettorboxing --> {0, bar_height}
+ * - pillarboxing --> {bar_width , 0}
+ */
+ vec2 bar_size;
+
+ //! Calculated camera position
+ vec2 cam_pos;
+ };
+
+ //! rendering data needed to render on screen
+ struct RenderContext {
+ const Sprite & sprite;
+ const Texture & texture;
+ const vec2 & pos;
+ const double & angle;
+ const double & scale;
+ };
public:
/**
@@ -41,61 +78,93 @@ public:
*/
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 handle_events
- friend class LoopManager;
+public:
/**
- * \brief Handles SDL events such as window close and input.
- * \param running Reference to a boolean flag that controls the main loop.
+ * \brief Constructs an SDLContext instance.
+ * Initializes SDL, creates a window and renderer.
*/
- void handle_events(bool & running);
+ SDLContext(Mediator & mediator);
-private:
- //! Will only use get_ticks
- friend class AnimatorSystem;
- //! Will only use delay
- friend class LoopTimer;
/**
- * \brief Gets the current SDL ticks since the program started.
- * \return Current ticks in milliseconds as a constant uint64_t.
+ * \brief Destroys the SDLContext instance.
+ * Cleans up SDL resources, including the window and renderer.
*/
- uint64_t get_ticks() const;
+ ~SDLContext();
+
+public:
/**
- * \brief Pauses the execution for a specified duration.
+ * \brief Retrieves a list of all events from the SDL context.
*
- * This function uses SDL's delay function to halt the program execution
- * for a given number of milliseconds, allowing for frame rate control
- * or other timing-related functionality.
+ * This method retrieves all the events from the SDL context that are currently
+ * available. It is primarily used by the InputSystem to process various
+ * input events such as mouse clicks, mouse movements, and keyboard presses.
*
- * \param ms Duration of the delay in milliseconds.
+ * \return Events that occurred since last call to `get_events()`
*/
- void delay(int ms) const;
-
-private:
+ std::vector<EventData> get_events();
/**
- * \brief Constructs an SDLContext instance.
- * Initializes SDL, creates a window and renderer.
+ * \brief Fills event_list with triggered window events
+ *
+ * This method checks if any window events are triggered and adds them to the event_list.
+ *
*/
- SDLContext();
-
+ void handle_window_event(const SDL_WindowEvent & window_event,
+ std::vector<EventData> & event_list);
/**
- * \brief Destroys the SDLContext instance.
- * Cleans up SDL resources, including the window and renderer.
+ * \brief Converts an SDL scan code to the custom Keycode type.
+ *
+ * This method maps an SDL scan code to the corresponding `Keycode` enum value,
+ * which is used internally by the system to identify the keys.
+ *
+ * \param sdl_key The SDL scan code to convert.
+ * \return The corresponding `Keycode` value or `Keycode::NONE` if the key is unrecognized.
*/
- ~SDLContext();
+ Keycode sdl_to_keycode(SDL_Scancode sdl_key);
-private:
- //! Will use the funtions: texture_from_path, get_width,get_height.
- friend class Texture;
+ /**
+ * \brief Converts an SDL mouse button code to the custom MouseButton type.
+ *
+ * This method maps an SDL mouse button code to the corresponding `MouseButton`
+ * enum value, which is used internally by the system to identify mouse buttons.
+ *
+ * \param sdl_button The SDL mouse button code to convert.
+ * \return The corresponding `MouseButton` value or `MouseButton::NONE` if the key is unrecognized
+ */
+ MouseButton sdl_to_mousebutton(Uint8 sdl_button);
+ /**
+ * \brief Gets the current state of the keyboard.
+ *
+ * Updates the internal keyboard state by checking the current key states using
+ * SDL's `SDL_GetKeyboardState()`, and returns a reference to the `keyboard_state_t`.
+ *
+ * \return A constant reference to the `keyboard_state_t`, which holds the state
+ * of each key (true = pressed, false = not pressed).
+ */
+ const keyboard_state_t & get_keyboard_state();
- //! Will use the funtions: texture_from_path, get_width,get_height.
- friend class Animator;
+public:
+ /**
+ * \brief Gets the current SDL ticks since the program started.
+ * \return Current ticks in milliseconds as a constant uint64_t.
+ */
+ uint64_t get_ticks() const;
+ /**
+ * \brief Pauses the execution for a specified duration.
+ *
+ * This function uses SDL's delay function to halt the program execution for a given number
+ * of milliseconds, allowing for frame rate control or other timing-related functionality.
+ *
+ * \param ms Duration of the delay in milliseconds.
+ */
+ void delay(int ms) const;
+public:
/**
* \brief Loads a texture from a file path.
* \param path Path to the image file.
@@ -104,31 +173,18 @@ private:
std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>>
texture_from_path(const std::string & path);
/**
- * \brief Gets the width of a texture.
+ * \brief Gets the size of a texture.
* \param texture Reference to the Texture object.
- * \return Width of the texture as an integer.
+ * \return Width and height of the texture as an integer in pixels.
*/
- int get_width(const Texture &) const;
-
- /**
- * \brief Gets the height of a texture.
- * \param texture Reference to the Texture object.
- * \return Height of the texture as an integer.
- */
- int get_height(const Texture &) const;
-
-private:
- //! Will use draw,clear_screen, present_screen, camera.
- friend class RenderSystem;
+ ivec2 get_size(const Texture & ctx);
+public:
/**
* \brief Draws a sprite to the screen using the specified transform and camera.
- * \param sprite Reference to the Sprite to draw.
- * \param transform Reference to the Transform for positioning.
- * \param camera Reference to the Camera for view adjustments.
+ * \param RenderContext Reference to rendering data to draw
*/
- void draw(const Sprite & sprite, const Transform & transform,
- const Camera & camera);
+ void draw(const RenderContext & ctx);
//! Clears the screen, preparing for a new frame.
void clear_screen();
@@ -137,21 +193,173 @@ private:
void present_screen();
/**
- * \brief Sets the current camera for rendering.
- * \param camera Reference to the Camera object.
+ * \brief calculates camera view settings. such as black_bars, zoomed_viewport, scaling and
+ * adjusting window size.
+ *
+ * \note only supports windowed mode.
+ * \param camera Reference to the current Camera object in the scene.
+ * \param new_pos new camera position from transform and offset
+ */
+ void update_camera_view(const Camera & camera, const vec2 & new_pos);
+
+public:
+ //! the data needed to construct a sdl dst rectangle
+ struct DestinationRectangleData {
+ const Sprite & sprite;
+ const Texture & texture;
+ const vec2 & pos;
+ const double & img_scale;
+ };
+
+ /**
+ * \brief calculates the sqaure size of the image for destination
+ *
+ * \param data needed to calculate a destination rectangle
+ * \return sdl rectangle to draw a dst image to draw on the screen
+ */
+ SDL_FRect get_dst_rect(const DestinationRectangleData & data) const;
+ /**
+ * \brief Set an additional color value multiplied into render copy operations.
+ *
+ * \param texture the given texture to adjust
+ * \param color the color data for the texture
*/
- void camera(const Camera & camera);
+ void set_color_texture(const Texture & texture, const Color & color);
private:
//! sdl Window
std::unique_ptr<SDL_Window, std::function<void(SDL_Window *)>> game_window;
//! renderer for the crepe engine
- std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>>
- game_renderer;
+ std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>> game_renderer;
- //! viewport for the camera window
- SDL_Rect viewport = {0, 0, 640, 480};
+ //! black bars rectangle to draw
+ SDL_FRect black_bars[2] = {};
+
+ /**
+ * \cam_aux_data extra data that the component cannot hold.
+ *
+ * - this is defined in this class because get_events() needs this information aswell
+ */
+ CameraAuxiliaryData cam_aux_data;
+
+private:
+ //! instance of the font_facade
+ FontFacade font_facade{};
+
+public:
+ /**
+ * \brief Function to Get asset from font_family
+ *
+ * This function uses the FontFacade function to convert a font_family to an asset.
+ *
+ * \param font_family name of the font style that needs to be used (will return an asset with default font path of the font_family doesnt exist)
+ *
+ * \return asset with the font style absolute path
+ */
+ Asset get_font_from_name(const std::string & font_family);
+ //! variable to store the state of each key (true = pressed, false = not pressed)
+ keyboard_state_t keyboard_state;
+ //! lookup table for converting SDL_SCANCODES to Keycodes
+ const std::unordered_map<SDL_Scancode, Keycode> lookup_table
+ = {{SDL_SCANCODE_SPACE, Keycode::SPACE},
+ {SDL_SCANCODE_APOSTROPHE, Keycode::APOSTROPHE},
+ {SDL_SCANCODE_COMMA, Keycode::COMMA},
+ {SDL_SCANCODE_MINUS, Keycode::MINUS},
+ {SDL_SCANCODE_PERIOD, Keycode::PERIOD},
+ {SDL_SCANCODE_SLASH, Keycode::SLASH},
+ {SDL_SCANCODE_0, Keycode::D0},
+ {SDL_SCANCODE_1, Keycode::D1},
+ {SDL_SCANCODE_2, Keycode::D2},
+ {SDL_SCANCODE_3, Keycode::D3},
+ {SDL_SCANCODE_4, Keycode::D4},
+ {SDL_SCANCODE_5, Keycode::D5},
+ {SDL_SCANCODE_6, Keycode::D6},
+ {SDL_SCANCODE_7, Keycode::D7},
+ {SDL_SCANCODE_8, Keycode::D8},
+ {SDL_SCANCODE_9, Keycode::D9},
+ {SDL_SCANCODE_SEMICOLON, Keycode::SEMICOLON},
+ {SDL_SCANCODE_EQUALS, Keycode::EQUAL},
+ {SDL_SCANCODE_A, Keycode::A},
+ {SDL_SCANCODE_B, Keycode::B},
+ {SDL_SCANCODE_C, Keycode::C},
+ {SDL_SCANCODE_D, Keycode::D},
+ {SDL_SCANCODE_E, Keycode::E},
+ {SDL_SCANCODE_F, Keycode::F},
+ {SDL_SCANCODE_G, Keycode::G},
+ {SDL_SCANCODE_H, Keycode::H},
+ {SDL_SCANCODE_I, Keycode::I},
+ {SDL_SCANCODE_J, Keycode::J},
+ {SDL_SCANCODE_K, Keycode::K},
+ {SDL_SCANCODE_L, Keycode::L},
+ {SDL_SCANCODE_M, Keycode::M},
+ {SDL_SCANCODE_N, Keycode::N},
+ {SDL_SCANCODE_O, Keycode::O},
+ {SDL_SCANCODE_P, Keycode::P},
+ {SDL_SCANCODE_Q, Keycode::Q},
+ {SDL_SCANCODE_R, Keycode::R},
+ {SDL_SCANCODE_S, Keycode::S},
+ {SDL_SCANCODE_T, Keycode::T},
+ {SDL_SCANCODE_U, Keycode::U},
+ {SDL_SCANCODE_V, Keycode::V},
+ {SDL_SCANCODE_W, Keycode::W},
+ {SDL_SCANCODE_X, Keycode::X},
+ {SDL_SCANCODE_Y, Keycode::Y},
+ {SDL_SCANCODE_Z, Keycode::Z},
+ {SDL_SCANCODE_LEFTBRACKET, Keycode::LEFT_BRACKET},
+ {SDL_SCANCODE_BACKSLASH, Keycode::BACKSLASH},
+ {SDL_SCANCODE_RIGHTBRACKET, Keycode::RIGHT_BRACKET},
+ {SDL_SCANCODE_GRAVE, Keycode::GRAVE_ACCENT},
+ {SDL_SCANCODE_ESCAPE, Keycode::ESCAPE},
+ {SDL_SCANCODE_RETURN, Keycode::ENTER},
+ {SDL_SCANCODE_TAB, Keycode::TAB},
+ {SDL_SCANCODE_BACKSPACE, Keycode::BACKSPACE},
+ {SDL_SCANCODE_INSERT, Keycode::INSERT},
+ {SDL_SCANCODE_DELETE, Keycode::DELETE},
+ {SDL_SCANCODE_RIGHT, Keycode::RIGHT},
+ {SDL_SCANCODE_LEFT, Keycode::LEFT},
+ {SDL_SCANCODE_DOWN, Keycode::DOWN},
+ {SDL_SCANCODE_UP, Keycode::UP},
+ {SDL_SCANCODE_PAGEUP, Keycode::PAGE_UP},
+ {SDL_SCANCODE_PAGEDOWN, Keycode::PAGE_DOWN},
+ {SDL_SCANCODE_HOME, Keycode::HOME},
+ {SDL_SCANCODE_END, Keycode::END},
+ {SDL_SCANCODE_CAPSLOCK, Keycode::CAPS_LOCK},
+ {SDL_SCANCODE_SCROLLLOCK, Keycode::SCROLL_LOCK},
+ {SDL_SCANCODE_NUMLOCKCLEAR, Keycode::NUM_LOCK},
+ {SDL_SCANCODE_PRINTSCREEN, Keycode::PRINT_SCREEN},
+ {SDL_SCANCODE_PAUSE, Keycode::PAUSE},
+ {SDL_SCANCODE_F1, Keycode::F1},
+ {SDL_SCANCODE_F2, Keycode::F2},
+ {SDL_SCANCODE_F3, Keycode::F3},
+ {SDL_SCANCODE_F4, Keycode::F4},
+ {SDL_SCANCODE_F5, Keycode::F5},
+ {SDL_SCANCODE_F6, Keycode::F6},
+ {SDL_SCANCODE_F7, Keycode::F7},
+ {SDL_SCANCODE_F8, Keycode::F8},
+ {SDL_SCANCODE_F9, Keycode::F9},
+ {SDL_SCANCODE_F10, Keycode::F10},
+ {SDL_SCANCODE_F11, Keycode::F11},
+ {SDL_SCANCODE_F12, Keycode::F12},
+ {SDL_SCANCODE_KP_0, Keycode::KP0},
+ {SDL_SCANCODE_KP_1, Keycode::KP1},
+ {SDL_SCANCODE_KP_2, Keycode::KP2},
+ {SDL_SCANCODE_KP_3, Keycode::KP3},
+ {SDL_SCANCODE_KP_4, Keycode::KP4},
+ {SDL_SCANCODE_KP_5, Keycode::KP5},
+ {SDL_SCANCODE_KP_6, Keycode::KP6},
+ {SDL_SCANCODE_KP_7, Keycode::KP7},
+ {SDL_SCANCODE_KP_8, Keycode::KP8},
+ {SDL_SCANCODE_KP_9, Keycode::KP9},
+ {SDL_SCANCODE_LSHIFT, Keycode::LEFT_SHIFT},
+ {SDL_SCANCODE_LCTRL, Keycode::LEFT_CONTROL},
+ {SDL_SCANCODE_LALT, Keycode::LEFT_ALT},
+ {SDL_SCANCODE_LGUI, Keycode::LEFT_SUPER},
+ {SDL_SCANCODE_RSHIFT, Keycode::RIGHT_SHIFT},
+ {SDL_SCANCODE_RCTRL, Keycode::RIGHT_CONTROL},
+ {SDL_SCANCODE_RALT, Keycode::RIGHT_ALT},
+ {SDL_SCANCODE_RGUI, Keycode::RIGHT_SUPER},
+ {SDL_SCANCODE_MENU, Keycode::MENU}};
};
} // namespace crepe
diff --git a/src/crepe/facade/Sound.cpp b/src/crepe/facade/Sound.cpp
index b589759..97e455e 100644
--- a/src/crepe/facade/Sound.cpp
+++ b/src/crepe/facade/Sound.cpp
@@ -2,58 +2,12 @@
#include "../util/Log.h"
#include "Sound.h"
-#include "SoundContext.h"
using namespace crepe;
using namespace std;
-Sound::Sound(const Asset & src) : Resource(src) {
+Sound::Sound(const Asset & src, Mediator & mediator) : Resource(src, mediator) {
this->sample.load(src.get_path().c_str());
dbg_trace();
}
Sound::~Sound() { dbg_trace(); }
-
-void Sound::play() {
- SoundContext & ctx = this->context.get();
- if (ctx.engine.getPause(this->handle)) {
- // resume if paused
- ctx.engine.setPause(this->handle, false);
- } else {
- // or start new sound
- this->handle = ctx.engine.play(this->sample, this->volume);
- ctx.engine.setLooping(this->handle, this->looping);
- }
-}
-
-void Sound::pause() {
- SoundContext & ctx = this->context.get();
- if (ctx.engine.getPause(this->handle)) return;
- ctx.engine.setPause(this->handle, true);
-}
-
-void Sound::rewind() {
- SoundContext & ctx = this->context.get();
- if (!ctx.engine.isValidVoiceHandle(this->handle)) return;
- ctx.engine.seek(this->handle, 0);
-}
-
-void Sound::set_volume(float volume) {
- this->volume = volume;
-
- SoundContext & ctx = this->context.get();
- if (!ctx.engine.isValidVoiceHandle(this->handle)) return;
- ctx.engine.setVolume(this->handle, this->volume);
-}
-
-void Sound::set_looping(bool looping) {
- this->looping = looping;
-
- SoundContext & ctx = this->context.get();
- if (!ctx.engine.isValidVoiceHandle(this->handle)) return;
- ctx.engine.setLooping(this->handle, this->looping);
-}
-
-void Sound::set_context(SoundContext & ctx) {
- this->context = ctx;
-}
-
diff --git a/src/crepe/facade/Sound.h b/src/crepe/facade/Sound.h
index 94b1996..4a5d692 100644
--- a/src/crepe/facade/Sound.h
+++ b/src/crepe/facade/Sound.h
@@ -3,86 +3,29 @@
#include <soloud/soloud.h>
#include <soloud/soloud_wav.h>
-#include "../util/OptionalRef.h"
#include "../Resource.h"
namespace crepe {
class SoundContext;
+class Mediator;
/**
* \brief Sound resource facade
*
- * This class is a wrapper around a \c SoLoud::Wav instance, which holds a
- * single sample. It is part of the sound facade.
+ * This class is a wrapper around a \c SoLoud::Wav instance, which holds a single sample. It is
+ * part of the sound facade.
*/
class Sound : public Resource {
public:
- Sound(const Asset & src);
+ Sound(const Asset & src, Mediator & mediator);
~Sound(); // dbg_trace
- /**
- * \brief Pause this sample
- *
- * Pauses this sound if it is playing, or does nothing if it is already
- * paused. The playhead position is saved, such that calling \c play() after
- * this function makes the sound resume.
- */
- void pause();
- /**
- * \brief Play this sample
- *
- * Resume playback if this sound is paused, or start from the beginning of
- * the sample.
- *
- * \note This class only saves a reference to the most recent 'voice' of this
- * sound. Calling \c play() while the sound is already playing causes
- * multiple instances of the sample to play simultaniously. The sample
- * started last is the one that is controlled afterwards.
- */
- void play();
- /**
- * \brief Reset playhead position
- *
- * Resets the playhead position so that calling \c play() after this function
- * makes it play from the start of the sample. If the sound is not paused
- * before calling this function, this function will stop playback.
- */
- void rewind();
- /**
- * \brief Set playback volume / gain
- *
- * \param volume Volume (0 = muted, 1 = full volume)
- */
- void set_volume(float volume);
- /**
- * \brief Get playback volume / gain
- *
- * \return Volume
- */
- float get_volume() const { return this->volume; }
- /**
- * \brief Set looping behavior for this sample
- *
- * \param looping Looping behavior (false = one-shot, true = loop)
- */
- void set_looping(bool looping);
- /**
- * \brief Get looping behavior
- *
- * \return true if looping, false if one-shot
- */
- bool get_looping() const { return this->looping; }
-
-public:
- void set_context(SoundContext & ctx);
private:
+ //! Deserialized resource (soloud)
SoLoud::Wav sample;
- SoLoud::handle handle;
- OptionalRef<SoundContext> context;
-
- float volume = 1.0f;
- bool looping = false;
+ //! SoundContext uses \c sample
+ friend class SoundContext;
};
} // namespace crepe
diff --git a/src/crepe/facade/SoundContext.cpp b/src/crepe/facade/SoundContext.cpp
index b65dfb2..b1f8cb3 100644
--- a/src/crepe/facade/SoundContext.cpp
+++ b/src/crepe/facade/SoundContext.cpp
@@ -6,10 +6,31 @@ using namespace crepe;
SoundContext::SoundContext() {
dbg_trace();
- engine.init();
+ this->engine.init();
+ this->engine.setMaxActiveVoiceCount(this->config.audio.voices);
}
SoundContext::~SoundContext() {
dbg_trace();
- engine.deinit();
+ this->engine.deinit();
+}
+
+SoundHandle SoundContext::play(Sound & resource) {
+ SoLoud::handle real_handle = this->engine.play(resource.sample, 1.0f);
+ SoundHandle handle = this->next_handle;
+ this->registry[handle] = real_handle;
+ this->next_handle++;
+ return handle;
+}
+
+void SoundContext::stop(const SoundHandle & handle) {
+ this->engine.stop(this->registry[handle]);
+}
+
+void SoundContext::set_volume(const SoundHandle & handle, float volume) {
+ this->engine.setVolume(this->registry[handle], volume);
+}
+
+void SoundContext::set_loop(const SoundHandle & handle, bool loop) {
+ this->engine.setLooping(this->registry[handle], loop);
}
diff --git a/src/crepe/facade/SoundContext.h b/src/crepe/facade/SoundContext.h
index d22ff7a..d986c59 100644
--- a/src/crepe/facade/SoundContext.h
+++ b/src/crepe/facade/SoundContext.h
@@ -2,15 +2,18 @@
#include <soloud/soloud.h>
+#include "../api/Config.h"
+
#include "Sound.h"
+#include "SoundHandle.h"
namespace crepe {
/**
* \brief Sound engine facade
*
- * This class is a wrapper around a \c SoLoud::Soloud instance, which provides
- * the methods for playing \c Sound instances. It is part of the sound facade.
+ * This class is a wrapper around a \c SoLoud::Soloud instance, which provides the methods for
+ * playing \c Sound instances. It is part of the sound facade.
*/
class SoundContext {
public:
@@ -22,10 +25,57 @@ public:
SoundContext & operator=(const SoundContext &) = delete;
SoundContext & operator=(SoundContext &&) = delete;
+ /**
+ * \brief Play a sample
+ *
+ * Plays a Sound from the beginning of the sample and returns a handle to control it later.
+ *
+ * \param resource Sound instance to play
+ *
+ * \returns Handle to control this voice
+ */
+ virtual SoundHandle play(Sound & resource);
+ /**
+ * \brief Stop a voice immediately if it is still playing
+ *
+ * \note This function does nothing if the handle is invalid or if the sound is already
+ * stopped / finished playing.
+ *
+ * \param handle Voice handle returned by SoundContext::play
+ */
+ virtual void stop(const SoundHandle & handle);
+ /**
+ * \brief Change the volume of a voice
+ *
+ * \note This function does nothing if the handle is invalid or if the sound is already
+ * stopped / finished playing.
+ *
+ * \param handle Voice handle returned by SoundContext::play
+ * \param volume New gain value (0=silent, 1=default)
+ */
+ virtual void set_volume(const SoundHandle & handle, float volume);
+ /**
+ * \brief Set the looping behavior of a voice
+ *
+ * \note This function does nothing if the handle is invalid or if the sound is already
+ * stopped / finished playing.
+ *
+ * \param handle Voice handle returned by SoundContext::play
+ * \param loop Looping behavior (false=oneshot, true=loop)
+ */
+ virtual void set_loop(const SoundHandle & handle, bool loop);
+
private:
+ //! Abstracted class
SoLoud::Soloud engine;
- //! Sound directly calls methods on \c engine
- friend class Sound;
+
+ //! Config reference
+ Config & config = Config::get_instance();
+
+ //! Sound handle registry
+ std::unordered_map<SoundHandle, SoLoud::handle> registry;
+ //! Unique handle counter
+ SoundHandle next_handle = 0;
};
} // namespace crepe
diff --git a/src/crepe/facade/SoundHandle.h b/src/crepe/facade/SoundHandle.h
new file mode 100644
index 0000000..b7925fc
--- /dev/null
+++ b/src/crepe/facade/SoundHandle.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include <cstddef>
+
+namespace crepe {
+
+/**
+ * \brief Voice handle returned by
+ */
+typedef size_t SoundHandle;
+
+} // namespace crepe
diff --git a/src/crepe/facade/Texture.cpp b/src/crepe/facade/Texture.cpp
new file mode 100644
index 0000000..b63403d
--- /dev/null
+++ b/src/crepe/facade/Texture.cpp
@@ -0,0 +1,28 @@
+#include "../util/Log.h"
+#include "facade/SDLContext.h"
+#include "manager/Mediator.h"
+
+#include "Resource.h"
+#include "Texture.h"
+#include "types.h"
+
+using namespace crepe;
+using namespace std;
+
+Texture::Texture(const Asset & src, Mediator & mediator) : Resource(src, mediator) {
+ dbg_trace();
+ SDLContext & ctx = mediator.sdl_context;
+ this->texture = ctx.texture_from_path(src.get_path());
+ this->size = ctx.get_size(*this);
+ this->aspect_ratio = static_cast<float>(this->size.x) / this->size.y;
+}
+
+Texture::~Texture() {
+ dbg_trace();
+ this->texture.reset();
+}
+
+const ivec2 & Texture::get_size() const noexcept { return this->size; }
+const float & Texture::get_ratio() const noexcept { return this->aspect_ratio; }
+
+SDL_Texture * Texture::get_img() const noexcept { return this->texture.get(); }
diff --git a/src/crepe/facade/Texture.h b/src/crepe/facade/Texture.h
new file mode 100644
index 0000000..cdacac4
--- /dev/null
+++ b/src/crepe/facade/Texture.h
@@ -0,0 +1,69 @@
+#pragma once
+
+#include <SDL2/SDL_render.h>
+#include <memory>
+
+#include "../Resource.h"
+
+#include "types.h"
+
+namespace crepe {
+
+class Mediator;
+class Asset;
+
+/**
+ * \class Texture
+ * \brief Manages texture loading and properties.
+ *
+ * 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 : public Resource {
+
+public:
+ /**
+ * \brief Constructs a Texture from an Asset resource.
+ * \param src Asset with texture data to load.
+ * \param mediator use the SDLContext reference to load the image
+ */
+ Texture(const Asset & src, Mediator & mediator);
+
+ /**
+ * \brief Destroys the Texture instance
+ */
+ ~Texture();
+
+ /**
+ * \brief get width and height of image in pixels
+ * \return pixel size width and height
+ *
+ */
+ const ivec2 & get_size() const noexcept;
+
+ /**
+ * \brief aspect_ratio of image
+ * \return ratio
+ *
+ */
+ const float & get_ratio() const noexcept;
+
+ /**
+ * \brief get the image texture
+ * \return SDL_Texture
+ *
+ */
+ SDL_Texture * get_img() const noexcept;
+
+private:
+ //! The texture of the class from the library
+ std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> texture;
+
+ // texture size in pixel
+ ivec2 size;
+
+ //! ratio of image
+ float aspect_ratio;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/CMakeLists.txt b/src/crepe/manager/CMakeLists.txt
new file mode 100644
index 0000000..f73e165
--- /dev/null
+++ b/src/crepe/manager/CMakeLists.txt
@@ -0,0 +1,25 @@
+target_sources(crepe PUBLIC
+ ComponentManager.cpp
+ EventManager.cpp
+ Manager.cpp
+ SaveManager.cpp
+ SceneManager.cpp
+ LoopTimerManager.cpp
+ ResourceManager.cpp
+)
+
+target_sources(crepe PUBLIC FILE_SET HEADERS FILES
+ ComponentManager.h
+ ComponentManager.hpp
+ EventManager.h
+ EventManager.hpp
+ Manager.h
+ Mediator.h
+ SaveManager.h
+ SceneManager.h
+ SceneManager.hpp
+ LoopTimerManager.h
+ ResourceManager.h
+ ResourceManager.hpp
+)
+
diff --git a/src/crepe/manager/ComponentManager.cpp b/src/crepe/manager/ComponentManager.cpp
new file mode 100644
index 0000000..df30d27
--- /dev/null
+++ b/src/crepe/manager/ComponentManager.cpp
@@ -0,0 +1,74 @@
+#include "../api/GameObject.h"
+#include "../api/Metadata.h"
+#include "../types.h"
+#include "../util/Log.h"
+
+#include "ComponentManager.h"
+
+using namespace crepe;
+using namespace std;
+
+ComponentManager::ComponentManager(Mediator & mediator) : Manager(mediator) {
+ mediator.component_manager = *this;
+ dbg_trace();
+}
+ComponentManager::~ComponentManager() { dbg_trace(); }
+
+void ComponentManager::delete_all_components_of_id(game_object_id_t id) {
+ // Do not delete persistent objects
+ if (this->persistent[id]) {
+ return;
+ }
+
+ // Loop through all the types (in the unordered_map<>)
+ for (auto & [type, component_array] : this->components) {
+ // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
+ if (id < component_array.size()) {
+ // Clear the components at this specific id
+ component_array[id].clear();
+ }
+ }
+}
+
+void ComponentManager::delete_all_components() {
+ // Loop through all the types (in the unordered_map<>)
+ for (auto & [type, component_array] : this->components) {
+ // Loop through all the ids (in the vector<>)
+ for (game_object_id_t id = 0; id < component_array.size(); id++) {
+ // Do not delete persistent objects
+ if (!this->persistent[id]) {
+ // Clear the components at this specific id
+ component_array[id].clear();
+ }
+ }
+ }
+
+ this->next_id = 0;
+}
+
+GameObject ComponentManager::new_object(const string & name, const string & tag,
+ const vec2 & position, double rotation, double scale) {
+ // Find the first available id (taking persistent objects into account)
+ while (this->persistent[this->next_id]) {
+ this->next_id++;
+ }
+
+ GameObject object{*this, this->next_id, name, tag, position, rotation, scale};
+ this->next_id++;
+
+ return object;
+}
+
+void ComponentManager::set_persistent(game_object_id_t id, bool persistent) {
+ this->persistent[id] = persistent;
+}
+
+set<game_object_id_t> ComponentManager::get_objects_by_name(const string & name) const {
+ return this->get_objects_by_predicate<Metadata>(
+ [name](const Metadata & data) { return data.name == name; });
+}
+
+set<game_object_id_t> ComponentManager::get_objects_by_tag(const string & tag) const {
+ return this->get_objects_by_predicate<Metadata>(
+ [tag](const Metadata & data) { return data.tag == tag; });
+}
diff --git a/src/crepe/manager/ComponentManager.h b/src/crepe/manager/ComponentManager.h
new file mode 100644
index 0000000..19a8e81
--- /dev/null
+++ b/src/crepe/manager/ComponentManager.h
@@ -0,0 +1,230 @@
+#pragma once
+
+#include <memory>
+#include <set>
+#include <typeindex>
+#include <unordered_map>
+#include <vector>
+
+#include "../Component.h"
+#include "../types.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+class GameObject;
+
+/**
+ * \brief Manages all components
+ *
+ * This class manages all components. It provides methods to add, delete and get components.
+ */
+class ComponentManager : public Manager {
+ // TODO: This relation should be removed! I (loek) believe that the scene manager should
+ // create/destroy components because the GameObject's are stored in concrete Scene classes,
+ // which will in turn call GameObject's destructor, which will in turn call
+ // ComponentManager::delete_components_by_id or something. This is a pretty major change, so
+ // here is a comment and temporary fix instead :tada:
+ friend class SceneManager;
+
+public:
+ ComponentManager(Mediator & mediator);
+ ~ComponentManager(); // dbg_trace
+
+ /**
+ * \brief Create a new game object using the component manager
+ *
+ * \param name Metadata::name (required)
+ * \param tag Metadata::tag (optional, empty by default)
+ * \param position Transform::position (optional, origin by default)
+ * \param rotation Transform::rotation (optional, 0 by default)
+ * \param scale Transform::scale (optional, 1 by default)
+ *
+ * \returns GameObject interface
+ *
+ * \note This method automatically assigns a new entity ID
+ */
+ GameObject new_object(const std::string & name, const std::string & tag = "",
+ const vec2 & position = {0, 0}, double rotation = 0,
+ double scale = 1);
+
+protected:
+ /**
+ * GameObject is used as an interface to add/remove components, and the game programmer is
+ * supposed to use it instead of interfacing with the component manager directly.
+ */
+ friend class GameObject;
+ /**
+ * \brief Add a component to the ComponentManager
+ *
+ * This method adds a component to the ComponentManager. The component is created with the
+ * given arguments and added to the ComponentManager.
+ *
+ * \tparam T The type of the component
+ * \tparam Args The types of the arguments
+ * \param id The id of the GameObject this component belongs to
+ * \param args The arguments to create the component
+ * \return The created component
+ */
+ template <typename T, typename... Args>
+ T & add_component(game_object_id_t id, Args &&... args);
+ /**
+ * \brief Delete all components of a specific type and id
+ *
+ * This method deletes all components of a specific type and id.
+ *
+ * \tparam T The type of the component
+ * \param id The id of the GameObject this component belongs to
+ */
+ template <typename T>
+ void delete_components_by_id(game_object_id_t id);
+ /**
+ * \brief Delete all components of a specific type
+ *
+ * This method deletes all components of a specific type.
+ *
+ * \tparam T The type of the component
+ */
+ template <typename T>
+ void delete_components();
+ /**
+ * \brief Delete all components of a specific id
+ *
+ * This method deletes all components of a specific id.
+ *
+ * \param id The id of the GameObject this component belongs to
+ */
+ void delete_all_components_of_id(game_object_id_t id);
+ /**
+ * \brief Delete all components
+ *
+ * This method deletes all components.
+ */
+ void delete_all_components();
+ /**
+ * \brief Set a GameObject as persistent
+ *
+ * This method sets a GameObject as persistent. If a GameObject is persistent, its
+ * components will not be deleted.
+ *
+ * \param id The id of the GameObject to set as persistent
+ * \param persistent The persistent flag
+ */
+ void set_persistent(game_object_id_t id, bool persistent);
+
+public:
+ /**
+ * \brief Get all components of a specific type and id
+ *
+ * This method gets all components of a specific type and id.
+ *
+ * \tparam T The type of the component
+ * \param id The id of the GameObject this component belongs to
+ * \return A vector of all components of the specific type and id
+ */
+ template <typename T>
+ RefVector<T> get_components_by_id(game_object_id_t id) const;
+ /**
+ * \brief Get all components of a specific type
+ *
+ * This method gets all components of a specific type.
+ *
+ * \tparam T The type of the component
+ * \return A vector of all components of the specific type
+ */
+ template <typename T>
+ RefVector<T> get_components_by_type() const;
+ /**
+ * \brief Get all components of a specific type on a GameObject with name \c name
+ *
+ * \tparam T The type of the component
+ * \param name Metadata::name for the same game_object_id as the returned components
+ * \return Components matching criteria
+ */
+ template <typename T>
+ RefVector<T> get_components_by_name(const std::string & name) const;
+ /**
+ * \brief Get all components of a specific type on a GameObject with tag \c tag
+ *
+ * \tparam T The type of the component
+ * \param name Metadata::tag for the same game_object_id as the returned components
+ * \return Components matching criteria
+ */
+ template <typename T>
+ RefVector<T> get_components_by_tag(const std::string & tag) const;
+
+private:
+ /**
+ * \brief Get object IDs by predicate function
+ *
+ * This function calls the predicate function \c pred for all components matching type \c T,
+ * and adds their parent game_object_id to a \c std::set if the predicate returns true.
+ *
+ * \tparam T The type of the component to check the predicate against
+ * \param pred Predicate function
+ *
+ * \note The predicate function may be called for multiple components with the same \c
+ * game_object_id. In this case, the ID is added if *any* call returns \c true.
+ *
+ * \returns game_object_id for all components where the predicate returned true
+ */
+ template <typename T>
+ std::set<game_object_id_t>
+ get_objects_by_predicate(const std::function<bool(const T &)> & pred) const;
+
+ /**
+ * \brief Get components of type \c T for multiple game object IDs
+ *
+ * \tparam T The type of the components to return
+ * \param ids The object IDs
+ *
+ * \return All components matching type \c T and one of the IDs in \c ids
+ */
+ template <typename T>
+ RefVector<T> get_components_by_ids(const std::set<game_object_id_t> & ids) const;
+
+ /**
+ * \brief Get object IDs for objects with name \c name
+ *
+ * \param name Object name to match
+ * \returns Object IDs where Metadata::name is equal to \c name
+ */
+ std::set<game_object_id_t> get_objects_by_name(const std::string & name) const;
+ /**
+ * \brief Get object IDs for objects with tag \c tag
+ *
+ * \param tag Object tag to match
+ * \returns Object IDs where Metadata::tag is equal to \c tag
+ */
+ std::set<game_object_id_t> get_objects_by_tag(const std::string & tag) const;
+
+private:
+ //! By Component \c std::type_index (readability helper type)
+ template <typename T>
+ using by_type = std::unordered_map<std::type_index, T>;
+ //! By \c game_object_id index (readability helper type)
+ template <typename T>
+ using by_id_index = std::vector<T>;
+ /**
+ * \brief The components
+ *
+ * This unordered_map stores all components. The key is the type of the component and the
+ * value is a vector of vectors of unique pointers to the components.
+ *
+ * Every component type has its own vector of vectors of unique pointers to the components.
+ * The first vector is for the ids of the GameObjects and the second vector is for the
+ * components (because a GameObject might have multiple components).
+ */
+ by_type<by_id_index<std::vector<std::unique_ptr<Component>>>> components;
+
+ //! Persistent flag for each GameObject
+ std::unordered_map<game_object_id_t, bool> persistent;
+
+ //! ID of next GameObject allocated by \c ComponentManager::new_object
+ game_object_id_t next_id = 0;
+};
+
+} // namespace crepe
+
+#include "ComponentManager.hpp"
diff --git a/src/crepe/ComponentManager.hpp b/src/crepe/manager/ComponentManager.hpp
index 98efb49..9e70865 100644
--- a/src/crepe/ComponentManager.hpp
+++ b/src/crepe/manager/ComponentManager.hpp
@@ -40,7 +40,6 @@ T & ComponentManager::add_component(game_object_id_t id, Args &&... args) {
// Check if the vector size is not greater than get_instances_max
int max_instances = instance->get_instances_max();
if (max_instances != -1 && components[type][id].size() >= max_instances) {
- // TODO: Exception
throw std::runtime_error(
"Exceeded maximum number of instances for this component type");
}
@@ -55,14 +54,18 @@ template <typename T>
void ComponentManager::delete_components_by_id(game_object_id_t id) {
using namespace std;
+ // Do not delete persistent objects
+ if (this->persistent[id]) {
+ return;
+ }
+
// Determine the type of T (this is used as the key of the unordered_map<>)
type_index type = typeid(T);
// Find the type (in the unordered_map<>)
if (this->components.find(type) != this->components.end()) {
// Get the correct vector<>
- vector<vector<unique_ptr<Component>>> & component_array
- = this->components[type];
+ vector<vector<unique_ptr<Component>>> & component_array = this->components[type];
// Make sure that the id (that we are looking for) is within the boundaries of the vector<>
if (id < component_array.size()) {
@@ -79,62 +82,55 @@ void ComponentManager::delete_components() {
if (this->components.find(type) == this->components.end()) return;
- this->components[type].clear();
+ // Loop through the whole vector<> of this specific type
+ for (game_object_id_t i = 0; i < this->components[type].size(); ++i) {
+ // Do not delete persistent objects
+ if (!this->persistent[i]) {
+ this->components[type][i].clear();
+ }
+ }
}
template <typename T>
-std::vector<std::reference_wrapper<T>>
-ComponentManager::get_components_by_id(game_object_id_t id) const {
+RefVector<T> ComponentManager::get_components_by_id(game_object_id_t id) const {
using namespace std;
- // Determine the type of T (this is used as the key of the unordered_map<>)
- type_index type = typeid(T);
-
- // Create an empty vector<>
- vector<reference_wrapper<T>> component_vector;
+ static_assert(is_base_of<Component, T>::value,
+ "get_components_by_id must recieve a derivative class of Component");
- if (this->components.find(type) == this->components.end())
- return component_vector;
+ type_index type = typeid(T);
+ if (!this->components.contains(type)) return {};
- // Get the correct vector<>
- const vector<vector<unique_ptr<Component>>> & component_array
+ const by_id_index<vector<unique_ptr<Component>>> & components_by_id
= this->components.at(type);
-
- // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
- if (id >= component_array.size()) return component_vector;
-
- // Loop trough the whole vector<>
- for (const unique_ptr<Component> & component_ptr : component_array[id]) {
- // Cast the unique_ptr to a raw pointer
- T * casted_component = static_cast<T *>(component_ptr.get());
-
- if (casted_component == nullptr) continue;
-
- // Add the dereferenced raw pointer to the vector<>
- component_vector.push_back(*casted_component);
+ if (id >= components_by_id.size()) return {};
+
+ RefVector<T> out = {};
+ const vector<unique_ptr<Component>> & components = components_by_id.at(id);
+ for (auto & component_ptr : components) {
+ if (component_ptr == nullptr) continue;
+ Component & component = *component_ptr.get();
+ out.push_back(static_cast<T &>(component));
}
- return component_vector;
+ return out;
}
template <typename T>
-std::vector<std::reference_wrapper<T>>
-ComponentManager::get_components_by_type() const {
+RefVector<T> ComponentManager::get_components_by_type() const {
using namespace std;
// Determine the type of T (this is used as the key of the unordered_map<>)
type_index type = typeid(T);
// Create an empty vector<>
- vector<reference_wrapper<T>> component_vector;
+ RefVector<T> component_vector;
// Find the type (in the unordered_map<>)
- if (this->components.find(type) == this->components.end())
- return component_vector;
+ if (this->components.find(type) == this->components.end()) return component_vector;
// Get the correct vector<>
- const vector<vector<unique_ptr<Component>>> & component_array
- = this->components.at(type);
+ const vector<vector<unique_ptr<Component>>> & component_array = this->components.at(type);
// Loop through the whole vector<>
for (const vector<unique_ptr<Component>> & component : component_array) {
@@ -155,4 +151,46 @@ ComponentManager::get_components_by_type() const {
return component_vector;
}
+template <typename T>
+std::set<game_object_id_t>
+ComponentManager::get_objects_by_predicate(const std::function<bool(const T &)> & pred) const {
+ using namespace std;
+
+ set<game_object_id_t> objects = {};
+ RefVector<T> components = this->get_components_by_type<T>();
+
+ for (const T & component : components) {
+ game_object_id_t id = dynamic_cast<const Component &>(component).game_object_id;
+ if (objects.contains(id)) continue;
+ if (!pred(component)) continue;
+ objects.insert(id);
+ }
+
+ return objects;
+}
+
+template <typename T>
+RefVector<T>
+ComponentManager::get_components_by_ids(const std::set<game_object_id_t> & ids) const {
+ using namespace std;
+
+ RefVector<T> out = {};
+ for (game_object_id_t id : ids) {
+ RefVector<T> components = get_components_by_id<T>(id);
+ out.insert(out.end(), components.begin(), components.end());
+ }
+
+ return out;
+}
+
+template <typename T>
+RefVector<T> ComponentManager::get_components_by_name(const std::string & name) const {
+ return this->get_components_by_ids<T>(this->get_objects_by_name(name));
+}
+
+template <typename T>
+RefVector<T> ComponentManager::get_components_by_tag(const std::string & tag) const {
+ return this->get_components_by_ids<T>(this->get_objects_by_tag(tag));
+}
+
} // namespace crepe
diff --git a/src/crepe/manager/EventManager.cpp b/src/crepe/manager/EventManager.cpp
new file mode 100644
index 0000000..6aa49ee
--- /dev/null
+++ b/src/crepe/manager/EventManager.cpp
@@ -0,0 +1,44 @@
+#include "EventManager.h"
+
+using namespace crepe;
+using namespace std;
+
+EventManager::EventManager(Mediator & mediator) : Manager(mediator) {
+ this->mediator.event_manager = *this;
+}
+void EventManager::dispatch_events() {
+ for (auto & event : this->events_queue) {
+ this->handle_event(event.type, event.channel, *event.event.get());
+ }
+ this->events_queue.clear();
+}
+
+void EventManager::handle_event(type_index type, event_channel_t channel, const Event & data) {
+ auto handlers_it = this->subscribers.find(type);
+ if (handlers_it == this->subscribers.end()) return;
+
+ vector<CallbackEntry> & handlers = handlers_it->second;
+ for (auto & handler : handlers) {
+ bool check_channel = handler.channel != CHANNEL_ALL || channel != CHANNEL_ALL;
+ if (check_channel && handler.channel != channel) continue;
+
+ bool handled = handler.callback->exec(data);
+ if (handled) return;
+ }
+}
+
+void EventManager::clear() {
+ this->subscribers.clear();
+ this->events_queue.clear();
+}
+
+void EventManager::unsubscribe(subscription_t id) {
+ for (auto & [event_type, handlers] : this->subscribers) {
+ for (auto it = handlers.begin(); it != handlers.end(); it++) {
+ // find listener with subscription id
+ if ((*it).id != id) continue;
+ it = handlers.erase(it);
+ return;
+ }
+ }
+}
diff --git a/src/crepe/manager/EventManager.h b/src/crepe/manager/EventManager.h
new file mode 100644
index 0000000..639e37f
--- /dev/null
+++ b/src/crepe/manager/EventManager.h
@@ -0,0 +1,148 @@
+#pragma once
+
+#include <memory>
+#include <typeindex>
+#include <unordered_map>
+#include <vector>
+
+#include "../api/Event.h"
+#include "../api/EventHandler.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+//! Event listener unique ID
+typedef size_t subscription_t;
+
+/**
+ * \brief Event channel
+ *
+ * Events can be sent to a specific channel, which prevents listeners on other channels from
+ * being called. The default channel is EventManager::CHANNEL_ALL, which calls all listeners.
+ */
+typedef size_t event_channel_t;
+
+/**
+ * \brief Manages event subscriptions, triggers, and queues, enabling decoupled event handling.
+ *
+ * The `EventManager` acts as a centralized event system. It allows for registering callbacks
+ * for specific event types, triggering events synchronously, queueing events for later
+ * processing, and managing subscriptions via unique identifiers.
+ */
+class EventManager : public Manager {
+public:
+ static constexpr const event_channel_t CHANNEL_ALL = -1;
+ /**
+ * \param mediator A reference to a Mediator object used for transfering managers.
+ */
+ EventManager(Mediator & mediator);
+ /**
+ * \brief Subscribe to a specific event type.
+ *
+ * Registers a callback for a given event type and optional channel. Each callback
+ * is assigned a unique subscription ID that can be used for later unsubscription.
+ *
+ * \tparam EventType The type of the event to subscribe to.
+ * \param callback The callback function to be invoked when the event is triggered.
+ * \param channel The channel number to subscribe to (default is CHANNEL_ALL, which listens to all channels).
+ * \return A unique subscription ID associated with the registered callback.
+ */
+ template <typename EventType>
+ subscription_t subscribe(const EventHandler<EventType> & callback,
+ event_channel_t channel = CHANNEL_ALL);
+
+ /**
+ * \brief Unsubscribe a previously registered callback.
+ *
+ * Removes a callback from the subscription list based on its unique subscription ID.
+ *
+ * \param event_id The unique subscription ID of the callback to remove.
+ */
+ void unsubscribe(subscription_t event_id);
+
+ /**
+ * \brief Trigger an event immediately.
+ *
+ * Synchronously invokes all registered callbacks for the given event type on the specified channel.
+ *
+ * \tparam EventType The type of the event to trigger.
+ * \param event The event instance to pass to the callbacks.
+ * \param channel The channel to trigger the event on (default is CHANNEL_ALL, which triggers on all channels).
+ */
+ template <typename EventType>
+ void trigger_event(const EventType & event = {}, event_channel_t channel = CHANNEL_ALL);
+
+ /**
+ * \brief Queue an event for later processing.
+ *
+ * Adds an event to the event queue to be processed during the next call to `dispatch_events`.
+ *
+ * \tparam EventType The type of the event to queue.
+ * \param event The event instance to queue.
+ * \param channel The channel to associate with the event (default is CHANNEL_ALL).
+ */
+ template <typename EventType>
+ void queue_event(const EventType & event = {}, event_channel_t channel = CHANNEL_ALL);
+
+ /**
+ * \brief Process all queued events.
+ *
+ * Iterates through the event queue and triggers callbacks for each queued event.
+ * Events are removed from the queue once processed.
+ */
+ void dispatch_events();
+
+ /**
+ * \brief Clear all subscriptions.
+ *
+ * Removes all registered event handlers and clears the subscription list.
+ */
+ void clear();
+
+private:
+ /**
+ * \struct QueueEntry
+ * \brief Represents an entry in the event queue.
+ */
+ struct QueueEntry {
+ std::unique_ptr<Event> event; ///< The event instance.
+ event_channel_t channel = CHANNEL_ALL; ///< The channel associated with the event.
+ std::type_index type; ///< The type of the event.
+ };
+
+ /**
+ * \brief Internal event handler
+ *
+ * This function processes a single event, and is used to process events both during
+ * EventManager::dispatch_events and inside EventManager::trigger_event
+ *
+ * \param type \c typeid of concrete Event class
+ * \param channel Event channel
+ * \param data Event data
+ */
+ void handle_event(std::type_index type, event_channel_t channel, const Event & data);
+
+ /**
+ * \struct CallbackEntry
+ * \brief Represents a registered event handler callback.
+ */
+ struct CallbackEntry {
+ std::unique_ptr<IEventHandlerWrapper> callback; ///< The callback function wrapper.
+ event_channel_t channel = CHANNEL_ALL; ///< The channel this callback listens to.
+ subscription_t id = -1; ///< Unique subscription ID.
+ };
+
+ //! The queue of events to be processed during dispatch.
+ std::vector<QueueEntry> events_queue;
+
+ //! A map of event type to registered callbacks.
+ std::unordered_map<std::type_index, std::vector<CallbackEntry>> subscribers;
+
+ //! Counter to generate unique subscription IDs.
+ subscription_t subscription_counter = 0;
+};
+
+} // namespace crepe
+
+#include "EventManager.hpp"
diff --git a/src/crepe/manager/EventManager.hpp b/src/crepe/manager/EventManager.hpp
new file mode 100644
index 0000000..a5f4556
--- /dev/null
+++ b/src/crepe/manager/EventManager.hpp
@@ -0,0 +1,36 @@
+#pragma once
+
+#include "EventManager.h"
+
+namespace crepe {
+
+template <typename EventType>
+subscription_t EventManager::subscribe(const EventHandler<EventType> & callback,
+ event_channel_t channel) {
+ subscription_counter++;
+ std::type_index event_type = typeid(EventType);
+ std::unique_ptr<EventHandlerWrapper<EventType>> handler
+ = std::make_unique<EventHandlerWrapper<EventType>>(callback);
+ std::vector<CallbackEntry> & handlers = this->subscribers[event_type];
+ handlers.emplace_back(CallbackEntry{
+ .callback = std::move(handler), .channel = channel, .id = subscription_counter});
+ return subscription_counter;
+}
+
+template <typename EventType>
+void EventManager::queue_event(const EventType & event, event_channel_t channel) {
+ static_assert(std::is_base_of<Event, EventType>::value,
+ "EventType must derive from Event");
+ this->events_queue.push_back(QueueEntry{
+ .event = std::make_unique<EventType>(event),
+ .channel = channel,
+ .type = typeid(EventType),
+ });
+}
+
+template <typename EventType>
+void EventManager::trigger_event(const EventType & event, event_channel_t channel) {
+ this->handle_event(typeid(EventType), channel, event);
+}
+
+} // namespace crepe
diff --git a/src/crepe/manager/LoopTimerManager.cpp b/src/crepe/manager/LoopTimerManager.cpp
new file mode 100644
index 0000000..a6e4788
--- /dev/null
+++ b/src/crepe/manager/LoopTimerManager.cpp
@@ -0,0 +1,91 @@
+#include <chrono>
+#include <thread>
+
+#include "../util/Log.h"
+
+#include "LoopTimerManager.h"
+
+using namespace crepe;
+using namespace std::chrono;
+using namespace std::chrono_literals;
+
+LoopTimerManager::LoopTimerManager(Mediator & mediator) : Manager(mediator) {
+ this->mediator.loop_timer = *this;
+ dbg_trace();
+}
+
+void LoopTimerManager::start() {
+ this->last_frame_time = std::chrono::steady_clock::now();
+
+ this->elapsed_time = elapsed_time_t{0};
+ this->elapsed_fixed_time = elapsed_time_t{0};
+ this->delta_time = duration_t{0};
+}
+
+void LoopTimerManager::update() {
+ time_point_t current_frame_time = std::chrono::steady_clock::now();
+ // Convert to duration in seconds for delta time
+ this->delta_time = current_frame_time - last_frame_time;
+
+ if (this->delta_time > this->maximum_delta_time) {
+ this->delta_time = this->maximum_delta_time;
+ }
+ if (this->delta_time > 0s) {
+ this->actual_fps = static_cast<unsigned>(1.0 / this->delta_time.count());
+ } else {
+ this->actual_fps = 0;
+ }
+ this->elapsed_time += duration_cast<elapsed_time_t>(this->delta_time);
+ this->last_frame_time = current_frame_time;
+}
+
+duration_t LoopTimerManager::get_delta_time() const {
+ return this->delta_time * this->time_scale;
+}
+
+elapsed_time_t LoopTimerManager::get_elapsed_time() const { return this->elapsed_time; }
+
+void LoopTimerManager::advance_fixed_elapsed_time() {
+ this->elapsed_fixed_time
+ += std::chrono::duration_cast<elapsed_time_t>(this->fixed_delta_time);
+}
+
+void LoopTimerManager::set_target_framerate(unsigned fps) {
+ this->target_fps = fps;
+ //check if fps is lower or equals 0
+ if (fps <= 0) return;
+ // target time per frame in seconds
+ this->frame_target_time = duration_t(1s) / this->target_fps;
+}
+
+unsigned LoopTimerManager::get_fps() const { return this->actual_fps; }
+
+void LoopTimerManager::set_time_scale(double value) { this->time_scale = value; }
+
+float LoopTimerManager::get_time_scale() const { return this->time_scale; }
+
+void LoopTimerManager::enforce_frame_rate() {
+ time_point_t current_frame_time = std::chrono::steady_clock::now();
+ duration_t frame_duration = current_frame_time - this->last_frame_time;
+ // Check if frame duration is less than the target frame time
+ if (frame_duration < this->frame_target_time) {
+ duration_t delay_time = this->frame_target_time - frame_duration;
+ if (delay_time > 0s) {
+ std::this_thread::sleep_for(delay_time);
+ }
+ }
+}
+
+duration_t LoopTimerManager::get_lag() const {
+ return this->elapsed_time - this->elapsed_fixed_time;
+}
+
+duration_t LoopTimerManager::get_scaled_fixed_delta_time() const {
+ return this->fixed_delta_time * this->time_scale;
+}
+
+void LoopTimerManager::set_fixed_delta_time(float seconds) {
+ this->fixed_delta_time = duration_t(seconds);
+}
+
+duration_t LoopTimerManager::get_fixed_delta_time() const { return this->fixed_delta_time; }
diff --git a/src/crepe/manager/LoopTimerManager.h b/src/crepe/manager/LoopTimerManager.h
new file mode 100644
index 0000000..76b02d3
--- /dev/null
+++ b/src/crepe/manager/LoopTimerManager.h
@@ -0,0 +1,175 @@
+#pragma once
+
+#include <chrono>
+
+#include "Manager.h"
+
+namespace crepe {
+
+typedef std::chrono::duration<float> duration_t;
+typedef std::chrono::duration<unsigned long long, std::micro> elapsed_time_t;
+
+/**
+ * \brief Manages timing and frame rate for the game loop.
+ *
+ * The LoopTimerManager class is responsible for calculating and managing timing functions
+ * such as delta time, frames per second (FPS), fixed time steps, and time scaling. It ensures
+ * consistent frame updates and supports game loop operations, such as handling fixed updates
+ * for physics and other time-sensitive operations.
+ */
+class LoopTimerManager : public Manager {
+public:
+ /**
+ * \param mediator A reference to a Mediator object used for transfering managers.
+ */
+ LoopTimerManager(Mediator & mediator);
+ /**
+ * \brief Get the current delta time for the current frame.
+ *
+ * This value represents the estimated frame duration of the current frame.
+ * This value can be used in the frame_update to convert pixel based values to time based values.
+ *
+ * \return Delta time in seconds since the last frame.
+ */
+ duration_t get_delta_time() const;
+
+ /**
+ * \brief Get the current elapsed time (total time passed )
+ *
+ * \note The current game time may vary from real-world elapsed time. It is the cumulative
+ * sum of each frame's delta time.
+ *
+ * \return Elapsed game time in seconds.
+ */
+ elapsed_time_t get_elapsed_time() const;
+
+ /**
+ * \brief Set the target frames per second (FPS).
+ *
+ * \param fps The desired frames rendered per second.
+ */
+ void set_target_framerate(unsigned fps);
+
+ /**
+ * \brief Get the current frames per second (FPS).
+ *
+ * \return Current FPS.
+ */
+ unsigned int get_fps() const;
+
+ /**
+ * \brief Get the current time scale.
+ *
+ * \return The current time scale, where (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up).
+ * up the game.
+ */
+ float get_time_scale() const;
+
+ /**
+ * \brief Set the time scale.
+ *
+ * time_scale is a value that changes the delta time that can be retrieved using get_delta_time function.
+ *
+ * \param time_scale The desired time scale (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up).
+ */
+ void set_time_scale(double time_scale);
+
+ /**
+ * \brief Get the fixed delta time in seconds without scaling by the time scale.
+ *
+ * This value is used in the LoopManager to determine how many times
+ * the fixed_update should be called within a given interval.
+ *
+ * \return The unscaled fixed delta time in seconds.
+ */
+ duration_t get_fixed_delta_time() const;
+
+ /**
+ * \brief Set the fixed_delta_time in seconds.
+ *
+ * \param seconds fixed_delta_time in seconds.
+ *
+ * The fixed_delta_time value is used to determine how many times per second the fixed_update and process_input functions are called.
+ *
+ */
+ void set_fixed_delta_time(float seconds);
+
+ /**
+ * \brief Retrieves the scaled fixed delta time in seconds.
+ *
+ * The scaled fixed delta time is the timing value used within the `fixed_update` function.
+ * It is adjusted by the time_scale to account for any changes in the simulation's
+ * speed.
+ *
+ * \return The fixed delta time, scaled by the current time scale, in seconds.
+ */
+ duration_t get_scaled_fixed_delta_time() const;
+
+private:
+ //! Friend relation to use start,enforce_frame_rate,get_lag,update,advance_fixed_update.
+ friend class LoopManager;
+ /**
+ * \brief Start the loop timer.
+ *
+ * Initializes the timer to begin tracking frame times.
+ */
+ void start();
+ /**
+ * \brief Enforce the frame rate limit.
+ *
+ * Ensures that the game loop does not exceed the target FPS by delaying frame updates as
+ * necessary.
+ */
+ void enforce_frame_rate();
+ /**
+ * \brief Get the accumulated lag in the game loop.
+ *
+ * Lag represents the difference between the target frame time and the actual frame time,
+ * useful for managing fixed update intervals.
+ *
+ * \return Accumulated lag in seconds.
+ */
+ duration_t get_lag() const;
+
+ /**
+ * \brief Update the timer to the current frame.
+ *
+ * Calculates and updates the delta time for the current frame and adds it to the cumulative
+ * game time.
+ */
+ void update();
+
+ /**
+ * \brief Progress the elapsed fixed time by the fixed delta time interval.
+ *
+ * This method advances the game's fixed update loop by adding the fixed_delta_time
+ * to elapsed_fixed_time, ensuring the fixed update catches up with the elapsed time.
+ */
+ void advance_fixed_elapsed_time();
+
+private:
+ //! Target frames per second.
+ unsigned int target_fps = 60;
+ //! Actual frames per second.
+ unsigned int actual_fps = 0;
+ //! Time scale for speeding up or slowing down the game (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up).
+ float time_scale = 1;
+ //! Maximum delta time in seconds to avoid large jumps.
+ duration_t maximum_delta_time{0.25};
+ //! Delta time for the current frame in seconds.
+ duration_t delta_time{0.0};
+ //! Target time per frame in seconds
+ duration_t frame_target_time{1.0 / target_fps};
+ //! Fixed delta time for fixed updates in seconds.
+ duration_t fixed_delta_time{1.0 / 50.0};
+ //! Total elapsed game time in microseconds.
+ elapsed_time_t elapsed_time{0};
+ //! Total elapsed time for fixed updates in microseconds.
+ elapsed_time_t elapsed_fixed_time{0};
+
+ typedef std::chrono::steady_clock::time_point time_point_t;
+ //! Time of the last frame.
+ time_point_t last_frame_time;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/Manager.cpp b/src/crepe/manager/Manager.cpp
new file mode 100644
index 0000000..1182785
--- /dev/null
+++ b/src/crepe/manager/Manager.cpp
@@ -0,0 +1,5 @@
+#include "Manager.h"
+
+using namespace crepe;
+
+Manager::Manager(Mediator & mediator) : mediator(mediator) {}
diff --git a/src/crepe/manager/Manager.h b/src/crepe/manager/Manager.h
new file mode 100644
index 0000000..84d80fe
--- /dev/null
+++ b/src/crepe/manager/Manager.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include "Mediator.h"
+
+namespace crepe {
+
+/**
+ * \brief Base manager class
+ *
+ * Managers are used for various tasks that fall outside the ECS system category. All managers
+ * are required to register themselves to the mediator passed to the constructor, and this
+ * mutable reference is saved for convenience, even though not all managers use the mediator
+ * directly.
+ */
+class Manager {
+public:
+ Manager(Mediator & mediator);
+ virtual ~Manager() = default;
+
+protected:
+ Mediator & mediator;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/Mediator.h b/src/crepe/manager/Mediator.h
new file mode 100644
index 0000000..a336410
--- /dev/null
+++ b/src/crepe/manager/Mediator.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include "../util/OptionalRef.h"
+
+namespace crepe {
+
+class ComponentManager;
+class SceneManager;
+class EventManager;
+class LoopTimerManager;
+class SaveManager;
+class ResourceManager;
+class SDLContext;
+
+/**
+ * Struct to pass references to classes that would otherwise need to be singletons down to
+ * other classes within the engine hierarchy. Made to prevent constant changes to subclasses to
+ * pass specific references through dependency injection. All references on this struct
+ * *should* be explicitly checked for availability as this struct does not guarantee anything.
+ *
+ * \note Dereferencing members of this struct should be deferred. If you are a user of this
+ * class, keep a reference to this mediator instead of just picking references from it when you
+ * receive an instance.
+ *
+ * \warning This class should never be directly accessible from the API
+ */
+struct Mediator {
+ OptionalRef<SDLContext> sdl_context;
+ OptionalRef<ComponentManager> component_manager;
+ OptionalRef<SceneManager> scene_manager;
+ OptionalRef<EventManager> event_manager;
+ OptionalRef<LoopTimerManager> loop_timer;
+ OptionalRef<SaveManager> save_manager;
+ OptionalRef<ResourceManager> resource_manager;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/ResourceManager.cpp b/src/crepe/manager/ResourceManager.cpp
new file mode 100644
index 0000000..a141a46
--- /dev/null
+++ b/src/crepe/manager/ResourceManager.cpp
@@ -0,0 +1,30 @@
+#include "util/Log.h"
+
+#include "ResourceManager.h"
+
+using namespace crepe;
+using namespace std;
+
+ResourceManager::ResourceManager(Mediator & mediator) : Manager(mediator) {
+ dbg_trace();
+ mediator.resource_manager = *this;
+}
+ResourceManager::~ResourceManager() { dbg_trace(); }
+
+void ResourceManager::clear() {
+ std::erase_if(this->resources, [](const pair<const Asset, CacheEntry> & pair) {
+ const CacheEntry & entry = pair.second;
+ return entry.persistent == false;
+ });
+}
+
+void ResourceManager::clear_all() { this->resources.clear(); }
+
+void ResourceManager::set_persistent(const Asset & asset, bool persistent) {
+ this->get_entry(asset).persistent = persistent;
+}
+
+ResourceManager::CacheEntry & ResourceManager::get_entry(const Asset & asset) {
+ if (!this->resources.contains(asset)) this->resources[asset] = {};
+ return this->resources.at(asset);
+}
diff --git a/src/crepe/manager/ResourceManager.h b/src/crepe/manager/ResourceManager.h
new file mode 100644
index 0000000..84b275d
--- /dev/null
+++ b/src/crepe/manager/ResourceManager.h
@@ -0,0 +1,78 @@
+#pragma once
+
+#include <memory>
+#include <unordered_map>
+
+#include "../Resource.h"
+#include "../api/Asset.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+/**
+ * \brief Owner of concrete Resource instances
+ *
+ * ResourceManager caches concrete Resource instances per Asset. Concrete resources are
+ * destroyed at the end of scenes by default, unless the game programmer marks them as
+ * persistent.
+ */
+class ResourceManager : public Manager {
+public:
+ ResourceManager(Mediator & mediator);
+ virtual ~ResourceManager(); // dbg_trace
+
+private:
+ //! Cache entry
+ struct CacheEntry {
+ //! Concrete resource instance
+ std::unique_ptr<Resource> resource = nullptr;
+ //! Prevent ResourceManager::clear from removing this entry
+ bool persistent = false;
+ };
+ //! Internal cache
+ std::unordered_map<const Asset, CacheEntry> resources;
+ /**
+ * \brief Ensure a cache entry exists for this asset and return a mutable reference to it
+ *
+ * \param asset Asset the concrete resource is instantiated from
+ *
+ * \returns Mutable reference to cache entry
+ */
+ CacheEntry & get_entry(const Asset & asset);
+
+public:
+ /**
+ * \brief Mark a resource as persistent (i.e. used across multiple scenes)
+ *
+ * \param asset Asset the concrete resource is instantiated from
+ * \param persistent Whether this resource is persistent (true=keep, false=destroy)
+ */
+ void set_persistent(const Asset & asset, bool persistent);
+
+ /**
+ * \brief Retrieve reference to concrete Resource by Asset
+ *
+ * \param asset Asset the concrete resource is instantiated from
+ * \tparam Resource Concrete derivative of Resource
+ *
+ * This class instantiates the concrete resource if it is not yet stored in the internal
+ * cache, or returns a reference to the cached resource if it already exists.
+ *
+ * \returns Reference to concrete resource
+ *
+ * \throws std::runtime_error if the \c Resource parameter does not match with the actual
+ * type of the resource stored in the cache for this Asset
+ */
+ template <typename Resource>
+ Resource & get(const Asset & asset);
+
+ //! Clear non-persistent resources from cache
+ void clear();
+ //! Clear all resources from cache regardless of persistence
+ void clear_all();
+};
+
+} // namespace crepe
+
+#include "ResourceManager.hpp"
diff --git a/src/crepe/manager/ResourceManager.hpp b/src/crepe/manager/ResourceManager.hpp
new file mode 100644
index 0000000..cf5c949
--- /dev/null
+++ b/src/crepe/manager/ResourceManager.hpp
@@ -0,0 +1,27 @@
+#pragma once
+
+#include <format>
+
+#include "ResourceManager.h"
+
+namespace crepe {
+
+template <typename T>
+T & ResourceManager::get(const Asset & asset) {
+ using namespace std;
+ static_assert(is_base_of<Resource, T>::value,
+ "cache must recieve a derivative class of Resource");
+
+ CacheEntry & entry = this->get_entry(asset);
+ if (entry.resource == nullptr) entry.resource = make_unique<T>(asset, this->mediator);
+
+ T * concrete_resource = dynamic_cast<T *>(entry.resource.get());
+ if (concrete_resource == nullptr)
+ throw runtime_error(format("ResourceManager: mismatch between requested type and "
+ "actual type of resource ({})",
+ asset.get_path()));
+
+ return *concrete_resource;
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/SaveManager.cpp b/src/crepe/manager/SaveManager.cpp
index 2974b91..f313ed2 100644
--- a/src/crepe/api/SaveManager.cpp
+++ b/src/crepe/manager/SaveManager.cpp
@@ -1,13 +1,25 @@
+#include "../ValueBroker.h"
+#include "../api/Config.h"
#include "../facade/DB.h"
-#include "../util/Log.h"
-#include "Config.h"
#include "SaveManager.h"
-#include "ValueBroker.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
+ = {new DB(cfg.savemgr.location), [](void * db) { delete static_cast<DB *>(db); }};
+ }
+ return *static_cast<DB *>(this->db.get());
+}
+
template <>
string SaveManager::serialize(const string & value) const noexcept {
return value;
@@ -90,22 +102,6 @@ int32_t SaveManager::deserialize(const string & value) const noexcept {
return deserialize<int64_t>(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);
@@ -133,44 +129,41 @@ template void SaveManager::set(const string &, const float &);
template void SaveManager::set(const string &, const double &);
template <typename T>
+T SaveManager::get(const string & key) {
+ return this->deserialize<T>(this->get_db().get(key));
+}
+template uint8_t SaveManager::get(const string &);
+template int8_t SaveManager::get(const string &);
+template uint16_t SaveManager::get(const string &);
+template int16_t SaveManager::get(const string &);
+template uint32_t SaveManager::get(const string &);
+template int32_t SaveManager::get(const string &);
+template uint64_t SaveManager::get(const string &);
+template int64_t SaveManager::get(const string &);
+template float SaveManager::get(const string &);
+template double SaveManager::get(const string &);
+template string SaveManager::get(const string &);
+
+template <typename T>
ValueBroker<T> SaveManager::get(const string & key, const T & default_value) {
if (!this->has(key)) this->set<T>(key, default_value);
- return this->get<T>(key);
+ T value;
+ return {
+ [this, key](const T & target) { this->set<T>(key, target); },
+ [this, key, value]() mutable -> const T & {
+ value = this->get<T>(key);
+ return value;
+ },
+ };
}
template ValueBroker<uint8_t> SaveManager::get(const string &, const uint8_t &);
template ValueBroker<int8_t> SaveManager::get(const string &, const int8_t &);
-template ValueBroker<uint16_t> SaveManager::get(const string &,
- const uint16_t &);
+template ValueBroker<uint16_t> SaveManager::get(const string &, const uint16_t &);
template ValueBroker<int16_t> SaveManager::get(const string &, const int16_t &);
-template ValueBroker<uint32_t> SaveManager::get(const string &,
- const uint32_t &);
+template ValueBroker<uint32_t> SaveManager::get(const string &, const uint32_t &);
template ValueBroker<int32_t> SaveManager::get(const string &, const int32_t &);
-template ValueBroker<uint64_t> SaveManager::get(const string &,
- const uint64_t &);
+template ValueBroker<uint64_t> SaveManager::get(const string &, const uint64_t &);
template ValueBroker<int64_t> SaveManager::get(const string &, const int64_t &);
template ValueBroker<float> SaveManager::get(const string &, const float &);
template ValueBroker<double> SaveManager::get(const string &, const double &);
template ValueBroker<string> SaveManager::get(const string &, const string &);
-
-template <typename T>
-ValueBroker<T> SaveManager::get(const string & key) {
- T value;
- return {
- [this, key](const T & target) { this->set<T>(key, target); },
- [this, key, value]() mutable -> const T & {
- value = this->deserialize<T>(this->get_db().get(key));
- return value;
- },
- };
-}
-template ValueBroker<uint8_t> SaveManager::get(const string &);
-template ValueBroker<int8_t> SaveManager::get(const string &);
-template ValueBroker<uint16_t> SaveManager::get(const string &);
-template ValueBroker<int16_t> SaveManager::get(const string &);
-template ValueBroker<uint32_t> SaveManager::get(const string &);
-template ValueBroker<int32_t> SaveManager::get(const string &);
-template ValueBroker<uint64_t> SaveManager::get(const string &);
-template ValueBroker<int64_t> SaveManager::get(const string &);
-template ValueBroker<float> SaveManager::get(const string &);
-template ValueBroker<double> SaveManager::get(const string &);
-template ValueBroker<string> SaveManager::get(const string &);
diff --git a/src/crepe/api/SaveManager.h b/src/crepe/manager/SaveManager.h
index 4be85fb..1e34bc0 100644
--- a/src/crepe/api/SaveManager.h
+++ b/src/crepe/manager/SaveManager.h
@@ -1,9 +1,12 @@
#pragma once
+#include <functional>
#include <memory>
#include "../ValueBroker.h"
+#include "Manager.h"
+
namespace crepe {
class DB;
@@ -18,13 +21,14 @@ 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
*
* \param key The value key
- * \param default_value Value to initialize \c key with if it does not already exist in the database
+ * \param default_value Value to initialize \c key with if it does not already exist in the
+ * database
*
* \return Read/write reference to the value
*/
@@ -32,17 +36,17 @@ public:
ValueBroker<T> get(const std::string & key, const T & default_value);
/**
- * \brief Get a read/write reference to a value
+ * \brief Get a value directly
*
* \param key The value key
*
- * \return Read/write reference to the value
+ * \return The value
*
- * \note Attempting to read this value before it is initialized (i.e. set)
- * will result in an exception
+ * \note Attempting to read this value before it is initialized (i.e. set) will result in an
+ * exception
*/
template <typename T>
- ValueBroker<T> get(const std::string & key);
+ T get(const std::string & key);
/**
* \brief Set a value directly
@@ -62,8 +66,8 @@ public:
*/
bool has(const std::string & key);
-private:
- SaveManager();
+public:
+ SaveManager(Mediator & mediator);
virtual ~SaveManager() = default;
private:
@@ -88,26 +92,13 @@ private:
template <typename T>
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<void, std::function<void(void *)>> db = nullptr;
};
} // namespace crepe
diff --git a/src/crepe/api/SceneManager.cpp b/src/crepe/manager/SceneManager.cpp
index 4a38787..d4ca90b 100644
--- a/src/crepe/api/SceneManager.cpp
+++ b/src/crepe/manager/SceneManager.cpp
@@ -1,14 +1,15 @@
#include <algorithm>
#include <memory>
-#include "../ComponentManager.h"
-
+#include "ComponentManager.h"
#include "SceneManager.h"
using namespace crepe;
using namespace std;
-SceneManager::SceneManager(ComponentManager & mgr) : component_manager(mgr) {}
+SceneManager::SceneManager(Mediator & mediator) : Manager(mediator) {
+ mediator.scene_manager = *this;
+}
void SceneManager::set_next_scene(const string & name) { next_scene = name; }
@@ -16,20 +17,22 @@ void SceneManager::load_next_scene() {
// next scene not set
if (this->next_scene.empty()) return;
- auto it
- = find_if(this->scenes.begin(), this->scenes.end(),
- [&next_scene = this->next_scene](unique_ptr<Scene> & scene) {
- return scene->name == next_scene;
- });
+ auto it = find_if(this->scenes.begin(), this->scenes.end(),
+ [&next_scene = this->next_scene](unique_ptr<Scene> & scene) {
+ return scene.get()->get_name() == next_scene;
+ });
// next scene not found
if (it == this->scenes.end()) return;
unique_ptr<Scene> & scene = *it;
// Delete all components of the current scene
- ComponentManager & mgr = this->component_manager;
+ ComponentManager & mgr = this->mediator.component_manager;
mgr.delete_all_components();
// Load the new scene
scene->load_scene();
+
+ //clear the next scene
+ next_scene.clear();
}
diff --git a/src/crepe/api/SceneManager.h b/src/crepe/manager/SceneManager.h
index 553194f..e0955c2 100644
--- a/src/crepe/api/SceneManager.h
+++ b/src/crepe/manager/SceneManager.h
@@ -1,29 +1,34 @@
#pragma once
#include <memory>
-#include <queue>
#include <vector>
-#include "Scene.h"
+#include "../api/Scene.h"
+
+#include "Manager.h"
namespace crepe {
class ComponentManager;
-class SceneManager {
+/**
+ * \brief Manages scenes
+ *
+ * This class manages scenes. It can add new scenes and load them. It also manages the current scene
+ * and the next scene.
+ */
+class SceneManager : public Manager {
public:
- SceneManager(ComponentManager & mgr);
- virtual ~SceneManager() = default;
+ SceneManager(Mediator & mediator);
public:
/**
* \brief Add a new concrete scene to the scene manager
*
* \tparam T Type of concrete scene
- * \param name Name of new scene
*/
- template <typename T>
- void add_scene(const std::string & name);
+ template <typename T, typename... Args>
+ void add_scene(Args &&... args);
/**
* \brief Set the next scene
*
@@ -36,11 +41,10 @@ public:
void load_next_scene();
private:
+ //! Vector of concrete scenes (added by add_scene())
std::vector<std::unique_ptr<Scene>> scenes;
+ //! Next scene to load
std::string next_scene;
-
-protected:
- ComponentManager & component_manager;
};
} // namespace crepe
diff --git a/src/crepe/manager/SceneManager.hpp b/src/crepe/manager/SceneManager.hpp
new file mode 100644
index 0000000..dff4e51
--- /dev/null
+++ b/src/crepe/manager/SceneManager.hpp
@@ -0,0 +1,25 @@
+#pragma once
+
+#include "SceneManager.h"
+
+namespace crepe {
+
+template <typename T, typename... Args>
+void SceneManager::add_scene(Args &&... args) {
+ using namespace std;
+ static_assert(is_base_of<Scene, T>::value, "T must be derived from Scene");
+
+ Scene * scene = new T(std::forward<Args>(args)...);
+ unique_ptr<Scene> unique_scene(scene);
+
+ unique_scene->mediator = this->mediator;
+
+ this->scenes.emplace_back(std::move(unique_scene));
+
+ // The first scene added, is the one that will be loaded at the beginning
+ if (next_scene.empty()) {
+ next_scene = scene->get_name();
+ }
+}
+
+} // namespace crepe
diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp
new file mode 100644
index 0000000..680dbb8
--- /dev/null
+++ b/src/crepe/system/AISystem.cpp
@@ -0,0 +1,186 @@
+#include <algorithm>
+#include <cmath>
+
+#include "manager/ComponentManager.h"
+#include "manager/LoopTimerManager.h"
+#include "manager/Mediator.h"
+
+#include "AISystem.h"
+
+using namespace crepe;
+using namespace std::chrono;
+
+void AISystem::update() {
+ const Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+ LoopTimerManager & loop_timer = mediator.loop_timer;
+ RefVector<AI> ai_components = mgr.get_components_by_type<AI>();
+
+ float dt = loop_timer.get_scaled_fixed_delta_time().count();
+
+ // Loop through all AI components
+ for (AI & ai : ai_components) {
+ if (!ai.active) {
+ continue;
+ }
+
+ RefVector<Rigidbody> rigidbodies
+ = mgr.get_components_by_id<Rigidbody>(ai.game_object_id);
+ if (rigidbodies.empty()) {
+ throw std::runtime_error(
+ "AI component must be attached to a GameObject with a Rigidbody component");
+ }
+ Rigidbody & rigidbody = rigidbodies.front().get();
+ if (!rigidbody.active) {
+ continue;
+ }
+ if (rigidbody.data.mass <= 0) {
+ throw std::runtime_error("Mass must be greater than 0");
+ }
+
+ // Calculate the force to apply to the entity
+ vec2 force = this->calculate(ai, rigidbody);
+ // Calculate the acceleration (using the above calculated force)
+ vec2 acceleration = force / rigidbody.data.mass;
+ // Finally, update Rigidbody's velocity
+ rigidbody.data.linear_velocity += acceleration * dt;
+ }
+}
+
+vec2 AISystem::calculate(AI & ai, const Rigidbody & rigidbody) {
+ const Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+ RefVector<Transform> transforms = mgr.get_components_by_id<Transform>(ai.game_object_id);
+ Transform & transform = transforms.front().get();
+
+ vec2 force;
+
+ // Run all the behaviors that are on, and stop if the force gets too high
+ if (ai.on(AI::BehaviorTypeMask::FLEE)) {
+ vec2 force_to_add = this->flee(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+ if (ai.on(AI::BehaviorTypeMask::ARRIVE)) {
+ vec2 force_to_add = this->arrive(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+ if (ai.on(AI::BehaviorTypeMask::SEEK)) {
+ vec2 force_to_add = this->seek(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+ if (ai.on(AI::BehaviorTypeMask::PATH_FOLLOW)) {
+ vec2 force_to_add = this->path_follow(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+
+ return force;
+}
+
+bool AISystem::accumulate_force(const AI & ai, vec2 & running_total, vec2 & force_to_add) {
+ float magnitude = running_total.length();
+ float magnitude_remaining = ai.max_force - magnitude;
+
+ if (magnitude_remaining <= 0.0f) {
+ // If the force is already at/above the max force, return false
+ return false;
+ }
+
+ float magnitude_to_add = force_to_add.length();
+ if (magnitude_to_add < magnitude_remaining) {
+ // If the force to add is less than the remaining force, add it
+ running_total += force_to_add;
+ } else {
+ // If the force to add is greater than the remaining force, add a fraction of it
+ force_to_add.normalize();
+ running_total += force_to_add * magnitude_remaining;
+ }
+
+ return true;
+}
+
+vec2 AISystem::seek(const AI & ai, const Rigidbody & rigidbody,
+ const Transform & transform) const {
+ // Calculate the desired velocity
+ vec2 desired_velocity = ai.seek_target - transform.position;
+ desired_velocity.normalize();
+ desired_velocity *= rigidbody.data.max_linear_velocity;
+
+ return desired_velocity - rigidbody.data.linear_velocity;
+}
+
+vec2 AISystem::flee(const AI & ai, const Rigidbody & rigidbody,
+ const Transform & transform) const {
+ // Calculate the desired velocity if the entity is within the panic distance
+ 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 Rigidbody & rigidbody,
+ const Transform & transform) const {
+ // Calculate the desired velocity (taking into account the deceleration rate)
+ vec2 to_target = ai.arrive_target - transform.position;
+ float distance = to_target.length();
+ if (distance > 0.0f) {
+ if (ai.arrive_deceleration <= 0.0f) {
+ throw std::runtime_error("Deceleration rate must be greater than 0");
+ }
+
+ float speed = distance / ai.arrive_deceleration;
+ speed = std::min(speed, rigidbody.data.max_linear_velocity);
+ vec2 desired_velocity = to_target * (speed / distance);
+
+ return desired_velocity - rigidbody.data.linear_velocity;
+ }
+
+ return vec2{0, 0};
+}
+
+vec2 AISystem::path_follow(AI & ai, const Rigidbody & rigidbody, const Transform & transform) {
+ if (ai.path.empty()) {
+ return vec2{0, 0};
+ }
+
+ // Get the target node
+ vec2 target = ai.path.at(ai.path_index);
+ // Calculate the force to apply to the entity
+ vec2 to_target = target - transform.position;
+ if (to_target.length_squared() > ai.path_node_distance * ai.path_node_distance) {
+ // If the entity is not close enough to the target node, seek it
+ ai.seek_target = target;
+ ai.arrive_target = target;
+ } else {
+ // If the entity is close enough to the target node, move to the next node
+ ai.path_index++;
+ if (ai.path_index >= ai.path.size()) {
+ if (ai.path_loop) {
+ // If the path is looping, reset the path index
+ ai.path_index = 0;
+ } else {
+ // If the path is not looping, arrive at the last node
+ ai.path_index = ai.path.size() - 1;
+ return this->arrive(ai, rigidbody, transform);
+ }
+ }
+ }
+
+ // Seek the target node
+ return this->seek(ai, rigidbody, transform);
+}
diff --git a/src/crepe/system/AISystem.h b/src/crepe/system/AISystem.h
new file mode 100644
index 0000000..d5f8a8e
--- /dev/null
+++ b/src/crepe/system/AISystem.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include "api/AI.h"
+#include "api/Rigidbody.h"
+
+#include "System.h"
+#include "api/Transform.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief The AISystem is used to control the movement of entities using AI.
+ *
+ * The AISystem is used to control the movement of entities using AI. The AISystem can be used to
+ * implement different behaviors such as seeking, fleeing, arriving, and path following.
+ */
+class AISystem : public System {
+public:
+ using System::System;
+
+ //! Update the AI system
+ void update() override;
+
+private:
+ /**
+ * \brief Calculate the total force to apply to the entity
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ */
+ vec2 calculate(AI & ai, const Rigidbody & rigidbody);
+ /**
+ * \brief Accumulate the force to apply to the entity
+ *
+ * \param ai The AI component
+ * \param running_total The running total of the force
+ * \param force_to_add The force to add
+ * \return true if the force was added, false otherwise
+ */
+ bool accumulate_force(const AI & ai, vec2 & running_total, vec2 & force_to_add);
+
+ /**
+ * \brief Calculate the seek force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The seek force
+ */
+ vec2 seek(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) const;
+ /**
+ * \brief Calculate the flee force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The flee force
+ */
+ vec2 flee(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) const;
+ /**
+ * \brief Calculate the arrive force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The arrive force
+ */
+ vec2 arrive(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) const;
+ /**
+ * \brief Calculate the path follow force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The path follow force
+ */
+ vec2 path_follow(AI & ai, const Rigidbody & rigidbody, const Transform & transform);
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp
index 9d18873..107b25d 100644
--- a/src/crepe/system/AnimatorSystem.cpp
+++ b/src/crepe/system/AnimatorSystem.cpp
@@ -1,27 +1,42 @@
-#include <cstdint>
-#include <functional>
-#include <vector>
-#include "api/Animator.h"
-#include "facade/SDLContext.h"
+
+#include "../api/Animator.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/LoopTimerManager.h"
+#include <chrono>
#include "AnimatorSystem.h"
-#include "ComponentManager.h"
using namespace crepe;
+using namespace std::chrono;
void AnimatorSystem::update() {
- ComponentManager & mgr = this->component_manager;
+ ComponentManager & mgr = this->mediator.component_manager;
+ LoopTimerManager & timer = this->mediator.loop_timer;
+ RefVector<Animator> animations = mgr.get_components_by_type<Animator>();
- std::vector<std::reference_wrapper<Animator>> animations
- = mgr.get_components_by_type<Animator>();
+ float elapsed_time = duration_cast<duration<float>>(timer.get_elapsed_time()).count();
- uint64_t tick = SDLContext::get_instance().get_ticks();
for (Animator & a : animations) {
- if (a.active) {
- a.curr_row = (tick / 100) % a.row;
- a.animator_rect.x = (a.curr_row * a.animator_rect.w) + a.curr_col;
- a.spritesheet.sprite_rect = a.animator_rect;
+ if (!a.active) continue;
+ if (a.data.fps == 0) continue;
+
+ Animator::Data & ctx = a.data;
+ float frame_duration = 1.0f / ctx.fps;
+
+ int last_frame = ctx.row;
+
+ int cycle_end = (ctx.cycle_end == -1) ? a.grid_size.x : ctx.cycle_end;
+ int total_frames = cycle_end - ctx.cycle_start;
+
+ int curr_frame = static_cast<int>(elapsed_time / frame_duration) % total_frames;
+
+ ctx.row = ctx.cycle_start + curr_frame;
+ a.spritesheet.mask.x = ctx.row * a.spritesheet.mask.w;
+ a.spritesheet.mask.y = (ctx.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/AnimatorSystem.h b/src/crepe/system/AnimatorSystem.h
index aa97084..7d3f565 100644
--- a/src/crepe/system/AnimatorSystem.h
+++ b/src/crepe/system/AnimatorSystem.h
@@ -2,9 +2,6 @@
#include "System.h"
-//TODO:
-// control if flip works with animation system
-
namespace crepe {
/**
@@ -21,11 +18,11 @@ public:
/**
* \brief Updates the Animator components.
*
- * This method is called periodically (likely every frame) to update the state of all
- * Animator components, moving the animations forward and managing their behavior (e.g., looping).
+ * This method is called to update the state of all
+ * Animator components, moving the animations forward and managing their behavior (e.g.,
+ * looping).
*/
void update() override;
- // FIXME: never say "likely" in the documentation lmao
};
} // namespace crepe
diff --git a/src/crepe/system/AudioSystem.cpp b/src/crepe/system/AudioSystem.cpp
index 67967ef..b1aa0f8 100644
--- a/src/crepe/system/AudioSystem.cpp
+++ b/src/crepe/system/AudioSystem.cpp
@@ -1,21 +1,62 @@
#include "AudioSystem.h"
-#include "ComponentManager.h"
-#include "../api/AudioSource.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/ResourceManager.h"
+#include "../types.h"
using namespace crepe;
using namespace std;
void AudioSystem::update() {
- ComponentManager & mgr = this->component_manager;
- vector<reference_wrapper<AudioSource>> components = mgr.get_components_by_type<AudioSource>();
+ ComponentManager & component_manager = this->mediator.component_manager;
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ RefVector<AudioSource> components
+ = component_manager.get_components_by_type<AudioSource>();
- for (auto component_ref : components) {
- AudioSource & component = component_ref.get();
- if (!component.active) continue;
+ for (AudioSource & component : components) {
+ Sound & resource = resource_manager.get<Sound>(component.source);
- // TODO: fetch Sound instance from resourcemanager
- // TODO: lots of state diffing
+ this->diff_update(component, resource);
+
+ this->update_last(component);
}
}
+void AudioSystem::diff_update(AudioSource & component, Sound & resource) {
+ SoundContext & context = this->get_context();
+
+ if (component.active != component.last_active) {
+ if (!component.active) {
+ context.stop(component.voice);
+ return;
+ }
+ if (component.play_on_awake) component.oneshot_play = true;
+ }
+ if (!component.active) return;
+
+ if (component.oneshot_play) {
+ component.voice = context.play(resource);
+ component.oneshot_play = false;
+ }
+ if (component.oneshot_stop) {
+ context.stop(component.voice);
+ component.oneshot_stop = false;
+ }
+ if (component.volume != component.last_volume) {
+ context.set_volume(component.voice, component.volume);
+ }
+ if (component.loop != component.last_loop) {
+ context.set_loop(component.voice, component.loop);
+ }
+}
+
+void AudioSystem::update_last(AudioSource & component) {
+ component.last_active = component.active;
+ component.last_loop = component.loop;
+ component.last_volume = component.volume;
+}
+
+SoundContext & AudioSystem::get_context() {
+ if (this->context == nullptr) this->context = make_unique<SoundContext>();
+ return *this->context.get();
+}
diff --git a/src/crepe/system/AudioSystem.h b/src/crepe/system/AudioSystem.h
index e037f51..2ddc443 100644
--- a/src/crepe/system/AudioSystem.h
+++ b/src/crepe/system/AudioSystem.h
@@ -1,5 +1,7 @@
#pragma once
+#include "../api/AudioSource.h"
+#include "../facade/Sound.h"
#include "../facade/SoundContext.h"
#include "System.h"
@@ -12,8 +14,38 @@ public:
void update() override;
private:
- SoundContext context {};
+ /**
+ * \brief Update `last_*` members of \c component
+ *
+ * Copies all component properties stored for comparison between AudioSystem::update() calls
+ *
+ * \param component AudioSource component to update
+ */
+ void update_last(AudioSource & component);
+
+ /**
+ * \brief Compare update component
+ *
+ * Compares properties of \c component and \c data, and calls SoundContext functions where
+ * applicable.
+ *
+ * \param component AudioSource component to update
+ * \param resource Sound instance for AudioSource's Asset
+ */
+ void diff_update(AudioSource & component, Sound & resource);
+
+protected:
+ /**
+ * \brief Get SoundContext
+ *
+ * SoundContext is retrieved through this function instead of being a direct member of
+ * AudioSystem to aid with testability.
+ */
+ virtual SoundContext & get_context();
+
+private:
+ //! SoundContext
+ std::unique_ptr<SoundContext> context = nullptr;
};
} // namespace crepe
-
diff --git a/src/crepe/system/CMakeLists.txt b/src/crepe/system/CMakeLists.txt
index f507b90..0e2db76 100644
--- a/src/crepe/system/CMakeLists.txt
+++ b/src/crepe/system/CMakeLists.txt
@@ -7,6 +7,8 @@ target_sources(crepe PUBLIC
RenderSystem.cpp
AudioSystem.cpp
AnimatorSystem.cpp
+ InputSystem.cpp
+ AISystem.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
@@ -17,4 +19,6 @@ target_sources(crepe PUBLIC FILE_SET HEADERS FILES
RenderSystem.h
AudioSystem.h
AnimatorSystem.h
+ InputSystem.h
+ AISystem.h
)
diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp
index c74ca1d..af8adce 100644
--- a/src/crepe/system/CollisionSystem.cpp
+++ b/src/crepe/system/CollisionSystem.cpp
@@ -1,5 +1,575 @@
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <functional>
+#include <optional>
+#include <utility>
+#include <variant>
+
+#include "../manager/ComponentManager.h"
+#include "../manager/EventManager.h"
+#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 "Collider.h"
#include "CollisionSystem.h"
+#include "types.h"
+#include "util/OptionalRef.h"
using namespace crepe;
-void CollisionSystem::update() {}
+void CollisionSystem::update() {
+ std::vector<CollisionInternal> all_colliders;
+ game_object_id_t id = 0;
+ ComponentManager & mgr = this->mediator.component_manager;
+ RefVector<Rigidbody> rigidbodies = mgr.get_components_by_type<Rigidbody>();
+ // 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<Transform>(id).front().get();
+ // Check if the boxcollider is active and has the same id as the rigidbody.
+ RefVector<BoxCollider> boxcolliders = mgr.get_components_by_type<BoxCollider>();
+ for (BoxCollider & boxcollider : boxcolliders) {
+ if (boxcollider.game_object_id != id) continue;
+ if (!boxcollider.active) continue;
+ all_colliders.push_back({.id = id,
+ .collider = collider_variant{boxcollider},
+ .transform = transform,
+ .rigidbody = rigidbody});
+ }
+ // Check if the circlecollider is active and has the same id as the rigidbody.
+ RefVector<CircleCollider> circlecolliders
+ = mgr.get_components_by_type<CircleCollider>();
+ for (CircleCollider & circlecollider : circlecolliders) {
+ if (circlecollider.game_object_id != id) continue;
+ if (!circlecollider.active) continue;
+ all_colliders.push_back({.id = id,
+ .collider = collider_variant{circlecollider},
+ .transform = transform,
+ .rigidbody = rigidbody});
+ }
+ }
+
+ // Check between all colliders if there is a collision
+ std::vector<std::pair<CollisionInternal, CollisionInternal>> collided
+ = this->gather_collisions(all_colliders);
+
+ // For both objects call the collision handler
+ for (auto & collision_pair : collided) {
+ this->collision_handler_request(collision_pair.first, collision_pair.second);
+ this->collision_handler_request(collision_pair.second, collision_pair.first);
+ }
+}
+
+void CollisionSystem::collision_handler_request(CollisionInternal & this_data,
+ CollisionInternal & other_data) {
+
+ CollisionInternalType type
+ = this->get_collider_type(this_data.collider, other_data.collider);
+ std::pair<vec2, CollisionSystem::Direction> resolution_data
+ = this->collision_handler(this_data, other_data, type);
+ ComponentManager & mgr = this->mediator.component_manager;
+ OptionalRef<Metadata> this_metadata
+ = mgr.get_components_by_id<Metadata>(this_data.id).front().get();
+ OptionalRef<Metadata> other_metadata
+ = mgr.get_components_by_id<Metadata>(other_data.id).front().get();
+ OptionalRef<Collider> this_collider;
+ OptionalRef<Collider> other_collider;
+ switch (type) {
+ case CollisionInternalType::BOX_BOX: {
+ this_collider = std::get<std::reference_wrapper<BoxCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(other_data.collider);
+ break;
+ }
+ case CollisionInternalType::BOX_CIRCLE: {
+ this_collider = std::get<std::reference_wrapper<BoxCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(other_data.collider);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_BOX: {
+ this_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(other_data.collider);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_CIRCLE: {
+ this_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(other_data.collider);
+ break;
+ }
+ }
+
+ // collision info
+ crepe::CollisionSystem::CollisionInfo collision_info{
+ .this_collider = this_collider,
+ .this_transform = this_data.transform,
+ .this_rigidbody = this_data.rigidbody,
+ .this_metadata = this_metadata,
+ .other_collider = other_collider,
+ .other_transform = other_data.transform,
+ .other_rigidbody = other_data.rigidbody,
+ .other_metadata = other_metadata,
+ .resolution = resolution_data.first,
+ .resolution_direction = resolution_data.second,
+ };
+
+ // Determine if static needs to be called
+ this->determine_collision_handler(collision_info);
+}
+
+std::pair<vec2, CollisionSystem::Direction>
+CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal & data2,
+ CollisionInternalType type) {
+ vec2 resolution;
+ switch (type) {
+ case CollisionInternalType::BOX_BOX: {
+ const BoxCollider & collider1
+ = std::get<std::reference_wrapper<BoxCollider>>(data1.collider);
+ const BoxCollider & collider2
+ = std::get<std::reference_wrapper<BoxCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform,
+ data2.rigidbody);
+ resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1,
+ collider_pos2);
+ break;
+ }
+ case CollisionInternalType::BOX_CIRCLE: {
+ const BoxCollider & collider1
+ = std::get<std::reference_wrapper<BoxCollider>>(data1.collider);
+ const CircleCollider & collider2
+ = std::get<std::reference_wrapper<CircleCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ 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);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_CIRCLE: {
+ const CircleCollider & collider1
+ = std::get<std::reference_wrapper<CircleCollider>>(data1.collider);
+ const CircleCollider & collider2
+ = std::get<std::reference_wrapper<CircleCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform,
+ data2.rigidbody);
+ resolution = this->get_circle_circle_resolution(collider1, collider2,
+ collider_pos1, collider_pos2);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_BOX: {
+ const CircleCollider & collider1
+ = std::get<std::reference_wrapper<CircleCollider>>(data1.collider);
+ const BoxCollider & collider2
+ = std::get<std::reference_wrapper<BoxCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ 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);
+ break;
+ }
+ }
+
+ Direction resolution_direction = Direction::NONE;
+ if (resolution.x != 0 && resolution.y != 0) {
+ resolution_direction = Direction::BOTH;
+ } else if (resolution.x != 0) {
+ resolution_direction = Direction::X_DIRECTION;
+ //checks if the other velocity has a value and if this object moved
+ if (data1.rigidbody.data.linear_velocity.x != 0
+ && data1.rigidbody.data.linear_velocity.y != 0)
+ resolution.y = -data1.rigidbody.data.linear_velocity.y
+ * (resolution.x / data1.rigidbody.data.linear_velocity.x);
+ } else if (resolution.y != 0) {
+ resolution_direction = Direction::Y_DIRECTION;
+ //checks if the other velocity has a value and if this object moved
+ if (data1.rigidbody.data.linear_velocity.x != 0
+ && data1.rigidbody.data.linear_velocity.y != 0)
+ resolution.x = -data1.rigidbody.data.linear_velocity.x
+ * (resolution.y / data1.rigidbody.data.linear_velocity.y);
+ }
+
+ return std::make_pair(resolution, resolution_direction);
+}
+
+vec2 CollisionSystem::get_box_box_resolution(const BoxCollider & box_collider1,
+ const BoxCollider & box_collider2,
+ const vec2 & final_position1,
+ const vec2 & final_position2) const {
+ vec2 resolution; // Default resolution vector
+ vec2 delta = final_position2 - final_position1;
+
+ // Compute half-dimensions of the boxes
+ float half_width1 = box_collider1.dimensions.x / 2.0;
+ float half_height1 = box_collider1.dimensions.y / 2.0;
+ float half_width2 = box_collider2.dimensions.x / 2.0;
+ float half_height2 = box_collider2.dimensions.y / 2.0;
+
+ // Calculate overlaps along X and Y axes
+ float overlap_x = (half_width1 + half_width2) - std::abs(delta.x);
+ float overlap_y = (half_height1 + half_height2) - std::abs(delta.y);
+
+ // Check if there is a collision should always be true
+ if (overlap_x > 0 && overlap_y > 0) {
+ // Determine the direction of resolution
+ if (overlap_x < overlap_y) {
+ // Resolve along the X-axis (smallest overlap)
+ resolution.x = (delta.x > 0) ? -overlap_x : overlap_x;
+ } else if (overlap_y < overlap_x) {
+ // Resolve along the Y-axis (smallest overlap)
+ resolution.y = (delta.y > 0) ? -overlap_y : overlap_y;
+ } else {
+ // Equal overlap, resolve both directions with preference
+ resolution.x = (delta.x > 0) ? -overlap_x : overlap_x;
+ resolution.y = (delta.y > 0) ? -overlap_y : overlap_y;
+ }
+ }
+
+ return resolution;
+}
+
+vec2 CollisionSystem::get_circle_circle_resolution(const CircleCollider & circle_collider1,
+ const CircleCollider & circle_collider2,
+ const vec2 & final_position1,
+ const vec2 & final_position2) const {
+ vec2 delta = final_position2 - final_position1;
+
+ // Compute the distance between the two circle centers
+ float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y);
+
+ // Compute the combined radii of the two circles
+ float combined_radius = circle_collider1.radius + circle_collider2.radius;
+
+ // Compute the penetration depth
+ float penetration_depth = combined_radius - distance;
+
+ // Normalize the delta vector to get the collision direction
+ vec2 collision_normal = delta / distance;
+
+ // Compute the resolution vector
+ vec2 resolution = -collision_normal * penetration_depth;
+
+ return resolution;
+}
+
+vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_collider,
+ const BoxCollider & box_collider,
+ const vec2 & circle_position,
+ const vec2 & box_position) const {
+ vec2 delta = circle_position - box_position;
+
+ // Compute half-dimensions of the box
+ float half_width = box_collider.dimensions.x / 2.0f;
+ float half_height = box_collider.dimensions.y / 2.0f;
+
+ // Clamp circle center to the nearest point on the box
+ vec2 closest_point;
+ closest_point.x = std::clamp(delta.x, -half_width, half_width);
+ closest_point.y = std::clamp(delta.y, -half_height, half_height);
+
+ // Find the vector from the circle center to the closest point
+ vec2 closest_delta = delta - closest_point;
+
+ // Normalize the delta to get the collision direction
+ float distance
+ = std::sqrt(closest_delta.x * closest_delta.x + closest_delta.y * closest_delta.y);
+ vec2 collision_normal = closest_delta / distance;
+
+ // Compute penetration depth
+ float penetration_depth = circle_collider.radius - distance;
+
+ // Compute the resolution vector
+ vec2 resolution = collision_normal * penetration_depth;
+
+ return resolution;
+}
+
+void CollisionSystem::determine_collision_handler(CollisionInfo & info) {
+ // Check rigidbody type for static
+ if (info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return;
+ // If second body is static perform the static collision handler in this system
+ if (info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) {
+ this->static_collision_handler(info);
+ };
+ // Call collision event for user
+ CollisionEvent data(info);
+ EventManager & emgr = this->mediator.event_manager;
+ emgr.trigger_event<CollisionEvent>(data, info.this_collider.game_object_id);
+}
+
+void CollisionSystem::static_collision_handler(CollisionInfo & info) {
+ // Move object back using calculate move back value
+ info.this_transform.position += info.resolution;
+
+ switch (info.resolution_direction) {
+ case Direction::BOTH:
+ //bounce
+ if (info.this_rigidbody.data.elastisity_coefficient > 0) {
+ info.this_rigidbody.data.linear_velocity
+ = -info.this_rigidbody.data.linear_velocity
+ * info.this_rigidbody.data.elastisity_coefficient;
+ }
+ //stop movement
+ else {
+ info.this_rigidbody.data.linear_velocity = {0, 0};
+ }
+ break;
+ case Direction::Y_DIRECTION:
+ // Bounce
+ if (info.this_rigidbody.data.elastisity_coefficient > 0) {
+ info.this_rigidbody.data.linear_velocity.y
+ = -info.this_rigidbody.data.linear_velocity.y
+ * info.this_rigidbody.data.elastisity_coefficient;
+ }
+ // Stop movement
+ else {
+ info.this_rigidbody.data.linear_velocity.y = 0;
+ info.this_transform.position.x -= info.resolution.x;
+ }
+ break;
+ case Direction::X_DIRECTION:
+ // Bounce
+ if (info.this_rigidbody.data.elastisity_coefficient > 0) {
+ info.this_rigidbody.data.linear_velocity.x
+ = -info.this_rigidbody.data.linear_velocity.x
+ * info.this_rigidbody.data.elastisity_coefficient;
+ }
+ // Stop movement
+ else {
+ info.this_rigidbody.data.linear_velocity.x = 0;
+ info.this_transform.position.y -= info.resolution.y;
+ }
+ break;
+ case Direction::NONE:
+ // Not possible
+ break;
+ }
+}
+
+std::vector<std::pair<CollisionSystem::CollisionInternal, CollisionSystem::CollisionInternal>>
+CollisionSystem::gather_collisions(std::vector<CollisionInternal> & colliders) {
+
+ // TODO:
+ // If no colliders skip
+ // Check if colliders has rigidbody if not skip
+
+ // TODO:
+ // If amount is higer than lets say 16 for now use quadtree otwerwise skip
+ // Quadtree code
+ // Quadtree is placed over the input vector
+
+ // Return data of collided colliders which are variants
+ std::vector<std::pair<CollisionInternal, CollisionInternal>> collisions_ret;
+ //using visit to visit the variant to access the active and id.
+ for (size_t i = 0; i < colliders.size(); ++i) {
+ for (size_t j = i + 1; j < colliders.size(); ++j) {
+ if (colliders[i].id == colliders[j].id) continue;
+ if (!have_common_layer(colliders[i].rigidbody.data.collision_layers,
+ colliders[j].rigidbody.data.collision_layers))
+ continue;
+ CollisionInternalType type
+ = get_collider_type(colliders[i].collider, colliders[j].collider);
+ if (!get_collision(
+ {
+ .collider = colliders[i].collider,
+ .transform = colliders[i].transform,
+ .rigidbody = colliders[i].rigidbody,
+ },
+ {
+ .collider = colliders[j].collider,
+ .transform = colliders[j].transform,
+ .rigidbody = colliders[j].rigidbody,
+ },
+ type))
+ continue;
+ collisions_ret.emplace_back(colliders[i], colliders[j]);
+ }
+ }
+
+ return collisions_ret;
+}
+
+bool CollisionSystem::have_common_layer(const std::set<int> & layers1,
+ const std::set<int> & layers2) {
+
+ // Check if any number is equal in the layers
+ for (int num : layers1) {
+ if (layers2.contains(num)) {
+ // Common layer found
+ return true;
+ break;
+ }
+ }
+ // No common layer found
+ return false;
+}
+
+CollisionSystem::CollisionInternalType
+CollisionSystem::get_collider_type(const collider_variant & collider1,
+ const collider_variant & collider2) const {
+ if (std::holds_alternative<std::reference_wrapper<CircleCollider>>(collider1)) {
+ if (std::holds_alternative<std::reference_wrapper<CircleCollider>>(collider2)) {
+ return CollisionInternalType::CIRCLE_CIRCLE;
+ } else {
+ return CollisionInternalType::CIRCLE_BOX;
+ }
+ } else {
+ if (std::holds_alternative<std::reference_wrapper<CircleCollider>>(collider2)) {
+ return CollisionInternalType::BOX_CIRCLE;
+ } else {
+ return CollisionInternalType::BOX_BOX;
+ }
+ }
+}
+
+bool CollisionSystem::get_collision(const CollisionInternal & first_info,
+ const CollisionInternal & second_info,
+ CollisionInternalType type) const {
+ switch (type) {
+ case CollisionInternalType::BOX_BOX: {
+ const BoxCollider & box_collider1
+ = std::get<std::reference_wrapper<BoxCollider>>(first_info.collider);
+ const BoxCollider & box_collider2
+ = std::get<std::reference_wrapper<BoxCollider>>(second_info.collider);
+ return this->get_box_box_collision(box_collider1, box_collider2,
+ first_info.transform, second_info.transform,
+ second_info.rigidbody, second_info.rigidbody);
+ }
+ case CollisionInternalType::BOX_CIRCLE: {
+ const BoxCollider & box_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(first_info.collider);
+ const CircleCollider & circle_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(second_info.collider);
+ return this->get_box_circle_collision(
+ box_collider, circle_collider, first_info.transform, second_info.transform,
+ second_info.rigidbody, second_info.rigidbody);
+ }
+ case CollisionInternalType::CIRCLE_CIRCLE: {
+ const CircleCollider & circle_collider1
+ = std::get<std::reference_wrapper<CircleCollider>>(first_info.collider);
+ const CircleCollider & circle_collider2
+ = std::get<std::reference_wrapper<CircleCollider>>(second_info.collider);
+ return this->get_circle_circle_collision(
+ circle_collider1, circle_collider2, first_info.transform,
+ second_info.transform, second_info.rigidbody, second_info.rigidbody);
+ }
+ case CollisionInternalType::CIRCLE_BOX: {
+ const CircleCollider & circle_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(first_info.collider);
+ const BoxCollider & box_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(second_info.collider);
+ return this->get_box_circle_collision(
+ box_collider, circle_collider, first_info.transform, second_info.transform,
+ second_info.rigidbody, second_info.rigidbody);
+ }
+ }
+ return false;
+}
+
+bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const {
+ // Get current positions of colliders
+ vec2 final_position1 = this->get_current_position(box1.offset, transform1, rigidbody1);
+ vec2 final_position2 = this->get_current_position(box2.offset, transform2, rigidbody2);
+
+ // Calculate half-extents (half width and half height)
+ float half_width1 = box1.dimensions.x / 2.0;
+ float half_height1 = box1.dimensions.y / 2.0;
+ float half_width2 = box2.dimensions.x / 2.0;
+ float half_height2 = box2.dimensions.y / 2.0;
+
+ // Check if the boxes overlap along the X and Y axes
+ return (final_position1.x + half_width1 > final_position2.x - half_width2
+ && final_position1.x - half_width1 < final_position2.x + half_width2
+ && final_position1.y + half_height1 > final_position2.y - half_height2
+ && final_position1.y - half_height1 < final_position2.y + half_height2);
+}
+
+bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1,
+ const CircleCollider & circle2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const {
+ // Get current positions of colliders
+ vec2 final_position1 = this->get_current_position(box1.offset, transform1, rigidbody1);
+ vec2 final_position2 = this->get_current_position(circle2.offset, transform2, rigidbody2);
+
+ // Calculate box half-extents
+ float half_width = box1.dimensions.x / 2.0;
+ float half_height = box1.dimensions.y / 2.0;
+
+ // Find the closest point on the box to the circle's center
+ float closest_x = std::max(final_position1.x - half_width,
+ std::min(final_position2.x, final_position1.x + half_width));
+ float closest_y = std::max(final_position1.y - half_height,
+ std::min(final_position2.y, final_position1.y + half_height));
+
+ // Calculate the distance squared between the circle's center and the closest point on the box
+ float distance_x = final_position2.x - closest_x;
+ float distance_y = final_position2.y - closest_y;
+ 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;
+}
+
+bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1,
+ const CircleCollider & circle2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const {
+ // Get current positions of colliders
+ vec2 final_position1 = this->get_current_position(circle1.offset, transform1, rigidbody1);
+ vec2 final_position2 = this->get_current_position(circle2.offset, transform2, rigidbody2);
+
+ float distance_x = final_position1.x - final_position2.x;
+ float distance_y = final_position1.y - final_position2.y;
+ float distance_squared = distance_x * distance_x + distance_y * distance_y;
+
+ // Calculate the sum of the radii
+ float radius_sum = circle1.radius + circle2.radius;
+
+ // Check if the distance between the centers is less than or equal to the sum of the radii
+ return distance_squared < radius_sum * radius_sum;
+}
+
+vec2 CollisionSystem::get_current_position(const vec2 & collider_offset,
+ const Transform & transform,
+ const Rigidbody & rigidbody) const {
+ // Get the rotation in radians
+ float radians1 = transform.rotation * (M_PI / 180.0);
+
+ // Calculate total offset with scale
+ vec2 total_offset = (rigidbody.data.offset + collider_offset) * transform.scale;
+
+ // Rotate
+ float rotated_total_offset_x1
+ = total_offset.x * cos(radians1) - total_offset.y * sin(radians1);
+ float rotated_total_offset_y1
+ = total_offset.x * sin(radians1) + total_offset.y * cos(radians1);
+
+ // Final positions considering scaling and rotation
+ return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1));
+}
diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h
index c1a70d8..5b136c6 100644
--- a/src/crepe/system/CollisionSystem.h
+++ b/src/crepe/system/CollisionSystem.h
@@ -1,13 +1,311 @@
#pragma once
+#include <optional>
+#include <variant>
+#include <vector>
+
+#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 "Collider.h"
#include "System.h"
namespace crepe {
+//! A system responsible for detecting and handling collisions between colliders.
class CollisionSystem : public System {
public:
using System::System;
+
+private:
+ //! A variant type that can hold either a BoxCollider or a CircleCollider.
+ using collider_variant = std::variant<std::reference_wrapper<BoxCollider>,
+ std::reference_wrapper<CircleCollider>>;
+
+ //! Enum representing the types of collider pairs for collision detection.
+ enum class CollisionInternalType {
+ BOX_BOX,
+ CIRCLE_CIRCLE,
+ BOX_CIRCLE,
+ CIRCLE_BOX,
+ };
+
+ /**
+ * \brief A structure to store the collision data of a single collider.
+ *
+ * This structure all components and id that are for needed within this system when calculating or handeling collisions.
+ * The transform and rigidbody are mostly needed for location and rotation.
+ * In rigidbody additional info is written about what the body of the object is,
+ * and how it should respond on a collision.
+ */
+ struct CollisionInternal {
+ game_object_id_t id = 0;
+ collider_variant collider;
+ Transform & transform;
+ Rigidbody & rigidbody;
+ };
+
+ //! Enum representing movement directions during collision resolution.
+ enum class Direction {
+ //! No movement required.
+ NONE,
+ //! Movement in the X direction.
+ X_DIRECTION,
+ //! Movement in the Y direction.
+ Y_DIRECTION,
+ //! Movement in both X and Y directions.
+ BOTH
+ };
+
+public:
+ /**
+ * \brief Structure representing detailed collision information between two colliders.
+ *
+ * Includes information about the colliding objects and the resolution data for handling the collision.
+ */
+ struct CollisionInfo {
+ Collider & this_collider;
+ Transform & this_transform;
+ Rigidbody & this_rigidbody;
+ Metadata & this_metadata;
+ Collider & other_collider;
+ Transform & other_transform;
+ Rigidbody & other_rigidbody;
+ Metadata & other_metadata;
+ //! The resolution vector for the collision.
+ vec2 resolution;
+ //! The direction of movement for resolving the collision.
+ Direction resolution_direction = Direction::NONE;
+ };
+
+public:
+ //! Updates the collision system by checking for collisions between colliders and handling them.
void update() override;
+
+private:
+ /**
+ * \brief Determines the type of collider pair from two colliders.
+ *
+ * Uses std::holds_alternative to identify the types of the provided colliders.
+ *
+ * \param collider1 First collider variant (BoxCollider or CircleCollider).
+ * \param collider2 Second collider variant (BoxCollider or CircleCollider).
+ * \return The combined type of the two colliders.
+ */
+ CollisionInternalType get_collider_type(const collider_variant & collider1,
+ const collider_variant & collider2) const;
+
+ /**
+ * \brief Calculates the current position of a collider.
+ *
+ * Combines the Collider offset, Transform position, and Rigidbody offset to compute the position of the collider.
+ *
+ * \param collider_offset The offset of the collider.
+ * \param transform The Transform of the associated game object.
+ * \param rigidbody The Rigidbody of the associated game object.
+ * \return The calculated position of the collider.
+ */
+ vec2 get_current_position(const vec2 & collider_offset, const Transform & transform,
+ const Rigidbody & rigidbody) const;
+
+private:
+ /**
+ * \brief Handles collision resolution between two colliders.
+ *
+ * Processes collision data and adjusts objects to resolve collisions and/or calls the user oncollision script function.
+ *
+ * \param data1 Collision data for the first collider.
+ * \param data2 Collision data for the second collider.
+ */
+ void collision_handler_request(CollisionInternal & data1, CollisionInternal & data2);
+
+ /**
+ * \brief Resolves collision between two colliders and calculates the movement required.
+ *
+ * Determines the displacement and direction needed to separate colliders based on their types.
+ *
+ * \param data1 Collision data for the first collider.
+ * \param data2 Collision data for the second collider.
+ * \param type The type of collider pair.
+ * \return A pair containing the resolution vector and direction for the first collider.
+ */
+ std::pair<vec2, Direction> collision_handler(CollisionInternal & data1,
+ CollisionInternal & data2,
+ CollisionInternalType type);
+
+ /**
+ * \brief Calculates the resolution vector for two BoxColliders.
+ *
+ * Computes the displacement required to separate two overlapping BoxColliders.
+ *
+ * \param box_collider1 The first BoxCollider.
+ * \param box_collider2 The second BoxCollider.
+ * \param position1 The position of the first BoxCollider.
+ * \param position2 The position of the second BoxCollider.
+ * \return The resolution vector for the collision.
+ */
+ vec2 get_box_box_resolution(const BoxCollider & box_collider1,
+ const BoxCollider & box_collider2, const vec2 & position1,
+ const vec2 & position2) const;
+
+ /**
+ * \brief Calculates the resolution vector for two CircleCollider.
+ *
+ * Computes the displacement required to separate two overlapping CircleCollider.
+ *
+ * \param circle_collider1 The first CircleCollider.
+ * \param circle_collider2 The second CircleCollider.
+ * \param final_position1 The position of the first CircleCollider.
+ * \param final_position2 The position of the second CircleCollider.
+ * \return The resolution vector for the collision.
+ */
+ vec2 get_circle_circle_resolution(const CircleCollider & circle_collider1,
+ const CircleCollider & circle_collider2,
+ const vec2 & final_position1,
+ const vec2 & final_position2) const;
+
+ /**
+ * \brief Calculates the resolution vector for two CircleCollider.
+ *
+ * Computes the displacement required to separate two overlapping CircleCollider.
+ *
+ * \param circle_collider The first CircleCollider.
+ * \param box_collider The second CircleCollider.
+ * \param circle_position The position of the CircleCollider.
+ * \param box_position The position of the BoxCollider.
+ * \return The resolution vector for the collision.
+ */
+ vec2 get_circle_box_resolution(const CircleCollider & circle_collider,
+ const BoxCollider & box_collider,
+ const vec2 & circle_position,
+ const vec2 & box_position) const;
+
+ /**
+ * \brief Determines the appropriate collision handler for a collision.
+ *
+ * Decides the correct resolution process based on the dynamic or static nature of the colliders involved.
+ *
+ * \param info Collision information containing data about both colliders.
+ */
+ void determine_collision_handler(CollisionInfo & info);
+
+ /**
+ * \brief Handles collisions involving static objects.
+ *
+ * Resolves collisions by adjusting positions and modifying velocities if bounce is enabled.
+ *
+ * \param info Collision information containing data about both colliders.
+ */
+ void static_collision_handler(CollisionInfo & info);
+
+private:
+ /**
+ * \brief Checks for collisions between colliders.
+ *
+ * Identifies collisions and generates pairs of colliding objects for further processing.
+ *
+ * \param colliders A collection of all active colliders.
+ * \return A list of collision pairs with their associated data.
+ */
+ std::vector<std::pair<CollisionInternal, CollisionInternal>>
+ gather_collisions(std::vector<CollisionInternal> & colliders);
+
+ /**
+ * \brief Checks if two collision layers have at least one common layer.
+ *
+ * This function checks if there is any overlapping layer between the two inputs.
+ * It compares each layer from the first input to see
+ * if it exists in the second input. If at least one common layer is found,
+ * the function returns true, indicating that the two colliders share a common
+ * collision layer.
+ *
+ * \param layers1 all collision layers for the first collider.
+ * \param layers2 all collision layers for the second collider.
+ * \return Returns true if there is at least one common layer, false otherwise.
+ */
+
+ bool have_common_layer(const std::set<int> & layers1, const std::set<int> & layers2);
+
+ /**
+ * \brief Checks for collision between two colliders.
+ *
+ * Calls the appropriate collision detection function based on the collider types.
+ *
+ * \param first_info Collision data for the first collider.
+ * \param second_info Collision data for the second collider.
+ * \param type The type of collider pair.
+ * \return True if a collision is detected, otherwise false.
+ */
+ bool get_collision(const CollisionInternal & first_info,
+ const CollisionInternal & second_info,
+ CollisionInternalType type) const;
+
+ /**
+ * \brief Detects collisions between two BoxColliders.
+ *
+ * \param box1 The first BoxCollider.
+ * \param box2 The second BoxCollider.
+ * \param transform1 Transform of the first object.
+ * \param transform2 Transform of the second object.
+ * \param rigidbody1 Rigidbody of the first object.
+ * \param rigidbody2 Rigidbody of the second object.
+ * \return True if a collision is detected, otherwise false.
+ */
+ bool get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2,
+ const Transform & transform1, const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const;
+
+ /**
+ * \brief Check collision for box on circle collider
+ *
+ * \param box1 The BoxCollider
+ * \param circle2 The CircleCollider
+ * \param transform1 Transform of the first object.
+ * \param transform2 Transform of the second object.
+ * \param rigidbody1 Rigidbody of the first object.
+ * \param rigidbody2 Rigidbody of the second object.
+ * \return True if a collision is detected, otherwise false.
+ */
+ bool get_box_circle_collision(const BoxCollider & box1, const CircleCollider & circle2,
+ const Transform & transform1, const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const;
+
+ /**
+ * \brief Check collision for circle on circle collider
+ *
+ * \param circle1 First CircleCollider
+ * \param circle2 Second CircleCollider
+ * \param transform1 Transform of the first object.
+ * \param transform2 Transform of the second object.
+ * \param rigidbody1 Rigidbody of the first object.
+ * \param rigidbody2 Rigidbody of the second object.
+ * \return True if a collision is detected, otherwise false.
+ *
+ * \return status of collision
+ */
+ bool get_circle_circle_collision(const CircleCollider & circle1,
+ const CircleCollider & circle2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const;
+};
+
+/**
+ * \brief Event triggered during a collision between objects.
+ */
+class CollisionEvent : public Event {
+public:
+ crepe::CollisionSystem::CollisionInfo info;
+ CollisionEvent(const crepe::CollisionSystem::CollisionInfo & collisionInfo)
+ : info(collisionInfo) {}
};
} // namespace crepe
diff --git a/src/crepe/system/InputSystem.cpp b/src/crepe/system/InputSystem.cpp
new file mode 100644
index 0000000..fca540f
--- /dev/null
+++ b/src/crepe/system/InputSystem.cpp
@@ -0,0 +1,215 @@
+#include "../api/Button.h"
+#include "../facade/SDLContext.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/EventManager.h"
+#include "util/Log.h"
+
+#include "InputSystem.h"
+
+using namespace crepe;
+
+void InputSystem::update() {
+ ComponentManager & mgr = this->mediator.component_manager;
+
+ SDLContext & context = this->mediator.sdl_context;
+ std::vector<EventData> event_list = context.get_events();
+ RefVector<Button> buttons = mgr.get_components_by_type<Button>();
+ RefVector<Camera> cameras = mgr.get_components_by_type<Camera>();
+ OptionalRef<Camera> curr_cam_ref;
+
+ // Find the active camera
+ for (Camera & cam : cameras) {
+ if (!cam.active) continue;
+ curr_cam_ref = cam;
+ break;
+ }
+ if (!curr_cam_ref) return;
+
+ Camera & current_cam = curr_cam_ref;
+ RefVector<Transform> transform_vec
+ = mgr.get_components_by_id<Transform>(current_cam.game_object_id);
+ Transform & cam_transform = transform_vec.front().get();
+
+ vec2 camera_origin = cam_transform.position + current_cam.data.postion_offset
+ - (current_cam.viewport_size / 2);
+
+ for (const EventData & event : event_list) {
+ // Only calculate mouse coordinates for relevant events
+ if (event.event_type == EventType::MOUSE_DOWN
+ || event.event_type == EventType::MOUSE_UP
+ || event.event_type == EventType::MOUSE_MOVE
+ || event.event_type == EventType::MOUSE_WHEEL) {
+ this->handle_mouse_event(event, camera_origin, current_cam);
+
+ } else {
+ this->handle_non_mouse_event(event);
+ }
+ }
+}
+
+void InputSystem::handle_mouse_event(const EventData & event, const vec2 & camera_origin,
+ const Camera & current_cam) {
+ EventManager & event_mgr = this->mediator.event_manager;
+ vec2 adjusted_mouse;
+ adjusted_mouse.x = event.data.mouse_data.mouse_position.x + camera_origin.x;
+ adjusted_mouse.x = event.data.mouse_data.mouse_position.y + camera_origin.y;
+ // Check if the mouse is within the viewport
+ if ((adjusted_mouse.x < camera_origin.x
+ || adjusted_mouse.x > camera_origin.x + current_cam.viewport_size.x
+ || adjusted_mouse.y < camera_origin.y
+ || adjusted_mouse.y > camera_origin.y + current_cam.viewport_size.y))
+ return;
+
+ // Handle mouse-specific events
+ switch (event.event_type) {
+ case EventType::MOUSE_DOWN:
+ event_mgr.queue_event<MousePressEvent>({
+ .mouse_pos = adjusted_mouse,
+ .button = event.data.mouse_data.mouse_button,
+ });
+ this->last_mouse_down_position = adjusted_mouse;
+ this->last_mouse_button = event.data.mouse_data.mouse_button;
+ break;
+
+ case EventType::MOUSE_UP: {
+ event_mgr.queue_event<MouseReleaseEvent>({
+ .mouse_pos = adjusted_mouse,
+ .button = event.data.mouse_data.mouse_button,
+ });
+ vec2 delta_move = adjusted_mouse - this->last_mouse_down_position;
+ int click_tolerance = Config::get_instance().input.click_tolerance;
+ if (this->last_mouse_button == event.data.mouse_data.mouse_button
+ && std::abs(delta_move.x) <= click_tolerance
+ && std::abs(delta_move.y) <= click_tolerance) {
+ event_mgr.queue_event<MouseClickEvent>({
+ .mouse_pos = adjusted_mouse,
+ .button = event.data.mouse_data.mouse_button,
+ });
+ this->handle_click(event.data.mouse_data.mouse_button, adjusted_mouse);
+ }
+ break;
+ }
+
+ case EventType::MOUSE_MOVE:
+ event_mgr.queue_event<MouseMoveEvent>({
+ .mouse_pos = adjusted_mouse,
+ .mouse_delta = event.data.mouse_data.rel_mouse_move,
+ });
+ this->handle_move(event, adjusted_mouse);
+ break;
+
+ case EventType::MOUSE_WHEEL:
+ event_mgr.queue_event<MouseScrollEvent>({
+ .mouse_pos = adjusted_mouse,
+ .scroll_direction = event.data.mouse_data.scroll_direction,
+ .scroll_delta = event.data.mouse_data.scroll_delta,
+ });
+ break;
+
+ default:
+ break;
+ }
+}
+
+void InputSystem::handle_non_mouse_event(const EventData & event) {
+ EventManager & event_mgr = this->mediator.event_manager;
+ switch (event.event_type) {
+ case EventType::KEY_DOWN:
+
+ event_mgr.queue_event<KeyPressEvent>(
+ {.repeat = event.data.key_data.key_repeat, .key = event.data.key_data.key});
+ break;
+ case EventType::KEY_UP:
+ event_mgr.queue_event<KeyReleaseEvent>({.key = event.data.key_data.key});
+ break;
+ case EventType::SHUTDOWN:
+ event_mgr.queue_event<ShutDownEvent>({});
+ break;
+ case EventType::WINDOW_EXPOSE:
+ event_mgr.queue_event<WindowExposeEvent>({});
+ break;
+ case EventType::WINDOW_RESIZE:
+ event_mgr.queue_event<WindowResizeEvent>(
+ WindowResizeEvent{.dimensions = event.data.window_data.resize_dimension});
+ break;
+ case EventType::WINDOW_MOVE:
+ event_mgr.queue_event<WindowMoveEvent>(
+ {.delta_move = event.data.window_data.move_delta});
+ break;
+ case EventType::WINDOW_MINIMIZE:
+ event_mgr.queue_event<WindowMinimizeEvent>({});
+ break;
+ case EventType::WINDOW_MAXIMIZE:
+ event_mgr.queue_event<WindowMaximizeEvent>({});
+ break;
+ case EventType::WINDOW_FOCUS_GAIN:
+ event_mgr.queue_event<WindowFocusGainEvent>({});
+ break;
+ case EventType::WINDOW_FOCUS_LOST:
+ event_mgr.queue_event<WindowFocusLostEvent>({});
+ break;
+ default:
+ break;
+ }
+}
+
+void InputSystem::handle_move(const EventData & event_data, const vec2 & mouse_pos) {
+ ComponentManager & mgr = this->mediator.component_manager;
+
+ RefVector<Button> buttons = mgr.get_components_by_type<Button>();
+
+ for (Button & button : buttons) {
+ if (!button.active) continue;
+ RefVector<Transform> transform_vec
+ = mgr.get_components_by_id<Transform>(button.game_object_id);
+ Transform & transform(transform_vec.front().get());
+
+ bool was_hovering = button.hover;
+ if (this->is_mouse_inside_button(mouse_pos, button, transform)) {
+ button.hover = true;
+ if (!button.on_mouse_enter) continue;
+ if (!was_hovering) {
+ button.on_mouse_enter();
+ }
+ } else {
+ button.hover = false;
+ // Trigger the on_exit callback if the hover state just changed to false
+ if (!button.on_mouse_exit) continue;
+ if (was_hovering) {
+ button.on_mouse_exit();
+ }
+ }
+ }
+}
+
+void InputSystem::handle_click(const MouseButton & mouse_button, const vec2 & mouse_pos) {
+ ComponentManager & mgr = this->mediator.component_manager;
+
+ RefVector<Button> buttons = mgr.get_components_by_type<Button>();
+
+ for (Button & button : buttons) {
+ if (!button.active) continue;
+ if (!button.on_click) continue;
+ RefVector<Transform> transform_vec
+ = mgr.get_components_by_id<Transform>(button.game_object_id);
+ Transform & transform = transform_vec.front().get();
+
+ if (this->is_mouse_inside_button(mouse_pos, button, transform)) {
+
+ button.on_click();
+ }
+ }
+}
+
+bool InputSystem::is_mouse_inside_button(const vec2 & mouse_pos, const Button & button,
+ const Transform & transform) {
+ int actual_x = transform.position.x + button.offset.x;
+ int actual_y = transform.position.y + button.offset.y;
+
+ int half_width = button.dimensions.x / 2;
+ int half_height = button.dimensions.y / 2;
+
+ // Check if the mouse is within the button's boundaries
+ return mouse_pos.x >= actual_x - half_width && mouse_pos.x <= actual_x + half_width
+ && mouse_pos.y >= actual_y - half_height && mouse_pos.y <= actual_y + half_height;
+}
diff --git a/src/crepe/system/InputSystem.h b/src/crepe/system/InputSystem.h
new file mode 100644
index 0000000..eefd9fe
--- /dev/null
+++ b/src/crepe/system/InputSystem.h
@@ -0,0 +1,99 @@
+#pragma once
+
+#include "../api/Config.h"
+#include "../facade/EventData.h"
+
+#include "../types.h"
+#include "../util/OptionalRef.h"
+
+#include "System.h"
+
+namespace crepe {
+
+class Camera;
+class Button;
+class Transform;
+/**
+ * \brief Handles the processing of input events created by SDLContext
+ *
+ * This system processes events such as mouse clicks, mouse movement, and keyboard
+ * actions. It is responsible for detecting interactions with UI buttons and
+ * passing the corresponding events to the registered listeners.
+ */
+class InputSystem : public System {
+public:
+ using System::System;
+
+ /**
+ * \brief Updates the system, processing all input events.
+ * This method processes all events and triggers corresponding actions.
+ */
+ void update() override;
+
+private:
+ //! Stores the last position of the mouse when the button was pressed.
+ vec2 last_mouse_down_position;
+ // TODO: specify world/hud space and make regular `vec2`
+
+ //! Stores the last mouse button pressed.
+ MouseButton last_mouse_button = MouseButton::NONE;
+ /**
+ * \brief Handles mouse-related events.
+ * \param event The event data for the mouse event.
+ * \param camera_origin The origin position of the camera in world space.
+ * \param current_cam The currently active camera.
+ *
+ * This method processes mouse events, adjusts the mouse position to world coordinates,
+ * and triggers the appropriate mouse-specific event handling logic.
+ */
+ void handle_mouse_event(const EventData & event, const vec2 & camera_origin,
+ const Camera & current_cam);
+ /**
+ * \brief Handles non-mouse-related events.
+ * \param event The event data for the non-mouse event.
+ *
+ * This method processes events that do not involve the mouse, such as keyboard events,
+ * window events, and shutdown events, and triggers the corresponding event actions.
+ */
+ void handle_non_mouse_event(const EventData & event);
+ /**
+ * \brief Handles the mouse click event.
+ * \param mouse_button The mouse button involved in the click.
+ * \param world_mouse_x The X coordinate of the mouse in world space.
+ * \param world_mouse_y The Y coordinate of the mouse in world space.
+ *
+ * This method processes the mouse click event and triggers the corresponding button action.
+ */
+ void handle_click(const MouseButton & mouse_button, const vec2 & mouse_pos);
+
+ /**
+ * \brief Handles the mouse movement event.
+ * \param event_data The event data containing information about the mouse movement.
+ * \param world_mouse_x The X coordinate of the mouse in world space.
+ * \param world_mouse_y The Y coordinate of the mouse in world space.
+ *
+ * This method processes the mouse movement event and updates the button hover state.
+ */
+ void handle_move(const EventData & event_data, const vec2 & mouse_pos);
+
+ /**
+ * \brief Checks if the mouse position is inside the bounds of the button.
+ * \param world_mouse_x The X coordinate of the mouse in world space.
+ * \param world_mouse_y The Y coordinate of the mouse in world space.
+ * \param button The button to check.
+ * \param transform The transform component of the button.
+ * \return True if the mouse is inside the button, false otherwise.
+ */
+ bool is_mouse_inside_button(const vec2 & mouse_pos, const Button & button,
+ const Transform & transform);
+
+ /**
+ * \brief Handles the button press event, calling the on_click callback if necessary.
+ * \param button The button being pressed.
+ *
+ * This method triggers the on_click action for the button when it is pressed.
+ */
+ void handle_button_press(Button & button);
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp
index 33db52e..35a1d41 100644
--- a/src/crepe/system/ParticleSystem.cpp
+++ b/src/crepe/system/ParticleSystem.cpp
@@ -1,141 +1,121 @@
+#include <chrono>
#include <cmath>
#include <cstdlib>
#include <ctime>
-#include "api/ParticleEmitter.h"
-#include "api/Transform.h"
-#include "api/Vector2.h"
+#include "../api/ParticleEmitter.h"
+#include "../api/Transform.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/LoopTimerManager.h"
-#include "ComponentManager.h"
#include "ParticleSystem.h"
using namespace crepe;
void ParticleSystem::update() {
// Get all emitters
- ComponentManager & mgr = this->component_manager;
- std::vector<std::reference_wrapper<ParticleEmitter>> emitters
- = mgr.get_components_by_type<ParticleEmitter>();
+ const Mediator & mediator = this->mediator;
+ LoopTimerManager & loop_timer = mediator.loop_timer;
+ ComponentManager & mgr = mediator.component_manager;
+ float dt = loop_timer.get_scaled_fixed_delta_time().count();
+
+ RefVector<ParticleEmitter> emitters = mgr.get_components_by_type<ParticleEmitter>();
for (ParticleEmitter & emitter : emitters) {
// Get transform linked to emitter
const Transform & transform
- = mgr.get_components_by_id<Transform>(emitter.game_object_id)
- .front()
- .get();
+ = mgr.get_components_by_id<Transform>(emitter.game_object_id).front().get();
// Emit particles based on emission_rate
- int updates
- = calculate_update(this->update_count, emitter.data.emission_rate);
- for (size_t i = 0; i < updates; i++) {
- emit_particle(emitter, transform);
+ emitter.spawn_accumulator += emitter.data.emission_rate * dt;
+ while (emitter.spawn_accumulator >= 1.0) {
+ this->emit_particle(emitter, transform);
+ emitter.spawn_accumulator -= 1.0;
}
// Update all particles
- for (Particle & particle : emitter.data.particles) {
+ for (Particle & particle : emitter.particles) {
if (particle.active) {
- particle.update();
+ particle.update(dt);
}
}
// Check if within boundary
- check_bounds(emitter, transform);
+ this->check_bounds(emitter, transform);
}
-
- this->update_count = (this->update_count + 1) % this->MAX_UPDATE_COUNT;
}
-void ParticleSystem::emit_particle(ParticleEmitter & emitter,
- const Transform & transform) {
- constexpr double DEG_TO_RAD = M_PI / 180.0;
+void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & transform) {
+ constexpr float DEG_TO_RAD = M_PI / 180.0;
- Vector2 initial_position = emitter.data.position + transform.position;
- double random_angle
- = generate_random_angle(emitter.data.min_angle, emitter.data.max_angle);
+ vec2 initial_position = emitter.data.offset + transform.position;
+ float random_angle
+ = this->generate_random_angle(emitter.data.min_angle, emitter.data.max_angle);
- double random_speed
- = generate_random_speed(emitter.data.min_speed, emitter.data.max_speed);
- double angle_radians = random_angle * DEG_TO_RAD;
+ float random_speed
+ = this->generate_random_speed(emitter.data.min_speed, emitter.data.max_speed);
+ float angle_radians = random_angle * DEG_TO_RAD;
- Vector2 velocity = {random_speed * std::cos(angle_radians),
- random_speed * std::sin(angle_radians)};
+ vec2 velocity
+ = {random_speed * std::cos(angle_radians), random_speed * std::sin(angle_radians)};
- for (Particle & particle : emitter.data.particles) {
+ for (Particle & particle : emitter.particles) {
if (!particle.active) {
- particle.reset(emitter.data.end_lifespan, initial_position,
- velocity, random_angle);
+ particle.reset(emitter.data.end_lifespan, initial_position, velocity,
+ random_angle);
break;
}
}
}
-int ParticleSystem::calculate_update(int count, double emission) const {
- double integer_part = std::floor(emission);
- double fractional_part = emission - integer_part;
-
- if (fractional_part > 0) {
- int denominator = static_cast<int>(1.0 / fractional_part);
- return (count % denominator == 0) ? 1 : 0;
- }
-
- return static_cast<int>(emission);
-}
-
-void ParticleSystem::check_bounds(ParticleEmitter & emitter,
- const Transform & transform) {
- Vector2 offset = emitter.data.boundary.offset + transform.position
- + emitter.data.position;
- double half_width = emitter.data.boundary.width / 2.0;
- double half_height = emitter.data.boundary.height / 2.0;
-
- const double LEFT = offset.x - half_width;
- const double RIGHT = offset.x + half_width;
- const double TOP = offset.y - half_height;
- const double BOTTOM = offset.y + half_height;
-
- for (Particle & particle : emitter.data.particles) {
- const Vector2 & position = particle.position;
- bool within_bounds = (position.x >= LEFT && position.x <= RIGHT
- && position.y >= TOP && position.y <= BOTTOM);
-
+void ParticleSystem::check_bounds(ParticleEmitter & emitter, const Transform & transform) {
+ vec2 offset = emitter.data.boundary.offset + transform.position + emitter.data.offset;
+ float half_width = emitter.data.boundary.width / 2.0;
+ float half_height = emitter.data.boundary.height / 2.0;
+
+ float left = offset.x - half_width;
+ float right = offset.x + half_width;
+ float top = offset.y - half_height;
+ float bottom = offset.y + half_height;
+
+ for (Particle & particle : emitter.particles) {
+ const vec2 & position = particle.position;
+ bool within_bounds = (position.x >= left && position.x <= right && position.y >= top
+ && position.y <= bottom);
+ //if not within bounds do a reset or stop velocity
if (!within_bounds) {
if (emitter.data.boundary.reset_on_exit) {
particle.active = false;
} else {
particle.velocity = {0, 0};
- if (position.x < LEFT) particle.position.x = LEFT;
- else if (position.x > RIGHT) particle.position.x = RIGHT;
- if (position.y < TOP) particle.position.y = TOP;
- else if (position.y > BOTTOM) particle.position.y = BOTTOM;
+ if (position.x < left) particle.position.x = left;
+ else if (position.x > right) particle.position.x = right;
+ if (position.y < top) particle.position.y = top;
+ else if (position.y > bottom) particle.position.y = bottom;
}
}
}
}
-double ParticleSystem::generate_random_angle(double min_angle,
- double max_angle) const {
+float ParticleSystem::generate_random_angle(float min_angle, float max_angle) const {
if (min_angle == max_angle) {
return min_angle;
} else if (min_angle < max_angle) {
return min_angle
- + static_cast<double>(std::rand()
- % static_cast<int>(max_angle - min_angle));
+ + static_cast<float>(std::rand() % static_cast<int>(max_angle - min_angle));
} else {
- double angle_offset = (360 - min_angle) + max_angle;
- double random_angle = min_angle
- + static_cast<double>(
- std::rand() % static_cast<int>(angle_offset));
+ float angle_offset = (360 - min_angle) + max_angle;
+ float random_angle
+ = min_angle + static_cast<float>(std::rand() % static_cast<int>(angle_offset));
return (random_angle >= 360) ? random_angle - 360 : random_angle;
}
}
-double ParticleSystem::generate_random_speed(double min_speed,
- double max_speed) const {
+float ParticleSystem::generate_random_speed(float min_speed, float max_speed) const {
if (min_speed == max_speed) {
return min_speed;
} else {
return min_speed
- + static_cast<double>(std::rand()
- % static_cast<int>(max_speed - min_speed));
+ + static_cast<float>(std::rand() % static_cast<int>(max_speed - min_speed));
}
}
diff --git a/src/crepe/system/ParticleSystem.h b/src/crepe/system/ParticleSystem.h
index 0acc2b9..154521d 100644
--- a/src/crepe/system/ParticleSystem.h
+++ b/src/crepe/system/ParticleSystem.h
@@ -4,84 +4,59 @@
#include "System.h"
-#include "System.h"
-
namespace crepe {
class ParticleEmitter;
class Transform;
/**
- * \brief ParticleSystem class responsible for managing particle emission,
- * updates, and bounds checking.
- */
+ * \brief ParticleSystem class responsible for managing particle emission, updates, and bounds
+ * checking.
+ */
class ParticleSystem : public System {
public:
using System::System;
/**
- * \brief Updates all particle emitters by emitting particles, updating
- * particle states, and checking bounds.
+ * \brief Updates all particle emitters by emitting particles, updating particle states, and
+ * checking bounds.
*/
void update() override;
private:
/**
- * \brief Emits a particle from the specified emitter based on its emission
- * properties.
- *
+ * \brief Emits a particle from the specified emitter based on its emission properties.
+ *
* \param emitter Reference to the ParticleEmitter.
- * \param transform Const reference to the Transform component associated
- * with the emitter.
+ * \param transform Const reference to the Transform component associated with the emitter.
*/
void emit_particle(ParticleEmitter & emitter, const Transform & transform);
/**
- * \brief Calculates the number of times particles should be emitted based on
- * emission rate and update count.
- *
- * \param count Current update count.
- * \param emission Emission rate.
- * \return The number of particles to emit.
- */
- int calculate_update(int count, double emission) const;
-
- /**
- * \brief Checks whether particles are within the emitter’s boundary, resets
- * or stops particles if they exit.
- *
+ * \brief Checks whether particles are within the emitter’s boundary, resets or stops
+ * particles if they exit.
+ *
* \param emitter Reference to the ParticleEmitter.
- * \param transform Const reference to the Transform component associated
- * with the emitter.
+ * \param transform Const reference to the Transform component associated with the emitter.
*/
void check_bounds(ParticleEmitter & emitter, const Transform & transform);
/**
- * \brief Generates a random angle for particle emission within the specified
- * range.
- *
+ * \brief Generates a random angle for particle emission within the specified range.
+ *
* \param min_angle Minimum emission angle in degrees.
* \param max_angle Maximum emission angle in degrees.
* \return Random angle in degrees.
*/
- double generate_random_angle(double min_angle, double max_angle) const;
+ float generate_random_angle(float min_angle, float max_angle) const;
/**
- * \brief Generates a random speed for particle emission within the specified
- * range.
- *
+ * \brief Generates a random speed for particle emission within the specified range.
+ *
* \param min_speed Minimum emission speed.
* \param max_speed Maximum emission speed.
* \return Random speed.
*/
- double generate_random_speed(double min_speed, double max_speed) const;
-
-private:
- //! Counter to count updates to determine how many times emit_particle is
- // called.
- unsigned int update_count = 0;
- //! Determines the lowest amount of emission rate (1000 = 0.001 = 1 particle
- // per 1000 updates).
- static constexpr unsigned int MAX_UPDATE_COUNT = 100;
+ float generate_random_speed(float min_speed, float max_speed) const;
};
} // namespace crepe
diff --git a/src/crepe/system/PhysicsSystem.cpp b/src/crepe/system/PhysicsSystem.cpp
index da79707..3b3b8ab 100644
--- a/src/crepe/system/PhysicsSystem.cpp
+++ b/src/crepe/system/PhysicsSystem.cpp
@@ -1,97 +1,99 @@
#include <cmath>
-#include "../ComponentManager.h"
#include "../api/Config.h"
#include "../api/Rigidbody.h"
#include "../api/Transform.h"
#include "../api/Vector2.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/LoopTimerManager.h"
+#include "../manager/Mediator.h"
#include "PhysicsSystem.h"
using namespace crepe;
void PhysicsSystem::update() {
- ComponentManager & mgr = this->component_manager;
- std::vector<std::reference_wrapper<Rigidbody>> rigidbodies
- = mgr.get_components_by_type<Rigidbody>();
- std::vector<std::reference_wrapper<Transform>> transforms
- = mgr.get_components_by_type<Transform>();
- double gravity = Config::get_instance().physics.gravity;
+ const Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+ LoopTimerManager & loop_timer = mediator.loop_timer;
+ RefVector<Rigidbody> rigidbodies = mgr.get_components_by_type<Rigidbody>();
+ float dt = loop_timer.get_scaled_fixed_delta_time().count();
+
+ float gravity = Config::get_instance().physics.gravity;
for (Rigidbody & rigidbody : rigidbodies) {
if (!rigidbody.active) continue;
+ Transform & transform
+ = mgr.get_components_by_id<Transform>(rigidbody.game_object_id).front().get();
switch (rigidbody.data.body_type) {
case Rigidbody::BodyType::DYNAMIC:
- for (Transform & transform : transforms) {
- if (transform.game_object_id == rigidbody.game_object_id) {
+ if (transform.game_object_id == rigidbody.game_object_id) {
+ // Add gravity
- // Add gravity
- if (rigidbody.data.use_gravity) {
- rigidbody.data.linear_velocity.y
- += (rigidbody.data.mass
- * rigidbody.data.gravity_scale * gravity);
- }
- // Add damping
- if (rigidbody.data.angular_damping != 0) {
- rigidbody.data.angular_velocity
- *= rigidbody.data.angular_damping;
- }
- if (rigidbody.data.linear_damping != Vector2{0, 0}) {
- rigidbody.data.linear_velocity
- *= rigidbody.data.linear_damping;
- }
+ if (rigidbody.data.mass <= 0) {
+ throw std::runtime_error("Mass must be greater than 0");
+ }
- // Max velocity check
- if (rigidbody.data.angular_velocity
- > rigidbody.data.max_angular_velocity) {
- rigidbody.data.angular_velocity
- = rigidbody.data.max_angular_velocity;
- } else if (rigidbody.data.angular_velocity
- < -rigidbody.data.max_angular_velocity) {
- rigidbody.data.angular_velocity
- = -rigidbody.data.max_angular_velocity;
- }
+ if (gravity <= 0) {
+ throw std::runtime_error("Config Gravity must be greater than 0");
+ }
- if (rigidbody.data.linear_velocity.x
- > rigidbody.data.max_linear_velocity.x) {
- rigidbody.data.linear_velocity.x
- = rigidbody.data.max_linear_velocity.x;
- } else if (rigidbody.data.linear_velocity.x
- < -rigidbody.data.max_linear_velocity.x) {
- rigidbody.data.linear_velocity.x
- = -rigidbody.data.max_linear_velocity.x;
- }
+ if (rigidbody.data.gravity_scale > 0 && !rigidbody.data.constraints.y) {
+ rigidbody.data.linear_velocity.y
+ += (rigidbody.data.mass * rigidbody.data.gravity_scale * gravity
+ * dt);
+ }
+ // Add coefficient rotation
+ if (rigidbody.data.angular_velocity_coefficient > 0) {
+ rigidbody.data.angular_velocity
+ *= std::pow(rigidbody.data.angular_velocity_coefficient, dt);
+ }
- if (rigidbody.data.linear_velocity.y
- > rigidbody.data.max_linear_velocity.y) {
- rigidbody.data.linear_velocity.y
- = rigidbody.data.max_linear_velocity.y;
- } else if (rigidbody.data.linear_velocity.y
- < -rigidbody.data.max_linear_velocity.y) {
- rigidbody.data.linear_velocity.y
- = -rigidbody.data.max_linear_velocity.y;
- }
+ // Add coefficient movement horizontal
+ if (rigidbody.data.linear_velocity_coefficient.x > 0
+ && !rigidbody.data.constraints.x) {
+ rigidbody.data.linear_velocity.x
+ *= std::pow(rigidbody.data.linear_velocity_coefficient.x, dt);
+ }
- // Move object
- if (!rigidbody.data.constraints.rotation) {
- transform.rotation
- += rigidbody.data.angular_velocity;
- transform.rotation
- = std::fmod(transform.rotation, 360.0);
- if (transform.rotation < 0) {
- transform.rotation += 360.0;
- }
- }
- if (!rigidbody.data.constraints.x) {
- transform.position.x
- += rigidbody.data.linear_velocity.x;
- }
- if (!rigidbody.data.constraints.y) {
- transform.position.y
- += rigidbody.data.linear_velocity.y;
+ // Add coefficient movement horizontal
+ if (rigidbody.data.linear_velocity_coefficient.y > 0
+ && !rigidbody.data.constraints.y) {
+ rigidbody.data.linear_velocity.y
+ *= std::pow(rigidbody.data.linear_velocity_coefficient.y, dt);
+ }
+
+ // Max velocity check
+ if (rigidbody.data.angular_velocity
+ > rigidbody.data.max_angular_velocity) {
+ rigidbody.data.angular_velocity = rigidbody.data.max_angular_velocity;
+ } else if (rigidbody.data.angular_velocity
+ < -rigidbody.data.max_angular_velocity) {
+ rigidbody.data.angular_velocity = -rigidbody.data.max_angular_velocity;
+ }
+
+ // Set max velocity to maximum length
+ if (rigidbody.data.linear_velocity.length()
+ > rigidbody.data.max_linear_velocity) {
+ rigidbody.data.linear_velocity.normalize();
+ rigidbody.data.linear_velocity *= rigidbody.data.max_linear_velocity;
+ }
+
+ // Move object
+ if (!rigidbody.data.constraints.rotation) {
+ transform.rotation += rigidbody.data.angular_velocity * dt;
+ transform.rotation = std::fmod(transform.rotation, 360.0);
+ if (transform.rotation < 0) {
+ transform.rotation += 360.0;
}
}
+ if (!rigidbody.data.constraints.x) {
+ transform.position.x += rigidbody.data.linear_velocity.x * dt;
+ }
+ if (!rigidbody.data.constraints.y) {
+ transform.position.y += rigidbody.data.linear_velocity.y * dt;
+ }
}
break;
case Rigidbody::BodyType::KINEMATIC:
diff --git a/src/crepe/system/PhysicsSystem.h b/src/crepe/system/PhysicsSystem.h
index 5433a0f..26152a5 100644
--- a/src/crepe/system/PhysicsSystem.h
+++ b/src/crepe/system/PhysicsSystem.h
@@ -6,16 +6,16 @@ namespace crepe {
/**
* \brief System that controls all physics
- *
- * This class is a physics system that uses a rigidbody and transform
- * to add physics to a game object.
+ *
+ * This class is a physics system that uses a rigidbody and transform to add physics to a game
+ * object.
*/
class PhysicsSystem : public System {
public:
using System::System;
/**
* \brief updates the physics system.
- *
+ *
* It calculates new velocties and changes the postion in the transform.
*/
void update() override;
diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp
index 0d37808..62d42ec 100644
--- a/src/crepe/system/RenderSystem.cpp
+++ b/src/crepe/system/RenderSystem.cpp
@@ -1,51 +1,160 @@
+#include <algorithm>
+#include <cassert>
+#include <cmath>
#include <functional>
+#include <optional>
+#include <stdexcept>
#include <vector>
-#include "../ComponentManager.h"
+#include "../api/Camera.h"
+#include "../api/ParticleEmitter.h"
#include "../api/Sprite.h"
+#include "../api/Text.h"
#include "../api/Transform.h"
+#include "../facade/Font.h"
#include "../facade/SDLContext.h"
-#include "../util/Log.h"
+#include "../facade/Texture.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/ResourceManager.h"
#include "RenderSystem.h"
+#include "types.h"
using namespace crepe;
+using namespace std;
-void RenderSystem::clear_screen() const {
- SDLContext::get_instance().clear_screen();
+void RenderSystem::clear_screen() {
+ SDLContext & ctx = this->mediator.sdl_context;
+ ctx.clear_screen();
}
-void RenderSystem::present_screen() const {
- SDLContext::get_instance().present_screen();
+void RenderSystem::present_screen() {
+ SDLContext & ctx = this->mediator.sdl_context;
+ ctx.present_screen();
}
+
void RenderSystem::update_camera() {
- ComponentManager & mgr = this->component_manager;
+ ComponentManager & mgr = this->mediator.component_manager;
+ SDLContext & ctx = this->mediator.sdl_context;
+ RefVector<Camera> cameras = mgr.get_components_by_type<Camera>();
- std::vector<std::reference_wrapper<Camera>> cameras
- = mgr.get_components_by_type<Camera>();
+ if (cameras.size() == 0) throw std::runtime_error("No cameras in current scene");
for (Camera & cam : cameras) {
- SDLContext::get_instance().camera(cam);
- this->curr_cam = &cam;
+ if (!cam.active) continue;
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(cam.game_object_id).front().get();
+ vec2 new_camera_pos = transform.position + cam.data.postion_offset;
+ ctx.update_camera_view(cam, new_camera_pos);
+ return;
}
+ throw std::runtime_error("No active cameras in current scene");
}
-void RenderSystem::render_sprites() const {
- ComponentManager & mgr = this->component_manager;
- std::vector<std::reference_wrapper<Sprite>> sprites
- = mgr.get_components_by_type<Sprite>();
+bool sorting_comparison(const Sprite & a, const Sprite & b) {
+ if (a.data.sorting_in_layer != b.data.sorting_in_layer)
+ return a.data.sorting_in_layer < b.data.sorting_in_layer;
+ if (a.data.order_in_layer != b.data.order_in_layer)
+ return a.data.order_in_layer < b.data.order_in_layer;
- SDLContext & render = SDLContext::get_instance();
- for (const Sprite & sprite : sprites) {
- auto transforms
- = mgr.get_components_by_id<Transform>(sprite.game_object_id);
- render.draw(sprite, transforms[0], *curr_cam);
- }
+ return false;
+}
+
+RefVector<Sprite> RenderSystem::sort(RefVector<Sprite> & objs) const {
+ RefVector<Sprite> sorted_objs(objs);
+ std::sort(sorted_objs.begin(), sorted_objs.end(), sorting_comparison);
+
+ return sorted_objs;
}
void RenderSystem::update() {
this->clear_screen();
- this->update_camera();
- this->render_sprites();
+ this->render();
this->present_screen();
}
+
+bool RenderSystem::render_particle(const Sprite & sprite, const double & scale) {
+
+ ComponentManager & mgr = this->mediator.component_manager;
+ SDLContext & ctx = this->mediator.sdl_context;
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ Texture & res = resource_manager.get<Texture>(sprite.source);
+
+ vector<reference_wrapper<ParticleEmitter>> emitters
+ = mgr.get_components_by_id<ParticleEmitter>(sprite.game_object_id);
+
+ bool rendering_particles = false;
+
+ for (const ParticleEmitter & em : emitters) {
+ if (&em.sprite != &sprite) continue;
+ rendering_particles = true;
+ if (!em.active) continue;
+
+ for (const Particle & p : em.particles) {
+ if (!p.active) continue;
+
+ ctx.draw(SDLContext::RenderContext{
+ .sprite = sprite,
+ .texture = res,
+ .pos = p.position,
+ .angle = p.angle,
+ .scale = scale,
+ });
+ }
+ }
+ return rendering_particles;
+}
+void RenderSystem::render_normal(const Sprite & sprite, const Transform & tm) {
+ SDLContext & ctx = this->mediator.sdl_context;
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ const Texture & res = resource_manager.get<Texture>(sprite.source);
+
+ ctx.draw(SDLContext::RenderContext{
+ .sprite = sprite,
+ .texture = res,
+ .pos = tm.position,
+ .angle = tm.rotation,
+ .scale = tm.scale,
+ });
+}
+
+void RenderSystem::render() {
+ ComponentManager & mgr = this->mediator.component_manager;
+ this->update_camera();
+
+ RefVector<Sprite> sprites = mgr.get_components_by_type<Sprite>();
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ RefVector<Sprite> sorted_sprites = this->sort(sprites);
+ RefVector<Text> text_components = mgr.get_components_by_type<Text>();
+ for (Text & text : text_components) {
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(text.game_object_id).front().get();
+ this->render_text(text, transform);
+ }
+ for (const Sprite & sprite : sorted_sprites) {
+ if (!sprite.active) continue;
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(sprite.game_object_id).front().get();
+
+ bool rendered_particles = this->render_particle(sprite, transform.scale);
+
+ if (rendered_particles) continue;
+
+ this->render_normal(sprite, transform);
+ }
+}
+void RenderSystem::render_text(Text & text, const Transform & tm) {
+ SDLContext & ctx = this->mediator.sdl_context;
+
+ if (!text.font.has_value()) {
+ text.font.emplace(ctx.get_font_from_name(text.font_family));
+ }
+
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+
+ if (!text.font.has_value()) {
+ return;
+ }
+ const Asset & font_asset = text.font.value();
+ const Font & res = resource_manager.get<Font>(font_asset);
+}
diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h
index da4e910..56a0553 100644
--- a/src/crepe/system/RenderSystem.h
+++ b/src/crepe/system/RenderSystem.h
@@ -1,18 +1,21 @@
#pragma once
-#include "api/Camera.h"
+#include <cmath>
#include "System.h"
+#include "types.h"
namespace crepe {
+class Camera;
+class Sprite;
+class Transform;
+class Text;
/**
- * \class RenderSystem
* \brief Manages rendering operations for all game objects.
*
- * RenderSystem is responsible for rendering sprites, clearing and presenting the screen,
- * and managing the active camera. It functions as a singleton, providing centralized
- * rendering services for the application.
+ * RenderSystem is responsible for rendering, clearing and presenting the screen, and
+ * managing the active camera.
*/
class RenderSystem : public System {
public:
@@ -25,31 +28,56 @@ public:
private:
//! Clears the screen in preparation for rendering.
- void clear_screen() const;
+ void clear_screen();
//! Presents the rendered frame to the display.
- void present_screen() const;
+ void present_screen();
//! Updates the active camera used for rendering.
void update_camera();
- //! Renders all active sprites to the screen.
- void render_sprites() const;
+ //! Renders the whole screen
+ void render();
+
+ /**
+ * \brief Renders all the particles on the screen from a given sprite.
+ *
+ * \param sprite renders the particles with given texture
+ * \param tm the Transform component for scale. This is not a const reference because each
+ * particle has a position and rotation that needs to overwrite the transform position and
+ * rotation without overwriting the current transform. and because the transform
+ * constructor is now protected i cannot make tmp inside
+ * \return true if particles have been rendered
+ */
+ bool render_particle(const Sprite & sprite, const double & scale);
+ /**
+ * \brief Renders all Text components
+ *
+ * \param text The text component to be rendered.
+ * \param tm the Transform component that holds the position,rotation and scale
+ */
+ void render_text(Text & text, const Transform & tm);
+ /**
+ * \brief renders a sprite with a Transform component on the screen
+ *
+ * \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 Transform & tm);
+
+ /**
+ * \brief sort a vector sprite objects with
+ *
+ * \param objs the vector that will do a sorting algorithm on
+ * \return returns a sorted reference vector
+ */
+ RefVector<Sprite> sort(RefVector<Sprite> & objs) const;
/**
- * \todo Include color handling for sprites.
- * \todo Implement particle emitter rendering with sprites.
* \todo Add text rendering using SDL_ttf for text components.
* \todo Implement a text component and a button component.
- * \todo Ensure each sprite is checked for active status before rendering.
- * \todo Sort all layers by order before rendering.
* \todo Consider adding text input functionality.
*/
-
-private:
- //! Pointer to the current active camera for rendering
- Camera * curr_cam = nullptr;
- // TODO: needs a better solution
};
} // namespace crepe
diff --git a/src/crepe/system/ScriptSystem.cpp b/src/crepe/system/ScriptSystem.cpp
index f4a826b..d6b2ca1 100644
--- a/src/crepe/system/ScriptSystem.cpp
+++ b/src/crepe/system/ScriptSystem.cpp
@@ -1,10 +1,6 @@
-#include <forward_list>
-#include <functional>
-#include <vector>
-
-#include "../ComponentManager.h"
#include "../api/BehaviorScript.h"
#include "../api/Script.h"
+#include "../manager/ComponentManager.h"
#include "ScriptSystem.h"
@@ -14,32 +10,19 @@ using namespace crepe;
void ScriptSystem::update() {
dbg_trace();
- forward_list<reference_wrapper<Script>> scripts = this->get_scripts();
-
- for (auto & script_ref : scripts) {
- Script & script = script_ref.get();
- BehaviorScript & component = *script.parent_ref;
- if (!component.initialized) {
- script.init();
- component.initialized = true;
- }
- script.update();
- }
-}
-
-forward_list<reference_wrapper<Script>> ScriptSystem::get_scripts() const {
- forward_list<reference_wrapper<Script>> scripts = {};
- ComponentManager & mgr = this->component_manager;
- vector<reference_wrapper<BehaviorScript>> behavior_scripts
- = mgr.get_components_by_type<BehaviorScript>();
+ ComponentManager & mgr = this->mediator.component_manager;
+ RefVector<BehaviorScript> behavior_scripts = mgr.get_components_by_type<BehaviorScript>();
- for (auto behavior_script_ref : behavior_scripts) {
- BehaviorScript & behavior_script = behavior_script_ref.get();
+ for (BehaviorScript & behavior_script : behavior_scripts) {
if (!behavior_script.active) continue;
+
Script * script = behavior_script.script.get();
if (script == nullptr) continue;
- scripts.push_front(*script);
- }
- return scripts;
+ if (!script->initialized) {
+ script->init();
+ script->initialized = true;
+ }
+ script->update();
+ }
}
diff --git a/src/crepe/system/ScriptSystem.h b/src/crepe/system/ScriptSystem.h
index deb89cb..3db1b1e 100644
--- a/src/crepe/system/ScriptSystem.h
+++ b/src/crepe/system/ScriptSystem.h
@@ -1,7 +1,5 @@
#pragma once
-#include <forward_list>
-
#include "System.h"
namespace crepe {
@@ -10,7 +8,7 @@ class Script;
/**
* \brief Script system
- *
+ *
* The script system is responsible for all \c BehaviorScript components, and
* calls the methods on classes derived from \c Script.
*/
@@ -25,15 +23,6 @@ public:
* the \c BehaviorScript instance.
*/
void update() override;
-
-private:
- /**
- * \brief Aggregate all active \c BehaviorScript components and return a list
- * of references to their \c Script instances (utility)
- *
- * \returns List of active \c Script instances
- */
- std::forward_list<std::reference_wrapper<Script>> get_scripts() const;
};
} // namespace crepe
diff --git a/src/crepe/system/System.cpp b/src/crepe/system/System.cpp
index 937a423..ecc740d 100644
--- a/src/crepe/system/System.cpp
+++ b/src/crepe/system/System.cpp
@@ -1,7 +1,5 @@
-#include "../util/Log.h"
-
#include "System.h"
using namespace crepe;
-System::System(ComponentManager & mgr) : component_manager(mgr) { dbg_trace(); }
+System::System(const Mediator & mediator) : mediator(mediator) {}
diff --git a/src/crepe/system/System.h b/src/crepe/system/System.h
index 36f7edc..063dfbf 100644
--- a/src/crepe/system/System.h
+++ b/src/crepe/system/System.h
@@ -1,6 +1,6 @@
#pragma once
-#include "../ComponentManager.h"
+#include "../manager/Mediator.h"
namespace crepe {
@@ -9,9 +9,8 @@ class ComponentManager;
/**
* \brief Base ECS system class
*
- * This class is used as the base for all system classes. Classes derived from
- * System must implement the System::update() method and copy Script::Script
- * with the `using`-syntax.
+ * This class is used as the base for all system classes. Classes derived from System must
+ * implement the System::update() method and copy Script::Script with the `using`-syntax.
*/
class System {
public:
@@ -21,11 +20,11 @@ public:
virtual void update() = 0;
public:
- System(ComponentManager &);
+ System(const Mediator & m);
virtual ~System() = default;
protected:
- ComponentManager & component_manager;
+ const Mediator & mediator;
};
} // namespace crepe
diff --git a/src/crepe/types.h b/src/crepe/types.h
index 0d459e8..69cc526 100644
--- a/src/crepe/types.h
+++ b/src/crepe/types.h
@@ -1,9 +1,30 @@
#pragma once
+#include "api/Vector2.h"
+
#include <cstdint>
+#include <functional>
+#include <vector>
namespace crepe {
+//! GameObject ID
typedef uint32_t game_object_id_t;
-}
+//! vector of reference_wrapper
+template <typename T>
+using RefVector = std::vector<std::reference_wrapper<T>>;
+
+//! Default Vector2<int> type
+typedef Vector2<int> ivec2;
+
+//! Default Vector2<unsigned int> type
+typedef Vector2<unsigned int> uvec2;
+
+//! Default Vector2<float> type
+typedef Vector2<float> vec2;
+
+//! Default Vector2<double> type
+typedef Vector2<double> dvec2;
+
+}; // namespace crepe
diff --git a/src/crepe/util/Log.cpp b/src/crepe/util/Log.cpp
index e583734..84d80a8 100644
--- a/src/crepe/util/Log.cpp
+++ b/src/crepe/util/Log.cpp
@@ -1,9 +1,8 @@
-#include <cstdarg>
-#include <cstdio>
-#include <cstdlib>
+#include <iostream>
#include <string>
#include "../api/Config.h"
+
#include "Log.h"
using namespace crepe;
@@ -33,6 +32,6 @@ void Log::log(const Level & level, const string & msg) {
if (!out.ends_with("\n")) out += "\n";
// TODO: also log to file or smth
- fwrite(out.c_str(), 1, out.size(), stdout);
- fflush(stdout);
+ cout.write(out.data(), out.size());
+ cout.flush();
}
diff --git a/src/crepe/util/Log.h b/src/crepe/util/Log.h
index 01452b2..fc0bb3a 100644
--- a/src/crepe/util/Log.h
+++ b/src/crepe/util/Log.h
@@ -9,16 +9,14 @@
// utility macros
#define _crepe_logf_here(level, fmt, ...) \
- crepe::Log::logf( \
- level, "{}" fmt, \
- crepe::LogColor().fg_white(false).str(std::format( \
- "{} ({}:{})", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__)), \
- __VA_ARGS__)
+ crepe::Log::logf(level, "{}" fmt, \
+ crepe::LogColor().fg_white(false).str(std::format( \
+ "{} ({}:{})", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__)), \
+ __VA_ARGS__)
// very illegal global function-style macros
// NOLINTBEGIN
-#define dbg_logf(fmt, ...) \
- _crepe_logf_here(crepe::Log::Level::DEBUG, ": " fmt, __VA_ARGS__)
+#define dbg_logf(fmt, ...) _crepe_logf_here(crepe::Log::Level::DEBUG, ": " fmt, __VA_ARGS__)
#define dbg_log(str) _crepe_logf_here(crepe::Log::Level::DEBUG, ": {}", str)
#define dbg_trace() _crepe_logf_here(crepe::Log::Level::TRACE, "", "")
// NOLINTEND
@@ -36,11 +34,11 @@ class Log {
public:
//! Log message severity
enum Level {
- TRACE, //< Include (internal) function calls
- DEBUG, //< Include dbg_logf output
- INFO, //< General-purpose messages
- WARNING, //< Non-fatal errors
- ERROR, //< Fatal errors
+ TRACE, //!< Include (internal) function calls
+ DEBUG, //!< Include dbg_logf output
+ INFO, //!< General-purpose messages
+ WARNING, //!< Non-fatal errors
+ ERROR, //!< Fatal errors
};
/**
@@ -59,8 +57,7 @@ public:
* \param args Format arguments
*/
template <class... Args>
- static void logf(const Level & level, std::format_string<Args...> fmt,
- Args &&... args);
+ static void logf(const Level & level, std::format_string<Args...> fmt, Args &&... args);
/**
* \brief Format a message and log it (with default severity \c INFO)
@@ -76,6 +73,8 @@ private:
* \brief Output a message prefix depending on the log level
*
* \param level Message severity
+ *
+ * \return Colored message severity prefix string
*/
static std::string prefix(const Level & level);
};
diff --git a/src/crepe/util/Log.hpp b/src/crepe/util/Log.hpp
index 651f076..c2156cd 100644
--- a/src/crepe/util/Log.hpp
+++ b/src/crepe/util/Log.hpp
@@ -10,8 +10,7 @@ void Log::logf(std::format_string<Args...> fmt, Args &&... args) {
}
template <class... Args>
-void Log::logf(const Level & level, std::format_string<Args...> fmt,
- Args &&... args) {
+void Log::logf(const Level & level, std::format_string<Args...> fmt, Args &&... args) {
Log::log(level, std::format(fmt, std::forward<Args>(args)...));
}
diff --git a/src/crepe/util/LogColor.cpp b/src/crepe/util/LogColor.cpp
index ae44d72..5411898 100644
--- a/src/crepe/util/LogColor.cpp
+++ b/src/crepe/util/LogColor.cpp
@@ -1,6 +1,7 @@
#include <cstdarg>
#include "../api/Config.h"
+
#include "LogColor.h"
using namespace crepe;
@@ -27,51 +28,19 @@ LogColor & LogColor::reset() {
return *this;
}
-LogColor & LogColor::fg_black(bool bright) {
- return this->add_code(bright ? 90 : 30);
-}
-LogColor & LogColor::fg_red(bool bright) {
- return this->add_code(bright ? 91 : 31);
-}
-LogColor & LogColor::fg_green(bool bright) {
- return this->add_code(bright ? 92 : 32);
-}
-LogColor & LogColor::fg_yellow(bool bright) {
- return this->add_code(bright ? 93 : 33);
-}
-LogColor & LogColor::fg_blue(bool bright) {
- return this->add_code(bright ? 94 : 34);
-}
-LogColor & LogColor::fg_magenta(bool bright) {
- return this->add_code(bright ? 95 : 35);
-}
-LogColor & LogColor::fg_cyan(bool bright) {
- return this->add_code(bright ? 96 : 36);
-}
-LogColor & LogColor::fg_white(bool bright) {
- return this->add_code(bright ? 97 : 37);
-}
-LogColor & LogColor::bg_black(bool bright) {
- return this->add_code(bright ? 100 : 40);
-}
-LogColor & LogColor::bg_red(bool bright) {
- return this->add_code(bright ? 101 : 41);
-}
-LogColor & LogColor::bg_green(bool bright) {
- return this->add_code(bright ? 102 : 42);
-}
-LogColor & LogColor::bg_yellow(bool bright) {
- return this->add_code(bright ? 103 : 43);
-}
-LogColor & LogColor::bg_blue(bool bright) {
- return this->add_code(bright ? 104 : 44);
-}
-LogColor & LogColor::bg_magenta(bool bright) {
- return this->add_code(bright ? 105 : 45);
-}
-LogColor & LogColor::bg_cyan(bool bright) {
- return this->add_code(bright ? 106 : 46);
-}
-LogColor & LogColor::bg_white(bool bright) {
- return this->add_code(bright ? 107 : 47);
-}
+LogColor & LogColor::fg_black(bool bright) { return this->add_code(bright ? 90 : 30); }
+LogColor & LogColor::fg_red(bool bright) { return this->add_code(bright ? 91 : 31); }
+LogColor & LogColor::fg_green(bool bright) { return this->add_code(bright ? 92 : 32); }
+LogColor & LogColor::fg_yellow(bool bright) { return this->add_code(bright ? 93 : 33); }
+LogColor & LogColor::fg_blue(bool bright) { return this->add_code(bright ? 94 : 34); }
+LogColor & LogColor::fg_magenta(bool bright) { return this->add_code(bright ? 95 : 35); }
+LogColor & LogColor::fg_cyan(bool bright) { return this->add_code(bright ? 96 : 36); }
+LogColor & LogColor::fg_white(bool bright) { return this->add_code(bright ? 97 : 37); }
+LogColor & LogColor::bg_black(bool bright) { return this->add_code(bright ? 100 : 40); }
+LogColor & LogColor::bg_red(bool bright) { return this->add_code(bright ? 101 : 41); }
+LogColor & LogColor::bg_green(bool bright) { return this->add_code(bright ? 102 : 42); }
+LogColor & LogColor::bg_yellow(bool bright) { return this->add_code(bright ? 103 : 43); }
+LogColor & LogColor::bg_blue(bool bright) { return this->add_code(bright ? 104 : 44); }
+LogColor & LogColor::bg_magenta(bool bright) { return this->add_code(bright ? 105 : 45); }
+LogColor & LogColor::bg_cyan(bool bright) { return this->add_code(bright ? 106 : 46); }
+LogColor & LogColor::bg_white(bool bright) { return this->add_code(bright ? 107 : 47); }
diff --git a/src/crepe/util/LogColor.h b/src/crepe/util/LogColor.h
index 4b65127..132fb94 100644
--- a/src/crepe/util/LogColor.h
+++ b/src/crepe/util/LogColor.h
@@ -12,7 +12,13 @@ namespace crepe {
*/
class LogColor {
public:
- //! Get color code as stl string (or color content string)
+ /**
+ * \brief Get color code as STL string
+ *
+ * \param content If given, color this string and append a color reset escape sequence.
+ *
+ * \returns Color escape sequence
+ */
const std::string str(const std::string & content = "") const;
public:
@@ -20,6 +26,13 @@ public:
LogColor & reset();
public:
+ /**
+ * \name Foreground colors
+ *
+ * These functions set the foreground (text) color. The \c bright parameter
+ * makes the color brighter, or bold on some terminals.
+ * \{
+ */
LogColor & fg_black(bool bright = false);
LogColor & fg_red(bool bright = false);
LogColor & fg_green(bool bright = false);
@@ -28,8 +41,16 @@ public:
LogColor & fg_magenta(bool bright = false);
LogColor & fg_cyan(bool bright = false);
LogColor & fg_white(bool bright = false);
+ /// \}
public:
+ /**
+ * \name Background colors
+ *
+ * These functions set the background color. The \c bright parameter makes
+ * the color brighter.
+ * \{
+ */
LogColor & bg_black(bool bright = false);
LogColor & bg_red(bool bright = false);
LogColor & bg_green(bool bright = false);
@@ -38,6 +59,7 @@ public:
LogColor & bg_magenta(bool bright = false);
LogColor & bg_cyan(bool bright = false);
LogColor & bg_white(bool bright = false);
+ /// \}
private:
/**
diff --git a/src/crepe/util/OptionalRef.h b/src/crepe/util/OptionalRef.h
index 1ad3a6d..1b2cb3f 100644
--- a/src/crepe/util/OptionalRef.h
+++ b/src/crepe/util/OptionalRef.h
@@ -12,20 +12,46 @@ namespace crepe {
template <typename T>
class OptionalRef {
public:
+ //! Initialize empty (nonexistant) reference
OptionalRef() = default;
- OptionalRef(T &);
- OptionalRef<T> & operator=(T &);
+ //! Initialize reference with value
+ OptionalRef(T & ref);
+ /**
+ * \brief Assign new reference
+ *
+ * \param ref Reference to assign
+ *
+ * \return Reference to this (required for operator)
+ */
+ OptionalRef<T> & operator=(T & ref);
+ /**
+ * \brief Retrieve this reference (cast)
+ *
+ * \returns Internal reference if it is set
+ *
+ * \throws std::runtime_error if this function is called while the reference it not set
+ */
+ operator T &() const;
+ /**
+ * \brief Retrieve this reference (member access)
+ *
+ * \returns Internal reference if it is set
+ *
+ * \throws std::runtime_error if this function is called while the reference it not set
+ */
+ T * operator->() const;
+ /**
+ * \brief Check if this reference is not empty
+ *
+ * \returns `true` if reference is set, or `false` if it is not
+ */
explicit operator bool() const noexcept;
- void set(T &) noexcept;
- T & get() const;
+ /**
+ * \brief Make this reference empty
+ */
void clear() noexcept;
- OptionalRef(const OptionalRef<T> &);
- OptionalRef(OptionalRef<T> &&);
- OptionalRef<T> & operator=(const OptionalRef<T> &);
- OptionalRef<T> & operator=(OptionalRef<T> &&);
-
private:
/**
* \brief Reference to the value of type \c T
@@ -35,7 +61,6 @@ private:
T * ref = nullptr;
};
-}
+} // namespace crepe
#include "OptionalRef.hpp"
-
diff --git a/src/crepe/util/OptionalRef.hpp b/src/crepe/util/OptionalRef.hpp
index 7b201b0..5e36b3a 100644
--- a/src/crepe/util/OptionalRef.hpp
+++ b/src/crepe/util/OptionalRef.hpp
@@ -8,53 +8,26 @@ namespace crepe {
template <typename T>
OptionalRef<T>::OptionalRef(T & ref) {
- this->set(ref);
-}
-
-template <typename T>
-OptionalRef<T>::OptionalRef(const OptionalRef<T> & other) {
- this->ref = other.ref;
-}
-
-template <typename T>
-OptionalRef<T>::OptionalRef(OptionalRef<T> && other) {
- this->ref = other.ref;
- other.clear();
-}
-
-template <typename T>
-OptionalRef<T> & OptionalRef<T>::operator=(const OptionalRef<T> & other) {
- this->ref = other.ref;
- return *this;
-}
-
-template <typename T>
-OptionalRef<T> & OptionalRef<T>::operator=(OptionalRef<T> && other) {
- this->ref = other.ref;
- other.clear();
- return *this;
+ this->ref = &ref;
}
template <typename T>
-T & OptionalRef<T>::get() const {
+OptionalRef<T>::operator T &() const {
if (this->ref == nullptr)
throw std::runtime_error("OptionalRef: attempt to dereference nullptr");
return *this->ref;
}
template <typename T>
-void OptionalRef<T>::set(T & ref) noexcept {
- this->ref = &ref;
-}
-
-template <typename T>
-void OptionalRef<T>::clear() noexcept {
- this->ref = nullptr;
+T * OptionalRef<T>::operator->() const {
+ if (this->ref == nullptr)
+ throw std::runtime_error("OptionalRef: attempt to dereference nullptr");
+ return this->ref;
}
template <typename T>
OptionalRef<T> & OptionalRef<T>::operator=(T & ref) {
- this->set(ref);
+ this->ref = &ref;
return *this;
}
@@ -63,5 +36,9 @@ OptionalRef<T>::operator bool() const noexcept {
return this->ref != nullptr;
}
+template <typename T>
+void OptionalRef<T>::clear() noexcept {
+ this->ref = nullptr;
}
+} // namespace crepe
diff --git a/src/crepe/util/Proxy.h b/src/crepe/util/Proxy.h
index f84e462..789144a 100644
--- a/src/crepe/util/Proxy.h
+++ b/src/crepe/util/Proxy.h
@@ -7,8 +7,8 @@ namespace crepe {
/**
* \brief Utility wrapper for \c ValueBroker
*
- * This class can be used to to wrap a ValueBroker instance so it behaves like
- * a regular variable.
+ * This class can be used to to wrap a ValueBroker instance so it behaves like a regular
+ * variable.
*
* \tparam T Type of the underlying variable
*/
@@ -16,6 +16,8 @@ template <typename T>
class Proxy {
public:
//! Set operator
+ Proxy & operator=(Proxy &);
+ //! Set operator
Proxy & operator=(const T &);
//! Get operator
operator const T &();
diff --git a/src/crepe/util/Proxy.hpp b/src/crepe/util/Proxy.hpp
index b9923db..ef2b69f 100644
--- a/src/crepe/util/Proxy.hpp
+++ b/src/crepe/util/Proxy.hpp
@@ -14,6 +14,12 @@ Proxy<T> & Proxy<T>::operator=(const T & val) {
}
template <typename T>
+Proxy<T> & Proxy<T>::operator=(Proxy & proxy) {
+ this->broker.set(T(proxy));
+ return *this;
+}
+
+template <typename T>
Proxy<T>::operator const T &() {
return this->broker.get();
}
diff --git a/src/doc/feature/animator_creation.dox b/src/doc/feature/animator_creation.dox
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/src/doc/feature/animator_creation.dox
diff --git a/src/doc/feature/gameobject.dox b/src/doc/feature/gameobject.dox
new file mode 100644
index 0000000..c561874
--- /dev/null
+++ b/src/doc/feature/gameobject.dox
@@ -0,0 +1,18 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup feature_gameobject GameObjects
+\ingroup feature
+\brief GameObject to create a Scene
+
+GameObjects are the fundamental building blocks of a Scene. They represent entities
+in the game world and can have various components attached to them to define their
+behavior and properties. GameObjects can be created and modified within the
+Scene, allowing for a flexible and dynamic game environment.
+
+\see Component
+\see Scene
+
+*/
+}
diff --git a/src/doc/feature/proxy.dox b/src/doc/feature/proxy.dox
new file mode 100644
index 0000000..66bbd2f
--- /dev/null
+++ b/src/doc/feature/proxy.dox
@@ -0,0 +1,43 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup feature_proxy Proxy utility
+\ingroup feature
+\brief Use ValueBroker as if it were a regular variable
+
+Proxy provides operators that allow you to use a ValueBroker instance as if it
+were a regular variable. Proxy implements a constructor that allows it to be
+used as a substitute return type for any function that returns ValueBroker.
+
+\see ValueBroker
+\see Proxy
+
+\par Example
+
+```cpp
+#include <crepe/util/Proxy.h>
+#include <crepe/ValueBroker.h>
+
+int calculation(int value) {
+ return 3 * value;
+}
+
+void anywhere() {
+ crepe::ValueBroker<int> foo_handle;
+ crepe::Proxy foo = foo_handle;
+
+ // implicitly calls .set()
+ foo += 10;
+
+ // implicitly calls .get()
+ int out = calculation(foo);
+
+ // explicitly cast (also calls .get())
+ int casted = int(foo);
+}
+
+```
+
+*/
+}
diff --git a/src/doc/feature/savemgr.dox b/src/doc/feature/savemgr.dox
new file mode 100644
index 0000000..6aeab03
--- /dev/null
+++ b/src/doc/feature/savemgr.dox
@@ -0,0 +1,80 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup feature_savemgr Save data
+\ingroup feature
+\brief Functions to persistently store and retrieve arbitrary values
+
+The SaveManager may be used to persistently store game state such as player
+progress, statistics, achievements, etc. It works like a key-value store, where
+the key is a string and the value is an arbitrary type.
+
+SaveManager implements the following:
+
+- Storage and retrieval of primitive types and strings.
+- Automatic initialization of the database using default values.
+- The underlying database format is journaled, which reduces the likelihood of
+ players losing save data when an unexpected crash occurs while the SaveManager
+ is writing to disk.
+
+\see SaveManager
+
+\par Example
+
+The SaveManager instance reference may be retrieved by calling \c
+get_save_manager(). This function is available---
+
+- Within (derivatives of) Script
+
+- \todo Within (derivatives of) Scene
+
+- \todo As a public member function of LoopManager
+
+```cpp
+// Retrieve save manager
+crepe::SaveManager & save_manager = get_save_manager();
+```
+
+SaveManager may be used *explicitly*, using the \ref SaveManager::set "set()",
+\ref SaveManager::get "get()" and \ref SaveManager::has "has()" methods:
+```cpp
+// Check if the key "foo" exists, and initialize it to 3 if it doesn't
+if (!save_manager.has("foo"))
+ save_manager.set<int>("foo", 3);
+// Get value of key "foo"
+int foo = save_manager.get<int>("foo");
+
+// ~~~ arbitrary game code ~~~
+foo += 10;
+// ~~~ arbitrary game code ~~~
+
+// Save "foo" back to database
+save_manager.set<int>("foo", foo);
+```
+
+Alternatively, SaveManager::get may be called with a default value as second
+parameter. This changes its return type to ValueBroker, which acts as a
+read/write handle to the specific key requested, and remembers the key and its
+value type for you:
+```cpp
+// Get a read/write handle to the value stored in key "foo", and initialize it
+// to 3 if it doesn't exist yet
+ValueBroker foo_handle = save_manager.get<int>("foo", 3);
+int foo = foo_handle.get();
+
+// ~~~ arbitrary game code ~~~
+foo += 10;
+// ~~~ arbitrary game code ~~~
+
+// Save back to database
+foo_handle.set(foo);
+```
+
+To further simplify game code, the return value of SaveManager::get may be
+implicitly cast to Proxy instead of ValueBroker. This allows the database value
+to be used as if it were a regular variable. This usage is detailed separately
+in \"\ref feature_proxy\".
+
+*/
+}
diff --git a/src/doc/feature/scene.dox b/src/doc/feature/scene.dox
new file mode 100644
index 0000000..4124e37
--- /dev/null
+++ b/src/doc/feature/scene.dox
@@ -0,0 +1,72 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup feature_scene Scenes
+\ingroup feature
+\brief User-defined scenes
+
+Scenes can be used to implement game environments, and allow arbitrary game
+objects to be organized as part of the game structure. Scenes are implemented as
+derivative classes of Scene, which are added to the game using the SceneManager.
+Scenes describe the start of a Scene and cannot modify GameObjects during
+runtime of a Scene (use \ref feature_script for this purpose).
+
+\see SceneManager
+\see GameObject
+\see Script
+\see Scene
+
+\par Example
+
+This example demonstrates how to define and add scenes to the loop/scene manager
+in the `crepe` framework. Each concrete scene should be derived from Scene. In
+the example below, the concrete scene is named MyScene. A concrete scene should,
+at least, implement (override) two methods, namely load_scene() and get_name().
+The scene is build (using GameObjects) in the load_scene() method. GameObjects
+should be made using the component_manager::new_object().
+
+In the example below, two GameObjects (named object1 and object2) are added to
+MyScene. object1 and object2 do not have any non-default Components attached to
+them, however, if needed, this should also be done in load_scene(). Each
+concrete scene must have a unique name. This unique name is used to load a new
+concrete scene (via a Script). The unique name is set using the get_name()
+method. In the example below, MyScene's unique name is my_scene.
+
+After setting up one or more concrete scene(s), the concrete scene(s) should be
+added to the loop/scene manager. This is done in your main(). Firstly, the
+LoopManager should be instantiated. Than, all the concrete scene(s) should be
+added to the loop/scene manger via loop_mgr::add_scene<>(). The templated
+argument should define the concrete scene to be added.
+
+```cpp
+#include <crepe/api/LoopManager.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Scene.h>
+#include <crepe/types.h>
+
+using namespace crepe;
+
+class MyScene : public Scene {
+public:
+ void load_scene() {
+ ComponentManager & mgr = this->component_manager;
+ GameObject object1 = mgr.new_object("object1", "tag_my_scene", vec2{0, 0}, 0, 1);
+ GameObject object2 = mgr.new_object("object2", "tag_my_scene", vec2{1, 0}, 0, 1);
+ }
+
+ string get_name() const { return "my_scene"; }
+};
+
+int main() {
+ LoopManager loop_mgr;
+
+ // Add the scenes to the loop manager
+ loop_mgr.add_scene<MyScene>();
+
+ loop_mgr.start();
+}
+```
+
+*/
+}
diff --git a/src/doc/feature/script.dox b/src/doc/feature/script.dox
new file mode 100644
index 0000000..d25a63b
--- /dev/null
+++ b/src/doc/feature/script.dox
@@ -0,0 +1,62 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup feature_script Scripting
+\ingroup feature
+\brief User-defined scripts for game objects
+
+Scripts can be used to implement game behavior, and allow arbitrary code to run
+as part of the game loop. Scripts are implemented as derivative classes of
+Script, which are added to game objects using the BehaviorScript \ref Component
+"component".
+
+\todo This section is incomplete:
+- Utility functions to get components/events/etc inside script
+- How to listen for events
+- Extensions of script (keylistener)
+
+\see Script
+\see BehaviorScript
+\see GameObject
+
+\par Example
+
+First, define a class that inherits from Script. This class acts as an
+interface, and has two functions (\ref Script::init "\c init()" and \ref
+Script::update "\c update()"), which may be implemented (they are empty by
+default). From now on, this derivative class will be referred to as a *concrete
+script*.
+
+```cpp
+#include <crepe/api/Script.h>
+#include <crepe/api/BehaviorScript.h>
+
+class MyScript : public crepe::Script {
+ void init() {
+ // called once
+ }
+ void update() {
+ // called on fixed update
+ }
+};
+```
+
+Concrete scripts can be instantiated and attached to \ref GameObject
+"game objects" using the BehaviorScript \ref Component "component".
+
+```cpp
+using namespace crepe;
+GameObject obj = component_manager.new_object("name");
+
+// create BehaviorScript instance
+BehaviorScript & behavior_script = obj.add_component<BehaviorScript>();
+// attach (and instantiate) MyScript to behavior_script
+behavior_script.set_script<MyScript>();
+
+// the above can also be done in a single call for convenience:
+obj.add_component<BehaviorScript>().set_script<MyScript>();
+```
+
+*/
+}
diff --git a/src/doc/features.dox b/src/doc/features.dox
new file mode 100644
index 0000000..21a040a
--- /dev/null
+++ b/src/doc/features.dox
@@ -0,0 +1,28 @@
+// vim:ft=doxygen
+/**
+
+\htmlonly
+<style>
+table.memberdecls { display: none; }
+ul { margin: 1ex 0pt; }
+</style>
+\endhtmlonly
+
+\defgroup feature Features
+\brief Engine components
+
+This page lists engine features and contains usage instructions for each
+feature.
+
+\par Features
+
+- Scripting
+ - \ref feature_script \n\copybrief feature_script
+
+- Game flow management
+ - \ref feature_scene \n\copybrief feature_scene
+
+- Entity
+ - \ref feature_gameobject \n\copybrief feature_gameobject
+
+*/
diff --git a/src/doc/index.dox b/src/doc/index.dox
new file mode 100644
index 0000000..7796f34
--- /dev/null
+++ b/src/doc/index.dox
@@ -0,0 +1,17 @@
+// vim:ft=doxygen
+/**
+
+\mainpage crêpe game engine
+
+Welcome to the documentation for the crêpe game engine.
+
+\see feature
+
+*/
+
+/**
+
+\namespace crepe
+\brief Engine namespace
+
+*/
diff --git a/src/doc/installing.dox b/src/doc/installing.dox
new file mode 100644
index 0000000..48b27d7
--- /dev/null
+++ b/src/doc/installing.dox
@@ -0,0 +1,9 @@
+// vim:ft=doxygen
+/**
+
+\defgroup install Installation
+\brief Engine installation instructions
+
+\todo This entire page
+
+*/
diff --git a/src/doc/internal/component.dox b/src/doc/internal/component.dox
new file mode 100644
index 0000000..0dd4cb5
--- /dev/null
+++ b/src/doc/internal/component.dox
@@ -0,0 +1,41 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup internal_component Components
+\ingroup internal
+\brief ECS Components
+
+Components are attached to GameObject instances and are composed by the game
+programmer to create specific entities in the game world. While they are
+implemented as C++ classes, components should be treated as C-style structs,
+meaning all members are public and they do not contain functions.
+
+A basic component has the following structure:
+```cpp
+#include <crepe/Component.h>
+
+class MyComponent : public crepe::Component {
+public:
+ // Add your custom component's ininitializer properties after the `id`
+ // parameter. The first parameter is controlled by GameObject::add_component,
+ // while all other parameters are forwarded using std::forward.
+ MyComponent(game_object_id_t id, ...);
+
+ // Optionally define the `get_instances_max` method to limit the amount of
+ // instances of this component per GameObject. The default implementation for
+ // this function returns -1, which means the instance count does not have an
+ // upper limit:
+ virtual int get_instances_max() const { return -1; }
+
+ // Properties
+ // ...
+};
+```
+
+Generally, components are "handled" by \ref internal_system "systems", which may
+optionally change the components' state. Components' state may also be
+controlled by the game programmer through \ref feature_script "scripts".
+
+*/
+}
diff --git a/src/doc/internal/resource.dox b/src/doc/internal/resource.dox
new file mode 100644
index 0000000..56f1de0
--- /dev/null
+++ b/src/doc/internal/resource.dox
@@ -0,0 +1,12 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup internal_resource Resources
+\ingroup internal
+\brief Concrete resources
+
+\todo This section is incomplete
+
+*/
+}
diff --git a/src/doc/internal/style.dox b/src/doc/internal/style.dox
new file mode 100644
index 0000000..dad2df0
--- /dev/null
+++ b/src/doc/internal/style.dox
@@ -0,0 +1,9 @@
+// vim:ft=doxygen
+/**
+
+\defgroup internal_style Code style
+\ingroup internal
+\brief Coding conventions
+\include{doc} contributing.md
+
+*/
diff --git a/src/doc/internal/system.dox b/src/doc/internal/system.dox
new file mode 100644
index 0000000..17a101e
--- /dev/null
+++ b/src/doc/internal/system.dox
@@ -0,0 +1,26 @@
+// vim:ft=doxygen
+namespace crepe {
+/**
+
+\defgroup internal_system Systems
+\ingroup internal
+\brief ECS Systems
+
+\todo This section is incomplete
+
+A system is responsible for processing the data stored in \ref
+internal_component "components".
+
+A basic system has the following structure:
+```cpp
+#include <crepe/system/System.h>
+
+class MySystem : public System {
+public:
+ using System::System;
+ void update() override;
+};
+```
+
+*/
+}
diff --git a/src/doc/internals.dox b/src/doc/internals.dox
new file mode 100644
index 0000000..2d2ca56
--- /dev/null
+++ b/src/doc/internals.dox
@@ -0,0 +1,10 @@
+// vim:ft=doxygen
+/**
+
+\defgroup internal Internals
+\brief Internal engine structure and other conventions
+
+\todo This page is incomplete
+\todo Anything about Contexts?
+
+*/
diff --git a/src/doc/layout.xml b/src/doc/layout.xml
new file mode 100644
index 0000000..6336655
--- /dev/null
+++ b/src/doc/layout.xml
@@ -0,0 +1,255 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<doxygenlayout version="1.0">
+ <navindex>
+ <tab type="mainpage" visible="yes" title="Intro"/>
+ <tab type="user" url="@ref install" title="Installation"/>
+ <tab type="user" url="@ref feature" title="Features"/>
+ <tab type="user" url="@ref internal" title="Internals"/>
+ <tab type="pages" visible="no" title="" intro=""/>
+ <tab type="topics" visible="no" title="" intro=""/>
+ <tab type="modules" visible="no" title="" intro="">
+ <tab type="modulelist" visible="yes" title="" intro=""/>
+ <tab type="modulemembers" visible="yes" title="" intro=""/>
+ </tab>
+ <tab type="namespaces" visible="yes" title="">
+ <tab type="namespacelist" visible="yes" title="" intro=""/>
+ <tab type="namespacemembers" visible="yes" title="" intro=""/>
+ </tab>
+ <tab type="concepts" visible="no" title="">
+ </tab>
+ <tab type="interfaces" visible="no" title="">
+ <tab type="interfacelist" visible="yes" title="" intro=""/>
+ <tab type="interfaceindex" visible="$ALPHABETICAL_INDEX" title=""/>
+ <tab type="interfacehierarchy" visible="yes" title="" intro=""/>
+ </tab>
+ <tab type="classes" visible="yes" title="">
+ <tab type="classlist" visible="yes" title="" intro=""/>
+ <tab type="classindex" visible="$ALPHABETICAL_INDEX" title=""/>
+ <tab type="hierarchy" visible="yes" title="" intro=""/>
+ <tab type="classmembers" visible="yes" title="" intro=""/>
+ </tab>
+ <tab type="structs" visible="no" title="">
+ <tab type="structlist" visible="yes" title="" intro=""/>
+ <tab type="structindex" visible="$ALPHABETICAL_INDEX" title=""/>
+ </tab>
+ <tab type="exceptions" visible="no" title="">
+ <tab type="exceptionlist" visible="yes" title="" intro=""/>
+ <tab type="exceptionindex" visible="$ALPHABETICAL_INDEX" title=""/>
+ <tab type="exceptionhierarchy" visible="yes" title="" intro=""/>
+ </tab>
+ <tab type="files" visible="no" title="">
+ <tab type="filelist" visible="yes" title="" intro=""/>
+ <tab type="globals" visible="yes" title="" intro=""/>
+ </tab>
+ <tab type="examples" visible="no" title="" intro=""/>
+ </navindex>
+ <class>
+ <briefdescription visible="yes"/>
+ <detaileddescription title=""/>
+ <includes visible="$SHOW_HEADERFILE"/>
+ <inheritancegraph visible="yes"/>
+ <collaborationgraph visible="yes"/>
+ <memberdecl>
+ <nestedclasses visible="yes" title=""/>
+ <publictypes title=""/>
+ <services title=""/>
+ <interfaces title=""/>
+ <publicslots title=""/>
+ <signals title=""/>
+ <publicattributes title=""/>
+ <publicstaticattributes title=""/>
+ <publicmethods title=""/>
+ <publicstaticmethods title=""/>
+ <protectedtypes title=""/>
+ <protectedslots title=""/>
+ <protectedmethods title=""/>
+ <protectedstaticmethods title=""/>
+ <protectedattributes title=""/>
+ <protectedstaticattributes title=""/>
+ <packagetypes title=""/>
+ <packagemethods title=""/>
+ <packagestaticmethods title=""/>
+ <packageattributes title=""/>
+ <packagestaticattributes title=""/>
+ <properties title=""/>
+ <events title=""/>
+ <privatetypes title=""/>
+ <privateslots title=""/>
+ <privatemethods title=""/>
+ <privatestaticmethods title=""/>
+ <privateattributes title=""/>
+ <privatestaticattributes title=""/>
+ <friends title=""/>
+ <related title="" subtitle=""/>
+ <membergroups visible="yes"/>
+ </memberdecl>
+ <memberdef>
+ <inlineclasses title=""/>
+ <typedefs title=""/>
+ <enums title=""/>
+ <services title=""/>
+ <interfaces title=""/>
+ <constructors title=""/>
+ <functions title=""/>
+ <related title=""/>
+ <variables title=""/>
+ <properties title=""/>
+ <events title=""/>
+ </memberdef>
+ <allmemberslink visible="yes"/>
+ <usedfiles visible="$SHOW_USED_FILES"/>
+ <authorsection visible="yes"/>
+ </class>
+ <namespace>
+ <briefdescription visible="yes"/>
+ <detaileddescription title=""/>
+ <memberdecl>
+ <nestednamespaces visible="yes" title=""/>
+ <constantgroups visible="yes" title=""/>
+ <interfaces visible="yes" title=""/>
+ <classes visible="no" title=""/>
+ <concepts visible="yes" title=""/>
+ <structs visible="yes" title=""/>
+ <exceptions visible="yes" title=""/>
+ <typedefs title=""/>
+ <sequences title=""/>
+ <dictionaries title=""/>
+ <enums title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <properties title=""/>
+ <membergroups visible="yes"/>
+ </memberdecl>
+ <memberdef>
+ <inlineclasses title=""/>
+ <typedefs title=""/>
+ <sequences title=""/>
+ <dictionaries title=""/>
+ <enums title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <properties title=""/>
+ </memberdef>
+ <authorsection visible="yes"/>
+ </namespace>
+ <concept>
+ <briefdescription visible="yes"/>
+ <includes visible="$SHOW_HEADERFILE"/>
+ <definition visible="yes" title=""/>
+ <detaileddescription title=""/>
+ <authorsection visible="yes"/>
+ </concept>
+ <file>
+ <briefdescription visible="yes"/>
+ <includes visible="$SHOW_INCLUDE_FILES"/>
+ <includegraph visible="yes"/>
+ <includedbygraph visible="yes"/>
+ <sourcelink visible="yes"/>
+ <memberdecl>
+ <interfaces visible="yes" title=""/>
+ <classes visible="yes" title=""/>
+ <structs visible="yes" title=""/>
+ <exceptions visible="yes" title=""/>
+ <namespaces visible="yes" title=""/>
+ <concepts visible="yes" title=""/>
+ <constantgroups visible="yes" title=""/>
+ <defines title=""/>
+ <typedefs title=""/>
+ <sequences title=""/>
+ <dictionaries title=""/>
+ <enums title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <properties title=""/>
+ <membergroups visible="yes"/>
+ </memberdecl>
+ <detaileddescription title=""/>
+ <memberdef>
+ <inlineclasses title=""/>
+ <defines title=""/>
+ <typedefs title=""/>
+ <sequences title=""/>
+ <dictionaries title=""/>
+ <enums title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <properties title=""/>
+ </memberdef>
+ <authorsection/>
+ </file>
+ <group>
+ <detaileddescription title=""/>
+ <groupgraph visible="yes"/>
+ <memberdecl>
+ <nestedgroups visible="yes" title=""/>
+ <modules visible="yes" title=""/>
+ <dirs visible="yes" title=""/>
+ <files visible="yes" title=""/>
+ <namespaces visible="yes" title=""/>
+ <concepts visible="yes" title=""/>
+ <classes visible="yes" title=""/>
+ <defines title=""/>
+ <typedefs title=""/>
+ <sequences title=""/>
+ <dictionaries title=""/>
+ <enums title=""/>
+ <enumvalues title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <signals title=""/>
+ <publicslots title=""/>
+ <protectedslots title=""/>
+ <privateslots title=""/>
+ <events title=""/>
+ <properties title=""/>
+ <friends title=""/>
+ <membergroups visible="yes"/>
+ </memberdecl>
+ <memberdef>
+ <pagedocs/>
+ <inlineclasses title=""/>
+ <defines title=""/>
+ <typedefs title=""/>
+ <sequences title=""/>
+ <dictionaries title=""/>
+ <enums title=""/>
+ <enumvalues title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <signals title=""/>
+ <publicslots title=""/>
+ <protectedslots title=""/>
+ <privateslots title=""/>
+ <events title=""/>
+ <properties title=""/>
+ <friends title=""/>
+ </memberdef>
+ <authorsection visible="yes"/>
+ </group>
+ <module>
+ <briefdescription visible="yes"/>
+ <exportedmodules visible="yes"/>
+ <memberdecl>
+ <concepts visible="yes" title=""/>
+ <classes visible="yes" title=""/>
+ <enums title=""/>
+ <typedefs title=""/>
+ <functions title=""/>
+ <variables title=""/>
+ <membergroups title=""/>
+ </memberdecl>
+ <detaileddescription title=""/>
+ <memberdecl>
+ <files visible="yes"/>
+ </memberdecl>
+ </module>
+ <directory>
+ <briefdescription visible="yes"/>
+ <directorygraph visible="yes"/>
+ <memberdecl>
+ <dirs visible="yes"/>
+ <files visible="yes"/>
+ </memberdecl>
+ <detaileddescription title=""/>
+ </directory>
+</doxygenlayout>
diff --git a/src/doc/style.css b/src/doc/style.css
new file mode 100644
index 0000000..c12240c
--- /dev/null
+++ b/src/doc/style.css
@@ -0,0 +1,6 @@
+#titlearea,
+address,
+a[href="namespaces.html"]
+{ display: none; }
+
+h2.groupheader { margin-top: revert; }
diff --git a/src/example/AITest.cpp b/src/example/AITest.cpp
new file mode 100644
index 0000000..93ba500
--- /dev/null
+++ b/src/example/AITest.cpp
@@ -0,0 +1,90 @@
+#include <crepe/api/AI.h>
+#include <crepe/api/BehaviorScript.h>
+#include <crepe/api/Camera.h>
+#include <crepe/api/Color.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/LoopManager.h>
+#include <crepe/api/Rigidbody.h>
+#include <crepe/api/Scene.h>
+#include <crepe/api/Script.h>
+#include <crepe/api/Sprite.h>
+#include <crepe/manager/Mediator.h>
+#include <crepe/types.h>
+
+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;
+ }
+
+ bool mousemove(const MouseMoveEvent & event) {
+ /*RefVector<AI> aivec = this->get_components<AI>();
+ AI & ai = aivec.front().get();
+ ai.flee_target
+ = vec2{static_cast<float>(event.mouse_x), static_cast<float>(event.mouse_y)};*/
+ return true;
+ }
+
+ void init() {
+ subscribe<ShutDownEvent>(
+ [this](const ShutDownEvent & ev) -> bool { return this->shutdown(ev); });
+ subscribe<MouseMoveEvent>(
+ [this](const MouseMoveEvent & ev) -> bool { return this->mousemove(ev); });
+ }
+};
+
+class Scene1 : public Scene {
+public:
+ void load_scene() override {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+
+ GameObject game_object1 = mgr.new_object("", "", vec2{0, 0}, 0, 1);
+ GameObject game_object2 = mgr.new_object("", "", vec2{0, 0}, 0, 1);
+
+ Asset img{"asset/texture/test_ap43.png"};
+
+ Sprite & test_sprite = game_object1.add_component<Sprite>(
+ img, Sprite::Data{
+ .color = Color::MAGENTA,
+ .flip = Sprite::FlipSettings{false, false},
+ .sorting_in_layer = 2,
+ .order_in_layer = 2,
+ .size = {0, 100},
+ .angle_offset = 0,
+ .position_offset = {0, 0},
+ });
+
+ AI & ai = game_object1.add_component<AI>(3000);
+ // ai.arrive_on();
+ // ai.flee_on();
+ ai.path_follow_on();
+ ai.make_oval_path(500, 1000, {0, -1000}, 1.5708, true);
+ ai.make_oval_path(1000, 500, {0, 500}, 4.7124, false);
+ game_object1.add_component<Rigidbody>(Rigidbody::Data{
+ .mass = 0.1f,
+ .max_linear_velocity = 40,
+ });
+ game_object1.add_component<BehaviorScript>().set_script<Script1>();
+
+ game_object2.add_component<Camera>(ivec2{1080, 720}, vec2{5000, 5000},
+ Camera::Data{
+ .bg_color = Color::WHITE,
+ .zoom = 1,
+ });
+ }
+
+ string get_name() const override { return "Scene1"; }
+};
+
+int main() {
+ LoopManager engine;
+ engine.add_scene<Scene1>();
+ engine.start();
+
+ return 0;
+}
diff --git a/src/example/CMakeLists.txt b/src/example/CMakeLists.txt
index 3a5b543..f62414e 100644
--- a/src/example/CMakeLists.txt
+++ b/src/example/CMakeLists.txt
@@ -16,18 +16,9 @@ function(add_example target_name)
add_dependencies(examples ${target_name})
endfunction()
-add_example(audio_internal)
-# add_example(components_internal)
-add_example(script)
-add_example(log)
-add_example(rendering)
-add_example(asset_manager)
-add_example(physics)
-add_example(savemgr)
-add_example(proxy)
-add_example(db)
-add_example(ecs)
-add_example(scene_manager)
-add_example(particles)
-add_example(gameloop)
-
+add_example(rendering_particle)
+add_example(game)
+add_example(button)
+add_example(loadfont)
+add_example(FontExample)
+add_example(AITest)
diff --git a/src/example/FontExample.cpp b/src/example/FontExample.cpp
new file mode 100644
index 0000000..6a334b1
--- /dev/null
+++ b/src/example/FontExample.cpp
@@ -0,0 +1,55 @@
+#include <SDL2/SDL_ttf.h>
+#include <chrono>
+#include <crepe/api/Camera.h>
+#include <crepe/api/Config.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/LoopManager.h>
+#include <crepe/api/Scene.h>
+#include <crepe/api/Script.h>
+#include <crepe/api/Text.h>
+#include <crepe/facade/Font.h>
+#include <crepe/facade/SDLContext.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/manager/Mediator.h>
+#include <crepe/manager/ResourceManager.h>
+#include <exception>
+#include <iostream>
+#include <memory>
+using namespace crepe;
+using namespace std;
+using namespace std::chrono;
+class TestScript : public Script {
+public:
+ steady_clock::time_point start_time;
+ virtual void init() override { start_time = steady_clock::now(); }
+ virtual void update() override {
+ auto now = steady_clock::now();
+ auto elapsed = duration_cast<seconds>(now - start_time).count();
+
+ if (elapsed >= 5) {
+ Mediator & med = mediator;
+ EventManager & event_mgr = med.event_manager;
+ event_mgr.trigger_event<ShutDownEvent>();
+ }
+ }
+};
+class TestScene : public Scene {
+public:
+ void load_scene() override {
+ GameObject text_object = this->new_object("test", "test", vec2{0, 0}, 0, 1);
+ text_object.add_component<Text>(vec2(100, 100), vec2(0, 0), "OpenSymbol",
+ Text::Data{});
+ text_object.add_component<BehaviorScript>().set_script<TestScript>();
+ text_object.add_component<Camera>(ivec2{300, 300}, vec2{100, 100}, Camera::Data{});
+ }
+ std::string get_name() const override { return "hey"; }
+};
+int main() {
+ // Config& config = Config::get_instance();
+ // config.log.level = Log::Level::TRACE;
+ LoopManager engine;
+ engine.add_scene<TestScene>();
+ engine.start();
+
+ return 0;
+}
diff --git a/src/example/asset_manager.cpp b/src/example/asset_manager.cpp
deleted file mode 100644
index a2ca8c3..0000000
--- a/src/example/asset_manager.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-#include <crepe/api/AssetManager.h>
-#include <crepe/api/Texture.h>
-#include <crepe/facade/Sound.h>
-
-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<Sound>("mwe/audio/bgm.ogg");
- auto sfx1 = mgr.cache<Sound>("mwe/audio/sfx1.wav");
- auto sfx2 = mgr.cache<Sound>("mwe/audio/sfx2.wav");
-
- auto img = mgr.cache<Texture>("asset/texture/img.png");
- auto img1 = mgr.cache<Texture>("asset/texture/second.png");
- }
-
- {
- auto bgm = mgr.cache<Sound>("mwe/audio/bgm.ogg");
- auto sfx1 = mgr.cache<Sound>("mwe/audio/sfx1.wav");
- auto sfx2 = mgr.cache<Sound>("mwe/audio/sfx2.wav");
-
- auto img = mgr.cache<Texture>("asset/texture/img.png");
- auto img1 = mgr.cache<Texture>("asset/texture/second.png");
- }
-}
diff --git a/src/example/audio_internal.cpp b/src/example/audio_internal.cpp
deleted file mode 100644
index 9b60e6b..0000000
--- a/src/example/audio_internal.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/** \file
- *
- * Standalone example for usage of the internal \c Sound class.
- */
-
-#include <crepe/api/Config.h>
-#include <crepe/facade/SoundContext.h>
-#include <crepe/facade/Sound.h>
-#include <crepe/Asset.h>
-#include <crepe/util/Log.h>
-
-#include <thread>
-
-using namespace crepe;
-using namespace std;
-using namespace std::chrono_literals;
-using std::make_unique;
-
-// Unrelated stuff that is not part of this POC
-int _ = []() {
- // Show dbg_trace() output
- auto & cfg = Config::get_instance();
- cfg.log.level = Log::Level::TRACE;
-
- return 0; // satisfy compiler
-}();
-
-int main() {
- SoundContext ctx{};
- Sound sound{ctx};
- // Load a background track (Ogg Vorbis)
- auto _bgm = sound.clone(Asset{"mwe/audio/bgm.ogg"});
- Sound & bgm = *dynamic_cast<Sound *>(_bgm.get());
- // Load three short samples (WAV)
- auto _sfx1 = sound.clone(Asset{"mwe/audio/sfx1.wav"});
- Sound & sfx1 = *dynamic_cast<Sound *>(_sfx1.get());
- auto _sfx2 = sound.clone(Asset{"mwe/audio/sfx2.wav"});
- Sound & sfx2 = *dynamic_cast<Sound *>(_sfx2.get());
- auto _sfx3 = sound.clone(Asset{"mwe/audio/sfx3.wav"});
- Sound & sfx3 = *dynamic_cast<Sound *>(_sfx3.get());
-
- // Start the background track
- bgm.play();
-
- // Play each sample sequentially while pausing and resuming the background
- // track
- this_thread::sleep_for(500ms);
- sfx1.play();
- this_thread::sleep_for(500ms);
- sfx2.play();
- bgm.pause();
- this_thread::sleep_for(500ms);
- sfx3.play();
- bgm.play();
- this_thread::sleep_for(500ms);
-
- // Play all samples simultaniously
- sfx1.play();
- sfx2.play();
- sfx3.play();
- this_thread::sleep_for(1000ms);
-
- // Stop all audio and exit
- return EXIT_SUCCESS;
-}
diff --git a/src/example/button.cpp b/src/example/button.cpp
new file mode 100644
index 0000000..4220588
--- /dev/null
+++ b/src/example/button.cpp
@@ -0,0 +1,41 @@
+#include <SDL2/SDL_timer.h>
+#include <chrono>
+#include <crepe/Component.h>
+#include <crepe/api/Animator.h>
+#include <crepe/api/Button.h>
+#include <crepe/api/Camera.h>
+#include <crepe/api/Color.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Sprite.h>
+#include <crepe/api/Texture.h>
+#include <crepe/api/Transform.h>
+#include <crepe/facade/SDLContext.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/system/AnimatorSystem.h>
+#include <crepe/system/InputSystem.h>
+#include <crepe/system/RenderSystem.h>
+#include <crepe/types.h>
+using namespace crepe;
+using namespace std;
+
+int main(int argc, char * argv[]) {
+ Mediator mediator;
+ ComponentManager mgr{mediator};
+ RenderSystem sys{mediator};
+ EventManager event_mgr{mediator};
+ InputSystem input_sys{mediator};
+ SDLContext sdl_context{mediator};
+ GameObject obj = mgr.new_object("camera", "camera", vec2{0, 0}, 0, 1);
+ auto & camera = obj.add_component<Camera>(
+ ivec2{500, 500}, vec2{500, 500}, Camera::Data{.bg_color = Color::WHITE, .zoom = 1.0f});
+ auto start = std::chrono::steady_clock::now();
+ while (true) {
+ const keyboard_state_t & keyboard_state = sdl_context.get_keyboard_state();
+ input_sys.update();
+ sys.update();
+ event_mgr.dispatch_events();
+ SDL_Delay(30);
+ }
+ return 0;
+}
diff --git a/src/example/components_internal.cpp b/src/example/components_internal.cpp
deleted file mode 100644
index eeecdc0..0000000
--- a/src/example/components_internal.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/** \file
- *
- * Standalone example for usage of the internal ECS
- */
-
-#include <cassert>
-#include <chrono>
-
-#include <crepe/Component.h>
-#include <crepe/ComponentManager.h>
-
-#include <crepe/api/GameObject.h>
-#include <crepe/api/Rigidbody.h>
-#include <crepe/api/Sprite.h>
-
-#include <crepe/util/Log.h>
-
-using namespace crepe;
-using namespace std;
-
-#define OBJ_COUNT 100000
-
-int main() {
- dbg_trace();
-
- ComponentManager mgr{};
-
- auto start_adding = chrono::high_resolution_clock::now();
-
- GameObject * game_object[OBJ_COUNT];
-
- for (int i = 0; i < OBJ_COUNT; ++i) {
- GameObject obj = mgr.new_object("Name", "Tag");
- obj.add_component<Sprite>("test");
- obj.add_component<Rigidbody>(0, 0, i);
- }
-
- auto stop_adding = chrono::high_resolution_clock::now();
-
- auto sprites = mgr.get_components_by_type<Sprite>();
- for (auto sprite : sprites) {
- assert(true);
- }
-
- auto stop_looping = chrono::high_resolution_clock::now();
-
- auto add_time = chrono::duration_cast<chrono::microseconds>(stop_adding
- - start_adding);
- auto loop_time = chrono::duration_cast<chrono::microseconds>(stop_looping
- - stop_adding);
- printf("add time: %ldus\n", add_time.count());
- printf("loop time: %ldus\n", loop_time.count());
-
- return 0;
-}
diff --git a/src/example/db.cpp b/src/example/db.cpp
deleted file mode 100644
index ee4e8fc..0000000
--- a/src/example/db.cpp
+++ /dev/null
@@ -1,30 +0,0 @@
-#include <crepe/api/Config.h>
-#include <crepe/facade/DB.h>
-#include <crepe/util/Log.h>
-
-using namespace crepe;
-using namespace std;
-
-// run before main
-static auto _ = []() {
- auto & cfg = Config::get_instance();
- cfg.log.level = Log::Level::TRACE;
- return 0;
-}();
-
-int main() {
- dbg_trace();
-
- DB db("file.db");
-
- const char * test_key = "test-key";
- string test_data = "Hello world!";
-
- dbg_logf("DB has key = {}", db.has(test_key));
-
- db.set(test_key, test_data);
-
- dbg_logf("key = \"{}\"", db.get(test_key));
-
- return 0;
-}
diff --git a/src/example/ecs.cpp b/src/example/ecs.cpp
deleted file mode 100644
index 5f83da1..0000000
--- a/src/example/ecs.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-#include <iostream>
-
-#include <crepe/ComponentManager.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/api/Metadata.h>
-#include <crepe/api/Transform.h>
-
-using namespace crepe;
-using namespace std;
-
-int main() {
- ComponentManager mgr{};
-
- // Create a few GameObjects
- try {
- GameObject body = mgr.new_object("body", "person", Vector2{0, 0}, 0, 1);
- GameObject right_leg
- = mgr.new_object("rightLeg", "person", Vector2{1, 1}, 0, 1);
- GameObject left_leg
- = mgr.new_object("leftLeg", "person", Vector2{1, 1}, 0, 1);
- GameObject right_foot
- = mgr.new_object("rightFoot", "person", Vector2{2, 2}, 0, 1);
- GameObject left_foot
- = mgr.new_object("leftFoot", "person", Vector2{2, 2}, 0, 1);
-
- // Set the parent of each GameObject
- right_foot.set_parent(right_leg);
- left_foot.set_parent(left_leg);
- right_leg.set_parent(body);
- left_leg.set_parent(body);
-
- // Adding a second Transform component is not allowed and will invoke an exception
- body.add_component<Transform>(Vector2{10, 10}, 0, 1);
- } catch (const exception & e) {
- cerr << e.what() << endl;
- }
-
- // Get the Metadata and Transform components of each GameObject
- vector<reference_wrapper<Metadata>> metadata
- = mgr.get_components_by_type<Metadata>();
- vector<reference_wrapper<Transform>> transform
- = mgr.get_components_by_type<Transform>();
-
- // Print the Metadata and Transform components
- for (auto & m : metadata) {
- cout << "Id: " << m.get().game_object_id << " Name: " << m.get().name
- << " Tag: " << m.get().tag << " Parent: " << m.get().parent
- << " Children: ";
- for (auto & c : m.get().children) {
- cout << c << " ";
- }
- cout << endl;
- }
- for (auto & t : transform) {
- cout << "Id: " << t.get().game_object_id << " Position: ["
- << t.get().position.x << ", " << t.get().position.y << "]" << endl;
- }
-
- return 0;
-}
diff --git a/src/example/game.cpp b/src/example/game.cpp
new file mode 100644
index 0000000..22effd2
--- /dev/null
+++ b/src/example/game.cpp
@@ -0,0 +1,292 @@
+#include "api/CircleCollider.h"
+#include "api/ParticleEmitter.h"
+#include "api/Scene.h"
+#include "manager/ComponentManager.h"
+#include "manager/Mediator.h"
+#include "types.h"
+#include <crepe/api/BoxCollider.h>
+#include <crepe/api/Camera.h>
+#include <crepe/api/Color.h>
+#include <crepe/api/Event.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/LoopManager.h>
+#include <crepe/api/Rigidbody.h>
+#include <crepe/api/Script.h>
+#include <crepe/api/Sprite.h>
+#include <crepe/api/Transform.h>
+#include <crepe/api/Vector2.h>
+
+using namespace crepe;
+
+using namespace std;
+
+class MyScript1 : public Script {
+ bool flip = false;
+ bool oncollision(const CollisionEvent & test) {
+ Log::logf("Box {} script on_collision()", test.info.this_collider.game_object_id);
+ return true;
+ }
+ bool keypressed(const KeyPressEvent & test) {
+ Log::logf("Box script keypressed()");
+ switch (test.key) {
+ case Keycode::A: {
+ Rigidbody & tf = this->get_component<Rigidbody>();
+ tf.data.linear_velocity.x -= 1;
+ break;
+ }
+ case Keycode::W: {
+ Rigidbody & tf = this->get_component<Rigidbody>();
+ // tf.data.linear_velocity.y -= 1;
+ tf.add_force_linear({0, -1});
+ break;
+ }
+ case Keycode::S: {
+ Rigidbody & tf = this->get_component<Rigidbody>();
+ tf.data.linear_velocity.y += 1;
+ break;
+ }
+ case Keycode::D: {
+ Rigidbody & tf = this->get_component<Rigidbody>();
+ tf.data.linear_velocity.x += 1;
+ break;
+ }
+ case Keycode::E: {
+ if (flip) {
+ flip = false;
+ this->get_component<BoxCollider>().active = true;
+ this->get_components<Sprite>()[0].get().active = true;
+ this->get_component<CircleCollider>().active = false;
+ this->get_components<Sprite>()[1].get().active = false;
+ } else {
+ flip = true;
+ this->get_component<BoxCollider>().active = false;
+ this->get_components<Sprite>()[0].get().active = false;
+ this->get_component<CircleCollider>().active = true;
+ this->get_components<Sprite>()[1].get().active = true;
+ }
+
+ //add collider switch
+ break;
+ }
+ case Keycode::Q: {
+ Rigidbody & rg = this->get_component<Rigidbody>();
+ rg.data.angular_velocity = 1;
+ break;
+ }
+ default:
+ break;
+ }
+ return false;
+ }
+
+ void init() {
+ Log::logf("init");
+ subscribe<CollisionEvent>(
+ [this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); });
+ subscribe<KeyPressEvent>(
+ [this](const KeyPressEvent & ev) -> bool { return this->keypressed(ev); });
+ }
+ void update() {
+ Rigidbody & tf = this->get_component<Rigidbody>();
+ Log::logf("linear_velocity.x {}", tf.data.linear_velocity.x);
+ Log::logf("linear_velocity.y {}", tf.data.linear_velocity.y);
+ // tf.data.linear_velocity = {0,0};
+ }
+};
+
+class MyScript2 : public Script {
+ bool flip = false;
+ bool oncollision(const CollisionEvent & test) {
+ Log::logf("Box {} script on_collision()", test.info.this_collider.game_object_id);
+ return true;
+ }
+ bool keypressed(const KeyPressEvent & test) {
+ Log::logf("Box script keypressed()");
+ switch (test.key) {
+ case Keycode::LEFT: {
+ Transform & tf = this->get_component<Transform>();
+ tf.position.x -= 1;
+ break;
+ }
+ case Keycode::UP: {
+ Transform & tf = this->get_component<Transform>();
+ tf.position.y -= 1;
+ break;
+ }
+ case Keycode::DOWN: {
+ Transform & tf = this->get_component<Transform>();
+ tf.position.y += 1;
+ break;
+ }
+ case Keycode::RIGHT: {
+ Transform & tf = this->get_component<Transform>();
+ tf.position.x += 1;
+ break;
+ }
+ case Keycode::PAUSE: {
+ if (flip) {
+ flip = false;
+ this->get_component<BoxCollider>().active = true;
+ this->get_components<Sprite>()[0].get().active = true;
+ this->get_component<CircleCollider>().active = false;
+ this->get_components<Sprite>()[1].get().active = false;
+ } else {
+ flip = true;
+ this->get_component<BoxCollider>().active = false;
+ this->get_components<Sprite>()[0].get().active = false;
+ this->get_component<CircleCollider>().active = true;
+ this->get_components<Sprite>()[1].get().active = true;
+ }
+
+ //add collider switch
+ break;
+ }
+ default:
+ break;
+ }
+ return false;
+ }
+
+ void init() {
+ Log::logf("init");
+ subscribe<CollisionEvent>(
+ [this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); });
+ subscribe<KeyPressEvent>(
+ [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() {
+
+ Color color(0, 0, 0, 255);
+
+ float screen_size_width = 320;
+ float screen_size_height = 240;
+ float world_collider = 1000;
+ //define playable world
+ GameObject world = new_object(
+ "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1);
+ world.add_component<Rigidbody>(Rigidbody::Data{
+ .mass = 0,
+ .gravity_scale = 0,
+ .body_type = Rigidbody::BodyType::STATIC,
+ .offset = {0, 0},
+ });
+ world.add_component<BoxCollider>(
+ vec2{world_collider, world_collider},
+ vec2{0, 0 - (screen_size_height / 2 + world_collider / 2)}); // Top
+ world.add_component<BoxCollider>(
+ vec2{world_collider, world_collider},
+ vec2{0, screen_size_height / 2 + world_collider / 2}); // Bottom
+ world.add_component<BoxCollider>(
+ vec2{world_collider, world_collider},
+ vec2{0 - (screen_size_width / 2 + world_collider / 2), 0}); // Left
+ world.add_component<BoxCollider>(
+ vec2{world_collider, world_collider},
+ vec2{screen_size_width / 2 + world_collider / 2, 0}); // right
+ world.add_component<Camera>(
+ ivec2{static_cast<int>(screen_size_width), static_cast<int>(screen_size_height)},
+ vec2{screen_size_width, screen_size_height},
+ Camera::Data{
+ .bg_color = Color::WHITE,
+ .zoom = 1,
+ });
+
+ GameObject game_object1 = new_object(
+ "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1);
+ game_object1.add_component<Rigidbody>(Rigidbody::Data{
+ .mass = 1,
+ .gravity_scale = 1,
+ .body_type = Rigidbody::BodyType::DYNAMIC,
+ .linear_velocity = {0, 1},
+ .constraints = {0, 0, 0},
+ .elastisity_coefficient = 0,
+ .offset = {0, 0},
+ });
+ // add box with boxcollider
+ game_object1.add_component<BoxCollider>(vec2{20, 20});
+ game_object1.add_component<BehaviorScript>().set_script<MyScript1>();
+
+ Asset img1{"asset/texture/square.png"};
+ game_object1.add_component<Sprite>(img1, Sprite::Data{
+ .size = {20, 20},
+ });
+
+ //add circle with cirlcecollider deactiveated
+ game_object1.add_component<CircleCollider>(10).active = false;
+ Asset img2{"asset/texture/circle.png"};
+ game_object1
+ .add_component<Sprite>(img2,
+ Sprite::Data{
+ .size = {20, 20},
+ })
+ .active
+ = false;
+
+ GameObject game_object2 = new_object(
+ "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1);
+ game_object2.add_component<Rigidbody>(Rigidbody::Data{
+ .mass = 1,
+ .gravity_scale = 0,
+ .body_type = Rigidbody::BodyType::STATIC,
+ .linear_velocity = {0, 0},
+ .constraints = {0, 0, 0},
+ .elastisity_coefficient = 1,
+ .offset = {0, 0},
+ });
+ // add box with boxcollider
+ game_object2.add_component<BoxCollider>(vec2{20, 20});
+ game_object2.add_component<BehaviorScript>().set_script<MyScript2>();
+
+ game_object2.add_component<Sprite>(img1, Sprite::Data{
+ .size = {20, 20},
+ });
+
+ //add circle with cirlcecollider deactiveated
+ game_object2.add_component<CircleCollider>(10).active = false;
+
+ game_object2
+ .add_component<Sprite>(img2,
+ Sprite::Data{
+ .size = {20, 20},
+ })
+ .active
+ = false;
+ Asset img5{"asset/texture/square.png"};
+
+ GameObject particle = new_object(
+ "Name", "Tag", vec2{screen_size_width / 2, screen_size_height / 2}, 0, 1);
+ auto & particle_image = particle.add_component<Sprite>(img5, Sprite::Data{
+ .size = {5, 5},
+ });
+ auto & test
+ = particle.add_component<ParticleEmitter>(particle_image, ParticleEmitter::Data{
+ .offset = {0, 0},
+ .max_particles = 256,
+ .emission_rate = 1,
+ .min_speed = 10,
+ .max_speed = 20,
+ .min_angle = -20,
+ .max_angle = 20,
+ .begin_lifespan = 0,
+ .end_lifespan = 5,
+ });
+ }
+
+ string get_name() const { return "scene1"; }
+};
+
+int main(int argc, char * argv[]) {
+
+ LoopManager gameloop;
+ gameloop.add_scene<ConcreteScene1>();
+ gameloop.start();
+ return 0;
+}
diff --git a/src/example/gameloop.cpp b/src/example/gameloop.cpp
deleted file mode 100644
index a676f20..0000000
--- a/src/example/gameloop.cpp
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "crepe/api/LoopManager.h"
-using namespace crepe;
-int main() {
- LoopManager gameloop;
- gameloop.start();
- return 1;
-}
diff --git a/src/example/loadfont.cpp b/src/example/loadfont.cpp
new file mode 100644
index 0000000..e459332
--- /dev/null
+++ b/src/example/loadfont.cpp
@@ -0,0 +1,49 @@
+#include <SDL2/SDL_ttf.h>
+#include <crepe/api/Asset.h>
+#include <crepe/api/Text.h>
+#include <crepe/facade/Font.h>
+#include <crepe/facade/FontFacade.h>
+#include <crepe/facade/SDLContext.h>
+#include <crepe/manager/Mediator.h>
+#include <crepe/manager/ResourceManager.h>
+#include <exception>
+#include <iostream>
+#include <memory>
+#include <optional>
+using namespace crepe;
+int main() {
+
+ // SDLFontContext font_facade;
+ Mediator mediator;
+ FontFacade font_facade{};
+ SDLContext sdl_context{mediator};
+ // ComponentManager component_manager{mediator};
+ ResourceManager resource_manager{mediator};
+ try {
+ // Correct way to create a unique pointer for Text
+ std::unique_ptr<Text> label = std::make_unique<Text>(
+ 1, vec2(100, 100), vec2(0, 0), "OpenSymbol", Text::Data{}, "test text");
+ // std::cout << "Path: " << label->font.get_path() << std::endl;
+ Asset asset1 = font_facade.get_font_asset("OpenSymbol");
+ std::cout << asset1.get_path() << std::endl;
+ std::unique_ptr<Text> label2 = std::make_unique<Text>(
+ 1, vec2(100, 100), vec2(0, 0), "fsaafdafsdafsdafsdasfdds", Text::Data{});
+ Asset asset = Asset("test test");
+ label->font.emplace(asset);
+ std::cout << label->font.value().get_path() << std::endl;
+ // label2->font = std::make_optional(asset);
+ // std::cout << "Path: " << label2->font.get_path() << std::endl;
+ ResourceManager & resource_mgr = mediator.resource_manager;
+ const Font & res = resource_manager.get<Font>(label->font.value());
+ // TTF_Font * test_font = res.get_font();
+ // if (test_font == NULL) {
+ // std::cout << "error with font" << std::endl;
+ // } else {
+ // std::cout << "correct font retrieved" << std::endl;
+ // }
+ } catch (const std::exception & e) {
+ std::cout << "Standard exception thrown: " << e.what() << std::endl;
+ }
+
+ return 0;
+}
diff --git a/src/example/log.cpp b/src/example/log.cpp
deleted file mode 100644
index 5baa021..0000000
--- a/src/example/log.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/** \file
- *
- * Standalone example for usage of the logging functions
- */
-
-#include <crepe/api/Config.h>
-#include <crepe/util/Log.h>
-
-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() {
- dbg_trace();
- dbg_log("debug message");
- Log::logf("info message with variable: {}", 3);
- Log::logf(Log::Level::WARNING, "warning");
- Log::logf(Log::Level::ERROR, "error");
-
- return 0;
-}
diff --git a/src/example/particles.cpp b/src/example/particles.cpp
deleted file mode 100644
index b65671a..0000000
--- a/src/example/particles.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-#include <crepe/ComponentManager.h>
-#include <crepe/api/AssetManager.h>
-
-#include <crepe/Component.h>
-#include <crepe/api/Color.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/api/ParticleEmitter.h>
-#include <crepe/api/Rigidbody.h>
-#include <crepe/api/Sprite.h>
-#include <crepe/api/Texture.h>
-#include <crepe/api/Transform.h>
-
-using namespace crepe;
-using namespace std;
-
-int main(int argc, char * argv[]) {
- 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<Sprite>(
- make_shared<Texture>("asset/texture/img.png"), color,
- FlipSettings{true, true});
- game_object.add_component<ParticleEmitter>(ParticleEmitter::Data{
- .position = {0, 0},
- .max_particles = 100,
- .emission_rate = 0,
- .min_speed = 0,
- .max_speed = 0,
- .min_angle = 0,
- .max_angle = 0,
- .begin_lifespan = 0,
- .end_lifespan = 0,
- .force_over_time = Vector2{0, 0},
- .boundary{
- .width = 0,
- .height = 0,
- .offset = Vector2{0, 0},
- .reset_on_exit = false,
- },
- .sprite = test_sprite,
- });
-
- return 0;
-}
diff --git a/src/example/physics.cpp b/src/example/physics.cpp
deleted file mode 100644
index ad663a0..0000000
--- a/src/example/physics.cpp
+++ /dev/null
@@ -1,24 +0,0 @@
-#include <crepe/Component.h>
-#include <crepe/ComponentManager.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/api/Rigidbody.h>
-#include <crepe/api/Transform.h>
-#include <crepe/system/PhysicsSystem.h>
-
-using namespace crepe;
-using namespace std;
-
-int main(int argc, char * argv[]) {
- ComponentManager mgr{};
-
- GameObject game_object = mgr.new_object("Name", "Tag", Vector2{0, 0}, 0, 0);
- game_object.add_component<Rigidbody>(Rigidbody::Data{
- .mass = 1,
- .gravity_scale = 1,
- .body_type = Rigidbody::BodyType::DYNAMIC,
- .constraints = {0, 0, 0},
- .use_gravity = true,
- .bounce = false,
- });
- return 0;
-}
diff --git a/src/example/proxy.cpp b/src/example/proxy.cpp
deleted file mode 100644
index 69451f8..0000000
--- a/src/example/proxy.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/** \file
- *
- * Standalone example for usage of the proxy type
- */
-
-#include <crepe/ValueBroker.h>
-#include <crepe/api/Config.h>
-#include <crepe/util/Log.h>
-#include <crepe/util/Proxy.h>
-
-using namespace std;
-using namespace crepe;
-
-void test_ro_ref(const int & val) {}
-void test_rw_ref(int & val) {}
-void test_ro_val(int val) {}
-
-int main() {
- auto & cfg = Config::get_instance();
- cfg.log.level = Log::Level::DEBUG;
-
- int real_value = 0;
-
- ValueBroker<int> broker{
- [&real_value](const int & target) {
- dbg_logf("set {} to {}", real_value, target);
- real_value = target;
- },
- [&real_value]() -> const int & {
- dbg_logf("get {}", real_value);
- return real_value;
- },
- };
-
- Proxy<int> proxy{broker};
-
- broker.set(54);
- proxy = 84;
-
- test_ro_ref(proxy); // this is allowed
- // test_rw_ref(proxy); // this should throw a compile error
- test_ro_val(proxy);
-
- return 0;
-}
diff --git a/src/example/rendering.cpp b/src/example/rendering.cpp
deleted file mode 100644
index 2157bdc..0000000
--- a/src/example/rendering.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-#include "api/Camera.h"
-#include <crepe/ComponentManager.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/system/RenderSystem.h>
-#include <crepe/util/Log.h>
-
-#include <crepe/api/AssetManager.h>
-#include <crepe/api/Color.h>
-#include <crepe/api/Sprite.h>
-#include <crepe/api/Texture.h>
-#include <crepe/api/Transform.h>
-#include <crepe/api/Vector2.h>
-
-#include <chrono>
-#include <memory>
-
-using namespace std;
-using namespace crepe;
-
-int main() {
- dbg_trace();
-
- ComponentManager mgr{};
- RenderSystem sys{mgr};
-
- GameObject obj = mgr.new_object("name", "tag", Vector2{0, 0}, 1, 1);
- GameObject obj1 = mgr.new_object("name", "tag", Vector2{500, 0}, 1, 0.1);
- GameObject obj2 = mgr.new_object("name", "tag", Vector2{800, 0}, 1, 0.1);
-
- // Normal adding components
- {
- Color color(0, 0, 0, 0);
- obj.add_component<Sprite>(
- make_shared<Texture>("asset/texture/img.png"), color,
- FlipSettings{false, false});
- obj.add_component<Camera>(Color::get_red());
- }
- {
- Color color(0, 0, 0, 0);
- obj1.add_component<Sprite>(
- make_shared<Texture>("asset/texture/second.png"), color,
- FlipSettings{true, true});
- }
-
- /*
- {
- Color color(0, 0, 0, 0);
- auto img = mgr.cache<Texture>("asset/texture/second.png");
- obj2.add_component<Sprite>(img, color, FlipSettings{true, true});
- }
- */
-
- auto start = std::chrono::steady_clock::now();
- while (std::chrono::steady_clock::now() - start < std::chrono::seconds(5)) {
- sys.update();
- }
-}
diff --git a/src/example/rendering_particle.cpp b/src/example/rendering_particle.cpp
new file mode 100644
index 0000000..add43f4
--- /dev/null
+++ b/src/example/rendering_particle.cpp
@@ -0,0 +1,73 @@
+#include "api/Asset.h"
+#include <crepe/Component.h>
+#include <crepe/api/Animator.h>
+#include <crepe/api/Button.h>
+#include <crepe/api/Camera.h>
+#include <crepe/api/Color.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/LoopManager.hpp>
+#include <crepe/api/ParticleEmitter.h>
+#include <crepe/api/Rigidbody.h>
+#include <crepe/api/Sprite.h>
+#include <crepe/api/Transform.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/Mediator.h>
+#include <crepe/types.h>
+#include <iostream>
+
+using namespace crepe;
+using namespace std;
+
+class TestScene : public Scene {
+public:
+ void load_scene() {
+
+ cout << "TestScene" << endl;
+ 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);
+
+ Asset img{"asset/spritesheet/spritesheet_test.png"};
+
+ Sprite & test_sprite = game_object.add_component<Sprite>(
+ img, Sprite::Data{
+ .color = color,
+ .flip = Sprite::FlipSettings{false, false},
+ .sorting_in_layer = 2,
+ .order_in_layer = 2,
+ .size = {0, 100},
+ .angle_offset = 0,
+ .position_offset = {0, 0},
+ });
+
+ //auto & anim = game_object.add_component<Animator>(test_sprite,ivec2{32, 64}, uvec2{4,1}, Animator::Data{});
+ //anim.set_anim(0);
+
+ auto & cam = game_object.add_component<Camera>(ivec2{720, 1280}, vec2{400, 400},
+ Camera::Data{
+ .bg_color = Color::WHITE,
+ });
+
+ function<void()> on_click = [&]() { cout << "button clicked" << std::endl; };
+ function<void()> on_enter = [&]() { cout << "enter" << std::endl; };
+ function<void()> on_exit = [&]() { cout << "exit" << std::endl; };
+
+ auto & button
+ = game_object.add_component<Button>(vec2{200, 200}, vec2{0, 0}, on_click, false);
+ button.on_mouse_enter = on_enter;
+ button.on_mouse_exit = on_exit;
+ button.is_toggle = true;
+ button.active = true;
+ }
+
+ string get_name() const { return "TestScene"; };
+};
+
+int main(int argc, char * argv[]) {
+ LoopManager engine;
+ engine.add_scene<TestScene>();
+ engine.start();
+ return 0;
+}
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 <cassert>
-#include <crepe/api/Config.h>
-#include <crepe/api/SaveManager.h>
-#include <crepe/util/Log.h>
-#include <crepe/util/Proxy.h>
-
-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<int> prop = mgr.get<int>(key, 0);
- Proxy<int> val = mgr.get<int>(key, 0);
-
- dbg_logf("val = {}", mgr.get<int>(key).get());
- prop.set(1);
- dbg_logf("val = {}", mgr.get<int>(key).get());
- val = 2;
- dbg_logf("val = {}", mgr.get<int>(key).get());
- mgr.set<int>(key, 3);
- dbg_logf("val = {}", mgr.get<int>(key).get());
-
- dbg_logf("has key = {}", mgr.has(key));
- assert(true == mgr.has(key));
-
- return 0;
-}
diff --git a/src/example/scene_manager.cpp b/src/example/scene_manager.cpp
deleted file mode 100644
index 24ab72e..0000000
--- a/src/example/scene_manager.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-#include <iostream>
-
-#include <crepe/ComponentManager.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/api/Metadata.h>
-#include <crepe/api/Scene.h>
-#include <crepe/api/SceneManager.h>
-#include <crepe/api/Vector2.h>
-
-using namespace crepe;
-using namespace std;
-
-class ConcreteScene1 : public Scene {
-public:
- using Scene::Scene;
-
- void load_scene() {
- auto & mgr = this->component_manager;
- GameObject object1
- = mgr.new_object("scene_1", "tag_scene_1", Vector2{0, 0}, 0, 1);
- GameObject object2
- = mgr.new_object("scene_1", "tag_scene_1", Vector2{1, 0}, 0, 1);
- GameObject object3
- = mgr.new_object("scene_1", "tag_scene_1", Vector2{2, 0}, 0, 1);
- }
-};
-
-class ConcreteScene2 : public Scene {
-public:
- using Scene::Scene;
-
- void load_scene() {
- auto & mgr = this->component_manager;
- GameObject object1
- = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 0}, 0, 1);
- GameObject object2
- = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 1}, 0, 1);
- GameObject object3
- = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 2}, 0, 1);
- GameObject object4
- = mgr.new_object("scene_2", "tag_scene_2", Vector2{0, 3}, 0, 1);
- }
-};
-
-int main() {
- ComponentManager component_mgr{};
- SceneManager scene_mgr{component_mgr};
-
- // Add the scenes to the scene manager
- scene_mgr.add_scene<ConcreteScene1>("scene1");
- scene_mgr.add_scene<ConcreteScene2>("scene2");
-
- // There is no need to call set_next_scene() at the beginning because the
- // first scene will be automatically set as the next scene
-
- // Load scene1 (the first scene added)
- scene_mgr.load_next_scene();
-
- // Get the Metadata components of each GameObject of Scene1
- vector<reference_wrapper<Metadata>> metadata
- = component_mgr.get_components_by_type<Metadata>();
-
- cout << "Metadata components of Scene1:" << endl;
- // Print the Metadata
- for (auto & m : metadata) {
- cout << "Id: " << m.get().game_object_id << " Name: " << m.get().name
- << " Tag: " << m.get().tag << endl;
- }
-
- // Set scene2 as the next scene
- scene_mgr.set_next_scene("scene2");
- // Load scene2
- scene_mgr.load_next_scene();
-
- // Get the Metadata components of each GameObject of Scene2
- metadata = component_mgr.get_components_by_type<Metadata>();
-
- cout << "Metadata components of Scene2:" << endl;
- // Print the Metadata
- for (auto & m : metadata) {
- cout << "Id: " << m.get().game_object_id << " Name: " << m.get().name
- << " Tag: " << m.get().tag << endl;
- }
-
- return 0;
-}
diff --git a/src/example/script.cpp b/src/example/script.cpp
deleted file mode 100644
index a23295b..0000000
--- a/src/example/script.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/** \file
- *
- * Standalone example for usage of the script component and system
- */
-
-#include <crepe/ComponentManager.h>
-#include <crepe/system/ScriptSystem.h>
-#include <crepe/util/Log.h>
-
-#include <crepe/api/BehaviorScript.h>
-#include <crepe/api/Config.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/api/Script.h>
-#include <crepe/api/Transform.h>
-
-using namespace crepe;
-using namespace std;
-
-// Unrelated stuff that is not part of this POC
-int _ = []() {
- // Show dbg_trace() output
- auto & cfg = Config::get_instance();
- cfg.log.level = Log::Level::TRACE;
-
- return 0; // satisfy compiler
-}();
-
-// User-defined script:
-class MyScript : public Script {
- void update() {
- // Retrieve component from the same GameObject this script is on
- Transform & test = get_component<Transform>();
- dbg_logf("Transform({:.2f}, {:.2f})", test.position.x, test.position.y);
- }
-};
-
-int main() {
- ComponentManager component_manager{};
- ScriptSystem system{component_manager};
-
- // Create game object with Transform and BehaviorScript components
- GameObject obj = component_manager.new_object("name");
- obj.add_component<BehaviorScript>().set_script<MyScript>();
-
- // Update all scripts. This should result in MyScript::update being called
- system.update();
-
- return EXIT_SUCCESS;
-}
diff --git a/src/makefile b/src/makefile
index 5f80204..a0e8f02 100644
--- a/src/makefile
+++ b/src/makefile
@@ -1,6 +1,9 @@
.PHONY: FORCE
-FMT := $(shell git ls-files '*.c' '*.cpp' '*.h' '*.hpp')
format: FORCE
- clang-tidy -p build/compile_commands.json --fix-errors $(FMT)
+ $(MAKE) -C .. $@
+
+LINT := $(shell git ls-files '*.c' '*.cpp' '*.h' '*.hpp')
+lint: FORCE
+ clang-tidy -p build/compile_commands.json --fix-errors $(LINT)
diff --git a/src/test/AssetTest.cpp b/src/test/AssetTest.cpp
index 563a253..93fd6a9 100644
--- a/src/test/AssetTest.cpp
+++ b/src/test/AssetTest.cpp
@@ -7,27 +7,15 @@ using namespace std;
using namespace crepe;
using namespace testing;
-class AssetTest : public Test {
-public:
- Config & cfg = Config::get_instance();
- void SetUp() override {
- this->cfg.asset.root_pattern = ".crepe-root";
- }
-};
-
-TEST_F(AssetTest, Existant) {
- ASSERT_NO_THROW(Asset{"asset/texture/img.png"});
-}
+TEST(AssetTest, Existant) { ASSERT_NO_THROW(Asset{"asset/texture/img.png"}); }
-TEST_F(AssetTest, Nonexistant) {
- ASSERT_ANY_THROW(Asset{"asset/nonexistant"});
-}
+TEST(AssetTest, Nonexistant) { ASSERT_ANY_THROW(Asset{"asset/nonexistant"}); }
-TEST_F(AssetTest, Rootless) {
+TEST(AssetTest, Rootless) {
+ Config & cfg = Config::get_instance();
cfg.asset.root_pattern.clear();
string arbitrary = "\\/this is / /../passed through as-is";
Asset asset{arbitrary};
ASSERT_EQ(arbitrary, asset.get_path());
}
-
diff --git a/src/test/AudioTest.cpp b/src/test/AudioTest.cpp
index e181de9..48bba1b 100644
--- a/src/test/AudioTest.cpp
+++ b/src/test/AudioTest.cpp
@@ -1,26 +1,161 @@
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
-#include <crepe/ComponentManager.h>
#include <crepe/api/AudioSource.h>
#include <crepe/api/GameObject.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/ResourceManager.h>
#include <crepe/system/AudioSystem.h>
using namespace std;
+using namespace std::chrono_literals;
using namespace crepe;
using namespace testing;
class AudioTest : public Test {
+private:
+ class TestSoundContext : public SoundContext {
+ public:
+ MOCK_METHOD(SoundHandle, play, (Sound & resource), (override));
+ MOCK_METHOD(void, stop, (const SoundHandle &), (override));
+ MOCK_METHOD(void, set_volume, (const SoundHandle &, float), (override));
+ MOCK_METHOD(void, set_loop, (const SoundHandle &, bool), (override));
+ };
+
+ class TestAudioSystem : public AudioSystem {
+ public:
+ using AudioSystem::AudioSystem;
+ StrictMock<TestSoundContext> context;
+ virtual SoundContext & get_context() { return this->context; }
+ };
+
+private:
+ Mediator mediator;
+ ComponentManager component_manager{mediator};
+ ResourceManager resource_manager{mediator};
+
public:
- ComponentManager component_manager{};
- AudioSystem system {component_manager};
+ TestAudioSystem system{mediator};
+ TestSoundContext & context = system.context;
- void SetUp() override {
- auto & mgr = this->component_manager;
- GameObject entity = mgr.new_object("name");
- entity.add_component<AudioSource>("mwe/audio/sfx1.wav");
- }
+private:
+ GameObject entity = component_manager.new_object("name");
+
+public:
+ AudioSource & component = entity.add_component<AudioSource>("mwe/audio/bgm.ogg");
};
TEST_F(AudioTest, Default) {
+ EXPECT_CALL(context, play(_)).Times(0);
+ EXPECT_CALL(context, stop(_)).Times(0);
+ EXPECT_CALL(context, set_volume(_, _)).Times(0);
+ EXPECT_CALL(context, set_loop(_, _)).Times(0);
+ system.update();
+}
+
+TEST_F(AudioTest, Play) {
+ system.update();
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, play(_)).Times(0);
+ component.play();
+ }
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, play(_)).Times(1);
+ system.update();
+ }
}
+TEST_F(AudioTest, Stop) {
+ system.update();
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, stop(_)).Times(0);
+ component.stop();
+ }
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, stop(_)).Times(1);
+ system.update();
+ }
+}
+
+TEST_F(AudioTest, Volume) {
+ system.update();
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, set_volume(_, _)).Times(0);
+ component.volume += 0.2;
+ }
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, set_volume(_, component.volume)).Times(1);
+ system.update();
+ }
+}
+
+TEST_F(AudioTest, Looping) {
+ system.update();
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, set_loop(_, _)).Times(0);
+ component.loop = !component.loop;
+ }
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, set_loop(_, component.loop)).Times(1);
+ system.update();
+ }
+}
+
+TEST_F(AudioTest, StopOnDeactivate) {
+ system.update();
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, stop(_)).Times(1);
+ component.active = false;
+ system.update();
+ }
+}
+
+TEST_F(AudioTest, PlayOnActive) {
+ component.active = false;
+ component.play_on_awake = true;
+ system.update();
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(context, play(_)).Times(1);
+ component.active = true;
+ system.update();
+ }
+}
+
+TEST_F(AudioTest, PlayImmediately) {
+ component.play_on_awake = false;
+ component.play();
+
+ EXPECT_CALL(context, play(_)).Times(1);
+
+ system.update();
+}
diff --git a/src/test/CMakeLists.txt b/src/test/CMakeLists.txt
index 437c296..11b4ca9 100644
--- a/src/test/CMakeLists.txt
+++ b/src/test/CMakeLists.txt
@@ -1,5 +1,6 @@
target_sources(test_main PUBLIC
main.cpp
+ CollisionTest.cpp
PhysicsTest.cpp
ScriptTest.cpp
ParticleTest.cpp
@@ -7,5 +8,20 @@ target_sources(test_main PUBLIC
AssetTest.cpp
ResourceManagerTest.cpp
OptionalRefTest.cpp
+ RenderSystemTest.cpp
+ EventTest.cpp
+ ECSTest.cpp
+ SceneManagerTest.cpp
+ ValueBrokerTest.cpp
+ DBTest.cpp
+ Vector2Test.cpp
+ LoopManagerTest.cpp
+ LoopTimerTest.cpp
+ InputTest.cpp
+ ScriptEventTest.cpp
+ ScriptSceneTest.cpp
+ Profiling.cpp
+ SaveManagerTest.cpp
+ ScriptSaveManagerTest.cpp
+ ScriptECSTest.cpp
)
-
diff --git a/src/test/CollisionTest.cpp b/src/test/CollisionTest.cpp
new file mode 100644
index 0000000..ff9e7cc
--- /dev/null
+++ b/src/test/CollisionTest.cpp
@@ -0,0 +1,391 @@
+#include "api/BoxCollider.h"
+#include "manager/Mediator.h"
+#include <cmath>
+#include <cstddef>
+#include <gtest/gtest.h>
+
+#define private public
+#define protected public
+
+#include <crepe/api/Event.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Rigidbody.h>
+#include <crepe/api/Script.h>
+#include <crepe/api/Transform.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/manager/Mediator.h>
+#include <crepe/system/CollisionSystem.h>
+#include <crepe/system/ScriptSystem.h>
+#include <crepe/types.h>
+#include <crepe/util/Log.h>
+
+using namespace std;
+using namespace std::chrono_literals;
+using namespace crepe;
+using namespace testing;
+
+class CollisionHandler : public Script {
+public:
+ int box_id;
+ function<void(const CollisionEvent & ev)> test_fn = [](const CollisionEvent & ev) {};
+
+ CollisionHandler(int box_id) { this->box_id = box_id; }
+
+ bool on_collision(const CollisionEvent & ev) {
+ //Log::logf("Box {} script on_collision()", box_id);
+ test_fn(ev);
+ return true;
+ }
+
+ void init() {
+ subscribe<CollisionEvent>(
+ [this](const CollisionEvent & ev) -> bool { return this->on_collision(ev); });
+ }
+ void update() {
+ // Retrieve component from the same GameObject this script is on
+ }
+};
+
+class CollisionTest : public Test {
+public:
+ Mediator m;
+ EventManager event_mgr{m};
+ ComponentManager mgr{m};
+ CollisionSystem collision_sys{m};
+ ScriptSystem script_sys{m};
+
+ GameObject world = mgr.new_object("world", "", {50, 50});
+ GameObject game_object1 = mgr.new_object("object1", "", {50, 50});
+ GameObject game_object2 = mgr.new_object("object2", "", {50, 30});
+
+ CollisionHandler * script_object1_ref = nullptr;
+ CollisionHandler * script_object2_ref = nullptr;
+
+ void SetUp() override {
+ world.add_component<Rigidbody>(Rigidbody::Data{
+ // TODO: remove unrelated properties:
+ .body_type = Rigidbody::BodyType::STATIC,
+ .offset = {0, 0},
+ });
+ // Create a box with an inner size of 10x10 units
+ world.add_component<BoxCollider>(vec2{100, 100}, vec2{0, -100}); // Top
+ world.add_component<BoxCollider>(vec2{100, 100}, vec2{0, 100}); // Bottom
+ world.add_component<BoxCollider>(vec2{100, 100}, vec2{-100, 0}); // Left
+ world.add_component<BoxCollider>(vec2{100, 100}, vec2{100, 0}); // right
+
+ game_object1.add_component<Rigidbody>(Rigidbody::Data{
+ .mass = 1,
+ .gravity_scale = 0.01,
+ .body_type = Rigidbody::BodyType::DYNAMIC,
+ .linear_velocity = {0, 0},
+ .constraints = {0, 0, 0},
+ .elastisity_coefficient = 1,
+ .offset = {0, 0},
+ .collision_layers = {0},
+ });
+ game_object1.add_component<BoxCollider>(vec2{10, 10}, vec2{0, 0});
+ BehaviorScript & script_object1
+ = game_object1.add_component<BehaviorScript>().set_script<CollisionHandler>(1);
+ script_object1_ref = static_cast<CollisionHandler *>(script_object1.script.get());
+ ASSERT_NE(script_object1_ref, nullptr);
+
+ game_object2.add_component<Rigidbody>(Rigidbody::Data{
+ .mass = 1,
+ .gravity_scale = 0.01,
+ .body_type = Rigidbody::BodyType::DYNAMIC,
+ .linear_velocity = {0, 0},
+ .constraints = {0, 0, 0},
+ .elastisity_coefficient = 1,
+ .offset = {0, 0},
+ .collision_layers = {0},
+ });
+ game_object2.add_component<BoxCollider>(vec2{10, 10}, vec2{0, 0});
+ BehaviorScript & script_object2
+ = game_object2.add_component<BehaviorScript>().set_script<CollisionHandler>(2);
+ script_object2_ref = static_cast<CollisionHandler *>(script_object2.script.get());
+ ASSERT_NE(script_object2_ref, nullptr);
+
+ // Ensure Script::init() is called on all BehaviorScript instances
+ script_sys.update();
+ }
+};
+
+TEST_F(CollisionTest, collision_example) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ };
+ EXPECT_FALSE(collision_happend);
+ collision_sys.update();
+ EXPECT_FALSE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_dynamic_both_no_velocity) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, 10);
+ EXPECT_EQ(ev.info.resolution.y, 10);
+ EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ EXPECT_EQ(ev.info.resolution.x, 10);
+ EXPECT_EQ(ev.info.resolution.y, 10);
+ EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH);
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {50, 30};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_dynamic_x_direction_no_velocity) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, -5);
+ EXPECT_EQ(ev.info.resolution.y, 0);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::X_DIRECTION);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ EXPECT_EQ(ev.info.resolution.x, 5);
+ EXPECT_EQ(ev.info.resolution.y, 0);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::X_DIRECTION);
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {45, 30};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_dynamic_y_direction_no_velocity) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, 0);
+ EXPECT_EQ(ev.info.resolution.y, -5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::Y_DIRECTION);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ EXPECT_EQ(ev.info.resolution.x, 0);
+ EXPECT_EQ(ev.info.resolution.y, 5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::Y_DIRECTION);
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {50, 25};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_dynamic_both) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, 10);
+ EXPECT_EQ(ev.info.resolution.y, 10);
+ EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ EXPECT_EQ(ev.info.resolution.x, 10);
+ EXPECT_EQ(ev.info.resolution.y, 10);
+ EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH);
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {50, 30};
+ Rigidbody & rg1 = this->mgr.get_components_by_id<Rigidbody>(1).front().get();
+ rg1.data.linear_velocity = {10, 10};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.linear_velocity = {10, 10};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_dynamic_x_direction) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, -5);
+ EXPECT_EQ(ev.info.resolution.y, 5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::X_DIRECTION);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ EXPECT_EQ(ev.info.resolution.x, 5);
+ EXPECT_EQ(ev.info.resolution.y, -5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::X_DIRECTION);
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {45, 30};
+ Rigidbody & rg1 = this->mgr.get_components_by_id<Rigidbody>(1).front().get();
+ rg1.data.linear_velocity = {10, 10};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.linear_velocity = {10, 10};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_dynamic_y_direction) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, 5);
+ EXPECT_EQ(ev.info.resolution.y, -5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::Y_DIRECTION);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 2);
+ EXPECT_EQ(ev.info.resolution.x, -5);
+ EXPECT_EQ(ev.info.resolution.y, 5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::Y_DIRECTION);
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {50, 25};
+ Rigidbody & rg1 = this->mgr.get_components_by_id<Rigidbody>(1).front().get();
+ rg1.data.linear_velocity = {10, 10};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.linear_velocity = {10, 10};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_static_both) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, 10);
+ EXPECT_EQ(ev.info.resolution.y, 10);
+ EXPECT_EQ(ev.info.resolution_direction, crepe::CollisionSystem::Direction::BOTH);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ // is static should not be called
+ FAIL();
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {50, 30};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.body_type = crepe::Rigidbody::BodyType::STATIC;
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_static_x_direction) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, -5);
+ EXPECT_EQ(ev.info.resolution.y, 5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::X_DIRECTION);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ // is static should not be called
+ FAIL();
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {45, 30};
+ Rigidbody & rg1 = this->mgr.get_components_by_id<Rigidbody>(1).front().get();
+ rg1.data.linear_velocity = {10, 10};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.body_type = crepe::Rigidbody::BodyType::STATIC;
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_static_y_direction) {
+ bool collision_happend = false;
+ script_object1_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.resolution.x, 5);
+ EXPECT_EQ(ev.info.resolution.y, -5);
+ EXPECT_EQ(ev.info.resolution_direction,
+ crepe::CollisionSystem::Direction::Y_DIRECTION);
+ };
+ script_object2_ref->test_fn = [&collision_happend](const CollisionEvent & ev) {
+ // is static should not be called
+ FAIL();
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {50, 25};
+ Rigidbody & rg1 = this->mgr.get_components_by_id<Rigidbody>(1).front().get();
+ rg1.data.linear_velocity = {10, 10};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.body_type = crepe::Rigidbody::BodyType::STATIC;
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
+
+TEST_F(CollisionTest, collision_box_box_static_multiple) { //todo check visually
+ bool collision_happend = false;
+ float offset_value = 0;
+ float resolution = 0;
+ script_object1_ref->test_fn = [&](const CollisionEvent & ev) {
+ collision_happend = true;
+ EXPECT_EQ(ev.info.this_collider.game_object_id, 1);
+ EXPECT_EQ(ev.info.this_collider.offset.x, offset_value);
+ EXPECT_EQ(ev.info.resolution.x, resolution);
+ };
+ script_object2_ref->test_fn = [&](const CollisionEvent & ev) {
+ // is static should not be called
+ FAIL();
+ };
+ EXPECT_FALSE(collision_happend);
+ Transform & tf = this->mgr.get_components_by_id<Transform>(1).front().get();
+ tf.position = {45, 30};
+ Rigidbody & rg1 = this->mgr.get_components_by_id<Rigidbody>(1).front().get();
+ rg1.data.linear_velocity = {10, 10};
+ Rigidbody & rg2 = this->mgr.get_components_by_id<Rigidbody>(2).front().get();
+ rg2.data.body_type = crepe::Rigidbody::BodyType::STATIC;
+ BoxCollider & bxc = this->mgr.get_components_by_id<BoxCollider>(1).front().get();
+ bxc.offset = {5, 0};
+ this->game_object1.add_component<BoxCollider>(vec2{-5, 0}, vec2{10, 10});
+ offset_value = 5;
+ resolution = 10;
+ collision_sys.update();
+ offset_value = -5;
+ resolution = 10;
+ tf.position = {55, 30};
+ collision_sys.update();
+ EXPECT_TRUE(collision_happend);
+}
diff --git a/src/test/DBTest.cpp b/src/test/DBTest.cpp
new file mode 100644
index 0000000..7f2c339
--- /dev/null
+++ b/src/test/DBTest.cpp
@@ -0,0 +1,37 @@
+#include <gtest/gtest.h>
+
+#include <crepe/facade/DB.h>
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class DBTest : public Test {
+public:
+ DB db;
+};
+
+TEST_F(DBTest, ReadWrite) {
+ db.set("foo", "bar");
+ EXPECT_EQ(db.get("foo"), "bar");
+}
+
+TEST_F(DBTest, Nonexistant) {
+ EXPECT_THROW(db.get("foo"), std::out_of_range);
+ db.set("foo", "bar");
+ EXPECT_NO_THROW(db.get("foo"));
+}
+
+TEST_F(DBTest, Has) {
+ EXPECT_EQ(db.has("foo"), false);
+ db.set("foo", "bar");
+ EXPECT_EQ(db.has("foo"), true);
+}
+
+TEST_F(DBTest, MultipleKeys) {
+ db.set("foo", "foo");
+ db.set("bar", "bar");
+
+ EXPECT_EQ(db.get("foo"), "foo");
+ EXPECT_EQ(db.get("bar"), "bar");
+}
diff --git a/src/test/ECSTest.cpp b/src/test/ECSTest.cpp
new file mode 100644
index 0000000..af2b7b0
--- /dev/null
+++ b/src/test/ECSTest.cpp
@@ -0,0 +1,468 @@
+#include <gtest/gtest.h>
+
+#define protected public
+#define private public
+
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Metadata.h>
+#include <crepe/api/Transform.h>
+#include <crepe/api/Vector2.h>
+#include <crepe/manager/ComponentManager.h>
+
+using namespace std;
+using namespace crepe;
+
+class ECSTest : public ::testing::Test {
+ Mediator m;
+
+public:
+ ComponentManager mgr{m};
+
+ class TestComponent : public Component {
+ using Component::Component;
+ };
+};
+
+TEST_F(ECSTest, createGameObject) {
+ GameObject obj = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ EXPECT_EQ(metadata[0].get().name, "body");
+ EXPECT_EQ(metadata[0].get().tag, "person");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+ EXPECT_EQ(transform[0].get().rotation, 0);
+ EXPECT_EQ(transform[0].get().scale, 1);
+}
+
+TEST_F(ECSTest, deleteAllGameObjects) {
+ GameObject obj0 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ GameObject obj1 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+
+ mgr.delete_all_components();
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 0);
+ EXPECT_EQ(transform.size(), 0);
+
+ GameObject obj2 = mgr.new_object("body2", "person2", vec2{1, 0}, 5, 1);
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[0].get().name, "body2");
+ EXPECT_EQ(metadata[0].get().tag, "person2");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+
+ EXPECT_EQ(transform[0].get().game_object_id, 0);
+ EXPECT_EQ(transform[0].get().position.x, 1);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+ EXPECT_EQ(transform[0].get().rotation, 5);
+ EXPECT_EQ(transform[0].get().scale, 1);
+}
+
+TEST_F(ECSTest, deleteGameObject) {
+ GameObject obj0 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ GameObject obj1 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+
+ mgr.delete_all_components_of_id(0);
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 1);
+ EXPECT_EQ(metadata[0].get().name, "body");
+ EXPECT_EQ(metadata[0].get().tag, "person");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+
+ EXPECT_EQ(transform[0].get().game_object_id, 1);
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+ EXPECT_EQ(transform[0].get().rotation, 0);
+ EXPECT_EQ(transform[0].get().scale, 1);
+}
+
+TEST_F(ECSTest, manyGameObjects) {
+ for (int i = 0; i < 5000; i++) {
+ GameObject obj = mgr.new_object("body", "person", vec2{0, 0}, 0, i);
+ }
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 5000);
+ EXPECT_EQ(transform.size(), 5000);
+ for (int i = 0; i < 5000; i++) {
+ EXPECT_EQ(metadata[i].get().game_object_id, i);
+ EXPECT_EQ(metadata[i].get().name, "body");
+ EXPECT_EQ(metadata[i].get().tag, "person");
+ EXPECT_EQ(metadata[i].get().parent, -1);
+ EXPECT_EQ(metadata[i].get().children.size(), 0);
+
+ EXPECT_EQ(transform[i].get().game_object_id, i);
+ EXPECT_EQ(transform[i].get().position.x, 0);
+ EXPECT_EQ(transform[i].get().position.y, 0);
+ EXPECT_EQ(transform[i].get().rotation, 0);
+ EXPECT_EQ(transform[i].get().scale, i);
+ }
+
+ mgr.delete_components<Metadata>();
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 0);
+ EXPECT_EQ(transform.size(), 5000);
+
+ for (int i = 0; i < 10000 - 5000; i++) {
+ string tag = "person" + to_string(i);
+ GameObject obj = mgr.new_object("body", tag, vec2{0, 0}, i, 0);
+ }
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 10000 - 5000);
+ EXPECT_EQ(transform.size(), 10000);
+
+ for (int i = 0; i < 10000 - 5000; i++) {
+ EXPECT_EQ(metadata[i].get().game_object_id, i + 5000);
+ EXPECT_EQ(metadata[i].get().name, "body");
+ EXPECT_EQ(metadata[i].get().tag, "person" + to_string(i));
+ EXPECT_EQ(metadata[i].get().parent, -1);
+ EXPECT_EQ(metadata[i].get().children.size(), 0);
+
+ EXPECT_EQ(transform[i].get().game_object_id, i);
+ EXPECT_EQ(transform[i].get().position.x, 0);
+ EXPECT_EQ(transform[i].get().position.y, 0);
+ EXPECT_EQ(transform[i].get().rotation, 0);
+ EXPECT_EQ(transform[i].get().scale, i);
+ }
+
+ mgr.delete_all_components();
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 0);
+ EXPECT_EQ(transform.size(), 0);
+
+ for (int i = 0; i < 10000; i++) {
+ string name = "body" + to_string(i);
+ GameObject obj = mgr.new_object(name, "person", vec2{0, 0}, 0, 0);
+ }
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 10000);
+ EXPECT_EQ(transform.size(), 10000);
+
+ for (int i = 0; i < 10000; i++) {
+ EXPECT_EQ(metadata[i].get().game_object_id, i);
+ EXPECT_EQ(metadata[i].get().name, "body" + to_string(i));
+ EXPECT_EQ(metadata[i].get().tag, "person");
+ EXPECT_EQ(metadata[i].get().parent, -1);
+ EXPECT_EQ(metadata[i].get().children.size(), 0);
+
+ EXPECT_EQ(transform[i].get().game_object_id, i);
+ EXPECT_EQ(transform[i].get().position.x, 0);
+ EXPECT_EQ(transform[i].get().position.y, 0);
+ EXPECT_EQ(transform[i].get().rotation, 0);
+ EXPECT_EQ(transform[i].get().scale, 0);
+ }
+}
+
+TEST_F(ECSTest, getComponentsByID) {
+ GameObject obj0 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ GameObject obj1 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_id<Metadata>(0);
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_id<Transform>(1);
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[0].get().name, "body");
+ EXPECT_EQ(metadata[0].get().tag, "person");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+
+ EXPECT_EQ(transform[0].get().game_object_id, 1);
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+ EXPECT_EQ(transform[0].get().rotation, 0);
+ EXPECT_EQ(transform[0].get().scale, 1);
+}
+
+TEST_F(ECSTest, tooMuchComponents) {
+ try {
+ GameObject obj0 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ obj0.add_component<Transform>(vec2{10, 10}, 0, 1);
+ } catch (const exception & e) {
+ EXPECT_EQ(e.what(),
+ string("Exceeded maximum number of instances for this component type"));
+ }
+
+ try {
+ GameObject obj1 = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ obj1.add_component<Metadata>("body", "person");
+ } catch (const exception & e) {
+ EXPECT_EQ(e.what(),
+ string("Exceeded maximum number of instances for this component type"));
+ }
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+
+ EXPECT_EQ(metadata.size(), 2);
+ EXPECT_EQ(metadata[0].get().name, "body");
+ EXPECT_EQ(metadata[1].get().name, "body");
+}
+
+TEST_F(ECSTest, partentChild) {
+ {
+ GameObject body = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ GameObject right_leg = mgr.new_object("rightLeg", "person", vec2{1, 1}, 0, 1);
+ GameObject left_leg = mgr.new_object("leftLeg", "person", vec2{1, 1}, 0, 1);
+ GameObject right_foot = mgr.new_object("rightFoot", "person", vec2{2, 2}, 0, 1);
+ GameObject left_foot = mgr.new_object("leftFoot", "person", vec2{2, 2}, 0, 1);
+
+ // Set the parent of each GameObject
+ right_foot.set_parent(right_leg);
+ left_foot.set_parent(left_leg);
+ right_leg.set_parent(body);
+ left_leg.set_parent(body);
+ }
+
+ // Get the Metadata and Transform components of each GameObject
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+
+ // Check IDs
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[1].get().game_object_id, 1);
+ EXPECT_EQ(metadata[2].get().game_object_id, 2);
+ EXPECT_EQ(metadata[3].get().game_object_id, 3);
+ EXPECT_EQ(metadata[4].get().game_object_id, 4);
+
+ // Check the parent-child relationships
+ EXPECT_EQ(metadata[0].get().name, "body");
+ EXPECT_EQ(metadata[1].get().name, "rightLeg");
+ EXPECT_EQ(metadata[2].get().name, "leftLeg");
+ EXPECT_EQ(metadata[3].get().name, "rightFoot");
+ EXPECT_EQ(metadata[4].get().name, "leftFoot");
+
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[1].get().parent, 0);
+ EXPECT_EQ(metadata[2].get().parent, 0);
+ EXPECT_EQ(metadata[3].get().parent, 1);
+ EXPECT_EQ(metadata[4].get().parent, 2);
+
+ EXPECT_EQ(metadata[0].get().children.size(), 2);
+ EXPECT_EQ(metadata[1].get().children.size(), 1);
+ EXPECT_EQ(metadata[2].get().children.size(), 1);
+ EXPECT_EQ(metadata[3].get().children.size(), 0);
+ EXPECT_EQ(metadata[4].get().children.size(), 0);
+
+ EXPECT_EQ(metadata[0].get().children[0], 1);
+ EXPECT_EQ(metadata[0].get().children[1], 2);
+ EXPECT_EQ(metadata[1].get().children[0], 3);
+ EXPECT_EQ(metadata[2].get().children[0], 4);
+}
+
+TEST_F(ECSTest, persistent) {
+ GameObject obj0 = mgr.new_object("obj0", "obj0", vec2{0, 0}, 0, 1);
+ GameObject obj1 = mgr.new_object("obj1", "obj1", vec2{0, 0}, 0, 1);
+ obj1.set_persistent();
+ GameObject obj2 = mgr.new_object("obj2", "obj2", vec2{0, 0}, 0, 1);
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 3);
+ EXPECT_EQ(transform.size(), 3);
+
+ mgr.delete_components_by_id<Metadata>(1);
+ mgr.delete_components<Metadata>();
+ mgr.delete_all_components_of_id(1);
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 3);
+
+ mgr.delete_all_components();
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 1);
+ EXPECT_EQ(metadata[0].get().name, "obj1");
+ EXPECT_EQ(metadata[0].get().tag, "obj1");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+
+ EXPECT_EQ(transform[0].get().game_object_id, 1);
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+
+ GameObject obj3 = mgr.new_object("obj3", "obj3", vec2{0, 0}, 0, 5);
+ GameObject obj4 = mgr.new_object("obj4", "obj4", vec2{0, 0}, 0, 5);
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 3);
+ EXPECT_EQ(transform.size(), 3);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[0].get().name, "obj3");
+
+ EXPECT_EQ(metadata[1].get().game_object_id, 1);
+ EXPECT_EQ(metadata[1].get().name, "obj1");
+
+ EXPECT_EQ(metadata[2].get().game_object_id, 2);
+ EXPECT_EQ(metadata[2].get().name, "obj4");
+
+ EXPECT_EQ(transform[0].get().game_object_id, 0);
+ EXPECT_EQ(transform[0].get().scale, 5);
+
+ EXPECT_EQ(transform[1].get().game_object_id, 1);
+ EXPECT_EQ(transform[1].get().scale, 1);
+
+ EXPECT_EQ(transform[2].get().game_object_id, 2);
+ EXPECT_EQ(transform[2].get().scale, 5);
+}
+
+TEST_F(ECSTest, resetPersistent) {
+ GameObject obj0 = mgr.new_object("obj0", "obj0", vec2{0, 0}, 0, 1);
+ GameObject obj1 = mgr.new_object("obj1", "obj1", vec2{0, 0}, 0, 1);
+ obj1.set_persistent();
+ GameObject obj2 = mgr.new_object("obj2", "obj2", vec2{0, 0}, 0, 1);
+
+ vector<reference_wrapper<Metadata>> metadata = mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 3);
+ EXPECT_EQ(transform.size(), 3);
+
+ mgr.delete_all_components();
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ vector<reference_wrapper<Metadata>> metadata_id = mgr.get_components_by_id<Metadata>(1);
+
+ EXPECT_EQ(metadata_id.size(), 1);
+ EXPECT_EQ(metadata_id[0].get().game_object_id, 1);
+ EXPECT_EQ(metadata_id[0].get().name, "obj1");
+
+ mgr.set_persistent(1, false);
+ mgr.delete_all_components();
+
+ metadata = mgr.get_components_by_type<Metadata>();
+ transform = mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 0);
+ EXPECT_EQ(transform.size(), 0);
+}
+
+TEST_F(ECSTest, IDByName) {
+ GameObject foo = mgr.new_object("foo");
+ GameObject bar = mgr.new_object("bar");
+
+ {
+ auto objects = mgr.get_objects_by_name("");
+ EXPECT_EQ(objects.size(), 0);
+ }
+
+ {
+ auto objects = mgr.get_objects_by_name("foo");
+ EXPECT_EQ(objects.size(), 1);
+ EXPECT_TRUE(objects.contains(foo.id));
+ }
+}
+
+TEST_F(ECSTest, IDByTag) {
+ GameObject foo = mgr.new_object("foo", "common tag");
+ GameObject bar = mgr.new_object("bar", "common tag");
+
+ {
+ auto objects = mgr.get_objects_by_tag("");
+ EXPECT_EQ(objects.size(), 0);
+ }
+
+ {
+ auto objects = mgr.get_objects_by_tag("common tag");
+ EXPECT_EQ(objects.size(), 2);
+ EXPECT_TRUE(objects.contains(foo.id));
+ EXPECT_TRUE(objects.contains(bar.id));
+ }
+}
+
+TEST_F(ECSTest, ComponentsByName) {
+ GameObject foo = mgr.new_object("foo");
+ foo.add_component<TestComponent>();
+ GameObject bar = mgr.new_object("bar");
+ bar.add_component<TestComponent>();
+ bar.add_component<TestComponent>();
+
+ {
+ auto objects = mgr.get_components_by_name<TestComponent>("");
+ EXPECT_EQ(objects.size(), 0);
+ }
+
+ {
+ auto objects = mgr.get_components_by_name<TestComponent>("foo");
+ EXPECT_EQ(objects.size(), 1);
+ }
+
+ {
+ auto objects = mgr.get_components_by_name<TestComponent>("bar");
+ EXPECT_EQ(objects.size(), 2);
+ }
+}
+
+TEST_F(ECSTest, ComponentsByTag) {
+ GameObject foo = mgr.new_object("foo", "common tag");
+ foo.add_component<TestComponent>();
+ GameObject bar = mgr.new_object("bar", "common tag");
+ bar.add_component<TestComponent>();
+ bar.add_component<TestComponent>();
+
+ {
+ auto objects = mgr.get_components_by_tag<TestComponent>("");
+ EXPECT_EQ(objects.size(), 0);
+ }
+
+ {
+ auto objects = mgr.get_components_by_tag<TestComponent>("common tag");
+ EXPECT_EQ(objects.size(), 3);
+ }
+}
diff --git a/src/test/EventTest.cpp b/src/test/EventTest.cpp
new file mode 100644
index 0000000..f8be3fe
--- /dev/null
+++ b/src/test/EventTest.cpp
@@ -0,0 +1,228 @@
+#include <crepe/api/Event.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/manager/Mediator.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+using namespace std;
+using namespace std::chrono_literals;
+using namespace crepe;
+
+class EventManagerTest : public ::testing::Test {
+protected:
+ Mediator mediator;
+ EventManager event_mgr{mediator};
+ void SetUp() override {
+ // Clear any existing subscriptions or events before each test
+ event_mgr.clear();
+ }
+
+ void TearDown() override {
+ // Ensure cleanup after each test
+ event_mgr.clear();
+ }
+};
+TEST_F(EventManagerTest, EventSubscription) {
+ EventHandler<KeyPressEvent> key_handler = [](const KeyPressEvent & e) { return true; };
+
+ // Subscribe to KeyPressEvent
+ event_mgr.subscribe<KeyPressEvent>(key_handler, 1);
+
+ // Verify subscription (not directly verifiable; test by triggering event)
+
+ event_mgr.trigger_event<KeyPressEvent>(
+ KeyPressEvent{
+ .repeat = true,
+ .key = Keycode::A,
+ },
+ 1);
+ event_mgr.trigger_event<KeyPressEvent>(
+ KeyPressEvent{
+ .repeat = true,
+ .key = Keycode::A,
+
+ },
+ EventManager::CHANNEL_ALL);
+}
+TEST_F(EventManagerTest, EventManagerTest_trigger_all_channels) {
+ bool triggered = false;
+
+ EventHandler<MouseClickEvent> mouse_handler = [&](const MouseClickEvent & e) {
+ triggered = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false;
+ };
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler, EventManager::CHANNEL_ALL);
+
+ MouseClickEvent click_event{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE};
+ event_mgr.trigger_event<MouseClickEvent>(click_event, EventManager::CHANNEL_ALL);
+
+ EXPECT_TRUE(triggered);
+}
+TEST_F(EventManagerTest, EventManagerTest_trigger_one_channel) {
+ bool triggered = false;
+ int test_channel = 1;
+ EventHandler<MouseClickEvent> mouse_handler = [&](const MouseClickEvent & e) {
+ triggered = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false;
+ };
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler, test_channel);
+
+ MouseClickEvent click_event{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE};
+ event_mgr.trigger_event<MouseClickEvent>(click_event, EventManager::CHANNEL_ALL);
+
+ EXPECT_FALSE(triggered);
+ event_mgr.trigger_event<MouseClickEvent>(click_event, test_channel);
+}
+
+TEST_F(EventManagerTest, EventManagerTest_callback_propagation) {
+
+ // Flags to track handler calls
+ bool triggered_true = false;
+ bool triggered_false = false;
+
+ // Handlers
+ EventHandler<MouseClickEvent> mouse_handler_true = [&](const MouseClickEvent & e) {
+ triggered_true = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return true; // Stops propagation
+ };
+
+ EventHandler<MouseClickEvent> mouse_handler_false = [&](const MouseClickEvent & e) {
+ triggered_false = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false; // Allows propagation
+ };
+
+ // Test event
+ MouseClickEvent click_event{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE};
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler_true, EventManager::CHANNEL_ALL);
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler_false, EventManager::CHANNEL_ALL);
+
+ // Trigger event
+ event_mgr.trigger_event<MouseClickEvent>(click_event, EventManager::CHANNEL_ALL);
+
+ // Check that only the true handler was triggered
+ EXPECT_TRUE(triggered_true);
+ EXPECT_FALSE(triggered_false);
+
+ // Reset and clear
+ triggered_true = false;
+ triggered_false = false;
+ event_mgr.clear();
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler_false, EventManager::CHANNEL_ALL);
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler_true, EventManager::CHANNEL_ALL);
+
+ // Trigger event again
+ event_mgr.trigger_event<MouseClickEvent>(click_event, EventManager::CHANNEL_ALL);
+
+ // Check that both handlers were triggered
+ EXPECT_TRUE(triggered_true);
+ EXPECT_TRUE(triggered_false);
+}
+
+TEST_F(EventManagerTest, EventManagerTest_queue_dispatch) {
+ bool triggered1 = false;
+ bool triggered2 = false;
+ int test_channel = 1;
+ EventHandler<MouseClickEvent> mouse_handler1 = [&](const MouseClickEvent & e) {
+ triggered1 = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false; // Allows propagation
+ };
+ EventHandler<MouseClickEvent> mouse_handler2 = [&](const MouseClickEvent & e) {
+ triggered2 = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false; // Allows propagation
+ };
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler1);
+ event_mgr.subscribe<MouseClickEvent>(mouse_handler2, test_channel);
+
+ event_mgr.queue_event<MouseClickEvent>(
+ MouseClickEvent{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE});
+ event_mgr.queue_event<MouseClickEvent>(
+ MouseClickEvent{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE},
+ test_channel);
+ event_mgr.dispatch_events();
+ EXPECT_TRUE(triggered1);
+ EXPECT_TRUE(triggered2);
+}
+
+TEST_F(EventManagerTest, EventManagerTest_unsubscribe) {
+
+ // Flags to track if handlers are triggered
+ bool triggered1 = false;
+ bool triggered2 = false;
+
+ // Define EventHandlers
+ EventHandler<MouseClickEvent> mouse_handler1 = [&](const MouseClickEvent & e) {
+ triggered1 = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false; // Allows propagation
+ };
+
+ EventHandler<MouseClickEvent> mouse_handler2 = [&](const MouseClickEvent & e) {
+ triggered2 = true;
+ EXPECT_EQ(e.mouse_pos.x, 100);
+ EXPECT_EQ(e.mouse_pos.y, 200);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false; // Allows propagation
+ };
+ // Subscribe handlers
+ subscription_t handler1_id = event_mgr.subscribe<MouseClickEvent>(mouse_handler1);
+ subscription_t handler2_id = event_mgr.subscribe<MouseClickEvent>(mouse_handler2);
+
+ // Queue events
+ event_mgr.queue_event<MouseClickEvent>(
+ MouseClickEvent{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE});
+
+ // Dispatch events - both handlers should be triggered
+ event_mgr.dispatch_events();
+ EXPECT_TRUE(triggered1); // Handler 1 should be triggered
+ EXPECT_TRUE(triggered2); // Handler 2 should be triggered
+
+ // Reset flags
+ triggered1 = false;
+ triggered2 = false;
+
+ // Unsubscribe handler1
+ event_mgr.unsubscribe(handler1_id);
+
+ // Queue the same event again
+ event_mgr.queue_event<MouseClickEvent>(
+ MouseClickEvent{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE});
+
+ // Dispatch events - only handler 2 should be triggered, handler 1 should NOT
+ event_mgr.dispatch_events();
+ EXPECT_FALSE(triggered1); // Handler 1 should NOT be triggered
+ EXPECT_TRUE(triggered2); // Handler 2 should be triggered
+
+ // Reset flags
+ triggered2 = false;
+
+ // Unsubscribe handler2
+ event_mgr.unsubscribe(handler2_id);
+
+ // Queue the event again
+ event_mgr.queue_event<MouseClickEvent>(
+ MouseClickEvent{.mouse_pos = {100, 200}, .button = MouseButton::LEFT_MOUSE});
+
+ // Dispatch events - no handler should be triggered
+ event_mgr.dispatch_events();
+ EXPECT_FALSE(triggered1); // Handler 1 should NOT be triggered
+ EXPECT_FALSE(triggered2); // Handler 2 should NOT be triggered
+}
diff --git a/src/test/InputTest.cpp b/src/test/InputTest.cpp
new file mode 100644
index 0000000..2d844d4
--- /dev/null
+++ b/src/test/InputTest.cpp
@@ -0,0 +1,267 @@
+#include <gtest/gtest.h>
+
+#include <crepe/manager/ResourceManager.h>
+#include <crepe/system/RenderSystem.h>
+
+#define protected public
+#define private public
+
+#include "api/KeyCodes.h"
+#include "manager/ComponentManager.h"
+#include "manager/EventManager.h"
+#include "manager/Mediator.h"
+#include "system/InputSystem.h"
+#include <SDL2/SDL.h>
+#include <SDL2/SDL_keycode.h>
+#include <crepe/api/Button.h>
+#include <crepe/api/Camera.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Metadata.h>
+#include <crepe/api/Transform.h>
+#include <crepe/api/Vector2.h>
+#include <crepe/facade/SDLContext.h>
+#include <gmock/gmock.h>
+
+using namespace std;
+using namespace std::chrono_literals;
+using namespace crepe;
+
+class InputTest : public ::testing::Test {
+public:
+ Mediator mediator;
+ ComponentManager mgr{mediator};
+ SDLContext sdl_context{mediator};
+
+ InputSystem input_system{mediator};
+ ResourceManager resman{mediator};
+ RenderSystem render{mediator};
+ EventManager event_manager{mediator};
+ //GameObject camera;
+
+protected:
+ void SetUp() override {
+ GameObject obj = mgr.new_object("camera", "camera", vec2{0, 0}, 0, 1);
+ auto & camera
+ = obj.add_component<Camera>(ivec2{500, 500}, vec2{500, 500},
+ Camera::Data{.bg_color = Color::WHITE, .zoom = 1.0f});
+ render.update();
+ //mediator.event_manager = event_manager;
+ //mediator.component_manager = mgr;
+ //event_manager.clear();
+ }
+ void TearDown() override {}
+ void simulate_mouse_click(int mouse_x, int mouse_y, Uint8 mouse_button) {
+ SDL_Event event;
+
+ // Simulate Mouse Button Down event
+ SDL_zero(event);
+ event.type = SDL_MOUSEBUTTONDOWN;
+ event.button.x = mouse_x;
+ event.button.y = mouse_y;
+ event.button.button = mouse_button;
+ SDL_PushEvent(&event);
+
+ // Simulate Mouse Button Up event
+ SDL_zero(event);
+ event.type = SDL_MOUSEBUTTONUP;
+ event.button.x = mouse_x;
+ event.button.y = mouse_y;
+ event.button.button = mouse_button;
+ SDL_PushEvent(&event);
+ }
+};
+
+TEST_F(InputTest, MouseDown) {
+ bool mouse_triggered = false;
+ EventHandler<MousePressEvent> on_mouse_down = [&](const MousePressEvent & event) {
+ mouse_triggered = true;
+ //middle of the screen = 0,0
+ EXPECT_EQ(event.mouse_pos.x, 0);
+ EXPECT_EQ(event.mouse_pos.y, 0);
+ EXPECT_EQ(event.button, MouseButton::LEFT_MOUSE);
+ return false;
+ };
+ event_manager.subscribe<MousePressEvent>(on_mouse_down);
+
+ SDL_Event event;
+ SDL_zero(event);
+ event.type = SDL_MOUSEBUTTONDOWN;
+ // middle of the screen of a 500*500 camera = 250*250
+ event.button.x = 250;
+ event.button.y = 250;
+ event.button.button = SDL_BUTTON_LEFT;
+ SDL_PushEvent(&event);
+
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(mouse_triggered);
+}
+
+TEST_F(InputTest, MouseUp) {
+ bool function_triggered = false;
+ EventHandler<MouseReleaseEvent> on_mouse_release = [&](const MouseReleaseEvent & e) {
+ function_triggered = true;
+ EXPECT_EQ(e.mouse_pos.x, 0);
+ EXPECT_EQ(e.mouse_pos.y, 0);
+ EXPECT_EQ(e.button, MouseButton::LEFT_MOUSE);
+ return false;
+ };
+ event_manager.subscribe<MouseReleaseEvent>(on_mouse_release);
+
+ SDL_Event event;
+ SDL_zero(event);
+ event.type = SDL_MOUSEBUTTONUP;
+ event.button.x = 250;
+ event.button.y = 250;
+ event.button.button = SDL_BUTTON_LEFT;
+ SDL_PushEvent(&event);
+
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(function_triggered);
+}
+
+TEST_F(InputTest, MouseMove) {
+ bool function_triggered = false;
+ EventHandler<MouseMoveEvent> on_mouse_move = [&](const MouseMoveEvent & e) {
+ function_triggered = true;
+ EXPECT_EQ(e.mouse_pos.x, 0);
+ EXPECT_EQ(e.mouse_pos.y, 0);
+ EXPECT_EQ(e.mouse_delta.x, 10);
+ EXPECT_EQ(e.mouse_delta.y, 10);
+ return false;
+ };
+ event_manager.subscribe<MouseMoveEvent>(on_mouse_move);
+
+ SDL_Event event;
+ SDL_zero(event);
+ event.type = SDL_MOUSEMOTION;
+ event.motion.x = 250;
+ event.motion.y = 250;
+ event.motion.xrel = 10;
+ event.motion.yrel = 10;
+ SDL_PushEvent(&event);
+
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(function_triggered);
+}
+
+TEST_F(InputTest, KeyDown) {
+ bool function_triggered = false;
+
+ // Define event handler for KeyPressEvent
+ EventHandler<KeyPressEvent> on_key_press = [&](const KeyPressEvent & event) {
+ function_triggered = true;
+ EXPECT_EQ(event.key, Keycode::B); // Validate the key is 'B'
+ EXPECT_EQ(event.repeat, true); // Validate repeat flag
+ return false;
+ };
+
+ event_manager.subscribe<KeyPressEvent>(on_key_press);
+
+ // Simulate SDL_KEYDOWN event
+ SDL_Event test_event;
+ SDL_zero(test_event);
+ test_event.type = SDL_KEYDOWN; // Key down event
+ test_event.key.keysym.scancode = SDL_SCANCODE_B; // Set scancode for 'B'
+ test_event.key.repeat = 1; // Set repeat flag
+ SDL_PushEvent(&test_event);
+
+ input_system.update(); // Process the event
+ event_manager.dispatch_events(); // Dispatch events to handlers
+
+ EXPECT_TRUE(function_triggered); // Check if the handler was triggered
+}
+
+TEST_F(InputTest, KeyUp) {
+ bool function_triggered = false;
+ EventHandler<KeyReleaseEvent> on_key_release = [&](const KeyReleaseEvent & event) {
+ function_triggered = true;
+ EXPECT_EQ(event.key, Keycode::B);
+ return false;
+ };
+ event_manager.subscribe<KeyReleaseEvent>(on_key_release);
+
+ SDL_Event event;
+ SDL_zero(event);
+ event.type = SDL_KEYUP;
+ event.key.keysym.scancode = SDL_SCANCODE_B;
+ SDL_PushEvent(&event);
+
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(function_triggered);
+}
+
+TEST_F(InputTest, MouseClick) {
+ bool on_click_triggered = false;
+ EventHandler<MouseClickEvent> on_mouse_click = [&](const MouseClickEvent & event) {
+ on_click_triggered = true;
+ EXPECT_EQ(event.button, MouseButton::LEFT_MOUSE);
+ EXPECT_EQ(event.mouse_pos.x, 0);
+ EXPECT_EQ(event.mouse_pos.y, 0);
+ return false;
+ };
+ event_manager.subscribe<MouseClickEvent>(on_mouse_click);
+
+ this->simulate_mouse_click(250, 250, SDL_BUTTON_LEFT);
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(on_click_triggered);
+}
+
+TEST_F(InputTest, testButtonClick) {
+ GameObject button_obj = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ bool button_clicked = false;
+ std::function<void()> on_click = [&]() { button_clicked = true; };
+ auto & button = button_obj.add_component<Button>(vec2{100, 100}, vec2{0, 0}, on_click);
+
+ bool hover = false;
+ button.active = true;
+ this->simulate_mouse_click(999, 999, SDL_BUTTON_LEFT);
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_FALSE(button_clicked);
+
+ this->simulate_mouse_click(250, 250, SDL_BUTTON_LEFT);
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(button_clicked);
+}
+
+TEST_F(InputTest, testButtonHover) {
+ GameObject button_obj = mgr.new_object("body", "person", vec2{0, 0}, 0, 1);
+ bool button_clicked = false;
+ std::function<void()> on_click = [&]() { button_clicked = true; };
+ auto & button = button_obj.add_component<Button>(vec2{100, 100}, vec2{0, 0}, on_click);
+ button.active = true;
+
+ // Mouse not on button
+ SDL_Event event;
+ SDL_zero(event);
+ event.type = SDL_MOUSEMOTION;
+ event.motion.x = 700;
+ event.motion.y = 700;
+ event.motion.xrel = 10;
+ event.motion.yrel = 10;
+ SDL_PushEvent(&event);
+
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_FALSE(button.hover);
+
+ // Mouse on button
+ SDL_Event hover_event;
+ SDL_zero(hover_event);
+ hover_event.type = SDL_MOUSEMOTION;
+ hover_event.motion.x = 250;
+ hover_event.motion.y = 250;
+ hover_event.motion.xrel = 10;
+ hover_event.motion.yrel = 10;
+ SDL_PushEvent(&hover_event);
+
+ input_system.update();
+ event_manager.dispatch_events();
+ EXPECT_TRUE(button.hover);
+}
diff --git a/src/test/LoopManagerTest.cpp b/src/test/LoopManagerTest.cpp
new file mode 100644
index 0000000..df132ae
--- /dev/null
+++ b/src/test/LoopManagerTest.cpp
@@ -0,0 +1,78 @@
+#include <chrono>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <thread>
+#define private public
+#define protected public
+#include <crepe/api/LoopManager.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/manager/LoopTimerManager.h>
+using namespace std::chrono;
+using namespace crepe;
+
+class DISABLED_LoopManagerTest : public ::testing::Test {
+protected:
+ class TestGameLoop : public crepe::LoopManager {
+ public:
+ MOCK_METHOD(void, fixed_update, (), (override));
+ MOCK_METHOD(void, frame_update, (), (override));
+ };
+
+ TestGameLoop test_loop;
+ void SetUp() override {}
+};
+
+TEST_F(DISABLED_LoopManagerTest, FixedUpdate) {
+ // Arrange
+ test_loop.loop_timer.set_target_framerate(60);
+
+ // Set expectations for the mock calls
+ EXPECT_CALL(test_loop, frame_update).Times(::testing::Between(55, 65));
+ EXPECT_CALL(test_loop, fixed_update).Times(::testing::Between(48, 52));
+
+ // Start the loop in a separate thread
+ std::thread loop_thread([&]() { test_loop.start(); });
+
+ // Let the loop run for exactly 1 second
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+
+ // Stop the game loop
+ test_loop.game_running = false;
+ // Wait for the loop thread to finish
+ loop_thread.join();
+
+ // Test finished
+}
+
+TEST_F(DISABLED_LoopManagerTest, ScaledFixedUpdate) {
+ // Arrange
+ test_loop.loop_timer.set_target_framerate(60);
+
+ // Set expectations for the mock calls
+ EXPECT_CALL(test_loop, frame_update).Times(::testing::Between(55, 65));
+ EXPECT_CALL(test_loop, fixed_update).Times(::testing::Between(48, 52));
+
+ // Start the loop in a separate thread
+ std::thread loop_thread([&]() { test_loop.start(); });
+
+ // Let the loop run for exactly 1 second
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+
+ // Stop the game loop
+ test_loop.game_running = false;
+ // Wait for the loop thread to finish
+ loop_thread.join();
+
+ // Test finished
+}
+
+TEST_F(DISABLED_LoopManagerTest, ShutDown) {
+ // Arrange
+ test_loop.loop_timer.set_target_framerate(60);
+ // Start the loop in a separate thread
+ std::thread loop_thread([&]() { test_loop.start(); });
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ test_loop.event_manager.trigger_event<ShutDownEvent>(ShutDownEvent{});
+ // Wait for the loop thread to finish
+ loop_thread.join();
+}
diff --git a/src/test/LoopTimerTest.cpp b/src/test/LoopTimerTest.cpp
new file mode 100644
index 0000000..7bd6305
--- /dev/null
+++ b/src/test/LoopTimerTest.cpp
@@ -0,0 +1,97 @@
+#include <chrono>
+#include <gtest/gtest.h>
+#include <thread>
+
+#define private public
+#define protected public
+
+#include <crepe/manager/LoopTimerManager.h>
+#include <crepe/manager/Mediator.h>
+
+using namespace std::chrono;
+using namespace crepe;
+
+class LoopTimerTest : public ::testing::Test {
+protected:
+ Mediator mediator;
+ LoopTimerManager loop_timer{mediator};
+
+ void SetUp() override { loop_timer.start(); }
+};
+
+TEST_F(LoopTimerTest, EnforcesTargetFrameRate) {
+ // Set the target FPS to 60 (which gives a target time per frame of ~16.67 ms)
+ loop_timer.set_target_framerate(60);
+
+ auto start_time = steady_clock::now();
+ loop_timer.enforce_frame_rate();
+
+ auto elapsed_time = steady_clock::now() - start_time;
+ auto elapsed_ms = duration_cast<milliseconds>(elapsed_time).count();
+
+ // For 60 FPS, the target frame time is around 16.67ms
+ ASSERT_NEAR(elapsed_ms, 16.7, 5);
+}
+
+TEST_F(LoopTimerTest, SetTargetFps) {
+ // Set the target FPS to 120
+ loop_timer.set_target_framerate(120);
+
+ // Calculate the expected frame time (~8.33ms per frame)
+ duration_t expected_frame_time = std::chrono::duration<float>(1.0 / 120.0);
+
+ ASSERT_NEAR(loop_timer.frame_target_time.count(), expected_frame_time.count(), 0.001);
+}
+
+TEST_F(LoopTimerTest, DeltaTimeCalculation) {
+ // Set the target FPS to 60 (16.67 ms per frame)
+ loop_timer.set_target_framerate(60);
+
+ auto start_time = steady_clock::now();
+ loop_timer.update();
+ auto end_time = steady_clock::now();
+
+ // Check the delta time
+ duration_t delta_time = loop_timer.get_delta_time();
+
+ auto elapsed_time = duration_cast<seconds>(end_time - start_time).count();
+
+ // Assert that delta_time is close to the elapsed time
+ ASSERT_NEAR(delta_time.count(), elapsed_time, 1);
+}
+
+TEST_F(LoopTimerTest, DISABLED_getCurrentTime) {
+ // Set the target FPS to 60 (16.67 ms per frame)
+ loop_timer.set_target_framerate(60);
+
+ auto start_time = steady_clock::now();
+
+ // Sleep
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
+
+ loop_timer.update();
+
+ auto end_time = steady_clock::now();
+
+ // Get the elapsed time in seconds as a double
+ auto elapsed_time
+ = std::chrono::duration_cast<elapsed_time_t>(end_time - start_time).count();
+
+ ASSERT_NEAR(loop_timer.get_elapsed_time().count(), elapsed_time, 5);
+}
+TEST_F(LoopTimerTest, getFPS) {
+ // Set the target FPS to 60 (which gives a target time per frame of ~16.67 ms)
+ loop_timer.set_target_framerate(60);
+
+ auto start_time = steady_clock::now();
+ loop_timer.enforce_frame_rate();
+
+ auto elapsed_time = steady_clock::now() - start_time;
+ loop_timer.update();
+ unsigned int fps = loop_timer.get_fps();
+ auto elapsed_ms = duration_cast<milliseconds>(elapsed_time).count();
+
+ // For 60 FPS, the target frame time is around 16.67ms
+ ASSERT_NEAR(elapsed_ms, 16.7, 1);
+ ASSERT_NEAR(fps, 60, 2);
+}
diff --git a/src/test/OptionalRefTest.cpp b/src/test/OptionalRefTest.cpp
index 219ccca..83f7b23 100644
--- a/src/test/OptionalRefTest.cpp
+++ b/src/test/OptionalRefTest.cpp
@@ -6,33 +6,37 @@ using namespace std;
using namespace crepe;
using namespace testing;
-TEST(OptionalRefTest, Explicit) {
+TEST(OptionalRefTest, Normal) {
string value = "foo";
- OptionalRef<string> ref;
- EXPECT_FALSE(ref);
- ASSERT_THROW(ref.get(), runtime_error);
+ OptionalRef<string> ref = value;
- ref.set(value);
EXPECT_TRUE(ref);
- ASSERT_NO_THROW(ref.get());
+ ASSERT_NO_THROW({
+ string & value_ref = ref;
+ EXPECT_EQ(value_ref, value);
+ });
ref.clear();
EXPECT_FALSE(ref);
- ASSERT_THROW(ref.get(), runtime_error);
+ ASSERT_THROW({ string & value_ref = ref; }, runtime_error);
}
-TEST(OptionalRefTest, Implicit) {
+TEST(OptionalRefTest, Empty) {
string value = "foo";
- OptionalRef<string> ref = value;
- EXPECT_TRUE(ref);
- ASSERT_NO_THROW(ref.get());
+ OptionalRef<string> ref;
- ref.clear();
EXPECT_FALSE(ref);
- ASSERT_THROW(ref.get(), runtime_error);
-
- ref = value;
- EXPECT_TRUE(ref);
- ASSERT_NO_THROW(ref.get());
+ ASSERT_THROW({ string & value_ref = ref; }, runtime_error);
}
+TEST(OptionalRefTest, Chain) {
+ string value = "foo";
+ OptionalRef<string> ref1 = value;
+ OptionalRef<string> ref2 = ref1;
+
+ EXPECT_TRUE(ref2);
+ string & value_ref = ref2;
+ EXPECT_EQ(value_ref, value);
+ value_ref = "bar";
+ EXPECT_EQ(value_ref, value);
+}
diff --git a/src/test/ParticleTest.cpp b/src/test/ParticleTest.cpp
index cd2ec2a..9263e00 100644
--- a/src/test/ParticleTest.cpp
+++ b/src/test/ParticleTest.cpp
@@ -1,56 +1,66 @@
-#include "api/Vector2.h"
-#include <crepe/ComponentManager.h>
-#include <crepe/Particle.h>
+#include "api/Asset.h"
#include <crepe/api/Config.h>
#include <crepe/api/GameObject.h>
-#include <crepe/api/ParticleEmitter.h>
#include <crepe/api/Rigidbody.h>
#include <crepe/api/Sprite.h>
#include <crepe/api/Transform.h>
-#include <crepe/system/ParticleSystem.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/LoopTimerManager.h>
#include <gtest/gtest.h>
#include <math.h>
+#define protected public
+#define private public
+#include <crepe/Particle.h>
+#include <crepe/api/ParticleEmitter.h>
+#include <crepe/system/ParticleSystem.h>
using namespace std;
using namespace std::chrono_literals;
using namespace crepe;
class ParticlesTest : public ::testing::Test {
+ Mediator m;
+
public:
- ComponentManager component_manager;
- ParticleSystem particle_system{component_manager};
+ ComponentManager component_manager{m};
+ ParticleSystem particle_system{m};
+ LoopTimerManager loop_timer{m};
void SetUp() override {
ComponentManager & mgr = this->component_manager;
std::vector<std::reference_wrapper<Transform>> transforms
= mgr.get_components_by_id<Transform>(0);
if (transforms.empty()) {
- GameObject game_object = mgr.new_object("", "", Vector2{0, 0}, 0, 0);
+ GameObject game_object = mgr.new_object("", "", vec2{0, 0}, 0, 0);
Color color(0, 0, 0, 0);
- Sprite test_sprite = game_object.add_component<Sprite>(
- make_shared<Texture>("asset/texture/img.png"), color,
- FlipSettings{true, true});
+ auto s1 = Asset("asset/texture/img.png");
+ Sprite & test_sprite = game_object.add_component<Sprite>(
+ s1, Sprite::Data{
+ .color = color,
+ .flip = Sprite::FlipSettings{true, true},
+ .size = {10, 10},
+ });
- game_object.add_component<ParticleEmitter>(ParticleEmitter::Data{
- .position = {0, 0},
- .max_particles = 100,
- .emission_rate = 0,
- .min_speed = 0,
- .max_speed = 0,
- .min_angle = 0,
- .max_angle = 0,
- .begin_lifespan = 0,
- .end_lifespan = 0,
- .force_over_time = Vector2{0, 0},
- .boundary{
- .width = 0,
- .height = 0,
- .offset = Vector2{0, 0},
- .reset_on_exit = false,
- },
- .sprite = test_sprite,
- });
+ game_object.add_component<ParticleEmitter>(test_sprite,
+ ParticleEmitter::Data{
+ .offset = {0, 0},
+ .max_particles = 100,
+ .emission_rate = 0,
+ .min_speed = 0,
+ .max_speed = 0,
+ .min_angle = 0,
+ .max_angle = 0,
+ .begin_lifespan = 0,
+ .end_lifespan = 0,
+ .force_over_time = vec2{0, 0},
+ .boundary{
+ .width = 0,
+ .height = 0,
+ .offset = vec2{0, 0},
+ .reset_on_exit = false,
+ },
+ });
}
transforms = mgr.get_components_by_id<Transform>(0);
Transform & transform = transforms.front().get();
@@ -60,7 +70,7 @@ public:
std::vector<std::reference_wrapper<ParticleEmitter>> rigidbodies
= mgr.get_components_by_id<ParticleEmitter>(0);
ParticleEmitter & emitter = rigidbodies.front().get();
- emitter.data.position = {0, 0};
+ emitter.data.offset = {0, 0};
emitter.data.emission_rate = 0;
emitter.data.min_speed = 0;
emitter.data.max_speed = 0;
@@ -68,9 +78,9 @@ public:
emitter.data.max_angle = 0;
emitter.data.begin_lifespan = 0;
emitter.data.end_lifespan = 0;
- emitter.data.force_over_time = Vector2{0, 0};
- emitter.data.boundary = {0, 0, Vector2{0, 0}, false};
- for (auto & particle : emitter.data.particles) {
+ emitter.data.force_over_time = vec2{0, 0};
+ emitter.data.boundary = {0, 0, vec2{0, 0}, false};
+ for (auto & particle : emitter.particles) {
particle.active = false;
}
}
@@ -79,8 +89,7 @@ public:
TEST_F(ParticlesTest, spawnParticle) {
Config::get_instance().physics.gravity = 1;
ComponentManager & mgr = this->component_manager;
- ParticleEmitter & emitter
- = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
+ ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
emitter.data.end_lifespan = 5;
emitter.data.boundary.height = 100;
emitter.data.boundary.width = 100;
@@ -90,19 +99,19 @@ TEST_F(ParticlesTest, spawnParticle) {
emitter.data.max_angle = 10;
particle_system.update();
//check if nothing happend
- EXPECT_EQ(emitter.data.particles[0].active, false);
- emitter.data.emission_rate = 1;
+ EXPECT_EQ(emitter.particles[0].active, false);
+ emitter.data.emission_rate = 50;
//check particle spawnes
particle_system.update();
- EXPECT_EQ(emitter.data.particles[0].active, true);
+ EXPECT_EQ(emitter.particles[0].active, true);
particle_system.update();
- EXPECT_EQ(emitter.data.particles[1].active, true);
+ EXPECT_EQ(emitter.particles[1].active, true);
particle_system.update();
- EXPECT_EQ(emitter.data.particles[2].active, true);
+ EXPECT_EQ(emitter.particles[2].active, true);
particle_system.update();
- EXPECT_EQ(emitter.data.particles[3].active, true);
+ EXPECT_EQ(emitter.particles[3].active, true);
- for (auto & particle : emitter.data.particles) {
+ for (auto & particle : emitter.particles) {
// Check velocity range
EXPECT_GE(particle.velocity.x, emitter.data.min_speed);
// Speed should be greater than or equal to min_speed
@@ -124,45 +133,42 @@ TEST_F(ParticlesTest, spawnParticle) {
TEST_F(ParticlesTest, moveParticleHorizontal) {
Config::get_instance().physics.gravity = 1;
ComponentManager & mgr = this->component_manager;
- ParticleEmitter & emitter
- = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
+ ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
emitter.data.end_lifespan = 100;
emitter.data.boundary.height = 100;
emitter.data.boundary.width = 100;
- emitter.data.min_speed = 1;
- emitter.data.max_speed = 1;
+ emitter.data.min_speed = 50;
+ emitter.data.max_speed = 50;
emitter.data.max_angle = 0;
- emitter.data.emission_rate = 1;
+ emitter.data.emission_rate = 50;
for (int a = 1; a < emitter.data.boundary.width / 2; a++) {
particle_system.update();
- EXPECT_EQ(emitter.data.particles[0].position.x, a);
+ EXPECT_EQ(emitter.particles[0].position.x, a);
}
}
TEST_F(ParticlesTest, moveParticleVertical) {
Config::get_instance().physics.gravity = 1;
ComponentManager & mgr = this->component_manager;
- ParticleEmitter & emitter
- = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
+ ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
emitter.data.end_lifespan = 100;
emitter.data.boundary.height = 100;
emitter.data.boundary.width = 100;
- emitter.data.min_speed = 1;
- emitter.data.max_speed = 1;
+ emitter.data.min_speed = 50;
+ emitter.data.max_speed = 50;
emitter.data.min_angle = 90;
emitter.data.max_angle = 90;
- emitter.data.emission_rate = 1;
+ emitter.data.emission_rate = 50;
for (int a = 1; a < emitter.data.boundary.width / 2; a++) {
particle_system.update();
- EXPECT_EQ(emitter.data.particles[0].position.y, a);
+ EXPECT_EQ(emitter.particles[0].position.y, a);
}
}
TEST_F(ParticlesTest, boundaryParticleReset) {
Config::get_instance().physics.gravity = 1;
ComponentManager & mgr = this->component_manager;
- ParticleEmitter & emitter
- = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
+ ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
emitter.data.end_lifespan = 100;
emitter.data.boundary.height = 10;
emitter.data.boundary.width = 10;
@@ -175,14 +181,13 @@ TEST_F(ParticlesTest, boundaryParticleReset) {
for (int a = 0; a < emitter.data.boundary.width / 2 + 1; a++) {
particle_system.update();
}
- EXPECT_EQ(emitter.data.particles[0].active, false);
+ EXPECT_EQ(emitter.particles[0].active, false);
}
TEST_F(ParticlesTest, boundaryParticleStop) {
Config::get_instance().physics.gravity = 1;
ComponentManager & mgr = this->component_manager;
- ParticleEmitter & emitter
- = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
+ ParticleEmitter & emitter = mgr.get_components_by_id<ParticleEmitter>(0).front().get();
emitter.data.end_lifespan = 100;
emitter.data.boundary.height = 10;
emitter.data.boundary.width = 10;
@@ -196,12 +201,12 @@ TEST_F(ParticlesTest, boundaryParticleStop) {
particle_system.update();
}
const double TOLERANCE = 0.01;
- EXPECT_NEAR(emitter.data.particles[0].velocity.x, 0, TOLERANCE);
- EXPECT_NEAR(emitter.data.particles[0].velocity.y, 0, TOLERANCE);
- if (emitter.data.particles[0].velocity.x != 0)
- EXPECT_NEAR(std::abs(emitter.data.particles[0].position.x),
+ EXPECT_NEAR(emitter.particles[0].velocity.x, 0, TOLERANCE);
+ EXPECT_NEAR(emitter.particles[0].velocity.y, 0, TOLERANCE);
+ if (emitter.particles[0].velocity.x != 0)
+ EXPECT_NEAR(std::abs(emitter.particles[0].position.x),
emitter.data.boundary.height / 2, TOLERANCE);
- if (emitter.data.particles[0].velocity.y != 0)
- EXPECT_NEAR(std::abs(emitter.data.particles[0].position.y),
- emitter.data.boundary.width / 2, TOLERANCE);
+ if (emitter.particles[0].velocity.y != 0)
+ EXPECT_NEAR(std::abs(emitter.particles[0].position.y), emitter.data.boundary.width / 2,
+ TOLERANCE);
}
diff --git a/src/test/PhysicsTest.cpp b/src/test/PhysicsTest.cpp
index edb76e9..3afb3c7 100644
--- a/src/test/PhysicsTest.cpp
+++ b/src/test/PhysicsTest.cpp
@@ -1,8 +1,10 @@
-#include <crepe/ComponentManager.h>
#include <crepe/api/Config.h>
#include <crepe/api/GameObject.h>
#include <crepe/api/Rigidbody.h>
#include <crepe/api/Transform.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/LoopTimerManager.h>
+#include <crepe/manager/Mediator.h>
#include <crepe/system/PhysicsSystem.h>
#include <gtest/gtest.h>
@@ -11,25 +13,26 @@ using namespace std::chrono_literals;
using namespace crepe;
class PhysicsTest : public ::testing::Test {
+ Mediator m;
+
public:
- ComponentManager component_manager;
- PhysicsSystem system{component_manager};
+ ComponentManager component_manager{m};
+ PhysicsSystem system{m};
+ LoopTimerManager loop_timer{m};
void SetUp() override {
ComponentManager & mgr = this->component_manager;
vector<reference_wrapper<Transform>> transforms
= mgr.get_components_by_id<Transform>(0);
if (transforms.empty()) {
- auto entity = mgr.new_object("", "", Vector2{0, 0}, 0, 0);
+ auto entity = mgr.new_object("", "", vec2{0, 0}, 0, 0);
entity.add_component<Rigidbody>(Rigidbody::Data{
.mass = 1,
.gravity_scale = 1,
.body_type = Rigidbody::BodyType::DYNAMIC,
- .max_linear_velocity = Vector2{10, 10},
+ .max_linear_velocity = 10,
.max_angular_velocity = 10,
.constraints = {0, 0},
- .use_gravity = true,
- .bounce = false,
});
}
transforms = mgr.get_components_by_id<Transform>(0);
@@ -49,50 +52,47 @@ public:
TEST_F(PhysicsTest, gravity) {
Config::get_instance().physics.gravity = 1;
ComponentManager & mgr = this->component_manager;
- vector<reference_wrapper<Transform>> transforms
- = mgr.get_components_by_id<Transform>(0);
+ vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0);
const Transform & transform = transforms.front().get();
ASSERT_FALSE(transforms.empty());
EXPECT_EQ(transform.position.y, 0);
system.update();
- EXPECT_EQ(transform.position.y, 1);
+ EXPECT_NEAR(transform.position.y, 0.0004, 0.0001);
system.update();
- EXPECT_EQ(transform.position.y, 3);
+ EXPECT_NEAR(transform.position.y, 0.002, 0.001);
}
TEST_F(PhysicsTest, max_velocity) {
ComponentManager & mgr = this->component_manager;
- vector<reference_wrapper<Rigidbody>> rigidbodies
- = mgr.get_components_by_id<Rigidbody>(0);
+ vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0);
Rigidbody & rigidbody = rigidbodies.front().get();
+ rigidbody.data.gravity_scale = 0;
ASSERT_FALSE(rigidbodies.empty());
EXPECT_EQ(rigidbody.data.linear_velocity.y, 0);
rigidbody.add_force_linear({100, 100});
rigidbody.add_force_angular(100);
system.update();
- EXPECT_EQ(rigidbody.data.linear_velocity.y, 10);
- EXPECT_EQ(rigidbody.data.linear_velocity.x, 10);
+ EXPECT_NEAR(rigidbody.data.linear_velocity.y, 7.07, 0.01);
+ EXPECT_NEAR(rigidbody.data.linear_velocity.x, 7.07, 0.01);
EXPECT_EQ(rigidbody.data.angular_velocity, 10);
rigidbody.add_force_linear({-100, -100});
rigidbody.add_force_angular(-100);
system.update();
- EXPECT_EQ(rigidbody.data.linear_velocity.y, -10);
- EXPECT_EQ(rigidbody.data.linear_velocity.x, -10);
+ EXPECT_NEAR(rigidbody.data.linear_velocity.y, -7.07, 0.01);
+ EXPECT_NEAR(rigidbody.data.linear_velocity.x, -7.07, 0.01);
EXPECT_EQ(rigidbody.data.angular_velocity, -10);
}
TEST_F(PhysicsTest, movement) {
- Config::get_instance().physics.gravity = 0;
ComponentManager & mgr = this->component_manager;
- vector<reference_wrapper<Rigidbody>> rigidbodies
- = mgr.get_components_by_id<Rigidbody>(0);
+ vector<reference_wrapper<Rigidbody>> rigidbodies = mgr.get_components_by_id<Rigidbody>(0);
Rigidbody & rigidbody = rigidbodies.front().get();
- vector<reference_wrapper<Transform>> transforms
- = mgr.get_components_by_id<Transform>(0);
+ rigidbody.data.gravity_scale = 0;
+ vector<reference_wrapper<Transform>> transforms = mgr.get_components_by_id<Transform>(0);
const Transform & transform = transforms.front().get();
ASSERT_FALSE(rigidbodies.empty());
ASSERT_FALSE(transforms.empty());
@@ -100,31 +100,33 @@ TEST_F(PhysicsTest, movement) {
rigidbody.add_force_linear({1, 1});
rigidbody.add_force_angular(1);
system.update();
- EXPECT_EQ(transform.position.x, 1);
- EXPECT_EQ(transform.position.y, 1);
- EXPECT_EQ(transform.rotation, 1);
+ EXPECT_NEAR(transform.position.x, 0.02, 0.001);
+ EXPECT_NEAR(transform.position.y, 0.02, 0.001);
+ EXPECT_NEAR(transform.rotation, 0.02, 0.001);
rigidbody.data.constraints = {1, 1, 1};
- EXPECT_EQ(transform.position.x, 1);
- EXPECT_EQ(transform.position.y, 1);
- EXPECT_EQ(transform.rotation, 1);
-
- rigidbody.data.linear_damping.x = 0.5;
- rigidbody.data.linear_damping.y = 0.5;
- rigidbody.data.angular_damping = 0.5;
+ EXPECT_NEAR(transform.position.x, 0.02, 0.001);
+ EXPECT_NEAR(transform.position.y, 0.02, 0.001);
+ EXPECT_NEAR(transform.rotation, 0.02, 0.001);
+ rigidbody.data.constraints = {0, 0, 0};
+ rigidbody.data.linear_velocity_coefficient.x = 0.5;
+ rigidbody.data.linear_velocity_coefficient.y = 0.5;
+ rigidbody.data.angular_velocity_coefficient = 0.5;
system.update();
- EXPECT_EQ(rigidbody.data.linear_velocity.x, 0.5);
- EXPECT_EQ(rigidbody.data.linear_velocity.y, 0.5);
- EXPECT_EQ(rigidbody.data.angular_velocity, 0.5);
+ EXPECT_NEAR(rigidbody.data.linear_velocity.x, 0.98, 0.01);
+ EXPECT_NEAR(rigidbody.data.linear_velocity.y, 0.98, 0.01);
+ EXPECT_NEAR(rigidbody.data.angular_velocity, 0.98, 0.01);
rigidbody.data.constraints = {1, 1, 0};
- rigidbody.data.angular_damping = 0;
+ rigidbody.data.angular_velocity_coefficient = 0;
rigidbody.data.max_angular_velocity = 1000;
rigidbody.data.angular_velocity = 360;
system.update();
- EXPECT_EQ(transform.rotation, 1);
+ EXPECT_NEAR(transform.rotation, 7.24, 0.01);
rigidbody.data.angular_velocity = -360;
system.update();
- EXPECT_EQ(transform.rotation, 1);
+ EXPECT_NEAR(transform.rotation, 0.04, 0.001);
+ system.update();
+ EXPECT_NEAR(transform.rotation, 352.84, 0.01);
}
diff --git a/src/test/Profiling.cpp b/src/test/Profiling.cpp
new file mode 100644
index 0000000..16736b8
--- /dev/null
+++ b/src/test/Profiling.cpp
@@ -0,0 +1,249 @@
+#include <chrono>
+#include <cmath>
+#include <crepe/api/Asset.h>
+#include <crepe/manager/Mediator.h>
+#include <crepe/manager/ResourceManager.h>
+#include <crepe/system/ParticleSystem.h>
+#include <crepe/system/PhysicsSystem.h>
+#include <crepe/system/RenderSystem.h>
+#include <gtest/gtest.h>
+
+#define private public
+#define protected public
+
+#include <crepe/api/Event.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/ParticleEmitter.h>
+#include <crepe/api/Rigidbody.h>
+#include <crepe/api/Script.h>
+#include <crepe/api/Transform.h>
+#include <crepe/facade/SDLContext.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/system/CollisionSystem.h>
+#include <crepe/system/ScriptSystem.h>
+#include <crepe/types.h>
+#include <crepe/util/Log.h>
+
+using namespace std;
+using namespace std::chrono_literals;
+using namespace crepe;
+using namespace testing;
+
+class TestScript : public Script {
+ bool oncollision(const CollisionEvent & test) {
+ Log::logf("Box {} script on_collision()", test.info.this_collider.game_object_id);
+ return true;
+ }
+ void init() {
+ subscribe<CollisionEvent>(
+ [this](const CollisionEvent & ev) -> bool { return this->oncollision(ev); });
+ }
+ void update() {
+ // Retrieve component from the same GameObject this script is on
+ }
+};
+
+class DISABLED_ProfilingTest : public Test {
+public:
+ // Config for test
+ // Minimum amount to let test pass
+ const int min_gameobject_count = 100;
+ // Maximum amount to stop test
+ const int max_gameobject_count = 150;
+ // Amount of times a test runs to calculate average
+ const int average = 5;
+ // Maximum duration to stop test
+ const std::chrono::microseconds duration = 16000us;
+
+ Mediator m;
+ SDLContext sdl_context{m};
+ ResourceManager resman{m};
+ ComponentManager mgr{m};
+ // Add system used for profling tests
+ CollisionSystem collision_sys{m};
+ PhysicsSystem physics_sys{m};
+ ParticleSystem particle_sys{m};
+ RenderSystem render_sys{m};
+ ScriptSystem script_sys{m};
+
+ // Test data
+ std::map<std::string, std::chrono::microseconds> timings;
+ int game_object_count = 0;
+ std::chrono::microseconds total_time = 0us;
+
+ void SetUp() override {
+
+ GameObject do_not_use = mgr.new_object("DO_NOT_USE", "", {0, 0});
+ do_not_use.add_component<Camera>(ivec2{1080, 720}, vec2{2000, 2000},
+ Camera::Data{
+ .bg_color = Color::WHITE,
+ .zoom = 1.0f,
+ });
+ // initialize systems here:
+ //calls init
+ script_sys.update();
+ //creates window
+ render_sys.update();
+ }
+
+ // Helper function to time an update call and store its duration
+ template <typename Func>
+ std::chrono::microseconds time_function(const std::string & name, Func && func) {
+ auto start = std::chrono::steady_clock::now();
+ func();
+ auto end = std::chrono::steady_clock::now();
+ std::chrono::microseconds duration
+ = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
+ timings[name] += duration;
+ return duration;
+ }
+
+ // Run and profile all systems, return the total time in milliseconds
+ std::chrono::microseconds run_all_systems() {
+ std::chrono::microseconds total_microseconds = 0us;
+ total_microseconds += time_function("PhysicsSystem", [&]() { physics_sys.update(); });
+ total_microseconds
+ += time_function("CollisionSystem", [&]() { collision_sys.update(); });
+ total_microseconds
+ += time_function("ParticleSystem", [&]() { particle_sys.update(); });
+ total_microseconds += time_function("RenderSystem", [&]() { render_sys.update(); });
+ return total_microseconds;
+ }
+
+ // Print timings of all functions
+ void log_timings() const {
+ std::string result = "\nFunction timings:\n";
+
+ for (const auto & [name, duration] : timings) {
+ result += name + " took " + std::to_string(duration.count() / 1000.0 / average)
+ + " ms (" + std::to_string(duration.count() / average) + " µs).\n";
+ }
+
+ result += "Total time: " + std::to_string(this->total_time.count() / 1000.0 / average)
+ + " ms (" + std::to_string(this->total_time.count() / average) + " µs)\n";
+
+ result += "Amount of gameobjects: " + std::to_string(game_object_count) + "\n";
+
+ GTEST_LOG_(INFO) << result;
+ }
+
+ void clear_timings() {
+ for (auto & [key, value] : timings) {
+ value = std::chrono::microseconds(0);
+ }
+ }
+};
+
+TEST_F(DISABLED_ProfilingTest, Profiling_1) {
+ while (this->total_time / this->average < this->duration) {
+
+ {
+ //define gameobject used for testing
+ GameObject gameobject = mgr.new_object("gameobject", "", {0, 0});
+ }
+
+ this->game_object_count++;
+
+ this->total_time = 0us;
+ clear_timings();
+
+ for (int amount = 0; amount < this->average; amount++) {
+ this->total_time += run_all_systems();
+ }
+
+ if (this->game_object_count >= this->max_gameobject_count) break;
+ }
+ log_timings();
+ EXPECT_GE(this->game_object_count, this->min_gameobject_count);
+}
+
+TEST_F(DISABLED_ProfilingTest, Profiling_2) {
+ while (this->total_time / this->average < this->duration) {
+
+ {
+ //define gameobject used for testing
+ GameObject gameobject = mgr.new_object(
+ "gameobject", "", {static_cast<float>(game_object_count * 2), 0});
+ gameobject.add_component<Rigidbody>(Rigidbody::Data{
+ .gravity_scale = 0.0,
+ .body_type = Rigidbody::BodyType::STATIC,
+ });
+ gameobject.add_component<BoxCollider>(vec2{0, 0}, vec2{1, 1});
+
+ gameobject.add_component<BehaviorScript>().set_script<TestScript>();
+ Sprite & test_sprite = gameobject.add_component<Sprite>(
+ Asset{"asset/texture/square.png"},
+ Sprite::Data{
+ .color = {0, 0, 0, 0},
+ .flip = {.flip_x = false, .flip_y = false},
+ .sorting_in_layer = 1,
+ .order_in_layer = 1,
+ .size = {.y = 500},
+ });
+ }
+
+ this->game_object_count++;
+
+ this->total_time = 0us;
+ clear_timings();
+ for (int amount = 0; amount < this->average; amount++) {
+ this->total_time += run_all_systems();
+ }
+
+ if (this->game_object_count >= this->max_gameobject_count) break;
+ }
+ log_timings();
+ EXPECT_GE(this->game_object_count, this->min_gameobject_count);
+}
+
+TEST_F(DISABLED_ProfilingTest, Profiling_3) {
+ while (this->total_time / this->average < this->duration) {
+
+ {
+ //define gameobject used for testing
+ GameObject gameobject = mgr.new_object(
+ "gameobject", "", {static_cast<float>(game_object_count * 2), 0});
+ gameobject.add_component<Rigidbody>(Rigidbody::Data{
+ .gravity_scale = 0,
+ .body_type = Rigidbody::BodyType::STATIC,
+ });
+ gameobject.add_component<BoxCollider>(vec2{0, 0}, vec2{1, 1});
+ gameobject.add_component<BehaviorScript>().set_script<TestScript>();
+ Sprite & test_sprite = gameobject.add_component<Sprite>(
+ Asset{"asset/texture/square.png"},
+ Sprite::Data{
+ .color = {0, 0, 0, 0},
+ .flip = {.flip_x = false, .flip_y = false},
+ .sorting_in_layer = 1,
+ .order_in_layer = 1,
+ .size = {.y = 500},
+ });
+ auto & test = gameobject.add_component<ParticleEmitter>(
+ test_sprite, ParticleEmitter::Data{
+ .max_particles = 10,
+ .emission_rate = 100,
+ .end_lifespan = 100000,
+ .boundary{
+ .width = 1000,
+ .height = 1000,
+ .offset = vec2{0, 0},
+ .reset_on_exit = false,
+ },
+
+ });
+ }
+ render_sys.update();
+ this->game_object_count++;
+
+ this->total_time = 0us;
+ clear_timings();
+ for (int amount = 0; amount < this->average; amount++) {
+ this->total_time += run_all_systems();
+ }
+
+ if (this->game_object_count >= this->max_gameobject_count) break;
+ }
+ log_timings();
+ EXPECT_GE(this->game_object_count, this->min_gameobject_count);
+}
diff --git a/src/test/RenderSystemTest.cpp b/src/test/RenderSystemTest.cpp
new file mode 100644
index 0000000..b4519cb
--- /dev/null
+++ b/src/test/RenderSystemTest.cpp
@@ -0,0 +1,186 @@
+#include "api/Asset.h"
+#include "facade/SDLContext.h"
+#include "manager/ResourceManager.h"
+#include "types.h"
+#include <functional>
+#include <gtest/gtest.h>
+#include <memory>
+#include <vector>
+
+#define private public
+#define protected public
+
+#include <crepe/api/Camera.h>
+#include <crepe/api/Color.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Sprite.h>
+#include <crepe/manager/ComponentManager.h>
+
+#include <crepe/system/RenderSystem.h>
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class RenderSystemTest : public Test {
+ Mediator m;
+
+public:
+ ComponentManager mgr{m};
+ SDLContext ctx{m};
+ ResourceManager resource_manager{m};
+ RenderSystem sys{m};
+ GameObject entity1 = this->mgr.new_object("name");
+ GameObject entity2 = this->mgr.new_object("name");
+ GameObject entity3 = this->mgr.new_object("name");
+ GameObject entity4 = this->mgr.new_object("name");
+
+ void SetUp() override {
+ auto s1 = Asset("asset/texture/img.png");
+ auto s2 = Asset("asset/texture/img.png");
+ auto s3 = Asset("asset/texture/img.png");
+ auto s4 = Asset("asset/texture/img.png");
+ auto & sprite1
+ = entity1.add_component<Sprite>(s1, Sprite::Data{
+ .color = Color(0, 0, 0, 0),
+ .flip = Sprite::FlipSettings{false, false},
+ .sorting_in_layer = 5,
+ .order_in_layer = 5,
+ .size = {10, 10},
+ });
+
+ EXPECT_EQ(sprite1.data.order_in_layer, 5);
+ EXPECT_EQ(sprite1.data.sorting_in_layer, 5);
+ auto & sprite2
+ = entity2.add_component<Sprite>(s2, Sprite::Data{
+ .color = Color(0, 0, 0, 0),
+ .flip = Sprite::FlipSettings{false, false},
+ .sorting_in_layer = 2,
+ .order_in_layer = 1,
+ });
+ EXPECT_EQ(sprite2.data.sorting_in_layer, 2);
+ EXPECT_EQ(sprite2.data.order_in_layer, 1);
+
+ auto & sprite3
+ = entity3.add_component<Sprite>(s3, Sprite::Data{
+ .color = Color(0, 0, 0, 0),
+ .flip = Sprite::FlipSettings{false, false},
+ .sorting_in_layer = 1,
+ .order_in_layer = 2,
+ });
+ EXPECT_EQ(sprite3.data.sorting_in_layer, 1);
+ EXPECT_EQ(sprite3.data.order_in_layer, 2);
+
+ auto & sprite4
+ = entity4.add_component<Sprite>(s4, Sprite::Data{
+ .color = Color(0, 0, 0, 0),
+ .flip = Sprite::FlipSettings{false, false},
+ .sorting_in_layer = 1,
+ .order_in_layer = 1,
+ });
+ EXPECT_EQ(sprite4.data.sorting_in_layer, 1);
+ EXPECT_EQ(sprite4.data.order_in_layer, 1);
+ }
+};
+
+TEST_F(RenderSystemTest, NoCamera) {
+ // No camera
+ EXPECT_ANY_THROW({ this->sys.update(); });
+}
+
+TEST_F(RenderSystemTest, make_sprites) {}
+
+TEST_F(RenderSystemTest, sorting_sprites) {
+ vector<reference_wrapper<Sprite>> sprites = this->mgr.get_components_by_type<Sprite>();
+ ASSERT_EQ(sprites.size(), 4);
+
+ vector<reference_wrapper<Sprite>> sorted_sprites = this->sys.sort(sprites);
+ ASSERT_EQ(sorted_sprites.size(), 4);
+
+ // Expected order after sorting:
+ // 1. sorting_in_layer: 1, order_in_layer: 1 (entity4)
+ // 2. sorting_in_layer: 1, order_in_layer: 2 (entity3)
+ // 3. sorting_in_layer: 2, order_in_layer: 1 (entity2)
+ // 4. sorting_in_layer: 5, order_in_layer: 5 (entity1)
+
+ EXPECT_EQ(sorted_sprites[0].get().data.sorting_in_layer, 1);
+ EXPECT_EQ(sorted_sprites[0].get().data.order_in_layer, 1);
+
+ EXPECT_EQ(sorted_sprites[1].get().data.sorting_in_layer, 1);
+ EXPECT_EQ(sorted_sprites[1].get().data.order_in_layer, 2);
+
+ EXPECT_EQ(sorted_sprites[2].get().data.sorting_in_layer, 2);
+ EXPECT_EQ(sorted_sprites[2].get().data.order_in_layer, 1);
+
+ EXPECT_EQ(sorted_sprites[3].get().data.sorting_in_layer, 5);
+ EXPECT_EQ(sorted_sprites[3].get().data.order_in_layer, 5);
+
+ for (size_t i = 1; i < sorted_sprites.size(); ++i) {
+ const Sprite & prev = sorted_sprites[i - 1].get();
+ const Sprite & curr = sorted_sprites[i].get();
+
+ if (prev.data.sorting_in_layer == curr.data.sorting_in_layer) {
+ EXPECT_LE(prev.data.order_in_layer, curr.data.order_in_layer);
+ } else {
+ EXPECT_LE(prev.data.sorting_in_layer, curr.data.sorting_in_layer);
+ }
+ }
+}
+
+TEST_F(RenderSystemTest, Update) {
+ entity1.add_component<Camera>(ivec2{100, 100}, vec2{100, 100},
+ Camera::Data{.bg_color = Color::WHITE, .zoom = 1.0f});
+ {
+ vector<reference_wrapper<Sprite>> sprites = this->mgr.get_components_by_type<Sprite>();
+ ASSERT_EQ(sprites.size(), 4);
+
+ EXPECT_EQ(sprites[0].get().game_object_id, 0);
+ EXPECT_EQ(sprites[1].get().game_object_id, 1);
+ EXPECT_EQ(sprites[2].get().game_object_id, 2);
+ EXPECT_EQ(sprites[3].get().game_object_id, 3);
+ }
+ this->sys.update();
+ {
+ vector<reference_wrapper<Sprite>> sprites = this->mgr.get_components_by_type<Sprite>();
+ ASSERT_EQ(sprites.size(), 4);
+
+ EXPECT_EQ(sprites[0].get().game_object_id, 0);
+ EXPECT_EQ(sprites[1].get().game_object_id, 1);
+ EXPECT_EQ(sprites[2].get().game_object_id, 2);
+ EXPECT_EQ(sprites[3].get().game_object_id, 3);
+ }
+}
+
+TEST_F(RenderSystemTest, Camera) {
+ {
+ auto cameras = this->mgr.get_components_by_type<Camera>();
+ EXPECT_NE(cameras.size(), 1);
+ }
+ {
+ entity1.add_component<Camera>(ivec2{100, 100}, vec2{100, 100},
+ Camera::Data{.bg_color = Color::WHITE, .zoom = 1.0f});
+
+ auto cameras = this->mgr.get_components_by_type<Camera>();
+ EXPECT_EQ(cameras.size(), 1);
+ }
+
+ //TODO improve with newer version
+}
+TEST_F(RenderSystemTest, Color) {
+ entity1.add_component<Camera>(ivec2{100, 100}, vec2{100, 100},
+ Camera::Data{.bg_color = Color::WHITE, .zoom = 1.0f});
+
+ auto & sprite = this->mgr.get_components_by_id<Sprite>(entity1.id).front().get();
+ //ASSERT_NE(sprite.texture.texture.get(), nullptr);
+
+ sprite.data.color = Color::GREEN;
+ EXPECT_EQ(sprite.data.color.r, Color::GREEN.r);
+ EXPECT_EQ(sprite.data.color.g, Color::GREEN.g);
+ EXPECT_EQ(sprite.data.color.b, Color::GREEN.b);
+ EXPECT_EQ(sprite.data.color.a, Color::GREEN.a);
+ this->sys.update();
+ EXPECT_EQ(sprite.data.color.r, Color::GREEN.r);
+ EXPECT_EQ(sprite.data.color.g, Color::GREEN.g);
+ EXPECT_EQ(sprite.data.color.b, Color::GREEN.b);
+ EXPECT_EQ(sprite.data.color.a, Color::GREEN.a);
+}
diff --git a/src/test/ResourceManagerTest.cpp b/src/test/ResourceManagerTest.cpp
index 5d1ae7a..965eeab 100644
--- a/src/test/ResourceManagerTest.cpp
+++ b/src/test/ResourceManagerTest.cpp
@@ -1,51 +1,84 @@
+#include "manager/Mediator.h"
#include <gtest/gtest.h>
+#define private public
+#define protected public
+
+#include <crepe/api/GameObject.h>
+#include <crepe/manager/ResourceManager.h>
#include <crepe/util/Log.h>
-#include <crepe/api/Config.h>
-#include <crepe/api/ResourceManager.h>
using namespace std;
using namespace crepe;
using namespace testing;
class ResourceManagerTest : public Test {
+ Mediator mediator;
+
public:
- ResourceManager & resman = ResourceManager::get_instance();
- Config & cfg = Config::get_instance();
+ ResourceManager resource_manager{mediator};
+
+ class Unrelated : public Resource {
+ using Resource::Resource;
+ };
+
+ Asset asset_a{"asset/texture/img.png"};
+ Asset asset_b{"asset/texture/ERROR.png"};
- void SetUp() override {
- cfg.log.level = Log::Level::TRACE;
- resman.clear();
- }
+ class TestResource : public Resource {
+ public:
+ static unsigned instances;
+
+ public:
+ const unsigned instance;
+ TestResource(const Asset & src, Mediator & mediator)
+ : Resource(src, mediator),
+ instance(this->instances++) {}
+ ~TestResource() { this->instances--; }
+ bool operator==(const TestResource & other) const {
+ return this->instance == other.instance;
+ }
+ };
+
+private:
+ void SetUp() override { TestResource::instances = 0; }
};
+unsigned ResourceManagerTest::TestResource::instances = 0;
+
+TEST_F(ResourceManagerTest, Default) {
+ TestResource & res_1 = resource_manager.get<TestResource>(asset_a);
+ TestResource & res_2 = resource_manager.get<TestResource>(asset_a);
+ TestResource & res_3 = resource_manager.get<TestResource>(asset_b);
+ TestResource & res_4 = resource_manager.get<TestResource>(asset_b);
+
+ ASSERT_EQ(res_1, res_2);
+ ASSERT_EQ(res_3, res_4);
+ EXPECT_NE(res_1, res_3);
-TEST_F(ResourceManagerTest, Main) {
- Asset path1 = "mwe/audio/sfx1.wav";
- Asset path2 = "mwe/audio/sfx1.wav";
- ASSERT_EQ(path1, path2);
-
- Sound * ptr1 = nullptr;
- Sound * ptr2 = nullptr;
- {
- Log::logf(Log::Level::DEBUG, "Get first sound (constructor call)");
- Sound & sound = resman.cache<Sound>(path1);
- ptr1 = &sound;
- }
- {
- Log::logf(Log::Level::DEBUG, "Get same sound (NO constructor call)");
- Sound & sound = resman.cache<Sound>(path2);
- ptr2 = &sound;
- }
- EXPECT_EQ(ptr1, ptr2);
-
- Log::logf(Log::Level::DEBUG, "Clear cache (destructor call)");
- resman.clear();
-
- Log::logf(Log::Level::DEBUG, "Get first sound again (constructor call)");
- Sound & sound = resman.cache<Sound>(path1);
-
- // NOTE: there is no way (that I know of) to ensure the above statement
- // allocates the new Sound instance in a different location than the first,
- // so this test was verified using the above print statements.
+ EXPECT_EQ(TestResource::instances, 2);
+
+ resource_manager.clear();
+}
+
+TEST_F(ResourceManagerTest, Persistent) {
+ resource_manager.set_persistent(asset_a, true);
+ EXPECT_EQ(TestResource::instances, 0);
+
+ resource_manager.get<TestResource>(asset_a);
+ resource_manager.get<TestResource>(asset_a);
+ resource_manager.get<TestResource>(asset_b);
+ resource_manager.get<TestResource>(asset_b);
+ EXPECT_EQ(TestResource::instances, 2);
+
+ resource_manager.clear();
+ EXPECT_EQ(TestResource::instances, 1);
+
+ resource_manager.clear_all();
+ EXPECT_EQ(TestResource::instances, 0);
}
+TEST_F(ResourceManagerTest, UnmatchedType) {
+ EXPECT_NO_THROW({ resource_manager.get<TestResource>(asset_a); });
+
+ EXPECT_THROW({ resource_manager.get<Unrelated>(asset_a); }, runtime_error);
+}
diff --git a/src/test/SaveManagerTest.cpp b/src/test/SaveManagerTest.cpp
new file mode 100644
index 0000000..7609e69
--- /dev/null
+++ b/src/test/SaveManagerTest.cpp
@@ -0,0 +1,51 @@
+#include <gtest/gtest.h>
+
+#include <crepe/ValueBroker.h>
+#include <crepe/facade/DB.h>
+#include <crepe/manager/SaveManager.h>
+
+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<string>("foo", "bar");
+ ASSERT_TRUE(mgr.has("foo"));
+
+ string value = mgr.get<string>("foo");
+ EXPECT_EQ(value, "bar");
+}
+
+TEST_F(SaveManagerTest, DefaultValue) {
+ ValueBroker value = mgr.get<int>("foo", 3);
+
+ ASSERT_EQ(value.get(), 3);
+ value.set(5);
+ EXPECT_EQ(value.get(), 5);
+}
+
+TEST_F(SaveManagerTest, MultipleKeys) {
+ ValueBroker foo = mgr.get<int>("foo", 1);
+ ValueBroker bar = mgr.get<int>("bar", 2);
+
+ EXPECT_EQ(foo.get(), 1);
+ EXPECT_EQ(bar.get(), 2);
+
+ EXPECT_EQ(mgr.get<int>("foo"), 1);
+ EXPECT_EQ(mgr.get<int>("bar"), 2);
+}
diff --git a/src/test/SceneManagerTest.cpp b/src/test/SceneManagerTest.cpp
new file mode 100644
index 0000000..480e07a
--- /dev/null
+++ b/src/test/SceneManagerTest.cpp
@@ -0,0 +1,160 @@
+#include <gtest/gtest.h>
+
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Metadata.h>
+#include <crepe/api/Scene.h>
+#include <crepe/api/Transform.h>
+#include <crepe/api/Vector2.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/SceneManager.h>
+#include <crepe/types.h>
+
+using namespace std;
+using namespace crepe;
+
+class ConcreteScene1 : public Scene {
+public:
+ void load_scene() {
+ GameObject object1 = new_object("scene_1", "tag_scene_1", vec2{0, 0}, 0, 1);
+ GameObject object2 = new_object("scene_1", "tag_scene_1", vec2{1, 0}, 0, 1);
+ GameObject object3 = new_object("scene_1", "tag_scene_1", vec2{2, 0}, 0, 1);
+ }
+
+ string get_name() const { return "scene1"; }
+};
+
+class ConcreteScene2 : public Scene {
+public:
+ void load_scene() {
+ GameObject object1 = new_object("scene_2", "tag_scene_2", vec2{0, 0}, 0, 1);
+ GameObject object2 = new_object("scene_2", "tag_scene_2", vec2{0, 1}, 0, 1);
+ GameObject object3 = new_object("scene_2", "tag_scene_2", vec2{0, 2}, 0, 1);
+ GameObject object4 = new_object("scene_2", "tag_scene_2", vec2{0, 3}, 0, 1);
+ }
+
+ string get_name() const { return "scene2"; }
+};
+
+class ConcreteScene3 : public Scene {
+public:
+ ConcreteScene3(const string & name) : name(name) {}
+
+ void load_scene() {
+ GameObject object1 = new_object("scene_3", "tag_scene_3", vec2{0, 0}, 0, 1);
+ }
+
+ string get_name() const { return name; }
+
+private:
+ const string name;
+};
+
+class SceneManagerTest : public ::testing::Test {
+ Mediator m;
+
+public:
+ ComponentManager component_mgr{m};
+ SceneManager scene_mgr{m};
+};
+
+TEST_F(SceneManagerTest, loadScene) {
+ scene_mgr.add_scene<ConcreteScene1>();
+ scene_mgr.add_scene<ConcreteScene2>();
+
+ scene_mgr.load_next_scene();
+
+ vector<reference_wrapper<Metadata>> metadata
+ = component_mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform
+ = component_mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 3);
+ EXPECT_EQ(transform.size(), 3);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[0].get().name, "scene_1");
+ EXPECT_EQ(metadata[0].get().tag, "tag_scene_1");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+
+ EXPECT_EQ(metadata[1].get().game_object_id, 1);
+ EXPECT_EQ(metadata[1].get().name, "scene_1");
+ EXPECT_EQ(metadata[1].get().tag, "tag_scene_1");
+ EXPECT_EQ(metadata[1].get().parent, -1);
+ EXPECT_EQ(metadata[1].get().children.size(), 0);
+ EXPECT_EQ(transform[1].get().position.x, 1);
+ EXPECT_EQ(transform[1].get().position.y, 0);
+
+ EXPECT_EQ(metadata[2].get().game_object_id, 2);
+ EXPECT_EQ(metadata[2].get().name, "scene_1");
+ EXPECT_EQ(metadata[2].get().tag, "tag_scene_1");
+ EXPECT_EQ(metadata[2].get().parent, -1);
+ EXPECT_EQ(metadata[2].get().children.size(), 0);
+ EXPECT_EQ(transform[2].get().position.x, 2);
+ EXPECT_EQ(transform[2].get().position.y, 0);
+
+ scene_mgr.set_next_scene("scene2");
+ scene_mgr.load_next_scene();
+
+ metadata = component_mgr.get_components_by_type<Metadata>();
+ transform = component_mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 4);
+ EXPECT_EQ(transform.size(), 4);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[0].get().name, "scene_2");
+ EXPECT_EQ(metadata[0].get().tag, "tag_scene_2");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+
+ EXPECT_EQ(metadata[1].get().game_object_id, 1);
+ EXPECT_EQ(metadata[1].get().name, "scene_2");
+ EXPECT_EQ(metadata[1].get().tag, "tag_scene_2");
+ EXPECT_EQ(metadata[1].get().parent, -1);
+ EXPECT_EQ(metadata[1].get().children.size(), 0);
+ EXPECT_EQ(transform[1].get().position.x, 0);
+ EXPECT_EQ(transform[1].get().position.y, 1);
+
+ EXPECT_EQ(metadata[2].get().game_object_id, 2);
+ EXPECT_EQ(metadata[2].get().name, "scene_2");
+ EXPECT_EQ(metadata[2].get().tag, "tag_scene_2");
+ EXPECT_EQ(metadata[2].get().parent, -1);
+ EXPECT_EQ(metadata[2].get().children.size(), 0);
+ EXPECT_EQ(transform[2].get().position.x, 0);
+ EXPECT_EQ(transform[2].get().position.y, 2);
+
+ EXPECT_EQ(metadata[3].get().game_object_id, 3);
+ EXPECT_EQ(metadata[3].get().name, "scene_2");
+ EXPECT_EQ(metadata[3].get().tag, "tag_scene_2");
+ EXPECT_EQ(metadata[3].get().parent, -1);
+ EXPECT_EQ(metadata[3].get().children.size(), 0);
+ EXPECT_EQ(transform[3].get().position.x, 0);
+ EXPECT_EQ(transform[3].get().position.y, 3);
+}
+
+TEST_F(SceneManagerTest, perfectForwarding) {
+ scene_mgr.add_scene<ConcreteScene3>("scene3");
+
+ scene_mgr.load_next_scene();
+
+ vector<reference_wrapper<Metadata>> metadata
+ = component_mgr.get_components_by_type<Metadata>();
+ vector<reference_wrapper<Transform>> transform
+ = component_mgr.get_components_by_type<Transform>();
+
+ EXPECT_EQ(metadata.size(), 1);
+ EXPECT_EQ(transform.size(), 1);
+
+ EXPECT_EQ(metadata[0].get().game_object_id, 0);
+ EXPECT_EQ(metadata[0].get().name, "scene_3");
+ EXPECT_EQ(metadata[0].get().tag, "tag_scene_3");
+ EXPECT_EQ(metadata[0].get().parent, -1);
+ EXPECT_EQ(metadata[0].get().children.size(), 0);
+ EXPECT_EQ(transform[0].get().position.x, 0);
+ EXPECT_EQ(transform[0].get().position.y, 0);
+}
diff --git a/src/test/ScriptECSTest.cpp b/src/test/ScriptECSTest.cpp
new file mode 100644
index 0000000..1ec33ba
--- /dev/null
+++ b/src/test/ScriptECSTest.cpp
@@ -0,0 +1,41 @@
+#include <gtest/gtest.h>
+
+#define protected public
+
+#include <crepe/api/BehaviorScript.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Metadata.h>
+#include <crepe/api/Script.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/system/ScriptSystem.h>
+
+#include "ScriptTest.h"
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class ScriptECSTest : public ScriptTest {
+public:
+ class TestComponent : public Component {
+ using Component::Component;
+ };
+};
+
+TEST_F(ScriptECSTest, GetOwnComponent) {
+ MyScript & script = this->script;
+ Metadata & metadata = script.get_component<Metadata>();
+
+ EXPECT_EQ(metadata.name, OBJ_NAME);
+}
+
+TEST_F(ScriptECSTest, GetOwnComponents) {
+ const unsigned COUNT = 4;
+
+ for (unsigned i = 0; i < COUNT; i++) entity.add_component<TestComponent>();
+
+ MyScript & script = this->script;
+ RefVector<TestComponent> components = script.get_components<TestComponent>();
+
+ EXPECT_EQ(components.size(), COUNT);
+}
diff --git a/src/test/ScriptEventTest.cpp b/src/test/ScriptEventTest.cpp
new file mode 100644
index 0000000..c1b4028
--- /dev/null
+++ b/src/test/ScriptEventTest.cpp
@@ -0,0 +1,50 @@
+#include <gtest/gtest.h>
+
+// stupid hack to allow access to private/protected members under test
+#define private public
+#define protected public
+
+#include <crepe/api/BehaviorScript.h>
+#include <crepe/api/Event.h>
+#include <crepe/api/GameObject.h>
+#include <crepe/api/Script.h>
+#include <crepe/api/Vector2.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/system/ScriptSystem.h>
+
+#include "ScriptTest.h"
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class ScriptEventTest : public ScriptTest {
+public:
+ EventManager & event_manager = mediator.event_manager;
+
+ class MyEvent : public Event {};
+};
+
+TEST_F(ScriptEventTest, Default) {
+ BehaviorScript & behaviorscript = this->behaviorscript;
+ MyScript & script = this->script;
+ EventManager & evmgr = this->event_manager;
+
+ unsigned event_count = 0;
+ script.subscribe<MyEvent>([&](const MyEvent &) {
+ event_count++;
+ return true;
+ });
+
+ system.update();
+ behaviorscript.active = false;
+ EXPECT_EQ(0, event_count);
+
+ evmgr.trigger_event<MyEvent>();
+ EXPECT_EQ(0, event_count);
+
+ behaviorscript.active = true;
+ evmgr.trigger_event<MyEvent>();
+ EXPECT_EQ(1, event_count);
+}
diff --git a/src/test/ScriptSaveManagerTest.cpp b/src/test/ScriptSaveManagerTest.cpp
new file mode 100644
index 0000000..64403c4
--- /dev/null
+++ b/src/test/ScriptSaveManagerTest.cpp
@@ -0,0 +1,35 @@
+#include <gtest/gtest.h>
+
+// stupid hack to allow access to private/protected members under test
+#define private public
+#define protected public
+
+#include <crepe/facade/DB.h>
+#include <crepe/manager/SaveManager.h>
+
+#include "ScriptTest.h"
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class ScriptSaveManagerTest : public ScriptTest {
+public:
+ class TestSaveManager : public SaveManager {
+ using SaveManager::SaveManager;
+
+ // in-memory database for testing
+ DB db{};
+ virtual DB & get_db() override { return this->db; }
+ };
+
+ TestSaveManager save_mgr{mediator};
+};
+
+TEST_F(ScriptSaveManagerTest, GetSaveManager) {
+ MyScript & script = this->script;
+
+ SaveManager & mgr = script.get_save_manager();
+
+ EXPECT_EQ(&mgr, &save_mgr);
+}
diff --git a/src/test/ScriptSceneTest.cpp b/src/test/ScriptSceneTest.cpp
new file mode 100644
index 0000000..2568049
--- /dev/null
+++ b/src/test/ScriptSceneTest.cpp
@@ -0,0 +1,30 @@
+#include <gtest/gtest.h>
+
+// stupid hack to allow access to private/protected members under test
+#define private public
+#define protected public
+
+#include "ScriptTest.h"
+#include <crepe/manager/SceneManager.h>
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class ScriptSceneTest : public ScriptTest {
+public:
+ SceneManager scene_manager{mediator};
+
+ class MyScene : public Scene {};
+};
+
+TEST_F(ScriptSceneTest, Default) {
+ BehaviorScript & behaviorscript = this->behaviorscript;
+ MyScript & script = this->script;
+
+ const char * non_default_value = "foo";
+ ASSERT_NE(non_default_value, scene_manager.next_scene);
+
+ script.set_next_scene(non_default_value);
+ EXPECT_EQ(non_default_value, scene_manager.next_scene);
+}
diff --git a/src/test/ScriptTest.cpp b/src/test/ScriptTest.cpp
index 19fef6d..acdae70 100644
--- a/src/test/ScriptTest.cpp
+++ b/src/test/ScriptTest.cpp
@@ -1,72 +1,75 @@
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
// stupid hack to allow access to private/protected members under test
#define private public
#define protected public
-#include <crepe/ComponentManager.h>
-#include <crepe/api/BehaviorScript.h>
-#include <crepe/api/GameObject.h>
-#include <crepe/api/Script.h>
-#include <crepe/api/Vector2.h>
-#include <crepe/system/ScriptSystem.h>
+#include "ScriptTest.h"
using namespace std;
using namespace crepe;
using namespace testing;
-class ScriptTest : public Test {
-public:
- ComponentManager component_manager{};
- ScriptSystem system{component_manager};
-
- class MyScript : public Script {
- // NOTE: default (private) visibility of init and update shouldn't cause
- // issues!
- void init() { this->init_count++; }
- void update() { this->update_count++; }
-
- public:
- unsigned init_count = 0;
- unsigned update_count = 0;
- };
-
- BehaviorScript * behaviorscript_ref = nullptr;
- MyScript * script_ref = nullptr;
-
- void SetUp() override {
- auto & mgr = this->component_manager;
- GameObject entity = mgr.new_object("name");
- BehaviorScript & component = entity.add_component<BehaviorScript>();
-
- this->behaviorscript_ref = &component;
- EXPECT_EQ(this->behaviorscript_ref->script.get(), nullptr);
- component.set_script<MyScript>();
- ASSERT_NE(this->behaviorscript_ref->script.get(), nullptr);
-
- this->script_ref = (MyScript *) this->behaviorscript_ref->script.get();
- ASSERT_NE(this->script_ref, nullptr);
- }
-};
+void ScriptTest::SetUp() {
+ auto & mgr = this->component_manager;
+ BehaviorScript & component = entity.add_component<BehaviorScript>();
+
+ this->behaviorscript = component;
+ ASSERT_TRUE(this->behaviorscript);
+ EXPECT_EQ(component.script.get(), nullptr);
+ component.set_script<NiceMock<MyScript>>();
+ ASSERT_NE(component.script.get(), nullptr);
+
+ this->script = *(MyScript *) component.script.get();
+ ASSERT_TRUE(this->script);
+}
TEST_F(ScriptTest, Default) {
- EXPECT_EQ(0, this->script_ref->init_count);
- EXPECT_EQ(0, this->script_ref->update_count);
+ MyScript & script = this->script;
+ EXPECT_CALL(script, init()).Times(0);
+ EXPECT_CALL(script, update()).Times(0);
}
TEST_F(ScriptTest, UpdateOnce) {
- EXPECT_EQ(0, this->script_ref->init_count);
- EXPECT_EQ(0, this->script_ref->update_count);
+ MyScript & script = this->script;
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(script, init()).Times(1);
+ EXPECT_CALL(script, update()).Times(1);
+ system.update();
+ }
- this->system.update();
- EXPECT_EQ(1, this->script_ref->init_count);
- EXPECT_EQ(1, this->script_ref->update_count);
+ {
+ InSequence seq;
+
+ EXPECT_CALL(script, init()).Times(0);
+ EXPECT_CALL(script, update()).Times(1);
+ system.update();
+ }
}
-TEST_F(ScriptTest, ListScripts) {
- size_t script_count = 0;
- for (auto & _ : this->system.get_scripts()) {
- script_count++;
+TEST_F(ScriptTest, UpdateInactive) {
+ BehaviorScript & behaviorscript = this->behaviorscript;
+ MyScript & script = this->script;
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(script, init()).Times(0);
+ EXPECT_CALL(script, update()).Times(0);
+ behaviorscript.active = false;
+ system.update();
+ }
+
+ {
+ InSequence seq;
+
+ EXPECT_CALL(script, init()).Times(1);
+ EXPECT_CALL(script, update()).Times(1);
+ behaviorscript.active = true;
+ system.update();
}
- ASSERT_EQ(1, script_count);
}
diff --git a/src/test/ScriptTest.h b/src/test/ScriptTest.h
new file mode 100644
index 0000000..31fa7c9
--- /dev/null
+++ b/src/test/ScriptTest.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+#include <crepe/api/BehaviorScript.h>
+#include <crepe/api/Script.h>
+#include <crepe/manager/ComponentManager.h>
+#include <crepe/manager/EventManager.h>
+#include <crepe/system/ScriptSystem.h>
+class ScriptTest : public testing::Test {
+protected:
+ crepe::Mediator mediator;
+ static constexpr const char * OBJ_NAME = "foo";
+
+public:
+ crepe::ComponentManager component_manager{mediator};
+ crepe::ScriptSystem system{mediator};
+ crepe::EventManager event_mgr{mediator};
+ crepe::GameObject entity = component_manager.new_object(OBJ_NAME);
+
+ class MyScript : public crepe::Script {
+ // NOTE: explicitly stating `public:` is not required on actual scripts
+
+ public:
+ MOCK_METHOD(void, init, (), (override));
+ MOCK_METHOD(void, update, (), (override));
+ };
+
+ crepe::OptionalRef<crepe::BehaviorScript> behaviorscript;
+ crepe::OptionalRef<MyScript> script;
+
+ virtual void SetUp();
+};
diff --git a/src/test/ValueBrokerTest.cpp b/src/test/ValueBrokerTest.cpp
new file mode 100644
index 0000000..e6bb058
--- /dev/null
+++ b/src/test/ValueBrokerTest.cpp
@@ -0,0 +1,63 @@
+#include <gtest/gtest.h>
+
+#include <crepe/ValueBroker.h>
+#include <crepe/util/Proxy.h>
+
+using namespace std;
+using namespace crepe;
+using namespace testing;
+
+class ValueBrokerTest : public Test {
+public:
+ int read_count = 0;
+ int write_count = 0;
+ int value = 0;
+
+ ValueBroker<int> broker{
+ [this](const int & target) -> void {
+ this->write_count++;
+ this->value = target;
+ },
+ [this]() -> const int & {
+ this->read_count++;
+ return this->value;
+ },
+ };
+ Proxy<int> proxy{broker};
+
+ void SetUp() override {
+ ASSERT_EQ(read_count, 0);
+ ASSERT_EQ(write_count, 0);
+ }
+};
+
+TEST_F(ValueBrokerTest, BrokerWrite) {
+ broker.set(0);
+ EXPECT_EQ(read_count, 0);
+ EXPECT_EQ(write_count, 1);
+}
+
+TEST_F(ValueBrokerTest, BrokerRead) {
+ broker.get();
+ EXPECT_EQ(read_count, 1);
+ EXPECT_EQ(write_count, 0);
+}
+
+TEST_F(ValueBrokerTest, ProxyWrite) {
+ proxy = 0;
+ EXPECT_EQ(read_count, 0);
+ EXPECT_EQ(write_count, 1);
+}
+
+void dummy(int) {}
+TEST_F(ValueBrokerTest, ProxyRead) {
+ dummy(proxy);
+ EXPECT_EQ(read_count, 1);
+ EXPECT_EQ(write_count, 0);
+}
+
+TEST_F(ValueBrokerTest, ProxyReadWrite) {
+ proxy = proxy;
+ ASSERT_EQ(read_count, 1);
+ ASSERT_EQ(write_count, 1);
+}
diff --git a/src/test/Vector2Test.cpp b/src/test/Vector2Test.cpp
new file mode 100644
index 0000000..1e21af9
--- /dev/null
+++ b/src/test/Vector2Test.cpp
@@ -0,0 +1,532 @@
+#include <gtest/gtest.h>
+
+#include <crepe/api/Vector2.h>
+
+using namespace crepe;
+
+class Vector2Test : public ::testing::Test {
+public:
+ Vector2<int> int_vec1;
+ Vector2<int> int_vec2;
+ Vector2<double> double_vec1;
+ Vector2<double> double_vec2;
+ Vector2<long> long_vec1;
+ Vector2<long> long_vec2;
+ Vector2<float> float_vec1;
+ Vector2<float> float_vec2;
+
+ void SetUp() override {
+ int_vec1 = {1, 2};
+ int_vec2 = {3, 4};
+ double_vec1 = {1.0, 2.0};
+ double_vec2 = {3.0, 4.0};
+ long_vec1 = {1, 2};
+ long_vec2 = {3, 4};
+ float_vec1 = {1.0f, 2.0f};
+ float_vec2 = {3.0f, 4.0f};
+ }
+};
+
+TEST_F(Vector2Test, Subtract) {
+ Vector2<int> result = int_vec1 - int_vec2;
+ EXPECT_EQ(result.x, -2);
+ EXPECT_EQ(result.y, -2);
+
+ Vector2<double> result2 = double_vec1 - double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, -2.0);
+ EXPECT_FLOAT_EQ(result2.y, -2.0);
+
+ Vector2<long> result3 = long_vec1 - long_vec2;
+ EXPECT_EQ(result3.x, -2);
+ EXPECT_EQ(result3.y, -2);
+
+ Vector2<float> result4 = float_vec1 - float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, -2.0f);
+ EXPECT_FLOAT_EQ(result4.y, -2.0f);
+}
+
+TEST_F(Vector2Test, SubtractScalar) {
+ Vector2<int> result = int_vec1 - 1;
+ EXPECT_EQ(result.x, 0);
+ EXPECT_EQ(result.y, 1);
+
+ Vector2<double> result2 = double_vec1 - 1.0;
+ EXPECT_FLOAT_EQ(result2.x, 0.0);
+ EXPECT_FLOAT_EQ(result2.y, 1.0);
+
+ Vector2<long> result3 = long_vec1 - 1;
+ EXPECT_EQ(result3.x, 0);
+ EXPECT_EQ(result3.y, 1);
+
+ Vector2<float> result4 = float_vec1 - 1.0f;
+ EXPECT_FLOAT_EQ(result4.x, 0.0f);
+ EXPECT_FLOAT_EQ(result4.y, 1.0f);
+}
+
+TEST_F(Vector2Test, Add) {
+ Vector2<int> result = int_vec1 + int_vec2;
+ EXPECT_EQ(result.x, 4);
+ EXPECT_EQ(result.y, 6);
+
+ Vector2<double> result2 = double_vec1 + double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, 4.0);
+ EXPECT_FLOAT_EQ(result2.y, 6.0);
+
+ Vector2<long> result3 = long_vec1 + long_vec2;
+ EXPECT_EQ(result3.x, 4);
+ EXPECT_EQ(result3.y, 6);
+
+ Vector2<float> result4 = float_vec1 + float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, 4.0f);
+ EXPECT_FLOAT_EQ(result4.y, 6.0f);
+}
+
+TEST_F(Vector2Test, AddScalar) {
+ Vector2<int> result = int_vec1 + 1;
+ EXPECT_EQ(result.x, 2);
+ EXPECT_EQ(result.y, 3);
+
+ Vector2<double> result2 = double_vec1 + 1.0;
+ EXPECT_FLOAT_EQ(result2.x, 2.0);
+ EXPECT_FLOAT_EQ(result2.y, 3.0);
+
+ Vector2<long> result3 = long_vec1 + 1;
+ EXPECT_EQ(result3.x, 2);
+ EXPECT_EQ(result3.y, 3);
+
+ Vector2<float> result4 = float_vec1 + 1.0f;
+ EXPECT_FLOAT_EQ(result4.x, 2.0f);
+ EXPECT_FLOAT_EQ(result4.y, 3.0f);
+}
+
+TEST_F(Vector2Test, Multiply) {
+ Vector2<int> result = int_vec1 * int_vec2;
+ EXPECT_EQ(result.x, 3);
+ EXPECT_EQ(result.y, 8);
+
+ Vector2<double> result2 = double_vec1 * double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, 3.0);
+ EXPECT_FLOAT_EQ(result2.y, 8.0);
+
+ Vector2<long> result3 = long_vec1 * long_vec2;
+ EXPECT_EQ(result3.x, 3);
+ EXPECT_EQ(result3.y, 8);
+
+ Vector2<float> result4 = float_vec1 * float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, 3.0f);
+ EXPECT_FLOAT_EQ(result4.y, 8.0f);
+}
+
+TEST_F(Vector2Test, MultiplyScalar) {
+ Vector2<int> result = int_vec1 * 2;
+ EXPECT_EQ(result.x, 2);
+ EXPECT_EQ(result.y, 4);
+
+ Vector2<double> result2 = double_vec1 * 2.0;
+ EXPECT_FLOAT_EQ(result2.x, 2.0);
+ EXPECT_FLOAT_EQ(result2.y, 4.0);
+
+ Vector2<long> result3 = long_vec1 * 2;
+ EXPECT_EQ(result3.x, 2);
+ EXPECT_EQ(result3.y, 4);
+
+ Vector2<float> result4 = float_vec1 * 2.0f;
+ EXPECT_FLOAT_EQ(result4.x, 2.0f);
+ EXPECT_FLOAT_EQ(result4.y, 4.0f);
+}
+
+TEST_F(Vector2Test, Divide) {
+ Vector2<int> result = int_vec1 / int_vec2;
+ EXPECT_EQ(result.x, 0);
+ EXPECT_EQ(result.y, 0);
+
+ Vector2<double> result2 = double_vec1 / double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, 0.33333333333333331);
+ EXPECT_FLOAT_EQ(result2.y, 0.5);
+
+ Vector2<long> result3 = long_vec1 / long_vec2;
+ EXPECT_EQ(result3.x, 0);
+ EXPECT_EQ(result3.y, 0);
+
+ Vector2<float> result4 = float_vec1 / float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, 0.333333343f);
+ EXPECT_FLOAT_EQ(result4.y, 0.5f);
+}
+
+TEST_F(Vector2Test, DivideScalar) {
+ Vector2<int> result = int_vec1 / 2;
+ EXPECT_EQ(result.x, 0);
+ EXPECT_EQ(result.y, 1);
+
+ Vector2<double> result2 = double_vec1 / 2.0;
+ EXPECT_FLOAT_EQ(result2.x, 0.5);
+ EXPECT_FLOAT_EQ(result2.y, 1.0);
+
+ Vector2<long> result3 = long_vec1 / 2;
+ EXPECT_EQ(result3.x, 0);
+ EXPECT_EQ(result3.y, 1);
+
+ Vector2<float> result4 = float_vec1 / 2.0f;
+ EXPECT_FLOAT_EQ(result4.x, 0.5f);
+ EXPECT_FLOAT_EQ(result4.y, 1.0f);
+}
+
+TEST_F(Vector2Test, AddChain) {
+ Vector2<int> result = int_vec1;
+ result += int_vec2;
+ EXPECT_EQ(result.x, 4);
+ EXPECT_EQ(result.y, 6);
+
+ Vector2<double> result2 = double_vec1;
+ result2 += double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, 4.0);
+ EXPECT_FLOAT_EQ(result2.y, 6.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 += long_vec2;
+ EXPECT_EQ(result3.x, 4);
+ EXPECT_EQ(result3.y, 6);
+
+ Vector2<float> result4 = float_vec1;
+ result4 += float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, 4.0f);
+ EXPECT_FLOAT_EQ(result4.y, 6.0f);
+}
+
+TEST_F(Vector2Test, AddScalarChain) {
+ Vector2<int> result = int_vec1;
+ result += 1;
+ EXPECT_EQ(result.x, 2);
+ EXPECT_EQ(result.y, 3);
+
+ Vector2<double> result2 = double_vec1;
+ result2 += 1.0;
+ EXPECT_FLOAT_EQ(result2.x, 2.0);
+ EXPECT_FLOAT_EQ(result2.y, 3.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 += 1;
+ EXPECT_EQ(result3.x, 2);
+ EXPECT_EQ(result3.y, 3);
+
+ Vector2<float> result4 = float_vec1;
+ result4 += 1.0f;
+ EXPECT_FLOAT_EQ(result4.x, 2.0f);
+ EXPECT_FLOAT_EQ(result4.y, 3.0f);
+}
+
+TEST_F(Vector2Test, SubtractChain) {
+ Vector2<int> result = int_vec1;
+ result -= int_vec2;
+ EXPECT_EQ(result.x, -2);
+ EXPECT_EQ(result.y, -2);
+
+ Vector2<double> result2 = double_vec1;
+ result2 -= double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, -2.0);
+ EXPECT_FLOAT_EQ(result2.y, -2.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 -= long_vec2;
+ EXPECT_EQ(result3.x, -2);
+ EXPECT_EQ(result3.y, -2);
+
+ Vector2<float> result4 = float_vec1;
+ result4 -= float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, -2.0f);
+ EXPECT_FLOAT_EQ(result4.y, -2.0f);
+}
+
+TEST_F(Vector2Test, SubtractScalarChain) {
+ Vector2<int> result = int_vec1;
+ result -= 1;
+ EXPECT_EQ(result.x, 0);
+ EXPECT_EQ(result.y, 1);
+
+ Vector2<double> result2 = double_vec1;
+ result2 -= 1.0;
+ EXPECT_FLOAT_EQ(result2.x, 0.0);
+ EXPECT_FLOAT_EQ(result2.y, 1.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 -= 1;
+ EXPECT_EQ(result3.x, 0);
+ EXPECT_EQ(result3.y, 1);
+
+ Vector2<float> result4 = float_vec1;
+ result4 -= 1.0f;
+ EXPECT_FLOAT_EQ(result4.x, 0.0f);
+ EXPECT_FLOAT_EQ(result4.y, 1.0f);
+}
+
+TEST_F(Vector2Test, MultiplyChain) {
+ Vector2<int> result = int_vec1;
+ result *= int_vec2;
+ EXPECT_EQ(result.x, 3);
+ EXPECT_EQ(result.y, 8);
+
+ Vector2<double> result2 = double_vec1;
+ result2 *= double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, 3.0);
+ EXPECT_FLOAT_EQ(result2.y, 8.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 *= long_vec2;
+ EXPECT_EQ(result3.x, 3);
+ EXPECT_EQ(result3.y, 8);
+
+ Vector2<float> result4 = float_vec1;
+ result4 *= float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, 3.0f);
+ EXPECT_FLOAT_EQ(result4.y, 8.0f);
+}
+
+TEST_F(Vector2Test, MultiplyScalarChain) {
+ Vector2<int> result = int_vec1;
+ result *= 2;
+ EXPECT_EQ(result.x, 2);
+ EXPECT_EQ(result.y, 4);
+
+ Vector2<double> result2 = double_vec1;
+ result2 *= 2.0;
+ EXPECT_FLOAT_EQ(result2.x, 2.0);
+ EXPECT_FLOAT_EQ(result2.y, 4.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 *= 2;
+ EXPECT_EQ(result3.x, 2);
+ EXPECT_EQ(result3.y, 4);
+
+ Vector2<float> result4 = float_vec1;
+ result4 *= 2.0f;
+ EXPECT_FLOAT_EQ(result4.x, 2.0f);
+ EXPECT_FLOAT_EQ(result4.y, 4.0f);
+}
+
+TEST_F(Vector2Test, DivideChain) {
+ Vector2<int> result = int_vec1;
+ result /= int_vec2;
+ EXPECT_EQ(result.x, 0);
+ EXPECT_EQ(result.y, 0);
+
+ Vector2<double> result2 = double_vec1;
+ result2 /= double_vec2;
+ EXPECT_FLOAT_EQ(result2.x, 0.33333333333333331);
+ EXPECT_FLOAT_EQ(result2.y, 0.5);
+
+ Vector2<long> result3 = long_vec1;
+ result3 /= long_vec2;
+ EXPECT_EQ(result3.x, 0);
+ EXPECT_EQ(result3.y, 0);
+
+ Vector2<float> result4 = float_vec1;
+ result4 /= float_vec2;
+ EXPECT_FLOAT_EQ(result4.x, 0.333333343f);
+ EXPECT_FLOAT_EQ(result4.y, 0.5f);
+}
+
+TEST_F(Vector2Test, DivideScalarChain) {
+ Vector2<int> result = int_vec1;
+ result /= 2;
+ EXPECT_EQ(result.x, 0);
+ EXPECT_EQ(result.y, 1);
+
+ Vector2<double> result2 = double_vec1;
+ result2 /= 2.0;
+ EXPECT_FLOAT_EQ(result2.x, 0.5);
+ EXPECT_FLOAT_EQ(result2.y, 1.0);
+
+ Vector2<long> result3 = long_vec1;
+ result3 /= 2;
+ EXPECT_EQ(result3.x, 0);
+ EXPECT_EQ(result3.y, 1);
+
+ Vector2<float> result4 = float_vec1;
+ result4 /= 2.0f;
+ EXPECT_FLOAT_EQ(result4.x, 0.5f);
+ EXPECT_FLOAT_EQ(result4.y, 1.0f);
+}
+
+TEST_F(Vector2Test, Negatation) {
+ Vector2<int> result = -int_vec1;
+ EXPECT_EQ(result.x, -1);
+ EXPECT_EQ(result.y, -2);
+
+ Vector2<double> result2 = -double_vec1;
+ EXPECT_FLOAT_EQ(result2.x, -1.0);
+ EXPECT_FLOAT_EQ(result2.y, -2.0);
+
+ Vector2<long> result3 = -long_vec1;
+ EXPECT_EQ(result3.x, -1);
+ EXPECT_EQ(result3.y, -2);
+
+ Vector2<float> result4 = -float_vec1;
+ EXPECT_FLOAT_EQ(result4.x, -1.0f);
+ EXPECT_FLOAT_EQ(result4.y, -2.0f);
+}
+
+TEST_F(Vector2Test, Equals) {
+ EXPECT_TRUE(int_vec1 == int_vec1);
+ EXPECT_FALSE(int_vec1 == int_vec2);
+ EXPECT_TRUE(double_vec1 == double_vec1);
+ EXPECT_FALSE(double_vec1 == double_vec2);
+ EXPECT_TRUE(long_vec1 == long_vec1);
+ EXPECT_FALSE(long_vec1 == long_vec2);
+}
+
+TEST_F(Vector2Test, NotEquals) {
+ EXPECT_FALSE(int_vec1 != int_vec1);
+ EXPECT_TRUE(int_vec1 != int_vec2);
+ EXPECT_FALSE(double_vec1 != double_vec1);
+ EXPECT_TRUE(double_vec1 != double_vec2);
+ EXPECT_FALSE(long_vec1 != long_vec1);
+ EXPECT_TRUE(long_vec1 != long_vec2);
+}
+
+TEST_F(Vector2Test, Truncate) {
+ Vector2<int> vec = {3, 4};
+ vec.truncate(3);
+ EXPECT_EQ(vec.x, 0);
+ EXPECT_EQ(vec.y, 0);
+
+ Vector2<double> vec2 = {3.0, 4.0};
+ vec2.truncate(3.0);
+ EXPECT_FLOAT_EQ(vec2.x, 1.8);
+ EXPECT_FLOAT_EQ(vec2.y, 2.4);
+
+ Vector2<long> vec3 = {3, 4};
+ vec3.truncate(3);
+ EXPECT_EQ(vec3.x, 0);
+ EXPECT_EQ(vec3.y, 0);
+
+ Vector2<float> vec4 = {3.0f, 4.0f};
+ vec4.truncate(3.0f);
+ EXPECT_FLOAT_EQ(vec4.x, 1.8f);
+ EXPECT_FLOAT_EQ(vec4.y, 2.4f);
+}
+
+TEST_F(Vector2Test, Normalize) {
+ Vector2<int> vec = {3, 4};
+ vec.normalize();
+ EXPECT_EQ(vec.x, 0);
+ EXPECT_EQ(vec.y, 0);
+
+ Vector2<double> vec2 = {3.0, 4.0};
+ vec2.normalize();
+ EXPECT_FLOAT_EQ(vec2.x, 0.6);
+ EXPECT_FLOAT_EQ(vec2.y, 0.8);
+
+ Vector2<long> vec3 = {3, 4};
+ vec3.normalize();
+ EXPECT_EQ(vec3.x, 0);
+ EXPECT_EQ(vec3.y, 0);
+
+ Vector2<float> vec4 = {3.0f, 4.0f};
+ vec4.normalize();
+ EXPECT_FLOAT_EQ(vec4.x, 0.6f);
+ EXPECT_FLOAT_EQ(vec4.y, 0.8f);
+}
+
+TEST_F(Vector2Test, Length) {
+ Vector2<int> vec = {3, 4};
+ EXPECT_EQ(vec.length(), 5);
+
+ Vector2<double> vec2 = {3.0, 4.0};
+ EXPECT_FLOAT_EQ(vec2.length(), 5.0);
+
+ Vector2<long> vec3 = {3, 4};
+ EXPECT_EQ(vec3.length(), 5);
+
+ Vector2<float> vec4 = {3.0f, 4.0f};
+ EXPECT_FLOAT_EQ(vec4.length(), 5.0f);
+}
+
+TEST_F(Vector2Test, LengthSquared) {
+ Vector2<int> vec = {3, 4};
+ EXPECT_EQ(vec.length_squared(), 25);
+
+ Vector2<double> vec2 = {3.0, 4.0};
+ EXPECT_FLOAT_EQ(vec2.length_squared(), 25.0);
+
+ Vector2<long> vec3 = {3, 4};
+ EXPECT_EQ(vec3.length_squared(), 25);
+
+ Vector2<float> vec4 = {3.0f, 4.0f};
+ EXPECT_FLOAT_EQ(vec4.length_squared(), 25.0f);
+}
+
+TEST_F(Vector2Test, Dot) {
+ Vector2<int> vec1 = {3, 4};
+ Vector2<int> vec2 = {5, 6};
+ EXPECT_EQ(vec1.dot(vec2), 39);
+
+ Vector2<double> vec3 = {3.0, 4.0};
+ Vector2<double> vec4 = {5.0, 6.0};
+ EXPECT_FLOAT_EQ(vec3.dot(vec4), 39.0);
+
+ Vector2<long> vec5 = {3, 4};
+ Vector2<long> vec6 = {5, 6};
+ EXPECT_EQ(vec5.dot(vec6), 39);
+
+ Vector2<float> vec7 = {3.0f, 4.0f};
+ Vector2<float> vec8 = {5.0f, 6.0f};
+ EXPECT_FLOAT_EQ(vec7.dot(vec8), 39.0f);
+}
+
+TEST_F(Vector2Test, Distance) {
+ Vector2<int> vec1 = {1, 1};
+ Vector2<int> vec2 = {4, 5};
+ EXPECT_EQ(vec1.distance(vec2), 5);
+
+ Vector2<double> vec3 = {1.0, 1.0};
+ Vector2<double> vec4 = {4.0, 5.0};
+ EXPECT_FLOAT_EQ(vec3.distance(vec4), 5.0);
+
+ Vector2<long> vec5 = {1, 1};
+ Vector2<long> vec6 = {4, 5};
+ EXPECT_EQ(vec5.distance(vec6), 5);
+
+ Vector2<float> vec7 = {1.0f, 1.0f};
+ Vector2<float> vec8 = {4.0f, 5.0f};
+ EXPECT_FLOAT_EQ(vec7.distance(vec8), 5.0f);
+}
+
+TEST_F(Vector2Test, DistanceSquared) {
+ Vector2<int> vec1 = {3, 4};
+ Vector2<int> vec2 = {5, 6};
+ EXPECT_EQ(vec1.distance_squared(vec2), 8);
+
+ Vector2<double> vec3 = {3.0, 4.0};
+ Vector2<double> vec4 = {5.0, 6.0};
+ EXPECT_FLOAT_EQ(vec3.distance_squared(vec4), 8.0);
+
+ Vector2<long> vec5 = {3, 4};
+ Vector2<long> vec6 = {5, 6};
+ EXPECT_EQ(vec5.distance_squared(vec6), 8);
+
+ Vector2<float> vec7 = {3.0f, 4.0f};
+ Vector2<float> vec8 = {5.0f, 6.0f};
+ EXPECT_FLOAT_EQ(vec7.distance_squared(vec8), 8.0f);
+}
+
+TEST_F(Vector2Test, Perpendicular) {
+ Vector2<int> vec = {3, 4};
+ Vector2<int> result = vec.perpendicular();
+ EXPECT_EQ(result.x, -4);
+ EXPECT_EQ(result.y, 3);
+
+ Vector2<double> vec2 = {3.0, 4.0};
+ Vector2<double> result2 = vec2.perpendicular();
+ EXPECT_FLOAT_EQ(result2.x, -4.0);
+ EXPECT_FLOAT_EQ(result2.y, 3.0);
+
+ Vector2<long> vec3 = {3, 4};
+ Vector2<long> result3 = vec3.perpendicular();
+ EXPECT_EQ(result3.x, -4);
+ EXPECT_EQ(result3.y, 3);
+
+ Vector2<float> vec4 = {3.0f, 4.0f};
+ Vector2<float> result4 = vec4.perpendicular();
+ EXPECT_FLOAT_EQ(result4.x, -4.0f);
+ EXPECT_FLOAT_EQ(result4.y, 3.0f);
+}
diff --git a/src/test/main.cpp b/src/test/main.cpp
index 19a8d6e..0e1bc75 100644
--- a/src/test/main.cpp
+++ b/src/test/main.cpp
@@ -1,7 +1,7 @@
-#include <crepe/api/Config.h>
-
#include <gtest/gtest.h>
+#include <crepe/api/Config.h>
+
using namespace crepe;
using namespace testing;
@@ -11,7 +11,11 @@ public:
// This function is called before each test
void OnTestStart(const TestInfo &) override {
- cfg.log.level = Log::Level::WARNING;
+ cfg = {
+ .log = {
+ .level = Log::Level::WARNING,
+ },
+ };
}
};
@@ -23,4 +27,3 @@ int main(int argc, char ** argv) {
return RUN_ALL_TESTS();
}
-