├── .gitignore ├── .gitmodules ├── .travis.yml ├── CMakeLists.txt ├── CODESTYLE.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── deps └── json │ └── json.hpp ├── res ├── fonts │ └── BPDots │ │ ├── BPdots.otf │ │ ├── BPdotsBold.otf │ │ ├── BPdotsDiamond.otf │ │ ├── BPdotsDiamondBold.otf │ │ ├── BPdotsDiamondLight.otf │ │ ├── BPdotsLight.otf │ │ ├── BPdotsMinus.otf │ │ ├── BPdotsMinusBold.otf │ │ ├── BPdotsPlus.otf │ │ ├── BPdotsPlusBold.otf │ │ ├── BPdotsSquare.otf │ │ ├── BPdotsSquareBold.otf │ │ ├── BPdotsSquareLight.otf │ │ ├── BPdotsVertical.otf │ │ ├── BPdotsVerticalBold.otf │ │ └── Creative Commons Attribution-No Derivative Works.txt ├── gameobjects │ ├── bd.json │ ├── fps.json │ ├── grass.json │ ├── mouse.json │ └── player.json └── txrs │ ├── animations │ └── player │ │ └── Soldier.png │ ├── building.png │ ├── crosshair.png │ ├── grass.png │ ├── player.png │ └── sand.png └── src ├── Game.cpp ├── Game.h ├── gameobject ├── GameObject.cpp ├── GameObject.h ├── GameObjectFactory.cpp ├── GameObjectFactory.h └── components │ ├── AnimationComponent.cpp │ ├── AnimationComponent.h │ ├── CameraComponent.cpp │ ├── CameraComponent.h │ ├── ColliderAABBComponent.cpp │ ├── ColliderAABBComponent.h │ ├── Component.h │ ├── FPSComponent.cpp │ ├── FPSComponent.h │ ├── MouseComponent.cpp │ ├── MouseComponent.h │ ├── PlayerComponent.cpp │ ├── PlayerComponent.h │ ├── RendererComponent.cpp │ ├── RendererComponent.h │ ├── RigidBodyComponent.cpp │ ├── RigidBodyComponent.h │ ├── TestComponent.cpp │ ├── TestComponent.h │ ├── TransformComponent.cpp │ └── TransformComponent.h ├── main.cpp ├── resource ├── ResourceHolder.cpp ├── ResourceHolder.h └── ResourceManager.h ├── state ├── GameState.h ├── PlayingState.cpp └── PlayingState.h ├── systems ├── Collider │ ├── AABBCollider.cpp │ ├── AABBCollider.h │ ├── SAT_Collider.cpp │ └── SAT_Collider.h ├── ColliderSpace.cpp └── ColliderSpace.h └── util ├── DebugRenderer.cpp ├── DebugRenderer.h ├── FileUtil.cpp ├── FileUtil.h ├── Mathf.h ├── NonCopyable.h ├── NonMoveable.h ├── Renderer.cpp └── Renderer.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | # CMake build folder 35 | build/ 36 | .vs 37 | <<<<<<< HEAD 38 | ======= 39 | 40 | #CodeBlocks 41 | *.layout 42 | *.depend 43 | *.cbp 44 | bin/ 45 | obj/ 46 | >>>>>>> 9990422359331f2330abfad091c9c755b5d21515 47 | 48 | \.vscode/ 49 | 50 | \.idea/ 51 | 52 | cmake-build-debug/ 53 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/SFML"] 2 | path = deps/SFML 3 | url = https://github.com/SFML/SFML 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: cpp 2 | 3 | before_install: 4 | - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y 5 | - sudo apt-get update -qq 6 | - sudo apt-get install g++-6 7 | - export CXX="g++-6" CC="gcc-6" 8 | 9 | before_script: 10 | - sudo apt-get install -y libudev-dev libjpeg62-dev libsndfile1-dev libglew1.5 libglew1.5-dev libfreetype6 libjpeg-turbo8 libjpeg8 libopenal-data libopenal1 libopenal-dev libxrandr2 libxrender1 libsoil1 libxrandr-dev 11 | 12 | script: mkdir build && cd build && cmake .. && make -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Specify the minimum CMAKE version required 2 | cmake_minimum_required(VERSION 2.8) 3 | 4 | # Your project's name 5 | project(Zombie-Shooter) 6 | 7 | # Add all files from the source/ folder to CMake 8 | file(GLOB_RECURSE SRC 9 | "src/*.cpp" 10 | "src/*.h" 11 | "src/*.hpp" 12 | ) 13 | 14 | file(GLOB_RECURSE SRC_GAMEOBJECT 15 | "src/gameobject/*.cpp" 16 | "src/gameobject/*.h" 17 | "src/gameobject/*.hpp" 18 | ) 19 | 20 | file(GLOB_RECURSE SRC_RESOURCE 21 | "src/resource/*.cpp" 22 | "src/resource/*.h" 23 | "src/resouce/*.hpp" 24 | ) 25 | 26 | file(GLOB_RECURSE SRC_STATE 27 | "src/state/*.cpp" 28 | "src/state/*.h" 29 | "src/state/*.hpp" 30 | ) 31 | 32 | file(GLOB_RECURSE SRC_SYSTEMS 33 | "src/systems/*.cpp" 34 | "src/systems/*.h" 35 | "src/systems/*.hpp" 36 | ) 37 | 38 | file(GLOB_RECURSE SRC_UTIL 39 | "src/util/*.cpp" 40 | "src/util/*.h" 41 | "src/util/*.hpp" 42 | ) 43 | 44 | # Define the executable 45 | add_executable(${PROJECT_NAME} ${SRC} ${SRC_GAMEOBJECT} ${SRC_RESOURCE} ${SRC_STATE} ${SRC_SYSTEMS} ${SRC_UTIL}) 46 | 47 | #Define the filters 48 | source_group("gameobject" FILES ${SRC_GAMEOBJECT}) 49 | source_group("resources" FILES ${SRC_RESOURCE}) 50 | source_group("state" FILES ${SRC_STATE}) 51 | source_group("system" FILES ${SRC_SYSTEMS}) 52 | source_group("util" FILES ${SRC_UTIL}) 53 | 54 | # Copy res folder to executable on build 55 | add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD 56 | COMMAND ${CMAKE_COMMAND} -E copy_directory 57 | ${CMAKE_SOURCE_DIR}/res $/res) 58 | 59 | # JSON library 60 | include_directories(deps/json) 61 | 62 | # SFML 63 | add_definitions(-DSFML_STATIC) 64 | set(SFML_BUILD_DOC OFF CACHE BOOL "" FORCE) 65 | set(SFML_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) 66 | set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) 67 | set(CMAKE_BUILD_TYPE Debug) 68 | add_subdirectory(deps/SFML) 69 | include_directories(deps/SFML/include) 70 | target_link_libraries(${PROJECT_NAME} sfml-network sfml-graphics sfml-window sfml-system sfml-audio) 71 | 72 | # GCC Arguments 73 | if(CMAKE_COMPILER_IS_GNUXX) 74 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wno-pmf-conversions") 75 | elseif(CMAKE_COMPILER_IS_MSVC) 76 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-pmf-conversions") 77 | endif(CMAKE_COMPILER_IS_GNUXX) 78 | 79 | set_target_properties(${PROJECT_NAME} PROPERTIES 80 | CXX_STANDARD 14 81 | CXX_STANDARD_REQUIRED ON 82 | CXX_EXTENSIONS OFF 83 | ) 84 | -------------------------------------------------------------------------------- /CODESTYLE.md: -------------------------------------------------------------------------------- 1 | # Code Style 2 | 3 | ## Naming conventions 4 | 5 | * File names: PascalCase 6 | * Folder names: underscore_lower_case 7 | 8 | * Class names: PascalCase 9 | * Struct names: PascalCase 10 | * Class members: m_camelCase 11 | 12 | * Functions: camelCase 13 | * Local variables: camelCase 14 | 15 | * Namespaces: PascalCase 16 | 17 | * Constants: SCREAMING_SNAKE_CASE 18 | 19 | ## Class Style 20 | 21 | ```C++ 22 | class Foo 23 | { 24 | public: 25 | Foo(); 26 | 27 | void foo(); 28 | void bar(); 29 | 30 | protected: 31 | void barFoo(); 32 | 33 | private: 34 | void fooBar(); 35 | 36 | int m_number; 37 | }; 38 | ``` 39 | 40 | * Public functions and members at top, protected in middle, private at bottom 41 | * Notice a space between the final class member/function and the next accessor! 42 | 43 | * Private members must be prefixed with "m_" 44 | 45 | * Initilzation lists: 46 | 47 | ```C++ 48 | Foo::Foo(int x, int y) 49 | : m_x (x) 50 | , m_y (y) { } 51 | ``` 52 | 53 | ## Namespaces 54 | 55 | * NO `using namespace std;` Your pull request will be denied if that is included. 56 | * Namespaces should be PascalCase 57 | * Nested namespaces: 58 | 59 | ```C++ 60 | namespace Foo { 61 | namespace Bar 62 | { 63 | void codeGoesHere() 64 | { 65 | 66 | } 67 | }} 68 | ``` 69 | 70 | ## Includes 71 | * All headers should have header guards (#pragma once) 72 | 73 | * Includes in files should be in the following order: 74 | * "h file corresponding to this cpp file (if applicable)", 75 | * "headers from the same component", 76 | * "headers from other components", 77 | * "headers from SFML" 78 | * "system headers and standard lib headers" 79 | 80 | * Example: 81 | ``` 82 | #include "System.h" 83 | 84 | #include "../component/Components.h" 85 | #include "../Entity.h" 86 | 87 | #include "../../maths/MathFunctions.h" 88 | #include "../../util/json.hpp" 89 | 90 | #include 91 | 92 | #include 93 | #include 94 | ``` 95 | 96 | ## Constants 97 | * Do not use C-Style "defines" for constants. 98 | * Use constexpr! It is compile-time determined just like #define is, no excuses! 99 | * Functions can be marked as "constexpr" as well. 100 | 101 | ## Functions 102 | 103 | * Primitives can be passed by value, or reference 104 | * Objects pass as either const reference (or reference), and NEVER BY VALUE 105 | * Indent style: 106 | 107 | ```C++ 108 | bool functionName(int arg1, const std::string& arg2) 109 | { 110 | if (arg1 > 5) 111 | { 112 | std::cout << arg2 << "\n"; 113 | return true; 114 | } 115 | return false; 116 | } 117 | ``` 118 | 119 | * For setter functions, use R-Value references and move scematics if you can(eg) 120 | ```C++ 121 | void Foo:setString(std::string&& str) 122 | { 123 | m_string = std::move(str); 124 | } 125 | ``` 126 | 127 | or, plain old "const reference" 128 | 129 | However, if the setter is for an object <4 bytes in size (or 8 if your compiler is 64 bit), then pass by value 130 | 131 | ## Slash 132 | 133 | * Don't use the `\`, it can cause errors on Linux. Correct use: 134 | ```C++ 135 | #include 136 | ``` 137 | 138 | * This goes for strings as file paths too! 139 | 140 | ```C++ 141 | std::string filePath = "forward/slashes/so/it/works/cross/platform.png" 142 | ``` 143 | 144 | ## Pointers 145 | 146 | * Please prefer unique pointers to raw owning pointers 147 | ```C++ 148 | int* x = new int(5); //No! 149 | auto y = std::make_unique(5) //Yes! 150 | ``` 151 | 152 | * If you have to use "new" and especially "malloc()", then you are probably doing something wrong. 153 | * Only case raw pointers are fine is if they are non-owning pointers. 154 | 155 | ## Enums 156 | 157 | * Use enum class, not regular enums! 158 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | This document shows how you can get started with contributing to this community 4 | project. 5 | 6 | If you want to merge your code into the project, you should join our Discord 7 | server. We continuously discuss ideas and things to do - so just come up, ask 8 | for help, and they will give you a task. 9 | 10 | You should check out some Git Tutorials, as you will need to know about 11 | cloning, commiting, branching, conflict resolving and basic git commands. 12 | 13 | # Getting started 14 | 15 | First, install Git on your computer. You can use the GitHub App installer, but 16 | we won't use the GitHub App for our Git stuff. The GitHub App Installer 17 | installs some command line tools we need to use. Don't be alarmed about the 18 | complexity of these! Once you get the hang of it, things will make sense. 19 | Pinky promise! 20 | 21 | As a second step: fork the project. The development team has 22 | decided to use forks to keep everything clean. You can fork the project by 23 | clicking the `fork` button on the upper right side of the GitHub page. 24 | 25 | After that, clone the fork. Open the Git Shell and navigate to the folder you 26 | want the project to be in. Copy the clone URL from the address bar of the 27 | fork, or look it up on the GitHub UI. 28 | 29 | Next, enter this in the shell: 30 | 31 | ``` 32 | $ git clone 33 | ``` 34 | 35 | Git should now download the fork. When finished downloading, change the current 36 | directory to the repository's root: 37 | ``` 38 | $ cd ZombieGame 39 | ``` 40 | 41 | There is only a slight problem now: how can we update our fork if someone makes 42 | a change to the main repository? 43 | 44 | The first step to this is to add another remote to our local repository: 45 | ``` 46 | $ git remote add upstream https://github.com/HopsonCommunity/ZombieGame 47 | ``` 48 | 49 | Now the original repository where we forked from has been added as another 50 | remote. That means we can pull all the changes from the original repository 51 | into our own local repository to keep it up-to-date with the main development 52 | repository. 53 | 54 | # Working on a feature 55 | If you are working on a feature, create a separate branch for it. This way 56 | all your work will be separated from the everyone else's work and you'll keep 57 | your repository clean, avoiding unnecessary conflicts. 58 | 59 | For example, you're implementing an inventory system: 60 | 61 | 1. First, you need to create a branch for it and work there. 62 | ``` 63 | $ git checkout -b inventory 64 | ``` 65 | 66 | 2. After that, you create some files and commit them. 67 | ``` 68 | $ git add . 69 | $ git commit -m "Implemented an inventory system" 70 | ``` 71 | 72 | 3. Meanwhile, other programmers made some changes and merged them into the 73 | main repository. The best way of doing that is to update the `master` 74 | branch, which is only for the code on the upstream and then 75 | [`rebase`](https://git-scm.com/docs/git-rebase) changes from `master` into 76 | the `inventory` branch: 77 | 78 | On branch `inventory`: 79 | ``` 80 | $ git checkout master # change the branch to master 81 | $ git pull upstream master # pull the changes 82 | $ git checkout inventory # go to inventory branch 83 | $ git rebase master # move all the new commits from the master branch 84 | # before your current work 85 | ``` 86 | 87 | Or, if you don't need new changes in your master right now and don't want 88 | to type so much, then you can pull changes with the rebase instead of 89 | merge. 90 | 91 | On branch `inventory`: 92 | ``` 93 | $ git pull upstream master -r # -r stands for rebase 94 | ``` 95 | 96 | 4. You need to push your changes to your fork: 97 | ``` 98 | $ git push origin inventory 99 | ``` 100 | 5. And now you just make a pull request (PR) from `origin/inventory` to 101 | `upstream/master`. When your PR is merged you can safely delete the 102 | `inventory` branch, or, if you want to continue working on the inventory 103 | system, just pull the merge as described in point 3. 104 | 105 | ### HAVE FUN CODING 106 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Community-Game 2 | This game is the second series of the community games by Matthew Hopson's Discord Community. 3 | This time around, we're replicating a Zombie game that we found online. 4 | 5 | # How to join us 6 | 7 | Just join our public discord, where all of the development happens. For project related talk just look under the "Community Project" category. 8 | 9 | `https://discord.gg/feKbBwS` 10 | 11 | # Building and Contributing 12 | 13 | If you want to know how to contribute to this project, 14 | look at [`CONTRIBUTING.md`](CONTRIBUTING.md). The document will tell you how you can get the project 15 | files with git, and how to contribute your code back into this 16 | main repository. 17 | 18 | There is also an easier way using the renewed desktop app "Github for Desktop", but this is not yet documented by anyone. 19 | You can follow the command instructions in the GUI app, however, as the backend to the GUI app is the Git command line. Therefor, 20 | the Github GUII app will have all the same features and buttons as Git (but git has them command-wise.) 21 | 22 | Also take a look at the [`CODESTYLE.md`](CODESTYLE.md) file. 23 | This file makes it clear which coding-format is acceptable in this repository. 24 | Pull Requests not conforming to the coding standard will be rejected. 25 | A rejected pull request can be re-opened when the code has been changed and is conforming. 26 | 27 | # Compiling the project 28 | 29 | First, download the repository to your local machine. 30 | 31 | `git clone --recursive https://github.com/HopsonCommunity/ZombieGame` 32 | 33 | ## Preparation 34 | 35 | #### Linux 36 | As SFML will be built from sources, you will be required to have the SFML sources. 37 | ##### Debian-based(eg. Lubuntu, Xubuntu, Ubuntu, ...) 38 | ``sudo apt-get install -y libpthread-stubs0-dev libgl1-mesa-dev libx11-dev libxrandr-dev libfreetype6-dev libglew1.5-dev libjpeg8-dev libsndfile1-dev libopenal-dev libudev-dev libxcb-image0-dev libjpeg-dev libflac-dev`` 39 | The -y parameter works by automatically accepting the requests for approval. 40 | 41 | ##### Arch Linux-based(eg. Manjaro) 42 | ``sudo pacman -S libpthread-stubs libx11 libxrandr libjpeg libsndfile libudev0 libxcb mesa libxrandr freetype2 glew libjpeg-turbo openal flac`` 43 | 44 | 45 | Other distributions will follow. The dependency names are listed here: 46 | https://www.sfml-dev.org/tutorials/2.4/compile-with-cmake.php 47 | 48 | ## Compiling with Visual Studio 49 | In Visual Studio, click on ``File->Open->Folder`` and select the root project folder. 50 | Visual Studio should detect the CMakeLists.txt file. It prints the CMake log into 51 | the console. It should look like this: 52 | 53 | :::If there are any errors, please check that you have copied over the dependencies to the right folder.::: 54 | Next, click on the Dropdown arrow at the Launch-Button and select the game. 55 | The project will now be compiled and executed. 56 | 57 | ## Compiling in CLion 58 | Go to ``FILE->Import Project`` and select the root project folder. 59 | 60 | Select ``Open Project`` and wait for CLion to prepare the IDE. 61 | 62 | Click the green play button and in the executable config select the only available. 63 | 64 | 65 | The IDE reads the CMakeLists.txt and compiles the program. 66 | 67 | ## Compiling without an IDE 68 | #### Preparation Windows 69 | Make sure you have MINGW with a c++ compiler, make installed in your path. 70 | Install CMake from the official website and add it to the PATH. 71 | 72 | **Note:** For the game to be correctly executed on Windows you will need to install OpenAL, check OpenAL at https://openal.org/downloads/ and download the latest installer. 73 | 74 | #### Linux 75 | Install a C++ compiler, make and CMake using your distribution's package manager. 76 | 77 | #### Mac is currently not supported as it is untested 78 | 79 | #### Compiling 80 | Go into the cloned repository and make a folder called `build` 81 | 82 | `mkdir build` 83 | 84 | Then, run CMake inside that build folder pointing the root folder. 85 | 86 | `cd build` 87 | `cmake ..` 88 | 89 | CMake creates the Makefile in the build directory. Now you can just run 90 | 91 | `make` 92 | 93 | and your files will be compiled. 94 | 95 | ## Program crashes when launching? 96 | 97 | In most cases, crashes will be caused by the lack of the "res/" folder where the 98 | executable files lie. Just copy the folder to your "build/" folder and this will 99 | most likely get you up and running again. 100 | 101 | If you're unable to resolve your errors, feel free to contact us on Discord! 102 | 103 | ### HAVE FUN CODING! 104 | -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdots.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdots.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsBold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsBold.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsDiamond.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsDiamond.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsDiamondBold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsDiamondBold.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsDiamondLight.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsDiamondLight.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsLight.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsLight.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsMinus.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsMinus.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsMinusBold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsMinusBold.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsPlus.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsPlus.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsPlusBold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsPlusBold.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsSquare.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsSquare.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsSquareBold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsSquareBold.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsSquareLight.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsSquareLight.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsVertical.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsVertical.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/BPdotsVerticalBold.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/fonts/BPDots/BPdotsVerticalBold.otf -------------------------------------------------------------------------------- /res/fonts/BPDots/Creative Commons Attribution-No Derivative Works.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution-No Derivative Works 3.0 Unported 2 | (http://creativecommons.org/licenses/by-nd/3.0/) 3 | 4 | You are free: 5 | 6 | to Share — to copy, distribute and transmit the work 7 | 8 | Under the following conditions: 9 | 10 | Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). 11 | 12 | No Derivative Works. You may not alter, transform, or build upon this work. 13 | 14 | For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. 15 | 16 | Any of the above conditions can be waived if you get permission from the copyright holder. 17 | 18 | Nothing in this license impairs or restricts the author's moral rights. -------------------------------------------------------------------------------- /res/gameobjects/bd.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [{ 3 | "componentType": "Renderer", 4 | "texture": "building", 5 | "offset_position": [16, 20], 6 | "offset_rotation": 0, 7 | "scale": [2, 2], 8 | "zIndex": 259 9 | }, 10 | { 11 | "componentType": "Transform", 12 | "position": [50, 40], 13 | "rotation": 0, 14 | "renderTransform": false 15 | }, 16 | { 17 | "componentType": "RigidBody", 18 | "inv_mass": 0, 19 | "velocity": [0, 0] 20 | }, 21 | { 22 | "componentType": "ColliderAABB", 23 | "neg_offset_position": [32, 25], 24 | "dimension": [64, 60] 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /res/gameobjects/fps.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [{ 3 | "componentType": "FPS", 4 | "position": [98, 2], 5 | "font": "BPDots/BPdotsSquareBold", 6 | "size": 26 7 | }] 8 | } -------------------------------------------------------------------------------- /res/gameobjects/grass.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [{ 3 | "componentType": "Renderer", 4 | "texture": "grass", 5 | "offset_position": [8, 8], 6 | "offset_rotation": 0, 7 | "scale": [5, 5], 8 | "zIndex": 0 9 | }, 10 | { 11 | "componentType": "Transform", 12 | "position": [0, 0], 13 | "rotation": 0, 14 | "renderTransform": false 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /res/gameobjects/mouse.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [{ 3 | "componentType": "Mouse" 4 | }, 5 | { 6 | "componentType": "Transform", 7 | "position": [0, 0], 8 | "rotation": 270, 9 | "renderTransform": false 10 | }, 11 | { 12 | "componentType": "Renderer", 13 | "texture": "crosshair", 14 | "offset_position": [4, 4], 15 | "offset_rotation": 0, 16 | "scale": [2, 2], 17 | "zIndex": 512 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /res/gameobjects/player.json: -------------------------------------------------------------------------------- 1 | { 2 | "components": [{ 3 | "componentType": "Player", 4 | "speed": 1 5 | }, 6 | { 7 | "componentType": "Animation", 8 | "FPS": 8, 9 | "startFrame": 0, 10 | "texture": "animations/player/Soldier", 11 | "offset_position": [16, 20], 12 | "offset_rotation": 90, 13 | "frame_width": 32, 14 | "scale": [2, 2], 15 | "zIndex": 2000 16 | }, 17 | { 18 | "componentType": "Transform", 19 | "position": [0, 0], 20 | "rotation": 0, 21 | "renderTransform": true 22 | }, 23 | { 24 | "componentType": "RigidBody", 25 | "inv_mass": 1, 26 | "velocity": [0, 0] 27 | }, 28 | { 29 | "componentType": "ColliderAABB", 30 | "neg_offset_position": [16, 16], 31 | "dimension": [32, 32] 32 | }, 33 | { 34 | "componentType": "Camera", 35 | "position": [0, 0], 36 | "resolution": [1280, 720] 37 | } 38 | ] 39 | } -------------------------------------------------------------------------------- /res/txrs/animations/player/Soldier.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/txrs/animations/player/Soldier.png -------------------------------------------------------------------------------- /res/txrs/building.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/txrs/building.png -------------------------------------------------------------------------------- /res/txrs/crosshair.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/txrs/crosshair.png -------------------------------------------------------------------------------- /res/txrs/grass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/txrs/grass.png -------------------------------------------------------------------------------- /res/txrs/player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/txrs/player.png -------------------------------------------------------------------------------- /res/txrs/sand.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HopsonCommunity/ZombieGame/9aaa12e7bcd0006ee48e727d1c2f11fe5d2d886b/res/txrs/sand.png -------------------------------------------------------------------------------- /src/Game.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Game.h" 3 | 4 | #include "state/PlayingState.h" 5 | #include "util/Renderer.h" 6 | #include "util/Renderer.h" 7 | 8 | Game::Game() 9 | : m_window ({1280, 720}, "Zombie Game"), 10 | m_factory (*this) 11 | { 12 | pushState(*this); 13 | } 14 | 15 | void Game::runGame() 16 | { 17 | unsigned tickCount = 0; 18 | constexpr unsigned UPDATES_PER_FRAME = 30; 19 | const sf::Time MS_PER_UPDATE = sf::seconds(1.0f / float(UPDATES_PER_FRAME)); 20 | 21 | sf::Clock timer; 22 | sf::Time lastTime = timer.getElapsedTime(); 23 | sf::Time lag = sf::Time::Zero; 24 | 25 | while (m_window.isOpen() && !m_states.empty()) 26 | { 27 | auto& state = getCurrentState(); 28 | 29 | //Time handling for the fixed update and 30 | //getting delta-time 31 | auto time = timer.getElapsedTime(); 32 | auto elapsed = time - lastTime; 33 | 34 | lastTime = time; 35 | lag += elapsed; 36 | 37 | //Real time updates 38 | state.handleInput(); 39 | state.update(elapsed); 40 | 41 | //Fixed update 42 | while (lag > MS_PER_UPDATE) 43 | { 44 | tickCount++; 45 | lag -= MS_PER_UPDATE; 46 | state.fixedUpdate(elapsed); 47 | } 48 | 49 | //Render 50 | m_window.clear(); 51 | Renderer Renderer(m_window); 52 | state.render(Renderer); 53 | Renderer.render(); 54 | m_window.display(); 55 | 56 | //done last so that window closing/ state pointer dangling does not cause crash 57 | handleEvents(); 58 | tryPop(); 59 | } 60 | } 61 | 62 | const sf::RenderWindow& Game::getWindow() const 63 | { 64 | return m_window; 65 | } 66 | 67 | template 68 | void Game::pushState(Args&&... args) 69 | { 70 | m_states.push_back(std::make_unique(std::forward(args)...)); 71 | m_states.back()->setup(); 72 | } 73 | 74 | 75 | void Game::popState() 76 | { 77 | m_shouldPopState = true; 78 | } 79 | 80 | GameState& Game::getCurrentState() 81 | { 82 | return *m_states.back(); 83 | } 84 | 85 | GameObjectFactory& Game::getGameObjectFactory() 86 | { 87 | return m_factory; 88 | } 89 | 90 | void Game::tryPop() 91 | { 92 | if (m_shouldPopState) 93 | { 94 | if (m_states.empty()) 95 | return; 96 | 97 | m_shouldPopState = false; 98 | m_states.pop_back(); 99 | } 100 | } 101 | 102 | void Game::handleEvents() 103 | { 104 | sf::Event event; 105 | 106 | while (m_window.pollEvent(event)) 107 | { 108 | getCurrentState().handleEvents(event); 109 | switch (event.type) 110 | { 111 | case sf::Event::Closed: 112 | m_window.close(); 113 | break; 114 | 115 | default: 116 | break; 117 | } 118 | } 119 | } 120 | 121 | sf::RenderWindow& Game::getRenderWindow() 122 | { 123 | return m_window; 124 | } 125 | 126 | 127 | -------------------------------------------------------------------------------- /src/Game.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #include "state/GameState.h" 8 | #include "gameobject/GameObjectFactory.h" 9 | 10 | class Game 11 | { 12 | public: 13 | Game(); 14 | 15 | void runGame(); 16 | 17 | const sf::RenderWindow& getWindow() const; 18 | 19 | template 20 | void pushState(Args&&... args); 21 | 22 | void popState(); 23 | 24 | GameState& getCurrentState(); 25 | 26 | GameObjectFactory& getGameObjectFactory(); 27 | sf::RenderWindow& getRenderWindow(); 28 | 29 | private: 30 | void tryPop(); 31 | void handleEvents(); 32 | 33 | sf::RenderWindow m_window; 34 | std::vector> m_states; 35 | bool m_shouldPopState = false; 36 | GameObjectFactory m_factory; 37 | 38 | }; 39 | -------------------------------------------------------------------------------- /src/gameobject/GameObject.cpp: -------------------------------------------------------------------------------- 1 | #include "GameObject.h" 2 | 3 | #include "components/Component.h" 4 | 5 | #include "../state/GameState.h" 6 | #include "../systems/ColliderSpace.h" 7 | 8 | GameObject::GameObject(GameState& gamestate, unsigned id) 9 | : m_id(id) 10 | , m_owningState(gamestate) { 11 | } 12 | 13 | void GameObject::setup() 14 | { 15 | for (auto& it : m_components) 16 | it.second->setup(); 17 | } 18 | 19 | void GameObject::update(const sf::Time& deltaTime) 20 | { 21 | for (auto& it : m_components) 22 | it.second->update(deltaTime); 23 | } 24 | 25 | void GameObject::fixed_update(const sf::Time& deltaTime) 26 | { 27 | for (auto& it : m_components) 28 | it.second->fixed_update(deltaTime); 29 | } 30 | 31 | void GameObject::render(Renderer& renderTarget) 32 | { 33 | for (auto& it : m_components) 34 | it.second->render(renderTarget); 35 | } 36 | 37 | std::unique_ptr GameObject::clone(GameState& owningState, unsigned id) 38 | { 39 | auto clone = std::make_unique(owningState, id); 40 | 41 | for (auto& it : m_components) 42 | clone->m_components[it.first] = it.second->clone(*clone); 43 | 44 | clone->setup(); 45 | 46 | return clone; 47 | } 48 | 49 | void GameObject::onCollision(CollisionInfo& info) { 50 | for(auto& it : m_components) 51 | it.second->onCollision(info); 52 | } 53 | 54 | void GameObject::onTrigger(TriggerInfo& info) { 55 | for(auto& it : m_components) 56 | it.second->onTrigger(info); 57 | } 58 | -------------------------------------------------------------------------------- /src/gameobject/GameObject.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | #include "components/Component.h" 9 | #include "../util/Renderer.h" 10 | 11 | class GameState; 12 | class CollisionInfo; 13 | class TriggerInfo; 14 | 15 | class GameObject 16 | { 17 | public: 18 | GameObject(GameState& gamestate, unsigned int id); 19 | 20 | template 21 | void addComponent(std::unique_ptr component) 22 | { 23 | m_components[T::ID] = std::move(component); 24 | } 25 | 26 | template 27 | void removeComponent() 28 | { 29 | m_components.erase(T::ID); 30 | } 31 | 32 | template 33 | T* getComponent() 34 | { 35 | unsigned int id = T::ID; 36 | auto it = m_components.find(id); 37 | if (it != m_components.end()) 38 | return static_cast(it->second.get()); 39 | 40 | return nullptr; 41 | } 42 | 43 | void setup(); 44 | void update(const sf::Time& deltaTime); 45 | void fixed_update(const sf::Time& deltaTime); 46 | void render(Renderer& renderTarget); 47 | 48 | std::unique_ptr clone(GameState& owningState, unsigned int id); 49 | 50 | void onCollision(CollisionInfo& info); 51 | void onTrigger(TriggerInfo& info); 52 | 53 | GameState& getOwningState() { return m_owningState;} 54 | 55 | private: 56 | std::unordered_map> m_components; 57 | unsigned int m_id; 58 | GameState& m_owningState; 59 | }; 60 | 61 | -------------------------------------------------------------------------------- /src/gameobject/GameObjectFactory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "GameObjectFactory.h" 4 | #include "../util/FileUtil.h" 5 | #include "components/TestComponent.h" 6 | #include "../Game.h" 7 | #include "components/TransformComponent.h" 8 | #include "components/RendererComponent.h" 9 | #include "components/PlayerComponent.h" 10 | #include "components/MouseComponent.h" 11 | #include "components/CameraComponent.h" 12 | #include "components/AnimationComponent.h" 13 | #include "components/ColliderAABBComponent.h" 14 | #include "components/RigidBodyComponent.h" 15 | #include "components/FPSComponent.h" 16 | 17 | GameObjectFactory::GameObjectFactory(Game& game) 18 | : m_last_ID(0) 19 | , m_game(game) 20 | {} 21 | 22 | std::unique_ptr GameObjectFactory::createGameObject(const std::string& name) 23 | { 24 | if (templates.find(name) == templates.end()) 25 | createTemplate(name); 26 | return templates.find(name)->second->clone(m_game.getCurrentState(), ++m_last_ID); 27 | } 28 | 29 | void GameObjectFactory::createTemplate(const std::string& name) 30 | { 31 | auto source = getFileContents("res/gameobjects/" + name + ".json"); 32 | auto json = nlohmann::json::parse(source.c_str()); 33 | auto gameObject = std::make_unique(m_game.getCurrentState(), 0); 34 | auto componentsJSON = json["components"]; 35 | 36 | for (unsigned i = 0; i < componentsJSON.size(); i++) 37 | { 38 | auto componentJSON = componentsJSON[i]; 39 | 40 | if (componentJSON["componentType"].get() == "Test") 41 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 42 | else if (componentJSON["componentType"].get() == "Renderer") 43 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 44 | else if (componentJSON["componentType"].get() == "Transform") 45 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 46 | else if (componentJSON["componentType"].get() == "Player") 47 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 48 | else if (componentJSON["componentType"].get() == "Mouse") 49 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 50 | else if (componentJSON["componentType"].get() == "Camera") 51 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 52 | else if (componentJSON["componentType"].get() == "Animation") 53 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 54 | else if (componentJSON["componentType"].get() == "ColliderAABB") 55 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 56 | else if (componentJSON["componentType"].get() == "RigidBody") 57 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 58 | else if (componentJSON["componentType"].get() == "FPS") 59 | gameObject->addComponent(std::make_unique(*gameObject, componentJSON)); 60 | } 61 | 62 | templates[name] = std::move(gameObject); 63 | } 64 | -------------------------------------------------------------------------------- /src/gameobject/GameObjectFactory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "GameObject.h" 4 | 5 | class Game; 6 | 7 | class GameObjectFactory 8 | { 9 | public: 10 | GameObjectFactory(Game& game); 11 | std::unique_ptr createGameObject(const std::string& name); 12 | 13 | private: 14 | void createTemplate(const std::string& name); 15 | 16 | std::unordered_map> templates; 17 | unsigned m_last_ID; 18 | Game& m_game; 19 | }; 20 | 21 | -------------------------------------------------------------------------------- /src/gameobject/components/AnimationComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "AnimationComponent.h" 2 | 3 | #include "TransformComponent.h" 4 | 5 | #include "../GameObject.h" 6 | 7 | #include "../../resource/ResourceHolder.h" 8 | 9 | unsigned AnimationComponent::ID = 6; 10 | 11 | AnimationComponent::AnimationComponent(GameObject& owner, nlohmann::json json) 12 | : Component(owner) 13 | { 14 | FrameTime = 1000.f/float(json["FPS"]); 15 | CurrentFrameID = json["startFrame"]; 16 | 17 | textureName = json["texture"]; 18 | sprite = sf::Sprite(ResourceHolder::get().textures.get(textureName)); 19 | offset_position = sf::Vector2f(json["offset_position"][0], json["offset_position"][1]); 20 | offset_rotation = json["offset_rotation"]; 21 | frame_width = json["frame_width"]; 22 | scale = sf::Vector2f(json["scale"][0], json["scale"][1]); 23 | zIndex = static_cast(json["zIndex"]); 24 | } 25 | 26 | AnimationComponent::AnimationComponent(GameObject& owner, float framesPerSecond, int currentFrameID, 27 | std::string textureName, sf::Vector2f offset_position, double offset_rotation, 28 | sf::Vector2f scale, int frame_width, ZIndex_t zIndex) 29 | : Component(owner) 30 | , FrameTime(framesPerSecond/1000.f) 31 | , CurrentFrameID(currentFrameID) 32 | , offset_position(offset_position), offset_rotation(offset_rotation), scale(scale) 33 | , frame_width(frame_width) 34 | , zIndex(zIndex) 35 | { 36 | sprite = sf::Sprite(ResourceHolder::get().textures.get(textureName)); 37 | } 38 | 39 | void AnimationComponent::setup() 40 | { 41 | CurrentFrameID=0; 42 | transform = m_owner.getComponent(); 43 | rectSourceSprite.height=sprite.getTextureRect().height; 44 | rectSourceSprite.width=frame_width; 45 | rectSourceSprite.top=0; 46 | clock.restart(); 47 | MaxFrameID=sprite.getTextureRect().width/frame_width; 48 | frame_direction=1; 49 | } 50 | 51 | void AnimationComponent::update(const sf::Time& ) 52 | { 53 | if (clock.getElapsedTime().asMilliseconds()>=FrameTime){ 54 | CurrentFrameID+=frame_direction; 55 | if (CurrentFrameID>=MaxFrameID){ 56 | frame_direction=-1; 57 | CurrentFrameID=MaxFrameID-1; 58 | }else if (CurrentFrameID<=0){ 59 | frame_direction=1; 60 | CurrentFrameID=0; 61 | } 62 | clock.restart(); 63 | } 64 | } 65 | 66 | void AnimationComponent::fixed_update(const sf::Time &) 67 | { 68 | 69 | } 70 | 71 | void AnimationComponent::render(Renderer& renderTarget) 72 | { 73 | rectSourceSprite.left=frame_width*CurrentFrameID; 74 | sprite.setTextureRect(rectSourceSprite); 75 | sprite.setOrigin(offset_position); 76 | sprite.setPosition(transform->position); 77 | sprite.setRotation(transform->rotation + offset_rotation); 78 | sprite.setScale(scale); 79 | renderTarget.draw(sprite, zIndex); 80 | } 81 | 82 | std::unique_ptr AnimationComponent::clone(GameObject& newGameObject) 83 | { 84 | return std::make_unique(newGameObject, FrameTime*1000.f, CurrentFrameID, 85 | textureName, offset_position, offset_rotation, scale, frame_width, zIndex); 86 | } 87 | 88 | -------------------------------------------------------------------------------- /src/gameobject/components/AnimationComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "Component.h" 6 | #include "../../util/Renderer.h" 7 | 8 | class TransformComponent; 9 | 10 | class AnimationComponent : public Component 11 | { 12 | public: 13 | AnimationComponent(GameObject& owner, nlohmann::json json); 14 | AnimationComponent (GameObject& owner, float framesPerSecond, int currentFrameID, std::string textureName, 15 | sf::Vector2f offset_position, double offset_rotation, sf::Vector2f scale, int frame_width, ZIndex_t zIndex); 16 | 17 | void setup() override; 18 | void update(const sf::Time& deltaTime) override; 19 | void fixed_update(const sf::Time &deltaTime) override; 20 | void render(Renderer& renderTarget) override; 21 | std::unique_ptr clone(GameObject& newGameObject) override; 22 | 23 | static unsigned ID; 24 | 25 | float FrameTime=1000.f; 26 | int CurrentFrameID; 27 | int MaxFrameID = 0; 28 | std::string textureName; 29 | sf::Sprite sprite; 30 | sf::Vector2f offset_position; 31 | double offset_rotation; 32 | sf::Vector2f scale; 33 | int frame_width; 34 | sf::IntRect rectSourceSprite; 35 | sf::Clock clock; 36 | int frame_direction; 37 | ZIndex_t zIndex; 38 | 39 | TransformComponent* transform; 40 | }; 41 | -------------------------------------------------------------------------------- /src/gameobject/components/CameraComponent.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "CameraComponent.h" 3 | #include "../GameObject.h" 4 | #include "../../state/GameState.h" 5 | #include "../../Game.h" 6 | #include "TransformComponent.h" 7 | 8 | unsigned CameraComponent::ID = 5; 9 | 10 | CameraComponent::CameraComponent(GameObject &owner, nlohmann::json json) 11 | : Component(owner) 12 | { 13 | dimensions = sf::FloatRect(json["position"][0], json["position"][1], json["resolution"][0], json["resolution"][1]); 14 | view = sf::View(dimensions); 15 | } 16 | 17 | CameraComponent::CameraComponent(GameObject &owner, sf::FloatRect dimensions) 18 | : Component(owner), view(dimensions) 19 | {} 20 | 21 | void CameraComponent::setup() 22 | { 23 | transform = m_owner.getComponent(); 24 | } 25 | 26 | void CameraComponent::update(const sf::Time &) 27 | { 28 | view.setCenter(transform->position); 29 | } 30 | 31 | void CameraComponent::fixed_update(const sf::Time &) 32 | {} 33 | 34 | void CameraComponent::render(Renderer&) 35 | {} 36 | 37 | std::unique_ptr CameraComponent::clone(GameObject &newGameObject) 38 | { 39 | return std::make_unique(newGameObject, dimensions); 40 | } -------------------------------------------------------------------------------- /src/gameobject/components/CameraComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../GameObject.h" 4 | #include "Component.h" 5 | #include "TransformComponent.h" 6 | 7 | class CameraComponent : public Component 8 | { 9 | public: 10 | CameraComponent(GameObject& owner, nlohmann::json json); 11 | CameraComponent(GameObject& owner, sf::FloatRect dimensions); 12 | 13 | void setup() override; 14 | void update(const sf::Time& deltaTime) override; 15 | void fixed_update(const sf::Time &deltaTime) override; 16 | void render(Renderer& renderTarget) override; 17 | std::unique_ptr clone(GameObject& newGameObject) override; 18 | 19 | static unsigned ID; 20 | 21 | sf::View view; 22 | sf::FloatRect dimensions; 23 | 24 | TransformComponent* transform; 25 | }; 26 | -------------------------------------------------------------------------------- /src/gameobject/components/ColliderAABBComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "ColliderAABBComponent.h" 2 | 3 | #include "RigidBodyComponent.h" 4 | #include "TransformComponent.h" 5 | 6 | #include "../GameObject.h" 7 | 8 | #include "../../systems/ColliderSpace.h" 9 | #include "../../state/GameState.h" 10 | 11 | #include 12 | 13 | unsigned int ColliderAABBComponent::ID = 7; 14 | 15 | ColliderAABBComponent::ColliderAABBComponent(GameObject& owner, nlohmann::json json) 16 | : Component(owner) 17 | { 18 | m_collider = AABBCollider( 19 | -sf::Vector2f(json["neg_offset_position"][0], json["neg_offset_position"][1]), 20 | sf::Vector2f(json["dimension"][0], json["dimension"][1]) 21 | ); 22 | } 23 | 24 | ColliderAABBComponent::ColliderAABBComponent(GameObject& owner, sf::Vector2f offset_position, sf::Vector2f dimension) 25 | : Component(owner) 26 | , m_collider(AABBCollider(offset_position, dimension)) {} 27 | 28 | ColliderAABBComponent::~ColliderAABBComponent() 29 | { 30 | m_owner.getOwningState().getColliderSpace()->remove(m_transform); 31 | } 32 | 33 | void ColliderAABBComponent::setup() 34 | { 35 | m_transform = m_owner.getComponent(); 36 | m_owner.getOwningState().getColliderSpace()->insert({ 37 | m_transform, 38 | m_owner.getComponent(), 39 | &m_collider, 40 | std::function([&] (CollisionInfo& c) { m_owner.onCollision(c); }), 41 | std::function([&] (TriggerInfo& t) { m_owner.onTrigger(t); }) 42 | }); 43 | } 44 | 45 | void ColliderAABBComponent::update(sf::Time const& ) 46 | {} 47 | 48 | void ColliderAABBComponent::fixed_update(sf::Time const& ) 49 | {} 50 | 51 | void ColliderAABBComponent::render(Renderer& renderTarget) 52 | { 53 | if (ColliderAABBComponent::collider_wire_frame) 54 | { 55 | auto ns = m_collider.getNormals(); 56 | auto ps = m_collider.getPoints(); 57 | 58 | sf::Vertex vs[5]; 59 | int i = 0; 60 | for (auto const& p : ps) 61 | { 62 | vs[i].position = p + m_transform->position; 63 | vs[i].color = sf::Color::Green; 64 | i++; 65 | } 66 | vs[4].position = m_collider.getPoints()[0] + m_transform->position; 67 | vs[4].color = sf::Color::Green; 68 | renderTarget.draw(vs, 5, sf::PrimitiveType::LinesStrip, ZIndex::FOREGROUND); 69 | 70 | sf::Vertex vns[4]; 71 | i = 0; 72 | for (auto const& n : ns) 73 | { 74 | sf::Vector2f start = m_transform->position; 75 | vns[i].position = start; 76 | vns[i+1].position = start + n*10.f; 77 | vns[i].color = sf::Color::Magenta; 78 | vns[i+1].color = sf::Color::Magenta; 79 | i += 2; 80 | } 81 | renderTarget.draw(vns, 8, sf::PrimitiveType::Lines, ZIndex::FOREGROUND); 82 | } 83 | } 84 | 85 | std::unique_ptr ColliderAABBComponent::clone(GameObject& newGameObject) 86 | { 87 | return std::make_unique(newGameObject, m_collider.getOrigin(), m_collider.getDimension()); 88 | } 89 | 90 | float ColliderAABBComponent::left() const 91 | { 92 | return m_transform->position.x + m_collider.getOrigin().x; 93 | } 94 | 95 | float ColliderAABBComponent::right() const 96 | { 97 | return m_transform->position.x + m_collider.getOrigin().x + m_collider.getDimension().x; 98 | } 99 | 100 | float ColliderAABBComponent::top() const 101 | { 102 | return m_transform->position.y + m_collider.getOrigin().y; 103 | } 104 | 105 | float ColliderAABBComponent::bottom() const 106 | { 107 | return m_transform->position.y + m_collider.getOrigin().y + m_collider.getDimension().y; 108 | } 109 | 110 | float ColliderAABBComponent::width() const 111 | { 112 | return m_collider.getDimension().x; 113 | } 114 | 115 | float ColliderAABBComponent::height() const 116 | { 117 | return m_collider.getDimension().y; 118 | } 119 | 120 | -------------------------------------------------------------------------------- /src/gameobject/components/ColliderAABBComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "Component.h" 6 | #include "../../systems/Collider/AABBCollider.h" 7 | 8 | class TransformComponent; 9 | 10 | class ColliderAABBComponent : public Component 11 | { 12 | static constexpr bool collider_wire_frame = false; // debug 13 | public: 14 | 15 | ColliderAABBComponent(GameObject& owner, nlohmann::json json); 16 | ColliderAABBComponent(GameObject& owner, sf::Vector2f offset_position, sf::Vector2f dimension); 17 | ~ColliderAABBComponent(); 18 | 19 | void setup() override; 20 | void update(const sf::Time& deltaTime) override; 21 | void fixed_update(const sf::Time &deltaTime) override; 22 | void render(Renderer& renderTarget) override; 23 | std::unique_ptr clone(GameObject& newGameObject) override; 24 | 25 | static unsigned ID; 26 | 27 | float left() const; 28 | float right() const; 29 | float top() const; 30 | float bottom() const; 31 | 32 | float width() const; 33 | float height() const; 34 | 35 | private: 36 | 37 | TransformComponent* m_transform; 38 | AABBCollider m_collider; 39 | }; -------------------------------------------------------------------------------- /src/gameobject/components/Component.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../../util/Renderer.h" 4 | 5 | #include 6 | #include 7 | 8 | class GameObject; 9 | class CollisionInfo; 10 | class TriggerInfo; 11 | class DebugRenderer; 12 | 13 | class Component 14 | { 15 | public: 16 | Component(GameObject& owner) 17 | : m_owner(owner) 18 | { } 19 | 20 | virtual void setup() = 0; 21 | virtual void update(const sf::Time& deltaTime) = 0; 22 | virtual void fixed_update(const sf::Time &deltaTime) = 0; 23 | virtual void render(Renderer& renderTarget) = 0; 24 | 25 | virtual std::unique_ptr clone(GameObject& newGameObject) = 0; 26 | 27 | virtual void onCollision(CollisionInfo&) {} 28 | virtual void onTrigger(TriggerInfo&) {} 29 | 30 | protected: 31 | GameObject& m_owner; 32 | }; 33 | -------------------------------------------------------------------------------- /src/gameobject/components/FPSComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "FPSComponent.h" 2 | 3 | #include "CameraComponent.h" 4 | 5 | #include "../GameObject.h" 6 | #include "../../resource/ResourceHolder.h" 7 | 8 | unsigned int FPSComponent::ID = 9; 9 | 10 | FPSComponent::FPSComponent(GameObject& owner, nlohmann::json json) 11 | : Component(owner) 12 | , prev_fps{0} 13 | { 14 | text = sf::Text("0", ResourceHolder::get().fonts.get(json["font"]), json["size"]); 15 | position = sf::Vector2f(json["position"][0], json["position"][1]); 16 | text.setFillColor(sf::Color::White); 17 | } 18 | 19 | FPSComponent::FPSComponent(GameObject& owner, sf::Text const& text, sf::Vector2f const& position) 20 | : Component(owner) 21 | , text(text) 22 | , position(position) 23 | , prev_fps{0} {} 24 | 25 | void FPSComponent::setup() 26 | {} 27 | 28 | void FPSComponent::update(const sf::Time& dt) 29 | { 30 | if (dt.asMicroseconds() != 0) { 31 | for (int i = 0; i < AVERAGE_FPS_COUNT - 1; ++i) 32 | prev_fps[i] = prev_fps[i+1]; 33 | prev_fps[AVERAGE_FPS_COUNT - 1] = static_cast((1.f/dt.asMicroseconds()) * 1000000); 34 | int fps = 0; 35 | for (int i = 0; i < AVERAGE_FPS_COUNT; ++i) fps += prev_fps[i]; 36 | text.setString(std::to_string(fps / AVERAGE_FPS_COUNT)); 37 | text.setOrigin(text.getLocalBounds().width/2.0f,text.getLocalBounds().height/2.0f); 38 | text.setPosition(position.x, position.y); 39 | } 40 | } 41 | 42 | void FPSComponent::fixed_update(const sf::Time&) 43 | {} 44 | 45 | void FPSComponent::render(Renderer& renderTarget) 46 | { 47 | renderTarget.drawHUD(text); 48 | } 49 | 50 | std::unique_ptr FPSComponent::clone(GameObject& newGameObject) 51 | { 52 | return std::make_unique(newGameObject, text, position); 53 | } -------------------------------------------------------------------------------- /src/gameobject/components/FPSComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Component.h" 4 | 5 | #include 6 | 7 | #include 8 | 9 | class GameObject; 10 | class CameraComponent; 11 | 12 | class FPSComponent : public Component 13 | { 14 | static constexpr int AVERAGE_FPS_COUNT = 60; 15 | 16 | public: 17 | 18 | FPSComponent(GameObject& owner, nlohmann::json json); 19 | FPSComponent(GameObject& owner, sf::Text const& text, sf::Vector2f const& position); 20 | 21 | virtual void setup(); 22 | virtual void update(const sf::Time& deltaTime); 23 | virtual void fixed_update(const sf::Time &deltaTime); 24 | virtual void render(Renderer& renderTarget); 25 | 26 | virtual std::unique_ptr clone(GameObject& newGameObject); 27 | 28 | static unsigned int ID; 29 | 30 | sf::Text text; 31 | sf::Vector2f position; 32 | int prev_fps[AVERAGE_FPS_COUNT]; 33 | 34 | CameraComponent* camera; 35 | }; -------------------------------------------------------------------------------- /src/gameobject/components/MouseComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "MouseComponent.h" 2 | #include "../../state/GameState.h" 3 | #include "../../Game.h" 4 | unsigned MouseComponent::ID = 4; 5 | 6 | MouseComponent::MouseComponent(GameObject &owner, nlohmann::json ) 7 | : Component(owner) 8 | { 9 | 10 | } 11 | 12 | MouseComponent::MouseComponent(GameObject &owner) 13 | : Component(owner) 14 | { 15 | 16 | } 17 | 18 | void MouseComponent::setup() 19 | { 20 | transform = m_owner.getComponent(); 21 | m_owner.getOwningState().getGamePointer()->getRenderWindow().setMouseCursorVisible(false); 22 | } 23 | 24 | void MouseComponent::update(const sf::Time &) 25 | { 26 | if (cameraComponent!= nullptr && cameraTransform != nullptr) 27 | { 28 | transform->position = sf::Vector2f( 29 | sf::Mouse::getPosition(m_owner.getOwningState().getGamePointer()->getRenderWindow()).x + 30 | cameraTransform->position.x - cameraComponent->view.getSize().x / 2, 31 | sf::Mouse::getPosition(m_owner.getOwningState().getGamePointer()->getRenderWindow()).y + 32 | cameraTransform->position.y - cameraComponent->view.getSize().y / 2); 33 | } 34 | else 35 | transform->position = sf::Vector2f(sf::Mouse::getPosition(m_owner.getOwningState().getGamePointer()->getRenderWindow()).x, sf::Mouse::getPosition(m_owner.getOwningState().getGamePointer()->getRenderWindow()).y); 36 | 37 | } 38 | 39 | void MouseComponent::fixed_update(const sf::Time &) 40 | { 41 | 42 | } 43 | 44 | void MouseComponent::render(Renderer&) 45 | { 46 | } 47 | 48 | std::unique_ptr MouseComponent::clone(GameObject &newGameObject) 49 | { 50 | return std::make_unique(newGameObject); 51 | } 52 | -------------------------------------------------------------------------------- /src/gameobject/components/MouseComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "Component.h" 5 | #include "../GameObject.h" 6 | #include "TransformComponent.h" 7 | #include "CameraComponent.h" 8 | 9 | class MouseComponent : public Component 10 | { 11 | public: 12 | MouseComponent(GameObject& owner, nlohmann::json json); 13 | MouseComponent(GameObject& owner); 14 | 15 | void setup() override; 16 | void update(const sf::Time& deltaTime) override; 17 | void fixed_update(const sf::Time &deltaTime) override; 18 | void render(Renderer& renderTarget) override; 19 | std::unique_ptr clone(GameObject& newGameObject) override; 20 | 21 | TransformComponent* transform; 22 | TransformComponent* cameraTransform; 23 | CameraComponent* cameraComponent; 24 | 25 | static unsigned ID; 26 | }; -------------------------------------------------------------------------------- /src/gameobject/components/PlayerComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "PlayerComponent.h" 2 | #include "../GameObject.h" 3 | 4 | unsigned PlayerComponent::ID = 3; 5 | 6 | PlayerComponent::PlayerComponent(GameObject &owner, nlohmann::json json) 7 | : Component(owner) 8 | { 9 | speed = json["speed"]; 10 | } 11 | 12 | PlayerComponent::PlayerComponent(GameObject &owner, float speed) 13 | : Component(owner), speed(speed) 14 | {} 15 | 16 | void PlayerComponent::setup() 17 | { 18 | transform = m_owner.getComponent(); 19 | } 20 | 21 | void PlayerComponent::update(const sf::Time &deltaTime) 22 | { 23 | if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { 24 | transform->position.y -= deltaTime.asMicroseconds() / 10000.0 * speed; 25 | } 26 | if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { 27 | transform->position.y += deltaTime.asMicroseconds() / 10000.0 * speed; 28 | } 29 | if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { 30 | transform->position.x += deltaTime.asMicroseconds() / 10000.0 * speed; 31 | } 32 | if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { 33 | transform->position.x -= deltaTime.asMicroseconds() / 10000.0 * speed; 34 | } 35 | 36 | if(mouse != nullptr) { 37 | transform->lookAt(mouse); 38 | } 39 | } 40 | 41 | void PlayerComponent::fixed_update(const sf::Time &) 42 | {} 43 | 44 | void PlayerComponent::render(Renderer&) 45 | {} 46 | 47 | std::unique_ptr PlayerComponent::clone(GameObject &newGameObject) 48 | { 49 | return std::make_unique(newGameObject, speed); 50 | } 51 | 52 | -------------------------------------------------------------------------------- /src/gameobject/components/PlayerComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "Component.h" 5 | #include "TransformComponent.h" 6 | 7 | #include "../../systems/ColliderSpace.h" 8 | #include 9 | 10 | class PlayerComponent : public Component 11 | { 12 | public: 13 | PlayerComponent(GameObject& owner, nlohmann::json json); 14 | PlayerComponent(GameObject& owner, float speed); 15 | 16 | void setup() override; 17 | void update(const sf::Time& deltaTime) override; 18 | void fixed_update(const sf::Time &deltaTime) override; 19 | void render(Renderer& renderTarget) override; 20 | std::unique_ptr clone(GameObject& newGameObject) override; 21 | 22 | static unsigned ID; 23 | 24 | float speed; 25 | 26 | TransformComponent* transform; 27 | TransformComponent* mouse; 28 | }; -------------------------------------------------------------------------------- /src/gameobject/components/RendererComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "RendererComponent.h" 2 | #include "../GameObject.h" 3 | #include "../../resource/ResourceHolder.h" 4 | 5 | unsigned RendererComponent::ID = 1; 6 | 7 | RendererComponent::RendererComponent(GameObject &owner, nlohmann::json json) : Component(owner) 8 | { 9 | textureName = json["texture"]; 10 | sprite = sf::Sprite(ResourceHolder::get().textures.get(textureName)); 11 | offset_position = sf::Vector2f(json["offset_position"][0], json["offset_position"][1]); 12 | offset_rotation = json["offset_rotation"]; 13 | scale = sf::Vector2f(json["scale"][0], json["scale"][1]); 14 | zIndex = static_cast(json["zIndex"]); 15 | } 16 | RendererComponent::RendererComponent(GameObject &owner, std::string textureName, sf::Vector2f offset_position, 17 | double offset_rotation, sf::Vector2f scale, ZIndex_t zIndex) 18 | : Component(owner) 19 | , offset_position(offset_position) 20 | , offset_rotation(offset_rotation) 21 | , scale(scale) 22 | , zIndex(zIndex) 23 | { 24 | sprite = sf::Sprite(ResourceHolder::get().textures.get(textureName)); 25 | } 26 | 27 | void RendererComponent::setup() 28 | { 29 | transform = m_owner.getComponent(); 30 | } 31 | 32 | void RendererComponent::update(const sf::Time &) 33 | {} 34 | 35 | void RendererComponent::fixed_update(const sf::Time &) 36 | {} 37 | 38 | void RendererComponent::render(Renderer& renderTarget) 39 | { 40 | sprite.setOrigin(offset_position); 41 | sprite.setPosition(transform->position); 42 | sprite.setRotation(transform->rotation + offset_rotation); 43 | sprite.setScale(scale); 44 | renderTarget.draw(sprite, zIndex); 45 | } 46 | 47 | std::unique_ptr RendererComponent::clone(GameObject& newGameObject) 48 | { 49 | return std::make_unique(newGameObject, textureName, offset_position, offset_rotation, scale, zIndex); 50 | } 51 | -------------------------------------------------------------------------------- /src/gameobject/components/RendererComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "Component.h" 5 | #include "TransformComponent.h" 6 | 7 | #include "../../util/Renderer.h" 8 | 9 | class RendererComponent : public Component 10 | { 11 | public: 12 | RendererComponent(GameObject& owner, nlohmann::json json); 13 | RendererComponent(GameObject& owner, std::string textureName, sf::Vector2f offset_position, double offset_rotation, 14 | sf::Vector2f scale, ZIndex_t zIndex); 15 | 16 | void setup() override; 17 | void update(const sf::Time& deltaTime) override; 18 | void fixed_update(const sf::Time &deltaTime) override; 19 | void render(Renderer& renderTarget) override; 20 | std::unique_ptr clone(GameObject& newGameObject) override; 21 | 22 | static unsigned ID; 23 | 24 | 25 | std::string textureName; 26 | sf::Sprite sprite; 27 | sf::Vector2f offset_position; 28 | double offset_rotation; 29 | sf::Vector2f scale; 30 | ZIndex_t zIndex = 0; 31 | 32 | TransformComponent* transform; 33 | }; 34 | -------------------------------------------------------------------------------- /src/gameobject/components/RigidBodyComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "RigidBodyComponent.h" 2 | 3 | #include "TransformComponent.h" 4 | 5 | #include "../GameObject.h" 6 | 7 | unsigned int RigidBodyComponent::ID = 8; 8 | 9 | RigidBodyComponent::RigidBodyComponent(GameObject& owner, nlohmann::json json) 10 | : Component(owner) 11 | { 12 | velocity = sf::Vector2f{ json["velocity"][0], json["velocity"][1] }; 13 | inv_mass = json.count("inv_mass") ? static_cast(json["inv_mass"]) : 1; 14 | } 15 | 16 | RigidBodyComponent::RigidBodyComponent(GameObject& owner, sf::Vector2f const& velocity, float inv_mass) 17 | : Component(owner) 18 | , velocity(velocity) 19 | , inv_mass(inv_mass) {} 20 | 21 | void RigidBodyComponent::setup() 22 | { 23 | transform = m_owner.getComponent(); 24 | } 25 | 26 | void RigidBodyComponent::update(const sf::Time& deltaTime) 27 | { 28 | transform->position += velocity * (deltaTime.asMilliseconds() / 1000.f); 29 | } 30 | 31 | void RigidBodyComponent::fixed_update(const sf::Time &) 32 | {} 33 | 34 | void RigidBodyComponent::render(Renderer& ) 35 | {} 36 | 37 | std::unique_ptr RigidBodyComponent::clone(GameObject& newGameObject) 38 | { 39 | return std::make_unique(newGameObject, velocity, inv_mass); 40 | } 41 | 42 | void RigidBodyComponent::addForce(sf::Vector2f const& force) 43 | { 44 | velocity += force * inv_mass; 45 | } 46 | -------------------------------------------------------------------------------- /src/gameobject/components/RigidBodyComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "Component.h" 6 | 7 | class GameObject; 8 | class TransformComponent; 9 | 10 | class RigidBodyComponent : public Component 11 | { 12 | public: 13 | 14 | RigidBodyComponent(GameObject& owner, nlohmann::json json); 15 | RigidBodyComponent(GameObject& owner, sf::Vector2f const& velocity, float inv_mass); 16 | 17 | virtual void setup(); 18 | virtual void update(const sf::Time& deltaTime); 19 | virtual void fixed_update(const sf::Time &deltaTime); 20 | virtual void render(Renderer& renderTarget); 21 | 22 | virtual std::unique_ptr clone(GameObject& newGameObject); 23 | 24 | void addForce(sf::Vector2f const& force); 25 | 26 | TransformComponent* transform; 27 | 28 | sf::Vector2f velocity; 29 | float inv_mass; 30 | 31 | static unsigned int ID; 32 | 33 | }; -------------------------------------------------------------------------------- /src/gameobject/components/TestComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "TestComponent.h" 2 | 3 | #include 4 | 5 | #include 6 | 7 | unsigned TestComponent::ID = 0; 8 | 9 | TestComponent::TestComponent(GameObject& owner, nlohmann::json ) 10 | : Component(owner) 11 | { 12 | 13 | } 14 | 15 | TestComponent::TestComponent(GameObject& owner, float someVal) 16 | : Component(owner) 17 | , SomeVal(someVal) 18 | { 19 | 20 | } 21 | 22 | void TestComponent::setup() 23 | {} 24 | 25 | void TestComponent::update(const sf::Time& ) 26 | {} 27 | 28 | void TestComponent::fixed_update(const sf::Time &) 29 | {} 30 | 31 | void TestComponent::render(Renderer& ) 32 | {} 33 | 34 | std::unique_ptr TestComponent::clone(GameObject& newGameObject) 35 | { 36 | return std::make_unique(newGameObject, SomeVal); 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/gameobject/components/TestComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Component.h" 4 | 5 | #include 6 | 7 | class TestComponent : public Component 8 | { 9 | public: 10 | TestComponent(GameObject& owner, nlohmann::json json); 11 | TestComponent(GameObject& owner, float someVal); 12 | 13 | void setup() override; 14 | void update(const sf::Time& deltaTime) override; 15 | void fixed_update(const sf::Time &deltaTime) override; 16 | void render(Renderer& renderTarget) override; 17 | std::unique_ptr clone(GameObject& newGameObject) override; 18 | 19 | static unsigned ID; 20 | 21 | float SomeVal; 22 | }; 23 | -------------------------------------------------------------------------------- /src/gameobject/components/TransformComponent.cpp: -------------------------------------------------------------------------------- 1 | #include "TransformComponent.h" 2 | #include "../../util/Mathf.h" 3 | 4 | unsigned TransformComponent::ID = 2; 5 | 6 | TransformComponent::TransformComponent(GameObject &owner, sf::Vector2f position, float rotation, bool renderTransform) 7 | : Component(owner), position(position), rotation(rotation), renderTransform(renderTransform) 8 | { 9 | 10 | } 11 | 12 | TransformComponent::TransformComponent(GameObject &owner, nlohmann::json json) 13 | : Component(owner) 14 | { 15 | position = sf::Vector2f(json["position"][0], json["position"][1]); 16 | rotation = json["rotation"]; 17 | renderTransform = json["renderTransform"]; 18 | } 19 | 20 | void TransformComponent::setup() 21 | {} 22 | 23 | void TransformComponent::update(const sf::Time& ) 24 | {} 25 | 26 | void TransformComponent::fixed_update(const sf::Time &) 27 | {} 28 | 29 | void TransformComponent::render(Renderer& renderTarget) 30 | { 31 | if (renderTransform) 32 | { 33 | static sf::CircleShape circle = sf::CircleShape(6); 34 | circle.setOrigin(circle.getRadius(), circle.getRadius()); 35 | circle.setPosition(position.x, position.y); 36 | circle.setFillColor(sf::Color::White); 37 | renderTarget.draw(circle, ZIndex::DEBUG); 38 | 39 | static sf::CircleShape rotationIndicator = sf::CircleShape(2); 40 | rotationIndicator.setOrigin(rotationIndicator.getRadius(), rotationIndicator.getRadius()); 41 | rotationIndicator.setPosition(cos(math::radians(rotation)) * 10 + position.x, sin(math::radians(rotation)) * 10 + position.y); 42 | rotationIndicator.setFillColor(sf::Color::Red); 43 | renderTarget.draw(rotationIndicator, ZIndex::DEBUG); 44 | } 45 | } 46 | 47 | void TransformComponent::lookAt(TransformComponent* target) 48 | { 49 | rotation = math::degrees(atan2((target->position.y - position.y), (target->position.x - position.x))); 50 | } 51 | 52 | std::unique_ptr TransformComponent::clone(GameObject& newGameObject) 53 | { 54 | return std::make_unique(newGameObject, position, rotation, renderTransform); 55 | } 56 | 57 | sf::Vector2f TransformComponent::front() const 58 | { 59 | return { static_cast(cos(math::radians(rotation))), 60 | static_cast(sin(math::radians(rotation))) }; 61 | } 62 | 63 | sf::Vector2f TransformComponent::right() const 64 | { 65 | return { static_cast(cos(math::radians(rotation + 90))), 66 | static_cast(sin(math::radians(rotation + 90))) }; 67 | } 68 | -------------------------------------------------------------------------------- /src/gameobject/components/TransformComponent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Component.h" 4 | #include 5 | 6 | class TransformComponent : public Component 7 | { 8 | public: 9 | TransformComponent(GameObject& owner, sf::Vector2f position, float rotation, bool renderTransform = false); 10 | TransformComponent(GameObject& owner, nlohmann::json json); 11 | 12 | void setup() override; 13 | void update(const sf::Time& deltaTime) override; 14 | void fixed_update(const sf::Time &deltaTime) override; 15 | void render(Renderer& renderTarget) override; 16 | std::unique_ptr clone(GameObject& newGameObject) override; 17 | 18 | static unsigned ID; 19 | 20 | sf::Vector2f position; 21 | double rotation; 22 | bool renderTransform = false; 23 | 24 | void lookAt(TransformComponent* target); 25 | sf::Vector2f front() const; 26 | sf::Vector2f right() const; 27 | }; 28 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Game.h" 2 | 3 | int main() 4 | { 5 | Game game; 6 | game.runGame(); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /src/resource/ResourceHolder.cpp: -------------------------------------------------------------------------------- 1 | #include "ResourceHolder.h" 2 | 3 | ResourceHolder& ResourceHolder::get() 4 | { 5 | static ResourceHolder holder; 6 | return holder; 7 | } 8 | 9 | ResourceHolder::ResourceHolder() 10 | : fonts ("fonts", "otf") 11 | , textures ("txrs", "png") 12 | , soundBuffers ("sfx", "ogg") 13 | { 14 | 15 | } -------------------------------------------------------------------------------- /src/resource/ResourceHolder.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #include "ResourceManager.h" 6 | #include "../util/NonCopyable.h" 7 | #include "../util/NonMoveable.h" 8 | 9 | class ResourceHolder : public NonCopyable, public NonMovable 10 | { 11 | public: 12 | static ResourceHolder& get(); 13 | 14 | ResourceManager fonts; 15 | ResourceManager textures; 16 | ResourceManager soundBuffers; 17 | 18 | private: 19 | ResourceHolder(); 20 | }; 21 | -------------------------------------------------------------------------------- /src/resource/ResourceManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | template 6 | class ResourceManager 7 | { 8 | using CrString = const std::string&; 9 | 10 | public: 11 | ResourceManager (CrString folder, CrString extention) 12 | : m_folder ("res/" + folder + "/") 13 | , m_extention ("." + extention) 14 | { } 15 | 16 | const Resource& get(CrString name) 17 | { 18 | if (!exists(name)) 19 | { 20 | add(name); 21 | } 22 | 23 | return m_resources.at(name); 24 | } 25 | 26 | bool exists(CrString name) const 27 | { 28 | return m_resources.find(name) != m_resources.end(); 29 | } 30 | 31 | void add(CrString name) 32 | { 33 | Resource r; 34 | 35 | //if the resource fails to load, then it adds a default "fail" resource 36 | if(!r.loadFromFile(getFullname(name))) 37 | { 38 | Resource fail; 39 | fail.loadFromFile(m_folder + "_fail_" + m_extention); 40 | m_resources.insert(std::make_pair(name, fail)); 41 | } 42 | else 43 | { 44 | m_resources.insert(std::make_pair(name, r)); 45 | } 46 | } 47 | 48 | private: 49 | std::string getFullname(CrString name) 50 | { 51 | return m_folder + name + m_extention; 52 | } 53 | 54 | const std::string m_folder; 55 | const std::string m_extention; 56 | 57 | std::unordered_map m_resources; 58 | }; 59 | -------------------------------------------------------------------------------- /src/state/GameState.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include "../util/NonCopyable.h" 5 | #include "../systems/ColliderSpace.h" 6 | #include "../util/DebugRenderer.h" 7 | #include "../util/Renderer.h" 8 | #include "../util/Renderer.h" 9 | 10 | class Game; 11 | 12 | class GameState : public NonCopyable 13 | { 14 | public: 15 | GameState(Game& game) 16 | : m_pGame (&game){} 17 | 18 | ~GameState() = default; 19 | 20 | virtual void handleEvents(sf::Event e) = 0; 21 | virtual void handleInput () = 0; 22 | 23 | virtual void update (const sf::Time& deltaTime) = 0; 24 | virtual void fixedUpdate(const sf::Time& deltaTime) = 0; 25 | 26 | virtual void setup() = 0; 27 | 28 | virtual void render(Renderer& renderTarget) = 0; 29 | 30 | Game* getGamePointer() { return m_pGame;} 31 | ColliderSpace* getColliderSpace() { return &m_ColliderSpace; } 32 | DebugRenderer* getDebugRenderer() { return &m_debugRenderer; } 33 | 34 | protected: 35 | Game* m_pGame; 36 | ColliderSpace m_ColliderSpace; 37 | DebugRenderer m_debugRenderer; 38 | }; 39 | 40 | -------------------------------------------------------------------------------- /src/state/PlayingState.cpp: -------------------------------------------------------------------------------- 1 | #include "PlayingState.h" 2 | #include "../gameobject/components/TransformComponent.h" 3 | #include "../gameobject/components/TestComponent.h" 4 | #include "../gameobject/components/PlayerComponent.h" 5 | #include "../gameobject/components/CameraComponent.h" 6 | #include "../gameobject/components/MouseComponent.h" 7 | #include "../gameobject/components/FPSComponent.h" 8 | #include "../gameobject/components/CameraComponent.h" 9 | #include "../gameobject/components/RendererComponent.h" 10 | 11 | PlayingState::PlayingState(Game& game) 12 | : GameState (game) 13 | { 14 | 15 | } 16 | 17 | 18 | void PlayingState::handleEvents(sf::Event) 19 | { 20 | 21 | } 22 | 23 | void PlayingState::handleInput() 24 | { 25 | 26 | } 27 | 28 | void PlayingState::update(const sf::Time& deltaTime) 29 | { 30 | for (size_t i=0; iupdate(deltaTime); 32 | } 33 | m_ColliderSpace.update(deltaTime); 34 | } 35 | 36 | void PlayingState::fixedUpdate(const sf::Time& deltaTime) 37 | { 38 | for (size_t i=0; ifixed_update(deltaTime); 40 | } 41 | } 42 | 43 | void PlayingState::render(Renderer& renderTarget) 44 | { 45 | renderTarget.setView(cameraComponent->view); 46 | for (size_t i=0; irender(renderTarget); 48 | } 49 | m_debugRenderer.draw(renderTarget); 50 | } 51 | 52 | void PlayingState::setup() 53 | { 54 | constexpr int RANGE = 25; 55 | for (int x = -RANGE; x <= RANGE; ++x) 56 | { 57 | for (int y = -RANGE; y <= RANGE; ++y) 58 | { 59 | m_gameObjects.push_back(m_pGame->getGameObjectFactory().createGameObject("grass")); 60 | auto ground = m_gameObjects.back(); 61 | ground->getComponent()->position = sf::Vector2f(x * 80, y * 80); 62 | } 63 | } 64 | m_gameObjects.push_back(m_pGame->getGameObjectFactory().createGameObject("mouse")); 65 | m_mouse = m_gameObjects.back(); 66 | m_gameObjects.push_back(m_pGame->getGameObjectFactory().createGameObject("player")); 67 | m_player = m_gameObjects.back(); 68 | m_gameObjects.push_back(m_pGame->getGameObjectFactory().createGameObject("bd")); 69 | m_building = m_gameObjects.back(); 70 | m_gameObjects.push_back(m_pGame->getGameObjectFactory().createGameObject("fps")); 71 | m_fps = m_gameObjects.back(); 72 | 73 | m_player->getComponent()->mouse = m_mouse->getComponent(); 74 | cameraComponent = m_player->getComponent(); 75 | m_mouse->getComponent()->cameraTransform = m_player->getComponent(); 76 | m_mouse->getComponent()->cameraComponent = cameraComponent; 77 | m_fps->getComponent()->camera = cameraComponent; 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/state/PlayingState.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "GameState.h" 4 | #include "../Game.h" 5 | #include "../util/Renderer.h" 6 | 7 | class CameraComponent; 8 | 9 | class PlayingState: public GameState 10 | { 11 | public: 12 | PlayingState(Game& game); 13 | 14 | void handleEvents(sf::Event e) override; 15 | void handleInput () override; 16 | 17 | void update (const sf::Time& deltaTime) override; 18 | void fixedUpdate(const sf::Time& deltaTime) override; 19 | 20 | void render(Renderer& renderTarget) override; 21 | 22 | void setup() override; 23 | 24 | private: 25 | 26 | std::vector> m_gameObjects; 27 | 28 | std::shared_ptr m_player; 29 | std::shared_ptr m_mouse; 30 | std::shared_ptr m_building; 31 | std::shared_ptr m_fps; 32 | 33 | CameraComponent* cameraComponent; 34 | }; 35 | 36 | -------------------------------------------------------------------------------- /src/systems/Collider/AABBCollider.cpp: -------------------------------------------------------------------------------- 1 | #include "AABBCollider.h" 2 | 3 | AABBCollider::AABBCollider() 4 | : AABBCollider({0, 0}, {0, 0}) {} 5 | 6 | AABBCollider::AABBCollider(sf::Vector2f const& origin, sf::Vector2f const& dimension) 7 | : m_points({ 8 | { origin.x, origin.y }, 9 | { origin.x + dimension.x, origin.y }, 10 | { origin.x + dimension.x, origin.y + dimension.y }, 11 | { origin.x, origin.y + dimension.y } 12 | }) {} 13 | 14 | AABBCollider::~AABBCollider() 15 | {} 16 | 17 | std::vector AABBCollider::getPoints(sf::Vector2f const& offset) const 18 | { 19 | auto pts = m_points; 20 | for(auto& v : pts) v += offset; 21 | return pts; 22 | } 23 | 24 | std::vector AABBCollider::getNormals() const 25 | { 26 | return { 27 | { 0, 1 }, 28 | { 1, 0 } 29 | }; 30 | } 31 | 32 | Projection AABBCollider::project(sf::Vector2f const& normal, sf::Vector2f const& offset) const 33 | { 34 | auto p = m_points[0] + offset; 35 | float min = p.x * normal.x + p.y * normal.y; 36 | float max = p.x * normal.x + p.y * normal.y; 37 | 38 | for(int i = 1; i < 4; ++i) 39 | { 40 | p = m_points[i] + offset; 41 | float dot = p.x * normal.x + p.y * normal.y; 42 | if (dot < min) min = dot; 43 | if (dot > max) max = dot; 44 | } 45 | return { min, max }; 46 | }; 47 | 48 | sf::Vector2f AABBCollider::getOrigin() const 49 | { 50 | return m_points[0]; 51 | } 52 | 53 | sf::Vector2f AABBCollider::getDimension() const 54 | { 55 | return m_points[2] - m_points[0]; 56 | } 57 | -------------------------------------------------------------------------------- /src/systems/Collider/AABBCollider.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "SAT_Collider.h" 4 | 5 | class AABBCollider : public SAT_Collider 6 | { 7 | public: 8 | 9 | AABBCollider(sf::Vector2f const& origin, sf::Vector2f const& dimension); 10 | AABBCollider(); 11 | virtual ~AABBCollider(); 12 | 13 | std::vector getPoints(sf::Vector2f const& offset = sf::Vector2f(0, 0)) const override; 14 | std::vector getNormals() const override; 15 | Projection project(sf::Vector2f const& normal, sf::Vector2f const& offset) const override; 16 | 17 | sf::Vector2f getOrigin() const; 18 | sf::Vector2f getDimension() const; 19 | 20 | private: 21 | 22 | std::vector m_points; 23 | 24 | }; -------------------------------------------------------------------------------- /src/systems/Collider/SAT_Collider.cpp: -------------------------------------------------------------------------------- 1 | #include "SAT_Collider.h" 2 | 3 | float Projection::size() const 4 | { 5 | return second - first; 6 | } 7 | 8 | bool Projection::overlap(Projection const& p0, Projection const& p1) 9 | { 10 | assert(p0.first < p0.second); 11 | assert(p1.first < p1.second); 12 | return !( 13 | (p1.first < p0.first && p1.second < p0.first) || 14 | (p1.first > p0.second && p1.second > p0.second) 15 | ); 16 | } 17 | 18 | Projection Projection::overlap_area(Projection const& p0, Projection const& p1) 19 | { 20 | assert(overlap(p0, p1)); 21 | return { std::max(p0.first , p1.first ) 22 | , std::min(p0.second, p1.second) }; 23 | } 24 | -------------------------------------------------------------------------------- /src/systems/Collider/SAT_Collider.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include 6 | #include 7 | 8 | struct Projection 9 | { 10 | float first; 11 | float second; 12 | 13 | float size() const; 14 | 15 | static bool overlap(Projection const& p0, Projection const& p1); 16 | static Projection overlap_area(Projection const& p0, Projection const& p1); 17 | }; 18 | 19 | class SAT_Collider 20 | { 21 | public: 22 | 23 | virtual ~SAT_Collider() {} 24 | 25 | virtual std::vector getPoints(sf::Vector2f const& offset = sf::Vector2f(0, 0)) const = 0; 26 | virtual std::vector getNormals() const = 0; 27 | virtual Projection project(sf::Vector2f const& normal, sf::Vector2f const& offset) const = 0; 28 | }; -------------------------------------------------------------------------------- /src/systems/ColliderSpace.cpp: -------------------------------------------------------------------------------- 1 | #include "ColliderSpace.h" 2 | 3 | #include "../gameobject/GameObject.h" 4 | #include "../gameobject/components/ColliderAABBComponent.h" 5 | #include "../gameobject/components/RigidBodyComponent.h" 6 | #include "../gameobject/components/TransformComponent.h" 7 | 8 | Raycast::Raycast() 9 | : Raycast({0, 0}, {1, 0}) {} 10 | 11 | Raycast::Raycast(sf::Vector2f const& start, sf::Vector2f const& direction, float distance) 12 | : start(start) 13 | , direction(direction) 14 | , distance(distance) {} 15 | 16 | bool Raycast::is_infinite() const 17 | { 18 | return distance >= Raycast::max_distance; 19 | } 20 | 21 | sf::Vector2f Raycast::at(float d) const 22 | { 23 | return start + direction * d; 24 | } 25 | 26 | float Raycast::at_x(float d) const 27 | { 28 | return start.x + direction.x * d; 29 | } 30 | 31 | float Raycast::at_y(float d) const 32 | { 33 | return start.y + direction.y * d; 34 | } 35 | 36 | RaycastInfo::RaycastInfo() 37 | : RaycastInfo(nullptr, 0) {} 38 | 39 | RaycastInfo::RaycastInfo(TransformComponent* other, float distance) 40 | : other(other) 41 | , distance(distance) {} 42 | 43 | RaycastInfo::operator bool() const 44 | { 45 | return other != nullptr; 46 | } 47 | 48 | bool ColliderOwner::operator != (ColliderOwner const& o) const 49 | { 50 | return !(*this == o); 51 | } 52 | 53 | bool ColliderOwner::operator == (ColliderOwner const& o) const 54 | { 55 | return tf == o.tf || rb == o.rb; 56 | } 57 | 58 | void ColliderSpace::insert(ColliderOwner const& collider) 59 | { 60 | m_colliders.push_back(collider); 61 | } 62 | 63 | void ColliderSpace::remove(ColliderOwner const& collider) 64 | { 65 | m_colliders.erase(std::remove(m_colliders.begin(), m_colliders.end(), collider), m_colliders.end()); 66 | } 67 | 68 | void ColliderSpace::remove(TransformComponent* tf) 69 | { 70 | remove({tf, nullptr, nullptr, nullptr, nullptr}); 71 | } 72 | 73 | void ColliderSpace::updateRigidBody(TransformComponent* tf, RigidBodyComponent* rb) 74 | { 75 | for(auto& c : m_colliders) 76 | { 77 | if (c.tf == tf) 78 | { 79 | c.rb = rb; 80 | break; 81 | } 82 | } 83 | } 84 | 85 | void ColliderSpace::update(sf::Time const&) 86 | { 87 | for (auto it0 = m_colliders.begin(); it0 != m_colliders.end(); ++it0) 88 | for (auto it1 = it0 + 1; it1 != m_colliders.end(); ++it1) 89 | checkCollision(*it0, *it1); 90 | } 91 | 92 | RaycastInfo ColliderSpace::raycast(Raycast const& r, std::unordered_set const& ignored) 93 | { 94 | RaycastInfo info(nullptr, r.distance); 95 | for (auto& c : m_colliders) 96 | { 97 | if (ignored.find(c.tf) == ignored.end()) 98 | { 99 | checkRaycastCollision(r, c, info); 100 | if (r.distance == 0) 101 | return info; 102 | } 103 | } 104 | return info; 105 | } 106 | 107 | void ColliderSpace::resolveCollision(ColliderOwner& c0, ColliderOwner& c1, sf::Vector2f const& direction) 108 | { 109 | auto rb0 = c0.rb; 110 | auto rb1 = c1.rb; 111 | if (rb0 && rb1) 112 | { 113 | float tot = rb0->inv_mass + rb1->inv_mass; 114 | float f0 = rb0->inv_mass / tot; 115 | float f1 = rb1->inv_mass / tot; 116 | 117 | constexpr float epsilon = 0.01; 118 | assert(f0 + f1 > 1 - epsilon || f0 + f1 < 1 + epsilon); 119 | 120 | c0.tf->position += direction * f0; 121 | c1.tf->position -= direction * f1; 122 | // event 123 | CollisionInfo ci0 {c1.tf, c1.collider, direction * f0}; 124 | CollisionInfo ci1 {c0.tf, c0.collider, direction * f1}; 125 | c0.onCollision(ci0); 126 | c1.onCollision(ci1); 127 | } 128 | TriggerInfo t0 {c1.tf, c1.collider}; 129 | TriggerInfo t1 {c0.tf, c0.collider}; 130 | c0.onTrigger(t0); 131 | c1.onTrigger(t1); 132 | } 133 | 134 | void ColliderSpace::checkRaycastCollision(Raycast const& r, ColliderOwner& co, RaycastInfo& info) 135 | { 136 | sf::Vector2f normal(r.direction.y, -r.direction.x); 137 | Projection proj = co.collider->project(normal, co.tf->position); 138 | float rayproj = r.start.x * normal.x + r.start.y * normal.y; 139 | if (proj.first <= rayproj && rayproj <= proj.second) { 140 | 141 | auto pts = co.collider->getPoints(co.tf->position); 142 | for (unsigned int i = 0; i < pts.size(); i++) 143 | { 144 | sf::Vector2f c = pts[i]; 145 | sf::Vector2f m = pts[(i+1)%pts.size()] - c; 146 | float d = r.direction.y * m.x - r.direction.x * m.y; 147 | if (d != 0) 148 | { 149 | float n = ((r.start.x - c.x) * r.direction.y - (r.start.y - c.y) * r.direction.x) / d; 150 | if (n >= 0 && n <= 1) 151 | { 152 | sf::Vector2f intersection = c + m * n; 153 | float ts; 154 | if (r.direction.y == 0) 155 | ts = (intersection.x - r.start.x) / r.direction.x; 156 | else 157 | ts = (intersection.y - r.start.y) / r.direction.y; 158 | if (ts >= 0 && ts <= r.distance) 159 | { 160 | info.other = co.tf; 161 | info.distance = ts; 162 | return; 163 | } 164 | } 165 | } 166 | } 167 | 168 | } 169 | } 170 | 171 | void ColliderSpace::checkCollision(ColliderOwner& c0, ColliderOwner& c1) 172 | { 173 | std::vector normals; // remove parallele normal ? with an unordered set ? (but sf::Vectorf doesn't implement a hash's function if i'm right) 174 | auto n0 = c0.collider->getNormals(); 175 | auto n1 = c1.collider->getNormals(); 176 | normals.reserve(n0.size() + n1.size()); 177 | for (auto& n : n0) normals.push_back(n); 178 | for (auto& n : n1) normals.push_back(n); 179 | 180 | float min_dist = std::numeric_limits::max(); 181 | sf::Vector2f min_axis; 182 | 183 | for (auto const& n : normals) 184 | { 185 | Projection p0 = c0.collider->project(n, c0.tf->position); 186 | Projection p1 = c1.collider->project(n, c1.tf->position); 187 | 188 | if (!Projection::overlap(p0, p1)) 189 | return; 190 | float mtv = getMTV(p0, p1); 191 | if (std::abs(mtv) < min_dist) min_axis = mtv < 0 ? -n : n, min_dist = std::abs(mtv); 192 | } 193 | resolveCollision(c0, c1, min_axis); 194 | } 195 | 196 | float ColliderSpace::getMTV(Projection const& p0, Projection const& p1) const 197 | { 198 | // containment 199 | if (p0.first < p1.first && p0.second > p1.second) 200 | return std::min(p1.second - p0.first, p0.second - p1.first); 201 | if (p0.first > p1.first && p0.second > p1.second) 202 | return std::min(p0.second - p1.first, p1.second - p0.first); 203 | 204 | if (p0.first > p1.first) 205 | return p0.second - p1.first; 206 | return p1.first - p0.second; 207 | } -------------------------------------------------------------------------------- /src/systems/ColliderSpace.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Collider/SAT_Collider.h" 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | class ColliderAABBComponent; 13 | class TransformComponent; 14 | class RigidBodyComponent; 15 | 16 | struct CollisionInfo 17 | { 18 | TransformComponent* other; 19 | SAT_Collider* other_collider; 20 | 21 | sf::Vector2f resolveMovement; 22 | }; 23 | 24 | struct TriggerInfo 25 | { 26 | TransformComponent* other; 27 | SAT_Collider* other_collider; 28 | }; 29 | 30 | struct Raycast 31 | { 32 | static constexpr float max_distance = 100000; // to avoid overflow... // std::numeric_limits::max() 33 | 34 | Raycast(sf::Vector2f const& start, sf::Vector2f const& direction, float distance = max_distance); 35 | Raycast(); 36 | 37 | bool is_infinite() const; 38 | sf::Vector2f at(float d) const; 39 | float at_x(float d) const; 40 | float at_y(float d) const; 41 | 42 | sf::Vector2f start, direction; 43 | float distance; 44 | }; 45 | 46 | struct ColliderOwner 47 | { 48 | bool operator == (ColliderOwner const& o) const; 49 | bool operator != (ColliderOwner const& o) const; 50 | 51 | TransformComponent* tf; 52 | RigidBodyComponent* rb; 53 | SAT_Collider* collider; 54 | 55 | std::function onCollision; 56 | std::function onTrigger; 57 | }; 58 | 59 | struct RaycastInfo 60 | { 61 | RaycastInfo(TransformComponent* other, float distance); 62 | RaycastInfo(); 63 | 64 | operator bool() const; 65 | 66 | TransformComponent* other; 67 | float distance; 68 | }; 69 | 70 | class ColliderSpace 71 | { 72 | public: 73 | 74 | void insert(ColliderOwner const& colider); 75 | void remove(ColliderOwner const& collider); 76 | void remove(TransformComponent* tf); 77 | void updateRigidBody(TransformComponent* tf, RigidBodyComponent* rb); 78 | 79 | void update(sf::Time const& time); 80 | 81 | RaycastInfo raycast(Raycast const& r, std::unordered_set const& ignored = {}); 82 | 83 | private: 84 | 85 | void checkCollision(ColliderOwner& c0, ColliderOwner& c1); 86 | void checkRaycastCollision(Raycast const& r, ColliderOwner& c, RaycastInfo& info); 87 | void resolveCollision(ColliderOwner& c0, ColliderOwner& c1, sf::Vector2f const& direction); 88 | float getMTV(Projection const& p0, Projection const& p1) const; 89 | 90 | std::vector m_colliders; 91 | }; -------------------------------------------------------------------------------- /src/util/DebugRenderer.cpp: -------------------------------------------------------------------------------- 1 | #include "DebugRenderer.h" 2 | 3 | DebugRenderer::Options::Options(int frame, sf::Color const& color) 4 | : frame(frame) 5 | , color(color) {} 6 | 7 | DebugRenderer::ToDraw::ToDraw(Raycast const& r, DebugRenderer::Options const& options) 8 | : type(DebugRenderer::ToDraw::Type::Raycast) 9 | , raycast(r) 10 | , options(options) {} 11 | 12 | DebugRenderer::ToDraw::ToDraw(sf::Text const& t, DebugRenderer::Options const& options) 13 | : type(DebugRenderer::ToDraw::Type::Text) 14 | , text(t) 15 | , options(options) {} 16 | 17 | DebugRenderer::ToDraw& DebugRenderer::ToDraw::operator=(ToDraw const& t) 18 | { 19 | type = t.type; 20 | options = t.options; 21 | if (type == DebugRenderer::ToDraw::Type::Raycast) 22 | { 23 | raycast = t.raycast; 24 | } 25 | else 26 | { 27 | text = t.text; 28 | } 29 | return *this; 30 | } 31 | 32 | DebugRenderer::ToDraw::~ToDraw() 33 | {} 34 | 35 | DebugRenderer::ToDraw::ToDraw(ToDraw const& t) 36 | { 37 | type = t.type; 38 | options = t.options; 39 | if (type == DebugRenderer::ToDraw::Type::Raycast) 40 | { 41 | raycast = t.raycast; 42 | } 43 | else 44 | { 45 | text = t.text; 46 | } 47 | } 48 | 49 | void DebugRenderer::drawRaycast(Raycast const& r, DebugRenderer::Options const& options) 50 | { 51 | m_toDraw.emplace_back(r, options); 52 | } 53 | 54 | void DebugRenderer::drawText(sf::Text const& t, DebugRenderer::Options const& options) 55 | { 56 | m_toDraw.emplace_back(t, options); 57 | } 58 | 59 | void DebugRenderer::draw(Renderer& renderer) 60 | { 61 | for (auto& d : m_toDraw) 62 | { 63 | if (d.type == DebugRenderer::ToDraw::Type::Raycast) 64 | { 65 | sf::Vertex vs[2]; 66 | vs[0].position = d.raycast.start; 67 | vs[0].color = d.options.color; 68 | vs[1].position = d.raycast.start + d.raycast.direction * d.raycast.distance; 69 | vs[1].color = d.options.color; 70 | renderer.draw(vs, 2, sf::PrimitiveType::Lines); 71 | } 72 | else if (d.type == DebugRenderer::ToDraw::Type::Text) 73 | { 74 | renderer.draw(d.text); 75 | } 76 | d.options.frame--; 77 | } 78 | m_toDraw.erase( std::remove_if(m_toDraw.begin(), m_toDraw.end(), [](DebugRenderer::ToDraw const& d) 79 | { 80 | return d.options.frame < 0; 81 | }), 82 | m_toDraw.end() ); 83 | } 84 | -------------------------------------------------------------------------------- /src/util/DebugRenderer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../systems/ColliderSpace.h" 4 | #include "Renderer.h" 5 | 6 | #include 7 | 8 | class DebugRenderer 9 | { 10 | public: 11 | 12 | struct Options 13 | { 14 | Options(int frame = 1, sf::Color const& color = sf::Color::Green); 15 | 16 | int frame; 17 | sf::Color color; 18 | }; 19 | 20 | void drawRaycast(Raycast const& r, Options const& options = Options()); 21 | void drawText(sf::Text const& text, Options const& options = Options()); 22 | 23 | void draw(Renderer& renderer); 24 | 25 | private: 26 | 27 | struct ToDraw 28 | { 29 | ToDraw(Raycast const& r, Options const& o); 30 | ToDraw(sf::Text const& t, Options const& o); 31 | ToDraw(ToDraw const& t); 32 | ~ToDraw(); 33 | ToDraw& operator=(ToDraw const& t); 34 | 35 | enum class Type 36 | { 37 | Raycast, 38 | Text 39 | } type; 40 | 41 | union 42 | { 43 | Raycast raycast; 44 | sf::Text text; 45 | }; 46 | Options options; 47 | }; 48 | 49 | std::vector m_toDraw; 50 | }; -------------------------------------------------------------------------------- /src/util/FileUtil.cpp: -------------------------------------------------------------------------------- 1 | #include "FileUtil.h" 2 | 3 | // Code is referenced from: 4 | // https://vicidi.wordpress.com/2015/03/09/reading-utf-file-with-bom-to-utf-8-encoded-stdstring-in-c11-on-windows/ 5 | 6 | #include 7 | #include 8 | 9 | #define ENCODING_ASCII 0 10 | #define ENCODING_UTF8 1 11 | 12 | 13 | std::string getFileContents(const std::string& filePath) 14 | { 15 | std::string result; 16 | std::ifstream ifs(filePath); 17 | std::stringstream ss; 18 | 19 | if (!ifs.is_open()) 20 | { 21 | return result; 22 | } 23 | /* 24 | if (ifs.eof()) 25 | result.clear(); 26 | else 27 | { 28 | int ch1 = ifs.get(); 29 | int ch2 = ifs.get(); 30 | int ch3 = ifs.get(); 31 | if (!(ch1 == 0xef && ch2 == 0xbb && ch3 == 0xbf)) 32 | ifs.seekg(0); 33 | } 34 | */ 35 | ss << ifs.rdbuf() << '\0'; 36 | result = ss.str(); 37 | 38 | return result; 39 | } 40 | -------------------------------------------------------------------------------- /src/util/FileUtil.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | std::string getFileContents(const std::string& filePath); 6 | 7 | -------------------------------------------------------------------------------- /src/util/Mathf.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | // Defines math constants and helper functions that are not included in . 6 | namespace math 7 | { 8 | using default_float_t = float; 9 | 10 | // Constant return value functions 11 | 12 | // Returns (PI). 13 | template 14 | constexpr T pi() 15 | { 16 | return static_cast(3.1415926535897932384626433832795); 17 | } 18 | 19 | // Returns (PI / 2). 20 | template 21 | constexpr T pid2() 22 | { 23 | return static_cast(1.5707963267948966192313216916398); 24 | } 25 | 26 | // Returns (PI * 2). 27 | template 28 | constexpr T pim2() 29 | { 30 | return static_cast(6.283185307179586476925286766559); 31 | } 32 | 33 | // Returns (PI / 4). 34 | template 35 | constexpr T pid4() 36 | { 37 | return static_cast(0.78539816339744830961566084581988); 38 | } 39 | 40 | // Returns (sqrt(2)). 41 | template 42 | constexpr T sqrt2() 43 | { 44 | return static_cast(1.4142135623730950488016887242097); 45 | } 46 | 47 | // Returns (sqrt(2) / 2). 48 | template 49 | constexpr T sqrt2d2() 50 | { 51 | return static_cast(0.70710678118654752440084436210485); 52 | } 53 | 54 | // Returns (PI / 180). 55 | template 56 | constexpr T deg2Rad() 57 | { 58 | return static_cast(0.01745329251994329576923690768489); 59 | } 60 | 61 | // Returns (180 / PI). 62 | template 63 | constexpr T rad2Deg() 64 | { 65 | return static_cast(57.295779513082320876798154814105); 66 | } 67 | 68 | // Helper functions 69 | 70 | // Returns the value of degrees in radians. 71 | template 72 | inline T radians(T degrees) 73 | { 74 | return degrees * deg2Rad(); 75 | } 76 | 77 | // Returns the value of radians in degrees. 78 | template 79 | inline T degrees(T radians) 80 | { 81 | return radians * rad2Deg(); 82 | } 83 | } -------------------------------------------------------------------------------- /src/util/NonCopyable.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct NonCopyable 4 | { 5 | NonCopyable() = default; 6 | 7 | NonCopyable& operator=(const NonCopyable&) = delete; 8 | 9 | NonCopyable(const NonCopyable&) = delete; 10 | }; 11 | -------------------------------------------------------------------------------- /src/util/NonMoveable.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct NonMovable 4 | { 5 | NonMovable() = default; 6 | NonMovable& operator = (NonMovable&&) = delete; 7 | NonMovable(NonMovable&&) = delete; 8 | }; -------------------------------------------------------------------------------- /src/util/Renderer.cpp: -------------------------------------------------------------------------------- 1 | #include "Renderer.h" 2 | 3 | Renderer::Renderer(sf::RenderTarget& renderer) 4 | : m_renderer(&renderer), 5 | m_screenRect(renderer.getViewport(renderer.getView())) {} 6 | 7 | Renderer::Renderer() 8 | : m_renderer(nullptr), 9 | m_screenRect(sf::IntRect(0, 0, 0, 0)) {} 10 | 11 | void Renderer::setRenderer(sf::RenderTarget& renderer) 12 | { 13 | this->m_renderer = &renderer; 14 | } 15 | 16 | void Renderer::setView(sf::View const& view) 17 | { 18 | m_renderer->setView(view); 19 | m_screenRect = m_renderer->getViewport(view); 20 | auto center = view.getCenter(); 21 | m_screenRect.left = center.x - m_screenRect.width / 2.f; 22 | m_screenRect.top = center.y - m_screenRect.height / 2.f; 23 | } 24 | 25 | const sf::View& Renderer::getView() const 26 | { 27 | return m_renderer->getView(); 28 | } 29 | 30 | sf::IntRect Renderer::getViewport(sf::View const& view) const 31 | { 32 | return m_renderer->getViewport(view); 33 | } 34 | 35 | sf::Vector2u Renderer::getSize() const 36 | { 37 | return m_renderer->getSize(); 38 | } 39 | 40 | bool Renderer::isInScreen(sf::FloatRect const& rect) const 41 | { 42 | return !( rect.left > m_screenRect.left + m_screenRect.width 43 | || rect.left + rect.width < m_screenRect.left 44 | || rect.top > m_screenRect.top + m_screenRect.height 45 | || rect.top + rect.height < m_screenRect.top 46 | ); 47 | } 48 | 49 | void Renderer::draw(sf::Shape const& shape, ZIndex_t zindex, sf::RenderStates const& states) 50 | { 51 | auto bounds = shape.getGlobalBounds(); 52 | if(isInScreen(bounds)) 53 | { 54 | m_drawCallbacks.push_back({ 55 | zindex, 56 | [&shape, states] (sf::RenderTarget& renderer) 57 | { 58 | renderer.draw(shape, states); 59 | } 60 | }); 61 | } 62 | } 63 | 64 | void Renderer::draw(sf::Sprite const& sprite, ZIndex_t zindex, sf::RenderStates const& states) 65 | { 66 | auto bounds = sprite.getGlobalBounds(); 67 | if(isInScreen(bounds)) 68 | { 69 | m_drawCallbacks.push_back({ 70 | zindex, 71 | [&sprite, states] (sf::RenderTarget& renderer) 72 | { 73 | renderer.draw(sprite, states); 74 | } 75 | }); 76 | } 77 | } 78 | 79 | void Renderer::draw(sf::Text const& text, ZIndex_t zindex, sf::RenderStates const& states) 80 | { 81 | auto bounds = text.getGlobalBounds(); 82 | if(isInScreen(bounds)) 83 | { 84 | m_drawCallbacks.push_back({ 85 | zindex, 86 | [&text, states] (sf::RenderTarget& renderer) 87 | { 88 | renderer.draw(text, states); 89 | } 90 | }); 91 | } 92 | } 93 | 94 | void Renderer::draw(sf::VertexArray const& vs, ZIndex_t zindex, sf::RenderStates const& states) 95 | { 96 | auto bounds = vs.getBounds(); 97 | if(isInScreen(bounds)) 98 | { 99 | m_drawCallbacks.push_back({ 100 | zindex, 101 | [&vs, states] (sf::RenderTarget& renderer) 102 | { 103 | renderer.draw(vs, states); 104 | } 105 | }); 106 | } 107 | } 108 | 109 | void Renderer::draw(const sf::Vertex* vertices, std::size_t vertexCount, sf::PrimitiveType type, ZIndex_t zindex, sf::RenderStates const& states) 110 | { 111 | sf::FloatRect rect(0, 0, 0, 0); 112 | for(unsigned int i = 0; i < vertexCount; ++i) 113 | { 114 | auto p = vertices[i].position; 115 | if (p.x < rect.left) rect.left = p.x; 116 | if (p.x > rect.width) rect.width = p.x; 117 | if (p.y < rect.top) rect.top = p.y; 118 | if (p.y > rect.height) rect.height = p.y; 119 | } 120 | rect.width -= rect.left; 121 | rect.height -= rect.top; 122 | 123 | if(isInScreen(rect)) 124 | { 125 | m_drawCallbacks.push_back({ 126 | zindex, 127 | [vertices, vertexCount, type, states] (sf::RenderTarget& renderer) 128 | { 129 | renderer.draw(vertices, vertexCount, type, states); 130 | } 131 | }); 132 | 133 | m_renderer->draw(vertices, vertexCount, type, states); 134 | } 135 | } 136 | 137 | void Renderer::drawHUD(sf::CircleShape const& shape, sf::RenderStates const& states) 138 | { 139 | sf::CircleShape s = shape; 140 | auto px = s.getPosition() / 100.f; 141 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 142 | s.setPosition(pw); 143 | m_drawCallbacks.push_back({ 144 | ZIndex_t(ZIndex::HUD), 145 | [s, states] (sf::RenderTarget& renderer) 146 | { 147 | renderer.draw(s, states); 148 | } 149 | }); 150 | } 151 | 152 | void Renderer::drawHUD(sf::RectangleShape const& shape, sf::RenderStates const& states) 153 | { 154 | sf::RectangleShape s = shape; 155 | auto px = s.getPosition() / 100.f; 156 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 157 | s.setPosition(pw); 158 | m_drawCallbacks.push_back({ 159 | ZIndex_t(ZIndex::HUD), 160 | [s, states] (sf::RenderTarget& renderer) 161 | { 162 | renderer.draw(s, states); 163 | } 164 | }); 165 | } 166 | 167 | void Renderer::drawHUD(sf::ConvexShape const& shape, sf::RenderStates const& states) 168 | { 169 | sf::ConvexShape s = shape; 170 | auto px = s.getPosition() / 100.f; 171 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 172 | s.setPosition(pw); 173 | m_drawCallbacks.push_back({ 174 | ZIndex_t(ZIndex::HUD), 175 | [s, states] (sf::RenderTarget& renderer) 176 | { 177 | renderer.draw(s, states); 178 | } 179 | }); 180 | } 181 | 182 | void Renderer::drawHUD(sf::Sprite const& sprite, sf::RenderStates const& states) 183 | { 184 | sf::Sprite s = sprite; 185 | auto px = s.getPosition() / 100.f; 186 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 187 | s.setPosition(pw); 188 | m_drawCallbacks.push_back({ 189 | ZIndex_t(ZIndex::HUD), 190 | [s, states] (sf::RenderTarget& renderer) 191 | { 192 | renderer.draw(s, states); 193 | } 194 | }); 195 | } 196 | 197 | void Renderer::drawHUD(sf::Text const& text, sf::RenderStates const& states) 198 | { 199 | sf::Text t = text; 200 | auto px = text.getPosition() / 100.f; 201 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 202 | t.setPosition(pw); 203 | m_drawCallbacks.push_back({ 204 | ZIndex_t(ZIndex::HUD), 205 | [t, states] (sf::RenderTarget& renderer) 206 | { 207 | renderer.draw(t, states); 208 | } 209 | }); 210 | } 211 | 212 | void Renderer::drawHUD(sf::VertexArray const& vs, sf::RenderStates const& states) 213 | { 214 | sf::VertexArray v = vs; 215 | for (unsigned int i = 0; i < vs.getVertexCount(); ++i) 216 | { 217 | auto px = vs[i].position / 100.f; 218 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 219 | v[i].position = pw; 220 | } 221 | m_drawCallbacks.push_back({ 222 | ZIndex_t(ZIndex::HUD), 223 | [v, states] (sf::RenderTarget& renderer) 224 | { 225 | renderer.draw(v, states); 226 | } 227 | }); 228 | } 229 | 230 | void Renderer::drawHUD(const sf::Vertex* vertices, std::size_t vertexCount, sf::PrimitiveType type, sf::RenderStates const& states) 231 | { 232 | auto vs = new sf::Vertex[vertexCount]; 233 | for (unsigned int i = 0; i < vertexCount; ++i) 234 | { 235 | auto px = vertices[i].position / 100.f; 236 | auto pw = m_renderer->mapPixelToCoords({static_cast(px.x * m_screenRect.width), static_cast(px.y * m_screenRect.height)}); 237 | vs[i].position = pw; 238 | } 239 | 240 | m_drawCallbacks.push_back({ 241 | ZIndex_t(ZIndex::HUD), 242 | [vs, vertexCount, type, states] (sf::RenderTarget& renderer) 243 | { 244 | renderer.draw(vs, vertexCount, type, states); 245 | } 246 | }); 247 | 248 | delete [] vs; 249 | } 250 | 251 | struct sortDrawables 252 | { 253 | template 254 | bool operator()(T const &a, T const &b) const { return b.first > a.first; } 255 | }; 256 | 257 | void Renderer::render() 258 | { 259 | std::sort(m_drawCallbacks.begin(), m_drawCallbacks.end(), sortDrawables()); 260 | for(auto& drawable : m_drawCallbacks) 261 | { 262 | drawable.second(*m_renderer); 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /src/util/Renderer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | using ZIndex_t = int; 7 | struct ZIndex { 8 | static constexpr ZIndex_t BACKGROUND = 0; 9 | static constexpr ZIndex_t MIDDLEGROUND = 256; 10 | static constexpr ZIndex_t FOREGROUND = 512; 11 | static constexpr ZIndex_t HUD = 1024; 12 | static constexpr ZIndex_t DEBUG = 2048; 13 | }; 14 | 15 | class Renderer 16 | { 17 | public: 18 | 19 | Renderer(sf::RenderTarget& renderer); 20 | Renderer(); 21 | 22 | void render(); 23 | 24 | void setRenderer(sf::RenderTarget& renderer); 25 | 26 | void setView(sf::View const& view); 27 | const sf::View& getView() const; 28 | sf::IntRect getViewport(sf::View const& view) const; 29 | sf::Vector2u getSize() const; 30 | 31 | void draw(sf::Shape const& shape, ZIndex_t zIndex = ZIndex::MIDDLEGROUND, sf::RenderStates const& states = sf::RenderStates::Default); 32 | void draw(sf::Sprite const& shape, ZIndex_t zIndex = ZIndex::MIDDLEGROUND, sf::RenderStates const& states = sf::RenderStates::Default); 33 | void draw(sf::Text const& shape, ZIndex_t zIndex = ZIndex::MIDDLEGROUND, sf::RenderStates const& states = sf::RenderStates::Default); 34 | void draw(sf::VertexArray const& shape, ZIndex_t zIndex = ZIndex::MIDDLEGROUND, sf::RenderStates const& states = sf::RenderStates::Default); 35 | void draw(const sf::Vertex* vertices, std::size_t vertexCount, sf::PrimitiveType type, 36 | ZIndex_t zIndex = ZIndex::MIDDLEGROUND, sf::RenderStates const& states = sf::RenderStates::Default); 37 | 38 | void drawHUD(sf::CircleShape const& shape, sf::RenderStates const& states = sf::RenderStates::Default); 39 | void drawHUD(sf::RectangleShape const& shape, sf::RenderStates const& states = sf::RenderStates::Default); 40 | void drawHUD(sf::ConvexShape const& shape, sf::RenderStates const& states = sf::RenderStates::Default); 41 | void drawHUD(sf::Sprite const& shape, sf::RenderStates const& states = sf::RenderStates::Default); 42 | void drawHUD(sf::Text const& shape, sf::RenderStates const& states = sf::RenderStates::Default); 43 | void drawHUD(sf::VertexArray const& shape, sf::RenderStates const& states = sf::RenderStates::Default); 44 | void drawHUD(const sf::Vertex* vertices, std::size_t vertexCount, sf::PrimitiveType type, 45 | sf::RenderStates const& states = sf::RenderStates::Default); 46 | 47 | private: 48 | using DrawCallback_t = std::function; 49 | std::vector> m_drawCallbacks; 50 | 51 | bool isInScreen(sf::FloatRect const& rect) const; 52 | 53 | sf::RenderTarget* m_renderer; 54 | sf::IntRect m_screenRect; 55 | 56 | }; --------------------------------------------------------------------------------