1 Commits

Author SHA1 Message Date
Jace 4494e7592d How NOT to do normal maps 2014-05-10 16:01:36 +02:00
149 changed files with 1475 additions and 8285 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 bc811a1b39
+34 -21
View File
@@ -1,21 +1,25 @@
#include "PrecompiledHeader.h"
#include "Camera.h"
Camera::Camera(float yFOV, float nearClip, float farClip)
Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip)
{
m_FOV = yFOV;
m_AspectRatio = aspectRatio;
m_NearClip = nearClip;
m_FarClip = farClip;
m_Position = glm::vec3(0.0);
/*m_Pitch = 0.f;
m_Yaw = 0.f;*/
UpdateProjectionMatrix();
UpdateViewMatrix();
}
glm::vec3 Camera::Forward()
{
return m_Orientation * glm::vec3(0, 0, -1);
}
//glm::vec3 Camera::Forward()
//{
// return glm::rotate(glm::vec3(0.f, 0.f, -1.f), -m_Yaw, glm::vec3(0.f, 1.f, 0.f));
//}
//
//glm::vec3 Camera::Right()
//{
@@ -30,14 +34,20 @@ glm::vec3 Camera::Forward()
// return orientation;
//}
void Camera::SetPosition(glm::vec3 val)
void Camera::AspectRatio(float val)
{
m_AspectRatio = val;
UpdateProjectionMatrix();
}
void Camera::Position(glm::vec3 val)
{
m_Position = val;
UpdateViewMatrix();
}
void Camera::SetOrientation(glm::quat val)
void Camera::Orientation(glm::quat val)
{
m_Orientation = val;
UpdateViewMatrix();
@@ -55,32 +65,35 @@ void Camera::SetOrientation(glm::quat val)
// UpdateViewMatrix();
//}
void Camera::UpdateProjectionMatrix()
{
m_ProjectionMatrix = glm::perspective(
m_FOV,
m_AspectRatio,
m_NearClip,
m_FarClip
);
}
void Camera::UpdateViewMatrix()
{
m_ViewMatrix = glm::toMat4(glm::inverse(m_Orientation)) * glm::translate(-m_Position);
}
void Camera::SetFOV(float val)
void Camera::FOV(float val)
{
m_FOV = val;
UpdateProjectionMatrix();
}
void Camera::SetNearClip(float val)
void Camera::NearClip(float val)
{
m_NearClip = val;
UpdateProjectionMatrix();
}
void Camera::SetFarClip(float val)
void Camera::FarClip(float val)
{
m_FarClip = val;
}
glm::mat4 Camera::ProjectionMatrix(float aspectRatio)
{
return glm::perspective(
m_FOV,
aspectRatio,
m_NearClip,
m_FarClip
);
}
UpdateProjectionMatrix();
}
+19 -7
View File
@@ -1,48 +1,60 @@
#ifndef Camera_h__
#define Camera_h__
//#include "PrecompiledHeader.h"
class Camera
{
public:
Camera(float yFOV, float nearClip, float farClip);
Camera(float yFOV, float aspectRatio, float nearClip, float farClip);
glm::vec3 Forward();
glm::vec3 Right();
float AspectRatio() const { return m_AspectRatio; }
void AspectRatio(float val);
glm::vec3 Position() const { return m_Position; }
void SetPosition(glm::vec3 val);
void Position(glm::vec3 val);
glm::quat Orientation() const { return m_Orientation; }
void SetOrientation(glm::quat val);
void Orientation(glm::quat val);
/*float Pitch() const { return m_Pitch; }
void Pitch(float val);
float Yaw() const { return m_Yaw; }
void Yaw(float val);*/
glm::mat4 ProjectionMatrix(float aspectRatio);
glm::mat4 ProjectionMatrix() const { return m_ProjectionMatrix; }
void ProjectionMatrix(glm::mat4 val) { m_ProjectionMatrix = val; }
glm::mat4 ViewMatrix() const { return m_ViewMatrix; }
void ViewMatrix(glm::mat4 val) { m_ViewMatrix = val; }
float FOV() const { return m_FOV; }
void SetFOV(float val);
void FOV(float val);
float NearClip() const { return m_NearClip; }
void SetNearClip(float val);
void NearClip(float val);
float FarClip() const { return m_FarClip; }
void SetFarClip(float val);
void FarClip(float val);
private:
void UpdateProjectionMatrix();
void UpdateViewMatrix();
float m_FOV;
float m_AspectRatio;
float m_NearClip;
float m_FarClip;
glm::vec3 m_Position;
glm::quat m_Orientation;
//float m_Pitch;
//float m_Yaw;
glm::mat4 m_ProjectionMatrix;
glm::mat4 m_ViewMatrix;
};
-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
-17
View File
@@ -1,17 +0,0 @@
#ifndef Components_Flag_h__
#define Components_Flag_h__
#include "Component.h"
namespace Components
{
struct Flag : Component
{
virtual Flag* Clone() const override { return new Flag(*this); }
};
}
#endif // Components_TankShell_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Components_FrameTimer_h__
#define Components_FrameTimer_h__
#include "Component.h"
namespace Components
{
struct FrameTimer : public Component
{
int Frames;
virtual FrameTimer* Clone() const override { return new FrameTimer(*this); }
};
}
#endif // Components_FrameTimer_h__
-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;
};
}
+1 -25
View File
@@ -9,34 +9,10 @@ namespace Components
struct Physics : Component
{
Physics()
: Mass(1.f), Static(false), Phantom(false), CalculateCenterOfMass(true), CenterOfMass(glm::vec3(0)), InitialLinearVelocity(glm::vec3(0)), InitialAngularVelocity(glm::vec3(0)),
LinearDamping(0.f), AngularDamping(0.05f), GravityFactor(1.f), Friction(0.5f), Restitution(0.4f), MaxLinearVelocity(200.f), MaxAngularVelocity(200.f),
CollisionLayer(0), CollisionSystemGroup(0), CollisionSubSystemId(0), CollisionSubSystemDontCollideWith(0), CollisionEvent(false){}
: Mass(0.f), Static(false){}
float Mass;
bool Static;
bool Phantom;
bool CalculateCenterOfMass;
glm::vec3 CenterOfMass;
glm::vec3 InitialLinearVelocity;
glm::vec3 InitialAngularVelocity;
float LinearDamping;
float AngularDamping;
float GravityFactor;
float Friction;
float Restitution;
float MaxLinearVelocity;
float MaxAngularVelocity;
int CollisionLayer;
int CollisionSystemGroup;
int CollisionSubSystemId;
int CollisionSubSystemDontCollideWith;
bool CollisionEvent;
virtual Physics* Clone() const override { return new Physics(*this); }
};
}
-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 -15
View File
@@ -9,26 +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)
, Radius(5.f)
{ }
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation;
float Radius;
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); }
};
}
-23
View File
@@ -1,23 +0,0 @@
#ifndef Components_TankShell_h__
#define Components_TankShell_h__
#include "Component.h"
namespace Components
{
struct TankShell : Component
{
TankShell()
: Damage(1.0f){ }
float Damage;
float ExplosionRadius;
float ExplosionStrength;
virtual TankShell* Clone() const override { return new TankShell(*this); }
};
}
#endif // Components_TankShell_h__
-17
View File
@@ -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__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Components_Timer_h__
#define Components_Timer_h__
#include "Component.h"
namespace Components
{
struct Timer : public Component
{
double Time;
virtual Timer* Clone() const override { return new Timer(*this); }
};
}
#endif // Components_Timer_h__
-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); }
};
}
-17
View File
@@ -1,17 +0,0 @@
#ifndef Trigger_h__
#define Trigger_h__
#include "Component.h"
namespace Components
{
struct Trigger : Component
{
bool TriggerOnce;
virtual Trigger* Clone() const override { return new Trigger(*this); }
};
}
#endif // Trigger_h__
-22
View File
@@ -1,22 +0,0 @@
#ifndef TriggerExplosion_h__
#define TriggerExplosion_h__
#include "Component.h"
namespace Components
{
struct TriggerExplosion : Component
{
TriggerExplosion()
: MaxVelocity(1.f), Radius(1.f){ }
// Velocity = (1 - (distance / radius)^2) * Strength;
float MaxVelocity;
float Radius; //HACK: Radius should only be in the SphereShapeComponent
virtual TriggerExplosion* Clone() const override { return new TriggerExplosion(*this); }
};
}
#endif // TriggerExplosion_h__
+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__
+8 -46
View File
@@ -1,42 +1,19 @@
#include <string>
#include <sstream>
#include "ResourceManager.h"
#include "OBJ.h"
#include "Model.h"
#include "Texture.h"
#include "EventBroker.h"
#include "RenderQueue.h"
#include "Renderer.h"
#include "InputManager.h"
#include "GUI/Frame.h"
#include "GUI/GameFrame.h"
#include "GameWorld.h"
class Engine
{
public:
Engine(int argc, char* argv[])
{
m_EventBroker = std::make_shared<EventBroker>();
m_ResourceManager = std::make_shared<ResourceManager>();
m_ResourceManager->RegisterType("OBJ", [](std::string resourceName) { return new OBJ(resourceName); });
auto rm = m_ResourceManager;
m_ResourceManager->RegisterType("Model", [rm](std::string resourceName) { return new Model(rm, *rm->Load<OBJ>("OBJ", resourceName)); });
m_ResourceManager->RegisterType("Texture", [](std::string resourceName) { return new Texture(resourceName); });
m_Renderer = std::make_shared<Renderer>(m_ResourceManager);
m_Renderer = std::make_shared<Renderer>();
m_Renderer->Initialize();
m_InputManager = std::make_shared<InputManager>(m_Renderer->GetWindow(), m_EventBroker);
m_FrameStack = new GUI::Frame(m_EventBroker, m_ResourceManager);
m_FrameStack->Width = 1280;
m_FrameStack->Height = 720;
new GUI::GameFrame(m_FrameStack, "GameFrame");
//m_World = std::make_shared<GameWorld>(m_EventBroker, m_ResourceManager);
//m_World->Initialize();
m_World = std::make_shared<GameWorld>(m_Renderer);
m_World->Initialize();
m_LastTime = glfwGetTime();
}
@@ -46,34 +23,19 @@ public:
void Tick()
{
double currentTime = glfwGetTime();
double dt = currentTime - m_LastTime;
double dt = currentTime - m_LastTime;
m_LastTime = currentTime;
// Update input
m_InputManager->Update(dt);
// Update frame stack
m_EventBroker->Process<GUI::Frame>();
m_FrameStack->UpdateLayered(dt);
// Render scene
m_FrameStack->DrawLayered(m_Renderer);
m_Renderer->Swap();
// Swap event queues
m_EventBroker->Clear();
m_World->Update(dt);
m_Renderer->Draw(dt);
glfwPollEvents();
}
private:
std::shared_ptr<ResourceManager> m_ResourceManager;
std::shared_ptr<EventBroker> m_EventBroker;
std::shared_ptr<Renderer> m_Renderer;
std::shared_ptr<InputManager> m_InputManager;
GUI::Frame* m_FrameStack;
// TODO: This should ultimately live in GameFrame
//std::shared_ptr<GameWorld> m_World;
std::shared_ptr<GameWorld> m_World;
double m_LastTime;
};
-68
View File
@@ -1,68 +0,0 @@
#include "PrecompiledHeader.h"
#include "EventBroker.h"
#include "Events/BindKey.h"
BaseEventRelay::~BaseEventRelay()
{
if (m_Broker != nullptr)
{
m_Broker->Unsubscribe(*this);
}
}
void EventBroker::Unsubscribe(BaseEventRelay &relay) // ?
{
auto contextIt = m_ContextRelays.find(relay.m_ContextTypeName);
if (contextIt == m_ContextRelays.end())
return;
auto eventRelays = contextIt->second;
auto itpair = eventRelays.equal_range(relay.m_EventTypeName);
for (auto it = itpair.first; it != itpair.second; ++it)
{
if (it->second == &relay)
{
eventRelays.erase(it);
break;
}
}
}
void EventBroker::Subscribe(BaseEventRelay &relay)
{
relay.m_Broker = this;
m_ContextRelays[relay.m_ContextTypeName].insert(std::make_pair(relay.m_EventTypeName, &relay));
}
int EventBroker::Process(std::string contextTypeName)
{
auto it = m_ContextRelays.find(contextTypeName);
if (it == m_ContextRelays.end())
return 0;
EventRelays_t &relays = it->second;
int eventsProcessed = 0;
for (auto &pair : *m_EventQueueRead)
{
std::string &eventTypeName = pair.first;
std::shared_ptr<Event> event = pair.second;
auto itpair = relays.equal_range(eventTypeName);
for (auto it2 = itpair.first; it2 != itpair.second; ++it2)
{
auto relay = it2->second;
relay->Receive(event);
eventsProcessed++;
}
}
return eventsProcessed;
}
void EventBroker::Clear()
{
std::swap(m_EventQueueRead, m_EventQueueWrite);
m_EventQueueWrite->clear();
}
-149
View File
@@ -1,149 +0,0 @@
#ifndef MessageRelay_h__
#define MessageRelay_h__
#include <typeinfo>
#include <functional>
#include <map>
#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 contextTypeName, std::string eventTypeName)
: m_ContextTypeName(contextTypeName)
, m_EventTypeName(eventTypeName)
, m_Broker(nullptr) { }
~BaseEventRelay();
public:
virtual bool Receive(const std::shared_ptr<Event> event) = 0;
protected:
std::string m_ContextTypeName;
std::string m_EventTypeName;
EventBroker* m_Broker;
};
template <typename ContextType, typename EventType>
class EventRelay : public BaseEventRelay
{
public:
typedef std::function<bool(const EventType&)> CallbackType;
EventRelay()
: m_Callback(nullptr)
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name()) { }
EventRelay(CallbackType callback)
: m_Callback(callback)
, BaseEventRelay(typeid(ContextType).name(), typeid(EventType).name()) { }
protected:
bool Receive(const std::shared_ptr<Event> event) override;
private:
CallbackType m_Callback;
};
template <typename ContextType, typename EventType>
bool EventRelay<ContextType, EventType>::Receive(const std::shared_ptr<Event> event)
{
if (m_Callback != nullptr)
{
return m_Callback(*static_cast<const EventType*>(event.get()));
}
else
{
return false;
}
}
class EventBroker
{
template <typename ContextType, typename EventType> friend class EventRelay;
public:
EventBroker()
{
m_EventQueueRead = std::make_shared<EventQueue_t>();
m_EventQueueWrite = std::make_shared<EventQueue_t>();
}
void Subscribe(BaseEventRelay &relay);
template <typename EventType>
void Publish(const EventType &event);
// Process all events no matter the context.
/*void Process()
{
}*/
/*
Process all events in a given context.
Returns: Number of events processed
*/
template <typename ContextType>
int Process();
int Process(std::string contextTypeName);
void Clear();
void Unsubscribe(BaseEventRelay &relay);
template <typename ContextType>
void UnsubscribeAll();
private:
typedef std::string ContextTypeName_t; // typeid(ContextType).name()
typedef std::string EventTypeName_t; // typeid(EventType).name()
typedef std::unordered_multimap<EventTypeName_t, BaseEventRelay*> EventRelays_t;
typedef std::unordered_map<ContextTypeName_t, EventRelays_t> ContextRelays_t;
ContextRelays_t m_ContextRelays;
typedef std::list<std::pair<EventTypeName_t, std::shared_ptr<Event>>> EventQueue_t;
std::shared_ptr<EventQueue_t> m_EventQueueRead;
std::shared_ptr<EventQueue_t> m_EventQueueWrite;
};
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);
}*/
m_EventQueueWrite->push_back(std::make_pair(typeid(EventType).name(), std::shared_ptr<EventType>(new EventType(event))));
}
template <typename ContextType>
int EventBroker::Process()
{
const std::string contextTypeName = typeid(ContextType).name();
return Process(contextTypeName);
}
template <typename ContextType>
void EventBroker::UnsubscribeAll()
{
const std::string contextTypeName = typeid(ContextType).name();
auto contextIt = m_ContextRelays.find(contextTypeName);
if (contextIt != m_ContextRelays.end())
{
m_ContextRelays.erase(contextIt);
}
}
#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__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_Damage_h__
#define Events_Damage_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct Damage : Event
{
EntityID Entity;
float damage;
};
}
#endif // Events_Damage_h__
-18
View File
@@ -1,18 +0,0 @@
#ifndef Events_DisableCollisions_h__
#define Events_DisableCollisions_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct DisableCollisions : Event
{
int Layer1;
int Layer2;
};
}
#endif // Events_DisableCollisions_h__
-18
View File
@@ -1,18 +0,0 @@
#ifndef Events_EnableCollisions_h__
#define Events_EnableCollisions_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct EnableCollisions : Event
{
int Layer1;
int Layer2;
};
}
#endif // Events_EnableCollisions_h__
-17
View File
@@ -1,17 +0,0 @@
#ifndef Events_EnterTrigger_h__
#define Events_EnterTrigger_h__
#include "Entity.h"
#include "EventBroker.h"
namespace Events
{
struct EnterTrigger : Event
{
EntityID Entity1;
EntityID Entity2;
};
}
#endif // Events_EnterTrigger_h__
-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__
-18
View File
@@ -1,18 +0,0 @@
#ifndef Events_SetViewportCamera_h__
#define Events_SetViewportCamera_h__
#include "EventBroker.h"
#include "Entity.h"
namespace Events
{
struct SetViewportCamera : Event
{
std::string ViewportFrame;
EntityID CameraEntity;
};
}
#endif // Events_SetViewportCamera_h__
-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:
-160
View File
@@ -1,160 +0,0 @@
#ifndef GUI_Frame_h__
#define GUI_Frame_h__
#include <memory>
#include <map>
#include "Util/Rectangle.h"
#include "EventBroker.h"
#include "ResourceManager.h"
#include "Renderer.h"
#include "RenderQueue.h"
#include "Texture.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, std::shared_ptr<::ResourceManager> resourceManager)
: EventBroker(eventBroker)
, ResourceManager(resourceManager)
, Rectangle()
, m_Name("UIParent")
, m_Layer(0)
{ }
// Create a frame as a child
Frame(Frame* parent, std::string name)
: Rectangle(static_cast<Rectangle>(*parent)) // Clone parent rectangle using copy constructor
, m_Name(name)
, m_Layer(0)
{ SetParent(std::shared_ptr<Frame>(parent)); }
::RenderQueue RenderQueue;
std::shared_ptr<Frame> Parent() const { return m_Parent; }
void SetParent(std::shared_ptr<Frame> parent)
{
if (parent == nullptr)
{
LOG_ERROR("Failed to create frame \"%s\": Invalid parent", m_Name.c_str());
return;
}
m_Layer = parent->Layer() + 1;
parent->AddChild(std::shared_ptr<Frame>(this));
m_Parent = parent;
EventBroker = parent->EventBroker;
ResourceManager = parent->ResourceManager;
}
void AddChild(std::shared_ptr<Frame> child)
{
m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child));
if (m_Parent)
{
m_Parent->AddChild(child);
}
}
typedef std::map<std::string, std::shared_ptr<Frame>>::const_iterator FrameChildrenIterator;
std::string Name() const { return m_Name; }
void SetName(std::string val) { m_Name = val; }
int Layer() const { return m_Layer; }
int Left() const override
{
if (m_Parent)
return m_Parent->Left() + X;
else
return X;
}
int Right() const override
{
return Left() + Width;
}
int Top() const override
{
if (m_Parent)
return m_Parent->Top() + Y;
else
return Y;
}
int Bottom() const override
{
return Top() + Height;
}
Rectangle AbsoluteRectangle()
{
return Rectangle(Left(), Top(), Width, Height);
}
void UpdateLayered(double dt)
{
// Update ourselves
this->Update(dt);
// Update children
for (auto &pairLayer : m_Children)
{
auto children = pairLayer.second;
for (auto &pairChild : children)
{
auto child = pairChild.second;
child->Update(dt);
}
}
}
virtual void Update(double dt) { }
void DrawLayered(std::shared_ptr<Renderer> renderer)
{
// Draw ourselves
renderer->SetViewport(AbsoluteRectangle());
this->Draw(renderer);
// Draw children
for (auto &pairLayer : m_Children)
{
auto children = pairLayer.second;
for (auto &pairChild : children)
{
auto child = pairChild.second;
Rectangle rect = child->AbsoluteRectangle();
renderer->SetViewport(rect);
child->Draw(renderer);
}
}
}
virtual void Draw(std::shared_ptr<Renderer> renderer) { }
protected:
std::shared_ptr<::EventBroker> EventBroker;
std::shared_ptr<::ResourceManager> ResourceManager;
std::string m_Name;
int m_Layer;
std::shared_ptr<Frame> m_Parent;
typedef std::multimap<std::string, std::shared_ptr<Frame>> Children_t; // name -> frame
std::map<int, Children_t> m_Children; // layer -> Children_t
};
}
#endif // GUI_Frame_h__
-62
View File
@@ -1,62 +0,0 @@
#ifndef GUI_GameFrame_h__
#define GUI_GameFrame_h__
#include "GUI/Frame.h"
#include "GUI/WorldFrame.h"
#include "GUI/Viewport.h"
#include "GUI/TextureFrame.h"
#include "Events/Damage.h"
#include "GameWorld.h"
namespace GUI
{
class GameFrame : public Frame
{
public:
GameFrame(Frame* parent, std::string name)
: Frame(parent, name)
{
EVENT_SUBSCRIBE_MEMBER(m_EDamage, &GameFrame::OnDamage);
m_World = std::make_shared<GameWorld>(EventBroker, ResourceManager);
auto worldFrame = new WorldFrame(this, "GameWorldFrame", m_World);
{
vp1 = new Viewport(worldFrame, "Viewport1", m_World);
vp1->X = 0;
vp1->Width = 640;
vp2 = new Viewport(worldFrame, "Viewport2", m_World);
vp2->X = vp1->Right();
vp2->Width = 640;
tex = new TextureFrame(vp1, "TextureFrameThingy");
tex->SetTexture("Textures/GUI/hurt.png");
}
m_World->Initialize();
}
void Update(double dt)
{
}
bool OnDamage(const Events::Damage &event)
{
//tex->SetTexture("Textures/GUI/hurt.png");
return false;
}
private:
EventRelay<Frame, Events::Damage> m_EDamage;
std::shared_ptr<GameWorld> m_World;
Viewport* vp1;
Viewport* vp2;
TextureFrame* tex;
};
}
#endif // GUI_GameFrame_h__
-43
View File
@@ -1,43 +0,0 @@
#ifndef GUI_TextureFrame_h__
#define GUI_TextureFrame_h__
#include "GUI/Frame.h"
#include "Texture.h"
namespace GUI
{
class TextureFrame : public Frame
{
public:
TextureFrame(Frame* parent, std::string name)
: Frame(parent, name) { }
void Draw(std::shared_ptr<Renderer> renderer) override
{
if (m_Texture == nullptr)
return;
RenderQueue.Clear();
SpriteJob job;
job.TextureID = m_Texture->ResourceID;
job.Texture = *m_Texture;
RenderQueue.Add(job);
renderer->SetCamera(nullptr);
renderer->DrawFrame(RenderQueue);
}
std::shared_ptr<::Texture> Texture() const { return m_Texture; }
void SetTexture(std::string resourceName)
{
m_Texture = std::shared_ptr<::Texture>(ResourceManager->Load<::Texture>("Texture", resourceName));
}
protected:
std::shared_ptr<::Texture> m_Texture;
};
}
#endif // GUI_TextureFrame_h__
-80
View File
@@ -1,80 +0,0 @@
#ifndef GUI_Viewport_h__
#define GUI_Viewport_h__
#include <memory>
#include "GUI/Frame.h"
#include "World.h"
#include "Systems/TransformSystem.h"
#include "Components/Transform.h"
#include "Components/Camera.h"
#include "RenderQueue.h"
#include "Camera.h"
namespace GUI
{
class Viewport : public Frame
{
public:
Viewport(Frame* parent, std::string name, std::shared_ptr<World> world)
: Frame(parent, name)
, m_World(world)
{ }
EntityID CameraEntity() const { return m_CameraEntity; }
void SetCameraEntity(EntityID cameraEntity)
{
m_CameraEntity = cameraEntity;
auto transformComponent = m_World->GetComponent<Components::Transform>(cameraEntity);
if (!transformComponent)
return;
auto cameraComponent = m_World->GetComponent<Components::Camera>(cameraEntity);
if (!cameraComponent)
return;
m_Camera = std::make_shared<Camera>(cameraComponent->FOV, cameraComponent->NearClip, cameraComponent->FarClip);
}
void Update(double dt) override
{
if (!m_TransformSystem)
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
auto transformComponent = m_World->GetComponent<Components::Transform>(m_CameraEntity);
if (!transformComponent)
return;
auto cameraComponent = m_World->GetComponent<Components::Camera>(m_CameraEntity);
if (!cameraComponent)
return;
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(m_CameraEntity);
m_Camera->SetFOV(cameraComponent->FOV);
m_Camera->SetNearClip(cameraComponent->NearClip);
m_Camera->SetFarClip(cameraComponent->FarClip);
m_Camera->SetPosition(absoluteTransform.Position);
m_Camera->SetOrientation(absoluteTransform.Orientation);
}
void Draw(std::shared_ptr<Renderer> renderer) override
{
if (!m_Camera)
return;
renderer->SetCamera(m_Camera);
renderer->DrawWorld(m_Parent->RenderQueue);
}
private:
std::shared_ptr<World> m_World;
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
std::shared_ptr<Camera> m_Camera;
EntityID m_CameraEntity;
};
}
#endif // GUI_Viewport_h__
-150
View File
@@ -1,150 +0,0 @@
#ifndef GUI_WorldFrame_h__
#define GUI_WorldFrame_h__
#include "GUI/Frame.h"
#include "GUI/Viewport.h"
#include "RenderQueue.h"
#include "World.h"
#include "Systems/TransformSystem.h"
#include "Events/SetViewportCamera.h"
#include "Components/Transform.h"
#include "Components/Model.h"
#include "Components/Sprite.h"
#include "Components/PointLight.h"
namespace GUI
{
class WorldFrame : public Frame
{
public:
WorldFrame(Frame* parent, std::string name, std::shared_ptr<World> world)
: Frame(parent, name)
, m_World(world)
{
EVENT_SUBSCRIBE_MEMBER(m_ESetViewportCamera, &WorldFrame::OnSetViewportCamera);
}
void Update(double dt) override
{
if (!m_TransformSystem)
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>();
m_World->Update(dt);
}
void Draw(std::shared_ptr<Renderer> renderer) override
{
RenderQueue.Clear();
renderer->ClearPointLights();
for (auto &pair : *m_World->GetEntities())
{
EntityID entity = pair.first;
auto transform = m_World->GetComponent<Components::Transform>(entity);
if (!transform)
continue;
auto modelComponent = m_World->GetComponent<Components::Model>(entity);
if (modelComponent)
{
auto modelAsset = ResourceManager->Load<Model>("Model", modelComponent->ModelFile);
if (modelAsset)
{
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
glm::mat4 modelMatrix = glm::translate(glm::mat4(), absoluteTransform.Position)
* glm::toMat4(absoluteTransform.Orientation)
* glm::scale(absoluteTransform.Scale);
EnqueueModel(modelAsset, modelMatrix);
}
}
auto spriteComponent = m_World->GetComponent<Components::Sprite>(entity);
if (spriteComponent)
{
auto textureAsset = ResourceManager->Load<Texture>("Texture", spriteComponent->SpriteFile);
if (textureAsset)
{
Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity);
glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(absoluteTransform.Orientation).z, glm::vec3(0, 0, -1));
glm::mat4 modelMatrix = glm::translate(absoluteTransform.Position)
* glm::toMat4(orientation2D)
* glm::scale(absoluteTransform.Scale);
EnqueueSprite(textureAsset, modelMatrix);
}
}
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity);
if (pointLightComponent)
{
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
renderer->AddPointLightToDraw(
position,
pointLightComponent->Specular,
pointLightComponent->Diffuse,
pointLightComponent->specularExponent,
pointLightComponent->ConstantAttenuation,
pointLightComponent->LinearAttenuation,
pointLightComponent->QuadraticAttenuation,
pointLightComponent->Radius
);
}
}
}
protected:
std::shared_ptr<World> m_World;
private:
EventRelay<Frame, Events::SetViewportCamera> m_ESetViewportCamera;
bool OnSetViewportCamera(const Events::SetViewportCamera &event)
{
// Search next layer for viewports and update cameras
auto itpair = m_Children[m_Layer + 1].equal_range(event.ViewportFrame);
for (auto it = itpair.first; it != itpair.second; ++it)
{
auto viewportFrame = std::dynamic_pointer_cast<GUI::Viewport>(it->second);
if (!viewportFrame)
continue;
viewportFrame->SetCameraEntity(event.CameraEntity);
}
return true;
}
std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
void EnqueueModel(Model* model, glm::mat4 modelMatrix)
{
for (auto texGroup : model->TextureGroups)
{
ModelJob job;
job.TextureID = texGroup.Texture->ResourceID;
job.DiffuseTexture = *texGroup.Texture;
job.NormalTexture = (texGroup.NormalMap) ? *texGroup.NormalMap : 0;
job.SpecularTexture = (texGroup.SpecularMap) ? *texGroup.SpecularMap : 0;
job.VAO = model->VAO;
job.StartIndex = texGroup.StartIndex;
job.EndIndex = texGroup.EndIndex;
job.ModelMatrix = modelMatrix;
RenderQueue.Add(job);
}
}
void EnqueueSprite(Texture* texture, glm::mat4 modelMatrix)
{
SpriteJob job;
job.TextureID = texture->ResourceID;
job.Texture = *texture;
job.ModelMatrix = modelMatrix;
RenderQueue.Add(job);
}
};
}
#endif // GUI_WorldFrame_h__
+205 -1226
View File
File diff suppressed because it is too large Load Diff
+6 -26
View File
@@ -7,53 +7,36 @@
#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"
#include "Systems/TriggerSystem.h"
#include "Systems/TimerSystem.h"
#include "Systems/DamageSystem.h"
#include "Components/Camera.h"
#include "Components/DirectionalLight.h"
#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"
#include "Components/Health.h"
#include "Components/Trigger.h"
#include "Components/Flag.h"
class GameWorld : public World
{
public:
GameWorld(std::shared_ptr<::EventBroker> eventBroker, std::shared_ptr<::ResourceManager> resourceManager)
: World(eventBroker, resourceManager)
{ }
GameWorld(std::shared_ptr<Renderer> renderer)
: m_Renderer(renderer), World() { }
void Initialize();
@@ -64,10 +47,7 @@ public:
void Update(double dt);
private:
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);
std::shared_ptr<Renderer> m_Renderer;
};
#endif // GameWorld_h__
-34
View File
@@ -1,34 +0,0 @@
#ifndef InputController_h__
#define InputController_h__
#include <memory>
#include "EventBroker.h"
#include "Events/InputCommand.h"
#include "Events/MouseMove.h"
template <typename EventContext>
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<EventContext, Events::InputCommand> m_EInputCommand;
EventRelay<EventContext, Events::MouseMove> m_EMouseMove;
};
#endif // InputController_h__
-231
View File
@@ -1,231 +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)
{
EventBroker->Process<InputManager>();
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<InputManager, Events::LockMouse> m_ELockMouse;
bool OnLockMouse(const Events::LockMouse &event);
EventRelay<InputManager, 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 -143
View File
@@ -1,7 +1,7 @@
#include "PrecompiledHeader.h"
#include "Model.h"
Model::Model(std::shared_ptr<ResourceManager> rm, OBJ &obj)
Model::Model(OBJ &obj, ResourceManager* rm)
{
OBJ::MaterialInfo* currentMaterial = nullptr;
TextureGroup* currentTexGroup = nullptr;
@@ -20,26 +20,14 @@ Model::Model(std::shared_ptr<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));
}
else
{
normalMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", "Textures/NeutralNormalMap.png"));
}
// Load specular map
std::shared_ptr<Texture> specularMap = nullptr;
if (!currentMaterial->SpecularMap.FileName.empty())
{
specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", currentMaterial->SpecularMap.FileName));
}
else
{
specularMap = std::shared_ptr<Texture>(rm->Load<Texture>("Texture", "Textures/NeutralSpecularMap.png"));
}
// TODO: Load material parameters
// Create new texture group (start index of new group is upcoming index)
@@ -48,21 +36,6 @@ Model::Model(std::shared_ptr<ResourceManager> rm, OBJ &obj)
currentTexGroup = &TextureGroups.back();
}
/*std::unordered_map<int, glm::vec3> similarNormals;
std::unordered_map<int, int> normalCount;
for (auto &faceDef : face.Definitions)
{
if (faceDef.NormalIndex == 0)
continue;
similarNormals[faceDef.VertexIndex - 1] += normal;
normalCount[faceDef.VertexIndex - 1]++;
int index = pair.first;
glm::vec3 averagedNormal = ;
Normals[]
}*/
// Face definitions
for (auto faceDef : face.Definitions)
{
@@ -92,9 +65,7 @@ Model::Model(std::shared_ptr<ResourceManager> rm, OBJ &obj)
if (Vertices.size() > 0)
{
CreateTangents();
//getSimilarVertexIndex();
CreateBuffers(Vertices, Normals, TangentNormals, BiTangentNormals, TextureCoords);
CreateBuffers(Vertices, Normals, TextureCoords);
}
else
{
@@ -102,7 +73,7 @@ Model::Model(std::shared_ptr<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");
@@ -131,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);
@@ -187,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.001f;
}
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 = Normals[i] + Normals[t];
tempTangent = TangentNormals[i] + TangentNormals[t];
tempBiTangent = 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(std::shared_ptr<ResourceManager> resourceManager, 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__
-93
View File
@@ -1,93 +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;
protected:
uint64_t Hash;
virtual void CalculateHash() = 0;
bool operator<(const RenderJob& rhs)
{
return this->Hash < rhs.Hash;
}
};
struct ModelJob : RenderJob
{
unsigned int ShaderID;
unsigned int TextureID;
GLuint ShaderProgram;
GLuint DiffuseTexture;
GLuint NormalTexture;
GLuint SpecularTexture;
GLuint VAO;
unsigned int StartIndex;
unsigned int EndIndex;
glm::mat4 ModelMatrix;
void CalculateHash() override
{
Hash = TextureID;
}
};
struct SpriteJob : RenderJob
{
unsigned int ShaderID;
unsigned int TextureID;
GLuint ShaderProgram;
GLuint Texture;
glm::mat4 ModelMatrix;
void CalculateHash() override
{
Hash = TextureID;
}
};
class RenderQueue
{
public:
template <typename T>
void Add(T &job)
{
job.CalculateHash();
m_Jobs.push_front(std::shared_ptr<T>(new T(job)));
m_Jobs.sort();
}
void Clear()
{
m_Jobs.clear();
}
std::forward_list<std::shared_ptr<RenderJob>>::const_iterator begin()
{
return m_Jobs.begin();
}
std::forward_list<std::shared_ptr<RenderJob>>::const_iterator end()
{
return m_Jobs.end();
}
private:
std::forward_list<std::shared_ptr<RenderJob>> m_Jobs;
};
#endif // RenderQueue_h__
+426 -742
View File
File diff suppressed because it is too large Load Diff
+25 -89
View File
@@ -13,8 +13,6 @@
#include "Components/PointLight.h"
#include "Skybox.h"
#include "ResourceManager.h"
#include "Util/Rectangle.h"
#include "RenderQueue.h"
class Renderer
{
@@ -23,57 +21,37 @@ 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(std::shared_ptr<::ResourceManager> resourceManager);
Renderer();
void Initialize();
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);
#pragma region NEWSTUFF
void SetViewport(const Rectangle &viewport)
{
m_Viewport = viewport;
}
void SetCamera(std::shared_ptr<Camera> camera)
{
m_Camera = camera;
}
void DrawFrame(RenderQueue &rq);
void DrawWorld(RenderQueue &rq);
void Swap();
#pragma endregion
void AddModelToDraw(Model* model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster);
void AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale);
void AddTextToDraw();
void AddPointLightToDraw(
glm::vec3 _position,
glm::vec3 _specular,
glm::vec3 _diffuse,
float _specularExponent,
float _ConstantAttenuation,
float _LinearAttenuation,
float _QuadraticAttenuation,
float _radius
float _specularExponent
);
void ClearPointLights();
void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding);
void LoadContent();
@@ -91,40 +69,9 @@ public:
void SetSphereModel(Model* _model);
private:
std::shared_ptr<::ResourceManager> ResourceManager;
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;
Rectangle m_Viewport;
std::shared_ptr<Camera> m_Camera;
struct Light
{
glm::vec3 Position;
glm::vec3 Specular;
glm::vec3 Diffuse;
float SpecularExponent;
glm::mat4 SphereModelMatrix;
float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation, Radius;
};
float Gamma;
std::list<Light> Lights;
GLFWwindow* m_Window;
GLint m_glVersion[2];
GLchar* m_glVendor;
@@ -132,7 +79,6 @@ private:
bool m_DrawNormals;
bool m_DrawWireframe;
bool m_DrawBounds;
float CAtt, LAtt, QAtt;
std::shared_ptr<Skybox> m_Skybox;
@@ -140,10 +86,6 @@ private:
glm::vec3 m_SunPosition;
glm::vec3 m_SunTarget;
glm::mat4 m_SunProjection;
glm::vec2 m_SunProjection_width;
glm::vec2 m_SunProjection_height;
glm::vec2 m_SunProjection_length;
GLuint m_DebugAABB;
GLuint m_ShadowFrameBuffer;
@@ -153,26 +95,26 @@ 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;
bool m_QuadView;
std::shared_ptr<Camera> m_Camera;
ShaderProgram m_ShaderProgram;
ShaderProgram m_FirstPassProgram;
ShaderProgram m_FirstPassNormalProgram;
ShaderProgram m_SecondPassProgram;
ShaderProgram m_SecondPassProgram_Debug;
ShaderProgram m_FinalPassProgram;
ShaderProgram m_SunPassProgram;
ShaderProgram m_ForwardRendering;
ShaderProgram m_ShaderProgramNormals;
ShaderProgram m_ShaderProgramShadows;
@@ -185,20 +127,14 @@ private:
void ClearStuff();
void DrawScene();
void DrawModels(ShaderProgram &shader);
void DrawShadowMap(RenderQueue &rq);
void DrawShadowMap();
void CreateShadowMap(int resolution);
void FrameBufferTextures();
void DrawFBO();
void DrawFBO2();
void DrawFBOScene(RenderQueue &rq);
void DrawLightScene(RenderQueue &rq);
void DrawSunLightScene();
void DrawFBOScene();
void DrawLightScene();
void BindFragDataLocation();
glm::mat4 CreateLightMatrix(Light &_light);
void UpdateSunProjection();
void CreateNormalMapTangent();
void ForwardRendering();
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 -38
View File
@@ -155,41 +155,4 @@ void ShaderProgram::Bind()
void ShaderProgram::Unbind()
{
glActiveShaderProgram(0, 0);
}
void ShaderProgram::LoadFromFolder(std::string folderPath)
{
auto path = boost::filesystem::path(folderPath);
if (!boost::filesystem::is_directory(path))
{
LOG_ERROR("Failed to load shader program: \"%s\" is not a directory", folderPath.c_str());
return;
}
for (auto it = boost::filesystem::directory_iterator(path); it != boost::filesystem::directory_iterator(); it++)
{
std::string filename = it->path().filename().string();
if (filename == "Vertex.glsl")
{
AddShader(std::shared_ptr<Shader>(new VertexShader(filename)));
}
else if (filename == "Fragment.glsl")
{
AddShader(std::shared_ptr<Shader>(new FragmentShader(filename)));
}
else if (filename == "Geometry.glsl")
{
AddShader(std::shared_ptr<Shader>(new GeometryShader(filename)));
}
}
}
void ShaderProgram::BindFragDataLocation(int colorNumber, std::string name)
{
if (m_ShaderProgramHandle == 0)
return;
glBindFragDataLocation(m_ShaderProgramHandle, colorNumber, name.c_str());
}
}
+2 -16
View File
@@ -6,11 +6,6 @@
#include <fstream>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include "ResourceManager.h"
class Shader
{
public:
@@ -62,32 +57,23 @@ public:
: ShaderType(fileName) { }
};
class ShaderProgram : public Resource
class ShaderProgram
{
public:
ShaderProgram()
: m_ShaderProgramHandle(0)
{ }
ShaderProgram(std::string folderPath)
: m_ShaderProgramHandle(0)
{ }
: m_ShaderProgramHandle(0) { }
~ShaderProgram();
void AddShader(std::shared_ptr<Shader> shader);
void BindFragDataLocation(int colorNumber, std::string name);
void Compile();
GLuint Link();
GLuint GetHandle();
operator GLuint() const { return m_ShaderProgramHandle; }
void Bind();
void Unbind();
private:
GLuint m_ShaderProgramHandle;
std::vector<std::shared_ptr<Shader>> m_Shaders;
void LoadFromFolder(std::string folderPath);
};
#endif // ShaderProgram_h__
+1 -9
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,12 +17,6 @@ void main()
{
vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord);
vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord);
vec4 ShadowTexel = texture(ShadowTexture, Input.TextureCoord);
//FragmentColor = LightingTexel + vec4(LightingTexel.a, LightingTexel.a, LightingTexel.a, 0.0);
//FragmentColor = DiffuseTexel;
FragmentColor = DiffuseTexel * (vec4(La, 0.0) + vec4(LightingTexel.rgb, 0.0)) + vec4(LightingTexel.a, LightingTexel.a, LightingTexel.a, 0.0);
//FragmentColor = vec4(pow(_FragmentColor.rgb, vec3(1.0 / Gamma)), _FragmentColor.a);
FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel;
}
-18
View File
@@ -1,18 +0,0 @@
#version 430
layout(binding=0) uniform sampler2D texture0;
in VertexData {
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Input;
out vec4 fragmentColor;
void main() {
// Texture
vec4 texel = texture(texture0, Input.TextureCoord);
fragmentColor = texel;
}
-25
View File
@@ -1,25 +0,0 @@
#version 430
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
layout (location = 0) in vec3 Position;
layout (location = 1) in vec3 Normal;
layout (location = 2) in vec2 TextureCoord;
out VertexData {
vec3 Position;
vec3 Normal;
vec2 TextureCoord;
} Output;
void main()
{
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position;
Output.Normal = Normal;
Output.TextureCoord = TextureCoord;
}
+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);
}
+9 -74
View File
@@ -1,96 +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;
//TerrainTextures
layout (binding=4) uniform sampler2D AsphaltTexture;
layout (binding=5) uniform sampler2D GrassTexture;
layout (binding=6) uniform sampler2D SandTexture;
layout (binding=7) uniform sampler2D BlendMap;
uniform float texScale; //Determines how many times the textures will loop over the terrain
uniform vec3 SunDirection_cameraspace;
uniform mat4 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, vec3 normal)
{
return 1.0;
if (Input.ShadowCoord.x < 0.0 || Input.ShadowCoord.x > 1.0 || Input.ShadowCoord.y < 0.0 || Input.ShadowCoord.y > 1.0)
return 0.9;
//Variable bias
vec3 n = normalize(normal);
vec3 l = normalize(SunDirection_cameraspace);
float cosTheta = clamp(dot(n, l), 0.0, 1.0);
float bias = tan(acos(cosTheta));
bias = clamp(bias, 0.0, 0.00003);
//Fixed bias
bias = 0;
if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z + bias)
{
return 0.6;
}
else
{
return 1.0;
}
}
void main()
{
//Fixa så den bara gör detta om modellen har en blend map
//vvvvvv
vec4 Blend = texture2D(BlendMap, Input.TextureCoord.st );
vec4 AsphaltTexel = texture2D(AsphaltTexture, Input.TextureCoord.st * texScale);
vec4 GrassTexel = texture2D(GrassTexture, Input.TextureCoord.st * texScale);
vec4 SandTexel = texture2D(SandTexture, Input.TextureCoord.st * texScale);
//Mix the Terrain-textures together
AsphaltTexel *= Blend.r;
GrassTexel = mix(AsphaltTexel, GrassTexel, Blend.g);
vec4 tex = mix(GrassTexel, SandTexel, Blend.b);
//^^^^^^
//Fixa så den bara gör detta om modellen har en blend map
// Diffuse Texture
frag_Diffuse = 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 = mat3(Input.Tangent, Input.BiTangent, Input.Normal);
frag_Normal = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Diffuse = normalize(vec4(TBN * vec3(texture(NormalMapTexture, Input.TextureCoord)), 0.0));
//frag_Normal = vec4(Input.Normal, 0.0);
// Diffuse Texture
//frag_Diffuse = tex;
frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord) * Shadow(Input.ShadowCoord, vec3(frag_Normal));
//G-buffer Specular
frag_Specular = texture(SpecularMapTexture, Input.TextureCoord);
frag_Normal = vec4(Input.Normal, 0.0);
}
+25 -17
View File
@@ -2,7 +2,6 @@
layout (binding=0) uniform sampler2D PositionTexture;
layout (binding=1) uniform sampler2D NormalsTexture;
layout (binding=2) uniform sampler2D SpecularTexture;
uniform vec2 ViewportSize;
uniform mat4 MVP;
@@ -13,19 +12,15 @@ uniform vec3 la;
uniform vec3 ls;
uniform vec3 ld;
uniform vec3 lp;
uniform float specularExponent;
uniform vec3 CameraPosition;
uniform float ConstantAttenuation;
uniform float LinearAttenuation;
uniform float QuadraticAttenuation;
uniform float LightRadius;
const float specularExponent = 50.0;
uniform vec3 CameraPosition;
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;
in VertexData
{
vec3 Position;
@@ -34,7 +29,7 @@ in VertexData
out vec4 FragColor;
vec4 phong(vec3 position, vec3 normal, vec3 specular)
vec4 phong4(vec3 position, vec3 normal)
{
// Diffuse
vec3 lightPos = vec3(V * vec4(lp, 1.0));
@@ -49,15 +44,30 @@ vec4 phong(vec3 position, vec3 normal, vec3 specular)
vec3 surfaceToViewer = normalize(-position);
vec3 halfWay = normalize(surfaceToViewer + directionToLight);
float dotSpecular = max(dot(halfWay, normal), 0.0);
float specularFactor = pow(dotSpecular, specularExponent);
vec3 Is = specular.r * ls * specularFactor;
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 / (1.0 - 0.0001 * pow(dist, 2));
float attenuation = pow(max(0.0f, 1.0 - (dist / LightRadius)), 2);
//float attenuation = clamp(0.0, 1.0, 1.0 / (0.001 + (0.001 * dist) + (0.001 * dist * dist)));
return vec4((Id) * attenuation, Is.r * attenuation);
//float attenuation = 1.0 / dot(directionToLight, directionToLight);
//float att_s = 5;
//float attenuation = pow(dist, 2) / pow(5.0, 2);
//attenuation = 1.0 / (1.0 + attenuation * att_s);
//att_s = 1.0 / (1.0 + att_s);
//attenuation = attenuation / (1.0 - att_s);
float radius = 5.0;
float alpha = dist / radius;
float dampingFactor = 1.0 - pow(alpha, 3);
return vec4((Id + Is) * attenuation, 1.0);
}
void main()
@@ -65,8 +75,6 @@ void main()
vec2 TextureCoord = gl_FragCoord.xy / ViewportSize;
vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
vec4 SpecularTexel = texture(SpecularTexture, TextureCoord);
FragColor = phong(vec3(PositionTexel), vec3(NormalTexel), vec3(SpecularTexel));
//FragColor = NormalTexel;
FragColor = phong4(vec3(PositionTexel), vec3(NormalTexel));
}
-61
View File
@@ -1,61 +0,0 @@
#version 430
layout (binding=0) uniform sampler2D PositionTexture;
layout (binding=1) uniform sampler2D NormalsTexture;
layout (binding=2) uniform sampler2D SpecularTexture;
uniform vec2 ViewportSize;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform vec3 CameraPosition;
uniform vec3 directionToSun;
const vec3 ks = vec3(1.0, 1.0, 1.0);
const vec3 kd = vec3(1.0, 1.0, 1.0);
const vec3 ka = vec3(1.0, 1.0, 1.0);
const float kshine = 1.0;
const vec3 SunDiffuseLight = vec3(0.3, 0.3, 0.3);
const vec3 SunSpecularLight = vec3(1.0, 1.0, 1.0);
const vec3 SunPos = directionToSun*vec3(100);
const float specularExponent = 5;
in VertexData
{
vec3 Position;
vec2 TextureCoord;
} Input;
out vec4 FragColor;
vec4 phong(vec3 position, vec3 normal, vec3 specular)
{
//Diffuse Sunlight
vec3 directionToLight = normalize(vec3(V * vec4(directionToSun, 0.0)));
float dotProdLight = dot(directionToLight, normal);
dotProdLight = max(dotProdLight, 0.0);
vec3 sId = kd * SunDiffuseLight * dotProdLight;
//Specular Sunlight
vec3 surfaceToViewer = normalize(-position);
vec3 halfWay = normalize(surfaceToViewer + directionToLight);
float dotSpecular = max(dot(halfWay, normal), 0.0);
float specularFactorSun = pow(dotSpecular, specularExponent);
vec3 sIs = specular.r * SunSpecularLight * specularFactorSun;
return vec4((sId), sIs.r);
}
void main()
{
vec2 TextureCoord = gl_FragCoord.xy / ViewportSize;
vec4 PositionTexel = texture(PositionTexture, TextureCoord);
vec4 NormalTexel = texture(NormalsTexture, TextureCoord);
vec4 SpecularTexel = texture(SpecularTexture, TextureCoord);
FragColor = phong(vec3(PositionTexel), vec3(normalize(NormalTexel)), vec3(SpecularTexel));
//FragColor = NormalTexel;
}

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