30 Commits

Author SHA1 Message Date
Jace f813f8d2ca What is this I don't even *falls asleep* 2014-05-27 10:25:52 +02:00
Jace f31b2b7ddb Merge branch 'render_queue'
Conflicts:
	src/GameWorld.cpp
	src/Renderer.cpp
	src/Shaders/Fragment.glsl
	src/Systems/PhysicsSystem.h
	vs11/Returngeance/Returngeance.vcxproj.filters
2014-05-27 09:35:52 +02:00
ViktorLjung f775864ed2 Fishy 2014-05-27 09:10:59 +02:00
Jace 7b622d530b No shadows and no skybox. 2014-05-27 08:35:39 +02:00
Jace 98167a806d Merge remote-tracking branch 'origin/deffered_rendering' into render_queue
Conflicts:
	src/Renderer.cpp
	src/Renderer.h
2014-05-27 07:10:50 +02:00
ViktorLjung c37df5c178 Damage and Spashdamage working, phantomShapes not really working 2014-05-27 07:04:29 +02:00
Jace d4b28a2228 Semi-working world rendering 2014-05-27 06:45:26 +02:00
Tleety 2db52ded2f Direction light working.
Cleaned up some code in Renderer.cpp
2014-05-27 03:09:52 +02:00
Jace 74239300bd Merge commit 'e3aab96a750d6e5d6f8ff42ffdb5a23a47ab929d' into render_queue
Conflicts:
	assets
	src/GameWorld.cpp
	src/Renderer.cpp
	src/Renderer.h
	src/Systems/RenderSystem.cpp
2014-05-26 04:21:08 +02:00
Jace 22442708cc One hell of a GUI interface (minus graphical)
"how does this even work lol"
2014-05-26 03:33:11 +02:00
Tleety 7d82c43df9 Started work on blend maps 2014-05-26 01:08:10 +02:00
ViktorLjung a0ee235473 Wrong assets 2014-05-26 01:04:31 +02:00
ViktorLjung 9a984dbb10 Broken 2014-05-26 01:03:25 +02:00
Jace 07c74ff9f5 I'll create a GUI interface using Visual Basic, see if I can track an IP address 2014-05-25 04:12:28 +02:00
Tleety e3aab96a75 Fixed forward rendering for transparensy 2014-05-25 01:52:57 +02:00
Jace 2fbcad4dbf Layer in render queue? 2014-05-24 20:32:54 +02:00
ViktorLjung dff888f82d Merge remote-tracking branch 'origin/master' into havok 2014-05-24 18:35:26 +02:00
ViktorLjung 60b8ad6799 Assets 2014-05-24 18:35:11 +02:00
Jace 1bf5a8464e Merge branch 'events' 2014-05-23 23:42:00 +02:00
Tleety a9f2911e41 Shadows working, and looking totaly not shit.
Improved location of the shadowmap to always be infront of the camera.
2014-05-23 22:42:11 +02:00
ViktorLjung a674295a83 Collisionfilters 2014-05-22 22:05:06 +02:00
ViktorLjung 6137adf604 Rockets deleted properly 2014-05-21 18:30:16 +02:00
Tleety dbad1ee7f5 Work done on light and shadows. 2014-05-21 16:51:05 +02:00
Jace 6d3aa5d394 Red rocket 2014-05-20 04:34:44 +02:00
ViktorLjung 7e5cf8efaa Fuckhack 2014-05-20 03:41:10 +02:00
ViktorLjung fe400e9af8 Merge remote-tracking branch 'origin/particles'
Conflicts:
	src/GameWorld.cpp
	src/Systems/ParticleSystem.cpp
2014-05-20 03:40:44 +02:00
Tleety e414087816 Some work done on lights and normals and other buggs/fixes 2014-05-20 03:33:42 +02:00
Stiffly 65acae410d Added Explosion function to particles 2014-05-20 00:38:30 +02:00
Tleety 82d5953c97 Specular maps working. 2014-05-19 21:36:28 +02:00
Stiffly 1a52b1d04c finlir 2014-05-18 20:32:10 +02:00
74 changed files with 3160 additions and 703 deletions
+1 -1
Submodule assets updated: 6cc38589ed...bc811a1b39
+20 -33
View File
@@ -1,25 +1,21 @@
#include "PrecompiledHeader.h"
#include "Camera.h"
Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip)
Camera::Camera(float yFOV, float nearClip, float farClip)
{
m_FOV = yFOV;
m_AspectRatio = aspectRatio;
m_NearClip = nearClip;
m_FarClip = farClip;
m_Position = glm::vec3(0.0);
/*m_Pitch = 0.f;
m_Yaw = 0.f;*/
UpdateProjectionMatrix();
UpdateViewMatrix();
}
//glm::vec3 Camera::Forward()
//{
// return glm::rotate(glm::vec3(0.f, 0.f, -1.f), -m_Yaw, glm::vec3(0.f, 1.f, 0.f));
//}
glm::vec3 Camera::Forward()
{
return m_Orientation * glm::vec3(0, 0, -1);
}
//
//glm::vec3 Camera::Right()
//{
@@ -34,20 +30,14 @@ Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip)
// return orientation;
//}
void Camera::AspectRatio(float val)
{
m_AspectRatio = val;
UpdateProjectionMatrix();
}
void Camera::Position(glm::vec3 val)
void Camera::SetPosition(glm::vec3 val)
{
m_Position = val;
UpdateViewMatrix();
}
void Camera::Orientation(glm::quat val)
void Camera::SetOrientation(glm::quat val)
{
m_Orientation = val;
UpdateViewMatrix();
@@ -65,35 +55,32 @@ void Camera::Orientation(glm::quat val)
// UpdateViewMatrix();
//}
void Camera::UpdateProjectionMatrix()
{
m_ProjectionMatrix = glm::perspective(
m_FOV,
m_AspectRatio,
m_NearClip,
m_FarClip
);
}
void Camera::UpdateViewMatrix()
{
m_ViewMatrix = glm::toMat4(glm::inverse(m_Orientation)) * glm::translate(-m_Position);
}
void Camera::FOV(float val)
void Camera::SetFOV(float val)
{
m_FOV = val;
UpdateProjectionMatrix();
}
void Camera::NearClip(float val)
void Camera::SetNearClip(float val)
{
m_NearClip = val;
UpdateProjectionMatrix();
}
void Camera::FarClip(float val)
void Camera::SetFarClip(float val)
{
m_FarClip = val;
UpdateProjectionMatrix();
}
glm::mat4 Camera::ProjectionMatrix(float aspectRatio)
{
return glm::perspective(
m_FOV,
aspectRatio,
m_NearClip,
m_FarClip
);
}
+7 -19
View File
@@ -1,60 +1,48 @@
#ifndef Camera_h__
#define Camera_h__
//#include "PrecompiledHeader.h"
class Camera
{
public:
Camera(float yFOV, float aspectRatio, float nearClip, float farClip);
Camera(float yFOV, float nearClip, float farClip);
glm::vec3 Forward();
glm::vec3 Right();
float AspectRatio() const { return m_AspectRatio; }
void AspectRatio(float val);
glm::vec3 Position() const { return m_Position; }
void Position(glm::vec3 val);
void SetPosition(glm::vec3 val);
glm::quat Orientation() const { return m_Orientation; }
void Orientation(glm::quat val);
void SetOrientation(glm::quat val);
/*float Pitch() const { return m_Pitch; }
void Pitch(float val);
float Yaw() const { return m_Yaw; }
void Yaw(float val);*/
glm::mat4 ProjectionMatrix() const { return m_ProjectionMatrix; }
void ProjectionMatrix(glm::mat4 val) { m_ProjectionMatrix = val; }
glm::mat4 ProjectionMatrix(float aspectRatio);
glm::mat4 ViewMatrix() const { return m_ViewMatrix; }
void ViewMatrix(glm::mat4 val) { m_ViewMatrix = val; }
float FOV() const { return m_FOV; }
void FOV(float val);
void SetFOV(float val);
float NearClip() const { return m_NearClip; }
void NearClip(float val);
void SetNearClip(float val);
float FarClip() const { return m_FarClip; }
void FarClip(float val);
void SetFarClip(float val);
private:
void UpdateProjectionMatrix();
void UpdateViewMatrix();
float m_FOV;
float m_AspectRatio;
float m_NearClip;
float m_FarClip;
glm::vec3 m_Position;
glm::quat m_Orientation;
//float m_Pitch;
//float m_Yaw;
glm::mat4 m_ProjectionMatrix;
glm::mat4 m_ViewMatrix;
};
+17
View File
@@ -0,0 +1,17 @@
#ifndef Components_Flag_h__
#define Components_Flag_h__
#include "Component.h"
namespace Components
{
struct Flag : Component
{
virtual Flag* Clone() const override { return new Flag(*this); }
};
}
#endif // Components_TankShell_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Components_FrameTimer_h__
#define Components_FrameTimer_h__
#include "Component.h"
namespace Components
{
struct FrameTimer : public Component
{
int Frames;
virtual FrameTimer* Clone() const override { return new FrameTimer(*this); }
};
}
#endif // Components_FrameTimer_h__
+4 -3
View File
@@ -19,7 +19,7 @@ struct ParticleEmitter : Component
, SpawnCount(0)
, SpreadAngle(0)
, LifeTime(0)
, TimeSinceLastSpawn(0) { }
, TimeSinceLastSpawn(100) { } // TEMP fulhack så att partiklarna spawnar direkt
EntityID ParticleTemplate;
float SpawnFrequency;
@@ -34,10 +34,11 @@ struct ParticleEmitter : Component
std::vector<float> AngularVelocitySpectrum;
std::vector<glm::vec3> OrientationSpectrum; //Keep?
virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); }
private:
double TimeSinceLastSpawn;
virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); }
};
}
+23 -1
View File
@@ -9,10 +9,32 @@ namespace Components
struct Physics : Component
{
Physics()
: Mass(0.f), Static(false){}
: Mass(1.f), Static(false), Phantom(false), CalculateCenterOfMass(true), CenterOfMass(glm::vec3(0)), InitialLinearVelocity(glm::vec3(0)), InitialAngularVelocity(glm::vec3(0)),
LinearDamping(0.f), AngularDamping(0.05f), GravityFactor(1.f), Friction(0.5f), Restitution(0.4f), MaxLinearVelocity(200.f), MaxAngularVelocity(200.f),
CollisionLayer(0), CollisionSystemGroup(0), CollisionSubSystemId(0), CollisionSubSystemDontCollideWith(0), CollisionEvent(false){}
float Mass;
bool Static;
bool Phantom;
bool CalculateCenterOfMass;
glm::vec3 CenterOfMass;
glm::vec3 InitialLinearVelocity;
glm::vec3 InitialAngularVelocity;
float LinearDamping;
float AngularDamping;
float GravityFactor;
float Friction;
float Restitution;
float MaxLinearVelocity;
float MaxAngularVelocity;
int CollisionLayer;
int CollisionSystemGroup;
int CollisionSubSystemId;
int CollisionSubSystemDontCollideWith;
bool CollisionEvent;
virtual Physics* Clone() const override { return new Physics(*this); }
};
+2
View File
@@ -16,9 +16,11 @@ struct PointLight : Component
, ConstantAttenuation(1.0f)
, LinearAttenuation(0.f)
, QuadraticAttenuation(3.f)
, Radius(5.f)
{ }
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation;
float Radius;
Color color;
glm::vec3 Specular;
+23
View File
@@ -0,0 +1,23 @@
#ifndef Components_TankShell_h__
#define Components_TankShell_h__
#include "Component.h"
namespace Components
{
struct TankShell : Component
{
TankShell()
: Damage(1.0f){ }
float Damage;
float ExplosionRadius;
float ExplosionStrength;
virtual TankShell* Clone() const override { return new TankShell(*this); }
};
}
#endif // Components_TankShell_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Components_Timer_h__
#define Components_Timer_h__
#include "Component.h"
namespace Components
{
struct Timer : public Component
{
double Time;
virtual Timer* Clone() const override { return new Timer(*this); }
};
}
#endif // Components_Timer_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Trigger_h__
#define Trigger_h__
#include "Component.h"
namespace Components
{
struct Trigger : Component
{
bool TriggerOnce;
virtual Trigger* Clone() const override { return new Trigger(*this); }
};
}
#endif // Trigger_h__
+22
View File
@@ -0,0 +1,22 @@
#ifndef TriggerExplosion_h__
#define TriggerExplosion_h__
#include "Component.h"
namespace Components
{
struct TriggerExplosion : Component
{
TriggerExplosion()
: MaxVelocity(1.f), Radius(1.f){ }
// Velocity = (1 - (distance / radius)^2) * Strength;
float MaxVelocity;
float Radius; //HACK: Radius should only be in the SphereShapeComponent
virtual TriggerExplosion* Clone() const override { return new TriggerExplosion(*this); }
};
}
#endif // TriggerExplosion_h__
+34 -10
View File
@@ -1,11 +1,16 @@
#include <string>
#include <sstream>
#include "ResourceManager.h"
#include "OBJ.h"
#include "Model.h"
#include "Texture.h"
#include "EventBroker.h"
#include "RenderQueue.h"
#include "Renderer.h"
#include "InputManager.h"
#include "GUI/Frame.h"
#include "GameWorld.h"
#include "GUI/GameFrame.h"
class Engine
{
@@ -14,15 +19,24 @@ public:
{
m_EventBroker = std::make_shared<EventBroker>();
m_Renderer = std::make_shared<Renderer>();
m_ResourceManager = std::make_shared<ResourceManager>();
m_ResourceManager->RegisterType("OBJ", [](std::string resourceName) { return new OBJ(resourceName); });
auto rm = m_ResourceManager;
m_ResourceManager->RegisterType("Model", [rm](std::string resourceName) { return new Model(rm, *rm->Load<OBJ>("OBJ", resourceName)); });
m_ResourceManager->RegisterType("Texture", [](std::string resourceName) { return new Texture(resourceName); });
m_Renderer = std::make_shared<Renderer>(m_ResourceManager);
m_Renderer->Initialize();
m_InputManager = std::make_shared<InputManager>(m_Renderer->GetWindow(), m_EventBroker);
//m_UIParent = std::make_shared<GUI::Frame>(m_EventBroker);
m_FrameStack = new GUI::Frame(m_EventBroker, m_ResourceManager);
m_FrameStack->Width = 1280;
m_FrameStack->Height = 720;
new GUI::GameFrame(m_FrameStack, "GameFrame");
m_World = std::make_shared<GameWorld>(m_EventBroker, m_Renderer);
m_World->Initialize();
//m_World = std::make_shared<GameWorld>(m_EventBroker, m_ResourceManager);
//m_World->Initialize();
m_LastTime = glfwGetTime();
}
@@ -32,24 +46,34 @@ public:
void Tick()
{
double currentTime = glfwGetTime();
double dt = currentTime - m_LastTime;
double dt = currentTime - m_LastTime;
m_LastTime = currentTime;
// Update input
m_InputManager->Update(dt);
m_World->Update(dt);
m_Renderer->Draw(dt);
// Update frame stack
m_EventBroker->Process<GUI::Frame>();
m_FrameStack->UpdateLayered(dt);
// Render scene
m_FrameStack->DrawLayered(m_Renderer);
m_Renderer->Swap();
// Swap event queues
m_EventBroker->Clear();
glfwPollEvents();
}
private:
std::shared_ptr<ResourceManager> m_ResourceManager;
std::shared_ptr<EventBroker> m_EventBroker;
std::shared_ptr<Renderer> m_Renderer;
std::shared_ptr<InputManager> m_InputManager;
//std::shared_ptr<GUI::Frame> m_UIParent;
GUI::Frame* m_FrameStack;
// TODO: This should ultimately live in GameFrame
std::shared_ptr<GameWorld> m_World;
//std::shared_ptr<GameWorld> m_World;
double m_LastTime;
};
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_Collision_h__
#define Events_Collision_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct Collision : Event
{
EntityID Entity1;
EntityID Entity2;
};
}
#endif // Events_Collision_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_Damage_h__
#define Events_Damage_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct Damage : Event
{
EntityID Entity;
float damage;
};
}
#endif // Events_Damage_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_DisableCollisions_h__
#define Events_DisableCollisions_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct DisableCollisions : Event
{
int Layer1;
int Layer2;
};
}
#endif // Events_DisableCollisions_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_EnableCollisions_h__
#define Events_EnableCollisions_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct EnableCollisions : Event
{
int Layer1;
int Layer2;
};
}
#endif // Events_EnableCollisions_h__
+17
View File
@@ -0,0 +1,17 @@
#ifndef Events_EnterTrigger_h__
#define Events_EnterTrigger_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct EnterTrigger : Event
{
EntityID Entity1;
EntityID Entity2;
};
}
#endif // Events_EnterTrigger_h__
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_SetViewportCamera_h__
#define Events_SetViewportCamera_h__
#include "EventBroker.h"
#include "Entity.h"
namespace Events
{
struct SetViewportCamera : Event
{
std::string ViewportFrame;
EntityID CameraEntity;
};
}
#endif // Events_SetViewportCamera_h__
+103 -18
View File
@@ -2,12 +2,14 @@
#define GUI_Frame_h__
#include <memory>
#include <map>
#include "Util/Rectangle.h"
#include "EventBroker.h"
// HACK: Decouple renderer plz
#include "ResourceManager.h"
#include "Renderer.h"
#include "RenderQueue.h"
#include "Texture.h"
namespace GUI
{
@@ -24,50 +26,133 @@ public:
};
// Set up a base frame with an event broker
Frame(std::shared_ptr<::EventBroker> eventBroker)
Frame(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: EventBroker(eventBroker)
, ResourceManager(resourceManager)
, Rectangle()
{ Initialize(); }
// Create a frame as a child
Frame(std::shared_ptr<Frame> parent)
: Rectangle(static_cast<Rectangle>(*parent)) // Clone parent rectangle using copy constructor
{ SetParent(parent); Initialize(); }
, m_Name("UIParent")
, m_Layer(0)
{ }
// Create a frame as a child
Frame(Frame* parent, std::string name)
: Rectangle(static_cast<Rectangle>(*parent)) // Clone parent rectangle using copy constructor
, m_Name(name)
, m_Layer(0)
{ SetParent(std::shared_ptr<Frame>(parent)); }
::RenderQueue RenderQueue;
virtual void Initialize() { }
std::shared_ptr<Frame> Parent() const { return m_Parent; }
void SetParent(std::shared_ptr<Frame> parent)
{
if (parent == nullptr)
{
LOG_ERROR("Failed to create frame \"%s\": Invalid parent", m_Name.c_str());
return;
}
m_Layer = parent->Layer() + 1;
parent->AddChild(std::shared_ptr<Frame>(this));
m_Parent = parent;
EventBroker = parent->EventBroker;
ResourceManager = parent->ResourceManager;
}
void AddChild(std::shared_ptr<Frame> child)
{
m_Children.push_back(child);
if (m_Parent != nullptr)
m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child));
if (m_Parent)
{
m_Parent->AddChild(child);
}
}
typedef std::list<std::shared_ptr<Frame>>::const_iterator FrameChildrenIterator;
FrameChildrenIterator begin()
typedef std::map<std::string, std::shared_ptr<Frame>>::const_iterator FrameChildrenIterator;
std::string Name() const { return m_Name; }
void SetName(std::string val) { m_Name = val; }
int Layer() const { return m_Layer; }
int Left() const override
{
return m_Children.begin();
if (m_Parent)
return m_Parent->Left() + X;
else
return X;
}
FrameChildrenIterator end()
int Right() const override
{
return m_Children.end();
return Left() + Width;
}
int Top() const override
{
if (m_Parent)
return m_Parent->Top() + Y;
else
return Y;
}
int Bottom() const override
{
return Top() + Height;
}
Rectangle AbsoluteRectangle()
{
return Rectangle(Left(), Top(), Width, Height);
}
void UpdateLayered(double dt)
{
// Update ourselves
this->Update(dt);
// Update children
for (auto &pairLayer : m_Children)
{
auto children = pairLayer.second;
for (auto &pairChild : children)
{
auto child = pairChild.second;
child->Update(dt);
}
}
}
virtual void Update(double dt) { }
virtual void Draw(Renderer* renderer) { }
void DrawLayered(std::shared_ptr<Renderer> renderer)
{
// Draw ourselves
renderer->SetViewport(AbsoluteRectangle());
this->Draw(renderer);
// Draw children
for (auto &pairLayer : m_Children)
{
auto children = pairLayer.second;
for (auto &pairChild : children)
{
auto child = pairChild.second;
Rectangle rect = child->AbsoluteRectangle();
renderer->SetViewport(rect);
child->Draw(renderer);
}
}
}
virtual void Draw(std::shared_ptr<Renderer> renderer) { }
protected:
std::shared_ptr<::EventBroker> EventBroker;
std::shared_ptr<::ResourceManager> ResourceManager;
std::string m_Name;
int m_Layer;
std::shared_ptr<Frame> m_Parent;
std::list<std::shared_ptr<Frame>> m_Children;
typedef std::multimap<std::string, std::shared_ptr<Frame>> Children_t; // name -> frame
std::map<int, Children_t> m_Children; // layer -> Children_t
};
}
+62
View File
@@ -0,0 +1,62 @@
#ifndef GUI_GameFrame_h__
#define GUI_GameFrame_h__
#include "GUI/Frame.h"
#include "GUI/WorldFrame.h"
#include "GUI/Viewport.h"
#include "GUI/TextureFrame.h"
#include "Events/Damage.h"
#include "GameWorld.h"
namespace GUI
{
class GameFrame : public Frame
{
public:
GameFrame(Frame* parent, std::string name)
: Frame(parent, name)
{
EVENT_SUBSCRIBE_MEMBER(m_EDamage, &GameFrame::OnDamage);
m_World = std::make_shared<GameWorld>(EventBroker, ResourceManager);
auto worldFrame = new WorldFrame(this, "GameWorldFrame", m_World);
{
vp1 = new Viewport(worldFrame, "Viewport1", m_World);
vp1->X = 0;
vp1->Width = 640;
vp2 = new Viewport(worldFrame, "Viewport2", m_World);
vp2->X = vp1->Right();
vp2->Width = 640;
tex = new TextureFrame(vp1, "TextureFrameThingy");
tex->SetTexture("Textures/GUI/hurt.png");
}
m_World->Initialize();
}
void Update(double dt)
{
}
bool OnDamage(const Events::Damage &event)
{
//tex->SetTexture("Textures/GUI/hurt.png");
return false;
}
private:
EventRelay<Frame, Events::Damage> m_EDamage;
std::shared_ptr<GameWorld> m_World;
Viewport* vp1;
Viewport* vp2;
TextureFrame* tex;
};
}
#endif // GUI_GameFrame_h__
+43
View File
@@ -0,0 +1,43 @@
#ifndef GUI_TextureFrame_h__
#define GUI_TextureFrame_h__
#include "GUI/Frame.h"
#include "Texture.h"
namespace GUI
{
class TextureFrame : public Frame
{
public:
TextureFrame(Frame* parent, std::string name)
: Frame(parent, name) { }
void Draw(std::shared_ptr<Renderer> renderer) override
{
if (m_Texture == nullptr)
return;
RenderQueue.Clear();
SpriteJob job;
job.TextureID = m_Texture->ResourceID;
job.Texture = *m_Texture;
RenderQueue.Add(job);
renderer->SetCamera(nullptr);
renderer->DrawFrame(RenderQueue);
}
std::shared_ptr<::Texture> Texture() const { return m_Texture; }
void SetTexture(std::string resourceName)
{
m_Texture = std::shared_ptr<::Texture>(ResourceManager->Load<::Texture>("Texture", resourceName));
}
protected:
std::shared_ptr<::Texture> m_Texture;
};
}
#endif // GUI_TextureFrame_h__
+62 -3
View File
@@ -4,6 +4,12 @@
#include <memory>
#include "GUI/Frame.h"
#include "World.h"
#include "Systems/TransformSystem.h"
#include "Components/Transform.h"
#include "Components/Camera.h"
#include "RenderQueue.h"
#include "Camera.h"
namespace GUI
{
@@ -11,9 +17,62 @@ namespace GUI
class Viewport : public Frame
{
public:
// Create a frame as a child
Viewport(std::shared_ptr<Frame> parent)
: Frame(parent) { }
Viewport(Frame* parent, std::string name, std::shared_ptr<World> world)
: Frame(parent, name)
, m_World(world)
{ }
EntityID CameraEntity() const { return m_CameraEntity; }
void SetCameraEntity(EntityID cameraEntity)
{
m_CameraEntity = cameraEntity;
auto transformComponent = m_World->GetComponent<Components::Transform>(cameraEntity);
if (!transformComponent)
return;
auto cameraComponent = m_World->GetComponent<Components::Camera>(cameraEntity);
if (!cameraComponent)
return;
m_Camera = std::make_shared<Camera>(cameraComponent->FOV, cameraComponent->NearClip, cameraComponent->FarClip);
}
void Update(double dt) override
{
if (!m_TransformSystem)
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
auto transformComponent = m_World->GetComponent<Components::Transform>(m_CameraEntity);
if (!transformComponent)
return;
auto cameraComponent = m_World->GetComponent<Components::Camera>(m_CameraEntity);
if (!cameraComponent)
return;
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(m_CameraEntity);
m_Camera->SetFOV(cameraComponent->FOV);
m_Camera->SetNearClip(cameraComponent->NearClip);
m_Camera->SetFarClip(cameraComponent->FarClip);
m_Camera->SetPosition(absoluteTransform.Position);
m_Camera->SetOrientation(absoluteTransform.Orientation);
}
void Draw(std::shared_ptr<Renderer> renderer) override
{
if (!m_Camera)
return;
renderer->SetCamera(m_Camera);
renderer->DrawWorld(m_Parent->RenderQueue);
}
private:
std::shared_ptr<World> m_World;
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
std::shared_ptr<Camera> m_Camera;
EntityID m_CameraEntity;
};
}
+150
View File
@@ -0,0 +1,150 @@
#ifndef GUI_WorldFrame_h__
#define GUI_WorldFrame_h__
#include "GUI/Frame.h"
#include "GUI/Viewport.h"
#include "RenderQueue.h"
#include "World.h"
#include "Systems/TransformSystem.h"
#include "Events/SetViewportCamera.h"
#include "Components/Transform.h"
#include "Components/Model.h"
#include "Components/Sprite.h"
#include "Components/PointLight.h"
namespace GUI
{
class WorldFrame : public Frame
{
public:
WorldFrame(Frame* parent, std::string name, std::shared_ptr<World> world)
: Frame(parent, name)
, m_World(world)
{
EVENT_SUBSCRIBE_MEMBER(m_ESetViewportCamera, &WorldFrame::OnSetViewportCamera);
}
void Update(double dt) override
{
if (!m_TransformSystem)
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
m_World->Update(dt);
}
void Draw(std::shared_ptr<Renderer> renderer) override
{
RenderQueue.Clear();
renderer->ClearPointLights();
for (auto &pair : *m_World->GetEntities())
{
EntityID entity = pair.first;
auto transform = m_World->GetComponent<Components::Transform>(entity);
if (!transform)
continue;
auto modelComponent = m_World->GetComponent<Components::Model>(entity);
if (modelComponent)
{
auto modelAsset = ResourceManager->Load<Model>("Model", modelComponent->ModelFile);
if (modelAsset)
{
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
glm::mat4 modelMatrix = glm::translate(glm::mat4(), absoluteTransform.Position)
* glm::toMat4(absoluteTransform.Orientation)
* glm::scale(absoluteTransform.Scale);
EnqueueModel(modelAsset, modelMatrix);
}
}
auto spriteComponent = m_World->GetComponent<Components::Sprite>(entity);
if (spriteComponent)
{
auto textureAsset = ResourceManager->Load<Texture>("Texture", spriteComponent->SpriteFile);
if (textureAsset)
{
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(absoluteTransform.Orientation).z, glm::vec3(0, 0, -1));
glm::mat4 modelMatrix = glm::translate(absoluteTransform.Position)
* glm::toMat4(orientation2D)
* glm::scale(absoluteTransform.Scale);
EnqueueSprite(textureAsset, modelMatrix);
}
}
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity);
if (pointLightComponent)
{
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
renderer->AddPointLightToDraw(
position,
pointLightComponent->Specular,
pointLightComponent->Diffuse,
pointLightComponent->specularExponent,
pointLightComponent->ConstantAttenuation,
pointLightComponent->LinearAttenuation,
pointLightComponent->QuadraticAttenuation,
pointLightComponent->Radius
);
}
}
}
protected:
std::shared_ptr<World> m_World;
private:
EventRelay<Frame, Events::SetViewportCamera> m_ESetViewportCamera;
bool OnSetViewportCamera(const Events::SetViewportCamera &event)
{
// Search next layer for viewports and update cameras
auto itpair = m_Children[m_Layer + 1].equal_range(event.ViewportFrame);
for (auto it = itpair.first; it != itpair.second; ++it)
{
auto viewportFrame = std::dynamic_pointer_cast<GUI::Viewport>(it->second);
if (!viewportFrame)
continue;
viewportFrame->SetCameraEntity(event.CameraEntity);
}
return true;
}
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
void EnqueueModel(Model* model, glm::mat4 modelMatrix)
{
for (auto texGroup : model->TextureGroups)
{
ModelJob job;
job.TextureID = texGroup.Texture->ResourceID;
job.DiffuseTexture = *texGroup.Texture;
job.NormalTexture = (texGroup.NormalMap) ? *texGroup.NormalMap : 0;
job.SpecularTexture = (texGroup.SpecularMap) ? *texGroup.SpecularMap : 0;
job.VAO = model->VAO;
job.StartIndex = texGroup.StartIndex;
job.EndIndex = texGroup.EndIndex;
job.ModelMatrix = modelMatrix;
RenderQueue.Add(job);
}
}
void EnqueueSprite(Texture* texture, glm::mat4 modelMatrix)
{
SpriteJob job;
job.TextureID = texture->ResourceID;
job.Texture = *texture;
job.ModelMatrix = modelMatrix;
RenderQueue.Add(job);
}
};
}
#endif // GUI_WorldFrame_h__
+145 -62
View File
@@ -5,8 +5,8 @@ void GameWorld::Initialize()
{
World::Initialize();
m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/Plane.obj");
m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/ArrowCube.obj");
ResourceManager->Preload("Model", "Models/Placeholders/PhysicsTest/Plane.obj");
ResourceManager->Preload("Model", "Models/Placeholders/PhysicsTest/ArrowCube.obj");
BindKey(GLFW_KEY_W, "vertical", 1.f);
BindKey(GLFW_KEY_S, "vertical", -1.f);
@@ -55,22 +55,7 @@ void GameWorld::Initialize()
cameraComp->FarClip = 2000.f;
auto freeSteering = AddComponent<Components::FreeSteering>(camera);
}
CommitEntity(camera);
auto viewport1 = CreateEntity();
{
auto viewport = AddComponent<Components::Viewport>(viewport1);
viewport->Right = 0.5f;
viewport->Camera = camera;
}
CommitEntity(viewport1);
auto viewport2 = CreateEntity();
{
auto viewport = AddComponent<Components::Viewport>(viewport2);
viewport->Left = 0.5f;
}
CommitEntity(viewport2);
auto player1 = CreateEntity();
{
@@ -85,6 +70,33 @@ void GameWorld::Initialize()
}
//{
// auto ground = CreateEntity();
// auto transform = AddComponent<Components::Transform>(ground);
// transform->Position = glm::vec3(0, -50, 0);
// //transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f);
// transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f));
// auto model = AddComponent<Components::Model>(ground);
// model->ModelFile = "Models/TestScene3/testScene.obj";
// //model->ModelFile = "Models/Placeholders/Terrain/Terrain2.obj";
//
// auto physics = AddComponent<Components::Physics>(ground);
// physics->Mass = 10;
// physics->Static = true;
// auto groundshape = CreateEntity(ground);
// auto transformshape = AddComponent<Components::Transform>(groundshape);
// auto meshShape = AddComponent<Components::MeshShape>(groundshape);
// //meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain2.obj";
// meshShape->ResourceName = "Models/TestScene3/testScene.obj";
//
// CommitEntity(groundshape);
// CommitEntity(ground);
//}
{
auto ground = CreateEntity();
auto transform = AddComponent<Components::Transform>(ground);
@@ -98,7 +110,7 @@ void GameWorld::Initialize()
auto physics = AddComponent<Components::Physics>(ground);
physics->Mass = 10;
physics->Static = true;
physics->CollisionLayer = 1;
auto groundshape = CreateEntity(ground);
auto transformshape = AddComponent<Components::Transform>(groundshape);
@@ -111,6 +123,52 @@ void GameWorld::Initialize()
CommitEntity(ground);
}
{
auto flag = CreateEntity();
auto transform = AddComponent<Components::Transform>(flag);
transform->Position = glm::vec3(0, -50, 100);
auto model = AddComponent<Components::Model>(flag);
model->ModelFile = "Models/Flag/FishingRod/FishingRod.obj";
{
auto fish = CreateEntity(flag);
auto transform = AddComponent<Components::Transform>(fish);
transform->Position = glm::vec3(-1.3f, 1.0, 0);
auto model = AddComponent<Components::Model>(fish);
model->ModelFile = "Models/Flag/LeFish/Salmon.obj";
CommitEntity(fish);
}
auto trigger = AddComponent<Components::Trigger>(flag);
{
auto shape = CreateEntity(flag);
auto transform = AddComponent<Components::Transform>(shape);
transform->Position = glm::vec3(-0.9f, 0.9f, 0);
auto box = AddComponent<Components::BoxShape>(shape);
box->Width = 1.1f;
box->Depth = 0.7f;
box->Height = 3.9f;
CommitEntity(shape);
}
auto flagComponent = AddComponent<Components::Flag>(flag);
CommitEntity(flag);
}
//for (int i = 0; i < 500; i++)
//{
// auto Light = CreateEntity();
// auto transform = AddComponent<Components::Transform>(Light);
// transform->Position = glm::vec3((5 + (i*2.f))*cos(i*2.f), 3.f, (5 + (i*2.f))*sin(i*2.f));
// auto light = AddComponent<Components::PointLight>(Light);
// light->Specular = glm::vec3(0.5f, 0.5f, 0.5f);
// light->Diffuse = glm::vec3(0.5f, 0.5f, 0.5f);
// light->Radius = 15.f;
// light->specularExponent = 100.f;
// CommitEntity(Light);
// //auto model = AddComponent<Components::Model>(Light, "Model");
// //model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj";
//}
/*{
@@ -304,15 +362,19 @@ void GameWorld::Initialize()
auto shot = CreateEntity(barrel);
auto transform = AddComponent<Components::Transform>(shot);
transform->Position = glm::vec3(0.35f, 0.f, -2.f);
transform->Orientation = glm::angleAxis(-glm::pi<float>()/2.f, glm::vec3(1, 0, 0));
transform->Orientation = glm::angleAxis(-glm::pi<float>() / 2.f, glm::vec3(1, 0, 0));
transform->Scale = glm::vec3(3.f);
AddComponent<Components::Template>(shot);
auto physics = AddComponent<Components::Physics>(shot);
physics->Mass = 25.f;
physics->Static = false;
physics->CollisionEvent = true;
auto modelComponent = AddComponent<Components::Model>(shot);
modelComponent->ModelFile = "Models/Placeholders/rocket/Rocket.obj";
auto tankShellComponent = AddComponent<Components::TankShell>(shot);
tankShellComponent->Damage = 20.f;
tankShellComponent->ExplosionRadius = 30.f;
tankShellComponent->ExplosionStrength = 300000.f;
{
auto shape = CreateEntity(shot);
auto transform = AddComponent<Components::Transform>(shape);
@@ -335,7 +397,7 @@ void GameWorld::Initialize()
auto cameraTower = CreateEntity(tower);
{
auto transform = AddComponent<Components::Transform>(cameraTower);
transform->Position.z = 11.f;
transform->Position.z = 16.f;
transform->Position.y = 4.f;
//transform->Orientation = glm::quat(glm::vec3(glm::pi<float>() / 8.f, 0.f, 0.f));
auto cameraComp = AddComponent<Components::Camera>(cameraTower);
@@ -343,20 +405,25 @@ void GameWorld::Initialize()
//auto freeSteering = AddComponent<Components::FreeSteering>(cameraTower);
}
CommitEntity(cameraTower);
GetComponent<Components::Viewport>(viewport1)->Camera = cameraTower;
{
Events::SetViewportCamera e;
e.CameraEntity = cameraTower;
e.ViewportFrame = "Viewport1";
EventBroker->Publish(e);
}
}
{
auto lightentity = CreateEntity(tank);
auto transform = AddComponent<Components::Transform>(lightentity);
transform->Position = glm::vec3(0, 0, 0);
auto light = AddComponent<Components::PointLight>(lightentity);
//light->Diffuse = glm::vec3(128.f/255.f, 172.f/255.f, 242.f/255.f);
//light->Specular = glm::vec3(1.f);
/*light->ConstantAttenuation = 0.3f;
light->LinearAttenuation = 0.003f;
light->QuadraticAttenuation = 0.002f;*/
}
//{
// auto lightentity = CreateEntity(tank);
// auto transform = AddComponent<Components::Transform>(lightentity);
// transform->Position = glm::vec3(0, 0, 0);
// auto light = AddComponent<Components::PointLight>(lightentity);
// //light->Diffuse = glm::vec3(128.f/255.f, 172.f/255.f, 242.f/255.f);
// //light->Specular = glm::vec3(1.f);
// /*light->ConstantAttenuation = 0.3f;
// light->LinearAttenuation = 0.003f;
// light->QuadraticAttenuation = 0.002f;*/
//}
// auto wheelpair = CreateEntity(tank);
// SetProperty(wheelpair, "Name", "WheelPair");
@@ -722,15 +789,19 @@ void GameWorld::Initialize()
auto shot = CreateEntity(barrel);
auto transform = AddComponent<Components::Transform>(shot);
transform->Position = glm::vec3(0.35f, 0.f, -2.f);
transform->Orientation = glm::angleAxis(-glm::pi<float>()/2.f, glm::vec3(1, 0, 0));
transform->Orientation = glm::angleAxis(-glm::pi<float>() / 2.f, glm::vec3(1, 0, 0));
transform->Scale = glm::vec3(3.f);
AddComponent<Components::Template>(shot);
auto physics = AddComponent<Components::Physics>(shot);
physics->Mass = 25.f;
physics->Static = false;
physics->CollisionEvent = true;
auto modelComponent = AddComponent<Components::Model>(shot);
modelComponent->ModelFile = "Models/Placeholders/rocket/Rocket.obj";
auto tankShellComponent = AddComponent<Components::TankShell>(shot);
tankShellComponent->Damage = 20.f;
tankShellComponent->ExplosionRadius = 30.f;
tankShellComponent->ExplosionStrength = 300000.f;
{
auto shape = CreateEntity(shot);
auto transform = AddComponent<Components::Transform>(shape);
@@ -761,20 +832,25 @@ void GameWorld::Initialize()
//auto freeSteering = AddComponent<Components::FreeSteering>(cameraTower);
}
CommitEntity(cameraTower);
GetComponent<Components::Viewport>(viewport2)->Camera = cameraTower;
{
Events::SetViewportCamera e;
e.CameraEntity = cameraTower;
e.ViewportFrame = "Viewport2";
EventBroker->Publish(e);
}
}
{
auto lightentity = CreateEntity(tank);
auto transform = AddComponent<Components::Transform>(lightentity);
transform->Position = glm::vec3(0, 0, 0);
auto light = AddComponent<Components::PointLight>(lightentity);
//light->Diffuse = glm::vec3(128.f/255.f, 172.f/255.f, 242.f/255.f);
//light->Specular = glm::vec3(1.f);
/*light->ConstantAttenuation = 0.3f;
light->LinearAttenuation = 0.003f;
light->QuadraticAttenuation = 0.002f;*/
}
//{
// auto lightentity = CreateEntity(tank);
// auto transform = AddComponent<Components::Transform>(lightentity);
// transform->Position = glm::vec3(0, 0, 0);
// auto light = AddComponent<Components::PointLight>(lightentity);
// //light->Diffuse = glm::vec3(128.f/255.f, 172.f/255.f, 242.f/255.f);
// //light->Specular = glm::vec3(1.f);
// /*light->ConstantAttenuation = 0.3f;
// light->LinearAttenuation = 0.003f;
// light->QuadraticAttenuation = 0.002f;*/
//}
// auto wheelpair = CreateEntity(tank);
// SetProperty(wheelpair, "Name", "WheelPair");
@@ -1103,7 +1179,7 @@ void GameWorld::Initialize()
CommitEntity(entity);
}*/
for(int i = 0; i < 1; i++)
/*for(int i = 0; i < 1; i++)
{
for (int y = 0; y < 15; y++)
{
@@ -1133,7 +1209,7 @@ void GameWorld::Initialize()
CommitEntity(brick);
}
}
}
}*/
/*for (int x = 0; x < 5; x++)
for (int y = 0; y < 5; y++)
@@ -1179,26 +1255,32 @@ void GameWorld::RegisterComponents()
m_ComponentFactory.Register<Components::Transform>([]() { return new Components::Transform(); });
m_ComponentFactory.Register<Components::Template>([]() { return new Components::Template(); });
m_ComponentFactory.Register<Components::Player>([]() { return new Components::Player(); });
m_ComponentFactory.Register<Components::Flag>([]() { return new Components::Flag(); });
}
void GameWorld::RegisterSystems()
{
m_SystemFactory.Register<Systems::TransformSystem>([this]() { return new Systems::TransformSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::TimerSystem>([this]() { return new Systems::TimerSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::DamageSystem>([this]() { return new Systems::DamageSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::TransformSystem>([this]() { return new Systems::TransformSystem(this, EventBroker, ResourceManager); });
//m_SystemFactory.Register<Systems::LevelGenerationSystem>([this]() { return new Systems::LevelGenerationSystem(this); });
m_SystemFactory.Register<Systems::InputSystem>([this]() { return new Systems::InputSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::DebugSystem>([this]() { return new Systems::DebugSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::InputSystem>([this]() { return new Systems::InputSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::DebugSystem>([this]() { return new Systems::DebugSystem(this, EventBroker, ResourceManager); });
//m_SystemFactory.Register<Systems::CollisionSystem>([this]() { return new Systems::CollisionSystem(this); });
m_SystemFactory.Register<Systems::ParticleSystem>([this]() { return new Systems::ParticleSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::ParticleSystem>([this]() { return new Systems::ParticleSystem(this, EventBroker, ResourceManager); });
//m_SystemFactory.Register<Systems::PlayerSystem>([this]() { return new Systems::PlayerSystem(this); });
m_SystemFactory.Register<Systems::FreeSteeringSystem>([this]() { return new Systems::FreeSteeringSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::TankSteeringSystem>([this]() { return new Systems::TankSteeringSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::SoundSystem>([this]() { return new Systems::SoundSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::PhysicsSystem>([this]() { return new Systems::PhysicsSystem(this, m_EventBroker); });
m_SystemFactory.Register<Systems::RenderSystem>([this]() { return new Systems::RenderSystem(this, m_EventBroker, m_Renderer); });
m_SystemFactory.Register<Systems::FreeSteeringSystem>([this]() { return new Systems::FreeSteeringSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::TankSteeringSystem>([this]() { return new Systems::TankSteeringSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::SoundSystem>([this]() { return new Systems::SoundSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::PhysicsSystem>([this]() { return new Systems::PhysicsSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::TriggerSystem>([this]() { return new Systems::TriggerSystem(this, EventBroker, ResourceManager); });
m_SystemFactory.Register<Systems::RenderSystem>([this]() { return new Systems::RenderSystem(this, EventBroker, ResourceManager); });
}
void GameWorld::AddSystems()
{
AddSystem<Systems::TimerSystem>();
AddSystem<Systems::DamageSystem>();
AddSystem<Systems::TransformSystem>();
//AddSystem<Systems::LevelGenerationSystem>();
AddSystem<Systems::InputSystem>();
@@ -1210,6 +1292,7 @@ void GameWorld::AddSystems()
AddSystem<Systems::TankSteeringSystem>();
AddSystem<Systems::SoundSystem>();
AddSystem<Systems::PhysicsSystem>();
AddSystem<Systems::TriggerSystem>();
AddSystem<Systems::RenderSystem>();
}
@@ -1219,7 +1302,7 @@ void GameWorld::BindKey(int keyCode, std::string command, float value)
e.KeyCode = keyCode;
e.Command = command;
e.Value = value;
m_EventBroker->Publish(e);
EventBroker->Publish(e);
}
void GameWorld::BindMouseButton(int button, std::string command, float value)
@@ -1228,7 +1311,7 @@ void GameWorld::BindMouseButton(int button, std::string command, float value)
e.Button = button;
e.Command = command;
e.Value = value;
m_EventBroker->Publish(e);
EventBroker->Publish(e);
}
void GameWorld::BindGamepadAxis(Gamepad::Axis axis, std::string command, float value)
@@ -1237,7 +1320,7 @@ void GameWorld::BindGamepadAxis(Gamepad::Axis axis, std::string command, float v
e.Axis = axis;
e.Command = command;
e.Value = value;
m_EventBroker->Publish(e);
EventBroker->Publish(e);
}
void GameWorld::BindGamepadButton(Gamepad::Button button, std::string command, float value)
@@ -1246,5 +1329,5 @@ void GameWorld::BindGamepadButton(Gamepad::Button button, std::string command, f
e.Button = button;
e.Command = command;
e.Value = value;
m_EventBroker->Publish(e);
EventBroker->Publish(e);
}
+9 -4
View File
@@ -17,6 +17,9 @@
#include "Systems/RenderSystem.h"
#include "Systems/SoundSystem.h"
#include "Systems/PhysicsSystem.h"
#include "Systems/TriggerSystem.h"
#include "Systems/TimerSystem.h"
#include "Systems/DamageSystem.h"
#include "Components/Camera.h"
#include "Components/DirectionalLight.h"
@@ -41,12 +44,16 @@
#include "Components/TowerSteering.h"
#include "Components/BarrelSteering.h"
#include "Components/Player.h"
#include "Components/Health.h"
#include "Components/Trigger.h"
#include "Components/Flag.h"
class GameWorld : public World
{
public:
GameWorld(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<Renderer> renderer)
: World(eventBroker), m_Renderer(renderer) { }
GameWorld(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: World(eventBroker, resourceManager)
{ }
void Initialize();
@@ -57,8 +64,6 @@ public:
void Update(double dt);
private:
std::shared_ptr<Renderer> m_Renderer;
void BindKey(int keyCode, std::string command, float value);
void BindMouseButton(int button, std::string command, float value);
void BindGamepadAxis(Gamepad::Axis axis, std::string command, float value);
+34 -7
View File
@@ -1,7 +1,7 @@
#include "PrecompiledHeader.h"
#include "Model.h"
Model::Model(ResourceManager* rm, OBJ &obj)
Model::Model(std::shared_ptr<ResourceManager> rm, OBJ &obj)
{
OBJ::MaterialInfo* currentMaterial = nullptr;
TextureGroup* currentTexGroup = nullptr;
@@ -23,11 +23,23 @@ Model::Model(ResourceManager* rm, OBJ &obj)
// TODO: Load normal map
std::shared_ptr<Texture> normalMap = nullptr;
if (!currentMaterial->NormalMap.FileName.empty())
{
normalMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->NormalMap.FileName));
}
else
{
normalMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", "Textures/NeutralNormalMap.png"));
}
// Load specular map
std::shared_ptr<Texture> specularMap = nullptr;
if (!currentMaterial->SpecularMap.FileName.empty())
{
specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->SpecularMap.FileName));
}
else
{
specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", "Textures/NeutralSpecularMap.png"));
}
// TODO: Load material parameters
// Create new texture group (start index of new group is upcoming index)
@@ -36,6 +48,21 @@ Model::Model(ResourceManager* rm, OBJ &obj)
currentTexGroup = &TextureGroups.back();
}
/*std::unordered_map<int, glm::vec3> similarNormals;
std::unordered_map<int, int> normalCount;
for (auto &faceDef : face.Definitions)
{
if (faceDef.NormalIndex == 0)
continue;
similarNormals[faceDef.VertexIndex - 1] += normal;
normalCount[faceDef.VertexIndex - 1]++;
int index = pair.first;
glm::vec3 averagedNormal = ;
Normals[]
}*/
// Face definitions
for (auto faceDef : face.Definitions)
{
@@ -178,7 +205,7 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
bool Model::IsNear( float v1, float v2 )
{
return fabs(v1 - v2) < 0.01f;
return fabs(v1 - v2) < 0.001f;
}
void Model::getSimilarVertexIndex()
@@ -190,15 +217,15 @@ void Model::getSimilarVertexIndex()
if(i != t)
{
if(IsNear(Vertices[i].x, Vertices[t].x)
& IsNear(Vertices[i].y, Vertices[t].y)
& IsNear(Vertices[i].z, Vertices[t].z)
&& IsNear(Vertices[i].y, Vertices[t].y)
&& IsNear(Vertices[i].z, Vertices[t].z)
)
{
glm::vec3 tempNormal, tempTangent, tempBiTangent;
tempNormal = glm::normalize(Normals[i] + Normals[t]);
tempTangent = glm::normalize(TangentNormals[i] + TangentNormals[t]);
tempBiTangent = glm::normalize(BiTangentNormals[i] + BiTangentNormals[t]);
tempNormal = Normals[i] + Normals[t];
tempTangent = TangentNormals[i] + TangentNormals[t];
tempBiTangent = BiTangentNormals[i] + BiTangentNormals[t];
Normals[i] = tempNormal;
Normals[t] = tempNormal;
+1 -1
View File
@@ -17,7 +17,7 @@
class Model : public Resource
{
public:
Model(ResourceManager* rm, OBJ &obj);
Model(std::shared_ptr<ResourceManager> resourceManager, OBJ &obj);
struct TextureGroup
{
+43 -12
View File
@@ -14,9 +14,23 @@ struct RenderJob
{
friend class RenderQueue;
unsigned int ViewportID;
protected:
uint64_t Hash;
virtual void CalculateHash() = 0;
bool operator<(const RenderJob& rhs)
{
return this->Hash < rhs.Hash;
}
};
struct ModelJob : RenderJob
{
unsigned int ShaderID;
unsigned int TextureID;
GLuint ShaderProgram;
GLuint DiffuseTexture;
GLuint NormalTexture;
GLuint SpecularTexture;
@@ -25,28 +39,35 @@ struct RenderJob
unsigned int EndIndex;
glm::mat4 ModelMatrix;
protected:
uint64_t Hash;
void CalculateHash()
void CalculateHash() override
{
Hash = ViewportID << 58 // 6 bits
| TextureID << 42; // 16 bits
Hash = TextureID;
}
};
bool operator<(const RenderJob& rhs)
struct SpriteJob : RenderJob
{
unsigned int ShaderID;
unsigned int TextureID;
GLuint ShaderProgram;
GLuint Texture;
glm::mat4 ModelMatrix;
void CalculateHash() override
{
return this->Hash < rhs.Hash;
Hash = TextureID;
}
};
class RenderQueue
{
public:
void Add(RenderJob &job)
template <typename T>
void Add(T &job)
{
job.CalculateHash();
m_Jobs.push_front(job);
m_Jobs.push_front(std::shared_ptr<T>(new T(job)));
m_Jobs.sort();
}
@@ -55,8 +76,18 @@ public:
m_Jobs.clear();
}
std::forward_list<std::shared_ptr<RenderJob>>::const_iterator begin()
{
return m_Jobs.begin();
}
std::forward_list<std::shared_ptr<RenderJob>>::const_iterator end()
{
return m_Jobs.end();
}
private:
std::forward_list<RenderJob> m_Jobs;
std::forward_list<std::shared_ptr<RenderJob>> m_Jobs;
};
#endif // RenderQueue_h__
+532 -208
View File
@@ -1,7 +1,8 @@
#include "PrecompiledHeader.h"
#include "Renderer.h"
Renderer::Renderer()
Renderer::Renderer(std::shared_ptr<::ResourceManager> resourceManager)
: ResourceManager(resourceManager)
{
m_VSync = false;
#ifdef DEBUG
@@ -13,14 +14,17 @@ Renderer::Renderer()
m_DrawWireframe = false;
m_DrawBounds = false;
#endif
Gamma = 2.2f;
Gamma = 0.85f;
CAtt = 1.0f;
LAtt = 0.0f;
QAtt = 3.0f;
m_ShadowMapRes = 2048*6;
m_SunPosition = glm::vec3(0, 3.5f, 10);
m_ShadowMapRes = 2048*2;
m_SunPosition = glm::vec3(0.f, 1.0f, 0.5f);
m_SunTarget = glm::vec3(0, 0, 0);
m_SunProjection = glm::ortho<float>(10.f, -10.f, 10.f, -10.f, 10.f, -10.f);
m_SunProjection_height = glm::vec2(-40.f, 40.f);
m_SunProjection_width = glm::vec2(-40.f, 40.f);
m_SunProjection_length = glm::vec2(-500.f, 500.f);
m_SunProjection = glm::ortho<float>(m_SunProjection_width.x, m_SunProjection_width.y, m_SunProjection_height.x, m_SunProjection_height.y, m_SunProjection_length.x, m_SunProjection_length.y);
/* Lights = 0;*/
}
@@ -66,13 +70,14 @@ void Renderer::Initialize()
}
// Create Camera
m_Camera = std::make_shared<Camera>(45.f, (float)m_Width / m_Height, 0.01f, 1000.f);
m_Camera->Position(glm::vec3(0.0f, 0.0f, 2.f));
m_Camera = std::make_shared<Camera>(45.f, 0.01f, 1000.f);
m_Camera->SetPosition(glm::vec3(0.0f, 0.0f, 2.f));
glfwSwapInterval(m_VSync);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glEnable(GL_SCISSOR_TEST);
LoadContent();
}
@@ -101,12 +106,22 @@ void Renderer::LoadContent()
m_ShaderProgramDebugAABB.AddShader(standardVS);
m_ShaderProgramDebugAABB.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/AABB.frag.glsl")));
m_ShaderProgramDebugAABB.Compile();
m_ShaderProgramDebugAABB.Link();
m_ShaderProgramDebugAABB.Link();*/
m_ShaderProgramSkybox.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Skybox.vert.glsl")));
m_ShaderProgramSkybox.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Skybox.frag.glsl")));
m_ShaderProgramSkybox.Compile();
m_ShaderProgramSkybox.Link();*/
m_ShaderProgramSkybox.Link();
m_SunPassProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/SunPass.vert.glsl")));
m_SunPassProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/SunPass.frag.glsl")));
m_SunPassProgram.Compile();
m_SunPassProgram.Link();
m_ForwardRendering.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardRendering.vert.glsl")));
m_ForwardRendering.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardRendering.frag.glsl")));
m_ForwardRendering.Compile();
m_ForwardRendering.Link();
m_ShaderProgramShadows.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ShadowMap.vert.glsl")));
m_ShaderProgramShadows.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ShadowMap.frag.glsl")));
@@ -139,6 +154,9 @@ void Renderer::LoadContent()
m_ScreenQuad = CreateQuad();
CreateShadowMap(m_ShadowMapRes);
FrameBufferTextures();
m_sphereModel = ResourceManager->Load<Model>("Model", "Models/Placeholders/PhysicsTest/Sphere.obj");
m_Skybox = std::make_shared<Skybox>("Textures/Skybox/Sunset", "jpg");
}
void Renderer::Draw(double dt)
@@ -152,17 +170,44 @@ void Renderer::Draw(double dt)
m_QuadView = true;
}
if(glfwGetKey(m_Window, GLFW_KEY_KP_1))
//if(glfwGetKey(m_Window, GLFW_KEY_KP_1))
//{
// Gamma -= 0.3f * dt;
// LOG_INFO("Gamma_UP: %f", Gamma);
//}
//if(glfwGetKey(m_Window, GLFW_KEY_KP_4))
//{
// Gamma += 0.3f * dt;
// LOG_INFO("Gamma_DOWN: %f", Gamma);
//}
if(glfwGetKey(m_Window, GLFW_KEY_KP_7))
{
Gamma -= 0.3f * dt;
LOG_INFO("Gamma_UP: %f", Gamma);
m_SunProjection_height.x += 10.f * dt;
LOG_INFO("Heightx+: %f", m_SunProjection_height);
m_SunProjection = glm::ortho<float>(m_SunProjection_width.x, m_SunProjection_width.y, m_SunProjection_height.x, m_SunProjection_height.y, m_SunProjection_length.x, m_SunProjection_length.y);
}
if(glfwGetKey(m_Window, GLFW_KEY_KP_4))
else if(glfwGetKey(m_Window, GLFW_KEY_KP_4))
{
Gamma += 0.3f * dt;
LOG_INFO("Gamma_DOWN: %f", Gamma);
m_SunProjection_height.x -= 10.f * dt;
LOG_INFO("Heightx-: %f", m_SunProjection_height);
m_SunProjection = glm::ortho<float>(m_SunProjection_width.x, m_SunProjection_width.y, m_SunProjection_height.x, m_SunProjection_height.y, m_SunProjection_length.x, m_SunProjection_length.y);
}
if(glfwGetKey(m_Window, GLFW_KEY_KP_8))
{
m_SunProjection_height.y += 10.f * dt;
LOG_INFO("Heightx+: %f", m_SunProjection_height);
m_SunProjection = glm::ortho<float>(m_SunProjection_width.x, m_SunProjection_width.y, m_SunProjection_height.x, m_SunProjection_height.y, m_SunProjection_length.x, m_SunProjection_length.y);
}
else if(glfwGetKey(m_Window, GLFW_KEY_KP_5))
{
m_SunProjection_height.y -= 10.f * dt;
LOG_INFO("Heightx-: %f", m_SunProjection_height);
m_SunProjection = glm::ortho<float>(m_SunProjection_width.x, m_SunProjection_width.y, m_SunProjection_height.x, m_SunProjection_height.y, m_SunProjection_length.x, m_SunProjection_length.y);
}
if(glfwGetKey(m_Window, GLFW_KEY_1))
{
if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD))
@@ -211,16 +256,195 @@ void Renderer::Draw(double dt)
glfwSwapBuffers(m_Window);
}
void Renderer::DrawFrame(RenderQueue &rq)
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(m_Viewport.X, -m_Viewport.Y, m_Viewport.Width, m_Viewport.Height);
glScissor(m_Viewport.X, -m_Viewport.Y, m_Viewport.Width, m_Viewport.Height);
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
glDisable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix((float)m_Width / m_Height) * m_Camera->ViewMatrix();
//glm::mat4 MVP;
m_ForwardRendering.Bind();
//for (auto tuple : ModelsToRender) //// Todo: Add so it's TransparentModelsToRender
//{
// Model* model;
// glm::mat4 modelMatrix;
// bool visible;
// std::tie(model, modelMatrix, visible, std::ignore) = tuple;
// if (!visible)
// continue;
// MVP = cameraMatrix * modelMatrix;
// glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
// glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
// glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
// glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix((float)m_Width / m_Height)));
// glBindVertexArray(model->VAO);
// for (auto texGroup : model->TextureGroups)
// {
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, *texGroup.Texture);
// glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
// }
//}
for (auto &job : rq)
{
//auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
//if (modelJob)
//{
// glm::mat4 modelMatrix = modelJob->ModelMatrix;
// MVP = cameraMatrix * modelMatrix;
// depthMVP = depthCameraMatrix * modelMatrix;
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(cameraProjection));
// //glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "SunDirection_cameraspace"), 1, glm::value_ptr(sunDirection_cameraview));
// glBindVertexArray(modelJob->VAO);
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture);
// if (modelJob->NormalTexture != 0)
// {
// glActiveTexture(GL_TEXTURE2);
// glBindTexture(GL_TEXTURE_2D, modelJob->NormalTexture);
// }
// if (modelJob->SpecularTexture)
// {
// glActiveTexture(GL_TEXTURE3);
// glBindTexture(GL_TEXTURE_2D, modelJob->SpecularTexture);
// }
// glDrawArrays(GL_TRIANGLES, modelJob->StartIndex, modelJob->EndIndex - modelJob->StartIndex + 1);
// continue;
//}
auto spriteJob = std::dynamic_pointer_cast<SpriteJob>(job);
if (spriteJob)
{
glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(glm::mat4()));
glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(glm::mat4()));
glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(glm::mat4()));
glUniformMatrix4fv(glGetUniformLocation(m_ForwardRendering.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(glm::mat4()));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, spriteJob->Texture);
glBindVertexArray(m_ScreenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
continue;
}
}
}
void Renderer::DrawWorld(RenderQueue &rq)
{
glDisable(GL_BLEND);
DrawShadowMap(rq);
/*
Base pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbBasePass);
glViewport(m_Viewport.X, -m_Viewport.Y, m_Viewport.Width, m_Viewport.Height);
glScissor(m_Viewport.X, -m_Viewport.Y, m_Viewport.Width, m_Viewport.Height);
//glViewport(0, 0, m_Width, m_Height);
// Clear G-buffer
GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers(4, windowBuffClear);
glClearColor(115.f / 255, 192.f / 255, 255.f / 255, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Execute the first render stage which will fill out the internal buffers with data(??)
m_FirstPassProgram.Bind();
GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
glDrawBuffers(4, windowBuffOpaque);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
DrawFBOScene(rq);
/*
Lighting pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbLightingPass);
GLenum lightingPassAttachments[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, lightingPassAttachments);
glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT);
m_SecondPassProgram.Bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, m_fSpecularTexture);
glCullFace(GL_FRONT);
DrawLightScene(rq);
DrawSunLightScene();
/*
Final pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
//glViewport(m_Viewport.X, m_Viewport.Y, m_Viewport.Width, m_Viewport.Height);
glViewport(0, 0, m_Width, m_Height);
glScissor(0, 0, m_Width, m_Height);
glClear(GL_DEPTH_BUFFER_BIT);
m_FinalPassProgram.Bind();
// Ambient light
glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.7f)));
glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_fLightingTexture);
glCullFace(GL_BACK);
glBindVertexArray(m_ScreenQuad);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
void Renderer::Swap()
{
glfwSwapBuffers(m_Window);
}
#pragma region TempRegion
void Renderer::DrawSkybox()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, m_Width, m_Height);
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
//glViewport(0, 0, m_Width, m_Height);
//glScissor(0, 0, m_Width, m_Height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_ShaderProgramSkybox.Bind();
glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * glm::toMat4(glm::inverse(m_Camera->Orientation()));
glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix((float)m_Width / m_Height) * glm::toMat4(glm::inverse(m_Camera->Orientation()));
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramSkybox.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(cameraMatrix));
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
m_Skybox->Draw();
@@ -235,8 +459,8 @@ void Renderer::CreateShadowMap(int resolution)
glGenTextures(1, &m_ShadowDepthTexture);
glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, resolution, resolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
@@ -253,21 +477,23 @@ void Renderer::CreateShadowMap(int resolution)
}
}
void Renderer::DrawShadowMap()
void Renderer::DrawShadowMap(RenderQueue &rq)
{
glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly
glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object
glCullFace(GL_BACK); //Make it so that only the back faces are rendered
glCullFace(GL_FRONT); //Make it so that only the back faces are rendered
//Binds the FBO and sets the veiwport, witch in effect is how large the shadowmap is and what resolution it has.
glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer);
glViewport(0, 0, m_ShadowMapRes, m_ShadowMapRes);
glScissor(0, 0, m_ShadowMapRes, m_ShadowMapRes);
glClear(GL_DEPTH_BUFFER_BIT);
//glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
//Creates the "camera" for the shadowmap from the direction of the sun.
glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0));
glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(m_Camera->Position() * glm::vec3(1, 1, 1));
//glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate((-m_Camera->Position() + (glm::vec3(40.0) * -m_Camera->Forward())) * glm::vec3(1, 1, 1));
glm::mat4 depthCamera = m_SunProjection * depthViewMatrix;
glm::mat4 MVP;
@@ -275,26 +501,23 @@ void Renderer::DrawShadowMap()
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Draws filled polygons
//For each model, render them to the shadowmap
for (auto tuple : ModelsToRender)
for (auto &job : rq)
{
Model* model;
glm::mat4 modelMatrix;
bool shadow;
std::tie(model, modelMatrix, std::ignore, shadow) = tuple;
if (!shadow)
continue;
MVP = depthCamera * modelMatrix;
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramShadows.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups)
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob)
{
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
glm::mat4 modelMatrix = modelJob->ModelMatrix;
MVP = depthCamera * modelMatrix;
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramShadows.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
//glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "SunDirection_cameraspace"), 1, glm::value_ptr(sunDirection_cameraview));
glBindVertexArray(modelJob->VAO);
glDrawArrays(GL_TRIANGLES, modelJob->StartIndex, modelJob->EndIndex - modelJob->StartIndex + 1);
continue;
}
}
}
void Renderer::DrawDebugShadowMap()
@@ -355,30 +578,31 @@ void Renderer::AddModelToDraw(Model* model, glm::vec3 position, glm::quat orient
void Renderer::AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale)
{
glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale);
//glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale);
glm::vec3 camToParticle = glm::normalize(m_Camera->Position() - position);
glm::vec3 up = glm::vec3(0,1,0);
glm::vec3 rightVec = glm::normalize(glm::cross(up, camToParticle));
glm::vec3 up2 = glm::normalize(glm::cross(camToParticle, rightVec));
//glm::vec3 camToParticle = glm::normalize(m_Camera->Position() - position);
//glm::vec3 up = glm::vec3(0,1,0);
//glm::vec3 rightVec = glm::normalize(glm::cross(up, camToParticle));
//glm::vec3 up2 = glm::normalize(glm::cross(camToParticle, rightVec));
//
//glm::mat4 billboardMatrix;
//billboardMatrix[0] = glm::vec4(rightVec, 0);
//billboardMatrix[1] = glm::vec4(up2, 0);
//billboardMatrix[2] = glm::vec4(camToParticle, 0);
////billboardMatrix[3] = glm::vec4(position, 0);
glm::mat4 billboardMatrix;
billboardMatrix[0] = glm::vec4(rightVec, 0);
billboardMatrix[1] = glm::vec4(up2, 0);
billboardMatrix[2] = glm::vec4(camToParticle, 0);
//billboardMatrix[3] = glm::vec4(position, 0);
TexturesToRender.push_back(std::make_tuple(texture, modelMatrix, billboardMatrix));
//TexturesToRender.push_back(std::make_tuple(texture, modelMatrix, billboardMatrix));
}
void Renderer::AddPointLightToDraw(
glm::vec3 _position,
glm::vec3 _specular,
glm::vec3 _diffuse,
float _specularExponent,
glm::vec3 _position,
glm::vec3 _specular,
glm::vec3 _diffuse,
float _specularExponent,
float _ConstantAttenuation,
float _LinearAttenuation,
float _QuadraticAttenuation
float _QuadraticAttenuation,
float _radius
)
{
Light light;
@@ -389,6 +613,7 @@ void Renderer::AddPointLightToDraw(
light.ConstantAttenuation = _ConstantAttenuation;
light.LinearAttenuation = _LinearAttenuation;
light.QuadraticAttenuation = _QuadraticAttenuation;
light.Radius = _radius;
light.SphereModelMatrix = CreateLightMatrix(light);
Lights.push_back(light);
}
@@ -548,7 +773,7 @@ void Renderer::FrameBufferTextures()
//Generate and bind diffuse texture
glGenTextures(1, &m_fDiffuseTexture);
glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -557,7 +782,7 @@ void Renderer::FrameBufferTextures()
//Generate and bind position texture
glGenTextures(1, &m_fPositionTexture);
glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, m_Width, m_Height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -566,7 +791,7 @@ void Renderer::FrameBufferTextures()
//Generate and bind normal texture
glGenTextures(1, &m_fNormalsTexture);
glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, m_Width, m_Height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -575,7 +800,7 @@ void Renderer::FrameBufferTextures()
//Generate and bind normal texture
glGenTextures(1, &m_fSpecularTexture);
glBindTexture(GL_TEXTURE_2D, m_fSpecularTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, m_Width, m_Height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -612,7 +837,7 @@ void Renderer::FrameBufferTextures()
glGenTextures(1, &m_fLightingTexture);
glBindTexture(GL_TEXTURE_2D, m_fLightingTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
@@ -634,92 +859,101 @@ void Renderer::FrameBufferTextures()
void Renderer::DrawFBO()
{
DrawShadowMap();
//DrawShadowMap();
for (auto &pair : m_Viewports)
{
Viewport &viewport = pair.second;
if (!viewport.Camera)
continue;
//for (auto &pair : m_Viewports)
//{
// Viewport &viewport = pair.second;
// if (!viewport.Camera)
// continue;
int x = viewport.Left * m_Width;
int y = viewport.Top * m_Height;
int width = (viewport.Right - viewport.Left) * m_Width;
int height = (viewport.Bottom - viewport.Top) * m_Height;
// int x = viewport.Left * m_Width;
// int y = viewport.Top * m_Height;
// int width = (viewport.Right - viewport.Left) * m_Width;
// int height = (viewport.Bottom - viewport.Top) * m_Height;
//
// /*
// Base pass
// */
// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbBasePass);
// glViewport(0, 0, m_Width, m_Height);
/*
Base pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbBasePass);
glViewport(0, 0, m_Width, m_Height);
// // Clear G-buffer
// GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
// glDrawBuffers(4, windowBuffClear);
// glClearColor(0.0f, 0.3f, 0.7f, 0.f);
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Clear G-buffer
GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, windowBuffClear);
glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// // Execute the first render stage which will fill out the internal buffers with data(??)
// m_FirstPassProgram.Bind();
// GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
// glDrawBuffers(4, windowBuffOpaque);
// Execute the first render stage which will fill out the internal buffers with data(??)
m_FirstPassProgram.Bind();
GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, windowBuffOpaque);
// glCullFace(GL_BACK);
//
// DrawFBOScene(viewport);
glCullFace(GL_BACK);
// /*
// Lighting pass
// */
// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbLightingPass);
// GLenum lightingPassAttachments[] = { GL_COLOR_ATTACHMENT0 };
// glDrawBuffers(1, lightingPassAttachments);
DrawFBOScene(viewport);
// glClearColor(0.f, 0.f, 0.f, 0.f);
// glClear(GL_COLOR_BUFFER_BIT);
/*
Lighting pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbLightingPass);
GLenum lightingPassAttachments[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, lightingPassAttachments);
// m_SecondPassProgram.Bind();
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
// glActiveTexture(GL_TEXTURE1);
// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
// glActiveTexture(GL_TEXTURE2);
// glBindTexture(GL_TEXTURE_2D, m_fSpecularTexture);
glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT);
// glCullFace(GL_FRONT);
// DrawLightScene(viewport);
DrawSunLightScene();
m_SecondPassProgram.Bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
// /*
// Final pass
// */
// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
// glViewport(x, y, width, height);
// glClear(GL_DEPTH_BUFFER_BIT);
glCullFace(GL_FRONT);
DrawLightScene(viewport);
// m_FinalPassProgram.Bind();
/*
Final pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(x, y, width, height);
glClear(GL_DEPTH_BUFFER_BIT);
// // Ambient light
// glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.7f)));
// glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma);
m_FinalPassProgram.Bind();
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
// glActiveTexture(GL_TEXTURE1);
// glBindTexture(GL_TEXTURE_2D, m_fLightingTexture);
// Ambient light
glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.1f, 0.1f, 0.1f)));
glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_fLightingTexture);
glCullFace(GL_BACK);
glBindVertexArray(m_ScreenQuad);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
// glCullFace(GL_BACK);
// glBindVertexArray(m_ScreenQuad);
// glEnableVertexAttribArray(0);
// glDrawArrays(GL_TRIANGLES, 0, 6);
//}
}
void Renderer::DrawFBOScene(Viewport &viewport)
void Renderer::DrawFBO2()
{
ForwardRendering();
}
void Renderer::DrawFBOScene(RenderQueue &rq)
{
// glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly
// glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object
// glCullFace(GL_BACK); //Make it so that only the back faces are rendered
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Draws filled polygons
glm::mat4 cameraMatrix = viewport.Camera->ProjectionMatrix() * viewport.Camera->ViewMatrix();
glm::mat4 cameraProjection = m_Camera->ProjectionMatrix((float)m_Viewport.Width / m_Viewport.Height);
glm::mat4 cameraMatrix = cameraProjection * m_Camera->ViewMatrix();
glm::mat4 MVP;
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
@@ -728,71 +962,84 @@ void Renderer::DrawFBOScene(Viewport &viewport)
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0));
//glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate((-m_Camera->Position() + (glm::vec3(40.0) * -m_Camera->Forward())) * glm::vec3(1, 1, 1));
glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 1, 1));
glm::mat4 depthCamera = m_SunProjection * depthViewMatrix;
glm::mat4 depthCameraMatrix = biasMatrix * depthCamera;
glm::mat4 depthMVP;
glm::vec3 sunDirection = m_SunTarget - m_SunPosition;
glm::vec3 sunDirection_cameraview = glm::vec3(cameraProjection * m_Camera->ViewMatrix() * glm::vec4(sunDirection, 1.0));
m_FirstPassProgram.Bind();
GLuint ShaderProgramHandle = m_FirstPassProgram.GetHandle();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture);
for (auto tuple : ModelsToRender)
for (auto &job : rq)
{
Model* model;
glm::mat4 modelMatrix;
bool visible;
std::tie(model, modelMatrix, visible, std::ignore) = tuple;
if (!visible)
continue;
MVP = cameraMatrix * modelMatrix;
depthMVP = depthCameraMatrix * modelMatrix;
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(viewport.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(viewport.Camera->ProjectionMatrix()));
glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups)
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob)
{
glm::mat4 modelMatrix = modelJob->ModelMatrix;
MVP = cameraMatrix * modelMatrix;
depthMVP = depthCameraMatrix * modelMatrix;
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "P"), 1, GL_FALSE, glm::value_ptr(cameraProjection));
glUniform3fv(glGetUniformLocation(ShaderProgramHandle, "SunDirection_cameraspace"), 1, glm::value_ptr(sunDirection_cameraview));
glBindVertexArray(modelJob->VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texGroup.Texture);
if (texGroup.NormalMap)
glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture);
if (modelJob->NormalTexture != 0)
{
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, *texGroup.NormalMap);
glBindTexture(GL_TEXTURE_2D, modelJob->NormalTexture);
}
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
if (modelJob->SpecularTexture)
{
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, modelJob->SpecularTexture);
}
glDrawArrays(GL_TRIANGLES, modelJob->StartIndex, modelJob->EndIndex - modelJob->StartIndex + 1);
continue;
}
}
for (auto tuple : TexturesToRender)
{
Texture* texture;
glm::mat4 modelMatrix;
glm::mat4 billboardMatrix;
std::tie(texture, modelMatrix, billboardMatrix) = tuple;
//auto spriteJob = std::dynamic_pointer_cast<SpriteJob>(job);
//if (spriteJob)
//{
// Texture* texture;
// glm::mat4 modelMatrix;
// glm::mat4 billboardMatrix;
// std::tie(texture, modelMatrix, billboardMatrix) = tuple;
//MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation()) * modelMatrix );
MVP = cameraMatrix * modelMatrix * billboardMatrix;
// //MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation()) * modelMatrix );
// MVP = cameraMatrix * modelMatrix * billboardMatrix;
depthMVP = depthCameraMatrix * modelMatrix;
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(viewport.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(viewport.Camera->ProjectionMatrix()));
// depthMVP = depthCameraMatrix * modelMatrix;
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
// glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix((float)m_Width / m_Height)));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texture);
glBindVertexArray(m_ScreenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, *texture);
// glBindVertexArray(m_ScreenQuad);
// glDrawArrays(GL_TRIANGLES, 0, 6);
// continue;
//}
}
}
void Renderer::DrawLightScene(Viewport &viewport)
void Renderer::DrawLightScene(RenderQueue &rq)
{
glEnable(GL_BLEND);
glBlendEquation (GL_FUNC_ADD);
@@ -802,32 +1049,72 @@ void Renderer::DrawLightScene(Viewport &viewport)
glDepthMask (GL_FALSE);
glBindVertexArray(m_sphereModel->VAO);
glm::mat4 cameraMatrix = viewport.Camera->ProjectionMatrix() * viewport.Camera->ViewMatrix();
glm::mat4 cameraProjection = m_Camera->ProjectionMatrix((float)m_Viewport.Width / m_Viewport.Height);
glm::mat4 cameraMatrix = cameraProjection * m_Camera->ViewMatrix();
glm::mat4 MVP;
glm::vec3 sunDirection = m_SunTarget - m_SunPosition;
m_SecondPassProgram.Bind();
GLuint ShaderProgramHandle = m_SecondPassProgram.GetHandle();
for (auto &light : Lights)
{
MVP = cameraMatrix * light.SphereModelMatrix;
glUniform2fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ViewportSize"), 1,glm::value_ptr(glm::vec2(m_Width, m_Height)));
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(viewport.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(viewport.Camera->ProjectionMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(light.SphereModelMatrix));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), 1, glm::value_ptr(light.Specular));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), 1, glm::value_ptr(light.Diffuse));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(light.Position));
glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), viewport.Camera->Position().x, viewport.Camera->Position().y, viewport.Camera->Position().z);
glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "specularExponent"), light.SpecularExponent);
// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), light.ConstantAttenuation);
// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), light.LinearAttenuation);
// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), light.QuadraticAttenuation);
glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), CAtt);
glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), LAtt);
glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), QAtt);
glUniform2fv(glGetUniformLocation(ShaderProgramHandle, "ViewportSize"), 1,glm::value_ptr(glm::vec2(m_Width, m_Height)));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "P"), 1, GL_FALSE, glm::value_ptr(cameraProjection));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "M"), 1, GL_FALSE, glm::value_ptr(light.SphereModelMatrix));
glUniform3fv(glGetUniformLocation(ShaderProgramHandle, "ls"), 1, glm::value_ptr(light.Specular));
glUniform3fv(glGetUniformLocation(ShaderProgramHandle, "ld"), 1, glm::value_ptr(light.Diffuse));
glUniform3fv(glGetUniformLocation(ShaderProgramHandle, "lp"), 1, glm::value_ptr(light.Position));
glUniform3f(glGetUniformLocation(ShaderProgramHandle, "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z);
glUniform1f(glGetUniformLocation(ShaderProgramHandle, "specularExponent"), light.SpecularExponent);
//glUniform1f(glGetUniformLocation(ShaderProgramHandle, "ConstantAttenuation"), CAtt);
//glUniform1f(glGetUniformLocation(ShaderProgramHandle, "LinearAttenuation"), LAtt);
//glUniform1f(glGetUniformLocation(ShaderProgramHandle, "QuadraticAttenuation"), QAtt);
glUniform1f(glGetUniformLocation(ShaderProgramHandle, "LightRadius"), light.Radius);
glUniform3fv(glGetUniformLocation(ShaderProgramHandle, "directionToSun"), 1, glm::value_ptr(-sunDirection));
glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size());
glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size());
};
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDisable(GL_BLEND);
}
void Renderer::DrawSunLightScene()
{
glCullFace(GL_BACK);
glEnable(GL_BLEND);
glBlendEquation (GL_FUNC_ADD);
glBlendFunc(GL_ONE,GL_ONE);
glDisable (GL_DEPTH_TEST);
glDepthMask (GL_FALSE);
//glBindVertexArray(m_sphereModel->VAO);
glm::mat4 cameraProjection = m_Camera->ProjectionMatrix((float)m_Viewport.Width / m_Viewport.Height);
glm::mat4 cameraMatrix = cameraProjection * m_Camera->ViewMatrix();
glm::mat4 MVP;
m_SunPassProgram.Bind();
GLuint ShaderProgramHandle = m_SunPassProgram.GetHandle();
glUniform2fv(glGetUniformLocation(ShaderProgramHandle, "ViewportSize"), 1, glm::value_ptr(glm::vec2(m_Width, m_Height)));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "P"), 1, GL_FALSE, glm::value_ptr(cameraProjection));
glUniform3f(glGetUniformLocation(ShaderProgramHandle, "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z);
glUniform3fv(glGetUniformLocation(ShaderProgramHandle, "directionToSun"), 1, glm::value_ptr(glm::normalize(m_SunPosition)));
glBindVertexArray(m_ScreenQuad);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glEnable (GL_DEPTH_TEST);
glDepthMask (GL_TRUE);
glDisable (GL_BLEND);
@@ -843,14 +1130,14 @@ glm::mat4 Renderer::CreateLightMatrix(Light &_light)
// float c = _light.ConstantAttenuation;
// float l = _light.LinearAttenuation;
// float q = _light.QuadraticAttenuation;
float c = CAtt;
float l = LAtt;
float q = QAtt;
float cutOffRadius = abs(sqrt((-4*c*q) + pow(l, 2) + (1024*q) - l) / (2*q));
//float c = CAtt;
//float l = LAtt;
//float q = QAtt;
//float cutOffRadius = abs(sqrt((-4*c*q) + pow(l, 2) + (1024*q) - l) / (2*q));
glm::mat4 model;
model *= glm::translate(_light.Position);
model *= glm::scale(glm::vec3(cutOffRadius));
model *= glm::scale(glm::vec3(_light.Radius*2));
return model;
}
@@ -868,7 +1155,7 @@ void Renderer::UpdateSunProjection()
glm::vec3(1.f, 1.f, 1.f)
};
glm::mat4 inverseProjectionViewMatrix = glm::inverse(m_Camera->ViewMatrix()) * glm::inverse(m_Camera->ProjectionMatrix());
glm::mat4 inverseProjectionViewMatrix = glm::inverse(m_Camera->ViewMatrix()) * glm::inverse(m_Camera->ProjectionMatrix((float)m_Width / m_Height));
//Also * with world matrix for light
for(auto corner : NDCCube)
@@ -881,35 +1168,72 @@ void Renderer::UpdateSunProjection()
//Pass the bounding box's extents to glOrtho or similar to set up the orthographic projection matrix for the shadow map.
}
void Renderer::RegisterViewport(int identifier, float left, float top, float right, float bottom)
void Renderer::ForwardRendering()
{
Viewport v;
v.Left = left;
v.Top = top;
v.Right = right;
v.Bottom = bottom;
v.Camera = nullptr;
m_Viewports[identifier] = v;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, m_Width, m_Height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix((float)m_Width / m_Height) * m_Camera->ViewMatrix();
glm::mat4 MVP;
m_ForwardRendering.Bind();
GLuint ShaderProgramHandle = m_ForwardRendering.GetHandle();
for (auto tuple : ModelsToRender) //// Todo: Add so it's TransparentModelsToRender
{
Model* model;
glm::mat4 modelMatrix;
bool visible;
std::tie(model, modelMatrix, visible, std::ignore) = tuple;
if (!visible)
continue;
MVP = cameraMatrix * modelMatrix;
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(ShaderProgramHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix((float)m_Width / m_Height)));
glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups)
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texGroup.Texture);
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
}
}
}
void Renderer::RegisterCamera(int identifier, float FOV, float nearClip, float farClip)
{
m_Cameras[identifier] = std::make_shared<Camera>(FOV, (float)m_Width / m_Height, nearClip, farClip);
m_Cameras[identifier] = std::make_shared<Camera>(FOV, nearClip, farClip);
}
void Renderer::UpdateViewport(int viewportIdentifier, int cameraIdentifier)
{
auto &viewport = m_Viewports[viewportIdentifier];
auto camera = m_Cameras[cameraIdentifier];
camera->AspectRatio(((viewport.Right - viewport.Left) * m_Width) / ((viewport.Bottom - viewport.Top) * m_Height));
viewport.Camera = camera;
//auto &viewport = m_Viewports[viewportIdentifier];
//auto camera = m_Cameras[cameraIdentifier];
//camera->AspectRatio(((viewport.Right - viewport.Left) * m_Width) / ((viewport.Bottom - viewport.Top) * m_Height));
//viewport.Camera = camera;
}
void Renderer::UpdateCamera(int cameraIdentifier, glm::vec3 position, glm::quat orientation, float FOV, float nearClip, float farClip)
{
m_Cameras[cameraIdentifier]->Position(position);
/*m_Cameras[cameraIdentifier]->Position(position);
m_Cameras[cameraIdentifier]->Orientation(orientation);
m_Cameras[cameraIdentifier]->FOV(FOV);
m_Cameras[cameraIdentifier]->NearClip(nearClip);
m_Cameras[cameraIdentifier]->FarClip(farClip);
m_Cameras[cameraIdentifier]->FarClip(farClip);*/
}
void Renderer::ClearPointLights()
{
Lights.clear();
}
+43 -9
View File
@@ -13,6 +13,8 @@
#include "Components/PointLight.h"
#include "Skybox.h"
#include "ResourceManager.h"
#include "Util/Rectangle.h"
#include "RenderQueue.h"
class Renderer
{
@@ -26,10 +28,10 @@ public:
int Height() const { return m_Height; }
std::list<std::tuple<Model*, glm::mat4, bool, bool>> ModelsToRender;
std::list<std::tuple<Texture*, glm::mat4, glm::mat4>> TexturesToRender;
std::list<std::tuple<Texture*, glm::mat4, glm::vec3>> TexturesToRender;
std::list<std::tuple<glm::mat4, bool>> AABBsToRender;
Renderer();
Renderer(std::shared_ptr<::ResourceManager> resourceManager);
void Initialize();
void Draw(double dt);
@@ -40,6 +42,23 @@ public:
void UpdateViewport(int viewportIdentifier, int cameraIdentifier);
void UpdateCamera(int cameraIdentifier, glm::vec3 position, glm::quat orientation, float FOV, float nearClip, float farClip);
#pragma region NEWSTUFF
void SetViewport(const Rectangle &viewport)
{
m_Viewport = viewport;
}
void SetCamera(std::shared_ptr<Camera> camera)
{
m_Camera = camera;
}
void DrawFrame(RenderQueue &rq);
void DrawWorld(RenderQueue &rq);
void Swap();
#pragma endregion
void AddModelToDraw(Model* model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster);
void AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale);
void AddTextToDraw();
@@ -50,8 +69,11 @@ public:
float _specularExponent,
float _ConstantAttenuation,
float _LinearAttenuation,
float _QuadraticAttenuation
float _QuadraticAttenuation,
float _radius
);
void ClearPointLights();
void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding);
void LoadContent();
@@ -70,6 +92,8 @@ public:
void SetSphereModel(Model* _model);
private:
std::shared_ptr<::ResourceManager> ResourceManager;
int m_Width, m_Height;
struct Viewport
@@ -84,6 +108,9 @@ private:
std::unordered_map<int, Viewport> m_Viewports;
std::unordered_map<int, std::shared_ptr<Camera>> m_Cameras;
Rectangle m_Viewport;
std::shared_ptr<Camera> m_Camera;
struct Light
{
glm::vec3 Position;
@@ -91,7 +118,7 @@ private:
glm::vec3 Diffuse;
float SpecularExponent;
glm::mat4 SphereModelMatrix;
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation;
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation, Radius;
};
float Gamma;
@@ -113,6 +140,10 @@ private:
glm::vec3 m_SunPosition;
glm::vec3 m_SunTarget;
glm::mat4 m_SunProjection;
glm::vec2 m_SunProjection_width;
glm::vec2 m_SunProjection_height;
glm::vec2 m_SunProjection_length;
GLuint m_DebugAABB;
GLuint m_ShadowFrameBuffer;
@@ -135,13 +166,13 @@ private:
bool m_QuadView;
std::shared_ptr<Camera> m_Camera;
ShaderProgram m_ShaderProgram;
ShaderProgram m_FirstPassProgram;
ShaderProgram m_SecondPassProgram;
ShaderProgram m_SecondPassProgram_Debug;
ShaderProgram m_FinalPassProgram;
ShaderProgram m_SunPassProgram;
ShaderProgram m_ForwardRendering;
ShaderProgram m_ShaderProgramNormals;
ShaderProgram m_ShaderProgramShadows;
@@ -154,16 +185,19 @@ private:
void ClearStuff();
void DrawScene();
void DrawModels(ShaderProgram &shader);
void DrawShadowMap();
void DrawShadowMap(RenderQueue &rq);
void CreateShadowMap(int resolution);
void FrameBufferTextures();
void DrawFBO();
void DrawFBOScene(Viewport &viewport);
void DrawLightScene(Viewport &viewport);
void DrawFBO2();
void DrawFBOScene(RenderQueue &rq);
void DrawLightScene(RenderQueue &rq);
void DrawSunLightScene();
void BindFragDataLocation();
glm::mat4 CreateLightMatrix(Light &_light);
void UpdateSunProjection();
void CreateNormalMapTangent();
void ForwardRendering();
GLuint CreateQuad();
+37
View File
@@ -156,3 +156,40 @@ void ShaderProgram::Unbind()
{
glActiveShaderProgram(0, 0);
}
void ShaderProgram::LoadFromFolder(std::string folderPath)
{
auto path = boost::filesystem::path(folderPath);
if (!boost::filesystem::is_directory(path))
{
LOG_ERROR("Failed to load shader program: \"%s\" is not a directory", folderPath.c_str());
return;
}
for (auto it = boost::filesystem::directory_iterator(path); it != boost::filesystem::directory_iterator(); it++)
{
std::string filename = it->path().filename().string();
if (filename == "Vertex.glsl")
{
AddShader(std::shared_ptr<Shader>(new VertexShader(filename)));
}
else if (filename == "Fragment.glsl")
{
AddShader(std::shared_ptr<Shader>(new FragmentShader(filename)));
}
else if (filename == "Geometry.glsl")
{
AddShader(std::shared_ptr<Shader>(new GeometryShader(filename)));
}
}
}
void ShaderProgram::BindFragDataLocation(int colorNumber, std::string name)
{
if (m_ShaderProgramHandle == 0)
return;
glBindFragDataLocation(m_ShaderProgramHandle, colorNumber, name.c_str());
}
+16 -2
View File
@@ -6,6 +6,11 @@
#include <fstream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include "ResourceManager.h"
class Shader
{
public:
@@ -57,23 +62,32 @@ public:
: ShaderType(fileName) { }
};
class ShaderProgram
class ShaderProgram : public Resource
{
public:
ShaderProgram()
: m_ShaderProgramHandle(0) { }
: m_ShaderProgramHandle(0)
{ }
ShaderProgram(std::string folderPath)
: m_ShaderProgramHandle(0)
{ }
~ShaderProgram();
void AddShader(std::shared_ptr<Shader> shader);
void BindFragDataLocation(int colorNumber, std::string name);
void Compile();
GLuint Link();
GLuint GetHandle();
operator GLuint() const { return m_ShaderProgramHandle; }
void Bind();
void Unbind();
private:
GLuint m_ShaderProgramHandle;
std::vector<std::shared_ptr<Shader>> m_Shaders;
void LoadFromFolder(std::string folderPath);
};
#endif // ShaderProgram_h__
+4 -3
View File
@@ -21,9 +21,10 @@ void main()
vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord);
vec4 ShadowTexel = texture(ShadowTexture, Input.TextureCoord);
vec4 _FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel;
FragmentColor = vec4(pow(_FragmentColor.rgb, vec3(1.0 / Gamma)), _FragmentColor.a);
//FragmentColor = LightingTexel + vec4(LightingTexel.a, LightingTexel.a, LightingTexel.a, 0.0);
//FragmentColor = DiffuseTexel;
FragmentColor = DiffuseTexel * (vec4(La, 0.0) + vec4(LightingTexel.rgb, 0.0)) + vec4(LightingTexel.a, LightingTexel.a, LightingTexel.a, 0.0);
//FragmentColor = vec4(pow(_FragmentColor.rgb, vec3(1.0 / Gamma)), _FragmentColor.a);
}
+18
View File
@@ -0,0 +1,18 @@
#version 430
layout(binding=0) uniform sampler2D texture0;
in VertexData {
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Input;
out vec4 fragmentColor;
void main() {
// Texture
vec4 texel = texture(texture0, Input.TextureCoord);
fragmentColor = texel;
}
+25
View File
@@ -0,0 +1,25 @@
#version 430
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
layout (location = 0) in vec3 Position;
layout (location = 1) in vec3 Normal;
layout (location = 2) in vec2 TextureCoord;
out VertexData {
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Output;
void main()
{
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position;
Output.Normal = Normal;
Output.TextureCoord = TextureCoord;
}
+52 -11
View File
@@ -5,6 +5,15 @@ layout (binding=1) uniform sampler2D ShadowTexture;
layout (binding=2) uniform sampler2D NormalMapTexture;
layout (binding=3) uniform sampler2D SpecularMapTexture;
//TerrainTextures
layout (binding=4) uniform sampler2D AsphaltTexture;
layout (binding=5) uniform sampler2D GrassTexture;
layout (binding=6) uniform sampler2D SandTexture;
layout (binding=7) uniform sampler2D BlendMap;
uniform float texScale; //Determines how many times the textures will loop over the terrain
uniform vec3 SunDirection_cameraspace;
uniform mat4 V;
in VertexData
{
@@ -19,16 +28,28 @@ in VertexData
out vec4 frag_Diffuse;
out vec4 frag_Position;
out vec4 frag_Normal;
out vec4 frag_specular;
out vec4 frag_Specular;
float Shadow(vec4 ShadowCoord)
float Shadow(vec4 ShadowCoord, vec3 normal)
{
//float cosTheta = clamp(dot(Input.Normal, 1.0), 0.0, 1.0);
float bias = 0.0005; // cosTheta is dot( n,l ), clamped between 0 and 1
bias = clamp(bias, 0.0, 0.01);
if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z - bias)
return 1.0;
if (Input.ShadowCoord.x < 0.0 || Input.ShadowCoord.x > 1.0 || Input.ShadowCoord.y < 0.0 || Input.ShadowCoord.y > 1.0)
return 0.9;
//Variable bias
vec3 n = normalize(normal);
vec3 l = normalize(SunDirection_cameraspace);
float cosTheta = clamp(dot(n, l), 0.0, 1.0);
float bias = tan(acos(cosTheta));
bias = clamp(bias, 0.0, 0.00003);
//Fixed bias
bias = 0;
if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z + bias)
{
return 0.3;
return 0.6;
}
else
{
@@ -38,18 +59,38 @@ float Shadow(vec4 ShadowCoord)
void main()
{
//Fixa så den bara gör detta om modellen har en blend map
//vvvvvv
vec4 Blend = texture2D(BlendMap, Input.TextureCoord.st );
vec4 AsphaltTexel = texture2D(AsphaltTexture, Input.TextureCoord.st * texScale);
vec4 GrassTexel = texture2D(GrassTexture, Input.TextureCoord.st * texScale);
vec4 SandTexel = texture2D(SandTexture, Input.TextureCoord.st * texScale);
//Mix the Terrain-textures together
AsphaltTexel *= Blend.r;
GrassTexel = mix(AsphaltTexel, GrassTexel, Blend.g);
vec4 tex = mix(GrassTexel, SandTexel, Blend.b);
//^^^^^^
//Fixa så den bara gör detta om modellen har en blend map
// Diffuse Texture
frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord) * Shadow(Input.ShadowCoord);
// G-buffer Position
frag_Position = vec4(Input.Position.xyz, 1.0);
// G-buffer Normal
mat3 TBN = transpose(mat3(Input.Tangent, Input.BiTangent, Input.Normal));
mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal);
frag_Normal = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Diffuse = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Normal = vec4(Input.Normal, 0.0);
// Diffuse Texture
//frag_Diffuse = tex;
frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord) * Shadow(Input.ShadowCoord, vec3(frag_Normal));
//G-buffer Specular
frag_specular = texture(SpecularMapTexture, Input.TextureCoord);
frag_Specular = texture(SpecularMapTexture, Input.TextureCoord);
}
+10 -23
View File
@@ -2,6 +2,7 @@
layout (binding=0) uniform sampler2D PositionTexture;
layout (binding=1) uniform sampler2D NormalsTexture;
layout (binding=2) uniform sampler2D SpecularTexture;
uniform vec2 ViewportSize;
uniform mat4 MVP;
@@ -17,12 +18,14 @@ uniform vec3 CameraPosition;
uniform float ConstantAttenuation;
uniform float LinearAttenuation;
uniform float QuadraticAttenuation;
uniform float LightRadius;
const vec3 ks = vec3(1.0, 1.0, 1.0);
const vec3 kd = vec3(1.0, 1.0, 1.0);
const vec3 ka = vec3(1.0, 1.0, 1.0);
const float kshine = 1.0;
in VertexData
{
vec3 Position;
@@ -31,7 +34,7 @@ in VertexData
out vec4 FragColor;
vec4 phong(vec3 position, vec3 normal)
vec4 phong(vec3 position, vec3 normal, vec3 specular)
{
// Diffuse
vec3 lightPos = vec3(V * vec4(lp, 1.0));
@@ -46,32 +49,15 @@ vec4 phong(vec3 position, vec3 normal)
vec3 surfaceToViewer = normalize(-position);
vec3 halfWay = normalize(surfaceToViewer + directionToLight);
float dotSpecular = max(dot(halfWay, normal), 0.0);
float specularFactor = pow(dotSpecular, specularExponent * 2.0);
vec3 Is = ks * ls * specularFactor;
float specularFactor = pow(dotSpecular, specularExponent);
vec3 Is = specular.r * ls * specularFactor;
//Attenuation
float dist = distance(lightPos, position);
//float attenuation = -log(min(1.0, dist / LightRadius));
float attenuation = 1.0 / (ConstantAttenuation + (LinearAttenuation * dist) + (QuadraticAttenuation * dist * dist));
float attenuation = pow(max(0.0f, 1.0 - (dist / LightRadius)), 2);
//float attenuation = 1.0 / (1.0 - 0.0001 * pow(dist, 2));
//float attenuation = clamp(0.0, 1.0, 1.0 / (0.001 + (0.001 * dist) + (0.001 * dist * dist)));
//float attenuation = 1.0 / dot(directionToLight, directionToLight);
//float att_s = 5;
//float attenuation = pow(dist, 2) / pow(5.0, 2);
//attenuation = 1.0 / (1.0 + attenuation * att_s);
//att_s = 1.0 / (1.0 + att_s);
//attenuation = attenuation / (1.0 - att_s);
//float radius = 5.0;
//float alpha = dist / radius;
//float dampingFactor = 1.0 - pow(alpha, 3);
return vec4((Id + Is) * attenuation, 1.0);
return vec4((Id) * attenuation, Is.r * attenuation);
}
void main()
@@ -79,7 +65,8 @@ void main()
vec2 TextureCoord = gl_FragCoord.xy / ViewportSize;
vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
vec4 SpecularTexel = texture(SpecularTexture, TextureCoord);
FragColor = phong(vec3(PositionTexel), vec3(NormalTexel));
FragColor = phong(vec3(PositionTexel), vec3(NormalTexel), vec3(SpecularTexel));
//FragColor = NormalTexel;
}
+61
View File
@@ -0,0 +1,61 @@
#version 430
layout (binding=0) uniform sampler2D PositionTexture;
layout (binding=1) uniform sampler2D NormalsTexture;
layout (binding=2) uniform sampler2D SpecularTexture;
uniform vec2 ViewportSize;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform vec3 CameraPosition;
uniform vec3 directionToSun;
const vec3 ks = vec3(1.0, 1.0, 1.0);
const vec3 kd = vec3(1.0, 1.0, 1.0);
const vec3 ka = vec3(1.0, 1.0, 1.0);
const float kshine = 1.0;
const vec3 SunDiffuseLight = vec3(0.3, 0.3, 0.3);
const vec3 SunSpecularLight = vec3(1.0, 1.0, 1.0);
const vec3 SunPos = directionToSun*vec3(100);
const float specularExponent = 5;
in VertexData
{
vec3 Position;
vec2 TextureCoord;
} Input;
out vec4 FragColor;
vec4 phong(vec3 position, vec3 normal, vec3 specular)
{
//Diffuse Sunlight
vec3 directionToLight = normalize(vec3(V * vec4(directionToSun, 0.0)));
float dotProdLight = dot(directionToLight, normal);
dotProdLight = max(dotProdLight, 0.0);
vec3 sId = kd * SunDiffuseLight * dotProdLight;
//Specular Sunlight
vec3 surfaceToViewer = normalize(-position);
vec3 halfWay = normalize(surfaceToViewer + directionToLight);
float dotSpecular = max(dot(halfWay, normal), 0.0);
float specularFactorSun = pow(dotSpecular, specularExponent);
vec3 sIs = specular.r * SunSpecularLight * specularFactorSun;
return vec4((sId), sIs.r);
}
void main()
{
vec2 TextureCoord = gl_FragCoord.xy / ViewportSize;
vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
vec4 SpecularTexel = texture(SpecularTexture, TextureCoord);
FragColor = phong(vec3(PositionTexel), vec3(normalize(NormalTexel)), vec3(SpecularTexel));
//FragColor = NormalTexel;
}
+21
View File
@@ -0,0 +1,21 @@
#version 430
uniform mat4 MVP;
layout (location = 0) in vec3 Position;
layout (location = 2) in vec2 TextureCoord;
uniform mat4 depthBiasMVP;
out VertexData
{
vec3 Position;
vec2 TextureCoord;
} Output;
void main()
{
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position;
Output.TextureCoord = (vec2(Position) + 1.0) / 2.0;
}
+8 -4
View File
@@ -12,13 +12,15 @@ class World;
class System
{
public:
System(World* world, std::shared_ptr<EventBroker> eventBroker)
System(World* world, std::shared_ptr<EventBroker> eventBroker, std::shared_ptr<ResourceManager> resourceManager)
: m_World(world)
, EventBroker(eventBroker) { }
, EventBroker(eventBroker)
, ResourceManager(resourceManager)
{ }
virtual ~System() { }
virtual void RegisterComponents(ComponentFactory* cf) { }
virtual void RegisterResourceTypes(ResourceManager* rm) { }
virtual void RegisterResourceTypes(std::shared_ptr<::ResourceManager> rm) { }
virtual void Initialize() { }
@@ -30,13 +32,15 @@ public:
// Called when a component is created
virtual void OnComponentCreated(std::string type, std::shared_ptr<Component> component) { }
// Called when a component is removed
virtual void OnComponentRemoved(std::string type, Component* component) { }
virtual void OnComponentRemoved(EntityID entity, std::string type, Component* component) { }
// Called when components are committed to an entity
virtual void OnEntityCommit(EntityID entity) { }
virtual void OnEntityRemoved(EntityID entity) { }
protected:
World* m_World;
std::shared_ptr<EventBroker> EventBroker;
std::shared_ptr<ResourceManager> ResourceManager;
};
class SystemFactory : public Factory<System*> { };
+22
View File
@@ -0,0 +1,22 @@
#include "PrecompiledHeader.h"
#include "DamageSystem.h"
#include "World.h"
void Systems::DamageSystem::RegisterComponents( ComponentFactory* cf )
{
cf->Register<Components::Health>([]() { return new Components::Health(); });
}
void Systems::DamageSystem::Initialize()
{
EVENT_SUBSCRIBE_MEMBER(m_EDamage, &Systems::DamageSystem::OnDamage);
}
bool Systems::DamageSystem::OnDamage( const Events::Damage &event )
{
auto health = m_World->GetComponent<Components::Health>(event.Entity);
health->health -= event.damage;
LOG_INFO("Damaged entity %i, Health left: %f", event.Entity, health->health);
return true;
}
+32
View File
@@ -0,0 +1,32 @@
#ifndef DamageSystem_h__
#define DamageSystem_h__
#include "System.h"
#include "Components/Health.h"
#include "Events/Damage.h"
namespace Systems
{
class DamageSystem : public System
{
public:
DamageSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager) { }
void Initialize() override;
void RegisterComponents(ComponentFactory* cf) override;
EventRelay<DamageSystem, Events::Damage> m_EDamage;
bool OnDamage(const Events::Damage &event);
private:
};
}
#endif // DamageSystem_h__
+3 -2
View File
@@ -12,8 +12,9 @@ namespace Systems
class DebugSystem : public System
{
public:
DebugSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
DebugSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void Initialize() override;
+3 -2
View File
@@ -12,8 +12,9 @@ namespace Systems
class FreeSteeringSystem : public System
{
public:
FreeSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
FreeSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
+3 -2
View File
@@ -11,8 +11,9 @@ namespace Systems
class HelicopterSteeringSystem : public System
{
public:
HelicopterSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
HelicopterSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
+3 -2
View File
@@ -25,8 +25,9 @@ namespace Systems
class InputSystem : public System
{
public:
InputSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
InputSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
+104 -35
View File
@@ -7,11 +7,32 @@
void Systems::ParticleSystem::Initialize()
{
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
tempSpawnedExplosions = false;
EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Systems::ParticleSystem::OnKeyUp);
}
void Systems::ParticleSystem::Update(double dt)
{
std::map<EntityID, double>::iterator it;
for(it = m_ExplosionEmitters.begin(); it != m_ExplosionEmitters.end();)
{
EntityID explosionID = it->first;
double spawnTime = it->second;
double timeLived = glfwGetTime() - spawnTime;
auto eComp = m_World->GetComponent<Components::ParticleEmitter>(explosionID);
if(timeLived > eComp->LifeTime)
{
m_World->RemoveEntity(explosionID);
it = m_ExplosionEmitters.erase(it);
//LOG_INFO("Deleted explosion emitter successfully");
}
else
{
it++;
}
}
}
void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
@@ -101,43 +122,41 @@ void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf)
void Systems::ParticleSystem::SpawnParticles(EntityID emitterID)
{
auto emitterComponent = m_World->GetComponent<Components::ParticleEmitter>(emitterID);
auto emitterTransform = m_World->GetComponent<Components::Transform>(emitterID);
glm::vec3 emitterPos = m_TransformSystem->AbsolutePosition(emitterID);
glm::quat emitterOrientation = emitterTransform->Orientation;
auto eComponent = m_World->GetComponent<Components::ParticleEmitter>(emitterID);
auto eTransform = m_World->GetComponent<Components::Transform>(emitterID);
glm::vec3 ePosition = m_TransformSystem->AbsolutePosition(emitterID);
glm::quat eOrientation = eTransform->Orientation;
glm::vec3 paticleSpeed = glm::vec3(eComponent->Speed);
float tempSpeed = 4;
glm::vec3 speed = glm::vec3(tempSpeed);
for(int i = 0; i < emitterComponent->SpawnCount; i++)
for(int i = 0; i < eComponent->SpawnCount; i++)
{
auto ent = m_World->CloneEntity(emitterComponent->ParticleTemplate);
auto particleEntity = m_World->CloneEntity(eComponent->ParticleTemplate);
auto particleTransform = m_World->GetComponent<Components::Transform>(ent);
particleTransform->Position = emitterPos;
auto particleTransform = m_World->GetComponent<Components::Transform>(particleEntity);
particleTransform->Position = ePosition;
particleTransform->Orientation = emitterOrientation;
particleTransform->Orientation = eOrientation;
//The emitter's orientation as "start value" times the default direction for emitter. Times the speed, and then rotate on x and y axis with the randomized spread angle.
float spreadAngle = emitterComponent->SpreadAngle;
particleTransform->Velocity = emitterOrientation * glm::vec3(0, 0, -1) * speed *
float spreadAngle = eComponent->SpreadAngle;
particleTransform->Velocity = eOrientation * glm::vec3(0, 0, -1) * paticleSpeed *
glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(1, 0, 0))) *
glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 1, 0))) *
glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 0, 1)));
auto particle = m_World->AddComponent<Components::Particle>(ent);
particle->LifeTime = emitterComponent->LifeTime;
particle->ScaleSpectrum = emitterComponent->ScaleSpectrum;
particle->VelocitySpectrum.push_back(particleTransform->Velocity);
auto particleComponent = m_World->AddComponent<Components::Particle>(particleEntity);
particleComponent->LifeTime = eComponent->LifeTime - 0.5;
particleComponent->ScaleSpectrum = eComponent->ScaleSpectrum;
particleComponent->VelocitySpectrum.push_back(particleTransform->Velocity);
if (emitterComponent->ScaleSpectrum.size() > 0)
if (eComponent->ScaleSpectrum.size() > 0)
{
if (emitterComponent->ScaleSpectrum.size() > 1)
if (eComponent->ScaleSpectrum.size() > 1)
{
particle->ScaleSpectrum = emitterComponent->ScaleSpectrum;
particleComponent->ScaleSpectrum = eComponent->ScaleSpectrum;
}
else
{
particleTransform->Scale = emitterComponent->ScaleSpectrum[0];
particleTransform->Scale = eComponent->ScaleSpectrum[0];
}
}
else
@@ -145,23 +164,22 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID)
particleTransform->Scale = glm::vec3(1, 1, 1);
}
if(emitterComponent->UseGoalVelocity)
particle->VelocitySpectrum.push_back(emitterComponent->GoalVelocity);
particle->OrientationSpectrum = emitterComponent->OrientationSpectrum;
if(particle->OrientationSpectrum.size() != 0)
particleTransform->Orientation = glm::angleAxis(0.f, particle->OrientationSpectrum[0]);
particle->AngularVelocitySpectrum = emitterComponent->AngularVelocitySpectrum;
if(eComponent->UseGoalVelocity)
particleComponent->VelocitySpectrum.push_back(eComponent->GoalVelocity);
particleComponent->OrientationSpectrum = eComponent->OrientationSpectrum;
if(particleComponent->OrientationSpectrum.size() != 0)
particleTransform->Orientation = glm::angleAxis(0.f, particleComponent->OrientationSpectrum[0]);
particleComponent->AngularVelocitySpectrum = eComponent->AngularVelocitySpectrum;
ParticleData data;
data.ParticleID = ent;
data.ParticleID = particleEntity;
data.SpawnTime = glfwGetTime();
if (particle->AngularVelocitySpectrum.size() != 0)
data.AngularVelocity = particle->AngularVelocitySpectrum[0];
if (particle->OrientationSpectrum.size() != 0)
data.Orientation = particle->OrientationSpectrum[0];
else data.Orientation = emitterOrientation * glm::vec3(0,0,-1);
if (particleComponent->AngularVelocitySpectrum.size() != 0)
data.AngularVelocity = particleComponent->AngularVelocitySpectrum[0];
if (particleComponent->OrientationSpectrum.size() != 0)
data.Orientation = particleComponent->OrientationSpectrum[0];
else data.Orientation = eOrientation * glm::vec3(0,0,-1);
m_ParticleEmitter[emitterID].push_back(data);
}
}
@@ -206,3 +224,54 @@ void Systems::ParticleSystem::ScalarInterpolation(double timeProgress, std::vect
dAlpha *= -1;
alpha = spectrum[0] + dAlpha * timeProgress;
}
void Systems::ParticleSystem::CreateExplosion(glm::vec3 _pos, double _lifeTime, int _particlesToSpawn, std::string _spritePath, glm::quat _relativeUpOri, float _speed, float _spreadAngle, float _particleScale)
{
auto explosion = m_World->CreateEntity();
auto emitter = m_World->AddComponent<Components::ParticleEmitter>(explosion);
emitter->LifeTime = _lifeTime;
emitter->SpawnCount = _particlesToSpawn;
emitter->Speed = _speed;
emitter->SpreadAngle = _spreadAngle;
emitter->SpawnFrequency = _lifeTime + 20; //temp
// emitter->UseGoalVelocity = true;
// emitter->GoalVelocity = glm::vec3(0,-_speed, 0);
m_World->CommitEntity(explosion);
auto particleEnt = m_World->CreateEntity();
auto TEMP = m_World->AddComponent<Components::Transform>(particleEnt);
TEMP->Scale = glm::vec3(0);
auto spriteComponent = m_World->AddComponent<Components::Sprite>(particleEnt);
spriteComponent->SpriteFile = _spritePath;
m_World->CommitEntity(particleEnt);
emitter->ParticleTemplate = particleEnt;
auto transform = m_World->AddComponent<Components::Transform>(explosion);
transform->Position = _pos;
transform->Orientation = _relativeUpOri;
SpawnParticles(explosion);
m_ExplosionEmitters[explosion] = glfwGetTime();
}
bool Systems::ParticleSystem::OnKeyUp(const Events::KeyUp &e)
{
if(!tempSpawnedExplosions)
{
if (e.KeyCode == GLFW_KEY_B)
{
tempSpawnedExplosions = true;
CreateExplosion(
glm::vec3(0, 10, 0),
0.5,
60,
"Textures/Sprites/NewtonTreeDeleteASAPPlease.png",
glm::angleAxis(glm::pi<float>()/2, glm::vec3(1,0,0)),
40,
glm::pi<float>(),
0.5f
);
}
}
return true;
}
+16 -4
View File
@@ -6,8 +6,9 @@
#include "Components/Transform.h"
#include "Components/ParticleEmitter.h"
#include "Components/Particle.h"
#include "Components/Model.h"
#include "Components/PointLight.h"
#include "Components/Sprite.h"
#include "EventBroker.h"
#include "Events/KeyUp.h"
#include "Color.h"
#include <GLFW/glfw3.h>
@@ -26,13 +27,19 @@ namespace Systems
class ParticleSystem : public System
{
public:
ParticleSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
ParticleSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
void Initialize() override;
void CreateExplosion(glm::vec3 _pos, double _lifeTime, int _particlesToSpawn, std::string _spritePath, glm::quat _relativeUpOri, float _speed, float _spreadAngle, float _particleScale);
virtual bool OnCommand(const Events::KeyUp &event) { return false; }
private:
void SpawnParticles(EntityID emitterID);
float RandomizeAngle(float spreadAngle);
@@ -43,8 +50,13 @@ private:
void Billboard();
std::map<EntityID, std::list<ParticleData>> m_ParticleEmitter;
std::map<EntityID, double> m_TimeSinceLastSpawn;
std::map<EntityID, double> m_ExplosionEmitters;
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
bool tempSpawnedExplosions;
EventRelay<ParticleSystem, Events::KeyUp> m_EKeyUp;
bool OnKeyUp(const Events::KeyUp &e);
};
+290 -53
View File
@@ -36,8 +36,10 @@ void Systems::PhysicsSystem::Initialize()
EVENT_SUBSCRIBE_MEMBER(m_ESetVelocity, &Systems::PhysicsSystem::OnSetVelocity);
EVENT_SUBSCRIBE_MEMBER(m_EApplyForce, &Systems::PhysicsSystem::OnApplyForce);
EVENT_SUBSCRIBE_MEMBER(m_EApplyPointImpulse, &Systems::PhysicsSystem::OnApplyPointImpulse);
EVENT_SUBSCRIBE_MEMBER(m_EEnableCollisions, &Systems::PhysicsSystem::OnEnableCollisions);
EVENT_SUBSCRIBE_MEMBER(m_EDisableCollisions, &Systems::PhysicsSystem::OnDisableCollisions);
hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer
hkMemorySystem::FrameInfo finfo(10000 * 1024); // Allocate 10MB of Physics solver buffer
hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo);
hkBaseSystem::init(memoryRouter, HavokErrorReport);
@@ -75,10 +77,10 @@ void Systems::PhysicsSystem::Initialize()
worldInfo.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM);
worldInfo.m_gravity = hkVector4(0.0f, -9.82f, 0.0f);
worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_DO_NOTHING;
worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_FIX_ENTITY;
// You must specify the size of the broad phase - objects should not be simulated outside this region
worldInfo.setBroadPhaseWorldSize(1000.0f);
worldInfo.setBroadPhaseWorldSize(1500.0f);
m_PhysicsWorld = new hkpWorld(worldInfo);
// When the simulation type is SIMULATION_TYPE_MULTITHREADED, in the debug build, the sdk performs checks
@@ -102,14 +104,40 @@ void Systems::PhysicsSystem::Initialize()
m_Context = new hkpPhysicsContext;
hkpPhysicsContext::registerAllPhysicsProcesses(); // all the physics viewers
m_Context->addWorld(m_PhysicsWorld); // add the physics world so the viewers can see it
SetupVisualDebugger(m_Context);
m_CollisionFilter = new hkpGroupFilter();
m_PhysicsWorld->setCollisionFilter( m_CollisionFilter );
m_PhysicsWorld->unmarkForWrite();
m_collisionResolution = new MyCollisionResolution;
m_collisionResolution = new MyCollisionResolution(this);
}
enum
{
GROUND_LAYER = 1,
VEHICLE1_LAYER = 2,
VEHICLE2_LAYER = 3,
EXPLOSION_LAYER = 4,
};
/*
{
Events::DisableCollisions e;
e.Layer1 = GROUND_LAYER;
e.Layer2 = EXPLOSION_LAYER;
EventBroker->Publish(e);
}*/
/*{
Events::DisableCollisions e;
e.Layer1 = VEHICLE1_LAYER;
e.Layer2 = EXPLOSION_LAYER;
EventBroker->Publish(e);
}
{
Events::DisableCollisions e;
e.Layer1 = VEHICLE2_LAYER;
e.Layer2 = EXPLOSION_LAYER;
EventBroker->Publish(e);
}*/
}
void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf)
@@ -122,6 +150,7 @@ void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf)
cf->Register<Components::MeshShape>([]() { return new Components::MeshShape(); });
cf->Register<Components::HingeConstraint>([]() { return new Components::HingeConstraint(); });
cf->Register<Components::WheelPair>([]() { return new Components::WheelPair(); });
cf->Register<Components::TankShell>([]() { return new Components::TankShell(); });
}
void Systems::PhysicsSystem::Update(double dt)
@@ -159,7 +188,6 @@ void Systems::PhysicsSystem::Update(double dt)
m_PhysicsWorld->unmarkForWrite();
}
}
static const double timestep = 1 / 60.0;
@@ -230,6 +258,10 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
{
auto tempalteComponent = m_World->GetComponent<Components::Template>(entity);
if(tempalteComponent)
return;
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
if (!transformComponent)
return;
@@ -255,21 +287,36 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
}
auto physicsComponent = m_World->GetComponent<Components::Physics>(entity);
if (physicsComponent)
if (physicsComponent && m_Shapes[entity].size() > 0)
{
hkpShape* shape;
if(entityParent != entity)
{
LOG_ERROR("Entity: %i , Only the baseparent can have a PhysicsComponent", entity);
return;
}
hkpShape* shape;
if(! physicsComponent->Static) // Not static
{
hkArray<hkpShape*> shapeArray;
for (auto &shapeData : m_Shapes[entity])
{
shapeArray.pushBack(shapeData.Shape);
auto childTransformComponent = m_World->GetComponent<Components::Transform>(shapeData.Entity);
hkpShape* shape;
if(shapeData.ConvexShape != nullptr)
{
hkQsTransform transform( GLMVEC3_TO_HKVECTOR4(childTransformComponent->Position), GLMQUAT_TO_HKQUATERNION(childTransformComponent->Orientation), GLMVEC3_TO_HKVECTOR4(childTransformComponent->Scale));
hkpConvexTransformShape* transformedBoxShape = new hkpConvexTransformShape( shapeData.ConvexShape, transform );
shapeArray.pushBack(transformedBoxShape);
}
if(shapeData.Shape != nullptr)
{
shapeArray.pushBack(shapeData.Shape);
}
}
@@ -277,15 +324,28 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
hkpListShape* listShape = new hkpListShape(shapeArray.begin(), shapeArray.getSize(), hkpShapeContainer::REFERENCE_POLICY_INCREMENT);
// Save the listShape for further use
m_ListShapes[entity] = listShape;
//shape = listShape;
hkMassProperties massProperties;
hkpBoxShape* box = new hkpBoxShape(listShape->m_aabbHalfExtents, 0.0f);
shape = new hkpBvShape(listShape, box);
hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape, physicsComponent->Mass, massProperties);
for (auto &shapeData : m_Shapes[entity])
{
if(shapeData.ConvexShape != nullptr)
{
shapeData.ConvexShape->removeReference();
}
if(shapeData.Shape != nullptr)
{
shapeData.Shape->removeReference();
}
}
// Clean up for less memory usage
m_Shapes.erase(entity);
hkMassProperties massProperties;
hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape, physicsComponent->Mass, massProperties);
hkpRigidBodyCinfo rigidBodyInfo;
{
@@ -298,8 +358,22 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
rigidBodyInfo.m_rotation.set(rotation(0), rotation(1), rotation(2), rotation(3));
rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor;
//rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; //HACK: CENTER OF MASS ALWAYS IN THE CENTER
if(physicsComponent->CalculateCenterOfMass)
physicsComponent->CenterOfMass = HKVECTOR4_TO_GLMVEC3(massProperties.m_centerOfMass);
rigidBodyInfo.m_centerOfMass = GLMVEC3_TO_HKVECTOR4(physicsComponent->CenterOfMass);
rigidBodyInfo.m_mass = massProperties.m_mass;
rigidBodyInfo.m_linearVelocity = GLMVEC3_TO_HKVECTOR4(physicsComponent->InitialLinearVelocity);
rigidBodyInfo.m_angularVelocity = GLMVEC3_TO_HKVECTOR4(physicsComponent->InitialAngularVelocity);
rigidBodyInfo.m_linearDamping = physicsComponent->LinearDamping;
rigidBodyInfo.m_angularDamping = physicsComponent->AngularDamping;
rigidBodyInfo.m_gravityFactor = physicsComponent->GravityFactor;
rigidBodyInfo.m_linearDamping = physicsComponent->LinearDamping;
rigidBodyInfo.m_friction = physicsComponent->Friction;
rigidBodyInfo.m_restitution = physicsComponent->Restitution;
rigidBodyInfo.m_maxLinearVelocity = physicsComponent->MaxLinearVelocity;
rigidBodyInfo.m_maxAngularVelocity = physicsComponent->MaxAngularVelocity;
rigidBodyInfo.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(physicsComponent->CollisionLayer, physicsComponent->CollisionSystemGroup, physicsComponent->CollisionSubSystemId, physicsComponent->CollisionSubSystemDontCollideWith);
rigidBodyInfo.m_enableDeactivation = false;
}
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
@@ -323,10 +397,13 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
m_PhysicsWorld->markForWrite();
vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels);
// Add the vehicle's entities and phantoms to the world
rigidBody->addContactListener( m_collisionResolution );
if(physicsComponent->CollisionEvent)
{
rigidBody->addContactListener( m_collisionResolution );
}
m_Vehicles[entity]->addToWorld(m_PhysicsWorld);
m_RigidBodies[entity] = rigidBody;
m_collisionResolution->m_RigidBodies[rigidBody] = entity;
m_RigidBodyEntities[rigidBody] = entity;
// The vehicle is an action
@@ -341,10 +418,13 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
else
{
m_PhysicsWorld->markForWrite();
rigidBody->addContactListener( m_collisionResolution );
if(physicsComponent->CollisionEvent)
{
rigidBody->addContactListener( m_collisionResolution );
}
m_PhysicsWorld->addEntity(rigidBody);
m_RigidBodies[entity] = rigidBody;
m_collisionResolution->m_RigidBodies[rigidBody] = entity;
m_RigidBodyEntities[rigidBody] = entity;
m_PhysicsWorld->unmarkForWrite();
shape->removeReference();
@@ -367,16 +447,39 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
hkVector4 scale = GLMVEC3_TO_HKVECTOR4(childTransformComponent->Scale);
hkQsTransform transform(position, rotation, scale);
staticCompoundShape->addInstance(shapeData.Shape, transform);
if(shapeData.ConvexShape != nullptr)
{
staticCompoundShape->addInstance(shapeData.ConvexShape, transform);
}
if(shapeData.Shape != nullptr)
{
staticCompoundShape->addInstance(shapeData.Shape, transform);
}
}
// This must be called after adding the instances and before using the shape.
staticCompoundShape->bake();
shape = staticCompoundShape;
m_Shapes.erase(entity);
hkMassProperties massProperties;
hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape, physicsComponent->Mass, massProperties);
for (auto &shapeData : m_Shapes[entity])
{
if(shapeData.ConvexShape != nullptr)
{
shapeData.ConvexShape->removeReference();
}
if(shapeData.Shape != nullptr)
{
shapeData.Shape->removeReference();
}
}
m_Shapes.erase(entity);
hkpRigidBodyCinfo rigidBodyInfo;
{
rigidBodyInfo.m_shape = shape;
@@ -388,8 +491,22 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
rigidBodyInfo.m_rotation.set(rotation(0), rotation(1), rotation(2), rotation(3));
rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor;
//rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; //HACK: CENTER OF MASS ALWAYS IN THE CENTER
if(physicsComponent->CalculateCenterOfMass)
physicsComponent->CenterOfMass = HKVECTOR4_TO_GLMVEC3(massProperties.m_centerOfMass);
rigidBodyInfo.m_centerOfMass = GLMVEC3_TO_HKVECTOR4(physicsComponent->CenterOfMass);
rigidBodyInfo.m_mass = massProperties.m_mass;
rigidBodyInfo.m_linearVelocity = GLMVEC3_TO_HKVECTOR4(physicsComponent->InitialLinearVelocity);
rigidBodyInfo.m_angularVelocity = GLMVEC3_TO_HKVECTOR4(physicsComponent->InitialAngularVelocity);
rigidBodyInfo.m_linearDamping = physicsComponent->LinearDamping;
rigidBodyInfo.m_angularDamping = physicsComponent->AngularDamping;
rigidBodyInfo.m_gravityFactor = physicsComponent->GravityFactor;
rigidBodyInfo.m_linearDamping = physicsComponent->LinearDamping;
rigidBodyInfo.m_friction = physicsComponent->Friction;
rigidBodyInfo.m_restitution = physicsComponent->Restitution;
rigidBodyInfo.m_maxLinearVelocity = physicsComponent->MaxLinearVelocity;
rigidBodyInfo.m_maxAngularVelocity = physicsComponent->MaxAngularVelocity;
rigidBodyInfo.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(physicsComponent->CollisionLayer, physicsComponent->CollisionSystemGroup, physicsComponent->CollisionSubSystemId, physicsComponent->CollisionSubSystemDontCollideWith);
rigidBodyInfo.m_enableDeactivation = false;
}
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
@@ -397,30 +514,57 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
m_PhysicsWorld->markForWrite();
m_PhysicsWorld->addEntity(rigidBody);
m_RigidBodies[entity] = rigidBody;
m_collisionResolution->m_RigidBodies[rigidBody] = entity;
m_RigidBodyEntities[rigidBody] = entity;
m_PhysicsWorld->unmarkForWrite();
shape->removeReference();
rigidBody->removeReference();
}
}
else
{
//TODO: COMMENT THIS SECTION
if(sphereComponent)
{
hkpSphereShape* sphereShape = new hkpSphereShape(sphereComponent->Radius);
//sphereShape->removeReference();
hkQsTransform transform( GLMVEC3_TO_HKVECTOR4(transformComponent->Position), GLMQUAT_TO_HKQUATERNION(transformComponent->Orientation), GLMVEC3_TO_HKVECTOR4(transformComponent->Scale));
hkpConvexTransformShape* transformedSphereShape = new hkpConvexTransformShape( sphereShape, transform );
auto triggerComponent = m_World->GetComponent<Components::Trigger >(entityParent);
if(triggerComponent)
{
auto parentTransformComponent = m_World->GetComponent<Components::Transform >(entityParent);
m_Shapes[entityParent].push_back(ShapeArrayData(entity, transformedSphereShape));
PhantomCallbackShape* phantom = new PhantomCallbackShape(this);
hkpBvShape* phantomShape = new hkpBvShape(sphereShape, phantom);
sphereShape->removeReference();
hkpRigidBodyCinfo rigidBodyInfo;
{
rigidBodyInfo.m_shape = phantomShape;
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
rigidBodyInfo.m_position = GLMVEC3_TO_HKVECTOR4(parentTransformComponent->Position);
rigidBodyInfo.m_mass = 1;
rigidBodyInfo.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(4, 0, 0, 0);
}
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
m_PhysicsWorld->markForWrite();
m_PhysicsWorld->addEntity(rigidBody);
m_PhysicsWorld->unmarkForWrite();
m_RigidBodies[entityParent] = rigidBody;
m_RigidBodyEntities[rigidBody] = entityParent;
phantomShape->removeReference();
phantom->removeReference();
sphereShape->removeReference();
rigidBody->removeReference();
}
else
{
m_Shapes[entityParent].push_back(ShapeArrayData(entity, sphereShape, nullptr));
}
}
//TODO: COMMENT THIS SECTION
else if(boxComponent)
@@ -428,16 +572,49 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
hkReal thickness = 0.05;
hkpBoxShape* boxShape = new hkpBoxShape(hkVector4(boxComponent->Width- thickness, boxComponent->Height -thickness, boxComponent->Depth - thickness), thickness);
hkQsTransform transform( GLMVEC3_TO_HKVECTOR4(transformComponent->Position), GLMQUAT_TO_HKQUATERNION(transformComponent->Orientation), GLMVEC3_TO_HKVECTOR4(transformComponent->Scale));
hkpConvexTransformShape* transformedBoxShape = new hkpConvexTransformShape( boxShape, transform );
m_Shapes[entityParent].push_back(ShapeArrayData(entity, transformedBoxShape));
boxShape->removeReference();
auto triggerComponent = m_World->GetComponent<Components::Trigger >(entityParent);
if(triggerComponent)
{
auto parentTransformComponent = m_World->GetComponent<Components::Transform >(entityParent);
PhantomCallbackShape* phantom = new PhantomCallbackShape(this);
hkpBvShape* phantomShape = new hkpBvShape(boxShape, phantom);
hkpRigidBodyCinfo rigidBodyInfo;
{
rigidBodyInfo.m_shape = phantomShape;
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
rigidBodyInfo.m_position = GLMVEC3_TO_HKVECTOR4(parentTransformComponent->Position);
rigidBodyInfo.m_mass = 1;
rigidBodyInfo.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(4, 0, 0, 0); // HACK:
}
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
m_PhysicsWorld->markForWrite();
m_PhysicsWorld->addEntity(rigidBody);
m_PhysicsWorld->unmarkForWrite();
m_RigidBodies[entityParent] = rigidBody;
m_RigidBodyEntities[rigidBody] = entityParent;
phantomShape->removeReference();
boxShape->removeReference();
phantom->removeReference();
rigidBody->removeReference();
}
else
{
m_Shapes[entityParent].push_back(ShapeArrayData(entity, boxShape, nullptr));
}
}
else if(meshShapeComponent)
{
std::vector<hkReal>* vertices = new std::vector<hkReal>;
std::vector<hkUint16>* vertexIndices = new std::vector<hkUint16>;
auto meshShape = m_World->GetResourceManager()->Load<OBJ>("OBJ", meshShapeComponent->ResourceName);
auto meshShape = ResourceManager->Load<OBJ>("OBJ", meshShapeComponent->ResourceName);
for (auto &vertex : meshShape->Vertices)
{
@@ -480,12 +657,9 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
m_ExtendedMeshShapes[entity].Code = code;
m_ExtendedMeshShapes[entity].MoppShape = moppShape;
m_Shapes[entityParent].push_back(ShapeArrayData(entity, moppShape)); //HACK: Should maybe have transform, not sure yet
m_Shapes[entityParent].push_back(ShapeArrayData(entity, nullptr, moppShape));
}
}
}
void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent)
@@ -498,12 +672,6 @@ void Systems::PhysicsSystem::OnComponentCreated(std::string type, std::shared_pt
}
void Systems::PhysicsSystem::OnComponentRemoved(std::string type, Component* component)
{
}
void Systems::PhysicsSystem::SetupVisualDebugger(hkpPhysicsContext* worlds)
{
// Setup the visual debugger
@@ -556,24 +724,93 @@ bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event)
bool Systems::PhysicsSystem::OnSetVelocity( const Events::SetVelocity &event )
{
m_PhysicsWorld->markForWrite();
m_RigidBodies[event.Entity]->setLinearVelocity(GLMVEC3_TO_HKVECTOR4(event.Velocity));
m_PhysicsWorld->unmarkForWrite();
if(m_RigidBodies.find(event.Entity) != m_RigidBodies.end())
{
m_PhysicsWorld->markForWrite();
m_RigidBodies[event.Entity]->setLinearVelocity(GLMVEC3_TO_HKVECTOR4(event.Velocity));
m_PhysicsWorld->unmarkForWrite();
}
return true;
}
bool Systems::PhysicsSystem::OnApplyForce(const Events::ApplyForce &event)
{
m_PhysicsWorld->markForWrite();
m_RigidBodies[event.Entity]->applyForce(event.DeltaTime, GLMVEC3_TO_HKVECTOR4(event.Force));
m_PhysicsWorld->unmarkForWrite();
if(m_RigidBodies.find(event.Entity) != m_RigidBodies.end())
{
m_PhysicsWorld->markForWrite();
m_RigidBodies[event.Entity]->applyForce(event.DeltaTime, GLMVEC3_TO_HKVECTOR4(event.Force));
m_PhysicsWorld->unmarkForWrite();
}
return true;
}
bool Systems::PhysicsSystem::OnApplyPointImpulse( const Events::ApplyPointImpulse &event )
{
if(m_RigidBodies.find(event.Entity) != m_RigidBodies.end())
{
m_PhysicsWorld->markForWrite();
m_RigidBodies[event.Entity]->applyPointImpulse(GLMVEC3_TO_HKVECTOR4(event.Impulse), GLMVEC3_TO_HKVECTOR4(event.Position));
m_PhysicsWorld->unmarkForWrite();
}
return true;
}
void Systems::PhysicsSystem::OnComponentRemoved(EntityID entity, std::string type, Component* component)
{
if(m_RigidBodies.find(entity) != m_RigidBodies.end())
{
LOG_INFO("Removed Trigger of entity %i", entity);
m_PhysicsWorld->markForWrite();
m_RigidBodyEntities.erase(m_RigidBodies[entity]);
m_PhysicsWorld->removeEntity(m_RigidBodies[entity]);
m_RigidBodies.erase(entity);
m_PhysicsWorld->unmarkForWrite();
}
}
void Systems::PhysicsSystem::OnEntityRemoved( EntityID entity )
{
if(m_RigidBodies.find(entity) != m_RigidBodies.end())
{
LOG_INFO("Removed rigid body of entity %i", entity);
m_PhysicsWorld->markForWrite();
m_RigidBodyEntities.erase(m_RigidBodies[entity]);
if(m_ListShapes.find(entity) != m_ListShapes.end())
{
m_ListShapes[entity]->removeReference();
m_ListShapes.erase(entity);
}
m_PhysicsWorld->removeEntity(m_RigidBodies[entity]);
m_RigidBodies.erase(entity);
m_PhysicsWorld->unmarkForWrite();
}
if(m_Vehicles.find(entity) != m_Vehicles.end())
{
m_PhysicsWorld->markForWrite();
m_Vehicles[entity]->removeFromWorld();
m_PhysicsWorld->unmarkForWrite();
}
}
bool Systems::PhysicsSystem::OnEnableCollisions( const Events::EnableCollisions &e )
{
m_CollisionFilter->enableCollisionsBetween(e.Layer1, e.Layer2);
m_PhysicsWorld->markForWrite();
m_RigidBodies[event.Entity]->applyPointImpulse(GLMVEC3_TO_HKVECTOR4(event.Impulse), GLMVEC3_TO_HKVECTOR4(event.Position));
m_PhysicsWorld->setCollisionFilter(m_CollisionFilter);
m_PhysicsWorld->unmarkForWrite();
return true;
}
bool Systems::PhysicsSystem::OnDisableCollisions( const Events::DisableCollisions &e )
{
m_CollisionFilter->disableCollisionsBetween(e.Layer1, e.Layer2);
m_PhysicsWorld->markForWrite();
m_PhysicsWorld->setCollisionFilter(m_CollisionFilter);
m_PhysicsWorld->unmarkForWrite();
return true;
}
+79 -17
View File
@@ -27,6 +27,7 @@
#include "Events/SetVelocity.h"
#include "Events/ApplyForce.h"
#include "Events/ApplyPointImpulse.h"
#include "Events/Collision.h"
#include "OBJ.h"
// Math and base include
@@ -75,29 +76,79 @@
#include <Physics2012/Dynamics/Collide/ContactListener/hkpContactListener.h>
class MyCollisionResolution: public hkReferencedObject, public hkpContactListener
{
public:
std::unordered_map<hkpRigidBody*, EntityID> m_RigidBodies;
#include <Physics2012/Collide/Agent/CompoundAgent/BvTree/hkpBvTreeAgent.h>
virtual void contactPointCallback( const hkpContactPointEvent& event )
{
EntityID entity1 = m_RigidBodies[event.getBody(0)];
EntityID entity2 = m_RigidBodies[event.getBody(1)];
//LOG_INFO("Entities colliding: %i, %i ", entity1, entity2);
}
};
#include "Components/TankShell.h"
#include <Physics2012/Collide/Shape/Misc/PhantomCallback/hkpPhantomCallbackShape.h>
#include "Events/EnableCollisions.h"
#include "Events/DisableCollisions.h"
#include "Components/Trigger.h"
#include "Components/Template.h"
#include "Events/EnterTrigger.h"
namespace Systems
{
class PhysicsSystem : public System
{
public:
PhysicsSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
class MyCollisionResolution: public hkReferencedObject, public hkpContactListener
{
public:
MyCollisionResolution(Systems::PhysicsSystem* physicsSystem)
: m_PhysicsSystem(physicsSystem) { }
virtual void contactPointCallback( const hkpContactPointEvent& event )
{
EntityID entity1 = m_PhysicsSystem->m_RigidBodyEntities[event.getBody(0)];
EntityID entity2 = m_PhysicsSystem->m_RigidBodyEntities[event.getBody(1)];
Events::Collision e;
e.Entity1 = entity1;
e.Entity2 = entity2;
m_PhysicsSystem->EventBroker->Publish(e);
LOG_INFO("CollisionEvent!");
}
private:
Systems::PhysicsSystem* m_PhysicsSystem;
};
friend class MyCollisionResolution;
class PhantomCallbackShape: public hkpPhantomCallbackShape
{
public:
PhantomCallbackShape(Systems::PhysicsSystem* physicsSystem)
: m_PhysicsSystem(physicsSystem) { }
virtual void phantomEnterEvent( const hkpCollidable* collidableA, const hkpCollidable* collidableB, const hkpCollisionInput& env )
{
EntityID entity1 = m_PhysicsSystem->m_RigidBodyEntities[hkpGetRigidBody(collidableA)];
EntityID entity2 = m_PhysicsSystem->m_RigidBodyEntities[hkpGetRigidBody(collidableB)];
if(m_PhysicsSystem->m_World->ValidEntity(entity1) && m_PhysicsSystem->m_World->ValidEntity(entity2))
{
Events::EnterTrigger e;
e.Entity1 = entity1;
e.Entity2 = entity2;
m_PhysicsSystem->EventBroker->Publish(e);
}
}
virtual void phantomLeaveEvent( const hkpCollidable* collidableA, const hkpCollidable* collidableB )
{
}
private:
Systems::PhysicsSystem* m_PhysicsSystem;
};
friend class PhantomCallbackShape;
PhysicsSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager) { }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
@@ -105,12 +156,14 @@ public:
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
void OnComponentCreated(std::string type, std::shared_ptr<Component> component) override;
void OnComponentRemoved(std::string type, Component* component) override;
void OnComponentRemoved(EntityID entity, std::string type, Component* component) override;
void OnEntityCommit(EntityID entity) override;
void OnEntityRemoved(EntityID entity) override;
private:
double m_Accumulator;
hkpWorld* m_PhysicsWorld;
hkpGroupFilter* m_CollisionFilter;
// Events
EventRelay<PhysicsSystem, Events::TankSteer> m_ETankSteer;
@@ -122,6 +175,12 @@ private:
EventRelay<PhysicsSystem, Events::ApplyPointImpulse> m_EApplyPointImpulse;
bool OnApplyPointImpulse(const Events::ApplyPointImpulse &event);
EventRelay<PhysicsSystem, Events::EnableCollisions> m_EEnableCollisions;
bool OnEnableCollisions(const Events::EnableCollisions &e);
EventRelay<PhysicsSystem, Events::DisableCollisions> m_EDisableCollisions;
bool OnDisableCollisions(const Events::DisableCollisions &e);
void SetUpPhysicsState(EntityID entity, EntityID parent);
void TearDownPhysicsState(EntityID entity, EntityID parent);
@@ -132,6 +191,7 @@ private:
void SetupPhysics(hkpWorld* physicsWorld);
std::unordered_map<EntityID, hkpRigidBody*> m_RigidBodies;
std::unordered_map<hkpRigidBody*, EntityID> m_RigidBodyEntities;
hkJobThreadPool* m_ThreadPool;
hkJobQueue* m_JobQueue;
@@ -146,12 +206,14 @@ private:
struct ShapeArrayData
{
ShapeArrayData(EntityID entity, hkpShape* shape)
ShapeArrayData(EntityID entity, hkpConvexShape* convexShape, hkpShape* shape)
{
Entity = entity;
ConvexShape = convexShape;
Shape = shape;
}
EntityID Entity;
hkpConvexShape* ConvexShape;
hkpShape* Shape;
};
std::unordered_map<EntityID, std::list<ShapeArrayData>> m_Shapes;
+80 -83
View File
@@ -2,11 +2,9 @@
#include "RenderSystem.h"
#include "World.h"
void Systems::RenderSystem::RegisterResourceTypes(ResourceManager* rm)
void Systems::RenderSystem::RegisterResourceTypes(std::shared_ptr<::ResourceManager> rm)
{
rm->RegisterType("Model", [rm](std::string resourceName) { return new Model(rm, *rm->Load<OBJ>("OBJ", resourceName)); });
rm->RegisterType("OBJ", [](std::string resourceName) { return new OBJ(resourceName); });
rm->RegisterType("Texture", [](std::string resourceName) { return new Texture(resourceName); });
rm->RegisterType("Shader", [](std::string resourceName) { return new ShaderProgram(resourceName); });
}
void Systems::RenderSystem::RegisterComponents(ComponentFactory* cf)
@@ -21,100 +19,99 @@ void Systems::RenderSystem::RegisterComponents(ComponentFactory* cf)
void Systems::RenderSystem::OnEntityCommit(EntityID entity)
{
auto transform = m_World->GetComponent<Components::Transform>(entity);
//auto transform = m_World->GetComponent<Components::Transform>(entity);
auto camera = m_World->GetComponent<Components::Camera>(entity);
if (transform && camera)
{
m_Renderer->RegisterCamera(entity, camera->FOV, camera->NearClip, camera->FarClip);
m_Renderer->UpdateCamera(entity, m_TransformSystem->AbsolutePosition(entity), m_TransformSystem->AbsoluteOrientation(entity), camera->FOV, camera->NearClip, camera->FarClip);
}
//auto camera = m_World->GetComponent<Components::Camera>(entity);
//if (transform && camera)
//{
// m_Renderer->RegisterCamera(entity, camera->FOV, camera->NearClip, camera->FarClip);
// m_Renderer->UpdateCamera(entity, m_TransformSystem->AbsolutePosition(entity), m_TransformSystem->AbsoluteOrientation(entity), camera->FOV, camera->NearClip, camera->FarClip);
//}
auto viewport = m_World->GetComponent<Components::Viewport>(entity);
if (viewport)
{
m_Renderer->RegisterViewport(entity, viewport->Left, viewport->Top, viewport->Right, viewport->Bottom);
if (viewport->Camera != 0)
{
m_Renderer->UpdateViewport(entity, viewport->Camera);
}
}
//auto viewport = m_World->GetComponent<Components::Viewport>(entity);
//if (viewport)
//{
// m_Renderer->RegisterViewport(entity, viewport->Left, viewport->Top, viewport->Right, viewport->Bottom);
// if (viewport->Camera != 0)
// {
// m_Renderer->UpdateViewport(entity, viewport->Camera);
// }
//}
}
void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto templateComponent = m_World->GetComponent<Components::Template>(entity);
if (templateComponent)
return;
//auto templateComponent = m_World->GetComponent<Components::Template>(entity);
//if (templateComponent)
// return;
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
//auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
// Draw models
auto modelComponent = m_World->GetComponent<Components::Model>(entity);
if (transformComponent && modelComponent)
{
auto model = m_World->GetResourceManager()->Load<Model>("Model", modelComponent->ModelFile);
if (model)
{
/*glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
glm::quat orientation = m_TransformSystem->AbsoluteOrientation(entity);
glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity);*/
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
m_Renderer->AddModelToDraw(model, absoluteTransform.Position, absoluteTransform.Orientation, absoluteTransform.Scale, modelComponent->Visible, modelComponent->ShadowCaster);
}
}
//// Draw models
//auto modelComponent = m_World->GetComponent<Components::Model>(entity);
//if (transformComponent && modelComponent)
//{
// auto model = m_World->ResourceManager->Load<Model>("Model", modelComponent->ModelFile);
// if (model)
// {
// /*glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
// glm::quat orientation = m_TransformSystem->AbsoluteOrientation(entity);
// glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity);*/
// Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
// m_Renderer->AddModelToDraw(model, absoluteTransform.Position, absoluteTransform.Orientation, absoluteTransform.Scale, modelComponent->Visible, modelComponent->ShadowCaster);
// }
//}
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity);
if (transformComponent && pointLightComponent)
{
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
m_Renderer->AddPointLightToDraw(
position,
pointLightComponent->Specular,
pointLightComponent->Diffuse,
pointLightComponent->specularExponent,
pointLightComponent->ConstantAttenuation,
pointLightComponent->LinearAttenuation,
pointLightComponent->QuadraticAttenuation
);
}
//auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity);
//if (transformComponent && pointLightComponent)
//{
// glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
// m_Renderer->AddPointLightToDraw(
// position,
// pointLightComponent->Specular,
// pointLightComponent->Diffuse,
// pointLightComponent->specularExponent,
// pointLightComponent->ConstantAttenuation,
// pointLightComponent->LinearAttenuation,
// pointLightComponent->QuadraticAttenuation
// );
//}
auto cameraComponent = m_World->GetComponent<Components::Camera>(entity);
if (transformComponent && cameraComponent)
{
m_Renderer->UpdateCamera(entity
, m_TransformSystem->AbsolutePosition(entity)
, m_TransformSystem->AbsoluteOrientation(entity)
, cameraComponent->FOV
, cameraComponent->NearClip
, cameraComponent->FarClip);
}
//auto cameraComponent = m_World->GetComponent<Components::Camera>(entity);
//if (transformComponent && cameraComponent)
//{
// m_Renderer->UpdateCamera(entity
// , m_TransformSystem->AbsolutePosition(entity)
// , m_TransformSystem->AbsoluteOrientation(entity)
// , cameraComponent->FOV
// , cameraComponent->NearClip
// , cameraComponent->FarClip);
//}
auto viewportComponent = m_World->GetComponent<Components::Viewport>(entity);
if (viewportComponent)
{
if (viewportComponent->Camera != 0)
{
m_Renderer->UpdateViewport(entity, viewportComponent->Camera);
}
}
//auto viewportComponent = m_World->GetComponent<Components::Viewport>(entity);
//if (viewportComponent)
//{
// if (viewportComponent->Camera != 0)
// {
// m_Renderer->UpdateViewport(entity, viewportComponent->Camera);
// }
//}
auto spriteComponent = m_World->GetComponent<Components::Sprite>(entity);
if (transformComponent && spriteComponent)
{
//TEMP
Texture* texture = m_World->GetResourceManager()->Load<Texture>("Texture", spriteComponent->SpriteFile);
//glBindTexture(GL_TEXTURE_2D, texture);
auto transform = m_World->GetComponent<Components::Transform>(spriteComponent->Entity);
glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(transform->Orientation).z, glm::vec3(0, 0, -1));
m_Renderer->AddTextureToDraw(texture, transform->Position, orientation2D, transform->Scale);
}
//auto spriteComponent = m_World->GetComponent<Components::Sprite>(entity);
//if (transformComponent && spriteComponent)
//{
// //TEMP
// Texture* texture = m_World->ResourceManager->Load<Texture>("Texture", spriteComponent->SpriteFile);
// //glBindTexture(GL_TEXTURE_2D, texture);
// auto transform = m_World->GetComponent<Components::Transform>(spriteComponent->Entity);
// glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(transform->Orientation).z, glm::vec3(0, 0, -1));
// m_Renderer->AddTextureToDraw(texture, transform->Position, orientation2D, transform->Scale);
//}
}
void Systems::RenderSystem::Initialize()
{
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
//m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
m_Renderer->SetSphereModel(m_World->GetResourceManager()->Load<Model>("Model", "Models/Placeholders/PhysicsTest/Sphere.obj"));
//m_Renderer->SetSphereModel(m_World->ResourceManager->Load<Model>("Model", "Models/Placeholders/PhysicsTest/Sphere.obj"));
}
+11 -9
View File
@@ -5,6 +5,7 @@
#include "System.h"
#include "Systems/TransformSystem.h"
#include "ShaderProgram.h"
#include "Model.h"
#include "Texture.h"
#include "Components/Transform.h"
@@ -14,10 +15,11 @@
#include "Components/PointLight.h"
#include "Components/DirectionalLight.h"
#include "Components/Viewport.h"
#include "Components/Template.h"
#include "Components/Transform.h"
#include "Renderer.h"
#include "RenderQueue.h"
#include "Events/SetViewportCamera.h"
namespace Systems
{
@@ -25,12 +27,12 @@ namespace Systems
class RenderSystem : public System
{
public:
RenderSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<Renderer> renderer)
: System(world, eventBroker)
, m_Renderer(renderer) { }
RenderSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void RegisterResourceTypes(ResourceManager* rm) override;
void RegisterResourceTypes(std::shared_ptr<::ResourceManager> rm) override;
void Initialize() override;
std::unordered_map<std::string, std::shared_ptr<Model>> m_CachedModels;
@@ -38,12 +40,12 @@ public:
void OnEntityCommit(EntityID entity) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
std::shared_ptr<Renderer> m_Renderer;
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
void EnqueueModel(Model* model, glm::mat4 modelMatrix);
void EnqueueSprite(Texture* texture, glm::mat4 modelMatrix);
};
+5 -5
View File
@@ -32,7 +32,7 @@ void Systems::SoundSystem::RegisterComponents(ComponentFactory* cf)
cf->Register<Components::SoundEmitter>([]() { return new Components::SoundEmitter(); });
}
void Systems::SoundSystem::RegisterResourceTypes(ResourceManager* rm)
void Systems::SoundSystem::RegisterResourceTypes(std::shared_ptr<::ResourceManager> rm)
{
rm->RegisterType("Sound", [](std::string resourceName) { return new Sound(resourceName); });
}
@@ -94,7 +94,7 @@ void Systems::SoundSystem::PlaySound(Components::SoundEmitter* emitter, std::str
if (m_Sources.find(emitter) == m_Sources.end())
return;
ALuint buffer = *m_World->GetResourceManager()->Load<Sound>("Sound", fileName);
ALuint buffer = *ResourceManager->Load<Sound>("Sound", fileName);
if (buffer == 0)
return;
ALuint source = m_Sources[emitter];
@@ -104,7 +104,7 @@ void Systems::SoundSystem::PlaySound(Components::SoundEmitter* emitter, std::str
void Systems::SoundSystem::PlaySound(std::shared_ptr<Components::SoundEmitter> emitter)
{
ALuint buffer = *m_World->GetResourceManager()->Load<Sound>("Sound", emitter->Path);
ALuint buffer = *ResourceManager->Load<Sound>("Sound", emitter->Path);
ALuint source = m_Sources[emitter.get()];
alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(m_Sources[emitter.get()]);
@@ -124,7 +124,7 @@ void Systems::SoundSystem::OnComponentCreated(std::string type, std::shared_ptr<
}
}
void Systems::SoundSystem::OnComponentRemoved(std::string type, Component* component)
void Systems::SoundSystem::OnComponentRemoved(EntityID entity, std::string type, Component* component)
{
if(type == "SoundEmitter")
{
@@ -151,7 +151,7 @@ bool Systems::SoundSystem::OnPlaySound(const Events::PlaySound &event)
{
LOG_DEBUG("Events::PlaySound.Resource = %s", event.Resource.c_str());
ALuint buffer = *m_World->GetResourceManager()->Load<Sound>("Sound", event.Resource);
ALuint buffer = *ResourceManager->Load<Sound>("Sound", event.Resource);
ALuint source = m_Sources.begin()->second;
alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(source);
+5 -4
View File
@@ -16,17 +16,18 @@ namespace Systems
class SoundSystem : public System
{
public:
SoundSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
SoundSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void RegisterResourceTypes(ResourceManager* rm) override;
void RegisterResourceTypes(std::shared_ptr<::ResourceManager> rm) override;
void Initialize() override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
void OnComponentCreated(std::string type, std::shared_ptr<Component> component) override;
void OnComponentRemoved(std::string type, Component* component) override;
void OnComponentRemoved(EntityID entity, std::string type, Component* component) override;
void PlaySound(Components::SoundEmitter* emitter, std::string path); // Use if you want to play a temporary .wav file not from component
void PlaySound(std::shared_ptr<Components::SoundEmitter> emitter); // Use if you want to play .wav file from component // imon no hate plx T.T
void StopSound(std::shared_ptr<Components::SoundEmitter> emitter);
+157
View File
@@ -11,6 +11,8 @@ void Systems::TankSteeringSystem::RegisterComponents( ComponentFactory* cf )
void Systems::TankSteeringSystem::Initialize()
{
EVENT_SUBSCRIBE_MEMBER(m_ECollision, &Systems::TankSteeringSystem::OnCollision);
for (int i = 0; i < 4; i++)
{
m_TankInputControllers[i] = std::shared_ptr<TankSteeringInputController>(new TankSteeringInputController(EventBroker, i + 1));
@@ -93,6 +95,147 @@ void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit
}
}
bool Systems::TankSteeringSystem::OnCollision( const Events::Collision &e )
{
if(m_World->ValidEntity(e.Entity1) && m_World->ValidEntity(e.Entity2))
{
auto tankShell1 = m_World->GetComponent<Components::TankShell>(e.Entity1);
auto tankShell2 = m_World->GetComponent<Components::TankShell>(e.Entity2);
EntityID shellEntity = 0;
Components::TankShell* shellComponent;
EntityID otherEntity = 0;
if (tankShell1)
{
shellEntity = e.Entity1;
otherEntity = e.Entity2;
shellComponent = tankShell1;
}
else if (tankShell2)
{
shellEntity = e.Entity2;
otherEntity = e.Entity1;
shellComponent = tankShell2;
}
else
{
return false;
}
auto physicsComponents = m_World->GetComponentsOfType<Components::Physics>();
auto shellTransform = m_World->GetComponent<Components::Transform>(shellEntity);
//auto otherTransform = m_World->GetComponent<Components::Transform>(otherEntity);
for (auto &physComponent : *physicsComponents)
{
EntityID physicsEntity = std::dynamic_pointer_cast<Components::Physics>(physComponent)->Entity;
auto physEntityTransform = m_World->GetComponent<Components::Transform>(physicsEntity);
float distance = glm::distance(physEntityTransform->Position, shellTransform->Position);
if (distance <= shellComponent->ExplosionRadius)
{
// DO STUFF! :D
float radius = shellComponent->ExplosionRadius;
float strength = (1.f - pow(distance / radius, 2)) * shellComponent->ExplosionStrength;
glm::vec3 direction = glm::normalize(physEntityTransform->Position - shellTransform->Position);
Events::ApplyPointImpulse e;
e.Entity = physicsEntity;
e.Impulse = direction * strength;
e.Position = physEntityTransform->Position;
EventBroker->Publish(e);
auto health = m_World->GetComponent<Components::Health>(physicsEntity);
if(health)
{
Events::Damage d;
d.Entity = physicsEntity;
d.damage = (1.f - pow(distance / radius, 2)) * shellComponent->Damage;
EventBroker->Publish(d);
}
m_World->RemoveEntity(shellEntity);
}
}
//if(tankShell1)
//{
// LOG_DEBUG("%i collided with %i", e.Entity1, e.Entity2);
// auto transform = m_World->GetComponent<Components::Transform>(e.Entity1);
// //m_World->GetSystem<Systems::ParticleSystem>()->CreateExplosion(transform->Position, 1, 60, "Textures/Sprites/NewtonTreeDeleteASAPPlease.png", glm::angleAxis(glm::pi<float>()/2, glm::vec3(1,0,0)), 40, glm::pi<float>(), 0.5f);
// glm::vec3 pointOfImpact = transform->Position;
// {
// auto ent = m_World->CreateEntity();
// LOG_DEBUG("Created trigger entity %i", ent);
// auto transform = m_World->AddComponent<Components::Transform>(ent);
// transform->Position = pointOfImpact;
// auto trigger = m_World->AddComponent<Components::Trigger>(ent);
// trigger->TriggerOnce = true;
// auto frameTimer = m_World->AddComponent<Components::FrameTimer>(ent);
// frameTimer->Frames = 100;
// auto explosion = m_World->AddComponent<Components::TriggerExplosion>(ent);
// explosion->MaxVelocity = 50.f;
// explosion->Radius = 30.f;
// {
// auto shape = m_World->CreateEntity(ent);
// auto transformshape = m_World->AddComponent<Components::Transform>(shape);
// auto sphere = m_World->AddComponent<Components::SphereShape>(shape);
// sphere->Radius = 30.f;
// m_World->CommitEntity(shape);
// }
// m_World->CommitEntity(ent);
// }
//
// m_World->RemoveEntity(e.Entity1);
//}
//if(tankShell2)
//{
// LOG_DEBUG("%i collided with %i", e.Entity1, e.Entity2);
// auto transform = m_World->GetComponent<Components::Transform>(e.Entity2);
// //m_World->GetSystem<Systems::ParticleSystem>()->CreateExplosion(transform->Position, 1, 60, "Textures/Sprites/NewtonTreeDeleteASAPPlease.png", glm::angleAxis(glm::pi<float>()/2, glm::vec3(1,0,0)), 40, glm::pi<float>(), 0.5f);
// glm::vec3 pointOfImpact = transform->Position;
// {
// auto ent = m_World->CreateEntity();
// LOG_DEBUG("Created trigger entity %i", ent);
// auto transform = m_World->AddComponent<Components::Transform>(ent);
// transform->Position = pointOfImpact;
// auto trigger = m_World->AddComponent<Components::Trigger>(ent);
// trigger->TriggerOnce = true;
// auto frameTimer = m_World->AddComponent<Components::FrameTimer>(ent);
// frameTimer->Frames = 100;
// auto explosion = m_World->AddComponent<Components::TriggerExplosion>(ent);
// explosion->MaxVelocity = 50.f;
// explosion->Radius = 30.f;
// {
// auto shape = m_World->CreateEntity(ent);
// auto transformshape = m_World->AddComponent<Components::Transform>(shape);
// auto sphere = m_World->AddComponent<Components::SphereShape>(shape);
// sphere->Radius = 30.f;
// m_World->CommitEntity(shape);
// }
// m_World->CommitEntity(ent);
// }
// m_World->RemoveEntity(e.Entity2);
//}
}
return true;
}
void Systems::TankSteeringSystem::TankSteeringInputController::Update( double dt )
{
PositionX = m_Horizontal;
@@ -141,6 +284,20 @@ bool Systems::TankSteeringSystem::TankSteeringInputController::OnCommand(const E
m_Shoot = val > 0;
}
else if(event.Command == "EnableCollisions")
{
Events::EnableCollisions e;
e.Layer1 = 1;
e.Layer2 = 2;
EventBroker->Publish(e);
}
else if(event.Command == "DisableCollisions")
{
Events::DisableCollisions e;
e.Layer1 = 1;
e.Layer2 = 2;
EventBroker->Publish(e);
}
return true;
}
+21 -2
View File
@@ -5,6 +5,7 @@
#include "Events/SetVelocity.h"
#include "Events/ApplyForce.h"
#include "Events/ApplyPointImpulse.h"
#include "Events/Collision.h"
#include "Components/Transform.h"
#include "Components/TankSteering.h"
#include "Components/TowerSteering.h"
@@ -12,17 +13,32 @@
#include "Components/Physics.h"
#include "Components/Vehicle.h"
#include "Components/Player.h"
#include "Components/Model.h"
#include "Systems/TransformSystem.h"
#include "Systems/ParticleSystem.h"
#include "InputController.h"
#include "Components/Health.h"
#include "Components/TankShell.h"
#include "Components/SphereShape.h"
#include "Events/EnableCollisions.h"
#include "Events/DisableCollisions.h"
#include "Components/Trigger.h"
#include "Components/TriggerExplosion.h"
#include "Components/FrameTimer.h"
#include "Events/Damage.h"
namespace Systems
{
class TankSteeringSystem : public System
{
public:
TankSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
TankSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
@@ -31,6 +47,9 @@ namespace Systems
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
EventRelay<TankSteeringSystem, Events::Collision> m_ECollision;
bool OnCollision(const Events::Collision &e);
class TankSteeringInputController;
std::array<std::shared_ptr<TankSteeringInputController>, 4> m_TankInputControllers;
+38
View File
@@ -0,0 +1,38 @@
#include "PrecompiledHeader.h"
#include "TimerSystem.h"
#include "World.h"
void Systems::TimerSystem::RegisterComponents( ComponentFactory* cf )
{
cf->Register<Components::Timer>([]() { return new Components::Timer(); });
cf->Register<Components::FrameTimer>([]() { return new Components::FrameTimer(); });
}
void Systems::TimerSystem::UpdateEntity( double dt, EntityID entity, EntityID parent )
{
auto timer = m_World->GetComponent<Components::Timer>(entity);
if(timer)
{
timer->Time -= dt;
if(timer->Time <= 0)
{
m_World->RemoveEntity(entity);
}
}
auto frameTimer = m_World->GetComponent<Components::FrameTimer>(entity);
if(frameTimer)
{
frameTimer->Frames -= 1;
if(frameTimer->Frames <= 0)
{
m_World->RemoveEntity(entity);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef TimerSystem_h__
#define TimerSystem_h__
#include "System.h"
#include "Components/Transform.h"
#include "Components/Timer.h"
#include "Components/FrameTimer.h"
namespace Systems
{
class TimerSystem : public System
{
public:
TimerSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager) { }
void RegisterComponents(ComponentFactory* cf) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
};
}
#endif // TimerSystem_h__
+3 -2
View File
@@ -10,8 +10,9 @@ namespace Systems
class TransformSystem : public System
{
public:
TransformSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
TransformSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager)
{ }
//void Update(double dt) override;
//void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
+117
View File
@@ -0,0 +1,117 @@
#include "PrecompiledHeader.h"
#include "TriggerSystem.h"
#include "World.h"
void Systems::TriggerSystem::RegisterComponents( ComponentFactory* cf )
{
cf->Register<Components::Trigger>([]() { return new Components::Trigger(); });
cf->Register<Components::TriggerExplosion>([]() { return new Components::TriggerExplosion(); });
}
void Systems::TriggerSystem::Initialize()
{
EVENT_SUBSCRIBE_MEMBER(m_EEnterTrigger, &Systems::TriggerSystem::OnEnterTrigger);
}
void Systems::TriggerSystem::Update( double dt )
{
}
void Systems::TriggerSystem::UpdateEntity( double dt, EntityID entity, EntityID parent )
{
}
void Systems::TriggerSystem::OnComponentCreated( std::string type, std::shared_ptr<Component> component )
{
}
void Systems::TriggerSystem::OnComponentRemoved(EntityID entity, std::string type, Component* component )
{
}
void Systems::TriggerSystem::OnEntityCommit( EntityID entity )
{
}
void Systems::TriggerSystem::OnEntityRemoved( EntityID entity )
{
}
bool Systems::TriggerSystem::OnEnterTrigger( const Events::EnterTrigger &event )
{
/*auto explosionComponent1 = m_World->GetComponent<Components::TriggerExplosion>(event.Entity1);
auto explosionComponent2 = m_World->GetComponent<Components::TriggerExplosion>(event.Entity2);
if(explosionComponent1)
{
Explosion(event.Entity2, event.Entity1);
}
else if (explosionComponent2)
{
Explosion(event.Entity1, event.Entity2);
}*/
auto flagComponent1 = m_World->GetComponent<Components::Flag>(event.Entity1);
auto flagComponent2 = m_World->GetComponent<Components::Flag>(event.Entity2);
if(flagComponent1)
{
Flag(event.Entity2, event.Entity1);
}
else if (flagComponent2)
{
Flag(event.Entity1, event.Entity2);
}
return true;
}
void Systems::TriggerSystem::Flag( EntityID entity, EntityID phantomEntity )
{
auto tankSteering = m_World->GetComponent<Components::TankSteering>(entity);
if (!tankSteering)
return;
m_World->RemoveComponent<Components::Trigger>(phantomEntity);
m_World->SetEntityParent(phantomEntity, entity);
auto phantomTransform = m_World->GetComponent<Components::Transform>(phantomEntity);
phantomTransform->Position = glm::vec3(1.f, 0.1f, 2.f);
}
void Systems::TriggerSystem::Explosion( EntityID entity, EntityID phantomEntity )
{
/*auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
auto PhantomTransformComponent = m_World->GetComponent<Components::Transform>(phantomEntity);
auto explosionComponent = m_World->GetComponent<Components::TriggerExplosion>(phantomEntity);
if(transformComponent && PhantomTransformComponent)
{
// Velocity = (1 - (distance / radius)^2) * Strength;
glm::vec3 vect = transformComponent->Position - PhantomTransformComponent->Position;
float distance = glm::length(vect);
float radius = explosionComponent->Radius;
float velocity = (1.f - pow(distance / radius, 2)) * explosionComponent->MaxVelocity;
glm::vec3 direction = glm::normalize(transformComponent->Position - PhantomTransformComponent->Position);
Events::SetVelocity e;
e.Entity = entity;
e.Velocity = direction*velocity;
EventBroker->Publish(e);
m_World->RemoveEntity(phantomEntity);
}*/
}
+46
View File
@@ -0,0 +1,46 @@
#ifndef TriggerSystem_h__
#define TriggerSystem_h__
#include "System.h"
#include "Components/Transform.h"
#include "Components/TankSteering.h"
#include "Events/SetVelocity.h"
#include "Events/ApplyForce.h"
#include "Events/ApplyPointImpulse.h"
#include <unordered_map>
#include "Components/Trigger.h"
#include "Components/TriggerExplosion.h"
#include "Events/EnterTrigger.h"
#include "Components/Flag.h"
#include <math.h>
namespace Systems
{
class TriggerSystem : public System
{
public:
TriggerSystem(World* world, std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: System(world, eventBroker, resourceManager) { }
void Initialize() override;
void RegisterComponents(ComponentFactory* cf) override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
void OnComponentCreated(std::string type, std::shared_ptr<Component> component) override;
void OnComponentRemoved(EntityID entity, std::string type, Component* component) override;
void OnEntityCommit(EntityID entity) override;
void OnEntityRemoved(EntityID entity) override;
EventRelay<TriggerSystem, Events::EnterTrigger> m_EEnterTrigger;
bool OnEnterTrigger(const Events::EnterTrigger &event);
private:
void Flag(EntityID entity, EntityID phantomEntity);
void Explosion(EntityID entity, EntityID phantomEntity);
};
}
#endif // TriggerSystem_h__
+9 -9
View File
@@ -19,24 +19,24 @@ struct Rectangle
int Width;
int Height;
const int& GetLeft() const { return X; }
virtual int Left() const { return X; }
void SetLeft(int left)
{
Width += X - left;
X = left;
}
int GetRight() const { return X + Width; }
virtual int Right() const { return X + Width; }
void SetRight(int right)
{
Width = right - X;
}
const int& GetTop() const { return Y; }
virtual int Top() const { return Y; }
void SetTop(int top)
{
Height += Y - top;
Y = top;
}
int GetBottom() const { return Y + Height; }
virtual int Bottom() const { return Y + Height; }
int SetBottom(int bottom)
{
Height = bottom - Y;
@@ -44,15 +44,15 @@ struct Rectangle
Rectangle& operator+=(const Rectangle &rhs)
{
SetLeft(std::min(GetLeft(), rhs.GetLeft()));
SetRight(std::max(GetRight(), rhs.GetRight()));
SetTop(std::min(GetTop(), rhs.GetTop()));
SetBottom(std::max(GetBottom(), rhs.GetBottom()));
SetLeft(std::min(Left(), rhs.Left()));
SetRight(std::max(Right(), rhs.Right()));
SetTop(std::min(Top(), rhs.Top()));
SetBottom(std::max(Bottom(), rhs.Bottom()));
}
static bool Intersects(const Rectangle &r1, const Rectangle &r2)
{
return !(r2.GetLeft() > r1.GetRight() || r2.GetRight() < r1.GetLeft() || r2.GetTop() > r1.GetBottom() || r2.GetBottom() < r1.GetTop());
return !(r2.Left() > r1.Right() || r2.Right() < r1.Left() || r2.Top() > r1.Bottom() || r2.Bottom() < r1.Top());
}
};
+22 -7
View File
@@ -38,7 +38,7 @@ void World::Update(double dt)
{
const std::string &type = pair.first;
auto system = pair.second;
m_EventBroker->Process(type);
EventBroker->Process(type);
system->Update(dt);
RecursiveUpdate(system, dt, 0);
}
@@ -72,17 +72,18 @@ EntityID World::GetEntityBaseParent(EntityID entity)
bool World::ValidEntity(EntityID entity)
{
return m_EntityParents.find(entity) != m_EntityParents.end();
return m_EntityParents.find(entity) != m_EntityParents.end()
&& m_EntitiesToRemove.find(entity) == m_EntitiesToRemove.end();
}
void World::RemoveEntity(EntityID entity)
{
m_EntitiesToRemove.push_back(entity);
m_EntitiesToRemove.insert(entity);
for (auto pair : m_EntityParents)
{
if (pair.second == entity)
{
m_EntitiesToRemove.push_back(pair.first);
m_EntitiesToRemove.insert(pair.first);
}
}
}
@@ -102,13 +103,19 @@ void World::ProcessEntityRemovals()
for (auto pair : m_Systems)
{
auto system = pair.second;
system->OnComponentRemoved(type, component.get());
system->OnComponentRemoved(entity, type, component.get());
}
m_ComponentsOfType[type].remove(component);
}
m_EntityComponents.erase(entity);
RecycleEntityID(entity);
// Trigger events
for (auto pair : m_Systems)
{
auto system = pair.second;
system->OnEntityRemoved(entity);
}
}
m_EntitiesToRemove.clear();
}
@@ -129,7 +136,7 @@ void World::Initialize()
{
auto system = pair.second;
system->RegisterComponents(&m_ComponentFactory);
system->RegisterResourceTypes(&m_ResourceManager);
system->RegisterResourceTypes(ResourceManager);
system->Initialize();
}
}
@@ -197,3 +204,11 @@ std::list<EntityID> World::GetEntityChildren(EntityID entity)
return it->second;
}
}
void World::SetEntityParent(EntityID entity, EntityID newParent)
{
EntityID currentParent = m_EntityParents[entity];
m_EntityChildren[currentParent].remove(entity);
m_EntityParents[entity] = newParent;
m_EntityChildren[newParent].push_back(entity);
}
+47 -9
View File
@@ -3,6 +3,7 @@
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <vector>
#include <string>
@@ -21,8 +22,9 @@
class World
{
public:
World(std::shared_ptr<::EventBroker> eventBroker)
: m_EventBroker(eventBroker)
World(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: EventBroker(eventBroker)
, ResourceManager(resourceManager)
, m_LastEntityID(0) { }
~World() { }
@@ -43,7 +45,6 @@ public:
EntityID CreateEntity(EntityID parent = 0);
EntityID CloneEntity(EntityID entity, EntityID parent = 0);
void RemoveEntity(EntityID entity);
bool ValidEntity(EntityID entity);
@@ -52,6 +53,8 @@ public:
EntityID GetEntityBaseParent(EntityID entity);
std::list<EntityID> GetEntityChildren(EntityID entity);
void SetEntityParent(EntityID entity, EntityID newParent);
template <class T>
T GetProperty(EntityID entity, std::string property)
{
@@ -76,10 +79,15 @@ public:
template <class T>
std::shared_ptr<T> AddComponent(EntityID entity);
template <class T>
void RemoveComponent(EntityID entity);
template <class T>
T* GetComponent(EntityID entity);
// Triggers commit events in systems
void CommitEntity(EntityID entity);
template <class T>
std::list<std::shared_ptr<Component>>* GetComponentsOfType();
/*std::vector<EntityID> GetEntityChildren(EntityID entity);*/
virtual void Update(double dt);
@@ -88,14 +96,12 @@ public:
std::unordered_map<EntityID, EntityID>* GetEntities() { return &m_EntityParents; }
ResourceManager* GetResourceManager() { return &m_ResourceManager; }
std::shared_ptr<::EventBroker> EventBroker() { return m_EventBroker; }
protected:
std::shared_ptr<::EventBroker> m_EventBroker;
std::shared_ptr<::EventBroker> EventBroker;
std::shared_ptr<::ResourceManager> ResourceManager;
SystemFactory m_SystemFactory;
ComponentFactory m_ComponentFactory;
ResourceManager m_ResourceManager;
std::unordered_map<std::string, std::shared_ptr<System>> m_Systems;
@@ -111,7 +117,7 @@ protected:
// Internal: Add a component to an entity
void AddComponent(EntityID entity, std::string componentType, std::shared_ptr<Component> component);
std::list<EntityID> m_EntitiesToRemove;
std::set<EntityID> m_EntitiesToRemove;
void ProcessEntityRemovals();
EntityID GenerateEntityID();
@@ -120,6 +126,18 @@ protected:
};
template <class T>
std::list<std::shared_ptr<Component>>* World::GetComponentsOfType()
{
const char* componentType = typeid(T).name();
auto it = m_ComponentsOfType.find(componentType);
if (it == m_ComponentsOfType.end())
return nullptr;
return &it->second;
}
template <class T>
std::shared_ptr<T> World::GetSystem()
{
@@ -151,6 +169,26 @@ std::shared_ptr<T> World::AddComponent(EntityID entity)
return component;
}
template <class T>
void World::RemoveComponent(EntityID entity)
{
const char* componentType = typeid(T).name();
auto it = m_EntityComponents[entity].find(componentType);
if (it == m_EntityComponents[entity].end())
return;
auto component = it->second;
component->Entity = 0;
m_ComponentsOfType[componentType].remove(component);
m_EntityComponents[entity].erase(it);
for (auto pair : m_Systems)
{
auto system = pair.second;
system->OnComponentRemoved(entity, componentType, component.get());
}
}
template <class T>
T* World::GetComponent(EntityID entity)
+1
View File
@@ -4,6 +4,7 @@
int main(int argc, char* argv[])
{
Engine engine(argc, argv);
LOG_INFO("------------ Engine initialized ------------");
while (engine.Running())
engine.Tick();
+3 -1
View File
@@ -1,6 +1,8 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Returngeance", "Returngeance\Returngeance.vcxproj", "{E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}"
EndProject
Project("{F088123C-0E9E-452A-89E6-6BA2F21D5CAC}") = "ModelingProject1", "ModelingProject1\ModelingProject1.modelproj", "{B35F204C-3377-457E-AC9E-D9606F421191}"
+25
View File
@@ -109,6 +109,7 @@
<ClCompile Include="..\..\src\ShaderProgram.cpp" />
<ClCompile Include="..\..\src\Skybox.cpp" />
<ClCompile Include="..\..\src\Sound.cpp" />
<ClCompile Include="..\..\src\Systems\DamageSystem.cpp" />
<ClCompile Include="..\..\src\Systems\DebugSystem.cpp" />
<ClCompile Include="..\..\src\Systems\FreeSteeringSystem.cpp" />
<ClCompile Include="..\..\src\Systems\HelicopterSteeringSystem.cpp" />
@@ -118,7 +119,9 @@
<ClCompile Include="..\..\src\Systems\RenderSystem.cpp" />
<ClCompile Include="..\..\src\Systems\SoundSystem.cpp" />
<ClCompile Include="..\..\src\Systems\TankSteeringSystem.cpp" />
<ClCompile Include="..\..\src\Systems\TimerSystem.cpp" />
<ClCompile Include="..\..\src\Systems\TransformSystem.cpp" />
<ClCompile Include="..\..\src\Systems\TriggerSystem.cpp" />
<ClCompile Include="..\..\src\Texture.cpp" />
<ClCompile Include="..\..\src\World.cpp" />
</ItemGroup>
@@ -130,6 +133,10 @@
<ClInclude Include="..\..\src\Components\BoxShape.h" />
<ClInclude Include="..\..\src\Components\Camera.h" />
<ClInclude Include="..\..\src\Components\DirectionalLight.h" />
<ClInclude Include="..\..\src\Components\Flag.h" />
<ClInclude Include="..\..\src\Components\FrameTimer.h" />
<ClInclude Include="..\..\src\Components\Timer.h" />
<ClInclude Include="..\..\src\Components\TriggerExplosion.h" />
<ClInclude Include="..\..\src\Components\ExtendedMeshShape.h" />
<ClInclude Include="..\..\src\Components\FreeSteering.h" />
<ClInclude Include="..\..\src\Components\Health.h" />
@@ -146,10 +153,12 @@
<ClInclude Include="..\..\src\Components\SoundEmitter.h" />
<ClInclude Include="..\..\src\Components\SphereShape.h" />
<ClInclude Include="..\..\src\Components\Sprite.h" />
<ClInclude Include="..\..\src\Components\TankShell.h" />
<ClInclude Include="..\..\src\Components\TankSteering.h" />
<ClInclude Include="..\..\src\Components\Template.h" />
<ClInclude Include="..\..\src\Components\TowerSteering.h" />
<ClInclude Include="..\..\src\Components\Transform.h" />
<ClInclude Include="..\..\src\Components\Trigger.h" />
<ClInclude Include="..\..\src\Components\Vehicle.h" />
<ClInclude Include="..\..\src\Components\Viewport.h" />
<ClInclude Include="..\..\src\Components\Wheel.h" />
@@ -163,6 +172,10 @@
<ClInclude Include="..\..\src\Events\BindGamepadButton.h" />
<ClInclude Include="..\..\src\Events\BindKey.h" />
<ClInclude Include="..\..\src\Events\BindMouseButton.h" />
<ClInclude Include="..\..\src\Events\Collision.h" />
<ClInclude Include="..\..\src\Events\Damage.h" />
<ClInclude Include="..\..\src\Events\DisableCollisions.h" />
<ClInclude Include="..\..\src\Events\EnableCollisions.h" />
<ClInclude Include="..\..\src\Events\GamepadAxis.h" />
<ClInclude Include="..\..\src\Events\GamepadButton.h" />
<ClInclude Include="..\..\src\Events\InputCommand.h" />
@@ -174,11 +187,16 @@
<ClInclude Include="..\..\src\Events\MouseRelease.h" />
<ClInclude Include="..\..\src\Events\PlaySound.h" />
<ClInclude Include="..\..\src\Events\SetVelocity.h" />
<ClInclude Include="..\..\src\Events\SetViewportCamera.h" />
<ClInclude Include="..\..\src\Events\TankSteer.h" />
<ClInclude Include="..\..\src\Events\EnterTrigger.h" />
<ClInclude Include="..\..\src\Factory.h" />
<ClInclude Include="..\..\src\GameWorld.h" />
<ClInclude Include="..\..\src\GUI\Frame.h" />
<ClInclude Include="..\..\src\EventBroker.h" />
<ClInclude Include="..\..\src\GUI\GameFrame.h" />
<ClInclude Include="..\..\src\GUI\WorldFrame.h" />
<ClInclude Include="..\..\src\GUI\TextureFrame.h" />
<ClInclude Include="..\..\src\GUI\Viewport.h" />
<ClInclude Include="..\..\src\InputController.h" />
<ClInclude Include="..\..\src\InputManager.h" />
@@ -193,6 +211,7 @@
<ClInclude Include="..\..\src\Skybox.h" />
<ClInclude Include="..\..\src\Sound.h" />
<ClInclude Include="..\..\src\System.h" />
<ClInclude Include="..\..\src\Systems\DamageSystem.h" />
<ClInclude Include="..\..\src\Systems\DebugSystem.h" />
<ClInclude Include="..\..\src\Systems\FreeSteeringSystem.h" />
<ClInclude Include="..\..\src\Systems\HelicopterSteeringSystem.h" />
@@ -202,7 +221,9 @@
<ClInclude Include="..\..\src\Systems\RenderSystem.h" />
<ClInclude Include="..\..\src\Systems\SoundSystem.h" />
<ClInclude Include="..\..\src\Systems\TankSteeringSystem.h" />
<ClInclude Include="..\..\src\Systems\TimerSystem.h" />
<ClInclude Include="..\..\src\Systems\TransformSystem.h" />
<ClInclude Include="..\..\src\Systems\TriggerSystem.h" />
<ClInclude Include="..\..\src\Texture.h" />
<ClInclude Include="..\..\src\Util\GLError.h" />
<ClInclude Include="..\..\src\Util\Rectangle.h" />
@@ -214,6 +235,8 @@
<None Include="..\..\src\Shaders\AABB.frag.glsl" />
<None Include="..\..\src\Shaders\FinalPass.frag.glsl" />
<None Include="..\..\src\Shaders\FinalPass.vert.glsl" />
<None Include="..\..\src\Shaders\ForwardRendering.frag.glsl" />
<None Include="..\..\src\Shaders\ForwardRendering.vert.glsl" />
<None Include="..\..\src\Shaders\Fragment.glsl" />
<None Include="..\..\src\Shaders\Fragment2-Debug.glsl" />
<None Include="..\..\src\Shaders\Fragment2.glsl" />
@@ -223,6 +246,8 @@
<None Include="..\..\src\Shaders\ShadowMap.vert.glsl" />
<None Include="..\..\src\Shaders\Skybox.frag.glsl" />
<None Include="..\..\src\Shaders\Skybox.vert.glsl" />
<None Include="..\..\src\Shaders\SunPass.frag.glsl" />
<None Include="..\..\src\Shaders\SunPass.vert.glsl" />
<None Include="..\..\src\Shaders\Vertex.glsl" />
<None Include="..\..\src\Shaders\Vertex2.glsl" />
<None Include="..\..\src\Shaders\VisualizeDepth.frag.glsl" />
@@ -66,6 +66,15 @@
<ClCompile Include="..\..\src\Systems\HelicopterSteeringSystem.cpp">
<Filter>Gameplay\Vehicles\Helicopter\Systems</Filter>
</ClCompile>
<ClCompile Include="..\..\src\Systems\TriggerSystem.cpp">
<Filter>Physics\Systems</Filter>
</ClCompile>
<ClCompile Include="..\..\src\Systems\TimerSystem.cpp">
<Filter>Base\Systems</Filter>
</ClCompile>
<ClCompile Include="..\..\src\Systems\DamageSystem.cpp">
<Filter>Gameplay\Systems</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Filter Include="Util">
@@ -158,6 +167,16 @@
<Filter Include="Gameplay\Components">
<UniqueIdentifier>{cb06b441-90b8-46ed-b347-4190dac7185b}</UniqueIdentifier>
</Filter>
<Filter Include="Gameplay\Systems">
<UniqueIdentifier>{3c2ea0e5-41a1-4b11-a891-1d59ead7223c}</UniqueIdentifier>
</Filter>
<Filter Include="Rendering\Events">
<UniqueIdentifier>{a025d51e-594d-4844-983b-f683726bf1bf}</UniqueIdentifier>
</Filter>
<Filter Include="Gameplay\Events">
<UniqueIdentifier>{9702064a-02a2-4b3c-a2ab-47c23a9cf49c}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\src\World.h" />
@@ -397,6 +416,63 @@
<ClInclude Include="..\..\src\Components\Player.h">
<Filter>Gameplay\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Events\Collision.h">
<Filter>Physics\Events</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\Health.h">
<Filter>Gameplay\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\TankShell.h">
<Filter>Physics\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Events\DisableCollisions.h">
<Filter>Physics\Events</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Events\EnableCollisions.h">
<Filter>Physics\Events</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\Trigger.h">
<Filter>Physics\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Systems\TriggerSystem.h">
<Filter>Physics\Systems</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\TriggerExplosion.h">
<Filter>Physics\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Events\EnterTrigger.h">
<Filter>Physics\Events</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Systems\TimerSystem.h">
<Filter>Base\Systems</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\Timer.h">
<Filter>Base\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\FrameTimer.h">
<Filter>Base\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Systems\DamageSystem.h">
<Filter>Gameplay\Systems</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Events\Damage.h">
<Filter>Gameplay\Events</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Components\Flag.h">
<Filter>Gameplay\Components</Filter>
</ClInclude>
<ClInclude Include="..\..\src\GUI\TextureFrame.h">
<Filter>GUI</Filter>
</ClInclude>
<ClInclude Include="..\..\src\GUI\WorldFrame.h">
<Filter>GUI</Filter>
</ClInclude>
<ClInclude Include="..\..\src\Events\SetViewportCamera.h">
<Filter>Rendering\Events</Filter>
</ClInclude>
<ClInclude Include="..\..\src\GUI\GameFrame.h">
<Filter>GUI</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="..\..\src\Shaders\Fragment2.glsl">
@@ -447,5 +523,17 @@
<None Include="..\..\src\Shaders\FinalPass.frag.glsl">
<Filter>Shaders</Filter>
</None>
<None Include="..\..\src\Shaders\ForwardRendering.frag.glsl">
<Filter>Shaders</Filter>
</None>
<None Include="..\..\src\Shaders\ForwardRendering.vert.glsl">
<Filter>Shaders</Filter>
</None>
<None Include="..\..\src\Shaders\SunPass.frag.glsl">
<Filter>Shaders</Filter>
</None>
<None Include="..\..\src\Shaders\SunPass.vert.glsl">
<Filter>Shaders</Filter>
</None>
</ItemGroup>
</Project>
+89
View File
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<VSPerformanceSession Version="1.00">
<Options>
<Solution>Returngeance.sln</Solution>
<CollectionMethod>Sampling</CollectionMethod>
<AllocationMethod>None</AllocationMethod>
<AddReport>true</AddReport>
<ResourceBasedAnalysisSelected>true</ResourceBasedAnalysisSelected>
<UniqueReport>Timestamp</UniqueReport>
<SamplingMethod>Cycles</SamplingMethod>
<CycleCount>10000000</CycleCount>
<PageFaultCount>10</PageFaultCount>
<SysCallCount>10</SysCallCount>
<SamplingCounter Name="" ReloadValue="00000000000f4240" DisplayName="" />
<RelocateBinaries>false</RelocateBinaries>
<HardwareCounters EnableHWCounters="false" />
<EtwSettings />
<PdhSettings>
<PdhCountersEnabled>false</PdhCountersEnabled>
<PdhCountersRate>500</PdhCountersRate>
<PdhCounters>
<PdhCounter>\Memory\Pages/sec</PdhCounter>
<PdhCounter>\PhysicalDisk(_Total)\Avg. Disk Queue Length</PdhCounter>
<PdhCounter>\Processor(_Total)\% Processor Time</PdhCounter>
</PdhCounters>
</PdhSettings>
</Options>
<ExcludeSmallFuncs>true</ExcludeSmallFuncs>
<InteractionProfilingEnabled>false</InteractionProfilingEnabled>
<JScriptProfilingEnabled>false</JScriptProfilingEnabled>
<PreinstrumentEvent>
<InstrEventExclude>false</InstrEventExclude>
</PreinstrumentEvent>
<PostinstrumentEvent>
<InstrEventExclude>false</InstrEventExclude>
</PostinstrumentEvent>
<Binaries>
<ProjBinary>
<Path>bin\Debug\Returngeance.exe</Path>
<ArgumentTimestamp>01/01/0001 00:00:00</ArgumentTimestamp>
<Instrument>true</Instrument>
<Sample>true</Sample>
<ExternalWebsite>false</ExternalWebsite>
<InteractionProfilingEnabled>false</InteractionProfilingEnabled>
<IsLocalJavascript>false</IsLocalJavascript>
<IsWindowsStoreApp>false</IsWindowsStoreApp>
<IsWWA>false</IsWWA>
<LaunchProject>true</LaunchProject>
<OverrideProjectSettings>false</OverrideProjectSettings>
<LaunchMethod>Executable</LaunchMethod>
<ExecutablePath>bin\Debug\Returngeance.exe</ExecutablePath>
<StartupDirectory>..\bin\Debug</StartupDirectory>
<Arguments>
</Arguments>
<NetAppHost>IIS</NetAppHost>
<NetBrowser>InternetExplorer</NetBrowser>
<ExcludeSmallFuncs>true</ExcludeSmallFuncs>
<JScriptProfilingEnabled>false</JScriptProfilingEnabled>
<PreinstrumentEvent>
<InstrEventExclude>false</InstrEventExclude>
</PreinstrumentEvent>
<PostinstrumentEvent>
<InstrEventExclude>false</InstrEventExclude>
</PostinstrumentEvent>
<ProjRef>{E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}|Returngeance\Returngeance.vcxproj</ProjRef>
<ProjPath>Returngeance\Returngeance.vcxproj</ProjPath>
<ProjName>Returngeance</ProjName>
</ProjBinary>
</Binaries>
<Reports>
<Report>
<Path>Returngeance140519.vsp</Path>
</Report>
<Report>
<Path>Returngeance140519(1).vsp</Path>
</Report>
<Report>
<Path>Returngeance140519(2).vsp</Path>
</Report>
<Report>
<Path>Returngeance140519(3).vsp</Path>
</Report>
</Reports>
<Launches>
<ProjBinary>
<Path>:PB:{E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}|Returngeance\Returngeance.vcxproj</Path>
</ProjBinary>
</Launches>
</VSPerformanceSession>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.