Revert "Indentation style changed to Horstmann"

This reverts commit f2259f712d.

Conflicts:

	src/GameWorld.cpp
	src/Systems/PhysicsSystem.cpp
This commit is contained in:
2014-04-12 01:48:15 +02:00
parent d7e65ff118
commit 3470a80f40
61 changed files with 697 additions and 354 deletions
+18 -9
View File
@@ -2,7 +2,8 @@
#include "Camera.h" #include "Camera.h"
Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip) Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip)
{ m_FOV = yFOV; {
m_FOV = yFOV;
m_AspectRatio = aspectRatio; m_AspectRatio = aspectRatio;
m_NearClip = nearClip; m_NearClip = nearClip;
m_FarClip = farClip; m_FarClip = farClip;
@@ -34,18 +35,21 @@ Camera::Camera(float yFOV, float aspectRatio, float nearClip, float farClip)
//} //}
void Camera::AspectRatio(float val) void Camera::AspectRatio(float val)
{ m_AspectRatio = val; {
m_AspectRatio = val;
UpdateProjectionMatrix(); UpdateProjectionMatrix();
} }
void Camera::Position(glm::vec3 val) void Camera::Position(glm::vec3 val)
{ m_Position = val; {
m_Position = val;
UpdateViewMatrix(); UpdateViewMatrix();
} }
void Camera::Orientation(glm::quat val) void Camera::Orientation(glm::quat val)
{ m_Orientation = val; {
m_Orientation = val;
UpdateViewMatrix(); UpdateViewMatrix();
} }
@@ -62,7 +66,8 @@ void Camera::Orientation(glm::quat val)
//} //}
void Camera::UpdateProjectionMatrix() void Camera::UpdateProjectionMatrix()
{ m_ProjectionMatrix = glm::perspective( {
m_ProjectionMatrix = glm::perspective(
m_FOV, m_FOV,
m_AspectRatio, m_AspectRatio,
m_NearClip, m_NearClip,
@@ -71,20 +76,24 @@ void Camera::UpdateProjectionMatrix()
} }
void Camera::UpdateViewMatrix() void Camera::UpdateViewMatrix()
{ m_ViewMatrix = glm::translate(glm::toMat4(m_Orientation), -m_Position); {
m_ViewMatrix = glm::translate(glm::toMat4(m_Orientation), -m_Position);
} }
void Camera::FOV(float val) void Camera::FOV(float val)
{ m_FOV = val; {
m_FOV = val;
UpdateProjectionMatrix(); UpdateProjectionMatrix();
} }
void Camera::NearClip(float val) void Camera::NearClip(float val)
{ m_NearClip = val; {
m_NearClip = val;
UpdateProjectionMatrix(); UpdateProjectionMatrix();
} }
void Camera::FarClip(float val) void Camera::FarClip(float val)
{ m_FarClip = val; {
m_FarClip = val;
UpdateProjectionMatrix(); UpdateProjectionMatrix();
} }
+2 -1
View File
@@ -2,7 +2,8 @@
#define Color_h__ #define Color_h__
struct Color struct Color
{ float r; {
float r;
float g; float g;
float b; float b;
}; };
+2 -1
View File
@@ -5,7 +5,8 @@
#include "Entity.h" #include "Entity.h"
struct Component struct Component
{ EntityID Entity; {
EntityID Entity;
}; };
class ComponentFactory : public Factory<Component*> { }; class ComponentFactory : public Factory<Component*> { };
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints // http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints
struct BallSocketConstraint : Component struct BallSocketConstraint : Component
{ // Create constraint between these entities {
// Create constraint between these entities
EntityID EntityA; EntityID EntityA;
EntityID EntityB; EntityID EntityB;
// The pivot point in local coordinates // The pivot point in local coordinates
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct Bounds : Component struct Bounds : Component
{ //Axis Aligned Bounding Box {
//Axis Aligned Bounding Box
glm::vec3 Origin; glm::vec3 Origin;
glm::vec3 VolumeVector; //The vector that defines the volume of the BB, it goes from one corner to the opposite one glm::vec3 VolumeVector; //The vector that defines the volume of the BB, it goes from one corner to the opposite one
}; };
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct BoxShape : Component struct BoxShape : Component
{ float Height; {
float Height;
float Width; float Width;
float Depth; float Depth;
}; };
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct Camera : Component 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 FOV;
float NearClip; float NearClip;
+2 -1
View File
@@ -9,7 +9,8 @@ namespace Components
{ {
struct Collision : Component struct Collision : Component
{ Collision() : Phantom(false), Interested(false) { } {
Collision() : Phantom(false), Interested(false) { }
bool Phantom; bool Phantom;
bool Interested; bool Interested;
+2 -1
View File
@@ -8,7 +8,8 @@ namespace Components
{ {
struct CustomShape : Component struct CustomShape : Component
{ std::string fileName; {
std::string fileName;
}; };
} }
+2 -1
View File
@@ -8,7 +8,8 @@ namespace Components
{ {
struct DirectionalLight : Component struct DirectionalLight : Component
{ float Intensity; {
float Intensity;
float MaxRange; float MaxRange;
float SpecularIntensity; float SpecularIntensity;
Color Color; Color Color;
+2 -1
View File
@@ -6,7 +6,8 @@
namespace Components namespace Components
{ {
struct FreeSteering : Component struct FreeSteering : Component
{ float Speed = 35; {
float Speed = 35;
}; };
} }
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints // http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints
struct HingeConstraint : Component struct HingeConstraint : Component
{ // Create constraint between these entities {
// Create constraint between these entities
EntityID EntityA; EntityID EntityA;
EntityID EntityB; EntityID EntityB;
// The pivot point in local coordinates // The pivot point in local coordinates
+2 -1
View File
@@ -11,7 +11,8 @@ namespace Components
{ {
struct Input : Component struct Input : Component
{ std::array<int, GLFW_KEY_LAST+1> KeyState; {
std::array<int, GLFW_KEY_LAST+1> KeyState;
std::array<int, GLFW_KEY_LAST+1> LastKeyState; 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> MouseState;
std::array<int, GLFW_MOUSE_BUTTON_LAST+1> LastMouseState; std::array<int, GLFW_MOUSE_BUTTON_LAST+1> LastMouseState;
+2 -1
View File
@@ -6,7 +6,8 @@
namespace Components namespace Components
{ {
struct MeshShape : Component struct MeshShape : Component
{ std::string Filename; {
std::string Filename;
}; };
} }
+2 -1
View File
@@ -10,7 +10,8 @@ namespace Components
{ {
struct Model : Component struct Model : Component
{ Model() : Visible(true), ShadowCaster(true) { } {
Model() : Visible(true), ShadowCaster(true) { }
std::string ModelFile; std::string ModelFile;
Color Color; Color Color;
bool Visible; bool Visible;
+2 -1
View File
@@ -9,7 +9,8 @@ namespace Components
{ {
struct ParticleEmitter : Component struct ParticleEmitter : Component
{ int ParticleTemplate; {
int ParticleTemplate;
float SpawnFrequency; float SpawnFrequency;
int SpawnCount; int SpawnCount;
std::vector<Color> ColorSpectrum; std::vector<Color> ColorSpectrum;
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct Physics : Component struct Physics : Component
{ float Mass = 0; {
float Mass = 0;
float Friction = 0; float Friction = 0;
glm::vec3 Gravity = glm::vec3(0, -9.82f, 0); glm::vec3 Gravity = glm::vec3(0, -9.82f, 0);
}; };
+2 -1
View File
@@ -8,7 +8,8 @@ namespace Components
{ {
struct PointLight : Component struct PointLight : Component
{ float Intensity; {
float Intensity;
float MaxRange; float MaxRange;
glm::vec3 Specular; glm::vec3 Specular;
glm::vec3 Diffuse; glm::vec3 Diffuse;
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct PowerUp : Component struct PowerUp : Component
{ float Speed; {
float Speed;
}; };
} }
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints // http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints
struct SliderConstraint : Component struct SliderConstraint : Component
{ // Create constraint between these entities {
// Create constraint between these entities
EntityID EntityA; EntityID EntityA;
EntityID EntityB; EntityID EntityB;
}; };
+2 -1
View File
@@ -9,7 +9,8 @@ namespace Components
{ {
struct SoundEmitter : Component struct SoundEmitter : Component
{ float Gain = 1.f; {
float Gain = 1.f;
float MaxDistance = 1.f; float MaxDistance = 1.f;
float ReferenceDistance = 1.f; float ReferenceDistance = 1.f;
float Pitch = 1.f; float Pitch = 1.f;
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct SphereShape : Component struct SphereShape : Component
{ float Radius; {
float Radius;
float RollingFriction; float RollingFriction;
}; };
+2 -1
View File
@@ -10,7 +10,8 @@ namespace Components
{ {
struct Sprite : Component struct Sprite : Component
{ std::string SpriteFile; {
std::string SpriteFile;
Color Color; Color Color;
}; };
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct Stat : Component struct Stat : Component
{ float Health; {
float Health;
bool Destroyable; bool Destroyable;
}; };
+2 -1
View File
@@ -6,7 +6,8 @@
namespace Components namespace Components
{ {
struct StaticMeshShape : Component struct StaticMeshShape : Component
{ std::string Filename; {
std::string Filename;
}; };
} }
+2 -1
View File
@@ -7,7 +7,8 @@ namespace Components
{ {
struct Transform : Component struct Transform : Component
{ Transform() {
Transform()
: Scale(glm::vec3(1.f)) { } : Scale(glm::vec3(1.f)) { }
glm::vec3 Position; glm::vec3 Position;
+14 -7
View File
@@ -2,7 +2,8 @@
#include "CubemapTexture.h" #include "CubemapTexture.h"
CubemapTexture::CubemapTexture(std::string posXFile, std::string negXFile, std::string posYFile, std::string negYFile, std::string posZFile, std::string negZFile) CubemapTexture::CubemapTexture(std::string posXFile, std::string negXFile, std::string posYFile, std::string negYFile, std::string posZFile, std::string negZFile)
{ m_Loaded = false; {
m_Loaded = false;
m_Texture = 0; m_Texture = 0;
m_TextureFiles[0] = posXFile; m_TextureFiles[0] = posXFile;
m_TextureFiles[1] = negXFile; m_TextureFiles[1] = negXFile;
@@ -13,13 +14,16 @@ CubemapTexture::CubemapTexture(std::string posXFile, std::string negXFile, std::
} }
CubemapTexture::~CubemapTexture() CubemapTexture::~CubemapTexture()
{ if (m_Texture != 0) {
{ //glDeleteTextures(1, &m_Texture); if (m_Texture != 0)
{
//glDeleteTextures(1, &m_Texture);
} }
} }
void CubemapTexture::Load() void CubemapTexture::Load()
{ m_Loaded = true; {
m_Loaded = true;
m_Texture = SOIL_load_OGL_cubemap( m_Texture = SOIL_load_OGL_cubemap(
m_TextureFiles[0].c_str(), m_TextureFiles[0].c_str(),
@@ -33,7 +37,8 @@ void CubemapTexture::Load()
0); 0);
if (m_Texture == 0) if (m_Texture == 0)
{ LOG_ERROR("SOIL cubemap loading error: %s", SOIL_last_result()); {
LOG_ERROR("SOIL cubemap loading error: %s", SOIL_last_result());
return; return;
} }
@@ -45,8 +50,10 @@ void CubemapTexture::Load()
} }
void CubemapTexture::Bind(GLenum textureUnit) void CubemapTexture::Bind(GLenum textureUnit)
{ if (!m_Loaded) {
{ LOG_WARNING("Cubemap \"%s\" was not loaded before being bound! Attempting to load now...", m_TextureFiles[0].c_str()); if (!m_Loaded)
{
LOG_WARNING("Cubemap \"%s\" was not loaded before being bound! Attempting to load now...", m_TextureFiles[0].c_str());
Load(); Load();
} }
+4 -2
View File
@@ -8,7 +8,8 @@ class Engine
{ {
public: public:
Engine(int argc, char* argv[]) Engine(int argc, char* argv[])
{ m_Renderer = std::make_shared<Renderer>(); {
m_Renderer = std::make_shared<Renderer>();
m_Renderer->Initialize(); m_Renderer->Initialize();
m_World = std::make_shared<GameWorld>(m_Renderer); m_World = std::make_shared<GameWorld>(m_Renderer);
@@ -20,7 +21,8 @@ public:
bool Running() const { return !glfwWindowShouldClose(m_Renderer->GetWindow()); } bool Running() const { return !glfwWindowShouldClose(m_Renderer->GetWindow()); }
void Tick() void Tick()
{ double currentTime = glfwGetTime(); {
double currentTime = glfwGetTime();
double dt = currentTime - m_LastTime; double dt = currentTime - m_LastTime;
m_LastTime = currentTime; m_LastTime = currentTime;
+8 -4
View File
@@ -11,16 +11,20 @@ class Factory
{ {
public: 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; {
m_FactoryFunctions[name] = factoryFunction;
} }
T Create(std::string name) T Create(std::string name)
{ auto it = m_FactoryFunctions.find(name); {
auto it = m_FactoryFunctions.find(name);
if (it != m_FactoryFunctions.end()) if (it != m_FactoryFunctions.end())
{ return it->second(); {
return it->second();
} }
else else
{ return nullptr; {
return nullptr;
} }
} }
+20 -11
View File
@@ -2,9 +2,11 @@
#include "GameWorld.h" #include "GameWorld.h"
void GameWorld::Initialize() void GameWorld::Initialize()
{ World::Initialize(); {
World::Initialize();
{ auto camera = CreateEntity(); {
auto camera = CreateEntity();
auto transform = AddComponent<Components::Transform>(camera, "Transform"); auto transform = AddComponent<Components::Transform>(camera, "Transform");
transform->Position.z = 20.f; transform->Position.z = 20.f;
transform->Position.y = 20.f; transform->Position.y = 20.f;
@@ -15,7 +17,8 @@ void GameWorld::Initialize()
auto freeSteering = AddComponent<Components::FreeSteering>(camera, "FreeSteering"); auto freeSteering = AddComponent<Components::FreeSteering>(camera, "FreeSteering");
} }
{ auto terrain = CreateEntity(); {
auto terrain = CreateEntity();
auto transform = AddComponent<Components::Transform>(terrain, "Transform"); auto transform = AddComponent<Components::Transform>(terrain, "Transform");
transform->Position = glm::vec3(0, -5, 0); transform->Position = glm::vec3(0, -5, 0);
transform->Scale = glm::vec3(1000.0f, 1, 1000.0f); transform->Scale = glm::vec3(1000.0f, 1, 1000.0f);
@@ -37,7 +40,8 @@ void GameWorld::Initialize()
for (int i = 0; i < 1; i++) for (int i = 0; i < 1; i++)
{ auto entity = CreateEntity(); {
auto entity = CreateEntity();
auto transform = AddComponent<Components::Transform>(entity, "Transform"); auto transform = AddComponent<Components::Transform>(entity, "Transform");
transform->Scale = glm::vec3(1.0f); transform->Scale = glm::vec3(1.0f);
transform->Position = glm::vec3(0, 10+i, 0); transform->Position = glm::vec3(0, 10+i, 0);
@@ -53,8 +57,8 @@ void GameWorld::Initialize()
box->Depth = 0.5; box->Depth = 0.5;
{ auto entity1 = CreateEntity(); {
auto entity1 = CreateEntity();
auto transform = AddComponent<Components::Transform>(entity1, "Transform"); auto transform = AddComponent<Components::Transform>(entity1, "Transform");
@@ -90,7 +94,8 @@ void GameWorld::Initialize()
} }
{ auto entity = CreateEntity(); {
auto entity = CreateEntity();
AddComponent(entity, "Transform"); AddComponent(entity, "Transform");
auto emitter = AddComponent<Components::SoundEmitter>(entity, "SoundEmitter"); auto emitter = AddComponent<Components::SoundEmitter>(entity, "SoundEmitter");
emitter->Path = "Sounds/korvring.wav"; emitter->Path = "Sounds/korvring.wav";
@@ -102,11 +107,13 @@ void GameWorld::Initialize()
} }
void GameWorld::Update(double dt) void GameWorld::Update(double dt)
{ World::Update(dt); {
World::Update(dt);
} }
void GameWorld::RegisterComponents() void GameWorld::RegisterComponents()
{ m_ComponentFactory.Register("Bounds", []() { return new Components::Bounds(); }); {
m_ComponentFactory.Register("Bounds", []() { return new Components::Bounds(); });
m_ComponentFactory.Register("Camera", []() { return new Components::Camera(); }); m_ComponentFactory.Register("Camera", []() { return new Components::Camera(); });
m_ComponentFactory.Register("Collision", []() { return new Components::Collision(); }); m_ComponentFactory.Register("Collision", []() { return new Components::Collision(); });
m_ComponentFactory.Register("DirectionalLight", []() { return new Components::DirectionalLight(); }); m_ComponentFactory.Register("DirectionalLight", []() { return new Components::DirectionalLight(); });
@@ -134,7 +141,8 @@ void GameWorld::RegisterComponents()
} }
void GameWorld::RegisterSystems() void GameWorld::RegisterSystems()
{ m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this); }); {
m_SystemFactory.Register("TransformSystem", [this]() { return new Systems::TransformSystem(this); });
//m_SystemFactory.Register("LevelGenerationSystem", [this]() { return new Systems::LevelGenerationSystem(this); }); //m_SystemFactory.Register("LevelGenerationSystem", [this]() { return new Systems::LevelGenerationSystem(this); });
m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_Renderer); }); m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_Renderer); });
//m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); });
@@ -151,7 +159,8 @@ void GameWorld::RegisterSystems()
} }
void GameWorld::AddSystems() void GameWorld::AddSystems()
{ AddSystem("TransformSystem"); {
AddSystem("TransformSystem");
//AddSystem("LevelGenerationSystem"); //AddSystem("LevelGenerationSystem");
AddSystem("InputSystem"); AddSystem("InputSystem");
//AddSystem("CollisionSystem"); //AddSystem("CollisionSystem");
+58 -29
View File
@@ -2,22 +2,27 @@
#include "Model.h" #include "Model.h"
Model::Model(const char* path) Model::Model(const char* path)
{ Loadobj(path, Vertices, Normals, TextureCoords); {
Loadobj(path, Vertices, Normals, TextureCoords);
CreateBuffers(Vertices, Normals, TextureCoords); CreateBuffers(Vertices, Normals, TextureCoords);
} }
Model::Model(OBJ &obj) Model::Model(OBJ &obj)
{ OBJ::MaterialInfo* currentMaterial = nullptr; {
OBJ::MaterialInfo* currentMaterial = nullptr;
TextureGroup* currentTexGroup = nullptr; TextureGroup* currentTexGroup = nullptr;
int index = 0; int index = 0;
for (auto face : obj.Faces) for (auto face : obj.Faces)
{ if (face.Material == nullptr) {
{ LOG_ERROR("Missing material for .obj file \"%s\"", obj.Path().string().c_str()); if (face.Material == nullptr)
{
LOG_ERROR("Missing material for .obj file \"%s\"", obj.Path().string().c_str());
return; return;
} }
// New material // New material
if (face.Material != currentMaterial) if (face.Material != currentMaterial)
{ currentMaterial = face.Material; {
currentMaterial = face.Material;
// Load texture // Load texture
std::shared_ptr<Texture> texture = std::make_shared<Texture>(currentMaterial->TextureFile); std::shared_ptr<Texture> texture = std::make_shared<Texture>(currentMaterial->TextureFile);
// TODO: Load material parameters // TODO: Load material parameters
@@ -29,18 +34,21 @@ Model::Model(OBJ &obj)
// Face definitions // Face definitions
for (auto faceDef : face.Definitions) for (auto faceDef : face.Definitions)
{ glm::vec3 vertex; {
glm::vec3 vertex;
std::tie(vertex.x, vertex.y, vertex.z) = obj.Vertices.at(faceDef.VertexIndex - 1); std::tie(vertex.x, vertex.y, vertex.z) = obj.Vertices.at(faceDef.VertexIndex - 1);
Vertices.push_back(vertex); Vertices.push_back(vertex);
if (faceDef.NormalIndex != 0) if (faceDef.NormalIndex != 0)
{ glm::vec3 normal; {
glm::vec3 normal;
std::tie(normal.x, normal.y, normal.z) = obj.Normals.at(faceDef.NormalIndex - 1); std::tie(normal.x, normal.y, normal.z) = obj.Normals.at(faceDef.NormalIndex - 1);
Normals.push_back(normal); Normals.push_back(normal);
} }
if (faceDef.TextureCoordIndex != 0) if (faceDef.TextureCoordIndex != 0)
{ glm::vec2 texCoord; {
glm::vec2 texCoord;
// TODO: W-coord? // TODO: W-coord?
std::tie(texCoord.x, texCoord.y, std::ignore) = obj.TextureCoords.at(faceDef.TextureCoordIndex - 1); std::tie(texCoord.x, texCoord.y, std::ignore) = obj.TextureCoords.at(faceDef.TextureCoordIndex - 1);
TextureCoords.push_back(texCoord); TextureCoords.push_back(texCoord);
@@ -52,12 +60,14 @@ Model::Model(OBJ &obj)
} }
if (Vertices.size() > 0) if (Vertices.size() > 0)
{ CreateBuffers(Vertices, Normals, TextureCoords); {
CreateBuffers(Vertices, Normals, TextureCoords);
} }
} }
bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std::vector <glm::vec3> &out_normals, std::vector <glm::vec2> &out_TextureCoords) bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std::vector <glm::vec3> &out_normals, std::vector <glm::vec2> &out_TextureCoords)
{ std::vector< unsigned int > vertexIndices, TextureCoordIndices, normalIndices; {
std::vector< unsigned int > vertexIndices, TextureCoordIndices, normalIndices;
std::vector< glm::vec3 > temp_vertices; std::vector< glm::vec3 > temp_vertices;
std::vector< glm::vec2 > temp_TextureCoords; std::vector< glm::vec2 > temp_TextureCoords;
std::vector< glm::vec3 > temp_normals; std::vector< glm::vec3 > temp_normals;
@@ -65,7 +75,8 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std
FILE* file = fopen(path, "r"); FILE* file = fopen(path, "r");
LOG_INFO("Loading .obj file"); LOG_INFO("Loading .obj file");
if( file == NULL ) if( file == NULL )
{ LOG_INFO("Load .obj file: failed"); {
LOG_INFO("Load .obj file: failed");
return false; return false;
} }
char lineHeader[512]; char lineHeader[512];
@@ -77,21 +88,25 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std
int res = fscanf(file, "%s", lineHeader); int res = fscanf(file, "%s", lineHeader);
if( res == EOF ) // EOF - End Of File if( res == EOF ) // EOF - End Of File
{ for( unsigned int i = 0; i < vertexIndices.size(); i++ ) {
{ unsigned int vertexIndex = vertexIndices[i]; for( unsigned int i = 0; i < vertexIndices.size(); i++ )
{
unsigned int vertexIndex = vertexIndices[i];
glm::vec3 vertex = temp_vertices[ vertexIndex-1]; glm::vec3 vertex = temp_vertices[ vertexIndex-1];
out_vertices.push_back(vertex); out_vertices.push_back(vertex);
} }
for( unsigned int i = 0; i < TextureCoordIndices.size(); i++ ) for( unsigned int i = 0; i < TextureCoordIndices.size(); i++ )
{ unsigned int TextureCoordIndex = TextureCoordIndices[i]; {
unsigned int TextureCoordIndex = TextureCoordIndices[i];
glm::vec2 TextureCoord = temp_TextureCoords[ TextureCoordIndex-1]; glm::vec2 TextureCoord = temp_TextureCoords[ TextureCoordIndex-1];
out_TextureCoords.push_back(TextureCoord); out_TextureCoords.push_back(TextureCoord);
} }
for( unsigned int i = 0; i < normalIndices.size(); i++ ) for( unsigned int i = 0; i < normalIndices.size(); i++ )
{ unsigned int normalIndex = normalIndices[i]; {
unsigned int normalIndex = normalIndices[i];
glm::vec3 normal = temp_normals[ normalIndex-1]; glm::vec3 normal = temp_normals[ normalIndex-1];
out_normals.push_back(normal); out_normals.push_back(normal);
} }
@@ -102,25 +117,30 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std
} }
if( strcmp( lineHeader, "v" ) == 0 ) // vertex if( strcmp( lineHeader, "v" ) == 0 ) // vertex
{ glm::vec3 vertex; {
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.push_back(vertex); temp_vertices.push_back(vertex);
} }
else if ( strcmp( lineHeader, "vt" ) == 0 ) // texture coordinate else if ( strcmp( lineHeader, "vt" ) == 0 ) // texture coordinate
{ glm::vec2 TextureCoord; {
glm::vec2 TextureCoord;
fscanf(file, "%f %f\n", &TextureCoord.x, &TextureCoord.y ); fscanf(file, "%f %f\n", &TextureCoord.x, &TextureCoord.y );
temp_TextureCoords.push_back(TextureCoord); temp_TextureCoords.push_back(TextureCoord);
} }
else if( strcmp( lineHeader, "vn" ) == 0 ) // normal else if( strcmp( lineHeader, "vn" ) == 0 ) // normal
{ glm::vec3 normal; {
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z ); fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
temp_normals.push_back(normal); temp_normals.push_back(normal);
} }
else if( strcmp( lineHeader, "f" ) == 0) else if( strcmp( lineHeader, "f" ) == 0)
{ unsigned int vertexIndex[3], TextureCoordIndex[3], normalIndex[3]; {
unsigned int vertexIndex[3], TextureCoordIndex[3], normalIndex[3];
int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &TextureCoordIndex[0], &normalIndex[0], &vertexIndex[1], &TextureCoordIndex[1], &normalIndex[1],&vertexIndex[2], &TextureCoordIndex[2], &normalIndex[2]); int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &TextureCoordIndex[0], &normalIndex[0], &vertexIndex[1], &TextureCoordIndex[1], &normalIndex[1],&vertexIndex[2], &TextureCoordIndex[2], &normalIndex[2]);
if(matches != 9) if(matches != 9)
{ printf("File can't be read, try exporting with other options\n"); {
printf("File can't be read, try exporting with other options\n");
return false; return false;
} }
vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[0]);
@@ -144,7 +164,8 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std
FILE* mtlfile = fopen(fileName, "r"); FILE* mtlfile = fopen(fileName, "r");
LOG_INFO("Loading .mtl file"); LOG_INFO("Loading .mtl file");
if( mtlfile == NULL ) if( mtlfile == NULL )
{ LOG_INFO("Load .mtl file: failed"); {
LOG_INFO("Load .mtl file: failed");
return false; return false;
} }
@@ -152,7 +173,8 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std
//read the first word of the line //read the first word of the line
while (true) while (true)
{ int mtlres = fscanf(mtlfile, "%s", mtllineHeader); {
int mtlres = fscanf(mtlfile, "%s", mtllineHeader);
if( mtlres == EOF ) // EOF - End Of File if( mtlres == EOF ) // EOF - End Of File
{ {
@@ -160,7 +182,8 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std
break; break;
} }
else if ( strcmp( mtllineHeader, "map_Kd" ) == 0 ) else if ( strcmp( mtllineHeader, "map_Kd" ) == 0 )
{ char textureFileName[512]; {
char textureFileName[512];
fscanf(mtlfile, "%s", textureFileName); fscanf(mtlfile, "%s", textureFileName);
texture.push_back(std::make_shared<Texture>(textureFileName)); texture.push_back(std::make_shared<Texture>(textureFileName));
LOG_INFO("Texture Loaded\n"); LOG_INFO("Texture Loaded\n");
@@ -182,35 +205,41 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
LOG_INFO("Generating VertexBuffer"); LOG_INFO("Generating VertexBuffer");
glGenBuffers(1, &VertexBuffer); glGenBuffers(1, &VertexBuffer);
if (vertices.size() > 0) if (vertices.size() > 0)
{ glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer); {
glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, VertexBuffer"); GLERROR("GLEW: BufferFail, VertexBuffer");
} }
else else
{ LOG_WARNING("Created empty vertex buffer!"); {
LOG_WARNING("Created empty vertex buffer!");
} }
LOG_INFO("Generating NormalBuffer"); LOG_INFO("Generating NormalBuffer");
glGenBuffers(1, &NormalBuffer); glGenBuffers(1, &NormalBuffer);
if (normals.size() > 0) if (normals.size() > 0)
{ glBindBuffer(GL_ARRAY_BUFFER, NormalBuffer); {
glBindBuffer(GL_ARRAY_BUFFER, NormalBuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, NormalBuffer"); GLERROR("GLEW: BufferFail, NormalBuffer");
} }
else else
{ LOG_WARNING("Created empty normal buffer!"); {
LOG_WARNING("Created empty normal buffer!");
} }
LOG_INFO("Generating textureCoordBuffer"); LOG_INFO("Generating textureCoordBuffer");
glGenBuffers(1, &TextureCoordBuffer); glGenBuffers(1, &TextureCoordBuffer);
if (textureCoords.size() > 0) if (textureCoords.size() > 0)
{ glBindBuffer(GL_ARRAY_BUFFER, TextureCoordBuffer); {
glBindBuffer(GL_ARRAY_BUFFER, TextureCoordBuffer);
glBufferData(GL_ARRAY_BUFFER, textureCoords.size() * sizeof(glm::vec2), &textureCoords[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, textureCoords.size() * sizeof(glm::vec2), &textureCoords[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, TextureCoordBuffer"); GLERROR("GLEW: BufferFail, TextureCoordBuffer");
} }
else else
{ LOG_WARNING("Created empty texture coordinate buffer!"); {
LOG_WARNING("Created empty texture coordinate buffer!");
} }
glGenVertexArrays(1, &VAO); glGenVertexArrays(1, &VAO);
+2 -1
View File
@@ -20,7 +20,8 @@ public:
Model(const char* path); Model(const char* path);
struct TextureGroup struct TextureGroup
{ std::shared_ptr<Texture> Texture; {
std::shared_ptr<Texture> Texture;
unsigned int StartIndex; unsigned int StartIndex;
unsigned int EndIndex; unsigned int EndIndex;
}; };
+60 -30
View File
@@ -2,12 +2,14 @@
#include "OBJ.h" #include "OBJ.h"
bool OBJ::LoadFromFile(std::string filename) bool OBJ::LoadFromFile(std::string filename)
{ m_Path = boost::filesystem::path(filename); {
m_Path = boost::filesystem::path(filename);
// http://paulbourke.net/dataformats/obj/ // http://paulbourke.net/dataformats/obj/
std::ifstream file(m_Path.string()); std::ifstream file(m_Path.string());
if (!file.is_open()) if (!file.is_open())
{ LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str()); {
LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str());
return false; return false;
} }
@@ -15,7 +17,8 @@ bool OBJ::LoadFromFile(std::string filename)
std::string line; std::string line;
while (std::getline(file, line)) while (std::getline(file, line))
{ if (line.length() == 0) {
if (line.length() == 0)
continue; continue;
std::stringstream ss(line); std::stringstream ss(line);
@@ -29,7 +32,8 @@ bool OBJ::LoadFromFile(std::string filename)
// Material files // Material files
if (prefix == "mtllib") if (prefix == "mtllib")
{ std::string materialFilename; {
std::string materialFilename;
ss >> materialFilename; ss >> materialFilename;
m_MaterialPath = m_Path.branch_path() / materialFilename; m_MaterialPath = m_Path.branch_path() / materialFilename;
ParseMaterial(); ParseMaterial();
@@ -38,7 +42,8 @@ bool OBJ::LoadFromFile(std::string filename)
// Material statement // Material statement
if (prefix == "usemtl") if (prefix == "usemtl")
{ std::string material; {
std::string material;
ss >> material; ss >> material;
m_CurrentMaterial = &Materials[material]; m_CurrentMaterial = &Materials[material];
continue; continue;
@@ -46,7 +51,8 @@ bool OBJ::LoadFromFile(std::string filename)
// Vertices // Vertices
if (prefix == "v") if (prefix == "v")
{ float x, y, z; {
float x, y, z;
ss >> x >> y >> z; ss >> x >> y >> z;
Vertices.push_back(std::make_tuple(x, y, z)); Vertices.push_back(std::make_tuple(x, y, z));
continue; continue;
@@ -54,26 +60,30 @@ bool OBJ::LoadFromFile(std::string filename)
// Normals // Normals
if (prefix == "vn") if (prefix == "vn")
{ float x, y, z; {
float x, y, z;
ss >> x >> y >> z; ss >> x >> y >> z;
Normals.push_back(std::make_tuple(x, y, z)); Normals.push_back(std::make_tuple(x, y, z));
} }
// Texture coordinates // Texture coordinates
if (prefix == "vt") if (prefix == "vt")
{ float u, v, w; {
float u, v, w;
ss >> u >> v >> w; ss >> u >> v >> w;
TextureCoords.push_back(std::make_tuple(u, v, w)); TextureCoords.push_back(std::make_tuple(u, v, w));
} }
// Face definitions // Face definitions
if (prefix == "f") if (prefix == "f")
{ Face face; {
Face face;
face.Material = m_CurrentMaterial; face.Material = m_CurrentMaterial;
std::string faceDefString; std::string faceDefString;
while (ss >> faceDefString) while (ss >> faceDefString)
{ std::stringstream ss2(faceDefString); {
std::stringstream ss2(faceDefString);
FaceDefinition faceDef = { 0, 0, 0 }; FaceDefinition faceDef = { 0, 0, 0 };
ss2 >> faceDef.VertexIndex; ss2 >> faceDef.VertexIndex;
@@ -82,11 +92,13 @@ bool OBJ::LoadFromFile(std::string filename)
continue; continue;
if (ss2.peek() == '/') if (ss2.peek() == '/')
{ ss2.ignore(); {
ss2.ignore();
ss2 >> faceDef.NormalIndex; ss2 >> faceDef.NormalIndex;
} }
else else
{ ss2 >> faceDef.TextureCoordIndex; {
ss2 >> faceDef.TextureCoordIndex;
ss2.ignore(); ss2.ignore();
ss2 >> faceDef.NormalIndex; ss2 >> faceDef.NormalIndex;
} }
@@ -100,10 +112,12 @@ bool OBJ::LoadFromFile(std::string filename)
} }
void OBJ::ParseMaterial() void OBJ::ParseMaterial()
{ // http://paulbourke.net/dataformats/mtl/ {
// http://paulbourke.net/dataformats/mtl/
std::ifstream file(m_MaterialPath.string()); std::ifstream file(m_MaterialPath.string());
if (!file.is_open()) if (!file.is_open())
{ LOG_ERROR("Failed to open .mtl \"%s\"", m_MaterialPath.string().c_str()); {
LOG_ERROR("Failed to open .mtl \"%s\"", m_MaterialPath.string().c_str());
return; return;
} }
@@ -114,7 +128,8 @@ void OBJ::ParseMaterial()
std::string line; std::string line;
while (std::getline(file, line)) while (std::getline(file, line))
{ if (line.length() == 0) {
if (line.length() == 0)
continue; continue;
std::stringstream ss(line); std::stringstream ss(line);
@@ -124,8 +139,10 @@ void OBJ::ParseMaterial()
// Create a new material definition // Create a new material definition
if (prefix == "newmtl") if (prefix == "newmtl")
{ MaterialInfo mat = {
{ "", MaterialInfo mat =
{
"",
std::make_tuple(0.2f, 0.2f, 0.2f), std::make_tuple(0.2f, 0.2f, 0.2f),
std::make_tuple(0.8f, 0.8f, 0.8f), std::make_tuple(0.8f, 0.8f, 0.8f),
std::make_tuple(1.0f, 1.0f, 1.0f), std::make_tuple(1.0f, 1.0f, 1.0f),
@@ -148,44 +165,52 @@ void OBJ::ParseMaterial()
// Ambient color // Ambient color
if (prefix == "Ka") if (prefix == "Ka")
{ float r, g, b; {
float r, g, b;
ss >> r >> g >> b; ss >> r >> g >> b;
currentMaterial->AmbientColor = std::make_tuple(r, g, b); currentMaterial->AmbientColor = std::make_tuple(r, g, b);
continue; continue;
} }
// Diffuse color // Diffuse color
if (prefix == "Kd") if (prefix == "Kd")
{ float r, g, b; {
float r, g, b;
ss >> r >> g >> b; ss >> r >> g >> b;
currentMaterial->DiffuseColor = std::make_tuple(r, g, b); currentMaterial->DiffuseColor = std::make_tuple(r, g, b);
continue; continue;
} }
// Specular color // Specular color
if (prefix == "Ks") if (prefix == "Ks")
{ float r, g, b; {
float r, g, b;
ss >> r >> g >> b; ss >> r >> g >> b;
currentMaterial->SpecularColor = std::make_tuple(r, g, b); currentMaterial->SpecularColor = std::make_tuple(r, g, b);
continue; continue;
} }
// Transmission filter // Transmission filter
if (prefix == "Tf") if (prefix == "Tf")
{ std::stringstream ss2; {
std::stringstream ss2;
ss2 << ss.str(); ss2 << ss.str();
std::string command; std::string command;
ss2 >> command; ss2 >> command;
if (command == "xyz") if (command == "xyz")
{ // TODO: "The "Ks xyz" statement specifies the specular reflectivity using CIEXYZ values." {
// TODO: "The "Ks xyz" statement specifies the specular reflectivity using CIEXYZ values."
} }
else if (command == "spectral") else if (command == "spectral")
{ // TODO: "The "Tf spectral" statement specifies the transmission filter using a spectral curve." {
// TODO: "The "Tf spectral" statement specifies the transmission filter using a spectral curve."
} }
else else
{ float r, g, b; {
float r, g, b;
ss >> r; ss >> r;
// G and B are optional // G and B are optional
if (!(ss >> g >> b)) if (!(ss >> g >> b))
{ g = r; {
g = r;
b = r; b = r;
} }
currentMaterial->TransmissionFilter = std::make_tuple(r, g, b); currentMaterial->TransmissionFilter = std::make_tuple(r, g, b);
@@ -194,22 +219,26 @@ void OBJ::ParseMaterial()
} }
// Optical density // Optical density
if (prefix == "Ni") if (prefix == "Ni")
{ ss >> currentMaterial->OpticalDensity; {
ss >> currentMaterial->OpticalDensity;
continue; continue;
} }
// Alpha // Alpha
if (prefix == "d" || prefix == "Tr") if (prefix == "d" || prefix == "Tr")
{ ss >> currentMaterial->Alpha; {
ss >> currentMaterial->Alpha;
continue; continue;
} }
// Shininess // Shininess
if (prefix == "Ns") if (prefix == "Ns")
{ ss >> currentMaterial->Shininess; {
ss >> currentMaterial->Shininess;
continue; continue;
} }
// Illumination model // Illumination model
if (prefix == "illum") if (prefix == "illum")
{ int illum = 0; {
int illum = 0;
ss >> illum; ss >> illum;
currentMaterial->IlluminationModel = illum; currentMaterial->IlluminationModel = illum;
continue; continue;
@@ -217,7 +246,8 @@ void OBJ::ParseMaterial()
// Texture file // Texture file
// TODO: // TODO:
if (prefix == "map_Ka" || prefix == "map_Kd") if (prefix == "map_Ka" || prefix == "map_Kd")
{ std::string textureFile; {
std::string textureFile;
ss >> textureFile; ss >> textureFile;
currentMaterial->TextureFile = (m_MaterialPath.branch_path() / textureFile).string(); currentMaterial->TextureFile = (m_MaterialPath.branch_path() / textureFile).string();
continue; continue;
+6 -3
View File
@@ -15,7 +15,8 @@ class OBJ
{ {
public: public:
struct MaterialInfo struct MaterialInfo
{ std::string TextureFile; {
std::string TextureFile;
std::tuple<float, float, float> AmbientColor; std::tuple<float, float, float> AmbientColor;
std::tuple<float, float, float> DiffuseColor; std::tuple<float, float, float> DiffuseColor;
std::tuple<float, float, float> SpecularColor; std::tuple<float, float, float> SpecularColor;
@@ -27,13 +28,15 @@ public:
}; };
struct FaceDefinition struct FaceDefinition
{ int VertexIndex; {
int VertexIndex;
int TextureCoordIndex; int TextureCoordIndex;
int NormalIndex; int NormalIndex;
}; };
struct Face struct Face
{ Face() : Material(nullptr) { } {
Face() : Material(nullptr) { }
std::vector<FaceDefinition> Definitions; std::vector<FaceDefinition> Definitions;
MaterialInfo* Material; MaterialInfo* Material;
}; };
+70 -35
View File
@@ -2,7 +2,8 @@
#include "Renderer.h" #include "Renderer.h"
Renderer::Renderer() Renderer::Renderer()
{ m_VSync = false; {
m_VSync = false;
#ifdef DEBUG #ifdef DEBUG
m_DrawNormals = false; m_DrawNormals = false;
m_DrawWireframe = false; m_DrawWireframe = false;
@@ -21,9 +22,11 @@ Renderer::Renderer()
} }
void Renderer::Initialize() void Renderer::Initialize()
{ // Initialize GLFW {
// Initialize GLFW
if (!glfwInit()) if (!glfwInit())
{ LOG_ERROR("GLFW: Initialization failed"); {
LOG_ERROR("GLFW: Initialization failed");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -34,7 +37,8 @@ void Renderer::Initialize()
//glfwWindowHint(GLFW_SAMPLES, 16); //glfwWindowHint(GLFW_SAMPLES, 16);
m_Window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr); m_Window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr);
if (!m_Window) if (!m_Window)
{ LOG_ERROR("GLFW: Failed to create window"); {
LOG_ERROR("GLFW: Failed to create window");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
glfwMakeContextCurrent(m_Window); glfwMakeContextCurrent(m_Window);
@@ -53,7 +57,8 @@ void Renderer::Initialize()
// Initialize GLEW // Initialize GLEW
if (glewInit() != GLEW_OK) if (glewInit() != GLEW_OK)
{ LOG_ERROR("GLEW: Initialization failed"); {
LOG_ERROR("GLEW: Initialization failed");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -70,7 +75,8 @@ void Renderer::Initialize()
} }
void Renderer::LoadContent() void Renderer::LoadContent()
{ auto standardVS = std::shared_ptr<Shader>(new VertexShader("Shaders/Vertex.glsl")); {
auto standardVS = std::shared_ptr<Shader>(new VertexShader("Shaders/Vertex.glsl"));
auto standardFS = std::shared_ptr<Shader>(new FragmentShader("Shaders/Fragment.glsl")); auto standardFS = std::shared_ptr<Shader>(new FragmentShader("Shaders/Fragment.glsl"));
m_ShaderProgram.AddShader(standardVS); m_ShaderProgram.AddShader(standardVS);
@@ -112,7 +118,8 @@ void Renderer::LoadContent()
} }
void Renderer::CreateShadowMap(int resolution) void Renderer::CreateShadowMap(int resolution)
{ glGenFramebuffers(1, &m_ShadowFrameBuffer); {
glGenFramebuffers(1, &m_ShadowFrameBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer);
// Depth texture // Depth texture
@@ -131,12 +138,14 @@ void Renderer::CreateShadowMap(int resolution)
glDrawBuffer(GL_NONE); glDrawBuffer(GL_NONE);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{ LOG_ERROR("Framebuffer incomplete!"); {
LOG_ERROR("Framebuffer incomplete!");
return; return;
} }
} }
void Renderer::Draw(double dt) void Renderer::Draw(double dt)
{ glDisable(GL_BLEND); {
glDisable(GL_BLEND);
DrawSkybox(); DrawSkybox();
DrawShadowMap(); DrawShadowMap();
@@ -145,11 +154,13 @@ void Renderer::Draw(double dt)
#ifdef DEBUG #ifdef DEBUG
// Draw bounding boxes // Draw bounding boxes
if (m_DrawBounds) if (m_DrawBounds)
{ glEnable(GL_BLEND); {
glEnable(GL_BLEND);
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
m_ShaderProgramDebugAABB.Bind(); m_ShaderProgramDebugAABB.Bind();
for (auto tuple : AABBsToRender) for (auto tuple : AABBsToRender)
{ glm::mat4 modelMatrix; {
glm::mat4 modelMatrix;
bool colliding; bool colliding;
std::tie(modelMatrix, colliding) = tuple; std::tie(modelMatrix, colliding) = tuple;
// Model matrix // Model matrix
@@ -174,7 +185,8 @@ void Renderer::Draw(double dt)
} }
void Renderer::DrawSkybox() void Renderer::DrawSkybox()
{ glBindFramebuffer(GL_FRAMEBUFFER, 0); {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, WIDTH, HEIGHT); glViewport(0, 0, WIDTH, HEIGHT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -186,7 +198,8 @@ void Renderer::DrawSkybox()
} }
void Renderer::DrawScene() void Renderer::DrawScene()
{ glBindFramebuffer(GL_FRAMEBUFFER, 0); {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, WIDTH, HEIGHT); glViewport(0, 0, WIDTH, HEIGHT);
glClear(GL_DEPTH_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT);
@@ -220,7 +233,8 @@ void Renderer::DrawScene()
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights, Light_quadraticAttenuation.data()); glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights, Light_quadraticAttenuation.data());
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights, Light_spotExponent.data()); glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights, Light_spotExponent.data());
if (m_DrawWireframe) if (m_DrawWireframe)
{ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} }
glActiveTexture(GL_TEXTURE1); glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture); glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture);
@@ -230,7 +244,8 @@ void Renderer::DrawScene()
glm::mat4 MVP; glm::mat4 MVP;
glm::mat4 depthMVP; glm::mat4 depthMVP;
for (auto tuple : ModelsToRender) for (auto tuple : ModelsToRender)
{ Model* model; {
Model* model;
glm::mat4 modelMatrix; glm::mat4 modelMatrix;
bool visible; bool visible;
std::tie(model, modelMatrix, visible, std::ignore) = tuple; std::tie(model, modelMatrix, visible, std::ignore) = tuple;
@@ -245,7 +260,8 @@ void Renderer::DrawScene()
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "view"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "view"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glBindVertexArray(model->VAO); glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups) for (auto texGroup : model->TextureGroups)
{ glActiveTexture(GL_TEXTURE0); {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texGroup.Texture); glBindTexture(GL_TEXTURE_2D, *texGroup.Texture);
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
} }
@@ -254,7 +270,8 @@ void Renderer::DrawScene()
#ifdef DEBUG #ifdef DEBUG
// Debug draw model normals // Debug draw model normals
if (m_DrawNormals) if (m_DrawNormals)
{ m_ShaderProgramNormals.Bind(); {
m_ShaderProgramNormals.Bind();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
DrawModels(m_ShaderProgramNormals); DrawModels(m_ShaderProgramNormals);
} }
@@ -262,7 +279,8 @@ void Renderer::DrawScene()
} }
void Renderer::DrawShadowMap() void Renderer::DrawShadowMap()
{ glEnable(GL_DEPTH_TEST); {
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE); glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT); glCullFace(GL_FRONT);
@@ -283,7 +301,8 @@ void Renderer::DrawShadowMap()
m_ShaderProgramShadows.Bind(); m_ShaderProgramShadows.Bind();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
for (auto tuple : ModelsToRender) for (auto tuple : ModelsToRender)
{ Model* model; {
Model* model;
glm::mat4 modelMatrix; glm::mat4 modelMatrix;
bool shadow; bool shadow;
std::tie(model, modelMatrix, std::ignore, shadow) = tuple; std::tie(model, modelMatrix, std::ignore, shadow) = tuple;
@@ -295,13 +314,15 @@ void Renderer::DrawShadowMap()
glBindVertexArray(model->VAO); glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups) for (auto texGroup : model->TextureGroups)
{ glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); {
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
} }
} }
} }
void Renderer::DrawDebugShadowMap() void Renderer::DrawDebugShadowMap()
{ glBindFramebuffer(GL_FRAMEBUFFER, 0); {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, 400, 400); glViewport(0, 0, 400, 400);
glClear(GL_DEPTH_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT);
@@ -315,7 +336,8 @@ void Renderer::DrawDebugShadowMap()
} }
void Renderer::DrawModels(ShaderProgram &shader) void Renderer::DrawModels(ShaderProgram &shader)
{ /*glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); {
/*glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix();
glm::mat4 MVP; glm::mat4 MVP;
for (auto tuple : ModelsToRender) for (auto tuple : ModelsToRender)
@@ -338,15 +360,18 @@ void Renderer::DrawModels(ShaderProgram &shader)
} }
void Renderer::DrawText() void Renderer::DrawText()
{ //DrawShitInTextForm {
//DrawShitInTextForm
} }
void Renderer::AddTextToDraw() void Renderer::AddTextToDraw()
{ //Add to draw shit vector {
//Add to draw shit vector
} }
void Renderer::AddModelToDraw(std::shared_ptr<Model> model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster) void Renderer::AddModelToDraw(std::shared_ptr<Model> model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster)
{ glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale); {
glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale);
// You can now use ModelMatrix to build the MVP matrix // You can now use ModelMatrix to build the MVP matrix
ModelsToRender.push_back(std::make_tuple(model.get(), modelMatrix, visible, shadowCaster)); ModelsToRender.push_back(std::make_tuple(model.get(), modelMatrix, visible, shadowCaster));
} }
@@ -360,7 +385,8 @@ void Renderer::AddPointLightToDraw(
float _quadraticAttenuation, float _quadraticAttenuation,
float _spotExponent float _spotExponent
) )
{ Light_position.push_back(_position.x); {
Light_position.push_back(_position.x);
Light_position.push_back(_position.y); Light_position.push_back(_position.y);
Light_position.push_back(_position.z); Light_position.push_back(_position.z);
Light_specular.push_back(_specular.x); Light_specular.push_back(_specular.x);
@@ -377,15 +403,18 @@ void Renderer::AddPointLightToDraw(
} }
void Renderer::AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding) void Renderer::AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding)
{ glm::mat4 model; {
glm::mat4 model;
model *= glm::translate(origin); model *= glm::translate(origin);
model *= glm::scale(volumeVector); model *= glm::scale(volumeVector);
AABBsToRender.push_back(std::make_tuple(model, colliding)); AABBsToRender.push_back(std::make_tuple(model, colliding));
} }
GLuint Renderer::CreateQuad() GLuint Renderer::CreateQuad()
{ float quadVertices[] = {
{ -1.0f, -1.0f, 0.0f, float quadVertices[] =
{
-1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f,
@@ -394,7 +423,8 @@ GLuint Renderer::CreateQuad()
1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
}; };
float quadTexCoords[] = float quadTexCoords[] =
{ 0.0f, 0.0f, {
0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
@@ -424,8 +454,10 @@ GLuint Renderer::CreateQuad()
} }
GLuint Renderer::CreateAABB() GLuint Renderer::CreateAABB()
{ float vertices[] = {
{ // Bottom float vertices[] =
{
// Bottom
-1.0f, -1.0f, 1.0f, // 0 -1.0f, -1.0f, 1.0f, // 0
1.0f, -1.0f, 1.0f, // 1 1.0f, -1.0f, 1.0f, // 1
1.0f, -1.0f, 1.0f, // 1 1.0f, -1.0f, 1.0f, // 1
@@ -474,8 +506,10 @@ GLuint Renderer::CreateAABB()
} }
GLuint Renderer::CreateSkybox() GLuint Renderer::CreateSkybox()
{ glm::vec3 skyBoxVertices[] = {
{ glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3( 1.0f, -1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, -1.0f), glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3 skyBoxVertices[] =
{
glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3( 1.0f, -1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, -1.0f), glm::vec3( 1.0f, -1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, 1.0f),
glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3( 1.0f, 1.0f, -1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3(-1.0f, 1.0f, -1.0f), glm::vec3( 1.0f, 1.0f, -1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3( 1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, 1.0f), glm::vec3(-1.0f, 1.0f, -1.0f),
glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3( 1.0f, -1.0f, 1.0f), glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3(-1.0f, -1.0f, 1.0f), glm::vec3( 1.0f, -1.0f, 1.0f), glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3( 1.0f, -1.0f, -1.0f), glm::vec3(-1.0f, -1.0f, -1.0f), glm::vec3(-1.0f, -1.0f, 1.0f),
@@ -499,7 +533,8 @@ GLuint Renderer::CreateSkybox()
return vao; return vao;
} }
void Renderer::ClearStuff() void Renderer::ClearStuff()
{ AABBsToRender.clear(); {
AABBsToRender.clear();
ModelsToRender.clear(); ModelsToRender.clear();
Light_position.clear(); Light_position.clear();
Light_specular.clear(); Light_specular.clear();
+46 -23
View File
@@ -2,12 +2,14 @@
#include "ShaderProgram.h" #include "ShaderProgram.h"
GLuint Shader::CompileShader(GLenum shaderType, std::string fileName) GLuint Shader::CompileShader(GLenum shaderType, std::string fileName)
{ LOG_INFO("Compiling shader \"%s\"", fileName.c_str()); {
LOG_INFO("Compiling shader \"%s\"", fileName.c_str());
std::string shaderFile; std::string shaderFile;
std::ifstream in(fileName, std::ios::in); std::ifstream in(fileName, std::ios::in);
if (!in) if (!in)
{ LOG_ERROR("Error: Failed to open shader file \"%s\"", fileName.c_str()); {
LOG_ERROR("Error: Failed to open shader file \"%s\"", fileName.c_str());
return 0; return 0;
} }
in.seekg(0, std::ios::end); in.seekg(0, std::ios::end);
@@ -31,7 +33,8 @@ GLuint Shader::CompileShader(GLenum shaderType, std::string fileName)
GLint compileStatus; GLint compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus); glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
if(compileStatus != GL_TRUE) if(compileStatus != GL_TRUE)
{ LOG_ERROR("Shader compilation failed"); {
LOG_ERROR("Shader compilation failed");
GLsizei infoLogLength; GLsizei infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar* infolog = new GLchar[infoLogLength]; GLchar* infolog = new GLchar[infoLogLength];
@@ -47,64 +50,81 @@ GLuint Shader::CompileShader(GLenum shaderType, std::string fileName)
} }
Shader::Shader(GLenum shaderType, std::string fileName) : m_ShaderType(shaderType), m_FileName(fileName) Shader::Shader(GLenum shaderType, std::string fileName) : m_ShaderType(shaderType), m_FileName(fileName)
{ m_ShaderHandle = 0; {
m_ShaderHandle = 0;
} }
Shader::~Shader() Shader::~Shader()
{ if (m_ShaderHandle != 0) {
{ glDeleteShader(m_ShaderHandle); if (m_ShaderHandle != 0)
{
glDeleteShader(m_ShaderHandle);
} }
} }
GLuint Shader::Compile() GLuint Shader::Compile()
{ m_ShaderHandle = CompileShader(m_ShaderType, m_FileName); {
m_ShaderHandle = CompileShader(m_ShaderType, m_FileName);
return m_ShaderHandle; return m_ShaderHandle;
} }
GLenum Shader::GetType() const GLenum Shader::GetType() const
{ return m_ShaderType; {
return m_ShaderType;
} }
std::string Shader::GetFileName() const std::string Shader::GetFileName() const
{ return m_FileName; {
return m_FileName;
} }
GLuint Shader::GetHandle() const GLuint Shader::GetHandle() const
{ return m_ShaderHandle; {
return m_ShaderHandle;
} }
bool Shader::IsCompiled() const bool Shader::IsCompiled() const
{ return m_ShaderHandle != 0; {
return m_ShaderHandle != 0;
} }
ShaderProgram::~ShaderProgram() ShaderProgram::~ShaderProgram()
{ if (m_ShaderProgramHandle != 0) {
{ glDeleteProgram(m_ShaderProgramHandle); if (m_ShaderProgramHandle != 0)
{
glDeleteProgram(m_ShaderProgramHandle);
} }
} }
void ShaderProgram::AddShader(std::shared_ptr<Shader> shader) void ShaderProgram::AddShader(std::shared_ptr<Shader> shader)
{ m_Shaders.push_back(shader); {
m_Shaders.push_back(shader);
} }
void ShaderProgram::Compile() void ShaderProgram::Compile()
{ for (auto &shader : m_Shaders) {
{ if (!shader->IsCompiled()) for (auto &shader : m_Shaders)
{ shader->Compile(); {
if (!shader->IsCompiled())
{
shader->Compile();
} }
} }
} }
GLuint ShaderProgram::Link() GLuint ShaderProgram::Link()
{ if (m_Shaders.size() == 0) {
{ LOG_ERROR("Failed to link shader program: No shaders bound"); if (m_Shaders.size() == 0)
{
LOG_ERROR("Failed to link shader program: No shaders bound");
return 0; return 0;
} }
LOG_INFO("Linking shader program"); LOG_INFO("Linking shader program");
m_ShaderProgramHandle = glCreateProgram(); m_ShaderProgramHandle = glCreateProgram();
for (auto &shader : m_Shaders) for (auto &shader : m_Shaders)
{ glAttachShader(m_ShaderProgramHandle, shader->GetHandle()); {
glAttachShader(m_ShaderProgramHandle, shader->GetHandle());
} }
glLinkProgram(m_ShaderProgramHandle); glLinkProgram(m_ShaderProgramHandle);
if (GLERROR("glLinkProgram")) if (GLERROR("glLinkProgram"))
@@ -115,16 +135,19 @@ GLuint ShaderProgram::Link()
} }
GLuint ShaderProgram::GetHandle() GLuint ShaderProgram::GetHandle()
{ return m_ShaderProgramHandle; {
return m_ShaderProgramHandle;
} }
void ShaderProgram::Bind() void ShaderProgram::Bind()
{ if (m_ShaderProgramHandle == 0) {
if (m_ShaderProgramHandle == 0)
return; return;
glUseProgram(m_ShaderProgramHandle); glUseProgram(m_ShaderProgramHandle);
} }
void ShaderProgram::Unbind() void ShaderProgram::Unbind()
{ glActiveShaderProgram(0, 0); {
glActiveShaderProgram(0, 0);
} }
+4 -2
View File
@@ -3,7 +3,8 @@
uniform vec4 Color; uniform vec4 Color;
in VertexData in VertexData
{ vec3 Position; {
vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
vec3 ShadowCoord; vec3 ShadowCoord;
@@ -12,6 +13,7 @@ in VertexData
out vec4 FragmentColor; out vec4 FragmentColor;
void main() void main()
{ //FragmentColor = vec4(1.0 - gl_Color.r, 1.0 - gl_Color.g, 1.0 - gl_Color.b, 0.0); {
//FragmentColor = vec4(1.0 - gl_Color.r, 1.0 - gl_Color.g, 1.0 - gl_Color.b, 0.0);
FragmentColor = Color; FragmentColor = Color;
} }
+8 -4
View File
@@ -17,7 +17,8 @@ uniform float quadraticAttenuation[maxNumberOfLights];
uniform float spotExponent[maxNumberOfLights]; uniform float spotExponent[maxNumberOfLights];
in VertexData in VertexData
{ vec3 Position; {
vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
vec3 ShadowCoord; vec3 ShadowCoord;
@@ -52,10 +53,12 @@ void main()
//bias = clamp(bias, 0.0, 0.01); //bias = clamp(bias, 0.0, 0.01);
float visibility = 1.0; float visibility = 1.0;
if (Input.ShadowCoord.x >= 0.0 && Input.ShadowCoord.x <= 1.0 && Input.ShadowCoord.y >= 0.0 && Input.ShadowCoord.y <= 1.0) if (Input.ShadowCoord.x >= 0.0 && Input.ShadowCoord.x <= 1.0 && Input.ShadowCoord.y >= 0.0 && Input.ShadowCoord.y <= 1.0)
{ float bias = 0.00005; {
float bias = 0.00005;
vec4 shadowMapValue = texture(shadowMap, Input.ShadowCoord.xy); vec4 shadowMapValue = texture(shadowMap, Input.ShadowCoord.xy);
if (shadowMapValue.z < clamp(Input.ShadowCoord.z - bias, 0, 1)) if (shadowMapValue.z < clamp(Input.ShadowCoord.z - bias, 0, 1))
{ visibility = 0.3; {
visibility = 0.3;
} }
} }
@@ -64,7 +67,8 @@ void main()
float attenuation; float attenuation;
for(int i = 0; i < numberOfLights && i < maxNumberOfLights; i++) for(int i = 0; i < numberOfLights && i < maxNumberOfLights; i++)
{ // Light {
// Light
//vec3 lightPosition = vec3(0, 0, 2); //vec3 lightPosition = vec3(0, 0, 2);
vec3 Ls = specular[i]; // Specular light vec3 Ls = specular[i]; // Specular light
vec3 Ld = diffuse[i]; // Diffuse light vec3 Ld = diffuse[i]; // Diffuse light
+2 -1
View File
@@ -5,5 +5,6 @@ uniform mat4 MVP;
out vec4 FragmentColor; out vec4 FragmentColor;
void main() void main()
{ FragmentColor = vec4(1.0, 1.0, 1.0, 1.0); {
FragmentColor = vec4(1.0, 1.0, 1.0, 1.0);
} }
+8 -4
View File
@@ -6,20 +6,24 @@ layout(triangles) in;
layout(line_strip, max_vertices = 6) out; layout(line_strip, max_vertices = 6) out;
in VertexData in VertexData
{ vec3 Position; {
vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
} Input[3]; } Input[3];
out VertexData out VertexData
{ vec3 Position; {
vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
} Output; } Output;
void main() void main()
{ for (int i = 0; i < gl_in.length(); i++) {
{ gl_Position = MVP * vec4(Input[i].Position, 1.0); for (int i = 0; i < gl_in.length(); i++)
{
gl_Position = MVP * vec4(Input[i].Position, 1.0);
EmitVertex(); EmitVertex();
gl_Position = MVP * vec4(Input[i].Position + Input[i].Normal, 1.0); gl_Position = MVP * vec4(Input[i].Position + Input[i].Normal, 1.0);
EmitVertex(); EmitVertex();
+2 -1
View File
@@ -5,5 +5,6 @@ uniform mat4 MVP;
layout(location = 0) out float FragmentDepth; layout(location = 0) out float FragmentDepth;
void main() void main()
{ FragmentDepth = gl_FragCoord.z; {
FragmentDepth = gl_FragCoord.z;
} }
+4 -2
View File
@@ -7,13 +7,15 @@ layout(location = 1) in vec3 Normal;
layout(location = 2) in vec2 TextureCoord; layout(location = 2) in vec2 TextureCoord;
out VertexData out VertexData
{ vec3 Position; {
vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
} Output; } Output;
void main() void main()
{ gl_Position = MVP * vec4(Position, 1.0); {
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position; Output.Position = Position;
Output.Normal = Normal; Output.Normal = Normal;
+4 -2
View File
@@ -3,12 +3,14 @@
uniform samplerCube CubemapTexture; uniform samplerCube CubemapTexture;
in VertexData in VertexData
{ vec3 TextureCoord; {
vec3 TextureCoord;
} Input; } Input;
out vec4 FragColor; out vec4 FragColor;
void main() void main()
{ FragColor = texture(CubemapTexture, Input.TextureCoord); {
FragColor = texture(CubemapTexture, Input.TextureCoord);
//FragColor = vec4(1.0, 1.0, 1.0, 0.0); //FragColor = vec4(1.0, 1.0, 1.0, 0.0);
} }
+4 -2
View File
@@ -5,10 +5,12 @@ uniform mat4 MVP;
layout(location = 0) in vec3 Position; layout(location = 0) in vec3 Position;
out VertexData out VertexData
{ vec3 TextureCoord; {
vec3 TextureCoord;
} Output; } Output;
void main() void main()
{ gl_Position = MVP * vec4(Position, 1.0); {
gl_Position = MVP * vec4(Position, 1.0);
Output.TextureCoord = Position; Output.TextureCoord = Position;
} }
+4 -2
View File
@@ -8,14 +8,16 @@ layout(location = 1) in vec3 Normal;
layout(location = 2) in vec2 TextureCoord; layout(location = 2) in vec2 TextureCoord;
out VertexData out VertexData
{ vec3 Position; {
vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
vec3 ShadowCoord; vec3 ShadowCoord;
} Output; } Output;
void main() void main()
{ gl_Position = MVP * vec4(Position, 1.0); {
gl_Position = MVP * vec4(Position, 1.0);
Output.Position = Position; Output.Position = Position;
Output.Normal = Normal; Output.Normal = Normal;
+6 -3
View File
@@ -3,20 +3,23 @@
layout(binding = 0) uniform sampler2D DepthTexture; layout(binding = 0) uniform sampler2D DepthTexture;
in VertexData in VertexData
{ vec3 Position; {
vec3 Position;
vec2 TextureCoord; vec2 TextureCoord;
} Input; } Input;
out vec4 FragmentColor; out vec4 FragmentColor;
float LinearizeDepth(float z) float LinearizeDepth(float z)
{ float n = 0.1; // camera z near {
float n = 0.1; // camera z near
float f = 800.0; // camera z far float f = 800.0; // camera z far
return (2.0 * n) / (f + n - z * (f - n)); return (2.0 * n) / (f + n - z * (f - n));
} }
void main() void main()
{ float z = texture(DepthTexture, Input.TextureCoord).x; {
float z = texture(DepthTexture, Input.TextureCoord).x;
vec4 color = vec4(z, z, z, 0); vec4 color = vec4(z, z, z, 0);
FragmentColor = color; FragmentColor = color;
+4 -2
View File
@@ -4,12 +4,14 @@ layout(location = 0) in vec3 Position;
layout(location = 2) in vec2 TextureCoord; layout(location = 2) in vec2 TextureCoord;
out VertexData out VertexData
{ vec3 Position; {
vec3 Position;
vec2 TextureCoord; vec2 TextureCoord;
} Output; } Output;
void main() void main()
{ gl_Position = vec4(Position, 1.0); {
gl_Position = vec4(Position, 1.0);
Output.Position = Position; Output.Position = Position;
Output.TextureCoord = TextureCoord; Output.TextureCoord = TextureCoord;
+10 -5
View File
@@ -2,7 +2,8 @@
#include "Skybox.h" #include "Skybox.h"
Skybox::Skybox(std::string skyboxPath, std::string extension /* = "png" */) Skybox::Skybox(std::string skyboxPath, std::string extension /* = "png" */)
{ m_Cubemap = std::make_shared<CubemapTexture>( {
m_Cubemap = std::make_shared<CubemapTexture>(
skyboxPath + "/right." + extension, skyboxPath + "/right." + extension,
skyboxPath + "/left." + extension, skyboxPath + "/left." + extension,
skyboxPath + "/top." + extension, skyboxPath + "/top." + extension,
@@ -14,8 +15,10 @@ Skybox::Skybox(std::string skyboxPath, std::string extension /* = "png" */)
} }
void Skybox::Initialize() void Skybox::Initialize()
{ float cubeVertices[] = {
{ -1.0f, -1.0f, -1.0f, float cubeVertices[] =
{
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f,
@@ -28,7 +31,8 @@ void Skybox::Initialize()
//std::copy(cubeVertices, cubeVertices + (3*8 - 1), m_CubeVertices); //std::copy(cubeVertices, cubeVertices + (3*8 - 1), m_CubeVertices);
unsigned int cubeIndices[] = unsigned int cubeIndices[] =
{ // Back {
// Back
0, 2, 3, 0, 2, 3,
0, 1, 2, 0, 1, 2,
@@ -78,7 +82,8 @@ Skybox::~Skybox()
} }
void Skybox::Draw() void Skybox::Draw()
{ m_Cubemap->Bind(GL_TEXTURE0); {
m_Cubemap->Bind(GL_TEXTURE0);
glBindVertexArray(vao); glBindVertexArray(vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
+22 -11
View File
@@ -13,42 +13,53 @@ void Systems::FreeSteeringSystem::Update(double dt)
} }
void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{ auto steering = m_World->GetComponent<Components::FreeSteering>(entity, "FreeSteering"); {
auto steering = m_World->GetComponent<Components::FreeSteering>(entity, "FreeSteering");
auto input = m_World->GetComponent<Components::Input>(entity, "Input"); auto input = m_World->GetComponent<Components::Input>(entity, "Input");
if (steering && input) if (steering && input)
{ auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform");
glm::vec3 Camera_Right = glm::vec3(glm::vec4(1, 0, 0, 0) * transform->Orientation); glm::vec3 Camera_Right = glm::vec3(glm::vec4(1, 0, 0, 0) * transform->Orientation);
glm::vec3 Camera_Forward = glm::vec3(glm::vec4(0, 0, 1, 0) * transform->Orientation); glm::vec3 Camera_Forward = glm::vec3(glm::vec4(0, 0, 1, 0) * transform->Orientation);
float speed = steering->Speed; float speed = steering->Speed;
if (input->KeyState[GLFW_KEY_LEFT_SHIFT]) if (input->KeyState[GLFW_KEY_LEFT_SHIFT])
{ speed *= 4.0f; {
speed *= 4.0f;
} }
if (input->KeyState[GLFW_KEY_LEFT_ALT]) if (input->KeyState[GLFW_KEY_LEFT_ALT])
{ speed /= 4.0f; {
speed /= 4.0f;
} }
if (input->KeyState[GLFW_KEY_A]) if (input->KeyState[GLFW_KEY_A])
{ transform->Position -= Camera_Right * (float)dt * speed; {
transform->Position -= Camera_Right * (float)dt * speed;
} }
else if (input->KeyState[GLFW_KEY_D]) else if (input->KeyState[GLFW_KEY_D])
{ transform->Position += Camera_Right * (float)dt * speed; {
transform->Position += Camera_Right * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_W]) if (input->KeyState[GLFW_KEY_W])
{ transform->Position -= Camera_Forward * (float)dt * speed; {
transform->Position -= Camera_Forward * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_S]) if (input->KeyState[GLFW_KEY_S])
{ transform->Position += Camera_Forward * (float)dt * speed; {
transform->Position += Camera_Forward * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_SPACE]) if (input->KeyState[GLFW_KEY_SPACE])
{ transform->Position += glm::vec3(0, 1, 0) * (float)dt * speed; {
transform->Position += glm::vec3(0, 1, 0) * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_LEFT_CONTROL]) if (input->KeyState[GLFW_KEY_LEFT_CONTROL])
{ transform->Position -= glm::vec3(0, 1, 0) * (float)dt * speed; {
transform->Position -= glm::vec3(0, 1, 0) * (float)dt * speed;
} }
if (input->MouseState[GLFW_MOUSE_BUTTON_LEFT]) if (input->MouseState[GLFW_MOUSE_BUTTON_LEFT])
{ // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3 {
// TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3
//--------------------------------------------------------------------- //---------------------------------------------------------------------
transform->Orientation = glm::angleAxis<float>(input->dY / 300.f, glm::vec3(1, 0, 0)) * transform->Orientation; transform->Orientation = glm::angleAxis<float>(input->dY / 300.f, glm::vec3(1, 0, 0)) * transform->Orientation;
+20 -10
View File
@@ -3,17 +3,20 @@
#include "World.h" #include "World.h"
void Systems::InputSystem::Update(double dt) void Systems::InputSystem::Update(double dt)
{ m_LastKeyState = m_CurrentKeyState; {
m_LastKeyState = m_CurrentKeyState;
m_LastMouseState = m_CurrentMouseState; m_LastMouseState = m_CurrentMouseState;
// Keyboard input // Keyboard input
for (int i = 0; i <= GLFW_KEY_LAST; ++i) for (int i = 0; i <= GLFW_KEY_LAST; ++i)
{ m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i); {
m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i);
} }
// Mouse buttons // Mouse buttons
for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i) for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i)
{ m_CurrentMouseState[i] = glfwGetMouseButton(m_Renderer->GetWindow(), i); {
m_CurrentMouseState[i] = glfwGetMouseButton(m_Renderer->GetWindow(), i);
} }
// Cursor position // Cursor position
@@ -26,36 +29,43 @@ void Systems::InputSystem::Update(double dt)
// Lock mouse while holding LMB // Lock mouse while holding LMB
if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT]) if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT])
{ m_LastMouseX = m_Renderer->WIDTH / 2.f; // xpos; {
m_LastMouseX = m_Renderer->WIDTH / 2.f; // xpos;
m_LastMouseY = m_Renderer->HEIGHT / 2.f; // ypos; m_LastMouseY = m_Renderer->HEIGHT / 2.f; // ypos;
glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY); glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY);
} }
// Hide/show cursor with LMB // Hide/show cursor with LMB
if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
{ glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); {
glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
} }
if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
{ glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); {
glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
} }
#ifdef DEBUG #ifdef DEBUG
// Wireframe // Wireframe
if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1]) if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1])
{ m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe()); {
m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe());
} }
// Normals // Normals
if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2]) if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2])
{ m_Renderer->DrawNormals(!m_Renderer->DrawNormals()); {
m_Renderer->DrawNormals(!m_Renderer->DrawNormals());
} }
// Bounds // Bounds
if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3]) if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3])
{ m_Renderer->DrawBounds(!m_Renderer->DrawBounds()); {
m_Renderer->DrawBounds(!m_Renderer->DrawBounds());
} }
#endif #endif
} }
void Systems::InputSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) void Systems::InputSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{ auto input = m_World->GetComponent<Components::Input>(entity, "Input"); {
auto input = m_World->GetComponent<Components::Input>(entity, "Input");
if (input == nullptr) if (input == nullptr)
return; return;
+66 -33
View File
@@ -5,7 +5,8 @@
Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world)
{ m_Broadphase = new btDbvtBroadphase(); {
m_Broadphase = new btDbvtBroadphase();
m_CollisionConfiguration = new btDefaultCollisionConfiguration(); m_CollisionConfiguration = new btDefaultCollisionConfiguration();
m_Dispatcher = new btCollisionDispatcher(m_CollisionConfiguration); m_Dispatcher = new btCollisionDispatcher(m_CollisionConfiguration);
m_Solver = new btSequentialImpulseConstraintSolver(); m_Solver = new btSequentialImpulseConstraintSolver();
@@ -16,16 +17,19 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world)
} }
void Systems::PhysicsSystem::Update(double dt) void Systems::PhysicsSystem::Update(double dt)
{ // Update entity transform in physics world {
// Update entity transform in physics world
for (auto pair : *m_World->GetEntities()) for (auto pair : *m_World->GetEntities())
{ EntityID entity = pair.first; {
EntityID entity = pair.first;
EntityID parent = pair.second; EntityID parent = pair.second;
if (parent != 0) if (parent != 0)
continue; continue;
if (m_PhysicsData.find(entity) != m_PhysicsData.end()) if (m_PhysicsData.find(entity) != m_PhysicsData.end())
{ PhysicsData* physicsData = &m_PhysicsData[entity]; {
PhysicsData* physicsData = &m_PhysicsData[entity];
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
btTransform transform; btTransform transform;
@@ -47,7 +51,8 @@ void Systems::PhysicsSystem::Update(double dt)
} }
void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{ auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent) if (!transformComponent)
return; return;
@@ -60,8 +65,10 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
auto wheelComponent = m_World->GetComponent<Components::Wheel>(entity, "Wheel"); auto wheelComponent = m_World->GetComponent<Components::Wheel>(entity, "Wheel");
if (physicsComponent || sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent) if (physicsComponent || sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent)
{ if (m_PhysicsData.find(entity) == m_PhysicsData.end()) {
{ SetUpPhysicsState(entity, parent); if (m_PhysicsData.find(entity) == m_PhysicsData.end())
{
SetUpPhysicsState(entity, parent);
} }
if (parent != 0) if (parent != 0)
@@ -80,8 +87,10 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
transformComponent->Orientation.w = transform.getRotation().w(); transformComponent->Orientation.w = transform.getRotation().w();
} }
else else
{ if (m_PhysicsData.find(entity) != m_PhysicsData.end()) {
{ TearDownPhysicsState(entity, parent); if (m_PhysicsData.find(entity) != m_PhysicsData.end())
{
TearDownPhysicsState(entity, parent);
} }
} }
@@ -90,12 +99,15 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
auto hingeComponent = m_World->GetComponent<Components::HingeConstraint>(entity, "HingeConstraint"); auto hingeComponent = m_World->GetComponent<Components::HingeConstraint>(entity, "HingeConstraint");
if (ballSocketComponent) if (ballSocketComponent)
{ EntityID entityA = ballSocketComponent->EntityA; {
EntityID entityA = ballSocketComponent->EntityA;
EntityID entityB = ballSocketComponent->EntityB; EntityID entityB = ballSocketComponent->EntityB;
if (m_Constraints.find(std::make_pair(entityA, entityB)) == m_Constraints.end()) if (m_Constraints.find(std::make_pair(entityA, entityB)) == m_Constraints.end())
{ if (m_PhysicsData.find(entityA) != m_PhysicsData.end() && m_PhysicsData.find(entityB) != m_PhysicsData.end()) {
{ btVector3 pivotA = btVector3(ballSocketComponent->PivotA.x, ballSocketComponent->PivotA.y, ballSocketComponent->PivotA.z); if (m_PhysicsData.find(entityA) != m_PhysicsData.end() && m_PhysicsData.find(entityB) != m_PhysicsData.end())
{
btVector3 pivotA = btVector3(ballSocketComponent->PivotA.x, ballSocketComponent->PivotA.y, ballSocketComponent->PivotA.z);
btVector3 pivotB = btVector3(ballSocketComponent->PivotB.x, ballSocketComponent->PivotB.y, ballSocketComponent->PivotB.z); btVector3 pivotB = btVector3(ballSocketComponent->PivotB.x, ballSocketComponent->PivotB.y, ballSocketComponent->PivotB.z);
m_Constraints[std::make_pair(entityA, entityB)] = new btPoint2PointConstraint(*m_PhysicsData[entityA].RigidBody, *m_PhysicsData[entityB].RigidBody, pivotA, pivotB); m_Constraints[std::make_pair(entityA, entityB)] = new btPoint2PointConstraint(*m_PhysicsData[entityA].RigidBody, *m_PhysicsData[entityB].RigidBody, pivotA, pivotB);
@@ -105,12 +117,15 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
} }
} }
else if (sliderComponent) else if (sliderComponent)
{ EntityID entityA = sliderComponent->EntityA; {
EntityID entityA = sliderComponent->EntityA;
EntityID entityB = sliderComponent->EntityB; EntityID entityB = sliderComponent->EntityB;
if (m_Constraints.find(std::make_pair(entityA, entityB)) == m_Constraints.end()) if (m_Constraints.find(std::make_pair(entityA, entityB)) == m_Constraints.end())
{ if (m_PhysicsData.find(entityA) != m_PhysicsData.end() && m_PhysicsData.find(entityB) != m_PhysicsData.end()) {
{ btTransform transformA; if (m_PhysicsData.find(entityA) != m_PhysicsData.end() && m_PhysicsData.find(entityB) != m_PhysicsData.end())
{
btTransform transformA;
m_PhysicsData[entityA].MotionState->getWorldTransform(transformA); m_PhysicsData[entityA].MotionState->getWorldTransform(transformA);
btTransform transformB; btTransform transformB;
m_PhysicsData[entityB].MotionState->getWorldTransform(transformB); m_PhysicsData[entityB].MotionState->getWorldTransform(transformB);
@@ -121,12 +136,15 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
} }
} }
else if (hingeComponent) else if (hingeComponent)
{ EntityID entityA = hingeComponent->EntityA; {
EntityID entityA = hingeComponent->EntityA;
EntityID entityB = hingeComponent->EntityB; EntityID entityB = hingeComponent->EntityB;
if (m_Constraints.find(std::make_pair(entityA, entityB)) == m_Constraints.end()) if (m_Constraints.find(std::make_pair(entityA, entityB)) == m_Constraints.end())
{ if (m_PhysicsData.find(entityA) != m_PhysicsData.end() && m_PhysicsData.find(entityB) != m_PhysicsData.end()) {
{ btVector3 PivotA = btVector3(hingeComponent->PivotA.x, hingeComponent->PivotA.y, hingeComponent->PivotA.z); if (m_PhysicsData.find(entityA) != m_PhysicsData.end() && m_PhysicsData.find(entityB) != m_PhysicsData.end())
{
btVector3 PivotA = btVector3(hingeComponent->PivotA.x, hingeComponent->PivotA.y, hingeComponent->PivotA.z);
btVector3 PivotB = btVector3(hingeComponent->PivotB.x, hingeComponent->PivotB.y, hingeComponent->PivotB.z); btVector3 PivotB = btVector3(hingeComponent->PivotB.x, hingeComponent->PivotB.y, hingeComponent->PivotB.z);
btVector3 AxisA = btVector3(hingeComponent->AxisA.x, hingeComponent->AxisA.y, hingeComponent->AxisA.z); btVector3 AxisA = btVector3(hingeComponent->AxisA.x, hingeComponent->AxisA.y, hingeComponent->AxisA.z);
@@ -214,9 +232,11 @@ void Systems::PhysicsSystem::OnComponentRemoved(std::string type, Component* com
} }
void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
{ auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent) if (!transformComponent)
{ LOG_WARNING("Physics component missing transform component on entity %i", entity); {
LOG_WARNING("Physics component missing transform component on entity %i", entity);
return; return;
} }
@@ -228,7 +248,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
auto staticMeshShapeComponent = m_World->GetComponent<Components::StaticMeshShape>(entity, "StaticMeshShape"); auto staticMeshShapeComponent = m_World->GetComponent<Components::StaticMeshShape>(entity, "StaticMeshShape");
if (compoundShapeComponent && (sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent)) if (compoundShapeComponent && (sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent))
{ LOG_WARNING("Entity %i has both compound shape and normal shape! Normal shapes must be children to entity with compound shape.", entity); {
LOG_WARNING("Entity %i has both compound shape and normal shape! Normal shapes must be children to entity with compound shape.", entity);
} }
PhysicsData* physicsData = &m_PhysicsData[entity]; PhysicsData* physicsData = &m_PhysicsData[entity];
@@ -238,7 +259,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
// Set-up compound shape // Set-up compound shape
if (compoundShapeComponent) if (compoundShapeComponent)
{ btCompoundShape* compoundShape = new btCompoundShape(); {
btCompoundShape* compoundShape = new btCompoundShape();
physicsData->CollisionShape = compoundShape; physicsData->CollisionShape = compoundShape;
btTransform transform; btTransform transform;
@@ -247,7 +269,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
btVector3 inertia; btVector3 inertia;
if (physicsComponent->Mass != 0) if (physicsComponent->Mass != 0)
{ physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia); {
physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia);
} }
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(physicsComponent->Mass, physicsData->MotionState, physicsData->CollisionShape, inertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(physicsComponent->Mass, physicsData->MotionState, physicsData->CollisionShape, inertia);
@@ -258,26 +281,32 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
// Set-up normal shapes // Set-up normal shapes
else if (boxShapeComponent) else if (boxShapeComponent)
{ physicsData->CollisionShape = new btBoxShape(btVector3(boxShapeComponent->Width, boxShapeComponent->Height, boxShapeComponent->Depth)); {
physicsData->CollisionShape = new btBoxShape(btVector3(boxShapeComponent->Width, boxShapeComponent->Height, boxShapeComponent->Depth));
} }
else if (sphereShapeComponent) else if (sphereShapeComponent)
{ physicsData->CollisionShape = new btSphereShape(sphereShapeComponent->Radius); {
physicsData->CollisionShape = new btSphereShape(sphereShapeComponent->Radius);
} }
else if (meshShapeComponent) else if (meshShapeComponent)
{ // TODO: Collision mesh things go here {
// TODO: Collision mesh things go here
//new btConvexTriangleMeshShape() //new btConvexTriangleMeshShape()
} }
if (boxShapeComponent || sphereShapeComponent || meshShapeComponent || staticMeshShapeComponent) if (boxShapeComponent || sphereShapeComponent || meshShapeComponent || staticMeshShapeComponent)
{ btTransform transform; {
btTransform transform;
transform.setFromOpenGLMatrix(glm::value_ptr(glm::translate(glm::mat4(), transformComponent->Position) * glm::toMat4(transformComponent->Orientation))); transform.setFromOpenGLMatrix(glm::value_ptr(glm::translate(glm::mat4(), transformComponent->Position) * glm::toMat4(transformComponent->Orientation)));
// If there's a local physics component // If there's a local physics component
if (physicsComponent) if (physicsComponent)
{ physicsData->MotionState = new btDefaultMotionState(transform); {
physicsData->MotionState = new btDefaultMotionState(transform);
btVector3 inertia; btVector3 inertia;
if (physicsComponent->Mass != 0) if (physicsComponent->Mass != 0)
{ physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia); {
physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia);
} }
btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(physicsComponent->Mass, physicsData->MotionState, physicsData->CollisionShape, inertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(physicsComponent->Mass, physicsData->MotionState, physicsData->CollisionShape, inertia);
@@ -286,16 +315,19 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
m_DynamicsWorld->addRigidBody(physicsData->RigidBody); m_DynamicsWorld->addRigidBody(physicsData->RigidBody);
} }
else else
{ // Otherwise, find our base parent and attach to compound shape {
// Otherwise, find our base parent and attach to compound shape
EntityID baseParent = m_World->GetEntityBaseParent(entity); EntityID baseParent = m_World->GetEntityBaseParent(entity);
auto basePhysicsComponent = m_World->GetComponent<Components::Physics>(baseParent, "Physics"); auto basePhysicsComponent = m_World->GetComponent<Components::Physics>(baseParent, "Physics");
if (!basePhysicsComponent) if (!basePhysicsComponent)
{ LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing physics component on base parent entity %i", entity, baseParent); {
LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing physics component on base parent entity %i", entity, baseParent);
return; return;
} }
auto baseCompoundShapeComponent = m_World->GetComponent<Components::CompoundShape>(baseParent, "CompoundShape"); auto baseCompoundShapeComponent = m_World->GetComponent<Components::CompoundShape>(baseParent, "CompoundShape");
if (!baseCompoundShapeComponent) if (!baseCompoundShapeComponent)
{ LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing compound shape on base parent entity %i", entity, baseParent); {
LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing compound shape on base parent entity %i", entity, baseParent);
return; return;
} }
PhysicsData* basePhysicsData = &m_PhysicsData.at(baseParent); PhysicsData* basePhysicsData = &m_PhysicsData.at(baseParent);
@@ -313,7 +345,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
} }
void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent) void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent)
{ PhysicsData* physicsData = &m_PhysicsData[entity]; {
PhysicsData* physicsData = &m_PhysicsData[entity];
delete physicsData->RigidBody; delete physicsData->RigidBody;
delete physicsData->MotionState; delete physicsData->MotionState;
+2 -1
View File
@@ -43,7 +43,8 @@ private:
struct PhysicsData struct PhysicsData
{ btRigidBody* RigidBody; {
btRigidBody* RigidBody;
btMotionState* MotionState; btMotionState* MotionState;
btCollisionShape* CollisionShape; btCollisionShape* CollisionShape;
}; };
+18 -9
View File
@@ -3,21 +3,26 @@
#include "World.h" #include "World.h"
void Systems::RenderSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component) void Systems::RenderSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component)
{ if(type == "Model") {
{ auto modelComponent = std::static_pointer_cast<Components::Model>(component); if(type == "Model")
{
auto modelComponent = std::static_pointer_cast<Components::Model>(component);
} }
} }
void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{ auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (transformComponent == nullptr) if (transformComponent == nullptr)
return; return;
// Draw models // Draw models
auto modelComponent = m_World->GetComponent<Components::Model>(entity, "Model"); auto modelComponent = m_World->GetComponent<Components::Model>(entity, "Model");
if (modelComponent != nullptr) if (modelComponent != nullptr)
{ if (m_CachedModels.find(modelComponent->ModelFile) == m_CachedModels.end()) {
{ m_CachedModels[modelComponent->ModelFile] = std::make_shared<Model>(OBJ(modelComponent->ModelFile)); if (m_CachedModels.find(modelComponent->ModelFile) == m_CachedModels.end())
{
m_CachedModels[modelComponent->ModelFile] = std::make_shared<Model>(OBJ(modelComponent->ModelFile));
} }
auto model = m_CachedModels[modelComponent->ModelFile]; auto model = m_CachedModels[modelComponent->ModelFile];
@@ -32,7 +37,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
auto collision = m_World->GetComponent<Components::Collision>(entity, "Collision"); auto collision = m_World->GetComponent<Components::Collision>(entity, "Collision");
auto bounds = m_World->GetComponent<Components::Bounds>(entity, "Bounds"); auto bounds = m_World->GetComponent<Components::Bounds>(entity, "Bounds");
if (bounds != nullptr) if (bounds != nullptr)
{ glm::vec3 origin = m_TransformSystem->AbsolutePosition(entity) + (transformComponent->Scale * bounds->Origin); {
glm::vec3 origin = m_TransformSystem->AbsolutePosition(entity) + (transformComponent->Scale * bounds->Origin);
glm::vec3 volumeVector = transformComponent->Scale * bounds->VolumeVector; glm::vec3 volumeVector = transformComponent->Scale * bounds->VolumeVector;
m_Renderer->AddAABBToDraw(origin, volumeVector, (collision != nullptr && collision->CollidingEntities.size() > 0)); m_Renderer->AddAABBToDraw(origin, volumeVector, (collision != nullptr && collision->CollidingEntities.size() > 0));
} }
@@ -40,7 +46,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity, "PointLight"); auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity, "PointLight");
if (pointLightComponent != nullptr) if (pointLightComponent != nullptr)
{ glm::vec3 position = m_TransformSystem->AbsolutePosition(entity); {
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
m_Renderer->AddPointLightToDraw( m_Renderer->AddPointLightToDraw(
position, position,
pointLightComponent->Specular, pointLightComponent->Specular,
@@ -53,7 +60,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
auto cameraComponent = m_World->GetComponent<Components::Camera>(entity, "Camera"); auto cameraComponent = m_World->GetComponent<Components::Camera>(entity, "Camera");
if (cameraComponent != nullptr) if (cameraComponent != nullptr)
{ m_Renderer->GetCamera()->Position(transformComponent->Position); {
m_Renderer->GetCamera()->Position(transformComponent->Position);
m_Renderer->GetCamera()->Orientation(transformComponent->Orientation); m_Renderer->GetCamera()->Orientation(transformComponent->Orientation);
m_Renderer->GetCamera()->FOV(cameraComponent->FOV); m_Renderer->GetCamera()->FOV(cameraComponent->FOV);
@@ -63,7 +71,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
} }
void Systems::RenderSystem::Initialize() void Systems::RenderSystem::Initialize()
{ m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>("TransformSystem"); {
m_TransformSystem = m_World->GetSystem<Systems::TransformSystem>("TransformSystem");
} }
+46 -23
View File
@@ -4,15 +4,18 @@
Systems::SoundSystem::SoundSystem(World* world) Systems::SoundSystem::SoundSystem(World* world)
: System(world) : System(world)
{ //initialize OpenAL {
//initialize OpenAL
ALCdevice* Device = alcOpenDevice(NULL); ALCdevice* Device = alcOpenDevice(NULL);
ALCcontext* context; ALCcontext* context;
if(Device) if(Device)
{ context = alcCreateContext(Device, NULL); {
context = alcCreateContext(Device, NULL);
alcMakeContextCurrent(context); alcMakeContextCurrent(context);
} }
else else
{ LOG_ERROR("OMG OPEN AL FAIL"); {
LOG_ERROR("OMG OPEN AL FAIL");
} }
alGetError(); alGetError();
@@ -27,13 +30,15 @@ void Systems::SoundSystem::Update(double dt)
} }
void Systems::SoundSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) void Systems::SoundSystem::UpdateEntity(double dt, EntityID entity, EntityID parent)
{ auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (transformComponent == nullptr) if (transformComponent == nullptr)
return; return;
auto entityName = m_World->GetProperty<std::string>(entity, "Name"); auto entityName = m_World->GetProperty<std::string>(entity, "Name");
if (entityName == "Camera") if (entityName == "Camera")
{ glm::vec3 playerPos = transformComponent->Position; {
glm::vec3 playerPos = transformComponent->Position;
ALfloat listenerPos[3] = { playerPos.x, playerPos.y, -playerPos.z }; ALfloat listenerPos[3] = { playerPos.x, playerPos.y, -playerPos.z };
glm::vec3 playerVel = transformComponent->Velocity; glm::vec3 playerVel = transformComponent->Velocity;
@@ -52,7 +57,8 @@ void Systems::SoundSystem::UpdateEntity(double dt, EntityID entity, EntityID par
auto soundEmitter = m_World->GetComponent<Components::SoundEmitter>(entity, "SoundEmitter"); auto soundEmitter = m_World->GetComponent<Components::SoundEmitter>(entity, "SoundEmitter");
if(soundEmitter != nullptr) if(soundEmitter != nullptr)
{ ALuint source = m_Sources[soundEmitter]; {
ALuint source = m_Sources[soundEmitter];
alSourcef(source, AL_GAIN, soundEmitter->Gain); alSourcef(source, AL_GAIN, soundEmitter->Gain);
//alSourcef(source, AL_MAX_DISTANCE, soundEmitter->MaxDistance); //alSourcef(source, AL_MAX_DISTANCE, soundEmitter->MaxDistance);
alSourcef(source, AL_REFERENCE_DISTANCE, soundEmitter->ReferenceDistance); alSourcef(source, AL_REFERENCE_DISTANCE, soundEmitter->ReferenceDistance);
@@ -71,7 +77,8 @@ void Systems::SoundSystem::UpdateEntity(double dt, EntityID entity, EntityID par
} }
void Systems::SoundSystem::PlaySound(Components::SoundEmitter* emitter, std::string fileName) void Systems::SoundSystem::PlaySound(Components::SoundEmitter* emitter, std::string fileName)
{ if (m_Sources.find(emitter) == m_Sources.end()) {
if (m_Sources.find(emitter) == m_Sources.end())
return; return;
ALuint buffer = LoadFile(fileName); ALuint buffer = LoadFile(fileName);
@@ -83,61 +90,73 @@ void Systems::SoundSystem::PlaySound(Components::SoundEmitter* emitter, std::str
} }
void Systems::SoundSystem::PlaySound(std::shared_ptr<Components::SoundEmitter> emitter) void Systems::SoundSystem::PlaySound(std::shared_ptr<Components::SoundEmitter> emitter)
{ ALuint buffer = LoadFile(emitter->Path); {
ALuint buffer = LoadFile(emitter->Path);
ALuint source = m_Sources[emitter.get()]; ALuint source = m_Sources[emitter.get()];
alSourcei(source, AL_BUFFER, buffer); alSourcei(source, AL_BUFFER, buffer);
alSourcePlay(m_Sources[emitter.get()]); alSourcePlay(m_Sources[emitter.get()]);
} }
void Systems::SoundSystem::StopSound(std::shared_ptr<Components::SoundEmitter> emitter) void Systems::SoundSystem::StopSound(std::shared_ptr<Components::SoundEmitter> emitter)
{ alSourceStop(m_Sources[emitter.get()]); {
alSourceStop(m_Sources[emitter.get()]);
} }
void Systems::SoundSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component) void Systems::SoundSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component)
{ if(type == "SoundEmitter") {
{ ALuint source = CreateSource(); if(type == "SoundEmitter")
{
ALuint source = CreateSource();
m_Sources[component.get()] = source; m_Sources[component.get()] = source;
} }
} }
void Systems::SoundSystem::OnComponentRemoved(std::string type, Component* component) void Systems::SoundSystem::OnComponentRemoved(std::string type, Component* component)
{ if(type == "SoundEmitter") {
{ if (m_Sources.find(component) != m_Sources.end()) if(type == "SoundEmitter")
{ ALuint source = m_Sources[component]; {
if (m_Sources.find(component) != m_Sources.end())
{
ALuint source = m_Sources[component];
alDeleteSources(1, &source); alDeleteSources(1, &source);
} }
} }
} }
ALuint Systems::SoundSystem::LoadFile(std::string path) ALuint Systems::SoundSystem::LoadFile(std::string path)
{ if (m_BufferCache.find(path) != m_BufferCache.end()) {
if (m_BufferCache.find(path) != m_BufferCache.end())
return m_BufferCache[path]; return m_BufferCache[path];
FILE* fp = NULL; FILE* fp = NULL;
fp = fopen(path.c_str(), "rb"); fp = fopen(path.c_str(), "rb");
if (fp == NULL) if (fp == NULL)
{ LOG_ERROR("Failed to load sound file \"%s\"", path.c_str()); {
LOG_ERROR("Failed to load sound file \"%s\"", path.c_str());
return 0; return 0;
} }
//CHECK FOR VALID WAVE-FILE //CHECK FOR VALID WAVE-FILE
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='R' || type[1]!='I' || type[2]!='F' || type[3]!='F') if(type[0]!='R' || type[1]!='I' || type[2]!='F' || type[3]!='F')
{ LOG_ERROR("ERROR: No RIFF in WAVE-file"); {
LOG_ERROR("ERROR: No RIFF in WAVE-file");
return 0; return 0;
} }
fread(&size, sizeof(unsigned long), 1, fp); fread(&size, sizeof(unsigned long), 1, fp);
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='W' || type[1]!='A' || type[2]!='V' || type[3]!='E') if(type[0]!='W' || type[1]!='A' || type[2]!='V' || type[3]!='E')
{ LOG_ERROR("ERROR: Not WAVE-file"); {
LOG_ERROR("ERROR: Not WAVE-file");
return 0; return 0;
} }
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='f' || type[1]!='m' || type[2]!='t' || type[3]!=' ') if(type[0]!='f' || type[1]!='m' || type[2]!='t' || type[3]!=' ')
{ LOG_ERROR("ERROR: No fmt in WAVE-file"); {
LOG_ERROR("ERROR: No fmt in WAVE-file");
return 0; return 0;
} }
@@ -152,7 +171,8 @@ ALuint Systems::SoundSystem::LoadFile(std::string path)
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='d' || type[1]!='a' || type[2]!='t' || type[3]!='a') if(type[0]!='d' || type[1]!='a' || type[2]!='t' || type[3]!='a')
{ LOG_ERROR("ERROR: WAVE-file Missing data"); {
LOG_ERROR("ERROR: WAVE-file Missing data");
return 0; return 0;
} }
@@ -165,13 +185,15 @@ ALuint Systems::SoundSystem::LoadFile(std::string path)
// Create buffer // Create buffer
ALuint format = 0; ALuint format = 0;
if(bitsPerSample == 8) if(bitsPerSample == 8)
{ if(channels == 1) {
if(channels == 1)
format = AL_FORMAT_MONO8; format = AL_FORMAT_MONO8;
else if(channels == 2) else if(channels == 2)
format = AL_FORMAT_STEREO8; format = AL_FORMAT_STEREO8;
} }
if(bitsPerSample == 16) if(bitsPerSample == 16)
{ if (channels == 1) {
if (channels == 1)
format = AL_FORMAT_MONO16; format = AL_FORMAT_MONO16;
else if (channels == 2) else if (channels == 2)
format = AL_FORMAT_STEREO16; format = AL_FORMAT_STEREO16;
@@ -187,7 +209,8 @@ ALuint Systems::SoundSystem::LoadFile(std::string path)
} }
ALuint Systems::SoundSystem::CreateSource() ALuint Systems::SoundSystem::CreateSource()
{ ALuint source; {
ALuint source;
alGenSources((ALuint)1, &source); alGenSources((ALuint)1, &source);
alDopplerFactor(1); // Numbers greater than 1 will increase Doppler effect, numbers lower than 1 will decrease the Doppler effect alDopplerFactor(1); // Numbers greater than 1 will increase Doppler effect, numbers lower than 1 will decrease the Doppler effect
+15 -12
View File
@@ -14,11 +14,13 @@
//} //}
glm::vec3 Systems::TransformSystem::AbsolutePosition(EntityID entity) glm::vec3 Systems::TransformSystem::AbsolutePosition(EntityID entity)
{ glm::vec3 absPosition; {
glm::vec3 absPosition;
glm::quat accumulativeOrientation; glm::quat accumulativeOrientation;
do do
{ auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform");
//absPosition += transform->Position; //absPosition += transform->Position;
entity = m_World->GetEntityParent(entity); entity = m_World->GetEntityParent(entity);
auto transform2 = m_World->GetComponent<Components::Transform>(entity, "Transform"); auto transform2 = m_World->GetComponent<Components::Transform>(entity, "Transform");
@@ -26,34 +28,35 @@ glm::vec3 Systems::TransformSystem::AbsolutePosition(EntityID entity)
absPosition += transform2->Orientation * transform->Position; absPosition += transform2->Orientation * transform->Position;
else else
absPosition += transform->Position; absPosition += transform->Position;
} } while (entity != 0);
while (entity != 0);
return absPosition * accumulativeOrientation; return absPosition * accumulativeOrientation;
} }
glm::quat Systems::TransformSystem::AbsoluteOrientation(EntityID entity) glm::quat Systems::TransformSystem::AbsoluteOrientation(EntityID entity)
{ glm::quat absOrientation; {
glm::quat absOrientation;
do do
{ auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform");
absOrientation *= transform->Orientation; absOrientation *= transform->Orientation;
entity = m_World->GetEntityParent(entity); entity = m_World->GetEntityParent(entity);
} } while (entity != 0);
while (entity != 0);
return absOrientation; return absOrientation;
} }
glm::vec3 Systems::TransformSystem::AbsoluteScale(EntityID entity) glm::vec3 Systems::TransformSystem::AbsoluteScale(EntityID entity)
{ glm::vec3 absScale(1); {
glm::vec3 absScale(1);
do do
{ auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform"); {
auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform");
absScale *= transform->Scale; absScale *= transform->Scale;
entity = m_World->GetEntityParent(entity); entity = m_World->GetEntityParent(entity);
} } while (entity != 0);
while (entity != 0);
return absScale; return absScale;
} }
+10 -5
View File
@@ -2,25 +2,30 @@
#include "Texture.h" #include "Texture.h"
Texture::Texture(std::string path) Texture::Texture(std::string path)
{ Load(path); {
Load(path);
} }
void Texture::Load(std::string path) void Texture::Load(std::string path)
{ auto cachedTexture = m_TextureCache.find(path); {
auto cachedTexture = m_TextureCache.find(path);
if (cachedTexture == m_TextureCache.end()) if (cachedTexture == m_TextureCache.end())
{ m_TextureCache[path] = SOIL_load_OGL_texture(path.c_str(), 0, 0, SOIL_FLAG_INVERT_Y); {
m_TextureCache[path] = SOIL_load_OGL_texture(path.c_str(), 0, 0, SOIL_FLAG_INVERT_Y);
} }
m_Texture = m_TextureCache[path]; m_Texture = m_TextureCache[path];
} }
void Texture::Bind() void Texture::Bind()
{ glActiveTexture(GL_TEXTURE0); {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_Texture); glBindTexture(GL_TEXTURE_2D, m_Texture);
} }
Texture::~Texture() Texture::~Texture()
{ glDeleteTextures(1, &m_Texture); {
glDeleteTextures(1, &m_Texture);
} }
+4 -2
View File
@@ -5,9 +5,11 @@
#include <iostream> #include <iostream>
inline bool _GLERROR(char* info, char* file, char* func, unsigned int line) inline bool _GLERROR(char* info, char* file, char* func, unsigned int line)
{ GLenum error = glGetError(); {
GLenum error = glGetError();
if (error != GL_NO_ERROR) if (error != GL_NO_ERROR)
{ _LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s %i %s", info, error, gluErrorString(error)); {
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s %i %s", info, error, gluErrorString(error));
return true; return true;
} }
+10 -5
View File
@@ -20,7 +20,8 @@
#include <stdarg.h> #include <stdarg.h>
enum _LOG_LEVEL enum _LOG_LEVEL
{ LOG_LEVEL_ERROR, {
LOG_LEVEL_ERROR,
LOG_LEVEL_WARNING, LOG_LEVEL_WARNING,
LOG_LEVEL_INFO, LOG_LEVEL_INFO,
LOG_LEVEL_DEBUG LOG_LEVEL_DEBUG
@@ -33,14 +34,16 @@ static _LOG_LEVEL LOG_LEVEL = LOG_LEVEL_INFO;
#endif #endif
const static char* _LOG_LEVEL_PREFIX[] = const static char* _LOG_LEVEL_PREFIX[] =
{ "E: ", {
"E: ",
"W: ", "W: ",
"", "",
"D: " "D: "
}; };
static void _LOG(_LOG_LEVEL logLevel, char* file, char* func, unsigned int line, const char* format, ...) static void _LOG(_LOG_LEVEL logLevel, char* file, char* func, unsigned int line, const char* format, ...)
{ if (logLevel > LOG_LEVEL) {
if (logLevel > LOG_LEVEL)
return; return;
va_list args; va_list args;
@@ -53,11 +56,13 @@ static void _LOG(_LOG_LEVEL logLevel, char* file, char* func, unsigned int line,
va_end(args); va_end(args);
if (logLevel == LOG_LEVEL_ERROR) if (logLevel == LOG_LEVEL_ERROR)
{ std::cerr << file << ":" << line << " " << func << std::endl; {
std::cerr << file << ":" << line << " " << func << std::endl;
std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl;
} }
else else
{ std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; {
std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl;
} }
delete[] message; delete[] message;
+50 -25
View File
@@ -2,35 +2,44 @@
#include "World.h" #include "World.h"
void World::RecycleEntityID(EntityID id) void World::RecycleEntityID(EntityID id)
{ m_RecycledEntityIDs.push(id); {
m_RecycledEntityIDs.push(id);
} }
EntityID World::GenerateEntityID() EntityID World::GenerateEntityID()
{ if (!m_RecycledEntityIDs.empty()) {
{ EntityID id = m_RecycledEntityIDs.top(); if (!m_RecycledEntityIDs.empty())
{
EntityID id = m_RecycledEntityIDs.top();
m_RecycledEntityIDs.pop(); m_RecycledEntityIDs.pop();
return id; return id;
} }
else else
{ return ++m_LastEntityID; {
return ++m_LastEntityID;
} }
} }
void World::RecursiveUpdate(std::shared_ptr<System> system, double dt, EntityID parentEntity) void World::RecursiveUpdate(std::shared_ptr<System> system, double dt, EntityID parentEntity)
{ for (auto pair : m_EntityParents) {
{ EntityID child = pair.first; for (auto pair : m_EntityParents)
{
EntityID child = pair.first;
EntityID parent = pair.second; EntityID parent = pair.second;
if (parent == parentEntity) if (parent == parentEntity)
{ system->UpdateEntity(dt, child, parent); {
system->UpdateEntity(dt, child, parent);
RecursiveUpdate(system, dt, child); RecursiveUpdate(system, dt, child);
} }
} }
} }
void World::Update(double dt) void World::Update(double dt)
{ for (auto pair : m_Systems) {
{ auto system = pair.second; for (auto pair : m_Systems)
{
auto system = pair.second;
system->Update(dt); system->Update(dt);
RecursiveUpdate(system, dt, 0); RecursiveUpdate(system, dt, 0);
} }
@@ -48,12 +57,14 @@ void World::Update(double dt)
//} //}
EntityID World::GetEntityParent(EntityID entity) EntityID World::GetEntityParent(EntityID entity)
{ auto it = m_EntityParents.find(entity); {
auto it = m_EntityParents.find(entity);
return it == m_EntityParents.end() ? 0 : it->second; return it == m_EntityParents.end() ? 0 : it->second;
} }
EntityID World::GetEntityBaseParent(EntityID entity) EntityID World::GetEntityBaseParent(EntityID entity)
{ EntityID parent = GetEntityParent(entity); {
EntityID parent = GetEntityParent(entity);
if (parent == 0) if (parent == 0)
return entity; return entity;
else else
@@ -61,28 +72,36 @@ EntityID World::GetEntityBaseParent(EntityID entity)
} }
bool World::ValidEntity(EntityID entity) bool World::ValidEntity(EntityID entity)
{ return m_EntityParents.find(entity) != m_EntityParents.end(); {
return m_EntityParents.find(entity) != m_EntityParents.end();
} }
void World::RemoveEntity(EntityID entity) void World::RemoveEntity(EntityID entity)
{ m_EntitiesToRemove.push_back(entity); {
m_EntitiesToRemove.push_back(entity);
for (auto pair : m_EntityParents) for (auto pair : m_EntityParents)
{ if (pair.second == entity) {
{ m_EntitiesToRemove.push_back(pair.first); if (pair.second == entity)
{
m_EntitiesToRemove.push_back(pair.first);
} }
} }
} }
void World::ProcessEntityRemovals() void World::ProcessEntityRemovals()
{ for (auto entity : m_EntitiesToRemove) {
{ m_EntityParents.erase(entity); for (auto entity : m_EntitiesToRemove)
{
m_EntityParents.erase(entity);
// Remove components // Remove components
for (auto pair : m_EntityComponents[entity]) for (auto pair : m_EntityComponents[entity])
{ auto type = pair.first; {
auto type = pair.first;
auto component = pair.second; auto component = pair.second;
// Trigger events // Trigger events
for (auto pair : m_Systems) for (auto pair : m_Systems)
{ auto system = pair.second; {
auto system = pair.second;
system->OnComponentRemoved(type, component.get()); system->OnComponentRemoved(type, component.get());
} }
m_ComponentsOfType[type].remove(component); m_ComponentsOfType[type].remove(component);
@@ -95,7 +114,8 @@ void World::ProcessEntityRemovals()
} }
EntityID World::CreateEntity(EntityID parent /*= 0*/) EntityID World::CreateEntity(EntityID parent /*= 0*/)
{ EntityID newEntity = GenerateEntityID(); {
EntityID newEntity = GenerateEntityID();
m_EntityParents.insert(std::pair<EntityID, EntityID>(newEntity, parent)); m_EntityParents.insert(std::pair<EntityID, EntityID>(newEntity, parent));
return newEntity; return newEntity;
} }
@@ -106,23 +126,28 @@ World::~World()
} }
World::World() World::World()
{ m_LastEntityID = 0; {
m_LastEntityID = 0;
} }
void World::Initialize() void World::Initialize()
{ RegisterSystems(); {
RegisterSystems();
AddSystems(); AddSystems();
for (auto system : m_Systems) for (auto system : m_Systems)
{ system.second->Initialize(); {
system.second->Initialize();
} }
RegisterComponents(); RegisterComponents();
} }
std::shared_ptr<Component> World::AddComponent(EntityID entity, std::string componentType) std::shared_ptr<Component> World::AddComponent(EntityID entity, std::string componentType)
{ return AddComponent<Component>(entity, componentType); {
return AddComponent<Component>(entity, componentType);
} }
void World::AddSystem(std::string systemType) void World::AddSystem(std::string systemType)
{ m_Systems[systemType] = std::shared_ptr<System>(m_SystemFactory.Create(systemType)); {
m_Systems[systemType] = std::shared_ptr<System>(m_SystemFactory.Create(systemType));
} }
+16 -8
View File
@@ -45,7 +45,8 @@ public:
template <class T> template <class T>
T GetProperty(EntityID entity, std::string property) T GetProperty(EntityID entity, std::string property)
{ if(m_EntityProperties.find(entity) == m_EntityProperties.end()) {
if(m_EntityProperties.find(entity) == m_EntityProperties.end())
return T(); return T();
if(m_EntityProperties[entity].find(property) == m_EntityProperties[entity].end()) if(m_EntityProperties[entity].find(property) == m_EntityProperties[entity].end())
return T(); return T();
@@ -54,7 +55,8 @@ public:
} }
void SetProperty(EntityID entity, std::string property, boost::any value) void SetProperty(EntityID entity, std::string property, boost::any value)
{ m_EntityProperties[entity][property] = value; {
m_EntityProperties[entity][property] = value;
} }
template <class T> template <class T>
@@ -97,8 +99,10 @@ protected:
template <class T> template <class T>
std::shared_ptr<T> World::GetSystem(std::string systemType) std::shared_ptr<T> World::GetSystem(std::string systemType)
{ if (m_Systems.find(systemType) == m_Systems.end()) {
{ LOG_WARNING("Tried to get pointer to unregistered system \"%s\"!", systemType.c_str()); if (m_Systems.find(systemType) == m_Systems.end())
{
LOG_WARNING("Tried to get pointer to unregistered system \"%s\"!", systemType.c_str());
return nullptr; return nullptr;
} }
@@ -107,9 +111,11 @@ std::shared_ptr<T> World::GetSystem(std::string systemType)
template <class T> template <class T>
std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentType) std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentType)
{ std::shared_ptr<T> component = std::shared_ptr<T>(static_cast<T*>(m_ComponentFactory.Create(componentType))); {
std::shared_ptr<T> component = std::shared_ptr<T>(static_cast<T*>(m_ComponentFactory.Create(componentType)));
if (component == nullptr) if (component == nullptr)
{ LOG_ERROR("Failed to attach invalid component \"%s\" to entity #%i", componentType.c_str(), entity); {
LOG_ERROR("Failed to attach invalid component \"%s\" to entity #%i", componentType.c_str(), entity);
return nullptr; return nullptr;
} }
@@ -117,7 +123,8 @@ std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentTyp
m_ComponentsOfType[componentType].push_back(component); m_ComponentsOfType[componentType].push_back(component);
m_EntityComponents[entity][componentType] = component; m_EntityComponents[entity][componentType] = component;
for (auto pair : m_Systems) for (auto pair : m_Systems)
{ auto system = pair.second; {
auto system = pair.second;
system->OnComponentCreated(componentType, component); system->OnComponentCreated(componentType, component);
} }
return component; return component;
@@ -126,7 +133,8 @@ std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentTyp
template <class T> template <class T>
T* World::GetComponent(EntityID entity, std::string componentType) T* World::GetComponent(EntityID entity, std::string componentType)
{ return (T*)m_EntityComponents[entity][componentType].get(); {
return (T*)m_EntityComponents[entity][componentType].get();
} }
#endif // World_h__ #endif // World_h__
+2 -1
View File
@@ -2,7 +2,8 @@
#include "Engine.h" #include "Engine.h"
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ Engine engine(argc, argv); {
Engine engine(argc, argv);
while (engine.Running()) while (engine.Running())
engine.Tick(); engine.Tick();