diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 216b137..d932bf3 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -11,7 +11,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true - name: Install Libraries run: | @@ -19,7 +21,7 @@ jobs: sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev libsdl2-gfx-dev - name: Run CMake - run: cmake -G "Unix Makefiles" . + run: cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make run: make -j4 diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index d3b93b2..1405d20 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -11,14 +11,18 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true + + - uses: seanmiddleditch/gha-setup-ninja@master - name: Install Libraries run: | brew install sdl2 sdl2_image sdl2_gfx sdl2_ttf sdl2_mixer - name: Run CMake - run: cmake -G "Unix Makefiles" . + run: cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make run: | diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 3711181..bb50a8a 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -11,15 +11,19 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true + + - uses: seanmiddleditch/gha-setup-ninja@master - name: Setup Emscripten - uses: mymindstorm/setup-emsdk@v7 + uses: mymindstorm/setup-emsdk@v11 with: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Unix Makefiles" . + run: emcmake cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make - run: emmake make -j4 + run: make -j4 diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index ae3fd74..0995952 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -8,22 +8,35 @@ jobs: build: name: Build Windows runs-on: windows-latest + defaults: + run: + shell: msys2 {0} steps: - - name: Checkout - uses: actions/checkout@v2 + - uses: msys2/setup-msys2@v2 + with: + update: true + install: >- + make + git + mingw-w64-x86_64-gcc-libs + mingw-w64-x86_64-SDL2 + mingw-w64-x86_64-SDL2_mixer + mingw-w64-x86_64-SDL2_image + mingw-w64-x86_64-SDL2_ttf + mingw-w64-x86_64-SDL2_gfx + pacboy: >- + toolchain:p + cmake:p + ninja:p - - name: Install Libraries - run: | - Set-Item -Path Env:Path -Value ("C:/msys64/usr/bin;" + $Env:Path) - pacman --noconfirm -S mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: true - name: Run CMake - run: | - Set-Item -Path Env:Path -Value ("C:/msys64/mingw32/bin;" + $Env:Path) - cmake -G "MSYS Makefiles" . + run: cmake -G Ninja . -DCMAKE_BUILD_TYPE=Release - name: Make - run: | - Set-Item -Path Env:Path -Value ("C:/msys64/mingw32/bin;" + $Env:Path) - make -j4 + run: ninja diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b5d73ae..af488b6 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -11,18 +11,22 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 + with: + submodules: true + + - uses: seanmiddleditch/gha-setup-ninja@master - name: Setup Emscripten - uses: mymindstorm/setup-emsdk@v7 + uses: mymindstorm/setup-emsdk@v11 with: actions-cache-folder: "emsdk-cache" - name: Run CMake - run: emcmake cmake -G "Unix Makefiles" . + run: emcmake cmake -G "Unix Makefiles" . -DCMAKE_BUILD_TYPE=Release - name: Make - run: emmake make -j4 + run: ninja - name: Install graphviz run: sudo apt install graphviz @@ -33,7 +37,7 @@ jobs: doxyfile-path: "./Doxyfile" - name: Copy Bin to Docs - run: sudo cp -r ./bin ./docs/examples + run: sudo cp -r ./build/examples ./docs/examples - name: Deploy docs uses: peaceiris/actions-gh-pages@v3 diff --git a/.gitignore b/.gitignore index 0c6d177..7d95a29 100644 --- a/.gitignore +++ b/.gitignore @@ -41,11 +41,7 @@ Icon .Trashes CppCheckResults.xml -CMakeFiles -CMakeCache.txt -Makefile -*.cmake -install_manifest.txt -bin -docs -lib \ No newline at end of file +docs/ +.idea/ +build/ +Testing/ \ No newline at end of file diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index 9692d48..aa7c728 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -5,7 +5,8 @@ "intelliSenseMode": "gcc-x86", "cStandard": "c11", "cppStandard": "c++17", - "includePath": ["include"] + "includePath": ["afk/include"], + "compileCommands": "${workspaceFolder}/build/compile_commands.json" } ], "version": 4 diff --git a/.vscode/settings.json b/.vscode/settings.json index a76a135..b704bce 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -111,7 +111,12 @@ "filesystem": "cpp", "unordered_set": "cpp", "*.inc": "cpp", - "*.def": "cpp" + "*.def": "cpp", + "numbers": "cpp", + "semaphore": "cpp", + "any": "cpp", + "codecvt": "cpp" }, - "cmake.configureOnOpen": true -} \ No newline at end of file + "cmake.configureOnOpen": true, + "sonarlint.pathToCompileCommands": "c:\\Users\\alege\\Documents\\GitHub\\AfkLib\\build\\compile_commands.json" +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 435c849..c067766 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -2,14 +2,25 @@ "version": "2.0.0", "tasks": [ { - "label": "Build", - "type": "shell", - "command": "make -j24", + "type": "cppbuild", + "label": "C/C++: g++.exe build active file", + "command": "g++.exe", + "args": [ + "-fdiagnostics-color=always", + "-g", + "${file}", + "-o", + "${fileDirname}\\${fileBasenameNoExtension}.exe" + ], + "options": { + "cwd": "${fileDirname}" + }, "problemMatcher": ["$gcc"], "group": { "kind": "build", "isDefault": true - } + }, + "detail": "Task generated by Debugger." } ] } diff --git a/CMakeLists.txt b/CMakeLists.txt index 54a7f2b..748f6e6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,109 +1,13 @@ -cmake_minimum_required(VERSION 3.11) +cmake_minimum_required(VERSION 3.16) -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +project (root) -project (afk VERSION 1.0.0 LANGUAGES CXX) +# Config +set(CMAKE_EXPORT_COMPILE_COMMANDS on) +set(EXTERNAL_DIR ${PROJECT_SOURCE_DIR}/lib) -# Add sources -file(GLOB_RECURSE SOURCES ${CMAKE_BINARY_DIR}/src/*.cpp) -file(GLOB_RECURSE HEADERS ${CMAKE_BINARY_DIR}/include/*.h) - -# Create lib -add_library(${PROJECT_NAME} STATIC ${SOURCES} ${HEADERS}) - -# Add compile options -target_compile_options(${PROJECT_NAME} PRIVATE -O2 -Wall -Wextra -pedantic) - -# Add include -target_include_directories(${PROJECT_NAME} PUBLIC - $ - $ - PRIVATE src) - -# Versioning -set_target_properties(${PROJECT_NAME} PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION 1) - -if(EMSCRIPTEN) - target_compile_options( - ${PROJECT_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - ) - target_link_libraries( - ${PROJECT_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - -sDEMANGLE_SUPPORT=1 - ) - target_link_libraries(${PROJECT_NAME} -sUSE_SDL=2 -fsanitize=address) -else(EMSCRIPTEN) - # Find libs - find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) - find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) - find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) - find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) - find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) - find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) - - # Link Libs - target_link_libraries(${PROJECT_NAME} ${SDL_LIBRARY} ${SDL_MIXER_LIBRARY} ${SDL_IMAGE_LIBRARY} ${SDL_TTF_LIBRARY} ${SDL_GFX_LIBRARY} ${SDL_MAIN_LIBRARY}) -endif(EMSCRIPTEN) - -# Install info -if (EMSCRIPTEN) - if (NOT CMAKE_TOOLCHAIN_FILE) - message("CMAKE_TOOLCHAIN_FILE not provided, can not automatically install") - else() - get_filename_component(EMSDK_DIR ${CMAKE_TOOLCHAIN_FILE} DIRECTORY) - set(EMSDK_DIR ${EMSDK_DIR}/../../../system) - message("Lib install directory set to ${EMSDK_DIR}") - - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${EMSDK_DIR}/lib - LIBRARY DESTINATION ${EMSDK_DIR}/lib - RUNTIME DESTINATION ${EMSDK_DIR}/bin) - - install(DIRECTORY include/ DESTINATION ${EMSDK_DIR}/include/${PROJECT_NAME}) - endif() -elseif (WIN32) - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION C:/msys64/mingw32/lib - LIBRARY DESTINATION C:/msys64/mingw32/lib - RUNTIME DESTINATION C:/msys64/mingw32/bin) - - install(DIRECTORY include/ DESTINATION C:/msys64/mingw32/include/${PROJECT_NAME}) - - install(EXPORT ${PROJECT_NAME} DESTINATION C:/msys64/mingw32/share/${PROJECT_NAME}/cmake) - export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) -else() - include(GNUInstallDirs) - - install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) - - install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) - - install(EXPORT ${PROJECT_NAME} DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake) - export(TARGETS ${PROJECT_NAME} FILE ${PROJECT_NAME}.cmake) -endif() +# Core lib +add_subdirectory(${PROJECT_SOURCE_DIR}/afk) # Examples -include(${CMAKE_BINARY_DIR}/examples/CMakeLists.txt) \ No newline at end of file +add_subdirectory(${PROJECT_SOURCE_DIR}/examples) \ No newline at end of file diff --git a/README.md b/README.md index 3b040d8..d6683e1 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Allans FrameworK +# Allan's FrameworK ![Build Windows](https://github.com/AdsGames/AfkLib/workflows/Build%20Windows/badge.svg) ![Build Linux](https://github.com/AdsGames/AfkLib/workflows/Build%20Linux/badge.svg) @@ -30,7 +30,7 @@ Game framework ### Windows (MSYS2) ```bash -pacman -S mingw-w64-i686-gcc-libs mingw-w64-i686-SDL2 mingw-w64-i686-SDL2_mixer mingw-w64-i686-SDL2_image mingw-w64-i686-SDL2_ttf mingw-w64-i686-SDL2_gfx +pacman -S mingw-w64-x86_64-gcc-libs mingw-w64-x86_64-SDL2 mingw-w64-x86_64-SDL2_mixer mingw-w64-x86_64-SDL2_image mingw-w64-x86_64-SDL2_ttf mingw-w64-x86_64-SDL2_gfx ``` ### Mac OS @@ -48,7 +48,9 @@ sudo apt install libsdl2-dev libsdl2-image-dev libsdl2-ttf-dev libsdl2-mixer-dev ### Build ```bash -cmake . +mkdir build +cd build +cmake ../ ``` ```bash @@ -58,7 +60,9 @@ make ### Build Emscripten ```bash -emcmake cmake . +mkdir build +cd build +emcmake cmake ../ ``` ```bash @@ -68,5 +72,6 @@ make ### Install Library (works for emscripten) ```bash +cd build make install ``` diff --git a/afk/CMakeLists.txt b/afk/CMakeLists.txt new file mode 100644 index 0000000..09d60ed --- /dev/null +++ b/afk/CMakeLists.txt @@ -0,0 +1,92 @@ +cmake_minimum_required(VERSION 3.16) + +project (afk + VERSION 1.0.0 + LANGUAGES CXX +) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Sources +file(GLOB_RECURSE SOURCES ${PROJECT_SOURCE_DIR}/src/*.cpp) +file(GLOB_RECURSE HEADERS ${PROJECT_SOURCE_DIR}/include/*.h) + +# Lib +add_library(${PROJECT_NAME} + STATIC + ${SOURCES} + ${HEADERS} +) + +target_include_directories(${PROJECT_NAME} + PUBLIC + $ + $ + PRIVATE + ${EXTERNAL_INCLUDE_DIRS} +) + +target_compile_options(${PROJECT_NAME} + PRIVATE + -Wall + -Wextra + -pedantic +) + +set_target_properties(${PROJECT_NAME} + PROPERTIES + VERSION ${PROJECT_VERSION} + SOVERSION 1 +) + +# Emscripten specific options +if(EMSCRIPTEN) + target_compile_options(${PROJECT_NAME} + PRIVATE + -sUSE_SDL=2 + -sUSE_SDL_IMAGE=2 + -sUSE_SDL_TTF=2 + -sUSE_SDL_MIXER=2 + -sUSE_SDL_GFX=2 + ) + + set(EXTERNAL_INCLUDE_LIBS ${EXTERNAL_INCLUDE_LIBS} -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sUSE_SDL_TTF=2 -sUSE_SDL_MIXER=2 -sUSE_SDL_GFX=2) +endif(EMSCRIPTEN) + +# Link link libraries +include(${EXTERNAL_DIR}/libs.cmake) + +target_link_libraries(${PROJECT_NAME} PRIVATE ${EXTERNAL_INCLUDE_LIBS}) + +# Install info +IF(MINGW) + get_filename_component(BINARY_PATH ${CMAKE_C_COMPILER} PATH) + set(CMAKE_INSTALL_PREFIX ${BINARY_PATH}/..) +endif(MINGW) + +include(GNUInstallDirs) + +message(STATUS "Lib install directory set to ${CMAKE_INSTALL_PREFIX}") + +install( + TARGETS ${PROJECT_NAME} + EXPORT ${PROJECT_NAME} + ARCHIVE DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR} +) + +install( + DIRECTORY include/ + DESTINATION ${CMAKE_INSTALL_FULL_INCLUDEDIR}/${PROJECT_NAME} +) + +install( + EXPORT ${PROJECT_NAME} + DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}/cmake/${PROJECT_NAME} +) + +install( + FILES ${EXTERNAL_DIR}/${PROJECT_NAME}-config.cmake + DESTINATION ${CMAKE_INSTALL_FULL_LIBDIR}/cmake/${PROJECT_NAME} +) diff --git a/include/Game.h b/afk/include/Game.h similarity index 83% rename from include/Game.h rename to afk/include/Game.h index 64e385f..90659ea 100644 --- a/include/Game.h +++ b/afk/include/Game.h @@ -8,9 +8,10 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_GAME_H_ -#define INCLUDE_GAME_H_ +#ifndef AFK_GAME_H +#define AFK_GAME_H +#include #include #include "services/Service.h" @@ -40,21 +41,21 @@ class Game : public Service { * * @return name */ - std::string getName() const; + std::string getName() const override; /** * @brief Starts the main game loop * * @param scene_id Initial scene to start with */ - void start(); + void start() const; /** * @brief Notify about changes in queue * * @param ev event to be processed */ - void notify(const SDL_Event& ev); + void notify(const SDL_Event& ev) override; private: /** @@ -69,4 +70,4 @@ class Game : public Service { } // namespace afk -#endif // INCLUDE_GAME_H_ +#endif // AFK_GAME_H diff --git a/include/assets/Font.h b/afk/include/assets/Font.h similarity index 78% rename from include/assets/Font.h rename to afk/include/assets/Font.h index 0f736f6..7481286 100644 --- a/include/assets/Font.h +++ b/afk/include/assets/Font.h @@ -8,17 +8,17 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_FONT_H_ -#define INCLUDE_ASSETS_FONT_H_ +#ifndef AFK_FONT_H +#define AFK_FONT_H #include #include -#include "../color/Color.h" +#include "../common/Color.h" namespace afk { -enum class TextAlign { LEFT, RIGHT, CENTER }; +enum class TextAlign { Left, Right, Center }; /** * @brief Easy interface to interact with SDL fonts @@ -38,7 +38,7 @@ class Font { * @param size Size of font to load * @throws FileIOException If font can not be found at path */ - Font(const std::string& path, const int size); + Font(const std::string& path, int size); /** * @brief Load and assign font from given path @@ -47,7 +47,7 @@ class Font { * @param size Size of font to load * @throws FileIOException If font can not be found at path */ - void load(const std::string& path, const int size); + void load(const std::string& path, int size); /** * @brief Draw font at position @@ -58,11 +58,11 @@ class Font { * @param colour colour to colour text * @param align Text alignment, defaults to left */ - void draw(const int x, - const int y, + void draw(int x, + int y, const std::string& text, - const color::Color colour = color::black, - const TextAlign align = TextAlign::LEFT); + color::Color colour = color::black, + TextAlign align = TextAlign::Left); /** * @brief Get the height of the font @@ -84,7 +84,7 @@ class Font { * * @return Size of font loaded */ - int getSize(); + int getSize() const; /** * @brief Check if font has been loaded @@ -103,13 +103,13 @@ class Font { * @return TTF_Font* File that has been loaded * @throws FileIOException If font can not be found at path */ - static TTF_Font* loadFont(const std::string& path, const int size); + static TTF_Font* loadFont(const std::string& path, int size); /// Pointer to referenced font TTF_Font* font; /// Size of font - int font_size; + int fontSize; /** * @brief Helper for rendering text @@ -120,10 +120,10 @@ class Font { * @return SDL_Texture* New texture containing string */ SDL_Texture* renderText(SDL_Renderer* renderer, - const std::string text, - const color::Color colour); + const std::string& text, + color::Color colour); }; } // namespace afk -#endif // INCLUDE_ASSETS_FONT_H_ +#endif // AFK_FONT_H diff --git a/include/assets/Sound.h b/afk/include/assets/Sound.h similarity index 83% rename from include/assets/Sound.h rename to afk/include/assets/Sound.h index 21db98a..540da90 100644 --- a/include/assets/Sound.h +++ b/afk/include/assets/Sound.h @@ -10,10 +10,12 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_SOUND_H_ -#define INCLUDE_ASSETS_SOUND_H_ +#ifndef AFK_SOUND_H +#define AFK_SOUND_H +#include #include +#include #include namespace afk { @@ -54,10 +56,10 @@ class Sound { * @param speed Speed (unused) * @param loop Loop mode */ - void play(const float gain = 1.0f, - const float pan = 0.0f, - const float speed = 1.0f, - const bool loop = false); + void play(float gain = 1.0f, + float pan = 0.0f, + float speed = 1.0f, + bool loop = false); private: /** @@ -73,12 +75,12 @@ class Sound { Mix_Chunk* sample; /// Allocated channel - Uint32 channel; + int32_t channel; /// Current number of channels - static Uint32 channel_counter; + static uint32_t channelCounter; }; } // namespace afk -#endif // INCLUDE_ASSETS_SOUND_H_ +#endif // AFK_SOUND_H diff --git a/include/assets/Stream.h b/afk/include/assets/Stream.h similarity index 92% rename from include/assets/Stream.h rename to afk/include/assets/Stream.h index 80bd6ff..67c6bb9 100644 --- a/include/assets/Stream.h +++ b/afk/include/assets/Stream.h @@ -9,8 +9,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_STREAM_H_ -#define INCLUDE_ASSETS_STREAM_H_ +#ifndef AFK_STREAM_H +#define AFK_STREAM_H #include #include @@ -43,7 +43,7 @@ class Stream { * * @param loop Loop mode */ - void play(const bool loop = false); + void play(bool loop = false); /** * @brief Stop this instance of the stream from playing @@ -82,4 +82,4 @@ class Stream { } // namespace afk -#endif // INCLUDE_ASSETS_STREAM_H_ +#endif // AFK_STREAM_H diff --git a/include/assets/Texture.h b/afk/include/assets/Texture.h similarity index 73% rename from include/assets/Texture.h rename to afk/include/assets/Texture.h index 5dd5dfb..3cb3ab1 100644 --- a/include/assets/Texture.h +++ b/afk/include/assets/Texture.h @@ -8,13 +8,14 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ASSETS_TEXTURE_H_ -#define INCLUDE_ASSETS_TEXTURE_H_ +#ifndef AFK_TEXTURE_H +#define AFK_TEXTURE_H #include #include -#include "../color/Color.h" +#include "../common/Color.h" +#include "../common/Vec.h" namespace afk { @@ -23,9 +24,9 @@ namespace afk { * */ enum class TextureDrawMode { - DEFAULT = 0, - FLIP_H = 2, - FLIP_V = 1, + Default = 0, + FlipH = 2, + FlipV = 1, }; /** @@ -62,7 +63,7 @@ class Texture { * @param width Width in pixels * @param height Height in pixels */ - void create(const int width, const int height); + void create(int width, int height); /** * @brief Draw bitmap to screen @@ -71,7 +72,7 @@ class Texture { * @param y Y position to draw to * @see drawScaled */ - void draw(const int x, const int y) const; + void draw(int x, int y) const; /** * @brief Draw scaled texture to screen @@ -81,28 +82,21 @@ class Texture { * @param width Width to scale to * @param height Height to scale to * @param angle Rotation of draw - * @param mode Optinal draw mode + * @param mode Optional draw mode */ - void drawEx(const int x, - const int y, - const int width, - const int height, - const float angle = 0.0f, - const TextureDrawMode mode = TextureDrawMode::DEFAULT) const; + void drawEx(int x, + int y, + int width, + int height, + float angle = 0.0f, + TextureDrawMode mode = TextureDrawMode::Default) const; /** - * @brief Get the width of the texture + * @brief Get the size of the texture * - * @return Width of texture + * @return Size of texture */ - int getWidth() const; - - /** - * @brief Get the height of the texture - * - * @return Height of texture - */ - int getHeight() const; + Vec2 getSize(); /** * @brief Check if texture has been loaded @@ -112,6 +106,12 @@ class Texture { bool exists() const; private: + /** + * @brief Calculate and set size of texture + * + */ + void calculateSize(); + /** * @brief Helper which loads an SDL_Texture* from a file * @@ -123,8 +123,11 @@ class Texture { /// Pointer to referenced texture SDL_Texture* texture; + + /// Size of texture + Vec2 size; }; } // namespace afk -#endif // INCLUDE_ASSETS_TEXTURE_H_ +#endif // AFK_TEXTURE_H diff --git a/include/color/Color.h b/afk/include/common/Color.h similarity index 65% rename from include/color/Color.h rename to afk/include/common/Color.h index ce9fc4a..de74141 100644 --- a/include/color/Color.h +++ b/afk/include/common/Color.h @@ -8,23 +8,22 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COLOR_COLOR_H_ -#define INCLUDE_COLOR_COLOR_H_ +#ifndef AFK_COLOR_H +#define AFK_COLOR_H -#include +#include -namespace afk { -namespace color { +namespace afk::color { // Color struct Color { - Uint8 r; - Uint8 g; - Uint8 b; - Uint8 a; + uint8_t r; + uint8_t g; + uint8_t b; + uint8_t a; }; -// Color defenitions +// Color definitions static const Color black = {0, 0, 0, 255}; static const Color white = {255, 255, 255, 255}; static const Color red = {255, 0, 0, 255}; @@ -42,7 +41,7 @@ static const Color purple = {0, 255, 255, 255}; * @param b Blue value * @return Color */ -Color rgb(const Uint8 r, const Uint8 g, const Uint8 b); +Color rgb(uint8_t r, uint8_t g, uint8_t b); /** * @brief Create SDL Color from rgba values @@ -53,7 +52,7 @@ Color rgb(const Uint8 r, const Uint8 g, const Uint8 b); * @param a Alpha value * @return Color */ -Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); +Color rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a); /** * @brief Convert int representation of color to an Color @@ -61,7 +60,7 @@ Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); * @param colour Integer representation of color * @return Color */ -Color intToColor(const Uint32 colour); +Color intToColor(uint32_t colour); /** * @brief Convert rgb values to an integer color @@ -69,9 +68,9 @@ Color intToColor(const Uint32 colour); * @param r Red value * @param g Green value * @param b Blue value - * @return Uint32 + * @return uint32_t */ -Uint32 rgbToInt(const Uint8 r, const Uint8 g, const Uint8 b); +uint32_t rgbToInt(uint8_t r, uint8_t g, uint8_t b); /** * @brief Convert rgba values to an integer color @@ -80,19 +79,18 @@ Uint32 rgbToInt(const Uint8 r, const Uint8 g, const Uint8 b); * @param g Green value * @param b Blue value * @param a Alpha value - * @return Uint32 + * @return uint32_t */ -Uint32 rgbaToInt(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a); +uint32_t rgbaToInt(uint8_t r, uint8_t g, uint8_t b, uint8_t a); /** - * @brief Convert Color to Uint32 representation + * @brief Convert Color to uint32_t representation * * @param colour Color to convert - * @return Uint32 + * @return uint32_t */ -Uint32 colorToInt(const Color colour); +uint32_t colorToInt(Color colour); -} // namespace color -} // namespace afk +} // namespace afk::color -#endif // INCLUDE_COLOR_COLOR_H_ +#endif // AFK_COLOR_H diff --git a/include/common/Exceptions.h b/afk/include/common/Exceptions.h similarity index 87% rename from include/common/Exceptions.h rename to afk/include/common/Exceptions.h index 3313a69..f5fd74e 100644 --- a/include/common/Exceptions.h +++ b/afk/include/common/Exceptions.h @@ -1,7 +1,7 @@ /** * @file Exceptions.h * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Interally used exceptions. These can be handled properly in the main + * @brief Internally used exceptions. These can be handled properly in the main * game class. * @version 0.1 * @date 2021-03-08 @@ -9,8 +9,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMMON_EXCEPTIONS_H_ -#define INCLUDE_COMMON_EXCEPTIONS_H_ +#ifndef AFK_EXCEPTIONS_H +#define AFK_EXCEPTIONS_H #include #include @@ -21,14 +21,14 @@ namespace afk { * @brief Exception raised when a file is not found * */ -class FileIOException : public std::runtime_error { +class FileIoException : public std::runtime_error { public: /** * @brief Construct a new File I O Exception object * * @param msg Message to pass to runtime_error. */ - explicit FileIOException(const std::string& msg) : std::runtime_error(msg) {} + explicit FileIoException(const std::string& msg) : std::runtime_error(msg) {} }; /** @@ -106,7 +106,7 @@ class SceneLookupException : public std::runtime_error { }; /** - * @brief Exception raised when an assertian fails + * @brief Exception raised when an assertion fails * */ class AssertionFailedException : public std::runtime_error { @@ -122,4 +122,4 @@ class AssertionFailedException : public std::runtime_error { } // namespace afk -#endif // INCLUDE_COMMON_EXCEPTIONS_H_ +#endif // AFK_EXCEPTIONS_H diff --git a/afk/include/common/Vec.h b/afk/include/common/Vec.h new file mode 100644 index 0000000..d002bb9 --- /dev/null +++ b/afk/include/common/Vec.h @@ -0,0 +1,35 @@ +/** + * @file vec.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Vec types + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_VEC_H +#define AFK_VEC_H + +namespace afk { + +struct Vec2 { + Vec2() = default; + Vec2(float x, float y) : x(x), y(y) {} + + float x = 0.0f; + float y = 0.0f; +}; + +struct Vec3 { + Vec3() = default; + Vec3(float x, float y, float z) : x(x), y(y), z(z) {} + + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; +}; + +} // namespace afk + +#endif // AFK_VEC_H diff --git a/include/common/math.h b/afk/include/common/math.h similarity index 75% rename from include/common/math.h rename to afk/include/common/math.h index cb38788..2f6c068 100644 --- a/include/common/math.h +++ b/afk/include/common/math.h @@ -8,11 +8,10 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMMON_MATH_H_ -#define INCLUDE_COMMON_MATH_H_ +#ifndef AFK_MATH_H +#define AFK_MATH_H -namespace afk { -namespace math { +namespace afk::math { /** * @brief Lerp between two values @@ -20,7 +19,7 @@ namespace math { * @param start Start value * @param end End value * @param progress Progress from 0.0-1.0 - * @return float Lerped value + * @return float Lerp-ed value */ float lerp(float start, float end, float progress); @@ -34,7 +33,6 @@ float lerp(float start, float end, float progress); */ float clamp(float value, float min, float max); -} // namespace math -} // namespace afk +} // namespace afk::math -#endif // INCLUDE_COMMON_MATH_H_ +#endif // AFK_MATH_H diff --git a/afk/include/common/random.h b/afk/include/common/random.h new file mode 100644 index 0000000..ad4abef --- /dev/null +++ b/afk/include/common/random.h @@ -0,0 +1,41 @@ +/** + * @file RandomGenerator.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Static helper class that can create random numbers. + * @version 0.1 + * @date 2020-08-11 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_RANDOM_H +#define AFK_RANDOM_H + +#include + +namespace afk::random { + +/** + * @brief Returns a random float between two numbers + * + * @param min Min number + * @param max Max number + * @return Random number + */ +float randomFloat(float min, float max); + +/** + * @brief Returns a random int between two numbers + * + * @param min Min number + * @param max Max number + * @return Random number + */ +int randomInt(int min, int max); + +/// Random number generator +extern std::mt19937 rng; + +} // namespace afk::random + +#endif // AFK_RANDOM_H diff --git a/include/common/str.h b/afk/include/common/str.h similarity index 93% rename from include/common/str.h rename to afk/include/common/str.h index f86614a..fe7c305 100644 --- a/include/common/str.h +++ b/afk/include/common/str.h @@ -8,16 +8,15 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_COMMON_STR_H_ -#define INCLUDE_COMMON_STR_H_ +#ifndef AFK_STR_H +#define AFK_STR_H #include #include #include "Exceptions.h" -namespace afk { -namespace str { +namespace afk::str { /** * @brief Check if string is an integer @@ -97,7 +96,6 @@ std::string format(const std::string& format, Args... args) { return std::string(buf.get(), buf.get() + size - 1); } -} // namespace str -} // namespace afk +} // namespace afk::str -#endif // INCLUDE_COMMON_STR_H_ +#endif // AFK_STR_H diff --git a/afk/include/components/Collider.h b/afk/include/components/Collider.h new file mode 100644 index 0000000..cddcc08 --- /dev/null +++ b/afk/include/components/Collider.h @@ -0,0 +1,22 @@ +/** + * @file Collider.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Collider data component + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_COLLIDER_H +#define AFK_COLLIDER_H + +namespace afk { + +struct Collider { + bool colliding = false; +}; + +} // namespace afk + +#endif // AFK_COLLIDER_H diff --git a/afk/include/components/Particle.h b/afk/include/components/Particle.h new file mode 100644 index 0000000..1c271f5 --- /dev/null +++ b/afk/include/components/Particle.h @@ -0,0 +1,56 @@ +/** + * @file Particle.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Particle + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_PARTICLE_H +#define AFK_PARTICLE_H + +#include +#include "../common/Color.h" +#include "../common/Vec.h" + +namespace afk { + +enum class ParticleType : int { + Pixel, + Square, + Circle, + Image, + None, +}; + +struct Particle { + /// Type of particle + ParticleType type = ParticleType::Pixel; + + /// Starting size + float startSize = 1; + + /// Ending size + float endSize = 1; + + /// Current age + uint32_t age = 0; + + /// Max lifespan + float lifespan = 1000; + + /// Start color + color::Color startColor = color::black; + + /// End color + color::Color endColor = color::black; + + /// String + std::string texture; +}; + +} // namespace afk + +#endif // AFK_PARTICLE_H diff --git a/afk/include/components/ParticleEmitter.h b/afk/include/components/ParticleEmitter.h new file mode 100644 index 0000000..2e24fa7 --- /dev/null +++ b/afk/include/components/ParticleEmitter.h @@ -0,0 +1,51 @@ +/** + * @file ParticleEmitter.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Manage particles + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_PARTICLEEMITTER_H +#define AFK_PARTICLEEMITTER_H + +#include +#include +#include + +#include "../common/Color.h" +#include "../common/Vec.h" +#include "./Particle.h" +#include "./Physics.h" + +namespace afk { + +using ParticleTemplate = std::pair; + +struct ParticleEmitter { + /** + * @brief Add a particle to the emitter pool + * + * @param particle Particle template to add + * @return Particle& Reference to added particle + */ + ParticleTemplate& addPrefab() { + prefabs.emplace_back(std::make_pair(Particle(), Physics())); + return prefabs.back(); + } + + /// Frequency of emit + float frequency = 0.0f; + + /// Counter + float counter = 0.0f; + + /// Particle prefabs + std::vector prefabs{}; +}; + +} // namespace afk + +#endif // AFK_PARTICLEEMITTER_H diff --git a/afk/include/components/Physics.h b/afk/include/components/Physics.h new file mode 100644 index 0000000..79a005b --- /dev/null +++ b/afk/include/components/Physics.h @@ -0,0 +1,28 @@ +/** + * @file Physics.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Physics data component + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_PHYSICS_H +#define AFK_PHYSICS_H + +#include "../common/Vec.h" + +namespace afk { + +struct Physics { + /// X and Y velocity + Vec2 velocity = {0.0f, 0.0f}; + + /// X and Y acceleration + Vec2 acceleration = {0.0f, 0.0f}; +}; + +} // namespace afk + +#endif // AFK_PHYSICS_H diff --git a/afk/include/components/Sprite.h b/afk/include/components/Sprite.h new file mode 100644 index 0000000..66d65fc --- /dev/null +++ b/afk/include/components/Sprite.h @@ -0,0 +1,25 @@ +/** + * @file Sprite.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Stores sprite information for rendering engine + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_SPRITE_H +#define AFK_SPRITE_H + +#include "../assets/Texture.h" + +namespace afk { + +struct Sprite { + /// Texture of Sprite + Texture texture; +}; + +} // namespace afk + +#endif // AFK_SPRITE_H diff --git a/afk/include/components/Transform.h b/afk/include/components/Transform.h new file mode 100644 index 0000000..02650cd --- /dev/null +++ b/afk/include/components/Transform.h @@ -0,0 +1,31 @@ +/** + * @file Transform.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Transform, stores positioning + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_TRANSFORM_H +#define AFK_TRANSFORM_H + +#include "../common/Vec.h" + +namespace afk { + +struct Transform { + /// Position on x y z plane + Vec3 position = {0.0f, 0.0f, 0.0f}; + + /// Size + Vec2 size = {0.0f, 0.0f}; + + /// Rotation + float angle = 0.0f; +}; + +} // namespace afk + +#endif // AFK_TRANSFORM_H diff --git a/afk/include/components/components.h b/afk/include/components/components.h new file mode 100644 index 0000000..ae28748 --- /dev/null +++ b/afk/include/components/components.h @@ -0,0 +1,21 @@ +/** + * @file components.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Export all components + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_COMPONENTS_H +#define AFK_COMPONENTS_H + +#include "./Collider.h" +#include "./Particle.h" +#include "./ParticleEmitter.h" +#include "./Physics.h" +#include "./Sprite.h" +#include "./Transform.h" + +#endif // AFK_COMPONENTS_H diff --git a/afk/include/components/ui.h b/afk/include/components/ui.h new file mode 100644 index 0000000..fd49f2a --- /dev/null +++ b/afk/include/components/ui.h @@ -0,0 +1,17 @@ +/** + * @file ui.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Export all ui components + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_UI_H +#define AFK_UI_H + +#include "./ui/Button.h" +#include "./ui/Label.h" + +#endif // AFK_UI_H diff --git a/afk/include/components/ui/Button.h b/afk/include/components/ui/Button.h new file mode 100644 index 0000000..87ed3dd --- /dev/null +++ b/afk/include/components/ui/Button.h @@ -0,0 +1,63 @@ +/** + * @file Button.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief UI Button + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_BUTTON_H +#define AFK_BUTTON_H + +#include +#include +#include + +namespace afk { + +struct Button { + /// Constructor + Button() = default; + + Button(std::string text, std::string font) + : text(std::move(text)), font(std::move(font)) {} + + /// Text of Button + std::string text; + + /// Font of label + std::string font; + + /// On click callback + std::function onClick; + + /** + * @brief Set the text to display on ui element + * + * @param text to display + */ + void setText(const std::string& text) { this->text = text; } + + /** + * @brief Set the font to use for displaying text + * + * @param font id of font to render text with + */ + void setFont(const std::string& font) { this->font = font; } + + /** + * @brief Set the onClick function which will be called when element is + * clicked + * + * @param func function to assign to onClick + */ + void setOnClick(std::function func) { + this->onClick = std::move(func); + }; +}; + +} // namespace afk + +#endif // AFK_BUTTON_H diff --git a/afk/include/components/ui/Label.h b/afk/include/components/ui/Label.h new file mode 100644 index 0000000..951774d --- /dev/null +++ b/afk/include/components/ui/Label.h @@ -0,0 +1,32 @@ +/** + * @file Label.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief UI Label + * @version 0.1 + * @date 2021-03-15 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_LABEL_H +#define AFK_LABEL_H + +#include +#include "../../common/Color.h" + +namespace afk { + +struct Label { + /// Text of Label + std::string text; + + /// Color of text + color::Color color = color::black; + + /// Font of label + std::string font; +}; + +} // namespace afk + +#endif // AFK_LABEL_H diff --git a/afk/include/entities/Entity.h b/afk/include/entities/Entity.h new file mode 100644 index 0000000..91360f6 --- /dev/null +++ b/afk/include/entities/Entity.h @@ -0,0 +1,23 @@ +/** + * @file Entity.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Entity identifier alias + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_ENTITY_H +#define AFK_ENTITY_H + +#include + +namespace afk { + +using Entity = entt::entity; +using Registry = entt::registry; + +} // namespace afk + +#endif // AFK_ENTITY_H diff --git a/include/primitives/Primitives.h b/afk/include/primitives/Primitives.h similarity index 58% rename from include/primitives/Primitives.h rename to afk/include/primitives/Primitives.h index 74e41c5..1a367c7 100644 --- a/include/primitives/Primitives.h +++ b/afk/include/primitives/Primitives.h @@ -9,13 +9,14 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_PRIMITIVES_PRIMITIVES_H_ -#define INCLUDE_PRIMITIVES_PRIMITIVES_H_ +#ifndef AFK_PRIMITIVES_H +#define AFK_PRIMITIVES_H -#include "../color/Color.h" +#include -namespace afk { -namespace primitives { +#include "../common/Color.h" + +namespace afk::primitives { /** * @brief Draw a rectangle border @@ -26,11 +27,7 @@ namespace primitives { * @param h Height of rect * @param colour Colour of rect */ -void rect(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, - color::Color colour); +void rect(int32_t x, int32_t y, int32_t w, int32_t h, color::Color colour); /** * @brief Draw a filled rectangle @@ -41,11 +38,7 @@ void rect(const Sint32 x, * @param h Height of rect * @param colour Colour of rect */ -void rectfill(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, - color::Color colour); +void rectfill(int32_t x, int32_t y, int32_t w, int32_t h, color::Color colour); /** * @brief Draw a circle @@ -55,10 +48,7 @@ void rectfill(const Sint32 x, * @param r Radius * @param colour Colour of circle */ -void circle(const Sint16 cx, - const Sint16 cy, - const Sint16 r, - color::Color colour); +void circle(Sint16 cx, Sint16 cy, Sint16 r, color::Color colour); /** * @brief Draw a single pixel @@ -67,7 +57,7 @@ void circle(const Sint16 cx, * @param y Y position of pixel * @param colour Colour of pixel */ -void pixel(const Sint16 x, const Sint16 y, color::Color colour); +void pixel(Sint16 x, Sint16 y, color::Color colour); /** * @brief Draw line between two points @@ -78,13 +68,8 @@ void pixel(const Sint16 x, const Sint16 y, color::Color colour); * @param y2 Y end position of line * @param colour Colour of line */ -void line(const Sint16 x1, - const Sint16 y1, - const Sint16 x2, - const Sint16 y2, - color::Color colour); +void line(Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, color::Color colour); -} // namespace primitives -} // namespace afk +} // namespace afk::primitives -#endif // INCLUDE_PRIMITIVES_PRIMITIVES_H_ +#endif // AFK_PRIMITIVES_H diff --git a/afk/include/scene/Scene.h b/afk/include/scene/Scene.h new file mode 100644 index 0000000..c0fb127 --- /dev/null +++ b/afk/include/scene/Scene.h @@ -0,0 +1,168 @@ +/** + * @file Scene.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Parent scene class. Children can be added to scene manager. + * @version 0.1 + * @date 2016-12-30 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_SCENE_H +#define AFK_SCENE_H + +#include +#include +#include +#include +#include + +#include "../common/Exceptions.h" +#include "../components/Transform.h" +#include "../entities/Entity.h" +#include "../services/Services.h" + +/** + * @brief Scene for state machine + * + */ +namespace afk { + +class Scene { + public: + /** + * @brief Create a new Scene + * + */ + Scene(); + + /** + * @brief Destroy the Scene + * + */ + virtual ~Scene() = default; + + /** + * @brief Start the scene + * + */ + virtual void start(){}; + + /** + * @brief Update to be overridden by derived scenes + * + * @param delta Time since last call in ms + * + */ + virtual void update(uint32_t delta); + + /** + * @brief Draw to be overridden by derived scenes + * + */ + virtual void draw(); + + /** + * @brief Stop the scene + * + */ + virtual void stop(){}; + + /** + * @brief Internal cleanup call + * + */ + void stopInternal(); + + /** + * @brief Register a new entity + * + * @return entity + */ + Entity createEntity(); + + /** + * @brief Remove an entity + * + * @param entity Entity to remove + */ + void destroyEntity(Entity entity); + + /** + * @brief Add a component to an entity + * + * @tparam T Type of component + * @tparam Args Type of arguments to provide to component constructor + * @param id Entity to assign to + * @param args Arguments accepted by component + */ + template + T& createComponent(Entity id, Args&&... args) { + auto& component = registry.emplace(id, std::forward(args)...); + + // Sort always (inefficient!) + registry.sort([](const auto& lhs, const auto& rhs) { + return lhs.position.z < rhs.position.z; + }); + + return component; + } + + /** + * @brief Add a component to an entity without args + * + * @tparam T Type of component + * @param id Entity to assign to + */ + template + T& createComponent(Entity id) { + return registry.emplace(id); + } + + /** + * @brief Get a component for a given entity + * + * @tparam T Type of component + * @param id Id of entity + * @return T& Returned component reference + */ + template + T& getComponent(Entity id) { + return registry.get(id); + } + + /** + * @brief Get a reference to the registry + * + * @return registry& Registry reference + */ + Registry& getRegistry(); + + /// Audio service reference + AudioService& audio; + + /// Logger service reference + LoggingService& logger; + + /// Display service reference + DisplayService& display; + + /// Asset service reference + AssetService& assets; + + /// Input service reference + InputService& input; + + /// Scene service reference + SceneService& scene; + + /// Config service reference + ConfigService& config; + + private: + /// Entity registry + Registry registry; +}; +} // namespace afk + +#endif // AFK_SCENE_H diff --git a/include/services/Service.h b/afk/include/services/Service.h similarity index 80% rename from include/services/Service.h rename to afk/include/services/Service.h index fc1a1ca..b7691c3 100644 --- a/include/services/Service.h +++ b/afk/include/services/Service.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_SERVICE_H_ -#define INCLUDE_SERVICES_SERVICE_H_ +#ifndef AFK_SERVICE_H +#define AFK_SERVICE_H #include #include @@ -24,7 +24,7 @@ class Service { /** * @brief Virtual notify to be called by the queue * - * @param event Allegero event to be processed + * @param event SDL event to be processed */ virtual void notify(const SDL_Event& event) = 0; @@ -38,4 +38,4 @@ class Service { } // namespace afk -#endif // INCLUDE_SERVICES_SERVICE_H_ +#endif // AFK_SERVICE_H diff --git a/include/services/Services.h b/afk/include/services/Services.h similarity index 84% rename from include/services/Services.h rename to afk/include/services/Services.h index a4d780d..e3d7fb3 100644 --- a/include/services/Services.h +++ b/afk/include/services/Services.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_SERVICES_H_ -#define INCLUDE_SERVICES_SERVICES_H_ +#ifndef AFK_SERVICES_H +#define AFK_SERVICES_H #include @@ -87,30 +87,30 @@ class Services { private: /// Internal pointer to current LoggingService instance - static DebugLoggingService logging_service; + static DebugLoggingService loggingService; /// Internal pointer to current Event queue instance - static EventQueue event_service; + static EventQueue eventService; /// Internal pointer to current SceneService queue instance - static SceneService scene_service; + static SceneService sceneService; /// Internal pointer to current DisplayService instance - static DisplayService display_service; + static DisplayService displayService; /// Internal pointer to current InputService instance - static InputService input_service; + static InputService inputService; /// Internal pointer to current AudioService instance - static AudioService audio_service; + static AudioService audioService; /// Internal pointer to current AssetService instance - static AssetService asset_service; + static AssetService assetService; /// Internal pointer to current ConfigService instance - static ConfigService config_service; + static ConfigService configService; }; } // namespace afk -#endif // INCLUDE_SERVICES_SERVICES_H_ +#endif // AFK_SERVICES_H diff --git a/include/services/assets/AssetService.h b/afk/include/services/assets/AssetService.h similarity index 82% rename from include/services/assets/AssetService.h rename to afk/include/services/assets/AssetService.h index 62cea34..41574f7 100644 --- a/include/services/assets/AssetService.h +++ b/afk/include/services/assets/AssetService.h @@ -8,11 +8,11 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ -#define INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ +#ifndef AFK_ASSETSERVICE_H +#define AFK_ASSETSERVICE_H -#include #include +#include #include "../../assets/Font.h" #include "../../assets/Sound.h" @@ -39,7 +39,7 @@ class AssetService { * Cleans up assets upon unloading * */ - virtual ~AssetService(); + virtual ~AssetService() = default; /** * @brief Get reference to audio by key reference @@ -90,7 +90,7 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getImage */ - void loadImage(const std::string& key, const std::string& path); + const Texture& loadImage(const std::string& key, const std::string& path); /** * @brief Loads an audio file into memory from a given path. Font is assigned @@ -101,7 +101,7 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getAudioService */ - void loadAudio(const std::string& key, const std::string& path); + const Sound& loadAudio(const std::string& key, const std::string& path); /** * @brief Loads a font into memory from a given path. Audio file is assigned @@ -113,9 +113,9 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getFont */ - void loadFont(const std::string& key, - const std::string& path, - const int size); + const Font& loadFont(const std::string& key, + const std::string& path, + int size); /** * @brief Loads an audio stream into memory from a given path. Stream is @@ -126,22 +126,22 @@ class AssetService { * @throws FileIOException Thrown if file can not be loaded * @see getStream */ - void loadStream(const std::string& key, const std::string& path); + const Stream& loadStream(const std::string& key, const std::string& path); private: /// Container that stores all Sound assets - std::map loaded_audio; + std::unordered_map loadedAudio; /// Container that stores all Image assets - std::map loaded_image; + std::unordered_map loadedImage; /// Container that stores all Font assets - std::map loaded_font; + std::unordered_map loadedFont; /// Container that stores all Stream assets - std::map loaded_stream; + std::unordered_map loadedStream; }; } // namespace afk -#endif // INCLUDE_SERVICES_ASSETS_ASSETSERVICE_H_ +#endif // AFK_ASSETSERVICE_H diff --git a/include/services/audio/AudioService.h b/afk/include/services/audio/AudioService.h similarity index 73% rename from include/services/audio/AudioService.h rename to afk/include/services/audio/AudioService.h index 9917270..4540729 100644 --- a/include/services/audio/AudioService.h +++ b/afk/include/services/audio/AudioService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_AUDIO_AUDIOSERVICE_H_ -#define INCLUDE_SERVICES_AUDIO_AUDIOSERVICE_H_ +#ifndef AFK_AUDIOSERVICE_H +#define AFK_AUDIOSERVICE_H #include @@ -28,7 +28,7 @@ class AudioService { * @brief Destroy the Audio Service * */ - virtual ~AudioService() {} + virtual ~AudioService() = default; /** * @brief Play sound by id @@ -40,10 +40,10 @@ class AudioService { * @param loop Loop mode */ void playSound(const std::string& key, - const float gain = 1.0f, - const float pan = 0.0f, - const float speed = 1.0f, - const bool loop = false); + float gain = 1.0f, + float pan = 0.0f, + float speed = 1.0f, + bool loop = false); /** * @brief Play audio stream by id @@ -51,7 +51,7 @@ class AudioService { * @param key Id of stream to play * @param loop Loop mode, true for looping, false for one shot */ - void playStream(const std::string& key, const bool loop = false); + void playStream(const std::string& key, bool loop = false); /** * @brief Stop stream by id. Stops all instances of stream currently playing. @@ -63,7 +63,7 @@ class AudioService { } // namespace afk -#endif // INCLUDE_SERVICES_AUDIO_AUDIOSERVICE_H_ +#endif // AFK_AUDIOSERVICE_H /** * @example ex_sound.cpp diff --git a/include/services/config/ConfigService.h b/afk/include/services/config/ConfigService.h similarity index 76% rename from include/services/config/ConfigService.h rename to afk/include/services/config/ConfigService.h index c2ad4b7..e80912d 100644 --- a/include/services/config/ConfigService.h +++ b/afk/include/services/config/ConfigService.h @@ -8,12 +8,13 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ -#define INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ +#ifndef AFK_CONFIGSERVICE_H +#define AFK_CONFIGSERVICE_H -#include #include #include +#include +#include namespace afk { @@ -92,34 +93,34 @@ class ConfigService { */ template void set(const std::string& key, const T value) { - std::string s_val = std::to_string(value); + std::string sVal = std::to_string(value); - settings[key] = s_val; + settings[key] = sVal; - if (autosave) { + if (autoSave) { save(); } } /** - * @brief Set the autosave config + * @brief Set the auto save config * - * @param autosave If set to true, will autosave on each set to the original + * @param autoSave If set to true, will auto save on each set to the original * file path */ - void setAutosave(const bool autosave); + void setAutoSave(bool autoSave); private: - /// Name of file for save, and autosave reference - std::string file_name; + /// Name of file for save, and auto save reference + std::string fileName; - /// Autosave enabled status - bool autosave; + /// Auto save enabled status + bool autoSave; /// Container which stores all settings - std::map settings; + std::unordered_map settings; }; } // namespace afk -#endif // INCLUDE_SERVICES_CONFIG_CONFIGSERVICE_H_ +#endif // AFK_CONFIGSERVICE_H diff --git a/include/services/display/DisplayService.h b/afk/include/services/display/DisplayService.h similarity index 76% rename from include/services/display/DisplayService.h rename to afk/include/services/display/DisplayService.h index 6c5792f..787c3fe 100644 --- a/include/services/display/DisplayService.h +++ b/afk/include/services/display/DisplayService.h @@ -10,16 +10,16 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_DISPLAY_DISPLAYSERVICE_H_ -#define INCLUDE_SERVICES_DISPLAY_DISPLAYSERVICE_H_ +#ifndef AFK_DISPLAYSERVICE_H +#define AFK_DISPLAYSERVICE_H #include #include -#include "../../color/Color.h" +#include "../../common/Color.h" #include "../Service.h" -const int FRAME_BUFFER_SIZE = 50; +const int frameBufferSize = 50; namespace afk { @@ -30,14 +30,14 @@ class Scene; * */ enum class DisplayMode { - /// Stretches window in fullscreen - FULLSCREEN_WINDOW_STRETCH, + /// Stretches window in full screen + FullScreenWindowStretch, /// Shows window in highest resolution without clipping or stretching - FULLSCREEN_WINDOW_LETTERBOX, + FullScreenWindowLetterbox, /// Centers the window at the standard window resolution - FULLSCREEN_WINDOW_CENTER, + FullScreenWindowCenter, /// Shows window in windowed mode at set window size - WINDOWED, + Windowed, }; /** @@ -63,9 +63,9 @@ class DisplayService { * @brief Draw a scene. Calls the draw and draw_internal functions of a given * Scene object * - * @param current_scene Scene to draw + * @param currentScene Scene to draw */ - void draw(Scene* current_scene); + void draw(Scene* currentScene); /** * @brief Set the current display mode. Should be called once on @@ -74,7 +74,7 @@ class DisplayService { * @param mode Display mode to set it to * @see DisplayMode */ - void setMode(const DisplayMode mode); + void setMode(DisplayMode mode); /** * @brief Set the size of the buffer @@ -82,7 +82,7 @@ class DisplayService { * @param width Width of buffer in pixels * @param height Height of buffer in pixels */ - void setBufferSize(const Uint32 width, const Uint32 height); + void setBufferSize(uint32_t width, uint32_t height); /** * @brief Set the size of the window @@ -90,7 +90,7 @@ class DisplayService { * @param width Width of window in pixels * @param height Height of window in pixels */ - void setWindowSize(const Uint32 width, const Uint32 height); + void setWindowSize(uint32_t width, uint32_t height); /** * @brief Get the current display mode @@ -105,42 +105,42 @@ class DisplayService { * * @return Width of buffer in pixels */ - Uint32 getDrawWidth() const; + uint32_t getDrawWidth() const; /** * @brief Get the buffer height * * @return Height of buffer in pixels */ - Uint32 getDrawHeight() const; + uint32_t getDrawHeight() const; /** * @brief Get the x translation of the window * * @return X translation in pixels */ - Uint32 getTranslationX() const; + uint32_t getTranslationX() const; /** * @brief Get the y translation of the window * * @return Y translation in pixels */ - Uint32 getTranslationY() const; + uint32_t getTranslationY() const; /** * @brief Get the current width of the winodw * * @return width of window */ - Uint32 getDisplayServiceWidth() const; + uint32_t getDisplayServiceWidth() const; /** * @brief Get the current height of window * * @return height of window */ - Uint32 getDisplayServiceHeight() const; + uint32_t getDisplayServiceHeight() const; /** * @brief Get the scaling being done on buffer. This is equivalent to buffer @@ -173,10 +173,10 @@ class DisplayService { /** * @brief Resize window to given width and height * - * @param window_w Width in pixels - * @param window_h Height in pixels + * @param windowW Width in pixels + * @param windowH Height in pixels */ - void resize(const Uint32 window_w, const Uint32 window_h); + void resize(uint32_t windowW, uint32_t windowH); /** * @brief Set the window title @@ -222,31 +222,31 @@ class DisplayService { private: /// Width of buffer - Uint32 draw_w = 0; + uint32_t drawW = 0; /// Height of buffer - Uint32 draw_h = 0; + uint32_t drawH = 0; /// Width of window - Uint32 window_w = 0; + uint32_t windowW = 0; /// Height of window - Uint32 window_h = 0; + uint32_t windowH = 0; /// X translation of window - Uint32 translation_x = 0; + uint32_t translationX = 0; /// Y translation of window - Uint32 translation_y = 0; + uint32_t translationY = 0; /// X scaling amount - float scale_x = 0; + float scaleX = 0; /// Y scaling amount - float scale_y = 0; + float scaleY = 0; /// Current display mode - DisplayMode display_mode = DisplayMode::WINDOWED; + DisplayMode displayMode = DisplayMode::Windowed; /// Active window SDL_Window* window = nullptr; @@ -255,19 +255,19 @@ class DisplayService { SDL_Renderer* renderer = nullptr; /// Fps timer - Uint32 old_time = 0; + uint32_t oldTime = 0; /// Frame array for calculating fps - Uint32 frames_array[FRAME_BUFFER_SIZE] = {0}; + uint32_t framesArray[frameBufferSize] = {0}; /// Current fps - Uint32 fps = 0; + uint32_t fps = 0; /// Frame index - Uint32 frame_index = 0; + uint32_t frameIndex = 0; /// Clear color - color::Color clear_color; + color::Color clearColor = color::white; /** * @brief Sets the window scaling in percent @@ -275,7 +275,7 @@ class DisplayService { * @param x X scaling percent * @param y Y scaling percent */ - void setScale(const float x, const float y); + void setScale(float x, float y); /** * @brief Set the translation amount in pixels @@ -283,12 +283,12 @@ class DisplayService { * @param x X translation * @param y Y translation */ - void setTranslation(const Uint32 x, const Uint32 y); + void setTranslation(uint32_t x, uint32_t y); }; } // namespace afk -#endif // INCLUDE_SERVICES_DISPLAY_DISPLAYSERVICE_H_ +#endif // AFK_DISPLAYSERVICE_H /** * @example ex_display.cpp diff --git a/include/services/events/EventQueue.h b/afk/include/services/events/EventQueue.h similarity index 79% rename from include/services/events/EventQueue.h rename to afk/include/services/events/EventQueue.h index 17da175..000ba51 100644 --- a/include/services/events/EventQueue.h +++ b/afk/include/services/events/EventQueue.h @@ -9,10 +9,10 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_EVENTS_EVENTQUEUE_H_ -#define INCLUDE_SERVICES_EVENTS_EVENTQUEUE_H_ +#ifndef AFK_EVENTQUEUE_H +#define AFK_EVENTQUEUE_H -#include +#include #include #include "../Service.h" @@ -63,14 +63,14 @@ class EventQueue { * @param time Time in ms to call timer at * @param code User defined code to inject into timer */ - SDL_TimerID registerTimer(const Uint32 time, const char code); + SDL_TimerID registerTimer(uint32_t time, char code); /** * @brief Unregister user timer * - * @param timer Timer to remove from queue + * @param timerId Timer to remove from queue */ - void unregisterTimer(const SDL_TimerID timer); + void unregisterTimer(SDL_TimerID timerId); /** * @brief Timer callback for registered timers @@ -78,7 +78,7 @@ class EventQueue { * @param interval MS per call, interval to run at * @param param User defined params */ - static Uint32 timerCallback(Uint32 interval, void* param); + static uint32_t timerCallback(uint32_t interval, void* param); private: /// List of services which must be notified @@ -87,4 +87,4 @@ class EventQueue { } // namespace afk -#endif // INCLUDE_SERVICES_EVENTS_EVENTQUEUE_H_ +#endif // AFK_EVENTQUEUE_H diff --git a/include/services/input/InputService.h b/afk/include/services/input/InputService.h similarity index 73% rename from include/services/input/InputService.h rename to afk/include/services/input/InputService.h index 346b98e..a7cf1c7 100644 --- a/include/services/input/InputService.h +++ b/afk/include/services/input/InputService.h @@ -8,13 +8,14 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_INPUTSERVICE_H_ -#define INCLUDE_SERVICES_INPUT_INPUTSERVICE_H_ +#ifndef AFK_INPUTSERVICE_H +#define AFK_INPUTSERVICE_H #include #include #include +#include "../../common/Vec.h" #include "../Service.h" #include "JoystickState.h" #include "KeyboardState.h" @@ -52,14 +53,14 @@ class InputService : public Service { * * @return name */ - std::string getName() const; + std::string getName() const override; /** * @brief Notify input service of recent event * * @param event SDL event to process */ - void notify(const SDL_Event& event); + void notify(const SDL_Event& event) override; /** * @brief Get key just down state @@ -68,7 +69,7 @@ class InputService : public Service { * * @return Key state */ - bool keyPressed(const Keys key) const; + bool keyPressed(Keys key) const; /** * @brief Get key just up state @@ -77,7 +78,7 @@ class InputService : public Service { * * @return Key state */ - bool keyReleased(const Keys key) const; + bool keyReleased(Keys key) const; /** * @brief Get key down state @@ -86,7 +87,7 @@ class InputService : public Service { * * @return Key state */ - bool keyDown(const Keys key) const; + bool keyDown(Keys key) const; /** * @brief Get if any key is down @@ -116,7 +117,7 @@ class InputService : public Service { * * @return Key state */ - bool mousePressed(const MouseButtons button) const; + bool mousePressed(MouseButtons button) const; /** * @brief Get mouse button just up state @@ -125,7 +126,7 @@ class InputService : public Service { * * @return Key state */ - bool mouseReleased(const MouseButtons button) const; + bool mouseReleased(MouseButtons button) const; /** * @brief Get mouse button down state @@ -134,7 +135,17 @@ class InputService : public Service { * * @return Key state */ - bool mouseDown(const MouseButtons button) const; + bool mouseDown(MouseButtons button) const; + + /** + * @brief Get whether mouse is over a given area + * + * @param position Position to check + * @param size Size of area + * + * @return Over state + */ + bool mouseOver(Vec2 position, Vec2 size) const; /** * @brief Get mouse x position @@ -164,7 +175,7 @@ class InputService : public Service { * * @return Key state */ - bool joyPressed(const JoystickButtons button) const; + bool joyPressed(JoystickButtons button) const; /** * @brief Get joy button just up state @@ -173,7 +184,7 @@ class InputService : public Service { * * @return Key state */ - bool joyReleased(const JoystickButtons button) const; + bool joyReleased(JoystickButtons button) const; /** * @brief Get joy button down state @@ -182,16 +193,16 @@ class InputService : public Service { * * @return Key state */ - bool joyDown(const JoystickButtons button) const; + bool joyDown(JoystickButtons button) const; private: /** * @brief Joystick button event handler * - * @param event_type Type of sdl event + * @param eventType Type of sdl event * @param event Sdl event to be processed */ - void onJoystickEvent(const Uint32 event_type, const SDL_JoyButtonEvent event); + void onJoystickEvent(uint32_t eventType, SDL_JoyButtonEvent event); /** * @brief Joystick axis and stick event handler @@ -199,7 +210,7 @@ class InputService : public Service { * @param event_type Type of sdl event * @param event Sdl event to be processed */ - void onJoystickEvent(const SDL_JoyAxisEvent event); + void onJoystickEvent(SDL_JoyAxisEvent event); /** * @brief Joystick configuration event @@ -210,46 +221,46 @@ class InputService : public Service { /** * @brief Keyboard event handler * - * @param event_type Type of sdl event + * @param eventType Type of sdl event * @param event Sdl event to be processed */ - void onKeyboardEvent(const Uint32 event_type, const SDL_KeyboardEvent event); + void onKeyboardEvent(uint32_t eventType, SDL_KeyboardEvent event); /** * @brief Mouse axis handler * * @param event Sdl event to be processed */ - void onMouseEvent(const SDL_MouseWheelEvent event); + void onMouseEvent(SDL_MouseWheelEvent event); /** * @brief Mouse wheel handler * * @param event Sdl event to be processed */ - void onMouseEvent(const SDL_MouseMotionEvent event); + void onMouseEvent(SDL_MouseMotionEvent event); /** * @brief Mouse button handler * - * @param event_type Type of sdl event + * @param eventType Type of sdl event * @param event Sdl event to be processed */ - void onMouseEvent(const Uint32 event_type, const SDL_MouseButtonEvent event); + void onMouseEvent(uint32_t eventType, SDL_MouseButtonEvent event); /// Current keyboard state - KeyboardState keyboard_state; + KeyboardState keyboardState; /// Current mouse state - MouseState mouse_state; + MouseState mouseState; /// Current joystick state - JoystickState joystick_state; + JoystickState joystickState; }; } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_INPUTSERVICE_H_ +#endif // AFK_INPUTSERVICE_H /** * @example ex_mouse.cpp diff --git a/afk/include/services/input/JoystickCodes.h b/afk/include/services/input/JoystickCodes.h new file mode 100644 index 0000000..244cd09 --- /dev/null +++ b/afk/include/services/input/JoystickCodes.h @@ -0,0 +1,46 @@ +/** + * @file JoystickCodes.h + * @author Danny Van Stemp (dannyvanstemp@gmail.com) + * @brief Defines for codes used for joystick + * @version 0.1 + * @date 2018-11-20 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_JOYSTICKCODES_H +#define AFK_JOYSTICKCODES_H + +namespace afk { + +enum class JoystickButtons { + A = 0, + B = 1, + X = 2, + Y = 3, + BumperRight = 4, + BumperLeft = 5, + Back = 8, + Start = 9, + PadRight = 10, + PadLeft = 11, + PadDown = 12, + PadUp = 13 +}; + +enum class JoystickSticks { + LeftStickLeft = 1, + LeftStickRight = 0, + LeftStickDown = 2, + LeftStickUp = 3, + RightStickLeft = 7, + RightStickRight = 6, + RightStickDown = 8, + RightStickUp = 9, + LeftTrigger = 12, + RightTrigger = 18 +}; + +} // namespace afk + +#endif // AFK_JOYSTICKCODES_H diff --git a/include/services/input/JoystickState.h b/afk/include/services/input/JoystickState.h similarity index 87% rename from include/services/input/JoystickState.h rename to afk/include/services/input/JoystickState.h index 755f563..4a47751 100644 --- a/include/services/input/JoystickState.h +++ b/afk/include/services/input/JoystickState.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_JOYSTICKSTATE_H_ -#define INCLUDE_SERVICES_INPUT_JOYSTICKSTATE_H_ +#ifndef AFK_JOYSTICKSTATE_H +#define AFK_JOYSTICKSTATE_H #include @@ -89,12 +89,12 @@ struct JoystickState { stickReleased[i] = false; // Pressed since last tick? - if (stick[i] == true && lastTicksStick[i] == false) { + if (stick[i] && !lastTicksStick[i]) { stickMoved[i] = true; } // Released since last tick? - if (stick[i] == false && lastTicksStick[i] == true) { + if (!stick[i] && lastTicksStick[i]) { stickReleased[i] = true; } @@ -113,13 +113,13 @@ struct JoystickState { } // Pressed since last tick? - if (button[i] == true && lastTicksButton[i] == false) { + if (button[i] && !lastTicksButton[i]) { buttonPressed[i] = true; lastButtonPressed = i; } // Released since last tick? - if (button[i] == false && lastTicksButton[i] == true) { + if (!button[i] && lastTicksButton[i]) { buttonReleased[i] = true; lastButtonReleased = i; } @@ -132,4 +132,4 @@ struct JoystickState { } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_JOYSTICKSTATE_H_ +#endif // AFK_JOYSTICKSTATE_H diff --git a/afk/include/services/input/KeyboardKeys.h b/afk/include/services/input/KeyboardKeys.h new file mode 100644 index 0000000..f47a9d4 --- /dev/null +++ b/afk/include/services/input/KeyboardKeys.h @@ -0,0 +1,247 @@ +/** + * @file KeyboardKeys.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Definitions of keys that can be used by input manager + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#ifndef AFK_KEYBOARDKEYS_H +#define AFK_KEYBOARDKEYS_H + +namespace afk { + +enum class Keys { + Unknown = 0, + A = 4, + B = 5, + C = 6, + D = 7, + E = 8, + F = 9, + G = 10, + H = 11, + I = 12, + J = 13, + K = 14, + L = 15, + M = 16, + N = 17, + O = 18, + P = 19, + Q = 20, + R = 21, + S = 22, + T = 23, + U = 24, + V = 25, + W = 26, + X = 27, + Y = 28, + Z = 29, + One = 30, + Two = 31, + Three = 32, + Four = 33, + Five = 34, + Six = 35, + Seven = 36, + Eight = 37, + Nine = 38, + Zero = 39, + Return = 40, + Escape = 41, + Backspace = 42, + Tab = 43, + Space = 44, + Minus = 45, + Equals = 46, + Leftbracket = 47, + Rightbracket = 48, + Backslash = 49, + Nonushash = 50, + Semicolon = 51, + Apostrophe = 52, + Grave = 53, + Comma = 54, + Period = 55, + Slash = 56, + Capslock = 57, + F1 = 58, + F2 = 59, + F3 = 60, + F4 = 61, + F5 = 62, + F6 = 63, + F7 = 64, + F8 = 65, + F9 = 66, + F10 = 67, + F11 = 68, + F12 = 69, + Printscreen = 70, + Scrolllock = 71, + Pause = 72, + Insert = 73, + Home = 74, + Pageup = 75, + Delete = 76, + End = 77, + Pagedown = 78, + Right = 79, + Left = 80, + Down = 81, + Up = 82, + Numlockclear = 83, + KpDivide = 84, + KpMultiply = 85, + KpMinus = 86, + KpPlus = 87, + KpEnter = 88, + Kp1 = 89, + Kp2 = 90, + Kp3 = 91, + Kp4 = 92, + Kp5 = 93, + Kp6 = 94, + Kp7 = 95, + Kp8 = 96, + Kp9 = 97, + Kp0 = 98, + KpPeriod = 99, + Nonusbackslash = 100, + Application = 101, + Power = 102, + KpEquals = 103, + F13 = 104, + F14 = 105, + F15 = 106, + F16 = 107, + F17 = 108, + F18 = 109, + F19 = 110, + F20 = 111, + F21 = 112, + F22 = 113, + F23 = 114, + F24 = 115, + Execute = 116, + Help = 117, + Menu = 118, + Select = 119, + Stop = 120, + Again = 121, + Undo = 122, + Cut = 123, + Copy = 124, + Paste = 125, + Find = 126, + Mute = 127, + Volumeup = 128, + Volumedown = 129, + KpComma = 133, + KpEqualsas400 = 134, + Alterase = 153, + Sysreq = 154, + Cancel = 155, + Clear = 156, + Prior = 157, + Return2 = 158, + Separator = 159, + Out = 160, + Oper = 161, + Clearagain = 162, + Crsel = 163, + Exsel = 164, + Kp00 = 176, + Kp000 = 177, + Thousandsseparator = 178, + Decimalseparator = 179, + Currencyunit = 180, + Currencysubunit = 181, + KpLeftparen = 182, + KpRightparen = 183, + KpLeftbrace = 184, + KpRightbrace = 185, + KpTab = 186, + KpBackspace = 187, + KpA = 188, + KpB = 189, + KpC = 190, + KpD = 191, + KpE = 192, + KpF = 193, + KpXor = 194, + KpPower = 195, + KpPercent = 196, + KpLess = 197, + KpGreater = 198, + KpAmpersand = 199, + KpDblampersand = 200, + KpVerticalbar = 201, + KpDblverticalbar = 202, + KpColon = 203, + KpHash = 204, + KpSpace = 205, + KpAt = 206, + KpExclam = 207, + KpMemstore = 208, + KpMemrecall = 209, + KpMemclear = 210, + KpMemadd = 211, + KpMemsubtract = 212, + KpMemmultiply = 213, + KpMemdivide = 214, + KpPlusminus = 215, + KpClear = 216, + KpClearentry = 217, + KpBinary = 218, + KpOctal = 219, + KpDecimal = 220, + KpHexadecimal = 221, + Lctrl = 224, + Lshift = 225, + Lalt = 226, + Lgui = 227, + Rctrl = 228, + Rshift = 229, + Ralt = 230, + Rgui = 231, + Mode = 257, + Audionext = 258, + Audioprev = 259, + Audiostop = 260, + Audioplay = 261, + Audiomute = 262, + Mediaselect = 263, + Www = 264, + Mail = 265, + Calculator = 266, + Computer = 267, + AcSearch = 268, + AcHome = 269, + AcBack = 270, + AcForward = 271, + AcStop = 272, + AcRefresh = 273, + AcBookmarks = 274, + Brightnessdown = 275, + Brightnessup = 276, + Displayswitch = 277, + Kbdillumtoggle = 278, + Kbdillumdown = 279, + Kbdillumup = 280, + Eject = 281, + Sleep = 282, + App1 = 283, + App2 = 284, + Audiorewind = 285, + Audiofastforward = 286, + Max = 512 +}; + +} // namespace afk + +#endif // AFK_KEYBOARDKEYS_H diff --git a/include/services/input/KeyboardState.h b/afk/include/services/input/KeyboardState.h similarity index 60% rename from include/services/input/KeyboardState.h rename to afk/include/services/input/KeyboardState.h index c6f52c0..9922e2a 100644 --- a/include/services/input/KeyboardState.h +++ b/afk/include/services/input/KeyboardState.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_KEYBOARDSTATE_H_ -#define INCLUDE_SERVICES_INPUT_KEYBOARDSTATE_H_ +#ifndef AFK_KEYBOARDSTATE_H +#define AFK_KEYBOARDSTATE_H #include "KeyboardKeys.h" @@ -23,25 +23,25 @@ namespace afk { */ struct KeyboardState { /// Individual key states - bool key[static_cast(Keys::MAX)] = {false}; + bool key[static_cast(Keys::Max)] = {false}; /// keys just pressed - bool keyPressed[static_cast(Keys::MAX)] = {false}; + bool keyPressed[static_cast(Keys::Max)] = {false}; /// keys just released - bool keyReleased[static_cast(Keys::MAX)] = {false}; + bool keyReleased[static_cast(Keys::Max)] = {false}; /// Id of last key pressed - int lastKeyPressed = static_cast(Keys::UNKNOWN); + int lastKeyPressed = static_cast(Keys::Unknown); /// Id of last key released - int lastKeyReleased = static_cast(Keys::UNKNOWN); + int lastKeyReleased = static_cast(Keys::Unknown); /// True if any key down bool anyKeyDown = false; /// Previous key states - bool lastTicksKey[static_cast(Keys::MAX)] = {false}; + bool lastTicksKey[static_cast(Keys::Max)] = {false}; /** * @brief Update the keyboard state @@ -49,12 +49,12 @@ struct KeyboardState { */ void update() { // Reset last key - lastKeyPressed = static_cast(Keys::UNKNOWN); - lastKeyReleased = static_cast(Keys::UNKNOWN); + lastKeyPressed = static_cast(Keys::Unknown); + lastKeyReleased = static_cast(Keys::Unknown); anyKeyDown = false; // Check key just pressed - for (int i = 0; i < static_cast(Keys::MAX); i++) { + for (int i = 0; i < static_cast(Keys::Max); i++) { // Clear old values keyPressed[i] = false; keyReleased[i] = false; @@ -64,13 +64,13 @@ struct KeyboardState { } // Pressed since last tick? - if (key[i] == true && lastTicksKey[i] == false) { + if (key[i] && !lastTicksKey[i]) { keyPressed[i] = true; lastKeyPressed = i; } // Released since last tick? - if (key[i] == false && lastTicksKey[i] == true) { + if (!key[i] && lastTicksKey[i]) { keyReleased[i] = true; lastKeyReleased = i; } @@ -83,4 +83,4 @@ struct KeyboardState { } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_KEYBOARDSTATE_H_ +#endif // AFK_KEYBOARDSTATE_H diff --git a/include/services/input/MouseState.h b/afk/include/services/input/MouseState.h similarity index 60% rename from include/services/input/MouseState.h rename to afk/include/services/input/MouseState.h index 92c5a7a..500c16f 100644 --- a/include/services/input/MouseState.h +++ b/afk/include/services/input/MouseState.h @@ -10,8 +10,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_INPUT_MOUSESTATE_H_ -#define INCLUDE_SERVICES_INPUT_MOUSESTATE_H_ +#ifndef AFK_MOUSESTATE_H +#define AFK_MOUSESTATE_H #include #include @@ -19,10 +19,10 @@ namespace afk { enum class MouseButtons { - LEFT = 1, - CENTER = 2, - RIGHT = 3, - MAX = 4, + Left = 1, + Center = 2, + Right = 3, + Max = 4, }; /** @@ -40,25 +40,25 @@ struct MouseState { int z = 0; /// Previous mouse x position - int old_x = 0; + int oldX = 0; /// Previous mouse y position - int old_y = 0; + int oldY = 0; /// Individual button states - bool button[static_cast(MouseButtons::MAX)] = {false}; + bool button[static_cast(MouseButtons::Max)] = {false}; /// Buttons just pressed - bool down[static_cast(MouseButtons::MAX)] = {false}; + bool down[static_cast(MouseButtons::Max)] = {false}; /// Buttons just released - bool up[static_cast(MouseButtons::MAX)] = {false}; + bool up[static_cast(MouseButtons::Max)] = {false}; /// Mouse just moved bool moved = false; /// Previous button states - bool button_old[static_cast(MouseButtons::MAX)] = {false}; + bool buttonOld[static_cast(MouseButtons::Max)] = {false}; /** * @brief Update the mouse state @@ -66,34 +66,34 @@ struct MouseState { */ void update() { // Check if just moved - moved = old_x != x || old_y != y; - old_x = x; - old_y = y; + moved = oldX != x || oldY != y; + oldX = x; + oldY = y; // Check button just pressed - for (int i = 0; i < static_cast(MouseButtons::MAX); i++) { + for (int i = 0; i < static_cast(MouseButtons::Max); i++) { // Just up - if (button_old[i] && !button[i]) { + if (buttonOld[i] && !button[i]) { up[i] = true; } // Just down - if (!button_old[i] && button[i]) { + if (!buttonOld[i] && button[i]) { down[i] = true; } // Same - if (button_old[i] == button[i]) { + if (buttonOld[i] == button[i]) { up[i] = false; down[i] = false; } // Set new old values - button_old[i] = button[i]; + buttonOld[i] = button[i]; } } }; } // namespace afk -#endif // INCLUDE_SERVICES_INPUT_MOUSESTATE_H_ +#endif // AFK_MOUSESTATE_H diff --git a/include/services/logging/DebugLoggingService.h b/afk/include/services/logging/DebugLoggingService.h similarity index 77% rename from include/services/logging/DebugLoggingService.h rename to afk/include/services/logging/DebugLoggingService.h index 5e1992c..df30092 100644 --- a/include/services/logging/DebugLoggingService.h +++ b/afk/include/services/logging/DebugLoggingService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_LOGGING_DEBUGLOGGINGSERVICE_H_ -#define INCLUDE_SERVICES_LOGGING_DEBUGLOGGINGSERVICE_H_ +#ifndef AFK_DEBUGLOGGINGSERVICE_H +#define AFK_DEBUGLOGGINGSERVICE_H #include @@ -34,4 +34,4 @@ class DebugLoggingService : public LoggingService { } // namespace afk -#endif // INCLUDE_SERVICES_LOGGING_DEBUGLOGGINGSERVICE_H_ +#endif // AFK_DEBUGLOGGINGSERVICE_H diff --git a/include/services/logging/LoggingService.h b/afk/include/services/logging/LoggingService.h similarity index 73% rename from include/services/logging/LoggingService.h rename to afk/include/services/logging/LoggingService.h index 52da7c4..f20e81c 100644 --- a/include/services/logging/LoggingService.h +++ b/afk/include/services/logging/LoggingService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_LOGGING_LOGGINGSERVICE_H_ -#define INCLUDE_SERVICES_LOGGING_LOGGINGSERVICE_H_ +#ifndef AFK_LOGGINGSERVICE_H +#define AFK_LOGGINGSERVICE_H #include namespace afk { @@ -21,7 +21,7 @@ namespace afk { **/ class LoggingService { public: - virtual ~LoggingService() {} + virtual ~LoggingService() = default; /** * @brief Does nothing @@ -33,4 +33,4 @@ class LoggingService { } // namespace afk -#endif // INCLUDE_SERVICES_LOGGING_LOGGINGSERVICE_H_ +#endif // AFK_LOGGINGSERVICE_H diff --git a/include/services/scene/SceneService.h b/afk/include/services/scene/SceneService.h similarity index 74% rename from include/services/scene/SceneService.h rename to afk/include/services/scene/SceneService.h index e89660e..7ef9c1c 100644 --- a/include/services/scene/SceneService.h +++ b/afk/include/services/scene/SceneService.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_SERVICES_SCENE_SCENESERVICE_H_ -#define INCLUDE_SERVICES_SCENE_SCENESERVICE_H_ +#ifndef AFK_SCENESERVICE_H +#define AFK_SCENESERVICE_H #include #include @@ -41,11 +41,11 @@ class SceneService { /** * @brief Add scene to engine * - * @param scene_id to add to engine + * @param sceneId to add to engine */ template - void addScene(const std::string& scene_id) { - scenes.push_back({scene_id, new T()}); + void addScene(const std::string& sceneId) { + scenes.push_back({sceneId, new T()}); } /** @@ -69,9 +69,9 @@ class SceneService { * @brief Set the next scene to be loaded in. Upon calling, deletes current * scene * - * @param scene_id Id of next scene to load + * @param sceneId Id of next scene to load */ - void setNextScene(const std::string& scene_id); + void setNextScene(const std::string& sceneId); private: /** @@ -80,7 +80,7 @@ class SceneService { */ struct SceneType { /// Id of scene - std::string scene_id; + std::string sceneId; /// Scene object Scene* scene; @@ -93,21 +93,21 @@ class SceneService { void changeScene(); /// Current scene pointer - Scene* current_scene; + Scene* currentScene; /// List of scene ids std::vector scenes; /// Current scene - std::string scene_id; + std::string sceneId; /// Next scene to load - std::string next_scene; + std::string nextScene; /// Last tick - Uint32 last_tick; + uint32_t lastTick; }; } // namespace afk -#endif // INCLUDE_SERVICES_SCENE_SCENESERVICE_H_ +#endif // AFK_SCENESERVICE_H diff --git a/afk/include/systems/CollisionSystem.h b/afk/include/systems/CollisionSystem.h new file mode 100644 index 0000000..5dd0d01 --- /dev/null +++ b/afk/include/systems/CollisionSystem.h @@ -0,0 +1,26 @@ +/** + * @file CollisionSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating transforms + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_COLLISIONSYSTEM_H +#define AFK_COLLISIONSYSTEM_H + +#include "entities/Entity.h" + +namespace afk::systems { + +/** + * @brief CollisionSystem + * + */ +void collisionSystem(Registry& registry); + +} // namespace afk::systems + +#endif // AFK_COLLISIONSYSTEM_H \ No newline at end of file diff --git a/afk/include/systems/ParticleSystem.h b/afk/include/systems/ParticleSystem.h new file mode 100644 index 0000000..c9a4e2e --- /dev/null +++ b/afk/include/systems/ParticleSystem.h @@ -0,0 +1,30 @@ +/** + * @file ParticleSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating and rendering particles + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_PARTICLESYSTEM_H +#define AFK_PARTICLESYSTEM_H + +#include +#include "entities/Entity.h" +#include "services/assets/AssetService.h" + +namespace afk::systems { + +/** + * @brief ParticleSystem + * + */ +void particleSystem(Registry& registry, uint32_t delta); + +void particleRenderSystem(Registry& registry, AssetService& assetService); + +} // namespace afk::systems + +#endif // AFK_PARTICLESYSTEM_H \ No newline at end of file diff --git a/afk/include/systems/PhysicsSystem.h b/afk/include/systems/PhysicsSystem.h new file mode 100644 index 0000000..55f5488 --- /dev/null +++ b/afk/include/systems/PhysicsSystem.h @@ -0,0 +1,26 @@ +/** + * @file PhysicsSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating transforms + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_PHYSICSSYSTEM_H +#define AFK_PHYSICSSYSTEM_H + +#include "entities/Entity.h" + +namespace afk::systems { + +/** + * @brief PhysicsSystem + * + */ +void physicsSystem(Registry& registry, uint32_t delta); + +} // namespace afk::systems + +#endif // AFK_PHYSICSSYSTEM_H \ No newline at end of file diff --git a/afk/include/systems/RenderSystem.h b/afk/include/systems/RenderSystem.h new file mode 100644 index 0000000..d980efa --- /dev/null +++ b/afk/include/systems/RenderSystem.h @@ -0,0 +1,29 @@ +/** + * @file RenderSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_RENDERSYSTEM_H +#define AFK_RENDERSYSTEM_H + +#include + +#include "entities/Entity.h" +#include "services/assets/AssetService.h" + +namespace afk::systems { + +/** + * @brief RenderSystem + * + */ +void renderSystem(Registry& registry); + +} // namespace afk::systems + +#endif // AFK_RENDERSYSTEM_H \ No newline at end of file diff --git a/afk/include/systems/UISystem.h b/afk/include/systems/UISystem.h new file mode 100644 index 0000000..daf737b --- /dev/null +++ b/afk/include/systems/UISystem.h @@ -0,0 +1,30 @@ +/** + * @file UISystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef AFK_UISYSTEM_H +#define AFK_UISYSTEM_H + +#include "entities/Entity.h" +#include "services/assets/AssetService.h" +#include "services/input/InputService.h" + +namespace afk::systems { + +/** + * @brief UISystem + * + */ +void uiSystem(Registry& registry, + AssetService& assetService, + InputService& inputService); + +} // namespace afk::systems + +#endif // AFK_UISYSTEM_H \ No newline at end of file diff --git a/include/entities/ui/MessageBox.h b/afk/include/ui/MessageBox.h similarity index 89% rename from include/entities/ui/MessageBox.h rename to afk/include/ui/MessageBox.h index cd2968f..0d7ce4a 100644 --- a/include/entities/ui/MessageBox.h +++ b/afk/include/ui/MessageBox.h @@ -8,8 +8,8 @@ * @copyright Copyright (c) 2021 * */ -#ifndef INCLUDE_ENTITIES_UI_MESSAGEBOX_H_ -#define INCLUDE_ENTITIES_UI_MESSAGEBOX_H_ +#ifndef AFK_MESSAGEBOX_H +#define AFK_MESSAGEBOX_H #include @@ -20,9 +20,9 @@ namespace afk { * */ enum class MessageBoxType { - WARN, - ERROR, - INFO, + Warn, + Error, + Info, }; /** @@ -77,7 +77,7 @@ class MessageBox { } // namespace afk -#endif // INCLUDE_ENTITIES_UI_MESSAGEBOX_H_ +#endif // AFK_MESSAGEBOX_H /** * @example ex_ui.cpp diff --git a/src/Game.cpp b/afk/src/Game.cpp similarity index 86% rename from src/Game.cpp rename to afk/src/Game.cpp index ae95c3a..0cfff82 100644 --- a/src/Game.cpp +++ b/afk/src/Game.cpp @@ -10,10 +10,12 @@ */ #include "Game.h" +#include +#include + #include "common/Exceptions.h" -#include "entities/ui/MessageBox.h" -#include "random/RandomGenerator.h" #include "services/Services.h" +#include "ui/MessageBox.h" #ifdef __EMSCRIPTEN__ #include @@ -40,7 +42,7 @@ void loop() { // Exit helper void showErrorDialog(const std::string& title, const std::string& message = "") { - MessageBox error(MessageBoxType::ERROR); + MessageBox error(MessageBoxType::Error); error.setTitle(title); error.setText(message); error.show(); @@ -65,14 +67,14 @@ std::string Game::getName() const { } // Start your engine! -void Game::start() { +void Game::start() const { try { #ifdef __EMSCRIPTEN__ emscripten_set_main_loop(loop, 0, 1); #else float timeDelta = 1000.0f / 30.0f; float timeAcc = 0.0f; - Uint32 startTime = 0; + uint32_t startTime; // Loop while (!closing) { @@ -93,15 +95,17 @@ void Game::start() { Services::getSceneService().draw(); // Inc accumulator - timeAcc += SDL_GetTicks() - startTime; + timeAcc += static_cast(SDL_GetTicks() - startTime); } #endif - } catch (const FileIOException& e) { + } catch (const FileIoException& e) { showErrorDialog("File Error", e.what()); } catch (const std::runtime_error& e) { showErrorDialog("Runtime Error", e.what()); + } catch (const std::exception& e) { + showErrorDialog("Exception", e.what()); } catch (...) { - showErrorDialog("Unknown Error", "An unknown error has occured :("); + showErrorDialog("Unknown Error", "An unknown error has occurred :("); } } diff --git a/src/assets/Font.cpp b/afk/src/assets/Font.cpp similarity index 75% rename from src/assets/Font.cpp rename to afk/src/assets/Font.cpp index 55bbe26..936e9b9 100644 --- a/src/assets/Font.cpp +++ b/afk/src/assets/Font.cpp @@ -10,18 +10,17 @@ */ #include "assets/Font.h" -#include "color/Color.h" #include "common/Exceptions.h" #include "services/Services.h" namespace afk { // Constructor -Font::Font() : font(nullptr), font_size(0) {} +Font::Font() : font(nullptr), fontSize(0) {} // Constructor with path Font::Font(const std::string& path, const int size) - : font(nullptr), font_size(size) { + : font(nullptr), fontSize(size) { load(path, size); } @@ -48,8 +47,8 @@ int Font::getHeight() { } // Get Size of font -int Font::getSize() { - return font_size; +int Font::getSize() const { + return fontSize; } // Check if exists @@ -59,12 +58,12 @@ bool Font::exists() const { // Return width given text int Font::getWidth(const std::string& text) { - if (!font || text == "") { + if (!font || text.empty()) { return 0; } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* texture = renderText(renderer, text.c_str(), color::black); + SDL_Texture* texture = renderText(renderer, text, color::black); int w; SDL_QueryTexture(texture, nullptr, nullptr, &w, nullptr); @@ -85,7 +84,7 @@ void Font::draw(const int x, } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* texture = renderText(renderer, text.c_str(), colour); + SDL_Texture* texture = renderText(renderer, text, colour); int w, h; SDL_QueryTexture(texture, nullptr, nullptr, &w, &h); @@ -93,16 +92,16 @@ void Font::draw(const int x, SDL_Rect target = {x, y, w, h}; switch (align) { - case TextAlign::LEFT: - SDL_RenderCopy(renderer, texture, NULL, &target); + case TextAlign::Left: + SDL_RenderCopy(renderer, texture, nullptr, &target); break; - case TextAlign::RIGHT: + case TextAlign::Right: target.x = x - w; - SDL_RenderCopy(renderer, texture, NULL, &target); + SDL_RenderCopy(renderer, texture, nullptr, &target); break; - case TextAlign::CENTER: + case TextAlign::Center: target.x = x - w / 2; - SDL_RenderCopy(renderer, texture, NULL, &target); + SDL_RenderCopy(renderer, texture, nullptr, &target); break; default: break; @@ -114,19 +113,19 @@ void Font::draw(const int x, // Load font from file TTF_Font* Font::loadFont(const std::string& path, const int size) { // Attempt to load - TTF_Font* temp_font = TTF_OpenFont(path.c_str(), size); + TTF_Font* tempFont = TTF_OpenFont(path.c_str(), size); - if (!temp_font) { - throw FileIOException("There was an error loading font " + path + " (" + + if (!tempFont) { + throw FileIoException("There was an error loading font " + path + " (" + TTF_GetError() + ")"); } - return temp_font; + return tempFont; } // Render font to texture SDL_Texture* Font::renderText(SDL_Renderer* renderer, - const std::string text, + const std::string& text, const color::Color colour) { SDL_Surface* surface = TTF_RenderText_Solid( font, text.c_str(), {colour.r, colour.g, colour.b, colour.a}); diff --git a/src/assets/Sound.cpp b/afk/src/assets/Sound.cpp similarity index 71% rename from src/assets/Sound.cpp rename to afk/src/assets/Sound.cpp index ca01fd7..534f968 100644 --- a/src/assets/Sound.cpp +++ b/afk/src/assets/Sound.cpp @@ -17,12 +17,12 @@ namespace afk { // Set channel counter to 0 -Uint32 Sound::channel_counter = 0; +uint32_t Sound::channelCounter = 0; // Default constructor Sound::Sound() : sample(nullptr) { - channel = channel_counter; - Sound::channel_counter++; + channel = channelCounter; + Sound::channelCounter++; } // Constructor with path @@ -45,26 +45,26 @@ void Sound::play(const float gain, } // TODO(alegemaate): Frequency - int int_pan = (pan + 1.0f) * 128; - int int_gain = gain * 255; + int intPan = static_cast((pan + 1.0f) * 128.0f); + int intGain = static_cast(gain * 255.0f); - Mix_SetPanning(channel, int_pan, 255 - int_pan); - Mix_Volume(channel, int_gain); + Mix_SetPanning(channel, intPan, 255 - intPan); + Mix_Volume(channel, intGain); Mix_PlayChannel(channel, sample, loop); } // Load sample from file Mix_Chunk* Sound::loadSample(const std::string& path) { // Attempt to load - Mix_Chunk* temp_sample = Mix_LoadWAV(path.c_str()); + Mix_Chunk* tempSample = Mix_LoadWAV(path.c_str()); // Throw exception if file is not loaded - if (!temp_sample) { - throw FileIOException("There was an error loading sound " + path + " (" + + if (!tempSample) { + throw FileIoException("There was an error loading sound " + path + " (" + Mix_GetError() + ")"); } - return temp_sample; + return tempSample; } } // namespace afk diff --git a/src/assets/Stream.cpp b/afk/src/assets/Stream.cpp similarity index 86% rename from src/assets/Stream.cpp rename to afk/src/assets/Stream.cpp index a79940d..5074812 100644 --- a/src/assets/Stream.cpp +++ b/afk/src/assets/Stream.cpp @@ -53,15 +53,15 @@ bool Stream::isPlaying() const { // Load SDL sample from file Mix_Music* Stream::loadStream(const std::string& path) { // Attempt to load - Mix_Music* temp_stream = Mix_LoadMUS(path.c_str()); + Mix_Music* tempStream = Mix_LoadMUS(path.c_str()); // Throw exception if file is not loaded - if (!temp_stream) { - throw FileIOException("There was an error loading stream " + path + " (" + + if (!tempStream) { + throw FileIoException("There was an error loading stream " + path + " (" + Mix_GetError() + ")"); } - return temp_stream; + return tempStream; } } // namespace afk diff --git a/src/assets/Texture.cpp b/afk/src/assets/Texture.cpp similarity index 67% rename from src/assets/Texture.cpp rename to afk/src/assets/Texture.cpp index 7fc4061..9b6a3ee 100644 --- a/src/assets/Texture.cpp +++ b/afk/src/assets/Texture.cpp @@ -12,7 +12,6 @@ #include -#include "color/Color.h" #include "common/Exceptions.h" #include "services/Services.h" @@ -22,44 +21,43 @@ namespace afk { Texture::Texture() : texture(nullptr) {} // Constructor with path -Texture::Texture(const std::string& path) { +Texture::Texture(const std::string& path) : texture(nullptr) { load(path); } // Load texture from file void Texture::load(const std::string& path) { texture = loadTexture(path); + calculateSize(); } // Create texture with specified dimensions void Texture::create(const int width, const int height) { - SDL_Surface* temp_surface = + SDL_Surface* tempSurface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0); - if (!temp_surface) { + if (!tempSurface) { throw InitException("There was an error creating surface "); } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* temp_texture = - SDL_CreateTextureFromSurface(renderer, temp_surface); - if (!temp_texture) { + SDL_Texture* tempTexture = + SDL_CreateTextureFromSurface(renderer, tempSurface); + if (!tempTexture) { throw InitException("There was an error creating texture "); } - SDL_FreeSurface(temp_surface); + SDL_FreeSurface(tempSurface); - texture = temp_texture; -} + texture = tempTexture; -// Return height of loaded texture -int Texture::getHeight() const { - if (!texture) { - return 0; - } + calculateSize(); +} - int h; - SDL_QueryTexture(texture, nullptr, nullptr, nullptr, &h); - return h; +// Calculate size of texture +void Texture::calculateSize() { + int w, h; + SDL_QueryTexture(texture, nullptr, nullptr, &w, &h); + this->size = Vec2(w, h); } // Return if it exists @@ -68,14 +66,8 @@ bool Texture::exists() const { } // Return width of loaded texture -int Texture::getWidth() const { - if (!texture) { - return 0; - } - - int w; - SDL_QueryTexture(texture, nullptr, nullptr, &w, nullptr); - return w; +Vec2 Texture::getSize() { + return size; } // Draw texture to screen @@ -86,7 +78,7 @@ void Texture::draw(const int x, const int y) const { SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Rect target = {x, y, getWidth(), getHeight()}; + SDL_Rect target = {x, y, size.x, size.y}; SDL_RenderCopy(renderer, texture, nullptr, &target); } @@ -105,31 +97,31 @@ void Texture::drawEx(const int x, SDL_Rect target = {x, y, width, height}; SDL_Point center = {width / 2, height / 2}; - SDL_RendererFlip flip = static_cast(mode); + auto flip = static_cast(mode); SDL_RenderCopyEx(renderer, texture, nullptr, &target, angle, ¢er, flip); } -// Load SDL texture from file +// Load an SDL texture from file SDL_Texture* Texture::loadTexture(const std::string& path) { // Attempt to load - SDL_Surface* temp_surface = IMG_Load(path.c_str()); - if (!temp_surface) { - throw FileIOException("There was an error loading surface " + path + " (" + + SDL_Surface* tempSurface = IMG_Load(path.c_str()); + if (!tempSurface) { + throw FileIoException("There was an error loading surface " + path + " (" + SDL_GetError() + ")"); } SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); - SDL_Texture* temp_texture = - SDL_CreateTextureFromSurface(renderer, temp_surface); - if (!temp_texture) { + SDL_Texture* tempTexture = + SDL_CreateTextureFromSurface(renderer, tempSurface); + if (!tempTexture) { throw InitException("There was an error creating texture " + path + " (" + SDL_GetError() + ")"); } - SDL_FreeSurface(temp_surface); + SDL_FreeSurface(tempSurface); - return temp_texture; + return tempTexture; } } // namespace afk diff --git a/afk/src/common/Color.cpp b/afk/src/common/Color.cpp new file mode 100644 index 0000000..4b8a516 --- /dev/null +++ b/afk/src/common/Color.cpp @@ -0,0 +1,53 @@ +/** + * @file Color.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of color helper functions + * @version 0.1 + * @date 2021-03-05 + * + * @copyright Copyright (c) 2021 + * + */ +#include "common/Color.h" + +namespace afk::color { + +// Create color from RGB +Color rgb(const uint8_t r, const uint8_t g, const uint8_t b) { + return rgba(r, g, b, 255); +} + +// Create color from rgba +Color rgba(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a) { + return {r, g, b, a}; +} + +// Create color from int +Color intToColor(const uint32_t colour) { + Color tempCol = {}; + tempCol.r = (colour >> 16) & 0xFF; + tempCol.g = (colour >> 8) & 0xFF; + tempCol.b = colour & 0xFF; + tempCol.a = 255; + return tempCol; +} + +// Convert rgb to int +uint32_t rgbToInt(const uint8_t r, const uint8_t g, const uint8_t b) { + return rgbaToInt(r, g, b, 255); +} + +// Convert rgba to int +uint32_t rgbaToInt(const uint8_t r, + const uint8_t g, + const uint8_t b, + const uint8_t a) { + return (uint32_t)((a << 24) + (r << 16) + (g << 8) + (b << 0)); +} + +// Convert color to int +uint32_t colorToInt(const Color colour) { + return rgbaToInt(colour.r, colour.g, colour.b, colour.a); +} + +} // namespace afk::color diff --git a/src/common/math.cpp b/afk/src/common/math.cpp similarity index 87% rename from src/common/math.cpp rename to afk/src/common/math.cpp index 052f2e8..a60839f 100644 --- a/src/common/math.cpp +++ b/afk/src/common/math.cpp @@ -11,8 +11,7 @@ #include "common/math.h" -namespace afk { -namespace math { +namespace afk::math { // Lerp between two values float lerp(float start, float end, float progress) { @@ -30,5 +29,4 @@ float clamp(float value, float min, float max) { return value; } -} // namespace math -} // namespace afk +} // namespace afk::math diff --git a/afk/src/common/random.cpp b/afk/src/common/random.cpp new file mode 100644 index 0000000..fb2e86a --- /dev/null +++ b/afk/src/common/random.cpp @@ -0,0 +1,30 @@ +/** + * @file RandomGenerator.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of Random class methods + * @version 0.1 + * @date 2020-08-11 + * + * @copyright Copyright (c) 2021 + * + */ +#include "common/random.h" + +namespace afk::random { + +// Init generator +std::mt19937 rng = std::mt19937(std::random_device{}()); + +// Random Float +float randomFloat(const float min, const float max) { + std::uniform_real_distribution floatDist{min, max}; + return floatDist(rng); +} + +// Random Int +int randomInt(const int min, const int max) { + std::uniform_int_distribution intDist{min, max}; + return intDist(rng); +} + +} // namespace afk::random diff --git a/src/common/str.cpp b/afk/src/common/str.cpp similarity index 93% rename from src/common/str.cpp rename to afk/src/common/str.cpp index 625126c..531cab9 100644 --- a/src/common/str.cpp +++ b/afk/src/common/str.cpp @@ -12,8 +12,7 @@ #include -namespace afk { -namespace str { +namespace afk::str { // Checks bool isInteger(const std::string& str) { @@ -55,5 +54,4 @@ float toFloat(const std::string& str) { return std::stof(str); } -} // namespace str -} // namespace afk +} // namespace afk::str diff --git a/src/primitives/Primitives.cpp b/afk/src/primitives/Primitives.cpp similarity index 84% rename from src/primitives/Primitives.cpp rename to afk/src/primitives/Primitives.cpp index d677a79..11bb712 100644 --- a/src/primitives/Primitives.cpp +++ b/afk/src/primitives/Primitives.cpp @@ -13,14 +13,13 @@ #include "primitives/Primitives.h" #include "services/Services.h" -namespace afk { -namespace primitives { +namespace afk::primitives { // Draw a rectangle -void rect(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, +void rect(const int32_t x, + const int32_t y, + const int32_t w, + const int32_t h, color::Color colour) { SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); @@ -30,10 +29,10 @@ void rect(const Sint32 x, } // Draw a filled rectangle -void rectfill(const Sint32 x, - const Sint32 y, - const Sint32 w, - const Sint32 h, +void rectfill(const int32_t x, + const int32_t y, + const int32_t w, + const int32_t h, color::Color colour) { SDL_Renderer* renderer = Services::getDisplayService().getRenderer(); @@ -67,5 +66,4 @@ void line(const Sint16 x1, lineRGBA(renderer, x1, y1, x2, y2, colour.r, colour.g, colour.b, colour.a); } -} // namespace primitives -} // namespace afk +} // namespace afk::primitives diff --git a/afk/src/scene/Scene.cpp b/afk/src/scene/Scene.cpp new file mode 100644 index 0000000..8afbf17 --- /dev/null +++ b/afk/src/scene/Scene.cpp @@ -0,0 +1,66 @@ +/** + * @file Scene.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of Scene class + * @version 0.1 + * @date 2016-12-30 + * + * @copyright Copyright (c) 2021 + * + */ +#include "scene/Scene.h" + +#include "systems/CollisionSystem.h" +#include "systems/ParticleSystem.h" +#include "systems/PhysicsSystem.h" +#include "systems/RenderSystem.h" +#include "systems/UISystem.h" + +namespace afk { + +// Constructor +Scene::Scene() + : audio(afk::Services::getAudioService()), + logger(afk::Services::getLoggingService()), + display(afk::Services::getDisplayService()), + assets(afk::Services::getAssetService()), + input(afk::Services::getInputService()), + scene(afk::Services::getSceneService()), + config(afk::Services::getConfigService()) {} + +// Internal update method +void Scene::update(uint32_t delta) { + systems::collisionSystem(registry); + systems::physicsSystem(registry, delta); + systems::particleSystem(registry, delta); +} + +// Draw internal method +void Scene::draw() { + // Draw + systems::renderSystem(registry); + systems::uiSystem(registry, assets, input); + systems::particleRenderSystem(registry, assets); +} + +// Internal cleanup (on switch scene) +void Scene::stopInternal() { + // entities.clear(); +} + +// Register a new entity +Entity Scene::createEntity() { + return registry.create(); +} + +// Remove an entity +void Scene::destroyEntity(Entity entity) { + registry.destroy(entity); +} + +// Get a reference to the registry +Registry& Scene::getRegistry() { + return registry; +} + +} // namespace afk diff --git a/src/services/Services.cpp b/afk/src/services/Services.cpp similarity index 55% rename from src/services/Services.cpp rename to afk/src/services/Services.cpp index c6e0190..e5b379b 100644 --- a/src/services/Services.cpp +++ b/afk/src/services/Services.cpp @@ -10,50 +10,48 @@ */ #include "services/Services.h" -#include "common/Exceptions.h" - namespace afk { // Init services -DebugLoggingService Services::logging_service; -EventQueue Services::event_service; -SceneService Services::scene_service; -DisplayService Services::display_service; -InputService Services::input_service; -AudioService Services::audio_service; -AssetService Services::asset_service; -ConfigService Services::config_service; +DebugLoggingService Services::loggingService; +EventQueue Services::eventService; +SceneService Services::sceneService; +DisplayService Services::displayService; +InputService Services::inputService; +AudioService Services::audioService; +AssetService Services::assetService; +ConfigService Services::configService; AudioService& Services::getAudioService() { - return audio_service; + return audioService; } AssetService& Services::getAssetService() { - return asset_service; + return assetService; } DisplayService& Services::getDisplayService() { - return display_service; + return displayService; } ConfigService& Services::getConfigService() { - return config_service; + return configService; } LoggingService& Services::getLoggingService() { - return logging_service; + return loggingService; } InputService& Services::getInputService() { - return input_service; + return inputService; } SceneService& Services::getSceneService() { - return scene_service; + return sceneService; } EventQueue& Services::getEventQueue() { - return event_service; + return eventService; } } // namespace afk diff --git a/src/services/assets/AssetService.cpp b/afk/src/services/assets/AssetService.cpp similarity index 63% rename from src/services/assets/AssetService.cpp rename to afk/src/services/assets/AssetService.cpp index cdacc2a..183ffb9 100644 --- a/src/services/assets/AssetService.cpp +++ b/afk/src/services/assets/AssetService.cpp @@ -11,8 +11,6 @@ #include "services/assets/AssetService.h" #include -#include -#include #include #include "common/Exceptions.h" @@ -38,69 +36,71 @@ AssetService::AssetService() { } } -// Destructor -AssetService::~AssetService() { - // Todo cleanup -} - // Load image from disk and assign key -void AssetService::loadImage(const std::string& key, const std::string& path) { +const Texture& AssetService::loadImage(const std::string& key, + const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading image: " + key); try { - loaded_image[key] = Texture(path); + loadedImage[key] = Texture(path); + return loadedImage[key]; } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load image " + key); + throw FileIoException("Could not load image " + key); } } // Load audio from disk and assign key -void AssetService::loadAudio(const std::string& key, const std::string& path) { +const Sound& AssetService::loadAudio(const std::string& key, + const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading audio: " + key); try { - loaded_audio[key] = Sound(path); + loadedAudio[key] = Sound(path); + return loadedAudio[key]; } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load sound " + key); + throw FileIoException("Could not load sound " + key); } } // Load font from disk and assign key -void AssetService::loadFont(const std::string& key, - const std::string& path, - const int size) { +const Font& AssetService::loadFont(const std::string& key, + const std::string& path, + const int size) { Services::getLoggingService().log("[Asset Manager] Loading font: " + key); try { - loaded_font[key] = Font(path, size); + loadedFont[key] = Font(path, size); + return loadedFont[key]; } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load font " + key); + throw FileIoException("Could not load font " + key); } } // Load stream from disk and assign key -void AssetService::loadStream(const std::string& key, const std::string& path) { +const Stream& AssetService::loadStream(const std::string& key, + const std::string& path) { Services::getLoggingService().log("[Asset Manager] Loading stream: " + key); try { - loaded_stream[key] = Stream(path); + loadedStream[key] = Stream(path); + return loadedStream[key]; } catch (const std::runtime_error& e) { - throw FileIOException(e.what()); + throw FileIoException(e.what()); } catch (...) { - throw FileIOException("Could not load stream " + key); + throw FileIoException("Could not load stream " + key); } } // Get image reference const Texture& AssetService::getImage(const std::string& key) { try { - return loaded_image.at(key); + return loadedImage.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find image " + key); } @@ -109,7 +109,7 @@ const Texture& AssetService::getImage(const std::string& key) { // Get audio reference const Sound& AssetService::getAudio(const std::string& key) { try { - return loaded_audio.at(key); + return loadedAudio.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find sound " + key); } @@ -118,7 +118,7 @@ const Sound& AssetService::getAudio(const std::string& key) { // Get font reference const Font& AssetService::getFont(const std::string& key) { try { - return loaded_font.at(key); + return loadedFont.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find font " + key); } @@ -127,7 +127,7 @@ const Font& AssetService::getFont(const std::string& key) { // Get stream reference const Stream& AssetService::getStream(const std::string& key) { try { - return loaded_stream.at(key); + return loadedStream.at(key); } catch (const std::out_of_range&) { throw KeyLookupException("Could not find stream " + key); } diff --git a/src/services/audio/AudioService.cpp b/afk/src/services/audio/AudioService.cpp similarity index 100% rename from src/services/audio/AudioService.cpp rename to afk/src/services/audio/AudioService.cpp diff --git a/src/services/config/ConfigService.cpp b/afk/src/services/config/ConfigService.cpp similarity index 72% rename from src/services/config/ConfigService.cpp rename to afk/src/services/config/ConfigService.cpp index cda526a..6caa5a3 100644 --- a/src/services/config/ConfigService.cpp +++ b/afk/src/services/config/ConfigService.cpp @@ -19,7 +19,7 @@ namespace afk { // Constructor -ConfigService::ConfigService() : autosave(false) { +ConfigService::ConfigService() : autoSave(false) { Services::getLoggingService().log("[Config Service]: Starting up"); } @@ -34,19 +34,19 @@ void ConfigService::load(const std::string& path) { std::ifstream fileStream(path); if (!fileStream.is_open()) { - throw FileIOException("Could not open file from " + path); + throw FileIoException("Could not open file from " + path); } while (getline(fileStream, line)) { // Split string - int delimLoc = line.find("="); - if (delimLoc == -1) { + int delimiterLocation = line.find('='); + if (delimiterLocation == -1) { continue; } // Get values - std::string key = line.substr(0, delimLoc); - std::string value = line.substr(delimLoc + 1, line.length()); + std::string key = line.substr(0, delimiterLocation); + std::string value = line.substr(delimiterLocation + 1, line.length()); // Conversion settings[key] = value; @@ -59,12 +59,12 @@ void ConfigService::load(const std::string& path) { "[Setting Manager] Loaded settings from file " + path); // Set internal file name - file_name = path; + fileName = path; } // Save file void ConfigService::save() { - save(file_name); + save(fileName); } void ConfigService::save(const std::string& path) { @@ -75,7 +75,7 @@ void ConfigService::save(const std::string& path) { std::ofstream fileStream(path); if (!fileStream.is_open()) { - throw FileIOException("Could not open file from path " + path); + throw FileIoException("Could not open file from path " + path); } for (auto const& entry : this->settings) { @@ -85,9 +85,9 @@ void ConfigService::save(const std::string& path) { fileStream.close(); } -// Set autosave -void ConfigService::setAutosave(const bool autosave) { - this->autosave = autosave; +// Set auto save +void ConfigService::setAutoSave(const bool autoSave) { + this->autoSave = autoSave; } } // namespace afk diff --git a/src/services/display/DisplayService.cpp b/afk/src/services/display/DisplayService.cpp similarity index 56% rename from src/services/display/DisplayService.cpp rename to afk/src/services/display/DisplayService.cpp index 82acb2b..f800c10 100644 --- a/src/services/display/DisplayService.cpp +++ b/afk/src/services/display/DisplayService.cpp @@ -17,16 +17,10 @@ #include "common/Exceptions.h" #include "scene/Scene.h" -#include "color/Color.h" -#include "services/Services.h" - namespace afk { // Setup DisplayService -DisplayService::DisplayService() : clear_color(color::white) { - // Set initial time - old_time = SDL_GetTicks(); -} +DisplayService::DisplayService() : oldTime(SDL_GetTicks()) {} // Cleanup window DisplayService::~DisplayService() { @@ -40,78 +34,79 @@ DisplayService::~DisplayService() { } } -void DisplayService::draw(Scene* current_scene) { +void DisplayService::draw(Scene* currentScene) { if (!window || !renderer) { return; } // Render a frame - SDL_SetRenderDrawColor(renderer, clear_color.r, clear_color.g, clear_color.b, - clear_color.a); + SDL_SetRenderDrawColor(renderer, clearColor.r, clearColor.g, clearColor.b, + clearColor.a); SDL_RenderClear(renderer); - current_scene->draw(); + currentScene->draw(); // Flip SDL_RenderPresent(renderer); // Update frame index - frames_array[frame_index] = SDL_GetTicks() - old_time; - old_time = SDL_GetTicks(); - frame_index = (frame_index + 1) % FRAME_BUFFER_SIZE; - - float fps_total = 0; - for (Uint32 i = 0; i < FRAME_BUFFER_SIZE; ++i) { - fps_total += frames_array[i]; + uint32_t currentTime = SDL_GetTicks(); + framesArray[frameIndex] = currentTime - oldTime; + oldTime = currentTime; + frameIndex = (frameIndex + 1) % frameBufferSize; + + float fpsTotal = 0; + for (unsigned int i : framesArray) { + fpsTotal += i; } // FPS = average - fps = 1000.0f / (fps_total / FRAME_BUFFER_SIZE); + fps = 1000.0f / (fpsTotal / frameBufferSize); } // Returns current display mode DisplayMode DisplayService::getDisplayMode() const { - return display_mode; + return displayMode; } // Gets draw width -Uint32 DisplayService::getDrawWidth() const { - return draw_w; +uint32_t DisplayService::getDrawWidth() const { + return drawW; } // Gets draw height -Uint32 DisplayService::getDrawHeight() const { - return draw_h; +uint32_t DisplayService::getDrawHeight() const { + return drawH; } // Gets translation x -Uint32 DisplayService::getTranslationX() const { - return translation_x; +uint32_t DisplayService::getTranslationX() const { + return translationX; } // Gets translation y -Uint32 DisplayService::getTranslationY() const { - return translation_y; +uint32_t DisplayService::getTranslationY() const { + return translationY; } // Gets scale width -Uint32 DisplayService::getDisplayServiceWidth() const { - return window_w; +uint32_t DisplayService::getDisplayServiceWidth() const { + return windowW; } // Gets scale height -Uint32 DisplayService::getDisplayServiceHeight() const { - return window_h; +uint32_t DisplayService::getDisplayServiceHeight() const { + return windowH; } // Gets scale x float DisplayService::getScaleX() const { - return scale_x; + return scaleX; } // Gets scale y float DisplayService::getScaleY() const { - return scale_y; + return scaleY; } // Hide mouse from display @@ -125,64 +120,64 @@ void DisplayService::showMouse() { } // Resize window -void DisplayService::resize(const Uint32 window_w, const Uint32 window_h) { +void DisplayService::resize(const uint32_t windowW, const uint32_t windowH) { // Get monitor width SDL_DisplayMode info; SDL_GetCurrentDisplayMode(0, &info); // Window mode - switch (display_mode) { - // Fullscreen windowed stretch - case DisplayMode::FULLSCREEN_WINDOW_STRETCH: + switch (displayMode) { + // Full screen windowed stretch + case DisplayMode::FullScreenWindowStretch: // Set flags SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // Set up screen size and positions setWindowSize(info.w, info.h); - setScale(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h); + setScale(static_cast(windowW) / drawW, + static_cast(windowH) / drawH); setTranslation(0.0f, 0.0f); break; - // Fullscreen window center - case DisplayMode::FULLSCREEN_WINDOW_CENTER: + // Full screen window center + case DisplayMode::FullScreenWindowCenter: // Set flags SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // Set up screen size and positions setWindowSize(info.w, info.h); setScale(1.0f, 1.0f); - setTranslation((window_w - scale_x * draw_w) / 2, - (window_h - scale_y * draw_h) / 2); + setTranslation((windowW - scaleX * drawW) / 2, + (windowH - scaleY * drawH) / 2); break; - // Fullscreen window center - case DisplayMode::FULLSCREEN_WINDOW_LETTERBOX: + // Full screen window center + case DisplayMode::FullScreenWindowLetterbox: // Set flags SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // Set up screen size and positions setWindowSize(info.w, info.h); - setScale(std::min(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h), - std::min(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h)); - setTranslation((window_w - scale_x * draw_w) / 2, - (window_h - scale_y * draw_h) / 2); + setScale(std::min(static_cast(windowW) / drawW, + static_cast(windowH) / drawH), + std::min(static_cast(windowW) / drawW, + static_cast(windowH) / drawH)); + setTranslation((windowW - scaleX * drawW) / 2, + (windowH - scaleY * drawH) / 2); break; // Windowed - case DisplayMode::WINDOWED: + case DisplayMode::Windowed: // Set flags SDL_SetWindowFullscreen(window, 0); // Set up screen size and positions - setWindowSize(window_w, window_h); - setScale(static_cast(window_w) / draw_w, - static_cast(window_h) / draw_h); + setWindowSize(windowW, windowH); + setScale(static_cast(windowW) / drawW, + static_cast(windowH) / drawH); setTranslation(0.0f, 0.0f); break; @@ -193,31 +188,33 @@ void DisplayService::resize(const Uint32 window_w, const Uint32 window_h) { } // Set scale - SDL_RenderSetScale(renderer, draw_w, draw_h); + SDL_RenderSetScale(renderer, drawW, drawH); } // Set window size -void DisplayService::setWindowSize(const Uint32 width, const Uint32 height) { - window_w = width; - window_h = height; +void DisplayService::setWindowSize(const uint32_t width, + const uint32_t height) { + windowW = width; + windowH = height; } // Set buffer size -void DisplayService::setBufferSize(const Uint32 width, const Uint32 height) { - draw_w = width; - draw_h = height; +void DisplayService::setBufferSize(const uint32_t width, + const uint32_t height) { + drawW = width; + drawH = height; } // Set scale void DisplayService::setScale(const float width, const float height) { - scale_x = width; - scale_y = height; + scaleX = width; + scaleY = height; } // Set translation -void DisplayService::setTranslation(const Uint32 x, const Uint32 y) { - translation_x = x; - translation_y = y; +void DisplayService::setTranslation(const uint32_t x, const uint32_t y) { + translationX = x; + translationY = y; } // Set window @@ -229,7 +226,7 @@ void DisplayService::setTitle(const std::string& title) { void DisplayService::setIcon(const std::string& path) { SDL_Surface* icon = IMG_Load(path.c_str()); if (!icon) { - throw FileIOException("Could not load icon " + path); + throw FileIoException("Could not load icon " + path); } SDL_SetWindowIcon(window, icon); SDL_FreeSurface(icon); @@ -237,7 +234,7 @@ void DisplayService::setIcon(const std::string& path) { // Set clear colour void DisplayService::setBackgroundColor(const color::Color& color) { - clear_color = color; + clearColor = color; } // Get fps @@ -263,15 +260,15 @@ void DisplayService::setMode(const DisplayMode mode) { } // Set mode - display_mode = mode; + displayMode = mode; // Resize window - resize(window_w, window_h); + resize(windowW, windowH); // Create display window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, - window_w, window_h, SDL_WINDOW_RESIZABLE); + windowW, windowH, SDL_WINDOW_RESIZABLE); if (!window) { throw InitException("Could not create window"); } diff --git a/src/services/events/EventQueue.cpp b/afk/src/services/events/EventQueue.cpp similarity index 72% rename from src/services/events/EventQueue.cpp rename to afk/src/services/events/EventQueue.cpp index 57bce23..9fdec82 100644 --- a/src/services/events/EventQueue.cpp +++ b/afk/src/services/events/EventQueue.cpp @@ -10,10 +10,8 @@ */ #include #include -#include #include "services/Services.h" -#include "services/events/EventQueue.h" namespace afk { @@ -45,37 +43,37 @@ void EventQueue::registerService(Service* service) { void EventQueue::unregisterService(Service* service) { Services::getLoggingService().log("[" + service->getName() + "] Shutting down"); - services.erase(std::remove(services.begin(), services.end(), service)); + services.erase(std::remove(services.begin(), services.end(), service), services.end()); } // Register user timer -SDL_TimerID EventQueue::registerTimer(const Uint32 time, const char code) { +SDL_TimerID EventQueue::registerTimer(const uint32_t time, const char code) { void* c = malloc(sizeof(code)); memcpy(c, &code, sizeof(code)); - SDL_TimerID timer_id = SDL_AddTimer(time, EventQueue::timerCallback, c); - return timer_id; + SDL_TimerID timerId = SDL_AddTimer(time, EventQueue::timerCallback, c); + return timerId; } // Unregister user timer -void EventQueue::unregisterTimer(const SDL_TimerID timer_id) { - SDL_RemoveTimer(timer_id); +void EventQueue::unregisterTimer(const SDL_TimerID timerId) { + SDL_RemoveTimer(timerId); } // Timer callback -Uint32 EventQueue::timerCallback(Uint32 interval, void* param) { +uint32_t EventQueue::timerCallback(uint32_t interval, void* param) { SDL_Event event; - SDL_UserEvent userevent; + SDL_UserEvent userEvent; char code = *(reinterpret_cast(param)); - userevent.type = SDL_USEREVENT; - userevent.code = code; - userevent.data1 = NULL; - userevent.data2 = NULL; + userEvent.type = SDL_USEREVENT; + userEvent.code = code; + userEvent.data1 = nullptr; + userEvent.data2 = nullptr; event.type = SDL_USEREVENT; - event.user = userevent; + event.user = userEvent; SDL_PushEvent(&event); return interval; diff --git a/src/services/input/InputService.cpp b/afk/src/services/input/InputService.cpp similarity index 60% rename from src/services/input/InputService.cpp rename to afk/src/services/input/InputService.cpp index b45dd5f..64adb41 100644 --- a/src/services/input/InputService.cpp +++ b/afk/src/services/input/InputService.cpp @@ -14,7 +14,7 @@ #include "common/Exceptions.h" #include "services/Services.h" -const float JOYSTICK_DEADZONE = 0.6f; +const float JOYSTICK_DEAD_ZONE = 0.6f; namespace afk { @@ -24,10 +24,10 @@ InputService::InputService() { Services::getEventQueue().registerService(this); // Set joystick enabled - joystick_state.enabled = SDL_NumJoysticks() > 0; + joystickState.enabled = SDL_NumJoysticks() > 0; // Open joystick if enabled - if (joystick_state.enabled) { + if (joystickState.enabled) { SDL_JoystickOpen(0); } } @@ -74,20 +74,20 @@ void InputService::notify(const SDL_Event& event) { // Update routine void InputService::update() { - mouse_state.update(); - keyboard_state.update(); - joystick_state.update(); + mouseState.update(); + keyboardState.update(); + joystickState.update(); } // Joystick button event -void InputService::onJoystickEvent(const Uint32 event_type, +void InputService::onJoystickEvent(const uint32_t eventType, const SDL_JoyButtonEvent event) { - switch (event_type) { + switch (eventType) { case SDL_JOYBUTTONDOWN: - joystick_state.button[event.button] = true; + joystickState.button[event.button] = true; break; case SDL_JOYBUTTONUP: - joystick_state.button[event.button] = false; + joystickState.button[event.button] = false; break; default: break; @@ -97,38 +97,38 @@ void InputService::onJoystickEvent(const Uint32 event_type, // Joystick axis event void InputService::onJoystickEvent(const SDL_JoyAxisEvent event) { // Translated axis - const int trans_axis = (JOY_MAX_AXES + event.axis) * 2; + const int transAxis = (JOY_MAX_AXES + event.axis) * 2; // Check if moved enough - if (event.value > JOYSTICK_DEADZONE) { - joystick_state.stick[trans_axis] = true; - } else if (event.value < -JOYSTICK_DEADZONE) { - joystick_state.stick[trans_axis + 1] = true; + if (event.value > JOYSTICK_DEAD_ZONE) { + joystickState.stick[transAxis] = true; + } else if (event.value < -JOYSTICK_DEAD_ZONE) { + joystickState.stick[transAxis + 1] = true; } else { - joystick_state.stick[trans_axis] = false; - joystick_state.stick[trans_axis + 1] = false; + joystickState.stick[transAxis] = false; + joystickState.stick[transAxis + 1] = false; } } -// Joystick reconfig event +// Joystick reconfigure event void InputService::onJoystickReconfigureEvent() { - joystick_state.enabled = SDL_NumJoysticks() > 0; + joystickState.enabled = SDL_NumJoysticks() > 0; // Open joystick if enabled - if (joystick_state.enabled) { + if (joystickState.enabled) { SDL_JoystickOpen(0); } } // Keyboard event -void InputService::onKeyboardEvent(const Uint32 event_type, +void InputService::onKeyboardEvent(const uint32_t eventType, const SDL_KeyboardEvent event) { - switch (event_type) { + switch (eventType) { case SDL_KEYDOWN: - keyboard_state.key[event.keysym.scancode] = true; + keyboardState.key[event.keysym.scancode] = true; break; case SDL_KEYUP: - keyboard_state.key[event.keysym.scancode] = false; + keyboardState.key[event.keysym.scancode] = false; break; default: break; @@ -137,29 +137,29 @@ void InputService::onKeyboardEvent(const Uint32 event_type, // Mouse axis handler void InputService::onMouseEvent(const SDL_MouseMotionEvent event) { - mouse_state.x = (event.x - Services::getDisplayService().getTranslationX()) / + mouseState.x = (event.x - Services::getDisplayService().getTranslationX()) / Services::getDisplayService().getScaleX(); - mouse_state.y = (event.y - Services::getDisplayService().getTranslationY()) / + mouseState.y = (event.y - Services::getDisplayService().getTranslationY()) / Services::getDisplayService().getScaleY(); } // Mouse axis handler void InputService::onMouseEvent(const SDL_MouseWheelEvent event) { - mouse_state.z = event.y; + mouseState.z = event.y; } // Mouse button handler -void InputService::onMouseEvent(const Uint32 event_type, +void InputService::onMouseEvent(const uint32_t eventType, const SDL_MouseButtonEvent event) { - switch (event_type) { + switch (eventType) { case SDL_MOUSEBUTTONUP: - if (event.button < static_cast(MouseButtons::MAX)) { - mouse_state.button[event.button] = false; + if (event.button < static_cast(MouseButtons::Max)) { + mouseState.button[event.button] = false; } break; case SDL_MOUSEBUTTONDOWN: - if (event.button < static_cast(MouseButtons::MAX)) { - mouse_state.button[event.button] = true; + if (event.button < static_cast(MouseButtons::Max)) { + mouseState.button[event.button] = true; } break; default: @@ -169,95 +169,104 @@ void InputService::onMouseEvent(const Uint32 event_type, // Get key just down state bool InputService::keyPressed(const Keys key) const { - if (key > Keys::MAX) { + if (key > Keys::Max) { return false; } - return keyboard_state.keyPressed[static_cast(key)]; + return keyboardState.keyPressed[static_cast(key)]; } // Get key just up state bool InputService::keyReleased(const Keys key) const { - if (key > Keys::MAX) { + if (key > Keys::Max) { return false; } - return keyboard_state.keyReleased[static_cast(key)]; + return keyboardState.keyReleased[static_cast(key)]; } // Get key down state bool InputService::keyDown(const Keys key) const { - if (key > Keys::MAX) { + if (key > Keys::Max) { return false; } - return keyboard_state.key[static_cast(key)]; + return keyboardState.key[static_cast(key)]; } // Get any key down state bool InputService::anyKeyDown() const { - return keyboard_state.anyKeyDown; + return keyboardState.anyKeyDown; } // Get last key pressed int InputService::lastKeyPressed() const { - return keyboard_state.lastKeyPressed; + return keyboardState.lastKeyPressed; } // Get last key pressed int InputService::lastKeyReleased() const { - return keyboard_state.lastKeyReleased; + return keyboardState.lastKeyReleased; } // Get mouse button just down state bool InputService::mousePressed(const MouseButtons button) const { - if (button > MouseButtons::MAX) { + if (button > MouseButtons::Max) { return false; } - return mouse_state.down[static_cast(button)]; + return mouseState.down[static_cast(button)]; } // Get mouse button just up state bool InputService::mouseReleased(const MouseButtons button) const { - if (button > MouseButtons::MAX) { + if (button > MouseButtons::Max) { return false; } - return mouse_state.up[static_cast(button)]; + return mouseState.up[static_cast(button)]; } // Get mouse button down state bool InputService::mouseDown(const MouseButtons button) const { - if (button > MouseButtons::MAX) { + if (button > MouseButtons::Max) { return false; } - return mouse_state.button[static_cast(button)]; + return mouseState.button[static_cast(button)]; +} + +// Get mouse button down state +bool InputService::mouseOver(const Vec2 position, const Vec2 size) const { + if (mouseState.x < position.x || mouseState.x > position.x + size.x || + mouseState.y < position.y || mouseState.y > position.y + size.y) { + return false; + } + return true; } // Get mouse x position int InputService::mouseX() const { - return mouse_state.x; + return mouseState.x; } // Get mouse y position int InputService::mouseY() const { - return mouse_state.y; + return mouseState.y; } // Check if joystick enabled bool InputService::joyEnabled() const { - return joystick_state.enabled; + return joystickState.enabled; } // Get joy button just down state bool InputService::joyPressed(const JoystickButtons button) const { - return joystick_state.buttonPressed[static_cast(button)]; + return joystickState.buttonPressed[static_cast(button)]; } // Get joy button just up state bool InputService::joyReleased(const JoystickButtons button) const { - return joystick_state.buttonReleased[static_cast(button)]; + return joystickState.buttonReleased[static_cast(button)]; } // Get joy button down state bool InputService::joyDown(const JoystickButtons button) const { - return joystick_state.button[static_cast(button)]; + return joystickState.button[static_cast(button)]; } } // namespace afk diff --git a/src/services/logging/DebugLoggingService.cpp b/afk/src/services/logging/DebugLoggingService.cpp similarity index 100% rename from src/services/logging/DebugLoggingService.cpp rename to afk/src/services/logging/DebugLoggingService.cpp diff --git a/src/services/logging/LoggingService.cpp b/afk/src/services/logging/LoggingService.cpp similarity index 100% rename from src/services/logging/LoggingService.cpp rename to afk/src/services/logging/LoggingService.cpp diff --git a/src/services/scene/SceneService.cpp b/afk/src/services/scene/SceneService.cpp similarity index 56% rename from src/services/scene/SceneService.cpp rename to afk/src/services/scene/SceneService.cpp index ba40b35..b2a4508 100644 --- a/src/services/scene/SceneService.cpp +++ b/afk/src/services/scene/SceneService.cpp @@ -14,19 +14,15 @@ #include "common/Exceptions.h" #include "scene/Scene.h" -#include "services/Services.h" namespace afk { // Register events SceneService::SceneService() - : current_scene(nullptr), - scene_id(""), - next_scene(""), - last_tick(SDL_GetTicks()) {} + : currentScene(nullptr), lastTick(SDL_GetTicks()) {} // Unregister events -SceneService::~SceneService() {} +SceneService::~SceneService() = default; // Update scene void SceneService::update() { @@ -34,64 +30,64 @@ void SceneService::update() { changeScene(); // Update scene - if (current_scene) { - Uint32 delta = SDL_GetTicks() - last_tick; - current_scene->update(delta); + if (currentScene) { + uint32_t currentTick = SDL_GetTicks(); + uint32_t delta = currentTick - lastTick; + lastTick = currentTick; + currentScene->update(delta); } - - last_tick = SDL_GetTicks(); } // Update scene void SceneService::draw() { - Services::getDisplayService().draw(current_scene); + Services::getDisplayService().draw(currentScene); } // Get scene Scene* SceneService::getSceneService() { - return this->current_scene; + return this->currentScene; } // Change game screen void SceneService::changeScene() { // If the scene needs not to be changed - if (next_scene == "") { + if (nextScene.empty()) { return; } // Cleanup current scene - if (current_scene) { - current_scene->stop(); - current_scene->stopInternal(); + if (currentScene) { + currentScene->stop(); + currentScene->stopInternal(); } // Find scene auto it = std::find_if( scenes.begin(), scenes.end(), - [this](const SceneType& scene) { return scene.scene_id == next_scene; }); + [this](const SceneType& scene) { return scene.sceneId == nextScene; }); // Dad not found if (it == scenes.end()) { - throw SceneLookupException("Scene not found (" + next_scene + ")"); + throw SceneLookupException("Scene not found (" + nextScene + ")"); } // Create scene - current_scene = (*it).scene; - current_scene->start(); + currentScene = (*it).scene; + currentScene->start(); // Change the current scene ID - scene_id = next_scene; + sceneId = nextScene; // NULL the next scene ID - next_scene = ""; + nextScene = ""; } // Set next scene to load -void SceneService::setNextScene(const std::string& scene_id) { +void SceneService::setNextScene(const std::string& sceneId) { // If the user doesn't want to exit - if (next_scene != "exit") { + if (nextScene != "exit") { // Set the next scene - next_scene = scene_id; + nextScene = sceneId; } } diff --git a/afk/src/systems/CollisionSystem.cpp b/afk/src/systems/CollisionSystem.cpp new file mode 100644 index 0000000..adf61c8 --- /dev/null +++ b/afk/src/systems/CollisionSystem.cpp @@ -0,0 +1,44 @@ +/** + * @file CollisionSystem.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Implementation of CollisionSystem + * @version 0.1 + * @date 2022-04-22 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/CollisionSystem.h" + +#include "components/Collider.h" +#include "components/Transform.h" + +namespace afk::systems { + +void collisionSystem(Registry& registry) { + auto view = registry.view(); + + for (auto [entity, tran, collider] : view.each()) { + // Reset state + collider.colliding = false; + + for (auto [entityOther, tranOther, colliderOther] : view.each()) { + // Check if is entity + if (entity == entityOther) { + continue; + } + + // Check if colliding + if (tran.position.x > tranOther.position.x + tranOther.size.x || + tran.position.x + tran.size.x < tranOther.position.x || + tran.position.y > tranOther.position.y + tranOther.size.y || + tran.position.y + tran.size.y < tranOther.position.y) { + continue; + } + + collider.colliding = true; + } + } +} + +} // namespace afk::system \ No newline at end of file diff --git a/afk/src/systems/ParticleSystem.cpp b/afk/src/systems/ParticleSystem.cpp new file mode 100644 index 0000000..c8b462c --- /dev/null +++ b/afk/src/systems/ParticleSystem.cpp @@ -0,0 +1,113 @@ +/** + * @file ParticleSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating and rendering particles + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/ParticleSystem.h" + +#include "common/math.h" +#include "common/random.h" +#include "components/Particle.h" +#include "components/ParticleEmitter.h" +#include "components/Transform.h" +#include "primitives/Primitives.h" + +namespace afk::systems { + +/** + * @brief ParticleSystem + * + */ +void particleSystem(Registry& registry, uint32_t delta) { + auto particleView = registry.view(); + + int count = 0; + for (auto [entity, tran, particle] : particleView.each()) { + tran.size.x = math::lerp(particle.startSize, particle.endSize, + particle.age / particle.lifespan); + tran.size.y = tran.size.x; + + particle.age += delta; + if (particle.age > particle.lifespan) { + registry.destroy(entity); + } + + count++; + } + + auto systemView = registry.view(); + + for (auto [entity, tran, emitter] : systemView.each()) { + emitter.counter += delta; + + while (emitter.counter > emitter.frequency && !emitter.prefabs.empty()) { + int index = random::randomInt(0, emitter.prefabs.size() - 1); + auto& [particle, physics] = emitter.prefabs.at(index); + + emitter.counter -= emitter.frequency; + + const float startX = + tran.position.x + random::randomFloat(0, tran.size.x); + const float startY = + tran.position.y + random::randomFloat(0, tran.size.y); + + const auto& particleId = registry.create(); + registry.emplace(particleId, particle); + registry.emplace(particleId, physics); + registry.emplace(particleId, + Vec3(startX, startY, tran.position.z), + Vec2(particle.startSize, particle.startSize)); + } + } +} + +void particleRenderSystem(Registry& registry, AssetService& assetService) { + auto view = registry.view(); + + for (auto [entity, tran, particle] : view.each()) { + float lifePercent = particle.age / particle.lifespan; + + // Lerp size + float size = math::lerp(particle.startSize, particle.endSize, lifePercent); + + // Lerp color + uint8_t r = + math::lerp(particle.startColor.r, particle.endColor.r, lifePercent); + uint8_t g = + math::lerp(particle.startColor.g, particle.endColor.g, lifePercent); + uint8_t b = + math::lerp(particle.startColor.b, particle.endColor.b, lifePercent); + uint8_t a = + math::lerp(particle.startColor.a, particle.endColor.a, lifePercent); + color::Color color = {r, g, b, a}; + + // Switch over type + switch (particle.type) { + case ParticleType::Square: + primitives::rectfill(tran.position.x, tran.position.y, size, size, + color); + break; + case ParticleType::Circle: + primitives::circle(tran.position.x, tran.position.y, size, color); + break; + case ParticleType::Pixel: + primitives::pixel(tran.position.x, tran.position.y, color); + break; + case ParticleType::Image: { + auto texture = assetService.getImage(particle.texture); + texture.drawEx(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, tran.angle); + break; + } + default: + break; + } + } +} + +} // namespace afk::systems diff --git a/afk/src/systems/PhysicsSystem.cpp b/afk/src/systems/PhysicsSystem.cpp new file mode 100644 index 0000000..6f72f75 --- /dev/null +++ b/afk/src/systems/PhysicsSystem.cpp @@ -0,0 +1,35 @@ +/** + * @file PhysicsSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of updating transforms + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/PhysicsSystem.h" +#include "components/Physics.h" +#include "components/Transform.h" +#include "services/assets/AssetService.h" + +namespace afk::systems { + +/** + * @brief PhysicsSystem + * + */ +void physicsSystem(Registry& registry, uint32_t delta) { + auto view = registry.view(); + + const float deltaSeconds = static_cast(delta) / 1000.0f; + + for (auto [entity, tran, physics] : view.each()) { + tran.position.x += physics.velocity.x * deltaSeconds; + tran.position.y += physics.velocity.y * deltaSeconds; + physics.velocity.x += physics.acceleration.x * deltaSeconds; + physics.velocity.y += physics.acceleration.y * deltaSeconds; + } +} + +} // namespace afk::systems diff --git a/afk/src/systems/RenderSystem.cpp b/afk/src/systems/RenderSystem.cpp new file mode 100644 index 0000000..67bf541 --- /dev/null +++ b/afk/src/systems/RenderSystem.cpp @@ -0,0 +1,30 @@ +/** + * @file RenderSystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/RenderSystem.h" +#include "components/Sprite.h" +#include "components/Transform.h" + +namespace afk::systems { + +/** + * @brief RenderSystem + * + */ +void renderSystem(Registry& registry) { + auto view = registry.view(); + + for (auto [entity, tran, sprite] : view.each()) { + sprite.texture.drawEx(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, tran.angle); + } +} + +} // namespace afk::systems diff --git a/afk/src/systems/UISystem.cpp b/afk/src/systems/UISystem.cpp new file mode 100644 index 0000000..7e929ab --- /dev/null +++ b/afk/src/systems/UISystem.cpp @@ -0,0 +1,58 @@ +/** + * @file UISystem.h + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief System in charge of rendering components + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "systems/UISystem.h" + +#include "components/Transform.h" +#include "components/ui/Button.h" +#include "components/ui/Label.h" +#include "primitives/Primitives.h" + +namespace afk::systems { + +/** + * @brief UISystem + * + */ +void uiSystem(Registry& registry, + AssetService& assetService, + InputService& inputService) { + auto viewLabels = registry.view(); + for (auto [entity, tran, label] : viewLabels.each()) { + auto font = assetService.getFont(label.font); + font.draw(tran.position.x, tran.position.y, label.text, label.color); + } + + auto viewButtons = registry.view(); + for (auto [entity, tran, button] : viewButtons.each()) { + // Draw button background + primitives::rectfill(tran.position.x, tran.position.y, tran.size.x, + tran.size.y, color::white); + + // Draw button border + primitives::rect(tran.position.x, tran.position.y, tran.size.x, tran.size.y, + color::black); + + // Draw text + auto font = assetService.getFont(button.font); + font.draw(tran.position.x, tran.position.y, button.text); + + if (button.onClick) { + if (inputService.mouseDown(MouseButtons::Left)) { + if (inputService.mouseOver(Vec2(tran.position.x, tran.position.y), + Vec2(tran.size.x, tran.size.y))) { + button.onClick(); + } + } + } + } +} + +} // namespace afk::systems diff --git a/src/entities/ui/MessageBox.cpp b/afk/src/ui/MessageBox.cpp similarity index 74% rename from src/entities/ui/MessageBox.cpp rename to afk/src/ui/MessageBox.cpp index 58d01a3..079c233 100644 --- a/src/entities/ui/MessageBox.cpp +++ b/afk/src/ui/MessageBox.cpp @@ -8,13 +8,14 @@ * @copyright Copyright (c) 2021 * */ -#include "entities/ui/MessageBox.h" +#include "ui/MessageBox.h" +#include #include "services/Services.h" namespace afk { -MessageBox::MessageBox(MessageBoxType type) : title(""), text(""), type(type) {} +MessageBox::MessageBox(MessageBoxType type) : type(type) {} // Set the title of the message box void MessageBox::setTitle(const std::string& title) { @@ -29,19 +30,19 @@ void MessageBox::setText(const std::string& text) { // Show the message box on screen int MessageBox::show() { SDL_Window* window = Services::getDisplayService().getWindow(); - int return_code = SDL_ShowSimpleMessageBox(resolveType(), title.c_str(), + int returnCode = SDL_ShowSimpleMessageBox(resolveType(), title.c_str(), text.c_str(), window); - return return_code; + return returnCode; } // Get type of box in SDL terms int MessageBox::resolveType() { switch (type) { - case MessageBoxType::ERROR: + case MessageBoxType::Error: return SDL_MESSAGEBOX_ERROR; - case MessageBoxType::INFO: + case MessageBoxType::Info: return SDL_MESSAGEBOX_INFORMATION; - case MessageBoxType::WARN: + case MessageBoxType::Warn: default: return SDL_MESSAGEBOX_WARNING; } diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 79e1509..07f08ad 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,82 +1,48 @@ -cmake_minimum_required(VERSION 3.11) - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) - -# Add include dir -include_directories(${CMAKE_BINARY_DIR}/include) -include_directories(${CMAKE_BINARY_DIR}/bin) - -# Find libs -if(NOT EMSCRIPTEN) - find_library(SDL_LIBRARY NAMES SDL2 REQUIRED) - find_library(SDL_MIXER_LIBRARY NAMES SDL2_mixer REQUIRED) - find_library(SDL_IMAGE_LIBRARY NAMES SDL2_image REQUIRED) - find_library(SDL_TTF_LIBRARY NAMES SDL2_ttf REQUIRED) - find_library(SDL_GFX_LIBRARY NAMES SDL2_gfx REQUIRED) - find_library(SDL_MAIN_LIBRARY NAMES SDL2main REQUIRED) -endif(NOT EMSCRIPTEN) +cmake_minimum_required(VERSION 3.16) +project (examples + VERSION 1.0.0 + LANGUAGES CXX +) +# Config +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(EXAMPLES ex_display ex_sprite ex_rotate ex_fps ex_mouse ex_physics ex_sound ex_particles ex_keyboard ex_collision ex_message_box) + # Build examples -set(EXAMPLES ex_display ex_collision ex_sprite ex_ui ex_message_box ex_fps ex_keyboard ex_mouse ex_sound ex_particles ex_rotate) - foreach(EX_NAME ${EXAMPLES}) - add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/${EX_NAME}.cpp) - target_compile_options(${EX_NAME} PRIVATE -O2 -Wall -Wextra -pedantic -Wno-unused-parameter) - - # Emscripten support - if(EMSCRIPTEN) + add_executable(${EX_NAME} ${CMAKE_CURRENT_LIST_DIR}/src/${EX_NAME}.cpp) + + target_compile_options(${EX_NAME} + PRIVATE + -Wall + -Wextra + -pedantic + -Wno-unused-parameter + ) + + # Emscripten specific options + if(EMSCRIPTEN) set(CMAKE_EXECUTABLE_SUFFIX ".html") - target_compile_options( - ${EX_NAME} - PRIVATE - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - ) - target_link_libraries( - ${EX_NAME} - -sWASM=1 - -sUSE_SDL=2 - -sUSE_SDL_IMAGE=2 - -sUSE_SDL_TTF=2 - -sUSE_SDL_MIXER=2 - -sUSE_SDL_GFX=2 - -sSDL2_IMAGE_FORMATS=["png"] - -sDEMANGLE_SUPPORT=1 - -sTOTAL_MEMORY=512MB - afk - ) - set_target_properties( - ${EX_NAME} - PROPERTIES - LINK_FLAGS - "--preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets --use-preload-plugins" - ) - # Run of the mill executable - else(EMSCRIPTEN) - if(MINGW) - target_link_libraries(${EX_NAME} -lmingw32) - endif(MINGW) - target_link_libraries( - ${EX_NAME} - -lm - ${SDL_MAIN_LIBRARY} - ${SDL_LIBRARY} - ${SDL_MIXER_LIBRARY} - ${SDL_IMAGE_LIBRARY} - ${SDL_TTF_LIBRARY} - ${SDL_GFX_LIBRARY} - afk + set(EXTRA_LIBRARIES + "--use-preload-plugins \ + --preload-file ${CMAKE_CURRENT_LIST_DIR}/assets@/assets \ + -s DISABLE_EXCEPTION_CATCHING=0 \ + -s DEMANGLE_SUPPORT=1 \ + -s SDL2_IMAGE_FORMATS=[\"png\"]" ) endif(EMSCRIPTEN) + + # Link libraries + if(MINGW) + target_link_libraries(${EX_NAME} PRIVATE -lmingw32) + endif(MINGW) + + target_link_libraries(${EX_NAME} PRIVATE ${EXTRA_LIBRARIES} afk) endforeach() # Export assets -file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/bin/assets/) +file(COPY ${CMAKE_CURRENT_LIST_DIR}/assets/ DESTINATION ${CMAKE_BINARY_DIR}/examples/assets/) + \ No newline at end of file diff --git a/examples/ex_collision.cpp b/examples/ex_collision.cpp deleted file mode 100644 index e85e7e6..0000000 --- a/examples/ex_collision.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file ex_sprite.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "../include/Game.h" -#include "../include/entities/Sprite.h" -#include "../include/entities/ui/Label.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(512, 512); - display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_collision"); - - assets.loadImage("lenna", "assets/lenna.png"); - assets.loadFont("freesans", "assets/freesans.ttf", 12); - - auto& lenna_1 = add(*this, "lenna"); - lenna_1.setPosition(10, 10); - lenna_1.setSize(40, 40); - lenna_1_id = lenna_1.id; - - auto& lenna_2 = add(*this, "lenna"); - lenna_2.setPosition(10, 80); - lenna_2.setSize(40, 40); - lenna_2_id = lenna_2.id; - - auto& label = add(*this, 0, 0); - label.setFont("freesans"); - label_id = label.id; - } - - void update(Uint32 delta) { - auto& label = get(label_id); - auto& lenna_1 = get(lenna_1_id); - auto& lenna_2 = get(lenna_2_id); - - if (input.mouseDown(afk::MouseButtons::LEFT)) { - lenna_1.setPosition(input.mouseX(), input.mouseY()); - } - - if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna_2.setPosition(input.mouseX(), input.mouseY()); - } - - if (lenna_1.isColliding(lenna_2)) { - label.setText("Colliding!"); - } else { - label.setText("Not colliding"); - } - } - - void stop() { logger.log("Stopping!"); } - - private: - ObjId lenna_1_id; - ObjId lenna_2_id; - ObjId label_id; -}; - -int main(int argv, char** args) { - afk::Game game = afk::Game(); - - afk::SceneService& scenes = afk::Services::getSceneService(); - scenes.addScene("demo"); - scenes.setNextScene("demo"); - - game.start(); - return 0; -} diff --git a/examples/ex_fps.cpp b/examples/ex_fps.cpp deleted file mode 100644 index e43247b..0000000 --- a/examples/ex_fps.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @file ex_fps.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ - -#include "../include/Game.h" -#include "../include/entities/Sprite.h" -#include "../include/entities/ui/Label.h" -#include "../include/random/RandomGenerator.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -const int NUM_SPRITE = 100; -const int SCREEN_H = 400; -const int SCREEN_H_2 = 200; -const int SCREEN_W = 400; -const int SPRITE_SIZE = 20; - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(SCREEN_W, SCREEN_H); - display.setBufferSize(SCREEN_W, SCREEN_H); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_fps"); - - assets.loadFont("freesans", "assets/freesans.ttf", 64); - assets.loadImage("lenna", "assets/lenna.png"); - - afk::Label& label = add(*this, 10, 5, 100); - label.setText("FPS"); - label.setFont("freesans"); - label_id = label.id; - - for (unsigned int i = 0; i < NUM_SPRITE; i++) { - afk::Sprite& sprite = add(*this, "lenna"); - sprite.setSize(SPRITE_SIZE, SPRITE_SIZE); - sprites[i] = sprite.id; - } - } - - void update(Uint32 delta) { - Scene::update(delta); - - iter += static_cast(delta) / 10.0f; - - int fps = display.getFps(); - - get(label_id).setText(std::to_string(fps)); - - for (unsigned int i = 0; i < NUM_SPRITE; i++) { - afk::Sprite& sprite = get(sprites[i]); - sprite.setPosition(fmod(iter + i, SCREEN_W), - sin(iter / 100.0f + i) * SCREEN_H_2 + SCREEN_H_2); - sprite.setAngle(sprite.getAngle() + delta / 10.0f); - } - } - - void stop() { logger.log("Stopping!"); } - - private: - ObjId label_id = -1; - ObjId sprites[NUM_SPRITE]; - - float iter = 0; -}; - -int main(int argv, char** args) { - afk::Game game = afk::Game(); - - afk::SceneService& scenes = afk::Services::getSceneService(); - scenes.addScene("demo"); - scenes.setNextScene("demo"); - - game.start(); - return 0; -} diff --git a/examples/ex_keyboard.cpp b/examples/ex_keyboard.cpp deleted file mode 100644 index 7d2298d..0000000 --- a/examples/ex_keyboard.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @file ex_keyboard.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "../include/Game.h" -#include "../include/entities/Sprite.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -class Character : public afk::Sprite { - public: - Character(afk::Scene& scene, const float x, const float y) - : Sprite(scene, x, y) { - setTexture("lenna"); - setSize(30, 30); - } - - void update(Uint32 delta) { - Sprite::update(delta); - - float speed = delta / 10.0f; - if (scene.input.keyDown(afk::Keys::UP)) { - setPosition(x, y - speed); - } - if (scene.input.keyDown(afk::Keys::DOWN)) { - setPosition(x, y + speed); - } - if (scene.input.keyDown(afk::Keys::LEFT)) { - setPosition(x - speed, y); - } - if (scene.input.keyDown(afk::Keys::RIGHT)) { - setPosition(x + speed, y); - } - } -}; - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(512, 512); - display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_keyboard"); - - assets.loadImage("lenna", "assets/lenna.png"); - - add(*this, 100, 100); - } - - void stop() { logger.log("Stopping!"); } -}; - -class MainGame : public afk::Game { - public: - MainGame() : Game() { - afk::SceneService& scene = afk::Services::getSceneService(); - scene.addScene("demo"); - scene.setNextScene("demo"); - - start(); - } -}; - -int main(int argv, char** args) { - MainGame game = MainGame(); - - return 0; -} diff --git a/examples/ex_message_box.cpp b/examples/ex_message_box.cpp deleted file mode 100644 index f947353..0000000 --- a/examples/ex_message_box.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @file ex_message_box.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "../include/Game.h" -#include "../include/entities/ui/Button.h" -#include "../include/entities/ui/MessageBox.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(256, 256); - display.setBufferSize(256, 256); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_message_box"); - - assets.loadFont("freesans", "assets/freesans.ttf", 12); - - afk::Button& button1 = add(*this, 10, 10, 10); - button1.setFont("freesans"); - button1.setText("Question Message"); - button1.sizeToText(); - button1.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Info"); - message_box.setText("Text"); - message_box.show(); - }); - - afk::Button& button2 = add(*this, 10, 50, 10); - button2.setFont("freesans"); - button2.setText("Warning Message"); - button2.sizeToText(); - button2.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::WARN); - message_box.setTitle("Warning"); - message_box.setText("Text"); - message_box.show(); - }); - - afk::Button& button3 = add(*this, 10, 90, 10); - button3.setFont("freesans"); - button3.setText("Error Message"); - button3.sizeToText(); - button3.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::ERROR); - message_box.setTitle("Error"); - message_box.setText("Text"); - message_box.show(); - }); - } - - void stop() { logger.log("Stopping!"); } -}; - -class MainGame : public afk::Game { - public: - MainGame() : Game() { - afk::SceneService& scene = afk::Services::getSceneService(); - scene.addScene("demo"); - scene.setNextScene("demo"); - start(); - } -}; - -int main(int argv, char** args) { - MainGame game = MainGame(); - - return 0; -} diff --git a/examples/ex_mouse.cpp b/examples/ex_mouse.cpp deleted file mode 100644 index 478aac1..0000000 --- a/examples/ex_mouse.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file ex_mouse.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "../include/Game.h" -#include "../include/entities/Sprite.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(512, 512); - display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_mouse"); - - assets.loadImage("lenna", "assets/lenna.png"); - - afk::Sprite& lenna = add(*this, "lenna"); - - lenna.setSize(30, 30); - lenna.setPosition(100, 100); - lennaId = lenna.id; - } - - void update(Uint32 delta) { - Scene::update(delta); - - afk::Sprite& lenna = get(lennaId); - - if (input.mousePressed(afk::MouseButtons::LEFT)) { - lenna.setPosition(input.mouseX(), input.mouseY()); - } - if (input.mouseDown(afk::MouseButtons::RIGHT)) { - lenna.setSize(input.mouseX(), input.mouseY()); - } - } - - void stop() { logger.log("Stopping!"); } - - private: - ObjId lennaId; -}; - -int main(int argv, char** args) { - afk::Game game = afk::Game(); - - afk::SceneService& scenes = afk::Services::getSceneService(); - scenes.addScene("demo"); - scenes.setNextScene("demo"); - - game.start(); - return 0; -} diff --git a/examples/ex_particles.cpp b/examples/ex_particles.cpp deleted file mode 100644 index 3d666ce..0000000 --- a/examples/ex_particles.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @file ex_particles.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "../include/Game.h" -#include "../include/color/Color.h" -#include "../include/entities/ParticleEmitter.h" -#include "../include/random/RandomGenerator.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(512, 512); - display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_particles"); - display.setBackgroundColor(afk::color::black); - - assets.loadImage("fuzzball", "assets/fuzzball.png"); - - afk::ParticleEmitter& emitter = add(*this, 256, 256); - emitter.setSize(30, 30); - - for (int i = 0; i < 100; i++) { - afk::Particle particle(*this, 0, 0, 0, afk::ParticleType::SQUARE); - particle.setLifespan(afk::Random::randomInt(100, 1000)); - particle.setSize(10.0f, 3.0f); - particle.setColor(afk::color::rgb(128, 22, 22), - afk::color::rgb(100, 100, 100)); - particle.setVelocity(afk::Random::randomFloat(-5.0f, 5.0f), - afk::Random::randomFloat(-1.0f, -2.0f)); - particle.setAcceleration(0, 0.2f); - emitter.addParticle(particle); - } - - afk::ParticleEmitter& emitter_2 = - add(*this, 128, 256); - emitter_2.setSize(1, 1); - - for (int i = 0; i < 100; i++) { - afk::Particle particle(*this, 0, 0, 0, afk::ParticleType::CIRCLE); - particle.setLifespan(afk::Random::randomInt(100, 200)); - particle.setSize(3.0f, 2.0f); - particle.setColor(afk::color::blue, afk::color::white); - particle.setVelocity(afk::Random::randomFloat(-5, 5), -100); - particle.setAcceleration(0, 3.0f); - emitter_2.addParticle(particle); - } - - afk::ParticleEmitter& emitter_3 = - add(*this, 384, 256); - emitter_3.setSize(5, 5); - smoke_id = emitter_3.id; - - for (int i = 0; i < 400; i++) { - afk::Particle particle(*this, 0, 0, 0, afk::ParticleType::IMAGE); - particle.setLifespan(afk::Random::randomInt(800, 1500)); - particle.setTexture("fuzzball"); - particle.setSize(16.0f, 20.0f); - particle.setVelocity(afk::Random::randomFloat(2.0f, 2.5f), -5.0f); - emitter_3.addParticle(particle); - } - } - - void update(Uint32 delta) { - Scene::update(delta); - - get(smoke_id).setPosition(input.mouseX(), - input.mouseY()); - } - - void stop() { logger.log("Stopping!"); } - - private: - ObjId smoke_id; -}; - -int main(int argv, char** args) { - afk::Game game = afk::Game(); - - afk::SceneService& scenes = afk::Services::getSceneService(); - scenes.addScene("demo"); - scenes.setNextScene("demo"); - - game.start(); - return 0; -} diff --git a/examples/ex_rotate.cpp b/examples/ex_rotate.cpp deleted file mode 100644 index 0a813cf..0000000 --- a/examples/ex_rotate.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file ex_rotate.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "../include/Game.h" -#include "../include/entities/Sprite.h" -#include "../include/scene/Scene.h" -#include "../include/services/Services.h" - -class DemoScene : public afk::Scene { - public: - void start() { - logger.log("Starting!"); - - display.setWindowSize(512, 512); - display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); - display.setTitle("ex_sprite"); - - assets.loadImage("lenna", "assets/lenna.png"); - - afk::Sprite& lenna = add(*this, "lenna"); - lennaId = lenna.id; - } - - void update(Uint32 delta) { - Scene::update(delta); - - afk::Sprite& lenna = get(lennaId); - lenna.setAngle(lenna.getAngle() + delta / 10.0f); - } - - void stop() { logger.log("Stopping!"); } - - private: - ObjId lennaId; -}; - -int main(int argv, char** args) { - afk::Game game = afk::Game(); - - afk::SceneService& scenes = afk::Services::getSceneService(); - scenes.addScene("demo"); - scenes.setNextScene("demo"); - - game.start(); - - return 0; -} diff --git a/examples/src/ex_collision.cpp b/examples/src/ex_collision.cpp new file mode 100644 index 0000000..b396ff4 --- /dev/null +++ b/examples/src/ex_collision.cpp @@ -0,0 +1,90 @@ +/** + * @file ex_sprite.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#include "../include/Game.h" +#include "../include/components/components.h" +#include "../include/components/ui.h" +#include "../include/entities/Entity.h" +#include "../include/scene/Scene.h" + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_collision"); + + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); + assets.loadFont("freesans", "assets/freesans.ttf", 12); + + lennaEntity1 = createEntity(); + createComponent(lennaEntity1, afk::Vec3(10, 10, 0), + afk::Vec2(40, 40)); + createComponent(lennaEntity1, lennaTexture); + createComponent(lennaEntity1); + + lennaEntity2 = createEntity(); + createComponent(lennaEntity2, afk::Vec3(10, 80, 0), + afk::Vec2(40, 40)); + createComponent(lennaEntity2, lennaTexture); + createComponent(lennaEntity2); + + labelEntity = createEntity(); + createComponent(labelEntity, afk::Vec3(10, 5, 0)); + auto& label = createComponent(labelEntity); + label.font = "freesans"; + } + + void update(uint32_t delta) override { + auto& label = getComponent(labelEntity); + auto& lennaTransform1 = getComponent(lennaEntity1); + auto& lennaTransform2 = getComponent(lennaEntity2); + + if (input.mouseDown(afk::MouseButtons::Left)) { + lennaTransform1.position.x = input.mouseX(); + lennaTransform1.position.y = input.mouseY(); + } + + if (input.mouseDown(afk::MouseButtons::Right)) { + lennaTransform2.position.x = input.mouseX(); + lennaTransform2.position.y = input.mouseY(); + } + + auto& collider = getComponent(lennaEntity1); + if (collider.colliding) { + label.text = "Colliding!"; + } else { + label.text = "Not colliding"; + } + + Scene::update(delta); + } + + void stop() override { logger.log("Stopping!"); } + + private: + afk::Entity lennaEntity1; + afk::Entity lennaEntity2; + afk::Entity labelEntity; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + return 0; +} diff --git a/examples/ex_display.cpp b/examples/src/ex_display.cpp similarity index 81% rename from examples/ex_display.cpp rename to examples/src/ex_display.cpp index bf9d180..79120be 100644 --- a/examples/ex_display.cpp +++ b/examples/src/ex_display.cpp @@ -10,20 +10,19 @@ */ #include "../include/Game.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(100, 100); display.setBufferSize(100, 100); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_display"); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/examples/src/ex_fps.cpp b/examples/src/ex_fps.cpp new file mode 100644 index 0000000..a5aa457 --- /dev/null +++ b/examples/src/ex_fps.cpp @@ -0,0 +1,89 @@ +/** + * @file ex_fps.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ + +#include "../include/Game.h" +#include "../include/common/random.h" +#include "../include/components/components.h" +#include "../include/components/ui.h" +#include "../include/entities/Entity.h" +#include "../include/scene/Scene.h" + +const int NUM_SPRITE = 100; +const int SCREEN_H = 400; +const int SCREEN_H_2 = 200; +const int SCREEN_W = 400; +const int SPRITE_SIZE = 20; + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(SCREEN_W, SCREEN_H); + display.setBufferSize(SCREEN_W, SCREEN_H); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_fps"); + + assets.loadFont("freesans", "assets/freesans.ttf", 64); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); + + labelEntity = createEntity(); + createComponent(labelEntity, afk::Vec3(10, 5, 0)); + auto& label = createComponent(labelEntity); + label.font = "freesans"; + + for (auto& sprite : sprites) { + auto entity = createEntity(); + createComponent(entity, lennaTexture); + auto& transform = createComponent(entity); + transform.size.x = SPRITE_SIZE; + transform.size.y = SPRITE_SIZE; + sprite = entity; + } + } + + void update(uint32_t delta) override { + Scene::update(delta); + + iter += static_cast(delta) / 10.0f; + + int fps = display.getFps(); + + auto& label = getComponent(labelEntity); + label.text = std::to_string(fps); + + for (unsigned int i = 0; i < NUM_SPRITE; i++) { + auto& transform = getComponent(sprites[i]); + transform.position.x = fmod(iter + i, SCREEN_W); + transform.position.y = sin(iter / 100.0f + i) * SCREEN_H_2 + SCREEN_H_2; + transform.angle += delta / 10.0f; + } + } + + void stop() override { logger.log("Stopping!"); } + + private: + afk::Entity labelEntity; + afk::Entity sprites[NUM_SPRITE]; + + float iter = 0; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + return 0; +} diff --git a/examples/src/ex_keyboard.cpp b/examples/src/ex_keyboard.cpp new file mode 100644 index 0000000..ff2c667 --- /dev/null +++ b/examples/src/ex_keyboard.cpp @@ -0,0 +1,101 @@ +/** + * @file ex_keyboard.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#include "../include/Game.h" +#include "../include/components/components.h" +#include "../include/scene/Scene.h" + +void characterSystem(afk::Registry& registry, + afk::InputService& input, + uint32_t delta) { + auto view = registry.view(); + + for (auto [entity, transform] : view.each()) { + float speed = delta / 10.0f; + if (input.keyDown(afk::Keys::Up)) { + transform.position.y -= speed; + } + if (input.keyDown(afk::Keys::Down)) { + transform.position.y += speed; + } + if (input.keyDown(afk::Keys::Left)) { + transform.position.x -= speed; + } + if (input.keyDown(afk::Keys::Right)) { + transform.position.x += speed; + } + } +} + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_keyboard"); + + assets.loadImage("lenna", "assets/lenna.png"); + + createCharacter(); + } + + void createCharacter() { + afk::Entity id = createEntity(); + createComponent(id, afk::Vec3(100, 100, 0), + afk::Vec2(40, 40)); + + auto& lennaTexture = assets.getImage("lenna"); + createComponent(id, lennaTexture); + entityIds.push_back(id); + } + + void update(uint32_t delta) override { + Scene::update(delta); + + if (input.keyPressed(afk::Keys::A)) { + createCharacter(); + } + + if (input.keyPressed(afk::Keys::R)) { + if (entityIds.size() > 0) { + afk::Entity id = entityIds.back(); + destroyEntity(id); + entityIds.pop_back(); + } + } + + characterSystem(getRegistry(), input, delta); + } + + void stop() override { logger.log("Stopping!"); } + + private: + std::vector entityIds; +}; + +class MainGame : public afk::Game { + public: + MainGame() : Game() { + afk::SceneService& scene = afk::Services::getSceneService(); + scene.addScene("demo"); + scene.setNextScene("demo"); + + start(); + } +}; + +int main(int argv, char** args) { + MainGame game = MainGame(); + + return 0; +} diff --git a/examples/src/ex_message_box.cpp b/examples/src/ex_message_box.cpp new file mode 100644 index 0000000..7de673e --- /dev/null +++ b/examples/src/ex_message_box.cpp @@ -0,0 +1,88 @@ +/** + * @file ex_message_box.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#include "../include/Game.h" +#include "../include/components/ui.h" +#include "../include/scene/Scene.h" +#include "../include/ui/MessageBox.h" + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(256, 256); + display.setBufferSize(256, 256); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_message_box"); + + assets.loadFont("freesans", "assets/freesans.ttf", 12); + + auto buttonEntity1 = createEntity(); + createComponent(buttonEntity1, afk::Vec3(10, 10, 10), + afk::Vec2(160, 20)); + auto& button1 = createComponent(buttonEntity1); + button1.setFont("freesans"); + button1.setText("Question Message"); + // button1.sizeToText(); + button1.setOnClick([]() { + afk::MessageBox messageBox(afk::MessageBoxType::Info); + messageBox.setTitle("Info"); + messageBox.setText("Text"); + messageBox.show(); + }); + + auto buttonEntity2 = createEntity(); + createComponent(buttonEntity2, afk::Vec3(10, 50, 10), + afk::Vec2(160, 20)); + auto& button2 = createComponent(buttonEntity2); + button2.setFont("freesans"); + button2.setText("Warning Message"); + // button2.sizeToText(); + button2.setOnClick([]() { + afk::MessageBox messageBox(afk::MessageBoxType::Warn); + messageBox.setTitle("Warning"); + messageBox.setText("Text"); + messageBox.show(); + }); + + auto buttonEntity3 = createEntity(); + createComponent(buttonEntity3, afk::Vec3(10, 90, 10), + afk::Vec2(160, 20)); + auto& button3 = createComponent(buttonEntity3); + button3.setFont("freesans"); + button3.setText("Error Message"); + // button3.sizeToText(); + button3.setOnClick([]() { + afk::MessageBox messageBox(afk::MessageBoxType::Error); + messageBox.setTitle("Error"); + messageBox.setText("Text"); + messageBox.show(); + }); + } + + void stop() override { logger.log("Stopping!"); } +}; + +class MainGame : public afk::Game { + public: + MainGame() : Game() { + afk::SceneService& scene = afk::Services::getSceneService(); + scene.addScene("demo"); + scene.setNextScene("demo"); + start(); + } +}; + +int main(int argv, char** args) { + MainGame game = MainGame(); + + return 0; +} diff --git a/examples/src/ex_mouse.cpp b/examples/src/ex_mouse.cpp new file mode 100644 index 0000000..3f665c6 --- /dev/null +++ b/examples/src/ex_mouse.cpp @@ -0,0 +1,64 @@ +/** + * @file ex_mouse.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#include "../include/Game.h" +#include "../include/components/components.h" +#include "../include/entities/Entity.h" +#include "../include/scene/Scene.h" + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_mouse"); + + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); + + lennaEntity = createEntity(); + createComponent(lennaEntity, lennaTexture); + createComponent(lennaEntity, afk::Vec3(100, 100, 0), + afk::Vec2(30, 30)); + } + + void update(uint32_t delta) override { + Scene::update(delta); + + auto& transform = getComponent(lennaEntity); + + if (input.mouseDown(afk::MouseButtons::Left)) { + transform.position.x = input.mouseX(); + transform.position.y = input.mouseY(); + } + if (input.mouseDown(afk::MouseButtons::Right)) { + transform.size.x = input.mouseX(); + transform.size.y = input.mouseY(); + } + } + + void stop() override { logger.log("Stopping!"); } + + private: + afk::Entity lennaEntity; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + return 0; +} diff --git a/examples/src/ex_particles.cpp b/examples/src/ex_particles.cpp new file mode 100644 index 0000000..f12b23b --- /dev/null +++ b/examples/src/ex_particles.cpp @@ -0,0 +1,165 @@ +/** + * @file ex_particles.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#include "../include/Game.h" +#include "../include/common/Color.h" +#include "../include/common/Vec.h" +#include "../include/common/random.h" +#include "../include/components/components.h" +#include "../include/components/ui.h" +#include "../include/scene/Scene.h" + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_particles"); + display.setBackgroundColor(afk::color::black); + + assets.loadImage("fuzzball", "assets/fuzzball.png"); + assets.loadFont("freesans", "assets/freesans.ttf", 24); + + // Weird box thing + emitterEntity1 = createEntity(); + auto& emitter1 = + createComponent(emitterEntity1, 10.0f); + createComponent(emitterEntity1, afk::Vec3(256, 256, 0), + afk::Vec2(30, 30)); + + for (int i = 0; i < 100; i++) { + auto& [particle, physics] = emitter1.addPrefab(); + particle.type = afk::ParticleType::Square; + particle.lifespan = afk::random::randomInt(100, 1000); + particle.startSize = 10.0f, particle.endSize = 3.0f; + particle.startColor = afk::color::rgb(128, 22, 22); + particle.endColor = afk::color::rgb(100, 100, 100); + physics.velocity = {afk::random::randomFloat(-5.0f, 5.0f), + afk::random::randomFloat(-1.0f, -2.0f)}; + physics.acceleration = {0, 2.0f}; + } + + // Water + emitterEntity2 = createEntity(); + auto& emitter2 = + createComponent(emitterEntity2, 10.0f); + createComponent(emitterEntity2, afk::Vec3(64, 256, 0), + afk::Vec2(1, 1)); + + for (int i = 0; i < 100; i++) { + auto& [particle, physics] = emitter2.addPrefab(); + particle.type = afk::ParticleType::Circle; + particle.lifespan = afk::random::randomInt(1000, 2000); + particle.startSize = 3.0f; + particle.endSize = 2.0f; + particle.startColor = afk::color::blue; + particle.endColor = afk::color::white; + physics.velocity = {afk::random::randomFloat(-20.0, 20.0), + afk::random::randomFloat(-200.0f, -220.0f)}; + physics.acceleration = {0, 200.0f}; + } + + // Smoke + emitterEntity3 = createEntity(); + auto& emitter3 = + createComponent(emitterEntity3, 10.0f); + createComponent(emitterEntity3, afk::Vec3(0, 0, 0), + afk::Vec2(5, 5)); + + for (int i = 0; i < 400; i++) { + auto& [particle, physics] = emitter3.addPrefab(); + particle.type = afk::ParticleType::Image; + particle.lifespan = 3000; + particle.startSize = 24.0f; + particle.endSize = 48.0f; + particle.texture = "fuzzball"; + physics.velocity = {2.0f, -10.0f}; + physics.acceleration = {10.0f, 0}; + } + + emitterEntity4 = createEntity(); + auto& emitter4 = + createComponent(emitterEntity4, 10.0f); + createComponent(emitterEntity4, afk::Vec3(128, 256, 0), + afk::Vec2(1, 1)); + + // Sparks + for (int i = 0; i < 400; i++) { + auto& [particle, physics] = emitter4.addPrefab(); + particle.type = afk::ParticleType::Square; + particle.startColor = afk::color::rgba(128, 20, 20, 128); + particle.endColor = afk::color::rgba(200, 200, 200, 0); + particle.lifespan = afk::random::randomInt(400, 500); + particle.startSize = 3.0f; + particle.endSize = 1.0f; + physics.velocity = {afk::random::randomFloat(-40.0f, 40.0f), + afk::random::randomFloat(-40.0f, 40.0f)}; + physics.acceleration = {0, 200.0f}; + } + + // FPS label + fpsLabel = createEntity(); + createComponent(fpsLabel, afk::Vec3(10, 5, 0)); + auto& fpsLabelComponent = createComponent(fpsLabel); + fpsLabelComponent.font = "freesans"; + fpsLabelComponent.color = afk::color::white; + + countLabel = createEntity(); + createComponent(countLabel, afk::Vec3(10, 20, 0)); + auto& countLabelComponent = createComponent(countLabel); + countLabelComponent.font = "freesans"; + countLabelComponent.color = afk::color::white; + } + + void update(uint32_t delta) override { + Scene::update(delta); + + // Move smoke to mouse + auto& smoke_transform = getComponent(emitterEntity3); + smoke_transform.position.x = input.mouseX(); + smoke_transform.position.y = input.mouseY(); + + // Set fps label + int fps = display.getFps(); + auto& fpsLabelComponent = getComponent(fpsLabel); + fpsLabelComponent.text = "FPS: " + std::to_string(fps); + + // Set count label + int count = 0; + getRegistry().view().each([&count](auto&) { count++; }); + auto& countLabelComponent = getComponent(countLabel); + countLabelComponent.text = "Count: " + std::to_string(count); + } + + void stop() override { logger.log("Stopping!"); } + + private: + afk::Entity emitterEntity1; + afk::Entity emitterEntity2; + afk::Entity emitterEntity3; + afk::Entity emitterEntity4; + + afk::Entity fpsLabel; + afk::Entity countLabel; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + return 0; +} diff --git a/examples/src/ex_physics.cpp b/examples/src/ex_physics.cpp new file mode 100644 index 0000000..6354f5a --- /dev/null +++ b/examples/src/ex_physics.cpp @@ -0,0 +1,76 @@ +/** + * @file ex_physics.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief Demonstrates usage of physics component + * @version 0.1 + * @date 2022-04-20 + * + * @copyright Copyright (c) 2022 + * + */ +#include "../include/Game.h" +#include "../include/common/Vec.h" +#include "../include/components/components.h" +#include "../include/entities/Entity.h" +#include "../include/scene/Scene.h" + +void bounceSystem(afk::Registry& registry) { + auto view = registry.view(); + + for (auto [entity, transform, physics] : view.each()) { + if (transform.position.x > 512 - transform.size.x) { + physics.velocity.x *= -1; + } + if (transform.position.y > 512 - transform.size.y) { + physics.velocity.y *= -1; + } + if (transform.position.x < 0) { + physics.velocity.x *= -1; + } + if (transform.position.y < 0) { + physics.velocity.y *= -1; + } + } +} + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_physics"); + + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); + + lennaEntity = createEntity(); + createComponent(lennaEntity, lennaTexture); + createComponent(lennaEntity, afk::Vec3(0, 0, 0), + afk::Vec2(40, 40)); + createComponent(lennaEntity, afk::Vec2(100.0f, 400.0f)); + } + + void update(uint32_t delta) override { + Scene::update(delta); + bounceSystem(getRegistry()); + } + + void stop() override { logger.log("Stopping!"); } + + private: + afk::Entity lennaEntity; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + + return 0; +} diff --git a/examples/src/ex_rotate.cpp b/examples/src/ex_rotate.cpp new file mode 100644 index 0000000..f40670b --- /dev/null +++ b/examples/src/ex_rotate.cpp @@ -0,0 +1,58 @@ +/** + * @file ex_rotate.cpp + * @author Allan Legemaate (alegemaate@gmail.com) + * @brief + * @version 0.1 + * @date 2021-03-08 + * + * @copyright Copyright (c) 2021 + * + */ +#include "../include/Game.h" +#include "../include/common/Vec.h" +#include "../include/components/components.h" +#include "../include/entities/Entity.h" +#include "../include/scene/Scene.h" + +class DemoScene : public afk::Scene { + public: + void start() override { + logger.log("Starting!"); + + display.setWindowSize(512, 512); + display.setBufferSize(512, 512); + display.setMode(afk::DisplayMode::Windowed); + display.setTitle("ex_sprite"); + + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); + + lennaEntity = createEntity(); + createComponent(lennaEntity, lennaTexture); + createComponent(lennaEntity, afk::Vec3(156, 156, 0), + afk::Vec2(200, 200)); + } + + void update(uint32_t delta) override { + Scene::update(delta); + + auto& transform = getComponent(lennaEntity); + transform.angle += delta / 10.0f; + } + + void stop() override { logger.log("Stopping!"); } + + private: + afk::Entity lennaEntity; +}; + +int main(int argv, char** args) { + afk::Game game = afk::Game(); + + afk::SceneService& scenes = afk::Services::getSceneService(); + scenes.addScene("demo"); + scenes.setNextScene("demo"); + + game.start(); + + return 0; +} diff --git a/examples/ex_sound.cpp b/examples/src/ex_sound.cpp similarity index 74% rename from examples/ex_sound.cpp rename to examples/src/ex_sound.cpp index e8c5884..2e04182 100644 --- a/examples/ex_sound.cpp +++ b/examples/src/ex_sound.cpp @@ -9,30 +9,28 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_mouse"); assets.loadAudio("win", "assets/win.wav"); } - void update(Uint32 delta) { + void update(uint32_t delta) override { Scene::update(delta); - if (input.mousePressed(afk::MouseButtons::LEFT)) { + if (input.mousePressed(afk::MouseButtons::Left)) { audio.playSound("win", 1.0f, 0.0f, 1.0f, false); } } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/examples/ex_sprite.cpp b/examples/src/ex_sprite.cpp similarity index 57% rename from examples/ex_sprite.cpp rename to examples/src/ex_sprite.cpp index f8c3299..9762186 100644 --- a/examples/ex_sprite.cpp +++ b/examples/src/ex_sprite.cpp @@ -9,26 +9,29 @@ * */ #include "../include/Game.h" -#include "../include/entities/Sprite.h" +#include "../include/common/Vec.h" +#include "../include/components/components.h" #include "../include/scene/Scene.h" -#include "../include/services/Services.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); display.setBufferSize(512, 512); - display.setMode(afk::DisplayMode::WINDOWED); + display.setMode(afk::DisplayMode::Windowed); display.setTitle("ex_sprite"); - assets.loadImage("lenna", "assets/lenna.png"); + auto& lennaTexture = assets.loadImage("lenna", "assets/lenna.png"); - add(*this, "lenna"); + auto sprite = createEntity(); + createComponent(sprite, lennaTexture); + createComponent(sprite, afk::Vec3(0, 0, 0), + afk::Vec2(50, 50)); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/examples/ex_ui.cpp b/examples/src/ex_ui.cpp similarity index 63% rename from examples/ex_ui.cpp rename to examples/src/ex_ui.cpp index 8b33d07..b4c4139 100644 --- a/examples/ex_ui.cpp +++ b/examples/src/ex_ui.cpp @@ -9,18 +9,18 @@ * */ #include "../include/Game.h" -#include "../include/entities/ui/Button.h" -#include "../include/entities/ui/Checkbox.h" -#include "../include/entities/ui/Image.h" -#include "../include/entities/ui/Inputbox.h" -#include "../include/entities/ui/Label.h" -#include "../include/entities/ui/MessageBox.h" #include "../include/scene/Scene.h" #include "../include/services/Services.h" +#include "../include/ui/Button.h" +#include "../include/ui/Checkbox.h" +#include "../include/ui/Image.h" +#include "../include/ui/Inputbox.h" +#include "../include/ui/Label.h" +#include "../include/ui/MessageBox.h" class DemoScene : public afk::Scene { public: - void start() { + void start() override { logger.log("Starting!"); display.setWindowSize(512, 512); @@ -36,24 +36,24 @@ class DemoScene : public afk::Scene { button.setFont("freesans"); button.sizeToText(); button.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Nice"); - message_box.setText("You Clicked\nThe button"); - message_box.show(); + afk::MessageBox messsageBox(afk::MessageBoxType::INFO); + messsageBox.setTitle("Nice"); + messsageBox.setText("You Clicked\nThe button"); + messsageBox.show(); }); afk::Checkbox& checkbox = add(*this, 10, 40); checkbox.setText("CHECK ME"); checkbox.setFont("freesans"); checkbox.setOnCheck([](const bool checked) { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Nice"); + afk::MessageBox messsageBox(afk::MessageBoxType::INFO); + messsageBox.setTitle("Nice"); if (checked) { - message_box.setText("The checkbox is checked"); + messsageBox.setText("The checkbox is checked"); } else { - message_box.setText("The checkbox is unchecked"); + messsageBox.setText("The checkbox is unchecked"); } - message_box.show(); + messsageBox.show(); }); afk::Label& label = add(*this, 10, 70); @@ -66,16 +66,17 @@ class DemoScene : public afk::Scene { afk::Image& image = add(*this, 10, 120); image.setTexture("lenna"); - image.setSize(20, 20); + image.transform.size.x = 20; + image.transform.size.y = 20; image.setOnClick([]() { - afk::MessageBox message_box(afk::MessageBoxType::INFO); - message_box.setTitle("Nice"); - message_box.setText("Clicked the image"); - message_box.show(); + afk::MessageBox messsageBox(afk::MessageBoxType::INFO); + messsageBox.setTitle("Nice"); + messsageBox.setText("Clicked the image"); + messsageBox.show(); }); } - void stop() { logger.log("Stopping!"); } + void stop() override { logger.log("Stopping!"); } }; int main(int argv, char** args) { diff --git a/include/entities/GameObject.h b/include/entities/GameObject.h deleted file mode 100644 index 066b2c1..0000000 --- a/include/entities/GameObject.h +++ /dev/null @@ -1,290 +0,0 @@ -/** - * @file GameObject.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief A general purpose game object, generally absctracted in sub classes. - * @see Sprite - * @see Button - * @version 0.1 - * @date 2017-01-03 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_GAMEOBJECT_H_ -#define INCLUDE_ENTITIES_GAMEOBJECT_H_ - -#include -#include -#include - -/// Unique id type alias -using ObjId = Uint32; - -namespace afk { - -// Forward declare scene class -class Scene; - -/** - * @brief A collidable object! Parent class for many others - * - */ -class GameObject { - public: - /** - * @brief Construct a new GameObject - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - explicit GameObject(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Destroy the GameObject - * - */ - virtual ~GameObject(); - - /** - * @brief Update loop to be overriden by derived classes. Automatically called - * by Scene. - * - * @param delta Time since last call in ms - */ - virtual void update(Uint32 delta); - - /** - * @brief Internal game object management - * - */ - void updateInternal(); - - /** - * @brief Draw loop to be overriden by derived classes. Automatically called - * by Scene. - * - * Do not add other game objects in the draw loop! This will cause undefined - * behaviour. - * - */ - virtual void draw(); - - /** - * @brief Set gameobject parent - * - * @param parent_id - */ - void setParent(const ObjId parent_id); - - /** - * @brief Add a collider with a game object - * - */ - void addCollider(const ObjId obj_id); - - /** - * @brief Remove a collider with a game object - * - */ - void removeCollider(const ObjId obj_id); - - /** - * @brief Checks collision between this game object and another. - * - * @param other Some other game object - * @return True on collision, else false - */ - bool isColliding(const GameObject& other); - - /** - * @brief Checks collision between this game object and another. - * Calls on collide on both objects if there is a collision - * - * @param other Some other game object - * @return True on collision, else false - */ - bool collide(GameObject& other); - - /** - * @brief Callback which is triggered on collision with another game object if - * registered with the Scene. - * - * @param other The game object which is being collided with. - */ - virtual void onCollide(GameObject& other); - - /** - * @brief Set the size of game object in pixels - * - */ - void setSize(const unsigned int width, const unsigned int height); - - /** - * @brief Set the position of game object in pixels - * - */ - void setPosition(const float x, const float y); - - /** - * @brief Set angle of game object in degrees - * - */ - void setAngle(const float angle); - - /** - * @brief Set the visibility of the GameObject. Will not draw when not - * visible. - * - * @param visible Visibility to set to - */ - void setVisible(const bool visible); - - /** - * @brief Set the enabled of the GameObject. Will not update when not enabled. - * - * @param enabled Enabled to set to - */ - void setEnabled(const bool enabled); - - /** - * @brief Set hooked state. This removes the GameObject from the draw and - * update loop as well as its children. - * - * @param hooked Enabled to set to - */ - void setHooked(const bool hooked); - - /** - * @brief Get the width of the game object - * - * @return Width of game object - */ - int getWidth() const; - - /** - * @brief Get the height of the game object - * - * @return Height of game object - */ - int getHeight() const; - - /** - * @brief Get x position of game object - * - * @return X position - */ - float getX() const; - - /** - * @brief Get y position of game object - * - * @return Y position - */ - float getY() const; - - /** - * @brief Get z position of game object. Used for z sorting - * - * @return Z position - */ - int getZ() const; - - /** - * @brief Get the angle of the game object. - * - * @return Angle - */ - float getAngle() const; - - /** - * @brief Get the visibility of game object - * - * @return true If visible - * @return false If not visible - */ - bool getVisible() const; - - /** - * @brief Check if enabled - * - * @return true If enabled - * @return false If not enabled - */ - bool getEnabled() const; - - /** - * @brief Check if enabled - * - * @return true If enabled - * @return false If not enabled - */ - bool getHooked() const; - - /** - * @brief Definition for < operator. Less than if z is less than the other - * game object. - * - * @param obj Other game object - * @return True if the z of this game object is less than the other - */ - bool operator<(const GameObject& obj) const { return (z < obj.getZ()); } - - /// Autoassigned unique id - const ObjId id; - - protected: - /// Reference to registered scene - Scene& scene; - - /// X position on x y plane - float x; - - /// Y position on x y plane - float y; - - /// Z position, used for sorting - int z; - - /// Height in pixels of game object - int height; - - /// Width in pixels of game object - int width; - - /// Rotation - float angle; - - /// Visibility - bool visible; - - /// Enabled - bool enabled; - - /// Hooked - bool hooked; - - /// Delta x - float last_x; - - /// Delta y - float last_y; - - private: - /// Parent Id - ObjId parent_id; - - /// Static id counter - static ObjId index; - - /// Colliders - std::vector colliders; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_GAMEOBJECT_H_ diff --git a/include/entities/Particle.h b/include/entities/Particle.h deleted file mode 100644 index 8571159..0000000 --- a/include/entities/Particle.h +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @file Particle.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Just little blips that make things look cool - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_PARTICLE_H_ -#define INCLUDE_ENTITIES_PARTICLE_H_ - -#include "../entities/Sprite.h" -#include "../primitives/Primitives.h" - -namespace afk { - -/** - * @brief Possible types of particles - * - */ -enum class ParticleType : int { - PIXEL, - SQUARE, - CIRCLE, - IMAGE, - NONE, -}; - -/** - * @brief Represents a single Particle - * - */ -class Particle : public Sprite { - public: - /** - * @brief Create a new particle - * - * @param x X position - * @param y Y position - * @param type Type of particle - */ - explicit Particle(Scene& scene, - float x = 0.0f, - float y = 0.0f, - float z = 0, - ParticleType type = ParticleType::PIXEL); - - /** - * @brief Update particle - * - * @param delta Time since last call in ms - * - */ - void update(Uint32 delta) override; - - /** - * @brief Draw particle - * - */ - void draw() override; - - /** - * @brief Set the size of the particle in pixels - * - * @param size Size of particle - */ - void setSize(const float size); - - /** - * @brief Set the size of particle over lifespan - * - * @param start_size Size to start at - * @param end_size Size to end at - */ - void setSize(const float start_size, const float end_size); - - /** - * @brief Set the velocity of particle - * - * @param x X velocity in pixels per second - * @param y Y velocity in pixels per second - */ - void setVelocity(const float x, const float y); - - /** - * @brief Set the acceleration of particle - * - * @param x X acceleration in pixels per second - * @param y Y acceleration in pixels per second - */ - void setAcceleration(const float x, const float y); - - /** - * @brief Set the lifespan of particle in ms - * - * @param lifespan Number of ms to stay alive - */ - void setLifespan(const float lifespan); - - /** - * @brief Set the particle color - * - * @param color Color to set to - */ - void setColor(const color::Color& color); - - /** - * @brief Set the particle color over lifespan - * - * @param start_color Starting color - * @param end_color Ending color - */ - void setColor(const color::Color& start_color, const color::Color& end_color); - - /** - * @brief Reset age - * - */ - void reset(); - - /** - * @brief Check if dead - * - */ - bool dead(); - - private: - /// Type of particle - ParticleType type; - - /// Starting size - float start_size; - - /// Ending size - float end_size; - - /// Velocity x - float velocity_x; - - /// Velocity y - float velocity_y; - - /// Acceleration x - float acceleration_x; - - /// Acceleration y - float acceleration_y; - - /// Current age - float age; - - /// Max lifespan - float lifespan; - - /// Start color - color::Color start_color; - - /// End color - color::Color end_color; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_PARTICLE_H_ - -/** - * @example ex_particles.cpp - * This is an example of how to use the ParticleEmitter class to create particle - * effects. - */ diff --git a/include/entities/ParticleEmitter.h b/include/entities/ParticleEmitter.h deleted file mode 100644 index 8f0bc22..0000000 --- a/include/entities/ParticleEmitter.h +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file ParticleEmitter.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief A particle emitter. Can be fed a particle to emit - * and configured. - * @version 0.1 - * @date 2021-03-06 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_PARTICLEEMITTER_H_ -#define INCLUDE_ENTITIES_PARTICLEEMITTER_H_ - -#include - -#include "GameObject.h" -#include "Particle.h" - -namespace afk { - -/** - * @brief Particle Emitter - * - */ -class ParticleEmitter : public GameObject { - public: - /** - * @brief Construct a new ParticleEmitter object - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - * @param frequency Frequency in ms to emit, 0 is burst - */ - explicit ParticleEmitter(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0, - const int frequency = 0); - - /** - * @brief Destroy the ParticleEmitter object - * - */ - virtual ~ParticleEmitter() {} - - /** - * @brief Hook into draw loop - * - */ - void draw() override; - - /** - * @brief Hook into update loop - * - * @param delta Time since last call in ms - * - */ - void update(Uint32 delta) override; - - /** - * @brief Add particles to system - * - * @param particle Particle to add - * @param count Number of particles to push back, defaults to 1 - */ - void addParticle(const Particle& particle, const Uint32 count = 1); - - /** - * @brief Disable more particles from being emitted - * - */ - void enable(); - - /** - * @brief Enable particle emitting - * - */ - void disable(); - - protected: - /// Particles - std::vector particles; - - /// Emitting state - bool emitting; - - /// Frequency to emit in ms - int frequency; - - /// Current tick - int current_tick; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_PARTICLEEMITTER_H_ - -/** - * @example ex_particles.cpp - * This is an example of how to use the ParticleEmitter class to create particle - * effects. - */ diff --git a/include/entities/Sprite.h b/include/entities/Sprite.h deleted file mode 100644 index 282b510..0000000 --- a/include/entities/Sprite.h +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @file Sprite.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Simple textured GameObject - * @version 0.1 - * @date 2020-10-20 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_SPRITE_H_ -#define INCLUDE_ENTITIES_SPRITE_H_ - -#include - -#include "../assets/Texture.h" -#include "GameObject.h" - -namespace afk { - -/** - * @brief A simple texturable game object - * - */ -class Sprite : public GameObject { - public: - /** - * @brief Construct a new Sprite object - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - explicit Sprite(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Construct a new Sprite object - * - * @param scene Reference to scene which is stored in game object - * @param texture Id of texture to assign to sprite - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - Sprite(Scene& scene, - const std::string& texture, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Destroy the Sprite object - * - */ - virtual ~Sprite(); - - /** - * @brief Hook into draw loop - * - */ - void draw() override; - - /** - * @brief Set the Texture of the sprite - * - * @param texture Id of texture to assign - */ - void setTexture(const std::string& texture); - - protected: - /// Texture of Sprite - Texture texture; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_SPRITE_H_ - -/** - * @example ex_sprite.cpp - * This example shows basic usage of a sprite - */ - -/** - * @example ex_fps.cpp - * This example shows a stress test of sprites - */ diff --git a/include/entities/ui/Button.h b/include/entities/ui/Button.h deleted file mode 100644 index a929a4b..0000000 --- a/include/entities/ui/Button.h +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @file Button.h - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief A ui elemenent that accepts a click callback. - * @version 0.1 - * @date 2017-04-11 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_BUTTON_H_ -#define INCLUDE_ENTITIES_UI_BUTTON_H_ - -#include "UIElement.h" - -#include - -#include "../../assets/Texture.h" - -namespace afk { - -/** - * @brief Implementation of clickable UI Button - * - */ -class Button : public UIElement { - public: - /** - * @brief Construct a new Button object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Button(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the button to the screen. - * - */ - void draw() override; - - /** - * @brief Helper to size button to text - * - */ - void sizeToText(); -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_BUTTON_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Checkbox.h b/include/entities/ui/Checkbox.h deleted file mode 100644 index 3bf8b41..0000000 --- a/include/entities/ui/Checkbox.h +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @file Checkbox.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief UI Checkbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_CHECKBOX_H_ -#define INCLUDE_ENTITIES_UI_CHECKBOX_H_ - -#include "UIElement.h" - -#include - -namespace afk { - -/** - * @brief Implementation of clickable UI Button - * - */ -class Checkbox : public UIElement { - public: - /** - * @brief Construct a new Checkbox object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Checkbox(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the checkbox to the screen. - * - */ - void draw() override; - - /** - * @brief Check if checkbox checked - * - */ - bool getChecked() const; - - /** - * @brief Set checked state - * - */ - void setChecked(const bool checked); - - /** - * @brief Set the onCheck function which will be called when element is - * check - * - * @param func function to assign to onCheck - */ - void setOnCheck(std::function func); - - protected: - /// Intercept on click - void handleOnClick() override; - - private: - /// Checked state - bool checked; - - /// On check callback - std::function onCheck; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_CHECKBOX_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Image.h b/include/entities/ui/Image.h deleted file mode 100644 index ca56e18..0000000 --- a/include/entities/ui/Image.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file Image.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief UI Image - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_IMAGE_H_ -#define INCLUDE_ENTITIES_UI_IMAGE_H_ - -#include - -#include "../../assets/Texture.h" -#include "UIElement.h" - -namespace afk { - -/** - * @brief A simple texturable game object - * - */ -class Image : public UIElement { - public: - /** - * @brief Construct a new Image object - * - * @param scene Reference to scene which is stored in game object - * @param x X position - * @param y Y position - * @param z Z position (for sorting) - */ - explicit Image(Scene& scene, - const float x = 0.0f, - const float y = 0.0f, - const int z = 0); - - /** - * @brief Hook into draw loop - * - */ - void draw() override; - - /** - * @brief Set the Texture of the sprite - * - * @param texture Id of texture to assign - */ - void setTexture(const std::string& texture); - - protected: - /// Texture of Image - Texture texture; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_IMAGE_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Inputbox.h b/include/entities/ui/Inputbox.h deleted file mode 100644 index 0895c0f..0000000 --- a/include/entities/ui/Inputbox.h +++ /dev/null @@ -1,81 +0,0 @@ -/** - * @file Inputbox.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief UI Inputbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_INPUTBOX_H_ -#define INCLUDE_ENTITIES_UI_INPUTBOX_H_ - -#include "UIElement.h" - -#include - -namespace afk { - -/** - * @brief Implementation of clickable UI Button - * - */ -class Inputbox : public UIElement { - public: - /** - * @brief Construct a new Inputbox object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Inputbox(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the inputbox to the screen. - * - */ - void draw() override; - - /** - * @brief Update loop override - * - */ - void update(Uint32 delta) override; - - /** - * @brief Set the onChange function which will be called when element text - * changes - * - * @param func function to assign to onChange - */ - void setOnChange(std::function func); - - /** - * @brief Set the text of the input box - * - * @param text Text to insert - */ - void setText(const std::string& text) override; - - private: - /// Text iterator - std::string::iterator iter; - - /// On check callback - std::function onChange; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_INPUTBOX_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/Label.h b/include/entities/ui/Label.h deleted file mode 100644 index 4db00b8..0000000 --- a/include/entities/ui/Label.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file Label.h - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief UI Label that simply displays text. - * @version 0.1 - * @date 2018-11-25 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_LABEL_H_ -#define INCLUDE_ENTITIES_UI_LABEL_H_ - -#include "UIElement.h" - -#include -namespace afk { - -/** - * @brief Implementation of Label class - */ -class Label : public UIElement { - public: - /** - * @brief Construct a new Label object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - explicit Label(Scene& scene, - const float x = 0, - const float y = 0, - const int z = 0); - - /** - * @brief Draw the label to the screen. - * - */ - void draw() override; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_LABEL_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/entities/ui/UIElement.h b/include/entities/ui/UIElement.h deleted file mode 100644 index 8a1acac..0000000 --- a/include/entities/ui/UIElement.h +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @file UIElement.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Parent class of many other UIElement subclasses. Handles most things - * that all UIElements may need. - * @version 0.1 - * @date 2020-11-01 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_ENTITIES_UI_UIELEMENT_H_ -#define INCLUDE_ENTITIES_UI_UIELEMENT_H_ - -#include -#include - -#include "../../assets/Font.h" -#include "../GameObject.h" - -namespace afk { - -/** - * @brief Parent class for other UI elements such as buttons and labels. - * - */ -class UIElement : public GameObject { - public: - /** - * @brief Construct a new UIElement object - * - * @param scene Scene to add element to - * @param x X position of element - * @param y Y position of element - * @param z Z position of element (for sorting) - */ - UIElement(Scene& scene, const float x, const float y, const int z); - - /** - * @brief Draw the ui element to the screen. Can be overriden by other ui - * elements. - * - */ - void draw() override; - - /** - * @brief Update ui element. Checks for collisions and clicks. - * - * @param delta Time since last call in ms - * - */ - void update(Uint32 delta) override; - - /** - * @brief Set the font to use for displaying text - * - * @param font id of font to render text with - */ - void setFont(const std::string& font); - - /** - * @brief Set the text align of font - * - * @param align Text align - */ - void setTextAlign(const TextAlign align); - - /** - * @brief Set the text to display on ui element - * - * @param text to display - */ - virtual void setText(const std::string& text); - - /** - * @brief Set the onClick function which will be called when element is - * clicked - * - * @param func function to assign to onClick - */ - void setOnClick(std::function func); - - /** - * @brief Get the text - * - * @returns text - */ - std::string getText() const; - - protected: - /// Font to use for displaying text - Font font; - - // Font align - TextAlign text_align; - - /// Text to display where applicable - std::string text; - - /// Intermediate on click handler - virtual void handleOnClick(); - - /// Holds reference to onClick function - std::function onClick; - - /// Stores id of focused element - static ObjId focused; -}; - -} // namespace afk - -#endif // INCLUDE_ENTITIES_UI_UIELEMENT_H_ - -/** - * @example ex_ui.cpp - * This example shows how to use various ui elements - */ diff --git a/include/random/RandomGenerator.h b/include/random/RandomGenerator.h deleted file mode 100644 index 048f06c..0000000 --- a/include/random/RandomGenerator.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * @file RandomGenerator.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Static helper class that can create random numbers. - * @version 0.1 - * @date 2020-08-11 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_RANDOM_RANDOMGENERATOR_H_ -#define INCLUDE_RANDOM_RANDOMGENERATOR_H_ - -#include - -namespace afk { - -/** - * @brief Random number generator - * - */ -class Random { - public: - /** - * @brief Returns a random float between two numbers - * - * @param min Min number - * @param max Max number - * @return Random number - */ - static float randomFloat(const float min, const float max); - - /** - * @brief Returns a random int between two numbers - * - * @param min Min number - * @param max Max number - * @return Random number - */ - static int randomInt(const int min, const int max); - - private: - /// Random number generator - static std::mt19937 rng; -}; - -} // namespace afk - -#endif // INCLUDE_RANDOM_RANDOMGENERATOR_H_ diff --git a/include/scene/Scene.h b/include/scene/Scene.h deleted file mode 100644 index 7ee692a..0000000 --- a/include/scene/Scene.h +++ /dev/null @@ -1,178 +0,0 @@ -/** - * @file Scene.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Parent scene class. Children can be added to scene manager. - * @version 0.1 - * @date 2016-12-30 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_SCENE_SCENE_H_ -#define INCLUDE_SCENE_SCENE_H_ - -#include -#include -#include -#include -#include - -#include "../common/Exceptions.h" -#include "../entities/GameObject.h" -#include "../services/Services.h" - -/** - * @brief Scene for state machine - * - */ -namespace afk { -class Scene { - public: - /** - * @brief Create a new Scene - * - */ - Scene(); - - /** - * @brief Destroy the Scene - * - */ - virtual ~Scene() {} - - /** - * @brief Start the scene - * - */ - virtual void start(){}; - - /** - * @brief Update to be overridden by derived scenes - * - * @param delta Time since last call in ms - * - */ - virtual void update(Uint32 delta); - - /** - * @brief Draw to be overridden by derived scenes - * - */ - virtual void draw(); - - /** - * @brief Stop the scene - * - */ - virtual void stop(){}; - - /** - * @brief Internall cleanup call - * - */ - void stopInternal(); - - /** - * @brief Add game object to update and draw pool, returns by reference - * - * @tparam T Type of game object - * @tparam Args Arguments to forward to T - * @param args Argument values which will be forwarded to T when constructing - * a new game object - * @return Reference to created game object - */ - template - T& add(Args&&... args) { - // Create the game object - GameObject* obj = new T(std::forward(args)...); - - // Add to lookup - lookup_map[obj->id] = update_pool.size(); - - // Push - update_pool.emplace_back(obj); - - // Force sort on next update - need_sort = true; - - // Return the object! - return get(obj->id); - } - - /** - * @brief Removes a game object from the scene pool - * - * @param id Id of object to remove - */ - void remove(const ObjId id); - - /** - * @brief Check if obj id exists in scene - * - * @param id Object id to check - * @return true If the object exists - * @return false If the object does not exist - */ - bool has(const ObjId id); - - /** - * @brief Gets a game object by id and casts to type T - * - * @tparam T Type of game object - * @param id Id of game object to look up - * @return Reference to game object if found - * @throws KeyLookupException if game object could not be found - */ - template - T& get(const ObjId id) { - GameObject& obj = get(id); - try { - return dynamic_cast(obj); - } catch (...) { - throw KeyLookupException("Could not cast entity " + std::to_string(id) + - " to type"); - } - } - - /** - * @brief Gets a game object by id without the cast - * - * @param id Id of game object to look up - * @return Reference to game object if found - * @throws KeyLookupException if game object could not be found - */ - GameObject& get(const ObjId id) { - if (!has(id)) { - throw KeyLookupException("Could not find entity by id " + - std::to_string(id)); - } - - unsigned int index = lookup_map[id]; - return *update_pool.at(index); - } - - /// Service references - AudioService& audio; - LoggingService& logger; - DisplayService& display; - AssetService& assets; - InputService& input; - SceneService& scene; - ConfigService& config; - - private: - /// Holds game objects - std::vector> update_pool; - - /// Quick gameobject lookup - std::map lookup_map; - - /// Store objects to be removed - std::vector remove_pool; - - /// Needs sorting - bool need_sort; -}; -} // namespace afk - -#endif // INCLUDE_SCENE_SCENE_H_ diff --git a/include/services/input/JoystickCodes.h b/include/services/input/JoystickCodes.h deleted file mode 100644 index 4973700..0000000 --- a/include/services/input/JoystickCodes.h +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file JoystickCodes.h - * @author Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief Defines for codes used for joystick - * @version 0.1 - * @date 2018-11-20 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_SERVICES_INPUT_JOYSTICKCODES_H_ -#define INCLUDE_SERVICES_INPUT_JOYSTICKCODES_H_ - -namespace afk { - -enum class JoystickButtons { - A = 0, - B = 1, - X = 2, - Y = 3, - BUMPER_RIGHT = 4, - BUMPER_LEFT = 5, - BACK = 8, - START = 9, - PAD_RIGHT = 10, - PAD_LEFT = 11, - PAD_DOWN = 12, - PAD_UP = 13 -}; - -enum class JoystickSticks { - LEFT_STICK_LEFT = 1, - LEFT_STICK_RIGHT = 0, - LEFT_STICK_DOWN = 2, - LEFT_STICK_UP = 3, - RIGHT_STICK_LEFT = 7, - RIGHT_STICK_RIGHT = 6, - RIGHT_STICK_DOWN = 8, - RIGHT_STICK_UP = 9, - LEFT_TRIGGER = 12, - RIGHT_TRIGGER = 18 -}; - -} // namespace afk - -#endif // INCLUDE_SERVICES_INPUT_JOYSTICKCODES_H_ diff --git a/include/services/input/KeyboardKeys.h b/include/services/input/KeyboardKeys.h deleted file mode 100644 index 6fbbc4c..0000000 --- a/include/services/input/KeyboardKeys.h +++ /dev/null @@ -1,247 +0,0 @@ -/** - * @file KeyboardKeys.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Defenitions of keys that can be used by input manager - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#ifndef INCLUDE_SERVICES_INPUT_KEYBOARDKEYS_H_ -#define INCLUDE_SERVICES_INPUT_KEYBOARDKEYS_H_ - -namespace afk { - -enum class Keys { - UNKNOWN = 0, - A = 4, - B = 5, - C = 6, - D = 7, - E = 8, - F = 9, - G = 10, - H = 11, - I = 12, - J = 13, - K = 14, - L = 15, - M = 16, - N = 17, - O = 18, - P = 19, - Q = 20, - R = 21, - S = 22, - T = 23, - U = 24, - V = 25, - W = 26, - X = 27, - Y = 28, - Z = 29, - ONE = 30, - TWO = 31, - THREE = 32, - FOUR = 33, - FIVE = 34, - SIX = 35, - SEVEN = 36, - EIGHT = 37, - NINE = 38, - ZERO = 39, - RETURN = 40, - ESCAPE = 41, - BACKSPACE = 42, - TAB = 43, - SPACE = 44, - MINUS = 45, - EQUALS = 46, - LEFTBRACKET = 47, - RIGHTBRACKET = 48, - BACKSLASH = 49, - NONUSHASH = 50, - SEMICOLON = 51, - APOSTROPHE = 52, - GRAVE = 53, - COMMA = 54, - PERIOD = 55, - SLASH = 56, - CAPSLOCK = 57, - F1 = 58, - F2 = 59, - F3 = 60, - F4 = 61, - F5 = 62, - F6 = 63, - F7 = 64, - F8 = 65, - F9 = 66, - F10 = 67, - F11 = 68, - F12 = 69, - PRINTSCREEN = 70, - SCROLLLOCK = 71, - PAUSE = 72, - INSERT = 73, - HOME = 74, - PAGEUP = 75, - DELETE = 76, - END = 77, - PAGEDOWN = 78, - RIGHT = 79, - LEFT = 80, - DOWN = 81, - UP = 82, - NUMLOCKCLEAR = 83, - KP_DIVIDE = 84, - KP_MULTIPLY = 85, - KP_MINUS = 86, - KP_PLUS = 87, - KP_ENTER = 88, - KP_1 = 89, - KP_2 = 90, - KP_3 = 91, - KP_4 = 92, - KP_5 = 93, - KP_6 = 94, - KP_7 = 95, - KP_8 = 96, - KP_9 = 97, - KP_0 = 98, - KP_PERIOD = 99, - NONUSBACKSLASH = 100, - APPLICATION = 101, - POWER = 102, - KP_EQUALS = 103, - F13 = 104, - F14 = 105, - F15 = 106, - F16 = 107, - F17 = 108, - F18 = 109, - F19 = 110, - F20 = 111, - F21 = 112, - F22 = 113, - F23 = 114, - F24 = 115, - EXECUTE = 116, - HELP = 117, - MENU = 118, - SELECT = 119, - STOP = 120, - AGAIN = 121, - UNDO = 122, - CUT = 123, - COPY = 124, - PASTE = 125, - FIND = 126, - MUTE = 127, - VOLUMEUP = 128, - VOLUMEDOWN = 129, - KP_COMMA = 133, - KP_EQUALSAS400 = 134, - ALTERASE = 153, - SYSREQ = 154, - CANCEL = 155, - CLEAR = 156, - PRIOR = 157, - RETURN2 = 158, - SEPARATOR = 159, - OUT = 160, - OPER = 161, - CLEARAGAIN = 162, - CRSEL = 163, - EXSEL = 164, - KP_00 = 176, - KP_000 = 177, - THOUSANDSSEPARATOR = 178, - DECIMALSEPARATOR = 179, - CURRENCYUNIT = 180, - CURRENCYSUBUNIT = 181, - KP_LEFTPAREN = 182, - KP_RIGHTPAREN = 183, - KP_LEFTBRACE = 184, - KP_RIGHTBRACE = 185, - KP_TAB = 186, - KP_BACKSPACE = 187, - KP_A = 188, - KP_B = 189, - KP_C = 190, - KP_D = 191, - KP_E = 192, - KP_F = 193, - KP_XOR = 194, - KP_POWER = 195, - KP_PERCENT = 196, - KP_LESS = 197, - KP_GREATER = 198, - KP_AMPERSAND = 199, - KP_DBLAMPERSAND = 200, - KP_VERTICALBAR = 201, - KP_DBLVERTICALBAR = 202, - KP_COLON = 203, - KP_HASH = 204, - KP_SPACE = 205, - KP_AT = 206, - KP_EXCLAM = 207, - KP_MEMSTORE = 208, - KP_MEMRECALL = 209, - KP_MEMCLEAR = 210, - KP_MEMADD = 211, - KP_MEMSUBTRACT = 212, - KP_MEMMULTIPLY = 213, - KP_MEMDIVIDE = 214, - KP_PLUSMINUS = 215, - KP_CLEAR = 216, - KP_CLEARENTRY = 217, - KP_BINARY = 218, - KP_OCTAL = 219, - KP_DECIMAL = 220, - KP_HEXADECIMAL = 221, - LCTRL = 224, - LSHIFT = 225, - LALT = 226, - LGUI = 227, - RCTRL = 228, - RSHIFT = 229, - RALT = 230, - RGUI = 231, - MODE = 257, - AUDIONEXT = 258, - AUDIOPREV = 259, - AUDIOSTOP = 260, - AUDIOPLAY = 261, - AUDIOMUTE = 262, - MEDIASELECT = 263, - WWW = 264, - MAIL = 265, - CALCULATOR = 266, - COMPUTER = 267, - AC_SEARCH = 268, - AC_HOME = 269, - AC_BACK = 270, - AC_FORWARD = 271, - AC_STOP = 272, - AC_REFRESH = 273, - AC_BOOKMARKS = 274, - BRIGHTNESSDOWN = 275, - BRIGHTNESSUP = 276, - DISPLAYSWITCH = 277, - KBDILLUMTOGGLE = 278, - KBDILLUMDOWN = 279, - KBDILLUMUP = 280, - EJECT = 281, - SLEEP = 282, - APP1 = 283, - APP2 = 284, - AUDIOREWIND = 285, - AUDIOFASTFORWARD = 286, - MAX = 512 -}; - -} // namespace afk - -#endif // INCLUDE_SERVICES_INPUT_KEYBOARDKEYS_H_ diff --git a/lib/afk-config.cmake b/lib/afk-config.cmake new file mode 100644 index 0000000..39986b3 --- /dev/null +++ b/lib/afk-config.cmake @@ -0,0 +1,4 @@ +# afk-config.cmake - package configuration file + +get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) +include(${SELF_DIR}/afk.cmake) \ No newline at end of file diff --git a/lib/cmake/Copyright.txt b/lib/cmake/Copyright.txt new file mode 100644 index 0000000..d17e35d --- /dev/null +++ b/lib/cmake/Copyright.txt @@ -0,0 +1,132 @@ +CMake - Cross Platform Makefile Generator +Copyright 2000-2019 Kitware, Inc. and Contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name of Kitware, Inc. nor the names of Contributors + may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------ + +The following individuals and institutions are among the Contributors: + +* Aaron C. Meadows +* Adriaan de Groot +* Aleksey Avdeev +* Alexander Neundorf +* Alexander Smorkalov +* Alexey Sokolov +* Alex Merry +* Alex Turbov +* Amine Ben Hassouna +* Andreas Pakulat +* Andreas Schneider +* André Rigland Brodtkorb +* Axel Huebl, Helmholtz-Zentrum Dresden - Rossendorf +* Benjamin Eikel +* Bjoern Ricks +* Brad Hards +* Christopher Harvey +* Christoph Grüninger +* Clement Creusot +* Daniel Blezek +* Daniel Pfeifer +* Enrico Scholz +* Eran Ifrah +* Esben Mose Hansen, Ange Optimization ApS +* Geoffrey Viola +* Google Inc +* Gregor Jasny +* Helio Chissini de Castro +* Ilya Lavrenov +* Insight Software Consortium +* Jan Woetzel +* Julien Schueller +* Kelly Thompson +* Laurent Montel +* Konstantin Podsvirov +* Mario Bensi +* Martin Gräßlin +* Mathieu Malaterre +* Matthaeus G. Chajdas +* Matthias Kretz +* Matthias Maennich +* Michael Hirsch, Ph.D. +* Michael Stürmer +* Miguel A. Figueroa-Villanueva +* Mike Jackson +* Mike McQuaid +* Nicolas Bock +* Nicolas Despres +* Nikita Krupen'ko +* NVIDIA Corporation +* OpenGamma Ltd. +* Patrick Stotko +* Per Øyvind Karlsen +* Peter Collingbourne +* Petr Gotthard +* Philip Lowman +* Philippe Proulx +* Raffi Enficiaud, Max Planck Society +* Raumfeld +* Roger Leigh +* Rolf Eike Beer +* Roman Donchenko +* Roman Kharitonov +* Ruslan Baratov +* Sebastian Holtermann +* Stephen Kelly +* Sylvain Joubert +* Thomas Sondergaard +* Tobias Hunger +* Todd Gamblin +* Tristan Carel +* University of Dundee +* Vadim Zhukov +* Will Dicharry + +See version control history for details of individual contributions. + +The above copyright and license notice applies to distributions of +CMake in source and binary form. Third-party software packages supplied +with CMake under compatible licenses provide their own copyright notices +documented in corresponding subdirectories or source files. + +------------------------------------------------------------------------------ + +CMake was initially developed by Kitware with the following sponsorship: + + * National Library of Medicine at the National Institutes of Health + as part of the Insight Segmentation and Registration Toolkit (ITK). + + * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel + Visualization Initiative. + + * National Alliance for Medical Image Computing (NAMIC) is funded by the + National Institutes of Health through the NIH Roadmap for Medical Research, + Grant U54 EB005149. + + * Kitware, Inc. diff --git a/lib/cmake/FindSDL2.cmake b/lib/cmake/FindSDL2.cmake new file mode 100644 index 0000000..598890f --- /dev/null +++ b/lib/cmake/FindSDL2.cmake @@ -0,0 +1,392 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2 +-------- + +Locate SDL2 library + +This module defines the following 'IMPORTED' targets: + +:: + + SDL2::Core (for compatibility with older versions) + SDL2::SDL2 (compatibility with CONFIG mode) + The SDL2 library, if found. + Libraries should link to SDL2::SDL2 + + SDL2::Main (for compatibility with older versions) + SDL2::SDL2main (compatibility with CONFIG mode) + The SDL2main library, if found. + Applications should link to SDL2::SDL2main instead of SDL2::SDL2 + + + +This module will set the following variables in your project: + +:: + + SDL2_LIBRARIES, the name of the library to link against + SDL2_INCLUDE_DIRS, where to find SDL.h + SDL2_FOUND, if false, do not try to link to SDL2 + SDL2MAIN_FOUND, if false, do not try to link to SDL2main + SDL2_VERSION_STRING, human-readable string containing the version of SDL2 + + + +This module responds to the following cache variables: + +:: + + SDL2_PATH + Set a custom SDL2 Library path (default: empty) + + SDL2_NO_DEFAULT_PATH + Disable search SDL2 Library in default path. + If SDL2_PATH (default: ON) + Else (default: OFF) + + SDL2_INCLUDE_DIR + SDL2 headers path. + + SDL2_LIBRARY + SDL2 Library (.dll, .so, .a, etc) path. + + SDL2MAIN_LIBRAY + SDL2main Library (.a) path. + + SDL2_BUILDING_LIBRARY + This flag is useful only when linking to SDL2_LIBRARIES insead of + SDL2::Main. It is required only when building a library that links to + SDL2_LIBRARIES, because only applications need main() (No need to also + link to SDL2main). + If this flag is defined, then no SDL2main will be added to SDL2_LIBRARIES + and no SDL2::Main target will be created. + + +Don't forget to include SDLmain.h and SDLmain.m in your project for the +OS X framework based version. (Other versions link to -lSDL2main which +this module will try to find on your behalf.) Also for OS X, this +module will automatically add the -framework Cocoa on your behalf. + + +Additional Note: If you see an empty SDL2_LIBRARY in your project +configuration, it means CMake did not find your SDL2 library +(SDL2.dll, libsdl2.so, SDL2.framework, etc). Set SDL2_LIBRARY to point +to your SDL2 library, and configure again. Similarly, if you see an +empty SDL2MAIN_LIBRARY, you should set this value as appropriate. These +values are used to generate the final SDL2_LIBRARIES variable and the +SDL2::Core and SDL2::Main targets, but when these values are unset, +SDL2_LIBRARIES, SDL2::Core and SDL2::Main does not get created. + + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. l.e.galup 9-20-02 + + + +Created by Amine Ben Hassouna: + Adapt FindSDL.cmake to SDL2 (FindSDL2.cmake). + Add cache variables for more flexibility: + SDL2_PATH, SDL2_NO_DEFAULT_PATH (for details, see doc above). + Mark 'Threads' as a required dependency for non-OSX systems. + Modernize the FindSDL2.cmake module by creating specific targets: + SDL2::Core and SDL2::Main (for details, see doc above). + + +Original FindSDL.cmake module: + Modified by Eric Wing. Added code to assist with automated building + by using environmental variables and providing a more + controlled/consistent search behavior. Added new modifications to + recognize OS X frameworks and additional Unix paths (FreeBSD, etc). + Also corrected the header search path to follow "proper" SDL + guidelines. Added a search for SDLmain which is needed by some + platforms. Added a search for threads which is needed by some + platforms. Added needed compile switches for MinGW. + +On OSX, this will prefer the Framework version (if found) over others. +People will have to manually change the cache value of SDL2_LIBRARY to +override this selection or set the SDL2_PATH variable or the CMake +environment CMAKE_INCLUDE_PATH to modify the search paths. + +Note that the header path has changed from SDL/SDL.h to just SDL.h +This needed to change because "proper" SDL convention is #include +"SDL.h", not . This is done for portability reasons +because not all systems place things in SDL/ (see FreeBSD). +#]=======================================================================] + +# Define options for searching SDL2 Library in a custom path + +set(SDL2_PATH "" CACHE STRING "Custom SDL2 Library path") + +set(_SDL2_NO_DEFAULT_PATH OFF) +if(SDL2_PATH) + set(_SDL2_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_NO_DEFAULT_PATH ${_SDL2_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2 Library in default path") +unset(_SDL2_NO_DEFAULT_PATH) + +set(SDL2_NO_DEFAULT_PATH_CMD) +if(SDL2_NO_DEFAULT_PATH) + set(SDL2_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2 include directory +find_path(SDL2_INCLUDE_DIR SDL.h + HINTS + ENV SDL2DIR + ${SDL2_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + include/SDL2 include + PATHS ${SDL2_PATH} + DOC "Where the SDL2 headers can be found" +) + +set(SDL2_INCLUDE_DIRS "${SDL2_INCLUDE_DIR}") + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# SDL-2.0 is the name used by FreeBSD ports... +# don't confuse it for the version number. +find_library(SDL2_LIBRARY + NAMES SDL2 SDL-2.0 + HINTS + ENV SDL2DIR + ${SDL2_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_PATH} + DOC "Where the SDL2 Library can be found" +) + +set(SDL2_LIBRARIES "${SDL2_LIBRARY}") + +if(NOT SDL2_BUILDING_LIBRARY) + if(NOT SDL2_INCLUDE_DIR MATCHES ".framework") + # Non-OS X framework versions expect you to also dynamically link to + # SDL2main. This is mainly for Windows and OS X. Other (Unix) platforms + # seem to provide SDL2main for compatibility even though they don't + # necessarily need it. + + if(SDL2_PATH) + set(SDL2MAIN_LIBRARY_PATHS "${SDL2_PATH}") + endif() + + if(NOT SDL2_NO_DEFAULT_PATH) + set(SDL2MAIN_LIBRARY_PATHS + /sw + /opt/local + /opt/csw + /opt + "${SDL2MAIN_LIBRARY_PATHS}" + ) + endif() + + find_library(SDL2MAIN_LIBRARY + NAMES SDL2main + HINTS + ENV SDL2DIR + ${SDL2_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2MAIN_LIBRARY_PATHS} + DOC "Where the SDL2main library can be found" + ) + unset(SDL2MAIN_LIBRARY_PATHS) + endif() +endif() + +# SDL2 may require threads on your system. +# The Apple build may not need an explicit flag because one of the +# frameworks may already provide it. +# But for non-OSX systems, I will use the CMake Threads package. +if(NOT APPLE) + find_package(Threads QUIET) + if(NOT Threads_FOUND) + set(SDL2_THREADS_NOT_FOUND "Could NOT find Threads (Threads is required by SDL2).") + if(SDL2_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_THREADS_NOT_FOUND}) + else() + if(NOT SDL2_FIND_QUIETLY) + message(STATUS ${SDL2_THREADS_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_THREADS_NOT_FOUND) + endif() +endif() + +# MinGW needs an additional link flag, -mwindows +# It's total link flags should look like -lmingw32 -lSDL2main -lSDL2 -mwindows +if(MINGW) + set(MINGW32_LIBRARY mingw32 "-mwindows" CACHE STRING "link flags for MinGW") +endif() + +if(SDL2_LIBRARY) + # For SDL2main + if(SDL2MAIN_LIBRARY AND NOT SDL2_BUILDING_LIBRARY) + list(FIND SDL2_LIBRARIES "${SDL2MAIN_LIBRARY}" _SDL2_MAIN_INDEX) + if(_SDL2_MAIN_INDEX EQUAL -1) + set(SDL2_LIBRARIES "${SDL2MAIN_LIBRARY}" ${SDL2_LIBRARIES}) + endif() + unset(_SDL2_MAIN_INDEX) + endif() + + # For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa. + # CMake doesn't display the -framework Cocoa string in the UI even + # though it actually is there if I modify a pre-used variable. + # I think it has something to do with the CACHE STRING. + # So I use a temporary variable until the end so I can set the + # "real" variable in one-shot. + if(APPLE) + set(SDL2_LIBRARIES ${SDL2_LIBRARIES} -framework Cocoa) + endif() + + # For threads, as mentioned Apple doesn't need this. + # In fact, there seems to be a problem if I used the Threads package + # and try using this line, so I'm just skipping it entirely for OS X. + if(NOT APPLE) + set(SDL2_LIBRARIES ${SDL2_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) + endif() + + # For MinGW library + if(MINGW) + set(SDL2_LIBRARIES ${MINGW32_LIBRARY} ${SDL2_LIBRARIES}) + endif() + +endif() + +# Read SDL2 version +if(SDL2_INCLUDE_DIR AND EXISTS "${SDL2_INCLUDE_DIR}/SDL_version.h") + file(STRINGS "${SDL2_INCLUDE_DIR}/SDL_version.h" SDL2_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_INCLUDE_DIR}/SDL_version.h" SDL2_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_INCLUDE_DIR}/SDL_version.h" SDL2_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_MAJOR "${SDL2_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_MINOR "${SDL2_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_VERSION_PATCH "${SDL2_VERSION_PATCH_LINE}") + set(SDL2_VERSION_STRING ${SDL2_VERSION_MAJOR}.${SDL2_VERSION_MINOR}.${SDL2_VERSION_PATCH}) + unset(SDL2_VERSION_MAJOR_LINE) + unset(SDL2_VERSION_MINOR_LINE) + unset(SDL2_VERSION_PATCH_LINE) + unset(SDL2_VERSION_MAJOR) + unset(SDL2_VERSION_MINOR) + unset(SDL2_VERSION_PATCH) +endif() + +include(FindPackageHandleStandardArgs) + +set(SDL2_REQUIRED_VARS SDL2_LIBRARY SDL2_INCLUDE_DIR) +if(SDL2MAIN_LIBRARY) + list(APPEND SDL2_REQUIRED_VARS SDL2MAIN_LIBRARY SDL2_INCLUDE_DIR) +endif() + +find_package_handle_standard_args(SDL2 + REQUIRED_VARS ${SDL2_REQUIRED_VARS} + VERSION_VAR SDL2_VERSION_STRING) + +mark_as_advanced(SDL2_PATH + SDL2_NO_DEFAULT_PATH + SDL2_LIBRARY + SDL2MAIN_LIBRARY + SDL2_INCLUDE_DIR + SDL2_BUILDING_LIBRARY) + + +# SDL2:: targets (SDL2::Core and SDL2::Main) +if(SDL2_FOUND) + + # SDL2::Core target + if(SDL2_LIBRARY AND NOT TARGET SDL2::Core) + add_library(SDL2::Core UNKNOWN IMPORTED) + set_target_properties(SDL2::Core PROPERTIES + IMPORTED_LOCATION "${SDL2_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_INCLUDE_DIR}") + + if(APPLE) + # For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa. + # For more details, please see above. + set_property(TARGET SDL2::Core APPEND PROPERTY + INTERFACE_LINK_OPTIONS -framework Cocoa) + else() + # For threads, as mentioned Apple doesn't need this. + # For more details, please see above. + set_property(TARGET SDL2::Core APPEND PROPERTY + INTERFACE_LINK_LIBRARIES Threads::Threads) + endif() + endif() + + # SDL2::Main target + # Applications should link to SDL2::Main instead of SDL2::Core + # For more details, please see above. + if(NOT SDL2_BUILDING_LIBRARY AND NOT TARGET SDL2::Main) + + if(SDL2_INCLUDE_DIR MATCHES ".framework" OR NOT SDL2MAIN_LIBRARY) + add_library(SDL2::Main INTERFACE IMPORTED) + set_property(TARGET SDL2::Main PROPERTY + INTERFACE_LINK_LIBRARIES SDL2::Core) + elseif(SDL2MAIN_LIBRARY) + # MinGW requires that the mingw32 library is specified before the + # libSDL2main.a static library when linking. + # The SDL2::MainInternal target is used internally to make sure that + # CMake respects this condition. + add_library(SDL2::MainInternal UNKNOWN IMPORTED) + set_property(TARGET SDL2::MainInternal PROPERTY + IMPORTED_LOCATION "${SDL2MAIN_LIBRARY}") + set_property(TARGET SDL2::MainInternal PROPERTY + INTERFACE_LINK_LIBRARIES SDL2::Core) + + add_library(SDL2::Main INTERFACE IMPORTED) + + if(MINGW) + # MinGW needs an additional link flag '-mwindows' and link to mingw32 + set_property(TARGET SDL2::Main PROPERTY + INTERFACE_LINK_LIBRARIES "mingw32" "-mwindows") + endif() + + set_property(TARGET SDL2::Main APPEND PROPERTY + INTERFACE_LINK_LIBRARIES SDL2::MainInternal) + endif() + + # compatibility targets + add_library(SDL2::SDL2 ALIAS SDL2::Core) + add_library(SDL2::SDL2main ALIAS SDL2::Main) + + endif() +endif() diff --git a/lib/cmake/FindSDL2_gfx.cmake b/lib/cmake/FindSDL2_gfx.cmake new file mode 100644 index 0000000..970a92d --- /dev/null +++ b/lib/cmake/FindSDL2_gfx.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_gfx +-------------- + +Locate SDL2_gfx library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::GFX + The SDL2_gfx library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_GFX_LIBRARIES, the name of the library to link against + SDL2_GFX_INCLUDE_DIRS, where to find the headers + SDL2_GFX_FOUND, if false, do not try to link against + SDL2_GFX_VERSION_STRING - human-readable string containing the + version of SDL2_gfx + + + +This module responds to the following cache variables: + +:: + + SDL2_GFX_PATH + Set a custom SDL2_gfx Library path (default: empty) + + SDL2_GFX_NO_DEFAULT_PATH + Disable search SDL2_gfx Library in default path. + If SDL2_GFX_PATH (default: ON) + Else (default: OFF) + + SDL2_GFX_INCLUDE_DIR + SDL2_gfx headers path. + + SDL2_GFX_LIBRARY + SDL2_gfx Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_GFX_LIBRARY in your project +configuration, it means CMake did not find your SDL2_gfx library +(SDL2_gfx.dll, libsdl2_gfx.so, etc). Set SDL2_GFX_LIBRARY to point +to your SDL2_gfx library, and configure again. This value is used to +generate the final SDL2_GFX_LIBRARIES variable and the SDL2::GFX target, +but when this value is unset, SDL2_GFX_LIBRARIES and SDL2::GFX does not +get created. + + +$SDL2GFXDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2GFXDIR used in building SDL2_gfx. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_image.cmake to SDL2_gfx (FindSDL2_gfx.cmake). + Add cache variables for more flexibility: + SDL2_GFX_PATH, SDL2_GFX_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_gfx.cmake module by creating a specific target: + SDL2::GFX (for details, see doc above). + +Original FindSDL_image.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_GFX_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_gfx).") + if(SDL2_gfx_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_GFX_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_gfx_FIND_QUIETLY) + message(STATUS ${SDL2_GFX_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_GFX_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_gfx Library in a custom path + +set(SDL2_GFX_PATH "" CACHE STRING "Custom SDL2_gfx Library path") + +set(_SDL2_GFX_NO_DEFAULT_PATH OFF) +if(SDL2_GFX_PATH) + set(_SDL2_GFX_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_GFX_NO_DEFAULT_PATH ${_SDL2_GFX_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_gfx Library in default path") +unset(_SDL2_GFX_NO_DEFAULT_PATH) + +set(SDL2_GFX_NO_DEFAULT_PATH_CMD) +if(SDL2_GFX_NO_DEFAULT_PATH) + set(SDL2_GFX_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_gfx include directory +find_path(SDL2_GFX_INCLUDE_DIR SDL2_gfxPrimitives.h + HINTS + ENV SDL2GFXDIR + ENV SDL2DIR + ${SDL2_GFX_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2GFXDIR} + include/SDL2 include + PATHS ${SDL2_GFX_PATH} + DOC "Where the SDL2_gfx headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_gfx library +find_library(SDL2_GFX_LIBRARY + NAMES SDL2_gfx + HINTS + ENV SDL2GFXDIR + ENV SDL2DIR + ${SDL2_GFX_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_GFX_PATH} + DOC "Where the SDL2_gfx Library can be found" +) + +# Read SDL2_gfx version +if(SDL2_GFX_INCLUDE_DIR AND EXISTS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h") + file(STRINGS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h" SDL2_GFX_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_MAJOR[ \t]+[0-9]+$") + file(STRINGS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h" SDL2_GFX_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_MINOR[ \t]+[0-9]+$") + file(STRINGS "${SDL2_GFX_INCLUDE_DIR}/SDL2_gfxPrimitives.h" SDL2_GFX_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL2_GFXPRIMITIVES_MICRO[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL2_GFXPRIMITIVES_MAJOR[ \t]+([0-9]+)$" "\\1" SDL2_GFX_VERSION_MAJOR "${SDL2_GFX_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL2_GFXPRIMITIVES_MINOR[ \t]+([0-9]+)$" "\\1" SDL2_GFX_VERSION_MINOR "${SDL2_GFX_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL2_GFXPRIMITIVES_MICRO[ \t]+([0-9]+)$" "\\1" SDL2_GFX_VERSION_PATCH "${SDL2_GFX_VERSION_PATCH_LINE}") + set(SDL2_GFX_VERSION_STRING ${SDL2_GFX_VERSION_MAJOR}.${SDL2_GFX_VERSION_MINOR}.${SDL2_GFX_VERSION_PATCH}) + unset(SDL2_GFX_VERSION_MAJOR_LINE) + unset(SDL2_GFX_VERSION_MINOR_LINE) + unset(SDL2_GFX_VERSION_PATCH_LINE) + unset(SDL2_GFX_VERSION_MAJOR) + unset(SDL2_GFX_VERSION_MINOR) + unset(SDL2_GFX_VERSION_PATCH) +endif() + +set(SDL2_GFX_LIBRARIES ${SDL2_GFX_LIBRARY}) +set(SDL2_GFX_INCLUDE_DIRS ${SDL2_GFX_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_gfx + REQUIRED_VARS SDL2_GFX_LIBRARIES SDL2_GFX_INCLUDE_DIRS + VERSION_VAR SDL2_GFX_VERSION_STRING) + + +mark_as_advanced(SDL2_GFX_PATH + SDL2_GFX_NO_DEFAULT_PATH + SDL2_GFX_LIBRARY + SDL2_GFX_INCLUDE_DIR) + + +if(SDL2_GFX_FOUND) + + # SDL2::GFX target + if(SDL2_GFX_LIBRARY AND NOT TARGET SDL2::GFX) + add_library(SDL2::GFX UNKNOWN IMPORTED) + set_target_properties(SDL2::GFX PROPERTIES + IMPORTED_LOCATION "${SDL2_GFX_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_GFX_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_image.cmake b/lib/cmake/FindSDL2_image.cmake new file mode 100644 index 0000000..624e915 --- /dev/null +++ b/lib/cmake/FindSDL2_image.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_image +-------------- + +Locate SDL2_image library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::Image + The SDL2_image library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_IMAGE_LIBRARIES, the name of the library to link against + SDL2_IMAGE_INCLUDE_DIRS, where to find the headers + SDL2_IMAGE_FOUND, if false, do not try to link against + SDL2_IMAGE_VERSION_STRING - human-readable string containing the + version of SDL2_image + + + +This module responds to the following cache variables: + +:: + + SDL2_IMAGE_PATH + Set a custom SDL2_image Library path (default: empty) + + SDL2_IMAGE_NO_DEFAULT_PATH + Disable search SDL2_image Library in default path. + If SDL2_IMAGE_PATH (default: ON) + Else (default: OFF) + + SDL2_IMAGE_INCLUDE_DIR + SDL2_image headers path. + + SDL2_IMAGE_LIBRARY + SDL2_image Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_IMAGE_LIBRARY in your project +configuration, it means CMake did not find your SDL2_image library +(SDL2_image.dll, libsdl2_image.so, etc). Set SDL2_IMAGE_LIBRARY to point +to your SDL2_image library, and configure again. This value is used to +generate the final SDL2_IMAGE_LIBRARIES variable and the SDL2::Image target, +but when this value is unset, SDL2_IMAGE_LIBRARIES and SDL2::Image does not +get created. + + +$SDL2IMAGEDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2IMAGEDIR used in building SDL2_image. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_image.cmake to SDL2_image (FindSDL2_image.cmake). + Add cache variables for more flexibility: + SDL2_IMAGE_PATH, SDL2_IMAGE_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_image.cmake module by creating a specific target: + SDL2::Image (for details, see doc above). + +Original FindSDL_image.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_IMAGE_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_image).") + if(SDL2_image_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_IMAGE_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_image_FIND_QUIETLY) + message(STATUS ${SDL2_IMAGE_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_IMAGE_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_image Library in a custom path + +set(SDL2_IMAGE_PATH "" CACHE STRING "Custom SDL2_image Library path") + +set(_SDL2_IMAGE_NO_DEFAULT_PATH OFF) +if(SDL2_IMAGE_PATH) + set(_SDL2_IMAGE_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_IMAGE_NO_DEFAULT_PATH ${_SDL2_IMAGE_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_image Library in default path") +unset(_SDL2_IMAGE_NO_DEFAULT_PATH) + +set(SDL2_IMAGE_NO_DEFAULT_PATH_CMD) +if(SDL2_IMAGE_NO_DEFAULT_PATH) + set(SDL2_IMAGE_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_image include directory +find_path(SDL2_IMAGE_INCLUDE_DIR SDL_image.h + HINTS + ENV SDL2IMAGEDIR + ENV SDL2DIR + ${SDL2_IMAGE_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2IMAGEDIR} + include/SDL2 include + PATHS ${SDL2_IMAGE_PATH} + DOC "Where the SDL2_image headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_image library +find_library(SDL2_IMAGE_LIBRARY + NAMES SDL2_image + HINTS + ENV SDL2IMAGEDIR + ENV SDL2DIR + ${SDL2_IMAGE_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_IMAGE_PATH} + DOC "Where the SDL2_image Library can be found" +) + +# Read SDL2_image version +if(SDL2_IMAGE_INCLUDE_DIR AND EXISTS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h") + file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h" SDL2_IMAGE_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_IMAGE_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h" SDL2_IMAGE_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_IMAGE_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_IMAGE_INCLUDE_DIR}/SDL_image.h" SDL2_IMAGE_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_IMAGE_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_IMAGE_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_MAJOR "${SDL2_IMAGE_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_IMAGE_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_MINOR "${SDL2_IMAGE_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_IMAGE_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_IMAGE_VERSION_PATCH "${SDL2_IMAGE_VERSION_PATCH_LINE}") + set(SDL2_IMAGE_VERSION_STRING ${SDL2_IMAGE_VERSION_MAJOR}.${SDL2_IMAGE_VERSION_MINOR}.${SDL2_IMAGE_VERSION_PATCH}) + unset(SDL2_IMAGE_VERSION_MAJOR_LINE) + unset(SDL2_IMAGE_VERSION_MINOR_LINE) + unset(SDL2_IMAGE_VERSION_PATCH_LINE) + unset(SDL2_IMAGE_VERSION_MAJOR) + unset(SDL2_IMAGE_VERSION_MINOR) + unset(SDL2_IMAGE_VERSION_PATCH) +endif() + +set(SDL2_IMAGE_LIBRARIES ${SDL2_IMAGE_LIBRARY}) +set(SDL2_IMAGE_INCLUDE_DIRS ${SDL2_IMAGE_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_image + REQUIRED_VARS SDL2_IMAGE_LIBRARIES SDL2_IMAGE_INCLUDE_DIRS + VERSION_VAR SDL2_IMAGE_VERSION_STRING) + + +mark_as_advanced(SDL2_IMAGE_PATH + SDL2_IMAGE_NO_DEFAULT_PATH + SDL2_IMAGE_LIBRARY + SDL2_IMAGE_INCLUDE_DIR) + + +if(SDL2_IMAGE_FOUND) + + # SDL2::Image target + if(SDL2_IMAGE_LIBRARY AND NOT TARGET SDL2::Image) + add_library(SDL2::Image UNKNOWN IMPORTED) + set_target_properties(SDL2::Image PROPERTIES + IMPORTED_LOCATION "${SDL2_IMAGE_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_IMAGE_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_mixer.cmake b/lib/cmake/FindSDL2_mixer.cmake new file mode 100644 index 0000000..a71f26a --- /dev/null +++ b/lib/cmake/FindSDL2_mixer.cmake @@ -0,0 +1,220 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_mixer +-------------- + +Locate SDL2_mixer library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::Mixer + The SDL2_mixer library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_MIXER_LIBRARIES, the name of the library to link against + SDL2_MIXER_INCLUDE_DIRS, where to find the headers + SDL2_MIXER_FOUND, if false, do not try to link against + SDL2_MIXER_VERSION_STRING - human-readable string containing the + version of SDL2_mixer + +This module responds to the following cache variables: + +:: + + SDL2_MIXER_PATH + Set a custom SDL2_mixer Library path (default: empty) + + SDL2_MIXER_NO_DEFAULT_PATH + Disable search SDL2_mixer Library in default path. + If SDL2_MIXER_PATH (default: ON) + Else (default: OFF) + + SDL2_MIXER_INCLUDE_DIR + SDL2_mixer headers path. + + SDL2_MIXER_LIBRARY + SDL2_mixer Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_MIXER_LIBRARY in your project +configuration, it means CMake did not find your SDL2_mixer library +(SDL2_mixer.dll, libsdl2_mixer.so, etc). Set SDL2_MIXER_LIBRARY to point +to your SDL2_mixer library, and configure again. This value is used to +generate the final SDL2_MIXER_LIBRARIES variable and the SDL2::Mixer target, +but when this value is unset, SDL2_MIXER_LIBRARIES and SDL2::Mixer does not +get created. + + +$SDL2MIXERDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2MIXERDIR used in building SDL2_mixer. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_mixer.cmake to SDL2_mixer (FindSDL2_mixer.cmake). + Add cache variables for more flexibility: + SDL2_MIXER_PATH, SDL2_MIXER_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_mixer.cmake module by creating a specific target: + SDL2::Mixer (for details, see doc above). + +Original FindSDL_mixer.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_MIXER_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_mixer).") + if(SDL2_mixer_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_MIXER_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_mixer_FIND_QUIETLY) + message(STATUS ${SDL2_MIXER_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_MIXER_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_mixer Library in a custom path + +set(SDL2_MIXER_PATH "" CACHE STRING "Custom SDL2_mixer Library path") + +set(_SDL2_MIXER_NO_DEFAULT_PATH OFF) +if(SDL2_MIXER_PATH) + set(_SDL2_MIXER_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_MIXER_NO_DEFAULT_PATH ${_SDL2_MIXER_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_mixer Library in default path") +unset(_SDL2_MIXER_NO_DEFAULT_PATH) + +set(SDL2_MIXER_NO_DEFAULT_PATH_CMD) +if(SDL2_MIXER_NO_DEFAULT_PATH) + set(SDL2_MIXER_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_mixer include directory +find_path(SDL2_MIXER_INCLUDE_DIR SDL_mixer.h + HINTS + ENV SDL2MIXERDIR + ENV SDL2DIR + ${SDL2_MIXER_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2MIXERDIR} + include/SDL2 include + PATHS ${SDL2_MIXER_PATH} + DOC "Where the SDL2_mixer headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_mixer library +find_library(SDL2_MIXER_LIBRARY + NAMES SDL2_mixer + HINTS + ENV SDL2MIXERDIR + ENV SDL2DIR + ${SDL2_MIXER_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_MIXER_PATH} + DOC "Where the SDL2_mixer Library can be found" +) + +# Read SDL2_mixer version +if(SDL2_MIXER_INCLUDE_DIR AND EXISTS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h") + file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_MIXER_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_MIXER_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_MIXER_INCLUDE_DIR}/SDL_mixer.h" SDL2_MIXER_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_MIXER_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MAJOR "${SDL2_MIXER_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_MINOR "${SDL2_MIXER_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_MIXER_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_MIXER_VERSION_PATCH "${SDL2_MIXER_VERSION_PATCH_LINE}") + set(SDL2_MIXER_VERSION_STRING ${SDL2_MIXER_VERSION_MAJOR}.${SDL2_MIXER_VERSION_MINOR}.${SDL2_MIXER_VERSION_PATCH}) + unset(SDL2_MIXER_VERSION_MAJOR_LINE) + unset(SDL2_MIXER_VERSION_MINOR_LINE) + unset(SDL2_MIXER_VERSION_PATCH_LINE) + unset(SDL2_MIXER_VERSION_MAJOR) + unset(SDL2_MIXER_VERSION_MINOR) + unset(SDL2_MIXER_VERSION_PATCH) +endif() + +set(SDL2_MIXER_LIBRARIES ${SDL2_MIXER_LIBRARY}) +set(SDL2_MIXER_INCLUDE_DIRS ${SDL2_MIXER_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_mixer + REQUIRED_VARS SDL2_MIXER_LIBRARIES SDL2_MIXER_INCLUDE_DIRS + VERSION_VAR SDL2_MIXER_VERSION_STRING) + + +mark_as_advanced(SDL2_MIXER_PATH + SDL2_MIXER_NO_DEFAULT_PATH + SDL2_MIXER_LIBRARY + SDL2_MIXER_INCLUDE_DIR) + + +if(SDL2_MIXER_FOUND) + + # SDL2::Mixer target + if(SDL2_MIXER_LIBRARY AND NOT TARGET SDL2::Mixer) + add_library(SDL2::Mixer UNKNOWN IMPORTED) + set_target_properties(SDL2::Mixer PROPERTIES + IMPORTED_LOCATION "${SDL2_MIXER_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_MIXER_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_net.cmake b/lib/cmake/FindSDL2_net.cmake new file mode 100644 index 0000000..74c765b --- /dev/null +++ b/lib/cmake/FindSDL2_net.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_net +------------ + +Locate SDL2_net library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::Net + The SDL2_net library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_NET_LIBRARIES, the name of the library to link against + SDL2_NET_INCLUDE_DIRS, where to find the headers + SDL2_NET_FOUND, if false, do not try to link against + SDL2_NET_VERSION_STRING - human-readable string containing the + version of SDL2_net + + + +This module responds to the following cache variables: + +:: + + SDL2_NET_PATH + Set a custom SDL2_net Library path (default: empty) + + SDL2_NET_NO_DEFAULT_PATH + Disable search SDL2_net Library in default path. + If SDL2_NET_PATH (default: ON) + Else (default: OFF) + + SDL2_NET_INCLUDE_DIR + SDL2_net headers path. + + SDL2_NET_LIBRARY + SDL2_net Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_NET_LIBRARY in your project +configuration, it means CMake did not find your SDL2_net library +(SDL2_net.dll, libsdl2_net.so, etc). Set SDL2_NET_LIBRARY to point +to your SDL2_net library, and configure again. This value is used to +generate the final SDL2_NET_LIBRARIES variable and the SDL2::Net target, +but when this value is unset, SDL2_NET_LIBRARIES and SDL2::Net does not +get created. + + +$SDL2NETDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2NETDIR used in building SDL2_net. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_net.cmake to SDL2_net (FindSDL2_net.cmake). + Add cache variables for more flexibility: + SDL2_NET_PATH, SDL2_NET_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_net.cmake module by creating a specific target: + SDL2::Net (for details, see doc above). + +Original FindSDL_net.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_NET_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_net).") + if(SDL2_net_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_NET_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_net_FIND_QUIETLY) + message(STATUS ${SDL2_NET_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_NET_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_net Library in a custom path + +set(SDL2_NET_PATH "" CACHE STRING "Custom SDL2_net Library path") + +set(_SDL2_NET_NO_DEFAULT_PATH OFF) +if(SDL2_NET_PATH) + set(_SDL2_NET_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_NET_NO_DEFAULT_PATH ${_SDL2_NET_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_net Library in default path") +unset(_SDL2_NET_NO_DEFAULT_PATH) + +set(SDL2_NET_NO_DEFAULT_PATH_CMD) +if(SDL2_NET_NO_DEFAULT_PATH) + set(SDL2_NET_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_net include directory +find_path(SDL2_NET_INCLUDE_DIR SDL_net.h + HINTS + ENV SDL2NETDIR + ENV SDL2DIR + ${SDL2_NET_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2NETDIR} + include/SDL2 include + PATHS ${SDL2_NET_PATH} + DOC "Where the SDL2_net headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_net library +find_library(SDL2_NET_LIBRARY + NAMES SDL2_net + HINTS + ENV SDL2NETDIR + ENV SDL2DIR + ${SDL2_NET_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_NET_PATH} + DOC "Where the SDL2_net Library can be found" +) + +# Read SDL2_net version +if(SDL2_NET_INCLUDE_DIR AND EXISTS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h" SDL2_NET_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_NET_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h" SDL2_NET_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_NET_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_NET_INCLUDE_DIR}/SDL_net.h" SDL2_NET_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_NET_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_NET_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MAJOR "${SDL2_NET_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_NET_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_MINOR "${SDL2_NET_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_NET_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_NET_VERSION_PATCH "${SDL2_NET_VERSION_PATCH_LINE}") + set(SDL2_NET_VERSION_STRING ${SDL2_NET_VERSION_MAJOR}.${SDL2_NET_VERSION_MINOR}.${SDL2_NET_VERSION_PATCH}) + unset(SDL2_NET_VERSION_MAJOR_LINE) + unset(SDL2_NET_VERSION_MINOR_LINE) + unset(SDL2_NET_VERSION_PATCH_LINE) + unset(SDL2_NET_VERSION_MAJOR) + unset(SDL2_NET_VERSION_MINOR) + unset(SDL2_NET_VERSION_PATCH) +endif() + +set(SDL2_NET_LIBRARIES ${SDL2_NET_LIBRARY}) +set(SDL2_NET_INCLUDE_DIRS ${SDL2_NET_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_net + REQUIRED_VARS SDL2_NET_LIBRARIES SDL2_NET_INCLUDE_DIRS + VERSION_VAR SDL2_NET_VERSION_STRING) + + +mark_as_advanced(SDL2_NET_PATH + SDL2_NET_NO_DEFAULT_PATH + SDL2_NET_LIBRARY + SDL2_NET_INCLUDE_DIR) + + +if(SDL2_NET_FOUND) + + # SDL2::Net target + if(SDL2_NET_LIBRARY AND NOT TARGET SDL2::Net) + add_library(SDL2::Net UNKNOWN IMPORTED) + set_target_properties(SDL2::Net PROPERTIES + IMPORTED_LOCATION "${SDL2_NET_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_NET_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/cmake/FindSDL2_ttf.cmake b/lib/cmake/FindSDL2_ttf.cmake new file mode 100644 index 0000000..2ab9a76 --- /dev/null +++ b/lib/cmake/FindSDL2_ttf.cmake @@ -0,0 +1,222 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +# Copyright 2019 Amine Ben Hassouna +# Copyright 2000-2019 Kitware, Inc. and Contributors +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: + +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# * Neither the name of Kitware, Inc. nor the names of Contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#[=======================================================================[.rst: +FindSDL2_ttf +------------ + +Locate SDL2_ttf library + +This module defines the following 'IMPORTED' target: + +:: + + SDL2::TTF + The SDL2_ttf library, if found. + Have SDL2::Core as a link dependency. + + + +This module will set the following variables in your project: + +:: + + SDL2_TTF_LIBRARIES, the name of the library to link against + SDL2_TTF_INCLUDE_DIRS, where to find the headers + SDL2_TTF_FOUND, if false, do not try to link against + SDL2_TTF_VERSION_STRING - human-readable string containing the + version of SDL2_ttf + + + +This module responds to the following cache variables: + +:: + + SDL2_TTF_PATH + Set a custom SDL2_ttf Library path (default: empty) + + SDL2_TTF_NO_DEFAULT_PATH + Disable search SDL2_ttf Library in default path. + If SDL2_TTF_PATH (default: ON) + Else (default: OFF) + + SDL2_TTF_INCLUDE_DIR + SDL2_ttf headers path. + + SDL2_TTF_LIBRARY + SDL2_ttf Library (.dll, .so, .a, etc) path. + + +Additional Note: If you see an empty SDL2_TTF_LIBRARY in your project +configuration, it means CMake did not find your SDL2_ttf library +(SDL2_ttf.dll, libsdl2_ttf.so, etc). Set SDL2_TTF_LIBRARY to point +to your SDL2_ttf library, and configure again. This value is used to +generate the final SDL2_TTF_LIBRARIES variable and the SDL2::TTF target, +but when this value is unset, SDL2_TTF_LIBRARIES and SDL2::TTF does not +get created. + + +$SDL2TTFDIR is an environment variable that would correspond to the +./configure --prefix=$SDL2TTFDIR used in building SDL2_ttf. + +$SDL2DIR is an environment variable that would correspond to the +./configure --prefix=$SDL2DIR used in building SDL2. + + + +Created by Amine Ben Hassouna: + Adapt FindSDL_ttf.cmake to SDL2_ttf (FindSDL2_ttf.cmake). + Add cache variables for more flexibility: + SDL2_TTF_PATH, SDL2_TTF_NO_DEFAULT_PATH (for details, see doc above). + Add SDL2 as a required dependency. + Modernize the FindSDL2_ttf.cmake module by creating a specific target: + SDL2::TTF (for details, see doc above). + +Original FindSDL_ttf.cmake module: + Created by Eric Wing. This was influenced by the FindSDL.cmake + module, but with modifications to recognize OS X frameworks and + additional Unix paths (FreeBSD, etc). +#]=======================================================================] + +# SDL2 Library required +find_package(SDL2 QUIET) +if(NOT SDL2_FOUND) + set(SDL2_TTF_SDL2_NOT_FOUND "Could NOT find SDL2 (SDL2 is required by SDL2_ttf).") + if(SDL2_ttf_FIND_REQUIRED) + message(FATAL_ERROR ${SDL2_TTF_SDL2_NOT_FOUND}) + else() + if(NOT SDL2_ttf_FIND_QUIETLY) + message(STATUS ${SDL2_TTF_SDL2_NOT_FOUND}) + endif() + return() + endif() + unset(SDL2_TTF_SDL2_NOT_FOUND) +endif() + + +# Define options for searching SDL2_ttf Library in a custom path + +set(SDL2_TTF_PATH "" CACHE STRING "Custom SDL2_ttf Library path") + +set(_SDL2_TTF_NO_DEFAULT_PATH OFF) +if(SDL2_TTF_PATH) + set(_SDL2_TTF_NO_DEFAULT_PATH ON) +endif() + +set(SDL2_TTF_NO_DEFAULT_PATH ${_SDL2_TTF_NO_DEFAULT_PATH} + CACHE BOOL "Disable search SDL2_ttf Library in default path") +unset(_SDL2_TTF_NO_DEFAULT_PATH) + +set(SDL2_TTF_NO_DEFAULT_PATH_CMD) +if(SDL2_TTF_NO_DEFAULT_PATH) + set(SDL2_TTF_NO_DEFAULT_PATH_CMD NO_DEFAULT_PATH) +endif() + +# Search for the SDL2_ttf include directory +find_path(SDL2_TTF_INCLUDE_DIR SDL_ttf.h + HINTS + ENV SDL2TTFDIR + ENV SDL2DIR + ${SDL2_TTF_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES SDL2 + # path suffixes to search inside ENV{SDL2DIR} + # and ENV{SDL2TTFDIR} + include/SDL2 include + PATHS ${SDL2_TTF_PATH} + DOC "Where the SDL2_ttf headers can be found" +) + +if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(VC_LIB_PATH_SUFFIX lib/x64) +else() + set(VC_LIB_PATH_SUFFIX lib/x86) +endif() + +# Search for the SDL2_ttf library +find_library(SDL2_TTF_LIBRARY + NAMES SDL2_ttf + HINTS + ENV SDL2TTFDIR + ENV SDL2DIR + ${SDL2_TTF_NO_DEFAULT_PATH_CMD} + PATH_SUFFIXES lib ${VC_LIB_PATH_SUFFIX} + PATHS ${SDL2_TTF_PATH} + DOC "Where the SDL2_ttf Library can be found" +) + +# Read SDL2_ttf version +if(SDL2_TTF_INCLUDE_DIR AND EXISTS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h") + file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h" SDL2_TTF_VERSION_MAJOR_LINE REGEX "^#define[ \t]+SDL_TTF_MAJOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h" SDL2_TTF_VERSION_MINOR_LINE REGEX "^#define[ \t]+SDL_TTF_MINOR_VERSION[ \t]+[0-9]+$") + file(STRINGS "${SDL2_TTF_INCLUDE_DIR}/SDL_ttf.h" SDL2_TTF_VERSION_PATCH_LINE REGEX "^#define[ \t]+SDL_TTF_PATCHLEVEL[ \t]+[0-9]+$") + string(REGEX REPLACE "^#define[ \t]+SDL_TTF_MAJOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_MAJOR "${SDL2_TTF_VERSION_MAJOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_TTF_MINOR_VERSION[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_MINOR "${SDL2_TTF_VERSION_MINOR_LINE}") + string(REGEX REPLACE "^#define[ \t]+SDL_TTF_PATCHLEVEL[ \t]+([0-9]+)$" "\\1" SDL2_TTF_VERSION_PATCH "${SDL2_TTF_VERSION_PATCH_LINE}") + set(SDL2_TTF_VERSION_STRING ${SDL2_TTF_VERSION_MAJOR}.${SDL2_TTF_VERSION_MINOR}.${SDL2_TTF_VERSION_PATCH}) + unset(SDL2_TTF_VERSION_MAJOR_LINE) + unset(SDL2_TTF_VERSION_MINOR_LINE) + unset(SDL2_TTF_VERSION_PATCH_LINE) + unset(SDL2_TTF_VERSION_MAJOR) + unset(SDL2_TTF_VERSION_MINOR) + unset(SDL2_TTF_VERSION_PATCH) +endif() + +set(SDL2_TTF_LIBRARIES ${SDL2_TTF_LIBRARY}) +set(SDL2_TTF_INCLUDE_DIRS ${SDL2_TTF_INCLUDE_DIR}) + +include(FindPackageHandleStandardArgs) + +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2_ttf + REQUIRED_VARS SDL2_TTF_LIBRARIES SDL2_TTF_INCLUDE_DIRS + VERSION_VAR SDL2_TTF_VERSION_STRING) + + +mark_as_advanced(SDL2_TTF_PATH + SDL2_TTF_NO_DEFAULT_PATH + SDL2_TTF_LIBRARY + SDL2_TTF_INCLUDE_DIR) + + +if(SDL2_TTF_FOUND) + + # SDL2::TTF target + if(SDL2_TTF_LIBRARY AND NOT TARGET SDL2::TTF) + add_library(SDL2::TTF UNKNOWN IMPORTED) + set_target_properties(SDL2::TTF PROPERTIES + IMPORTED_LOCATION "${SDL2_TTF_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${SDL2_TTF_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES SDL2::Core) + endif() +endif() diff --git a/lib/libs.cmake b/lib/libs.cmake new file mode 100644 index 0000000..9ab02c6 --- /dev/null +++ b/lib/libs.cmake @@ -0,0 +1,28 @@ +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${EXTERNAL_DIR}/cmake) + + +set(EXTERNAL_INCLUDE_DIRS "") +set(EXTERNAL_INCLUDE_LIBS "") + +# sdl +if (NOT EMSCRIPTEN) + find_package(SDL2 REQUIRED) + find_package(SDL2_mixer REQUIRED) + find_package(SDL2_image REQUIRED) + find_package(SDL2_ttf REQUIRED) + find_package(SDL2_gfx REQUIRED) + + list (APPEND EXTERNAL_INCLUDE_LIBS + SDL2::Image + SDL2::Mixer + SDL2::TTF + SDL2::GFX + SDL2::Main + ) + +endif(NOT EMSCRIPTEN) + +# entt +find_package(EnTT REQUIRED) + +list (APPEND EXTERNAL_INCLUDE_LIBS EnTT::EnTT) diff --git a/src/color/Color.cpp b/src/color/Color.cpp deleted file mode 100644 index b51a995..0000000 --- a/src/color/Color.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @file Color.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of color helper functions - * @version 0.1 - * @date 2021-03-05 - * - * @copyright Copyright (c) 2021 - * - */ -#include "color/Color.h" - -namespace afk { -namespace color { - -// Create color from RGB -Color rgb(const Uint8 r, const Uint8 g, const Uint8 b) { - return rgba(r, g, b, 255); -} - -// Create color from rgba -Color rgba(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a) { - return {r, g, b, a}; -} - -// Create color from int -Color intToColor(const Uint32 colour) { - Color tempcol; - tempcol.r = (colour >> 16) & 0xFF; - tempcol.g = (colour >> 8) & 0xFF; - tempcol.b = colour & 0xFF; - tempcol.a = 255; - return tempcol; -} - -// Convert rgb to int -Uint32 rgbToInt(const Uint8 r, const Uint8 g, const Uint8 b) { - return rgbaToInt(r, g, b, 255); -} - -// Convert rgba to int -Uint32 rgbaToInt(const Uint8 r, const Uint8 g, const Uint8 b, const Uint8 a) { - return (Uint32)((a << 24) + (r << 16) + (g << 8) + (b << 0)); -} - -// Convert color to int -Uint32 colorToInt(const Color colour) { - return rgbaToInt(colour.r, colour.g, colour.b, colour.a); -} - -} // namespace color -} // namespace afk diff --git a/src/entities/GameObject.cpp b/src/entities/GameObject.cpp deleted file mode 100644 index e85c4aa..0000000 --- a/src/entities/GameObject.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/** - * @file GameObject.h - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of GameObject class - * @version 0.1 - * @date 2017-01-03 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/GameObject.h" - -#include "scene/Scene.h" - -#include - -namespace afk { - -// Set incrementing index count -ObjId GameObject::index = 1; - -// Constructor -GameObject::GameObject(Scene& scene, const float x, const float y, const int z) - : id(GameObject::index), - scene(scene), - x(x), - y(y), - z(z), - height(0), - width(0), - angle(0.0f), - visible(true), - enabled(true), - hooked(true), - last_x(0), - last_y(0), - parent_id(0) { - GameObject::index += 1; -} - -// Destructor -GameObject::~GameObject() {} - -// Update -void GameObject::update(Uint32 delta) { - (void)delta; -} - -// Update -void GameObject::updateInternal() { - // Update delta position - last_x = x; - last_y = y; - - // Parent functions - if (parent_id != 0) { - // Autoremove if parent is dead - try { - auto& parent = scene.get(parent_id); - - // Set hooked state - hooked = parent.getHooked(); - - // Set position - x += parent.x - parent.last_x; - y += parent.y - parent.last_y; - - } catch (const KeyLookupException&) { - scene.remove(id); - } - } - - // Colliders - std::remove_if(colliders.begin(), colliders.end(), - [&](const auto& obj_id) { return !scene.has(obj_id); }); - for (auto& obj_id : colliders) { - collide(scene.get(obj_id)); - } -} - -// Draw -void GameObject::draw() {} - -// Add child -void GameObject::setParent(const ObjId parent_id) { - this->parent_id = parent_id; -} - -// Add a collider with a game object -void GameObject::addCollider(const ObjId obj_id) { - colliders.push_back(obj_id); -} - -// Remove a collider with a game object -void GameObject::removeCollider(const ObjId obj_id) { - auto it = std::find(colliders.begin(), colliders.end(), obj_id); - if (it != colliders.end()) { - colliders.erase(it); - } -} - -// Is colliding with game object -bool GameObject::isColliding(const GameObject& other) { - return x < other.x + other.width && x + width > other.x && - y < other.y + other.height && y + height > other.y; -} - -// Collide game objects -bool GameObject::collide(GameObject& other) { - bool colliding = isColliding(other); - - if (colliding) { - this->onCollide(other); - other.onCollide(*this); - } - - return colliding; -} - -// On collide can be overriden -void GameObject::onCollide(GameObject& other) { - (void)(other); -} - -// Set the size of game object in pixels -void GameObject::setSize(const unsigned int width, const unsigned int height) { - this->width = width; - this->height = height; -} - -// Set the position of game object in pixels -void GameObject::setPosition(const float x, const float y) { - this->x = x; - this->y = y; -} - -// Set angle of game object in degrees -void GameObject::setAngle(const float angle) { - this->angle = angle; -} - -// Set visibility -void GameObject::setVisible(const bool visible) { - this->visible = visible; -} - -// Set enabled -void GameObject::setEnabled(const bool enabled) { - this->enabled = enabled; -} - -// Set hooked -void GameObject::setHooked(const bool hooked) { - this->hooked = hooked; -} - -// Get z index -int GameObject::getWidth() const { - return this->width; -} - -// Get z index -int GameObject::getHeight() const { - return this->height; -} - -// Get z index -float GameObject::getX() const { - return this->x; -} - -// Get z index -float GameObject::getY() const { - return this->y; -} - -// Get z index -int GameObject::getZ() const { - return this->z; -} - -// Get z index -float GameObject::getAngle() const { - return this->angle; -} - -// Get visibility -bool GameObject::getVisible() const { - return this->visible; -} - -// Get enabled -bool GameObject::getEnabled() const { - return this->enabled; -} - -// Get hooked -bool GameObject::getHooked() const { - return this->hooked; -} - -} // namespace afk diff --git a/src/entities/Particle.cpp b/src/entities/Particle.cpp deleted file mode 100644 index bc80204..0000000 --- a/src/entities/Particle.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @file Particle.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Particle - * @version 0.1 - * @date 2021-03-08 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/Particle.h" -#include "common/math.h" -#include "scene/Scene.h" - -namespace afk { - -// Constructor -Particle::Particle(Scene& scene, - const float x, - const float y, - const float z, - const ParticleType type) - : Sprite(scene, x, y, z), - type(type), - start_size(1), - end_size(1), - velocity_x(0), - velocity_y(0), - acceleration_x(0), - acceleration_y(0), - age(0), - lifespan(1000), - start_color(color::black), - end_color(color::black) {} - -// Logic -void Particle::update(Uint32 delta) { - if (dead()) { - return; - } - - // Update velocity - x += (velocity_x + acceleration_x * age) / 1000 * delta; - y += (velocity_y + acceleration_y * age) / 1000 * delta; - - // Its dead - this->age += 4.0f; -} - -// Draw -void Particle::draw() { - if (dead()) { - return; - } - - float life_percent = age / lifespan; - - // Lerp size - float size = math::lerp(start_size, end_size, life_percent); - - // Lerp color - Uint8 r = math::lerp(start_color.r, end_color.r, life_percent); - Uint8 g = math::lerp(start_color.g, end_color.g, life_percent); - Uint8 b = math::lerp(start_color.b, end_color.b, life_percent); - Uint8 a = math::lerp(start_color.a, end_color.a, life_percent); - color::Color color = {r, g, b, a}; - - // Switch over type - switch (type) { - case ParticleType::SQUARE: - primitives::rectfill(x, y, size, size, color); - break; - case ParticleType::CIRCLE: - primitives::circle(x, y, size, color); - break; - case ParticleType::PIXEL: - primitives::pixel(x, y, color); - break; - case ParticleType::IMAGE: - texture.drawEx(x, y, size, size, 0); - default: - break; - } -} - -// Set the size of the particle in pixels -void Particle::setSize(const float size) { - this->start_size = size; - this->end_size = size; -} - -// Set the size of particle over lifespan -void Particle::setSize(const float start_size, const float end_size) { - this->start_size = start_size; - this->end_size = end_size; -} - -// Set the velocity of particle -void Particle::setVelocity(const float x, const float y) { - this->velocity_x = x; - this->velocity_y = y; -} - -// Set the accleration of particle -void Particle::setAcceleration(const float x, const float y) { - this->acceleration_x = x; - this->acceleration_y = y; -} - -// Set the lifespan of particle in ms, start dead -void Particle::setLifespan(const float lifespan) { - this->lifespan = lifespan; - this->age = lifespan; -} - -// Set the particle color -void Particle::setColor(const color::Color& color) { - this->start_color = color; - this->end_color = color; -} - -// Set the particle color over lifespan -void Particle::setColor(const color::Color& start_color, - const color::Color& end_color) { - this->start_color = start_color; - this->end_color = end_color; -} - -// Reest age -void Particle::reset() { - this->age = 0; -} - -// Check if dead -bool Particle::dead() { - return this->age >= this->lifespan; -} - -} // namespace afk diff --git a/src/entities/ParticleEmitter.cpp b/src/entities/ParticleEmitter.cpp deleted file mode 100644 index 6ef8734..0000000 --- a/src/entities/ParticleEmitter.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @file ParticleEmitter.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of a particle emitter. - * and configured. - * @version 0.1 - * @date 2021-03-06 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ParticleEmitter.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "random/RandomGenerator.h" -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -// Constructor -ParticleEmitter::ParticleEmitter(Scene& scene, - const float x, - const float y, - const int z, - const int frequency) - : GameObject(scene, x, y, z), - emitting(true), - frequency(frequency), - current_tick(0) {} - -// Draw -void ParticleEmitter::draw() { - for (auto& particle : particles) { - particle.draw(); - } -} - -// Update -void ParticleEmitter::update(Uint32 delta) { - if (emitting) { - current_tick += delta; - } - - for (auto& particle : particles) { - particle.update(delta); - - if (particle.dead() && emitting && current_tick >= frequency) { - current_tick -= frequency; - particle.reset(); - particle.setPosition(Random::randomInt(x, x + width), - Random::randomInt(y, y + width)); - } - } -} - -// Add -void ParticleEmitter::addParticle(const Particle& particle, - const Uint32 count) { - for (Uint32 i = 0; i < count; i++) { - particles.push_back(Particle(particle)); - } -} - -// Enable -void ParticleEmitter::enable() { - this->emitting = true; -} - -// Disable -void ParticleEmitter::disable() { - this->emitting = false; -} - -} // namespace afk diff --git a/src/entities/Sprite.cpp b/src/entities/Sprite.cpp deleted file mode 100644 index 41718f5..0000000 --- a/src/entities/Sprite.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @file Sprite.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Sprite - * @version 0.1 - * @date 2020-10-20 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/Sprite.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" - -namespace afk { - -// Constructor -Sprite::Sprite(Scene& scene, const float x, const float y, const int z) - : GameObject(scene, x, y, z) {} - -// Constructor -Sprite::Sprite(Scene& scene, - const std::string& texture, - const float x, - const float y, - const int z) - : Sprite(scene, x, y, z) { - setTexture(texture); -} - -// Destructor -Sprite::~Sprite() {} - -void Sprite::setTexture(const std::string& texture) { - this->texture = scene.assets.getImage(texture); - this->width = this->texture.getWidth(); - this->height = this->texture.getHeight(); -} - -// Draw -void Sprite::draw() { - // Draw image - texture.drawEx(x, y, width, height, angle); - - // Draw bounding box - if (Services::getConfigService().get("debug", false)) { - primitives::rect(x, y, width, height, color::red); - } -} - -} // namespace afk diff --git a/src/entities/ui/Button.cpp b/src/entities/ui/Button.cpp deleted file mode 100644 index 403bbce..0000000 --- a/src/entities/ui/Button.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @file Button.cpp - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief Implementation of Button - * @version 0.1 - * @date 2017-04-11 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/Button.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -const int DEFAULT_HEIGHT = 20; -const int DEFAULT_WIDTH = 20; -const int DEFAULT_PADDING = 5; - -// Ctor -Button::Button(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z) { - width = DEFAULT_WIDTH; - height = DEFAULT_HEIGHT; -} - -// Draw button -void Button::draw() { - // Draw button background - primitives::rectfill(x, y, width, height, color::white); - - // Draw button border - primitives::rect(x, y, width, height, color::black); - - // Text - font.draw(x + DEFAULT_PADDING, y + DEFAULT_PADDING, text, color::black, - text_align); -} - -// Override text setter -void Button::sizeToText() { - if (!font.exists()) { - return; - } - height = font.getHeight() + DEFAULT_PADDING * 2; - width = font.getWidth(text) + DEFAULT_PADDING * 2; -} - -} // namespace afk diff --git a/src/entities/ui/Checkbox.cpp b/src/entities/ui/Checkbox.cpp deleted file mode 100644 index 01f4f74..0000000 --- a/src/entities/ui/Checkbox.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file Checkbox.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of UI Checkbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#include - -#include "entities/ui/Checkbox.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" -#include "services/Services.h" - -const int DEFAULT_HEIGHT = 20; -const int DEFAULT_WIDTH = 20; - -namespace afk { - -// Ctor -Checkbox::Checkbox(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z), checked(false), onCheck(nullptr) { - this->height = DEFAULT_HEIGHT; - this->width = DEFAULT_WIDTH; -} - -// Draw checkbox -void Checkbox::draw() { - // Draw checkbox background - primitives::rectfill(x, y, width, height, color::white); - - // Draw checkbox border - primitives::rect(x, y, width, height, color::black); - - if (checked) { - primitives::rectfill(x + width / 4, y + height / 4, width - width / 2, - height - height / 2, color::black); - } - - // Draw text label - font.draw(x + width + 10, y + height - font.getHeight(), text, color::black); -} - -// Check checkbox stat -bool Checkbox::getChecked() const { - return checked; -} - -// Set checked state -void Checkbox::setChecked(const bool checked) { - this->checked = checked; -} - -// Set on click -void Checkbox::setOnCheck(std::function func) { - this->onCheck = func; -} - -// On click interceptor -void Checkbox::handleOnClick() { - checked = !checked; - if (onCheck) { - onCheck(checked); - } - if (onClick) { - onClick(); - } -} - -} // namespace afk diff --git a/src/entities/ui/Image.cpp b/src/entities/ui/Image.cpp deleted file mode 100644 index bd9ce9f..0000000 --- a/src/entities/ui/Image.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file Image.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Texturable ui element - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/Image.h" - -#include "scene/Scene.h" - -namespace afk { - -// Detailed constructor -Image::Image(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z) {} - -// Draw image -void Image::draw() { - texture.drawEx(x, y, width, height, angle); -} - -void Image::setTexture(const std::string& texture) { - this->texture = scene.assets.getImage(texture); - this->width = this->texture.getWidth(); - this->height = this->texture.getHeight(); -} - -} // namespace afk diff --git a/src/entities/ui/Inputbox.cpp b/src/entities/ui/Inputbox.cpp deleted file mode 100644 index 974f718..0000000 --- a/src/entities/ui/Inputbox.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @file Inputbox.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of UI Inputbox - * @version 0.1 - * @date 2021-03-12 - * - * @copyright Copyright (c) 2021 - * - */ -#include -#include - -#include "entities/ui/Inputbox.h" - -#include "color/Color.h" -#include "primitives/Primitives.h" -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -const int NUMBER_OFFSET = 19; -const int LOWER_OFFSET = 93; -const int UPPER_OFFSET = 61; - -const int DEFAULT_HEIGHT = 20; -const int DEFAULT_WIDTH = 100; -const int DEFAULT_PADDING = 5; - -// Ctor -Inputbox::Inputbox(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z), iter(text.end()), onChange(nullptr) { - this->height = DEFAULT_HEIGHT; - this->width = DEFAULT_WIDTH; -} - -// Draw checkbox -void Inputbox::draw() { - // Draw checkbox background - primitives::rectfill(x, y, width, height, color::white); - - // Draw checkbox border - primitives::rect(x, y, width, height, color::black); - - // Focus border - if (id == UIElement::focused) { - primitives::rect(x + 1, y + 1, width - 2, height - 2, color::black); - } - - // Draw text label - font.draw(x + DEFAULT_PADDING, y + height - font.getHeight(), text, - color::black); - - // Draw the caret - std::string edit_pos = text.substr(0, std::distance(text.begin(), iter)); - int line_x = font.getWidth(edit_pos); - - afk::primitives::line(line_x + x + DEFAULT_PADDING, y + 2, - line_x + x + DEFAULT_PADDING, y + height - 2, - afk::color::black); -} - -// Update loop -void Inputbox::update(Uint32 delta) { - // Update parent - UIElement::update(delta); - - // Ensure focused - if (id != UIElement::focused) { - return; - } - - int lastKeyInt = scene.input.lastKeyPressed(); - afk::Keys lastKey = static_cast(lastKeyInt); - bool shiftDown = scene.input.keyDown(afk::Keys::LSHIFT) || - scene.input.keyDown(afk::Keys::RSHIFT); - bool ctrlDown = scene.input.keyDown(afk::Keys::LCTRL) || - scene.input.keyDown(afk::Keys::RCTRL); - - // Ignore blank key - if (lastKey == afk::Keys::UNKNOWN) { - return; - } - - // Letters - if (lastKey >= afk::Keys::A && lastKey <= afk::Keys::Z) { - if (shiftDown) { - iter = text.insert(iter, lastKeyInt + UPPER_OFFSET); - } else { - iter = text.insert(iter, lastKeyInt + LOWER_OFFSET); - } - std::advance(iter, 1); - } - - // Numbers - else if (lastKey >= afk::Keys::ONE && lastKey <= afk::Keys::NINE) { - iter = text.insert(iter, lastKeyInt + NUMBER_OFFSET); - std::advance(iter, 1); - } - - // Special zero case - else if (lastKey == afk::Keys::ZERO) { - iter = text.insert(iter, 48); - std::advance(iter, 1); - } - - // Space - else if (lastKey == afk::Keys::SPACE) { - iter = text.insert(iter, 32); - std::advance(iter, 1); - } - - // Backspace - else if (lastKey == afk::Keys::BACKSPACE && iter != text.begin()) { - if (ctrlDown) { - iter = text.erase(text.begin(), iter); - } else { - std::advance(iter, -1); - iter = text.erase(iter); - } - } - - // Delete - else if (lastKey == afk::Keys::DELETE && iter != text.end()) { - iter = text.erase(iter); - } - - // Right - else if (lastKey == afk::Keys::RIGHT && iter != text.end()) { - std::advance(iter, 1); - } - - // Left - else if (lastKey == afk::Keys::LEFT && iter != text.begin()) { - std::advance(iter, -1); - } -} - -// Set text -void Inputbox::setText(const std::string& text) { - this->text = text; - iter = this->text.end(); -} - -// Set on click -void Inputbox::setOnChange(std::function func) { - this->onChange = func; -} - -} // namespace afk diff --git a/src/entities/ui/Label.cpp b/src/entities/ui/Label.cpp deleted file mode 100644 index 5bf552a..0000000 --- a/src/entities/ui/Label.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * @file Label.cpp - * @author - * Allan Legemaate (alegemaate@gmail.com) - * Danny Van Stemp (dannyvanstemp@gmail.com) - * @brief Implementation of Label class - * @version 0.1 - * @date 2018-11-25 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/Label.h" - -#include "color/Color.h" - -namespace afk { - -// Detailed constructor -Label::Label(Scene& scene, const float x, const float y, const int z) - : UIElement(scene, x, y, z) {} - -// Draw label -void Label::draw() { - // Text - font.draw(x, y, text, color::black, text_align); -} - -} // namespace afk diff --git a/src/entities/ui/UIElement.cpp b/src/entities/ui/UIElement.cpp deleted file mode 100644 index 0380579..0000000 --- a/src/entities/ui/UIElement.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file UIElement.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of UIElement - * @version 0.1 - * @date 2020-11-01 - * - * @copyright Copyright (c) 2021 - * - */ -#include "entities/ui/UIElement.h" - -#include -#include "scene/Scene.h" -#include "services/Services.h" - -namespace afk { - -// Static -ObjId UIElement::focused = 0; - -// Constructor -UIElement::UIElement(Scene& scene, const float x, const float y, const int z) - : GameObject(scene, x, y, z), - text_align(TextAlign::LEFT), - text(""), - onClick(nullptr) {} - -// Set font of element -void UIElement::setFont(const std::string& font) { - if (font != "") { - this->font = Services::getAssetService().getFont(font); - } -} - -// Set text align -void UIElement::setTextAlign(const TextAlign align) { - text_align = align; -} - -// Set text of element -void UIElement::setText(const std::string& text) { - this->text = text; -} - -// Draw -void UIElement::draw() {} - -// Update -void UIElement::update(Uint32 delta) { - InputService& input = Services::getInputService(); - - if (input.mousePressed(MouseButtons::LEFT)) { - bool is_colliding = input.mouseX() < x + width && - input.mouseY() < y + height && input.mouseX() > x && - input.mouseY() > y; - - if (is_colliding) { - UIElement::focused = id; - handleOnClick(); - } - } -} - -// Set on click -void UIElement::setOnClick(std::function func) { - this->onClick = func; -} - -// Get text -std::string UIElement::getText() const { - return text; -} - -// Intermediate on click hanlder -void UIElement::handleOnClick() { - if (onClick) { - onClick(); - } -} - -} // namespace afk diff --git a/src/random/RandomGenerator.cpp b/src/random/RandomGenerator.cpp deleted file mode 100644 index accb412..0000000 --- a/src/random/RandomGenerator.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @file RandomGenerator.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Random class methods - * @version 0.1 - * @date 2020-08-11 - * - * @copyright Copyright (c) 2021 - * - */ -#include "random/RandomGenerator.h" - -#include - -namespace afk { - -// Init generator -std::mt19937 Random::rng = std::mt19937(std::random_device{}()); - -// Random Float -float Random::randomFloat(const float min, const float max) { - std::uniform_real_distribution float_dist{min, max}; - return float_dist(rng); -} - -// Random Int -int Random::randomInt(const int min, const int max) { - std::uniform_int_distribution int_dist{min, max}; - return int_dist(rng); -} - -} // namespace afk diff --git a/src/scene/Scene.cpp b/src/scene/Scene.cpp deleted file mode 100644 index 15f8fe5..0000000 --- a/src/scene/Scene.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/** - * @file Scene.cpp - * @author Allan Legemaate (alegemaate@gmail.com) - * @brief Implementation of Scene class - * @version 0.1 - * @date 2016-12-30 - * - * @copyright Copyright (c) 2021 - * - */ -#include "scene/Scene.h" - -#include - -#include "common/Exceptions.h" -#include "entities/GameObject.h" - -namespace afk { - -// Constructor -Scene::Scene() - : audio(afk::Services::getAudioService()), - logger(afk::Services::getLoggingService()), - display(afk::Services::getDisplayService()), - assets(afk::Services::getAssetService()), - input(afk::Services::getInputService()), - scene(afk::Services::getSceneService()), - config(afk::Services::getConfigService()), - need_sort(false) {} - -// Internal cleanup (on switch scene) -void Scene::stopInternal() { - update_pool.clear(); - lookup_map.clear(); -} - -// Draw internal method -void Scene::draw() { - // Draw - for (auto& obj : update_pool) { - if (obj->getVisible() && obj->getHooked()) { - obj->draw(); - } - } -} - -// Internal update method -void Scene::update(Uint32 delta) { - // Update all (we need to indices here since updates can add objects) - for (Uint32 i = 0; i < update_pool.size(); ++i) { - if (update_pool.at(i)->getEnabled() && update_pool.at(i)->getHooked()) { - update_pool.at(i)->update(delta); - } - } - - // Internal updates - for (auto& obj : update_pool) { - obj->updateInternal(); - } - - // Remove any game objects that need to be cleaned up - for (auto& id : remove_pool) { - // Get vector index - auto index = lookup_map.at(id); - - // Erase game object - update_pool.erase(update_pool.begin() + index); - - // Remove from lookup map - lookup_map.erase(id); - - // We will need a sort after this - need_sort = true; - } - - // Clear remove pool - remove_pool.clear(); - - // Sort flag toggled - if (need_sort) { - // Z sort, use defined < operator - std::sort(update_pool.begin(), update_pool.end(), - [](auto& obj1, auto& obj2) -> bool { return *obj1 < *obj2; }); - - // Repopulate lookup map - for (unsigned int i = 0; i < update_pool.size(); i++) { - lookup_map[update_pool.at(i)->id] = i; - } - - // Done sorting - need_sort = false; - } -} - -// Remove game object from scene -void Scene::remove(const ObjId id) { - remove_pool.push_back(id); -} - -// Check if obj id exists in scene -bool Scene::has(const ObjId id) { - return lookup_map.count(id) == 1; -} - -} // namespace afk