Merge remote-tracking branch 'origin/master' into PlayerMovement

# Conflicts:
#	include/Engine/Collision/Collision.h
#	include/Engine/Collision/CollisionSystem.h
#	include/Engine/Collision/TriggerSystem.h
#	resources/Schema/Components.xsd
#	resources/Schema/Entities/CollisionTestLevel.xml
#	resources/Schema/Types/Entity.xsd
#	src/Engine/Collision/Collision.cpp
#	src/Game/Game.cpp
This commit is contained in:
2016-01-15 20:28:43 +01:00
64 changed files with 2719 additions and 365 deletions
+9 -2
View File
@@ -9,8 +9,8 @@ find_package(ZLIB REQUIRED)
find_package(PNG REQUIRED)
find_package(Xerces REQUIRED)
# Because FindOpenAL is retarded
#set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${CMAKE_SOURCE_DIR}/deps/include/AL")
#find_package(OpenAL REQUIRED)
set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${CMAKE_SOURCE_DIR}/deps/include/OpenAL")
find_package(OpenAL REQUIRED)
if(UNIX)
find_package(X11 REQUIRED)
endif()
@@ -52,6 +52,12 @@ file(GLOB SOURCE_FILES_Network
)
source_group(Network FILES ${SOURCE_FILES_Network})
file(GLOB SOURCE_FILES_Sound
"${INCLUDE_PATH}/Sound/*.h"
"Sound/*.cpp"
)
source_group(Sound FILES ${SOURCE_FILES_Sound})
file(GLOB SOURCE_FILES_Rendering
"${INCLUDE_PATH}/Rendering/*.h"
"Rendering/*.cpp"
@@ -86,6 +92,7 @@ set(SOURCE_FILES
${SOURCE_FILES_Core_Util}
${SOURCE_FILES_Input}
${SOURCE_FILES_Network}
${SOURCE_FILES_Sound}
${SOURCE_FILES_GUI}
${SOURCE_FILES_Rendering}
${SOURCE_FILES_Rendering_Util}
+2 -2
View File
@@ -265,11 +265,11 @@ bool attachAABBComponentFromModel(World* world, EntityID id)
return false;
}
glm::mat4 modelMatrix = modelRes->m_Matrix;
glm::mat4 modelMatrix = modelRes->Matrix();
glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY);
glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY);
for (const auto& v : modelRes->m_Vertices) {
for (const auto& v : modelRes->Vertices()) {
const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1);
maxi.x = std::max(wPos.x, maxi.x);
maxi.y = std::max(wPos.y, maxi.y);
+56 -48
View File
@@ -1,4 +1,7 @@
#include "Core/ResourceManager.h"
#include "boost/thread/thread.hpp"
#include "boost/thread/mutex.hpp"
#include "boost/thread/lock_guard.hpp"
std::unordered_map<std::string, std::string> ResourceManager::m_CompilerTypenameToResourceType;
std::unordered_map<std::string, std::function<Resource*(std::string)>> ResourceManager::m_FactoryFunctions;
@@ -6,10 +9,13 @@ std::unordered_map<std::pair<std::string, std::string>, Resource*> ResourceManag
std::unordered_map<std::string, Resource*> ResourceManager::m_ResourceFromName;
std::unordered_map<Resource*, Resource*> ResourceManager::m_ResourceParents;
unsigned int ResourceManager::m_CurrentResourceTypeID = 0;
bool ResourceManager::UseThreading = false;
std::unordered_map<std::string, unsigned int> ResourceManager::m_ResourceTypeIDs;
std::unordered_map<unsigned int, unsigned int> ResourceManager::m_ResourceCount;
bool ResourceManager::m_Preloading = false;
FileWatcher ResourceManager::m_FileWatcher;
std::unordered_map<std::pair<std::string, std::string>, boost::thread> ResourceManager::m_LoadingThreads;
std::unordered_map<std::pair<std::string, std::string>, std::exception_ptr> ResourceManager::m_LoadingThreadExceptions;
boost::recursive_mutex ResourceManager::m_Mutex;
unsigned int ResourceManager::GetTypeID(std::string resourceType)
{
@@ -74,63 +80,65 @@ void ResourceManager::Update()
m_FileWatcher.Check();
}
void ResourceManager::Preload(std::string resourceType, std::string resourceName)
{
if (IsResourceLoaded(resourceType, resourceName)) {
//LOG_WARNING("Attempted to preload resource \"%s\" multiple times!", resourceName.c_str());
return;
}
m_Preloading = true;
LOG_INFO("Preloading resource \"%s\"", resourceName.c_str());
CreateResource(resourceType, resourceName, nullptr);
m_Preloading = false;
}
Resource* ResourceManager::Load(std::string resourceType, std::string resourceName, Resource* parent /*= nullptr*/)
{
auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName));
if (it != m_ResourceCache.end()) {
return it->second;
}
if (m_Preloading) {
LOG_INFO("Preloading resource \"%s\"", resourceName.c_str());
} else {
LOG_WARNING("Hot-loading resource \"%s\"", resourceName.c_str());
}
return CreateResource(resourceType, resourceName, parent);
}
Resource* ResourceManager::CreateResource(std::string resourceType, std::string resourceName, Resource* parent)
Resource* ResourceManager::createResource(const std::string& resourceType, const std::string& resourceName, Resource* parent, std::exception_ptr& exception)
{
auto facIt = m_FactoryFunctions.find(resourceType);
if (facIt == m_FactoryFunctions.end()) {
LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": type not registered", resourceName.c_str(), resourceType.c_str());
return nullptr;
cacheResource(nullptr, resourceType, resourceName, parent);
//This basically throws an exception.
exception = std::make_exception_ptr(Resource::FailedLoadingException()); return nullptr;
}
// Call the factory function
Resource* resource;
try {
resource = facIt->second(resourceName);
return cacheResource(facIt->second(resourceName), resourceType, resourceName, parent);
} catch (const Resource::StillLoadingException&) {
exception = std::current_exception(); return nullptr;
} catch (const std::exception& e) {
LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": %s", resourceName.c_str(), resourceType.c_str(), e.what());
cacheResource(nullptr, resourceType, resourceName, parent);
exception = std::current_exception(); return nullptr;
}
}
Resource* ResourceManager::createResourceThrowing(const std::string& resourceType, const std::string& resourceName, Resource* parent)
{
std::exception_ptr exception;
Resource* res = createResource(resourceType, resourceName, parent, exception);
if (exception) {
std::rethrow_exception(exception);
}
return res;
}
Resource* ResourceManager::cacheResource(Resource* resource, const std::string& resourceType, const std::string& resourceName, Resource* parent)
{
//Lock the mutex immediately, and unlock it when leaving the code block.
boost::lock_guard<decltype(m_Mutex)> guard(m_Mutex);
if (resource != nullptr) {
// Store IDs
resource->TypeID = GetTypeID(resourceType);
resource->ResourceID = GetNewResourceID(resource->TypeID);
} catch (const std::exception& e) {
resource = nullptr;
LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": %s", resourceName.c_str(), resourceType.c_str(), e.what());
}
// Cache
m_ResourceCache[std::make_pair(resourceType, resourceName)] = resource;
m_ResourceFromName[resourceName] = resource;
if (parent != nullptr) {
m_ResourceParents[resource] = parent;
}
if (!boost::filesystem::is_directory(resourceName)) {
LOG_DEBUG("Adding watch for %s", resourceName.c_str());
m_FileWatcher.AddWatch(resourceName, fileWatcherCallback);
}
return resource;
// Cache
m_ResourceCache[std::make_pair(resourceType, resourceName)] = resource;
m_ResourceFromName[resourceName] = resource;
if (parent != nullptr) {
m_ResourceParents[resource] = parent;
}
//if (!boost::filesystem::is_directory(resourceName)) {
// LOG_DEBUG("Adding watch for %s", resourceName.c_str());
// m_FileWatcher.AddWatch(resourceName, fileWatcherCallback);
//}
return resource;
}
bool ResourceManager::IsMainThread()
{
static boost::thread::id MainThreadId = boost::this_thread::get_id();
return boost::this_thread::get_id() == MainThreadId;
}
+66
View File
@@ -0,0 +1,66 @@
#include "Rendering/DrawFinalPass.h"
DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass)
{
m_Renderer = renderer;
m_LightCullingPass = lightCullingPass;
InitializeTextures();
InitializeShaderPrograms();
}
void DrawFinalPass::InitializeTextures()
{
m_WhiteTexture = ResourceManager::Load<Texture>("Textures/Core/Blank.png");
}
void DrawFinalPass::InitializeShaderPrograms()
{
m_ForwardPlusProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram");
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlus.vert.glsl")));
m_ForwardPlusProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlus.frag.glsl")));
m_ForwardPlusProgram->Compile();
m_ForwardPlusProgram->Link();
}
void DrawFinalPass::Draw(RenderScene& scene)
{
GLERROR("DrawFinalPass::Draw: Pre");
DrawFinalPassState state;
m_ForwardPlusProgram->Bind();
GLuint shaderHandle = m_ForwardPlusProgram->GetHandle();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO());
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(m_Renderer->Camera()->ProjectionMatrix()));
glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
//TODO: Render: Add code for more jobs than modeljobs.
for (auto &job : scene.ForwardJobs) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if(modelJob) {
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(modelJob->Color));
if(modelJob->DiffuseTexture != nullptr) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, modelJob->DiffuseTexture->m_Texture);
} else {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, 0, modelJob->StartIndex);
continue;
}
}
GLERROR("DrawFinalPass::Draw: END");
}
@@ -0,0 +1,18 @@
#include "Rendering/DrawFinalPassState.h"
DrawFinalPassState::DrawFinalPassState()
{
BindFramebuffer(0);
Enable(GL_BLEND);
BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Enable(GL_DEPTH_TEST);
Enable(GL_CULL_FACE);
ClearColor(glm::vec4(200.f / 255, 0.f / 255, 200.f / 255, 0.f));
Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
DrawFinalPassState::~DrawFinalPassState()
{
}
+4 -5
View File
@@ -14,7 +14,6 @@ void DrawScenePass::InitializeTextures()
void DrawScenePass::InitializeShaderPrograms()
{
//Gör så att shaders är en resource, tex som texture classen. Konstruktorn måste vara privat.
m_BasicForwardProgram = ResourceManager::Load<ShaderProgram>("#BasicForwardProgram");
m_BasicForwardProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/BasicForward.vert.glsl")));
@@ -26,16 +25,16 @@ void DrawScenePass::InitializeShaderPrograms()
void DrawScenePass::Draw(RenderScene& scene)
{
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLERROR("Renderer::Draw PickingPass");
GLERROR("DrawScenePass::Draw: Pre");
DrawScenePassState state = DrawScenePassState();
m_BasicForwardProgram->Bind();
for (auto &job : scene.ForwardJobs) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
GLuint ShaderHandle = m_BasicForwardProgram->GetHandle();
m_BasicForwardProgram->Bind();
//TODO: Kolla upp "header/include/common" shader saken så man slipper skicka in asmycket uniforms
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
glUniformMatrix4fv(glGetUniformLocation(ShaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
@@ -57,7 +56,7 @@ void DrawScenePass::Draw(RenderScene& scene)
//continue;
}
}
GLERROR("DrawScene Error");
}
GLERROR("DrawScenePass::Draw: End");
}
+151
View File
@@ -0,0 +1,151 @@
#include "Rendering/LightCullingPass.h"
LightCullingPass::LightCullingPass(IRenderer* renderer)
{
m_Renderer = renderer;
SetSSBOSizes();
InitializeSSBOs();
InitializeShaderPrograms();
//GenerateNewFrustum(TODO);
}
LightCullingPass::~LightCullingPass()
{
}
void LightCullingPass::GenerateNewFrustum(RenderScene& scene)
{
if (scene.PointLightJobs.size() == 0)
return;
GLERROR("CalculateFrustum Error: Pre");
m_CalculateFrustumProgram->Bind();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
glUniformMatrix4fv(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "P"), 1, false, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2f(glGetUniformLocation(m_CalculateFrustumProgram->GetHandle(), "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
glDispatchCompute((int)(m_Renderer->Resolution().Width/(TILE_SIZE*TILE_SIZE) + 1), (int)(m_Renderer->Resolution().Height/(TILE_SIZE*TILE_SIZE) + 1), 1);
GLERROR("CalculateFrustum Error: End");
}
void LightCullingPass::OnResolutionChange()
{
SetSSBOSizes();
}
void LightCullingPass::SetSSBOSizes()
{
m_NumberOfTiles = (int)(m_Renderer->Resolution().Width*m_Renderer->Resolution().Height)/TILE_SIZE;
//m_Frustums = new Frustum[s];
//m_LightGrid = new LightGrid[s];
//m_LightIndex = new float[s*200];
m_Frustums = new Frustum[m_NumberOfTiles];
m_LightGrid = new LightGrid[m_NumberOfTiles];
m_LightIndex = new float[m_NumberOfTiles*MAX_LIGHTS_PER_TILE];
}
void LightCullingPass::CullLights(RenderScene& scene)
{
GLERROR("CullLights Error: Pre");
m_LightOffset = 0;
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO);
if (m_PointLights.size() > 0) {
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(PointLight) * m_PointLights.size(), &(m_PointLights[0]), GL_DYNAMIC_COPY);
} else {
GLfloat zero = 0.f;
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GLfloat), &zero , GL_DYNAMIC_COPY);
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
m_LightCullProgram->Bind();
glUniform2f(glGetUniformLocation(m_LightCullProgram->GetHandle(), "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
glUniformMatrix4fv(glGetUniformLocation(m_LightCullProgram->GetHandle(), "V"), 1, false, glm::value_ptr(scene.Camera->ViewMatrix()));
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_FrustumSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightGridSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, m_LightOffsetSSBO);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightIndexSSBO);
glDispatchCompute(m_Renderer->Resolution().Width / TILE_SIZE, m_Renderer->Resolution().Height / TILE_SIZE, 1);
GLERROR("CullLights Error: End");
}
void LightCullingPass::FillLightList(RenderScene& scene)
{
m_PointLights.clear();
for(auto &job : scene.PointLightJobs) {
auto pointLightjob = std::dynamic_pointer_cast<PointLightJob>(job);
if (pointLightjob) {
PointLight p;
p.Color = pointLightjob->Color;
p.Falloff = pointLightjob->Falloff;
p.Intensity = pointLightjob->Intensity;
p.Position = glm::vec4(glm::vec3(pointLightjob->Position), 1.f);
p.Radius = pointLightjob->Radius;
p.Padding = 123.f;
m_PointLights.push_back(p);
continue;
}
}
}
void LightCullingPass::InitializeSSBOs()
{
glGenBuffers(1, &m_FrustumSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Frustum)*m_NumberOfTiles, m_Frustums, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_FrustumSSBO");
glGenBuffers(1, &m_LightSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO);
if(m_PointLights.size() > 0) {
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(PointLight) * m_PointLights.size(), &(m_PointLights[0]), GL_DYNAMIC_COPY);
}
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightSSBO");
glGenBuffers(1, &m_LightGridSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightGrid)*m_NumberOfTiles, m_LightGrid, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightGridSSBO");
glGenBuffers(1, &m_LightOffsetSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightOffsetSSBO");
glGenBuffers(1, &m_LightIndexSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(float)*m_NumberOfTiles*MAX_LIGHTS_PER_TILE, m_LightIndex, GL_DYNAMIC_COPY);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLERROR("m_LightIndexSSBO");
}
void LightCullingPass::InitializeShaderPrograms()
{
m_CalculateFrustumProgram = ResourceManager::Load<ShaderProgram>("#CalculateFrustumProgram");
m_CalculateFrustumProgram->AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/GridFrustum.comp.glsl")));
m_CalculateFrustumProgram->Compile();
m_CalculateFrustumProgram->Link();
m_LightCullProgram = ResourceManager::Load<ShaderProgram>("#LightCullProgram");
m_LightCullProgram->AddShader(std::shared_ptr<Shader>(new ComputeShader("Shaders/CullLights.comp.glsl")));
m_LightCullProgram->Compile();
m_LightCullProgram->Link();
}
+62 -48
View File
@@ -1,60 +1,74 @@
#include "Rendering/Model.h"
Model::Model(std::string fileName)
: RawModel(fileName)
{
// Generate GL buffers
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, m_Vertices.size() * sizeof(Vertex), &m_Vertices[0], GL_STATIC_DRAW);
//Try loading the model asyncronously, if it throws any exceptions then let it propagate back to caller.
m_RawModel = ResourceManager::Load<RawModel, true>(fileName);
glGenBuffers(1, &ElementBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Indices.size() * sizeof(unsigned int), &m_Indices[0], GL_STATIC_DRAW);
for (auto& group : m_RawModel->MaterialGroups) {
if (!group.TexturePath.empty()) {
group.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(group.TexturePath));
}
if (!group.NormalMapPath.empty()) {
group.NormalMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(group.NormalMapPath));
}
if (!group.SpecularMapPath.empty()) {
group.SpecularMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(group.SpecularMapPath));
}
}
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
GLERROR("GLEW: BufferFail4");
// Generate GL buffers
GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, m_RawModel->m_Vertices.size() * sizeof(RawModel::Vertex), &m_RawModel->m_Vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
std::vector<int> structSizes = { 3, 3, 3, 3, 2, 4, 4, 4, 4, 4, 4 };
int stride = 0;
for (int size : structSizes) {
stride += size;
}
stride *= sizeof(GLfloat);
int offset = 0;
{
int element = 0;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * offset)); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
}
GLERROR("GLEW: BufferFail5");
glGenBuffers(1, &ElementBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_RawModel->m_Indices.size() * sizeof(unsigned int), &m_RawModel->m_Indices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glEnableVertexAttribArray(7);
glEnableVertexAttribArray(8);
glEnableVertexAttribArray(9);
glEnableVertexAttribArray(10);
GLERROR("GLEW: BufferFail5");
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
GLERROR("GLEW: BufferFail4");
//CreateBuffers();
glBindBuffer(GL_ARRAY_BUFFER, buffer);
std::vector<int> structSizes = { 3, 3, 3, 3, 2, 4, 4, 4, 4, 4, 4 };
int stride = 0;
for (int size : structSizes) {
stride += size;
}
stride *= sizeof(GLfloat);
int offset = 0;
{
int element = 0;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * offset)); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++;
}
GLERROR("GLEW: BufferFail5");
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glEnableVertexAttribArray(7);
glEnableVertexAttribArray(8);
glEnableVertexAttribArray(9);
glEnableVertexAttribArray(10);
GLERROR("GLEW: BufferFail5");
//CreateBuffers();
}
Model::~Model()
+4 -10
View File
@@ -145,9 +145,7 @@ RawModel::RawModel(std::string fileName)
aiString path;
aiTextureMapping mapping;
material->GetTexture(aiTextureType_DIFFUSE, 0, &path, &mapping);
std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
//LOG_DEBUG("Diffuse texture: %s", absolutePath.c_str());
matGroup.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(absolutePath));
matGroup.TexturePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
}
// Normal map
//LOG_DEBUG("%i normal maps found", material->GetTextureCount(aiTextureType_HEIGHT));
@@ -155,9 +153,7 @@ RawModel::RawModel(std::string fileName)
aiString path;
aiTextureMapping mapping;
material->GetTexture(aiTextureType_HEIGHT, 0, &path, &mapping);
std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
//LOG_DEBUG("Normal map: %s", absolutePath.c_str());
matGroup.NormalMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(absolutePath));
matGroup.NormalMapPath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
}
// Specular map
//LOG_DEBUG("%i specular maps found", material->GetTextureCount(aiTextureType_SPECULAR));
@@ -165,11 +161,9 @@ RawModel::RawModel(std::string fileName)
aiString path;
aiTextureMapping mapping;
material->GetTexture(aiTextureType_SPECULAR, 0, &path, &mapping);
std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
//LOG_DEBUG("Specular map: %s", absolutePath.c_str());
matGroup.SpecularMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(absolutePath));
matGroup.SpecularMapPath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string();
}
TextureGroups.push_back(matGroup);
MaterialGroups.push_back(matGroup);
// Bones
std::map<int, std::vector<std::tuple<int, float>>> vertexWeights;
+1
View File
@@ -3,6 +3,7 @@
bool RenderState::Enable(GLenum cap)
{
if (glIsEnabled(cap)) {
//LOG_WARNING("Trying to enable somthing that is already enabled.");
return false;
}
m_ResetFunctions.push_back(std::bind(glDisable, cap));
+58 -15
View File
@@ -40,11 +40,17 @@ void RenderSystem::switchCamera(EntityID entity)
if (m_World->HasComponent(m_CurrentCamera, "Model")) {
m_World->GetComponent(m_CurrentCamera, "Model")["Visible"] = true;
}
if (m_World->HasComponent(m_CurrentCamera, "Listener")) {
m_World->DeleteComponent(m_CurrentCamera, "Listener");
}
}
if (m_World->HasComponent(entity, "Model")) {
m_World->GetComponent(entity, "Model")["Visible"] = false;
}
if (!m_World->HasComponent(entity, "Listener")) {
m_World->AttachComponent(entity, "Listener");
}
m_CurrentCamera = entity;
m_SwitchCamera = false;
@@ -85,20 +91,51 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& jobs, World
continue;
}
Model* model = ResourceManager::Load<::Model>(resource);
if (model == nullptr) {
model = ResourceManager::Load<::Model>("Models/Core/Error.obj");
Model* model;
try {
model = ResourceManager::Load<::Model, true>(resource);
} catch (const Resource::StillLoadingException&) {
//continue;
model = ResourceManager::Load<::Model>("Models/Core/UnitRaptor.obj");
} catch (const std::exception&) {
try {
model = ResourceManager::Load<::Model>("Models/Core/Error.obj");
} catch (const std::exception&) {
continue;
}
}
glm::mat4 modelMatrix = Transform::ModelMatrix(modelComponent.EntityID, world);
for (auto texGroup : model->TextureGroups) {
std::shared_ptr<ModelJob> modelJob = std::shared_ptr<ModelJob>(new ModelJob(model, m_Camera, modelMatrix, texGroup, modelComponent, world));
for (auto matGroup : model->MaterialGroups()) {
std::shared_ptr<ModelJob> modelJob = std::shared_ptr<ModelJob>(new ModelJob(model, m_Camera, modelMatrix, matGroup, modelComponent, world));
jobs.push_back(modelJob);
}
}
}
void RenderSystem::fillLight(std::list<std::shared_ptr<RenderJob>>& jobs, World* world)
{
auto pointLights = world->GetComponents("PointLight");
if (pointLights == nullptr) {
return;
}
for (auto& pointlightC : *pointLights) {
bool visible = pointlightC["Visible"];
if (!visible) {
continue;
}
auto transformC = world->GetComponent(pointlightC.EntityID, "Transform");
if (&transformC == nullptr) {
return;
}
std::shared_ptr<PointLightJob> pointLightJob = std::shared_ptr<PointLightJob>(new PointLightJob(transformC, pointlightC, m_World));
jobs.push_back(pointLightJob);
}
}
bool RenderSystem::OnInputCommand(const Events::InputCommand& e)
{
if (e.Command == "SwitchCamera" && e.Value > 0) {
@@ -119,11 +156,12 @@ void RenderSystem::Update(World* world, double dt)
//Only supports opaque geometry atm
m_RenderFrame->Clear();
RenderScene rs;
rs.Camera = m_Camera;
rs.Viewport = Rectangle(1280, 720);
fillModels(rs.ForwardJobs, world);
m_RenderFrame->Add(rs);
RenderScene scene;
scene.Camera = m_Camera;
scene.Viewport = Rectangle(1280, 720);
fillModels(scene.ForwardJobs, world);
fillLight(scene.PointLightJobs, world);
m_RenderFrame->Add(scene);
}
@@ -131,6 +169,9 @@ void RenderSystem::updateCamera(World* world, double dt)
{
if (m_SwitchCamera) {
auto cameras = world->GetComponents("Camera");
if (cameras == nullptr) {
return;
}
for (auto it = cameras->begin(); it != cameras->end(); it++) {
if ((*it).EntityID == m_CurrentCamera) {
it++;
@@ -142,11 +183,13 @@ void RenderSystem::updateCamera(World* world, double dt)
break;
}
}
ComponentWrapper& cameraComponent = world->GetComponent(m_CurrentCamera, "Camera");
ComponentWrapper& cameraTransform = world->GetComponent(m_CurrentCamera, "Transform");
if (m_World->HasComponent(m_CurrentCamera, "Camera")) {
ComponentWrapper& cameraComponent = world->GetComponent(m_CurrentCamera, "Camera");
ComponentWrapper& cameraTransform = world->GetComponent(m_CurrentCamera, "Transform");
m_DebugCameraInputController->SetOrientation(glm::quat((glm::vec3)cameraTransform["Orientation"]));
m_DebugCameraInputController->SetPosition(cameraTransform["Position"]);
m_DebugCameraInputController->SetOrientation(glm::quat((glm::vec3)cameraTransform["Orientation"]));
m_DebugCameraInputController->SetPosition(cameraTransform["Position"]);
}
}
if (m_World->ValidEntity(m_CurrentCamera)) {
+33 -8
View File
@@ -92,16 +92,22 @@ void Renderer::Update(double dt)
void Renderer::Draw(RenderFrame& frame)
{
glClearColor(255.f / 255, 163.f / 255, 176.f / 255, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_PickingPass->ClearPicking();
for (auto scene : frame.RenderScenes){
m_Camera = scene->Camera; // remove renderer camera when Editor uses the render scene cameras.
FillDepth(*scene);
m_PickingPass->Draw(*scene);
m_LightCullingPass->GenerateNewFrustum(*scene);
m_LightCullingPass->FillLightList(*scene);
m_LightCullingPass->CullLights(*scene);
m_DrawFinalPass->Draw(*scene);
//m_DrawScenePass->Draw(rq);
m_DrawScenePass->Draw(*scene);
GLERROR("Renderer::Draw m_DrawScenePass->Draw");
}
@@ -131,14 +137,14 @@ void Renderer::DrawScreenQuad(GLuint textureToDraw)
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->TextureGroups[0].EndIndex - m_ScreenQuad->TextureGroups[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->TextureGroups[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
}
void Renderer::InitializeTextures()
{
m_ErrorTexture=ResourceManager::Load<Texture>("Textures/Core/ErrorTexture.png");
m_WhiteTexture=ResourceManager::Load<Texture>("Textures/Core/Blank.png");
m_ErrorTexture = ResourceManager::Load<Texture>("Textures/Core/ErrorTexture.png");
m_WhiteTexture = ResourceManager::Load<Texture>("Textures/Core/Blank.png");
}
void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type)
@@ -149,7 +155,7 @@ void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filterin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, NULL);//TODO: Renderer: Fix the precision and Resolution
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr);//TODO: Renderer: Fix the precision and Resolution
GLERROR("Texture initialization failed");
}
@@ -157,4 +163,23 @@ void Renderer::InitializeRenderPasses()
{
m_DrawScenePass = new DrawScenePass(this);
m_PickingPass = new PickingPass(this, m_EventBroker);
m_LightCullingPass = new LightCullingPass(this);
m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass);
}
//Temp func
void Renderer::FillDepth(RenderScene& scene)
{
for (auto job : scene.ForwardJobs) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if(! modelJob) {
return;
}
glm::vec3 abspos = Transform::AbsolutePosition(modelJob->World, modelJob->Entity);
glm::vec3 worldpos = glm::vec3(scene.Camera->ViewMatrix() * glm::vec4(abspos, 1));
modelJob->Depth = worldpos.z;
}
scene.ForwardJobs.sort(Renderer::DepthSort);
}
+32 -32
View File
@@ -2,48 +2,48 @@
Texture::Texture(std::string path)
{
PNG image(path);
PNG image(path);
if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) {
image = PNG("Textures/Core/ErrorTexture.png");
if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) {
LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed.");
return;
}
}
if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) {
image = PNG("Textures/Core/ErrorTexture.png");
if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) {
LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed.");
return;
}
}
this->Width = image.Width;
this->Height = image.Height;
this->Width = image.Width;
this->Height = image.Height;
GLint format;
switch (image.Format) {
case Image::ImageFormat::RGB:
format = GL_RGB;
break;
case Image::ImageFormat::RGBA:
format = GL_RGBA;
break;
}
GLint format;
switch (image.Format) {
case Image::ImageFormat::RGB:
format = GL_RGB;
break;
case Image::ImageFormat::RGBA:
format = GL_RGBA;
break;
}
// Construct the OpenGL texture
glGenTextures(1, &m_Texture);
glBindTexture(GL_TEXTURE_2D, m_Texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, image.Data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLERROR("Texture load");
// Construct the OpenGL texture
glGenTextures(1, &m_Texture);
glBindTexture(GL_TEXTURE_2D, m_Texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, image.Data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLERROR("Texture load");
}
Texture::~Texture()
{
glDeleteTextures(1, &m_Texture);
glDeleteTextures(1, &m_Texture);
}
void Texture::Bind(GLenum textureUnit /* = GL_TEXTURE0 */)
{
glActiveTexture(textureUnit);
glBindTexture(GL_TEXTURE_2D, m_Texture);
glActiveTexture(textureUnit);
glBindTexture(GL_TEXTURE_2D, m_Texture);
}
+304
View File
@@ -0,0 +1,304 @@
#include "Sound/SoundSystem.h"
SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode)
{
m_EventBroker = eventBroker;
m_World = world;
m_EditorEnabled = editorMode;
initOpenAL();
alSpeedOfSound(340.29f);
alDistanceModel(AL_LINEAR_DISTANCE);
alDopplerFactor(1);
EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnEntity, &SoundSystem::OnPlaySoundOnEntity);
EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnPosition, &SoundSystem::OnPlaySoundOnPosition);
EVENT_SUBSCRIBE_MEMBER(m_EPlayBackgroundMusic, &SoundSystem::OnPlayBackgroundMusic);
EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundSystem::OnStopSound);
EVENT_SUBSCRIBE_MEMBER(m_EPauseSound, &SoundSystem::OnPauseSound);
EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundSystem::OnContinueSound);
EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundSystem::OnSetBGMGain);
EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundSystem::OnSetSFXGain);
}
SoundSystem::~SoundSystem()
{
stopEmitters(); // Stopps emitters
deleteInactiveEmitters(); // Deletes stopped emitters
// Delete entities
std::unordered_map<EntityID, Source*>::iterator it;
for (it = m_Sources.begin(); it != m_Sources.end(); it++) {
m_World->DeleteEntity((*it).first);
}
m_Sources.clear();
alcDestroyContext(m_ALCcontext);
alcCloseDevice(m_ALCdevice);
}
void SoundSystem::stopEmitters()
{
std::unordered_map<EntityID, Source*>::iterator it;
for (it = m_Sources.begin(); it != m_Sources.end(); it++) {
if (getSourceState(it->second->ALsource) == AL_PLAYING) {
stopSound(it->second);
}
}
}
void SoundSystem::Update(double dt)
{
m_EventBroker->Process<SoundSystem>();
addNewEmitters(dt); // can be optimized with "EEntityCreated"
deleteInactiveEmitters(); // can be optimized with "EEntityDeleted"
updateEmitters( dt);
updateListener( dt);
}
void SoundSystem::deleteInactiveEmitters()
{
std::unordered_map<EntityID, Source*>::iterator it;
for (it = m_Sources.begin(); it != m_Sources.end();) {
if (m_World->ValidEntity(it->first)
&& m_World->HasComponent(it->first, "SoundEmitter")) {
if (getSourceState(it->second->ALsource) != AL_STOPPED) {
// Nothing to see here, move along
it++;
continue;
} else {
// Sound has been stopped / finished playing.
alDeleteBuffers(1, &it->second->ALsource);
alDeleteSources(1, &it->second->ALsource);
m_World->DeleteEntity(it->first);
delete it->second;
it = m_Sources.erase(it);
}
} else {
// Entity / Component has been removed
stopSound((*it).second);
alDeleteBuffers(1, &it->second->ALsource);
alDeleteSources(1, &it->second->ALsource);
delete it->second;
it = m_Sources.erase(it);
}
}
}
void SoundSystem::addNewEmitters(double dt)
{
auto emitterComponents = m_World->GetComponents("SoundEmitter");
if (emitterComponents == nullptr) {
return;
}
for (auto it = emitterComponents->begin(); it != emitterComponents->end(); it++) {
EntityID emitter = (*it).EntityID;
std::unordered_map<EntityID, Source*>::iterator source;
source = m_Sources.find(emitter);
if (source == m_Sources.end()) { // Did not exist, add it
Source* source = createSource((std::string)(*it)["FilePath"]);
m_Sources[emitter] = source;
}
}
}
void SoundSystem::updateEmitters(double dt)
{
std::unordered_map<EntityID, Source*>::iterator it;
for (it = m_Sources.begin(); it != m_Sources.end(); it++) {
// Get previous pos
glm::vec3 previousPos;
alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z);
// Get next pos
glm::vec3 nextPos = Transform::AbsolutePosition(m_World, it->first);
// Calculate velocity
glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt;
setSourcePos(it->second->ALsource, nextPos);
setSourceVel(it->second->ALsource, velocity);
float gain;
(bool)(it->second->Type) ? gain = m_SFXVolumeChannel : gain = m_BGMVolumeChannel;
auto emitter = m_World->GetComponent(it->first, "SoundEmitter");
setSoundProperties(it->second->ALsource, &emitter);
// To make an emitter play when spawned in editor mode
if (m_EditorEnabled) {
// Path changed
if (it->second->SoundResource->Path() != (std::string)emitter["FilePath"]) {
it->second->SoundResource = ResourceManager::Load<Sound>((std::string)emitter["FilePath"]);
if (it->second->SoundResource->Buffer() != 0) {
playSound(it->second);
}
}
}
}
}
void SoundSystem::updateListener(double dt)
{
// Should only be one listener.
auto listenerComponents = m_World->GetComponents("Listener");
if (listenerComponents == nullptr) {
return;
}
for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) {
EntityID listener = (*it).EntityID;
glm::vec3 previousPos;
alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos
glm::vec3 nextPos = Transform::AbsolutePosition(m_World, listener); // Get next (current) pos
glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; // Calculate velocity
setListenerPos(nextPos);
setListenerVel(velocity);
setListenerOri(glm::eulerAngles(Transform::AbsoluteOrientation(m_World, listener)));
}
}
Source* SoundSystem::createSource(std::string filePath)
{
ALuint alSource;
alGenSources((ALuint)1, &alSource);
alSourcef(alSource, AL_REFERENCE_DISTANCE, 1.0);
alSourcef(alSource, AL_MAX_DISTANCE, FLT_MAX);
Source* source = new Source();
source->ALsource = alSource;
source->SoundResource = ResourceManager::Load<Sound>(filePath);
return source;
}
void SoundSystem::playSound(Source* source)
{
alSourcei(source->ALsource, AL_BUFFER, source->SoundResource->Buffer());
alSourcePlay(source->ALsource);
}
void SoundSystem::stopSound(Source* source)
{
alSourceStop(source->ALsource);
}
bool SoundSystem::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e)
{
Source* source = createSource(e.FilePath);
source->Type = SoundType::SFX;
m_Sources[e.EmitterID] = source;
playSound(source);
return false;
}
bool SoundSystem::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e)
{
Source* source = createSource(e.FilePath);
auto emitterID = m_World->CreateEntity();
auto transform = m_World->AttachComponent(emitterID, "Transform");
(glm::vec3&)transform["Position"] = e.Position;
auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter");
(float&)(double)emitter["Gain"] = e.Gain;
(float&)(double)emitter["Pitch"] = e.Pitch;
(bool&)emitter["Loop"] = e.Loop;
(float&)(double)emitter["MaxDistance"] = e.MaxDistance;
(float&)(double)emitter["RollOffFactor"] = e.RollOffFactor;
(float&)(double)emitter["ReferenceDistance"] = e.ReferenceDistance;
auto model = m_World->AttachComponent(emitterID, "Model");
(std::string&)model["Resource"] = "Models/Core/UnitCube.obj";
source->Type = SoundType::SFX;
m_Sources[emitterID] = source;
playSound(source);
return true;
}
bool SoundSystem::OnPauseSound(const Events::PauseSound & e)
{
alSourcePause(m_Sources[e.EmitterID]->ALsource);
return true;
}
bool SoundSystem::OnStopSound(const Events::StopSound & e)
{
alSourceStop(m_Sources[e.EmitterID]->ALsource);
return true;
}
bool SoundSystem::OnContinueSound(const Events::ContinueSound & e)
{
alSourcePlay(m_Sources[e.EmitterID]->ALsource);
return true;
}
bool SoundSystem::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e)
{
auto listenerComponents = m_World->GetComponents("Listener");
for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) {
auto emitterChild = m_World->CreateEntity((*it).EntityID);
auto emitter = m_World->AttachComponent(emitterChild, "SoundEmitter");
(bool&)emitter["Loop"] = true;
(std::string&)emitter["FilePath"] = e.FilePath;
m_World->AttachComponent(emitterChild, "Transform");
Source* source = createSource(e.FilePath);
source->Type = SoundType::BGM;
m_Sources[emitterChild] = source;
playSound(source);
}
return true;
}
bool SoundSystem::OnSetBGMGain(const Events::SetBGMGain & e)
{
m_BGMVolumeChannel = e.Gain;
return true;
}
bool SoundSystem::OnSetSFXGain(const Events::SetSFXGain & e)
{
m_SFXVolumeChannel = e.Gain;
return true;
}
void SoundSystem::setListenerOri(glm::vec3 ori)
{
// Calculate forward and up vector.
glm::vec3 forward = glm::vec3(0.0, 0.0, -1.0);
forward = glm::rotateX(forward, ori.x);
forward = glm::rotateY(forward, ori.y);
forward = glm::rotateZ(forward, ori.z);
glm::normalize(forward);
glm::vec3 up = glm::vec3(0.0, 1.0, 0.0);
up = glm::rotateX(up, ori.x);
up = glm::rotateY(up, ori.y);
up = glm::rotateZ(up, ori.z);
glm::normalize(up);
ALfloat lOri[6] = { forward.x, forward.y, forward.z, up.x, up.y, up.z };
alListenerfv(AL_ORIENTATION, lOri);
}
ALenum SoundSystem::getSourceState(ALuint source)
{
ALenum state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
return state;
}
void SoundSystem::setGain(Source * source, float gain)
{
alSourcef(source->ALsource, AL_GAIN, gain);
}
void SoundSystem::setSoundProperties(ALuint source, ComponentWrapper* soundComponent)
{
alSourcef(source, AL_GAIN, (float)(double)(*soundComponent)["Gain"]);
alSourcef(source, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]);
alSourcei(source, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO
alSourcef(source, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]);
alSourcef(source, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]);
alSourcef(source, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]);
}
void SoundSystem::initOpenAL()
{
// Initialize OpenAL
m_ALCdevice = alcOpenDevice(nullptr);
if (m_ALCdevice != nullptr) {
m_ALCcontext = alcCreateContext(m_ALCdevice, nullptr);
alcMakeContextCurrent(m_ALCcontext);
} else {
LOG_ERROR("OpenAL failed to initialize.");
}
}