├── Animation.cpp ├── Animation.h ├── AppState.h ├── Application.cpp ├── Application.h ├── CMakeLists.txt ├── CtrlPanel.cpp ├── CtrlPanel.h ├── Game.cpp ├── Game.h ├── GameOverScreen.cpp ├── GameOverScreen.h ├── GameSetupScreen.cpp ├── GameSetupScreen.h ├── LICENSE ├── Land.cpp ├── Land.h ├── Menu.cpp ├── Menu.h ├── Message.h ├── MessageStream.cpp ├── MessageStream.h ├── Missile.cpp ├── Missile.h ├── MsgComponents.cpp ├── MsgComponents.h ├── Player.cpp ├── Player.h ├── README.md ├── ResourceIdentifiers.h ├── ResourceManager.h ├── Tank.cpp ├── Tank.h ├── TitleScreen.cpp ├── TitleScreen.h ├── WeaponPostEffects.cpp ├── WeaponPostEffects.h ├── World.cpp ├── World.h ├── WorldObject.h ├── cmake └── Modules │ └── FindSFML.cmake ├── constants.h ├── data ├── ExplosionAsmall.png ├── FreeSans.ttf ├── Ubuntu-C.ttf ├── arrowdown.png ├── tank.png ├── target.png ├── title.png └── turret.png ├── simplexnoise.cpp ├── simplexnoise.h ├── utilities.cpp └── utilities.h /Animation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | No rights Reserved. 3 | Amish Kumar Naidu 4 | amhndu at gmail.com 5 | */ 6 | #include "Animation.h" 7 | #include "Application.h" 8 | 9 | Animation::Animation(TextureIdentifier tid) : 10 | WorldObject(PassiveType), 11 | timer(), 12 | baseImage(Application::getTexture(tid)), 13 | frameSpr(baseImage), 14 | frameSize(), 15 | repeat(false), 16 | frameposition(), 17 | frame(), 18 | endFrame(), 19 | totalFrames(), 20 | secondsPerFrame(1/15.0) 21 | { 22 | selfDestruct = false; 23 | } 24 | Animation::Animation(TextureIdentifier tid,const sf::Vector2i& fsize,const sf::Vector2f& pos, 25 | double spf,bool loop,int startFrame,int endframe ) : 26 | WorldObject(PassiveType), 27 | timer(), 28 | baseImage(Application::getTexture(tid)), 29 | frameSpr(baseImage), 30 | frameSize(fsize), 31 | repeat(loop), 32 | frameposition(), 33 | frame(startFrame), 34 | endFrame(endframe), 35 | totalFrames(), 36 | secondsPerFrame(spf) 37 | { 38 | selfDestruct = false; 39 | frameSpr.setOrigin(frameSize.x/2,frameSize.y/2); 40 | frameSpr.setPosition(pos); 41 | updateFrameDimensions(); 42 | } 43 | void Animation::updateFrameDimensions() 44 | { 45 | //vector of total frames per dimensions 46 | sf::Vector2i framesPerDim( (baseImage.getSize().x/frameSize.x),(baseImage.getSize().y/frameSize.y) ); 47 | //If we have a grid of x*y frames, then e.g. say 4*4 48 | //frame.x = currentFrame mod x; e.g 0%4 = 5%4 ... 49 | //frame.y = (currentFrame - frame.x)/y e.g (2-2)/4 = 0, (6-2)/4 = 1 ... 50 | //or frame.y = currentFrame/y,since they are integers it does not make a difference 51 | frameposition.x = frame % framesPerDim.x; 52 | frameposition.y = frame / framesPerDim.x; 53 | //Multiply frameSize , to create co-ordinates for sprite 54 | frameposition.x = frameposition.x * frameSize.x; 55 | frameposition.y = frameposition.y * frameSize.y; 56 | totalFrames = framesPerDim.x * framesPerDim.y; 57 | if(!endFrame) //if not explicitly provided i.e not initialized to zero 58 | endFrame = totalFrames - 1; 59 | else 60 | endFrame %= totalFrames; 61 | frameSpr.setTextureRect(sf::IntRect(frameposition,frameSize)); 62 | } 63 | void Animation::setFrameSize(const sf::Vector2i& size) 64 | { 65 | frameSize = size; 66 | frameSpr.setOrigin(frameSize.x/2,frameSize.y/2); 67 | updateFrameDimensions(); 68 | } 69 | void Animation::setFrameSize(int x,int y) 70 | { 71 | frameSize.x = x; 72 | frameSize.y = y; 73 | frameSpr.setOrigin(frameSize.x/2,frameSize.y/2); 74 | updateFrameDimensions(); 75 | } 76 | void Animation::reset() 77 | { 78 | frame = 0; 79 | timer = 0; 80 | updateFrameDimensions(); 81 | } 82 | void Animation::draw(sf::RenderTarget& target) 83 | { 84 | target.draw(frameSpr); 85 | } 86 | void Animation::step(float dt) 87 | { 88 | timer += dt; 89 | int c = frame; 90 | while(timer > secondsPerFrame) 91 | { 92 | timer -= secondsPerFrame; 93 | if(++frame >= endFrame) 94 | { 95 | if(!repeat) 96 | selfDestruct = true; 97 | else 98 | frame = 0; 99 | } 100 | updateFrameDimensions(); 101 | } 102 | c = frame - c; 103 | c = 0; 104 | } 105 | void Animation::handleCollision(WorldObject &b){} 106 | 107 | //Animation Creator 108 | std::unique_ptr AnimationCreator::create(AnimationType t,const sf::Vector2f& position) 109 | { 110 | std::unique_ptr anim(nullptr); 111 | switch(t) 112 | { 113 | case MissileExplosionA: 114 | { 115 | anim.reset(new Animation(ExplosionA,sf::Vector2i(128,128),position,1/25.0)); 116 | anim->setRotation(rand()%360); 117 | anim->setScale(94.0/128.0,94.0/128.0);// scale = new_size / initial_size 118 | } 119 | break; 120 | case ArrowDown: 121 | { 122 | anim.reset(new Animation(ArrowDownSpriteSheet,sf::Vector2i(52,58),position,1/35.0,true)); 123 | anim->setScale(30/52.0,30/52.0); 124 | } 125 | break; 126 | } 127 | return anim; 128 | } 129 | -------------------------------------------------------------------------------- /Animation.h: -------------------------------------------------------------------------------- 1 | #ifndef ANIMATION_H 2 | #define ANIMATION_H 3 | 4 | #include "WorldObject.h" 5 | #include "ResourceIdentifiers.h" 6 | 7 | class Animation : public WorldObject 8 | { 9 | public: 10 | Animation(TextureIdentifier tid); 11 | Animation(TextureIdentifier tid,const sf::Vector2i& fsize,const sf::Vector2f& pos = sf::Vector2f(), 12 | double spf = 1/15.0,bool loop = false,int startFrame = 0,int endframe = 0); 13 | inline int getFrame() { return frame; } 14 | inline bool getRepeat() { return repeat; } 15 | inline void setRepeat(bool flag) { repeat = flag; } 16 | inline void setScale(double x,double y) { frameSpr.setScale(x,y); } 17 | inline sf::Vector2f getPosition() { return frameSpr.getPosition(); } 18 | inline void setPosition(const sf::Vector2f& pos) { frameSpr.setPosition(pos); } 19 | inline void setRotation(float angle){ frameSpr.setRotation(angle); } 20 | inline float getRotation(){ return frameSpr.getRotation(); } 21 | void setFrameSize(const sf::Vector2i& size); 22 | void setFrameSize(int x,int y); 23 | inline const sf::Vector2i& getFrameSize() { return frameSize;} 24 | void draw(sf::RenderTarget&); 25 | void step(float dt); 26 | void handleCollision(WorldObject &b); 27 | void reset(); 28 | void setSPF(double spf) { secondsPerFrame = spf;} 29 | private: 30 | double timer; 31 | sf::Texture& baseImage; 32 | sf::Sprite frameSpr; 33 | sf::Vector2i frameSize; 34 | bool repeat; 35 | sf::Vector2i frameposition; 36 | int frame; 37 | int endFrame; 38 | int totalFrames; 39 | double secondsPerFrame; // spf = 1/fps 40 | private: 41 | void updateFrameDimensions(); 42 | }; 43 | 44 | enum AnimationType 45 | { 46 | MissileExplosionA, 47 | ArrowDown 48 | }; 49 | 50 | namespace AnimationCreator 51 | { 52 | std::unique_ptr create(AnimationType t,const sf::Vector2f& position = sf::Vector2f()); 53 | } 54 | #endif // ANIMATION_H 55 | -------------------------------------------------------------------------------- /AppState.h: -------------------------------------------------------------------------------- 1 | #ifndef APPSTATE_H 2 | #define APPSTATE_H 3 | #include 4 | #include 5 | #include "MsgComponents.h" 6 | #include 7 | 8 | enum AppStateType 9 | { 10 | TitleScreenState, 11 | GameSetupState, 12 | GameState, 13 | GameOverState 14 | }; 15 | 16 | class AppState : public Receiver 17 | { 18 | public: 19 | AppState(); 20 | AppState(AppStateType t) : type(t) {}; 21 | virtual ~AppState(){}; 22 | virtual void reset() = 0; 23 | virtual void draw(sf::RenderWindow &window) = 0; 24 | virtual void update(float dt) = 0; 25 | virtual void passEvent(sf::Event event) = 0; 26 | AppStateType type; 27 | }; 28 | 29 | #endif // APPSTATE_H 30 | -------------------------------------------------------------------------------- /Application.cpp: -------------------------------------------------------------------------------- 1 | #include "Application.h" 2 | #include "ResourceIdentifiers.h" 3 | void Application::run() 4 | { 5 | mainWindow.create(sf::VideoMode(constants::windowWidth,constants::windowHeight),"A Game feat. Tanks"); 6 | mainWindow.setFramerateLimit(120); 7 | mainWindow.setVerticalSyncEnabled(false); 8 | sf::Clock frameTimer; 9 | changeState(TitleScreenState); 10 | msgStream.getGroup("AllAppStates").subscribe(&mGame); 11 | msgStream.getGroup("AllAppStates").subscribe(&mGameOver); 12 | msgStream.getGroup("GameState").subscribe(&mGame); 13 | currentState->reset(); 14 | while(mainWindow.isOpen()) 15 | { 16 | sf::Event event; 17 | while(mainWindow.pollEvent(event)) 18 | { 19 | if(event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)) 20 | { 21 | //msgStream.sendMessage(Message("WindowClosed"),"EventListeners"); 22 | mainWindow.close(); 23 | return; 24 | } 25 | else 26 | currentState->passEvent(event); 27 | } 28 | mainWindow.clear(sf::Color::White); 29 | currentState->draw(mainWindow); 30 | mainWindow.display(); 31 | sf::Time dt = frameTimer.getElapsedTime(); 32 | frameTimer.restart(); 33 | currentState->update(dt.asSeconds()); 34 | } 35 | } 36 | void Application::quit(const std::string& error) 37 | { 38 | if(error != "none") 39 | std::cerr << error << std::endl; 40 | mainWindow.close(); 41 | } 42 | sf::Texture& Application::getTexture(TextureIdentifier id) 43 | { 44 | if(!ResourcesLoaded) 45 | loadResources(); 46 | return textureMgr.get(id); 47 | } 48 | sf::Font& Application::getFont(FontIdentifier id) 49 | { 50 | if(!ResourcesLoaded) 51 | loadResources(); 52 | return fontMgr.get(id); 53 | } 54 | void Application::loadResources() 55 | { 56 | if(ResourcesLoaded) 57 | return; 58 | if( !(textureMgr.load(TankTexture,"data/tank.png") && 59 | textureMgr.load(TurretTexture,"data/turret.png") && 60 | textureMgr.load(ExplosionA,"data/ExplosionAsmall.png") && 61 | textureMgr.load(TurretTarget,"data/target.png") && 62 | textureMgr.load(ArrowDownSpriteSheet,"data/arrowdown.png") && 63 | textureMgr.load(TitleBg,"data/title.png") && 64 | fontMgr.load(FreeSans,"data/FreeSans.ttf") && 65 | fontMgr.load(UbuntuCondensed,"data/Ubuntu-C.ttf")) ) 66 | throw std::runtime_error("failed to load resources"); 67 | else 68 | ResourcesLoaded = true; 69 | } 70 | void Application::changeState(AppStateType as) 71 | { 72 | statesStack.push_back(as); 73 | // msgStream.getGroup("EventListeners").unsubscribe(currentState); 74 | currentState = getState(as); 75 | // msgStream.getGroup("EventListeners").subscribe(currentState); 76 | } 77 | AppState* Application::getState(AppStateType as) 78 | { 79 | switch(as) 80 | { 81 | case TitleScreenState: 82 | return &titleState; 83 | case GameState: 84 | return &mGame; 85 | case GameOverState: 86 | return &mGameOver; 87 | case GameSetupState: 88 | return &mSetupScreen; 89 | } 90 | return nullptr; 91 | } 92 | 93 | TextureManager Application::textureMgr; 94 | FontManager Application::fontMgr; 95 | bool Application::ResourcesLoaded{false}; 96 | MessageStream Application::msgStream; 97 | std::deque Application::statesStack; 98 | sf::RenderWindow Application::mainWindow; 99 | Game Application::mGame; 100 | GameOverScreen Application::mGameOver; 101 | TitleScreen Application::titleState; 102 | GameSetupScreen Application::mSetupScreen; 103 | AppState* Application::currentState; 104 | int main() 105 | { 106 | srand(time(NULL)); 107 | Application::loadResources(); 108 | Application::run(); 109 | return EXIT_SUCCESS; 110 | } 111 | -------------------------------------------------------------------------------- /Application.h: -------------------------------------------------------------------------------- 1 | #ifndef APPLICATION_H 2 | #define APPLICATION_H 3 | #include 4 | #include 5 | #include 6 | #include "ResourceManager.h" 7 | #include "MessageStream.h" 8 | #include "Game.h" 9 | #include "GameOverScreen.h" 10 | #include "TitleScreen.h" 11 | #include "GameSetupScreen.h" 12 | 13 | class Application 14 | { 15 | public: 16 | Application() = delete; 17 | static sf::RenderWindow& getWindow(){ return mainWindow; } 18 | static sf::Texture& getTexture(TextureIdentifier id); 19 | static sf::Font& getFont(FontIdentifier id); 20 | static AppStateType getCurrentStateType() { return statesStack.back(); } 21 | static void changeState(AppStateType as); 22 | static MessageStream& getMsgStream() { return msgStream; } 23 | static void loadResources(); 24 | static void run(); 25 | static void quit(const std::string& error = "none"); 26 | static Game& getGame(){ return mGame; } 27 | private: 28 | static AppState* getState(AppStateType as); 29 | static TextureManager textureMgr; 30 | static FontManager fontMgr; 31 | static bool ResourcesLoaded; 32 | static MessageStream msgStream; 33 | static std::deque statesStack; 34 | static sf::RenderWindow mainWindow; 35 | static Game mGame; 36 | static GameOverScreen mGameOver; 37 | static TitleScreen titleState; 38 | static GameSetupScreen mSetupScreen; 39 | static AppState* currentState; 40 | }; 41 | 42 | #endif // APPLICATION_H 43 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.6) 2 | project(miniTanks) 3 | 4 | # Specify C++11 flag for g++ 5 | if(CMAKE_COMPILER_IS_GNUCXX OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") 6 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O2") 7 | endif() 8 | 9 | # Add directory containing FindSFML.cmake to module path 10 | set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/Modules/;${CMAKE_MODULE_PATH};${CMAKE_SOURCE_DIR}") 11 | 12 | # Add sources 13 | set(SOURCES 14 | "${PROJECT_SOURCE_DIR}/Animation.cpp" 15 | "${PROJECT_SOURCE_DIR}/Application.cpp" 16 | "${PROJECT_SOURCE_DIR}/CtrlPanel.cpp" 17 | "${PROJECT_SOURCE_DIR}/Game.cpp" 18 | "${PROJECT_SOURCE_DIR}/GameOverScreen.cpp" 19 | "${PROJECT_SOURCE_DIR}/GameSetupScreen.cpp" 20 | "${PROJECT_SOURCE_DIR}/Land.cpp" 21 | "${PROJECT_SOURCE_DIR}/Menu.cpp" 22 | "${PROJECT_SOURCE_DIR}/MessageStream.cpp" 23 | "${PROJECT_SOURCE_DIR}/Missile.cpp" 24 | "${PROJECT_SOURCE_DIR}/MsgComponents.cpp" 25 | "${PROJECT_SOURCE_DIR}/Player.cpp" 26 | "${PROJECT_SOURCE_DIR}/simplexnoise.cpp" 27 | "${PROJECT_SOURCE_DIR}/Tank.cpp" 28 | "${PROJECT_SOURCE_DIR}/TitleScreen.cpp" 29 | "${PROJECT_SOURCE_DIR}/utilities.cpp" 30 | "${PROJECT_SOURCE_DIR}/WeaponPostEffects.cpp" 31 | "${PROJECT_SOURCE_DIR}/World.cpp" ) 32 | # Find SFML 33 | find_package(SFML 2 COMPONENTS graphics window system) 34 | 35 | if(SFML_FOUND) 36 | include_directories(${SFML_INCLUDE_DIR}) 37 | else() 38 | set(SFML_ROOT "" CACHE PATH "SFML top-level directory") 39 | message("\n-> SFML directory not found. Set SFML_ROOT to SFML's top-level path (containing \"include\" and \"lib\" directories).") 40 | message("-> Make sure the SFML libraries with the same configuration (Release/Debug, Static/Dynamic) exist.\n") 41 | endif() 42 | 43 | file(COPY data DESTINATION .) 44 | 45 | add_executable(miniTanks ${SOURCES}) 46 | 47 | target_link_libraries(miniTanks ${SFML_LIBRARIES}) 48 | -------------------------------------------------------------------------------- /CtrlPanel.cpp: -------------------------------------------------------------------------------- 1 | #include "CtrlPanel.h" 2 | #include "Application.h" 3 | #include 4 | 5 | const int fontSize = 15; 6 | 7 | CtrlPanel::CtrlPanel(Game& g) : 8 | WorldObject(PassiveType), 9 | _game(g), 10 | fpsi(), 11 | p(), 12 | settingPower(false), 13 | settingAngle(false), 14 | prevMouseX(), 15 | mouseOldCoord(), 16 | fps("",Application::getFont(FreeSans),fontSize), 17 | player("Player : 1",Application::getFont(FreeSans),fontSize), 18 | rotation("",Application::getFont(FreeSans),fontSize), 19 | power("Power : ",Application::getFont(FreeSans),fontSize), 20 | fire("FIRE",Application::getFont(FreeSans),fontSize), 21 | gaugeBg(sf::Vector2f(100,10)), 22 | gaugeFill(sf::Vector2f(0,10)), 23 | crosshair(Application::getTexture(TurretTarget)), 24 | currPlayerMarker(AnimationCreator::create(ArrowDown)) 25 | { 26 | int xpadding = 30,ypadding = 30,lpadding = 5; 27 | int width = constants::windowWidth/3; 28 | int height = fontSize; 29 | //line 1 30 | player.setPosition (xpadding + width*0,ypadding); 31 | player.setColor (sf::Color::Black); 32 | fps.setPosition (xpadding + width*1,ypadding); 33 | fps.setColor (sf::Color::Black); 34 | fire.setPosition (xpadding + width*2,ypadding); 35 | fire.setColor (sf::Color::Black); 36 | //line 2 37 | rotation.setPosition (xpadding + width*0,ypadding + height + lpadding*1); 38 | rotation.setColor (sf::Color::Black); 39 | power.setPosition (xpadding + width*1,ypadding + height + lpadding*1); 40 | power.setColor (sf::Color::Black); 41 | gaugeBg.setPosition (power.getGlobalBounds().left+power.getGlobalBounds().width,power.getGlobalBounds().top); 42 | gaugeBg.setFillColor (sf::Color(240,240,240)); 43 | gaugeBg.setOutlineThickness(1); 44 | gaugeBg.setOutlineColor (sf::Color::Black); 45 | gaugeFill.setPosition (gaugeBg.getPosition()); 46 | gaugeFill.setFillColor (sf::Color::Blue); 47 | crosshair.setOrigin(-60, crosshair.getLocalBounds().height / 2); 48 | } 49 | void CtrlPanel::draw(sf::RenderTarget &target) 50 | { 51 | fpsi = 1/float(fpsTimer.getElapsedTime().asSeconds()); 52 | fpsTimer.restart(); 53 | target.draw(rotation); 54 | target.draw(fps); 55 | target.draw(player); 56 | target.draw(power); 57 | target.draw(gaugeBg); 58 | target.draw(gaugeFill); 59 | target.draw(fire); 60 | auto pl = _game.getCurrPlayer(); 61 | if(settingAngle) 62 | { 63 | if(pl) 64 | { 65 | crosshair.setPosition(pl->getTankPos()); 66 | crosshair.setRotation(pl->getTurretAngle()); 67 | } 68 | target.draw(crosshair); 69 | } 70 | if(_game.isPlayerTurn()) 71 | { 72 | if(pl) 73 | currPlayerMarker->setPosition(pl->getTankPos()-sf::Vector2f(0,100)); 74 | currPlayerMarker->draw(target); 75 | } 76 | } 77 | void CtrlPanel::step(float dt) 78 | { 79 | fps.setString("FPS : " + std::to_string(fpsi)); 80 | auto pl = _game.getCurrPlayer(); 81 | if(pl == nullptr) 82 | return; 83 | 84 | if(_game.isPlayerTurn()) 85 | currPlayerMarker->step(dt); 86 | 87 | if(p != _game.getPlayerIndex()+1) 88 | { 89 | p = _game.getPlayerIndex()+1; 90 | gaugeFill.setSize(sf::Vector2f(pl->getPower()*gaugeBg.getSize().x,gaugeBg.getSize().y)); 91 | player.setString("Player : " + std::to_string(p)); 92 | } 93 | if(settingAngle || settingPower) 94 | { 95 | sf::Vector2i mouse = sf::Mouse::getPosition(Application::getWindow()); 96 | int delta = mouse.x-prevMouseX; 97 | if(settingAngle) 98 | pl->rotateTurret( delta/2 ); 99 | else 100 | changePower( delta/2,pl ); 101 | prevMouseX = mouse.x; 102 | int mouse_margin = 20; 103 | if(mouse.x < mouse_margin) //workaround for mouse lock 104 | { 105 | sf::Mouse::setPosition(sf::Vector2i(constants::windowWidth-mouse_margin-1,mouse.y),Application::getWindow()); 106 | prevMouseX = constants::windowWidth-mouse_margin-1; 107 | } 108 | else if(mouse.x > constants::windowWidth-mouse_margin-1) 109 | { 110 | sf::Mouse::setPosition(sf::Vector2i(mouse_margin,mouse.y),Application::getWindow()); 111 | prevMouseX = mouse_margin; 112 | } 113 | if(mouse.y < mouse_margin) 114 | { 115 | sf::Mouse::setPosition(sf::Vector2i(mouse.x,constants::windowHeight-mouse_margin-1),Application::getWindow()); 116 | } 117 | else if(mouse.y > constants::windowHeight-mouse_margin) 118 | { 119 | sf::Mouse::setPosition(sf::Vector2i(mouse.x,mouse_margin),Application::getWindow()); 120 | } 121 | } 122 | rotation.setString("Rotation : " + std::to_string(360-int(pl->getTurretAngle()))); 123 | } 124 | void CtrlPanel::postSettingAngle() 125 | { 126 | _game.decCounter(); 127 | settingAngle = false; 128 | sf::Mouse::setPosition(mouseOldCoord,Application::getWindow());//set mouse back to position it was before setting angle 129 | Application::getWindow().setMouseCursorVisible(true); 130 | rotation.setStyle(sf::Text::Regular); 131 | } 132 | void CtrlPanel::initSettingAngle(Player *pl) 133 | { 134 | _game.incCounter(); 135 | settingAngle = true; 136 | mouseOldCoord = sf::Mouse::getPosition(Application::getWindow());//save current coords to set it back when setting angle is over 137 | prevMouseX = mouseOldCoord.x; 138 | Application::getWindow().setMouseCursorVisible(false); 139 | rotation.setStyle(sf::Text::Bold); 140 | } 141 | void CtrlPanel::changePower(int delta,Player *pl) 142 | { 143 | float powerf = pl->getPower() + 0.01*delta; 144 | powerf = std::max(std::min(powerf,1.0f),0.0f); 145 | pl->setPower(powerf); 146 | gaugeFill.setSize(sf::Vector2f(powerf*gaugeBg.getSize().x,gaugeBg.getSize().y)); 147 | } 148 | void CtrlPanel::receiveMessage(const Message& msg) 149 | { 150 | if(msg.ID == "WindowEvent") 151 | { 152 | const sf::Event& event = msg.getItem(0); 153 | auto pl = _game.getCurrPlayer(); 154 | if(pl == nullptr) 155 | return; 156 | if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) 157 | { 158 | sf::Vector2f mcoord(event.mouseWheel.x,event.mouseButton.y); 159 | 160 | if(settingAngle) postSettingAngle(); 161 | else if(settingPower) 162 | { 163 | _game.decCounter(); 164 | settingPower = false; 165 | Application::getWindow().setMouseCursorVisible(true); 166 | gaugeBg.setOutlineThickness(1); 167 | gaugeBg.setOutlineColor(sf::Color::Black); 168 | } 169 | else if(_game.isPlayerTurn() && rotation.getGlobalBounds().contains(mcoord)) initSettingAngle(pl); 170 | else if(_game.isPlayerTurn() && gaugeBg.getGlobalBounds().contains(mcoord)) 171 | { 172 | _game.incCounter(); 173 | settingPower = true; 174 | Application::getWindow().setMouseCursorVisible(false); 175 | prevMouseX = mcoord.x; 176 | gaugeBg.setOutlineThickness(2); 177 | gaugeBg.setOutlineColor(sf::Color::Red); 178 | } 179 | else if(_game.isPlayerTurn() && fire.getGlobalBounds().contains(sf::Vector2f(event.mouseButton.x,event.mouseButton.y)) ) 180 | pl->fire(); 181 | } 182 | else if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R) 183 | { 184 | if(settingAngle) postSettingAngle(); 185 | else if(_game.isPlayerTurn()) initSettingAngle(pl); 186 | } 187 | else if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space && _game.isPlayerTurn()) 188 | pl->fire(); 189 | else if(_game.isPlayerTurn() && event.type == sf::Event::MouseWheelMoved) 190 | { 191 | sf::Vector2f mcoord(event.mouseWheel.x,event.mouseButton.y); 192 | if(gaugeBg.getGlobalBounds().contains(mcoord)) 193 | changePower(event.mouseWheel.delta,pl); 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /CtrlPanel.h: -------------------------------------------------------------------------------- 1 | #ifndef CtrlPanel_H 2 | #define CtrlPanel_H 3 | #include "WorldObject.h" 4 | #include "Game.h" 5 | #include "Animation.h" 6 | 7 | class CtrlPanel : public WorldObject 8 | { 9 | public: 10 | CtrlPanel(Game& g); 11 | void handleCollision(WorldObject &b){}; 12 | void draw(sf::RenderTarget &target); 13 | void step(float dt); 14 | void reset(){}; 15 | void receiveMessage(const Message& msg); 16 | private: 17 | void initSettingAngle(Player *pl); 18 | void postSettingAngle(); 19 | void changePower(int delta,Player *pl); 20 | Game& _game; 21 | int fpsi; 22 | size_t p; 23 | bool settingPower; 24 | bool settingAngle; //if setting angle change angle of the turret by deltaX 25 | int prevMouseX; //deltaX = mouse.x - prevMouseX , change angle in degrees 26 | sf::Vector2i mouseOldCoord;// used to reset mouse to old position after setting angle 27 | sf::Clock fpsTimer; 28 | sf::Text fps; 29 | sf::Text player; 30 | sf::Text rotation; 31 | sf::Text power; 32 | sf::Text fire; 33 | sf::RectangleShape gaugeBg; 34 | sf::RectangleShape gaugeFill; 35 | sf::Sprite crosshair; 36 | std::unique_ptr currPlayerMarker; 37 | }; 38 | 39 | #endif // CtrlPanel_H 40 | -------------------------------------------------------------------------------- /Game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | No rights Reserved. 3 | Amish Kumar Naidu 4 | amhndu at gmail.com 5 | */ 6 | #include "Application.h" 7 | #include "constants.h" 8 | #include "CtrlPanel.h" 9 | #include 10 | 11 | //#define STEPPED 12 | Game::Game() : 13 | AppState(GameState), 14 | playerActive(0), 15 | counter(0), 16 | landSliding(false), 17 | land(nullptr) 18 | {} 19 | void Game::reset() 20 | { 21 | newGame(); 22 | } 23 | void Game::newGame(int n_players,Land::Landtype land_t) 24 | { 25 | world.clear(); 26 | players.clear(); 27 | playerActive = 0; 28 | counter = 0; 29 | 30 | land = static_cast(world.addObj(WorldObject::LandType)); 31 | auto &gland = Application::getMsgStream().getGroup("Land"); 32 | gland.clear(); 33 | gland.subscribe(land); 34 | land->genHeightMap(land_t); 35 | 36 | auto &gCtrlPanel = Application::getMsgStream().getGroup("CtrlPanel"); 37 | gCtrlPanel.clear(); 38 | gCtrlPanel.subscribe(world.addObj(new CtrlPanel(*this))); 39 | 40 | auto >anks = Application::getMsgStream().getGroup("Tanks"); 41 | gtanks.clear(); 42 | //initialize players 43 | int pw = constants::windowWidth/n_players; //divide width into p parts 44 | for(int i = 0;i < n_players; ++i) 45 | { 46 | Tank* pTank = static_cast(world.addObj(WorldObject::TankType)); 47 | gtanks.subscribe(pTank); 48 | Playerptr pl(new Player(pTank,"Player "+ std::to_string(i+1) )); 49 | int x = rand()%(pw-50) + pw*i + 25; //place tank within the ith part within a padding of 25pixels on both sides 50 | pTank->setPosition(sf::Vector2f(x,constants::windowHeight-getLandHeight(x)-10)); 51 | pTank->setPlayer(pl.get()); 52 | players.push_back(std::move(pl)); 53 | } 54 | world.play(); 55 | } 56 | 57 | void Game::draw(sf::RenderWindow &window) 58 | { 59 | world.drawAll(window); 60 | } 61 | void Game::update(float dt) 62 | { 63 | if(isPlayerTurn()) //i.e weapObjs == 0 && landSliding == false 64 | { //check if game is over 65 | if(players.size() == 1) 66 | { 67 | Application::getMsgStream().sendMessage(Message("GameOver", 68 | std::string("Last Tank Alive Won")),"AllAppStates"); 69 | Application::changeState(GameOverState); 70 | reset(); 71 | } 72 | else if(players.empty()) 73 | { 74 | Application::getMsgStream().sendMessage(Message("GameOver", 75 | std::string("Game Drawn")),"AllAppStates"); 76 | Application::changeState(GameOverState); 77 | reset(); 78 | } 79 | } 80 | #ifndef STEPPED 81 | world.stepAll(dt); 82 | #endif // STEPPED 83 | } 84 | void Game::passEvent(sf::Event Event) 85 | { 86 | if(Event.type == sf::Event::KeyPressed) 87 | { 88 | switch(Event.key.code) 89 | { 90 | case sf::Keyboard::Left: 91 | if( isPlayerTurn() && players[playerActive] != nullptr) 92 | players[playerActive]->moveTank(-1); 93 | break; 94 | case sf::Keyboard::Right: 95 | if( isPlayerTurn() && players[playerActive] != nullptr) 96 | players[playerActive]->moveTank(1); 97 | break; 98 | #ifdef STEPPED 99 | case sf::Keyboard::S: 100 | world.crudeStepAll(); 101 | break; 102 | #endif // STEPPED 103 | default: 104 | break; 105 | } 106 | } 107 | Application::getMsgStream().sendMessage(Message("WindowEvent",Event),"CtrlPanel"); 108 | } 109 | void Game::receiveMessage(const Message& msg) 110 | { 111 | if(msg.ID == "SetLandSlide") 112 | { 113 | landSliding = true; 114 | } 115 | else if(msg.ID == "UnsetLandSlide") 116 | { 117 | landSliding = false; 118 | } 119 | else if(msg.ID == "PlayerTurnOver") 120 | { 121 | if(++playerActive >= players.size()) 122 | playerActive = 0; 123 | } 124 | else if(msg.ID == "TankDestroyed") 125 | { 126 | size_t pi = 0; 127 | for(auto p_it = players.begin();p_it != players.end();) 128 | { 129 | if((*p_it)->isDead()) 130 | { 131 | Application::getMsgStream().getGroup("Tanks").unsubscribe(&(*p_it)->getTank()); 132 | p_it = players.erase(p_it); 133 | if(pi < playerActive) --playerActive; 134 | } 135 | else (++p_it,++pi); 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /Game.h: -------------------------------------------------------------------------------- 1 | #ifndef GAME_H 2 | #define GAME_H 3 | #include "World.h" 4 | #include "Land.h" 5 | #include "Player.h" 6 | #include "AppState.h" 7 | #include 8 | 9 | class Game : public AppState 10 | { 11 | public: 12 | Game(); 13 | void draw(sf::RenderWindow &window); 14 | void update(float dt); 15 | void receiveMessage(const Message &msg); 16 | void passEvent(sf::Event Event); 17 | void reset(); 18 | 19 | void newGame(int n_players = 2,Land::Landtype land_t = Land::Random); 20 | 21 | inline sf::Vector2f getLandNormal(int x,int y){ return land->getNormal(x,y); } 22 | inline float getLandNormAng(int x,int y){ return land->getNormAngle(x,y); } 23 | inline int getLandHeight(int x){ return land->getHeight(x); } 24 | 25 | inline void incCounter() { ++counter; } 26 | inline void decCounter() { --counter;assert(counter>=0); } 27 | 28 | WorldObject* addWorldObj(WorldObject* wo){ return world.addObj(wo); } 29 | 30 | size_t getPlayerIndex(){ return playerActive; } 31 | Player* getCurrPlayer(){ return players[playerActive].get(); } 32 | bool isPlayerTurn(){ return counter==0 && landSliding==false; } 33 | private: 34 | std::deque players; 35 | size_t playerActive; 36 | 37 | //flags and counters 38 | int counter; //weapons,effects,tanks on free fall etc. counter 39 | bool landSliding; 40 | 41 | Land *land; 42 | World world; 43 | private: 44 | void handleInput(); 45 | 46 | }; 47 | 48 | #endif // GAME_H 49 | -------------------------------------------------------------------------------- /GameOverScreen.cpp: -------------------------------------------------------------------------------- 1 | #include "GameOverScreen.h" 2 | #include "Application.h" 3 | 4 | GameOverScreen::GameOverScreen() : 5 | AppState(GameOverState), 6 | bgImg(), 7 | bgSpr(), 8 | message("",Application::getFont(FreeSans)), 9 | gameOverText("Game Over !",Application::getFont(FreeSans)) 10 | { 11 | message.setColor(sf::Color::Black); 12 | gameOverText.setColor(sf::Color::Black); 13 | gameOverText.setCharacterSize(40); 14 | message.setCharacterSize(20); 15 | gameOverText.setOrigin(gameOverText.getLocalBounds().width/2,gameOverText.getLocalBounds().height/2); 16 | } 17 | void GameOverScreen::reset() 18 | { 19 | sf::RenderWindow &win = Application::getWindow(); 20 | bgImg.create(win.getSize().x,win.getSize().y); 21 | bgImg.update(win); 22 | bgSpr.setTexture(bgImg); 23 | gameOverText.setPosition(win.getSize().x/2,2*gameOverText.getCharacterSize()); 24 | message.setOrigin(message.getLocalBounds().width/2,message.getLocalBounds().height/2); 25 | message.setPosition(gameOverText.getPosition().x,gameOverText.getPosition().y 26 | + gameOverText.getLocalBounds().height + message.getCharacterSize()); 27 | } 28 | void GameOverScreen::draw(sf::RenderWindow &window) 29 | { 30 | window.draw(bgSpr); 31 | window.draw(gameOverText); 32 | window.draw(message); 33 | } 34 | void GameOverScreen::update(float dt){} 35 | void GameOverScreen::passEvent(sf::Event Event) 36 | { 37 | if(Event.type == sf::Event::KeyPressed || Event.type == sf::Event::MouseButtonReleased) 38 | Application::changeState(GameSetupState); 39 | } 40 | void GameOverScreen::receiveMessage(const Message& msg) 41 | { 42 | if(msg.ID == "GameOver") 43 | { 44 | const std::string &gcase = msg.getItem(0); 45 | message.setString(gcase); 46 | reset(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /GameOverScreen.h: -------------------------------------------------------------------------------- 1 | #ifndef GAMEOVERSCREEN_H 2 | #define GAMEOVERSCREEN_H 3 | #include "AppState.h" 4 | 5 | class GameOverScreen : public AppState 6 | { 7 | public: 8 | GameOverScreen(); 9 | void reset(); 10 | void draw(sf::RenderWindow &window); 11 | void update(float dt); 12 | void receiveMessage(const Message& msg); 13 | void passEvent(sf::Event Event); 14 | private: 15 | sf::Texture bgImg; 16 | sf::Sprite bgSpr; 17 | sf::Text message; 18 | sf::Text gameOverText; 19 | }; 20 | 21 | #endif // GAMEOVERSCREEN_H 22 | -------------------------------------------------------------------------------- /GameSetupScreen.cpp: -------------------------------------------------------------------------------- 1 | #include "GameSetupScreen.h" 2 | #include "Application.h" 3 | #include "Land.h" 4 | GameSetupScreen::GameSetupScreen() : 5 | AppState(GameSetupState), 6 | setupMenu(Application::getFont(FreeSans),40), 7 | numPlayersSubMenu(Application::getFont(FreeSans),40), 8 | landTypeSubMenu(Application::getFont(FreeSans),40), 9 | numOfPlyrs(2), 10 | l_type(Land::Flats), 11 | bg(Application::getTexture(TitleBg)) 12 | { 13 | setupMenu.setSelectionBgColor(sf::Color(0,0,0,100)); 14 | setupMenu.setBackgroundColor(sf::Color::Transparent); 15 | setupMenu.setPosition(0,300); 16 | numPlayersSubMenu.setActive(false); 17 | numPlayersSubMenu.add(sf::Color::White," 2"," 3"," 4"," 5"," 6"," 7"," 8"); 18 | numPlayersSubMenu.setBackgroundColor(sf::Color(100,100,100,150)); 19 | numPlayersSubMenu.setSelectionBgColor(sf::Color(0,0,0,100)); 20 | numPlayersSubMenu.create(200,4*numPlayersSubMenu.getLineSpacing()); 21 | numPlayersSubMenu.setPosition(setupMenu.getPosition().x+constants::windowWidth/2,setupMenu.getPosition().y); 22 | landTypeSubMenu.setActive(false); 23 | landTypeSubMenu.setPosition(setupMenu.getPosition().x+constants::windowWidth/2,setupMenu.getPosition().y+setupMenu.getLineSpacing()); 24 | landTypeSubMenu.add(sf::Color::White,"Flats","Valley","Hilly","Random"); 25 | landTypeSubMenu.setBackgroundColor(sf::Color(100,100,100,150)); 26 | landTypeSubMenu.setSelectionBgColor(sf::Color(0,0,0,100)); 27 | landTypeSubMenu.create(200); 28 | setupMenu.add(sf::Color::White,"Players : "+std::to_string(numOfPlyrs),"Land type : "+landtypes[l_type],std::string("Start Game")); 29 | setupMenu.create(constants::windowWidth,constants::windowHeight); 30 | } 31 | void GameSetupScreen::reset(){} 32 | void GameSetupScreen::draw(sf::RenderWindow &window) 33 | { 34 | window.draw(bg); 35 | setupMenu.draw(window); 36 | if(numPlayersSubMenu.getActive()) 37 | numPlayersSubMenu.draw(window); 38 | if(landTypeSubMenu.getActive()) 39 | landTypeSubMenu.draw(window); 40 | } 41 | void GameSetupScreen::update(float dt) 42 | { 43 | setupMenu.step(dt); 44 | numPlayersSubMenu.step(dt); 45 | landTypeSubMenu.step(dt); 46 | int query = setupMenu.querySelecion(); 47 | if(query >= 0) 48 | { 49 | switch(query) 50 | { 51 | case 0://"Player" 52 | numPlayersSubMenu.setActive(true); 53 | landTypeSubMenu.setActive(false); 54 | setupMenu.setActive(false); 55 | break; 56 | case 1://"Land Type" 57 | landTypeSubMenu.setActive(true); 58 | numPlayersSubMenu.setActive(false); 59 | setupMenu.setActive(false); 60 | break; 61 | case 2://"Start Game" 62 | Application::changeState(GameState); 63 | Application::getGame().newGame(numOfPlyrs,static_cast(l_type)); 64 | break; 65 | default: 66 | assert(false); 67 | } 68 | } 69 | if(numPlayersSubMenu.getActive()) 70 | { 71 | query = numPlayersSubMenu.querySelecion(); 72 | if(query >= 0) 73 | { 74 | numOfPlyrs = query+2; 75 | numPlayersSubMenu.setActive(false); 76 | setupMenu.setActive(true); 77 | setupMenu.clear(); 78 | setupMenu.add(sf::Color::White,"Players : "+std::to_string(numOfPlyrs),"Land type : "+landtypes[l_type],"Start Game"); 79 | setupMenu.create(constants::windowWidth,0); 80 | } 81 | } 82 | else if(landTypeSubMenu.getActive()) 83 | { 84 | query = landTypeSubMenu.querySelecion(); 85 | if(query >= 0) 86 | { 87 | l_type = query; 88 | landTypeSubMenu.setActive(false); 89 | setupMenu.clear(); 90 | setupMenu.setActive(true); 91 | setupMenu.add(sf::Color::White,"Players : "+std::to_string(numOfPlyrs),"Land type : "+landtypes[l_type],"Start Game"); 92 | setupMenu.create(constants::windowWidth,0); 93 | } 94 | } 95 | } 96 | void GameSetupScreen::passEvent(sf::Event event) 97 | { 98 | setupMenu.passEvent(event); 99 | landTypeSubMenu.passEvent(event); 100 | numPlayersSubMenu.passEvent(event); 101 | } 102 | -------------------------------------------------------------------------------- /GameSetupScreen.h: -------------------------------------------------------------------------------- 1 | #ifndef GAMESETUPSCREEN_H 2 | #define GAMESETUPSCREEN_H 3 | 4 | #include "AppState.h" 5 | #include "Menu.h" 6 | 7 | #include 8 | #include 9 | 10 | class GameSetupScreen : public AppState 11 | { 12 | public: 13 | GameSetupScreen(); 14 | virtual ~GameSetupScreen() = default; 15 | void reset(); 16 | void draw(sf::RenderWindow &window); 17 | void update(float dt); 18 | void passEvent(sf::Event event); 19 | private: 20 | Menu setupMenu; 21 | Menu numPlayersSubMenu; 22 | Menu landTypeSubMenu; 23 | int numOfPlyrs; 24 | int l_type; 25 | sf::Sprite bg; 26 | std::array landtypes{{"Flats","Valley","Hilly","Random"}}; 27 | }; 28 | 29 | #endif // GAMESETUPSCREEN_H 30 | -------------------------------------------------------------------------------- /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 | . -------------------------------------------------------------------------------- /Land.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | No rights Reserved. 3 | Amish Kumar Naidu 4 | amhndu at gmail.com 5 | */ 6 | #include "Land.h" 7 | #include "Application.h" 8 | #include "utilities.h" 9 | #include "simplexnoise.h" 10 | 11 | Land::Land() : 12 | WorldObject(LandType), 13 | LandModified(false), 14 | hmap(constants::windowWidth), 15 | slColumns(), 16 | LandSpr(), 17 | LandImg(), 18 | LandTexture() 19 | { 20 | LandImg.create(constants::windowWidth, constants::windowHeight, sf::Color::Transparent); 21 | } 22 | void Land::destroyCircle(int x0, int y0, int radius) 23 | { 24 | int x = 0 , y = radius; 25 | int sqradius = radius*radius; 26 | while( x < radius ) 27 | { 28 | destroyColumn(x0+x,y0-y,y0+y); 29 | destroyColumn(x0-x,y0-y,y0+y); 30 | ++x; 31 | y = cachedSqrt(sqradius-x*x)+0.5; 32 | } 33 | } 34 | void Land::destroyColumn(int x,int top,int bottom) 35 | { 36 | if(!isInWindow(x,0)) 37 | return; 38 | int LandTop = constants::windowHeight-hmap[x]; 39 | bottom = std::min(bottom,constants::windowHeight-1); 40 | top = std::max(0,top); 41 | if(bottom > LandTop) 42 | { 43 | // We have two cases , 44 | // case 1 the part is inside the Land , making a cavity 45 | if(top > LandTop) 46 | { 47 | for(int iy = top; iy <= bottom ; ++iy) 48 | LandImg.setPixel(x,iy,sf::Color::Transparent); 49 | std::list &slColList = slColumns[x]; 50 | slManifest cav{top,bottom,60}; 51 | for(auto i = slColList.begin() ;;) //insert the cavity appropriately into the list 52 | { 53 | if(cav.dest < i->src || i == slColList.end()) 54 | { 55 | slColList.insert(i,cav); 56 | break; 57 | } 58 | if(i->intersects(cav)) //then merge i to cav and continue with the new i 59 | { 60 | cav.merge(*i); 61 | i = slColList.erase(i); 62 | } 63 | else ++i; 64 | } 65 | Application::getMsgStream().sendMessage(Message("SetLandSlide"),"GameState"); 66 | } 67 | // case 2 the part is on the surface , it makes a crater 68 | else 69 | { 70 | for(int iy = LandTop; iy <= bottom ; ++iy) 71 | LandImg.setPixel(x,iy,sf::Color::Transparent); 72 | hmap[x] = constants::windowHeight-bottom; 73 | } 74 | hmap[x] = std::max(hmap[x],0); 75 | LandModified = true; 76 | } 77 | } 78 | void Land::step(float dt) 79 | { 80 | // if(LandModified) //last iteration's flag 81 | // { 82 | // LandTexture.loadFromImage(LandImg); 83 | // Application::getMsgStream().getGroup("Tanks").sendMessage(Message("LandModified")); 84 | // LandModified = false; 85 | // } 86 | std::list colrem;//columns to remove 87 | for(auto &i : slColumns) 88 | { 89 | std::list &slColList = i.second; 90 | int x = i.first; 91 | for(auto j = slColList.rbegin(); j != slColList.rend() ; ++j) 92 | { 93 | bool doneSliding = false; //whether the cavity has been filled due to sliding 94 | j->velocity += constants::gravity*dt; 95 | int ds = j->velocity*dt+0.5 , ulim = constants::windowHeight-hmap[x]; 96 | if(ds <= 0) continue; 97 | if(ds + j->src >= j->dest) 98 | { 99 | ds = j->dest - j->src + 1; 100 | j->src = j->dest; 101 | doneSliding = true; 102 | } 103 | else j->src += ds; 104 | auto upperCol = std::next(j); 105 | if(upperCol != slColList.rend()) 106 | ulim = (upperCol->dest += ds); 107 | else 108 | hmap[x] = std::max(0,hmap[x]-ds); 109 | for(int k = j->src;k >= ulim;--k) 110 | { 111 | //for (x,k) set the pixel to (x,k-ds) i.e. move the pixels below by ds 112 | LandImg.setPixel(x , k , 113 | (k-ds>=0)?LandImg.getPixel(x,k-ds):sf::Color::Transparent); 114 | } 115 | if(doneSliding) 116 | { 117 | auto jminus1 = std::prev(j); 118 | slColList.erase(std::prev(j.base())); 119 | j = jminus1; 120 | } 121 | } 122 | if(slColList.empty()) //if no cavities 123 | { 124 | colrem.push_back(x); 125 | } 126 | LandModified = true; 127 | } 128 | for(int x : colrem) 129 | { 130 | slColumns.erase(x); 131 | if(slColumns.empty()) 132 | { 133 | Application::getMsgStream().sendMessage(Message("UnsetLandSlide"),"GameState"); 134 | } 135 | } 136 | } 137 | void Land::draw(sf::RenderTarget &target) 138 | { 139 | if(LandModified) 140 | { 141 | LandTexture.loadFromImage(LandImg); 142 | LandModified = false; 143 | } 144 | target.draw(LandSpr); 145 | } 146 | void Land::reset() 147 | { 148 | hmap.resize(constants::windowWidth); 149 | } 150 | int Land::getHeight(int x) 151 | { 152 | if(x >= 0 && x < int(hmap.size())) 153 | { 154 | return hmap[x]; 155 | } 156 | return 0; 157 | } 158 | sf::Vector2f Land::getNormal(int x,int y) 159 | { 160 | //Calculate the weighted average of the solid pixels to get the normal 161 | float avgX = 0; 162 | float avgY = 0; 163 | int sq = 3;//size of the square to calculate the average 164 | for(int w = -sq; w <= sq; w++) 165 | { 166 | for(int h = -sq; h <= sq; h++) 167 | { 168 | if(isPixelSolid(x+w,y+h)) 169 | { 170 | avgX -= w; 171 | avgY -= h; 172 | } 173 | } 174 | } 175 | float mod = std::hypot(avgX,avgY); 176 | return (mod)?sf::Vector2f(avgX/mod,avgY/mod):sf::Vector2f(); 177 | } 178 | float Land::getNormAngle(int x,int y) 179 | { 180 | //Calculate the weighted average of the solid pixels to get the normal 181 | float avgX = 0,avgY = 0; 182 | int sq = 3;//size of the square to calculate the average 183 | for(int w = -sq; w <= sq; w++) 184 | { 185 | for(int h = -sq; h <= sq; h++) 186 | { 187 | if(isPixelSolid(x + w, y + h)) 188 | { 189 | avgX -= w; 190 | avgY -= h; 191 | } 192 | } 193 | } 194 | // float slope = (-hmap[x-sq]+hmap[x+sq])/-float(sq); 195 | // float slope2 =(-hmap[x-sq]+hmap[x+sq])/-float(sq+1); 196 | // std::cout << "Angles :\n\t" << TO_DEG(arctan(1.f,slope)) << "\n\t" << TO_DEG(arctan(1.f,slope2)) << "\n\t" << TO_DEG(arctan(slope,1.f)) << "\n\t"; 197 | // std::cout << "Correct : " << TO_DEG(arctan(-avgY,avgX)) << std::endl; 198 | // return arctan(1.f,slope2); 199 | return arctan(-avgY,avgX); 200 | } 201 | void Land::genHeightMap(Landtype Land_t) 202 | { 203 | if(Land_t == Random) { Land_t = Landtype(rand() % Random); } 204 | int octaves, llim = 0, ulim = constants::windowHeight; 205 | double persistance, scale, detail; 206 | switch(Land_t) 207 | { 208 | case Flats: //Many magic numbers here , found by trial and error 209 | octaves = 1; 210 | persistance = 1; 211 | scale = 1; 212 | detail = constants::windowWidth * 1.25; 213 | ulim = constants::windowHeight * 2 / 3.0 - 100; 214 | llim = constants::windowHeight / 3.0; 215 | break; 216 | case Hilly: 217 | octaves = 4; 218 | persistance = 0.4; 219 | scale = 1; 220 | detail = constants::windowWidth / 3.0; 221 | break; 222 | case Valley: 223 | octaves = 4; 224 | persistance = 0.2; 225 | scale = 1; 226 | detail = constants::windowWidth / 2.0; 227 | break; 228 | default: 229 | octaves = 8; 230 | persistance = 0.75; 231 | scale = 1; 232 | detail = constants::windowWidth / 3.0; 233 | break; 234 | } 235 | LandImg.create(LandImg.getSize().x,LandImg.getSize().y,sf::Color::Transparent); 236 | double offsetx = (rand() % 1000); 237 | double y = rand() % 1000; 238 | for(int i = 0; i < constants::windowWidth; i++) 239 | { 240 | hmap[i] = scaled_octave_noise_2d(octaves, persistance, scale, llim, ulim, double(i + offsetx) / detail, y / detail); 241 | for(int h = constants::windowHeight - hmap[i]; h < constants::windowHeight ; ++h) 242 | { 243 | LandImg.setPixel(i, h, grad(double(constants::windowHeight - h) / (hmap[i]), 244 | sf::Color(150, 155, 0), sf::Color(50, 150, 50))); 245 | } 246 | } 247 | LandTexture.loadFromImage(LandImg); 248 | LandSpr.setTexture(LandTexture); 249 | } 250 | void Land::handleCollision(WorldObject &b) 251 | { 252 | switch(b.type) 253 | { 254 | case TankType: 255 | b.handleCollision(*this); 256 | case WeaponType: 257 | b.handleCollision(*this); 258 | break; 259 | default: 260 | break; 261 | } 262 | } 263 | void Land::receiveMessage(const Message& msg) 264 | { 265 | if(msg.ID == "DestroyCircle") 266 | { 267 | sf::Vector2i pos = msg.getItem(0); 268 | int r = msg.getItem(1); 269 | destroyCircle(pos.x,pos.y,r); 270 | } 271 | } 272 | bool Land::isPixelSolid(int x,int y) 273 | { 274 | if(isInRange(size_t(x),size_t(0),hmap.size())) 275 | return LandImg.getPixel(x,y) != sf::Color::Transparent; 276 | return true;//outside the window consider the pixels to be solid 277 | } 278 | -------------------------------------------------------------------------------- /Land.h: -------------------------------------------------------------------------------- 1 | #ifndef Land_H 2 | #define Land_H 3 | #include "WorldObject.h" 4 | #include 5 | #include 6 | #include "utilities.h" 7 | #include "Tank.h" 8 | 9 | struct slManifest //sliding columns information structure 10 | { 11 | int src,dest; //describes the cavity in the range [src,dest) 12 | double velocity; 13 | void inline merge(slManifest b) 14 | { 15 | src = std::min(b.src,src); 16 | dest = std::max(b.dest,dest); 17 | } 18 | bool inline intersects(slManifest b) 19 | { 20 | slManifest *minRange = (dest-src < b.dest-b.src)?this:&b; 21 | slManifest *maxRange = (dest-src > b.dest-b.src)?this:&b; 22 | if(isInRange(minRange->src,maxRange->src,maxRange->dest)) 23 | return true; 24 | if(isInRange(minRange->dest,maxRange->src,maxRange->dest)) 25 | return true; 26 | return false; 27 | } 28 | }; 29 | 30 | class Land : public WorldObject 31 | { 32 | public: 33 | Land(); 34 | ~Land() = default; 35 | enum Landtype 36 | { 37 | Flats, 38 | Valley, 39 | Hilly, 40 | Random, 41 | TotalTypes 42 | }; 43 | void genHeightMap(Landtype Land_t); 44 | void step(float dt); 45 | void draw(sf::RenderTarget &target); 46 | void reset(); 47 | void handleCollision(WorldObject &b); 48 | void receiveMessage(const Message& msg); 49 | sf::Vector2f getNormal(int x,int y); 50 | float getNormAngle(int x,int y);//get normal angle 51 | int getHeight(int x); 52 | bool LandModified; 53 | friend Tank; 54 | private: 55 | void destroyCircle(int x0,int y0, int radius); 56 | void destroyColumn(int x,int top,int bottom); 57 | bool isPixelSolid(int x,int y); 58 | std::vector hmap; 59 | std::map> slColumns; 60 | sf::Sprite LandSpr; 61 | sf::Image LandImg; 62 | sf::Texture LandTexture; 63 | }; 64 | 65 | #endif // Land_H 66 | -------------------------------------------------------------------------------- /Menu.cpp: -------------------------------------------------------------------------------- 1 | #include "Menu.h" 2 | #include "Application.h" 3 | #include "utilities.h" 4 | 5 | Menu::Menu(const sf::Font& f,int charSize,int linePad,int scrollBarWidth) : 6 | rndrTxtre(), 7 | spr(), 8 | selectionBg(), 9 | scrollBar(), 10 | view(), 11 | font(f), 12 | menuList(), 13 | active(true), 14 | characterSize(charSize), 15 | linePadding(linePad), 16 | marker(0), 17 | itemsVisible(0), 18 | scrolled(0), 19 | scroll(false), 20 | clicked(-1), 21 | bgColor(sf::Color::Transparent) 22 | { 23 | selectionBg.setFillColor(sf::Color(210,210,210)); 24 | scrollBar.setFillColor(sf::Color(100,100,100)); 25 | scrollBar.setSize(sf::Vector2f(scrollBarWidth,0)); 26 | if(linePad == -1)//at least i don't use negative line paddings , so this ok for me, 27 | { 28 | linePadding = font.getLineSpacing(characterSize)-characterSize; 29 | } 30 | } 31 | void Menu::draw(sf::RenderTarget &target) 32 | { 33 | target.draw(spr); 34 | if(scroll) 35 | target.draw(scrollBar); 36 | } 37 | void Menu::clear() 38 | { 39 | menuList.clear(); 40 | } 41 | void Menu::add(const std::string& item,sf::Color textColor) 42 | { 43 | sfTextPtr newText(new sf::Text(item,font,characterSize)); 44 | newText->setColor(textColor); 45 | newText->setPosition(0,menuList.size()*(linePadding+characterSize)); 46 | menuList.push_back(std::move(newText)); 47 | } 48 | void Menu::create(float width,float height) 49 | { 50 | if(height == 0) 51 | height = menuList.size()*(linePadding+characterSize); 52 | else 53 | height = std::min(menuList.size()*float(linePadding+characterSize),round(height,linePadding+characterSize)); 54 | 55 | itemsVisible = (height/(linePadding+characterSize)); 56 | //max width of the sf::Texts of the menu items 57 | float maxwidth = (**std::max_element(menuList.begin(),menuList.end(), 58 | [](sfTextPtr& a,sfTextPtr &b){ return a->getLocalBounds().widthgetLocalBounds().width;})).getLocalBounds().width; 59 | if(size_t(itemsVisible) < menuList.size()) 60 | { 61 | scroll = true; 62 | } 63 | if(width == 0) width = maxwidth; 64 | else 65 | width = std::max(width,maxwidth); 66 | rndrTxtre.clear(bgColor); 67 | rndrTxtre.create(width,height); 68 | view = rndrTxtre.getDefaultView(); 69 | selectionBg.setSize(sf::Vector2f(width,linePadding+characterSize)); 70 | if(scroll) 71 | { 72 | scrollBar.setSize(sf::Vector2f( scrollBar.getSize().x,std::max(5.0f,height/(menuList.size()+1-itemsVisible)))); 73 | scrollBar.setPosition(spr.getPosition().x+width,spr.getPosition().y+0); 74 | } 75 | 76 | rndrTxtre.clear(bgColor); 77 | rndrTxtre.draw(selectionBg); 78 | for(const auto &a : menuList) 79 | { 80 | rndrTxtre.draw(*a); 81 | } 82 | rndrTxtre.display(); 83 | spr.setTexture(rndrTxtre.getTexture(),true); 84 | } 85 | void Menu::step(float dt) 86 | { 87 | if(!active) return; 88 | int deltaScroll = 0; 89 | bool update = false; 90 | 91 | sf::Vector2f mouse = sf::Vector2f(sf::Mouse::getPosition(Application::getWindow())); 92 | sf::Vector2f relMouse = mouse - spr.getPosition(); 93 | sf::Vector2f mouseInView = rndrTxtre.mapPixelToCoords(static_cast(relMouse)); 94 | if(scroll && sf::Mouse::isButtonPressed(sf::Mouse::Left) && contains(scrollBar.getPosition().x,spr.getPosition().y,scrollBar.getSize().x,view.getSize().y,mouse.x,mouse.y)) 95 | { 96 | int new_scrolled = (menuList.size()-itemsVisible+1)*relMouse.y/(view.getSize().y); 97 | if(new_scrolled != scrolled) 98 | { 99 | deltaScroll = new_scrolled-scrolled; 100 | update = true; 101 | } 102 | } 103 | if(update) updateTexture(deltaScroll); 104 | } 105 | void Menu::passEvent(const sf::Event &event) 106 | { 107 | if(!active) return; 108 | bool update = false; 109 | int deltaScroll = 0; 110 | if(event.type == sf::Event::KeyPressed) 111 | { 112 | switch(event.key.code) 113 | { 114 | case sf::Keyboard::Up: 115 | if(--marker < 0) 116 | { 117 | marker = menuList.size()-1; 118 | deltaScroll = menuList.size()-itemsVisible; 119 | } 120 | else if(marker < scrolled) 121 | deltaScroll = -1; 122 | update = true; 123 | break; 124 | case sf::Keyboard::Down: 125 | if(size_t(++marker) > menuList.size()-1) 126 | { 127 | deltaScroll = -menuList.size()+itemsVisible; 128 | marker = 0; 129 | } 130 | else if(marker-scrolled+1>itemsVisible) 131 | deltaScroll = 1; 132 | update = true; 133 | break; 134 | case sf::Keyboard::Return: 135 | clicked = marker; 136 | break; 137 | default: 138 | break; 139 | } 140 | } 141 | else if(event.type == sf::Event::MouseMoved) 142 | { 143 | sf::Vector2f mouse(event.mouseMove.x,event.mouseMove.y); 144 | sf::Vector2f mouseInView = rndrTxtre.mapPixelToCoords(sf::Vector2i(mouse) - sf::Vector2i(spr.getPosition())); 145 | if(spr.getGlobalBounds().contains(mouse) && mouseInView.y/(linePadding+characterSize) != marker && mouseInView.y/(linePadding+characterSize)-scrolled <= menuList.size()) 146 | { 147 | marker = mouseInView.y/(linePadding+characterSize); 148 | update = true; 149 | } 150 | } 151 | else if(event.type == sf::Event::MouseButtonPressed) 152 | { 153 | sf::Vector2f mouse(event.mouseButton.x,event.mouseButton.y); 154 | sf::Vector2f mouseInView = rndrTxtre.mapPixelToCoords(sf::Vector2i(mouse) - sf::Vector2i(spr.getPosition())); 155 | if(spr.getGlobalBounds().contains(mouse) && mouseInView.y/(linePadding+characterSize) != marker && mouseInView.y/(linePadding+characterSize)-scrolled <= menuList.size()) 156 | { 157 | clicked = marker = mouseInView.y/(linePadding+characterSize); 158 | update = true; 159 | } 160 | } 161 | else if(event.type == sf::Event::MouseWheelMoved) 162 | { 163 | if(-event.mouseWheel.delta+scrolled+itemsVisible <= int(menuList.size()) && -event.mouseWheel.delta+scrolled >= 0) 164 | { 165 | sf::Vector2f mouse(event.mouseWheel.x,event.mouseWheel.y); 166 | if(spr.getGlobalBounds().contains(mouse)) 167 | { 168 | deltaScroll = -event.mouseWheel.delta; 169 | update = true; 170 | mouse.y += deltaScroll*(linePadding+characterSize);//adjust for the new scroll 171 | mouse -= spr.getPosition(); 172 | mouse = rndrTxtre.mapPixelToCoords(static_cast(mouse)); 173 | if(mouse.y/(linePadding+characterSize) != marker/* && mouse.y/(linePadding+characterSize)-scrolled <= itemsVisible*/) 174 | marker = mouse.y/(linePadding+characterSize); 175 | } 176 | } 177 | } 178 | 179 | if(update) updateTexture(deltaScroll); 180 | } 181 | void Menu::updateTexture(int deltaScroll) 182 | { 183 | selectionBg.setPosition(0,marker*(linePadding+characterSize)); 184 | if(deltaScroll) 185 | { 186 | scrolled += deltaScroll; 187 | view.move(0,deltaScroll*(linePadding+characterSize)); 188 | scrollBar.setPosition(scrollBar.getPosition().x,spr.getPosition().y+(view.getSize().y-scrollBar.getSize().y)*scrolled/(menuList.size()-itemsVisible)); 189 | } 190 | rndrTxtre.setView(view); 191 | rndrTxtre.clear(bgColor); 192 | rndrTxtre.draw(selectionBg); 193 | for(const auto &a : menuList) 194 | { 195 | rndrTxtre.draw(*a); 196 | } 197 | rndrTxtre.display(); 198 | } 199 | -------------------------------------------------------------------------------- /Menu.h: -------------------------------------------------------------------------------- 1 | #ifndef MENU_H 2 | #define MENU_H 3 | #include 4 | #include 5 | #include 6 | 7 | typedef std::unique_ptr sfTextPtr; 8 | 9 | class Menu 10 | { 11 | public: 12 | Menu(const sf::Font &f,int charSize = 20,int linePad = -1,int scrollBarWidth = 6); 13 | ~Menu() = default; 14 | void draw(sf::RenderTarget &target); 15 | template 16 | inline void add(const std::string& str,Tail... T) 17 | { 18 | add(str); 19 | add(T...); 20 | } 21 | template 22 | inline void add(const sf::Color& color,const std::string& str,Tail... T) 23 | { 24 | add(str,color); 25 | add(color,T...); 26 | } 27 | void add(const sf::Color& color){}//does nothing required for the variadic template recursion when Tail is nothing 28 | //the string mustn't contain any escape characters like '\n' and '\v' i.e they should only 29 | //span one line 30 | void add(const std::string& item,sf::Color textColor = sf::Color::Black); 31 | void step(float dt); 32 | //create the menu after adding all the menu item 33 | //calling with no arguments means set it to fit all the menu items, 34 | //width >= max width of menu items 35 | //height is rounded to a nearby multiple of (linePadding+characterSize), and the extra menu items are scrollable 36 | //and clamped to the maximum height of all the items 37 | void create(float width = 0,float height = 0); 38 | void passEvent(const sf::Event& event); 39 | void clear();//clear and reset the menu items 40 | //clicked < 0 means not clicked yet, after querying it is set to -1 41 | inline int querySelecion() 42 | { 43 | int temp = clicked; 44 | clicked=-1; 45 | return temp; 46 | } 47 | inline int getCharacterSize(){ return characterSize; } 48 | inline int getLinePadding(){ return linePadding; } 49 | inline void setCharacterSize(int size){ characterSize=size;} 50 | inline void setLinePadding(int pad){ linePadding=pad;} 51 | inline void setPosition(float x,float y) 52 | { 53 | scrollBar.move(-spr.getPosition()); 54 | spr.setPosition(x,y); 55 | scrollBar.move(spr.getPosition()); 56 | } 57 | inline void setSelectionBgColor(const sf::Color& theColor){ selectionBg.setFillColor(theColor); } 58 | inline const sf::Color& getSelectionBgColor(){ return selectionBg.getFillColor(); } 59 | inline void setScrollBarColor(const sf::Color& theColor){ scrollBar.setFillColor(theColor); } 60 | inline const sf::Color& getScrollBarColor(){ return scrollBar.getFillColor(); } 61 | inline sf::Vector2f getPosition(){ return spr.getPosition();} 62 | inline int getLineSpacing(){ return linePadding+characterSize; } 63 | inline void setActive(bool val){ active = val; } 64 | inline bool getActive(){ return active; } 65 | inline const sf::Vector2f& getSize(){ return view.getSize(); } 66 | inline void setBackgroundColor(const sf::Color& theColor){ bgColor=theColor; } 67 | private: 68 | void updateTexture(int deltaScroll = 0); 69 | sf::RenderTexture rndrTxtre; 70 | sf::Sprite spr; 71 | sf::RectangleShape selectionBg; 72 | sf::RectangleShape scrollBar; 73 | sf::View view; 74 | const sf::Font &font; 75 | std::list menuList; 76 | bool active; 77 | int characterSize; 78 | int linePadding; 79 | int marker; 80 | int itemsVisible; //in the view 81 | int scrolled;//no of items above not visible 82 | bool scroll; 83 | int clicked;//on item 84 | sf::Color bgColor; 85 | }; 86 | 87 | #endif // MENU_H 88 | -------------------------------------------------------------------------------- /Message.h: -------------------------------------------------------------------------------- 1 | #ifndef MESSAGE_H 2 | #define MESSAGE_H 3 | #include 4 | #include 5 | #include 6 | 7 | class MsgItemBase{}; 8 | 9 | template 10 | class MsgItem : public MsgItemBase 11 | { 12 | public: 13 | MsgItem(const T& val) : item(val) {} 14 | T item; 15 | }; 16 | 17 | class Message 18 | { 19 | public: 20 | Message(); 21 | Message(const std::string& id) : ID(id) {} 22 | ~Message() = default; 23 | template 24 | Message(const std::string& id,T... items) : ID(id) { add(items...); } 25 | 26 | template 27 | void add(const T& a,Tail... tail) 28 | { 29 | data.push_back(std::unique_ptr(new MsgItem(a))); 30 | add(tail...); 31 | } 32 | void add(){}; 33 | 34 | template 35 | const T& getItem(std::size_t n) const 36 | { 37 | return static_cast*>(data[n].get())->item; 38 | } 39 | 40 | std::string ID; 41 | private: 42 | std::vector> data; 43 | }; 44 | 45 | #endif // MESSAGE_H 46 | -------------------------------------------------------------------------------- /MessageStream.cpp: -------------------------------------------------------------------------------- 1 | #include "MessageStream.h" 2 | #include 3 | 4 | MessageStream::MessageStream() 5 | { 6 | //ctor 7 | } 8 | 9 | void MessageStream::addGroup(std::string name,MsgGroup &grp) 10 | { 11 | groups.insert(std::make_pair(name,std::move(grp))); 12 | } 13 | void MessageStream::removeGroup(std::string name) 14 | { 15 | groups.erase(name); 16 | } 17 | MsgGroup& MessageStream::getGroup(std::string name) //if group 'name' doesn't exist it is created and returned 18 | { 19 | return groups[name]; 20 | } 21 | void MessageStream::sendMessage(const Message &msg,std::string grp) 22 | { 23 | auto it = groups.find(grp); 24 | if(it != groups.end()) 25 | it->second.sendMessage(msg); 26 | else 27 | std::cerr << "Error : MessageStream::sendMessage : Message group \"" 28 | << grp << "\"not found." << std::endl; 29 | } 30 | -------------------------------------------------------------------------------- /MessageStream.h: -------------------------------------------------------------------------------- 1 | #ifndef MESSAGESTREAM_H 2 | #define MESSAGESTREAM_H 3 | #include "MsgComponents.h" 4 | #include 5 | 6 | class MessageStream 7 | { 8 | public: 9 | MessageStream(); 10 | void addGroup(std::string name,MsgGroup &grp); 11 | void removeGroup(std::string name); 12 | MsgGroup& getGroup(std::string name); 13 | void sendMessage(const Message &msg,std::string grp); 14 | private: 15 | std::map groups; 16 | }; 17 | 18 | #endif // MESSAGESTREAM_H 19 | -------------------------------------------------------------------------------- /Missile.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | No rights Reserved. 3 | Amish Kumar Naidu 4 | amhndu at gmail.com 5 | */ 6 | #include "Missile.h" 7 | #include "Application.h" 8 | #include "Land.h" 9 | #include "Tank.h" 10 | #include "utilities.h" 11 | #include "WeaponPostEffects.h" 12 | 13 | Missile::Missile(double x, double y) : velocity(0, 0) , acceleration(0, constants::gravity) 14 | { 15 | type = WorldObject::WeaponType; 16 | selfDestruct = false; 17 | projectile.setRadius(2.5); 18 | projectile.setFillColor(sf::Color::Magenta); 19 | projectile.setPosition(x, y); 20 | Application::getGame().incCounter(); 21 | } 22 | Missile::~Missile() 23 | { 24 | Application::getGame().decCounter(); 25 | } 26 | void Missile::setVelocity(double x, double y) 27 | { 28 | velocity.x = x; 29 | velocity.y = y; 30 | } 31 | void Missile::setAcceleration(double x, double y) 32 | { 33 | acceleration.x = x; 34 | acceleration.y = y; 35 | } 36 | void Missile::handleCollision(WorldObject &b) 37 | { 38 | switch(b.type) 39 | { 40 | case WorldObject::TankType: 41 | { 42 | Tank &t = static_cast(b); 43 | if(intersects(projectile,t.getTankRect())) 44 | explode(); 45 | } 46 | break; 47 | case WorldObject::LandType: 48 | { 49 | Land &l = static_cast(b); 50 | if(projectile.getPosition().y + projectile.getRadius() > (constants::windowHeight - l.getHeight(projectile.getPosition().x))) 51 | explode(); 52 | } 53 | break; 54 | default: 55 | break; 56 | } 57 | } 58 | void Missile::draw(sf::RenderTarget &target) 59 | { 60 | target.draw(projectile); 61 | } 62 | void Missile::step(float dt) 63 | { 64 | velocity += acceleration * dt; 65 | projectile.move( velocity * dt ); 66 | if(projectile.getPosition().x >= constants::windowWidth || projectile.getPosition().x < 0 67 | || projectile.getPosition().y >= constants::windowHeight) 68 | { 69 | selfDestruct = true; 70 | } 71 | } 72 | void Missile::explode() 73 | { 74 | Application::getMsgStream().sendMessage(Message("DestroyCircle",sf::Vector2i(projectile.getPosition()),30),"Land"); 75 | Application::getGame().addWorldObj(new Explosion(MissileExplosionA,projectile.getPosition(),30)); 76 | selfDestruct = true; 77 | } 78 | -------------------------------------------------------------------------------- /Missile.h: -------------------------------------------------------------------------------- 1 | #ifndef MISSILE_H 2 | #define MISSILE_H 3 | #include "WorldObject.h" 4 | 5 | class Missile : public WorldObject 6 | { 7 | public: 8 | Missile(double x, double y); 9 | ~Missile(); 10 | void handleCollision(WorldObject &b); 11 | void draw(sf::RenderTarget &target); 12 | void step(float dt); 13 | void setVelocity(double x, double y); 14 | void setAcceleration(double x, double y); 15 | inline void reset(){ selfDestruct = true; } 16 | private: 17 | void explode(void); 18 | sf::CircleShape projectile; 19 | sf::Vector2f velocity; 20 | sf::Vector2f acceleration; 21 | }; 22 | 23 | #endif // MISSILE_H 24 | -------------------------------------------------------------------------------- /MsgComponents.cpp: -------------------------------------------------------------------------------- 1 | #include "MsgComponents.h" 2 | 3 | MsgGroup::MsgGroup() 4 | {} 5 | MsgGroup::MsgGroup(MsgGroup &&cpy) : subscribers(std::move(cpy.subscribers)) 6 | {} 7 | 8 | void MsgGroup::sendMessage(const Message &msg) 9 | { 10 | for(auto &R : subscribers) R->receiveMessage(msg); 11 | } 12 | void MsgGroup::unsubscribe(Receiver *r) 13 | { 14 | subscribers.remove(r); 15 | } 16 | void MsgGroup::subscribe(Receiver *r) 17 | { 18 | subscribers.push_back(r); 19 | } 20 | -------------------------------------------------------------------------------- /MsgComponents.h: -------------------------------------------------------------------------------- 1 | #ifndef MSGCOMPONENTS_H 2 | #define MSGCOMPONENTS_H 3 | #include "Message.h" 4 | #include 5 | class Receiver 6 | { 7 | public: 8 | virtual ~Receiver(){}; 9 | virtual void receiveMessage(const Message &msg) {}; 10 | }; 11 | 12 | class MsgGroup 13 | { 14 | public: 15 | MsgGroup(); 16 | MsgGroup(MsgGroup &&cpy); 17 | void sendMessage(const Message &msg); 18 | void clear(){ subscribers.clear(); } 19 | void subscribe(Receiver *r); 20 | void unsubscribe(Receiver *r); 21 | private: 22 | std::list subscribers; 23 | }; 24 | #endif // MSGCOMPONENTS_H 25 | -------------------------------------------------------------------------------- /Player.cpp: -------------------------------------------------------------------------------- 1 | #include "Player.h" 2 | #include "Application.h" 3 | #include "Missile.h" 4 | #include "utilities.h" 5 | 6 | Player::Player(Tank *val,const std::string& name) : 7 | myTank(val), 8 | playerName(name), 9 | life(maxlife), 10 | power(0.4) 11 | {} 12 | void Player::fire() 13 | { 14 | double phi = TO_RAD(myTank->turret.getRotation()); 15 | double sin = std::sin(phi) , cos = std::cos(phi); 16 | double TankVelocity = power*500; 17 | Missile *m=new Missile(myTank->turret.getPosition().x + myTank->turret.getLocalBounds().width * cos, 18 | myTank->turret.getPosition().y + myTank->turret.getLocalBounds().width * sin); 19 | m->setVelocity(TankVelocity * cos, TankVelocity * sin); 20 | Application::getGame().addWorldObj(m); 21 | Application::getMsgStream().sendMessage(Message("PlayerTurnOver"),"GameState"); 22 | } 23 | -------------------------------------------------------------------------------- /Player.h: -------------------------------------------------------------------------------- 1 | #ifndef PLAYER_H 2 | #define PLAYER_H 3 | #include "Tank.h" 4 | 5 | class Player 6 | { 7 | public: 8 | static const int maxlife = 100; 9 | Player() = default; 10 | Player(Tank *val,const std::string& name = "Player"); 11 | void fire(); 12 | inline const std::string& getName() { return playerName; } 13 | inline Tank &getTank() { return *myTank; } 14 | inline void setTank(Tank *t){myTank = t;} 15 | inline void rotateTurret(float f){ myTank->turret.rotate(f); } 16 | inline void setPower(float pow){ power=pow;} 17 | inline float getPower(){ return power; } 18 | inline void setTankPos(const sf::Vector2f& pos) { myTank->setPosition(pos); } 19 | inline float getTurretAngle(){ return myTank->turret.getRotation(); } 20 | inline const sf::Vector2f& getTankPos() { return myTank->tank.getPosition(); } 21 | inline void moveTank(int dir){ myTank->setMovement(dir); } //left: -1, right: 1 22 | inline void setLife(int l){life = l;} 23 | inline int getLife() { return life; } 24 | inline bool isDead(){return !(life);} 25 | private: 26 | Tank *myTank; 27 | std::string playerName; 28 | int life; 29 | float power; //in range [0,1] 30 | }; 31 | typedef std::unique_ptr Playerptr; 32 | #endif // PLAYER_H 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mini Tanks 2 | ============= 3 | 4 | Project page : http://amhndu.github.io/Projects/mini-tanks.html 5 | 6 | A turn-based, artillery game where you destroy other tanks to win in a fully destructible, procedurally generated terrain. Supports multiplayer with upto 8 local players. 7 | This was inspired by Pocket Tanks and Scorched Earth. 8 | Programmed in C++11 with SFML used for graphics. 9 | 10 | Controls and Objective 11 | ------------------------ 12 | Use your mouse to click on the HUD or press R to set the Rotation of the turret, similarly set power by clicking the power bar (or by hovering the cursor above it and using your scroll wheel) 13 | Use Arrow Keys Left or Right to move the Tank. 14 | Click on "FIRE" on the HUD or press Space to fire. 15 | The objective is very simple, destroy other tanks and you win. 16 | 17 | Source: 18 | ------------------------ 19 | [Github: amhndu/tanks-game](https://github.com/amhndu/tanks-game). 20 | 21 | Screenshots 22 | ------------------------ 23 | ![Screenshot 1](http://amhndu.github.io/screenshots/tanks0.jpg) 24 | ![Screenshot 2](http://amhndu.github.io/screenshots/tanks1.jpg) 25 | ![Screenshot 3](http://amhndu.github.io/screenshots/tanks2.jpg) 26 | ![Screenshot 4](http://amhndu.github.io/screenshots/tanks3.jpg) 27 | ![Screenshot 5](http://amhndu.github.io/screenshots/tanks4.jpg) 28 | 29 | Video 30 | ------------------------- 31 | [Youtube Video](http://www.youtube.com/watch?v=YbG_ej2fQKE) 32 | 33 | Compiling 34 | -------------------------- 35 | You need a C++11 compliant compiler and [SFML 2.0+](http://sfml-dev.org) to compile *Mini Tanks*. After you've downloaded the source and dependencies, you can use [cmake](http://cmake.org) to compile *Mini Tanks*. 36 | On any Linux distribution, these are the typical steps : 37 | ``` 38 | $ git clone https://github.com/amhndu/tanks-game 39 | $ cd tanks-game 40 | $ cmake . 41 | $ make 42 | ``` 43 | If you don't have cmake and don't wish to install it either, then you can simply compile Mini Tanks by compiling all the cpp files and then linking them with SFML using your IDE/compiler. e.g. With g++, you can enter this command : 44 | ``` 45 | $ g++ -o miniTanks *.cpp -std=c++11 -lsfml-graphics -lsfml-window -lsfml-system 46 | ``` 47 | Note : To compile on windows, you also need to link the sfml-main component. 48 | 49 | Download 50 | -------------------------- 51 | [Download the source](https://github.com/amhndu/tanks-game/archive/master.zip) 52 | Executables : 53 | Note : These are outdated by a few commits (which were only some fixes). It is recommended to compile Mini Tanks from source if you can. 54 | [Linux 32-bit](https://www.dropbox.com/s/v4shlyt8j8odv4e/tanks-bin-linux32.tar.gz) (compiled using g++ 4.8.1) 55 | [Windows 32-bit](https://www.dropbox.com/s/ixu8g65mszea4b4/tanks-bin-win32.zip) (compiled using VC 2013 and requires VC2013 redistributable) 56 | 57 | 58 | Contact me 59 | ---------------------------- 60 | Email : amhndu --at-- gmail --period-- com 61 | -------------------------------------------------------------------------------- /ResourceIdentifiers.h: -------------------------------------------------------------------------------- 1 | #ifndef RESOURCEIDENTIFIERS_INCLUDED 2 | #define RESOURCEIDENTIFIERS_INCLUDED 3 | #include 4 | enum TextureIdentifier 5 | { 6 | TankTexture, 7 | ExplosionA, 8 | // ExplosionB, 9 | TurretTexture, 10 | TurretTarget, 11 | ArrowDownSpriteSheet, 12 | TitleBg 13 | }; 14 | enum FontIdentifier 15 | { 16 | FreeSans, 17 | UbuntuCondensed 18 | }; 19 | 20 | template 21 | class ResourceManager; 22 | 23 | typedef ResourceManager TextureManager; 24 | typedef ResourceManager FontManager; 25 | 26 | 27 | #endif // RESOURCEIDENTIFIERS_INCLUDED 28 | -------------------------------------------------------------------------------- /ResourceManager.h: -------------------------------------------------------------------------------- 1 | #ifndef RESOURCEMANAGER_H 2 | #define RESOURCEMANAGER_H 3 | #include 4 | #include 5 | #include 6 | 7 | template 8 | class ResourceManager 9 | { 10 | public: 11 | ResourceManager() = default; 12 | bool load(Identifier id, const std::string& file) 13 | { 14 | std::unique_ptr a(new Resource()); 15 | bool status = a->loadFromFile(file); 16 | auto x = resMap.insert(std::make_pair(id,std::move(a))); 17 | assert(x.second); 18 | return status; 19 | } 20 | template 21 | bool load(Identifier id, const std::string& file,Parameter secParam) 22 | { 23 | std::unique_ptr a(new Resource()); 24 | bool status = a->loadFromFile(file,secParam); 25 | resMap.insert(std::make_pair(id,std::move(a))); 26 | return status; 27 | } 28 | Resource &get(Identifier id) 29 | { 30 | auto res = resMap.find(id); 31 | assert(res != resMap.end()); 32 | return *(res->second); 33 | } 34 | private: 35 | std::map > resMap; 36 | }; 37 | #include "ResourceIdentifiers.h" 38 | #endif // RESOURCEMANAGER_H 39 | -------------------------------------------------------------------------------- /Tank.cpp: -------------------------------------------------------------------------------- 1 | #include "Tank.h" 2 | #include "Application.h" 3 | #include "Missile.h" 4 | #include "utilities.h" 5 | #include "WeaponPostEffects.h" 6 | 7 | #define HMAP(n) Application::getGame().getLandHeight(n) 8 | #define R_POINTDIST(n) (cachedSqrt(1 + (HMAP(n) - HMAP((n)+1))*(HMAP(n) - HMAP((n)+1)))+0.5) 9 | #define L_POINTDIST(n) (-cachedSqrt(1+ (HMAP((n)-1) - HMAP(n))*(HMAP((n)-1) - HMAP(n)))-0.5) 10 | #define TANK_WIDTH tank.getLocalBounds().width 11 | #define TANK_HEIGHT tank.getLocalBounds().height 12 | 13 | const float lvelocity = 150; 14 | 15 | Tank::Tank() : 16 | WorldObject(TankType) , 17 | myOwner(nullptr) , 18 | moving() , 19 | tank(Application::getTexture(TankTexture)) , 20 | turret(Application::getTexture(TurretTexture)), 21 | lifeBg(sf::Vector2f(TANK_WIDTH,5)), 22 | lifeFill(sf::Vector2f()), 23 | freefall(true), 24 | velocity(), 25 | Name(), 26 | fadingLife(true), 27 | fadingTimer(1) 28 | { 29 | Application::getGame().incCounter(); 30 | tank.setOrigin(tank.getLocalBounds().width / 2, tank.getLocalBounds().height); 31 | turret.setOrigin(0, turret.getLocalBounds().height / 2); 32 | turret.setRotation(-45); 33 | lifeBg.setOutlineColor(sf::Color::Black); 34 | lifeBg.setOutlineThickness(1); 35 | lifeBg.setFillColor(sf::Color::Yellow); 36 | lifeFill.setFillColor(sf::Color::Red); 37 | Name.setColor(sf::Color::Black); 38 | Name.setCharacterSize(15); 39 | Name.setFont(Application::getFont(UbuntuCondensed)); 40 | setPosition(sf::Vector2f()); 41 | } 42 | Tank::~Tank() 43 | { 44 | if(freefall) 45 | Application::getGame().decCounter(); 46 | } 47 | sf::RectangleShape Tank::getTankRect() 48 | { 49 | sf::RectangleShape rs(sf::Vector2f(tank.getLocalBounds().width,tank.getLocalBounds().height)); 50 | rs.setPosition(tank.getPosition().x,tank.getPosition().y-TANK_HEIGHT/2); 51 | return rs; 52 | } 53 | void Tank::weapAct(float dlife) 54 | { 55 | int newlife = std::max(0.0f,myOwner->getLife()-dlife); 56 | assert(newlife<=Player::maxlife); 57 | myOwner->setLife(newlife); 58 | if(newlife == 0) 59 | { 60 | selfDestruct = true; 61 | Application::getMsgStream().sendMessage(Message("TankDestroyed"),"GameState"); 62 | } 63 | setLifeFill(newlife); 64 | fadingLife = true; 65 | fadingTimer = 1; 66 | lifeBg.setFillColor(lifeBg.getFillColor()+sf::Color(0,0,0,255)); 67 | lifeBg.setOutlineColor(lifeBg.getOutlineColor()+sf::Color(0,0,0,255)); 68 | lifeFill.setFillColor(lifeFill.getFillColor()+sf::Color(0,0,0,255)); 69 | Name.setColor(Name.getColor()+sf::Color(0,0,0,255)); 70 | } 71 | void Tank::setPlayer(Player *p) 72 | { 73 | myOwner = p; 74 | Name.setString(p->getName()); 75 | setPosition(tank.getPosition()); 76 | setLifeFill(p->getLife()); 77 | } 78 | void Tank::setLifeFill(int l) 79 | { 80 | lifeFill.setSize(sf::Vector2f(l*lifeBg.getSize().x/100,lifeBg.getSize().y)); 81 | } 82 | void Tank::receiveMessage(const Message& msg) 83 | {} 84 | void Tank::handleCollision(WorldObject &b) 85 | { 86 | switch(b.type) 87 | { 88 | case LandType: 89 | if(freefall) 90 | { 91 | int x0 = tank.getPosition().x , y0 = tank.getPosition().y; 92 | int h = constants::windowHeight-HMAP(x0); 93 | if(h <= y0)//collision 94 | { 95 | float ang = Application::getGame().getLandNormAng(x0,y0); 96 | tank.setRotation(std::fmod(90 - TO_DEG(ang),360) ); 97 | freefall = false; 98 | velocity = sf::Vector2f(); 99 | Application::getGame().decCounter(); 100 | setPosition(x0,h); 101 | break; 102 | } 103 | } 104 | break; 105 | case WeaponType: 106 | case WeaponPostEffectType: 107 | b.handleCollision(*this); 108 | break; 109 | default: 110 | break; 111 | } 112 | } 113 | 114 | void Tank::draw(sf::RenderTarget &target) 115 | { 116 | target.draw(turret); 117 | target.draw(tank); 118 | if(lifeFill.getFillColor().a != 0) 119 | { 120 | target.draw(lifeBg); 121 | target.draw(lifeFill); 122 | target.draw(Name); 123 | } 124 | } 125 | void Tank::setMovement(int val) { moving = val; } 126 | void Tank::step(float dt) 127 | { 128 | if(freefall) 129 | { 130 | velocity.y += constants::gravity*dt; 131 | sf::Vector2f ds = velocity*dt; 132 | tank.move(ds); 133 | turret.move(ds); 134 | lifeBg.move(ds); 135 | lifeFill.move(ds); 136 | Name.move(ds); 137 | } 138 | else 139 | { 140 | if(tank.getPosition().y std::tan(TO_RAD(80))) //if ascend (going up) is too steep 156 | return; 157 | tank.move(ds); 158 | turret.move(ds); 159 | lifeBg.move(ds); 160 | lifeFill.move(ds); 161 | Name.move(ds); 162 | float ang = Application::getGame().getLandNormAng(tank.getPosition().x,tank.getPosition().y); 163 | tank.setRotation(std::fmod(90 - TO_DEG(ang),360) ); 164 | } 165 | } 166 | sf::Vector2f dist = sf::Vector2f(sf::Mouse::getPosition(Application::getWindow())) - tank.getPosition(); 167 | if(Application::getGame().isPlayerTurn() && sq(dist.x)+sq(dist.y) <= sq(50)) 168 | { 169 | fadingLife = true; 170 | fadingTimer = 1; 171 | lifeBg.setFillColor(lifeBg.getFillColor()+sf::Color(0,0,0,255)); 172 | lifeBg.setOutlineColor(lifeBg.getOutlineColor()+sf::Color(0,0,0,255)); 173 | lifeFill.setFillColor(lifeFill.getFillColor()+sf::Color(0,0,0,255)); 174 | Name.setColor(Name.getColor()+sf::Color(0,0,0,255)); 175 | } 176 | else if(fadingLife && (fadingTimer-=dt) < 0) 177 | { 178 | if(lifeBg.getFillColor().a != 0) 179 | { 180 | const float rate = 255.0/1;//fade out in 1 second 181 | int dAlpha = rate*dt; 182 | lifeFill.setFillColor(lifeFill.getFillColor()-sf::Color(0,0,0,dAlpha)); 183 | lifeBg.setFillColor(lifeBg.getFillColor()-sf::Color(0,0,0,dAlpha)); 184 | lifeBg.setOutlineColor(lifeBg.getOutlineColor()-sf::Color(0,0,0,dAlpha)); 185 | Name.setColor(Name.getColor()-sf::Color(0,0,0,dAlpha)); 186 | } 187 | else 188 | fadingLife = false; 189 | } 190 | } 191 | void Tank::reset() 192 | { 193 | moving = 0; 194 | turret.setRotation(-45); 195 | if(!freefall) 196 | { 197 | freefall = true; 198 | Application::getGame().incCounter(); 199 | } 200 | } 201 | void Tank::setPosition(const sf::Vector2f& pos) 202 | { 203 | tank.setPosition(pos); 204 | turret.setPosition(pos-sf::Vector2f(0,TANK_HEIGHT/2)); 205 | lifeBg.setPosition(pos.x-lifeBg.getGlobalBounds().width/2,pos.y-std::max(TANK_HEIGHT,TANK_WIDTH)-turret.getLocalBounds().width); 206 | lifeFill.setPosition(lifeBg.getPosition()); 207 | Name.setPosition(pos.x-Name.getLocalBounds().width/2,lifeBg.getPosition().y-lifeBg.getLocalBounds().height-Name.getLocalBounds().height); 208 | } 209 | -------------------------------------------------------------------------------- /Tank.h: -------------------------------------------------------------------------------- 1 | #ifndef Tank_H 2 | #define Tank_H 3 | 4 | #include "WorldObject.h" 5 | class Player; 6 | class Tank : public WorldObject 7 | { 8 | public: 9 | Tank(); 10 | ~Tank(); 11 | void draw(sf::RenderTarget &target); 12 | void step(float dt); 13 | void handleCollision(WorldObject &b); 14 | void reset(); 15 | void receiveMessage(const Message& msg); 16 | 17 | void setMovement(int val); 18 | void weapAct(float ); //called when hit by some weapon 19 | void setPosition(const sf::Vector2f& pos); 20 | void setPosition(int x,int y) { setPosition(sf::Vector2f(x,y)); } 21 | friend class Player; 22 | void setPlayer(Player *p); 23 | Player &getPlayer() { return *myOwner; } 24 | 25 | sf::Sprite& getTankSpr(){ return tank; } 26 | sf::Sprite& getTurretSpr(){ return turret; } 27 | sf::RectangleShape getTankRect(); 28 | 29 | private: 30 | void setLifeFill(int l); 31 | 32 | Player *myOwner; 33 | int moving;//on land 34 | sf::Sprite tank; 35 | sf::Sprite turret; 36 | sf::RectangleShape lifeBg; 37 | sf::RectangleShape lifeFill; 38 | bool freefall; 39 | sf::Vector2f velocity; 40 | sf::Text Name; 41 | 42 | bool fadingLife; 43 | float fadingTimer;//fading starts after this runs out 44 | }; 45 | 46 | #endif // Tank_H 47 | -------------------------------------------------------------------------------- /TitleScreen.cpp: -------------------------------------------------------------------------------- 1 | #include "TitleScreen.h" 2 | #include "Application.h" 3 | 4 | TitleScreen::TitleScreen() : 5 | AppState(TitleScreenState), 6 | bg(Application::getTexture(TitleBg)), 7 | mainMenu(Application::getFont(FreeSans),40) 8 | { 9 | mainMenu.add("Play",sf::Color::White); 10 | mainMenu.add("Exit",sf::Color::White); 11 | mainMenu.setSelectionBgColor(sf::Color(0,0,0,100)); 12 | mainMenu.create(constants::windowWidth,0); 13 | mainMenu.setPosition(0,300); 14 | } 15 | 16 | TitleScreen::~TitleScreen() 17 | { 18 | //dtor 19 | } 20 | void TitleScreen::reset() 21 | {} 22 | void TitleScreen::draw(sf::RenderWindow &window) 23 | { 24 | window.draw(bg); 25 | mainMenu.draw(window); 26 | } 27 | void TitleScreen::update(float dt) 28 | { 29 | mainMenu.step(dt); 30 | int query = mainMenu.querySelecion(); 31 | if(query >= 0) 32 | { 33 | switch(query) 34 | { 35 | case 0://Play 36 | Application::changeState(GameSetupState); 37 | break; 38 | case 1://Exit 39 | Application::quit(); 40 | break; 41 | default: 42 | PRINT_VAR(query) 43 | break; 44 | } 45 | } 46 | } 47 | void TitleScreen::passEvent(sf::Event event) 48 | { 49 | mainMenu.passEvent(event); 50 | } 51 | -------------------------------------------------------------------------------- /TitleScreen.h: -------------------------------------------------------------------------------- 1 | #ifndef TITLESCREEN_H 2 | #define TITLESCREEN_H 3 | 4 | #include "AppState.h" 5 | #include "Menu.h" 6 | 7 | class TitleScreen : public AppState 8 | { 9 | public: 10 | TitleScreen(); 11 | ~TitleScreen(); 12 | void reset(); 13 | void draw(sf::RenderWindow &window); 14 | void update(float dt); 15 | void passEvent(sf::Event event); 16 | private: 17 | sf::Sprite bg; 18 | Menu mainMenu; 19 | }; 20 | 21 | #endif // TITLESCREEN_H 22 | -------------------------------------------------------------------------------- /WeaponPostEffects.cpp: -------------------------------------------------------------------------------- 1 | #include "WeaponPostEffects.h" 2 | #include "Tank.h" 3 | #include "utilities.h" 4 | #include "Application.h" 5 | 6 | Explosion::Explosion(AnimationType animType,sf::Vector2f pos,int r) : 7 | WorldObject(WeaponPostEffectType), 8 | expCircle(r), 9 | expAnim(AnimationCreator::create(animType,pos)) 10 | { 11 | expCircle.setOrigin(r,r); 12 | expCircle.setPosition(pos); 13 | Application::getGame().incCounter(); 14 | } 15 | Explosion::~Explosion() 16 | { 17 | Application::getGame().decCounter(); 18 | } 19 | void Explosion::handleCollision(WorldObject &b) 20 | { 21 | switch(b.type) 22 | { 23 | case WorldObject::TankType: 24 | { 25 | Tank &t = static_cast(b); 26 | bool &tankActed = tanksActedOn[&t]; 27 | if(tankActed == false && intersects(expCircle,t.getTankRect())) 28 | { 29 | sf::Vector2f vec = expCircle.getPosition() - t.getTankRect().getPosition(); 30 | float blowPower = 50*(1-std::hypot(vec.x,vec.y)/(expCircle.getRadius()+t.getTankRect().getLocalBounds().width/2)); 31 | t.weapAct(blowPower); 32 | tankActed = true; 33 | } 34 | } 35 | break; 36 | default: 37 | break; 38 | } 39 | } 40 | void Explosion::draw(sf::RenderTarget &target) 41 | { 42 | if(expAnim->selfDestruct == true) 43 | { 44 | selfDestruct = true; 45 | } 46 | expAnim->draw(target); 47 | } 48 | void Explosion::step(float dt) 49 | { 50 | expAnim->step(dt); 51 | } 52 | void Explosion::reset() 53 | { 54 | selfDestruct = true; 55 | } 56 | -------------------------------------------------------------------------------- /WeaponPostEffects.h: -------------------------------------------------------------------------------- 1 | #ifndef WEAPONPOSTEFFECTS_H 2 | #define WEAPONPOSTEFFECTS_H 3 | #include "WorldObject.h" 4 | #include "Animation.h" 5 | //Effects seen after a weapon explodes ... 6 | class Tank; 7 | class Explosion : public WorldObject 8 | { 9 | public: 10 | Explosion(AnimationType animType,sf::Vector2f pos,int r = 25); 11 | ~Explosion(); 12 | inline void setRadius(int r){ expCircle.setRadius(r); } 13 | inline int getRadius(){ return expCircle.getRadius(); } 14 | void handleCollision(WorldObject &b); 15 | void draw(sf::RenderTarget &target); 16 | void step(float dt); 17 | void reset(); 18 | private: 19 | std::map tanksActedOn; 20 | sf::CircleShape expCircle; 21 | std::unique_ptr expAnim; 22 | }; 23 | 24 | #endif // WEAPONPOSTEFFECTS_H 25 | -------------------------------------------------------------------------------- /World.cpp: -------------------------------------------------------------------------------- 1 | #include "World.h" 2 | #include "Tank.h" 3 | #include "Land.h" 4 | #include 5 | 6 | World::World() : timer(0) { } 7 | //WorldObject* World::addObj(WorldObjectptr obj) 8 | //{ 9 | // objects.push_back(std::move(obj)); 10 | // return objects.back().get(); 11 | //} 12 | WorldObject* World::addObj(WorldObject* optr) 13 | { 14 | objects.push_back(WorldObjectptr(optr)); 15 | return optr; 16 | } 17 | WorldObject* World::addObj(WorldObject::Type t) 18 | { 19 | WorldObjectptr obj; 20 | bool playNice = true; 21 | switch(t) 22 | { 23 | case WorldObject::TankType: 24 | obj.reset(new Tank()); 25 | break; 26 | case WorldObject::LandType: 27 | obj.reset(new Land()); 28 | break; 29 | default: 30 | playNice = false; 31 | } 32 | if(playNice) 33 | { 34 | objects.push_back(std::move(obj)); 35 | return objects.back().get(); 36 | } 37 | return nullptr; 38 | } 39 | void World::removeObj(std::list::iterator o) 40 | { 41 | objects.erase(o); 42 | } 43 | void World::drawAll(sf::RenderWindow &win) 44 | { 45 | for(auto &objit : objects) 46 | objit->draw(win); 47 | } 48 | void World::crudeStepAll(float dt) 49 | { 50 | for(auto objit = objects.begin();objit != objects.end();) 51 | { 52 | if(!((*objit)->selfDestruct)) 53 | { 54 | for(auto j = std::next(objit) ; j != objects.end() ; ++j) 55 | (*objit)->handleCollision(*(*j).get()); 56 | /* ^ 57 | dereference the iterator , get the raw pointer and dereference it*/ 58 | (*objit)->step(dt); 59 | ++objit; 60 | } 61 | else 62 | objit = objects.erase(objit); 63 | } 64 | } 65 | void World::stepAll(float dt) 66 | { 67 | // crudeStepAll(dt); 68 | timer += dt; 69 | while(timer > updateRate) 70 | { 71 | timer -= updateRate; 72 | crudeStepAll(updateRate); 73 | } 74 | } 75 | void World::play() 76 | { 77 | for(auto &objit : objects) 78 | objit->reset(); 79 | timer = 0; 80 | } 81 | void World::traceAll() 82 | { 83 | int i = 1; 84 | for(auto obj = objects.begin() ; obj != objects.end() ; ++obj,++i) 85 | { 86 | std::cout << "Object " << i << std::endl; 87 | std::cout << "\tobject.type = " << (*obj)->type << std::endl; 88 | std::cout << "\tobject.selfDestruct = " << (*obj)->selfDestruct << std::endl; 89 | std::cout << "\tAddress of object = " << (*obj).get() << std::endl; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /World.h: -------------------------------------------------------------------------------- 1 | #ifndef WORLD_H 2 | #define WORLD_H 3 | #include 4 | #include "WorldObject.h" 5 | 6 | class World 7 | { 8 | public: 9 | World(); 10 | ~World() = default; 11 | // WorldObject* addObj(WorldObjectptr); 12 | WorldObject* addObj(WorldObject*); 13 | WorldObject* addObj(WorldObject::Type t); 14 | void removeObj(std::list::iterator); 15 | void play(); 16 | void drawAll(sf::RenderWindow &win); 17 | void stepAll(float dt); 18 | void crudeStepAll(float dt); 19 | void traceAll(); 20 | void clear(){ objects.clear(); } 21 | std::list objects; 22 | private: 23 | float timer; 24 | const double updateRate{1.f/100.f}; //seconds per update 25 | }; 26 | 27 | #endif // WORLD_H 28 | -------------------------------------------------------------------------------- /WorldObject.h: -------------------------------------------------------------------------------- 1 | #ifndef WORLDOBJECT_H 2 | #define WORLDOBJECT_H 3 | #include 4 | #include 5 | #include "MsgComponents.h" 6 | 7 | class WorldObject; 8 | typedef std::unique_ptr WorldObjectptr; 9 | 10 | class WorldObject : public Receiver 11 | { 12 | public: 13 | enum Type 14 | { 15 | PassiveType , 16 | LandType, 17 | TankType, 18 | WeaponType, 19 | WeaponPostEffectType, 20 | TotalTypes 21 | } type; 22 | WorldObject() = default; 23 | WorldObject(Type m_type) : type(m_type) , selfDestruct(false) {} 24 | virtual ~WorldObject(){}; 25 | virtual void handleCollision(WorldObject &b) = 0; 26 | virtual void draw(sf::RenderTarget &target) = 0; 27 | virtual void step(float dt) = 0; 28 | virtual void reset() = 0; 29 | bool selfDestruct; //if true, World deletes the object 30 | }; 31 | 32 | #endif // WORLDOBJECT_H 33 | -------------------------------------------------------------------------------- /cmake/Modules/FindSFML.cmake: -------------------------------------------------------------------------------- 1 | # This script locates the SFML library 2 | # ------------------------------------ 3 | # 4 | # Usage 5 | # ----- 6 | # 7 | # When you try to locate the SFML libraries, you must specify which modules you want to use (system, window, graphics, network, audio, main). 8 | # If none is given, the SFML_LIBRARIES variable will be empty and you'll end up linking to nothing. 9 | # example: 10 | # find_package(SFML COMPONENTS graphics window system) // find the graphics, window and system modules 11 | # 12 | # You can enforce a specific version, either MAJOR.MINOR or only MAJOR. 13 | # If nothing is specified, the version won't be checked (ie. any version will be accepted). 14 | # example: 15 | # find_package(SFML COMPONENTS ...) // no specific version required 16 | # find_package(SFML 2 COMPONENTS ...) // any 2.x version 17 | # find_package(SFML 2.4 COMPONENTS ...) // version 2.4 or greater 18 | # 19 | # By default, the dynamic libraries of SFML will be found. To find the static ones instead, 20 | # you must set the SFML_STATIC_LIBRARIES variable to TRUE before calling find_package(SFML ...). 21 | # Since you have to link yourself all the SFML dependencies when you link it statically, the following 22 | # additional variables are defined: SFML_XXX_DEPENDENCIES and SFML_DEPENDENCIES (see their detailed 23 | # description below). 24 | # In case of static linking, the SFML_STATIC macro will also be defined by this script. 25 | # example: 26 | # set(SFML_STATIC_LIBRARIES TRUE) 27 | # find_package(SFML 2 COMPONENTS network system) 28 | # 29 | # On Mac OS X if SFML_STATIC_LIBRARIES is not set to TRUE then by default CMake will search for frameworks unless 30 | # CMAKE_FIND_FRAMEWORK is set to "NEVER" for example. Please refer to CMake documentation for more details. 31 | # Moreover, keep in mind that SFML frameworks are only available as release libraries unlike dylibs which 32 | # are available for both release and debug modes. 33 | # 34 | # If SFML is not installed in a standard path, you can use the SFML_ROOT CMake (or environment) variable 35 | # to tell CMake where SFML is. 36 | # 37 | # Output 38 | # ------ 39 | # 40 | # This script defines the following variables: 41 | # - For each specified module XXX (system, window, graphics, network, audio, main): 42 | # - SFML_XXX_LIBRARY_DEBUG: the name of the debug library of the xxx module (set to SFML_XXX_LIBRARY_RELEASE is no debug version is found) 43 | # - SFML_XXX_LIBRARY_RELEASE: the name of the release library of the xxx module (set to SFML_XXX_LIBRARY_DEBUG is no release version is found) 44 | # - SFML_XXX_LIBRARY: the name of the library to link to for the xxx module (includes both debug and optimized names if necessary) 45 | # - SFML_XXX_FOUND: true if either the debug or release library of the xxx module is found 46 | # - SFML_XXX_DEPENDENCIES: the list of libraries the module depends on, in case of static linking 47 | # - SFML_LIBRARIES: the list of all libraries corresponding to the required modules 48 | # - SFML_FOUND: true if all the required modules are found 49 | # - SFML_INCLUDE_DIR: the path where SFML headers are located (the directory containing the SFML/Config.hpp file) 50 | # - SFML_DEPENDENCIES: the list of libraries SFML depends on, in case of static linking 51 | # 52 | # example: 53 | # find_package(SFML 2 COMPONENTS system window graphics audio REQUIRED) 54 | # include_directories(${SFML_INCLUDE_DIR}) 55 | # add_executable(myapp ...) 56 | # target_link_libraries(myapp ${SFML_LIBRARIES}) 57 | 58 | # define the SFML_STATIC macro if static build was chosen 59 | if(SFML_STATIC_LIBRARIES) 60 | add_definitions(-DSFML_STATIC) 61 | endif() 62 | 63 | # deduce the libraries suffix from the options 64 | set(FIND_SFML_LIB_SUFFIX "") 65 | if(SFML_STATIC_LIBRARIES) 66 | set(FIND_SFML_LIB_SUFFIX "${FIND_SFML_LIB_SUFFIX}-s") 67 | endif() 68 | 69 | # define the list of search paths for headers and libraries 70 | set(FIND_SFML_PATHS 71 | ${SFML_ROOT} 72 | $ENV{SFML_ROOT} 73 | ~/Library/Frameworks 74 | /Library/Frameworks 75 | /usr/local 76 | /usr 77 | /sw 78 | /opt/local 79 | /opt/csw 80 | /opt) 81 | 82 | # find the SFML include directory 83 | find_path(SFML_INCLUDE_DIR SFML/Config.hpp 84 | PATH_SUFFIXES include 85 | PATHS ${FIND_SFML_PATHS}) 86 | 87 | # check the version number 88 | set(SFML_VERSION_OK TRUE) 89 | if(SFML_FIND_VERSION AND SFML_INCLUDE_DIR) 90 | # extract the major and minor version numbers from SFML/Config.hpp 91 | # we have to handle framework a little bit differently : 92 | if("${SFML_INCLUDE_DIR}" MATCHES "SFML.framework") 93 | set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/Headers/Config.hpp") 94 | else() 95 | set(SFML_CONFIG_HPP_INPUT "${SFML_INCLUDE_DIR}/SFML/Config.hpp") 96 | endif() 97 | FILE(READ "${SFML_CONFIG_HPP_INPUT}" SFML_CONFIG_HPP_CONTENTS) 98 | STRING(REGEX MATCH ".*#define SFML_VERSION_MAJOR ([0-9]+).*#define SFML_VERSION_MINOR ([0-9]+).*" SFML_CONFIG_HPP_CONTENTS "${SFML_CONFIG_HPP_CONTENTS}") 99 | STRING(REGEX REPLACE ".*#define SFML_VERSION_MAJOR ([0-9]+).*" "\\1" SFML_VERSION_MAJOR "${SFML_CONFIG_HPP_CONTENTS}") 100 | STRING(REGEX REPLACE ".*#define SFML_VERSION_MINOR ([0-9]+).*" "\\1" SFML_VERSION_MINOR "${SFML_CONFIG_HPP_CONTENTS}") 101 | math(EXPR SFML_REQUESTED_VERSION "${SFML_FIND_VERSION_MAJOR} * 10 + ${SFML_FIND_VERSION_MINOR}") 102 | 103 | # if we could extract them, compare with the requested version number 104 | if (SFML_VERSION_MAJOR) 105 | # transform version numbers to an integer 106 | math(EXPR SFML_VERSION "${SFML_VERSION_MAJOR} * 10 + ${SFML_VERSION_MINOR}") 107 | 108 | # compare them 109 | if(SFML_VERSION LESS SFML_REQUESTED_VERSION) 110 | set(SFML_VERSION_OK FALSE) 111 | endif() 112 | else() 113 | # SFML version is < 2.0 114 | if (SFML_REQUESTED_VERSION GREATER 19) 115 | set(SFML_VERSION_OK FALSE) 116 | set(SFML_VERSION_MAJOR 1) 117 | set(SFML_VERSION_MINOR x) 118 | endif() 119 | endif() 120 | endif() 121 | 122 | # find the requested modules 123 | set(SFML_FOUND TRUE) # will be set to false if one of the required modules is not found 124 | foreach(FIND_SFML_COMPONENT ${SFML_FIND_COMPONENTS}) 125 | string(TOLOWER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_LOWER) 126 | string(TOUPPER ${FIND_SFML_COMPONENT} FIND_SFML_COMPONENT_UPPER) 127 | set(FIND_SFML_COMPONENT_NAME sfml-${FIND_SFML_COMPONENT_LOWER}${FIND_SFML_LIB_SUFFIX}) 128 | 129 | # no suffix for sfml-main, it is always a static library 130 | if(FIND_SFML_COMPONENT_LOWER STREQUAL "main") 131 | set(FIND_SFML_COMPONENT_NAME sfml-${FIND_SFML_COMPONENT_LOWER}) 132 | endif() 133 | 134 | # debug library 135 | find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG 136 | NAMES ${FIND_SFML_COMPONENT_NAME}-d 137 | PATH_SUFFIXES lib64 lib 138 | PATHS ${FIND_SFML_PATHS}) 139 | 140 | # release library 141 | find_library(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE 142 | NAMES ${FIND_SFML_COMPONENT_NAME} 143 | PATH_SUFFIXES lib64 lib 144 | PATHS ${FIND_SFML_PATHS}) 145 | 146 | if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG OR SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE) 147 | # library found 148 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND TRUE) 149 | 150 | # if both are found, set SFML_XXX_LIBRARY to contain both 151 | if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE) 152 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY debug ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG} 153 | optimized ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE}) 154 | endif() 155 | 156 | # if only one debug/release variant is found, set the other to be equal to the found one 157 | if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE) 158 | # debug and not release 159 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG}) 160 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG}) 161 | endif() 162 | if (SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE AND NOT SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG) 163 | # release and not debug 164 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE}) 165 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY ${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE}) 166 | endif() 167 | else() 168 | # library not found 169 | set(SFML_FOUND FALSE) 170 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_FOUND FALSE) 171 | set(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY "") 172 | set(FIND_SFML_MISSING "${FIND_SFML_MISSING} SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY") 173 | endif() 174 | 175 | # mark as advanced 176 | MARK_AS_ADVANCED(SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY 177 | SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_RELEASE 178 | SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY_DEBUG) 179 | 180 | # add to the global list of libraries 181 | set(SFML_LIBRARIES ${SFML_LIBRARIES} "${SFML_${FIND_SFML_COMPONENT_UPPER}_LIBRARY}") 182 | endforeach() 183 | 184 | # in case of static linking, we must also define the list of all the dependencies of SFML libraries 185 | if(SFML_STATIC_LIBRARIES) 186 | 187 | # detect the OS 188 | if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") 189 | set(FIND_SFML_OS_WINDOWS 1) 190 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux") 191 | set(FIND_SFML_OS_LINUX 1) 192 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD") 193 | set(FIND_SFML_OS_FREEBSD 1) 194 | elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") 195 | set(FIND_SFML_OS_MACOSX 1) 196 | endif() 197 | 198 | # start with an empty list 199 | set(SFML_DEPENDENCIES) 200 | set(FIND_SFML_DEPENDENCIES_NOTFOUND) 201 | 202 | # macro that searches for a 3rd-party library 203 | macro(find_sfml_dependency output friendlyname) 204 | find_library(${output} NAMES ${ARGN} PATHS ${FIND_SFML_PATHS} PATH_SUFFIXES lib) 205 | if(${${output}} STREQUAL "${output}-NOTFOUND") 206 | unset(output) 207 | set(FIND_SFML_DEPENDENCIES_NOTFOUND "${FIND_SFML_DEPENDENCIES_NOTFOUND} ${friendlyname}") 208 | endif() 209 | endmacro() 210 | 211 | # sfml-system 212 | list(FIND SFML_FIND_COMPONENTS "system" FIND_SFML_SYSTEM_COMPONENT) 213 | if(NOT ${FIND_SFML_SYSTEM_COMPONENT} EQUAL -1) 214 | 215 | # update the list -- these are only system libraries, no need to find them 216 | if(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD OR FIND_SFML_OS_MACOSX) 217 | set(SFML_SYSTEM_DEPENDENCIES "pthread") 218 | endif() 219 | if(FIND_SFML_OS_LINUX) 220 | set(SFML_SYSTEM_DEPENDENCIES "rt") 221 | endif() 222 | if(FIND_SFML_OS_WINDOWS) 223 | set(SFML_SYSTEM_DEPENDENCIES "winmm") 224 | endif() 225 | set(SFML_DEPENDENCIES ${SFML_DEPENDENCIES} ${SFML_SYSTEM_DEPENDENCIES}) 226 | endif() 227 | 228 | # sfml-network 229 | list(FIND SFML_FIND_COMPONENTS "network" FIND_SFML_NETWORK_COMPONENT) 230 | if(NOT ${FIND_SFML_NETWORK_COMPONENT} EQUAL -1) 231 | 232 | # update the list -- these are only system libraries, no need to find them 233 | if(FIND_SFML_OS_WINDOWS) 234 | set(SFML_NETWORK_DEPENDENCIES "ws2_32") 235 | endif() 236 | set(SFML_DEPENDENCIES ${SFML_DEPENDENCIES} ${SFML_NETWORK_DEPENDENCIES}) 237 | endif() 238 | 239 | # sfml-window 240 | list(FIND SFML_FIND_COMPONENTS "window" FIND_SFML_WINDOW_COMPONENT) 241 | if(NOT ${FIND_SFML_WINDOW_COMPONENT} EQUAL -1) 242 | 243 | # find libraries 244 | if(FIND_SFML_OS_LINUX) 245 | find_sfml_dependency(X11_LIBRARY "X11" X11) 246 | find_sfml_dependency(XRANDR_LIBRARY "Xrandr" Xrandr) 247 | endif() 248 | 249 | # update the list 250 | if(FIND_SFML_OS_WINDOWS) 251 | set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "opengl32" "winmm" "gdi32") 252 | elseif(FIND_SFML_OS_LINUX OR FIND_SFML_OS_FREEBSD) 253 | set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "GL" ${X11_LIBRARY} ${XRANDR_LIBRARY}) 254 | if(FIND_SFML_OS_FREEBSD) 255 | set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "usbhid") 256 | endif() 257 | elseif(FIND_SFML_OS_MACOSX) 258 | set(SFML_WINDOW_DEPENDENCIES ${SFML_WINDOW_DEPENDENCIES} "-framework OpenGL -framework Foundation -framework AppKit -framework IOKit -framework Carbon") 259 | endif() 260 | set(SFML_DEPENDENCIES ${SFML_DEPENDENCIES} ${SFML_WINDOW_DEPENDENCIES}) 261 | endif() 262 | 263 | # sfml-graphics 264 | list(FIND SFML_FIND_COMPONENTS "graphics" FIND_SFML_GRAPHICS_COMPONENT) 265 | if(NOT ${FIND_SFML_GRAPHICS_COMPONENT} EQUAL -1) 266 | 267 | # find libraries 268 | find_sfml_dependency(FREETYPE_LIBRARY "FreeType" freetype) 269 | find_sfml_dependency(GLEW_LIBRARY "GLEW" glew GLEW glew32 glew32s glew64 glew64s) 270 | find_sfml_dependency(JPEG_LIBRARY "libjpeg" jpeg) 271 | 272 | # update the list 273 | set(SFML_GRAPHICS_DEPENDENCIES ${FREETYPE_LIBRARY} ${GLEW_LIBRARY} ${JPEG_LIBRARY}) 274 | set(SFML_DEPENDENCIES ${SFML_DEPENDENCIES} ${SFML_GRAPHICS_DEPENDENCIES}) 275 | endif() 276 | 277 | # sfml-audio 278 | list(FIND SFML_FIND_COMPONENTS "audio" FIND_SFML_AUDIO_COMPONENT) 279 | if(NOT ${FIND_SFML_AUDIO_COMPONENT} EQUAL -1) 280 | 281 | # find libraries 282 | find_sfml_dependency(OPENAL_LIBRARY "OpenAL" openal openal32) 283 | find_sfml_dependency(SNDFILE_LIBRARY "libsndfile" sndfile) 284 | 285 | # update the list 286 | set(SFML_AUDIO_DEPENDENCIES ${OPENAL_LIBRARY} ${SNDFILE_LIBRARY}) 287 | set(SFML_DEPENDENCIES ${SFML_DEPENDENCIES} ${SFML_AUDIO_DEPENDENCIES}) 288 | endif() 289 | 290 | endif() 291 | 292 | # handle errors 293 | if(NOT SFML_VERSION_OK) 294 | # SFML version not ok 295 | set(FIND_SFML_ERROR "SFML found but version too low (requested: ${SFML_FIND_VERSION}, found: ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR})") 296 | set(SFML_FOUND FALSE) 297 | elseif(SFML_STATIC_LIBRARIES AND FIND_SFML_DEPENDENCIES_NOTFOUND) 298 | set(FIND_SFML_ERROR "SFML found but some of its dependencies are missing (${FIND_SFML_DEPENDENCIES_NOTFOUND})") 299 | set(SFML_FOUND FALSE) 300 | elseif(NOT SFML_FOUND) 301 | # include directory or library not found 302 | set(FIND_SFML_ERROR "Could NOT find SFML (missing: ${FIND_SFML_MISSING})") 303 | endif() 304 | if (NOT SFML_FOUND) 305 | if(SFML_FIND_REQUIRED) 306 | # fatal error 307 | message(FATAL_ERROR ${FIND_SFML_ERROR}) 308 | elseif(NOT SFML_FIND_QUIETLY) 309 | # error but continue 310 | message("${FIND_SFML_ERROR}") 311 | endif() 312 | endif() 313 | 314 | # handle success 315 | if(SFML_FOUND) 316 | message(STATUS "Found SFML ${SFML_VERSION_MAJOR}.${SFML_VERSION_MINOR} in ${SFML_INCLUDE_DIR}") 317 | endif() 318 | -------------------------------------------------------------------------------- /constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_INCLUDED 2 | #define CONSTANTS_INCLUDED 3 | 4 | namespace constants 5 | { 6 | const int windowWidth = 800; 7 | const int windowHeight = 600; 8 | const int gravity = 180; 9 | } 10 | 11 | #endif // CONSTANTS_INCLUDED 12 | -------------------------------------------------------------------------------- /data/ExplosionAsmall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/ExplosionAsmall.png -------------------------------------------------------------------------------- /data/FreeSans.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/FreeSans.ttf -------------------------------------------------------------------------------- /data/Ubuntu-C.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/Ubuntu-C.ttf -------------------------------------------------------------------------------- /data/arrowdown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/arrowdown.png -------------------------------------------------------------------------------- /data/tank.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/tank.png -------------------------------------------------------------------------------- /data/target.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/target.png -------------------------------------------------------------------------------- /data/title.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/title.png -------------------------------------------------------------------------------- /data/turret.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amhndu/tanks-game/61b7edcfb7e83316977c3a2bf31cb632cfc3dd8d/data/turret.png -------------------------------------------------------------------------------- /simplexnoise.cpp: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2007-2012 Eliot Eshelman 2 | * 3 | * This program is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This program is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this program. If not, see . 15 | * 16 | */ 17 | 18 | 19 | #include 20 | 21 | #include "simplexnoise.h" 22 | 23 | 24 | /* 2D, 3D and 4D Simplex Noise functions return 'Random' values in (-1, 1). 25 | 26 | This algorithm was originally designed by Ken Perlin, but my code has been 27 | adapted from the implementation written by Stefan Gustavson (stegu@itn.liu.se) 28 | 29 | Raw Simplex noise functions return the value generated by Ken's algorithm. 30 | 31 | Scaled Raw Simplex noise functions adjust the range of values returned from the 32 | traditional (-1, 1) to whichever bounds are passed to the function. 33 | 34 | Multi-Octave Simplex noise functions compine multiple noise values to create a 35 | more complex result. Each successive layer of noise is adjusted and scaled. 36 | 37 | Scaled Multi-Octave Simplex noise functions scale the values returned from the 38 | traditional (-1,1) range to whichever range is passed to the function. 39 | 40 | In many cases, you may think you only need a 1D noise function, but in practice 41 | 2D is almost always better. For instance, if you're using the current frame 42 | number as the parameter for the noise, all objects will end up with the same 43 | noise value at each frame. By adding a second parameter on the second 44 | dimension, you can ensure that each gets a unique noise value and they don't 45 | all look identical. 46 | */ 47 | 48 | 49 | // 2D Multi-octave Simplex noise. 50 | // 51 | // For each octave, a higher frequency/lower amplitude function will be added to the original. 52 | // The higher the persistence [0-1], the more of each succeeding octave will be added. 53 | float octave_noise_2d( const float octaves, const float persistence, const float scale, const float x, const float y ) 54 | { 55 | float total = 0; 56 | float frequency = scale; 57 | float amplitude = 1; 58 | // We have to keep track of the largest possible amplitude, 59 | // because each octave adds more, and we need a value in [-1, 1]. 60 | float maxAmplitude = 0; 61 | for( int i = 0; i < octaves; i++ ) 62 | { 63 | total += raw_noise_2d( x * frequency, y * frequency ) * amplitude; 64 | frequency *= 2; 65 | maxAmplitude += amplitude; 66 | amplitude *= persistence; 67 | } 68 | return total / maxAmplitude; 69 | } 70 | 71 | 72 | // 3D Multi-octave Simplex noise. 73 | // 74 | // For each octave, a higher frequency/lower amplitude function will be added to the original. 75 | // The higher the persistence [0-1], the more of each succeeding octave will be added. 76 | float octave_noise_3d( const float octaves, const float persistence, const float scale, const float x, const float y, const float z ) 77 | { 78 | float total = 0; 79 | float frequency = scale; 80 | float amplitude = 1; 81 | // We have to keep track of the largest possible amplitude, 82 | // because each octave adds more, and we need a value in [-1, 1]. 83 | float maxAmplitude = 0; 84 | for( int i = 0; i < octaves; i++ ) 85 | { 86 | total += raw_noise_3d( x * frequency, y * frequency, z * frequency ) * amplitude; 87 | frequency *= 2; 88 | maxAmplitude += amplitude; 89 | amplitude *= persistence; 90 | } 91 | return total / maxAmplitude; 92 | } 93 | 94 | 95 | // 4D Multi-octave Simplex noise. 96 | // 97 | // For each octave, a higher frequency/lower amplitude function will be added to the original. 98 | // The higher the persistence [0-1], the more of each succeeding octave will be added. 99 | float octave_noise_4d( const float octaves, const float persistence, const float scale, const float x, const float y, const float z, const float w ) 100 | { 101 | float total = 0; 102 | float frequency = scale; 103 | float amplitude = 1; 104 | // We have to keep track of the largest possible amplitude, 105 | // because each octave adds more, and we need a value in [-1, 1]. 106 | float maxAmplitude = 0; 107 | for( int i = 0; i < octaves; i++ ) 108 | { 109 | total += raw_noise_4d( x * frequency, y * frequency, z * frequency, w * frequency ) * amplitude; 110 | frequency *= 2; 111 | maxAmplitude += amplitude; 112 | amplitude *= persistence; 113 | } 114 | return total / maxAmplitude; 115 | } 116 | 117 | 118 | 119 | // 2D Scaled Multi-octave Simplex noise. 120 | // 121 | // Returned value will be between loBound and hiBound. 122 | float scaled_octave_noise_2d( const float octaves, const float persistence, const float scale, const float loBound, const float hiBound, const float x, const float y ) 123 | { 124 | return octave_noise_2d(octaves, persistence, scale, x, y) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2; 125 | } 126 | 127 | 128 | // 3D Scaled Multi-octave Simplex noise. 129 | // 130 | // Returned value will be between loBound and hiBound. 131 | float scaled_octave_noise_3d( const float octaves, const float persistence, const float scale, const float loBound, const float hiBound, const float x, const float y, const float z ) 132 | { 133 | return octave_noise_3d(octaves, persistence, scale, x, y, z) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2; 134 | } 135 | 136 | // 4D Scaled Multi-octave Simplex noise. 137 | // 138 | // Returned value will be between loBound and hiBound. 139 | float scaled_octave_noise_4d( const float octaves, const float persistence, const float scale, const float loBound, const float hiBound, const float x, const float y, const float z, const float w ) 140 | { 141 | return octave_noise_4d(octaves, persistence, scale, x, y, z, w) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2; 142 | } 143 | 144 | 145 | 146 | // 2D Scaled Simplex raw noise. 147 | // 148 | // Returned value will be between loBound and hiBound. 149 | float scaled_raw_noise_2d( const float loBound, const float hiBound, const float x, const float y ) 150 | { 151 | return raw_noise_2d(x, y) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2; 152 | } 153 | 154 | 155 | // 3D Scaled Simplex raw noise. 156 | // 157 | // Returned value will be between loBound and hiBound. 158 | float scaled_raw_noise_3d( const float loBound, const float hiBound, const float x, const float y, const float z ) 159 | { 160 | return raw_noise_3d(x, y, z) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2; 161 | } 162 | 163 | // 4D Scaled Simplex raw noise. 164 | // 165 | // Returned value will be between loBound and hiBound. 166 | float scaled_raw_noise_4d( const float loBound, const float hiBound, const float x, const float y, const float z, const float w ) 167 | { 168 | return raw_noise_4d(x, y, z, w) * (hiBound - loBound) / 2 + (hiBound + loBound) / 2; 169 | } 170 | 171 | 172 | 173 | // 2D raw Simplex noise 174 | float raw_noise_2d( const float x, const float y ) 175 | { 176 | // Noise contributions from the three corners 177 | float n0, n1, n2; 178 | // Skew the input space to determine which simplex cell we're in 179 | float F2 = 0.5 * (sqrtf(3.0) - 1.0); 180 | // Hairy factor for 2D 181 | float s = (x + y) * F2; 182 | int i = fastfloor( x + s ); 183 | int j = fastfloor( y + s ); 184 | float G2 = (3.0 - sqrtf(3.0)) / 6.0; 185 | float t = (i + j) * G2; 186 | // Unskew the cell origin back to (x,y) space 187 | float X0 = i - t; 188 | float Y0 = j - t; 189 | // The x,y distances from the cell origin 190 | float x0 = x - X0; 191 | float y0 = y - Y0; 192 | // For the 2D case, the simplex shape is an equilateral triangle. 193 | // Determine which simplex we are in. 194 | int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords 195 | if(x0 > y0) {i1 = 1; j1 = 0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1) 196 | else {i1 = 0; j1 = 1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1) 197 | // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and 198 | // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where 199 | // c = (3-sqrt(3))/6 200 | float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords 201 | float y1 = y0 - j1 + G2; 202 | float x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords 203 | float y2 = y0 - 1.0 + 2.0 * G2; 204 | // Work out the hashed gradient indices of the three simplex corners 205 | int ii = i & 255; 206 | int jj = j & 255; 207 | int gi0 = perm[ii + perm[jj]] % 12; 208 | int gi1 = perm[ii + i1 + perm[jj + j1]] % 12; 209 | int gi2 = perm[ii + 1 + perm[jj + 1]] % 12; 210 | // Calculate the contribution from the three corners 211 | float t0 = 0.5 - x0 * x0 - y0 * y0; 212 | if(t0 < 0) { n0 = 0.0; } 213 | else 214 | { 215 | t0 *= t0; 216 | n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient 217 | } 218 | float t1 = 0.5 - x1 * x1 - y1 * y1; 219 | if(t1 < 0) { n1 = 0.0; } 220 | else 221 | { 222 | t1 *= t1; 223 | n1 = t1 * t1 * dot(grad3[gi1], x1, y1); 224 | } 225 | float t2 = 0.5 - x2 * x2 - y2 * y2; 226 | if(t2 < 0) { n2 = 0.0; } 227 | else 228 | { 229 | t2 *= t2; 230 | n2 = t2 * t2 * dot(grad3[gi2], x2, y2); 231 | } 232 | // Add contributions from each corner to get the final noise value. 233 | // The result is scaled to return values in the interval [-1,1]. 234 | return 70.0 * (n0 + n1 + n2); 235 | } 236 | 237 | 238 | // 3D raw Simplex noise 239 | float raw_noise_3d( const float x, const float y, const float z ) 240 | { 241 | float n0, n1, n2, n3; // Noise contributions from the four corners 242 | // Skew the input space to determine which simplex cell we're in 243 | float F3 = 1.0 / 3.0; 244 | float s = (x + y + z) * F3; // Very nice and simple skew factor for 3D 245 | int i = fastfloor(x + s); 246 | int j = fastfloor(y + s); 247 | int k = fastfloor(z + s); 248 | float G3 = 1.0 / 6.0; // Very nice and simple unskew factor, too 249 | float t = (i + j + k) * G3; 250 | float X0 = i - t; // Unskew the cell origin back to (x,y,z) space 251 | float Y0 = j - t; 252 | float Z0 = k - t; 253 | float x0 = x - X0; // The x,y,z distances from the cell origin 254 | float y0 = y - Y0; 255 | float z0 = z - Z0; 256 | // For the 3D case, the simplex shape is a slightly irregular tetrahedron. 257 | // Determine which simplex we are in. 258 | int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords 259 | int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords 260 | if(x0 >= y0) 261 | { 262 | if(y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } // X Y Z order 263 | else if(x0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } // X Z Y order 264 | else { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } // Z X Y order 265 | } 266 | else // x0 y0) ? 32 : 0; 359 | int c2 = (x0 > z0) ? 16 : 0; 360 | int c3 = (y0 > z0) ? 8 : 0; 361 | int c4 = (x0 > w0) ? 4 : 0; 362 | int c5 = (y0 > w0) ? 2 : 0; 363 | int c6 = (z0 > w0) ? 1 : 0; 364 | int c = c1 + c2 + c3 + c4 + c5 + c6; 365 | int i1, j1, k1, l1; // The integer offsets for the second simplex corner 366 | int i2, j2, k2, l2; // The integer offsets for the third simplex corner 367 | int i3, j3, k3, l3; // The integer offsets for the fourth simplex corner 368 | // simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order. 369 | // Many values of c will never occur, since e.g. x>y>z>w makes x= 3 ? 1 : 0; 374 | j1 = simplex[c][1] >= 3 ? 1 : 0; 375 | k1 = simplex[c][2] >= 3 ? 1 : 0; 376 | l1 = simplex[c][3] >= 3 ? 1 : 0; 377 | // The number 2 in the "simplex" array is at the second largest coordinate. 378 | i2 = simplex[c][0] >= 2 ? 1 : 0; 379 | j2 = simplex[c][1] >= 2 ? 1 : 0; 380 | k2 = simplex[c][2] >= 2 ? 1 : 0; 381 | l2 = simplex[c][3] >= 2 ? 1 : 0; 382 | // The number 1 in the "simplex" array is at the second smallest coordinate. 383 | i3 = simplex[c][0] >= 1 ? 1 : 0; 384 | j3 = simplex[c][1] >= 1 ? 1 : 0; 385 | k3 = simplex[c][2] >= 1 ? 1 : 0; 386 | l3 = simplex[c][3] >= 1 ? 1 : 0; 387 | // The fifth corner has all coordinate offsets = 1, so no need to look that up. 388 | float x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords 389 | float y1 = y0 - j1 + G4; 390 | float z1 = z0 - k1 + G4; 391 | float w1 = w0 - l1 + G4; 392 | float x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords 393 | float y2 = y0 - j2 + 2.0 * G4; 394 | float z2 = z0 - k2 + 2.0 * G4; 395 | float w2 = w0 - l2 + 2.0 * G4; 396 | float x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords 397 | float y3 = y0 - j3 + 3.0 * G4; 398 | float z3 = z0 - k3 + 3.0 * G4; 399 | float w3 = w0 - l3 + 3.0 * G4; 400 | float x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords 401 | float y4 = y0 - 1.0 + 4.0 * G4; 402 | float z4 = z0 - 1.0 + 4.0 * G4; 403 | float w4 = w0 - 1.0 + 4.0 * G4; 404 | // Work out the hashed gradient indices of the five simplex corners 405 | int ii = i & 255; 406 | int jj = j & 255; 407 | int kk = k & 255; 408 | int ll = l & 255; 409 | int gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; 410 | int gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; 411 | int gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32; 412 | int gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32; 413 | int gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; 414 | // Calculate the contribution from the five corners 415 | float t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; 416 | if(t0 < 0) { n0 = 0.0; } 417 | else 418 | { 419 | t0 *= t0; 420 | n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0); 421 | } 422 | float t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; 423 | if(t1 < 0) { n1 = 0.0; } 424 | else 425 | { 426 | t1 *= t1; 427 | n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1); 428 | } 429 | float t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; 430 | if(t2 < 0) { n2 = 0.0; } 431 | else 432 | { 433 | t2 *= t2; 434 | n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2); 435 | } 436 | float t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; 437 | if(t3 < 0) { n3 = 0.0; } 438 | else 439 | { 440 | t3 *= t3; 441 | n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3); 442 | } 443 | float t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; 444 | if(t4 < 0) { n4 = 0.0; } 445 | else 446 | { 447 | t4 *= t4; 448 | n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4); 449 | } 450 | // Sum up and scale the result to cover the range [-1,1] 451 | return 27.0 * (n0 + n1 + n2 + n3 + n4); 452 | } 453 | 454 | 455 | int fastfloor( const float x ) { return x > 0 ? (int) x : (int) x - 1; } 456 | 457 | float dot( const int* g, const float x, const float y ) { return g[0] * x + g[1] * y; } 458 | float dot( const int* g, const float x, const float y, const float z ) { return g[0] * x + g[1] * y + g[2] * z; } 459 | float dot( const int* g, const float x, const float y, const float z, const float w ) { return g[0] * x + g[1] * y + g[2] * z + g[3] * w; } 460 | -------------------------------------------------------------------------------- /simplexnoise.h: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2007-2012 Eliot Eshelman 2 | * 3 | * This program is free software: you can redistribute it and/or modify 4 | * it under the terms of the GNU General Public License as published by 5 | * the Free Software Foundation, either version 3 of the License, or 6 | * (at your option) any later version. 7 | * 8 | * This program is distributed in the hope that it will be useful, 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | * GNU General Public License for more details. 12 | * 13 | * You should have received a copy of the GNU General Public License 14 | * along with this program. If not, see . 15 | * 16 | */ 17 | 18 | 19 | #ifndef SIMPLEX_H_ 20 | #define SIMPLEX_H_ 21 | 22 | 23 | /* 2D, 3D and 4D Simplex Noise functions return 'Random' values in (-1, 1). 24 | 25 | This algorithm was originally designed by Ken Perlin, but my code has been 26 | adapted from the implementation written by Stefan Gustavson (stegu@itn.liu.se) 27 | 28 | Raw Simplex noise functions return the value generated by Ken's algorithm. 29 | 30 | Scaled Raw Simplex noise functions adjust the range of values returned from the 31 | traditional (-1, 1) to whichever bounds are passed to the function. 32 | 33 | Multi-Octave Simplex noise functions combine multiple noise values to create a 34 | more complex result. Each successive layer of noise is adjusted and scaled. 35 | 36 | Scaled Multi-Octave Simplex noise functions scale the values returned from the 37 | traditional (-1,1) range to whichever range is passed to the function. 38 | 39 | In many cases, you may think you only need a 1D noise function, but in practice 40 | 2D is almost always better. For instance, if you're using the current frame 41 | number as the parameter for the noise, all objects will end up with the same 42 | noise value at each frame. By adding a second parameter on the second 43 | dimension, you can ensure that each gets a unique noise value and they don't 44 | all look identical. 45 | */ 46 | 47 | 48 | // Multi-octave Simplex noise 49 | // For each octave, a higher frequency/lower amplitude function will be added to the original. 50 | // The higher the persistence [0-1], the more of each succeeding octave will be added. 51 | float octave_noise_2d(const float octaves, 52 | const float persistence, 53 | const float scale, 54 | const float x, 55 | const float y); 56 | float octave_noise_3d(const float octaves, 57 | const float persistence, 58 | const float scale, 59 | const float x, 60 | const float y, 61 | const float z); 62 | float octave_noise_4d(const float octaves, 63 | const float persistence, 64 | const float scale, 65 | const float x, 66 | const float y, 67 | const float z, 68 | const float w); 69 | 70 | 71 | // Scaled Multi-octave Simplex noise 72 | // The result will be between the two parameters passed. 73 | float scaled_octave_noise_2d( const float octaves, 74 | const float persistence, 75 | const float scale, 76 | const float loBound, 77 | const float hiBound, 78 | const float x, 79 | const float y); 80 | float scaled_octave_noise_3d( const float octaves, 81 | const float persistence, 82 | const float scale, 83 | const float loBound, 84 | const float hiBound, 85 | const float x, 86 | const float y, 87 | const float z); 88 | float scaled_octave_noise_4d( const float octaves, 89 | const float persistence, 90 | const float scale, 91 | const float loBound, 92 | const float hiBound, 93 | const float x, 94 | const float y, 95 | const float z, 96 | const float w); 97 | 98 | // Scaled Raw Simplex noise 99 | // The result will be between the two parameters passed. 100 | float scaled_raw_noise_2d( const float loBound, 101 | const float hiBound, 102 | const float x, 103 | const float y); 104 | float scaled_raw_noise_3d( const float loBound, 105 | const float hiBound, 106 | const float x, 107 | const float y, 108 | const float z); 109 | float scaled_raw_noise_4d( const float loBound, 110 | const float hiBound, 111 | const float x, 112 | const float y, 113 | const float z, 114 | const float w); 115 | 116 | 117 | // Raw Simplex noise - a single noise value. 118 | float raw_noise_2d(const float x, const float y); 119 | float raw_noise_3d(const float x, const float y, const float z); 120 | float raw_noise_4d(const float x, const float y, const float, const float w); 121 | 122 | 123 | int fastfloor(const float x); 124 | 125 | float dot(const int* g, const float x, const float y); 126 | float dot(const int* g, const float x, const float y, const float z); 127 | float dot(const int* g, const float x, const float y, const float z, const float w); 128 | 129 | 130 | // The gradients are the midpoints of the vertices of a cube. 131 | static const int grad3[12][3] = 132 | { 133 | {1, 1, 0}, { -1, 1, 0}, {1, -1, 0}, { -1, -1, 0}, 134 | {1, 0, 1}, { -1, 0, 1}, {1, 0, -1}, { -1, 0, -1}, 135 | {0, 1, 1}, {0, -1, 1}, {0, 1, -1}, {0, -1, -1} 136 | }; 137 | 138 | 139 | // The gradients are the midpoints of the vertices of a hypercube. 140 | static const int grad4[32][4] = 141 | { 142 | {0, 1, 1, 1}, {0, 1, 1, -1}, {0, 1, -1, 1}, {0, 1, -1, -1}, 143 | {0, -1, 1, 1}, {0, -1, 1, -1}, {0, -1, -1, 1}, {0, -1, -1, -1}, 144 | {1, 0, 1, 1}, {1, 0, 1, -1}, {1, 0, -1, 1}, {1, 0, -1, -1}, 145 | { -1, 0, 1, 1}, { -1, 0, 1, -1}, { -1, 0, -1, 1}, { -1, 0, -1, -1}, 146 | {1, 1, 0, 1}, {1, 1, 0, -1}, {1, -1, 0, 1}, {1, -1, 0, -1}, 147 | { -1, 1, 0, 1}, { -1, 1, 0, -1}, { -1, -1, 0, 1}, { -1, -1, 0, -1}, 148 | {1, 1, 1, 0}, {1, 1, -1, 0}, {1, -1, 1, 0}, {1, -1, -1, 0}, 149 | { -1, 1, 1, 0}, { -1, 1, -1, 0}, { -1, -1, 1, 0}, { -1, -1, -1, 0} 150 | }; 151 | 152 | 153 | // Permutation table. The same list is repeated twice. 154 | static const int perm[512] = 155 | { 156 | 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 157 | 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 158 | 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 159 | 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 160 | 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 161 | 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 162 | 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 163 | 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 164 | 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 165 | 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 166 | 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 167 | 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, 168 | 169 | 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 170 | 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 171 | 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 172 | 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 173 | 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 174 | 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 175 | 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 176 | 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 177 | 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 178 | 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 179 | 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 180 | 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 181 | }; 182 | 183 | 184 | // A lookup table to traverse the simplex around a given point in 4D. 185 | static const int simplex[64][4] = 186 | { 187 | {0, 1, 2, 3}, {0, 1, 3, 2}, {0, 0, 0, 0}, {0, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 2, 3, 0}, 188 | {0, 2, 1, 3}, {0, 0, 0, 0}, {0, 3, 1, 2}, {0, 3, 2, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 3, 2, 0}, 189 | {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, 190 | {1, 2, 0, 3}, {0, 0, 0, 0}, {1, 3, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 3, 0, 1}, {2, 3, 1, 0}, 191 | {1, 0, 2, 3}, {1, 0, 3, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 0, 3, 1}, {0, 0, 0, 0}, {2, 1, 3, 0}, 192 | {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, 193 | {2, 0, 1, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 0, 1, 2}, {3, 0, 2, 1}, {0, 0, 0, 0}, {3, 1, 2, 0}, 194 | {2, 1, 0, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 1, 0, 2}, {0, 0, 0, 0}, {3, 2, 0, 1}, {3, 2, 1, 0} 195 | }; 196 | 197 | 198 | #endif /*SIMPLEX_H_*/ 199 | -------------------------------------------------------------------------------- /utilities.cpp: -------------------------------------------------------------------------------- 1 | #include "utilities.h" 2 | #include "Game.h" 3 | #include 4 | 5 | sf::Vector2f RotatePoint(sf::Vector2f Point, sf::Vector2f Origin, double phi) 6 | { 7 | double c = std::cos(phi) ,s = std::sin(phi); 8 | sf::Vector2f TranslatedPoint; 9 | TranslatedPoint.x = (Origin.x + (Point.x - Origin.x) * c 10 | - (Point.y - Origin.y) * s); 11 | TranslatedPoint.y = (Origin.y + (Point.y - Origin.y) * c 12 | + (Point.x - Origin.x) * s); 13 | return TranslatedPoint; 14 | } 15 | bool intersects(sf::CircleShape circle, sf::RectangleShape rect) 16 | { 17 | //turn the circle to (-angle of rect) so that rect OBB is now AABB 18 | circle.setPosition(RotatePoint(circle.getPosition(),rect.getPosition(),TO_RAD(-rect.getRotation()))); 19 | sf::Vector2f circleDistance; 20 | circleDistance.x = std::fabs(circle.getPosition().x - rect.getPosition().x); 21 | circleDistance.y = std::fabs(circle.getPosition().y - rect.getPosition().y); 22 | //check intersection with the edges 23 | if (circleDistance.x > (rect.getLocalBounds().width/2 + circle.getRadius())) { return false; } 24 | if (circleDistance.y > (rect.getLocalBounds().height/2 + circle.getRadius())) { return false; } 25 | 26 | if (circleDistance.x <= (rect.getLocalBounds().width/2)) { return true; } 27 | if (circleDistance.y <= (rect.getLocalBounds().height/2)) { return true; } 28 | //check corner intersection 29 | double cornerDistance_sq = sq(circleDistance.x - rect.getLocalBounds().width/2) + 30 | sq(circleDistance.y - rect.getLocalBounds().height/2); 31 | 32 | return (cornerDistance_sq <= sq(circle.getRadius())); 33 | } 34 | double cachedSqrt(int num) 35 | { 36 | static std::unordered_map cache; 37 | auto a = cache.find(num); 38 | if(a != cache.end()) 39 | return a->second; 40 | else 41 | { 42 | double temp = std::sqrt(num); 43 | cache[num] = temp; 44 | return temp; 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /utilities.h: -------------------------------------------------------------------------------- 1 | #ifndef UTILITIES_INCLUDED 2 | #define UTILITIES_INCLUDED 3 | #include 4 | #include 5 | #define LERP(t,a,b) ( (a) + (t) * ((b) - (a)) ) //liner interpolation 6 | #define TO_RAD(x) ( (x)*M_PI/180.0 ) 7 | #define TO_DEG(x) ( (x)*180.0/M_PI ) 8 | #include "constants.h" 9 | #define DBG 10 | #ifdef DBG 11 | #include 12 | #define PRINT_VAR(X) {std::cout << (#X) << " : " << (X) << std::endl;} 13 | #endif // DBG 14 | #ifndef M_PI 15 | #define M_PI 3.14159265358998 16 | #endif 17 | 18 | bool inline isInWindow(int x, int y) 19 | { 20 | return (x >= 0 && x < constants::windowWidth && y >= 0 && y < constants::windowHeight); 21 | } 22 | template 23 | 24 | bool inline isInRange(IntType t,IntType a,IntType b) //is t under the range [a,b] inclusive 25 | { 26 | //a must be greater than b , we don't check for 27 | return (t >= a && t <= b); 28 | } 29 | 30 | sf::Color inline grad(double t , sf::Color a, sf::Color b) 31 | { 32 | sf::Color res; 33 | res.r = LERP(t, a.r, b.r); 34 | res.g = LERP(t, a.g, b.g); 35 | res.b = LERP(t, a.b, b.b); 36 | res.a = LERP(t, a.a, b.a); 37 | return res; 38 | } 39 | 40 | template 41 | T inline arctan(T y,T x) 42 | { 43 | return x?std::atan2(y,x):M_PI_2; 44 | } 45 | 46 | template 47 | T inline sq(T a) 48 | { 49 | return a*a; 50 | } 51 | 52 | inline float round(float number,float divisor) 53 | { 54 | return divisor*static_cast(number/divisor+0.5); 55 | } 56 | inline double round(double number,double divisor) 57 | { 58 | return divisor*static_cast(number/divisor+0.5); 59 | } 60 | 61 | template //width and height must be +ve 62 | inline bool contains(T rectX,T rectY,T width,T height,T x, T y) 63 | { 64 | return (x >= rectX) && (x < rectX+width) && (y >= rectY) && (y < rectY+height); 65 | } 66 | 67 | sf::Vector2f RotatePoint(sf::Vector2f Point, sf::Vector2f Origin, double phi); 68 | bool intersects(sf::CircleShape circle, sf::RectangleShape rect); 69 | double cachedSqrt(int num); 70 | 71 | #endif // UTILITIES_INCLUDED 72 | --------------------------------------------------------------------------------