From cd315bbaa05bb022d36ae80bdacffd0eadd6b71d Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 25 Feb 2016 12:12:44 +0100 Subject: [PATCH 01/19] Added DoubleJump component and JumpSpeed in Player component so jumpheight can be adjusted for regular jump and double jump. --- resources/Schema/Components.xsd | 1 + resources/Schema/Components/DoubleJump.xml | 4 ++++ resources/Schema/Components/DoubleJump.xsd | 16 ++++++++++++++++ resources/Schema/Components/Player.xml | 1 + resources/Schema/Components/Player.xsd | 3 +++ resources/Schema/Entities/Player.xml | 1 + resources/Schema/Entities/PlayerRed.xml | 1 + src/Game/Systems/PlayerMovementSystem.cpp | 17 +++++++++++------ 8 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 resources/Schema/Components/DoubleJump.xml create mode 100644 resources/Schema/Components/DoubleJump.xsd diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 42abed82..e2d07374 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -46,4 +46,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/DoubleJump.xml b/resources/Schema/Components/DoubleJump.xml new file mode 100644 index 00000000..bb0d3bc7 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xml @@ -0,0 +1,4 @@ + + + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/DoubleJump.xsd b/resources/Schema/Components/DoubleJump.xsd new file mode 100644 index 00000000..65ff0419 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xsd @@ -0,0 +1,16 @@ + + + + + + + Enables a Player to double jump. + + + + Vertical velocity set on double jump. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index 00cff257..429aa5fb 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,5 +2,6 @@ 3 1.5 + 4.0 \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 1b33d222..b121fd06 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -11,6 +11,9 @@ + + Vertical velocity set when jumping. + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 7a5d2eb4..569dbc77 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -11,6 +11,7 @@ + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index cd01632e..3285a91f 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -11,6 +11,7 @@ + diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index a144dd18..916573a4 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -116,12 +116,18 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air - if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { - (bool)cPhysics["IsOnGround"] = false; + if (isOnGround) { + controller->SetDoubleJumping(false); + } + //If player presses Jump and is not crouching. + if (controller->Jumping() && !controller->Crouching()) { if (isOnGround) { - controller->SetDoubleJumping(false); - } else { + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["Player"]["JumpSpeed"]; + } else if (player.HasComponent("DoubleJump") && !controller->DoubleJumping()) { + //Enter here if player can double jump and is doing so. + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["DoubleJump"]["DoubleJumpSpeed"]; if (IsClient) { //put a hexagon at the players feet auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); @@ -134,7 +140,6 @@ void PlayerMovementSystem::updateMovementControllers(double dt) m_EventBroker->Publish(e); } } - velocity.y = 4.f; } if (player.HasComponent("AABB")) { From f56705d921aba781fc6845c7bcc27e26e6da2bf3 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Fri, 26 Feb 2016 11:51:20 +0100 Subject: [PATCH 02/19] You can now change the quality of SSAO by sliding the SSAO Quality --- include/Engine/Rendering/DrawFinalPass.h | 8 +- include/Engine/Rendering/IRenderer.h | 1 + include/Engine/Rendering/Renderer.h | 9 +- include/Engine/Rendering/SSAOPass.h | 42 +++- resources/DefaultConfig.ini | 35 ++- resources/Shaders/ForwardPlus.frag.glsl | 3 +- .../Shaders/ForwardPlusSplatMapRGB.frag.glsl | 3 +- resources/Shaders/SSAO.frag.glsl | 19 +- resources/Shaders/SSAO.vert.glsl | 5 + resources/Shaders/SSAOViewSpaceZ.frag.glsl | 6 +- src/Engine/Rendering/CubeMapPass.cpp | 1 + src/Engine/Rendering/DrawFinalPass.cpp | 36 +-- src/Engine/Rendering/FrameBuffer.cpp | 42 ++-- src/Engine/Rendering/Renderer.cpp | 13 +- src/Engine/Rendering/SSAOPass.cpp | 210 +++++++++++++++--- src/Game/Game.cpp | 2 +- 16 files changed, 334 insertions(+), 101 deletions(-) diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 1800c90e..e522cdc5 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -5,6 +5,7 @@ #include "DrawFinalPassState.h" #include "LightCullingPass.h" #include "CubeMapPass.h" +#include "SSAOPass.h" #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" @@ -14,12 +15,12 @@ class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(RenderScene& scene, GLuint SSAOTexture); + void Draw(RenderScene& scene); void ClearBuffer(); void OnWindowResize(); @@ -38,7 +39,7 @@ private: void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; void DrawSprites(std::list>&jobs, RenderScene& scene); - void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture); + void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); void DrawToDepthBuffer(std::list>& jobs, RenderScene& scene); @@ -71,6 +72,7 @@ private: const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; const CubeMapPass* m_CubeMapPass; + const SSAOPass* m_SSAOPass; ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index 4441bb7d..97293f06 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -5,6 +5,7 @@ #include "../OpenGL.h" #include "../GLM.h" #include "../Core/Util/Rectangle.h" +#include "../Core/ConfigFile.h" #include "Util/ScreenCoords.h" #include "Camera.h" #include "RenderQueue.h" diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index f3a6bf31..246b328d 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -32,8 +32,9 @@ class Renderer : public IRenderer static void glfwFrameBufferCallback(GLFWwindow* window, int width, int height); public: - Renderer(EventBroker* eventBroker) - : m_EventBroker(eventBroker) + Renderer(EventBroker* eventBroker, ConfigFile* config) + : m_EventBroker(eventBroker) + , m_Config(config) { } virtual void Initialize() override; @@ -47,6 +48,7 @@ private: //----------------------Variables----------------------// static std::unordered_map m_WindowToRenderer; + ConfigFile* m_Config; EventBroker* m_EventBroker; TextPass* m_TextPass; @@ -67,6 +69,9 @@ private: float m_SSAO_IntensityScale = 1.0f; int m_SSAO_NumOfSamples = 24; int m_SSAO_NumOfTurns = 7; + int m_SSAO_iterations = 9; + int m_SSAO_TextureQuality = 0; + int m_SSAO_Quality = 0; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index 792d1d82..a2cf349d 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -13,18 +13,32 @@ class SSAOPass { public: - SSAOPass(IRenderer* rendere); - ~SSAOPass() { - delete m_DrawBloomPass; - }; + SSAOPass(IRenderer* renderer, ConfigFile* config); + ~SSAOPass() { }; + + void ChangeQuality(int quality); void Draw(GLuint depthBuffer, Camera* camera); - void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); + void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int numOfTurns, int iterations, int quality); void ClearBuffer(); void OnWindowResize(); //Return the SSAO of the texture sent to Draw - GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } + GLuint SSAOTexture() const { + if (m_Quality == 0) { + return m_WhiteTexture->m_Texture; + } else { + return m_GaussianTexture_vert; + } + } + + int TextureQuality() const { + if (m_Quality == 0) { + return 13; + } else { + return m_TextureQuality; + } + } private: void InitializeTexture(); @@ -40,6 +54,7 @@ private: Model* m_ScreenQuad; const IRenderer* m_Renderer; + ConfigFile* m_Config; float m_Radius; float m_Bias; @@ -47,6 +62,11 @@ private: float m_IntensityScale; int m_NumOfSamples; int m_NumOfTurns; + int m_Iterations; + int m_TextureQuality; + int m_Quality; + + Texture* m_WhiteTexture; GLuint m_SSAOTexture; FrameBuffer m_SSAOFramBuffer; @@ -54,10 +74,16 @@ private: GLuint m_SSAOViewSpaceZTexture; FrameBuffer m_SSAOViewSpaceZFramBuffer; + GLuint m_GaussianTexture_horiz; + GLuint m_GaussianTexture_vert; + + FrameBuffer m_GaussianFrameBuffer_horiz; + FrameBuffer m_GaussianFrameBuffer_vert; + ShaderProgram* m_SSAOProgram; ShaderProgram* m_SSAOViewSpaceZProgram; - - DrawBloomPass* m_DrawBloomPass; + ShaderProgram* m_GaussianProgram_horiz; + ShaderProgram* m_GaussianProgram_vert; }; #endif \ No newline at end of file diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 60ee4823..d4696bba 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -36,4 +36,37 @@ ResourceLoading=true [Sound] BGMVolume=1.0 SFXVolume=1.0 -Announcer=female \ No newline at end of file +Announcer=female + +[SSAO] +Quality=0 + +[SSAO1] +Radius=1.0 +Bias=0.02 +Contrast=1.5 +Intensity=1.0 +NumSamples=8 +NumTurns=3 +NumIterations=5 +TextureQuality=2 + +[SSAO2] +Radius=1.0 +Bias=0.02 +Contrast=1.5 +Intensity=1.0 +NumSamples=16 +NumTurns=13 +NumIterations=9 +TextureQuality=1 + +[SSAO3] +Radius=1.0 +Bias=0.02 +Contrast=1.5 +Intensity=1.0 +NumSamples=24 +NumTurns=17 +NumIterations=13 +TextureQuality=0 \ No newline at end of file diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 6fbc9c27..00f95888 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -13,6 +13,7 @@ uniform vec4 AmbientColor; uniform float FillPercentage; uniform float GlowIntensity = 10; uniform vec3 CameraPosition; +uniform int SSAOQuality; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; @@ -125,7 +126,7 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu void main() { - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl index cf358b96..c67a9c99 100644 --- a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -11,6 +11,7 @@ uniform vec4 DiffuseColor; uniform vec4 FillColor; uniform vec4 Color; uniform vec4 AmbientColor; +uniform int SSAOQuality; //Get bineded at the same time as the textures uniform vec2 DiffuseUVRepeat1; @@ -177,7 +178,7 @@ vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, void main() { - float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy) >> int(SSAOQuality), 0).r; ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl index 68c830f8..749881c4 100644 --- a/resources/Shaders/SSAO.frag.glsl +++ b/resources/Shaders/SSAO.frag.glsl @@ -2,11 +2,11 @@ //Number of samples per pixel uniform int uNumOfSamples; -//#define NUM_SAMPLES (11) +//#define uNumOfSamples (11) //Number of turns around the cirle uniform int uNumOfTurns; -//#define NUM_TURNS (7) +//#define uNumOfTurns (7) layout (binding = 0) uniform sampler2D ViewSpaceZ; @@ -16,15 +16,16 @@ uniform float uProjScale; //#define ProjScale 500 uniform float uRadius; -//#define Radius 1.0f +//#define uRadius 1.0f uniform float uBias; -//#define Bias 0.012f +//#define uBias 0.05f uniform float uContrast; -//#define IntensityDivR6 1 +//#define uContrast 1.5f uniform float uIntensityScale; +//#define uIntensityScale 1.0f out float AO; @@ -88,13 +89,7 @@ void main() { vec3 origin = getVSPosition(originScreenCoord); - float radius; - if(origin.z < uRadius){ - radius = origin.z; - } else { - radius = uRadius; - } - + float radius = min(origin.z, uRadius); vec3 originNormal = getVSFaceNormal(origin); diff --git a/resources/Shaders/SSAO.vert.glsl b/resources/Shaders/SSAO.vert.glsl index a019c5ef..346bc141 100644 --- a/resources/Shaders/SSAO.vert.glsl +++ b/resources/Shaders/SSAO.vert.glsl @@ -2,7 +2,12 @@ layout (location = 0) in vec3 Position; +out VertexData{ + vec2 TextureCoordinate; +}Output; + void main() { gl_Position = vec4(Position, 1.0); + Output.TextureCoordinate = (vec2(Position) + 1) / 2; } \ No newline at end of file diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl index dbcfd899..d1bf6f17 100644 --- a/resources/Shaders/SSAOViewSpaceZ.frag.glsl +++ b/resources/Shaders/SSAOViewSpaceZ.frag.glsl @@ -3,11 +3,15 @@ layout (binding = 0) uniform sampler2D DepthBuffer; uniform vec3 ClipInfo; +in VertexData{ + vec2 TextureCoordinate; +}Input; + out float depthLinear; //Just for Debug, should be depthLinear //out vec4 fragmentColor; void main() { - float depthSample = texelFetch(DepthBuffer, ivec2(gl_FragCoord.xy), 0).r; + float depthSample = texture2D(DepthBuffer, Input.TextureCoordinate).r; depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); //float depthLinear = (NearClip) / ( -depthSample + 1.0f); //fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index 75f5e1c9..fc318498 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -17,6 +17,7 @@ void CubeMapPass::LoadTextures(std::string input) m_CubeMapTextures.push_back(img); } GenerateCubeMapTexture(); + m_PreviusCubeMapTexture = input; } } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 6cd2c1f1..48c07941 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,9 +1,9 @@ #include "Rendering/DrawFinalPass.h" - -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass) - : m_Renderer(renderer) - , m_LightCullingPass(lightCullingPass) - , m_CubeMapPass(cubeMapPass) +DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass) + : m_Renderer(renderer) + , m_LightCullingPass(lightCullingPass) + , m_CubeMapPass(cubeMapPass) + , m_SSAOPass(ssaoPass) { //TODO: Make sure that uniforms are not sent into shader if not needed. m_ShieldPixelRate = 8; @@ -175,7 +175,7 @@ void DrawFinalPass::InitializeShaderPrograms() GLERROR("Creating DepthFill program"); } -void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) +void DrawFinalPass::Draw(RenderScene& scene) { GLERROR("Pre"); DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); @@ -191,10 +191,10 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) //Fill depth buffer state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); state->BlendFunc(GL_ONE, GL_ONE); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawSprites(scene.Jobs.SpriteJob, scene); @@ -210,11 +210,11 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) //Draw Opaque shielded objects state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene, SSAOTexture); //might need changing + DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing GLERROR("Shielded Opaque object"); //Draw Transparen Shielded objects - DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene, SSAOTexture); //might need changing + DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene); //might need changing GLERROR("Shielded Transparent objects"); GLERROR("END"); @@ -250,9 +250,9 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) stateLowRes->Enable(GL_DEPTH_TEST); stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); stateLowRes->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); @@ -340,7 +340,7 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: GLERROR("MipMap Texture initialization failed"); } -void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); @@ -364,7 +364,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, SSAOTexture); + glBindTexture(GL_TEXTURE_2D, m_SSAOPass->SSAOTexture()); for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); @@ -383,7 +383,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + glUniform3fv(glGetUniformLocation(explosionSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); std::vector frameBones; if (explosionEffectJob->AnimationOffset.animation != nullptr) { @@ -401,7 +401,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionTextures(explosionHandle, explosionEffectJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + glUniform3fv(glGetUniformLocation(explosionHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); } break; @@ -463,7 +463,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelTextures(forwardSkinnedHandle, modelJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); - glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + glUniform3fv(glGetUniformLocation(forwardSkinnedHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); std::vector frameBones; if (modelJob->AnimationOffset.animation != nullptr) { @@ -753,6 +753,7 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + glUniform1i(glGetUniformLocation(shaderHandle, "SSAOQuality"), m_SSAOPass->TextureQuality()); GLERROR("Bind 1 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); GLERROR("Bind 2 uniform"); @@ -801,6 +802,7 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + glUniform1i(glGetUniformLocation(shaderHandle, "SSAOQuality"), m_SSAOPass->TextureQuality()); GLERROR("Bind 1 uniform"); GLint Location_M = glGetUniformLocation(shaderHandle, "M"); glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 794fb84e..9ba0d2d8 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -42,33 +42,33 @@ void FrameBuffer::Generate() GLERROR("PRE"); std::vector attachments; - - glGenFramebuffers(1, &m_BufferHandle); + if (m_BufferHandle == 0) { + glGenFramebuffers(1, &m_BufferHandle); + } glBindFramebuffer(GL_FRAMEBUFFER, m_BufferHandle); GLERROR("1"); - for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { - switch ((*it)->m_ResourceType) { - case GL_TEXTURE_2D: - glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0); - GLERROR("FrameBuffer generate: glFramebufferTexture2D"); + for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { + switch ((*it)->m_ResourceType) { + case GL_TEXTURE_2D: + glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0); + GLERROR("FrameBuffer generate: glFramebufferTexture2D"); - break; - case GL_RENDERBUFFER: - glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); - GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); - break; - } - GLERROR("2"); + break; + case GL_RENDERBUFFER: + glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); + GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); + break; + } + GLERROR("2"); - if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { - attachments.push_back((*it)->m_Attachment); - } - GLERROR("Attachment"); - - } - GLERROR("3"); + if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { + attachments.push_back((*it)->m_Attachment); + } + GLERROR("Attachment"); + } + GLERROR("3"); GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 251bba2b..fcf2bc84 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -121,7 +121,11 @@ void Renderer::Draw(RenderFrame& frame) ImGui::SliderFloat("SSAO IntensityScale", &m_SSAO_IntensityScale, 0.0f, 10.0f); ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); - m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); + ImGui::SliderInt("SSAO Blur Iterations", &m_SSAO_iterations, 0, 20); + ImGui::SliderInt("SSAO TextureQuality", &m_SSAO_TextureQuality, 0, 4); + ImGui::SliderInt("SSAO Quality", &m_SSAO_Quality, 0, 3); + //m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns, m_SSAO_iterations, m_SSAO_TextureQuality); + m_SSAOPass->ChangeQuality(m_SSAO_Quality); GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); @@ -159,7 +163,7 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StartTimerAndStopPrevious("Renderer-Light Culling"); m_LightCullingPass->CullLights(*scene); GLERROR("LightCulling"); - m_DrawFinalPass->Draw(*scene, ao); + m_DrawFinalPass->Draw(*scene); PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); @@ -248,9 +252,10 @@ void Renderer::InitializeRenderPasses() m_PickingPass = new PickingPass(this, m_EventBroker); m_LightCullingPass = new LightCullingPass(this); m_CubeMapPass = new CubeMapPass(this); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass); + m_SSAOPass = new SSAOPass(this, m_Config); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_SSAOPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); - m_SSAOPass = new SSAOPass(this); + } diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index d4cdcb19..7d39e34a 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -1,50 +1,134 @@ #include "Rendering/SSAOPass.h" -SSAOPass::SSAOPass(IRenderer* renderer) +SSAOPass::SSAOPass(IRenderer* renderer, ConfigFile* config) + : m_Renderer(renderer) + , m_Config(config) { - m_Renderer = renderer; + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); + + m_Quality = m_Config->Get("SSAO.Quality", 0); + if (m_Quality == 0) { + return; + } + + ChangeQuality(m_Quality); + +} + +void SSAOPass::ChangeQuality(int quality) +{ + if (m_Quality == quality) { + return; + } + + m_Quality = quality; + + if (m_Quality == 0) { + glDeleteTextures(1, &m_SSAOTexture); + glDeleteTextures(1, &m_SSAOViewSpaceZTexture); + glDeleteTextures(1, &m_GaussianTexture_horiz); + glDeleteTextures(1, &m_GaussianTexture_vert); + return; + } + + std::string qStr = std::to_string(m_Quality); + Setting( + m_Config->Get("SSAO" + qStr + ".Radius", 0.01), + m_Config->Get("SSAO" + qStr + ".Bias", 0.012), + m_Config->Get("SSAO" + qStr + ".Contrast", 1.0), + m_Config->Get("SSAO" + qStr + ".Intensity", 1.0), + m_Config->Get("SSAO" + qStr + ".NumSamples", 0), + m_Config->Get("SSAO" + qStr + ".NumTurns", 0), + m_Config->Get("SSAO" + qStr + ".NumIterations", 0), + m_Config->Get("SSAO" + qStr + ".TextureQuality", 4) + ); + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); InitializeTexture(); InitializeBuffer(); InitializeShaderProgram(); - Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); - m_DrawBloomPass = new DrawBloomPass(renderer); + } void SSAOPass::InitializeShaderProgram() { m_SSAOProgram = ResourceManager::Load("##SSAOProgram"); - m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); - m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); - m_SSAOProgram->Compile(); - m_SSAOProgram->Link(); + if (m_SSAOProgram->GetHandle() == 0) { + m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); + m_SSAOProgram->Compile(); + m_SSAOProgram->Link(); + } m_SSAOViewSpaceZProgram = ResourceManager::Load("##SSAOViewSpaceZProgram"); - m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); - m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); - m_SSAOViewSpaceZProgram->Compile(); - m_SSAOViewSpaceZProgram->Link(); + if (m_SSAOViewSpaceZProgram->GetHandle() == 0) { + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); + m_SSAOViewSpaceZProgram->Compile(); + m_SSAOViewSpaceZProgram->Link(); + } + + m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); + if (m_GaussianProgram_horiz->GetHandle() == 0) { + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); + m_GaussianProgram_horiz->Compile(); + m_GaussianProgram_horiz->Link(); + } + + m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); + if (m_GaussianProgram_vert->GetHandle() == 0) { + m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); + m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); + m_GaussianProgram_vert->Compile(); + m_GaussianProgram_vert->Link(); + } } void SSAOPass::InitializeTexture() { - GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); - GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); + + GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); + GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); } void SSAOPass::InitializeBuffer() { - m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); - m_SSAOFramBuffer.Generate(); + if (m_SSAOFramBuffer.GetHandle() == 0) { + m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); + } + m_SSAOFramBuffer.Generate(); + + + if (m_SSAOViewSpaceZFramBuffer.GetHandle() == 0) { + m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); + } + m_SSAOViewSpaceZFramBuffer.Generate(); + + + + if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { + m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); + } + m_GaussianFrameBuffer_horiz.Generate(); + + + if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { + m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); + } + m_GaussianFrameBuffer_vert.Generate(); - m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); - m_SSAOViewSpaceZFramBuffer.Generate(); } void SSAOPass::ClearBuffer() { + return; + m_SSAOFramBuffer.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -54,19 +138,32 @@ void SSAOPass::ClearBuffer() glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_SSAOViewSpaceZFramBuffer.Unbind(); + + m_GaussianFrameBuffer_horiz.Bind(); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_GaussianFrameBuffer_horiz.Unbind(); + + m_GaussianFrameBuffer_vert.Bind(); + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_GaussianFrameBuffer_vert.Unbind(); } -void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns) { +void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int numOfTurns, int iterations, int quality) { m_Radius = radius; m_Bias = bias; m_Contrast = contrast; m_IntensityScale = intensityScale; m_NumOfSamples = numOfSamples; - m_NumOfTurns = NumOfTurns; + m_NumOfTurns = numOfTurns; + m_Iterations = iterations; + m_TextureQuality = quality; } void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { + glDeleteTextures(1, texture); glGenTextures(1, texture); glBindTexture(GL_TEXTURE_2D, *texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); @@ -79,6 +176,10 @@ void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filterin void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) { + if (m_Quality == 0) { + return; + } + SSAOPassState state; GLuint viewSpaceZPShaderHandle = m_SSAOViewSpaceZProgram->GetHandle(); GLuint SSAOShaderHandle = m_SSAOProgram->GetHandle(); @@ -98,6 +199,7 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) (-1.0f), (+1.0f) );*/ + glViewport(0, 0, (m_Renderer->GetViewportSize().Width >> m_TextureQuality), (m_Renderer->GetViewportSize().Height >> m_TextureQuality)); //JOHAN TODO: Get this into state glUniform3fv(glGetUniformLocation(viewSpaceZPShaderHandle, "ClipInfo"), 1, glm::value_ptr(clipInfo)); glBindVertexArray(m_ScreenQuad->VAO); @@ -107,9 +209,9 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) glm::vec4 projInfo = glm::vec4( ((1.0 - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), - (-2.0 / (m_Renderer->GetViewportSize().Width * camera->ProjectionMatrix()[0][0])), + (-2.0 / ((m_Renderer->GetViewportSize().Width >> m_TextureQuality) * camera->ProjectionMatrix()[0][0])), ((1.0 + camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]), - (-2.0 / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])) + (-2.0 / ((m_Renderer->GetViewportSize().Height >> m_TextureQuality) * camera->ProjectionMatrix()[1][1])) ); @@ -120,26 +222,76 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); // How many pixel there are in a 1m long object 1m away from the camera - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(camera->FOV() * 0.5f))); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), (m_Renderer->GetViewportSize().Height >> m_TextureQuality) / (-2.0f * glm::tan(camera->FOV() * 0.5f))); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uContrast"), m_Contrast); glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uIntensityScale"), m_IntensityScale); glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfSamples"), m_NumOfSamples); - glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns);; + glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns); glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "uProjInfo"), 1, glm::value_ptr(projInfo)); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); - m_DrawBloomPass->ClearBuffer(); - m_DrawBloomPass->Draw(m_SSAOTexture); + DrawBloomPassState BloomState; + GLuint shaderHandle_horiz = m_GaussianProgram_horiz->GetHandle(); + GLuint shaderHandle_vert = m_GaussianProgram_vert->GetHandle(); + + m_GaussianFrameBuffer_horiz.Bind(); + m_GaussianProgram_horiz->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_SSAOTexture); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + //Iterate some times to make it more gaussian. + for (int i = 1; i < m_Iterations; i++) { + //Vertical pass + m_GaussianFrameBuffer_vert.Bind(); + m_GaussianProgram_vert->Bind(); + + glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + //horizontal pass + + m_GaussianFrameBuffer_horiz.Bind(); + m_GaussianProgram_horiz->Bind(); + + glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert); + + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + } + + //final vertical gaussian after the iterations are done + + m_GaussianFrameBuffer_vert.Bind(); + m_GaussianProgram_vert->Bind(); + + glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); + glBindVertexArray(m_ScreenQuad->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + + glViewport(0, 0, (m_Renderer->GetViewportSize().Width), (m_Renderer->GetViewportSize().Height)); } void SSAOPass::OnWindowResize() { - m_DrawBloomPass->OnWindowResize(); + if (m_Quality == 0) { + return; + } + InitializeTexture(); - m_SSAOFramBuffer.Generate(); - m_SSAOViewSpaceZFramBuffer.Generate(); } \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 24b7cd1e..3495730e 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -54,7 +54,7 @@ Game::Game(int argc, char* argv[]) m_EventBroker = new EventBroker(); // Create the renderer - m_Renderer = new Renderer(m_EventBroker); + m_Renderer = new Renderer(m_EventBroker, m_Config); m_Renderer->SetFullscreen(m_Config->Get("Video.Fullscreen", false)); m_Renderer->SetVSYNC(m_Config->Get("Video.VSYNC", false)); m_Renderer->SetResolution(Rectangle::Rectangle( From 0805375483accc1e5d5069ed878d79560b809348 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Fri, 26 Feb 2016 13:25:19 +0100 Subject: [PATCH 03/19] Deleted SSAO sliders except Quality --- include/Engine/Rendering/Renderer.h | 11 ----------- src/Engine/Rendering/Renderer.cpp | 16 +++------------- 2 files changed, 3 insertions(+), 24 deletions(-) diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 246b328d..47e88e57 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -60,17 +60,6 @@ private: Model* m_UnitQuad; Model* m_UnitSphere; - int m_DebugTextureToDraw = 0; - int m_CubeMapTexture = 0; - bool m_ResizeWindow = false; - float m_SSAO_Radius = 1.0f; - float m_SSAO_Bias = 0.05f; - float m_SSAO_Contrast = 1.5f; - float m_SSAO_IntensityScale = 1.0f; - int m_SSAO_NumOfSamples = 24; - int m_SSAO_NumOfTurns = 7; - int m_SSAO_iterations = 9; - int m_SSAO_TextureQuality = 0; int m_SSAO_Quality = 0; PickingPass* m_PickingPass; diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index fcf2bc84..4c7cd39f 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -115,23 +115,13 @@ void Renderer::Draw(RenderFrame& frame) m_CubeMapPass->LoadTextures("Sky"); } - ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); - ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); - ImGui::SliderFloat("SSAO contrast", &m_SSAO_Contrast, 0.0f, 10.0f); - ImGui::SliderFloat("SSAO IntensityScale", &m_SSAO_IntensityScale, 0.0f, 10.0f); - ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); - ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); - ImGui::SliderInt("SSAO Blur Iterations", &m_SSAO_iterations, 0, 20); - ImGui::SliderInt("SSAO TextureQuality", &m_SSAO_TextureQuality, 0, 4); - ImGui::SliderInt("SSAO Quality", &m_SSAO_Quality, 0, 3); - //m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns, m_SSAO_iterations, m_SSAO_TextureQuality); m_SSAOPass->ChangeQuality(m_SSAO_Quality); GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - //Clear other buffers + //Clear other buffers PerformanceTimer::StartTimer("Renderer-ClearBuffers"); m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); @@ -145,10 +135,10 @@ void Renderer::Draw(RenderFrame& frame) GLERROR("Drawing pickingpass"); PerformanceTimer::StopTimer("Renderer-Depth"); } - PerformanceTimer::StartTimer("AO generation"); + PerformanceTimer::StartTimer("Renderer-AO generation"); m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); GLuint ao = m_SSAOPass->SSAOTexture(); - PerformanceTimer::StopTimer("AO generation"); + PerformanceTimer::StopTimer("Renderer-AO generation"); for (auto scene : frame.RenderScenes){ PerformanceTimer::StartTimer("Renderer-Drawing PickingPass"); From 62e22d38217d1d8184c64bf263b55f9346fbc81f Mon Sep 17 00:00:00 2001 From: Teejoon Date: Fri, 26 Feb 2016 13:32:16 +0100 Subject: [PATCH 04/19] Fix --- include/Engine/Rendering/Renderer.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 47e88e57..4ed57e31 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -60,6 +60,9 @@ private: Model* m_UnitQuad; Model* m_UnitSphere; + int m_DebugTextureToDraw = 0; + int m_CubeMapTexture = 0; + bool m_ResizeWindow = false; int m_SSAO_Quality = 0; PickingPass* m_PickingPass; From b320d8d1e4717c9cb4dd5b922a4f36ca3f63252e Mon Sep 17 00:00:00 2001 From: Teejoon Date: Fri, 26 Feb 2016 18:01:38 +0100 Subject: [PATCH 05/19] WIP --- include/Engine/Rendering/DrawBloomPass.h | 17 +++++-- include/Engine/Rendering/Renderer.h | 1 + include/Engine/Rendering/SSAOPass.h | 2 +- src/Engine/Rendering/DrawBloomPass.cpp | 55 ++++++++++++++++----- src/Engine/Rendering/DrawFinalPass.cpp | 4 +- src/Engine/Rendering/DrawFinalPassState.cpp | 1 + src/Engine/Rendering/Renderer.cpp | 8 ++- src/Engine/Rendering/SSAOPass.cpp | 20 +++----- src/Engine/Rendering/Util/ScreenCoords.cpp | 9 +++- 9 files changed, 84 insertions(+), 33 deletions(-) diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 07c90e23..2fffbdc7 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -12,7 +12,7 @@ class DrawBloomPass { public: - DrawBloomPass(IRenderer* renderer /* ,Texture or finalpass*/ ); + DrawBloomPass(IRenderer* renderer, ConfigFile* config); ~DrawBloomPass() { } void InitializeTextures(); void InitializeFrameBuffers(); @@ -23,23 +23,32 @@ public: void FillGaussianBuffer(FrameBuffer* fb); void Draw(GLuint texture); + void ChangeQuality(int quality); void OnWindowResize(); //Getters //Return the blurred result of the texture that was sent into draw - GLuint GaussianTexture() const { return m_GaussianTexture_vert; } + GLuint GaussianTexture() const { + if (m_Quality == 0) { + return m_BlackTexture->m_Texture; + } else { + return m_GaussianTexture_vert; + } + } private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - Texture* m_WhiteTexture; + Texture* m_BlackTexture; Model* m_ScreenQuad; const IRenderer* m_Renderer; + ConfigFile* m_Config; //const LightCullingPass* m_LightCullingPass - GLuint m_iterations = 9; + int m_Iterations; + int m_Quality = 0; GLuint m_GaussianTexture_horiz; GLuint m_GaussianTexture_vert; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 4ed57e31..a64a4aa3 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -64,6 +64,7 @@ private: int m_CubeMapTexture = 0; bool m_ResizeWindow = false; int m_SSAO_Quality = 0; + int m_GLOW_Quality = 2; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index a2cf349d..ce3f85ed 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -64,7 +64,7 @@ private: int m_NumOfTurns; int m_Iterations; int m_TextureQuality; - int m_Quality; + int m_Quality = 0; Texture* m_WhiteTexture; diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index e8ad4cd5..fe93c167 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -1,19 +1,39 @@ #include "Rendering/DrawBloomPass.h" -DrawBloomPass::DrawBloomPass(IRenderer* renderer) +DrawBloomPass::DrawBloomPass(IRenderer* renderer, ConfigFile* config) + : m_Renderer(renderer) + , m_Config(config) { - m_Renderer = renderer; + InitializeTextures(); - m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + ChangeQuality(m_Config->Get("GLOW.Quality", 2)); +} - InitializeTextures(); - InitializeBuffers(); - InitializeShaderPrograms(); +void DrawBloomPass::ChangeQuality(int quality) +{ + if (m_Quality == quality) { + return; + } + m_Quality = quality; + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + + if (m_Quality == 0) { + glDeleteTextures(1, &m_GaussianTexture_horiz); + glDeleteTextures(1, &m_GaussianTexture_vert); + return; + } + + std::string qStr = std::to_string(m_Quality); + m_Iterations = m_Config->Get("GLOW" + qStr + ".NumIterations", 0); + + InitializeBuffers(); + InitializeShaderPrograms(); } void DrawBloomPass::InitializeTextures() { - m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); + m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); } void DrawBloomPass::InitializeShaderPrograms() @@ -40,18 +60,24 @@ void DrawBloomPass::InitializeBuffers() { GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); + if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { + m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); + } m_GaussianFrameBuffer_horiz.Generate(); GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - - m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); + if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { + m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); + } m_GaussianFrameBuffer_vert.Generate(); } void DrawBloomPass::ClearBuffer() { + if (m_Quality == 0) { + return; + } GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); @@ -66,6 +92,9 @@ void DrawBloomPass::ClearBuffer() void DrawBloomPass::Draw(GLuint texture) { + if (m_Quality == 0) { + return; + } GLERROR("DrawBloomPass::Draw: Pre"); DrawBloomPassState state; @@ -84,7 +113,7 @@ void DrawBloomPass::Draw(GLuint texture) glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //Iterate some times to make it more gaussian. - for (int i = 1; i < m_iterations; i++) { + for (int i = 1; i < m_Iterations; i++) { //Vertical pass m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); @@ -125,6 +154,9 @@ void DrawBloomPass::Draw(GLuint texture) void DrawBloomPass::OnWindowResize() { + if (m_Quality == 0) { + return; + } GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_vert.Generate(); GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); @@ -133,6 +165,7 @@ void DrawBloomPass::OnWindowResize() void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { + glDeleteTextures(1, texture); glGenTextures(1, texture); glBindTexture(GL_TEXTURE_2D, *texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 48c07941..7b373452 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -162,14 +162,14 @@ void DrawFinalPass::InitializeShaderPrograms() m_FillDepthBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); m_FillDepthBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); - m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + //m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); m_FillDepthBufferProgram->Compile(); m_FillDepthBufferProgram->Link(); GLERROR("Creating DepthFill program"); m_FillDepthBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); - m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + //m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); m_FillDepthBufferSkinnedProgram->Compile(); m_FillDepthBufferSkinnedProgram->Link(); GLERROR("Creating DepthFill program"); diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 8b5ddc8b..9741a0ce 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -8,6 +8,7 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) Enable(GL_BLEND); BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); Enable(GL_CULL_FACE); Enable(GL_STENCIL_TEST); StencilFunc(GL_NOTEQUAL, 1, 0xFF); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 4c7cd39f..85c9b97e 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -4,6 +4,8 @@ std::unordered_map Renderer::m_WindowToRenderer; void Renderer::Initialize() { + m_SSAO_Quality = m_Config->Get("SSAO.Quality", 0); + m_GLOW_Quality = m_Config->Get("GLOW.Quality", 0); InitializeWindow(); InitializeRenderPasses(); @@ -107,6 +109,7 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { GLERROR("PRE"); + glBindFramebuffer(GL_FRAMEBUFFER, 0); ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)"); if(m_CubeMapTexture == 0) { @@ -115,7 +118,10 @@ void Renderer::Draw(RenderFrame& frame) m_CubeMapPass->LoadTextures("Sky"); } + ImGui::SliderInt("SSAO Quality", &m_SSAO_Quality, 0, 3); + ImGui::SliderInt("Glow Quality", &m_GLOW_Quality, 0, 3); m_SSAOPass->ChangeQuality(m_SSAO_Quality); + m_DrawBloomPass->ChangeQuality(m_GLOW_Quality); GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); @@ -245,7 +251,7 @@ void Renderer::InitializeRenderPasses() m_SSAOPass = new SSAOPass(this, m_Config); m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_SSAOPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); - m_DrawBloomPass = new DrawBloomPass(this); + m_DrawBloomPass = new DrawBloomPass(this, m_Config); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); } diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 7d39e34a..495fcfc9 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -6,12 +6,7 @@ SSAOPass::SSAOPass(IRenderer* renderer, ConfigFile* config) { m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); - m_Quality = m_Config->Get("SSAO.Quality", 0); - if (m_Quality == 0) { - return; - } - - ChangeQuality(m_Quality); + ChangeQuality(m_Config->Get("SSAO.Quality", 0)); } @@ -102,33 +97,34 @@ void SSAOPass::InitializeBuffer() if (m_SSAOFramBuffer.GetHandle() == 0) { m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); } - m_SSAOFramBuffer.Generate(); + m_SSAOFramBuffer.Generate(); if (m_SSAOViewSpaceZFramBuffer.GetHandle() == 0) { m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); } - m_SSAOViewSpaceZFramBuffer.Generate(); + m_SSAOViewSpaceZFramBuffer.Generate(); if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); } - m_GaussianFrameBuffer_horiz.Generate(); + m_GaussianFrameBuffer_horiz.Generate(); if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); } - m_GaussianFrameBuffer_vert.Generate(); + m_GaussianFrameBuffer_vert.Generate(); } void SSAOPass::ClearBuffer() { - return; - + if (m_Quality == 0) { + return; + } m_SSAOFramBuffer.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); diff --git a/src/Engine/Rendering/Util/ScreenCoords.cpp b/src/Engine/Rendering/Util/ScreenCoords.cpp index 36f1295e..8b7768c8 100644 --- a/src/Engine/Rendering/Util/ScreenCoords.cpp +++ b/src/Engine/Rendering/Util/ScreenCoords.cpp @@ -31,22 +31,27 @@ glm::vec3 ScreenCoords::ToWorldPos(glm::vec2 screenCoord, float depth, float scr ScreenCoords::PixelData ScreenCoords::ToPixelData(float x, float y, FrameBuffer* PickDataBuffer, GLuint DepthBuffer) { + GLERROR("Pre"); PickDataBuffer->Bind(); unsigned char pdata[3]; glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pdata); + GLERROR("glReadPixels(pdata) Error"); PickDataBuffer->Unbind(); - glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer); + GLERROR("glBindFramebuffer(DepthBuffer) Error"); float depthData; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depthData); + GLERROR("glReadPixels(depthData) Error"); glBindFramebuffer(GL_FRAMEBUFFER, 0); + GLERROR("glBindFramebuffer(0) Error"); PixelData p; p.Color[0] = (int)pdata[0]; p.Color[1] = (int)pdata[1]; p.Depth = depthData; - GLERROR("ScreenCoords::ToPixelData Error"); + GLERROR("End"); return p; } From d3a245606ae675871423650cde27378219a7eb55 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Sun, 28 Feb 2016 15:02:40 +0100 Subject: [PATCH 06/19] SSAO and Glow is no longe conflicting with each other. Texture should get the id = 0 when they are deleted and not assigned a new texture after. Else they will start to conflict with each other. --- include/Engine/Rendering/DrawBloomPass.h | 6 ++--- include/Engine/Rendering/SSAOPass.h | 12 ++++----- src/Engine/Rendering/DrawBloomPass.cpp | 30 ++++++++++++++--------- src/Engine/Rendering/Renderer.cpp | 3 +-- src/Engine/Rendering/SSAOPass.cpp | 31 ++++++++++++++++-------- 5 files changed, 49 insertions(+), 33 deletions(-) diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 2fffbdc7..4ddb7e05 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -39,7 +39,7 @@ public: private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); Texture* m_BlackTexture; Model* m_ScreenQuad; @@ -50,8 +50,8 @@ private: int m_Iterations; int m_Quality = 0; - GLuint m_GaussianTexture_horiz; - GLuint m_GaussianTexture_vert; + GLuint m_GaussianTexture_horiz = 0; + GLuint m_GaussianTexture_vert = 0; FrameBuffer m_GaussianFrameBuffer_horiz; FrameBuffer m_GaussianFrameBuffer_vert; diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index ce3f85ed..a5f638cd 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -28,7 +28,7 @@ public: if (m_Quality == 0) { return m_WhiteTexture->m_Texture; } else { - return m_GaussianTexture_vert; + return m_Gaussian_vert; } } @@ -46,7 +46,7 @@ private: void InitializeShaderProgram(); void InitializeBuffer(); - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); //void blurHorizontal(GLuint depthBuffer); //void blurVertical(GLuint depthBuffer); @@ -68,14 +68,14 @@ private: Texture* m_WhiteTexture; - GLuint m_SSAOTexture; + GLuint m_SSAOTexture = 0; FrameBuffer m_SSAOFramBuffer; - GLuint m_SSAOViewSpaceZTexture; + GLuint m_SSAOViewSpaceZTexture = 0; FrameBuffer m_SSAOViewSpaceZFramBuffer; - GLuint m_GaussianTexture_horiz; - GLuint m_GaussianTexture_vert; + GLuint m_Gaussian_horiz = 0; + GLuint m_Gaussian_vert = 0; FrameBuffer m_GaussianFrameBuffer_horiz; FrameBuffer m_GaussianFrameBuffer_vert; diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index fe93c167..4fe885af 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -9,6 +9,11 @@ DrawBloomPass::DrawBloomPass(IRenderer* renderer, ConfigFile* config) ChangeQuality(m_Config->Get("GLOW.Quality", 2)); } +void DrawBloomPass::InitializeTextures() +{ + m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); +} + void DrawBloomPass::ChangeQuality(int quality) { if (m_Quality == quality) { @@ -21,19 +26,16 @@ void DrawBloomPass::ChangeQuality(int quality) if (m_Quality == 0) { glDeleteTextures(1, &m_GaussianTexture_horiz); glDeleteTextures(1, &m_GaussianTexture_vert); + m_GaussianTexture_horiz = 0; + m_GaussianTexture_vert = 0; return; } - - std::string qStr = std::to_string(m_Quality); - m_Iterations = m_Config->Get("GLOW" + qStr + ".NumIterations", 0); + InitializeTextures(); InitializeBuffers(); InitializeShaderPrograms(); -} - -void DrawBloomPass::InitializeTextures() -{ - m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); + std::string qStr = std::to_string(m_Quality); + m_Iterations = m_Config->Get("GLOW" + qStr + ".NumIterations", 0); } void DrawBloomPass::InitializeShaderPrograms() @@ -55,7 +57,6 @@ void DrawBloomPass::InitializeShaderPrograms() } } - void DrawBloomPass::InitializeBuffers() { GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); @@ -63,13 +64,13 @@ void DrawBloomPass::InitializeBuffers() if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); } - m_GaussianFrameBuffer_horiz.Generate(); + m_GaussianFrameBuffer_horiz.Generate(); GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); } - m_GaussianFrameBuffer_vert.Generate(); + m_GaussianFrameBuffer_vert.Generate(); } @@ -118,6 +119,7 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); glBindVertexArray(m_ScreenQuad->VAO); @@ -125,16 +127,19 @@ void DrawBloomPass::Draw(GLuint texture) glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //horizontal pass + m_GaussianFrameBuffer_vert.Unbind(); m_GaussianFrameBuffer_horiz.Bind(); m_GaussianProgram_horiz->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + m_GaussianFrameBuffer_horiz.Unbind(); } //final vertical gaussian after the iterations are done @@ -142,6 +147,7 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); @@ -163,7 +169,7 @@ void DrawBloomPass::OnWindowResize() m_GaussianFrameBuffer_horiz.Generate(); } -void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const +void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) { glDeleteTextures(1, texture); glGenTextures(1, texture); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 85c9b97e..76ee9506 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -143,7 +143,6 @@ void Renderer::Draw(RenderFrame& frame) } PerformanceTimer::StartTimer("Renderer-AO generation"); m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); - GLuint ao = m_SSAOPass->SSAOTexture(); PerformanceTimer::StopTimer("Renderer-AO generation"); for (auto scene : frame.RenderScenes){ @@ -159,8 +158,8 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StartTimerAndStopPrevious("Renderer-Light Culling"); m_LightCullingPass->CullLights(*scene); GLERROR("LightCulling"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); m_DrawFinalPass->Draw(*scene); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 495fcfc9..0ffa5647 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -21,8 +21,12 @@ void SSAOPass::ChangeQuality(int quality) if (m_Quality == 0) { glDeleteTextures(1, &m_SSAOTexture); glDeleteTextures(1, &m_SSAOViewSpaceZTexture); - glDeleteTextures(1, &m_GaussianTexture_horiz); - glDeleteTextures(1, &m_GaussianTexture_vert); + glDeleteTextures(1, &m_Gaussian_horiz); + glDeleteTextures(1, &m_Gaussian_vert); + m_SSAOTexture = 0; + m_SSAOViewSpaceZTexture = 0; + m_Gaussian_horiz = 0; + m_Gaussian_vert = 0; return; } @@ -88,8 +92,8 @@ void SSAOPass::InitializeTexture() { GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); - GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); - GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); + GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); + GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); } void SSAOPass::InitializeBuffer() @@ -108,13 +112,13 @@ void SSAOPass::InitializeBuffer() if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { - m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); + m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_Gaussian_horiz, GL_COLOR_ATTACHMENT0))); } m_GaussianFrameBuffer_horiz.Generate(); if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { - m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); + m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_Gaussian_vert, GL_COLOR_ATTACHMENT0))); } m_GaussianFrameBuffer_vert.Generate(); @@ -157,7 +161,7 @@ void SSAOPass::Setting(float radius, float bias, float contrast, float intensity m_TextureQuality = quality; } -void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const +void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) { glDeleteTextures(1, texture); glGenTextures(1, texture); @@ -251,23 +255,27 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); - glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); //horizontal pass + m_GaussianFrameBuffer_vert.Unbind(); m_GaussianFrameBuffer_horiz.Bind(); m_GaussianProgram_horiz->Bind(); - glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_Gaussian_vert); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + m_GaussianFrameBuffer_horiz.Unbind(); } //final vertical gaussian after the iterations are done @@ -275,12 +283,15 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) m_GaussianFrameBuffer_vert.Bind(); m_GaussianProgram_vert->Bind(); - glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1 , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); + m_GaussianFrameBuffer_vert.Unbind(); + glViewport(0, 0, (m_Renderer->GetViewportSize().Width), (m_Renderer->GetViewportSize().Height)); } From 9cbc6f77556e559d3797060f3cc8e200d74369a8 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Sun, 28 Feb 2016 16:16:22 +0100 Subject: [PATCH 07/19] Added GenerateTexture, GenerateMipMapTexture and DeleteTexture to CommonFunctions --- include/Engine/Rendering/DrawBloomPass.h | 2 - include/Engine/Rendering/DrawFinalPass.h | 3 -- include/Engine/Rendering/FrameBuffer.h | 9 ++++ include/Engine/Rendering/IRenderer.h | 1 + include/Engine/Rendering/SSAOPass.h | 2 - .../Engine/Rendering/Util/CommonFunctions.h | 3 ++ src/Engine/Rendering/DrawBloomPass.cpp | 25 +++-------- src/Engine/Rendering/DrawFinalPass.cpp | 42 ++++--------------- src/Engine/Rendering/FrameBuffer.cpp | 6 +++ src/Engine/Rendering/SSAOPass.cpp | 33 ++++----------- src/Engine/Rendering/Util/CommonFunctions.cpp | 33 +++++++++++++++ 11 files changed, 74 insertions(+), 85 deletions(-) diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 4ddb7e05..ee3a8489 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -39,8 +39,6 @@ public: private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); - Texture* m_BlackTexture; Model* m_ScreenQuad; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index e522cdc5..5e6f64b9 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -35,9 +35,6 @@ public: FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; } private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; - void DrawSprites(std::list>&jobs, RenderScene& scene); void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); diff --git a/include/Engine/Rendering/FrameBuffer.h b/include/Engine/Rendering/FrameBuffer.h index cf63b6c6..89418799 100644 --- a/include/Engine/Rendering/FrameBuffer.h +++ b/include/Engine/Rendering/FrameBuffer.h @@ -33,6 +33,15 @@ public: ~Texture2D(); }; +class Texture2DMultiSample : public ResourceType +{ +public: + Texture2DMultiSample(GLuint* resourceHandle, GLenum attachment) + : ResourceType(resourceHandle, attachment) { }; + + ~Texture2DMultiSample(); +}; + class RenderBuffer : public ResourceType { public: diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index 97293f06..2e6f3a97 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -11,6 +11,7 @@ #include "RenderQueue.h" #include "Model.h" #include "../Core/World.h" //So temp +#include "Util/CommonFunctions.h" struct PickData diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index a5f638cd..1cb28009 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -46,8 +46,6 @@ private: void InitializeShaderProgram(); void InitializeBuffer(); - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); - //void blurHorizontal(GLuint depthBuffer); //void blurVertical(GLuint depthBuffer); diff --git a/include/Engine/Rendering/Util/CommonFunctions.h b/include/Engine/Rendering/Util/CommonFunctions.h index e178f52d..7ff6e3f9 100644 --- a/include/Engine/Rendering/Util/CommonFunctions.h +++ b/include/Engine/Rendering/Util/CommonFunctions.h @@ -9,6 +9,9 @@ namespace CommonFunctions { Texture* LoadTexture(std::string path, bool threaded); +void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); +void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps); +void DeleteTexture(GLuint* texture); }; #endif \ No newline at end of file diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 4fe885af..0216d940 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -24,8 +24,8 @@ void DrawBloomPass::ChangeQuality(int quality) m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); if (m_Quality == 0) { - glDeleteTextures(1, &m_GaussianTexture_horiz); - glDeleteTextures(1, &m_GaussianTexture_vert); + CommonFunctions::DeleteTexture(&m_GaussianTexture_horiz); + CommonFunctions::DeleteTexture(&m_GaussianTexture_vert); m_GaussianTexture_horiz = 0; m_GaussianTexture_vert = 0; return; @@ -59,14 +59,14 @@ void DrawBloomPass::InitializeShaderPrograms() void DrawBloomPass::InitializeBuffers() { - GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) { m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0))); } m_GaussianFrameBuffer_horiz.Generate(); - GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); if (m_GaussianFrameBuffer_vert.GetHandle() == 0) { m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0))); } @@ -163,21 +163,8 @@ void DrawBloomPass::OnWindowResize() if (m_Quality == 0) { return; } - GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_vert.Generate(); - GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_GaussianFrameBuffer_horiz.Generate(); } - -void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) -{ - glDeleteTextures(1, texture); - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution - GLERROR("Texture initialization failed"); -} diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 7b373452..017ba9ba 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -29,9 +29,9 @@ void DrawFinalPass::InitializeFrameBuffers() GLERROR("RenderBuffer generation"); - GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); //GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); @@ -47,9 +47,9 @@ void DrawFinalPass::InitializeFrameBuffers() glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); GLERROR("RenderBufferLowRes generation"); - GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); //GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); @@ -300,46 +300,20 @@ void DrawFinalPass::OnWindowResize() glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); m_FinalPassFrameBuffer.Generate(); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); - GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); - GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); m_FinalPassFrameBufferLowRes.Generate(); GLERROR("Error changing texture resolutions"); } -void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const -{ - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution - GLERROR("Texture initialization failed"); -} - -void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const -{ - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture); - glGenerateMipmap(GL_TEXTURE_2D); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - GLERROR("MipMap Texture initialization failed"); -} - void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 9ba0d2d8..8638ebca 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -16,6 +16,12 @@ Texture2D::~Texture2D() } } +Texture2DMultiSample::~Texture2DMultiSample() +{ + if (m_ResourceHandle != 0) { + glDeleteTextures(1, m_ResourceHandle); + } +} RenderBuffer::~RenderBuffer() { diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 0ffa5647..8515cf95 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -19,14 +19,10 @@ void SSAOPass::ChangeQuality(int quality) m_Quality = quality; if (m_Quality == 0) { - glDeleteTextures(1, &m_SSAOTexture); - glDeleteTextures(1, &m_SSAOViewSpaceZTexture); - glDeleteTextures(1, &m_Gaussian_horiz); - glDeleteTextures(1, &m_Gaussian_vert); - m_SSAOTexture = 0; - m_SSAOViewSpaceZTexture = 0; - m_Gaussian_horiz = 0; - m_Gaussian_vert = 0; + CommonFunctions::DeleteTexture(&m_SSAOTexture); + CommonFunctions::DeleteTexture(&m_SSAOViewSpaceZTexture); + CommonFunctions::DeleteTexture(&m_Gaussian_horiz); + CommonFunctions::DeleteTexture(&m_Gaussian_vert); return; } @@ -89,11 +85,11 @@ void SSAOPass::InitializeShaderProgram() } void SSAOPass::InitializeTexture() { - GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); - GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); - GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); - GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); } void SSAOPass::InitializeBuffer() @@ -161,19 +157,6 @@ void SSAOPass::Setting(float radius, float bias, float contrast, float intensity m_TextureQuality = quality; } -void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) -{ - glDeleteTextures(1, texture); - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr); - GLERROR("Texture initialization failed"); -} - void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) { if (m_Quality == 0) { diff --git a/src/Engine/Rendering/Util/CommonFunctions.cpp b/src/Engine/Rendering/Util/CommonFunctions.cpp index 382cb790..5c5c449e 100644 --- a/src/Engine/Rendering/Util/CommonFunctions.cpp +++ b/src/Engine/Rendering/Util/CommonFunctions.cpp @@ -17,3 +17,36 @@ Texture* CommonFunctions::LoadTexture(std::string path, bool threaded) return img; } + +void CommonFunctions::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) +{ + glDeleteTextures(1, texture); + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr); + GLERROR("Texture initialization failed"); +} + +void CommonFunctions::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) +{ + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture); + glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + GLERROR("MipMap Texture initialization failed"); +} + +void CommonFunctions::DeleteTexture(GLuint* texture) +{ + glDeleteTextures(1, texture); + *texture = 0; +} \ No newline at end of file From db5170c6993baf18f0bb5be8a49fa36f44b76093 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 29 Feb 2016 09:37:51 +0100 Subject: [PATCH 08/19] WIP, should take shortest resolution even if forced upwards because of slopes, not solving the jittering problem though. + debug code. --- src/Engine/Collision/Collision.cpp | 156 ++++++++++++++++------- src/Engine/Collision/CollisionSystem.cpp | 2 + 2 files changed, 113 insertions(+), 45 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 68d99d92..166518c5 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -380,11 +380,11 @@ bool AABBvsTriangle(const AABB& box, enum BoxTriResolveCase { - ResolveDimX, - ResolveDimY, - ResolveDimZ, - Line, //Box edge colliding with triangle line. - Corner //Box corner colliding with the triangle face. + EResolveDimX, + EResolveDimY, + EResolveDimZ, + ELine, //Box edge colliding with triangle line. + ECorner //Box corner colliding with the triangle face. }; struct Resolution { @@ -396,10 +396,55 @@ bool AABBvsTriangle(const AABB& box, float DistanceSq; glm::vec3 Vector; }; + struct CaseResolutions + { + Resolution Vertex; + Resolution Line; + Resolution Corner; + Resolution* Shortest = &Vertex; + + void AddResolution(BoxTriResolveCase resCase, float distanceSq, const glm::vec3& resVec) + { + switch (resCase) { + case EResolveDimY: + case EResolveDimX: + case EResolveDimZ: + if (distanceSq < Vertex.DistanceSq) { + Vertex.Vector = resVec; + Vertex.DistanceSq = distanceSq; + Vertex.Case = resCase; + if (distanceSq < Line.DistanceSq) { + Shortest = &Vertex; + } + } + break; + case ELine: + if (distanceSq < Vertex.DistanceSq && distanceSq < Line.DistanceSq) { + Line.Vector = resVec; + Line.DistanceSq = distanceSq; + Line.Case = resCase; + Shortest = &Line; + } + break; + case ECorner: + //NOTE: It is assumed that the Corner is less than the + //added resolution, since only one corner should be added per triangle. + if (distanceSq < Vertex.DistanceSq && distanceSq < Line.DistanceSq) { + Corner.Vector = resVec; + Corner.DistanceSq = distanceSq; + Corner.Case = resCase; + Shortest = &Corner; + } + break; + default: + break; + } + } + }; //The smallest resolution that solves the collision. - Resolution resolveShortest; + CaseResolutions resolveShortest; //The smallest resolution that solves the collision, that resolves upwards. - Resolution resolveUpwards; + CaseResolutions resolveUpwards; //If player stands on the ground and collides with a ground triangle, //we might step up onto it if the step is small enough. bool canStairStepUp = isOnGround && FaceIsGround(triNormal.y); @@ -421,34 +466,27 @@ bool AABBvsTriangle(const AABB& box, //Project box. glm::vec2 boxMin(min[dim.first], min[dim.second]); glm::vec2 boxMax(max[dim.first], max[dim.second]); - glm::vec2 resolutionVector; - float resolutionDist; + glm::vec2 resolutionVector2D; + float resolutionDistSq; bool pushedFromTriangleLine; //if projections don't overlap, return false. - if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { + if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector2D, resolutionDistSq, pushedFromTriangleLine)) { return false; } else if (resolveCollision) { + glm::vec3 resolve3D = glm::vec3(0.f); + resolve3D[dim.first] = resolutionVector2D.x; + resolve3D[dim.second] = resolutionVector2D.y; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + BoxTriResolveCase resCase = pushedFromTriangleLine ? ELine : static_cast((abs(resolve3D[dim.first]) < 0.0001f) ? dim.second : dim.first); //Overwrite the smallest resolution if this is smaller. - if (resolutionDist < resolveShortest.DistanceSq) { - resolveShortest.Vector = glm::vec3(0.f); - resolveShortest.Vector[dim.first] = resolutionVector.x; - resolveShortest.Vector[dim.second] = resolutionVector.y; - resolveShortest.DistanceSq = resolutionDist; - //If we pushed away from triangle line (edge), or if we - //move the player along one coordinate axis (pick the dimension that isn't zero). - resolveShortest.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveShortest.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); - } + resolveShortest.AddResolution(resCase, resolutionDistSq, resolve3D); + //Overwrite the smallest upward resolution if this is smaller, and resolves upwards. constexpr int yAxis = 1; - bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector.x > 0 || dim.second == yAxis && resolutionVector.y > 0; - if (canStairStepUp && resIsUpwardsIn3D && resolutionDist < resolveUpwards.DistanceSq) { - resolveUpwards.Vector = glm::vec3(0.f); - resolveUpwards.Vector[dim.first] = resolutionVector.x; - resolveUpwards.Vector[dim.second] = resolutionVector.y; - resolveUpwards.DistanceSq = resolutionDist; - //If we pushed away from triangle line (edge), or if we - //move the player along one coordinate axis (pick the dimension that isn't zero). - resolveUpwards.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveUpwards.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector2D.x > 0 || dim.second == yAxis && resolutionVector2D.y > 0; + if (canStairStepUp && resIsUpwardsIn3D) { + resolveUpwards.AddResolution(resCase, resolutionDistSq, resolve3D); } } } @@ -472,37 +510,40 @@ bool AABBvsTriangle(const AABB& box, glm::vec3 cornerResolution = (1+t) * diagonal; //Overwrite the smallest resolution if cornerResolution is smaller. float lenSq = glm::length2(cornerResolution); - if (lenSq < resolveShortest.DistanceSq) { - resolveShortest.Vector = cornerResolution; - resolveShortest.Case = Corner; - } - if (canStairStepUp && cornerResolution.y > 0 && lenSq < resolveUpwards.DistanceSq) { - resolveUpwards.Vector = cornerResolution; - resolveUpwards.Case = Corner; - resolveUpwards.DistanceSq = lenSq; + resolveShortest.AddResolution(ECorner, lenSq, cornerResolution); + if (canStairStepUp && cornerResolution.y > 0) { + resolveUpwards.AddResolution(ECorner, lenSq, cornerResolution); } //Force the resolution upwards if it is smaller than the threshold verticalStepHeight. //Else take the shortest resolution. - bool takeUp = resolveUpwards.Vector.y > 0 && resolveUpwards.Vector.y < verticalStepHeight; - Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest; - outResolution = bestResolve.Vector; + bool takeUp = resolveUpwards.Shortest->Vector.y > 0 && resolveUpwards.Shortest->Vector.y < verticalStepHeight; + CaseResolutions& bestResolve = takeUp ? resolveUpwards : resolveShortest; + outResolution = bestResolve.Shortest->Vector; + std::string dbgString = ""; glm::vec3 projNorm; - switch (bestResolve.Case) { - case ResolveDimY: + switch (bestResolve.Shortest->Case) { + case EResolveDimY: boxVelocity.y = 0.f; if (outResolution.y > 0) isOnGround = true; - case ResolveDimX: - case ResolveDimZ: + case EResolveDimX: + case EResolveDimZ: //If we get here, the resolution is along one coordinate axis. //set velocity to 0 in y if it is along y-axis. + dbgString = "Vertex Collision"; + dbgString += isOnGround ? " Ground" : " Air"; + dbgString += takeUp ? " Force up" : " Normal"; + std::cout << (dbgString.c_str()) << std::endl; + ImGui::Text(dbgString.c_str()); return true; - case Line: + case ELine: + dbgString = "Line Collision"; projNorm = glm::normalize(outResolution); break; - case Corner: + case ECorner: + dbgString = "Corner Collision"; projNorm = triNormal; break; default: @@ -519,6 +560,23 @@ bool AABBvsTriangle(const AABB& box, outResolution.y = len / glm::sin(ang); outResolution.z = 0; } + float y; + if (bestResolve.Shortest->Case == ECorner) { + len = glm::length(bestResolve.Line.Vector); + ang = glm::half_pi() - glm::acos(bestResolve.Line.Vector.y / len); + if (len > 0.0000001f && ang > 0.0000001f) { + y = len / glm::sin(ang); + if (y < outResolution.y) { + outResolution.x = 0; + outResolution.y = y; + outResolution.z = 0; + } + } + } + y = bestResolve.Vertex.Vector.y; + if (bestResolve.Vertex.Case == EResolveDimY && y < outResolution.y) { + outResolution.y = y; + } //Also zero the vertical velocity, if it is positive, else project it onto the normal. //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. @@ -533,6 +591,10 @@ bool AABBvsTriangle(const AABB& box, boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; } } + dbgString += isOnGround ? " Ground" : " Air"; + dbgString += takeUp ? " Force up" : " Normal"; + std::cout << (dbgString.c_str()) << std::endl; + ImGui::Text(dbgString.c_str()); return true; } @@ -546,6 +608,7 @@ bool AABBvsTriangles(const AABB& box, glm::vec3& outResolutionVector, bool resolveCollision) { + std::cout << ("---->>>--AABBvsTriangles--------") << std::endl; bool hit = false; bool everHitTheGround = false; @@ -573,6 +636,9 @@ bool AABBvsTriangles(const AABB& box, if (!everHitTheGround) { isOnGround = false; } + std::cout << (isOnGround ? "Hit Ground" : "In Air") << std::endl; + ImGui::Text(isOnGround ? "Hit Ground" : "In Air"); + std::cout << ("--------AABBvsTriangles---->>>--") << std::endl; return hit; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 9689bf13..30b60df9 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -12,6 +12,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!boundingBox) { return; } + std::cout << "---->>>--Start Update--------" << std::endl; ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; @@ -115,4 +116,5 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } m_PrevPositions[entity] = boxA.Origin(); + std::cout << "--------End Update---->>>--" << std::endl; } From df7ace662608f963577c18cbd77ead058c6202e3 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 29 Feb 2016 11:44:29 +0100 Subject: [PATCH 09/19] We only uses one depth buffer now --- include/Engine/Rendering/DrawFinalPass.h | 4 ++-- include/Engine/Rendering/FrameBuffer.h | 9 --------- include/Engine/Rendering/PickingPass.h | 4 +--- include/Engine/Rendering/RenderState.h | 2 ++ .../Engine/Rendering/Util/CommonFunctions.h | 1 + src/Engine/Rendering/DrawBloomPass.cpp | 4 ++-- src/Engine/Rendering/DrawFinalPass.cpp | 18 +++++------------ src/Engine/Rendering/DrawFinalPassState.cpp | 3 ++- src/Engine/Rendering/FrameBuffer.cpp | 6 ------ src/Engine/Rendering/PickingPass.cpp | 19 +++--------------- src/Engine/Rendering/PickingPassState.cpp | 1 + src/Engine/Rendering/RenderState.cpp | 20 +++++++++++++++++++ src/Engine/Rendering/Renderer.cpp | 20 ++++++++++--------- src/Engine/Rendering/SSAOPass.cpp | 13 ++++++------ src/Engine/Rendering/Util/CommonFunctions.cpp | 10 ++++++++++ src/Game/main.cpp | 2 ++ 16 files changed, 69 insertions(+), 67 deletions(-) diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 5e6f64b9..97322603 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -15,7 +15,7 @@ class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass, GLuint* depthBuffer); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); @@ -59,7 +59,7 @@ private: GLuint m_SceneTexture; GLuint m_BloomTextureLowRes; GLuint m_SceneTextureLowRes; - GLuint m_DepthBuffer; + GLuint* m_DepthBuffer; GLuint m_DepthBufferLowRes; GLuint m_CubeMapTexture; diff --git a/include/Engine/Rendering/FrameBuffer.h b/include/Engine/Rendering/FrameBuffer.h index 89418799..cf63b6c6 100644 --- a/include/Engine/Rendering/FrameBuffer.h +++ b/include/Engine/Rendering/FrameBuffer.h @@ -33,15 +33,6 @@ public: ~Texture2D(); }; -class Texture2DMultiSample : public ResourceType -{ -public: - Texture2DMultiSample(GLuint* resourceHandle, GLenum attachment) - : ResourceType(resourceHandle, attachment) { }; - - ~Texture2DMultiSample(); -}; - class RenderBuffer : public ResourceType { public: diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index f6434781..df99a615 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -28,15 +28,13 @@ public: const ShaderProgram& PickingProgram() const { return *m_PickingProgram; } //const std::unordered_map& PickingColorsToEntity() const { return m_PickingColorsToEntity; } GLuint PickingTexture() const { return m_PickingTexture; } - GLuint DepthBuffer() const { return m_DepthBuffer; } + GLuint* DepthBuffer() { return &m_DepthBuffer; } const FrameBuffer& PickingBuffer() const { return m_PickingBuffer; } PickData Pick(glm::vec2 screenCoord); private: - void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - EventBroker* m_EventBroker; const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index c1886247..24f908a9 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -24,6 +24,8 @@ public: bool StencilFunc(GLenum func, GLint ref, GLuint mask); bool StencilMask(GLuint mask); bool DepthMask(GLboolean flag); + bool DepthFunc(GLenum func); + bool AlphaFunc(GLenum func, GLclampf thresholder); private: std::vector> m_ResetFunctions; diff --git a/include/Engine/Rendering/Util/CommonFunctions.h b/include/Engine/Rendering/Util/CommonFunctions.h index 7ff6e3f9..1ed3d82a 100644 --- a/include/Engine/Rendering/Util/CommonFunctions.h +++ b/include/Engine/Rendering/Util/CommonFunctions.h @@ -10,6 +10,7 @@ namespace CommonFunctions { Texture* LoadTexture(std::string path, bool threaded); void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type); +void GenerateMultiSampleTexture(GLuint* texture, int numSamples, glm::vec2 dimensions, GLint internalFormat); void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps); void DeleteTexture(GLuint* texture); }; diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 0216d940..12777941 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -82,11 +82,11 @@ void DrawBloomPass::ClearBuffer() GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_GaussianFrameBuffer_horiz.Unbind(); m_GaussianFrameBuffer_vert.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); GLERROR("END"); } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 017ba9ba..3e477296 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,9 +1,10 @@ #include "Rendering/DrawFinalPass.h" -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass) +DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass, SSAOPass* ssaoPass, GLuint* depthBuffer) : m_Renderer(renderer) , m_LightCullingPass(lightCullingPass) , m_CubeMapPass(cubeMapPass) , m_SSAOPass(ssaoPass) + , m_DepthBuffer(depthBuffer) { //TODO: Make sure that uniforms are not sent into shader if not needed. m_ShieldPixelRate = 8; @@ -23,19 +24,13 @@ void DrawFinalPass::InitializeTextures() void DrawFinalPass::InitializeFrameBuffers() { - glGenRenderbuffers(1, &m_DepthBuffer); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - GLERROR("RenderBuffer generation"); - - CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); //GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); //m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); @@ -182,7 +177,6 @@ void DrawFinalPass::Draw(RenderScene& scene) if (scene.ClearDepth) { //glClear(GL_DEPTH_BUFFER_BIT); state->Disable(GL_DEPTH_TEST); - state->DepthMask(GL_FALSE); } //TODO: Do we need check for this or will it be per scene always? glClearStencil(0x00); @@ -273,7 +267,7 @@ void DrawFinalPass::ClearBuffer() glClearColor(0.f, 0.f, 0.f, 0.f); GLERROR("1"); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); GLERROR("2"); glDisable(GL_SCISSOR_TEST); @@ -288,7 +282,7 @@ void DrawFinalPass::ClearBuffer() glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("ViewPort,Scissor LowRes"); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); GLERROR("END"); } @@ -297,8 +291,6 @@ void DrawFinalPass::ClearBuffer() void DrawFinalPass::OnWindowResize() { //InitializeFrameBuffers(); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 9741a0ce..6e1e3473 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -8,7 +8,8 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) Enable(GL_BLEND); BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); + DepthMask(GL_FALSE); + DepthFunc(GL_LEQUAL); Enable(GL_CULL_FACE); Enable(GL_STENCIL_TEST); StencilFunc(GL_NOTEQUAL, 1, 0xFF); diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 8638ebca..9ba0d2d8 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -16,12 +16,6 @@ Texture2D::~Texture2D() } } -Texture2DMultiSample::~Texture2DMultiSample() -{ - if (m_ResourceHandle != 0) { - glDeleteTextures(1, m_ResourceHandle); - } -} RenderBuffer::~RenderBuffer() { diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 1eab9939..fb58edf7 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -19,10 +19,10 @@ PickingPass::~PickingPass() void PickingPass::InitializeTextures() { - GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, + CommonFunctions::GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); - GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, + CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8); } @@ -366,7 +366,7 @@ void PickingPass::ClearPicking() m_PickingBuffer.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); m_PickingBuffer.Unbind(); GLERROR("END"); } @@ -407,16 +407,3 @@ PickData PickingPass::Pick(glm::vec2 screenCoord) pickData.World = pickInfo.World; return pickData; } - -void PickingPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const -{ - //TODO: Renderer: Make this in a sparate class - glGenTextures(1, texture); - glBindTexture(GL_TEXTURE_2D, *texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution - GLERROR("Texture initialization failed"); -} diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index f2d42bff..3c19dc06 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -14,6 +14,7 @@ PickingPassState::PickingPassState(GLuint frameBuffer) //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GLERROR("END"); + } PickingPassState::~PickingPassState() diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 26ba18a1..56812f9a 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -135,6 +135,26 @@ bool RenderState::DepthMask(GLboolean flag) return !GLERROR("DepthMask"); } +bool RenderState::DepthFunc(GLenum func) +{ + GLint original; + glGetIntegerv(GL_DEPTH_FUNC, &original); + m_ResetFunctions.push_back(std::bind(glDepthFunc, original)); + glDepthFunc(func); + return !GLERROR("DepthFunc"); +} + +bool RenderState::AlphaFunc(GLenum func, GLclampf thresholder) +{ + GLint originalFunc; + glGetIntegerv(GL_ALPHA_TEST_FUNC, &originalFunc); + GLint originalRef; + glGetIntegerv(GL_ALPHA_TEST_REF, &originalRef); + m_ResetFunctions.push_back(std::bind(glAlphaFunc, originalFunc, originalRef)); + glAlphaFunc(func, thresholder); + return !GLERROR("AlphaFunc"); +} + RenderState::~RenderState() { for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) { diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 76ee9506..e590cd97 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -28,9 +28,9 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height glViewport(0, 0, width, height); Renderer* currentRenderer = m_WindowToRenderer[window]; currentRenderer->m_ViewportSize = Rectangle(width, height); + currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawFinalPass->OnWindowResize(); currentRenderer->m_LightCullingPass->OnWindowResize(); - currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawBloomPass->OnWindowResize(); currentRenderer->m_SSAOPass->OnWindowResize(); } @@ -136,17 +136,16 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StopTimer("Renderer-ClearBuffers"); GLERROR("ClearBuffers"); for (auto scene : frame.RenderScenes) { - PerformanceTimer::StartTimer("Renderer-Depth"); + PerformanceTimer::StartTimer("Renderer-PickingPass"); m_PickingPass->Draw(*scene); GLERROR("Drawing pickingpass"); - PerformanceTimer::StopTimer("Renderer-Depth"); + PerformanceTimer::StopTimer("Renderer-PickingPass"); } PerformanceTimer::StartTimer("Renderer-AO generation"); - m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); + m_SSAOPass->Draw(*m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); PerformanceTimer::StopTimer("Renderer-AO generation"); for (auto scene : frame.RenderScenes){ - - PerformanceTimer::StartTimer("Renderer-Drawing PickingPass"); + PerformanceTimer::StartTimer("Renderer-Depth"); SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); @@ -206,8 +205,11 @@ void Renderer::Draw(RenderFrame& frame) PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); GLERROR("Imgui draw"); + PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); + + PerformanceTimer::StartTimer("Renderer-SwapBuffer"); glfwSwapBuffers(m_Window); - PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); + PerformanceTimer::StopTimer("Renderer-SwapBuffer"); } PickData Renderer::Pick(glm::vec2 screenCoord) @@ -248,9 +250,9 @@ void Renderer::InitializeRenderPasses() m_LightCullingPass = new LightCullingPass(this); m_CubeMapPass = new CubeMapPass(this); m_SSAOPass = new SSAOPass(this, m_Config); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_SSAOPass); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass, m_SSAOPass, m_PickingPass->DepthBuffer()); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this, m_Config); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); -} +} \ No newline at end of file diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 8515cf95..9992db70 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -88,8 +88,8 @@ void SSAOPass::InitializeTexture() { CommonFunctions::GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); CommonFunctions::GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R32F, GL_RED, GL_FLOAT); - CommonFunctions::GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); - CommonFunctions::GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RGB, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_Gaussian_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); + CommonFunctions::GenerateTexture(&m_Gaussian_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width >> m_TextureQuality, m_Renderer->GetViewportSize().Height >> m_TextureQuality), GL_R8, GL_RED, GL_FLOAT); } void SSAOPass::InitializeBuffer() @@ -127,22 +127,22 @@ void SSAOPass::ClearBuffer() } m_SSAOFramBuffer.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_SSAOFramBuffer.Unbind(); m_SSAOViewSpaceZFramBuffer.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_SSAOViewSpaceZFramBuffer.Unbind(); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_GaussianFrameBuffer_horiz.Unbind(); m_GaussianFrameBuffer_vert.Bind(); glClearColor(1.f, 1.f, 1.f, 1.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); } @@ -284,4 +284,5 @@ void SSAOPass::OnWindowResize() { } InitializeTexture(); + InitializeBuffer(); } \ No newline at end of file diff --git a/src/Engine/Rendering/Util/CommonFunctions.cpp b/src/Engine/Rendering/Util/CommonFunctions.cpp index 5c5c449e..913e005e 100644 --- a/src/Engine/Rendering/Util/CommonFunctions.cpp +++ b/src/Engine/Rendering/Util/CommonFunctions.cpp @@ -31,6 +31,16 @@ void CommonFunctions::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum f GLERROR("Texture initialization failed"); } +void CommonFunctions::GenerateMultiSampleTexture(GLuint* texture, int numSamples, glm::vec2 dimensions, GLint internalFormat) +{ + glDeleteTextures(1, texture); + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, *texture); + glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, numSamples, internalFormat, dimensions.x, dimensions.y, false); + GLERROR("Texture initialization failed"); +} + + void CommonFunctions::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) { glGenTextures(1, texture); diff --git a/src/Game/main.cpp b/src/Game/main.cpp index dd2a5a84..3c9b6d38 100644 --- a/src/Game/main.cpp +++ b/src/Game/main.cpp @@ -9,7 +9,9 @@ int main(int argc, char* argv[]) Game game(argc, argv); while (game.Running()) { + PerformanceTimer::StartTimer("Game-Tick"); game.Tick(); + PerformanceTimer::StopTimer("Game-Tick"); } return 0; From 8e21c5a5e42b2fafcff7b20348146881d143823c Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 29 Feb 2016 15:38:36 +0100 Subject: [PATCH 10/19] Reverts last WIP since it probably added code without improving anything. Revert "WIP, should take shortest resolution even if forced upwards because of slopes, not solving the jittering problem though. + debug code." This reverts commit db5170c6993baf18f0bb5be8a49fa36f44b76093. --- src/Engine/Collision/Collision.cpp | 156 +++++++---------------- src/Engine/Collision/CollisionSystem.cpp | 2 - 2 files changed, 45 insertions(+), 113 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 166518c5..68d99d92 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -380,11 +380,11 @@ bool AABBvsTriangle(const AABB& box, enum BoxTriResolveCase { - EResolveDimX, - EResolveDimY, - EResolveDimZ, - ELine, //Box edge colliding with triangle line. - ECorner //Box corner colliding with the triangle face. + ResolveDimX, + ResolveDimY, + ResolveDimZ, + Line, //Box edge colliding with triangle line. + Corner //Box corner colliding with the triangle face. }; struct Resolution { @@ -396,55 +396,10 @@ bool AABBvsTriangle(const AABB& box, float DistanceSq; glm::vec3 Vector; }; - struct CaseResolutions - { - Resolution Vertex; - Resolution Line; - Resolution Corner; - Resolution* Shortest = &Vertex; - - void AddResolution(BoxTriResolveCase resCase, float distanceSq, const glm::vec3& resVec) - { - switch (resCase) { - case EResolveDimY: - case EResolveDimX: - case EResolveDimZ: - if (distanceSq < Vertex.DistanceSq) { - Vertex.Vector = resVec; - Vertex.DistanceSq = distanceSq; - Vertex.Case = resCase; - if (distanceSq < Line.DistanceSq) { - Shortest = &Vertex; - } - } - break; - case ELine: - if (distanceSq < Vertex.DistanceSq && distanceSq < Line.DistanceSq) { - Line.Vector = resVec; - Line.DistanceSq = distanceSq; - Line.Case = resCase; - Shortest = &Line; - } - break; - case ECorner: - //NOTE: It is assumed that the Corner is less than the - //added resolution, since only one corner should be added per triangle. - if (distanceSq < Vertex.DistanceSq && distanceSq < Line.DistanceSq) { - Corner.Vector = resVec; - Corner.DistanceSq = distanceSq; - Corner.Case = resCase; - Shortest = &Corner; - } - break; - default: - break; - } - } - }; //The smallest resolution that solves the collision. - CaseResolutions resolveShortest; + Resolution resolveShortest; //The smallest resolution that solves the collision, that resolves upwards. - CaseResolutions resolveUpwards; + Resolution resolveUpwards; //If player stands on the ground and collides with a ground triangle, //we might step up onto it if the step is small enough. bool canStairStepUp = isOnGround && FaceIsGround(triNormal.y); @@ -466,27 +421,34 @@ bool AABBvsTriangle(const AABB& box, //Project box. glm::vec2 boxMin(min[dim.first], min[dim.second]); glm::vec2 boxMax(max[dim.first], max[dim.second]); - glm::vec2 resolutionVector2D; - float resolutionDistSq; + glm::vec2 resolutionVector; + float resolutionDist; bool pushedFromTriangleLine; //if projections don't overlap, return false. - if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector2D, resolutionDistSq, pushedFromTriangleLine)) { + if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { return false; } else if (resolveCollision) { - glm::vec3 resolve3D = glm::vec3(0.f); - resolve3D[dim.first] = resolutionVector2D.x; - resolve3D[dim.second] = resolutionVector2D.y; - //If we pushed away from triangle line (edge), or if we - //move the player along one coordinate axis (pick the dimension that isn't zero). - BoxTriResolveCase resCase = pushedFromTriangleLine ? ELine : static_cast((abs(resolve3D[dim.first]) < 0.0001f) ? dim.second : dim.first); //Overwrite the smallest resolution if this is smaller. - resolveShortest.AddResolution(resCase, resolutionDistSq, resolve3D); - + if (resolutionDist < resolveShortest.DistanceSq) { + resolveShortest.Vector = glm::vec3(0.f); + resolveShortest.Vector[dim.first] = resolutionVector.x; + resolveShortest.Vector[dim.second] = resolutionVector.y; + resolveShortest.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveShortest.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveShortest.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } //Overwrite the smallest upward resolution if this is smaller, and resolves upwards. constexpr int yAxis = 1; - bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector2D.x > 0 || dim.second == yAxis && resolutionVector2D.y > 0; - if (canStairStepUp && resIsUpwardsIn3D) { - resolveUpwards.AddResolution(resCase, resolutionDistSq, resolve3D); + bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector.x > 0 || dim.second == yAxis && resolutionVector.y > 0; + if (canStairStepUp && resIsUpwardsIn3D && resolutionDist < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = glm::vec3(0.f); + resolveUpwards.Vector[dim.first] = resolutionVector.x; + resolveUpwards.Vector[dim.second] = resolutionVector.y; + resolveUpwards.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveUpwards.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveUpwards.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); } } } @@ -510,40 +472,37 @@ bool AABBvsTriangle(const AABB& box, glm::vec3 cornerResolution = (1+t) * diagonal; //Overwrite the smallest resolution if cornerResolution is smaller. float lenSq = glm::length2(cornerResolution); - resolveShortest.AddResolution(ECorner, lenSq, cornerResolution); - if (canStairStepUp && cornerResolution.y > 0) { - resolveUpwards.AddResolution(ECorner, lenSq, cornerResolution); + if (lenSq < resolveShortest.DistanceSq) { + resolveShortest.Vector = cornerResolution; + resolveShortest.Case = Corner; + } + if (canStairStepUp && cornerResolution.y > 0 && lenSq < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = cornerResolution; + resolveUpwards.Case = Corner; + resolveUpwards.DistanceSq = lenSq; } //Force the resolution upwards if it is smaller than the threshold verticalStepHeight. //Else take the shortest resolution. - bool takeUp = resolveUpwards.Shortest->Vector.y > 0 && resolveUpwards.Shortest->Vector.y < verticalStepHeight; - CaseResolutions& bestResolve = takeUp ? resolveUpwards : resolveShortest; - outResolution = bestResolve.Shortest->Vector; + bool takeUp = resolveUpwards.Vector.y > 0 && resolveUpwards.Vector.y < verticalStepHeight; + Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest; + outResolution = bestResolve.Vector; - std::string dbgString = ""; glm::vec3 projNorm; - switch (bestResolve.Shortest->Case) { - case EResolveDimY: + switch (bestResolve.Case) { + case ResolveDimY: boxVelocity.y = 0.f; if (outResolution.y > 0) isOnGround = true; - case EResolveDimX: - case EResolveDimZ: + case ResolveDimX: + case ResolveDimZ: //If we get here, the resolution is along one coordinate axis. //set velocity to 0 in y if it is along y-axis. - dbgString = "Vertex Collision"; - dbgString += isOnGround ? " Ground" : " Air"; - dbgString += takeUp ? " Force up" : " Normal"; - std::cout << (dbgString.c_str()) << std::endl; - ImGui::Text(dbgString.c_str()); return true; - case ELine: - dbgString = "Line Collision"; + case Line: projNorm = glm::normalize(outResolution); break; - case ECorner: - dbgString = "Corner Collision"; + case Corner: projNorm = triNormal; break; default: @@ -560,23 +519,6 @@ bool AABBvsTriangle(const AABB& box, outResolution.y = len / glm::sin(ang); outResolution.z = 0; } - float y; - if (bestResolve.Shortest->Case == ECorner) { - len = glm::length(bestResolve.Line.Vector); - ang = glm::half_pi() - glm::acos(bestResolve.Line.Vector.y / len); - if (len > 0.0000001f && ang > 0.0000001f) { - y = len / glm::sin(ang); - if (y < outResolution.y) { - outResolution.x = 0; - outResolution.y = y; - outResolution.z = 0; - } - } - } - y = bestResolve.Vertex.Vector.y; - if (bestResolve.Vertex.Case == EResolveDimY && y < outResolution.y) { - outResolution.y = y; - } //Also zero the vertical velocity, if it is positive, else project it onto the normal. //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. @@ -591,10 +533,6 @@ bool AABBvsTriangle(const AABB& box, boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; } } - dbgString += isOnGround ? " Ground" : " Air"; - dbgString += takeUp ? " Force up" : " Normal"; - std::cout << (dbgString.c_str()) << std::endl; - ImGui::Text(dbgString.c_str()); return true; } @@ -608,7 +546,6 @@ bool AABBvsTriangles(const AABB& box, glm::vec3& outResolutionVector, bool resolveCollision) { - std::cout << ("---->>>--AABBvsTriangles--------") << std::endl; bool hit = false; bool everHitTheGround = false; @@ -636,9 +573,6 @@ bool AABBvsTriangles(const AABB& box, if (!everHitTheGround) { isOnGround = false; } - std::cout << (isOnGround ? "Hit Ground" : "In Air") << std::endl; - ImGui::Text(isOnGround ? "Hit Ground" : "In Air"); - std::cout << ("--------AABBvsTriangles---->>>--") << std::endl; return hit; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 30b60df9..9689bf13 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -12,7 +12,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!boundingBox) { return; } - std::cout << "---->>>--Start Update--------" << std::endl; ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; @@ -116,5 +115,4 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } m_PrevPositions[entity] = boxA.Origin(); - std::cout << "--------End Update---->>>--" << std::endl; } From d47a806c64e8d1711ad448af169f98463feb1c4d Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 29 Feb 2016 15:49:23 +0100 Subject: [PATCH 11/19] Made a easy hack to solve jittering when standing still. Jittering should still be present when moving, but at least it is less prominent when moving. --- src/Engine/Collision/CollisionSystem.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 9689bf13..95609ea6 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -12,6 +12,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!boundingBox) { return; } + ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; @@ -86,10 +87,12 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool notMovingxz = glm::all(glm::lessThan(glm::abs(glm::vec2(inOutVelocity.x, inOutVelocity.z)), glm::vec2(0.01f))) && prevPosIt != m_PrevPositions.end(); bool isOnGround = (bool)cPhysics["IsOnGround"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { - (glm::vec3&)cTransform["Position"] += resolutionVector; + //Move the position to previous position if it is not moving in the xz-plane, else resolve with the resolution vector. + (glm::vec3&)cTransform["Position"] += notMovingxz ? prevPosIt->second - boxA.Origin() : resolutionVector; boxA = *Collision::EntityAbsoluteAABB(entity); cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { From 3c35c0a956ce470e2abef733f99aea0dbe61221a Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 29 Feb 2016 15:50:26 +0100 Subject: [PATCH 12/19] Frustum culling octree updates after collisions, no more disappearing weapons. --- src/Game/Game.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 24b7cd1e..65dbf7e5 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -135,7 +135,6 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -145,6 +144,9 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); + // Octree for frustum culling must be updated after collisions, otherwise players frustum may be moved after tree is filled, and wrong things are culled. + ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; From 658eace09304f0e974dd70da05d285aaed912384 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 29 Feb 2016 18:20:14 +0100 Subject: [PATCH 13/19] Added component CapturePointGameMode that contains respawntime. --- include/Game/Systems/PlayerSpawnSystem.h | 6 ++-- resources/Schema/Components.xsd | 1 + .../Components/CapturePointGameMode.xml | 5 +++ .../Components/CapturePointGameMode.xsd | 18 ++++++++++ src/Game/Game.cpp | 1 - src/Game/Systems/PlayerSpawnSystem.cpp | 35 ++++++++++++------- 6 files changed, 49 insertions(+), 17 deletions(-) create mode 100644 resources/Schema/Components/CapturePointGameMode.xml create mode 100644 resources/Schema/Components/CapturePointGameMode.xsd diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index bf87bef8..70f94807 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -13,8 +13,6 @@ public: PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; - - static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -31,8 +29,8 @@ private: //EntityWrapper ID -> Player ID. std::map m_PlayerIDs; - static float m_RespawnTime; - float m_Timer; + float m_ForcedRespawnTime; + bool m_DbgConfigForceRespawn; EventRelay m_OnInputCommand; bool OnInputCommand(Events::InputCommand& e); diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index cad50c7e..f0bb67d2 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -48,4 +48,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xml b/resources/Schema/Components/CapturePointGameMode.xml new file mode 100644 index 00000000..3104e71f --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xml @@ -0,0 +1,5 @@ + + + 0.0 + 8.0 + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xsd b/resources/Schema/Components/CapturePointGameMode.xsd new file mode 100644 index 00000000..8b81d67a --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + The time since the last respawn wave. Players will be spawned when this reaches MaxRespawnTime. + + + Players will be spawned when RespawnTime reaches this. + + + + + \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 5388fd04..3914c3bf 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -48,7 +48,6 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); - PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 6254c674..1ee674cb 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,29 +1,40 @@ #include "Systems/PlayerSpawnSystem.h" -//This should be set by the config anyway. -float PlayerSpawnSystem::m_RespawnTime = 15.0f; - PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) - , m_Timer(0.f) + , m_DbgConfigForceRespawn(false) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); - m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_NetworkEnabled = config->Get("Networking.StartNetwork", false); + m_ForcedRespawnTime = config->Get("Debug.RespawnTime", -1.0f); + m_DbgConfigForceRespawn = m_ForcedRespawnTime > 0; } void PlayerSpawnSystem::Update(double dt) { - //Increase timer. - m_Timer += dt; - if (m_Timer < m_RespawnTime) { - return; + // If there are no CapturePointGameMode components we will just spawn immediately. + // Should be able to support older maps with this. + // TODO: In the future we might want to return instead, to avoid spawning in the menu for instance. + auto pool = m_World->GetComponents("CapturePointGameMode"); + if (pool != nullptr) + { + // Take the first CapturePointGameMode component found. + ComponentWrapper& modeComponent = *pool->begin(); + // Increase timer. + double& timer = (double&)modeComponent["RespawnTime"]; + timer += dt; + double maxRespawnTime = m_DbgConfigForceRespawn ? m_ForcedRespawnTime : (double)modeComponent["MaxRespawnTime"]; + if (timer < maxRespawnTime) { + return; + } + // If respawn time has passed, we spawn all players that have requested to be spawned. + timer = 0; } - //If respawn time has passed, we spawn all players that have requested to be spawned. - m_Timer = 0.f; - //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + // If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. if (m_SpawnRequests.size() == 0) { return; } From e2b7e5400da7cf8e95fbfc7da47b6f385a40b1ba Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 1 Mar 2016 10:20:52 +0100 Subject: [PATCH 14/19] Check so CapturePointGameMode pool exists and has a size. --- src/Game/Systems/PlayerSpawnSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 1ee674cb..e03a1778 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -19,7 +19,7 @@ void PlayerSpawnSystem::Update(double dt) // Should be able to support older maps with this. // TODO: In the future we might want to return instead, to avoid spawning in the menu for instance. auto pool = m_World->GetComponents("CapturePointGameMode"); - if (pool != nullptr) + if (pool != nullptr && pool->size() > 0) { // Take the first CapturePointGameMode component found. ComponentWrapper& modeComponent = *pool->begin(); From 21bf7f4df3794dd53257bcab5381393f0566dea9 Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 1 Mar 2016 11:03:16 +0100 Subject: [PATCH 15/19] Glow should now legit be working through transparency. --- resources/Shaders/ForwardPlus.frag.glsl | 8 ++++---- src/Engine/Rendering/DrawFinalPass.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 6fbc9c27..a3230eb1 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -169,8 +169,8 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); - float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2; + //float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; + //color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; @@ -181,9 +181,9 @@ void main() } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); //sceneColor = vec4(reflectionColor.xyz, 1); - color_result += glowTexel*GlowIntensity; + color_result.xyz += glowTexel.xyz*GlowIntensity; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); + bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); //Tiled Debug Code /* diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 6cd2c1f1..d084b919 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -193,10 +193,12 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); - state->BlendFunc(GL_ONE, GL_ONE); + //state->BlendFunc(GL_ONE, GL_ONE); + state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); - state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + //state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); From eaea6450682e01935acff5e2bb571d629db92803 Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 1 Mar 2016 11:19:44 +0100 Subject: [PATCH 16/19] Reflectance should now work as an inverse of the specular alpha value. --- resources/Shaders/ForwardPlus.frag.glsl | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index a3230eb1..d88154ef 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -169,8 +169,9 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); - //float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - //color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2; + float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; + vec4 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; + color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; From 77eaa457022f245e9f2f30a682baef3ba0ff5e86 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Tue, 1 Mar 2016 12:11:27 +0100 Subject: [PATCH 17/19] Merge remote-tracking branch 'origin/master' into HEAD Conflicts: src/Engine/Rendering/CubeMapPass.cpp src/Engine/Rendering/DrawFinalPass.cpp --- include/Engine/Collision/CollisionSystem.h | 1 + include/Engine/Core/EntityWrapper.h | 6 + include/Engine/Core/System.h | 2 +- include/Engine/Core/World.h | 2 +- include/Engine/Editor/EditorGUI.h | 8 + include/Engine/Editor/EditorSystem.h | 1 + include/Engine/Network/Client.h | 1 + include/Game/Systems/PlayerSpawnSystem.h | 6 +- .../Systems/Weapon/AssaultWeaponBehaviour.h | 30 +-- .../Systems/Weapon/DefenderWeaponBehaviour.h | 38 +++ include/Game/Systems/Weapon/WeaponBehaviour.h | 173 +++++++++++- resources/Schema/Components.xsd | 4 + resources/Schema/Components/AssaultWeapon.xml | 1 + resources/Schema/Components/AssaultWeapon.xsd | 2 + .../Components/CapturePointGameMode.xml | 5 + .../Components/CapturePointGameMode.xsd | 18 ++ .../Schema/Components/DefenderWeapon.xml | 16 ++ .../Schema/Components/DefenderWeapon.xsd | 44 +++ resources/Schema/Components/DoubleJump.xml | 4 + resources/Schema/Components/DoubleJump.xsd | 16 ++ resources/Schema/Components/Physics.xml | 1 - resources/Schema/Components/Physics.xsd | 1 - resources/Schema/Components/Player.xml | 2 + resources/Schema/Components/Player.xsd | 4 + resources/Schema/Components/Weapon.xml | 3 - resources/Schema/Components/Weapon.xsd | 17 -- .../Schema/Components/WeaponAttachment.xml | 5 + .../Schema/Components/WeaponAttachment.xsd | 28 ++ .../Schema/Entities/AssaultWeaponView.xml | 99 +++++++ .../Schema/Entities/AssaultWeaponWorld.xml | 40 +++ resources/Schema/Entities/DefenderShield.xml | 40 +++ .../Schema/Entities/DefenderWeaponView.xml | 99 +++++++ .../Schema/Entities/DefenderWeaponViewRed.xml | 99 +++++++ .../Schema/Entities/DefenderWeaponWorld.xml | 41 +++ .../Entities/DefenderWeaponWorldRed.xml | 41 +++ resources/Schema/Entities/MovementTest.xml | 253 +----------------- resources/Schema/Entities/Player.xml | 206 +++++--------- resources/Schema/Entities/PlayerRed.xml | 211 ++++++--------- resources/Schema/Types/Entity.xsd | 2 + resources/Schema/Types/WeaponSlotEnum.xsd | 16 ++ resources/Shaders/ForwardPlus.frag.glsl | 7 +- src/Engine/Collision/CollisionSystem.cpp | 93 ++++--- src/Engine/Core/EntityWrapper.cpp | 80 +++++- src/Engine/Core/Util/Logging.cpp | 4 +- src/Engine/Core/World.cpp | 2 +- src/Engine/Editor/EditorGUI.cpp | 13 + src/Engine/Editor/EditorSystem.cpp | 6 + src/Engine/Network/Client.cpp | 10 +- src/Engine/Network/Server.cpp | 6 +- src/Engine/Rendering/CubeMapPass.cpp | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 7 +- src/Game/Game.cpp | 13 +- .../Network/MultiplayerSnapshotFilter.cpp | 1 + src/Game/Systems/DamageIndicatorSystem.cpp | 2 +- src/Game/Systems/PlayerMovementSystem.cpp | 17 +- src/Game/Systems/PlayerSpawnSystem.cpp | 35 ++- src/Game/Systems/SpawnerSystem.cpp | 2 +- ...aviour.cpp => AssaultWeaponBehaviour.cpp_} | 52 ++-- .../Weapon/DefenderWeaponBehaviour.cpp | 188 +++++++++++++ .../{WeaponSystem.cpp => WeaponSystem.cpp_} | 56 +++- 60 files changed, 1481 insertions(+), 701 deletions(-) create mode 100644 include/Game/Systems/Weapon/DefenderWeaponBehaviour.h create mode 100644 resources/Schema/Components/CapturePointGameMode.xml create mode 100644 resources/Schema/Components/CapturePointGameMode.xsd create mode 100755 resources/Schema/Components/DefenderWeapon.xml create mode 100755 resources/Schema/Components/DefenderWeapon.xsd create mode 100644 resources/Schema/Components/DoubleJump.xml create mode 100644 resources/Schema/Components/DoubleJump.xsd delete mode 100644 resources/Schema/Components/Weapon.xml delete mode 100644 resources/Schema/Components/Weapon.xsd create mode 100644 resources/Schema/Components/WeaponAttachment.xml create mode 100644 resources/Schema/Components/WeaponAttachment.xsd create mode 100755 resources/Schema/Entities/AssaultWeaponView.xml create mode 100755 resources/Schema/Entities/AssaultWeaponWorld.xml create mode 100755 resources/Schema/Entities/DefenderShield.xml create mode 100755 resources/Schema/Entities/DefenderWeaponView.xml create mode 100755 resources/Schema/Entities/DefenderWeaponViewRed.xml create mode 100755 resources/Schema/Entities/DefenderWeaponWorld.xml create mode 100755 resources/Schema/Entities/DefenderWeaponWorldRed.xml create mode 100644 resources/Schema/Types/WeaponSlotEnum.xsd rename src/Game/Systems/Weapon/{AssaultWeaponBehaviour.cpp => AssaultWeaponBehaviour.cpp_} (87%) create mode 100644 src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp rename src/Game/Systems/Weapon/{WeaponSystem.cpp => WeaponSystem.cpp_} (56%) diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 9cd2fe63..19adea35 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -24,6 +24,7 @@ public: private: Octree* m_Octree; std::vector m_OctreeResult; + std::unordered_map m_PrevPositions; }; #endif \ No newline at end of file diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index b0e65d9e..8ece8e59 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -29,16 +29,22 @@ struct EntityWrapper EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); + EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid); + std::vector ChildrenWithComponent(const std::string& componentType); + void DeleteChildren(); bool IsChildOf(EntityWrapper potentialParent); bool Valid() const; ComponentWrapper operator[](const char* componentName); + ComponentWrapper operator[](const std::string& componentName); bool operator==(const EntityWrapper& e) const; bool operator!=(const EntityWrapper& e) const; explicit operator EntityID() const; private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); + EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent); + void childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent); }; namespace std diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index 1a387855..23d5f9a5 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -68,7 +68,7 @@ protected: const std::string m_ComponentType; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) = 0; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) = 0; }; class ImpureSystem : public virtual System diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 1604df37..c9f738ce 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -40,7 +40,7 @@ public: // Change the parent of an entity void SetParent(EntityID entity, EntityID parent); // Get children of an entity - const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetChildren(EntityID entity); + const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetDirectChildren(EntityID entity); // Get all component pools const std::unordered_map& GetComponentPools() const { return m_ComponentPools; } // Get the entity children map diff --git a/include/Engine/Editor/EditorGUI.h b/include/Engine/Editor/EditorGUI.h index 7a0289c6..57574e66 100644 --- a/include/Engine/Editor/EditorGUI.h +++ b/include/Engine/Editor/EditorGUI.h @@ -73,6 +73,12 @@ public: // Called when the user means to rename an entity. typedef std::function OnEntityChangeName_t; void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; } + // Called when the user pastes an entity previously "copied" + // @param EntityWrapper The entity to copy + // @param EntityWrapper The entity to parent the new copy to + // @return The new copy of the entity + typedef std::function OnEntityPaste_t; + void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; } // Called when the user means to attach a new component to an entity. typedef std::function OnComponentAttach_t; void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } @@ -111,6 +117,7 @@ private: std::string m_DroppedFile = ""; bool m_Paused = false; bool m_MouseLocked = false; + EntityWrapper m_CopyTarget = EntityWrapper::Invalid; // Callbacks OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; @@ -124,6 +131,7 @@ private: OnComponentDelete_t m_OnComponentDelete = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr; + OnEntityPaste_t m_OnEntityPaste = nullptr; // Events EventRelay m_EKeyDown; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index fcaa2e47..06ee53b6 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -56,6 +56,7 @@ private: void OnEntityDelete(EntityWrapper entity); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeName(EntityWrapper entity, const std::string& name); + EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent); void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 968c4bba..be76e265 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -19,6 +19,7 @@ #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/ConfigFile.h" +#include "Core/EPlayerDeath.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" #include "../Game/Events/EDoubleJump.h" diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index bf87bef8..70f94807 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -13,8 +13,6 @@ public: PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; - - static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -31,8 +29,8 @@ private: //EntityWrapper ID -> Player ID. std::map m_PlayerIDs; - static float m_RespawnTime; - float m_Timer; + float m_ForcedRespawnTime; + bool m_DbgConfigForceRespawn; EventRelay m_OnInputCommand; bool OnInputCommand(Events::InputCommand& e); diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 7bd9c175..993dd060 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -1,37 +1,33 @@ +#ifndef AssaultWeaponBehaviour_h__ +#define AssaultWeaponBehaviour_h__ + #include "Sound/EPlaySoundOnEntity.h" #include "Collision/Collision.h" -#include "Rendering/AnimationSystem.h" #include "Core/ConfigFile.h" #include "WeaponBehaviour.h" #include "../SpawnerSystem.h" #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" - -class AssaultWeaponBehaviour : public WeaponBehaviour +class AssaultWeaponBehaviour : public WeaponBehaviour { public: - AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper weaponEntity); - - virtual void Fire() override; - virtual void CeaseFire() override; - virtual void Reload() override; + AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) + : WeaponBehaviour(systemParams, "AssaultWeapon", renderer, collisionOctree) + { } - virtual void Update(double dt) override; +protected: + virtual void OnPrimaryFire(WeaponInfo& wi) override; + virtual void OnCeasePrimaryFire(WeaponInfo& wi) override; + virtual void OnReload(WeaponInfo& wi) override; private: - EntityWrapper m_FirstPersonModel; - EntityWrapper m_ThirdPersonModel; // State bool m_Firing = false; bool m_Reloading = false; double m_ReloadTimer = 0.0; - EntityWrapper m_FirstPersonReloadImpersonator; - EntityWrapper m_ThirdPersonReloadImpersonator; double m_TimeSinceLastFire = 0.0; - - EventRelay m_EAnimationComplete; - bool OnAnimationComplete(Events::AnimationComplete& e); + EntityWrapper m_FirstPersonReloadImpostor; bool hasAmmo(); void fireRound(); @@ -47,3 +43,5 @@ private: bool shoot(double damage); void showHitMarker(); }; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h new file mode 100644 index 00000000..5ca13d3e --- /dev/null +++ b/include/Game/Systems/Weapon/DefenderWeaponBehaviour.h @@ -0,0 +1,38 @@ +#include "WeaponBehaviour.h" +#include "Collision/Collision.h" +#include "Core/EPlayerDamage.h" +#include "Rendering/ESetCamera.h" + +class DefenderWeaponBehaviour : public WeaponBehaviour +{ +public: + DefenderWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree) + : System(systemParams) + , WeaponBehaviour(systemParams, "DefenderWeapon", renderer, collisionOctree) + , m_RandomEngine(m_RandomDevice()) + { + EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DefenderWeaponBehaviour::OnSetCamera); + } + + void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) override; + void UpdateWeapon(WeaponInfo& wi, double dt) override; + void OnPrimaryFire(WeaponInfo& wi) override; + void OnCeasePrimaryFire(WeaponInfo& wi) override; + bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) override; + +private: + std::random_device m_RandomDevice; + std::mt19937 m_RandomEngine; + EntityWrapper m_CurrentCamera; + + EventRelay m_ESetCamera; + bool OnSetCamera(const Events::SetCamera& e); + + // Weapon functions + void fireShell(WeaponInfo& wi); + void dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage); + + // Utility + float traceRayDistance(glm::vec3 origin, glm::vec3 direction); + Camera cameraFromEntity(EntityWrapper camera); +}; \ No newline at end of file diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h index 7a0b4626..f23269df 100644 --- a/include/Game/Systems/Weapon/WeaponBehaviour.h +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -5,30 +5,177 @@ #include "Rendering/IRenderer.h" #include "Core/Octree.h" #include "Collision/EntityAABB.h" +#include "Input/EInputCommand.h" +#include "Systems/SpawnerSystem.h" -class WeaponBehaviour : public System +template +class WeaponBehaviour : public PureSystem { + friend class WeaponSystem; + public: - WeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) - : System(systemParams) + WeaponBehaviour(SystemParams params, std::string componentType, IRenderer* renderer, Octree* collisionOctree) + : System(params) + , PureSystem(componentType) , m_Renderer(renderer) , m_CollisionOctree(collisionOctree) - , m_Player(player) - { } + { + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponBehaviour::_OnInputCommand) + } virtual ~WeaponBehaviour() = default; - WeaponBehaviour(const WeaponBehaviour&) = delete; - WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; - - virtual void Fire() = 0; - virtual void CeaseFire() { } - virtual void Reload() { } - virtual void Update(double dt) { } + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override + { + auto weapon = getActiveWeapon(entity); + if (!weapon) { + return; + } else { + UpdateWeapon(*weapon, dt); + } + } protected: + struct WeaponInfo + { + std::string WeaponComponent; + EntityWrapper Player; + EntityWrapper WeaponEntity; + EntityWrapper FirstPersonEntity; + EntityWrapper ThirdPersonEntity; + ComponentWrapper GetComponent() { return WeaponEntity[WeaponComponent]; } + }; + IRenderer* m_Renderer; Octree* m_CollisionOctree; - EntityWrapper m_Player; + std::unordered_map m_ActiveWeapons; + + virtual void UpdateWeapon(WeaponInfo& wi, double dt) { } + virtual void OnPrimaryFire(WeaponInfo& wi) { } + virtual void OnCeasePrimaryFire(WeaponInfo& wi) { } + virtual void OnReload(WeaponInfo& wi) { } + virtual bool OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) { return false; } + +private: + EventRelay m_EInputCommand; + bool _OnInputCommand(const Events::InputCommand& e) + { + EntityWrapper player = e.Player; + if (e.PlayerID == -1) { + player = LocalPlayer; + } + + // Make sure the player is alive + if (!player.Valid()) { + return false; + } + + // Make sure the player has this weapon + auto weapon = getWeaponComponent(player); + if (!weapon) { + return false; + } + + // Weapon selection + if (e.Command == "SelectWeapon") { + if (static_cast(e.Value) == static_cast((*weapon)["Slot"])) { + selectWeapon(player); + } + } + + // Only handle weapon actions if the weapon is active + auto activeWeapon = getActiveWeapon(player); + if (!activeWeapon) { + return false; + } + + // Fire + if (e.Command == "PrimaryFire") { + if (e.Value > 0) { + OnPrimaryFire(*activeWeapon); + } else { + OnCeasePrimaryFire(*activeWeapon); + } + } + + // Reload + if (e.Command == "Reload" && e.Value != 0) { + OnReload(*activeWeapon); + } + + return OnInputCommand(*activeWeapon, e); + } + + boost::optional getWeaponComponent(EntityWrapper player) + { + if (!player.HasComponent(m_ComponentType)) { + return boost::none; + } + + return player[m_ComponentType]; + } + + boost::optional getActiveWeapon(EntityWrapper player) + { + auto it = m_ActiveWeapons.find(player); + if (it == m_ActiveWeapons.end()) { + return boost::none; + } + WeaponInfo& activeWeapon = it->second; + + if (!activeWeapon.FirstPersonEntity.Valid() && !activeWeapon.ThirdPersonEntity.Valid()) { + return boost::none; + } + + return activeWeapon; + } + + void selectWeapon(EntityWrapper player) + { + // Find the weapon attachments matching the weapon type + std::vector weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); + EntityWrapper firstPersonAttachment; + EntityWrapper thirdPersonAttachment; + for (auto& attachment : weaponAttachments) { + ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; + if ((std::string&)cWeaponAttachment["Weapon"] == m_ComponentType) { + ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; + if ((ComponentInfo::EnumType)person == person.Enum("FirstPerson")) { + firstPersonAttachment = attachment; + } else if ((ComponentInfo::EnumType)person == person.Enum("ThirdPerson")) { + thirdPersonAttachment = attachment; + } + } + } + + if (!firstPersonAttachment.Valid() && !thirdPersonAttachment.Valid()) { + LOG_WARNING("No weapon attachment found for %s of player #%i", m_ComponentType.c_str(), player.ID); + return; + } + + // Purge other weapon entities + for (auto& attachment : weaponAttachments) { + //if (attachment == firstPersonAttachment || attachment == thirdPersonAttachment) { + // continue; + //} + attachment.DeleteChildren(); + } + + // Spawn the weapon(s) + EntityWrapper firstPersonWeapon; + EntityWrapper thirdPersonWeapon; + if (firstPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); + } + if (thirdPersonAttachment.Valid()) { + thirdPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); + } + + m_ActiveWeapons[player].WeaponComponent = m_ComponentType; + m_ActiveWeapons[player].Player = player; + m_ActiveWeapons[player].WeaponEntity = player; + m_ActiveWeapons[player].FirstPersonEntity = firstPersonWeapon; + m_ActiveWeapons[player].ThirdPersonEntity = thirdPersonWeapon; + } }; #endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 42abed82..eb41ed6a 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -46,4 +46,8 @@ + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index 6c645624..c835217b 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -8,4 +8,5 @@ 120 0.01 2 + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 95df64b7..7e9854a2 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -2,6 +2,7 @@ + @@ -28,6 +29,7 @@ Time it takes to reload the weapon in seconds + diff --git a/resources/Schema/Components/CapturePointGameMode.xml b/resources/Schema/Components/CapturePointGameMode.xml new file mode 100644 index 00000000..3104e71f --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xml @@ -0,0 +1,5 @@ + + + 0.0 + 8.0 + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointGameMode.xsd b/resources/Schema/Components/CapturePointGameMode.xsd new file mode 100644 index 00000000..8b81d67a --- /dev/null +++ b/resources/Schema/Components/CapturePointGameMode.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + The time since the last respawn wave. Players will be spawned when this reaches MaxRespawnTime. + + + Players will be spawned when RespawnTime reaches this. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/DefenderWeapon.xml b/resources/Schema/Components/DefenderWeapon.xml new file mode 100755 index 00000000..998f3bde --- /dev/null +++ b/resources/Schema/Components/DefenderWeapon.xml @@ -0,0 +1,16 @@ + + + 8 + 8 + 64 + 64 + 90 + 0.174533 + 10 + 120 + 0.01 + 0.5 + + false + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/DefenderWeapon.xsd b/resources/Schema/Components/DefenderWeapon.xsd new file mode 100755 index 00000000..3fe5a64a --- /dev/null +++ b/resources/Schema/Components/DefenderWeapon.xsd @@ -0,0 +1,44 @@ + + + + + + + + + + + Ammo currently loaded into the magazine + + + Max number of rounds in a magazine + + + Current ammo carried + + + Maximum ammo able to be carried + + + Damage dealt if all shotgun pellets hit + + + Spread angle in radians + + + + Rate of fire in rounds per minute + + + View punch in radians for each shell fired + + + Time it takes to load ONE SHELL into the weapon in seconds + + + + + + + + diff --git a/resources/Schema/Components/DoubleJump.xml b/resources/Schema/Components/DoubleJump.xml new file mode 100644 index 00000000..bb0d3bc7 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xml @@ -0,0 +1,4 @@ + + + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/DoubleJump.xsd b/resources/Schema/Components/DoubleJump.xsd new file mode 100644 index 00000000..65ff0419 --- /dev/null +++ b/resources/Schema/Components/DoubleJump.xsd @@ -0,0 +1,16 @@ + + + + + + + Enables a Player to double jump. + + + + Vertical velocity set on double jump. + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 84b6aba3..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,7 +2,6 @@ true - false 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 206e2a23..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,7 +13,6 @@ m/s^2 - The largest height of a "stair-step" that can be walked over diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index 00cff257..b50274ac 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,5 +2,7 @@ 3 1.5 + 4.0 + \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 1b33d222..006ae9d7 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -11,7 +11,11 @@ + + Vertical velocity set when jumping. + + diff --git a/resources/Schema/Components/Weapon.xml b/resources/Schema/Components/Weapon.xml deleted file mode 100644 index 38c6fce9..00000000 --- a/resources/Schema/Components/Weapon.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/resources/Schema/Components/Weapon.xsd b/resources/Schema/Components/Weapon.xsd deleted file mode 100644 index 8bddd8a9..00000000 --- a/resources/Schema/Components/Weapon.xsd +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xml b/resources/Schema/Components/WeaponAttachment.xml new file mode 100644 index 00000000..8867b2b7 --- /dev/null +++ b/resources/Schema/Components/WeaponAttachment.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/WeaponAttachment.xsd b/resources/Schema/Components/WeaponAttachment.xsd new file mode 100644 index 00000000..3b1291ae --- /dev/null +++ b/resources/Schema/Components/WeaponAttachment.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + Combine with a spawner to define a weapon attachment point + + + + The weapon component type this attachment refers to + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AssaultWeaponView.xml b/resources/Schema/Entities/AssaultWeaponView.xml new file mode 100755 index 00000000..4b985fbb --- /dev/null +++ b/resources/Schema/Entities/AssaultWeaponView.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AssaultWeaponWorld.xml b/resources/Schema/Entities/AssaultWeaponWorld.xml new file mode 100755 index 00000000..6fcb97b3 --- /dev/null +++ b/resources/Schema/Entities/AssaultWeaponWorld.xml @@ -0,0 +1,40 @@ + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/DefenderShield.xml b/resources/Schema/Entities/DefenderShield.xml new file mode 100755 index 00000000..da760e72 --- /dev/null +++ b/resources/Schema/Entities/DefenderShield.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + + + Models/Core/UnitHexagon.mesh + + true + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponView.xml b/resources/Schema/Entities/DefenderWeaponView.xml new file mode 100755 index 00000000..f6b6e89d --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponView.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/DefenderGunBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponViewRed.xml b/resources/Schema/Entities/DefenderWeaponViewRed.xml new file mode 100755 index 00000000..b5b1c322 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponViewRed.xml @@ -0,0 +1,99 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/DefenderGunRed.mesh + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponWorld.xml b/resources/Schema/Entities/DefenderWeaponWorld.xml new file mode 100755 index 00000000..826301b4 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponWorld.xml @@ -0,0 +1,41 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/DefenderGunBlue.mesh + + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/DefenderWeaponWorldRed.xml b/resources/Schema/Entities/DefenderWeaponWorldRed.xml new file mode 100755 index 00000000..7f697304 --- /dev/null +++ b/resources/Schema/Entities/DefenderWeaponWorldRed.xml @@ -0,0 +1,41 @@ + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Red/DefenderGunRed.mesh + + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 84aaa03a..41474568 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -10,7 +10,7 @@ - Schema/Entities/Player.xml + Schema/Entities/PlayerRed.xml @@ -118,257 +118,6 @@ - - - - - - - - 600 - - - - - - - - - 5 - - - - - - - - - - - - - - - - - - - - - - - Fonts/DroidSans.ttf,100 - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - - - - - - - - 1 - - - - - Models/Core/UnitHexagon.mesh - - - - - - - - - - - - - - Textures/Weapons/Crosshair/SmallThickHoleDot.png - false - - - - - - - - - - - - - - Idle - 1.9569972344146196 - 1 - - - Models/Characters/Assault/FirstPerson.mesh - true - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - - - Schema/Entities/WeaponReloadEffect.xml - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - Idle - 1.8055945618467364 - 1 - - - AimRifle - - - - - Models/Characters/Assault/AssaultAnimations.mesh - - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - false - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 7a5d2eb4..88f153ae 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -7,24 +7,31 @@ - 600 + + + - + + 1.6944730461160304 + + - 5 + - + + + @@ -304,7 +311,8 @@ - + + @@ -364,7 +372,7 @@ Idle - 0.97725610639912475 + 0.67172915251515519 1 @@ -376,100 +384,29 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - + + Schema/Entities/DefenderWeaponView.xml + + + + DefenderWeapon + - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - + + + + + + Schema/Entities/AssaultWeaponView.xml + + + + AssaultWeapon + + + @@ -493,7 +430,6 @@ Idle - 0.87583812735846323 1 @@ -502,6 +438,7 @@ AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -510,41 +447,35 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - + + Schema/Entities/DefenderWeaponWorld.xml + + + + DefenderWeapon + + + + - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - + + + + + + Schema/Entities/AssaultWeaponWorld.xml + + + + AssaultWeapon + + + + + + @@ -610,6 +541,17 @@ + + + + Schema/Entities/DefenderShield.xml + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index cd01632e..3cf17558 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -7,24 +7,31 @@ - 600 + + + - + + 1.6944730461160304 + + - 5 + - + + + @@ -365,7 +372,7 @@ Idle - 1.2667383999985162 + 0.67172915251515519 1 @@ -377,100 +384,29 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Red/AssaultWeaponRed.mesh - - - - - + + Schema/Entities/DefenderWeaponViewRed.xml + + + + DefenderWeapon + - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectViewRed.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - + + + + + + Schema/Entities/AssaultWeaponView.xml + + + + AssaultWeapon + + + @@ -494,7 +430,6 @@ Idle - 0.26532318661337229 1 @@ -503,6 +438,7 @@ AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -511,41 +447,35 @@ - + - - R_Arm_Weapon_Joint - - - Models/Weapons/Red/AssaultWeaponRed.mesh - - - - - + + Schema/Entities/DefenderWeaponWorldRed.xml + + + + DefenderWeapon + + + + - - - - - Schema/Entities/RayRed.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorldRed.xml - - - - - - + + + + + + Schema/Entities/AssaultWeaponWorld.xml + + + + AssaultWeapon + + + + + + @@ -584,20 +514,20 @@ - + - + Textures/Icons/Arrow.png false - + @@ -605,12 +535,23 @@ true - + + + + + Schema/Entities/DefenderShield.xml + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index a9c5f641..0965ef89 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -50,6 +50,8 @@ + + diff --git a/resources/Schema/Types/WeaponSlotEnum.xsd b/resources/Schema/Types/WeaponSlotEnum.xsd new file mode 100644 index 00000000..6713ca9d --- /dev/null +++ b/resources/Schema/Types/WeaponSlotEnum.xsd @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 00f95888..aa45d118 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -171,7 +171,8 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2; + vec4 reflectionTotal = reflectionColor * (1-specularTexel.a) * color_result.a; + color_result = color_result * clamp(1/specularTexel.a, 0, 1) + reflectionTotal; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; @@ -182,9 +183,9 @@ void main() } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); //sceneColor = vec4(reflectionColor.xyz, 1); - color_result += glowTexel*GlowIntensity; + color_result.xyz += glowTexel.xyz*GlowIntensity; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); + bloomColor = vec4(max(color_result.xyz - 1.0, 0.0), clamp(color_result.a, 0, 1)); //Tiled Debug Code /* diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index fcc3665f..95609ea6 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -12,55 +12,56 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!boundingBox) { return; } + ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; - glm::vec3 size = boxA.Size(); - float diameter = std::min(size.x, size.z); - glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"]; - glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; - float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; - //If the entity has moved farther than the size of its box, we need to handle it specially. - bool traceCollision = rayLength > diameter; - //hack solution: If prevOrigin is less than -9000 in all dimensions, - //then it means it is not set, i.e. this is the first collision check for the entity. - if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) { - Ray ray(prevOrigin, toCurrentPos); - m_OctreeResult.clear(); - m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); - for (auto& boxB : m_OctreeResult) { - if (boxA.Entity == boxB.Entity) { - continue; - } - bool hit; - float dist; - if (boxB.Entity.HasComponent("Model")) { - RawModel* model; - std::string res = (std::string)boxB.Entity["Model"]["Resource"]; - try { - model = ResourceManager::Load(res); - } catch (const std::exception&) { + auto prevPosIt = m_PrevPositions.find(entity); + if (prevPosIt != m_PrevPositions.end()) { + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = prevPosIt->second; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + if (rayLength > diameter) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { continue; } - float u, v; - hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); - } else { - hit = Collision::RayVsAABB(ray, boxB, dist); - } - if (hit && dist < rayLength) { - //Set the entity to where it was colliding, minus the maximum box size. - //TODO: Perhaps this should be done slightly more properly. - glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); - glm::vec3 resolve = newOriginPos - boxA.Origin(); - (glm::vec3&)cTransform["Position"] += resolve; - boxA = *Collision::EntityAbsoluteAABB(entity); - if (resolve.y > 0) { - everHitTheGround = true; - (bool)cPhysics["IsOnGround"] = true; - ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + continue; + } + float u, v; + hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); + } else { + hit = Collision::RayVsAABB(ray, boxB, dist); + } + if (hit && dist < rayLength) { + //Set the entity to where it was colliding, minus the maximum box size. + //TODO: Perhaps this should be done slightly more properly. + glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); + glm::vec3 resolve = newOriginPos - boxA.Origin(); + (glm::vec3&)cTransform["Position"] += resolve; + boxA = *Collision::EntityAbsoluteAABB(entity); + if (resolve.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + } + break; } - break; } } } @@ -86,10 +87,13 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool notMovingxz = glm::all(glm::lessThan(glm::abs(glm::vec2(inOutVelocity.x, inOutVelocity.z)), glm::vec2(0.01f))) && prevPosIt != m_PrevPositions.end(); bool isOnGround = (bool)cPhysics["IsOnGround"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { - (glm::vec3&)cTransform["Position"] += resolutionVector; + //Move the position to previous position if it is not moving in the xz-plane, else resolve with the resolution vector. + (glm::vec3&)cTransform["Position"] += notMovingxz ? prevPosIt->second - boxA.Origin() : resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { everHitTheGround = true; @@ -99,6 +103,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); if (resolutionVector.y > 0) { everHitTheGround = true; (bool)cPhysics["IsOnGround"] = true; @@ -112,5 +117,5 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c (bool)cPhysics["IsOnGround"] = false; } - (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin(); + m_PrevPositions[entity] = boxA.Origin(); } diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 4b45b8d0..b3bef55a 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -51,6 +51,40 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::Clone(EntityWrapper parent /*= Invalid*/) +{ + if (!Valid()) { + return EntityWrapper::Invalid; + } + + EntityWrapper clone = cloneRecursive(*this, EntityWrapper::Invalid); + this->World->SetParent(clone.ID, parent.ID); + return clone; +} + +std::vector EntityWrapper::ChildrenWithComponent(const std::string& componentType) +{ + std::vector childrenWithComponent; + childrenWithComponentRecursive(componentType, *this, childrenWithComponent); + return childrenWithComponent; +} + +void EntityWrapper::DeleteChildren() +{ + auto itPair = this->World->GetDirectChildren(this->ID); + if (itPair.first == itPair.second) { + return; + } + + std::vector entitiesToDelete; + for (auto it = itPair.first; it != itPair.second; it++) { + entitiesToDelete.push_back(it->second); + } + for (auto& e : entitiesToDelete) { + this->World->DeleteEntity(e); + } +} + bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) { EntityWrapper entity = *this; @@ -90,6 +124,11 @@ ComponentWrapper EntityWrapper::operator[](const char* componentName) } } +ComponentWrapper EntityWrapper::operator[](const std::string& componentName) +{ + return this->operator[](componentName.c_str()); +} + bool EntityWrapper::operator==(const EntityWrapper& e) const { return (this->ID == e.ID) && (this->World == e.World); @@ -111,7 +150,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } - auto itPair = this->World->GetChildren(parent); + auto itPair = this->World->GetDirectChildren(parent); if (itPair.first == itPair.second) { return EntityWrapper::Invalid; } @@ -131,3 +170,42 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::cloneRecursive(EntityWrapper entity, EntityWrapper parent) +{ + EntityWrapper clone = EntityWrapper(entity.World, entity.World->CreateEntity(parent.ID)); + entity.World->SetName(clone.ID, entity.Name()); + + // Clone components + for (auto& kv : entity.World->GetComponentPools()) { + if (kv.second->KnowsEntity(entity.ID)) { + ComponentWrapper c1 = kv.second->GetByEntity(entity.ID); + ComponentWrapper c2 = entity.World->AttachComponent(clone.ID, kv.first); + c1.Copy(c2); + } + } + + // Clone children + auto children = entity.World->GetDirectChildren(entity.ID); + for (auto it = children.first; it != children.second; ++it) { + EntityWrapper child(entity.World, it->second); + cloneRecursive(child, clone); + } + + return clone; +} + +void EntityWrapper::childrenWithComponentRecursive(const std::string& componentType, EntityWrapper& entity, std::vector& childrenWithComponent) +{ + auto itPair = this->World->GetDirectChildren(entity.ID); + if (itPair.first == itPair.second) { + return; + } + + for (auto it = itPair.first; it != itPair.second; ++it) { + EntityWrapper child = EntityWrapper(entity.World, it->second); + if (child.HasComponent(componentType)) { + childrenWithComponent.push_back(child); + } + childrenWithComponentRecursive(componentType, child, childrenWithComponent); + } +} diff --git a/src/Engine/Core/Util/Logging.cpp b/src/Engine/Core/Util/Logging.cpp index 63a6f380..c7612fd8 100644 --- a/src/Engine/Core/Util/Logging.cpp +++ b/src/Engine/Core/Util/Logging.cpp @@ -33,8 +33,8 @@ void _LOG(_LOG_LEVEL logLevel, const char* file, const char* func, unsigned int va_end(args); if (logLevel == LOG_LEVEL_ERROR) { - std::cerr << file << ":" << line << " " << func << std::endl; - std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; + //std::cerr << file << ":" << line << " " << func << std::endl; + //std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } else { std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; } diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 8788a92e..9b323ff4 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -127,7 +127,7 @@ void World::SetParent(EntityID entity, EntityID parent) m_EntityChildren.insert(std::make_pair(parent, entity)); } -const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetChildren(EntityID entity) +const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetDirectChildren(EntityID entity) { return m_EntityChildren.equal_range(entity); } diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index 70775a2b..f2690f13 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -598,6 +598,19 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e) entityImport(m_World); } + if (e.ModCtrl && e.KeyCode == GLFW_KEY_C) { + m_CopyTarget = m_CurrentSelection; + } + + if (e.ModCtrl && e.KeyCode == GLFW_KEY_V) { + if (m_OnEntityPaste != nullptr) { + EntityWrapper copy = m_OnEntityPaste(m_CopyTarget, m_CurrentSelection); + if (copy != EntityWrapper::Invalid) { + SelectEntity(copy); + } + } + } + if (e.KeyCode == GLFW_KEY_DELETE) { if (m_CurrentSelection.Valid()) { entityDelete(m_CurrentSelection); diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 97ea9d53..4bee1427 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -28,6 +28,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1)); m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2)); + m_EditorGUI->SetEntityPasteCallback(std::bind(&EditorSystem::OnEntityPaste, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); @@ -160,6 +161,11 @@ void EditorSystem::OnEntityChangeName(EntityWrapper entity, const std::string& n } } +EntityWrapper EditorSystem::OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent) +{ + return entityToCopy.Clone(parent); +} + void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType) { if (entity.Valid()) { diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index d94ccbc6..d8da7e16 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -261,8 +261,14 @@ void Client::parseEntityDeletion(Packet & packet) if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); if (m_World->ValidEntity(localEntity)) { - m_World->DeleteEntity(localEntity); - deleteFromServerClientMaps(entityToDelete, localEntity); + if (m_World->HasComponent(localEntity,"Player")) { + Events::PlayerDeath e; + e.Player = EntityWrapper(m_World, localEntity); + m_EventBroker->Publish(e); + } else { + m_World->DeleteEntity(localEntity); + deleteFromServerClientMaps(entityToDelete, localEntity); + } } } } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 7ed069d6..7c614cee 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -186,7 +186,7 @@ void Server::addInputCommandsToPacket(Packet& packet) void Server::addPlayersToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { @@ -234,7 +234,7 @@ void Server::addPlayersToPacket(Packet & packet, EntityID entityID) void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { @@ -601,7 +601,7 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { - auto children = m_World->GetChildren(childEntity.ID); + auto children = m_World->GetDirectChildren(childEntity.ID); for (auto it = children.first; it != children.second; it++) { EntityWrapper child(m_World, it->second); if(child.HasComponent("CapturePoint")) { diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index fc318498..e2a55b74 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -17,7 +17,7 @@ void CubeMapPass::LoadTextures(std::string input) m_CubeMapTextures.push_back(img); } GenerateCubeMapTexture(); - m_PreviusCubeMapTexture = input; + m_PreviusCubeMapTexture = input; } } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 3e477296..6b600d22 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -187,10 +187,11 @@ void DrawFinalPass::Draw(RenderScene& scene) state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); - state->BlendFunc(GL_ONE, GL_ONE); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); - GLERROR("TransparentObjects"); + //state->BlendFunc(GL_ONE, GL_ONE); state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + GLERROR("TransparentObjects"); + //state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 3495730e..2946d656 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -16,7 +16,7 @@ #include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/AmmoPickupSystem.h" #include "Game/Systems/DamageIndicatorSystem.h" -#include "Game/Systems/Weapon/WeaponSystem.h" +#include "Game/Systems/Weapon/DefenderWeaponBehaviour.h" #include "Rendering/AnimationSystem.h" #include "Game/Systems/HealthHUDSystem.h" #include "Rendering/BoneAttachmentSystem.h" @@ -48,7 +48,6 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); - PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); @@ -98,6 +97,10 @@ Game::Game(int argc, char* argv[]) m_NetworkClient->Connect(m_NetworkAddress, m_NetworkPort); m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " CLIENT"); } + } else { + // If network is disabled, pretend we're a server + m_IsClient = true; + m_IsServer = true; } // Create Octrees @@ -120,7 +123,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -135,7 +138,6 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -145,6 +147,9 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); + // Octree for frustum culling must be updated after collisions, otherwise players frustum may be moved after tree is filled, and wrong things are culled. + ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 69b7f282..295cdd7a 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -13,6 +13,7 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp component.Info.Name == "Transform" || component.Info.Name == "Physics" || component.Info.Name == "AssaultWeapon" + || component.Info.Name == "DefenderWeapon" || component.Info.Name == "Animation" || component.Info.Name == "AnimationOffset" || entity.Name() == "PlayerName" diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 92fbe607..ca26052d 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -13,7 +13,7 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) } void DamageIndicatorSystem::Update(double dt) { - if (!IsServer) { + if (!IsServer && LocalPlayer.Valid()) { for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) { if (!iter->spriteEntity.Valid()) { updateDamageIndicatorVector.erase(iter); diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 2e2502ec..b9ce23d4 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -116,12 +116,18 @@ void PlayerMovementSystem::updateMovementControllers(double dt) ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air - if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { - (bool)cPhysics["IsOnGround"] = false; + if (isOnGround) { + controller->SetDoubleJumping(false); + } + //If player presses Jump and is not crouching. + if (controller->Jumping() && !controller->Crouching()) { if (isOnGround) { - controller->SetDoubleJumping(false); - } else { + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["Player"]["JumpSpeed"]; + } else if (player.HasComponent("DoubleJump") && !controller->DoubleJumping()) { + //Enter here if player can double jump and is doing so. + (bool)cPhysics["IsOnGround"] = false; + velocity.y = player["DoubleJump"]["DoubleJumpSpeed"]; // If IsServer and network is off this will not work if (IsClient) { //put a hexagon at the players feet @@ -133,7 +139,6 @@ void PlayerMovementSystem::updateMovementControllers(double dt) m_EventBroker->Publish(e); } } - velocity.y = 4.f; } if (player.HasComponent("AABB")) { diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 6254c674..e03a1778 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,29 +1,40 @@ #include "Systems/PlayerSpawnSystem.h" -//This should be set by the config anyway. -float PlayerSpawnSystem::m_RespawnTime = 15.0f; - PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) - , m_Timer(0.f) + , m_DbgConfigForceRespawn(false) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); - m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_NetworkEnabled = config->Get("Networking.StartNetwork", false); + m_ForcedRespawnTime = config->Get("Debug.RespawnTime", -1.0f); + m_DbgConfigForceRespawn = m_ForcedRespawnTime > 0; } void PlayerSpawnSystem::Update(double dt) { - //Increase timer. - m_Timer += dt; - if (m_Timer < m_RespawnTime) { - return; + // If there are no CapturePointGameMode components we will just spawn immediately. + // Should be able to support older maps with this. + // TODO: In the future we might want to return instead, to avoid spawning in the menu for instance. + auto pool = m_World->GetComponents("CapturePointGameMode"); + if (pool != nullptr && pool->size() > 0) + { + // Take the first CapturePointGameMode component found. + ComponentWrapper& modeComponent = *pool->begin(); + // Increase timer. + double& timer = (double&)modeComponent["RespawnTime"]; + timer += dt; + double maxRespawnTime = m_DbgConfigForceRespawn ? m_ForcedRespawnTime : (double)modeComponent["MaxRespawnTime"]; + if (timer < maxRespawnTime) { + return; + } + // If respawn time has passed, we spawn all players that have requested to be spawned. + timer = 0; } - //If respawn time has passed, we spawn all players that have requested to be spawned. - m_Timer = 0.f; - //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + // If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. if (m_SpawnRequests.size() == 0) { return; } diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 90f677fe..6500460f 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -36,7 +36,7 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } // Find any SpawnPoints existing as children of spawner - auto children = spawner.World->GetChildren(spawner.ID); + auto children = spawner.World->GetDirectChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ similarity index 87% rename from src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp rename to src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ index 84d3ccd4..c3b3385f 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp_ @@ -1,13 +1,5 @@ #include "Systems/Weapon/AssaultWeaponBehaviour.h" -AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) - : WeaponBehaviour(systemParams, renderer, collisionOctree, player) -{ - m_FirstPersonModel = m_Player.FirstChildByName("Hands"); - m_ThirdPersonModel = m_Player.FirstChildByName("PlayerModel"); - EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); -} - void AssaultWeaponBehaviour::Fire() { m_TimeSinceLastFire = 0.0; @@ -36,7 +28,7 @@ void AssaultWeaponBehaviour::Reload() return; } - // Don't reload if we're completly out of ammo + // Don't reload if we're completely out of ammo if (ammo == 0) { playEmptySound(); m_TimeSinceLastFire = -0.0f; // HACK: To make empty sound play with interval @@ -56,14 +48,14 @@ void AssaultWeaponBehaviour::Update(double dt) { if (m_Reloading) { m_ReloadTimer -= dt; - // Re-enable glow on reload impersonator half-way through the animation + // Re-enable glow on reload impostor half-way through the animation if (IsClient) { if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { - if (m_FirstPersonReloadImpersonator.Valid()) { - m_FirstPersonReloadImpersonator["Model"]["GlowMap"] = true; + if (m_FirstPersonReloadImpostor.Valid()) { + m_FirstPersonReloadImpostor["Model"]["GlowMap"] = true; } - if (m_ThirdPersonReloadImpersonator.Valid()) { - m_ThirdPersonReloadImpersonator["Model"]["GlowMap"] = true; + if (m_ThirdPersonReloadImpostor.Valid()) { + m_ThirdPersonReloadImpostor["Model"]["GlowMap"] = true; } } } @@ -96,21 +88,6 @@ void AssaultWeaponBehaviour::Update(double dt) } } -bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) -{ - if (e.Entity != m_FirstPersonModel) { - return false; - } - - //if (e.Name == "ShootRifle") { - // if (!m_Firing) { - // playIdleAnimation(); - // } - //} - - return true; -} - bool AssaultWeaponBehaviour::hasAmmo() { ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; @@ -177,7 +154,6 @@ void AssaultWeaponBehaviour::spawnTracer() float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) { - // TODO: Cast a ray and size tracer appropriately float distance; glm::vec3 pos; auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); @@ -215,6 +191,12 @@ void AssaultWeaponBehaviour::playEmptySound() void AssaultWeaponBehaviour::viewPunch() { + // Since we send absolute client orientations to server, running this server side would + // cause aim desync. + if (!IsClient) { + return; + } + EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); if (!playerCamera.Valid()) { return; @@ -323,8 +305,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); if (IsClient) { - m_FirstPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpersonator["Model"]); + m_FirstPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpostor["Model"]); } firstPersonWeaponModel["Model"]["Visible"] = false; } @@ -332,8 +314,8 @@ void AssaultWeaponBehaviour::playReloadAnimation() EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); EntityWrapper reloadSpawner = m_Player.FirstChildByName("ThirdPersonReloadSpawner"); if (IsClient) { - m_ThirdPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpersonator["Model"]); + m_ThirdPersonReloadImpostor = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpostor["Model"]); } thirdPersonWeaponModel["Model"]["Visible"] = false; } @@ -371,7 +353,7 @@ bool AssaultWeaponBehaviour::shoot(double damage) return false; } - // Don't let us shoot ourselves in the foot + // Don't let us shoot ourselves in the foot somehow if (victim == LocalPlayer) { return false; } diff --git a/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp new file mode 100644 index 00000000..028bd10c --- /dev/null +++ b/src/Game/Systems/Weapon/DefenderWeaponBehaviour.cpp @@ -0,0 +1,188 @@ +#include "Systems/Weapon/DefenderWeaponBehaviour.h" + +void DefenderWeaponBehaviour::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cWeapon, double dt) +{ + (double&)cWeapon["TimeSinceLastFire"] += dt; + WeaponBehaviour::UpdateComponent(entity, cWeapon, dt); +} + +void DefenderWeaponBehaviour::UpdateWeapon(WeaponInfo& wi, double dt) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + + bool isFiring = cWeapon["IsFiring"]; + bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); + bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; + if (isFiring && cooldownPassed && isNotShielding) { + fireShell(wi); + } +} + +void DefenderWeaponBehaviour::OnPrimaryFire(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + cWeapon["IsFiring"] = true; + bool cooldownPassed = (double)cWeapon["TimeSinceLastFire"] >= (60.0 / (double)cWeapon["RPM"]); + bool isNotShielding = wi.Player.ChildrenWithComponent("Shield").size() == 0; + if (cooldownPassed && isNotShielding) { + fireShell(wi); + } +} + +void DefenderWeaponBehaviour::OnCeasePrimaryFire(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + cWeapon["IsFiring"] = false; +} + +bool DefenderWeaponBehaviour::OnInputCommand(WeaponInfo& wi, const Events::InputCommand& e) +{ + if (e.Command == "SpecialAbility" && IsServer) { + EntityWrapper attachment = wi.Player.FirstChildByName("ShieldAttachment"); + if (attachment.Valid()) { + if (e.Value > 0) { + SpawnerSystem::Spawn(attachment, attachment); + } else { + attachment.DeleteChildren(); + } + } + } + + return false; +} + +bool DefenderWeaponBehaviour::OnSetCamera(const Events::SetCamera& e) +{ + m_CurrentCamera = e.CameraEntity; + return true; +} + +void DefenderWeaponBehaviour::fireShell(WeaponInfo& wi) +{ + ComponentWrapper cWeapon = wi.GetComponent(); + + cWeapon["TimeSinceLastFire"] = 0.0; + int numPellets = cWeapon["NumPellets"]; + float spreadAngle = cWeapon["SpreadAngle"]; + std::uniform_real_distribution randomSpreadAngle(-spreadAngle, spreadAngle); + + // Calculate pellet angles + // HACK: Random for now? + // TODO: Make distribution even for each quadrant + std::vector pelletAngles; + for (int i = 0; i < numPellets; i++) { + pelletAngles.push_back(glm::vec2(randomSpreadAngle(m_RandomEngine), randomSpreadAngle(m_RandomEngine))); + LOG_DEBUG("%f %f", pelletAngles[i].x, pelletAngles[i].y); + } + + double pelletDamage = (double)cWeapon["BaseDamage"] / numPellets; + + // Tracers + EntityWrapper weaponModelEntity; + if (wi.Player == LocalPlayer) { + weaponModelEntity = wi.FirstPersonEntity; + } else { + weaponModelEntity = wi.ThirdPersonEntity; + } + if (weaponModelEntity.Valid()) { + EntityWrapper spawner = weaponModelEntity.FirstChildByName("WeaponMuzzle"); + for (auto& angles : pelletAngles) { + glm::vec3 direction = Transform::AbsoluteOrientation(spawner) * glm::quat(glm::vec3(angles, 0.f)) * glm::vec3(0, 0, -1); + float distance = traceRayDistance(Transform::AbsolutePosition(spawner), direction); + EntityWrapper ray = SpawnerSystem::Spawn(spawner); + ((glm::vec3&)ray["Transform"]["Scale"]).z = (distance / 100.f); + glm::vec3& orientation = ray["Transform"]["Orientation"]; + orientation.x += angles.x; + orientation.y += angles.y; + glm::vec3 trajectory = direction * distance; + dealDamage(wi, direction, pelletDamage); + } + } + +} + +void DefenderWeaponBehaviour::dealDamage(WeaponInfo& wi, glm::vec3 direction, double damage) +{ + // Only deal damage client side + if (!IsClient) { + return; + } + + // Only handle shooting for the local player + if (wi.Player != LocalPlayer) { + return; + } + + // Make sure the player isn't shooting from the grave + if (!wi.Player.Valid()) { + return; + } + + glm::vec3 maxRange = direction * 2.f; + EntityWrapper camera = wi.Player.FirstChildByName("Camera"); + glm::vec3 cameraPosition = Transform::AbsolutePosition(camera); + if (!camera.Valid()) { + return; + } + Rectangle screenResolution = m_Renderer->GetViewportSize(); + glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); + glm::vec2 screenCoords = cameraFromEntity(m_CurrentCamera).WorldToScreen(cameraPosition + maxRange, m_Renderer->GetViewportSize()); + PickData pickData = m_Renderer->Pick(centerScreen + screenCoords); + EntityWrapper victim(m_World, pickData.Entity); + if (!victim.Valid()) { + return; + } + + // Don't let us shoot ourselves in the foot somehow + if (victim == LocalPlayer) { + return; + } + + // Only care about players being hit + if (!victim.HasComponent("Player")) { + victim = victim.FirstParentWithComponent("Player"); + } + if (!victim.Valid()) { + return; + } + + // Check for friendly fire + if ((ComponentInfo::EnumType)victim["Team"]["Team"] == (ComponentInfo::EnumType)wi.Player["Team"]["Team"]) { + return; + } + + // Deal damage! + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Inflictor = wi.Player; + ePlayerDamage.Victim = victim; + ePlayerDamage.Damage = damage; + m_EventBroker->Publish(ePlayerDamage); + LOG_DEBUG("Damage: %f", damage); +} + +float DefenderWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) +{ + float distance; + glm::vec3 pos; + auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); + if (entity) { + return distance; + } else { + return 100.f; + } +} + +Camera DefenderWeaponBehaviour::cameraFromEntity(EntityWrapper camera) +{ + ComponentWrapper cTransform = camera["Transform"]; + ComponentWrapper cCamera = camera["Camera"]; + Camera cam( + (float)m_Renderer->Resolution().Width / m_Renderer->Resolution().Height, + (double)cCamera["FOV"], + (double)cCamera["NearClip"], + (double)cCamera["FarClip"] + ); + cam.SetPosition(cTransform["Position"]); + cam.SetOrientation(glm::quat((const glm::vec3&)cTransform["Orientation"])); + return cam; +} diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp_ similarity index 56% rename from src/Game/Systems/Weapon/WeaponSystem.cpp rename to src/Game/Systems/Weapon/WeaponSystem.cpp_ index 3a49ae90..d33c5098 100644 --- a/src/Game/Systems/Weapon/WeaponSystem.cpp +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp_ @@ -13,7 +13,7 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree weaponAttachments = player.ChildrenWithComponent("WeaponAttachment"); + + // Find the weapon attachments matching the slot selected + EntityWrapper firstPersonAttachment; + EntityWrapper thirdPersonAttachment; + for (auto& attachment : weaponAttachments) { + ComponentWrapper cWeaponAttachment = attachment["WeaponAttachment"]; + if ((ComponentInfo::EnumType)cWeaponAttachment["Slot"] == slot) { + ComponentWrapper::SubscriptProxy person = cWeaponAttachment["Person"]; + if (person == person.Enum("FirstPerson")) { + firstPersonAttachment = attachment; + } else if (person == person.Enum("ThirdPerson")) { + thirdPersonAttachment = attachment; + } + } + } + + if (firstPersonAttachment.Valid() && thirdPersonAttachment.Valid()) { + LOG_WARNING("No weapon attachment found for slot %i of player #%i", slot, player.ID); + return; + } + + // TODO: Delete old weapons + + // Spawn the weapon(s) + EntityWrapper firstPersonWeapon; + EntityWrapper thirdPersonWeapon; + if (firstPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(firstPersonAttachment, firstPersonAttachment); + } + if (thirdPersonAttachment.Valid()) { + firstPersonWeapon = SpawnerSystem::Spawn(thirdPersonAttachment, thirdPersonAttachment); + } + + // Create the correct behaviour + if (firstPersonWeapon.Valid()) { + if (firstPersonWeapon.HasComponent("AssaultWeapon") { + + } + } + // Primary if (slot == 1) { // TODO: if class... - if (m_ActiveWeapons.count(player) == 0) { - m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player))); - } else { - //m_ActiveWeapons.erase(player); - } + nextBehaviour = std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player); } // Secondary if (slot == 2) { //m_ActiveWeapons[player] = std::make_shared(); } + + if (nextBehaviour != nullptr) { + // TODO: Destroy previous behaviour and make new + if (m_ActiveWeapons.count(player) == 0) { + m_ActiveWeapons[player] = nextBehaviour; + } + } } bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) From 8cda614de456ef9103bed064deeae39260f1419a Mon Sep 17 00:00:00 2001 From: Teejoon Date: Tue, 1 Mar 2016 12:54:01 +0100 Subject: [PATCH 18/19] Added transparent object that disappeared from the merge --- src/Engine/Rendering/DrawFinalPass.cpp | 2 +- src/Engine/Rendering/PickingPassState.cpp | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 6b600d22..29499c79 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -189,7 +189,7 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("OpaqueObjects"); //state->BlendFunc(GL_ONE, GL_ONE); state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); //state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawSprites(scene.Jobs.SpriteJob, scene); diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index 3c19dc06..767b9577 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -9,7 +9,6 @@ PickingPassState::PickingPassState(GLuint frameBuffer) Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); Disable(GL_BLEND); - glm::vec4 clearColor = glm::vec4(0.f); //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); From 36f6ade87a461bd5e5d2f53e6cd47afa633d38f2 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 1 Mar 2016 13:36:34 +0100 Subject: [PATCH 19/19] Fixed editor keyboard shortcuts getting mixed up with GUI input actions --- src/Engine/Editor/EditorGUI.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index f2690f13..8ce15d0a 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -580,6 +580,11 @@ void EditorGUI::createWidgetToolButton(WidgetMode mode) bool EditorGUI::OnKeyDown(const Events::KeyDown& e) { + ImGuiIO& io = ImGui::GetIO(); + if (io.WantCaptureKeyboard) { + return false; + } + if (e.ModCtrl && e.KeyCode == GLFW_KEY_S) { if (m_CurrentSelection.Valid()) { EntityWrapper baseParent = m_CurrentSelection;