1 Commits

Author SHA1 Message Date
Jace 4494e7592d How NOT to do normal maps 2014-05-10 16:01:36 +02:00
114 changed files with 1282 additions and 5718 deletions
+1
View File
@@ -31,4 +31,5 @@ ipch/
Ankh.NoLoad
*.orig
assets/
!libs/*.lib
-4
View File
@@ -1,4 +0,0 @@
[submodule "assets"]
path = assets
url = returngeance@shard.imon.nu:Assets
branch = master
Submodule assets deleted from a71e214594
-2
View File
@@ -7,8 +7,6 @@
struct Component
{
EntityID Entity;
virtual Component* Clone() const = 0;
};
class ComponentFactory : public Factory<Component*> { };
-23
View File
@@ -1,23 +0,0 @@
#ifndef BarrelSteering_h__
#define BarrelSteering_h__
#include "Component.h"
namespace Components
{
struct BarrelSteering : Component
{
BarrelSteering()
: TurnSpeed(1.f), Axis(glm::vec3(0,1,0)){ }
float TurnSpeed;
glm::vec3 Axis;
EntityID ShotTemplate;
float ShotSpeed;
virtual BarrelSteering* Clone() const override { return new BarrelSteering(*this); }
};
}
#endif // BarrelSteering_h__
@@ -6,16 +6,14 @@
namespace Components
{
struct BoxShape : Component
struct Box : Component
{
BoxShape()
Box()
: Width(1.f), Height(1.f), Depth(1.f){ }
float Width;
float Height;
float Depth;
virtual BoxShape* Clone() const override { return new BoxShape(*this); }
};
}
+1 -7
View File
@@ -2,23 +2,17 @@
#define Components_Camera_h__
#include "Component.h"
#include "Entity.h"
namespace Components
{
struct Camera : Component
{
Camera()
: FOV(glm::radians(45.f))
, NearClip(0.1f)
, FarClip(100.f) { }
Camera() : FOV(glm::radians(45.f)), NearClip(0.1f), FarClip(100.f) { }
float FOV;
float NearClip;
float FarClip;
virtual Camera* Clone() const override { return new Camera(*this); }
};
}
-2
View File
@@ -13,8 +13,6 @@ struct DirectionalLight : Component
float MaxRange;
float SpecularIntensity;
Color Color;
virtual DirectionalLight* Clone() const override { return new DirectionalLight(*this); }
};
}
View File
-2
View File
@@ -9,8 +9,6 @@ struct FreeSteering : Component
{
FreeSteering() : Speed(35) { }
float Speed;
virtual FreeSteering* Clone() const override { return new FreeSteering(*this); }
};
}
-21
View File
@@ -1,21 +0,0 @@
#ifndef Components_Health_h__
#define Components_Health_h__
#include "Component.h"
namespace Components
{
struct Health : Component
{
Health()
: health(1.0f){ }
float health;
virtual Health* Clone() const override { return new Health(*this); }
};
}
#endif // Components_Health_h__
-16
View File
@@ -1,16 +0,0 @@
#ifndef HelicopterSteering_h__
#define HelicopterSteering_h__
#include "Component.h"
namespace Components
{
struct HelicopterSteering : Component
{
HelicopterSteering* Clone() const override { return new HelicopterSteering(*this); }
};
}
#endif // HelicopterSteering_h__
-20
View File
@@ -1,20 +0,0 @@
#ifndef Components_HingeConstraint_h__
#define Components_HingeConstraint_h__
#include "Component.h"
namespace Components
{
struct HingeConstraint : Component
{
EntityID LinkedEntity;
glm::vec3 Pivot;
glm::vec3 Axis;
virtual HingeConstraint* Clone() const override { return new HingeConstraint(*this); }
};
}
#endif // Components_HingeConstraint_h__
+10 -10
View File
@@ -1,6 +1,10 @@
#ifndef Components_Input_h__
#define Components_Input_h__
#include <array>
#include <GLFW/glfw3.h>
#include "Component.h"
namespace Components
@@ -8,16 +12,12 @@ namespace Components
struct Input : Component
{
/*Input()
: Keyboard(false)
, Mouse(false)
, GamepadID(0) { }
bool Keyboard;
bool Mouse;
int GamepadID;*/
virtual Input* Clone() const override { return new Input(*this); }
std::array<int, GLFW_KEY_LAST+1> KeyState;
std::array<int, GLFW_KEY_LAST+1> LastKeyState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> MouseState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> LastMouseState;
float dX, dY;
float WheelDelta;
};
}
-19
View File
@@ -1,19 +0,0 @@
#ifndef Components_MeshShape_h__
#define Components_MeshShape_h__
#include <string>
#include "Component.h"
namespace Components
{
struct MeshShape : Component
{
std::string ResourceName;
virtual MeshShape* Clone() const override { return new MeshShape(*this); }
};
}
#endif // !Components_MeshShape_h__
-2
View File
@@ -16,8 +16,6 @@ struct Model : Component
Color Color;
bool Visible;
bool ShadowCaster;
virtual Model* Clone() const override { return new Model(*this); }
};
}
-25
View File
@@ -1,25 +0,0 @@
#ifndef Components_Particle_h__
#define Components_Particle_h__
#include "System.h"
#include "Component.h"
#include "Color.h"
#include <vector>
namespace Components
{
struct Particle : Component
{
std::vector<Color> ColorSpectrum;
std::vector<glm::vec3> ScaleSpectrum;
double LifeTime;
std::vector<glm::vec3> VelocitySpectrum;
std::vector<float> AngularVelocitySpectrum;
std::vector<glm::vec3> OrientationSpectrum; //Keep?
virtual Particle* Clone() const override { return new Particle(*this); }
};
}
#endif // !Components_Particle_h__
+5 -25
View File
@@ -5,40 +5,20 @@
#include "Color.h"
#include <vector>
namespace Systems { class ParticleSystem; }
namespace Components
{
struct ParticleEmitter : Component
{
friend class Systems::ParticleSystem;
ParticleEmitter()
: SpawnFrequency(0)
, SpawnCount(0)
, SpreadAngle(0)
, LifeTime(0)
, TimeSinceLastSpawn(100) { } // TEMP fulhack så att partiklarna spawnar direkt
EntityID ParticleTemplate;
int ParticleTemplate;
float SpawnFrequency;
float Speed;
int SpawnCount;
std::vector<Color> ColorSpectrum;
std::vector<glm::vec3> ScaleSpectrum;
std::vector<float> ScaleSpectrum;
float SpreadAngle;
double LifeTime;
bool UseGoalVelocity;
glm::vec3 GoalVelocity;
std::vector<float> AngularVelocitySpectrum;
std::vector<glm::vec3> OrientationSpectrum; //Keep?
private:
double TimeSinceLastSpawn;
virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); }
float LifeTime;
std::vector<float[3]> VelocitySpectrum;
std::vector<float[3]> AngularVelocitySpectrum;
};
}
-2
View File
@@ -13,8 +13,6 @@ struct Physics : Component
float Mass;
bool Static;
virtual Physics* Clone() const override { return new Physics(*this); }
};
}
-21
View File
@@ -1,21 +0,0 @@
#ifndef Player_h__
#define Player_h__
#include "Component.h"
namespace Components
{
struct Player : Component
{
Player()
: ID(0) { }
int ID;
virtual Player* Clone() const override { return new Player(*this); }
};
}
#endif // Player_h__
+4 -13
View File
@@ -9,24 +9,15 @@ namespace Components
struct PointLight : Component
{
PointLight()
: Specular(1.0f, 1.0f, 1.0f)
, Diffuse(1.0f, 1.0f, 1.0f)
, specularExponent(50.0f)
, ConstantAttenuation(1.0f)
, LinearAttenuation(0.f)
, QuadraticAttenuation(3.f)
{ }
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation;
float Intensity;
float MaxRange;
float constantAttenuation, linearAttenuation, quadraticAttenuation;
float spotExponent;
Color color;
glm::vec3 Specular;
glm::vec3 Diffuse;
float specularExponent;
float Scale;
virtual PointLight* Clone() const override { return new PointLight(*this); }
};
}
-2
View File
@@ -17,8 +17,6 @@ struct SoundEmitter : Component
float Pitch;
bool Loop;
std::string Path;
virtual SoundEmitter* Clone() const override { return new SoundEmitter(*this); }
};
}
@@ -6,14 +6,12 @@
namespace Components
{
struct SphereShape : Component
struct Sphere : Component
{
SphereShape()
Sphere()
: Radius(1.f){ }
float Radius;
virtual SphereShape* Clone() const override { return new SphereShape(*this); }
};
}
-2
View File
@@ -13,8 +13,6 @@ struct Sprite : Component
{
std::string SpriteFile;
Color Color;
virtual Sprite* Clone() const override { return new Sprite(*this); }
};
}
-17
View File
@@ -1,17 +0,0 @@
#ifndef TankSteering_h__
#define TankSteering_h__
#include "Component.h"
namespace Components
{
struct TankSteering : Component
{
EntityID Player;
EntityID Turret;
EntityID Barrel;
TankSteering* Clone() const override { return new TankSteering(*this); }
};
}
#endif // TankSteering_h__
+1 -6
View File
@@ -6,12 +6,7 @@
namespace Components
{
struct Template
: public Component
{
virtual Template* Clone() const override { return nullptr; }
};
struct Template : Component { };
}
#endif // !Components_Template_h__
-20
View File
@@ -1,20 +0,0 @@
#ifndef TowerSteering_h__
#define TowerSteering_h__
#include "Component.h"
namespace Components
{
struct TowerSteering : Component
{
TowerSteering()
: TurnSpeed(1.f), Axis(glm::vec3(0,1,0)){ }
float TurnSpeed;
glm::vec3 Axis;
virtual TowerSteering* Clone() const override { return new TowerSteering(*this); }
};
}
#endif // TowerSteering_h__
+1 -3
View File
@@ -6,7 +6,7 @@
namespace Components
{
struct Transform : public Component
struct Transform : Component
{
Transform()
: Scale(glm::vec3(1.f)) { }
@@ -15,8 +15,6 @@ struct Transform : public Component
glm::quat Orientation;
glm::vec3 Velocity;
glm::vec3 Scale;
virtual Transform* Clone() const override { return new Transform(*this); }
};
}
+1 -7
View File
@@ -10,8 +10,7 @@ namespace Components
struct Vehicle : Component
{
Vehicle()
: MaxTorque(1000.0f), MinRPM(1000.0f), OptimalRPM(3000.0f), MaxRPM(4000.0f), MaxSteeringAngle(35), TopSpeed(130.0f),
MaxSpeedFullSteeringAngle(40.0f), SpringDamping(1.f){ }
: MaxTorque(500.0f), MinRPM(1000.0f), OptimalRPM(5500.0f), MaxRPM(7500.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { }
float MaxTorque;
float MinRPM;
@@ -19,12 +18,7 @@ struct Vehicle : Component
float MaxRPM;
// Degrees
float MaxSteeringAngle;
//TopSpeed not working fully yet
float TopSpeed;
float MaxSpeedFullSteeringAngle;
float SpringDamping;
Vehicle* Clone() const override { return new Vehicle(*this); }
};
}
-29
View File
@@ -1,29 +0,0 @@
#ifndef Components_Viewport_h__
#define Components_Viewport_h__
#include "Component.h"
namespace Components
{
struct Viewport : Component
{
Viewport()
: Left(0.f)
, Top(0.f)
, Right(1.f)
, Bottom(1.f)
, Camera(0) { }
float Left;
float Top;
float Right;
float Bottom;
EntityID Camera;
virtual Viewport* Clone() const override { return new Viewport(*this); }
};
}
#endif // Components_Viewport_h__
+1 -5
View File
@@ -14,7 +14,7 @@ struct Wheel : Component
Wheel()
: AxleID(0), Radius(0), Width(0), Mass(0), Steering(false), DownDirection(glm::vec3(0, -1, 0)), Friction(1.5f), SlipAngle(0.0f),
MaxBreakingTorque(50000.f), ConnectedToHandbrake(false), SuspensionStrength(50.0f), TorqueRatio(0.25f) { }
MaxBreakingTorque(1500.0f), ConnectedToHandbrake(false), SuspensionStrength(50.0f) { }
// The Hardpoint MUST be positioned INSIDE the chassis.
glm::vec3 Hardpoint;
@@ -30,14 +30,10 @@ struct Wheel : Component
float SlipAngle;
float MaxBreakingTorque;
bool ConnectedToHandbrake;
// The wheels total TorqueRatio must be equal to 1
float TorqueRatio;
private:
int ID;
glm::quat OriginalOrientation;
Wheel* Clone() const override { return new Wheel(*this); }
};
}
-18
View File
@@ -1,18 +0,0 @@
#ifndef Components_WheelPair_h__
#define Components_WheelPair_h__
#include "Component.h"
namespace Components
{
struct WheelPair : Component
{
// Flag for pair wheels
virtual WheelPair* Clone() const override { return new WheelPair(*this); }
};
}
#endif // Components_WheelPair_h__
+1 -14
View File
@@ -1,10 +1,7 @@
#include <string>
#include <sstream>
#include "EventBroker.h"
#include "Renderer.h"
#include "InputManager.h"
#include "GUI/Frame.h"
#include "GameWorld.h"
class Engine
@@ -12,16 +9,10 @@ class Engine
public:
Engine(int argc, char* argv[])
{
m_EventBroker = std::make_shared<EventBroker>();
m_Renderer = std::make_shared<Renderer>();
m_Renderer->Initialize();
m_InputManager = std::make_shared<InputManager>(m_Renderer->GetWindow(), m_EventBroker);
//m_UIParent = std::make_shared<GUI::Frame>(m_EventBroker);
m_World = std::make_shared<GameWorld>(m_EventBroker, m_Renderer);
m_World = std::make_shared<GameWorld>(m_Renderer);
m_World->Initialize();
m_LastTime = glfwGetTime();
@@ -35,7 +26,6 @@ public:
double dt = currentTime - m_LastTime;
m_LastTime = currentTime;
m_InputManager->Update(dt);
m_World->Update(dt);
m_Renderer->Draw(dt);
@@ -43,10 +33,7 @@ public:
}
private:
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;
// TODO: This should ultimately live in GameFrame
std::shared_ptr<GameWorld> m_World;
-29
View File
@@ -1,29 +0,0 @@
#include "PrecompiledHeader.h"
#include "EventBroker.h"
BaseEventRelay::~BaseEventRelay()
{
if (m_Broker != nullptr)
{
m_Broker->Unsubscribe(*this);
}
}
void EventBroker::Unsubscribe(BaseEventRelay &relay) // ?
{
auto itpair = m_Subscribers.equal_range(relay.m_TypeName);
for (auto it = itpair.first; it != itpair.second; ++it)
{
if (it->second == &relay)
{
m_Subscribers.erase(it);
break;
}
}
}
void EventBroker::Subscribe(BaseEventRelay &relay)
{
relay.m_Broker = this;
m_Subscribers.insert(std::make_pair(relay.m_TypeName, &relay));
}
-96
View File
@@ -1,96 +0,0 @@
#ifndef MessageRelay_h__
#define MessageRelay_h__
#include <typeinfo>
#include <functional>
#include <unordered_map>
#include <list>
#define EVENT_SUBSCRIBE_MEMBER(relay, handler) \
relay = decltype(relay)(std::bind(handler, this, std::placeholders::_1)); \
EventBroker->Subscribe(relay);
struct Event
{
protected:
Event() { }
};
class EventBroker;
class BaseEventRelay
{
friend class EventBroker;
protected:
BaseEventRelay(std::string typeName)
: m_TypeName(typeName), m_Broker(nullptr) { }
~BaseEventRelay();
public:
virtual bool Receive(const Event &event) = 0;
protected:
std::string m_TypeName;
EventBroker* m_Broker;
};
template <typename EventType>
class EventRelay : public BaseEventRelay
{
public:
typedef std::function<bool(const EventType&)> CallbackType;
EventRelay()
: m_Callback(nullptr)
, BaseEventRelay(typeid(EventType).name()) { }
EventRelay(CallbackType callback)
: m_Callback(callback)
, BaseEventRelay(typeid(EventType).name()) { }
protected:
bool Receive(const Event &event) override;
private:
CallbackType m_Callback;
};
template <typename EventType>
bool EventRelay<EventType>::Receive(const Event &event)
{
if (m_Callback != nullptr)
{
return m_Callback(static_cast<const EventType&>(event));
}
else
{
return false;
}
}
class EventBroker
{
template <typename EventType> friend class EventRelay;
public:
template <typename EventType>
void Publish(const EventType &event);
void Subscribe(BaseEventRelay &relay);
void Unsubscribe(BaseEventRelay &relay);
private:
std::unordered_multimap<std::string, BaseEventRelay*> m_Subscribers;
};
template <typename EventType>
void EventBroker::Publish(const EventType &event)
{
auto itpair = m_Subscribers.equal_range(typeid(EventType).name());
for (auto it = itpair.first; it != itpair.second; ++it)
{
it->second->Receive(event);
}
}
#endif // MessageRelay_h__
-18
View File
@@ -1,18 +0,0 @@
#ifndef Events_ApplyForce_h__
#define Events_ApplyForce_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct ApplyForce : Event
{
EntityID Entity;
double DeltaTime;
glm::vec3 Force;
};
}
#endif // Events_ApplyForce_h__
-18
View File
@@ -1,18 +0,0 @@
#ifndef Events_ApplyPointImpulse_h__
#define Events_ApplyPointImpulse_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct ApplyPointImpulse : Event
{
EntityID Entity;
glm::vec3 Position;
glm::vec3 Impulse;
};
}
#endif // Events_ApplyPointImpulse_h__
-21
View File
@@ -1,21 +0,0 @@
#ifndef Events_BindGamepadAxis_h__
#define Events_BindGamepadAxis_h__
#include <boost/any.hpp>
#include "EventBroker.h"
#include "Events/GamepadAxis.h"
namespace Events
{
struct BindGamepadAxis : Event
{
Gamepad::Axis Axis;
std::string Command;
float Value;
};
}
#endif // Events_BindGamepadAxis_h__
-21
View File
@@ -1,21 +0,0 @@
#ifndef Events_BindGamepadButton_h__
#define Events_BindGamepadButton_h__
#include <boost/any.hpp>
#include "EventBroker.h"
#include "Events/GamepadButton.h"
namespace Events
{
struct BindGamepadButton : Event
{
Gamepad::Button Button;
std::string Command;
float Value;
};
}
#endif // Events_BindGamepadButton_h__
-20
View File
@@ -1,20 +0,0 @@
#ifndef Events_BindKey_h__
#define Events_BindKey_h__
#include <boost/any.hpp>
#include "EventBroker.h"
namespace Events
{
struct BindKey : Event
{
int KeyCode;
std::string Command;
float Value;
};
}
#endif // Events_BindKey_h__
-18
View File
@@ -1,18 +0,0 @@
#ifndef Events_BindMouseButton_h__
#define Events_BindMouseButton_h__
#include "EventBroker.h"
namespace Events
{
struct BindMouseButton : Event
{
int Button;
std::string Command;
float Value;
};
}
#endif // Events_BindMouseButton_h__
-16
View File
@@ -1,16 +0,0 @@
#ifndef Events_CastRay_h__
#define Events_CastRay_h__
#include "EventBroker.h"
namespace Events
{
struct CastRay : Event
{
glm::vec3 Direction;
};
}
#endif // Events_CastRay_h__
-18
View File
@@ -1,18 +0,0 @@
#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__
-32
View File
@@ -1,32 +0,0 @@
#ifndef Events_GamepadAxis_h__
#define Events_GamepadAxis_h__
#include "EventBroker.h"
namespace Gamepad
{
enum class Axis
{
LeftX,
LeftY,
RightX,
RightY,
LeftTrigger,
RightTrigger,
LAST = RightTrigger
};
}
namespace Events
{
struct GamepadAxis : Event
{
int GamepadID;
Gamepad::Axis Axis;
float Value;
};
}
#endif // Events_GamepadAxis_h__
-45
View File
@@ -1,45 +0,0 @@
#ifndef Events_GamepadButton_h__
#define Events_GamepadButton_h__
#include "EventBroker.h"
namespace Gamepad
{
enum class Button
{
Up,
Down,
Left,
Right,
Start,
Back,
LeftThumb,
RightThumb,
LeftShoulder,
RightShoulder,
A,
B,
X,
Y,
LAST = Y
};
}
namespace Events
{
struct GamepadButtonDown : Event
{
int GamepadID;
Gamepad::Button Button;
};
struct GamepadButtonUp : Event
{
int GamepadID;
Gamepad::Button Button;
};
}
#endif // Events_GamepadButton_h__
-20
View File
@@ -1,20 +0,0 @@
#ifndef Events_InputCommand_h__
#define Events_InputCommand_h__
#include <boost/any.hpp>
#include "EventBroker.h"
namespace Events
{
struct InputCommand : Event
{
unsigned int PlayerID;
std::string Command;
float Value;
};
}
#endif // Events_InputCommand_h__
-16
View File
@@ -1,16 +0,0 @@
#ifndef Events_KeyDown_h__
#define Events_KeyDown_h__
#include "EventBroker.h"
namespace Events
{
struct KeyDown : Event
{
int KeyCode;
};
}
#endif // Events_KeyDown_h__
-16
View File
@@ -1,16 +0,0 @@
#ifndef Events_KeyUp_h__
#define Events_KeyUp_h__
#include "EventBroker.h"
namespace Events
{
struct KeyUp : Event
{
int KeyCode;
};
}
#endif // Events_KeyUp_h__
-14
View File
@@ -1,14 +0,0 @@
#ifndef Events_LockMouse_h__
#define Events_LockMouse_h__
#include "EventBroker.h"
namespace Events
{
struct LockMouse : Event { };
struct UnlockMouse : Event { };
}
#endif // Events_LockMouse_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_MouseMove_h__
#define Events_MouseMove_h__
#include "EventBroker.h"
namespace Events
{
struct MouseMove : Event
{
double X, Y;
double DeltaX, DeltaY;
};
}
#endif // Events_MouseMove_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_MousePress_h__
#define Events_MousePress_h__
#include "EventBroker.h"
namespace Events
{
struct MousePress : Event
{
int Button;
double X, Y;
};
}
#endif // Events_MousePress_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_MouseRelease_h__
#define Events_MouseRelease_h__
#include "EventBroker.h"
namespace Events
{
struct MouseRelease : Event
{
int Button;
double X, Y;
};
}
#endif // Events_MouseRelease_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Event_PlaySound_h__
#define Event_PlaySound_h__
#include "EventBroker.h"
namespace Events
{
struct PlaySound : Event
{
EntityID Emitter;
std::string Resource;
};
}
#endif // Event_PlaySound_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_RayIntersection_h__
#define Events_RayIntersection_h__
#include "EventBroker.h"
#include "Entity.h"
namespace Events
{
struct RayIntersection : Event
{
EntityID Entity;
};
}
#endif // Events_RayIntersection_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_SetVelocity_h__
#define Events_SetVelocity_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct SetVelocity : Event
{
EntityID Entity;
glm::vec3 Velocity;
};
}
#endif // Events_SetVelocity_h__
-19
View File
@@ -1,19 +0,0 @@
#ifndef Events_TankSteer_h__
#define Events_TankSteer_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct TankSteer : Event
{
EntityID Entity;
float PositionX;
float PositionY;
bool Handbrake;
};
}
#endif // Events_TankSteer_h__
+2 -22
View File
@@ -10,18 +10,12 @@ template <typename T>
class Factory
{
public:
/*void Register(std::string name, std::function<T(void)> factoryFunction)
void Register(std::string name, std::function<T(void)> factoryFunction)
{
m_FactoryFunctions[name] = factoryFunction;
}*/
template <typename T2>
void Register(std::function<T(void)> factoryFunction)
{
m_FactoryFunctions[typeid(T2).name()] = factoryFunction;
}
/*T Create(std::string name)
T Create(std::string name)
{
auto it = m_FactoryFunctions.find(name);
if (it != m_FactoryFunctions.end())
@@ -32,20 +26,6 @@ public:
{
return nullptr;
}
}*/
template <typename T2>
T Create()
{
auto it = m_FactoryFunctions.find(typeid(T2).name());
if (it != m_FactoryFunctions.end())
{
return it->second();
}
else
{
return nullptr;
}
}
private:
-75
View File
@@ -1,75 +0,0 @@
#ifndef GUI_Frame_h__
#define GUI_Frame_h__
#include <memory>
#include "Util/Rectangle.h"
#include "EventBroker.h"
// HACK: Decouple renderer plz
#include "Renderer.h"
namespace GUI
{
class Frame : public Rectangle
{
public:
enum class Anchor
{
Left,
Right,
Top,
Bottom
};
// Set up a base frame with an event broker
Frame(std::shared_ptr<::EventBroker> eventBroker)
: EventBroker(eventBroker)
, 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(); }
virtual void Initialize() { }
std::shared_ptr<Frame> Parent() const { return m_Parent; }
void SetParent(std::shared_ptr<Frame> parent)
{
parent->AddChild(std::shared_ptr<Frame>(this));
m_Parent = parent;
EventBroker = parent->EventBroker;
}
void AddChild(std::shared_ptr<Frame> child)
{
m_Children.push_back(child);
if (m_Parent != nullptr)
{
m_Parent->AddChild(child);
}
}
typedef std::list<std::shared_ptr<Frame>>::const_iterator FrameChildrenIterator;
FrameChildrenIterator begin()
{
return m_Children.begin();
}
FrameChildrenIterator end()
{
return m_Children.end();
}
virtual void Update(double dt) { }
virtual void Draw(Renderer* renderer) { }
protected:
std::shared_ptr<::EventBroker> EventBroker;
std::shared_ptr<Frame> m_Parent;
std::list<std::shared_ptr<Frame>> m_Children;
};
}
#endif // GUI_Frame_h__
-21
View File
@@ -1,21 +0,0 @@
#ifndef GUI_Viewport_h__
#define GUI_Viewport_h__
#include <memory>
#include "GUI/Frame.h"
namespace GUI
{
class Viewport : public Frame
{
public:
// Create a frame as a child
Viewport(std::shared_ptr<Frame> parent)
: Frame(parent) { }
};
}
#endif // GUI_Viewport_h__
+205 -1144
View File
File diff suppressed because it is too large Load Diff
+5 -20
View File
@@ -7,13 +7,10 @@
#include "Systems/TransformSystem.h"
//#include "Systems/CollisionSystem.h"
#include "Systems/InputSystem.h"
#include "Systems/DebugSystem.h"
//#include "Systems/LevelGenerationSystem.h"
#include "Systems/ParticleSystem.h"
//#include "Systems/ParticleSystem.h"
//#include "Systems/PlayerSystem.h"
#include "Systems/FreeSteeringSystem.h"
#include "Systems/TankSteeringSystem.h"
#include "Systems/HelicopterSteeringSystem.h"
#include "Systems/RenderSystem.h"
#include "Systems/SoundSystem.h"
#include "Systems/PhysicsSystem.h"
@@ -23,30 +20,23 @@
#include "Components/Input.h"
#include "Components/Model.h"
#include "Components/ParticleEmitter.h"
#include "Components/Particle.h"
#include "Components/PointLight.h"
#include "Components/SoundEmitter.h"
#include "Components/Sprite.h"
#include "Components/Template.h"
#include "Components/Transform.h"
#include "Components/Viewport.h"
#include "Components/Physics.h"
#include "Components/SphereShape.h"
#include "Components/BoxShape.h"
#include "Components/Sphere.h"
#include "Components/Box.h"
#include "Components/Vehicle.h"
#include "Components/Wheel.h"
#include "Components/HingeConstraint.h"
#include "Components/TankSteering.h"
#include "Components/TowerSteering.h"
#include "Components/BarrelSteering.h"
#include "Components/Player.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<Renderer> renderer)
: m_Renderer(renderer), World() { }
void Initialize();
@@ -58,11 +48,6 @@ public:
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);
void BindGamepadButton(Gamepad::Button button, std::string command, float value);
};
#endif // GameWorld_h__
-33
View File
@@ -1,33 +0,0 @@
#ifndef InputController_h__
#define InputController_h__
#include <memory>
#include "EventBroker.h"
#include "Events/InputCommand.h"
#include "Events/MouseMove.h"
class InputController
{
public:
InputController(std::shared_ptr<::EventBroker> eventBroker)
: EventBroker(eventBroker) { Initialize(); }
virtual void Initialize()
{
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &InputController::OnCommand);
EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &InputController::OnMouseMove);
}
virtual bool OnCommand(const Events::InputCommand &event) { return false; }
virtual bool OnMouseMove(const Events::MouseMove &event) { return false; }
protected:
std::shared_ptr<::EventBroker> EventBroker;
private:
EventRelay<Events::InputCommand> m_EInputCommand;
EventRelay<Events::MouseMove> m_EMouseMove;
};
#endif // InputController_h__
-229
View File
@@ -1,229 +0,0 @@
#include "PrecompiledHeader.h"
#include "InputManager.h"
#include <XInput.h>
void InputManager::Initialize()
{
m_LastGamepadAxisState = std::array<GamepadAxisState, XUSER_MAX_COUNT>();
m_LastGamepadButtonState = std::array<GamepadButtonState, XUSER_MAX_COUNT>();
EVENT_SUBSCRIBE_MEMBER(m_ELockMouse, &InputManager::OnLockMouse);
EVENT_SUBSCRIBE_MEMBER(m_EUnlockMouse, &InputManager::OnUnlockMouse);
}
void InputManager::Update(double dt)
{
m_LastKeyState = m_CurrentKeyState;
m_LastMouseState = m_CurrentMouseState;
m_LastMouseX = m_CurrentMouseX;
m_LastMouseY = m_CurrentMouseY;
// Keyboard input
for (int i = 0; i <= GLFW_KEY_LAST; ++i)
{
m_CurrentKeyState[i] = glfwGetKey(m_GLFWWindow, i);
if (m_CurrentKeyState[i] != m_LastKeyState[i])
{
// Publish key events
if (m_CurrentKeyState[i])
{
Events::KeyDown e;
e.KeyCode = i;
EventBroker->Publish(e);
}
else
{
Events::KeyUp e;
e.KeyCode = i;
EventBroker->Publish(e);
}
}
}
// Mouse buttons
for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i)
{
m_CurrentMouseState[i] = glfwGetMouseButton(m_GLFWWindow, i);
if (m_CurrentMouseState[i] != m_LastMouseState[i])
{
double x, y;
glfwGetCursorPos(m_GLFWWindow, &x, &y);
// Publish mouse button events
if (m_CurrentMouseState[i])
{
Events::MousePress e;
e.Button = i;
e.X = x;
e.Y = y;
EventBroker->Publish(e);
}
else
{
Events::MouseRelease e;
e.Button = i;
e.X = x;
e.Y = y;
EventBroker->Publish(e);
}
}
}
// Mouse movement
glfwGetCursorPos(m_GLFWWindow, &m_CurrentMouseX, &m_CurrentMouseY);
m_CurrentMouseDeltaX = m_CurrentMouseX - m_LastMouseX;
m_CurrentMouseDeltaY = m_CurrentMouseY - m_LastMouseY;
if (m_CurrentMouseDeltaX != 0 || m_CurrentMouseDeltaY != 0)
{
// Publish mouse move events
Events::MouseMove e;
e.X = m_CurrentMouseX;
e.Y = m_CurrentMouseY;
e.DeltaX = m_CurrentMouseDeltaX;
e.DeltaY = m_CurrentMouseDeltaY;
EventBroker->Publish(e);
}
// // Lock mouse while holding LMB
// if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
// m_LastMouseX = m_Renderer->Width() / 2.f; // xpos;
// m_LastMouseY = m_Renderer->Height() / 2.f; // ypos;
// glfwSetCursorPos(m_GLFWWindow, m_LastMouseX, m_LastMouseY);
// }
// // Hide/show cursor with LMB
// if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
// glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
// }
// if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
// {
// glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// }
// Xbox360 controller
//using namespace ;
DWORD dwResult;
for (int i = 0; i < MAX_GAMEPADS; i++)
{
XINPUT_STATE state = { 0 };
// Simply get the state of the controller from XInput.
dwResult = XInputGetState(i, &state);
if (dwResult == 0)
{
if(std::abs(state.Gamepad.sThumbLX) <= XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
state.Gamepad.sThumbLX = 0;
if(std::abs(state.Gamepad.sThumbLY) <= XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
state.Gamepad.sThumbLY = 0;
if(std::abs(state.Gamepad.sThumbRX) <= XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
state.Gamepad.sThumbRX = 0;
if(std::abs(state.Gamepad.sThumbRY) <= XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
state.Gamepad.sThumbRY = 0;
if(std::abs(state.Gamepad.bLeftTrigger) <= XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
state.Gamepad.bLeftTrigger = 0;
if(std::abs(state.Gamepad.bRightTrigger) <= XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
state.Gamepad.bRightTrigger = 0;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::LeftX)] = state.Gamepad.sThumbLX / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::LeftY)] = state.Gamepad.sThumbLY / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::RightX)] = state.Gamepad.sThumbRX / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::RightY)] = state.Gamepad.sThumbRY / 32767.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::LeftTrigger)] = state.Gamepad.bLeftTrigger / 255.f;
m_CurrentGamepadAxisState[i][static_cast<int>(Gamepad::Axis::RightTrigger)] = state.Gamepad.bRightTrigger / 255.f;
PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftX);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftY);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightX);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightY);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftTrigger);
PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightTrigger);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Up)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Down)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Left)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Right)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Start)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_START);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Back)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::LeftThumb)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::RightThumb)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::LeftShoulder)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::RightShoulder)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::A)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_A);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::B)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_B);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::X)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_X);
m_CurrentGamepadButtonState[i][static_cast<int>(Gamepad::Button::Y)] = static_cast<bool>(state.Gamepad.wButtons & XINPUT_GAMEPAD_Y);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Up);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Down);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Left);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Right);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Start);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Back);
PublishGamepadButtonIfChanged(i, Gamepad::Button::LeftThumb);
PublishGamepadButtonIfChanged(i, Gamepad::Button::RightThumb);
PublishGamepadButtonIfChanged(i, Gamepad::Button::LeftShoulder);
PublishGamepadButtonIfChanged(i, Gamepad::Button::RightShoulder);
PublishGamepadButtonIfChanged(i, Gamepad::Button::A);
PublishGamepadButtonIfChanged(i, Gamepad::Button::B);
PublishGamepadButtonIfChanged(i, Gamepad::Button::X);
PublishGamepadButtonIfChanged(i, Gamepad::Button::Y);
}
}
m_LastKeyState = m_CurrentKeyState;
m_LastMouseState = m_CurrentMouseState;
m_LastMouseX = m_CurrentMouseX;
m_LastMouseY = m_CurrentMouseY;
m_LastGamepadAxisState = m_CurrentGamepadAxisState;
m_LastGamepadButtonState = m_CurrentGamepadButtonState;
}
void InputManager::PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis)
{
float currentValue = m_CurrentGamepadAxisState[gamepadID][static_cast<int>(axis)];
float lastValue = m_LastGamepadAxisState[gamepadID][static_cast<int>(axis)];
if (currentValue != lastValue)
{
Events::GamepadAxis e;
e.GamepadID = gamepadID;
e.Axis = axis;
e.Value = currentValue;
EventBroker->Publish(e);
}
}
void InputManager::PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button)
{
bool currentState = m_CurrentGamepadButtonState[gamepadID][static_cast<int>(button)];
float lastState = m_LastGamepadButtonState[gamepadID][static_cast<int>(button)];
if (currentState != lastState)
{
if (currentState == true)
{
Events::GamepadButtonDown e;
e.GamepadID = gamepadID;
e.Button = button;
EventBroker->Publish(e);
}
else
{
Events::GamepadButtonUp e;
e.GamepadID = gamepadID;
e.Button = button;
EventBroker->Publish(e);
}
}
}
bool InputManager::OnLockMouse(const Events::LockMouse &event)
{
m_MouseLocked = true;
glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
return true;
}
bool InputManager::OnUnlockMouse(const Events::UnlockMouse &event)
{
m_MouseLocked = false;
glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
return true;
}
-67
View File
@@ -1,67 +0,0 @@
#ifndef InputManager_h__
#define InputManager_h__
#include <array>
#include "EventBroker.h"
#include "Events/KeyDown.h"
#include "Events/KeyUp.h"
#include "Events/MousePress.h"
#include "Events/MouseRelease.h"
#include "Events/MouseMove.h"
#include "Events/LockMouse.h"
#include "Events/GamepadAxis.h"
#include "Events/GamepadButton.h"
class InputManager
{
public:
InputManager(GLFWwindow* window, std::shared_ptr<::EventBroker> eventBroker)
: m_GLFWWindow(window)
, EventBroker(eventBroker)
, m_CurrentKeyState()
, m_LastKeyState()
, m_CurrentMouseState()
, m_LastMouseState()
, m_CurrentMouseX(0), m_CurrentMouseY(0)
, m_LastMouseX(0), m_LastMouseY(0)
, m_CurrentMouseDeltaX(0), m_CurrentMouseDeltaY(0)
, m_MouseLocked(false)
{ Initialize(); }
void Initialize();
static const short MAX_GAMEPADS = 4;
void Update(double dt);
private:
GLFWwindow* m_GLFWWindow;
std::shared_ptr<::EventBroker> EventBroker;
EventRelay<Events::LockMouse> m_ELockMouse;
bool OnLockMouse(const Events::LockMouse &event);
EventRelay<Events::UnlockMouse> m_EUnlockMouse;
bool OnUnlockMouse(const Events::UnlockMouse &event);
std::array<int, GLFW_KEY_LAST+1> m_CurrentKeyState;
std::array<int, GLFW_KEY_LAST+1> m_LastKeyState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> m_CurrentMouseState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> m_LastMouseState;
typedef std::array<float, static_cast<int>(Gamepad::Axis::LAST) + 1> GamepadAxisState;
std::array<GamepadAxisState, MAX_GAMEPADS> m_CurrentGamepadAxisState;
std::array<GamepadAxisState, MAX_GAMEPADS> m_LastGamepadAxisState;
typedef std::array<bool, static_cast<int>(Gamepad::Button::LAST) + 1> GamepadButtonState;
std::array<GamepadButtonState, MAX_GAMEPADS> m_CurrentGamepadButtonState;
std::array<GamepadButtonState, MAX_GAMEPADS> m_LastGamepadButtonState;
double m_CurrentMouseX, m_CurrentMouseY;
double m_LastMouseX, m_LastMouseY;
double m_CurrentMouseDeltaX, m_CurrentMouseDeltaY;
bool m_MouseLocked;
void PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis);
void PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button);
};
#endif // InputManager_h__
+4 -116
View File
@@ -1,7 +1,7 @@
#include "PrecompiledHeader.h"
#include "Model.h"
Model::Model(ResourceManager* rm, OBJ &obj)
Model::Model(OBJ &obj, ResourceManager* rm)
{
OBJ::MaterialInfo* currentMaterial = nullptr;
TextureGroup* currentTexGroup = nullptr;
@@ -20,7 +20,7 @@ Model::Model(ResourceManager* rm, OBJ &obj)
// Load texture
auto texture = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->DiffuseTexture.FileName));
// TODO: Load normal map
// 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));
@@ -65,9 +65,7 @@ Model::Model(ResourceManager* rm, OBJ &obj)
if (Vertices.size() > 0)
{
CreateTangents();
//getSimilarVertexIndex();
CreateBuffers(Vertices, Normals, TangentNormals, BiTangentNormals, TextureCoords);
CreateBuffers(Vertices, Normals, TextureCoords);
}
else
{
@@ -75,7 +73,7 @@ Model::Model(ResourceManager* rm, OBJ &obj)
}
}
void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec3> normals, std::vector<glm::vec3> tangents, std::vector<glm::vec3> biTangents, std::vector<glm::vec2>textureCoords)
void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec3> normals, std::vector<glm::vec2>textureCoords)
{
LOG_INFO("Generating VertexBuffer");
@@ -104,32 +102,6 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
LOG_WARNING("Created empty normal buffer!");
}
LOG_INFO("Generating TangentNormalsBuffer");
glGenBuffers(1, &TangentNormalsBuffer);
if (tangents.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, TangentNormalsBuffer);
glBufferData(GL_ARRAY_BUFFER, tangents.size() * sizeof(glm::vec3), &tangents[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, TangentNormalsBuffer");
}
else
{
LOG_WARNING("Created empty tangent buffer!");
}
LOG_INFO("Generating BiTangentNormalsBuffer");
glGenBuffers(1, &BiTangentNormalsBuffer);
if (biTangents.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, BiTangentNormalsBuffer);
glBufferData(GL_ARRAY_BUFFER, biTangents.size() * sizeof(glm::vec3), &biTangents[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, BiTangentNormalsBuffer");
}
else
{
LOG_WARNING("Created empty biTangent buffer!");
}
LOG_INFO("Generating textureCoordBuffer");
glGenBuffers(1, &TextureCoordBuffer);
@@ -160,94 +132,10 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0);
GLERROR("GLEW: BufferFail5");
glBindBuffer(GL_ARRAY_BUFFER, TangentNormalsBuffer);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERROR("GLEW: BufferFail5");
glBindBuffer(GL_ARRAY_BUFFER, BiTangentNormalsBuffer);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, 0);
GLERROR("GLEW: BufferFail5");
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
GLERROR("GLEW: BufferFail5");
}
bool Model::IsNear( float v1, float v2 )
{
return fabs(v1 - v2) < 0.01f;
}
void Model::getSimilarVertexIndex()
{
for(int i = 0; i < Vertices.size(); i++)
{
for(int t = 0; t < Vertices.size(); t++)
{
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)
)
{
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]);
Normals[i] = tempNormal;
Normals[t] = tempNormal;
TangentNormals[i] = tempTangent;
TangentNormals[t] = tempTangent;
BiTangentNormals[i] = tempBiTangent;
BiTangentNormals[t] = tempBiTangent;
}
}
}
}
}
void Model::CreateTangents()
{
for(int i = 0; i < Vertices.size(); i += 3)
{
glm::vec3 v0 = Vertices[i];
glm::vec3 v1 = Vertices[i+1];
glm::vec3 v2 = Vertices[i+2];
glm::vec2 uv0 = TextureCoords[i];
glm::vec2 uv1 = TextureCoords[i+1];
glm::vec2 uv2 = TextureCoords[i+2];
//Calculate the edge of the triangle
glm::vec3 edge1 = v1-v0;
glm::vec3 edge2 = v2-v0;
glm::vec2 deltaUV1 = uv1 - uv0;
glm::vec2 deltaUV2 = uv2 - uv0;
float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
glm::vec3 tangent, biTangent;
tangent = (edge1 * deltaUV2.y - edge2 * deltaUV1.y) * r;
biTangent = (edge2 * deltaUV1.x - edge1 * deltaUV2.x) * r;
TangentNormals.push_back(tangent);
TangentNormals.push_back(tangent);
TangentNormals.push_back(tangent);
BiTangentNormals.push_back(biTangent);
BiTangentNormals.push_back(biTangent);
BiTangentNormals.push_back(biTangent);
}
}
+2 -12
View File
@@ -17,7 +17,7 @@
class Model : public Resource
{
public:
Model(ResourceManager* rm, OBJ &obj);
Model(OBJ &obj, ResourceManager* rm);
struct TextureGroup
{
@@ -38,14 +38,10 @@ public:
private:
std::vector<glm::vec3> Normals;
std::vector<glm::vec3> TangentNormals;
std::vector<glm::vec3> BiTangentNormals;
std::vector<glm::vec2> TextureCoords;
GLuint VertexBuffer;
GLuint NormalBuffer;
GLuint TangentNormalsBuffer;
GLuint BiTangentNormalsBuffer;
GLuint TextureCoordBuffer;
bool Loadobj(
@@ -57,15 +53,9 @@ private:
void CreateBuffers(
std::vector<glm::vec3> _Vertices,
std::vector<glm::vec3> _Normals,
std::vector<glm::vec3> _Tangents,
std::vector<glm::vec3> _BiTangents,
std::vector<glm::vec3> _Normals,
std::vector<glm::vec2>_TextureCoords
);
void CreateTangents();
bool IsNear(float v1, float v2);
void getSimilarVertexIndex();
};
#endif // Model_h__
+1 -1
View File
@@ -9,7 +9,7 @@ bool OBJ::LoadFromFile(std::string filename)
std::ifstream file(m_Path.string());
if (!file.is_open())
{
LOG_ERROR("Failed to open .obj \"%s\": %s", m_Path.string().c_str(), strerror(errno));
LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str());
return false;
}
+1 -3
View File
@@ -12,9 +12,7 @@
#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>
#include "ResourceManager.h"
class OBJ : public Resource
class OBJ
{
public:
struct MaterialInfo
+22 -21
View File
@@ -7,13 +7,13 @@
void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpVehicleInstance& vehicle, EntityID vehicleEntity, std::vector<EntityID> wheelEntities)
{
auto vehicleComponent = world->GetComponent<Components::Vehicle>(vehicleEntity);
auto vehicleComponent = world->GetComponent<Components::Vehicle>(vehicleEntity, "Vehicle");
WheelData wheelData;
for (int i = 0; i < wheelEntities.size(); i++)
{
wheelData.WheelComponent = world->GetComponent<Components::Wheel>(wheelEntities[i]);
wheelData.TransformComponent = world->GetComponent<Components::Transform>(wheelEntities[i]);
wheelData.WheelComponent = world->GetComponent<Components::Wheel>(wheelEntities[i], "Wheel");
wheelData.TransformComponent = world->GetComponent<Components::Transform>(wheelEntities[i], "Transform");
m_Wheels.push_back(wheelData);
}
@@ -22,7 +22,7 @@ void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpV
//
vehicle.m_data = new hkpVehicleData;
vehicle.m_driverInput = new hkpVehicleDefaultAnalogDriverInput;
vehicle.m_steering = new TankSteering;
vehicle.m_steering = new hkpVehicleDefaultSteering;
vehicle.m_engine = new hkpVehicleDefaultEngine;
vehicle.m_transmission = new hkpVehicleDefaultTransmission;
vehicle.m_brake = new hkpVehicleDefaultBrake;
@@ -48,6 +48,7 @@ void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpV
setupWheelCollide(physicsWorld, vehicle, *static_cast<hkpVehicleRayCastWheelCollide*>(vehicle.m_wheelCollide));
//
// Check that all components are present.
//
@@ -104,7 +105,7 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data
data.m_torquePitchFactor = 0.5f;
data.m_torqueYawFactor = 0.35f;
data.m_chassisUnitInertiaYaw = 0.8f;
data.m_chassisUnitInertiaYaw = 1.0f;
data.m_chassisUnitInertiaRoll = 1.0f;
data.m_chassisUnitInertiaPitch = 1.0f;
@@ -164,7 +165,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS
// [mph/h] The steering angle decreases linearly
// based on your overall max speed of the vehicle.
steering.m_maxSpeedFullSteeringAngle = vehicleComponent.MaxSpeedFullSteeringAngle; // * (1.605f / 3.6f); //MPH???!
steering.m_maxSpeedFullSteeringAngle = 70.0f * (1.605f / 3.6f); //MPH???!
for (int i = 0; i < m_Wheels.size(); i++)
{
@@ -197,21 +198,20 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT
transmission.m_gearsRatio.setSize(numberOfGears);
transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels);
transmission.m_downshiftRPM = 3500.0f; //HACK: Should be in VehicleComponent
transmission.m_upshiftRPM = 7000.0f;
transmission.m_downshiftRPM = 3500.0f;
transmission.m_upshiftRPM = 6500.0f;
transmission.m_clutchDelayTime = 0.0f;
transmission.m_reverseGearRatio = 1.0f;
transmission.m_gearsRatio[0] = 3.0f;
transmission.m_gearsRatio[1] = 2.25f;
transmission.m_gearsRatio[2] = 1.5f;
transmission.m_gearsRatio[3] = 1.0f;
for(int i = 0; i < m_Wheels.size(); i++)
{
// The wheels total TorqueRatio must be equal to 1
transmission.m_wheelsTorqueRatio[i] = m_Wheels[i].WheelComponent->TorqueRatio;
}
transmission.m_gearsRatio[0] = 2.0f;
transmission.m_gearsRatio[1] = 1.5f;
transmission.m_gearsRatio[2] = 1.0f;
transmission.m_gearsRatio[3] = 0.75f;
transmission.m_wheelsTorqueRatio[0] = 0.2f;
transmission.m_wheelsTorqueRatio[1] = 0.2f;
transmission.m_wheelsTorqueRatio[2] = 0.3f;
transmission.m_wheelsTorqueRatio[3] = 0.3f;
transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio(
vehicleComponent.TopSpeed,
@@ -246,8 +246,9 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS
suspension.m_wheelParams[i].m_length = suspensionLength;
suspension.m_wheelSpringParams[i].m_strength = m_Wheels[i].WheelComponent->SuspensionStrength;
suspension.m_wheelSpringParams[i].m_dampingCompression = vehicleComponent.SpringDamping;
suspension.m_wheelSpringParams[i].m_dampingRelaxation = vehicleComponent.SpringDamping;
const float wd = 3.0f;
suspension.m_wheelSpringParams[i].m_dampingCompression = wd;
suspension.m_wheelSpringParams[i].m_dampingRelaxation = wd;
suspension.m_wheelParams[i].m_hardpointChassisSpace.set(m_Wheels[i].WheelComponent->Hardpoint.x, m_Wheels[i].WheelComponent->Hardpoint.y, m_Wheels[i].WheelComponent->Hardpoint.z);
@@ -266,7 +267,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultA
aerodynamics.m_liftCoefficient = -0.3f;
// Extra gavity applies in world space (independent of m_chassisCoordinateSystem).
aerodynamics.m_extraGravityws.set(0.0f, -8.0f, 0.0f); // fuck this shit
aerodynamics.m_extraGravityws.set(0.0f, -5.0f, 0.0f);
}
void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent)
+1 -30
View File
@@ -21,7 +21,6 @@
#include <Physics2012/Vehicle/Engine/Default/hkpVehicleDefaultEngine.h>
#include <Physics2012/Vehicle/VelocityDamper/Default/hkpVehicleDefaultVelocityDamper.h>
#include <Physics2012/Vehicle/Steering/Default/hkpVehicleDefaultSteering.h>
#include <Physics2012/Vehicle/Steering/hkpVehicleSteering.h>
#include <Physics2012/Vehicle/Suspension/Default/hkpVehicleDefaultSuspension.h>
#include <Physics2012/Vehicle/Transmission/Default/hkpVehicleDefaultTransmission.h>
#include <Physics2012/Vehicle/WheelCollide/RayCast/hkpVehicleRayCastWheelCollide.h>
@@ -33,32 +32,6 @@
#include "Components/Wheel.h"
#include "Components/Transform.h"
/// Tank specific steering implementation. Rear wheels steer in opposite direction
/// to front wheels.
class TankSteering: public hkpVehicleDefaultSteering
{
public:
virtual void calcSteering(const hkReal deltaTime, const hkpVehicleInstance* vehicle, const hkpVehicleDriverInput::FilteredDriverInputOutput& filteredInfoOutput, SteeringAnglesOutput& steeringOutput )
{
hkpVehicleDefaultSteering::calcMainSteeringAngle( deltaTime, vehicle, filteredInfoOutput, steeringOutput );
// Wheels.
for (int w_it = 0; w_it < m_doesWheelSteer.getSize(); w_it++)
{
if ( m_doesWheelSteer[w_it] )
{
steeringOutput.m_wheelsSteeringAngle [w_it] = steeringOutput.m_mainSteeringAngle;
}
else
{
// Steer with front and back wheels to simulate a tank.
steeringOutput.m_wheelsSteeringAngle [w_it] = -steeringOutput.m_mainSteeringAngle;
}
}
}
};
class VehicleSetup
{
public:
@@ -69,9 +42,8 @@ public:
{
Components::Wheel* WheelComponent;
Components::Transform* TransformComponent;
};
std::vector<WheelData> m_Wheels;
virtual void setupVehicleData(const hkpWorld* world, hkpVehicleData& data);
@@ -86,7 +58,6 @@ public:
virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent);
virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide);
};
#endif // Physics_Vehicle_h__
-62
View File
@@ -1,62 +0,0 @@
#ifndef RenderQueue_h__
#define RenderQueue_h__
#include <cstdint>
#include <forward_list>
#include "ResourceManager.h"
#include "Texture.h"
#include "Model.h"
class RenderQueue;
struct RenderJob
{
friend class RenderQueue;
unsigned int ViewportID;
unsigned int TextureID;
GLuint DiffuseTexture;
GLuint NormalTexture;
GLuint SpecularTexture;
GLuint VAO;
unsigned int StartIndex;
unsigned int EndIndex;
glm::mat4 ModelMatrix;
protected:
uint64_t Hash;
void CalculateHash()
{
Hash = ViewportID << 58 // 6 bits
| TextureID << 42; // 16 bits
}
bool operator<(const RenderJob& rhs)
{
return this->Hash < rhs.Hash;
}
};
class RenderQueue
{
public:
void Add(RenderJob &job)
{
job.CalculateHash();
m_Jobs.push_front(job);
m_Jobs.sort();
}
void Clear()
{
m_Jobs.clear();
}
private:
std::forward_list<RenderJob> m_Jobs;
};
#endif // RenderQueue_h__
+368 -361
View File
@@ -13,15 +13,12 @@ Renderer::Renderer()
m_DrawWireframe = false;
m_DrawBounds = false;
#endif
Gamma = 2.2f;
CAtt = 1.0f;
LAtt = 0.0f;
QAtt = 3.0f;
m_ShadowMapRes = 2048*6;
m_ShadowMapRes = 2048;
m_SunPosition = glm::vec3(0, 3.5f, 10);
m_SunTarget = glm::vec3(0, 0, 0);
m_SunProjection = glm::ortho<float>(10.f, -10.f, 10.f, -10.f, 10.f, -10.f);
/* Lights = 0;*/
m_SunProjection = glm::ortho<float>(-100, 100, -100, 100, -100, 100);
Lights = 0;
}
void Renderer::Initialize()
@@ -34,11 +31,11 @@ void Renderer::Initialize()
}
// Create a window
m_Width = 1280;
m_Height = 720;
WIDTH = 1280;
HEIGHT = 720;
// Antialiasing
//glfwWindowHint(GLFW_SAMPLES, 16);
m_Window = glfwCreateWindow(m_Width, m_Height, "OpenGL", nullptr, nullptr);
m_Window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr);
if (!m_Window)
{
LOG_ERROR("GLFW: Failed to create window");
@@ -66,7 +63,7 @@ void Renderer::Initialize()
}
// Create Camera
m_Camera = std::make_shared<Camera>(45.f, (float)m_Width / m_Height, 0.01f, 1000.f);
m_Camera = std::make_shared<Camera>(45.f, (float)WIDTH / HEIGHT, 0.01f, 1000.f);
m_Camera->Position(glm::vec3(0.0f, 0.0f, 2.f));
glfwSwapInterval(m_VSync);
@@ -92,7 +89,12 @@ void Renderer::LoadContent()
m_ShaderProgramNormals.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Normals.frag.glsl")));
m_ShaderProgramNormals.Compile();
m_ShaderProgramNormals.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")));
m_ShaderProgramShadows.Compile();
m_ShaderProgramShadows.Link();
m_ShaderProgramShadowsDrawDepth.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/VisualizeDepth.vert.glsl")));
m_ShaderProgramShadowsDrawDepth.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/VisualizeDepth.frag.glsl")));
m_ShaderProgramShadowsDrawDepth.Compile();
@@ -108,20 +110,22 @@ void Renderer::LoadContent()
m_ShaderProgramSkybox.Compile();
m_ShaderProgramSkybox.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")));
m_ShaderProgramShadows.Compile();
m_ShaderProgramShadows.Link();
m_FirstPassProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Vertex.glsl")));
m_FirstPassProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Fragment.glsl")));
m_FirstPassProgram.Compile();
glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 0, "frag_Diffuse");
glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 1, "frag_Position");
glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 2, "frag_Normal");
m_FirstPassProgram.Link();
m_FirstPassNormalProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Vertex.glsl")));
m_FirstPassNormalProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Fragment-Normal.glsl")));
m_FirstPassNormalProgram.Compile();
glBindFragDataLocation(m_FirstPassNormalProgram.GetHandle(), 0, "frag_Diffuse");
glBindFragDataLocation(m_FirstPassNormalProgram.GetHandle(), 1, "frag_Position");
glBindFragDataLocation(m_FirstPassNormalProgram.GetHandle(), 2, "frag_Normal");
m_FirstPassNormalProgram.Link();
m_SecondPassProgram.AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Vertex2.glsl")));
m_SecondPassProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Fragment2.glsl")));
m_SecondPassProgram.Compile();
@@ -136,13 +140,15 @@ void Renderer::LoadContent()
m_FinalPassProgram.AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/FinalPass.frag.glsl")));
m_FinalPassProgram.Compile();
m_FinalPassProgram.Link();
m_ScreenQuad = CreateQuad();
CreateShadowMap(m_ShadowMapRes);
FrameBufferTextures();
}
void Renderer::Draw(double dt)
{
if(glfwGetKey(m_Window, GLFW_KEY_F1))
{
m_QuadView = false;
@@ -152,57 +158,6 @@ void Renderer::Draw(double dt)
m_QuadView = true;
}
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_1))
{
if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD))
{
CAtt += 0.5f * dt;
LOG_INFO("Const: %f", CAtt);
}
if(glfwGetKey(m_Window, GLFW_KEY_KP_SUBTRACT))
{
CAtt -= 0.5f * dt;
LOG_INFO("Const: %f", CAtt);
}
}
if(glfwGetKey(m_Window, GLFW_KEY_2))
{
if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD))
{
LAtt += 0.5f * dt;
LOG_INFO("Linear: %f", LAtt);
}
if(glfwGetKey(m_Window, GLFW_KEY_KP_SUBTRACT))
{
LAtt -= 0.5f * dt;
LOG_INFO("Linear: %f", LAtt);
}
}
if(glfwGetKey(m_Window, GLFW_KEY_3))
{
if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD))
{
QAtt += 0.5f * dt;
LOG_INFO("Quadratic: %f", QAtt);
}
if(glfwGetKey(m_Window, GLFW_KEY_KP_SUBTRACT))
{
QAtt -= 0.5f * dt;
LOG_INFO("Quadratic: %f", QAtt);
}
}
glDisable(GL_BLEND);
DrawFBO();
@@ -216,48 +171,102 @@ void Renderer::Draw(double dt)
void Renderer::DrawSkybox()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, m_Width, m_Height);
glViewport(0, 0, WIDTH, 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() * glm::toMat4(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();
}
void Renderer::CreateShadowMap(int resolution)
void Renderer::DrawScene()
{
glGenFramebuffers(1, &m_ShadowFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer);
// glBindFramebuffer(GL_FRAMEBUFFER, 0);
// glViewport(0, 0, WIDTH, HEIGHT);
// Depth texture
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_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glClear(GL_DEPTH_BUFFER_BIT);
//glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE );
//glTexParameteri( GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY );
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
#ifdef DEBUG
glDisable(GL_CULL_FACE);
glPolygonMode(GL_BACK, GL_LINE);
#endif
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_ShadowDepthTexture, 0);
glDrawBuffer(GL_NONE);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
LOG_ERROR("Framebuffer incomplete!");
return;
// Draw models
glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 0, 0));
glm::mat4 depthCamera = m_SunProjection * depthViewMatrix;
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
m_ShaderProgram.Bind();
glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights);
// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "position"), Lights, Light_position.data());
// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "specular"), Lights, Light_specular.data());
// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "diffuse"), Lights, Light_diffuse.data());
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights, Light_constantAttenuation.data());
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights, Light_linearAttenuation.data());
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights, Light_quadraticAttenuation.data());
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights, Light_spotExponent.data());
if (m_DrawWireframe)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture);
//DrawModels(m_ShaderProgram);
glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix();
glm::mat4 depthCameraMatrix = biasMatrix * depthCamera;
glm::mat4 MVP;
glm::mat4 depthMVP;
for (auto tuple : ModelsToRender)
{
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_ShaderProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP));
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "model"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "view"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
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);
}
}
#ifdef DEBUG
// Debug draw model normals
if (m_DrawNormals)
{
m_ShaderProgramNormals.Bind();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
DrawModels(m_ShaderProgramNormals);
}
#endif
}
void Renderer::DrawShadowMap()
{
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);
@@ -266,9 +275,14 @@ void Renderer::DrawShadowMap()
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, 0, 0));
// glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0));
glm::mat4 depthCamera = m_SunProjection * depthViewMatrix;
//glm::mat4 cameraMatrix = depthProjectionMatrix * m_Camera->ViewMatrix();
glm::mat4 MVP;
m_ShaderProgramShadows.Bind();
@@ -293,8 +307,6 @@ void Renderer::DrawShadowMap()
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
}
}
}
void Renderer::DrawDebugShadowMap()
@@ -353,33 +365,34 @@ void Renderer::AddModelToDraw(Model* model, glm::vec3 position, glm::quat orient
ModelsToRender.push_back(std::make_tuple(model, modelMatrix, visible, shadowCaster));
}
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);
TexturesToRender.push_back(std::make_tuple(texture, modelMatrix, position));
}
void Renderer::AddPointLightToDraw(
glm::vec3 _position,
glm::vec3 _specular,
glm::vec3 _diffuse,
float _specularExponent,
float _ConstantAttenuation,
float _LinearAttenuation,
float _QuadraticAttenuation
float _specularExponent
)
{
Light light;
light.Position = _position;
light.Diffuse = _diffuse;
light.Specular = _specular;
light.SpecularExponent = _specularExponent;
light.ConstantAttenuation = _ConstantAttenuation;
light.LinearAttenuation = _LinearAttenuation;
light.QuadraticAttenuation = _QuadraticAttenuation;
light.SphereModelMatrix = CreateLightMatrix(light);
Lights.push_back(light);
Light_position.push_back(_position);
Light_specular.push_back(_specular);
Light_diffuse.push_back(_diffuse);
Light_specularExponent.push_back(_specularExponent);
Lights = Light_position.size();
CreateLightMatrix();
// Light_position.push_back(_position.x);
// Light_position.push_back(_position.y);
// Light_position.push_back(_position.z);
// Light_specular.push_back(_specular.x);
// Light_specular.push_back(_specular.y);
// Light_specular.push_back(_specular.z);
// Light_diffuse.push_back(_diffuse.x);
// Light_diffuse.push_back(_diffuse.y);
// Light_diffuse.push_back(_diffuse.z);
// Light_constantAttenuation.push_back(_constantAttenuation);
// Light_linearAttenuation.push_back(_linearAttenuation);
// Light_quadraticAttenuation.push_back(_quadraticAttenuation);
// Light_spotExponent.push_back(_spotExponent);
// Lights = Light_constantAttenuation.size();
}
void Renderer::AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding)
@@ -517,8 +530,15 @@ void Renderer::ClearStuff()
{
AABBsToRender.clear();
ModelsToRender.clear();
TexturesToRender.clear();
Lights.clear();
Light_position.clear();
Light_specular.clear();
Light_diffuse.clear();
Light_constantAttenuation.clear();
Light_linearAttenuation.clear();
Light_quadraticAttenuation.clear();
Light_spotExponent.clear();
Light_specularExponent.clear();
Lights = 0;
}
#pragma endregion
@@ -532,12 +552,12 @@ void Renderer::FrameBufferTextures()
glGenRenderbuffers(1, &m_fDepthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Width, m_Height);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WIDTH, HEIGHT);
//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_RGBA, WIDTH, 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);
@@ -546,7 +566,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_RGBA32F, WIDTH, 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);
@@ -555,29 +575,12 @@ 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_RGB10_A2, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
//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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
/*glGenTextures(1, &m_fShadowTexture);
glBindTexture(GL_TEXTURE_2D, m_fShadowTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, 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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);*/
//Bind fb
glBindFramebuffer(GL_FRAMEBUFFER, m_fbBasePass);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer);
@@ -586,13 +589,11 @@ void Renderer::FrameBufferTextures()
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fSpecularTexture, 0);
//glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fShadowTexture, 0);
GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if(fbStatus != GL_FRAMEBUFFER_COMPLETE)
{
LOG_ERROR("DeferredLighting:Init: m_fbBasePass incomplete: 0x%x\n", fbStatus);
LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus);
//exit(1);
}
@@ -601,7 +602,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_RGBA, WIDTH, 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);
@@ -613,117 +614,211 @@ void Renderer::FrameBufferTextures()
fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if(fbStatus != GL_FRAMEBUFFER_COMPLETE)
{
LOG_ERROR("DeferredLighting:Init: m_fbLightingPass incomplete: 0x%x\n", fbStatus);
LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus);
//exit(1);
}
}
//void Renderer::FrameBufferTextures()
//{
// m_fb = 0;
// m_fDepthBuffer = 0;
//
// glGenFramebuffers(1, &m_fb);
// glGenRenderbuffers(1, &m_fDepthBuffer);
//
// glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer);
// glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, WIDTH, HEIGHT);
//
// //Generate and bind diffuse texture
// glGenTextures(1, &m_fDiffuseTexture);
// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//
// //Generate and bind position texture
// glGenTextures(1, &m_fPositionTexture);
// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//
// //Generate and bind normal texture
// glGenTextures(1, &m_fNormalsTexture);
// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//
// //Generate and bind blend texture
// glGenTextures(1, &m_fBlendTexture);
// glBindTexture(GL_TEXTURE_2D, m_fBlendTexture);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//
// //Bind fb
// glBindFramebuffer(GL_FRAMEBUFFER, m_fb);
// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer);
//
// //Attach textures to the FB
// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0);
// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0);
// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0);
// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fBlendTexture, 0);
//
// GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
// if(fbStatus != GL_FRAMEBUFFER_COMPLETE)
// {
// printf("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus);
// exit(1);
// }
//
// glBindFramebuffer(GL_FRAMEBUFFER, 0);
//}
void Renderer::DrawFBO()
{
DrawShadowMap();
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;
/*
/*
Base pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbBasePass);
glViewport(0, 0, m_Width, m_Height);
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbBasePass);
// 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);
// 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 };
glDrawBuffers(3, windowBuffOpaque);
// Execute the first render stage which will fill out the internal buffers with data(??)
GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, windowBuffOpaque);
glCullFace(GL_BACK);
DrawFBOScene();
glCullFace(GL_BACK);
DrawFBOScene(viewport);
/*
/*
Lighting pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbLightingPass);
GLenum lightingPassAttachments[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, lightingPassAttachments);
*/
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);
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);
m_SecondPassProgram.Bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
glCullFace(GL_FRONT);
DrawLightScene(viewport);
glCullFace(GL_FRONT);
DrawLightScene();
/*
/*
Final pass
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(x, y, width, height);
glClear(GL_DEPTH_BUFFER_BIT);
*/
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//if(!m_QuadView)
//{
m_FinalPassProgram.Bind();
//}
//else
//{
// m_SecondPassProgram_Debug.Bind();
//}
// 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);
// Ambient light
glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f)));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_fLightingTexture);
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::DrawFBO()
//{
// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fb);
//
// GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };
// glDrawBuffers(4, windowBuffClear);
// glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//
// // Execute the first render stage which will fill out the internal buffers with data(??)
// //EnableRenderProgramStage1;
// m_FirstPassProgram.Bind();
// GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_NONE };
// glDrawBuffers(4, windowBuffOpaque);
// DrawFBOScene();
//
// GLenum windowBuffTransp[] = { GL_NONE, GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT3 };
// glDrawBuffers(4, windowBuffTransp);
// glEnable(GL_BLEND);
// glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// //Depth buffer shall not be updated
// glDepthMask(GL_FALSE);
// //DrawTransparent items
// glDepthMask(GL_TRUE);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glDisable(GL_BLEND);
//
// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
// //Probably means to use the second_pass shader
// //EnableRenderProgramDeferredStage();
// m_SecondPassProgram.Bind();
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// //SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures();
// glEnableVertexAttribArray(0);
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture);
//
// glActiveTexture(GL_TEXTURE1);
// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture);
//
// glActiveTexture(GL_TEXTURE2);
// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture);
//
// glActiveTexture(GL_TEXTURE3);
// glBindTexture(GL_TEXTURE_2D, m_fBlendTexture);
//
//
//
//
//
//
//
// //DrawSimpleSquare(); //I guess this draw a square and put the textures on it
// glBindVertexArray(m_ScreenQuad);
// glDrawArrays(GL_TRIANGLES, 0, 6);
// glDisableVertexAttribArray(0);
//
//}
void Renderer::DrawFBOScene()
{
// 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 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix();
glm::mat4 MVP;
glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0));
glm::mat4 depthCamera = m_SunProjection * depthViewMatrix;
glm::mat4 depthCameraMatrix = biasMatrix * depthCamera;
glm::mat4 depthMVP;
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture);
for (auto tuple : ModelsToRender)
{
@@ -733,67 +828,46 @@ void Renderer::DrawFBOScene(Viewport &viewport)
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)
{
if (texGroup.NormalMap)
{
m_FirstPassNormalProgram.Bind();
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassNormalProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassNormalProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassNormalProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassNormalProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix()));
}
else
{
m_FirstPassProgram.Bind();
glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
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()));
}
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texGroup.Texture);
if (texGroup.NormalMap)
{
glActiveTexture(GL_TEXTURE2);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, *texGroup.NormalMap);
}
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
}
}
for (auto tuple : TexturesToRender)
{
Texture* texture;
glm::mat4 modelMatrix;
glm::vec3 position;
std::tie(texture, modelMatrix, position) = tuple;
//MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation()) * modelMatrix );
glm::vec3 camToParticle = glm::normalize(viewport.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);
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()));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texture);
glBindVertexArray(m_ScreenQuad);
glDrawArrays(GL_TRIANGLES, 0, 6);
}
}
void Renderer::DrawLightScene(Viewport &viewport)
void Renderer::DrawLightScene()
{
glEnable(GL_BLEND);
glBlendEquation (GL_FUNC_ADD);
@@ -803,30 +877,25 @@ void Renderer::DrawLightScene(Viewport &viewport)
glDepthMask (GL_FALSE);
glBindVertexArray(m_sphereModel->VAO);
glm::mat4 cameraMatrix = viewport.Camera->ProjectionMatrix() * viewport.Camera->ViewMatrix();
glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix();
glm::mat4 MVP;
for (auto &light : Lights)
for(int i = 0; i < Lights; i++)
{
MVP = cameraMatrix * light.SphereModelMatrix;
MVP = cameraMatrix * lM[i];
glUniform2fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ViewportSize"), 1,glm::value_ptr(glm::vec2(m_Width, m_Height)));
glUniform2fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ViewportSize"), 1,glm::value_ptr(glm::vec2(WIDTH, 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);
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix()));
glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(lM[i]));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "la"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f)));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), 1, glm::value_ptr(Light_specular[i]));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), 1, glm::value_ptr(Light_diffuse[i]));
glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(Light_position[i]));
glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LightRadius"), 5.0f);
glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z);
//glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "speculatExponent"), Light_specularExponent[i]);
glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size());
};
glEnable (GL_DEPTH_TEST);
@@ -839,78 +908,16 @@ void Renderer::SetSphereModel( Model* _model )
m_sphereModel = _model;
}
glm::mat4 Renderer::CreateLightMatrix(Light &_light)
void Renderer::CreateLightMatrix()
{
// 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));
glm::mat4 model;
model *= glm::translate(_light.Position);
model *= glm::scale(glm::vec3(cutOffRadius));
return model;
}
void Renderer::UpdateSunProjection()
{
glm::vec3 NDCCube[] =
for(int i = 0; i < Lights; i++)
{
glm::vec3(-1.f, -1.f, -1.f),
glm::vec3(1.f, -1.f, -1.f),
glm::vec3(-1.f, 1.f, -1.f),
glm::vec3(1.f, 1.f, -1.f),
glm::vec3(-1.f, -1.f, 1.f),
glm::vec3(1.f, -1.f, 1.f),
glm::vec3(-1.f, 1.f, 1.f),
glm::vec3(1.f, 1.f, 1.f)
};
glm::mat4 inverseProjectionViewMatrix = glm::inverse(m_Camera->ViewMatrix()) * glm::inverse(m_Camera->ProjectionMatrix());
//Also * with world matrix for light
for(auto corner : NDCCube)
{
//corner *= inverseProjectionViewMatrix;
const float scale = 10.0f;
glm::mat4 model;
model *= glm::translate(Light_position[i]);
model *= glm::scale(glm::vec3(scale));
lM[i] = model;
}
//Calculate the bounding box of the transformed frustum corners. This will be the view frustum for the shadow map.
//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)
{
Viewport v;
v.Left = left;
v.Top = top;
v.Right = right;
v.Bottom = bottom;
v.Camera = nullptr;
m_Viewports[identifier] = v;
}
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);
}
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;
}
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]->Orientation(orientation);
m_Cameras[cameraIdentifier]->FOV(FOV);
m_Cameras[cameraIdentifier]->NearClip(nearClip);
m_Cameras[cameraIdentifier]->FarClip(farClip);
}
+21 -51
View File
@@ -21,12 +21,21 @@ public:
glm::mat4 viewMatrix;
glm::mat4 projectionMatrix;
int Width() const { return m_Width; }
int Height() const { return m_Height; }
int HEIGHT, WIDTH;
std::list<std::tuple<Model*, glm::mat4, bool, bool>> ModelsToRender;
std::list<std::tuple<Texture*, glm::mat4, glm::vec3>> TexturesToRender;
int Lights;
std::vector<glm::vec3> Light_position;
std::vector<glm::vec3> Light_specular;
std::vector<glm::vec3> Light_diffuse;
std::vector<float> Light_specularExponent;
std::vector<float> Light_constantAttenuation;
std::vector<float> Light_linearAttenuation;
std::vector<float> Light_quadraticAttenuation;
std::vector<float> Light_spotExponent;
std::list<std::tuple<glm::mat4, bool>> AABBsToRender;
Renderer();
@@ -35,22 +44,13 @@ public:
void Draw(double dt);
void DrawText();
void RegisterViewport(int identifier, float left, float top, float right, float bottom);
void RegisterCamera(int identifier, float FOV, float nearClip, float farClip);
void UpdateViewport(int viewportIdentifier, int cameraIdentifier);
void UpdateCamera(int cameraIdentifier, glm::vec3 position, glm::quat orientation, float FOV, float nearClip, float farClip);
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();
void AddPointLightToDraw(
glm::vec3 _position,
glm::vec3 _specular,
glm::vec3 _diffuse,
float _specularExponent,
float _ConstantAttenuation,
float _LinearAttenuation,
float _QuadraticAttenuation
float _specularExponent
);
void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding);
@@ -69,35 +69,9 @@ public:
void SetSphereModel(Model* _model);
private:
int m_Width, m_Height;
struct Viewport
{
float Left;
float Top;
float Right;
float Bottom;
std::shared_ptr<Camera> Camera;
};
std::unordered_map<int, Viewport> m_Viewports;
std::unordered_map<int, std::shared_ptr<Camera>> m_Cameras;
struct Light
{
glm::vec3 Position;
glm::vec3 Specular;
glm::vec3 Diffuse;
float SpecularExponent;
glm::mat4 SphereModelMatrix;
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation;
};
float Gamma;
std::list<Light> Lights;
GLFWwindow* m_Window;
GLint m_glVersion[2];
GLchar* m_glVendor;
@@ -105,7 +79,6 @@ private:
bool m_DrawNormals;
bool m_DrawWireframe;
bool m_DrawBounds;
float CAtt, LAtt, QAtt;
std::shared_ptr<Skybox> m_Skybox;
@@ -122,14 +95,13 @@ private:
GLuint m_fDiffuseTexture;
GLuint m_fPositionTexture;
GLuint m_fNormalsTexture;
GLuint m_fSpecularTexture;
GLuint m_fBlendTexture;
GLuint m_fbLightingPass;
GLuint m_fLightingTexture;
GLuint m_fShadowTexture;
GLuint m_fDepthBuffer;
GLenum draw_bufs[2];
glm::mat4 lM[5];
GLuint m_ScreenQuad;
Model* m_sphereModel;
@@ -139,6 +111,7 @@ private:
ShaderProgram m_ShaderProgram;
ShaderProgram m_FirstPassProgram;
ShaderProgram m_FirstPassNormalProgram;
ShaderProgram m_SecondPassProgram;
ShaderProgram m_SecondPassProgram_Debug;
ShaderProgram m_FinalPassProgram;
@@ -158,13 +131,10 @@ private:
void CreateShadowMap(int resolution);
void FrameBufferTextures();
void DrawFBO();
void DrawFBOScene(Viewport &viewport);
void DrawLightScene(Viewport &viewport);
void DrawFBOScene();
void DrawLightScene();
void BindFragDataLocation();
glm::mat4 CreateLightMatrix(Light &_light);
void UpdateSunProjection();
void CreateNormalMapTangent();
void CreateLightMatrix();
GLuint CreateQuad();
void DrawDebugShadowMap();
+4 -4
View File
@@ -16,7 +16,7 @@ Resource* ResourceManager::CreateResource(std::string resourceType, std::string
resource->TypeID = GetTypeID(resourceType);
resource->ResourceID = GetNewResourceID(resource->TypeID);
// Cache
m_ResourceCache[std::make_pair(resourceType, resourceName)] = resource;
m_ResourceCache[resourceName] = resource;
return resource;
}
@@ -28,7 +28,7 @@ void ResourceManager::RegisterType(std::string resourceType, std::function<Resou
void ResourceManager::Preload(std::string resourceType, std::string resourceName)
{
if (IsResourceLoaded(resourceType, resourceName))
if (IsResourceLoaded(resourceName))
{
LOG_WARNING("Attempted to preload resource \"%s\" multiple times!", resourceName);
return;
@@ -54,7 +54,7 @@ unsigned int ResourceManager::GetNewResourceID(unsigned int typeID)
return m_ResourceCount[typeID]++;
}
bool ResourceManager::IsResourceLoaded(std::string resourceType, std::string resourceName)
bool ResourceManager::IsResourceLoaded(std::string resourceName)
{
return m_ResourceCache.find(std::make_pair(resourceType, resourceName)) != m_ResourceCache.end();
return m_ResourceCache.find(resourceName) != m_ResourceCache.end();
}
+4 -5
View File
@@ -6,7 +6,6 @@
#include <vector>
#include <unordered_map>
#include "Util/UnorderedMapPair.h"
#include "Factory.h"
class Resource
@@ -29,7 +28,7 @@ public:
void Preload(std::string resourceType, std::string resourceName);
// Checks if a resource is in cache
bool IsResourceLoaded(std::string resourceType, std::string resourceName);
bool IsResourceLoaded(std::string resourceName);
template <typename T>
// Hot-loads a resource and caches it for future use
@@ -41,7 +40,7 @@ public:
private:
std::unordered_map<std::string, std::function<Resource*(std::string)>> m_FactoryFunctions; // type -> factory function
std::unordered_map<std::pair<std::string, std::string>, Resource*> m_ResourceCache; // (type, name) -> resource
std::unordered_map<std::string, Resource*> m_ResourceCache; // name -> resource
// TODO: Getters for IDs
unsigned int m_CurrentResourceTypeID;
@@ -61,7 +60,7 @@ private:
template <typename T>
T* ResourceManager::Load(std::string resourceType, std::string resourceName)
{
auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName));
auto it = m_ResourceCache.find(resourceName);
if (it != m_ResourceCache.end())
return static_cast<T*>(it->second);
@@ -80,7 +79,7 @@ T* ResourceManager::Load(std::string resourceType, std::string resourceName)
template <typename T>
T* ResourceManager::Fetch(std::string resourceName) const
{
auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName));
auto it = m_ResourceCache.find(resourceName);
if (it == m_ResourceCache.end())
{
LOG_ERROR("Failed to fetch resource \"%s\": Resource not loaded!", resourceName.c_str());
+1 -8
View File
@@ -1,11 +1,9 @@
#version 430
uniform vec3 La;
uniform float Gamma;
layout (binding=0) uniform sampler2D DiffuseTexture;
layout (binding=1) uniform sampler2D LightingTexture;
layout (binding=2) uniform sampler2D ShadowTexture;
in VertexData
{
@@ -19,11 +17,6 @@ void main()
{
vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord);
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 = DiffuseTexel;
FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel;
}
+32
View File
@@ -0,0 +1,32 @@
#version 430
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
layout (binding=0) uniform sampler2D DiffuseTexture;
layout (binding=1) uniform sampler2D NormalMap;
in VertexData
{
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Input;
out vec4 frag_Diffuse;
out vec4 frag_Position;
out vec4 frag_Normal;
void main()
{
// Diffuse Texture
frag_Diffuse = texture2D(DiffuseTexture, Input.TextureCoord);
// G-buffer Position
frag_Position = vec4(Input.Position.xyz, 0.0);
// G-buffer Normal
frag_Normal = vec4(normalize(vec3(Input.Normal * (texture2D(NormalMap, Input.TextureCoord)).xyz)), 0.0);
}
+8 -32
View File
@@ -1,55 +1,31 @@
#version 430
layout (binding=0) uniform sampler2D DiffuseTexture;
layout (binding=1) uniform sampler2D ShadowTexture;
layout (binding=2) uniform sampler2D NormalMapTexture;
layout (binding=3) uniform sampler2D SpecularMapTexture;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
layout (binding=0) uniform sampler2D DiffuseTexture;
in VertexData
{
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
vec4 ShadowCoord;
vec3 Tangent;
vec3 BiTangent;
} Input;
out vec4 frag_Diffuse;
out vec4 frag_Position;
out vec4 frag_Normal;
out vec4 frag_specular;
float Shadow(vec4 ShadowCoord)
{
//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 0.3;
}
else
{
return 1.0;
}
}
void main()
{
// Diffuse Texture
frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord); // * Shadow(Input.ShadowCoord);
frag_Diffuse = texture2D(DiffuseTexture, Input.TextureCoord);
// G-buffer Position
frag_Position = vec4(Input.Position.xyz, 1.0);
frag_Position = vec4(Input.Position.xyz, 0.0);
// G-buffer Normal
mat3 TBN = transpose(mat3(Input.Tangent, Input.BiTangent, Input.Normal));
frag_Normal = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Normal = vec4(Input.Normal, 0.0);
//G-buffer Specular
frag_specular = texture(SpecularMapTexture, Input.TextureCoord);
frag_Normal = vec4(Input.Normal, 0.0);
}
+12 -17
View File
@@ -12,14 +12,12 @@ uniform vec3 la;
uniform vec3 ls;
uniform vec3 ld;
uniform vec3 lp;
uniform float specularExponent;
uniform float LightRadius;
const float specularExponent = 50.0;
uniform vec3 CameraPosition;
uniform float ConstantAttenuation;
uniform float LinearAttenuation;
uniform float QuadraticAttenuation;
const vec3 ks = vec3(1.0, 1.0, 1.0);
const vec3 kd = vec3(1.0, 1.0, 1.0);
const vec3 ks = vec3(1.0, 0.0, 0.0);
const vec3 kd = vec3(0.8, 0.8, 0.8);
const vec3 ka = vec3(1.0, 1.0, 1.0);
const float kshine = 1.0;
@@ -31,7 +29,7 @@ in VertexData
out vec4 FragColor;
vec4 phong(vec3 position, vec3 normal)
vec4 phong4(vec3 position, vec3 normal)
{
// Diffuse
vec3 lightPos = vec3(V * vec4(lp, 1.0));
@@ -46,15 +44,12 @@ 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);
float specularFactor = pow(dotSpecular, specularExponent * 2);
vec3 Is = ks * 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 = -log(min(1.0, dist / LightRadius));
//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)));
@@ -67,9 +62,10 @@ vec4 phong(vec3 position, vec3 normal)
//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);
float radius = 5.0;
float alpha = dist / radius;
float dampingFactor = 1.0 - pow(alpha, 3);
return vec4((Id + Is) * attenuation, 1.0);
}
@@ -80,6 +76,5 @@ void main()
vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
FragColor = phong(vec3(PositionTexel), vec3(NormalTexel));
//FragColor = NormalTexel;
FragColor = phong4(vec3(PositionTexel), vec3(NormalTexel));
}
-9
View File
@@ -4,22 +4,16 @@ uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform mat4 DepthMVP;
layout (location = 0) in vec3 Position;
layout (location = 1) in vec3 Normal;
layout (location = 2) in vec2 TextureCoord;
layout (location = 3) in vec3 Tangent;
layout (location = 4) in vec3 BiTangent;
out VertexData
{
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
vec4 ShadowCoord;
vec3 Tangent;
vec3 BiTangent;
} Output;
void main()
@@ -29,7 +23,4 @@ void main()
Output.Position = vec3(V * M * vec4(Position, 1.0));
Output.Normal = normalize(vec3(inverse(transpose(V * M)) * vec4(Normal, 0.0)));
Output.TextureCoord = TextureCoord;
Output.ShadowCoord = DepthMVP * vec4(Position, 1.0);
Output.Tangent = normalize(vec3(inverse(transpose(V * M)) * vec4(Tangent, 0.0)));
Output.BiTangent = normalize(vec3(inverse(transpose(V * M)) * vec4(BiTangent, 0.0)));
}
+1 -4
View File
@@ -5,8 +5,6 @@ uniform mat4 MVP;
layout (location = 0) in vec3 Position;
layout (location = 2) in vec2 TextureCoord;
uniform mat4 depthBiasMVP;
out VertexData
{
vec3 Position;
@@ -17,6 +15,5 @@ void main()
{
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position;
Output.TextureCoord = (vec2(Position) + 1.0) / 2.0;
Output.TextureCoord = (vec2(Position) + 1) / 2;
}
+1 -6
View File
@@ -4,7 +4,6 @@
#include "Factory.h"
#include "Entity.h"
#include "Component.h"
#include "EventBroker.h"
#include "ResourceManager.h"
class World;
@@ -12,9 +11,7 @@ class World;
class System
{
public:
System(World* world, std::shared_ptr<EventBroker> eventBroker)
: m_World(world)
, EventBroker(eventBroker) { }
System(World* world) : m_World(world) { }
virtual ~System() { }
virtual void RegisterComponents(ComponentFactory* cf) { }
@@ -33,11 +30,9 @@ public:
virtual void OnComponentRemoved(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;
};
class SystemFactory : public Factory<System*> { };
-27
View File
@@ -2,30 +2,3 @@
#include "DebugSystem.h"
#include "World.h"
void Systems::DebugSystem::Initialize()
{
// Subscribe to events
m_EKeyDown = decltype(m_EKeyDown)(std::bind(&Systems::DebugSystem::OnKeyDown, this, std::placeholders::_1));
EventBroker->Subscribe(m_EKeyDown);
}
void Systems::DebugSystem::Update(double dt)
{
}
bool Systems::DebugSystem::OnKeyDown(const Events::KeyDown &event)
{
if (event.KeyCode == GLFW_KEY_ENTER)
{
Events::PlaySound e;
e.Emitter = 0;
e.Resource = "Sounds/korvring.wav";
EventBroker->Publish<Events::PlaySound>(e);
return true;
}
return false;
}
+2 -10
View File
@@ -3,8 +3,6 @@
#include "System.h"
#include "Components/Transform.h"
#include "Events/KeyDown.h"
#include "Events/PlaySound.h"
namespace Systems
{
@@ -12,16 +10,10 @@ namespace Systems
class DebugSystem : public System
{
public:
DebugSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
void Initialize() override;
DebugSystem(World* world)
: System(world) { }
void Update(double dt) override;
EventRelay<Events::KeyDown> m_EKeyDown;
bool OnKeyDown(const Events::KeyDown &event);
//void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
};
+48 -96
View File
@@ -4,116 +4,68 @@
void Systems::FreeSteeringSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::FreeSteering>([]() { return new Components::FreeSteering(); });
}
void Systems::FreeSteeringSystem::Initialize()
{
m_InputController = std::unique_ptr<FreeSteeringInputController>(new FreeSteeringInputController(EventBroker));
cf->Register("FreeSteering", []() { return new Components::FreeSteering(); });
}
void Systems::FreeSteeringSystem::Update(double dt)
{
}
void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto steering = m_World->GetComponent<Components::FreeSteering>(entity);
if (steering)
auto steering = m_World->GetComponent<Components::FreeSteering>(entity, "FreeSteering");
auto input = m_World->GetComponent<Components::Input>(entity, "Input");
if (steering && input)
{
auto transform = m_World->GetComponent<Components::Transform>(entity);
auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform");
glm::vec3 cameraRight = glm::vec3(transform->Orientation * glm::vec4(1, 0, 0, 0));
glm::vec3 cameraForward = glm::vec3(transform->Orientation * glm::vec4(0, 0, -1, 0));
glm::vec3 movement;
movement += cameraRight * m_InputController->Movement.x;
movement.y += m_InputController->Movement.y;
movement += cameraForward * -m_InputController->Movement.z;
float speedMultiplier = 1.f;
if (m_InputController->SpeedMultiplier > 0)
speedMultiplier *= 4;
else if (m_InputController->SpeedMultiplier < 0)
speedMultiplier /= 4;
glm::vec3 Camera_Right = glm::vec3(transform->Orientation * glm::vec4(1, 0, 0, 0));
glm::vec3 Camera_Forward = glm::vec3(transform->Orientation * glm::vec4(0, 0, -1, 0));
transform->Position += movement * steering->Speed * speedMultiplier * (float)dt;
glm::quat mouseOrientationPitch = glm::quat(m_InputController->MouseOrientation * glm::vec3(1, 0, 0));
glm::quat mouseOrientationYaw = glm::quat(m_InputController->MouseOrientation * glm::vec3(0, 1, 0));
glm::vec3 controllerOrientationEuler = m_InputController->ControllerOrientation * (float)dt;
glm::quat controllerOrientationPitch = glm::quat(controllerOrientationEuler * glm::vec3(1, 0, 0));
glm::quat controllerOrientationYaw = glm::quat(controllerOrientationEuler * glm::vec3(0, 1, 0));
// TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS
//---------------------------------------------------------------------
transform->Orientation = (mouseOrientationYaw * controllerOrientationYaw)
* transform->Orientation
* (mouseOrientationPitch * controllerOrientationPitch);
//---------------------------------------------------------------------
// TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS
}
m_InputController->MouseOrientation = glm::vec3(0);
}
bool Systems::FreeSteeringSystem::FreeSteeringInputController::OnCommand(const Events::InputCommand &event)
{
// Movement
if (event.Command == "cam_vertical")
{
Movement.z = -event.Value;
}
else if (event.Command == "cam_horizontal")
{
Movement.x = event.Value;
}
else if (event.Command == "cam_normal")
{
Movement.y = event.Value;
}
// Speed
else if (event.Command == "cam_speed")
{
SpeedMultiplier = event.Value;
}
// Mouse click
else if (event.Command == "cam_attack")
{
OrientationActive = event.Value > 0;
if (OrientationActive)
float speed = steering->Speed;
if (input->KeyState[GLFW_KEY_LEFT_SHIFT])
{
Events::LockMouse e;
EventBroker->Publish(e);
speed *= 4.0f;
}
else
if (input->KeyState[GLFW_KEY_LEFT_ALT])
{
Events::UnlockMouse e;
EventBroker->Publish(e);
speed /= 4.0f;
}
if (input->KeyState[GLFW_KEY_A])
{
transform->Position -= Camera_Right * (float)dt * speed;
}
else if (input->KeyState[GLFW_KEY_D])
{
transform->Position += Camera_Right * (float)dt * speed;
}
if (input->KeyState[GLFW_KEY_W])
{
transform->Position += Camera_Forward * (float)dt * speed;
}
if (input->KeyState[GLFW_KEY_S])
{
transform->Position -= Camera_Forward * (float)dt * speed;
}
if (input->KeyState[GLFW_KEY_SPACE])
{
transform->Position += glm::vec3(0, 1, 0) * (float)dt * speed;
}
if (input->KeyState[GLFW_KEY_LEFT_CONTROL])
{
transform->Position -= glm::vec3(0, 1, 0) * (float)dt * speed;
}
if (input->MouseState[GLFW_MOUSE_BUTTON_LEFT])
{
// TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3
//---------------------------------------------------------------------
transform->Orientation = glm::angleAxis<float>(input->dX / 300.f, glm::vec3(0, -1, 0)) * transform->Orientation;
transform->Orientation = transform->Orientation * glm::angleAxis<float>(input->dY / 300.f, glm::vec3(-1, 0, 0));
//---------------------------------------------------------------------
// TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS
}
}
else if (event.Command == "cam_vertical2")
{
ControllerOrientation.x = event.Value;
}
else if (event.Command == "cam_horizontal2")
{
ControllerOrientation.y = -event.Value;
}
return true;
}
bool Systems::FreeSteeringSystem::FreeSteeringInputController::OnMouseMove(const Events::MouseMove &event)
{
if (OrientationActive)
{
MouseOrientation = -glm::vec3(event.DeltaY / 300.f, event.DeltaX / 300.f, 0.f);
}
return true;
}
+3 -32
View File
@@ -2,48 +2,19 @@
#include "System.h"
#include "Components/Transform.h"
#include "Components/Input.h"
#include "Components/FreeSteering.h"
#include "InputController.h"
#include "Events/LockMouse.h"
namespace Systems
{
class FreeSteeringSystem : public System
{
public:
FreeSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
FreeSteeringSystem(World* world)
: System(world) { }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
class FreeSteeringInputController;
std::unique_ptr<FreeSteeringInputController> m_InputController;
};
class FreeSteeringSystem::FreeSteeringInputController : InputController
{
public:
FreeSteeringInputController(std::shared_ptr<::EventBroker> eventBroker)
: InputController(eventBroker)
, SpeedMultiplier(0.f)
, OrientationActive(false) { }
glm::vec3 Movement;
glm::vec3 MouseOrientation;
glm::vec3 ControllerOrientation;
float SpeedMultiplier;
bool OrientationActive;
protected:
virtual bool OnCommand(const Events::InputCommand &event);
virtual bool OnMouseMove(const Events::MouseMove &event);
};
}
-67
View File
@@ -1,67 +0,0 @@
#include "PrecompiledHeader.h"
#include "HelicopterSteeringSystem.h"
#include "World.h"
void Systems::HelicopterSteeringSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::HelicopterSteering>([]() { return new Components::HelicopterSteering(); });
}
void Systems::HelicopterSteeringSystem::Initialize()
{
m_InputController = std::unique_ptr<HelicopterSteeringInputController>(new HelicopterSteeringInputController(EventBroker));
}
void Systems::HelicopterSteeringSystem::Update(double dt)
{
}
void Systems::HelicopterSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto transform = m_World->GetComponent<Components::Transform>(entity);
if (!transform)
return;
auto helicopterComponent = m_World->GetComponent<Components::HelicopterSteering>(entity);
if (helicopterComponent)
{
glm::vec3 controllerRotationEuler = m_InputController->Rotation * (float)dt;
transform->Orientation *= glm::quat(controllerRotationEuler);
Events::ApplyForce e;
e.Entity = entity;
e.DeltaTime = dt;
e.Force = glm::normalize(transform->Orientation * glm::vec3(0, 1, 0)) * (m_InputController->Power * 3000.f * 9.82f * 8.f);
EventBroker->Publish(e);
}
}
bool Systems::HelicopterSteeringSystem::HelicopterSteeringInputController::OnCommand(const Events::InputCommand &event)
{
if (event.Command == "horizontal")
{
Rotation.z = -event.Value;
}
else if (event.Command == "vertical")
{
Rotation.x = -event.Value;
}
else if (event.Command == "normal")
{
Power = event.Value;
}
return true;
}
bool Systems::HelicopterSteeringSystem::HelicopterSteeringInputController::OnMouseMove(const Events::MouseMove &event)
{
return true;
}
void Systems::HelicopterSteeringSystem::HelicopterSteeringInputController::Update(double dt)
{
}
-54
View File
@@ -1,54 +0,0 @@
#include "System.h"
#include "Components/Transform.h"
#include "Components/HelicopterSteering.h"
#include "Events/SetVelocity.h"
#include "Events/ApplyForce.h"
#include "InputController.h"
namespace Systems
{
class HelicopterSteeringSystem : public System
{
public:
HelicopterSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
class HelicopterSteeringInputController;
std::unique_ptr<HelicopterSteeringInputController> m_InputController;
std::map<EntityID, double> m_TimeSinceLastShot;
};
class HelicopterSteeringSystem::HelicopterSteeringInputController : InputController
{
public:
HelicopterSteeringInputController(std::shared_ptr<::EventBroker> eventBroker)
: InputController(eventBroker)
, Power(0.f)
{ }
float Power;
glm::vec3 Rotation;
void Update(double dt);
protected:
bool OnCommand(const Events::InputCommand &event) override;
bool OnMouseMove(const Events::MouseMove &event) override;
};
}
+70 -249
View File
@@ -4,262 +4,83 @@
void Systems::InputSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::Input>([]() { return new Components::Input(); });
}
void Systems::InputSystem::Initialize()
{
// Subscribe to events
EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Systems::InputSystem::OnKeyDown);
EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Systems::InputSystem::OnKeyUp);
EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Systems::InputSystem::OnMousePress);
EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Systems::InputSystem::OnMouseRelease);
EVENT_SUBSCRIBE_MEMBER(m_EGamepadAxis, &Systems::InputSystem::OnGamepadAxis);
EVENT_SUBSCRIBE_MEMBER(m_EGamepadButtonDown, &Systems::InputSystem::OnGamepadButtonDown);
EVENT_SUBSCRIBE_MEMBER(m_EGamepadButtonUp, &Systems::InputSystem::OnGamepadButtonUp);
EVENT_SUBSCRIBE_MEMBER(m_EBindKey, &Systems::InputSystem::OnBindKey);
EVENT_SUBSCRIBE_MEMBER(m_EBindMouseButton, &Systems::InputSystem::OnBindMouseButton);
EVENT_SUBSCRIBE_MEMBER(m_EBindGamepadAxis, &Systems::InputSystem::OnBindGamepadAxis);
EVENT_SUBSCRIBE_MEMBER(m_EBindGamepadButton, &Systems::InputSystem::OnBindGamepadButton);
cf->Register("Input", []() { return new Components::Input(); });
}
void Systems::InputSystem::Update(double dt)
{
// #ifdef DEBUG
// // Wireframe
// if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1])
// {
// m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe());
// }
// // Normals
// if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2])
// {
// m_Renderer->DrawNormals(!m_Renderer->DrawNormals());
// }
// // Bounds
// if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3])
// {
// m_Renderer->DrawBounds(!m_Renderer->DrawBounds());
// }
// #endif
m_LastKeyState = m_CurrentKeyState;
m_LastMouseState = m_CurrentMouseState;
// Keyboard input
for (int i = 0; i <= GLFW_KEY_LAST; ++i)
{
m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i);
}
// Mouse buttons
for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i)
{
m_CurrentMouseState[i] = glfwGetMouseButton(m_Renderer->GetWindow(), i);
}
// Cursor position
double xpos, ypos;
glfwGetCursorPos(m_Renderer->GetWindow(), &xpos, &ypos);
m_CurrentMouseDeltaX = xpos - m_LastMouseX;
m_CurrentMouseDeltaY = ypos - m_LastMouseY;
m_LastMouseX = xpos;
m_LastMouseY = ypos;
// Lock mouse while holding LMB
if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT])
{
m_LastMouseX = m_Renderer->WIDTH / 2.f; // xpos;
m_LastMouseY = m_Renderer->HEIGHT / 2.f; // ypos;
glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY);
}
// Hide/show cursor with LMB
if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
{
glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
}
if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
{
glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
#ifdef DEBUG
// Wireframe
if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1])
{
m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe());
}
// Normals
if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2])
{
m_Renderer->DrawNormals(!m_Renderer->DrawNormals());
}
// Bounds
if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3])
{
m_Renderer->DrawBounds(!m_Renderer->DrawBounds());
}
#endif
}
bool Systems::InputSystem::OnKeyDown(const Events::KeyDown &event)
void Systems::InputSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto bindingIt = m_KeyBindings.find(event.KeyCode);
if (bindingIt != m_KeyBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandKeyboardValues[command][event.KeyCode] = value;
PublishCommand(1, command, GetCommandTotalValue(command));
}
auto input = m_World->GetComponent<Components::Input>(entity, "Input");
if (input == nullptr)
return;
return true;
input->KeyState = m_CurrentKeyState;
input->LastKeyState = m_LastKeyState;
input->MouseState = m_CurrentMouseState;
input->LastMouseState = m_LastMouseState;
input->dX = m_CurrentMouseDeltaX;
input->dY = m_CurrentMouseDeltaY;
}
bool Systems::InputSystem::OnKeyUp(const Events::KeyUp &event)
{
auto bindingIt = m_KeyBindings.find(event.KeyCode);
if (bindingIt != m_KeyBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandKeyboardValues[command][event.KeyCode] = 0;
PublishCommand(1, command, GetCommandTotalValue(command));;
}
return true;
}
bool Systems::InputSystem::OnMousePress(const Events::MousePress &event)
{
auto bindingIt = m_MouseButtonBindings.find(event.Button);
if (bindingIt != m_MouseButtonBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandMouseButtonValues[command][event.Button] = value;
PublishCommand(1, command, GetCommandTotalValue(command));
}
return true;
}
bool Systems::InputSystem::OnMouseRelease(const Events::MouseRelease &event)
{
auto bindingIt = m_MouseButtonBindings.find(event.Button);
if (bindingIt != m_MouseButtonBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandMouseButtonValues[command][event.Button] = 0;
PublishCommand(1, command, GetCommandTotalValue(command));
}
return true;
}
bool Systems::InputSystem::OnGamepadAxis(const Events::GamepadAxis &event)
{
auto bindingIt = m_GamepadAxisBindings.find(event.Axis);
if (bindingIt != m_GamepadAxisBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandGamepadAxisValues[command][event.Axis] = event.Value * value;
PublishCommand(event.GamepadID + 1, command, GetCommandTotalValue(command));
}
return true;
}
bool Systems::InputSystem::OnGamepadButtonDown(const Events::GamepadButtonDown &event)
{
auto bindingIt = m_GamepadButtonBindings.find(event.Button);
if (bindingIt != m_GamepadButtonBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandGamepadButtonValues[command][event.Button] = value;
PublishCommand(event.GamepadID + 1, command, GetCommandTotalValue(command));
}
return true;
}
bool Systems::InputSystem::OnGamepadButtonUp(const Events::GamepadButtonUp &event)
{
auto bindingIt = m_GamepadButtonBindings.find(event.Button);
if (bindingIt != m_GamepadButtonBindings.end())
{
std::string command;
float value;
std::tie(command, value) = bindingIt->second;
m_CommandGamepadButtonValues[command][event.Button] = 0;
PublishCommand(event.GamepadID + 1, command, GetCommandTotalValue(command));
}
return true;
}
bool Systems::InputSystem::OnBindKey(const Events::BindKey &event)
{
if (event.Command.empty())
{
m_KeyBindings.erase(event.KeyCode);
}
else
{
m_KeyBindings[event.KeyCode] = std::make_tuple(event.Command, event.Value);
LOG_DEBUG("Input: Bound key %c to %s", (char)event.KeyCode, event.Command.c_str());
}
return true;
}
bool Systems::InputSystem::OnBindMouseButton(const Events::BindMouseButton &event)
{
if (event.Command.empty())
{
m_MouseButtonBindings.erase(event.Button);
}
else
{
m_MouseButtonBindings[event.Button] = std::make_tuple(event.Command, event.Value);
LOG_DEBUG("Input: Bound mouse button %i to %s", event.Button, event.Command.c_str());
}
return true;
}
bool Systems::InputSystem::OnBindGamepadAxis(const Events::BindGamepadAxis &event)
{
if (event.Command.empty())
{
m_GamepadAxisBindings.erase(event.Axis);
}
else
{
m_GamepadAxisBindings[event.Axis] = std::make_tuple(event.Command, event.Value);
LOG_DEBUG("Input: Bound gamepad axis %i to %s", event.Axis, event.Command.c_str());
}
return true;
}
bool Systems::InputSystem::OnBindGamepadButton(const Events::BindGamepadButton &event)
{
if (event.Command.empty())
{
m_GamepadButtonBindings.erase(event.Button);
}
else
{
m_GamepadButtonBindings[event.Button] = std::make_tuple(event.Command, event.Value);
LOG_DEBUG("Input: Bound gamepad axis %i to %s", event.Button, event.Command.c_str());
}
return true;
}
float Systems::InputSystem::GetCommandTotalValue(std::string command)
{
float value = 0.f;
auto keyboardIt = m_CommandKeyboardValues.find(command);
if (keyboardIt != m_CommandKeyboardValues.end())
{
for (auto &key : keyboardIt->second)
{
value += key.second;
}
}
auto mouseButtonIt = m_CommandMouseButtonValues.find(command);
if (mouseButtonIt != m_CommandMouseButtonValues.end())
{
for (auto &button : mouseButtonIt->second)
{
value += button.second;
}
}
auto gamepadAxisIt = m_CommandGamepadAxisValues.find(command);
if (gamepadAxisIt != m_CommandGamepadAxisValues.end())
{
for (auto &axis : gamepadAxisIt->second)
{
value += axis.second;
}
}
auto gamepadButtonIt = m_CommandGamepadButtonValues.find(command);
if (gamepadButtonIt != m_CommandGamepadButtonValues.end())
{
for (auto &button : gamepadButtonIt->second)
{
value += button.second;
}
}
return std::max(-1.f, std::min(value, 1.f));
}
void Systems::InputSystem::PublishCommand(int playerID, std::string command, float value)
{
Events::InputCommand e;
e.PlayerID = playerID;
e.Command = command;
e.Value = value;
EventBroker->Publish(e);
LOG_DEBUG("Input: Published command %s=%f for player %i", e.Command.c_str(), e.Value, playerID);
}
std::array<int, GLFW_KEY_LAST+1> Systems::InputSystem::m_CurrentKeyState;
std::array<int, GLFW_KEY_LAST+1> Systems::InputSystem::m_LastKeyState;
+11 -53
View File
@@ -2,22 +2,10 @@
#define InputSystem_h__
#include <array>
#include <unordered_map>
#include <boost/any.hpp>
#include "System.h"
#include "Renderer.h"
#include "Components/Input.h"
#include "Events/KeyUp.h"
#include "Events/KeyDown.h"
#include "Events/MousePress.h"
#include "Events/MouseRelease.h"
#include "Events/GamepadAxis.h"
#include "Events/GamepadButton.h"
#include "Events/BindKey.h"
#include "Events/BindMouseButton.h"
#include "Events/BindGamepadAxis.h"
#include "Events/BindGamepadButton.h"
#include "Events/InputCommand.h"
namespace Systems
{
@@ -25,52 +13,22 @@ namespace Systems
class InputSystem : public System
{
public:
InputSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
InputSystem(World* world, std::shared_ptr<Renderer> renderer)
: System(world), m_Renderer(renderer) { }
void RegisterComponents(ComponentFactory* cf) override;
void Initialize() override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
std::unordered_map<std::string, std::unordered_map<int, float>> m_CommandKeyboardValues; // command string -> keyboard key value for command
std::unordered_map<std::string, std::unordered_map<int, float>> m_CommandMouseButtonValues; // command string -> mouse button value for command
std::unordered_map<std::string, std::unordered_map<Gamepad::Axis, float>> m_CommandGamepadAxisValues; // command string -> gamepad axis value for command
std::unordered_map<std::string, std::unordered_map<Gamepad::Button, float>> m_CommandGamepadButtonValues; // command string -> gamepad button value for command
// Input binding tables
std::unordered_map<int, std::tuple<std::string, float>> m_KeyBindings; // GLFW_KEY... -> command string & value
std::unordered_map<int, std::tuple<std::string, float>> m_MouseButtonBindings; // GLFW_MOUSE_BUTTON... -> command string
std::unordered_map<Gamepad::Axis, std::tuple<std::string, float>> m_GamepadAxisBindings; // Gamepad::Axis -> command string & value
std::unordered_map<Gamepad::Button, std::tuple<std::string, float>> m_GamepadButtonBindings; // Gamepad::Button -> command string
std::shared_ptr<Renderer> m_Renderer;
static std::array<int, GLFW_KEY_LAST+1> m_CurrentKeyState;
static std::array<int, GLFW_KEY_LAST+1> m_LastKeyState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> m_CurrentMouseState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> m_LastMouseState;
float m_CurrentMouseDeltaX, m_CurrentMouseDeltaY;
float m_LastMouseX, m_LastMouseY;
// Input events
EventRelay<Events::KeyDown> m_EKeyDown;
bool OnKeyDown(const Events::KeyDown &event);
EventRelay<Events::KeyUp> m_EKeyUp;
bool OnKeyUp(const Events::KeyUp &event);
EventRelay<Events::MousePress> m_EMousePress;
bool OnMousePress(const Events::MousePress &event);
EventRelay<Events::MouseRelease> m_EMouseRelease;
bool OnMouseRelease(const Events::MouseRelease &event);
EventRelay<Events::GamepadAxis> m_EGamepadAxis;
bool OnGamepadAxis(const Events::GamepadAxis &event);
EventRelay<Events::GamepadButtonDown> m_EGamepadButtonDown;
bool OnGamepadButtonDown(const Events::GamepadButtonDown &event);
EventRelay<Events::GamepadButtonUp> m_EGamepadButtonUp;
bool OnGamepadButtonUp(const Events::GamepadButtonUp &event);
// Input binding events
EventRelay<Events::BindKey> m_EBindKey;
bool OnBindKey(const Events::BindKey &event);
EventRelay<Events::BindMouseButton> m_EBindMouseButton;
bool OnBindMouseButton(const Events::BindMouseButton &event);
EventRelay<Events::BindGamepadAxis> m_EBindGamepadAxis;
bool OnBindGamepadAxis(const Events::BindGamepadAxis &event);
EventRelay<Events::BindGamepadButton> m_EBindGamepadButton;
bool OnBindGamepadButton(const Events::BindGamepadButton &event);
float GetCommandTotalValue(std::string command);
void PublishCommand(int playerID, std::string command, float value);
};
}
-277
View File
@@ -1,277 +0,0 @@
#include "PrecompiledHeader.h"
#include "ParticleSystem.h"
#include "World.h"
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)
{
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
if(!transformComponent)
return;
auto emitterComponent = m_World->GetComponent<Components::ParticleEmitter>(entity);
if(emitterComponent)
{
emitterComponent->TimeSinceLastSpawn += dt;
auto emitterTransformComponent = m_World->GetComponent<Components::Transform>(entity);
if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency)
{
SpawnParticles(entity);
emitterComponent->TimeSinceLastSpawn = 0;
}
std::list<ParticleData>::iterator it;
for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();)
{
EntityID particleID = (it)->ParticleID;
auto transformComponent = m_World->GetComponent<Components::Transform>(particleID);
auto particleComponent = m_World->GetComponent<Components::Particle>(particleID);
double timeLived = glfwGetTime() - it->SpawnTime;
if(timeLived > particleComponent->LifeTime)
{
m_World->RemoveEntity(particleID);
it = m_ParticleEmitter[entity].erase(it);
}
else
{
// FIX: calculate once
float timeProgress = timeLived / particleComponent->LifeTime;
// ColorInterpolation(timeProgress, particleComponent->ColorSpectrum, color);
// Scale interpolation
if(particleComponent->ScaleSpectrum.size() > 1)
VectorInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale);
// Velocity interpolation
if(particleComponent->VelocitySpectrum.size() > 1)
VectorInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity);
// Angular velocity interpolation
if (particleComponent->AngularVelocitySpectrum.size() != 0)
{
if(particleComponent->AngularVelocitySpectrum.size() > 1)
{
ScalarInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity);
transformComponent->Orientation = glm::angleAxis(it->AngularVelocity, it->Orientation);
}
else
{
transformComponent->Orientation *= glm::angleAxis(it->AngularVelocity, it->Orientation);
//it->Orientation = glm::angleAxis(it->AngularVelocity, it->Orientation);
}
}
//Angular velocity interpolation
if(particleComponent->OrientationSpectrum.size() > 1)
{
VectorInterpolation(timeProgress, particleComponent->OrientationSpectrum, it->Orientation);
glm::vec3 v1 = (particleComponent->OrientationSpectrum[0]);
glm::vec3 v2 = (it->Orientation);
glm::vec3 v3 = glm::normalize(glm::cross(v1,v2));
float angle = glm::acos(glm::dot(v1, v2) / (glm::length(v1) * glm::length(v2)));
transformComponent->Orientation = glm::angleAxis(angle, v3);
}
transformComponent->Position += transformComponent->Velocity * (float)dt;
it++;
}
}
}
}
void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::ParticleEmitter>([]() { return new Components::ParticleEmitter(); });
cf->Register<Components::Particle>([]() { return new Components::Particle(); });
}
void Systems::ParticleSystem::SpawnParticles(EntityID emitterID)
{
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);
for(int i = 0; i < eComponent->SpawnCount; i++)
{
auto particleEntity = m_World->CloneEntity(eComponent->ParticleTemplate);
auto particleTransform = m_World->GetComponent<Components::Transform>(particleEntity);
particleTransform->Position = ePosition;
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 = 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 particleComponent = m_World->AddComponent<Components::Particle>(particleEntity);
particleComponent->LifeTime = eComponent->LifeTime - 0.5;
particleComponent->ScaleSpectrum = eComponent->ScaleSpectrum;
particleComponent->VelocitySpectrum.push_back(particleTransform->Velocity);
if (eComponent->ScaleSpectrum.size() > 0)
{
if (eComponent->ScaleSpectrum.size() > 1)
{
particleComponent->ScaleSpectrum = eComponent->ScaleSpectrum;
}
else
{
particleTransform->Scale = eComponent->ScaleSpectrum[0];
}
}
else
{
particleTransform->Scale = glm::vec3(1, 1, 1);
}
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 = particleEntity;
data.SpawnTime = glfwGetTime();
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);
}
}
//Randomizes between -spreadAngle/2 and spreadAngle/2
float Systems::ParticleSystem::RandomizeAngle(float spreadAngle)
{
return ((float)rand() / ((float)RAND_MAX + 1) * spreadAngle) - spreadAngle/2;
}
//Interpolates the velocity of the particle
void Systems::ParticleSystem::VectorInterpolation(double timeProgress, std::vector<glm::vec3> spectrum, glm::vec3 &v)
{
float dAxisValue = glm::abs(spectrum[0].x - spectrum[1].x);
if(spectrum[0].x > spectrum[1].x)
dAxisValue *= -1;
v.x = spectrum[0].x + dAxisValue * timeProgress;
dAxisValue = glm::abs(spectrum[0].y - spectrum[1].y);
if (spectrum[0].y > spectrum[1].y)
dAxisValue *= -1;
v.y = spectrum[0].y + dAxisValue * timeProgress;
dAxisValue = glm::abs(spectrum[0].z - spectrum[1].z);
if(spectrum[0].z > spectrum[1].z)
dAxisValue *= -1;
v.z = spectrum[0].z + dAxisValue * timeProgress;
}
// void Systems::ParticleSystem::ColorInterpolation(double timeProgress, std::vector<Color> spectrum, Color &c)
// {
// float dColor = glm::abs(spectrum[0].r - spectrum[1].r);
// c.r = spectrum[0].r + dColor * timeProgress;
// dColor = glm::abs(spectrum[0].g - spectrum[1].g);
// c.g = spectrum[0].g + dColor * timeProgress;
// dColor = glm::abs(spectrum[0].b - spectrum[1].b);
// c.b = spectrum[0].b + dColor * timeProgress;
// }
void Systems::ParticleSystem::ScalarInterpolation(double timeProgress, std::vector<float> spectrum, float &alpha)
{
float dAlpha = glm::abs(spectrum[0] - spectrum[1]);
if(spectrum[0] > spectrum[1])
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;
}
-65
View File
@@ -1,65 +0,0 @@
#ifndef ParticleSystem_h__
#define ParticleSystem_h__
#include "System.h"
#include "Systems/TransformSystem.h"
#include "Components/Transform.h"
#include "Components/ParticleEmitter.h"
#include "Components/Particle.h"
#include "Components/Sprite.h"
#include "EventBroker.h"
#include "Events/KeyUp.h"
#include "Color.h"
#include <GLFW/glfw3.h>
namespace Systems
{
struct ParticleData
{
EntityID ParticleID;
double SpawnTime;
float AngularVelocity;
glm::vec3 Orientation;
Color color;
};
class ParticleSystem : public System
{
public:
ParticleSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
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);
//void ScaleInterpolation(double timeProgress, std::vector<float> spectrum, glm::vec3 &scale);
void VectorInterpolation(double timeProgress, std::vector<glm::vec3> spectrum, glm::vec3 &velocity);
//void ColorInterpolation(double timeProgress, std::vector<Color> spectrum, Color &color);
void ScalarInterpolation(double timeProgress, std::vector<float> spectrum, float &alpha);
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<Events::KeyUp> m_EKeyUp;
bool OnKeyUp(const Events::KeyUp &e);
};
}
#endif // !ParticleSystem_h__
+248 -416
View File
@@ -25,103 +25,48 @@
#include "PhysicsSystem.h"
#include "World.h"
void Systems::PhysicsSystem::Initialize()
Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world)
{
m_Accumulator = 0;
// Events
EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnTankSteer);
EVENT_SUBSCRIBE_MEMBER(m_ESetVelocity, &Systems::PhysicsSystem::OnSetVelocity);
EVENT_SUBSCRIBE_MEMBER(m_EApplyForce, &Systems::PhysicsSystem::OnApplyForce);
EVENT_SUBSCRIBE_MEMBER(m_EApplyPointImpulse, &Systems::PhysicsSystem::OnApplyPointImpulse);
hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer
hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo);
hkBaseSystem::init(memoryRouter, HavokErrorReport);
// Get the number of physical threads available on the system
hkHardwareInfo hwInfo;
hkGetHardwareInfo(hwInfo);
m_TotalNumThreadsUsed = hwInfo.m_numThreads;
// We use one less than this for our thread pool, because we must also use this thread for our simulation
hkCpuJobThreadPoolCinfo threadPoolCinfo;
threadPoolCinfo.m_numThreads = m_TotalNumThreadsUsed - 1;
// This line enables timers collection, by allocating 200 Kb per thread. If you leave this at its default (0),
// timer collection will not be enabled.
threadPoolCinfo.m_timerBufferPerThreadAllocation = 200000;
m_ThreadPool = new hkCpuJobThreadPool(threadPoolCinfo);
hkJobQueueCinfo info;
info.m_jobQueueHwSetup.m_numCpuThreads = m_TotalNumThreadsUsed;
m_JobQueue = new hkJobQueue(info);
//
// Enable monitors for this thread.
//
// Monitors have been enabled for thread pool threads already (see above comment).
hkMonitorStream::getInstance().resize(200000);
{
hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer
hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo);
hkBaseSystem::init(memoryRouter, HavokErrorReport);
hkpWorldCinfo worldInfo;
// Set the simulation type of the world to multi-threaded.
worldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_MULTITHREADED;
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_gravity = hkVector4(0.0f, -9.8f, 0.0f);
worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_FIX_ENTITY; // just fix the entity if the object falls off too far
// You must specify the size of the broad phase - objects should not be simulated outside this region
worldInfo.setBroadPhaseWorldSize(1500.0f);
worldInfo.setBroadPhaseWorldSize(1000.0f);
m_PhysicsWorld = new hkpWorld(worldInfo);
// When the simulation type is SIMULATION_TYPE_MULTITHREADED, in the debug build, the sdk performs checks
// to make sure only one thread is modifying the world at once to prevent multithreaded bugs. Each thread
// must call markForRead / markForWrite before it modifies the world to enable these checks.
m_PhysicsWorld->markForWrite();
// Register all collision agents, even though only box - box will be used in this particular example.
// It's important to register collision agents before adding any entities to the world.
hkpAgentRegisterUtil::registerAllAgents(m_PhysicsWorld->getCollisionDispatcher());
// We need to register all modules we will be running multi-threaded with the job queue
m_PhysicsWorld->registerWithJobQueue(m_JobQueue);
//
// Initialize the visual debugger so we can connect remotely to the simulation
// The context must exist beyond the use of the VDB instance, and you can make
// whatever contexts you like for your own viewer types.
//
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_PhysicsWorld->unmarkForWrite();
m_collisionResolution = new MyCollisionResolution(this);
}
// Register all collision agents, even though only box - box will be used in this particular example.
// It's important to register collision agents before adding any entities to the world.
hkpAgentRegisterUtil::registerAllAgents(m_PhysicsWorld->getCollisionDispatcher());
//
// Initialize the visual debugger so we can connect remotely to the simulation
// The context must exist beyond the use of the VDB instance, and you can make
// whatever contexts you like for your own viewer types.
//
hkpPhysicsContext* context = new hkpPhysicsContext;
hkpPhysicsContext::registerAllPhysicsProcesses(); // all the physics viewers
context->addWorld(m_PhysicsWorld); // add the physics world so the viewers can see it
SetupVisualDebugger(context);
//SetupPhysics(m_PhysicsWorld);
}
void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::Physics>([]() { return new Components::Physics(); });
cf->Register<Components::BoxShape>([]() { return new Components::BoxShape(); });
cf->Register<Components::SphereShape>([]() { return new Components::SphereShape(); });
cf->Register<Components::Vehicle>([]() { return new Components::Vehicle(); });
cf->Register<Components::Wheel>([]() { return new Components::Wheel(); });
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("Physics", []() { return new Components::Physics(); });
cf->Register("Box", []() { return new Components::Box(); });
cf->Register("Sphere", []() { return new Components::Sphere(); });
cf->Register("Vehicle", []() { return new Components::Vehicle(); });
cf->Register("Wheel", []() { return new Components::Wheel(); });
}
void Systems::PhysicsSystem::Update(double dt)
@@ -129,71 +74,51 @@ void Systems::PhysicsSystem::Update(double dt)
for (auto pair : *m_World->GetEntities())
{
EntityID entity = pair.first;
EntityID parent = pair.second;
if (m_RigidBodies.find(entity) == m_RigidBodies.end())
continue;
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent)
continue;
if(m_RigidBodies[entity]->isActive())
{
hkVector4 position;
hkQuaternion rotation;
if (parent)
{
auto absoluteTransform = m_World->GetSystem<Systems::TransformSystem>()->AbsoluteTransform(entity);
position = GLMVEC3_TO_HKVECTOR4(absoluteTransform.Position);
rotation = GLMQUAT_TO_HKQUATERNION(absoluteTransform.Orientation);
}
else
{
position = GLMVEC3_TO_HKVECTOR4(transformComponent->Position);
rotation = GLMQUAT_TO_HKQUATERNION(transformComponent->Orientation);
}
m_PhysicsWorld->markForWrite();
hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z);
hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w);
m_RigidBodies[entity]->setPositionAndRotation(position, rotation);
m_PhysicsWorld->unmarkForWrite();
}
}
static const double timestep = 1 / 60.0;
static const double timestep = 1 / 30.0;
m_Accumulator += dt;
while (m_Accumulator >= timestep)
{
m_PhysicsWorld->stepMultithreaded(m_JobQueue, m_ThreadPool, timestep);
//m_PhysicsWorld->stepDeltaTime(timestep);
m_PhysicsWorld->stepDeltaTime(timestep);
m_Accumulator -= timestep;
}
m_Context->syncTimers(m_ThreadPool);
// Step the visual debugger
StepVisualDebugger();
// Clear accumulated timer data in this thread and all slave threads
hkMonitorStream::getInstance().reset();
m_ThreadPool->clearTimerData();
}
// Step the visual debugger
StepVisualDebugger();
}
void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent)
return;
auto wheelComponent = m_World->GetComponent<Components::Wheel>(entity);
auto wheelComponent = m_World->GetComponent<Components::Wheel>(entity, "Wheel");
if (wheelComponent)
{
EntityID car = m_World->GetEntityParent(entity);
if(m_Vehicles.find(car) != m_Vehicles.end())
{
m_PhysicsWorld->markForWrite();
m_Vehicles[car]->getChassis()->activate();
hkVector4 hardPoint = m_Vehicles[car]->m_suspension->m_wheelParams[wheelComponent->ID].m_hardpointChassisSpace;
@@ -204,37 +129,50 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
hkQuaternion steeringOrientation = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_steeringOrientationChassisSpace;
hkReal spinAngle = -m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_spinAngle;
glm::quat orientation = HKQUATERNION_TO_GLMQUAT(steeringOrientation) * glm::angleAxis<float>(spinAngle, glm::vec3(1, 0, 0));
glm::quat orientation = glm::quat(steeringOrientation(3), steeringOrientation(0), steeringOrientation(1), steeringOrientation(2)) * glm::angleAxis<float>(spinAngle, glm::vec3(1, 0, 0));
transformComponent->Orientation = orientation * wheelComponent->OriginalOrientation;
m_PhysicsWorld->unmarkForWrite();
}
}
else if(m_Vehicles.find(entity) != m_Vehicles.end())
{
hkVector4 position = m_RigidBodies[entity]->getPosition();
transformComponent->Position = glm::vec3(position(0), position(1), position(2));
hkQuaternion orientation = m_RigidBodies[entity]->getRotation();
transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2));
}
else if(m_RigidBodies.find(entity) != m_RigidBodies.end())
{
auto transformComponentParent = m_World->GetComponent<Components::Transform>(parent);
transformComponent->Position = HKVECTOR4_TO_GLMVEC3(m_RigidBodies[entity]->getPosition());
transformComponent->Orientation = HKQUATERNION_TO_GLMQUAT(m_RigidBodies[entity]->getRotation());
// TODO: No support for Scale, MIGHT be possible
if (transformComponentParent)
if(m_RigidBodies[entity]->isActive())
{
transformComponent->Position -= transformComponentParent->Position;
transformComponent->Position = transformComponent->Position * transformComponentParent->Orientation;
transformComponent->Orientation = transformComponent->Orientation * glm::inverse(transformComponentParent->Orientation);
hkVector4 position = m_RigidBodies[entity]->getPosition();
transformComponent->Position = glm::vec3(position(0), position(1), position(2));
hkQuaternion orientation = m_RigidBodies[entity]->getRotation();
transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2));
}
}
// HACK: Vehicle test-controls
auto vehicleComponent = m_World->GetComponent<Components::Vehicle>(entity, "Vehicle");
auto inputComponent = m_World->GetComponent<Components::Input>(entity, "Input");
if (vehicleComponent && inputComponent)
{
hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus;
deviceStatus->m_positionY = inputComponent->KeyState[GLFW_KEY_UP] * -1 + inputComponent->KeyState[GLFW_KEY_DOWN] * 1;
deviceStatus->m_positionX = inputComponent->KeyState[GLFW_KEY_LEFT] * -1 + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1;
deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL];
}
}
void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
{
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent)
return;
auto wheelComponent = m_World->GetComponent<Components::Wheel>(entity);
auto wheelComponent = m_World->GetComponent<Components::Wheel>(entity, "Wheel");
if (wheelComponent)
{
wheelComponent->ID = m_Wheels.size();
@@ -242,251 +180,201 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity )
m_Wheels.push_back(entity);
}
EntityID entityParent = m_World->GetEntityBaseParent(entity);
auto sphereComponent = m_World->GetComponent<Components::SphereShape>(entity);
auto boxComponent = m_World->GetComponent<Components::BoxShape>(entity);
auto meshShapeComponent = m_World->GetComponent<Components::MeshShape >(entity);
if(entityParent == entity && (sphereComponent || boxComponent || meshShapeComponent))
{
LOG_ERROR("Entity: %i , Only the children can have a shapeComponent", entity);
auto physicsComponent = m_World->GetComponent<Components::Physics>(entity, "Physics");
if (!physicsComponent)
return;
}
auto physicsComponent = m_World->GetComponent<Components::Physics>(entity);
if (physicsComponent)
auto sphereComponent = m_World->GetComponent<Components::Sphere >(entity, "Sphere");
auto boxComponent = m_World->GetComponent<Components::Box >(entity, "Box");
hkpConvexShape* shape;
hkpRigidBodyCinfo rigidBodyInfo;
hkMassProperties massProperties;
if (sphereComponent)
{
hkpShape* shape;
if(entityParent != entity)
shape = new hkpSphereShape(sphereComponent->Radius);
rigidBodyInfo.m_shape = shape;
if (physicsComponent->Static)
{
LOG_ERROR("Entity: %i , Only the baseparent can have a PhysicsComponent", entity);
return;
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
}
else
{
rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA;
}
if(! physicsComponent->Static) // Not static
hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties);
}
else if (boxComponent)
{
hkReal thickness = 0.05;
shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness));
rigidBodyInfo.m_shape = shape;
if (physicsComponent->Static)
{
hkArray<hkpShape*> shapeArray;
for (auto &shapeData : m_Shapes[entity])
{
shapeArray.pushBack(shapeData.Shape);
}
// Create a hkpListShape* of all the childEntities collected in m_ShapeArrays
hkpListShape* listShape = new hkpListShape(shapeArray.begin(), shapeArray.getSize(), hkpShapeContainer::REFERENCE_POLICY_INCREMENT);
// Save the listShape for further use
m_ListShapes[entity] = listShape;
//shape = listShape;
hkpBoxShape* box = new hkpBoxShape(listShape->m_aabbHalfExtents, 0.0f);
shape = new hkpBvShape(listShape, box);
// Clean up for less memory usage
m_Shapes.erase(entity);
hkMassProperties massProperties;
hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape, physicsComponent->Mass, massProperties);
hkpRigidBodyCinfo rigidBodyInfo;
{
rigidBodyInfo.m_shape = shape;
rigidBodyInfo.m_motionType = hkpMotion::MOTION_DYNAMIC;
auto absoluteTransform = m_World->GetSystem<Systems::TransformSystem>()->AbsoluteTransform(entity);
hkVector4 position = GLMVEC3_TO_HKVECTOR4(absoluteTransform.Position);
hkQuaternion rotation = GLMQUAT_TO_HKQUATERNION(absoluteTransform.Orientation);
rigidBodyInfo.m_position.set(position(0), position(1), position(2), position(3));
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
rigidBodyInfo.m_mass = massProperties.m_mass;
}
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
auto vehicleComponent = m_World->GetComponent<Components::Vehicle >(entity);
if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end())
{
for (int i = 0; i < m_Wheels.size(); i++)
{
if(m_World->GetEntityParent(m_Wheels[i]) != entity)
{
m_Wheels.erase(m_Wheels.begin() + i);
i--;
}
}
VehicleSetup vehicleSetup;
// Create the basic vehicle.
m_Vehicles[entity] = new hkpVehicleInstance(rigidBody);
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 );
m_Vehicles[entity]->addToWorld(m_PhysicsWorld);
m_RigidBodies[entity] = rigidBody;
m_RigidBodyEntities[rigidBody] = entity;
// The vehicle is an action
m_PhysicsWorld->addAction(m_Vehicles[entity]);
m_PhysicsWorld->unmarkForWrite();
//m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here
m_Wheels.clear();
shape->removeReference();
rigidBody->removeReference();
}
else
{
m_PhysicsWorld->markForWrite();
rigidBody->addContactListener( m_collisionResolution );
m_PhysicsWorld->addEntity(rigidBody);
m_RigidBodies[entity] = rigidBody;
m_RigidBodyEntities[rigidBody] = entity;
m_PhysicsWorld->unmarkForWrite();
shape->removeReference();
rigidBody->removeReference();
}
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
}
else // Static
else
{
// Create the hkpStaticCompoundShape and add the instances.
// "meshShape" should not be modified by the user in any way after adding it as an instance.
hkpStaticCompoundShape* staticCompoundShape = new hkpStaticCompoundShape();
for (auto &shapeData : m_Shapes[entity])
{
auto childTransformComponent = m_World->GetComponent<Components::Transform>(shapeData.Entity);
hkVector4 position = GLMVEC3_TO_HKVECTOR4(childTransformComponent->Position);
hkQuaternion rotation = GLMQUAT_TO_HKQUATERNION(childTransformComponent->Orientation);
hkVector4 scale = GLMVEC3_TO_HKVECTOR4(childTransformComponent->Scale);
hkQsTransform transform(position, rotation, scale);
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);
hkpRigidBodyCinfo rigidBodyInfo;
{
rigidBodyInfo.m_shape = shape;
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
auto absoluteTransform = m_World->GetSystem<Systems::TransformSystem>()->AbsoluteTransform(entity);
hkVector4 position = GLMVEC3_TO_HKVECTOR4(absoluteTransform.Position);
hkQuaternion rotation = GLMQUAT_TO_HKQUATERNION(absoluteTransform.Orientation);
rigidBodyInfo.m_position.set(position(0), position(1), position(2), position(3));
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
rigidBodyInfo.m_mass = massProperties.m_mass;
}
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
m_PhysicsWorld->markForWrite();
m_PhysicsWorld->addEntity(rigidBody);
m_RigidBodies[entity] = rigidBody;
m_RigidBodyEntities[rigidBody] = entity;
m_PhysicsWorld->unmarkForWrite();
shape->removeReference();
rigidBody->removeReference();
rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA;
}
hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties);
}
else
{
//TODO: COMMENT THIS SECTION
if(sphereComponent)
{
hkpSphereShape* sphereShape = new hkpSphereShape(sphereComponent->Radius);
hkQsTransform transform( GLMVEC3_TO_HKVECTOR4(transformComponent->Position), GLMQUAT_TO_HKQUATERNION(transformComponent->Orientation), GLMVEC3_TO_HKVECTOR4(transformComponent->Scale));
hkpConvexTransformShape* transformedSphereShape = new hkpConvexTransformShape( sphereShape, transform );
m_Shapes[entityParent].push_back(ShapeArrayData(entity, transformedSphereShape));
sphereShape->removeReference();
}
//TODO: COMMENT THIS SECTION
else if(boxComponent)
{
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();
}
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);
for (auto &vertex : meshShape->Vertices)
{
hkReal x, y, z;
std::tie(x, y, z) = vertex;
vertices->push_back(x);
vertices->push_back(y);
vertices->push_back(z);
}
int i = 0;
for (auto &face : meshShape->Faces)
{
for (auto &faceDef : face.Definitions)
{
vertexIndices->push_back(faceDef.VertexIndex - 1);
}
}
hkpExtendedMeshShape* mesh = new hkpExtendedMeshShape();
hkReal thickness = 0.05f; // HACK: Convex radius should be 0 for static shapes and 0.05 for dynamic shapes.
mesh->setRadius(thickness);
{
hkpExtendedMeshShape::TrianglesSubpart part;
part.m_numTriangleShapes = meshShape->Faces.size();
part.m_indexBase = vertexIndices->data();
part.m_indexStriding = sizeof(hkUint16) * 3;
part.m_numVertices = vertices->size() / 3;
part.m_vertexBase = vertices->data();
part.m_vertexStriding = sizeof(hkReal) * 3;
part.m_stridingType = hkpExtendedMeshShape::INDICES_INT16;
mesh->addTrianglesSubpart(part);
}
hkpMoppCompilerInput mci;
hkpMoppCode* code = hkpMoppUtility::buildCode( mesh, mci );
hkpMoppBvTreeShape* moppShape = new hkpMoppBvTreeShape(mesh, code);
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
}
return;
}
rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z);
rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor;
rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass;
rigidBodyInfo.m_mass = massProperties.m_mass;
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
auto vehicleComponent = m_World->GetComponent<Components::Vehicle >(entity, "Vehicle");
if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end())
{
for (int i = 0; i < m_Wheels.size(); i++)
{
if(m_World->GetEntityParent(m_Wheels[i]) != entity)
{
m_Wheels.erase(m_Wheels.begin() + i);
i--;
}
}
VehicleSetup vehicleSetup;
// Create the basic vehicle.
m_Vehicles[entity] = new hkpVehicleInstance(rigidBody);
vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels);
// Add the vehicle's entities and phantoms to the world
m_Vehicles[entity]->addToWorld(m_PhysicsWorld);
m_RigidBodies[entity] = rigidBody;
// The vehicle is an action
m_PhysicsWorld->addAction(m_Vehicles[entity]);
//m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here
m_Wheels.clear();
shape->removeReference();
rigidBody->removeReference();
}
else
{
m_PhysicsWorld->addEntity(rigidBody);
m_RigidBodies[entity] = rigidBody;
shape->removeReference();
rigidBody->removeReference();
}
}
/*
void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
{
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent)
return;
auto physicsComponent = m_World->GetComponent<Components::Physics>(entity, "Physics");
if (!physicsComponent)
return;
auto sphereComponent = m_World->GetComponent<Components::Sphere >(entity, "Sphere");
auto boxComponent = m_World->GetComponent<Components::Box >(entity, "Box");
hkpConvexShape* shape;
hkpRigidBodyCinfo rigidBodyInfo;
hkMassProperties massProperties;
if (sphereComponent)
{
shape = new hkpSphereShape(sphereComponent->Radius);
rigidBodyInfo.m_shape = shape;
if (physicsComponent->Static)
{
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
}
else
{
rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA;
}
hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties);
}
else if (boxComponent)
{
hkReal thickness = 0.05;
shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness));
rigidBodyInfo.m_shape = shape;
if (physicsComponent->Static)
{
rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED;
}
else
{
rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA;
}
hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties);
}
else
{
return;
}
rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z);
rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor;
rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass;
rigidBodyInfo.m_mass = massProperties.m_mass;
// Create RigidBody
hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo);
auto vehicleComponent = m_World->GetComponent<Components::Vehicle >(entity, "Vehicle");
if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end())
{
VehicleSetup vehicleSetup;
// Create the basic vehicle.
m_Vehicles[entity] = new hkpVehicleInstance(rigidBody);
vehicleSetup.buildVehicle(m_PhysicsWorld, *m_Vehicles[entity]);
// Add the vehicle's entities and phantoms to the world
m_Vehicles[entity]->addToWorld(m_PhysicsWorld);
m_RigidBodies[entity] = rigidBody;
// The vehicle is an action
m_PhysicsWorld->addAction(m_Vehicles[entity]);
//m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here
shape->removeReference();
rigidBody->removeReference();
}
else
{
m_PhysicsWorld->addEntity(rigidBody);
m_RigidBodies[entity] = rigidBody;
shape->removeReference();
rigidBody->removeReference();
}
}
*/
void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent)
{
@@ -508,9 +396,8 @@ void Systems::PhysicsSystem::SetupVisualDebugger(hkpPhysicsContext* worlds)
{
// Setup the visual debugger
hkArray<hkProcessContext*> contexts;
contexts.pushBack(worlds);
m_VisualDebugger = new hkVisualDebugger(contexts);
m_VisualDebugger->serve();
@@ -536,58 +423,3 @@ void HK_CALL Systems::PhysicsSystem::HavokErrorReport(const char* msg, void*)
LOG_INFO("%s", msg);
}
bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event)
{
auto vehicleComponent = m_World->GetComponent<Components::Vehicle>(event.Entity);
if (vehicleComponent && m_Vehicles.find(event.Entity) != m_Vehicles.end() && m_RigidBodies.find(event.Entity) != m_RigidBodies.end())
{
hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[event.Entity]->m_deviceStatus;
deviceStatus->m_positionX = event.PositionX;
deviceStatus->m_positionY = event.PositionY;
if(event.PositionY > 0)
{
deviceStatus->m_reverseButtonPressed = true;
}
deviceStatus->m_handbrakeButtonPressed = event.Handbrake;
}
return true;
}
bool Systems::PhysicsSystem::OnSetVelocity( const Events::SetVelocity &event )
{
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();
return true;
}
bool Systems::PhysicsSystem::OnApplyPointImpulse( const Events::ApplyPointImpulse &event )
{
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::OnEntityRemoved( EntityID entity )
{
// TODO:
/*auto rigidBodyIt = m_RigidBodies.find(entity);
if (rigidBodyIt == m_RigidBodies.end())
return;
auto rigidBody = rigidBodyIt->second;
m_RigidBodies.erase(entity);
m_RigidBodyEntities.erase(rigidBody);
rigidBody->removeReference();*/
}
+6 -126
View File
@@ -1,34 +1,13 @@
#ifndef PhysicsSystem_h__
#define PhysicsSystem_h__
#define HKVECTOR4_TO_GLMVEC3(hkvec) \
glm::vec3(hkvec(0), hkvec(1), hkvec(2))
#define GLMVEC3_TO_HKVECTOR4(glmvec) \
hkVector4(glmvec.x, glmvec.y, glmvec.z)
#define HKQUATERNION_TO_GLMQUAT(gkquat) \
glm::quat(gkquat(3), gkquat(0), gkquat(1), gkquat(2))
#define GLMQUAT_TO_HKQUATERNION(glmquat) \
hkQuaternion(glmquat.x, glmquat.y, glmquat.z, glmquat.w)
#include "System.h"
#include "Systems/TransformSystem.h"
#include "Components/Transform.h"
#include "Components/Physics.h"
#include "Components/BoxShape.h"
#include "Components/SphereShape.h"
#include "Components/Sphere.h"
#include "Components/Box.h"
#include "Components/Vehicle.h"
#include "Components/Input.h"
#include "Components/MeshShape.h"
#include "Components/HingeConstraint.h"
#include "Components/WheelPair.h"
#include "Components/TowerSteering.h"
#include "Events/TankSteer.h"
#include "Events/SetVelocity.h"
#include "Events/ApplyForce.h"
#include "Events/ApplyPointImpulse.h"
#include "Events/Collision.h"
#include "OBJ.h"
// Math and base include
#include <Common/Base/hkBase.h>
@@ -55,93 +34,28 @@
#include <Common/Visualize/hkVisualDebugger.h>
#include <Physics2012/Utilities/VisualDebugger/hkpPhysicsContext.h>
#include <Physics2012/Collide/Shape/Compound/Collection/ExtendedMeshShape/hkpExtendedMeshShape.h>
#include <Physics2012/Collide/Shape/Compound/Tree/Mopp/hkpMoppBvTreeShape.h>
#include <Physics2012/Collide/Shape/Compound/Tree/Mopp/hkpMoppUtility.h>
#include <Common/Base/Thread/JobQueue/hkJobQueue.h>
#include <Common/Base/Thread/Job/ThreadPool/Cpu/hkCpuJobThreadPool.h>
#include <Common/Base/DebugUtil/MultiThreadCheck/hkMultiThreadCheck.h>
#include <Physics/Constraint/Data/Hinge/hkpHingeConstraintData.h>
#include <Physics/Constraint/Data/LimitedHinge/hkpLimitedHingeConstraintData.h>
#include <Physics2012/Collide/Shape/Compound/Collection/List/hkpListShape.h>
#include <Physics2012/Internal/Collide/StaticCompound/hkpStaticCompoundShape.h>
#include <Physics2012/Collide/Util/ShapeShrinker/hkpShapeShrinker.h>
#include <Physics2012/Collide/Shape/Misc/Bv/hkpBvShape.h>
#include "Physics/VehicleSetup.h"
#include <unordered_map>
#include <Physics2012/Dynamics/Collide/ContactListener/hkpContactListener.h>
#include "Components/Model.h"
namespace Systems
{
class PhysicsSystem : public System
{
public:
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);
auto modelComponent = m_PhysicsSystem->m_World->GetComponent<Components::Model>(entity1);
if (modelComponent && modelComponent->ModelFile == "Models/Placeholders/rocket/Rocket.obj" && entity2 == 6)
{
m_PhysicsSystem->m_PhysicsWorld->markForWrite();
m_PhysicsSystem->m_RigidBodies[entity1]->setPosition(hkVector4(2000, -2000, 2000));
m_PhysicsSystem->m_PhysicsWorld->unmarkForWrite();
}
}
private:
Systems::PhysicsSystem* m_PhysicsSystem;
};
friend class MyCollisionResolution;
PhysicsSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
PhysicsSystem(World* world);
void RegisterComponents(ComponentFactory* cf) 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 OnEntityCommit(EntityID entity) override;
void OnEntityRemoved(EntityID entity) override;
private:
double m_Accumulator;
hkpWorld* m_PhysicsWorld;
// Events
EventRelay<Events::TankSteer> m_ETankSteer;
bool OnTankSteer(const Events::TankSteer &event);
EventRelay<Events::SetVelocity> m_ESetVelocity;
bool OnSetVelocity(const Events::SetVelocity &event);
EventRelay<Events::ApplyForce> m_EApplyForce;
bool OnApplyForce(const Events::ApplyForce &event);
EventRelay<Events::ApplyPointImpulse> m_EApplyPointImpulse;
bool OnApplyPointImpulse(const Events::ApplyPointImpulse &event);
void SetUpPhysicsState(EntityID entity, EntityID parent);
void TearDownPhysicsState(EntityID entity, EntityID parent);
@@ -150,48 +64,14 @@ private:
void StepVisualDebugger();
static void HK_CALL HavokErrorReport(const char* msg, void*);
void SetupPhysics(hkpWorld* physicsWorld);
std::unordered_map<EntityID, hkpRigidBody*> m_RigidBodies;
std::unordered_map<hkpRigidBody*, EntityID> m_RigidBodyEntities;
hkJobThreadPool* m_ThreadPool;
hkJobQueue* m_JobQueue;
int m_TotalNumThreadsUsed;
hkpPhysicsContext* m_Context;
std::unordered_map<EntityID, hkpRigidBody*> m_RigidBodies;
std::unordered_map<EntityID, hkpVehicleInstance*> m_Vehicles;
std::vector<EntityID> m_Wheels;
hkpVehicleInstance* Systems::PhysicsSystem::createVehicle(VehicleSetup& vehicleSetup, hkpRigidBody* chassis);
struct ShapeArrayData
{
ShapeArrayData(EntityID entity, hkpShape* shape)
{
Entity = entity;
Shape = shape;
}
EntityID Entity;
hkpShape* Shape;
};
std::unordered_map<EntityID, std::list<ShapeArrayData>> m_Shapes;
std::unordered_map<EntityID, hkpListShape*> m_ListShapes;
struct ExtendedShapeData
{
hkpExtendedMeshShape* ExtendedMeshShape;
std::vector<hkReal>* Vertices;
std::vector<hkUint16>* VertexIndices;
hkpMoppCode* Code;
hkpMoppBvTreeShape* MoppShape;
};
std::unordered_map<EntityID, ExtendedShapeData > m_ExtendedMeshShapes;
MyCollisionResolution* m_collisionResolution;
};
}
#endif // PhysicsSystem_h__
-25
View File
@@ -1,25 +0,0 @@
#include "PrecompiledHeader.h"
#include "RaySystem.h"
#include "World.h"
void Systems::RaySystem::Initialize()
{
// Subscribe to events
EVENT_SUBSCRIBE_MEMBER(m_ECastRay, &Systems::RaySystem::OnCastRay);
}
void Systems::RaySystem::Update(double dt)
{
}
void Systems::RaySystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
}
bool Systems::RaySystem::OnCastRay(const Events::CastRay &event)
{
Ray r;
return true;
}
-35
View File
@@ -1,35 +0,0 @@
#ifndef DebugSystem_h__
#define DebugSystem_h__
#include "System.h"
#include "Events/CastRay.h"
namespace Systems
{
class RaySystem : public System
{
public:
RaySystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
void Initialize() override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private:
struct Ray
{
glm::vec3 Direction;
};
EventRelay<Events::CastRay> m_ECastRay;
bool OnCastRay(const Events::CastRay &event);
std::list<Ray> m_UnresolvedRays;
//void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
};
}
#endif // DebugSystem_h__
+41 -79
View File
@@ -2,119 +2,81 @@
#include "RenderSystem.h"
#include "World.h"
void Systems::RenderSystem::RegisterResourceTypes(ResourceManager* rm)
void Systems::RenderSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component)
{
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); });
}
void Systems::RenderSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::Camera>([]() { return new Components::Camera(); });
cf->Register<Components::Model>([]() { return new Components::Model(); });
cf->Register<Components::Sprite>([]() { return new Components::Sprite(); });
cf->Register<Components::PointLight>([]() { return new Components::PointLight(); });
cf->Register<Components::DirectionalLight>([]() { return new Components::DirectionalLight(); });
cf->Register<Components::Viewport>([]() { return new Components::Viewport(); });
}
void Systems::RenderSystem::OnEntityCommit(EntityID entity)
{
auto transform = m_World->GetComponent<Components::Transform>(entity);
auto camera = m_World->GetComponent<Components::Camera>(entity);
if (transform && camera)
if(type == "Model")
{
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 modelComponent = std::static_pointer_cast<Components::Model>(component);
}
}
void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto templateComponent = m_World->GetComponent<Components::Template>(entity);
if (templateComponent)
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (transformComponent == nullptr)
return;
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
// Draw models
auto modelComponent = m_World->GetComponent<Components::Model>(entity);
if (transformComponent && modelComponent)
auto modelComponent = m_World->GetComponent<Components::Model>(entity, "Model");
if (modelComponent != nullptr)
{
auto model = m_World->GetResourceManager()->Load<Model>("Model", modelComponent->ModelFile);
if (model)
if (model != nullptr)
{
/*glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
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);
glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity);
m_Renderer->AddModelToDraw(model, position, orientation, scale, modelComponent->Visible, modelComponent->ShadowCaster);
}
}
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity);
if (transformComponent && pointLightComponent)
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity, "PointLight");
if (pointLightComponent != nullptr)
{
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
m_Renderer->AddPointLightToDraw(
position,
pointLightComponent->Specular,
pointLightComponent->Diffuse,
pointLightComponent->specularExponent,
pointLightComponent->ConstantAttenuation,
pointLightComponent->LinearAttenuation,
pointLightComponent->QuadraticAttenuation
pointLightComponent->specularExponent
);
}
auto cameraComponent = m_World->GetComponent<Components::Camera>(entity);
if (transformComponent && cameraComponent)
auto cameraComponent = m_World->GetComponent<Components::Camera>(entity, "Camera");
if (cameraComponent != nullptr)
{
m_Renderer->UpdateCamera(entity
, m_TransformSystem->AbsolutePosition(entity)
, m_TransformSystem->AbsoluteOrientation(entity)
, cameraComponent->FOV
, cameraComponent->NearClip
, cameraComponent->FarClip);
}
m_Renderer->GetCamera()->Position(m_TransformSystem->AbsolutePosition(entity));
m_Renderer->GetCamera()->Orientation(m_TransformSystem->AbsoluteOrientation(entity));
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);
m_Renderer->GetCamera()->FOV(cameraComponent->FOV);
m_Renderer->GetCamera()->NearClip(cameraComponent->NearClip);
m_Renderer->GetCamera()->FarClip(cameraComponent->FarClip);
}
}
void Systems::RenderSystem::Initialize()
{
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>("TransformSystem");
m_Renderer->SetSphereModel(m_World->GetResourceManager()->Load<Model>("Model", "Models/Placeholders/PhysicsTest/Sphere.obj"));
}
void Systems::RenderSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register("Camera", []() { return new Components::Camera(); });
cf->Register("Model", []() { return new Components::Model(); });
cf->Register("Sprite", []() { return new Components::Sprite(); });
cf->Register("PointLight", []() { return new Components::PointLight(); });
cf->Register("DirectionalLight", []() { return new Components::DirectionalLight(); });
}
void Systems::RenderSystem::RegisterResourceTypes(ResourceManager* rm)
{
rm->RegisterType("Model", [rm](std::string resourceName) { return new Model(OBJ(resourceName), rm); });
rm->RegisterType("Texture", [](std::string resourceName) { return new Texture(resourceName); });
}
+3 -5
View File
@@ -13,7 +13,6 @@
#include "Components/Sprite.h"
#include "Components/PointLight.h"
#include "Components/DirectionalLight.h"
#include "Components/Viewport.h"
#include "Components/Template.h"
#include "Components/Transform.h"
@@ -25,9 +24,8 @@ 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<Renderer> renderer)
: System(world), m_Renderer(renderer) { }
void RegisterComponents(ComponentFactory* cf) override;
void RegisterResourceTypes(ResourceManager* rm) override;
@@ -35,7 +33,7 @@ public:
std::unordered_map<std::string, std::shared_ptr<Model>> m_CachedModels;
void OnEntityCommit(EntityID entity) override;
void OnComponentCreated(std::string type, std:: shared_ptr<Component> component) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
+5 -20
View File
@@ -2,7 +2,8 @@
#include "SoundSystem.h"
#include "World.h"
void Systems::SoundSystem::Initialize()
Systems::SoundSystem::SoundSystem(World* world)
: System(world)
{
//initialize OpenAL
ALCdevice* Device = alcOpenDevice(NULL);
@@ -21,15 +22,11 @@ void Systems::SoundSystem::Initialize()
alSpeedOfSound(340.29f); // Speed of sound
alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
// Subscribe to events
m_EPlaySound = decltype(m_EPlaySound)(std::bind(&Systems::SoundSystem::OnPlaySound, this, std::placeholders::_1));
EventBroker->Subscribe(m_EPlaySound);
}
void Systems::SoundSystem::RegisterComponents(ComponentFactory* cf)
{
cf->Register<Components::SoundEmitter>([]() { return new Components::SoundEmitter(); });
cf->Register("SoundEmitter", []() { return new Components::SoundEmitter(); });
}
void Systems::SoundSystem::RegisterResourceTypes(ResourceManager* rm)
@@ -44,7 +41,7 @@ void Systems::SoundSystem::Update(double dt)
void Systems::SoundSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{
auto transformComponent = m_World->GetComponent<Components::Transform>(entity);
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (transformComponent == nullptr)
return;
@@ -68,7 +65,7 @@ void Systems::SoundSystem::UpdateEntity(double dt, EntityID entity, EntityID par
alListenerfv(AL_ORIENTATION, listenerOri);
}
auto soundEmitter = m_World->GetComponent<Components::SoundEmitter>(entity);
auto soundEmitter = m_World->GetComponent<Components::SoundEmitter>(entity, "SoundEmitter");
if(soundEmitter != nullptr)
{
ALuint source = m_Sources[soundEmitter];
@@ -146,15 +143,3 @@ ALuint Systems::SoundSystem::CreateSource()
return source;
}
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 source = m_Sources.begin()->second;
alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(source);
return true;
}
+1 -9
View File
@@ -7,7 +7,6 @@
#include "System.h"
#include "Components/Transform.h"
#include "Components/SoundEmitter.h"
#include "Events/PlaySound.h"
#include "Sound.h"
namespace Systems
@@ -16,12 +15,9 @@ namespace Systems
class SoundSystem : public System
{
public:
SoundSystem(World* world, std::shared_ptr<::EventBroker> eventBroker)
: System(world, eventBroker) { }
SoundSystem(World* world);
void RegisterComponents(ComponentFactory* cf) override;
void RegisterResourceTypes(ResourceManager* rm) override;
void Initialize() override;
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
@@ -43,10 +39,6 @@ private:
//short bytesPerSample, bitsPerSample;
//unsigned long dataSize;
// Events
EventRelay<Events::PlaySound> m_EPlaySound;
bool OnPlaySound(const Events::PlaySound &event);
std::map<Component*, ALuint> m_Sources;
std::map<std::string, ALuint> m_BufferCache; // string = fileName
};

Some files were not shown because too many files have changed in this diff Show More