diff --git a/assets/Models/Submarine.obj b/assets/Models/Submarine.obj old mode 100644 new mode 100755 index 28e65c8..14569fc --- a/assets/Models/Submarine.obj +++ b/assets/Models/Submarine.obj @@ -1879,5 +1879,3 @@ f 166/13/239 259/24/24 401/34/255 f 161/12/240 166/13/239 400/32/253 f 163/27/245 161/12/240 399/29/251 f 256/19/19 163/27/245 398/30/30 -l 300 301 -l 299 298 diff --git a/assets/Textures/Background.png b/assets/Textures/Background.png new file mode 100755 index 0000000..353a610 Binary files /dev/null and b/assets/Textures/Background.png differ diff --git a/assets/Textures/GUI/HUD/LevelIndicatorBG.png b/assets/Textures/GUI/HUD/LevelIndicatorBG.png new file mode 100644 index 0000000..46cc1b3 Binary files /dev/null and b/assets/Textures/GUI/HUD/LevelIndicatorBG.png differ diff --git a/assets/Textures/GUI/HUD/ScoreIndicatorBG.png b/assets/Textures/GUI/HUD/ScoreIndicatorBG.png new file mode 100644 index 0000000..db97909 Binary files /dev/null and b/assets/Textures/GUI/HUD/ScoreIndicatorBG.png differ diff --git a/assets/Textures/GUI/Menu/Background.png b/assets/Textures/GUI/Menu/Background.png new file mode 100644 index 0000000..8b598c3 Binary files /dev/null and b/assets/Textures/GUI/Menu/Background.png differ diff --git a/assets/Textures/GUI/Menu/Left.png b/assets/Textures/GUI/Menu/Left.png new file mode 100644 index 0000000..e7813de Binary files /dev/null and b/assets/Textures/GUI/Menu/Left.png differ diff --git a/assets/Textures/GUI/Menu/MainOptions.png b/assets/Textures/GUI/Menu/MainOptions.png new file mode 100644 index 0000000..a38c916 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainOptions.png differ diff --git a/assets/Textures/GUI/Menu/MainOptionsClick.png b/assets/Textures/GUI/Menu/MainOptionsClick.png new file mode 100644 index 0000000..5a69342 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainOptionsClick.png differ diff --git a/assets/Textures/GUI/Menu/MainOptionsHover.png b/assets/Textures/GUI/Menu/MainOptionsHover.png new file mode 100644 index 0000000..c6e9c02 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainOptionsHover.png differ diff --git a/assets/Textures/GUI/Menu/MainSquidout.png b/assets/Textures/GUI/Menu/MainSquidout.png new file mode 100644 index 0000000..85d8748 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainSquidout.png differ diff --git a/assets/Textures/GUI/Menu/MainSquidoutClick.png b/assets/Textures/GUI/Menu/MainSquidoutClick.png new file mode 100644 index 0000000..f2206a3 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainSquidoutClick.png differ diff --git a/assets/Textures/GUI/Menu/MainSquidoutHover.png b/assets/Textures/GUI/Menu/MainSquidoutHover.png new file mode 100644 index 0000000..8fe33fe Binary files /dev/null and b/assets/Textures/GUI/Menu/MainSquidoutHover.png differ diff --git a/assets/Textures/GUI/Menu/MainTimeAttack.png b/assets/Textures/GUI/Menu/MainTimeAttack.png new file mode 100644 index 0000000..42ff9f3 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainTimeAttack.png differ diff --git a/assets/Textures/GUI/Menu/MainTimeAttackClick.png b/assets/Textures/GUI/Menu/MainTimeAttackClick.png new file mode 100644 index 0000000..3f37dc8 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainTimeAttackClick.png differ diff --git a/assets/Textures/GUI/Menu/MainTimeAttackHover.png b/assets/Textures/GUI/Menu/MainTimeAttackHover.png new file mode 100644 index 0000000..33cfc2d Binary files /dev/null and b/assets/Textures/GUI/Menu/MainTimeAttackHover.png differ diff --git a/assets/Textures/GUI/Menu/MainTitle.png b/assets/Textures/GUI/Menu/MainTitle.png new file mode 100644 index 0000000..9f2d607 Binary files /dev/null and b/assets/Textures/GUI/Menu/MainTitle.png differ diff --git a/assets/Textures/GUI/Menu/OptionsBGMTitle.png b/assets/Textures/GUI/Menu/OptionsBGMTitle.png new file mode 100644 index 0000000..5e35cbb Binary files /dev/null and b/assets/Textures/GUI/Menu/OptionsBGMTitle.png differ diff --git a/assets/Textures/GUI/Menu/OptionsSFXTitle.png b/assets/Textures/GUI/Menu/OptionsSFXTitle.png new file mode 100644 index 0000000..2c7b9b9 Binary files /dev/null and b/assets/Textures/GUI/Menu/OptionsSFXTitle.png differ diff --git a/assets/Textures/GUI/Menu/OptionsTitle.png b/assets/Textures/GUI/Menu/OptionsTitle.png new file mode 100644 index 0000000..08aa3f5 Binary files /dev/null and b/assets/Textures/GUI/Menu/OptionsTitle.png differ diff --git a/assets/Textures/GUI/Menu/SliderBackground.png b/assets/Textures/GUI/Menu/SliderBackground.png new file mode 100644 index 0000000..427e2e3 Binary files /dev/null and b/assets/Textures/GUI/Menu/SliderBackground.png differ diff --git a/assets/Textures/GUI/Menu/SliderHandle.png b/assets/Textures/GUI/Menu/SliderHandle.png new file mode 100644 index 0000000..49004d4 Binary files /dev/null and b/assets/Textures/GUI/Menu/SliderHandle.png differ diff --git a/assets/Textures/Test/Water.png b/assets/Textures/Test/Water.png new file mode 100755 index 0000000..2db8727 Binary files /dev/null and b/assets/Textures/Test/Water.png differ diff --git a/assets/Textures/Test/Water.psd b/assets/Textures/Test/Water.psd new file mode 100755 index 0000000..583db77 Binary files /dev/null and b/assets/Textures/Test/Water.psd differ diff --git a/include/Core/Engine.h b/include/Core/Engine.h index f5198f7..a9a47ec 100644 --- a/include/Core/Engine.h +++ b/include/Core/Engine.h @@ -49,47 +49,61 @@ #include "Physics/PhysicsSystem.h" #include "Physics/CPhysics.h" -#include "Physics/CBoxShape.h" +#include "Physics/CRectangleShape.h" #include "Physics/ESetImpulse.h" +#include "Physics/CWaterVolume.h" +#include "Game/EGameStart.h" +#include "Sound/EPlaySound.h" + +#include "GUI/Frame.h" +#include "GUI/Button.h" +#include "Game/MainMenu.h" +#include "Game/HUD.h" namespace dd { class Engine { + public: Engine(int argc, char* argv[]) { - m_EventBroker = std::make_shared(); + m_EventBroker = std::make_shared(); - m_Renderer = std::make_shared(); - m_Renderer->SetFullscreen(false); - //m_Renderer->SetResolution(Rectangle(0, 0, 1920, 1080)); - m_Renderer->SetResolution(Rectangle(0, 0, 675, 1080)); + m_Renderer = std::make_shared(); + m_Renderer->SetFullscreen(false); + //m_Renderer->SetResolution(Rectangle(0, 0, 1920, 1080)); + m_Renderer->SetResolution(Rectangle(0, 0, 675, 1080)); m_Renderer->Initialize(); - m_InputManager = std::make_shared(m_Renderer->Window(), m_EventBroker); + m_FrameStack = new GUI::Frame(m_EventBroker.get()); + m_FrameStack->Width = 675; + m_FrameStack->Height = 1080; + auto hud = new GUI::HUD(m_FrameStack, "HUD"); + auto menu = new GUI::MainMenu(m_FrameStack, "MainMenu"); + + m_InputManager = std::make_shared(m_Renderer->Window(), m_EventBroker); m_World = std::make_shared(m_EventBroker); - - - //TODO: Move this out of engine.h - m_World->ComponentFactory.Register(); - m_World->SystemFactory.Register( - [this]() { return new Systems::TransformSystem(m_World.get(), m_EventBroker); }); - m_World->AddSystem(); + //TODO: Move this out of engine.h + m_World->ComponentFactory.Register(); + m_World->SystemFactory.Register( + [this]() { return new Systems::TransformSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); - m_World->SystemFactory.Register([this]() { return new Systems::SoundSystem(m_World.get(), m_EventBroker); }); + m_World->SystemFactory.Register( + [this]() { return new Systems::SoundSystem(m_World.get(), m_EventBroker); }); m_World->AddSystem(); - m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); - m_World->ComponentFactory.Register(); - m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); @@ -98,43 +112,41 @@ public: m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); - m_World->SystemFactory.Register( - [this]() { return new Systems::PhysicsSystem(m_World.get(), m_EventBroker); }); - m_World->AddSystem(); + m_World->SystemFactory.Register( + [this]() { return new Systems::PhysicsSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); - m_World->SystemFactory.Register([this]() { return new Systems::LevelSystem(m_World.get(), m_EventBroker); }); + m_World->SystemFactory.Register( + [this]() { return new Systems::LevelSystem(m_World.get(), m_EventBroker); }); m_World->AddSystem(); - m_World->SystemFactory.Register([this]() { return new Systems::PadSystem(m_World.get(), m_EventBroker); }); + m_World->SystemFactory.Register( + [this]() { return new Systems::PadSystem(m_World.get(), m_EventBroker); }); m_World->AddSystem(); - m_World->SystemFactory.Register([this]() { return new Systems::BallSystem(m_World.get(), m_EventBroker); }); + m_World->SystemFactory.Register( + [this]() { return new Systems::BallSystem(m_World.get(), m_EventBroker); }); m_World->AddSystem(); - m_World->ComponentFactory.Register(); - m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); m_World->ComponentFactory.Register(); - m_World->Initialize(); + m_World->ComponentFactory.Register(); + m_World->Initialize(); - //TODO: Remove tobias light-test code. - /*{ - }*/ - //OctoBall - { - auto ent = m_World->CreateEntity(); - std::shared_ptr transform = m_World->AddComponent(ent); - transform->Position = glm::vec3(-0.f, 0.26f, -10.f); + { + auto ent = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent(ent); + transform->Position = glm::vec3(-0.f, 0.26f, -9.f); transform->Scale = glm::vec3(0.5f, 0.5f, 0.5f); transform->Velocity = glm::vec3(0.0f, -10.f, 0.f); - - auto model = m_World->AddComponent(ent); + auto model = m_World->AddComponent(ent); model->ModelFile = "Models/Test/Ball/Ballopus.obj"; - - std::shared_ptr circleShape = m_World->AddComponent(ent); + std::shared_ptr circleShape = m_World->AddComponent(ent); std::shared_ptr ball = m_World->AddComponent(ent); ball->Speed = 5.f; - std::shared_ptr physics = m_World->AddComponent(ent); - physics->Static = false; + std::shared_ptr physics = m_World->AddComponent(ent); + physics->Static = false; physics->Category = CollisionLayer::Type::Ball; physics->Mask = CollisionLayer::Type::Pad | CollisionLayer::Type::Brick | CollisionLayer::Type::Wall; physics->Calculate = true; @@ -142,10 +154,8 @@ public: auto plight = m_World->AddComponent(ent); plight->Radius = 2.f; - m_World->CommitEntity(ent); - - - } + m_World->CommitEntity(ent); + } //PointLightTest { @@ -154,28 +164,98 @@ public: transform->Position = glm::vec3(2.f, 1.5f, -9.f); auto pl = m_World->AddComponent(t_Light); pl->Radius = 8.f; + m_World->CommitEntity(t_Light); } //Halfpipe background test model. { auto t_halfPipe = m_World->CreateEntity(); auto transform = m_World->AddComponent(t_halfPipe); - transform->Position = glm::vec3(0.f, 0.f, -13.f); - transform->Scale = glm::vec3(5.f); + transform->Position = glm::vec3(0.f, 0.f, -15.f); + transform->Scale = glm::vec3(15.f); auto model = m_World->AddComponent(t_halfPipe); model->ModelFile = "Models/Test/halfpipe/Halfpipe.obj"; + model->Color = glm::vec4(1.f, 1.f, 1.f, 0.3f); + m_World->CommitEntity(t_halfPipe); } + //Background + { + auto background = m_World->CreateEntity(); + auto transform = m_World->AddComponent(background); + transform->Position = glm::vec3(0.f, 0.f, -30.f); + transform->Scale = glm::vec3(2681.f / 50.f, 1080.f / 50.f, 1.f); + auto sprite = m_World->AddComponent(background); + sprite->SpriteFile = "Textures/Background.png"; + m_World->CommitEntity(background); + } + + //Water test + { + auto t_waterBody = m_World->CreateEntity(); + auto transform = m_World->AddComponent(t_waterBody); + transform->Position = glm::vec3(0.f, -4.5f, -10.f); + transform->Scale = glm::vec3(7.f, 1.5f, 1.f); + auto water = m_World->AddComponent(t_waterBody); + auto body = m_World->AddComponent(t_waterBody); + m_World->CommitEntity(t_waterBody); + } + //TODO: Why does the ball not collide with these bricks? + //BottomBox + { + auto topWall = m_World->CreateEntity(); + auto transform = m_World->AddComponent(topWall); + transform->Position = glm::vec3(0.f, -6.f, -9.9f); + transform->Scale = glm::vec3(10.f, 0.5f, 1.f); + std::shared_ptr sprite = m_World->AddComponent(topWall); + sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; + std::shared_ptr boxShape = m_World->AddComponent( + topWall); + std::shared_ptr physics = m_World->AddComponent(topWall); + physics->Static = true; + m_World->CommitEntity(topWall); + } + //SideBox +// { +// auto topWall = m_World->CreateEntity(); +// std::shared_ptr transform = m_World->AddComponent(topWall); +// transform->Position = glm::vec3(3.f, -3.0f, -9.9f); +// transform->Scale = glm::vec3(0.5f, 3.f, 1.f); +// std::shared_ptr sprite = m_World->AddComponent(topWall); +// sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; +// std::shared_ptr boxShape = m_World->AddComponent( +// topWall); +// std::shared_ptr physics = m_World->AddComponent(topWall); +// physics->Static = true; +// m_World->CommitEntity(topWall); +// } +// //OtherSideBox +// { +// auto topWall = m_World->CreateEntity(); +// std::shared_ptr transform = m_World->AddComponent(topWall); +// transform->Position = glm::vec3(-4.f, -3.0f, -9.9f); +// transform->Scale = glm::vec3(0.5f, 3.0f, 1.f); +// std::shared_ptr sprite = m_World->AddComponent(topWall); +// sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; +// std::shared_ptr boxShape = m_World->AddComponent( +// topWall); +// std::shared_ptr physics = m_World->AddComponent(topWall); +// physics->Static = true; +// m_World->CommitEntity(topWall); +// } + { auto topWall = m_World->CreateEntity(); - std::shared_ptr transform = m_World->AddComponent(topWall); + std::shared_ptr transform = m_World->AddComponent( + topWall); transform->Position = glm::vec3(0.f, 6.f, -10.f); transform->Scale = glm::vec3(20.f, 0.5f, 1.f); std::shared_ptr sprite = m_World->AddComponent(topWall); sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; - std::shared_ptr boxShape = m_World->AddComponent(topWall); + std::shared_ptr boxShape = m_World->AddComponent( + topWall); std::shared_ptr physics = m_World->AddComponent(topWall); physics->Static = true; @@ -184,16 +264,19 @@ public: m_World->CommitEntity(topWall); } + { auto leftWall = m_World->CreateEntity(); - std::shared_ptr transform = m_World->AddComponent(leftWall); + std::shared_ptr transform = m_World->AddComponent( + leftWall); transform->Position = glm::vec3(-4.f, 1.f, -10.f); transform->Scale = glm::vec3(0.5f, 20.f, 1.f); std::shared_ptr sprite = m_World->AddComponent(leftWall); sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; - std::shared_ptr boxShape = m_World->AddComponent(leftWall); + std::shared_ptr boxShape = m_World->AddComponent( + leftWall); std::shared_ptr physics = m_World->AddComponent(leftWall); physics->Static = true; @@ -202,16 +285,19 @@ public: m_World->CommitEntity(leftWall); } + { auto rightWall = m_World->CreateEntity(); - std::shared_ptr transform = m_World->AddComponent(rightWall); + std::shared_ptr transform = m_World->AddComponent( + rightWall); transform->Position = glm::vec3(4.f, 1.f, -10.f); transform->Scale = glm::vec3(0.5f, 20.f, 1.f); std::shared_ptr sprite = m_World->AddComponent(rightWall); sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; - std::shared_ptr boxShape = m_World->AddComponent(rightWall); + std::shared_ptr boxShape = m_World->AddComponent( + rightWall); std::shared_ptr physics = m_World->AddComponent(rightWall); physics->Static = true; @@ -225,7 +311,7 @@ public: auto ent = m_World->CreateEntity(); m_World->SetProperty(ent, "Name", "Pad"); auto ctransform = m_World->AddComponent(ent); - ctransform->Position = glm::vec3(0.f, -5.f, -10.f); + ctransform->Position = glm::vec3(0.f, -3.5f, -10.f); ctransform->Scale = glm::vec3(1.0f, 1.0f, 1.f); auto rectangle = m_World->AddComponent(ent); auto physics = m_World->AddComponent(ent); @@ -240,7 +326,12 @@ public: m_World->CommitEntity(ent); } - m_LastTime = glfwGetTime(); + + //EVENT_SUBSCRIBE_MEMBER(m_EGameStart, &Engine::OnGameStart); + m_EGameStart = decltype(m_EGameStart)(std::bind(&Engine::OnGameStart, this, std::placeholders::_1)); + m_EventBroker->Subscribe(m_EGameStart); + + m_LastTime = glfwGetTime(); } bool Running() const { return !glfwWindowShouldClose(m_Renderer->Window()); } @@ -251,39 +342,32 @@ public: double dt = currentTime - m_LastTime; m_LastTime = currentTime; - ResourceManager::Update(); - // Update input m_InputManager->Update(dt); + // Swap event queues to get fresh input data in the read queue + //m_EventBroker->Swap(); - m_World->Update(dt); - - -// -// if (glfwGetKey(m_Renderer->Window(), GLFW_KEY_R)) { -// ResourceManager::Reload("Shaders/Deferred/3/Fragment.glsl"); -// } -// - //TODO Fill up the renderQueue with models (Temp fix) -// TEMPAddToRenderQueue(); - - // Render scene - //TODO send renderqueue to draw. -// m_Renderer->Draw(m_RendererQueue); - - if (glfwGetKey(m_Renderer->Window(), GLFW_KEY_R)) { - ResourceManager::Reload("Shaders/Deferred/3/Fragment.glsl"); + ResourceManager::Update(); + if (m_GameIsRunning) { + m_World->Update(dt); } + m_EventBroker->Process(); + m_FrameStack->UpdateLayered(dt); + m_RendererQueue.Clear(); + m_FrameStack->DrawLayered(m_RendererQueue); //TODO Fill up the renderQueue with models (Temp fix) - TEMPAddToRenderQueue(); + if (m_GameIsRunning) { + TEMPAddToRenderQueue(); + } // Render scene //TODO send renderqueue to draw. m_Renderer->Draw(m_RendererQueue); + m_EventBroker->Process(); // Swap event queues - m_EventBroker->Clear(); + m_EventBroker->Swap(); glfwPollEvents(); } @@ -294,12 +378,9 @@ public: //TODO: Get this out of engine.h void TEMPAddToRenderQueue() { - if (!m_TransformSystem) m_TransformSystem = m_World->GetSystem(); - m_RendererQueue.Clear(); - for (auto &pair : *m_World->GetEntities()) { EntityID entity = pair.first; @@ -328,8 +409,6 @@ public: } } - //TODO: Add LightLoadShit - auto pointLightComponent = m_World->GetComponent(entity); if (pointLightComponent) { @@ -340,6 +419,19 @@ public: pointLightComponent->Radius); } + auto parent = m_World->GetEntityParent(entity); + if(parent != 0) { + auto waterParticleComponent = m_World->GetComponent(parent); + if (waterParticleComponent) { + //TODO: Remove hardcoded color. + //TODO: Do i even need modelMatrix? + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + glm::mat4 modelMatrix = glm::translate(absoluteTransform.Position) + * glm::scale(absoluteTransform.Scale); + EnqueueWaterParticles(absoluteTransform.Position, glm::vec4(1.f, 1.f, 1.f, 1.f), modelMatrix, absoluteTransform.Position.z); + } + } + auto spriteComponent = m_World->GetComponent(entity); if (spriteComponent) @@ -368,7 +460,6 @@ public: } } - m_RendererQueue.Sort(); } //TODO: Get this out of engine.h @@ -387,7 +478,6 @@ public: job.EndIndex = texGroup.EndIndex; job.ModelMatrix = modelMatrix; job.Color = color; - job.fileName = fileName; m_RendererQueue.Deferred.Add(job); } @@ -421,15 +511,46 @@ public: } + void EnqueueWaterParticles(glm::vec3 position, glm::vec4 color, glm::mat4 modelMatrix, float depth) + { + WaterParticleJob job; + job.Position = position; + job.Color = color; + job.ModelMatrix = modelMatrix; + job.Depth = depth; + + m_RendererQueue.Forward.Add(job); + } + private: - std::shared_ptr m_ResourceManager; std::shared_ptr m_EventBroker; + GUI::Frame* m_FrameStack = nullptr; std::shared_ptr m_Renderer; RenderQueueCollection m_RendererQueue; std::shared_ptr m_InputManager; std::shared_ptr m_World; - + //TODO: Redo + bool m_GameIsRunning = false; + dd::EventRelay m_EGameStart; + bool OnGameStart(const dd::Events::GameStart &event) + { + m_GameIsRunning = true; + //Todo: Move this + { + dd::Events::PlaySound e; + e.path = "Sounds/BGM/under-the-sea-instrumental.wav"; + e.isAmbient = true; + m_EventBroker->Publish(e); + } + { + dd::Events::PlaySound e; + e.path = "Sounds/BGM/water-flowing.wav"; + e.volume = 0.3f; + e.isAmbient = true; + m_EventBroker->Publish(e); + } + }; double m_LastTime; }; diff --git a/include/Core/Engine.h.orig b/include/Core/Engine.h.orig new file mode 100644 index 0000000..f19102e --- /dev/null +++ b/include/Core/Engine.h.orig @@ -0,0 +1,562 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#include +#include +#include + +#include "ResourceManager.h" +#include "OBJ.h" +#include "Model.h" +#include "Texture.h" +#include "EventBroker.h" +#include "RenderQueue.h" +#include "Renderer.h" +#include "InputManager.h" +//TODO: Remove includes that are only here for the temporary draw solution. +#include "World.h" +#include "CTransform.h" +#include "Core/EventBroker.h" +#include "Rendering/CModel.h" +#include "Rendering/CSprite.h" +#include "CTemplate.h" +#include "Rendering/CPointLight.h" +#include "Transform/TransformSystem.h" +#include "Sound/SoundSystem.h" +#include "Sound/CCollisionSound.h" +#include "Game/LevelSystem.h" +#include "Game/PadSystem.h" +#include "Game/CBall.h" +#include "Game/CPad.h" +#include "Game/CBrick.h" +#include "Game/BallSystem.h" +#include "Game/Bricks/CPowerUpBrick.h" + +#include "Physics/PhysicsSystem.h" +#include "Physics/CPhysics.h" +#include "Physics/CRectangleShape.h" +#include "Physics/ESetImpulse.h" +#include "Physics/CWaterVolume.h" + +#include "Game/EGameStart.h" +#include "Sound/EPlaySound.h" + +#include "GUI/Frame.h" +#include "GUI/Button.h" +#include "Game/MainMenu.h" +#include "Game/HUD.h" + +namespace dd +{ + +class Engine +{ + +public: + Engine(int argc, char* argv[]) { + m_EventBroker = std::make_shared(); + + m_Renderer = std::make_shared(); + m_Renderer->SetFullscreen(false); + //m_Renderer->SetResolution(Rectangle(0, 0, 1920, 1080)); + m_Renderer->SetResolution(Rectangle(0, 0, 675, 1080)); + m_Renderer->Initialize(); + + m_FrameStack = new GUI::Frame(m_EventBroker.get()); + m_FrameStack->Width = 675; + m_FrameStack->Height = 1080; + auto hud = new GUI::HUD(m_FrameStack, "HUD"); + auto menu = new GUI::MainMenu(m_FrameStack, "MainMenu"); + + m_InputManager = std::make_shared(m_Renderer->Window(), m_EventBroker); + + m_World = std::make_shared(m_EventBroker); + + //TODO: Move this out of engine.h + m_World->ComponentFactory.Register(); + m_World->SystemFactory.Register( + [this]() { return new Systems::TransformSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + + m_World->ComponentFactory.Register(); + m_World->SystemFactory.Register( + [this]() { return new Systems::SoundSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); + + m_World->ComponentFactory.Register(); + + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + + m_World->SystemFactory.Register( + [this]() { return new Systems::PhysicsSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); + + m_World->SystemFactory.Register( + [this]() { return new Systems::LevelSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); + m_World->SystemFactory.Register( + [this]() { return new Systems::PadSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); + m_World->SystemFactory.Register( + [this]() { return new Systems::BallSystem(m_World.get(), m_EventBroker); }); + m_World->AddSystem(); + + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->ComponentFactory.Register(); + m_World->Initialize(); + + + //OctoBall + { + auto ent = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent(ent); + transform->Position = glm::vec3(-0.f, 0.26f, -9.f); + transform->Scale = glm::vec3(0.5f, 0.5f, 0.5f); + transform->Velocity = glm::vec3(0.0f, -10.f, 0.f); + auto model = m_World->AddComponent(ent); + model->ModelFile = "Models/Test/Ball/Ballopus.obj"; + std::shared_ptr circleShape = m_World->AddComponent(ent); + std::shared_ptr ball = m_World->AddComponent(ent); + ball->Speed = 5.f; +<<<<<<< HEAD + std::shared_ptr physics = m_World->AddComponent(ent); + physics->Static = false; + physics->Category = CollisionLayer::Type::Ball; + physics->Mask = CollisionLayer::Type::Pad | CollisionLayer::Type::Brick | CollisionLayer::Type::Wall; + physics->Calculate = true; +======= + std::shared_ptr physics = m_World->AddComponent(ent); + physics->Static = false; +>>>>>>> origin/master + + auto plight = m_World->AddComponent(ent); + plight->Radius = 2.f; + + m_World->CommitEntity(ent); + } + + //PointLightTest + { + auto t_Light = m_World->CreateEntity(); + auto transform = m_World->AddComponent(t_Light); + transform->Position = glm::vec3(2.f, 1.5f, -9.f); + auto pl = m_World->AddComponent(t_Light); + pl->Radius = 8.f; + m_World->CommitEntity(t_Light); + } + + //Halfpipe background test model. + { + auto t_halfPipe = m_World->CreateEntity(); + auto transform = m_World->AddComponent(t_halfPipe); + transform->Position = glm::vec3(0.f, 0.f, -15.f); + transform->Scale = glm::vec3(15.f); + auto model = m_World->AddComponent(t_halfPipe); + model->ModelFile = "Models/Test/halfpipe/Halfpipe.obj"; + model->Color = glm::vec4(1.f, 1.f, 1.f, 0.3f); + m_World->CommitEntity(t_halfPipe); + } + + //Background + { + auto background = m_World->CreateEntity(); + auto transform = m_World->AddComponent(background); + transform->Position = glm::vec3(0.f, 0.f, -30.f); + transform->Scale = glm::vec3(2681.f / 50.f, 1080.f / 50.f, 1.f); + auto sprite = m_World->AddComponent(background); + sprite->SpriteFile = "Textures/Background.png"; + m_World->CommitEntity(background); + } + + //Water test + { + auto t_waterBody = m_World->CreateEntity(); + auto transform = m_World->AddComponent(t_waterBody); + transform->Position = glm::vec3(0.f, -4.5f, -10.f); + transform->Scale = glm::vec3(7.f, 1.5f, 1.f); + auto water = m_World->AddComponent(t_waterBody); + auto body = m_World->AddComponent(t_waterBody); + m_World->CommitEntity(t_waterBody); + } + //TODO: Why does the ball not collide with these bricks? + //BottomBox + { + auto topWall = m_World->CreateEntity(); + auto transform = m_World->AddComponent(topWall); + transform->Position = glm::vec3(0.f, -6.f, -9.9f); + transform->Scale = glm::vec3(10.f, 0.5f, 1.f); + std::shared_ptr sprite = m_World->AddComponent(topWall); + sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; + std::shared_ptr boxShape = m_World->AddComponent( + topWall); + std::shared_ptr physics = m_World->AddComponent(topWall); + physics->Static = true; + m_World->CommitEntity(topWall); + } + //SideBox +// { +// auto topWall = m_World->CreateEntity(); +// std::shared_ptr transform = m_World->AddComponent(topWall); +// transform->Position = glm::vec3(3.f, -3.0f, -9.9f); +// transform->Scale = glm::vec3(0.5f, 3.f, 1.f); +// std::shared_ptr sprite = m_World->AddComponent(topWall); +// sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; +// std::shared_ptr boxShape = m_World->AddComponent( +// topWall); +// std::shared_ptr physics = m_World->AddComponent(topWall); +// physics->Static = true; +// m_World->CommitEntity(topWall); +// } +// //OtherSideBox +// { +// auto topWall = m_World->CreateEntity(); +// std::shared_ptr transform = m_World->AddComponent(topWall); +// transform->Position = glm::vec3(-4.f, -3.0f, -9.9f); +// transform->Scale = glm::vec3(0.5f, 3.0f, 1.f); +// std::shared_ptr sprite = m_World->AddComponent(topWall); +// sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; +// std::shared_ptr boxShape = m_World->AddComponent( +// topWall); +// std::shared_ptr physics = m_World->AddComponent(topWall); +// physics->Static = true; +// m_World->CommitEntity(topWall); +// } + + { + auto topWall = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent( + topWall); + transform->Position = glm::vec3(0.f, 6.f, -10.f); + transform->Scale = glm::vec3(20.f, 0.5f, 1.f); + + std::shared_ptr sprite = m_World->AddComponent(topWall); + sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; + + std::shared_ptr boxShape = m_World->AddComponent( + topWall); + + std::shared_ptr physics = m_World->AddComponent(topWall); + physics->Static = true; + physics->Category = CollisionLayer::Type::Wall; + physics->Mask = CollisionLayer::Type::Ball | CollisionLayer::Type::Brick; + + m_World->CommitEntity(topWall); + } + + { + auto leftWall = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent( + leftWall); + transform->Position = glm::vec3(-4.f, 1.f, -10.f); + transform->Scale = glm::vec3(0.5f, 20.f, 1.f); + + std::shared_ptr sprite = m_World->AddComponent(leftWall); + sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; + + std::shared_ptr boxShape = m_World->AddComponent( + leftWall); + + std::shared_ptr physics = m_World->AddComponent(leftWall); + physics->Static = true; + physics->Category = CollisionLayer::Type::Wall; + physics->Mask = CollisionLayer::Type::Ball | CollisionLayer::Type::Brick; + + m_World->CommitEntity(leftWall); + } + + { + auto rightWall = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent( + rightWall); + transform->Position = glm::vec3(4.f, 1.f, -10.f); + transform->Scale = glm::vec3(0.5f, 20.f, 1.f); + + std::shared_ptr sprite = m_World->AddComponent(rightWall); + sprite->SpriteFile = "Textures/Core/ErrorTexture.png"; + + std::shared_ptr boxShape = m_World->AddComponent( + rightWall); + + std::shared_ptr physics = m_World->AddComponent(rightWall); + physics->Static = true; + physics->Category = CollisionLayer::Type::Wall; + physics->Mask = CollisionLayer::Type::Ball | CollisionLayer::Type::Brick; + + m_World->CommitEntity(rightWall); + } + + { + auto ent = m_World->CreateEntity(); + m_World->SetProperty(ent, "Name", "Pad"); + auto ctransform = m_World->AddComponent(ent); + ctransform->Position = glm::vec3(0.f, -5.f, -10.f); + ctransform->Scale = glm::vec3(1.0f, 1.0f, 1.f); + auto rectangle = m_World->AddComponent(ent); + auto physics = m_World->AddComponent(ent); + physics->Static = false; + physics->Category = CollisionLayer::Type::Pad; + physics->Mask = CollisionLayer::Type::Ball | CollisionLayer::Type::PowerUp; + physics->Calculate = true; + auto cModel = m_World->AddComponent(ent); + cModel->ModelFile = "Models/Submarine2.obj"; + + auto pad = m_World->AddComponent(ent); + m_World->CommitEntity(ent); + } + + + //EVENT_SUBSCRIBE_MEMBER(m_EGameStart, &Engine::OnGameStart); + m_EGameStart = decltype(m_EGameStart)(std::bind(&Engine::OnGameStart, this, std::placeholders::_1)); + m_EventBroker->Subscribe(m_EGameStart); + + m_LastTime = glfwGetTime(); + } + + bool Running() const { return !glfwWindowShouldClose(m_Renderer->Window()); } + + void Tick() + { + double currentTime = glfwGetTime(); + double dt = currentTime - m_LastTime; + m_LastTime = currentTime; + + // Update input + m_InputManager->Update(dt); + // Swap event queues to get fresh input data in the read queue + //m_EventBroker->Swap(); + + ResourceManager::Update(); + if (m_GameIsRunning) { + m_World->Update(dt); + } + m_EventBroker->Process(); + m_FrameStack->UpdateLayered(dt); + + m_RendererQueue.Clear(); + m_FrameStack->DrawLayered(m_RendererQueue); + //TODO Fill up the renderQueue with models (Temp fix) + if (m_GameIsRunning) { + TEMPAddToRenderQueue(); + } + + // Render scene + //TODO send renderqueue to draw. + m_Renderer->Draw(m_RendererQueue); + + m_EventBroker->Process(); + // Swap event queues + m_EventBroker->Swap(); + + glfwPollEvents(); + } + + std::shared_ptr m_TransformSystem; + std::shared_ptr m_LevelSystem; + + //TODO: Get this out of engine.h + void TEMPAddToRenderQueue() + { + if (!m_TransformSystem) + m_TransformSystem = m_World->GetSystem(); + + for (auto &pair : *m_World->GetEntities()) + { + EntityID entity = pair.first; + + auto templateComponent = m_World->GetComponent(entity); + if (templateComponent) + continue; + + auto transform = m_World->GetComponent(entity); + if (!transform) + continue; + + auto modelComponent = m_World->GetComponent(entity); + if (modelComponent) + { + Model* modelAsset = nullptr; + modelAsset = ResourceManager::Load(modelComponent->ModelFile); + + if (modelAsset) + { + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + glm::mat4 modelMatrix = glm::translate(glm::mat4(), absoluteTransform.Position) + * glm::toMat4(absoluteTransform.Orientation) + * glm::scale(absoluteTransform.Scale); + EnqueueModel(modelAsset, modelMatrix, modelComponent->Transparent, modelComponent->Color, modelComponent->ModelFile); + } + } + + auto pointLightComponent = m_World->GetComponent(entity); + if (pointLightComponent) + { + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + EnqueuePointLight(absoluteTransform.Position, + pointLightComponent->Diffuse, + pointLightComponent->Specular, + pointLightComponent->Radius); + } + + auto parent = m_World->GetEntityParent(entity); + if(parent != 0) { + auto waterParticleComponent = m_World->GetComponent(parent); + if (waterParticleComponent) { + //TODO: Remove hardcoded color. + //TODO: Do i even need modelMatrix? + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + glm::mat4 modelMatrix = glm::translate(absoluteTransform.Position) + * glm::scale(absoluteTransform.Scale); + EnqueueWaterParticles(absoluteTransform.Position, glm::vec4(1.f, 1.f, 1.f, 1.f), modelMatrix, absoluteTransform.Position.z); + } + } + + + auto spriteComponent = m_World->GetComponent(entity); + if (spriteComponent) + { + + std::string normal = spriteComponent->NormalTexture; + std::string spec = spriteComponent->SpecularTexture; + + if (normal.empty()) { + normal = "Textures/Core/NeutralNormalMap.png"; + } + if (spec.empty()) { + spec = "Textures/Core/NeutralSpecularMap.png"; + } + auto texturediff = ResourceManager::Load(spriteComponent->SpriteFile); + auto texturenorm = ResourceManager::Load(normal); + auto texturespec = ResourceManager::Load(spec); + + + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(absoluteTransform.Orientation).z, glm::vec3(0, 0, -1)); + glm::mat4 modelMatrix = glm::translate(absoluteTransform.Position) + * glm::toMat4(orientation2D) + * glm::scale(absoluteTransform.Scale); + EnqueueSprite(texturediff, texturenorm, texturespec, modelMatrix, spriteComponent->Color, absoluteTransform.Position.z); + } + } + + } + + //TODO: Get this out of engine.h + void EnqueueModel(Model* model, glm::mat4 modelMatrix, float transparent, glm::vec4 color, std::string fileName) + { + for (auto texGroup : model->TextureGroups) + { + ModelJob job; + job.TextureID = (texGroup.Texture) ? texGroup.Texture->ResourceID : 0; + job.DiffuseTexture = (texGroup.Texture) ? *texGroup.Texture : 0; + job.NormalTexture = (texGroup.NormalMap) ? *texGroup.NormalMap : 0; + job.SpecularTexture = (texGroup.SpecularMap) ? *texGroup.SpecularMap : 0; + job.VAO = model->VAO; + job.ElementBuffer = model->ElementBuffer; + job.StartIndex = texGroup.StartIndex; + job.EndIndex = texGroup.EndIndex; + job.ModelMatrix = modelMatrix; + job.Color = color; + + m_RendererQueue.Deferred.Add(job); + } + } + + // TODO: Get this out of engine.h + void EnqueueSprite(Texture* texture, Texture* normalTexture, Texture* specularTexture, glm::mat4 modelMatrix, glm::vec4 color, float depth) + { + SpriteJob job; + job.TextureID = texture->ResourceID; + job.DiffuseTexture = *texture; + job.NormalTexture = *normalTexture; + job.SpecularTexture = *specularTexture; + job.ModelMatrix = modelMatrix; + job.Color = color; + job.Depth = depth; + + + m_RendererQueue.Forward.Add(job); + } + + void EnqueuePointLight(glm::vec3 position, glm::vec3 diffuseColor, glm::vec3 specularColor, float radius) + { + PointLightJob job; + job.Position = position; + job.DiffuseColor = diffuseColor; + job.SpecularColor = specularColor; + job.Radius = radius; + + m_RendererQueue.Lights.Add(job); + + } + + void EnqueueWaterParticles(glm::vec3 position, glm::vec4 color, glm::mat4 modelMatrix, float depth) + { + WaterParticleJob job; + job.Position = position; + job.Color = color; + job.ModelMatrix = modelMatrix; + job.Depth = depth; + + m_RendererQueue.Forward.Add(job); + } + +private: + std::shared_ptr m_EventBroker; + GUI::Frame* m_FrameStack = nullptr; + std::shared_ptr m_Renderer; + RenderQueueCollection m_RendererQueue; + std::shared_ptr m_InputManager; + std::shared_ptr m_World; + + //TODO: Redo + bool m_GameIsRunning = false; + dd::EventRelay m_EGameStart; + bool OnGameStart(const dd::Events::GameStart &event) + { + m_GameIsRunning = true; + //Todo: Move this + { + dd::Events::PlaySound e; + e.path = "Sounds/BGM/under-the-sea-instrumental.wav"; + e.isAmbient = true; + m_EventBroker->Publish(e); + } + { + dd::Events::PlaySound e; + e.path = "Sounds/BGM/water-flowing.wav"; + e.volume = 0.3f; + e.isAmbient = true; + m_EventBroker->Publish(e); + } + }; + double m_LastTime; +}; + +} diff --git a/include/Core/EventBroker.h b/include/Core/EventBroker.h index f19309c..cb5e39c 100644 --- a/include/Core/EventBroker.h +++ b/include/Core/EventBroker.h @@ -119,7 +119,7 @@ public: template int Process(); int Process(std::string contextTypeName); - void Clear(); + void Swap(); void Unsubscribe(BaseEventRelay &relay); private: diff --git a/include/Core/PNG.h b/include/Core/PNG.h index fc99324..994a5bc 100644 --- a/include/Core/PNG.h +++ b/include/Core/PNG.h @@ -33,9 +33,6 @@ class PNG : public Image public: PNG(std::string path); ~PNG(); - -private: - }; } diff --git a/include/Core/RenderQueue.h b/include/Core/RenderQueue.h index 9984770..0319267 100755 --- a/include/Core/RenderQueue.h +++ b/include/Core/RenderQueue.h @@ -22,8 +22,9 @@ #include #include -#include "Texture.h" -#include "Model.h" +#include "Core/Util/Rectangle.h" +#include "Core/Texture.h" +#include "Core/Model.h" namespace dd { @@ -52,8 +53,8 @@ struct ModelJob : RenderJob unsigned int ShaderID; unsigned int TextureID; - std::string fileName; - + glm::mat4 ProjectionMatrix; + glm::mat4 ViewMatrix; glm::mat4 ModelMatrix; GLuint DiffuseTexture; GLuint NormalTexture; @@ -90,6 +91,8 @@ struct SpriteJob : RenderJob unsigned int ShaderID; unsigned int TextureID; + glm::mat4 ProjectionMatrix; + glm::mat4 ViewMatrix; glm::mat4 ModelMatrix; GLuint DiffuseTexture; GLuint NormalTexture; @@ -115,6 +118,30 @@ struct PointLightJob : RenderJob } }; +struct FrameJob : SpriteJob +{ + Rectangle Scissor; + Rectangle Viewport; + std::string Name; + + void CalculateHash() override + { + Hash = 0; + } +}; + +struct WaterParticleJob : RenderJob +{ + glm::vec3 Position; + glm::vec4 Color; + glm::mat4 ModelMatrix; + + void CalculateHash() override + { + Hash = 0; + } +}; + class RenderQueue { public: @@ -122,7 +149,8 @@ public: void Add(T &job) { job.CalculateHash(); - Jobs.push_front(std::shared_ptr(new T(job))); + Jobs.push_back(std::shared_ptr(new T(job))); + m_Size++; } void Sort() @@ -133,19 +161,24 @@ public: void Clear() { Jobs.clear(); + m_Size = 0; } - std::forward_list>::const_iterator begin() + int Size() const { return m_Size; } + std::list>::const_iterator begin() { return Jobs.begin(); } - std::forward_list>::const_iterator end() + std::list>::const_iterator end() { return Jobs.end(); } - std::forward_list> Jobs; + std::list> Jobs; + +private: + int m_Size = 0; }; struct RenderQueueCollection @@ -153,12 +186,14 @@ struct RenderQueueCollection RenderQueue Deferred; RenderQueue Forward; RenderQueue Lights; + RenderQueue GUI; void Clear() { Deferred.Clear(); Forward.Clear(); Lights.Clear(); + GUI.Clear(); } void Sort() @@ -166,6 +201,7 @@ struct RenderQueueCollection Deferred.Sort(); Forward.Sort(); Lights.Sort(); + GUI.Sort(); } }; diff --git a/include/Core/Renderer.h b/include/Core/Renderer.h index 1b8e078..5a2b03f 100755 --- a/include/Core/Renderer.h +++ b/include/Core/Renderer.h @@ -72,12 +72,15 @@ private: ShaderProgram* m_spDeferred3; ShaderProgram* m_spForward; ShaderProgram* m_spScreen; + ShaderProgram* t_m_spWater; + ShaderProgram* t_m_spWater2; GLuint m_ScreenQuad = 0; Model* m_UnitSphere = nullptr; Model* m_UnitQuad = nullptr; Texture* m_StandardNormal; Texture* m_StandardSpecular; + Texture* t_m_WhiteSphereTexture; GLuint m_rbDepthBuffer = 0; GLuint m_fbDeferred1 = 0; @@ -89,11 +92,23 @@ private: GLuint m_tLighting = 0; GLuint m_fbDeferred3 = 0; GLuint m_tFinal = 0; + //Water GTexture + GLuint t_m_Gwater = 0; + //Water blur texture + GLuint t_m_BWater; + GLuint t_m_BWater2; + //WAterpass Framebuffer + GLuint t_m_fbWater; + //Waterpass Framebuffer + GLuint t_m_fbWaterBlur; + GLuint t_m_fbWaterBlur2; + GLuint m_CurrentScreenBuffer = 0; void LoadShaders(); void CreateBuffers(); GLuint CreateQuad(); + GLuint CreateWaterParticleVAO(RenderQueue &particles); static bool DepthSort(const std::shared_ptr &i, const std::shared_ptr &j) { return (i->Depth < j->Depth); } @@ -101,6 +116,8 @@ private: void DrawForward(RenderQueue &objects, RenderQueue &lights); void DrawScene(RenderQueue &objects, ShaderProgram &program); void DrawLightSpheres(RenderQueue &lights); + void DrawWater(RenderQueue &objects); + void DrawGUI(RenderQueue& rq); void DebugKeys(); }; diff --git a/include/Core/Texture.h b/include/Core/Texture.h index 13bd113..f7cfd69 100644 --- a/include/Core/Texture.h +++ b/include/Core/Texture.h @@ -43,6 +43,9 @@ public: operator GLuint() const { return m_Texture; } + unsigned int Width = 0; + unsigned int Height = 0; + private: GLuint m_Texture = 0; }; diff --git a/include/Core/Util/Rectangle.h b/include/Core/Util/Rectangle.h index 6ce0695..c24501f 100644 --- a/include/Core/Util/Rectangle.h +++ b/include/Core/Util/Rectangle.h @@ -44,29 +44,30 @@ struct Rectangle int Height; virtual int Left() const { return X; } - void SetLeft(int left) + virtual void SetLeft(int left) { - Width += X - left; + //Width += X - left; X = left; } virtual int Right() const { return X + Width; } - void SetRight(int right) + virtual void SetRight(int right) { Width = right - X; } virtual int Top() const { return Y; } - void SetTop(int top) + virtual void SetTop(int top) { - Height += Y - top; + //Height += Y - top; Y = top; } virtual int Bottom() const { return Y + Height; } - int SetBottom(int bottom) + virtual void SetBottom(int bottom) { Height = bottom - Y; } - Rectangle& operator+=(const Rectangle &rhs) { + Rectangle& operator+=(const Rectangle &rhs) + { SetLeft(std::min(Left(), rhs.Left())); SetRight(std::max(Right(), rhs.Right())); SetTop(std::min(Top(), rhs.Top())); diff --git a/include/GUI/Button.h b/include/GUI/Button.h new file mode 100644 index 0000000..b2a665d --- /dev/null +++ b/include/GUI/Button.h @@ -0,0 +1,147 @@ +#ifndef GUI_BUTTON_H__ +#define GUI_BUTTON_H__ + +#include "GUI/TextureFrame.h" +#include "GUI/EButtonEnter.h" +#include "GUI/EButtonLeave.h" +#include "GUI/EButtonPress.h" +#include "GUI/EButtonRelease.h" +#include "Core/EMouseMove.h" +#include "Core/EMousePress.h" +#include "Core/EMouseRelease.h" + +namespace dd +{ +namespace GUI +{ + +class Button : public TextureFrame +{ +public: + Button(Frame* parent, std::string name) + : TextureFrame(parent, name) + { + EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &Button::OnMouseMove); + EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Button::OnMousePress); + EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Button::OnMouseRelease); + } + + void SetTextureHover(std::string resourceName) + { + m_TextureHover = resourceName; + } + void SetTextureReleased(std::string resourceName) + { + m_TextureReleased = resourceName; + SetTexture(resourceName); + } + void SetTexturePressed(std::string resourceName) + { + m_TexturePressed = resourceName; + } + + void Draw(RenderQueueCollection& rq) override + { + if (m_Texture == nullptr && !m_TextureReleased.empty()) { + SetTexture(m_TextureReleased); + } + + TextureFrame::Draw(rq); + } + + virtual void OnEnter() { } + virtual void OnLeave() { } + virtual void OnPress() { } + virtual void OnRelease() { } + +protected: + bool m_MouseIsOver = false; + bool m_IsDown = false; + + virtual bool OnMouseMove(const Events::MouseMove& event) + { + bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); + if (isOver && !m_MouseIsOver) { // Enter + if (!m_IsDown) { + if (!m_TextureHover.empty()) { + SetTexture(m_TextureHover); + } + } + OnEnter(); + Events::ButtonEnter e; + e.FrameName = m_Name; + EventBroker->Publish(e); + } else if (!isOver && m_MouseIsOver) { // Leave + if (!m_IsDown) { + if (!m_TextureReleased.empty()) { + SetTexture(m_TextureReleased); + } + } + OnLeave(); + Events::ButtonLeave e; + e.FrameName = m_Name; + EventBroker->Publish(e); + } + m_MouseIsOver = isOver; + + return true; + } + virtual bool OnMousePress(const Events::MousePress& event) + { + if (!Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1))) { + return false; + } + + if (!m_TexturePressed.empty()) { + SetTexture(m_TexturePressed); + } + + m_IsDown = true; + OnPress(); + Events::ButtonPress e; + e.FrameName = m_Name; + e.Button = this; + EventBroker->Publish(e); + + return true; + } + virtual bool OnMouseRelease(const Events::MouseRelease& event) + { + bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); + if (!isOver && !m_IsDown) { + return false; + } + + if (m_MouseIsOver) { + if (!m_TextureHover.empty()) { + SetTexture(m_TextureHover); + } + } else { + if (!m_TextureReleased.empty()) { + SetTexture(m_TextureReleased); + } + } + + m_IsDown = false; + OnRelease(); + Events::ButtonRelease e; + e.FrameName = m_Name; + e.Button = this; + EventBroker->Publish(e); + + return true; + } + +private: + EventRelay m_EMouseMove; + EventRelay m_EMousePress; + EventRelay m_EMouseRelease; + + std::string m_TextureHover; + std::string m_TexturePressed; + std::string m_TextureReleased; +}; + +} +} +#endif diff --git a/include/GUI/EButtonEnter.h b/include/GUI/EButtonEnter.h new file mode 100644 index 0000000..b2fa352 --- /dev/null +++ b/include/GUI/EButtonEnter.h @@ -0,0 +1,40 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#ifndef Events_ButtonEnter_h__ +#define Events_ButtonEnter_h__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace Events +{ + +/** Thrown on GUI button hover. */ +struct ButtonEnter : Event +{ + std::string FrameName; +}; + +} + +} + +#endif // Events_ButtonEnter_h__ \ No newline at end of file diff --git a/include/GUI/EButtonLeave.h b/include/GUI/EButtonLeave.h new file mode 100644 index 0000000..c448190 --- /dev/null +++ b/include/GUI/EButtonLeave.h @@ -0,0 +1,40 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#ifndef Events_ButtonLeave_h__ +#define Events_ButtonLeave_h__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace Events +{ + +/** Thrown on GUI button hover. */ +struct ButtonLeave : Event +{ + std::string FrameName; +}; + +} + +} + +#endif // Events_ButtonLeave_h__ \ No newline at end of file diff --git a/include/GUI/EButtonPress.h b/include/GUI/EButtonPress.h new file mode 100644 index 0000000..9e18ece --- /dev/null +++ b/include/GUI/EButtonPress.h @@ -0,0 +1,43 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#ifndef Events_ButtonPress_h__ +#define Events_ButtonPress_h__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace GUI { class Button; } + +namespace Events +{ + +/** Thrown on GUI button press. */ +struct ButtonPress : Event +{ + std::string FrameName; + GUI::Button* Button; +}; + +} + +} + +#endif // Events_ButtonPress_h__ \ No newline at end of file diff --git a/include/GUI/EButtonRelease.h b/include/GUI/EButtonRelease.h new file mode 100644 index 0000000..a596c61 --- /dev/null +++ b/include/GUI/EButtonRelease.h @@ -0,0 +1,43 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#ifndef Events_ButtonRelease_h__ +#define Events_ButtonRelease_h__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace GUI { class Button; } + +namespace Events +{ + +/** Thrown on GUI button release. */ +struct ButtonRelease : Event +{ + std::string FrameName; + GUI::Button* Button; +}; + +} + +} + +#endif // Events_ButtonRelease_h__ \ No newline at end of file diff --git a/include/GUI/ESliderUpdate.h b/include/GUI/ESliderUpdate.h new file mode 100644 index 0000000..b2f3c9b --- /dev/null +++ b/include/GUI/ESliderUpdate.h @@ -0,0 +1,45 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#ifndef Events_SliderUpdate_h__ +#define Events_SliderUpdate_h__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace GUI { class Slider; } + +namespace Events +{ + +/** Thrown when GUI slider is moved. */ +struct SliderUpdate : Event +{ + std::string FrameName; + GUI::Slider* Slider; + float Percentage; + float DeltaPercentage; +}; + +} + +} + +#endif // Events_SliderUpdate_h__ \ No newline at end of file diff --git a/include/GUI/Frame.h b/include/GUI/Frame.h new file mode 100644 index 0000000..f7e302c --- /dev/null +++ b/include/GUI/Frame.h @@ -0,0 +1,264 @@ +#ifndef GUI_Frame_h__ +#define GUI_Frame_h__ + +#include +#include + +#include "Core/Util/Rectangle.h" +#include "Core/EventBroker.h" +#include "Core/EKeyDown.h" +#include "Core/EKeyUp.h" +#include "Core/ResourceManager.h" +#include "Core/Renderer.h" +#include "Core/RenderQueue.h" +#include "Core/Texture.h" +#include "Input/EInputCommand.h" + +namespace dd +{ +namespace GUI +{ + +class Frame : public Rectangle +{ +public: + enum class Anchor + { + Left, + Right, + Top, + Bottom + }; + + static const int BaseWidth = 1280; + static const int BaseHeight = 720; + + // Set up a base frame with an event broker + Frame(dd::EventBroker* eventBroker) + : EventBroker(eventBroker) + , BaseFrame(this) + , Rectangle() { } + + // Create a frame as a child + Frame(Frame* parent, std::string name) + : m_Name(name) + { + SetParent(parent); + EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Frame::OnKeyDown); + EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Frame::OnKeyUp); + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Frame::OnCommand); + } + + ~Frame() + { + /*for (auto layer : m_Children) + { + for (auto child : layer.second) + { + delete child.second; + } + } + + if (m_Parent) + { + m_Parent->RemoveChild(this); + }*/ + } + + Frame* Parent() const { return m_Parent; } + + void SetParent(Frame* parent) + { + if (parent == nullptr) { + LOG_ERROR("Failed to parent frame \"%s\": Invalid parent", m_Name.c_str()); + return; + } + + m_Layer = parent->Layer() + 1; + parent->AddChild(this); + m_Parent = parent; + EventBroker = parent->EventBroker; + BaseFrame = parent->BaseFrame; + } + + void AddChild(Frame* child) + { + m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child)); + if (m_Parent) { + m_Parent->AddChild(child); + } + } + + void RemoveChild(Frame* child) + { + auto it = m_Children.find(child->m_Layer); + if (it != m_Children.end()) { + m_Children.erase(it); + } + + if (m_Parent) { + m_Parent->RemoveChild(child); + } + } + + std::string Name() const { return m_Name; } + void SetName(std::string val) { m_Name = val; } + + int Layer() const { return m_Layer; } + + bool Hidden() const + { + if (m_Parent) + return m_Parent->Hidden() || m_Hidden; + else + return m_Hidden; + } + bool Visible() const + { + return !Hidden(); + } + + virtual void Hide() { m_Hidden = true; } + virtual void Show() { m_Hidden = false; } + + int Left() const override + { + if (m_Parent) + return m_Parent->Left() + X; + else + return X; + } + void SetLeft(int absLeft) override + { + if (m_Parent) { + X = absLeft - m_Parent->Left(); + } else { + X = absLeft; + } + } + int Right() const override + { + return Left() + Width; + } + void SetRight(int absRight) override + { + if (m_Parent) { + X = absRight - Width - m_Parent->Left(); + } else { + X = absRight - Width; + } + } + int Top() const override + { + if (m_Parent) + return m_Parent->Top() + Y; + else + return Y; + } + void SetTop(int absTop) override + { + if (m_Parent) { + Y = absTop - m_Parent->Top(); + } else { + Y = absTop; + } + } + int Bottom() const override + { + return Top() + Height; + } + void SetBottom(int absBottom) override + { + if (m_Parent) { + Y = absBottom - Height - m_Parent->Top(); + } else { + Y = absBottom - Height; + } + } + + glm::vec2 Scale() + { + if (m_Parent) + return m_Parent->Scale(); + else + return glm::vec2(Width, Height) / glm::vec2(BaseWidth, BaseHeight); + } + + Rectangle AbsoluteRectangle() + { + int left = Left(); + if (m_Parent) + left = std::max(left, m_Parent->Left()); + int top = Top(); + if (m_Parent) + top = std::max(top, m_Parent->Top()); + int width = Right() - left; + int height = Bottom() - top; + return Rectangle(left, top, width, height); + } + + void UpdateLayered(double dt) + { + // Update ourselves + this->Update(dt); + + // Update children + for (auto& pairLayer : m_Children) { + auto children = pairLayer.second; + for (auto& pairChild : children) { + auto child = pairChild.second; + child->Update(dt); + } + } + } + + virtual void Update(double dt) { } + + void DrawLayered(RenderQueueCollection& rq) + { + if (this->Hidden()) + return; + + // Draw ourselves + this->Draw(rq); + + // Draw children + for (auto& pairLayer : m_Children) { + auto children = pairLayer.second; + for (auto& pairChild : children) { + auto child = pairChild.second; + if (child->Hidden()) + continue; + child->Draw(rq); + } + } + } + + virtual void Draw(RenderQueueCollection& rq) { } + +protected: + dd::EventBroker* EventBroker; + Frame* BaseFrame = nullptr; + + std::string m_Name = "UIParent"; + int m_Layer = 0; + bool m_Hidden = false; + + Frame* m_Parent = nullptr; + typedef std::multimap Children_t; // name -> frame + std::map m_Children; // layer -> Children_t + + virtual bool OnKeyDown(const Events::KeyDown& event) { return false; } + virtual bool OnKeyUp(const Events::KeyUp& event) { return false; } + virtual bool OnCommand(const Events::InputCommand& event) { return false; } + +private: + EventRelay m_EKeyDown; + EventRelay m_EKeyUp; + EventRelay m_EInputCommand; +}; + +} +} + +#endif // GUI_Frame_h__ diff --git a/include/GUI/Slider.h b/include/GUI/Slider.h new file mode 100644 index 0000000..de53245 --- /dev/null +++ b/include/GUI/Slider.h @@ -0,0 +1,124 @@ +#ifndef GUI_SLIDER_H__ +#define GUI_SLIDER_H__ + +#include "GUI/TextureFrame.h" +#include "GUI/Button.h" +#include "GUI/EButtonPress.h" +#include "GUI/EButtonRelease.h" +#include "GUI/ESliderUpdate.h" +#include "Core/EMouseMove.h" + +namespace dd +{ +namespace GUI +{ + +class Slider : public TextureFrame +{ +public: + Slider(Frame* parent, std::string name) + : TextureFrame(parent, name) + { + m_SliderButton = new GUI::Button(this, "SliderButton"); + m_SliderButton->DisableScissor(); + + EVENT_SUBSCRIBE_MEMBER(m_EButtonPress, &Slider::OnButtonPress); + EVENT_SUBSCRIBE_MEMBER(m_EButtonRelease, &Slider::OnButtonRelease); + EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &Slider::OnMouseMove); + } + + float Percentage() const { return m_Percentage; } + void SetPercentage(const float percentage) + { + m_Percentage = percentage; + m_SliderButton->X = percentage * (Width - m_SliderButton->Width); + } + + void SetTextureHover(std::string resourceName) + { + m_SliderButton->SetTextureHover(resourceName); + } + void SetTextureReleased(std::string resourceName) + { + m_SliderButton->SetTextureReleased(resourceName); + } + void SetTexturePressed(std::string resourceName) + { + m_SliderButton->SetTexturePressed(resourceName); + } + + void AlignVertically() + { + m_SliderButton->Y = (Height / 2) - (m_SliderButton->Height / 2); + } + + ~Slider() + { + if (m_SliderButton != nullptr) { + delete m_SliderButton; + m_SliderButton = nullptr; + } + } + + virtual void Update(double dt) override + { + + } + +private: + Button* m_SliderButton = nullptr; + bool m_IsGrabbed = false; + float m_Percentage = 0.f; + + EventRelay m_EButtonPress; + EventRelay m_EButtonRelease; + EventRelay m_EMouseMove; + + virtual bool OnButtonPress(const Events::ButtonPress& event) + { + if (event.Button == m_SliderButton) { + m_IsGrabbed = true; + } + + return true; + } + + virtual bool OnButtonRelease(const Events::ButtonRelease& event) + { + if (event.Button == m_SliderButton) { + m_IsGrabbed = false; + } + + return true; + } + + virtual bool OnMouseMove(const Events::MouseMove& event) + { + if (m_IsGrabbed) { + // Set horizontal position + m_SliderButton->X += event.DeltaX; + if (m_SliderButton->Left() < Left()) { + m_SliderButton->SetLeft(Left()); + } else if (m_SliderButton->Right() > Right()) { + m_SliderButton->SetRight(Right()); + } + + // Update percentage + float newPercentage = m_SliderButton->X / (float)(Width - m_SliderButton->Width); + Events::SliderUpdate e; + e.FrameName = Name(); + e.Slider = this; + e.Percentage = newPercentage; + e.DeltaPercentage = newPercentage - m_Percentage; + EventBroker->Publish(e); + m_Percentage = newPercentage; + } + + return true; + } +}; + +} +} +#endif + diff --git a/include/GUI/TextureFrame.h b/include/GUI/TextureFrame.h new file mode 100644 index 0000000..0b2bb98 --- /dev/null +++ b/include/GUI/TextureFrame.h @@ -0,0 +1,106 @@ +#ifndef GUI_TextureFrame_h__ +#define GUI_TextureFrame_h__ + +#include "GUI/Frame.h" +#include "Core/Texture.h" + +namespace dd +{ +namespace GUI +{ + +class TextureFrame : public Frame +{ +public: + TextureFrame(Frame* parent, std::string name) + : Frame(parent, name) { } + + void EnableScissor() { m_ScissorEnabled = true; } + void DisableScissor() { m_ScissorEnabled = false; } + + void Draw(RenderQueueCollection& rq) override + { + if (m_Texture == nullptr) + return; + + // Main texture + { + FrameJob job; + job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); + job.Viewport = Rectangle(Left(), Top(), Width, Height); + job.TextureID = m_Texture->ResourceID; + job.DiffuseTexture = *m_Texture; + job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a * m_CurrentFade); + job.Name = Name(); + rq.GUI.Add(job); + } + + // Texture while fading + if (m_FadeTexture && m_CurrentFade < 1) { + FrameJob job; + job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); + job.Viewport = Rectangle(Left(), Top(), Width, Height); + job.TextureID = m_FadeTexture->ResourceID; + job.DiffuseTexture = *m_FadeTexture; + job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a); + job.Name = Name(); + rq.GUI.Add(job); + } + } + + dd::Texture* Texture() const { return m_Texture; } + + void SetTexture(std::string resourceName) + { + m_Texture = ResourceManager::Load(resourceName); + if (m_Texture == nullptr) { + m_Texture = ResourceManager::Load("Textures/Core/ErrorTexture.png"); + } + SizeToTexture(); + } + + void SizeToTexture() + { + if (m_Texture != nullptr) { + this->Width = m_Texture->Width; + this->Height = m_Texture->Height; + } + } + + void FadeToTexture(std::string resourceName, double duration) + { + m_FadeTexture = m_Texture; + SetTexture(resourceName); + m_FadeDuration = duration; + m_CurrentFade = 0.f; + } + + void Update(double dt) override + { + if (m_CurrentFade < 1) { + m_CurrentFade += dt / m_FadeDuration; + if (m_CurrentFade > 1) { + m_FadeTexture = nullptr; + m_CurrentFade = 1; + m_FadeDuration = 0; + } + } + } + + glm::vec4 Color() const { return m_Color; } + void SetColor(glm::vec4 val) { m_Color = val; } + +protected: + bool m_ScissorEnabled = true; + dd::Texture* m_Texture = nullptr; + dd::Texture* m_FadeTexture = nullptr; + glm::vec4 m_Color = glm::vec4(1.f, 1.f, 1.f, 1.f); + float m_FadeDuration = 0.f; + float m_CurrentFade = 1.f; + +}; + +} +} + +#endif // GUI_TextureFrame_h__ diff --git a/include/Game/EGameStart.h b/include/Game/EGameStart.h new file mode 100644 index 0000000..bfee0fd --- /dev/null +++ b/include/Game/EGameStart.h @@ -0,0 +1,25 @@ +// +// Created by Adam on 2015-09-25. +// + +#ifndef EVENTS_EGAMESTART_H__ +#define EVENTS_EGAMESTART_H__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace Events +{ + +struct GameStart : public Event +{ + +}; + +} + +} + +#endif diff --git a/include/Game/HUD.h b/include/Game/HUD.h new file mode 100644 index 0000000..e660a9e --- /dev/null +++ b/include/Game/HUD.h @@ -0,0 +1,37 @@ +#ifndef GUI_HUD_H__ +#define GUI_HUD_H__ + +#include "GUI/Frame.h" +#include "GUI/TextureFrame.h" + +namespace dd +{ +namespace GUI +{ + +class HUD : public Frame +{ +public: + HUD(Frame* parent, std::string name) + : Frame(parent, name) + { + Width = parent->Width; + Height = parent->Height; + + m_LevelIndicator = new GUI::TextureFrame(this, "HUDLevelIndicator"); + m_LevelIndicator->SetTexture("Textures/GUI/HUD/LevelIndicatorBG.png"); + + m_ScoreIndicator = new GUI::TextureFrame(this, "HUDScoreIndicator"); + m_ScoreIndicator->SetTexture("Textures/GUI/HUD/ScoreIndicatorBG.png"); + m_ScoreIndicator->SetRight(Right()); + } + +private: + TextureFrame* m_LevelIndicator = nullptr; + TextureFrame* m_ScoreIndicator = nullptr; +}; + +} +} +#endif + diff --git a/include/Game/LevelSystem.h b/include/Game/LevelSystem.h index f7f9170..545d2fb 100755 --- a/include/Game/LevelSystem.h +++ b/include/Game/LevelSystem.h @@ -19,12 +19,12 @@ #include "Game/ELifeLost.h" #include "Game/EResetBall.h" #include "Game/EScoreEvent.h" +#include "Physics/CRectangleShape.h" #include "Game/EMultiBall.h" #include "Game/EGameOver.h" #include "Game/ECreatePowerUp.h" #include "Game/EPowerUpTaken.h" #include "Game/Bricks/CPowerUpBrick.h" -#include "Physics/CBoxShape.h" #include "Physics/CPhysics.h" #include "Physics/CCircleShape.h" #include "Physics/ESetImpulse.h" diff --git a/include/Game/MainMenu.h b/include/Game/MainMenu.h new file mode 100644 index 0000000..a9afe4c --- /dev/null +++ b/include/Game/MainMenu.h @@ -0,0 +1,59 @@ +#ifndef GUI_MAINMENU_H__ +#define GUI_MAINMENU_H__ + +#include "GUI/TextureFrame.h" +#include "Game/MainMenuMain.h" +#include "Game/MainMenuOptions.h" +#include "Core/EKeyUp.h" + +namespace dd +{ +namespace GUI +{ + +class MainMenu : public TextureFrame +{ +public: + MainMenu(Frame* parent, std::string name) + : TextureFrame(parent, name) + { + SetTexture("Textures/GUI/Menu/Background.png"); + Width = 675; + Height = 1080; + + m_LeftBanner = new GUI::TextureFrame(this, "MainMenuLeftBanner"); + m_LeftBanner->SetTexture("Textures/GUI/Menu/Left.png"); + m_LeftBanner->Width = 231; + m_LeftBanner->Height = 1080; + + m_MainMenuMain = new GUI::MainMenuMain(this, "MainMenuMain"); + m_MainMenuMain->SetLeft(m_LeftBanner->Right()); + m_MainMenuMain->SetTop(60); + + m_MainMenuOptions = new GUI::MainMenuOptions(this, "MainMenuOptions"); + m_MainMenuOptions->SetLeft(m_LeftBanner->Right()); + m_MainMenuOptions->SetTop(m_MainMenuMain->Bottom()); + + EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &MainMenu::OnKeyUp); + } + +private: + TextureFrame* m_LeftBanner; + MainMenuMain* m_MainMenuMain; + MainMenuOptions* m_MainMenuOptions; + + EventRelay m_EKeyUp; + bool OnKeyUp(const Events::KeyUp& event) + { + if (event.KeyCode == GLFW_KEY_ESCAPE) { + Show(); + } + + return true; + } +}; + +} +} +#endif + diff --git a/include/Game/MainMenuMain.h b/include/Game/MainMenuMain.h new file mode 100644 index 0000000..24296ed --- /dev/null +++ b/include/Game/MainMenuMain.h @@ -0,0 +1,70 @@ +#ifndef GUI_MAINMENUMAIN_H__ +#define GUI_MAINMENUMAIN_H__ + +#include "GUI/TextureFrame.h" +#include "GUI/Button.h" +#include "Game/EGameStart.h" + +namespace dd +{ +namespace GUI +{ + +class MainMenuMain : public TextureFrame +{ +public: + MainMenuMain(Frame* parent, std::string name) + : TextureFrame(parent, name) + { + Width = 409; + Height = 543; + + m_Title = new GUI::TextureFrame(this, "MainMenuMainTitle"); + m_Title->SetTexture("Textures/GUI/Menu/MainTitle.png"); + + m_SquidoutButton = new GUI::Button(this, "MainMenuMainSquidoutButton"); + m_SquidoutButton->SetTop(m_Title->Bottom()); + m_SquidoutButton->SetTextureReleased("Textures/GUI/Menu/MainSquidout.png"); + m_SquidoutButton->SetTextureHover("Textures/GUI/Menu/MainSquidoutHover.png"); + m_SquidoutButton->SetTexturePressed("Textures/GUI/Menu/MainSquidoutClick.png"); + m_SquidoutButton->SizeToTexture(); + + m_TimeAttackButton = new GUI::Button(this, "MainMenuMainTimeAttackButton"); + m_TimeAttackButton->SetTop(m_SquidoutButton->Bottom()); + m_TimeAttackButton->SetTextureReleased("Textures/GUI/Menu/MainTimeAttack.png"); + m_TimeAttackButton->SetTextureHover("Textures/GUI/Menu/MainTimeAttackHover.png"); + m_TimeAttackButton->SetTexturePressed("Textures/GUI/Menu/MainTimeAttackClick.png"); + m_TimeAttackButton->SizeToTexture(); + + m_OptionsButton = new GUI::Button(this, "MainMenuMainOptionsButton"); + m_OptionsButton->SetTop(m_TimeAttackButton->Bottom()); + m_OptionsButton->SetTextureReleased("Textures/GUI/Menu/MainOptions.png"); + m_OptionsButton->SetTextureHover("Textures/GUI/Menu/MainOptionsHover.png"); + m_OptionsButton->SetTexturePressed("Textures/GUI/Menu/MainOptionsClick.png"); + m_OptionsButton->SizeToTexture(); + + EVENT_SUBSCRIBE_MEMBER(m_EButtonRelease, &MainMenuMain::OnButtonRelease); + } + +private: + TextureFrame* m_Title; + Button* m_SquidoutButton; + Button* m_TimeAttackButton; + Button* m_OptionsButton; + + EventRelay m_EButtonRelease; + virtual bool OnButtonRelease(const Events::ButtonRelease& event) + { + if (event.Button == m_SquidoutButton) { + Events::GameStart e; + EventBroker->Publish(e); + m_Parent->Hide(); + } + + return true; + } +}; + +} +} +#endif diff --git a/include/Game/MainMenuOptions.h b/include/Game/MainMenuOptions.h new file mode 100644 index 0000000..476fa4a --- /dev/null +++ b/include/Game/MainMenuOptions.h @@ -0,0 +1,82 @@ +#ifndef GUI_MAINMENUOPTIONS_H__ +#define GUI_MAINMENUOPTIONS_H__ + +#include "GUI/TextureFrame.h" +#include "GUI/Button.h" +#include "GUI/Slider.h" +#include "GUI/ESliderUpdate.h" +#include "Sound/EMasterVolume.h" + +namespace dd +{ +namespace GUI +{ + +class MainMenuOptions : public TextureFrame +{ +public: + MainMenuOptions(Frame* parent, std::string name) + : TextureFrame(parent, name) + { + Width = 409; + Height = 1080; + + m_Title = new GUI::TextureFrame(this, "MainMenuOptionsTitle"); + m_Title->SetTexture("Textures/GUI/Menu/OptionsTitle.png"); + + m_TitleSFX = new GUI::TextureFrame(this, "MainMenuOptionsSFXTitle"); + m_TitleSFX->SetTop(m_Title->Bottom() + 20); + m_TitleSFX->SetTexture("Textures/GUI/Menu/OptionsSFXTitle.png"); + m_SFXSlider = new GUI::Slider(this, "MainMenuOptionsSFXSlider"); + m_SFXSlider->X = 66; + m_SFXSlider->SetTop(m_TitleSFX->Bottom() + 10); + m_SFXSlider->SetTexture("Textures/GUI/Menu/SliderBackground.png"); + m_SFXSlider->SetTextureReleased("Textures/GUI/Menu/SliderHandle.png"); + m_SFXSlider->AlignVertically(); + m_SFXSlider->SetPercentage(1.f); + + m_TitleBGM = new GUI::TextureFrame(this, "MainMenuOptionsBGMTitle"); + m_TitleBGM->SetTop(m_SFXSlider->Bottom() + 20); + m_TitleBGM->SetTexture("Textures/GUI/Menu/OptionsBGMTitle.png"); + m_BGMSlider = new GUI::Slider(this, "MainMenuOptionsBGMSlider"); + m_BGMSlider->X = 66; + m_BGMSlider->SetTop(m_TitleBGM->Bottom() + 10); + m_BGMSlider->SetTexture("Textures/GUI/Menu/SliderBackground.png"); + m_BGMSlider->SetTextureReleased("Textures/GUI/Menu/SliderHandle.png"); + m_BGMSlider->AlignVertically(); + m_BGMSlider->SetPercentage(1.f); + + EVENT_SUBSCRIBE_MEMBER(m_ESliderUpdate, &MainMenuOptions::OnSliderUpdate); + } + +private: + TextureFrame* m_Title = nullptr; + TextureFrame* m_TitleSFX = nullptr; + Slider* m_SFXSlider = nullptr; + Slider* m_BGMSlider = nullptr; + TextureFrame* m_TitleBGM = nullptr; + + EventRelay m_ESliderUpdate; + bool OnSliderUpdate(const Events::SliderUpdate& event) + { + if (event.Slider == m_SFXSlider) { + Events::MasterVolume e; + e.isAmbient = false; + e.gain = event.Percentage; + EventBroker->Publish(e); + } + + if (event.Slider == m_BGMSlider) { + Events::MasterVolume e; + e.isAmbient = true; + e.gain = event.Percentage; + EventBroker->Publish(e); + } + + return true; + } +}; + +} +} +#endif diff --git a/include/Game/PadSystem.h b/include/Game/PadSystem.h index a4e5f9e..4a53907 100755 --- a/include/Game/PadSystem.h +++ b/include/Game/PadSystem.h @@ -14,7 +14,7 @@ #include "Core/EKeyUp.h" #include "Input/EBindKey.h" #include "Physics/EContact.h" -#include "Physics/CBoxShape.h" +#include "Physics/CRectangleShape.h" #include "Physics/CPhysics.h" #include "Physics/CCircleShape.h" #include "Physics/ESetImpulse.h" diff --git a/include/Physics/CBoxShape.h b/include/Physics/CRectangleShape.h similarity index 100% rename from include/Physics/CBoxShape.h rename to include/Physics/CRectangleShape.h diff --git a/include/Physics/CWaterVolume.h b/include/Physics/CWaterVolume.h new file mode 100755 index 0000000..33adcae --- /dev/null +++ b/include/Physics/CWaterVolume.h @@ -0,0 +1,19 @@ +#ifndef CWATERVOLUME_H +#define CWATERVOLUME_H +#include "Core/Component.h" + +namespace dd +{ +namespace Components +{ + +struct WaterVolume : public Component +{ + +}; + +} + +} + +#endif \ No newline at end of file diff --git a/include/Physics/PhysicsSystem.h b/include/Physics/PhysicsSystem.h index 0ce8ab7..eaaf49e 100644 --- a/include/Physics/PhysicsSystem.h +++ b/include/Physics/PhysicsSystem.h @@ -5,7 +5,7 @@ #include "Core/System.h" #include "Core/World.h" -#include "Physics/CBoxShape.h" +#include "CRectangleShape.h" #include "Physics/CPhysics.h" #include #include "Core/CTransform.h" @@ -15,7 +15,9 @@ #include "Physics/CCircleShape.h" #include "Core/EventBroker.h" #include "Game/CPad.h" +#include "Physics/CWaterVolume.h" #include "Game/CBall.h" +#include "Rendering/CSprite.h" namespace dd @@ -65,6 +67,15 @@ private: void CreateBody(EntityID entity); + b2ParticleSystem *m_ParticleSystem; + b2ParticleGroup* t_watergroup; + + std::unordered_map m_EntitiesToParticleHandle; + std::unordered_map m_ParticleHandleToEntities; + + void InitializeWater(); + void SyncWater(); //TODO: Probably remove this + void CreateParticleGroup(EntityID entity); struct Impulse { diff --git a/include/Physics/PhysicsSystem.h.orig b/include/Physics/PhysicsSystem.h.orig new file mode 100755 index 0000000..f1465aa --- /dev/null +++ b/include/Physics/PhysicsSystem.h.orig @@ -0,0 +1,149 @@ +#ifndef DAYDREAM_PHYSICSSYSTEM_H +#define DAYDREAM_PHYSICSSYSTEM_H + +#include + +#include "Core/System.h" +#include "Core/World.h" +#include "CRectangleShape.h" +#include "Physics/CPhysics.h" +#include +#include "Core/CTransform.h" +#include "Transform/TransformSystem.h" +#include "Physics/EContact.h" +#include "Physics/ESetImpulse.h" +#include "Physics/CCircleShape.h" +#include "Core/EventBroker.h" +#include "Game/CPad.h" +<<<<<<< HEAD +#include "Game/CBall.h" +======= +#include "Physics/CWaterVolume.h" +#include "Rendering/CSprite.h" +>>>>>>> origin/master + + +namespace dd +{ + +namespace Systems +{ + + +class PhysicsSystem : public System +{ + friend class ContractListener; + +public: + PhysicsSystem(World* world, std::shared_ptr eventBroker) + : System(world, eventBroker) {} + + ~PhysicsSystem(); + + EventRelay m_SetImpulse; + bool SetImpulse(const Events::SetImpulse &event); + + void RegisterComponents(ComponentFactory* cf) override; + void Initialize() override; + + // Called once per system every tick + void Update(double dt) override; + // Called once for every entity in the world every tick + void UpdateEntity(double dt, EntityID entity, EntityID parent) override; + + // Called when components are committed to an entity + void OnEntityCommit(EntityID entity) override; + + // Called when an entity is removed + void OnEntityRemoved(EntityID entity) override; + +private: + b2Vec2 m_Gravity; + b2World* m_PhysicsWorld; + float m_TimeStep; + float m_Accumulator; + + int m_VelocityIterations, m_PositionIterations; + + std::unordered_map m_EntitiesToBodies; + std::unordered_map m_BodiesToEntities; + + void CreateBody(EntityID entity); + + b2ParticleSystem *m_ParticleSystem; + b2ParticleGroup* t_watergroup; + + std::unordered_map m_EntitiesToParticleHandle; + std::unordered_map m_ParticleHandleToEntities; + + void InitializeWater(); + void SyncWater(); //TODO: Probably remove this + void CreateParticleGroup(EntityID entity); + + struct Impulse + { + b2Body* Body; + b2Vec2 Impulse; + b2Vec2 Point; + }; + std::list m_Impulses; + + + + class ContactListener : public b2ContactListener + { + public: + ContactListener(PhysicsSystem* physicsSystem) + : m_PhysicsSystem(physicsSystem) { } + + void BeginContact(b2Contact* contact) + { + b2WorldManifold worldManifold; + + contact->GetWorldManifold(&worldManifold); + + Events::Contact e; + e.Entity1 = m_PhysicsSystem->m_BodiesToEntities[contact->GetFixtureA()->GetBody()]; + e.Entity2 = m_PhysicsSystem->m_BodiesToEntities[contact->GetFixtureB()->GetBody()]; + e.Normal = glm::normalize(glm::vec2(contact->GetManifold()->localNormal.x, contact->GetManifold()->localNormal.y)); + e.SignificantNormal = glm::normalize((glm::abs(e.Normal.x) > glm::abs(e.Normal.y)) ? glm::vec2(e.Normal.x, 0) : glm::vec2(0, e.Normal.y)); + + m_PhysicsSystem->EventBroker->Publish(e); + } + void EndContact(b2Contact* contact) + { + + } + void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) + { + EntityID entityA = m_PhysicsSystem->m_BodiesToEntities[contact->GetFixtureA()->GetBody()]; + EntityID entityB = m_PhysicsSystem->m_BodiesToEntities[contact->GetFixtureB()->GetBody()]; + + auto physicsComponentA = m_PhysicsSystem->m_World->GetComponent(entityA); + auto physicsComponentB = m_PhysicsSystem->m_World->GetComponent(entityB); + + if (physicsComponentA != nullptr && physicsComponentB != nullptr) { + if (physicsComponentA->Calculate || physicsComponentB->Calculate) { + // Turn of collisions + contact->SetEnabled(false); + } + } + + + } + void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) + { + + } + + private: + PhysicsSystem* m_PhysicsSystem; + }; + + ContactListener* m_ContactListener; +}; + +} +} + +#endif //DAYDREAM_PHYSICSSYSTEM_H diff --git a/include/Sound/EMasterVolume.h b/include/Sound/EMasterVolume.h new file mode 100644 index 0000000..3f95e6d --- /dev/null +++ b/include/Sound/EMasterVolume.h @@ -0,0 +1,27 @@ +// +// Created by Adam on 2015-09-24. +// + +#ifndef EVENTS_EMASTERVOLUME_H__ +#define EVENTS_EMASTERVOLUME_H__ + +#include "Core/EventBroker.h" + +namespace dd +{ + +namespace Events +{ + +struct MasterVolume : public Event +{ + float gain = 1; + //To determine what channel group to apply the change to. + bool isAmbient = false; +}; + +} + +} + +#endif diff --git a/include/Sound/EPlaySound.h b/include/Sound/EPlaySound.h index ee51df0..a66300d 100644 --- a/include/Sound/EPlaySound.h +++ b/include/Sound/EPlaySound.h @@ -14,7 +14,7 @@ struct PlaySound : Event std::string path; float volume = 1.f; float pitch = 1.f; - bool loop = false; + bool isAmbient = false; }; } diff --git a/include/Sound/SoundSystem.h b/include/Sound/SoundSystem.h index af70ed6..32dd05e 100644 --- a/include/Sound/SoundSystem.h +++ b/include/Sound/SoundSystem.h @@ -10,6 +10,7 @@ #include "Sound.h" #include "Sound/EPlaySound.h" #include "Sound/EStopSound.h" +#include "Sound/EMasterVolume.h" #include "Physics/EContact.h" #include "Game/CBall.h" #include "Game/CBrick.h" @@ -38,17 +39,20 @@ private: dd::EventRelay m_EPlaySFX; dd::EventRelay m_EContact; dd::EventRelay m_EStopSound; + dd::EventRelay m_EMasterVolume; bool OnPlaySound(const dd::Events::PlaySound &event); bool OnContact(const dd::Events::Contact &event); bool OnStopSound(const dd::Events::StopSound &event); + bool OnMasterVolume(const dd::Events::MasterVolume &event); ALuint CreateSource(); - std::map m_SourcesToBuffers; + std::map m_BGMSourcesToBuffers; + std::map m_SFXSourcesToBuffers; ALCdevice* m_Device; - //Temp + float m_BGMMasterVolume, m_SFXMasterVolume; }; } diff --git a/src/game/CMakeLists.txt b/src/game/CMakeLists.txt index a63eb23..6834897 100755 --- a/src/game/CMakeLists.txt +++ b/src/game/CMakeLists.txt @@ -79,6 +79,12 @@ file(GLOB SOURCE_FILES_Sound ) source_group(Sound FILES ${SOURCE_FILES_Sound}) +file(GLOB SOURCE_FILES_GUI + "${INCLUDE_PATH}/GUI/*.h" + "GUI/*.cpp" +) +source_group(GUI FILES ${SOURCE_FILES_GUI}) + set(SOURCE_FILES ${SOURCE_FILES_Core} ${SOURCE_FILES_Core_Util} @@ -87,11 +93,14 @@ set(SOURCE_FILES ${SOURCE_FILES_Transform} ${SOURCE_FILES_Physics} ${SOURCE_FILES_Game} - ${SOURCE_FILES_Sound} ../../include/Game/EGameOver.h ../../include/Game/Bricks/CPowerUpBrick.h ../../include/Game/CPowerUp.h ../../include/Game/ECreatePowerUp.h ../../include/Game/EPowerUpTaken.h) + ${SOURCE_FILES_Sound} + ${SOURCE_FILES_GUI} +) if(CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") - set(STATIC_LIBRARY_FLAGS "${STATIC_LIBRARY_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -w") + set(STATIC_LIBRARY_FLAGS "${STATIC_LIBRARY_FLAGS}") endif() add_library(game ${SOURCE_FILES}) diff --git a/src/game/CMakeLists.txt.game b/src/game/CMakeLists.txt.game deleted file mode 100644 index 5e236f1..0000000 --- a/src/game/CMakeLists.txt.game +++ /dev/null @@ -1,38 +0,0 @@ -project(game) - -find_package(OpenGL REQUIRED) -find_package(GLEW REQUIRED) -find_package(GLFW REQUIRED) -find_package(Boost REQUIRED) -find_package(assimp REQUIRED) -find_package(ZLIB REQUIRED) -find_package(PNG REQUIRED) - -include_directories( - ${CMAKE_SOURCE_DIR}/include/dd - ${OPENGL_INCLUDE_DIR} - ${GLEW_INCLUDE_DIRS} - ${GLFW_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS} - ${assimp_INCLUDE_DIRS} - ${PNG_INCLUDE_DIRS} -) - -set(SOURCE_FILES - main.cpp -) - -if(CMAKE_COMPILER_IS_GNUCXX) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") -endif() - -add_executable(game ${SOURCE_FILES}) -target_link_libraries(game - daydream - ${OPENGL_LIBRARIES} - ${GLEW_LIBRARIES} - ${GLFW_LIBRARIES} - ${Boost_LIBRARIES} - ${assimp_LIBRARIES} - ${PNG_LIBRARIES} -) \ No newline at end of file diff --git a/src/game/Core/EventBroker.cpp b/src/game/Core/EventBroker.cpp index f24b073..2c68fd0 100644 --- a/src/game/Core/EventBroker.cpp +++ b/src/game/Core/EventBroker.cpp @@ -79,7 +79,7 @@ int dd::EventBroker::Process(std::string contextTypeName) return eventsProcessed; } -void dd::EventBroker::Clear() +void dd::EventBroker::Swap() { std::swap(m_EventQueueRead, m_EventQueueWrite); m_EventQueueWrite->clear(); diff --git a/src/game/Core/Renderer.cpp b/src/game/Core/Renderer.cpp index 6534db1..2226ba2 100755 --- a/src/game/Core/Renderer.cpp +++ b/src/game/Core/Renderer.cpp @@ -91,6 +91,12 @@ void dd::Renderer::LoadShaders() //glBindFragDataLocation(m_SPDeferred2, 0, "FragmentLighting"); m_spDeferred2->Link(); + //Water Pass + t_m_spWater = ResourceManager::Load("Shaders/Deferred/water/"); + t_m_spWater->Link(); + t_m_spWater2 = ResourceManager::Load("Shaders/Deferred/water2/"); + t_m_spWater2->Link(); + // Pass #3: Combining into final image m_spDeferred3 = ResourceManager::Load("Shaders/Deferred/3/"); m_spDeferred3->Link(); @@ -110,11 +116,13 @@ void dd::Renderer::LoadShaders() void dd::Renderer::CreateBuffers() { + //TODO: Make the most common cases of texture create and FBO create into a function so it's not so cluttered in here. m_ScreenQuad = CreateQuad(); m_UnitQuad = ResourceManager::Load("Models/Core/UnitQuad.obj"); m_UnitSphere = ResourceManager::Load("Models/Core/UnitSphere.obj"); m_StandardNormal = ResourceManager::Load("Textures/Core/NeutralNormalMap.png"); m_StandardSpecular = ResourceManager::Load("Textures/Core/NeutralSpecularMap.png"); + t_m_WhiteSphereTexture = ResourceManager::Load("Textures/Test/Water.png"); glGenRenderbuffers(1, &m_rbDepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_rbDepthBuffer); @@ -149,6 +157,13 @@ void dd::Renderer::CreateBuffers() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glGenTextures(1, &t_m_Gwater); + glBindTexture(GL_TEXTURE_2D, t_m_Gwater); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, m_Resolution.Width, m_Resolution.Height, 0, GL_RGBA, GL_FLOAT, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Create first pass framebuffer glGenFramebuffers(1, &m_fbDeferred1); @@ -185,14 +200,75 @@ void dd::Renderer::CreateBuffers() exit(EXIT_FAILURE); } + //Fill Water Texture + glGenTextures(1, &t_m_Gwater); + glBindTexture(GL_TEXTURE_2D, t_m_Gwater); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Resolution.Width, m_Resolution.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + //Fill water pass + glGenFramebuffers(1, &t_m_fbWater); + glBindFramebuffer(GL_FRAMEBUFFER, t_m_fbWater); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t_m_Gwater, 0); + GLenum waterPassDrawBuffers[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, waterPassDrawBuffers); + if (GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + LOG_ERROR("m_fbDeferred2 incomplete: 0x%x\n", fbStatus); + exit(EXIT_FAILURE); + } + + //water Blur texture + glGenTextures(1, &t_m_BWater); + glBindTexture(GL_TEXTURE_2D, t_m_BWater); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Resolution.Width, m_Resolution.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + //Fill waterBlur pass + glGenFramebuffers(1, &t_m_fbWaterBlur); + glBindFramebuffer(GL_FRAMEBUFFER, t_m_fbWaterBlur); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t_m_BWater, 0); + GLenum waterBlurDrawBuffers[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, waterBlurDrawBuffers); + if (GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + LOG_ERROR("m_fbDeferred2 incomplete: 0x%x\n", fbStatus); + exit(EXIT_FAILURE); + } + + //water Blur texture2 + glGenTextures(1, &t_m_BWater2); + glBindTexture(GL_TEXTURE_2D, t_m_BWater2); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_rbDepthBuffer); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Resolution.Width, m_Resolution.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + //Fill waterBlur pass2 + glGenFramebuffers(1, &t_m_fbWaterBlur2); + glBindFramebuffer(GL_FRAMEBUFFER, t_m_fbWaterBlur2); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t_m_BWater2, 0); + GLenum waterBlur2DrawBuffers[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, waterBlur2DrawBuffers); + if (GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + LOG_ERROR("m_fbDeferred2 incomplete: 0x%x\n", fbStatus); + exit(EXIT_FAILURE); + } + // Generate final deferred texture glGenTextures(1, &m_tFinal); glBindTexture(GL_TEXTURE_2D, m_tFinal); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Resolution.Width, m_Resolution.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Create third pass framebuffer glGenFramebuffers(1, &m_fbDeferred3); @@ -209,13 +285,13 @@ void dd::Renderer::CreateBuffers() void dd::Renderer::Draw(RenderQueueCollection& rq) { - - DrawDeferred(rq.Deferred, rq.Lights); rq.Forward.Jobs.sort(dd::Renderer::DepthSort); + DrawDeferred(rq.Deferred, rq.Lights); DrawForward(rq.Forward, rq.Lights); + DrawGUI(rq.GUI); // Finally: Draw the deferred+forward combined texture to the screen - glCullFace(GL_BACK); + glDisable(GL_CULL_FACE); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); @@ -257,7 +333,7 @@ void dd::Renderer::DrawDeferred(RenderQueue &objects, RenderQueue &lights) glBlendFunc(GL_ONE, GL_ONE); glDepthMask(GL_FALSE); glBindFramebuffer(GL_FRAMEBUFFER, m_fbDeferred2); - glClearColor(0, 0, 0, 1); + glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); m_spDeferred2->Bind(); DrawLightSpheres(lights); @@ -266,7 +342,7 @@ void dd::Renderer::DrawDeferred(RenderQueue &objects, RenderQueue &lights) glCullFace(GL_BACK); glDisable(GL_BLEND); glBindFramebuffer(GL_FRAMEBUFFER, m_fbDeferred3); - glClearColor(0, 0, 0, 1); + glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); m_spDeferred3->Bind(); glUniform3fv(glGetUniformLocation(*m_spDeferred3, "La"), 1, glm::value_ptr(glm::vec3(0.5f))); @@ -280,7 +356,6 @@ void dd::Renderer::DrawDeferred(RenderQueue &objects, RenderQueue &lights) void dd::Renderer::DrawForward(RenderQueue &objects, RenderQueue &lights) { - // Forward-render semi-transparent objects on top of the current framebuffer glDisable(GL_CULL_FACE); glCullFace(GL_BACK); @@ -296,6 +371,19 @@ void dd::Renderer::DrawForward(RenderQueue &objects, RenderQueue &lights) m_spForward->Bind(); DrawScene(objects, *m_spForward); + + //WaterPass + glDisable(GL_CULL_FACE); + glCullFace(GL_BACK); + glDepthMask(GL_TRUE); + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindFramebuffer(GL_FRAMEBUFFER, t_m_fbWater); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); + t_m_spWater->Bind(); + DrawWater(objects); } void dd::Renderer::DrawScene(RenderQueue &objects, ShaderProgram &program) @@ -311,6 +399,7 @@ void dd::Renderer::DrawScene(RenderQueue &objects, ShaderProgram &program) if (modelJob) { glm::mat4 modelMatrix = modelJob->ModelMatrix; MVP = PV * modelMatrix; + glUniform4fv(glGetUniformLocation(shaderProgramHandle, "Color"), 1, glm::value_ptr(modelJob->Color)); glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "V"), 1, GL_FALSE, glm::value_ptr(viewMatrix)); @@ -318,7 +407,6 @@ void dd::Renderer::DrawScene(RenderQueue &objects, ShaderProgram &program) glUniform3fv(glGetUniformLocation(shaderProgramHandle, "LightSpecular"), 1, glm::value_ptr(glm::vec3(1.f))); glUniform3fv(glGetUniformLocation(shaderProgramHandle, "LightDiffuse"), 1, glm::value_ptr(glm::vec3(1.f))); glUniform1f(glGetUniformLocation(shaderProgramHandle, "LightRadius"), 40.0f); - glUniform1f(glGetUniformLocation(shaderProgramHandle, "MaterialShininess"), modelJob->Shininess); glActiveTexture(GL_TEXTURE0); @@ -339,7 +427,6 @@ void dd::Renderer::DrawScene(RenderQueue &objects, ShaderProgram &program) glBindTexture(GL_TEXTURE_2D, *m_StandardSpecular); } - glBindVertexArray(modelJob->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex); @@ -355,6 +442,7 @@ void dd::Renderer::DrawScene(RenderQueue &objects, ShaderProgram &program) glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "V"), 1, GL_FALSE, glm::value_ptr(viewMatrix)); + glUniform4fv(glGetUniformLocation(shaderProgramHandle, "Color"), 1, glm::value_ptr(modelJob->Color)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture); @@ -409,6 +497,112 @@ void dd::Renderer::DrawLightSpheres(RenderQueue &lights) } } +void dd::Renderer::DrawWater(RenderQueue &rq) +{ + GLuint shaderProgramHandle = *t_m_spWater; + + glm::mat4 projectionMatrix = m_Camera->ProjectionMatrix(); + glm::mat4 viewMatrix = m_Camera->ViewMatrix(); + glm::mat4 PV = projectionMatrix * viewMatrix; + glm::mat4 MVP; + for ( auto &job : rq ) { + auto waterJob = std::dynamic_pointer_cast(job); + if (waterJob) { + glm::mat4 modelMatrix = waterJob->ModelMatrix; + MVP = PV * modelMatrix; + glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "M"), 1, GL_FALSE, + glm::value_ptr(modelMatrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderProgramHandle, "V"), 1, GL_FALSE, + glm::value_ptr(viewMatrix)); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, *t_m_WhiteSphereTexture); + + glBindVertexArray(m_UnitQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_UnitQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_UnitQuad->m_Indices.size(), GL_UNSIGNED_INT, 0, 0); + } + } + + + + //blur1 + shaderProgramHandle = *t_m_spWater2; + glDisable(GL_CULL_FACE); + glDepthMask(GL_FALSE); + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glBindFramebuffer(GL_FRAMEBUFFER, t_m_fbWaterBlur); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); + t_m_spWater2->Bind(); + float radius = 3.f; + + glUniform2fv(glGetUniformLocation(shaderProgramHandle, "dir"), 1, glm::value_ptr(glm::vec2(1.0f, 0.0f))); + glUniform1f(glGetUniformLocation(shaderProgramHandle, "res"), m_Resolution.Width); + glUniform1f(glGetUniformLocation(shaderProgramHandle, "radius"), radius); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, t_m_Gwater); + glBindVertexArray(m_ScreenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + + + //blur2 + shaderProgramHandle = *t_m_spWater2; + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glBindFramebuffer(GL_FRAMEBUFFER, m_fbDeferred3); + t_m_spWater2->Bind(); + + glUniform2fv(glGetUniformLocation(shaderProgramHandle, "dir"), 1, glm::value_ptr(glm::vec2(0.0f, 1.0f))); + glUniform1f(glGetUniformLocation(shaderProgramHandle, "res"), m_Resolution.Height); + glUniform1f(glGetUniformLocation(shaderProgramHandle, "radius"), radius); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, t_m_BWater); + glBindVertexArray(m_ScreenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); +} + + + +GLuint dd::Renderer::CreateWaterParticleVAO(RenderQueue &particles) +{ + float waterVerts[particles.Size()]; + int i = 0; + + for ( auto &job : particles ) { + auto waterJob = std::dynamic_pointer_cast(job); + if (!waterJob) + continue; + waterVerts[i ] = waterJob->Position.x; + waterVerts[i+1] = waterJob->Position.y; + waterVerts[i+2] = waterJob->Position.z; + i+3; + } + + GLuint vbo[1], vao; + glGenBuffers(1, vbo); + glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); + glBufferData(GL_ARRAY_BUFFER, 3 * particles.Size() * sizeof(float), waterVerts, GL_STATIC_DRAW); + glGenVertexArrays(1, &vao); + glBindVertexArray(vao); + glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); + glEnableVertexAttribArray(0); + + glBindVertexArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + + return vao; +} + GLuint dd::Renderer::CreateQuad() { float quadVertices[] = @@ -472,4 +666,64 @@ void dd::Renderer::DebugKeys() if (glfwGetKey(m_Window, GLFW_KEY_F6)) { m_CurrentScreenBuffer = m_tLighting; } + if (glfwGetKey(m_Window, GLFW_KEY_F7)) { + m_CurrentScreenBuffer = t_m_Gwater; + } + if (glfwGetKey(m_Window, GLFW_KEY_F8)) { + m_CurrentScreenBuffer = t_m_BWater; + } +} + +void dd::Renderer::DrawGUI(dd::RenderQueue& rq) +{ + glBindFramebuffer(GL_FRAMEBUFFER, m_fbDeferred3); + glDisable(GL_CULL_FACE); + glCullFace(GL_BACK); + glDisable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + //glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE); + + m_spScreen->Bind(); + + glm::mat4 MVP; + + for (auto &job : rq) { + auto frameJob = std::dynamic_pointer_cast(job); + if (frameJob) { + FrameJob jobCopy = *(frameJob.get()); + glm::mat4 viewMatrix = glm::mat4(1); //frameJob->ViewMatrix; + glm::mat4 PV = glm::mat4(1); //frameJob->ProjectionMatrix * viewMatrix; + glm::mat4 modelMatrix = glm::mat4(1); //frameJob->ModelMatrix; + MVP = PV * modelMatrix; + glUniformMatrix4fv(glGetUniformLocation(*m_spScreen, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(*m_spScreen, "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); + glUniformMatrix4fv(glGetUniformLocation(*m_spScreen, "V"), 1, GL_FALSE, glm::value_ptr(viewMatrix)); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, frameJob->DiffuseTexture); + //glActiveTexture(GL_TEXTURE1); + //glBindTexture(GL_TEXTURE_2D, frameJob->NormalTexture); + //glActiveTexture(GL_TEXTURE2); + //glBindTexture(GL_TEXTURE_2D, frameJob->SpecularTexture); + + Rectangle& vp = frameJob->Viewport; + glViewport(vp.X, m_Resolution.Height - vp.Y - vp.Height, vp.Width, vp.Height); + Rectangle& sc = frameJob->Scissor; + if (sc == Rectangle()) { + glDisable(GL_SCISSOR_TEST); + } else { + glEnable(GL_SCISSOR_TEST); + glScissor(sc.X, m_Resolution.Height - sc.Y - sc.Height, sc.Width, sc.Height); + } + + glBindVertexArray(m_ScreenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + + continue; + } + } + + glDisable(GL_SCISSOR_TEST); + glViewport(0, 0, m_Resolution.Width, m_Resolution.Height); } diff --git a/src/game/Core/Shaders/Deferred/1/Fragment.glsl b/src/game/Core/Shaders/Deferred/1/Fragment.glsl old mode 100644 new mode 100755 index 927a681..8f7dbed --- a/src/game/Core/Shaders/Deferred/1/Fragment.glsl +++ b/src/game/Core/Shaders/Deferred/1/Fragment.glsl @@ -24,6 +24,7 @@ layout (binding = 2) uniform sampler2D SpecularMap; uniform mat4 V; uniform float MaterialShininess; +uniform vec4 Color; in VertexData { @@ -49,6 +50,7 @@ void main() { // Diffuse Texture GDiffuse = texture(DiffuseTexture, Input.TextureCoord) * Input.DiffuseColor; + GDiffuse = GDiffuse * Color; // G-buffer Position GPosition = vec4(Input.Position.xyz, 1.0); diff --git a/src/game/Core/Shaders/Deferred/water/Fragment.glsl b/src/game/Core/Shaders/Deferred/water/Fragment.glsl new file mode 100755 index 0000000..dc9d544 --- /dev/null +++ b/src/game/Core/Shaders/Deferred/water/Fragment.glsl @@ -0,0 +1,90 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#version 440 + +layout (binding=0) uniform sampler2D DiffuseTexture; +layout (binding=1) uniform sampler2D NormalMap; +layout (binding=2) uniform sampler2D SpecularMap; + +uniform mat4 MVP; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec3 LightPosition; +uniform float LightRadius; +uniform vec3 LightSpecular; +uniform vec3 LightDiffuse; + +in VertexData +{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoord; + vec4 DiffuseColor; + vec4 SpecularColor; + vec4 BoneIndices1; + vec4 BoneIndices2; + vec4 BoneWeights1; + vec4 BoneWeights2; +} Input; + +out vec4 frag_Diffuse; + +vec4 phong(vec3 position, vec3 normal, vec3 specular, float specularExponent) +{ + // Diffuse + vec3 lightPos = vec3(V * vec4(LightPosition, 1.0)); + vec3 distanceToLight = lightPos - position; + vec3 directionToLight = normalize(distanceToLight); + float dotProd = dot(directionToLight, normal); + dotProd = max(dotProd, 0.0); + vec3 Idiffuse = LightDiffuse * dotProd; + + // Specular + //vec3 reflection = reflect(-directionToLight, normal); + vec3 surfaceToViewer = normalize(-position); + vec3 halfWay = normalize(surfaceToViewer + directionToLight); + float dotSpecular = max(dot(halfWay, normal), 0.0); + float specularFactor = pow(dotSpecular, specularExponent); + vec3 Ispecular = specular * LightSpecular * specularFactor; + + //Attenuation + float dist = distance(lightPos, position); + //float attenuation = 1.0 - pow(dist / LightRadius, 2); + float attenuation = pow(max(0.0f, 1.0 - (dist / LightRadius)), 2); + + return vec4((Idiffuse + Ispecular) * attenuation, 1.0); +} + +void main() +{ + vec4 normalTexel = texture(NormalMap, Input.TextureCoord); + mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); + vec3 normal = normalize(vec4(TBN * normalTexel.xyz, 0.0).xyz); + + vec4 specularTexel = texture(SpecularMap, Input.TextureCoord); + + vec4 diffuseTexel = texture(DiffuseTexture, Input.TextureCoord); + vec4 La = vec4(0.3, 0.3, 0.3, 1.0); + vec4 light = phong(Input.Position, normalize(normal), specularTexel.rgb, specularTexel.a); + //frag_Diffuse = light; + frag_Diffuse = diffuseTexel; +} \ No newline at end of file diff --git a/src/game/Core/Shaders/Deferred/water/Vertex.glsl b/src/game/Core/Shaders/Deferred/water/Vertex.glsl new file mode 100755 index 0000000..64a9e26 --- /dev/null +++ b/src/game/Core/Shaders/Deferred/water/Vertex.glsl @@ -0,0 +1,83 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#version 440 + +uniform mat4 MVP; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + +layout (location = 0) in vec3 Position; +layout (location = 1) in vec3 Normal; +layout (location = 2) in vec3 Tangent; +layout (location = 3) in vec3 BiTangent; +layout (location = 4) in vec2 TextureCoord; +layout (location = 5) in vec4 DiffuseColor; +layout (location = 6) in vec4 SpecularColor; +layout (location = 7) in vec4 BoneIndices1; +layout (location = 8) in vec4 BoneIndices2; +layout (location = 9) in vec4 BoneWeights1; +layout (location = 10) in vec4 BoneWeights2; + +out VertexData +{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoord; + vec4 DiffuseColor; + vec4 SpecularColor; + vec4 BoneIndices1; + vec4 BoneIndices2; + vec4 BoneWeights1; + vec4 BoneWeights2; +} Output; + +void main() +{ + mat4 boneTransform = mat4(1); + if (length(BoneWeights1 + BoneWeights2) > 0) { + boneTransform = BoneWeights1[0] * Bones[int(BoneIndices1[0])] + + BoneWeights1[1] * Bones[int(BoneIndices1[1])] + + BoneWeights1[2] * Bones[int(BoneIndices1[2])] + + BoneWeights1[3] * Bones[int(BoneIndices1[3])] + + BoneWeights2[0] * Bones[int(BoneIndices2[0])] + + BoneWeights2[1] * Bones[int(BoneIndices2[1])] + + BoneWeights2[2] * Bones[int(BoneIndices2[2])] + + BoneWeights2[3] * Bones[int(BoneIndices2[3])]; + } + + //gl_Position = MVP * boneTransform * vec4(Position, 1.0); + gl_Position = MVP * vec4(Position, 1.0); + + //TODO: Make sure that boneTransform works here. + Output.Position = (V * M * boneTransform * vec4(Position, 1.0)).xyz; + Output.Normal = (inverse(transpose(V * M)) * boneTransform * vec4(Normal, 0.0)).xyz; + Output.Tangent = Tangent; + Output.BiTangent = BiTangent; + Output.TextureCoord = TextureCoord; + Output.DiffuseColor = DiffuseColor; + Output.SpecularColor = SpecularColor; + Output.BoneIndices1 = BoneIndices1; + Output.BoneIndices2 = BoneIndices2; + Output.BoneWeights1 = BoneWeights1; + Output.BoneWeights2 = BoneWeights2; +} \ No newline at end of file diff --git a/src/game/Core/Shaders/Deferred/water2/Fragment.glsl b/src/game/Core/Shaders/Deferred/water2/Fragment.glsl new file mode 100755 index 0000000..b82af8f --- /dev/null +++ b/src/game/Core/Shaders/Deferred/water2/Fragment.glsl @@ -0,0 +1,70 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#version 440 + +uniform vec2 dir; +uniform float res; +uniform float radius; + +layout (binding=0) uniform sampler2D WaterTexture; + +in VertexData +{ + vec3 Position; + vec2 TextureCoord; +} Input; + +out vec4 frag_Diffuse; + +void main() +{ + vec4 WaterTexel = texture(WaterTexture, Input.TextureCoord); + + vec4 sum = vec4(0.0); + vec2 tc = Input.TextureCoord; + + //How much blur, 1 = blur by one pixel. + float blur = radius/res; + + float hstep = dir.x; + float vstep = dir.y; + + float Threshhold = 0.1; + + //apply filter using a 9 tap filter with predefined gaussian weights + + sum += texture(WaterTexture, vec2(tc.x - 4.0*blur*hstep, tc.y - 4.0*blur*vstep)) * 0.0162162162; + sum += texture(WaterTexture, vec2(tc.x - 3.0*blur*hstep, tc.y - 3.0*blur*vstep)) * 0.0540540541; + sum += texture(WaterTexture, vec2(tc.x - 2.0*blur*hstep, tc.y - 2.0*blur*vstep)) * 0.1216216216; + sum += texture(WaterTexture, vec2(tc.x - 1.0*blur*hstep, tc.y - 1.0*blur*vstep)) * 0.1945945946; + + sum += texture(WaterTexture, vec2(tc.x, tc.y)) * 0.2270270270; + + sum += texture(WaterTexture, vec2(tc.x + 1.0*blur*hstep, tc.y + 1.0*blur*vstep)) * 0.1945945946; + sum += texture(WaterTexture, vec2(tc.x + 2.0*blur*hstep, tc.y + 2.0*blur*vstep)) * 0.1216216216; + sum += texture(WaterTexture, vec2(tc.x + 3.0*blur*hstep, tc.y + 3.0*blur*vstep)) * 0.0540540541; + sum += texture(WaterTexture, vec2(tc.x + 4.0*blur*hstep, tc.y + 4.0*blur*vstep)) * 0.0162162162; + + frag_Diffuse = vec4(sum.rgb, 1.0) * vec4(0.0, 0.6, 1.5, 1.0); + float avgColor = frag_Diffuse.r + frag_Diffuse.g + frag_Diffuse.b; + avgColor = avgColor/3; + if ( avgColor*dir.y > Threshhold ){ + frag_Diffuse = vec4(0.0, 0.3, 1.0, 1.0); + } +} \ No newline at end of file diff --git a/src/game/Core/Shaders/Deferred/water2/Vertex.glsl b/src/game/Core/Shaders/Deferred/water2/Vertex.glsl new file mode 100755 index 0000000..08bb198 --- /dev/null +++ b/src/game/Core/Shaders/Deferred/water2/Vertex.glsl @@ -0,0 +1,34 @@ +/* + This file is part of Daydream Engine. + Copyright 2014 Adam Byléhn, Tobias Dahl, Simon Holmberg, Viktor Ljung + + Daydream Engine is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Daydream Engine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Daydream Engine. If not, see . +*/ + +#version 440 + +layout (location = 0) in vec3 Position; + +out VertexData +{ + vec3 Position; + vec2 TextureCoord; +} Output; + +void main() +{ + gl_Position = vec4(Position, 1.0); + Output.Position = Position; + Output.TextureCoord = (vec2(Position) + 1) / 2; +} \ No newline at end of file diff --git a/src/game/Core/Texture.cpp b/src/game/Core/Texture.cpp index f9ba46e..8fb8b33 100755 --- a/src/game/Core/Texture.cpp +++ b/src/game/Core/Texture.cpp @@ -31,6 +31,9 @@ dd::Texture::Texture(std::string path) } } + this->Width = image->Width; + this->Height = image->Height; + GLint format; switch (image->Format) { case Image::ImageFormat::RGB: diff --git a/src/game/Game/LevelSystem.cpp.orig b/src/game/Game/LevelSystem.cpp.orig new file mode 100644 index 0000000..b1d1139 --- /dev/null +++ b/src/game/Game/LevelSystem.cpp.orig @@ -0,0 +1,372 @@ +// +// Created by Adniklastrator on 2015-09-09. +// + + +#include "PrecompiledHeader.h" +#include "Game/LevelSystem.h" + + +void dd::Systems::LevelSystem::Initialize() +{ + EVENT_SUBSCRIBE_MEMBER(m_EContact, LevelSystem::OnContact); + EVENT_SUBSCRIBE_MEMBER(m_ELifeLost, LevelSystem::OnLifeLost); + EVENT_SUBSCRIBE_MEMBER(m_EScoreEvent, LevelSystem::OnScoreEvent); + EVENT_SUBSCRIBE_MEMBER(m_EMultiBall, LevelSystem::OnMultiBall); + EVENT_SUBSCRIBE_MEMBER(m_ECreatePowerUp, LevelSystem::OnCreatePowerUp); + EVENT_SUBSCRIBE_MEMBER(m_EPowerUpTaken, LevelSystem::OnPowerUpTaken); + EVENT_SUBSCRIBE_MEMBER(m_EStageCleared, LevelSystem::OnStageCleared); + + for (int i = 0; i < Lives(); i++) { + CreateLife(i); + } + + return; +} + +void dd::Systems::LevelSystem::CreateLife(int number) +{ + auto life = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent(life); + transform->Position = glm::vec3(-1.5f + number * 0.15f, -2.f, -5.f); + transform->Scale = glm::vec3(0.1f, 0.1f, 0.1f); + + std::shared_ptr lifeNr = m_World->AddComponent(life); + lifeNr->Number = number; + + auto model = m_World->AddComponent(life); + model->ModelFile = "Models/Test/Ball/Ballopus.obj"; + + + m_World->CommitEntity(life); +} + +void dd::Systems::LevelSystem::Update(double dt) +{ + if (!m_Initialized) { + CreateBasicLevel(Rows(), Lines(), SpaceBetweenBricks(), SpaceToEdge()); + m_Initialized = true; + } + + if (Lives() < 0) + { + SetLives(3); + Events::GameOver e; + EventBroker->Publish(e); + } +} + +void dd::Systems::LevelSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) +{ + auto ball = m_World->GetComponent(entity); + + if (ball != nullptr) { + auto transformBall = m_World->GetComponent(entity); + if (glm::abs(transformBall->Velocity.y) < 2) { + if (transformBall->Velocity.y > 0) { + transformBall->Velocity.y = 2; + } else { + transformBall->Velocity.y = -2; + } + } + if (transformBall->Position.y < -EdgeY() - 4) { + if (MultiBalls() != 0) { + SetMultiBalls(MultiBalls() - 1); +// m_World->RemoveComponent(entity); +// m_World->RemoveComponent(entity); +// m_World->RemoveComponent(entity); +// m_World->RemoveComponent(entity); + m_World->RemoveEntity(entity); + } else if (Lives() == PastLives()) { + Events::ResetBall be; + EventBroker->Publish(be); + Events::LifeLost e; + e.Entity = entity; + EventBroker->Publish(e); + return; + } + } else if (transformBall->Position.x > EdgeX()) { + if (transformBall->Velocity.x > 0) { + glm::vec2 reflectedVelocity = glm::reflect(glm::vec2(transformBall->Velocity.x, transformBall->Velocity.y), glm::vec2(1, 0)); + transformBall->Velocity = glm::vec3(reflectedVelocity, 0.f); + } + } else if (transformBall->Position.x < -EdgeX()) { + if (transformBall->Velocity.x < 0) { + glm::vec2 reflectedVelocity = glm::reflect(glm::vec2(transformBall->Velocity.x, transformBall->Velocity.y), glm::vec2(-1, 0)); + transformBall->Velocity = glm::vec3(reflectedVelocity, 0.f); + } + } else if (transformBall->Position.y > EdgeY()) { + if (transformBall->Velocity.y > 0) { + glm::vec2 reflectedVelocity = glm::reflect(glm::vec2(transformBall->Velocity.x, transformBall->Velocity.y), glm::vec2(0, 1)); + transformBall->Velocity = glm::vec3(reflectedVelocity, 0.f); + } + } + } + + if (Lives() != PastLives()) { + auto life = m_World->GetComponent(entity); + if (life != nullptr) { + if (life->Number + 1 == PastLives()) { +// m_World->RemoveComponent(entity); +// m_World->RemoveComponent(entity); + m_World->RemoveEntity(entity); + SetPastLives(Lives()); + } + } + } + if (NumberOfBricks() <= 0) { + /*SetRestarting(true); + if (MultiBalls() <= 0 && PowerUps() <= 0) { + Events::ResetBall e; + EventBroker->Publish(e); + Events::ScoreEvent es; + es.Score = 500; + EventBroker->Publish(es); + Events::StageCleared ec; + EventBroker->Publish(ec); + CreateBasicLevel(Rows(), Lines(), SpaceBetweenBricks(), SpaceToEdge()); + } else { + if (ball != nullptr && MultiBalls() > 0) { + SetMultiBalls(MultiBalls() - 1); + m_World->RemoveComponent(entity); + m_World->RemoveComponent(entity); + m_World->RemoveComponent(entity); + m_World->RemoveComponent(entity); + m_World->RemoveEntity(entity); + auto transformBall = m_World->GetComponent(entity); + } else { + auto powerUp = m_World->GetComponent(entity); + if (powerUp != nullptr) { + SetPowerUps(PowerUps() - 1); + m_World->RemoveComponent(entity); + m_World->RemoveComponent(entity); + m_World->RemoveEntity(entity); + } + } + }*/ + } +} + +void dd::Systems::LevelSystem::CreateBasicLevel(int rows, int lines, glm::vec2 spacesBetweenBricks, float spaceToEdge) +{ + SetNumberOfBricks(rows * lines); + std::cout << "You're only doing this once, right?" << std::endl; + int num = 0; + for (int i = 0; i < rows; i++) { + num++; + for (int j = 0; j < Lines(); j++) { + CreateBrick(i, j, spacesBetweenBricks, spaceToEdge, num); + } + if (num == 7) + num = 0; + } + + SetNumberOfBricks(rows * lines); + SetRestarting(false); + return; +} + +void dd::Systems::LevelSystem::CreateBrick(int row, int line, glm::vec2 spacesBetweenBricks, float spaceToEdge, int num) +{ + auto brick = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent(brick); + auto model = m_World->AddComponent(brick); + std::shared_ptr cBrick = m_World->AddComponent(brick); + std::shared_ptr cRec = m_World->AddComponent(brick); + std::shared_ptr cPhys = m_World->AddComponent(brick); + cPhys->Static = false; + cPhys->GravityScale = 0.f; + cPhys->Category = CollisionLayer::Type::Brick; + cPhys->Mask = CollisionLayer::Type::Ball; + + std::string fileName = "Textures/Bricks/"; + fileName.append(std::to_string(num)); + fileName.append(".png"); + //sprite->SpriteFile = fileName; + model->ModelFile = "Models/Test/Brick/Brick.obj"; + if ((line == 1 && row == 4) || (line == 3 && row == 2) || (line == 6 && row == 6)) { + std::shared_ptr cPow = m_World->AddComponent(brick); + } + float x = line * spacesBetweenBricks.x; + float y = row * spacesBetweenBricks.y; + transform->Scale = glm::vec3(0.8, 0.2, 0.2); + transform->Position = glm::vec3(x - 3, 5 - spaceToEdge - y , -10.f); + cBrick->Score = 10 * num; + + //sound + auto collisionSound = m_World->AddComponent(brick); + collisionSound->filePath = "Sounds/Brick/shortbrickbreak.wav"; + + m_World->CommitEntity(brick); + return; +} + +void dd::Systems::LevelSystem::ProcessCollision() +{ + // Like, go into brick component and check what it does upon collision. Maybe not done here? + return; +} + +void dd::Systems::LevelSystem::OnEntityRemoved(EntityID entity) +{ + auto brick = m_World->GetComponent(entity); + if (brick != nullptr) { + SetNumberOfBricks(NumberOfBricks() - 1); + Events::ScoreEvent es; + es.Score = brick->Score; + EventBroker->Publish(es); + /*if (numberOfBricks < 1) { + EndLevel(); + }*/ + } + return; +} + +bool dd::Systems::LevelSystem::OnContact(const dd::Events::Contact &event) +{ + EntityID entityBrick; + EntityID entityBall; + auto ball = m_World->GetComponent(event.Entity2); + auto brick = m_World->GetComponent(event.Entity1); + if (brick != nullptr) { + entityBrick = event.Entity1; + } else { + brick = m_World->GetComponent(event.Entity2); + if (brick != nullptr) { + entityBrick = event.Entity2; + } else { + return false; + } + } + if (ball != nullptr) { + entityBall = event.Entity2; + } else { + ball = m_World->GetComponent(event.Entity1); + if (ball != nullptr) { + entityBall = event.Entity1; + } else { + return false; + } + } + + brick = m_World->GetComponent(entityBrick); + if (brick == nullptr) { + return false; + } + + auto power = m_World->GetComponent(entityBrick); + if (power != nullptr) { + Events::CreatePowerUp e; + auto transform = m_World->GetComponent(entityBrick); + e.Position = transform->Position; + EventBroker->Publish(e); + } + + if (ball != nullptr && Restarting() == false) { + auto ballTransform = m_World->GetComponent(entityBall); + +// m_World->RemoveComponent(entityBrick); +// m_World->RemoveComponent(entityBrick); +// m_World->RemoveComponent(entityBrick); +// m_World->RemoveComponent(entityBrick); +// m_World->RemoveEntity(entityBrick); + + auto physicsComponent = m_World->GetComponent(entityBrick); + physicsComponent->GravityScale = 1.f; + physicsComponent->Mask = CollisionLayer::Type::Water | CollisionLayer::Type::Wall; + + auto transformComponentBrick = m_World->GetComponent(entityBrick); + auto transformComponentBall = m_World->GetComponent(entityBall); + + Events::SetImpulse e; + e.Entity = entityBrick; + + glm::vec2 point = glm::vec2(transformComponentBrick->Position.x + ((transformComponentBrick->Position.x - transformComponentBall->Position.x)/4), transformComponentBrick->Position.y + ((transformComponentBrick->Position.y - transformComponentBall->Position.y )/4)); + + e.Impulse = glm::normalize(point)/2.f; + e.Point = point; + EventBroker->Publish(e); + //TODO: Bricks dont collide with walls D= + + SetNumberOfBricks(NumberOfBricks() - 1); + if (NumberOfBricks() <= 0) { + SetMultiBalls(MultiBalls() + 1); + } + Events::ScoreEvent es; + es.Score = brick->Score; + EventBroker->Publish(es); + +<<<<<<< HEAD + // std::cout << NumberOfBricks() << std::endl; +======= + //std::cout << NumberOfBricks() << std::endl; +>>>>>>> origin/master + //std::cout << "Score: " << Score() << std::endl; + } + + return true; +} + +bool dd::Systems::LevelSystem::OnLifeLost(const dd::Events::LifeLost &event) +{ + SetLives(Lives() - 1); + + return true; +} + +bool dd::Systems::LevelSystem::OnScoreEvent(const dd::Events::ScoreEvent &event) +{ + SetScore(Score() += event.Score); + + return true; +} + +bool dd::Systems::LevelSystem::OnMultiBall(const dd::Events::MultiBall &event) +{ + SetMultiBalls(MultiBalls()+2); +} + +bool dd::Systems::LevelSystem::OnCreatePowerUp(const dd::Events::CreatePowerUp &event) +{ + SetPowerUps(PowerUps() + 1); + auto powerUp = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent(powerUp); + auto model = m_World->AddComponent(powerUp); + std::shared_ptr cRec = m_World->AddComponent(powerUp); + std::shared_ptr cPhys = m_World->AddComponent(powerUp); + cPhys->Static = false; + cPhys->Category = CollisionLayer::Type::PowerUp; + cPhys->Mask = CollisionLayer::Type::Pad; + + std::shared_ptr cPow = m_World->AddComponent(powerUp); + + + transform->Position = event.Position; + transform->Scale = glm::vec3(0.2, 0.2, 0.2); + transform->Velocity = glm::vec3(0, -4, 0); + + model->ModelFile = "Models/Test/Ball/Ballopus.obj"; + + m_World->CommitEntity(powerUp); + + return true; +} + +bool dd::Systems::LevelSystem::OnPowerUpTaken(const dd::Events::PowerUpTaken &event) +{ + SetPowerUps(PowerUps() - 1); + return true; +} + +bool dd::Systems::LevelSystem::OnStageCleared(const dd::Events::StageCleared &event) +{ + return true; +} + +void dd::Systems::LevelSystem::EndLevel() +{ + Events::StageCleared e; + EventBroker->Publish(e); + return; +} + diff --git a/src/game/Game/PadSystem.cpp b/src/game/Game/PadSystem.cpp index 8d66bb0..3241b28 100755 --- a/src/game/Game/PadSystem.cpp +++ b/src/game/Game/PadSystem.cpp @@ -72,6 +72,7 @@ void dd::Systems::PadSystem::Update(double dt) transform->Velocity += acceleration * (float)dt; transform->Velocity -= transform->Velocity * pad->SlowdownModifier * (float)dt; + if (Left()) { acceleration.x = -pad->AccelerationSpeed; } else if (Right()) { @@ -190,10 +191,9 @@ bool dd::Systems::PadSystem::OnContact(const dd::Events::Contact &event) //float movementX = (event.ContactPoint.x - transformPad->Position.x) * movementMultiplier; float movementY = glm::cos((abs(movementX) / ((1.6f) * movementMultiplier)) * 3.14159265359f / 2)+ 0.2; - //std::cout << movementX << " " << movementY << std::endl; - float len = glm::length(transformBall->Velocity); + //auto pointlight = m_World->AddComponent(ent); transformBall->Velocity += glm::vec3(transformPad->Velocity.x, 0, 0); diff --git a/src/game/Game/PadSystem.cpp.orig b/src/game/Game/PadSystem.cpp.orig new file mode 100755 index 0000000..7d21606 --- /dev/null +++ b/src/game/Game/PadSystem.cpp.orig @@ -0,0 +1,313 @@ +// +// Created by Adniklastrator on 2015-09-10. +// + +#include "PrecompiledHeader.h" +#include "Game/PadSystem.h" +#include "Core/World.h" +#include +#include +#include + + +void dd::Systems::PadSystem::Initialize() +{ + Events::BindKey r; + r.KeyCode = GLFW_KEY_RIGHT; + r.Command = "right"; + EventBroker->Publish(r); + + Events::BindKey l; + l.KeyCode = GLFW_KEY_LEFT; + l.Command = "left"; + EventBroker->Publish(l); + + EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &PadSystem::OnKeyDown); + EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &PadSystem::OnKeyUp); + EVENT_SUBSCRIBE_MEMBER(m_EContact, &PadSystem::OnContact); + EVENT_SUBSCRIBE_MEMBER(m_EContactPowerUp, &PadSystem::OnContactPowerUp); + EVENT_SUBSCRIBE_MEMBER(m_EResetBall, &PadSystem::OnResetBall); + EVENT_SUBSCRIBE_MEMBER(m_EMultiBall, &PadSystem::OnMultiBall); + EVENT_SUBSCRIBE_MEMBER(m_EStageCleared, &PadSystem::OnStageCleared); +} + +void dd::Systems::PadSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) +{ + auto ball = m_World->GetComponent(entity); + if (ball != nullptr) { + if (ReplaceBall() == true) { + SetReplaceBall(false); + + auto transform = m_World->GetComponent(entity); + transform->Position = glm::vec3(0.0f, 0.26f, -10.f); + transform->Velocity = glm::vec3(0.0f, -ball->Speed, 0.f); + } + } +} + +void dd::Systems::PadSystem::Update(double dt) +{ + if (Entity() == 0) { + for (auto it = m_World->GetEntities()->begin(); it != m_World->GetEntities()->end(); it++) { + if (m_World->GetProperty(it->first, "Name") == "Pad") { + SetEntity(it->first); + SetTransform(m_World->GetComponent(Entity())); + SetPad(m_World->GetComponent(Entity())); + break; + } + } + } + + auto transform = Transform(); + auto pad = Pad(); + auto acceleration = Acceleration(); + + if (transform->Velocity.x < -pad->MaxSpeed) { + transform->Velocity.x = -pad->MaxSpeed; + } + else if (transform->Velocity.x > pad->MaxSpeed) { + transform->Velocity.x = pad->MaxSpeed; + } + transform->Position += transform->Velocity * (float)dt; + transform->Velocity += acceleration * (float)dt; + transform->Velocity -= transform->Velocity * pad->SlowdownModifier * (float)dt; + + + if (Left()) { + acceleration.x = -pad->AccelerationSpeed; +<<<<<<< HEAD + } + else if (Right()) { +======= + } else if (Right()) { +>>>>>>> 72413dc0a93bd3a2f6ab9fa7e19bbc3b846232db + acceleration.x = pad->AccelerationSpeed; + } else { + acceleration.x = 0.f; + } + + SetTransform(transform); + SetPad(pad); + SetAcceleration(acceleration); + + if (MultiBall() == true) { + SetMultiBall(false); + + Events::MultiBall e; + e.padTransform = transform; + EventBroker->Publish(e); + } + + return; +} + +EntityID dd::Systems::PadSystem::CreateBall() +{ + auto ent = m_World->CreateEntity(); + std::shared_ptr transform = m_World->AddComponent(ent); + transform->Position = glm::vec3(0.5f, 0.26f, -10.f); + transform->Scale = glm::vec3(0.5f, 0.5f, 0.5f); + auto model = m_World->AddComponent(ent); + model->ModelFile = "Models/Test/Ball/Ballopus.obj"; + //auto pointlight = m_World->AddComponent(ent); + std::shared_ptr circleShape = m_World->AddComponent(ent); + std::shared_ptr cball = m_World->AddComponent(ent); + std::shared_ptr physics = m_World->AddComponent(ent); + physics->Static = false; + + cball->Speed = 10; + + m_World->CommitEntity(ent); + + return ent; +} + +bool dd::Systems::PadSystem::OnKeyDown(const dd::Events::KeyDown &event) +{ + int val = event.KeyCode; + if (val == GLFW_KEY_UP) { + //std::cout << "Up!" << std::endl; + } else if (val == GLFW_KEY_DOWN) { + //std::cout << "Down!" << std::endl; + } else if (val == GLFW_KEY_LEFT) { + //std::cout << "Left!" << std::endl; + //acceleration.x = -0.01f; + SetLeft(true); + } else if (val == GLFW_KEY_RIGHT) { + //std::cout << "Right!" << std::endl; + //acceleration.x = 0.01f; + SetRight(true); + } else if (val == GLFW_KEY_R) { + SetReplaceBall(true); + } else if (val == GLFW_KEY_M) { + SetMultiBall(true); + } else if (val == GLFW_KEY_D) { + return false; + } + return true; +} + +bool dd::Systems::PadSystem::OnKeyUp(const dd::Events::KeyUp &event) +{ + int val = event.KeyCode; + if (val == GLFW_KEY_UP) { + + } else if (val == GLFW_KEY_DOWN) { + + } else if (val == GLFW_KEY_LEFT) { + SetLeft(false); + } else if (val == GLFW_KEY_RIGHT) { + SetRight(false); + } + return true; +} + +bool dd::Systems::PadSystem::OnContact(const dd::Events::Contact &event) +{ + /* + EntityID entityBall = event.Entity2; + auto ball = m_World->GetComponent(entityBall); + if (ball == NULL) { + return false; + } + EntityID entityPad = event.Entity1; + auto pad = m_World->GetComponent(entityPad); + if (pad == NULL) { + return false; + } + auto transformBall = m_World->GetComponent(entityBall); + auto transformPad = m_World->GetComponent(entityPad); + + float movementMultiplier = 0.5f; + + //float movementX = (event.ContactPoint.x - transformPad->Position.x) * movementMultiplier; + //float movementY = glm::cos((abs(movementX) / (3.2f * movementMultiplier)) * 3.14159265359f / 2) * 2.f; + if (whatX > 0) { + movementX = movementMultiplier * whatX; + //std::cout << "Right!" << std::endl; + } else { + movementX = movementMultiplier * whatX; + //std::cout << "Left!" << std::endl; + } + + // std::cout << movementX << " " << movementY << std::endl; + + //float movementX = (event.ContactPoint.x - transformPad->Position.x) * movementMultiplier; +<<<<<<< HEAD + float movementY = glm::cos((abs(movementX) / ((1.6f) * movementMultiplier)) * 3.14159265359f / 2) + 1; +======= + float movementY = glm::cos((abs(movementX) / ((1.6f) * movementMultiplier)) * 3.14159265359f / 2)+ 0.2; +>>>>>>> 72413dc0a93bd3a2f6ab9fa7e19bbc3b846232db + + //std::cout << movementX << " " << movementY << std::endl; + + float len = glm::length(transformBall->Velocity); + //auto pointlight = m_World->AddComponent(ent); + + + transformBall->Velocity += glm::vec3(transformPad->Velocity.x, 0, 0); + transformBall->Velocity = glm::normalize(transformBall->Velocity) * len; + + + //transform->Velocity = glm::vec3(movementX, movementY, 0.f); + */ +} + +bool dd::Systems::PadSystem::OnContactPowerUp(const dd::Events::Contact &event) +{ + EntityID entityPower; + EntityID entityPad; + auto powerUp = m_World->GetComponent(event.Entity1); + auto pad = m_World->GetComponent(event.Entity2); + if (powerUp != nullptr) { + entityPower = event.Entity1; + } else { + powerUp = m_World->GetComponent(event.Entity2); + if (powerUp != nullptr) { + entityPower = event.Entity2; + } + } + if (pad != nullptr) { + entityPad = event.Entity2; + } else { + pad = m_World->GetComponent(event.Entity1); + if (pad != nullptr) { + entityPad = event.Entity1; + } + } + + if (entityPower == NULL || entityPad == NULL) { + return false; + } + + pad = m_World->GetComponent(entityPad); + if (pad == nullptr) { + return false; + } + + m_World->RemoveComponent(entityPower); + m_World->RemoveComponent(entityPower); + m_World->RemoveComponent(entityPower); + m_World->RemoveEntity(entityPower); + Events::PowerUpTaken ep; + ep.Name = "Something"; + EventBroker->Publish(ep); + + Events::MultiBall e; + auto transform = m_World->GetComponent(entityPad); + e.padTransform = transform; + EventBroker->Publish(e); + return true; +} + +bool dd::Systems::PadSystem::OnResetBall(const dd::Events::ResetBall &event) +{ + SetReplaceBall(true); + return true; +} + +bool dd::Systems::PadSystem::OnMultiBall(const dd::Events::MultiBall &event) +{ + auto ent1 = CreateBall(); + auto ent2 = CreateBall(); + auto transform1 = m_World->GetComponent(ent1); + auto transform2 = m_World->GetComponent(ent2); + auto ball1 = m_World->GetComponent(ent1); + auto ball2 = m_World->GetComponent(ent2); + auto padTransform = event.padTransform; + float x1 = padTransform->Position.x - 2, x2 = padTransform->Position.x + 2; + if (x1 < -3.1) { + x1 = 3; + } + if (x2 > 3.1) { + x2 = -3; + } + transform1->Position = glm::vec3(x1, -5.5, -10); + transform2->Position = glm::vec3(x2, -5.5, -10); + + transform1->Velocity = glm::normalize(glm::vec3(5, 5 ,0.f)) * ball1->Speed; + transform2->Velocity = glm::normalize(glm::vec3(-5, 5 ,0.f)) * ball2->Speed; + + return true; +} + +bool dd::Systems::PadSystem::OnStageCleared(const dd::Events::StageCleared &event) +{ + auto entity = CreateBall(); + return true; +} + +bool dd::Systems::PadSystem::PadSteeringInputController::OnCommand(const Events::InputCommand &event) +{ + std::string command = event.Command; + + std::cout << "Command!" << std::endl; + + if (command == "right") { + std::cout << "Right!" << std::endl; + } else if (command == "left") { + std::cout << "Left!" << std::endl; + } + + return true; +} \ No newline at end of file diff --git a/src/game/Physics/PhysicsSystem.cpp b/src/game/Physics/PhysicsSystem.cpp index 1126579..2b5588b 100644 --- a/src/game/Physics/PhysicsSystem.cpp +++ b/src/game/Physics/PhysicsSystem.cpp @@ -22,9 +22,19 @@ void dd::Systems::PhysicsSystem::Initialize() m_PhysicsWorld->SetContactListener(m_ContactListener); + InitializeWater(); + EVENT_SUBSCRIBE_MEMBER(m_SetImpulse, PhysicsSystem::SetImpulse); } +void dd::Systems::PhysicsSystem::InitializeWater() +{ + b2ParticleSystemDef m_ParticleSystemDef; + m_ParticleSystemDef.radius = 0.13f; + + m_ParticleSystem = m_PhysicsWorld->CreateParticleSystem(&m_ParticleSystemDef); +} + bool dd::Systems::PhysicsSystem::SetImpulse(const Events::SetImpulse &event) { b2Body* body = m_EntitiesToBodies[event.Entity]; @@ -83,10 +93,8 @@ void dd::Systems::PhysicsSystem::Update(double dt) float angle = -glm::eulerAngles(transformComponent->Orientation).z; body->SetTransform(position, angle); body->SetLinearVelocity(b2Vec2(transformComponent->Velocity.x, transformComponent->Velocity.y)); - body->SetGravityScale(physicsComponent->GravityScale); - b2Filter filter; filter.categoryBits = physicsComponent->Category; filter.maskBits = physicsComponent->Mask; @@ -100,10 +108,7 @@ void dd::Systems::PhysicsSystem::Update(double dt) m_Impulses.clear(); - - m_PhysicsWorld->Step(m_TimeStep, m_VelocityIterations, m_PositionIterations); - m_Accumulator -= dt; @@ -119,22 +124,47 @@ void dd::Systems::PhysicsSystem::Update(double dt) auto transformComponent = m_World->GetComponent(entity); if (! transformComponent) continue; - if (m_World->GetEntityParent(entity) == 0) { - b2Vec2 position = body->GetPosition(); - transformComponent->Position.x = position.x; - transformComponent->Position.y = position.y; + auto parent = m_World->GetEntityParent(entity); + if (parent == 0) { - float angle = body->GetAngle(); + auto physicsComponent = m_World->GetComponent(entity); + if (physicsComponent->Calculate) { + transformComponent->Position.x = transformComponent->Position.x + (transformComponent->Velocity.x * m_TimeStep); + transformComponent->Position.y = transformComponent->Position.y + (transformComponent->Velocity.y * m_TimeStep); + } + else { + b2Vec2 position = body->GetPosition(); + transformComponent->Position.x = position.x; + transformComponent->Position.y = position.y; + float angle = body->GetAngle(); + transformComponent->Orientation = glm::quat(glm::vec3(0, 0, -angle)); - transformComponent->Orientation = glm::quat(glm::vec3(0, 0, -angle)); - - b2Vec2 velocity = body->GetLinearVelocity(); - transformComponent->Velocity.x = velocity.x; - transformComponent->Velocity.y = velocity.y; - + b2Vec2 velocity = body->GetLinearVelocity(); + transformComponent->Velocity.x = velocity.x; + transformComponent->Velocity.y = velocity.y; + } } + } + + b2Vec2* positionBuffer = m_ParticleSystem->GetPositionBuffer(); + for (auto i : m_EntitiesToParticleHandle) { + EntityID entity = i.first; + b2ParticleHandle* particleH = i.second; + + b2Vec2 positionB2 = positionBuffer[particleH->GetIndex()]; + glm::vec2 position = glm::vec2(positionB2.x, positionB2.y); + + + EntityID entityParent = m_World->GetEntityParent(entity); + auto transform = m_World->GetComponent(entity); + auto transformParent = m_World->GetComponent(entityParent); + + transform->Position = glm::vec3(position.x, position.y, -10) - transformParent->Position; + } + + m_Accumulator -= dt; } } @@ -143,12 +173,19 @@ void dd::Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, Entity } - void dd::Systems::PhysicsSystem::OnEntityCommit(EntityID entity) { auto physicsComponent = m_World->GetComponent(entity); - if(physicsComponent) { + auto waterComponent = m_World->GetComponent(entity); + + if (physicsComponent && waterComponent) { + LOG_ERROR("Entity has both water and physics component, this is illegal. The police has been alerted."); + return; + } + if (physicsComponent) { CreateBody(entity); + } else if (waterComponent) { + CreateParticleGroup(entity); } } @@ -207,7 +244,7 @@ void dd::Systems::PhysicsSystem::CreateBody(EntityID entity) auto boxComponent = m_World->GetComponent(entity); if (boxComponent) { b2PolygonShape* bShape = new b2PolygonShape(); - bShape->SetAsBox(absoluteTransform.Scale.x/2, absoluteTransform.Scale.y/2); //TODO: THIS SUCKS DUDE 4?!?!?!? + bShape->SetAsBox(absoluteTransform.Scale.x/2, absoluteTransform.Scale.y/2); pShape = bShape; } else { auto circleComponent = m_World->GetComponent(entity); @@ -219,7 +256,7 @@ void dd::Systems::PhysicsSystem::CreateBody(EntityID entity) if (absoluteTransform.Scale.x != absoluteTransform.Scale.y && absoluteTransform.Scale.y != absoluteTransform.Scale.z) { LOG_WARNING("Circles has to be of uniform scale."); } - pShape->m_radius = absoluteTransform.Scale.x/2; //TODO: THIS ALSO SUCKS 4 WTH + pShape->m_radius = absoluteTransform.Scale.x/2; } } @@ -250,6 +287,44 @@ void dd::Systems::PhysicsSystem::CreateBody(EntityID entity) m_BodiesToEntities.insert(std::make_pair(body, entity)); } +void dd::Systems::PhysicsSystem::CreateParticleGroup(EntityID e) +{ + //TODO: Lägg alla pd i en lista + auto transform = m_World->GetComponent(e); + if (!transform) { + LOG_ERROR("No Transform component in CreateParticleGroup"); + return; + } + + b2ParticleGroupDef pd; + b2PolygonShape shape; + + shape.SetAsBox(transform->Scale.x/2.f, transform->Scale.y/2.f); + pd.shape = &shape; + pd.flags = b2_tensileParticle; + pd.position.Set(transform->Position.x, transform->Position.y); + //TODO: PUT IN LIST + t_watergroup = m_ParticleSystem->CreateParticleGroup(pd); + b2Vec2* t_ParticlePositions = m_ParticleSystem->GetPositionBuffer(); + for(int i = 0; i < m_ParticleSystem->GetParticleCount(); i++){ + { + auto t_waterparticle = m_World->CreateEntity(e); + auto transformChild = m_World->AddComponent(t_waterparticle); + //auto sprite = m_World->AddComponent(t_waterparticle); + + transformChild->Position = glm::vec3(t_ParticlePositions[i].x - transform->Position.x, t_ParticlePositions[i].y - transform->Position.y, -9.5f); + transformChild->Scale = glm::vec3(m_ParticleSystem->GetRadius())/transform->Scale; + //sprite->SpriteFile = "Textures/Ball.png"; + m_World->CommitEntity(t_waterparticle); + + m_EntitiesToParticleHandle.insert(std::make_pair(t_waterparticle, m_ParticleSystem->GetParticleHandleFromIndex(i))); + m_ParticleHandleToEntities.insert(std::make_pair( m_ParticleSystem->GetParticleHandleFromIndex(i), t_waterparticle)); + } + + } + LOG_INFO("ParticleCount: %i", m_ParticleSystem->GetParticleCount()); +} + dd::Systems::PhysicsSystem::~PhysicsSystem() { if (m_ContactListener != nullptr) { diff --git a/src/game/Physics/PhysicsSystem.cpp.orig b/src/game/Physics/PhysicsSystem.cpp.orig new file mode 100755 index 0000000..7fb8bc1 --- /dev/null +++ b/src/game/Physics/PhysicsSystem.cpp.orig @@ -0,0 +1,363 @@ +#include "PrecompiledHeader.h" +#include "Physics/PhysicsSystem.h" + + + +void dd::Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) +{ + cf->Register(); +} + +void dd::Systems::PhysicsSystem::Initialize() +{ + m_ContactListener = new ContactListener(this); + + m_Gravity = b2Vec2(0.f, -9.82f); + m_PhysicsWorld = new b2World(m_Gravity); + + m_TimeStep = 1.f/60.f; + m_VelocityIterations = 6; + m_PositionIterations = 2; + m_Accumulator = 0.f; + + m_PhysicsWorld->SetContactListener(m_ContactListener); + + InitializeWater(); + + EVENT_SUBSCRIBE_MEMBER(m_SetImpulse, PhysicsSystem::SetImpulse); +} + +void dd::Systems::PhysicsSystem::InitializeWater() +{ + b2ParticleSystemDef m_ParticleSystemDef; + m_ParticleSystemDef.radius = 0.13f; + + m_ParticleSystem = m_PhysicsWorld->CreateParticleSystem(&m_ParticleSystemDef); +} + +bool dd::Systems::PhysicsSystem::SetImpulse(const Events::SetImpulse &event) +{ + b2Body* body = m_EntitiesToBodies[event.Entity]; + + b2Vec2 impulse; + impulse.x = event.Impulse.x; + impulse.y = event.Impulse.y; + + b2Vec2 point; + point.x = event.Point.x; + point.y = event.Point.y; + + + Impulse i; + i.Body = body; + i.Impulse = impulse; + i.Point = point; + + m_Impulses.push_back(i); + + return true; +} + +void dd::Systems::PhysicsSystem::Update(double dt) +{ + + m_Accumulator += dt; + while(m_Accumulator >= m_TimeStep) + { + + for (auto i : m_EntitiesToBodies) { + EntityID entity = i.first; + b2Body* body = i.second; + + auto transformComponent = m_World->GetComponent(entity); + if (! transformComponent) { + continue; + LOG_ERROR("RigidBody with no TransformComponent"); + } + auto physicsComponent = m_World->GetComponent(entity); + if (! physicsComponent) { + continue; + LOG_ERROR("RigidBody with no PhysicsComponent"); + } + + + if (body == nullptr) { + LOG_ERROR("This body should not exist"); + continue; + } + + if (m_World->GetEntityParent(entity) == 0) { //TODO: Make this work with childs too + b2Vec2 position; + position.x = transformComponent->Position.x; + position.y = transformComponent->Position.y; + float angle = -glm::eulerAngles(transformComponent->Orientation).z; + body->SetTransform(position, angle); + body->SetLinearVelocity(b2Vec2(transformComponent->Velocity.x, transformComponent->Velocity.y)); + + body->SetGravityScale(physicsComponent->GravityScale); + +<<<<<<< HEAD + + b2Filter filter; + filter.categoryBits = physicsComponent->Category; + filter.maskBits = physicsComponent->Mask; + body->GetFixtureList()->SetFilterData(filter); + } + } + + for (auto i : m_Impulses) { + i.Body->ApplyLinearImpulse(i.Impulse, i.Point, true); +======= +>>>>>>> origin/master + } + m_Impulses.clear(); + + +<<<<<<< HEAD + + +======= + for (auto i : m_Impulses) { + i.Body->ApplyLinearImpulse(i.Impulse, i.Point, true); + } + m_Impulses.clear(); + m_Accumulator += dt; + while(m_Accumulator >= m_TimeStep) + { +>>>>>>> origin/master + m_PhysicsWorld->Step(m_TimeStep, m_VelocityIterations, m_PositionIterations); + m_Accumulator -= dt; + +<<<<<<< HEAD + +======= + for (auto i : m_EntitiesToBodies) { + EntityID entity = i.first; + b2Body* body = i.second; +>>>>>>> origin/master + + for (auto i : m_EntitiesToBodies) { + EntityID entity = i.first; + b2Body* body = i.second; + + if (body == nullptr) { + LOG_ERROR("This body should not exist"); + continue; + } + +<<<<<<< HEAD + auto transformComponent = m_World->GetComponent(entity); + if (! transformComponent) + continue; + if (m_World->GetEntityParent(entity) == 0) { + b2Vec2 position = body->GetPosition(); + transformComponent->Position.x = position.x; + transformComponent->Position.y = position.y; +======= + auto transformComponent = m_World->GetComponent(entity); + if (! transformComponent) + continue; + auto parent = m_World->GetEntityParent(entity); + if (parent == 0) { + b2Vec2 position = body->GetPosition(); + transformComponent->Position.x = position.x; + transformComponent->Position.y = position.y; +>>>>>>> origin/master + + float angle = body->GetAngle(); + + + transformComponent->Orientation = glm::quat(glm::vec3(0, 0, -angle)); + +<<<<<<< HEAD + b2Vec2 velocity = body->GetLinearVelocity(); + transformComponent->Velocity.x = velocity.x; + transformComponent->Velocity.y = velocity.y; + + } +======= +>>>>>>> origin/master + } + } + + b2Vec2* positionBuffer = m_ParticleSystem->GetPositionBuffer(); + for (auto i : m_EntitiesToParticleHandle) { + EntityID entity = i.first; + b2ParticleHandle* particleH = i.second; + + b2Vec2 positionB2 = positionBuffer[particleH->GetIndex()]; + glm::vec2 position = glm::vec2(positionB2.x, positionB2.y); + + + EntityID entityParent = m_World->GetEntityParent(entity); + auto transform = m_World->GetComponent(entity); + auto transformParent = m_World->GetComponent(entityParent); + + transform->Position = glm::vec3(position.x, position.y, -10) - transformParent->Position; + } +} + +void dd::Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) +{ + +} + +void dd::Systems::PhysicsSystem::OnEntityCommit(EntityID entity) +{ + auto physicsComponent = m_World->GetComponent(entity); + auto waterComponent = m_World->GetComponent(entity); + + if (physicsComponent && waterComponent) { + LOG_ERROR("Entity has both water and physics component, this is illegal. The police has been alerted."); + return; + } + if (physicsComponent) { + CreateBody(entity); + } else if (waterComponent) { + CreateParticleGroup(entity); + } +} + + +void dd::Systems::PhysicsSystem::OnEntityRemoved(EntityID entity) +{ + auto physics = m_World->GetComponent(entity); + if (physics == nullptr) { + return; + } + + b2Body* body = m_EntitiesToBodies[entity]; + + if (body != nullptr) { + m_EntitiesToBodies.erase(entity); + m_BodiesToEntities.erase(body); + + m_PhysicsWorld->DestroyBody(body); + } + +} + + +void dd::Systems::PhysicsSystem::CreateBody(EntityID entity) +{ + auto physicsComponent = m_World->GetComponent(entity); + if(!physicsComponent){ + LOG_ERROR("No PhysicsComponent in CreateBody"); + return; + } + + + auto transformComponent = m_World->GetComponent(entity); + if(!transformComponent) { + LOG_ERROR("No TransformComponent in CreateBody"); + return; + } + + auto absoluteTransform = m_World->GetSystem()->AbsoluteTransform(entity); + + b2BodyDef bodyDef; + bodyDef.position.Set(absoluteTransform.Position.x, absoluteTransform.Position.y); + bodyDef.angle = -glm::eulerAngles(absoluteTransform.Orientation).z; + + if (physicsComponent->Static) { + bodyDef.type = b2_staticBody; + } else { + bodyDef.type = b2_dynamicBody; + + } + + b2Body* body = m_PhysicsWorld->CreateBody(&bodyDef); + + b2Shape* pShape; + + auto boxComponent = m_World->GetComponent(entity); + if (boxComponent) { + b2PolygonShape* bShape = new b2PolygonShape(); + bShape->SetAsBox(absoluteTransform.Scale.x/2, absoluteTransform.Scale.y/2); + pShape = bShape; + } else { + auto circleComponent = m_World->GetComponent(entity); + if (circleComponent) { + pShape = new b2CircleShape(); + pShape->m_radius = absoluteTransform.Scale.x; + + + if (absoluteTransform.Scale.x != absoluteTransform.Scale.y && absoluteTransform.Scale.y != absoluteTransform.Scale.z) { + LOG_WARNING("Circles has to be of uniform scale."); + } + pShape->m_radius = absoluteTransform.Scale.x/2; + + } + } + + b2FixtureDef fixtureDef; + fixtureDef.shape = pShape; + fixtureDef.filter.categoryBits = physicsComponent->Category; + fixtureDef.filter.maskBits = physicsComponent->Mask; + + + if(physicsComponent->Static) { + body->CreateFixture(&fixtureDef); //Density kanske ska vara 0 på statiska kroppar + } + else { + fixtureDef.shape = pShape; + fixtureDef.density = 1.f; + fixtureDef.restitution = 1.0f; + fixtureDef.friction = 0.0f; + body->CreateFixture(&fixtureDef); + + } + + delete pShape; + + + body->SetGravityScale(physicsComponent->GravityScale); + m_EntitiesToBodies.insert(std::make_pair(entity, body)); + m_BodiesToEntities.insert(std::make_pair(body, entity)); +} + +void dd::Systems::PhysicsSystem::CreateParticleGroup(EntityID e) +{ + //TODO: Lägg alla pd i en lista + auto transform = m_World->GetComponent(e); + if (!transform) { + LOG_ERROR("No Transform component in CreateParticleGroup"); + return; + } + + b2ParticleGroupDef pd; + b2PolygonShape shape; + + shape.SetAsBox(transform->Scale.x/2.f, transform->Scale.y/2.f); + pd.shape = &shape; + pd.flags = b2_tensileParticle; + pd.position.Set(transform->Position.x, transform->Position.y); + //TODO: PUT IN LIST + t_watergroup = m_ParticleSystem->CreateParticleGroup(pd); + b2Vec2* t_ParticlePositions = m_ParticleSystem->GetPositionBuffer(); + for(int i = 0; i < m_ParticleSystem->GetParticleCount(); i++){ + { + auto t_waterparticle = m_World->CreateEntity(e); + auto transformChild = m_World->AddComponent(t_waterparticle); + //auto sprite = m_World->AddComponent(t_waterparticle); + + transformChild->Position = glm::vec3(t_ParticlePositions[i].x - transform->Position.x, t_ParticlePositions[i].y - transform->Position.y, -9.5f); + transformChild->Scale = glm::vec3(m_ParticleSystem->GetRadius())/transform->Scale; + //sprite->SpriteFile = "Textures/Ball.png"; + m_World->CommitEntity(t_waterparticle); + + m_EntitiesToParticleHandle.insert(std::make_pair(t_waterparticle, m_ParticleSystem->GetParticleHandleFromIndex(i))); + m_ParticleHandleToEntities.insert(std::make_pair( m_ParticleSystem->GetParticleHandleFromIndex(i), t_waterparticle)); + } + + } + LOG_INFO("ParticleCount: %i", m_ParticleSystem->GetParticleCount()); +} + +dd::Systems::PhysicsSystem::~PhysicsSystem() +{ + if (m_ContactListener != nullptr) { + delete m_ContactListener; + m_ContactListener = nullptr; + } +} diff --git a/src/game/Sound/SoundSystem.cpp b/src/game/Sound/SoundSystem.cpp index aaca752..90939a1 100644 --- a/src/game/Sound/SoundSystem.cpp +++ b/src/game/Sound/SoundSystem.cpp @@ -22,36 +22,29 @@ void dd::Systems::SoundSystem::Initialize() alGetError(); + //Probably unnecessary. vec3(0) probably default. const ALfloat pos[3] = {0, 0, 0}; - alListenerfv(AL_POSITION, pos); + //alListenerfv(AL_POSITION, pos); + + m_SFXMasterVolume = 1.f; + m_BGMMasterVolume = 1.f; //Subscribe to events EVENT_SUBSCRIBE_MEMBER(m_EContact, &SoundSystem::OnContact); EVENT_SUBSCRIBE_MEMBER(m_EPlaySFX, &SoundSystem::OnPlaySound); EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundSystem::OnStopSound); + EVENT_SUBSCRIBE_MEMBER(m_EMasterVolume, &SoundSystem::OnMasterVolume); + + - //Todo: Move this - { - dd::Events::PlaySound e; - e.path = "Sounds/BGM/soft-guitar.wav"; - e.loop = true; - EventBroker->Publish(e); - } - { - dd::Events::PlaySound e; - e.path = "Sounds/BGM/water-flowing.wav"; - e.volume = 0.3f; - e.loop = true; - EventBroker->Publish(e); - } } void dd::Systems::SoundSystem::Update(double dt) { - //LOG_INFO("Sources : %i", m_SourcesToBuffers.size()); - + //Clean up none-active sources + //Only used for SFX's. BGM's are handled on stop sound. std::vector deleteList; - for (auto item : m_SourcesToBuffers) { + for (auto item : m_SFXSourcesToBuffers) { ALint sourceState; alGetSourcei(item.first, AL_SOURCE_STATE, &sourceState); if (sourceState == AL_STOPPED) { @@ -62,9 +55,8 @@ void dd::Systems::SoundSystem::Update(double dt) for (int i = 0; i < deleteList.size(); i++) { alDeleteSources(1, &deleteList[i]); //alDeleteBuffers(1, &m_SourcesToBuffers[deleteList[i]]); - m_SourcesToBuffers.erase(deleteList[i]); + m_SFXSourcesToBuffers.erase(deleteList[i]); } - } ALuint dd::Systems::SoundSystem::CreateSource() @@ -83,21 +75,27 @@ bool dd::Systems::SoundSystem::OnPlaySound(const dd::Events::PlaySound &event) return false; } ALuint source = CreateSource(); - m_SourcesToBuffers[source] = sound; ALuint buffer = sound->Buffer(); alSourcei(source, AL_BUFFER, buffer); //Sound settings - alSourcef(source, AL_GAIN, event.volume); - alSourcef(source, AL_PITCH, event.pitch); - if (event.loop) { + float relativeVolume = 1.f; + if (event.isAmbient) { alSourcei(source, AL_LOOPING, AL_TRUE); + relativeVolume = m_BGMMasterVolume; + m_BGMSourcesToBuffers[source] = sound; + } - else if (!event.loop) + else if (!event.isAmbient) { + m_SFXSourcesToBuffers[source] = sound; alSourcei(source, AL_LOOPING, AL_FALSE); + relativeVolume = m_SFXMasterVolume; } + alSourcef(source, AL_GAIN, (event.volume * relativeVolume)); + alSourcef(source, AL_PITCH, event.pitch); + //Play alSourcePlay(source); @@ -106,15 +104,53 @@ bool dd::Systems::SoundSystem::OnPlaySound(const dd::Events::PlaySound &event) bool dd::Systems::SoundSystem::OnStopSound(const dd::Events::StopSound &event) { - for (auto item : m_SourcesToBuffers) { + + //TODO: Delete sources for bgms + ALuint itemToDelete; + for (auto item : m_BGMSourcesToBuffers) + { + if (item.second->Path() == event.path) { + itemToDelete = item.first; + break; + } + } + alSourceStop(itemToDelete); + alDeleteSources(1, &itemToDelete); + m_BGMSourcesToBuffers.erase(itemToDelete); + + //Should not because SFX's should be very short. + for (auto item : m_SFXSourcesToBuffers) + { if (item.second->Path() == event.path) { alSourceStop(item.first); return true; } } + return false; } +bool dd::Systems::SoundSystem::OnMasterVolume(const dd::Events::MasterVolume &event) +{ + //TODO: Make the volume depend on the value given when stored. + //TODO: .. now it ONLY uses the master volume + if (event.isAmbient) { + m_BGMMasterVolume = event.gain; + for (auto item : m_BGMSourcesToBuffers) + { + alSourcef(item.first, AL_GAIN, event.gain); + } + } + else if (!event.isAmbient) { + m_SFXMasterVolume = event.gain; + for (auto item : m_SFXSourcesToBuffers) + { + alSourcef(item.first, AL_GAIN, event.gain); + } + } +} + +//On contact: play the sound given in the CCOllisionSound. bool dd::Systems::SoundSystem::OnContact(const dd::Events::Contact &event) { //Check which entity has the collisionSound component. @@ -127,16 +163,12 @@ bool dd::Systems::SoundSystem::OnContact(const dd::Events::Contact &event) } } - { - dd::Events::StopSound e; - e.path = "Sounds/BGM/soft-guitar.wav"; - EventBroker->Publish(e); - } //Send play-sound event dd::Events::PlaySound e; e.path = collisionSound->filePath; + e.isAmbient = false; EventBroker->Publish(e); - return true; + //return true; }