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

# Conflicts:
#	include/Engine/Collision/FillFrustumOctreeSystem.h
#	include/Engine/Core/Octree.h
#	include/Engine/Rendering/RenderSystem.h
#	include/Game/Game.h
#	resources/DefaultInput.ini
#	resources/Schema/Components.xsd
#	resources/Schema/Entities/Player.xml
#	resources/Schema/Types/Entity.xsd
#	src/Engine/Rendering/RenderSystem.cpp
#	src/Game/Game.cpp
#	src/Game/Systems/PlayerMovementSystem.cpp
This commit is contained in:
2016-02-10 14:49:03 +01:00
174 changed files with 8445 additions and 1872 deletions
@@ -1,18 +0,0 @@
#include "Collision/CollidableOctreeSystem.h"
void CollidableOctreeSystem::Update(double dt)
{
m_Octree->ClearDynamicObjects();
}
void CollidableOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt)
{
if (entity.HasComponent("AABB")) {
boost::optional<EntityAABB> absoluteAABB = Collision::EntityAbsoluteAABB(entity);
if (absoluteAABB) {
m_Octree->AddDynamicObject(*absoluteAABB);
}
} else if (entity.HasComponent("Model")) {
// TODO: Derive AABB from model
}
}
+425 -100
View File
@@ -1,9 +1,11 @@
#include <algorithm>
#include <bitset>
#include "Collision/Collision.h"
#include "Engine/GLM.h"
#include "Core/World.h"
#include "Rendering/Model.h"
#include "imgui/imgui.h"
namespace Collision
{
@@ -116,36 +118,79 @@ bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation)
return glm::all(axisesIntersecting);
}
bool RayVsTriangle(const Ray& ray,
const glm::vec3& v0,
const glm::vec3& v1,
const glm::vec3& v2,
bool trueOnNegativeDistance)
{
glm::vec3 e1 = v1 - v0; //v1 - v0
glm::vec3 e2 = v2 - v0; //v2 - v0
glm::vec3 m = ray.Origin() - v0;
glm::vec3 MxE1 = glm::cross(m, e1);
glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);
float DetInv = glm::dot(e1, DxE2);
if (std::abs(DetInv) < FLT_EPSILON) {
return false;
}
DetInv = 1.0f / DetInv;
float u = glm::dot(m, DxE2) * DetInv;
float v = glm::dot(ray.Direction(), MxE1) * DetInv;
//u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem
if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) {
return false;
}
//Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit.
return trueOnNegativeDistance || 0 <= glm::dot(e2, MxE1) * DetInv;
}
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices)
{
for (int i = 0; i < modelIndices.size(); ++i) {
glm::vec3 v0 = modelVertices[modelIndices[i]].Position;
glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0
glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0
glm::vec3 m = ray.Origin() - v0;
glm::vec3 MxE1 = glm::cross(m, e1);
glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);
float DetInv = glm::dot(e1, DxE2);
if (std::abs(DetInv) < FLT_EPSILON) {
continue;
}
DetInv = 1.0f / DetInv;
float u = glm::dot(m, DxE2) * DetInv;
float v = glm::dot(ray.Direction(), MxE1) * DetInv;
//u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem
if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) {
continue;
}
//Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit.
if (0 <= glm::dot(e2, MxE1) * DetInv) {
glm::vec3 v1 = modelVertices[modelIndices[++i]].Position;
glm::vec3 v2 = modelVertices[modelIndices[++i]].Position;
if (RayVsTriangle(ray, v0, v1, v2)) {
return true;
}
}
return false;
}
bool RayVsTriangle(const Ray& ray,
const glm::vec3& v0,
const glm::vec3& v1,
const glm::vec3& v2,
float& outDistance,
float& outUCoord,
float& outVCoord,
bool trueOnNegativeDistance)
{
glm::vec3 e1 = v1 - v0; //v1 - v0
glm::vec3 e2 = v2 - v0; //v2 - v0
glm::vec3 m = ray.Origin() - v0;
glm::vec3 MxE1 = glm::cross(m, e1);
glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec
float DetInv = glm::dot(e1, DxE2);
if (std::abs(DetInv) < FLT_EPSILON) {
return false;
}
DetInv = 1.0f / DetInv;
float dist = glm::dot(e2, MxE1) * DetInv;
if (dist >= outDistance) {
return false;
}
outDistance = dist;
outUCoord = glm::dot(m, DxE2) * DetInv;
outVCoord = glm::dot(ray.Direction(), MxE1) * DetInv;
//u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem
//If u and v are positive, u+v <= 1, dist is positive, and less than closest.
return (0 <= (outUCoord + 0.001f) && 0 <= (outVCoord + 0.001f) && outUCoord + outVCoord <= 1 && (trueOnNegativeDistance || 0 <= dist));
}
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
const std::vector<unsigned int>& modelIndices,
@@ -157,26 +202,12 @@ bool RayVsModel(const Ray& ray,
bool hit = false;
for (int i = 0; i < modelIndices.size(); ++i) {
glm::vec3 v0 = modelVertices[modelIndices[i]].Position;
glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0
glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0
glm::vec3 m = ray.Origin() - v0;
glm::vec3 MxE1 = glm::cross(m, e1);
glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec
float DetInv = glm::dot(e1, DxE2);
if (std::abs(DetInv) < FLT_EPSILON) {
continue;
}
DetInv = 1.0f / DetInv;
float dist = glm::dot(e2, MxE1) * DetInv;
if (dist >= outDistance) {
continue;
}
float u = glm::dot(m, DxE2) * DetInv;
float v = glm::dot(ray.Direction(), MxE1) * DetInv;
//u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem
//If u and v are positive, u+v <= 1, dist is positive, and less than closest.
if (0 <= (u + 0.001f) && 0 <= (v + 0.001f) && u + v <= 1 && 0 <= dist) {
glm::vec3 v1 = modelVertices[modelIndices[++i]].Position;
glm::vec3 v2 = modelVertices[modelIndices[++i]].Position;
float dist;
float u;
float v;
if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) {
outDistance = dist;
outUCoord = u;
outVCoord = v;
@@ -199,92 +230,386 @@ bool RayVsModel(const Ray& ray,
return hit;
}
bool AABBvsTriangles(const AABB& box, const std::vector<RawModel::Vertex>& modelVertices, const std::vector<unsigned int>& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector)
constexpr inline int signNonZero(float x)
{
bool hit = false;
return x < 0 ? -1 : 1;
}
inline glm::vec3 signNonZero(const glm::vec3& x)
{
glm::vec3 r;
for (int i = 0; i < 3; ++i) {
r[i] = (float)signNonZero(x[i]);
}
return r;
}
template<typename T>
bool vectorHasLength(const T& vec)
{
return glm::any(glm::greaterThan(glm::abs(vec), T(0.0001f)));
}
bool rectangleVsTriangle(const glm::vec2& boxMin,
const glm::vec2& boxMax,
const std::array<glm::vec2, 3>& triPos,
glm::vec2& resolutionDirection,
float& resolutionDistanceSq,
bool& pushedFromTriNormal)
{
pushedFromTriNormal = false;
resolutionDistanceSq = INFINITY;
//Project along box normals (coordinate axes, since it's axis-aligned).
for (int ax = 0; ax < 2; ++ax) {
float minTri = INFINITY;
float maxTri = -INFINITY;
for (const glm::vec2& t : triPos) {
minTri = std::min(t[ax], minTri);
maxTri = std::max(t[ax], maxTri);
}
if (boxMax[ax] <= minTri || maxTri <= boxMin[ax]) {
return false;
}
//Here: maxBox > minTri && minBox < maxTri
//Left is negative.
float leftRes = minTri - boxMax[ax];
float rightRes = maxTri - boxMin[ax];
float push = rightRes < -leftRes ? rightRes : leftRes;
float absPushSq = abs(push);
absPushSq *= absPushSq;
if (absPushSq < resolutionDistanceSq) {
resolutionDistanceSq = absPushSq;
resolutionDirection[1 - ax] = 0.f;
resolutionDirection[ax] = push;
}
}
//Project along triangle normals.
//Put edges into normal vector, make normals in the loop.
std::array<glm::vec2, 3> triNormals = {
triPos[1] - triPos[0],
triPos[2] - triPos[1],
triPos[0] - triPos[2]
};
std::array<glm::vec2, 4> boxPos = {
boxMax,
glm::vec2(boxMax.x, boxMin.y),
glm::vec2(boxMin.x, boxMax.y),
boxMin
};
for (auto& normal : triNormals) {
if (!vectorHasLength(normal)) {
continue;
}
//Rotate edge to a normal.
normal = glm::normalize(glm::vec2(-normal.y, normal.x));
//Project triangle onto the normal.
float minTri = INFINITY;
float maxTri = -INFINITY;
for (const glm::vec2& point : triPos) {
float dot = glm::dot(normal, point);
minTri = std::min(dot, minTri);
maxTri = std::max(dot, maxTri);
}
//Project box onto the normal.
float minBox = INFINITY;
float maxBox = -INFINITY;
for (const glm::vec2& point : boxPos) {
float dot = glm::dot(normal, point);
minBox = std::min(dot, minBox);
maxBox = std::max(dot, maxBox);
}
if (maxBox <= minTri || maxTri <= minBox) {
return false;
}
//Here: maxBox > minTri && minBox < maxTri
//Left is negative.
float leftRes = minTri - maxBox;
float rightRes = maxTri - minBox;
float push = rightRes < -leftRes ? rightRes : leftRes;
float absPushSq = abs(push);
absPushSq *= absPushSq;
if (absPushSq < resolutionDistanceSq) {
resolutionDistanceSq = absPushSq;
resolutionDirection = push * normal;
pushedFromTriNormal = true;
}
}
return true;
}
constexpr float SlopeConstant(float degrees)
{
return (1.0f - degrees / 90.f);
}
//Returns true if the angle between horizon and the collision surface is less than 45 degrees.
constexpr bool FaceIsGround(float faceNormalY)
{
//TODO: Perhaps the 45 degrees could be saved in a component or in the config..
return faceNormalY > SlopeConstant(45.0f);
}
//An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 }
constexpr std::array<std::pair<int, int>, 3> dimensionPairs({ std::pair<int, int>(0, 2), std::pair<int, int>(0, 1), std::pair<int, int>(1, 2) });
bool AABBvsTriangle(const AABB& box,
const std::array<glm::vec3, 3>& triPos,
const glm::vec3& originalBoxVelocity,
float verticalStepHeight,
bool& isOnGround,
glm::vec3& boxVelocity,
glm::vec3& outResolution)
{
//Check so we don't have a zero area triangle when calculating the normal.
//Also, don't check a triangle facing away from the player.
//Less checks, and we should be able to walk out from models if we are trapped inside.
glm::vec3 triNormal = glm::cross(triPos[1] - triPos[0], triPos[2] - triPos[0]);
if (!vectorHasLength(triNormal) || (glm::dot(triNormal, originalBoxVelocity) > 0)) {
return false;
}
triNormal = glm::normalize(triNormal);
enum BoxTriResolveCase
{
ResolveDimX,
ResolveDimY,
ResolveDimZ,
Line, //Box edge colliding with triangle line.
Corner //Box corner colliding with the triangle face.
};
struct Resolution
{
Resolution()
: DistanceSq(INFINITY)
, Vector(0.f)
{ }
BoxTriResolveCase Case;
float DistanceSq;
glm::vec3 Vector;
};
//The smallest resolution that solves the collision.
Resolution resolveShortest;
//The smallest resolution that solves the collision, that resolves upwards.
Resolution resolveUpwards;
//If player stands on the ground and collides with a ground triangle,
//we might step up onto it if the step is small enough.
bool canStairStepUp = isOnGround && FaceIsGround(triNormal.y);
const glm::vec3& origin = box.Origin();
const glm::vec3& half = box.HalfSize();
const glm::vec3& min = box.MinCorner();
const glm::vec3& max = box.MaxCorner();
outResolutionVector.x = INFINITY;
for (int i = 0; i < modelIndices.size(); ++i) {
glm::vec3 p = modelVertices[i].Position;
p = glm::vec3(modelMatrix * glm::vec4(p.x, p.y, p.z, 1));
float distFromOrigin = glm::abs(origin.x - p.x);
float penetration = box.HalfSize().x - distFromOrigin;
if (penetration > 0 && penetration < glm::abs(outResolutionVector.x)) {
if (p.x > origin.x) {
outResolutionVector.x = -penetration;
} else {
outResolutionVector.x = penetration;
//For each projection in xy-, xz-, and yx-planes.
for (std::pair<int, int> dim : dimensionPairs) {
//2D Triangle.
//Project triangle.
std::array<glm::vec2, 3> t2D = {
glm::vec2(triPos[0][dim.first], triPos[0][dim.second]),
glm::vec2(triPos[1][dim.first], triPos[1][dim.second]),
glm::vec2(triPos[2][dim.first], triPos[2][dim.second])
};
//Project box.
glm::vec2 boxMin(min[dim.first], min[dim.second]);
glm::vec2 boxMax(max[dim.first], max[dim.second]);
glm::vec2 resolutionVector;
float resolutionDist;
bool pushedFromTriangleLine;
//if projections don't overlap, return false.
if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) {
return false;
} else {
//Overwrite the smallest resolution if this is smaller.
if (resolutionDist < resolveShortest.DistanceSq) {
resolveShortest.Vector = glm::vec3(0.f);
resolveShortest.Vector[dim.first] = resolutionVector.x;
resolveShortest.Vector[dim.second] = resolutionVector.y;
resolveShortest.DistanceSq = resolutionDist;
//If we pushed away from triangle line (edge), or if we
//move the player along one coordinate axis (pick the dimension that isn't zero).
resolveShortest.Case = pushedFromTriangleLine ? Line : static_cast<BoxTriResolveCase>((abs(resolveShortest.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first);
}
//Overwrite the smallest upward resolution if this is smaller, and resolves upwards.
constexpr int yAxis = 1;
bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector.x > 0 || dim.second == yAxis && resolutionVector.y > 0;
if (canStairStepUp && resIsUpwardsIn3D && resolutionDist < resolveUpwards.DistanceSq) {
resolveUpwards.Vector = glm::vec3(0.f);
resolveUpwards.Vector[dim.first] = resolutionVector.x;
resolveUpwards.Vector[dim.second] = resolutionVector.y;
resolveUpwards.DistanceSq = resolutionDist;
//If we pushed away from triangle line (edge), or if we
//move the player along one coordinate axis (pick the dimension that isn't zero).
resolveUpwards.Case = pushedFromTriangleLine ? Line : static_cast<BoxTriResolveCase>((abs(resolveUpwards.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first);
}
hit = true;
}
//glm::vec3 pLocal = origin - p;
//for (int axis = 0; axis < 3; ++axis) {
// if (p[axis] < min[axis] || p[axis] > max[axis]) {
// continue;
// }
// if (glm::abs(pLocal[axis]) < box.HalfSize()[axis]) {
// outResolutionVector[axis] = (glm::sign(pLocal[axis]) * box.HalfSize()[axis]) - pLocal[axis];
// hit = true;
// }
//}
}
return hit;
//If the triangle does intersect any of the cube diagonals, it will
//intersect the cube diagonal that comes
//closest to being perpendicular to the plane of the triangle.
glm::vec3 diagonal = signNonZero(triNormal) * half;
//The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0)
//The diagonal line contains all points P in P = origin + diagonal * t.
float t = glm::dot(triNormal, triPos[0] - origin) / glm::dot(triNormal, diagonal);
//If intersection point between plane and diagonal is within the box.
if (glm::abs(t) > 1) {
return false;
}
glm::vec3 cornerResolution = (1+t) * diagonal;
//Overwrite the smallest resolution if cornerResolution is smaller.
float lenSq = glm::length2(cornerResolution);
if (lenSq < resolveShortest.DistanceSq) {
resolveShortest.Vector = cornerResolution;
resolveShortest.Case = Corner;
}
if (canStairStepUp && cornerResolution.y > 0 && lenSq < resolveUpwards.DistanceSq) {
resolveUpwards.Vector = cornerResolution;
resolveUpwards.Case = Corner;
resolveUpwards.DistanceSq = lenSq;
}
//Force the resolution upwards if it is smaller than the threshold verticalStepHeight.
//Else take the shortest resolution.
bool takeUp = resolveUpwards.Vector.y > 0 && resolveUpwards.Vector.y < verticalStepHeight;
Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest;
outResolution = bestResolve.Vector;
glm::vec3 projNorm;
switch (bestResolve.Case) {
case ResolveDimY:
boxVelocity.y = 0.f;
if (outResolution.y > 0)
isOnGround = true;
case ResolveDimX:
case ResolveDimZ:
//If we get here, the resolution is along one coordinate axis.
//set velocity to 0 in y if it is along y-axis.
return true;
case Line:
projNorm = glm::normalize(outResolution);
break;
case Corner:
projNorm = triNormal;
break;
default:
break;
}
//If the collision was not on steep wall or similarly (e.g. walking on the ground), force resolution in y only.
if (FaceIsGround(projNorm.y)) {
//Ensure that the player always is moved upwards, instead of sliding down.
float len = glm::length(outResolution);
float ang = glm::half_pi<float>() - glm::acos(outResolution.y / len);
if (len > 0.0000001f && ang > 0.0000001f) {
outResolution.x = 0;
outResolution.y = len / glm::sin(ang);
outResolution.z = 0;
}
//Also zero the vertical velocity, if it is positive, else project it onto the normal.
//Project the velocity onto the normal of the hit line/face.
//w = v - <v,n>*n, |n|==1.
boxVelocity.y = std::min(boxVelocity.y - glm::dot(boxVelocity, projNorm) * projNorm.y, 0.f);
isOnGround = true;
} else {
//Enter here if the triangle is a steep slope, and it is not facing downwards.
//Project the velocity onto the normal of the hit line/face.
//w = v - <v,n>*n, |n|==1.
//"ice cream"-effect, air resistance + projected velocity.
if (!isOnGround) {
boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm;
}
}
return true;
}
bool attachAABBComponentFromModel(World* world, EntityID id)
bool AABBvsTriangles(const AABB& box,
const RawModel::Vertex* modelVertices,
const std::vector<unsigned int>& modelIndices,
const glm::mat4& modelMatrix,
glm::vec3& boxVelocity,
float verticalStepHeight,
bool& isOnGround,
glm::vec3& outResolutionVector)
{
if (!world->HasComponent(id, "Model")) {
return false;
}
ComponentWrapper model = world->GetComponent(id, "Model");
ComponentWrapper collision = world->AttachComponent(id, "AABB");
Model* modelRes = ResourceManager::Load<Model>(model["Resource"]);
if (modelRes == nullptr) {
return false;
bool hit = false;
bool everHitTheGround = false;
AABB newBox = box;
outResolutionVector = glm::vec3(0.f);
glm::vec3 originalBoxVelocity(boxVelocity);
for (int i = 0; i < modelIndices.size(); ) {
std::array<glm::vec3, 3> triVertices = {
Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix),
Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix),
Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix)
};
glm::vec3 outVec;
bool collideWithGround = isOnGround;
if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec)) {
hit = true;
outResolutionVector += outVec;
newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size());
if (collideWithGround) {
everHitTheGround = isOnGround = true;
}
}
}
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->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);
maxi.z = std::max(wPos.z, maxi.z);
mini.x = std::min(wPos.x, mini.x);
mini.y = std::min(wPos.y, mini.y);
mini.z = std::min(wPos.z, mini.z);
if (!everHitTheGround) {
isOnGround = false;
}
collision["Origin"] = 0.5f * (maxi + mini);
collision["Size"] = maxi - mini;
return true;
return hit;
}
boost::optional<EntityAABB> EntityAbsoluteAABB(EntityWrapper& entity)
{
if (!entity.HasComponent("AABB")) {
AABB modelSpaceBox;
if (entity.HasComponent("AABB")) {
ComponentWrapper& cAABB = entity["AABB"];
modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]);
} else if (entity.HasComponent("Model")) {
Model* model;
std::string res = entity["Model"]["Resource"];
if (res.empty()) {
return boost::none;
}
try {
model = ResourceManager::Load<::Model, true>(res);
} catch (const Resource::StillLoadingException&) {
return boost::none;
} catch (const std::exception&) {
return boost::none;
}
modelSpaceBox = model->Box();
} else {
return boost::none;
}
ComponentWrapper& cAABB = entity["AABB"];
glm::vec3 absPosition = Transform::AbsolutePosition(entity.World, entity.ID);
glm::vec3 absScale = Transform::AbsoluteScale(entity.World, entity.ID);
glm::vec3 origin = absPosition + (glm::vec3)cAABB["Origin"];
glm::vec3 size = (glm::vec3)cAABB["Size"] * absScale;
glm::mat4 modelMat = Transform::AbsoluteTransformation(entity);
glm::vec3 mini(INFINITY);
glm::vec3 maxi(-INFINITY);
glm::vec3 maxCorner = modelSpaceBox.MaxCorner();
glm::vec3 minCorner = modelSpaceBox.MinCorner();
for (int i = 0; i < 8; ++i) {
std::bitset<3> bits(i);
glm::vec3 corner;
corner.x = bits.test(0) ? maxCorner.x : minCorner.x;
corner.y = bits.test(1) ? maxCorner.y : minCorner.y;
corner.z = bits.test(2) ? maxCorner.z : minCorner.z;
corner = Transform::TransformPoint(corner, modelMat);
mini = glm::min(mini, corner);
maxi = glm::max(maxi, corner);
}
EntityAABB aabb;
aabb = AABB(mini, maxi);
EntityAABB aabb = EntityAABB::FromOriginSize(origin, size);
aabb.Entity = entity;
return aabb;
}
}
}
+33 -23
View File
@@ -1,6 +1,7 @@
#include "Collision/Collision.h"
#include "Collision/CollisionSystem.h"
#include "Core/AABB.h"
#include "Rendering/Model.h"
void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt)
{
@@ -19,39 +20,48 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
// Collide against octree items
m_OctreeResult.clear();
m_Octree->ObjectsInSameRegion(*boundingBox, m_OctreeResult);
bool everHitTheGround = false;
for (auto& boxB : m_OctreeResult) {
glm::vec3 resolutionVector;
if (boxA.Entity == boxB.Entity) {
continue;
}
if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) {
if (boxB.Entity.HasComponent("Model") && Collision::AABBVsAABB(boxA, boxB)) {
//Here we know boxB is a entity with Collideable, AABB, and Model.
RawModel* model;
try {
model = ResourceManager::Load<RawModel, true>(boxB.Entity["Model"]["Resource"]);
} catch (const std::exception&) {
continue;
}
glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity);
glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"];
bool isOnGround = (bool)cPhysics["IsOnGround"];
float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"];
if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) {
(glm::vec3&)cTransform["Position"] += resolutionVector;
cPhysics["Velocity"] = inOutVelocity;
if (isOnGround) {
everHitTheGround = true;
(bool)cPhysics["IsOnGround"] = true;
}
}
} else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) {
//Enter here if boxB has no Model.
(glm::vec3&)cTransform["Position"] += resolutionVector;
if (resolutionVector.y > 0) {
everHitTheGround = true;
(bool)cPhysics["IsOnGround"] = true;
((glm::vec3&)cPhysics["Velocity"]).y = 0.f;
}
}
}
// HACK: Temporarily collide against all collidable models since they're not in the octree yet
//auto otherCollidables = world->GetComponents("Model");
//for (auto& cModel : *otherCollidables) {
// if (cModel.EntityID == entity) {
// continue;
// }
// if (!world->HasComponent(cModel.EntityID, "Collidable")) {
// continue;
// }
// auto absPosition = RenderQueueFactory::AbsolutePosition(world, cModel.EntityID);
// auto absOrientation = RenderQueueFactory::AbsoluteOrientation(world, cModel.EntityID);
// auto absScale = RenderQueueFactory::AbsoluteScale(world, cModel.EntityID);
// glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale);
// auto model = ResourceManager::Load<Model>(cModel["Resource"]);
// glm::vec3 resolutionVector;
// if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) {
// (glm::vec3&)cTransform["Position"] += resolutionVector;
// }
//}
}
//This should apply air friction and such, iff zero models were hit.
if (!everHitTheGround) {
(bool)cPhysics["IsOnGround"] = false;
}
}
@@ -0,0 +1,21 @@
#include "Collision/FillFrustumOctreeSystem.h"
void FillFrustumOctreeSystem::Update(double dt)
{
m_Octree->ClearDynamicObjects();
}
void FillFrustumOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt)
{
if (entity.HasComponent("ExplosionEffect")) {
//TODO: Fix hack, get real box by using shader equation.
EntityAABB aabb = AABB(glm::vec3(-300), glm::vec3(300));
aabb.Entity = entity;
m_Octree->AddDynamicObject(aabb);
} else {
boost::optional<EntityAABB> absoluteAABB = Collision::EntityAbsoluteAABB(entity);
if (absoluteAABB) {
m_Octree->AddDynamicObject(*absoluteAABB);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
#include "Collision/FillOctreeSystem.h"
void FillOctreeSystem::Update(double dt)
{
m_Octree->ClearDynamicObjects();
}
void FillOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt)
{
boost::optional<EntityAABB> absoluteAABB = Collision::EntityAbsoluteAABB(entity);
if (absoluteAABB) {
m_Octree->AddDynamicObject(*absoluteAABB);
}
}
-1
View File
@@ -5,7 +5,6 @@
void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapper& cTrigger, double dt)
{
// The trigger *should* have a bounding box, or something, to test against so it can be triggered.
boost::optional<EntityAABB> triggerBox = Collision::EntityAbsoluteAABB(triggerEntity);
if (!triggerBox) {
return;
+9
View File
@@ -16,6 +16,15 @@ bool EntityWrapper::HasComponent(const std::string& componentName)
return World->HasComponent(ID, componentName);
}
void EntityWrapper::AttachComponent(const char* componentName)
{
if (!Valid()) {
LOG_WARNING("Could not attach \"%s\" component to #%i, entity is not valid.", componentName, ID);
return;
}
World->AttachComponent(ID, componentName);
}
EntityWrapper EntityWrapper::Parent()
{
if (this->World == nullptr || this->ID == EntityID_Invalid) {
-5
View File
@@ -275,9 +275,4 @@ std::vector<int> Child::childIndicesContainingBox(const AABB& box) const
}
}
bool Child::hasChildren() const
{
return m_Children[0] != nullptr;
}
}
+4
View File
@@ -97,3 +97,7 @@ glm::mat4 Transform::ModelMatrix(EntityID entity, World* world)
return modelMatrix;
}
glm::vec3 Transform::TransformPoint(const glm::vec3& point, const glm::mat4& matrix)
{
return glm::vec3(matrix * glm::vec4(point.x, point.y, point.z, 1));
}
+3 -3
View File
@@ -56,9 +56,9 @@ void EditorRenderSystem::Update(double dt)
for (auto matGroup : model->MaterialGroups()) {
std::shared_ptr<ModelJob> modelJob = std::make_shared<ModelJob>(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f);
if (cModel["Transparent"]) {
scene.TransparentObjects.push_back(modelJob);
scene.Jobs.TransparentObjects.push_back(modelJob);
} else {
scene.OpaqueObjects.push_back(modelJob);
scene.Jobs.OpaqueObjects.push_back(modelJob);
}
}
}
@@ -75,7 +75,7 @@ void EditorRenderSystem::Update(double dt)
EntityWrapper entity(m_World, cPointLight.EntityID);
ComponentWrapper& cTransform = entity["Transform"];
std::shared_ptr<PointLightJob> pointLightJob = std::make_shared<PointLightJob>(cTransform, cPointLight, entity.World);
scene.PointLightJobs.push_back(pointLightJob);
scene.Jobs.PointLight.push_back(pointLightJob);
}
}
+20 -14
View File
@@ -15,33 +15,39 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a
Skeleton* skeleton = model->m_RawModel->m_Skeleton;
const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["Name"]);
if(animation != nullptr) {
double animationSpeed = (double)animationComponent["Speed"];
if(skeleton == nullptr) {
return;
}
for (int i = 1; i <= 3; i++) {
const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]);
if (animation == nullptr) {
return;
}
double animationSpeed = (double)animationComponent["Speed" + std::to_string(i)];
if (animationSpeed != 0.0) {
double nextTime = (double)animationComponent["Time"] + animationSpeed * dt;
double nextTime = (double)animationComponent["Time" + std::to_string(i)] + animationSpeed * dt;
if (!(bool)animationComponent["Loop"] && glm::abs(nextTime) > animation->Duration) {
(double&)animationComponent["Time"] = glm::sign(nextTime) * animation->Duration;
(double&)animationComponent["Speed"] = 0.0;
if (!(bool)animationComponent["Loop" + std::to_string(i)] && glm::abs(nextTime) > animation->Duration) {
(double&)animationComponent["Time" + std::to_string(i)] = glm::sign(nextTime) * animation->Duration;
(double&)animationComponent["Speed" + std::to_string(i)] = 0.0;
Events::AnimationComplete e;
e.Entity = entity;
e.Name = (std::string)animationComponent["Name"];
e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)];
m_EventBroker->Publish(e);
} else {
if (glm::abs(nextTime) > animation->Duration) {
(double&)animationComponent["Time"] = glm::abs(nextTime) - animation->Duration;
(double&)animationComponent["Time" + std::to_string(i)] = glm::abs(nextTime) - animation->Duration;
} else {
(double&)animationComponent["Time"] = nextTime;
(double&)animationComponent["Time" + std::to_string(i)] = nextTime;
}
}
}
}
}
}
@@ -0,0 +1,70 @@
#include "Rendering/BoneAttachmentSystem.h"
void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt)
{
if(!entity.HasComponent("Transform")) {
return;
}
auto parent = entity.FirstParentWithComponent("Animation");
if (!parent.HasComponent("Model")) {
return;
}
Model* model;
try {
model = ResourceManager::Load<::Model, true>(parent["Model"]["Resource"]);
} catch (const std::exception&) {
return;
}
Skeleton* skeleton = model->m_RawModel->m_Skeleton;
if(skeleton == nullptr) {
return;
}
const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["AnimationName1"]);
if (!animation) {
return;
}
int id = skeleton->GetBoneID(entity["BoneAttachment"]["BoneName"]);
if(id == -1) {
return;
}
glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1));
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(boneTransform, scale, rotation, translation, skew, perspective);
glm::vec3 angles;
angles.y = asin(-boneTransform[0][2]);
if (cos(angles.y) != 0) {
angles.x = atan2(boneTransform[1][2], boneTransform[2][2]);
angles.z = atan2(boneTransform[0][1], boneTransform[0][0]);
} else {
angles.x = atan2(-boneTransform[2][0], boneTransform[1][1]);
angles.z = 0;
}
if ((bool)entity["BoneAttachment"]["InheritPosition"]) {
(glm::vec3&)entity["Transform"]["Position"] = translation + (glm::vec3)entity["BoneAttachment"]["PositionOffset"];
}
if ((bool)entity["BoneAttachment"]["InheritOrientation"]) {
(glm::vec3&)entity["Transform"]["Orientation"] = angles + (glm::vec3)entity["BoneAttachment"]["OrientationOffset"];
}
if ((bool)entity["BoneAttachment"]["InheritScale"]) {
(glm::vec3&)entity["Transform"]["Scale"] = scale * (glm::vec3)entity["BoneAttachment"]["ScaleOffset"];
}
}
+8 -8
View File
@@ -77,8 +77,8 @@ void DrawBloomPass::Draw(GLuint texture)
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
//Iterate some times to make it more gaussian.
for (int i = 1; i < m_iterations; i++) {
@@ -90,8 +90,8 @@ void DrawBloomPass::Draw(GLuint texture)
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
//horizontal pass
@@ -102,8 +102,8 @@ void DrawBloomPass::Draw(GLuint texture)
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
}
//final vertical gaussian after the iterations are done
@@ -115,8 +115,8 @@ void DrawBloomPass::Draw(GLuint texture)
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
GLERROR("DrawBloomPass::Draw: END");
}
@@ -6,8 +6,6 @@ DrawColorCorrectionPass::DrawColorCorrectionPass(IRenderer* renderer)
m_ScreenQuad = ResourceManager::Load<Model>("Models/Core/ScreenQuad.mesh");
//m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting.
InitializeShaderPrograms();
}
@@ -20,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms()
m_ColorCorrectionProgram->Link();
}
void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure)
void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure)
{
//glBindFramebuffer(GL_FRAMEBUFFER, 0);
GLERROR("DrawScreenQuadPass::Draw: Pre");
@@ -35,9 +33,13 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLf
glBindTexture(GL_TEXTURE_2D, sceneTexture);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, bloomTexture);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, sceneTextureLowRes);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, bloomTextureLowRes);
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
}
+733 -91
View File
@@ -2,8 +2,10 @@
DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass)
{
//TODO: Make sure that uniforms are not sent into shader if not needed.
m_Renderer = renderer;
m_LightCullingPass = lightCullingPass;
m_ShieldPixelRate = 8;
InitializeTextures();
InitializeShaderPrograms();
InitializeFrameBuffers();
@@ -21,18 +23,39 @@ void DrawFinalPass::InitializeFrameBuffers()
{
glGenRenderbuffers(1, &m_DepthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
GLERROR("RenderBuffer generation");
GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
//GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
//GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4);
//GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT);
m_FinalPassFrameBuffer.AddResource(std::shared_ptr<BufferResource>(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT)));
m_FinalPassFrameBuffer.AddResource(std::shared_ptr<BufferResource>(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT)));
//m_FinalPassFrameBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT)));
m_FinalPassFrameBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0)));
m_FinalPassFrameBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1)));
m_FinalPassFrameBuffer.Generate();
GLERROR("FBO generation");
glGenRenderbuffers(1, &m_DepthBufferLowRes);
glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate));
GLERROR("RenderBufferLowRes generation");
GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT);
//GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT);
//GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4);
//GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT);
m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr<BufferResource>(new RenderBuffer(&m_DepthBufferLowRes, GL_DEPTH_STENCIL_ATTACHMENT)));
//m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT)));
m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_SceneTextureLowRes, GL_COLOR_ATTACHMENT0)));
m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_BloomTextureLowRes, GL_COLOR_ATTACHMENT1)));
m_FinalPassFrameBufferLowRes.Generate();
GLERROR("FBO2 generation");
}
void DrawFinalPass::InitializeShaderPrograms()
@@ -55,6 +78,90 @@ void DrawFinalPass::InitializeShaderPrograms()
m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor");
m_ExplosionEffectProgram->Link();
GLERROR("Creating explosion program");
m_ForwardPlusSplatMapProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusSplatMapProgram");
m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlus.vert.glsl")));
m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl")));
m_ForwardPlusSplatMapProgram->Compile();
m_ForwardPlusSplatMapProgram->BindFragDataLocation(0, "sceneColor");
m_ForwardPlusSplatMapProgram->BindFragDataLocation(1, "bloomColor");
m_ForwardPlusSplatMapProgram->Link();
GLERROR("Creating Forward SplatMap program");
m_ExplosionEffectSplatMapProgram = ResourceManager::Load<ShaderProgram>("#ExplosionEffectSplatMapProgram");
m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlus.vert.glsl")));
m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr<Shader>(new GeometryShader("Shaders/ExplosionEffect.geom.glsl")));
m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl")));
m_ExplosionEffectSplatMapProgram->Compile();
m_ExplosionEffectSplatMapProgram->BindFragDataLocation(0, "sceneColor");
m_ExplosionEffectSplatMapProgram->BindFragDataLocation(1, "bloomColor");
m_ExplosionEffectSplatMapProgram->Link();
GLERROR("Creating explosion SplatMap program");
m_ForwardPlusSkinnedProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusSkinnedProgram");
m_ForwardPlusSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl")));
m_ForwardPlusSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlus.frag.glsl")));
m_ForwardPlusSkinnedProgram->Compile();
m_ForwardPlusSkinnedProgram->BindFragDataLocation(0, "sceneColor");
m_ForwardPlusSkinnedProgram->BindFragDataLocation(1, "bloomColor");
m_ForwardPlusSkinnedProgram->Link();
GLERROR("Creating forward+ Skinned program");
m_ExplosionEffectSkinnedProgram = ResourceManager::Load<ShaderProgram>("#ExplosionEffectSkinnedProgram");
m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl")));
m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr<Shader>(new GeometryShader("Shaders/ExplosionEffect.geom.glsl")));
m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlus.frag.glsl")));
m_ExplosionEffectSkinnedProgram->Compile();
m_ExplosionEffectSkinnedProgram->BindFragDataLocation(0, "sceneColor");
m_ExplosionEffectSkinnedProgram->BindFragDataLocation(1, "bloomColor");
m_ExplosionEffectSkinnedProgram->Link();
GLERROR("Creating explosion Skinned program");
m_ExplosionEffectSplatMapSkinnedProgram = ResourceManager::Load<ShaderProgram>("#ExplosionEffectSplatMapSkinnedProgram");
m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl")));
m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl")));
m_ExplosionEffectSplatMapSkinnedProgram->Compile();
m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor");
m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor");
m_ExplosionEffectSplatMapSkinnedProgram->Link();
GLERROR("Creating Forward SplatMap Skinned program");
m_ForwardPlusSplatMapSkinnedProgram = ResourceManager::Load<ShaderProgram>("#ForwardPlusSplatMapSkinnedProgram");
m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl")));
m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl")));
m_ForwardPlusSplatMapSkinnedProgram->Compile();
m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor");
m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor");
m_ForwardPlusSplatMapSkinnedProgram->Link();
GLERROR("Creating Forward SplatMap Skinned program");
m_ShieldToStencilProgram = ResourceManager::Load<ShaderProgram>("#ShieldToStencilProgram");
m_ShieldToStencilProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ShieldStencil.vert.glsl")));
m_ShieldToStencilProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ShieldStencil.frag.glsl")));
m_ShieldToStencilProgram->Compile();
m_ShieldToStencilProgram->Link();
GLERROR("Creating Shield program");
m_ShieldToStencilSkinnedProgram = ResourceManager::Load<ShaderProgram>("#ShieldToStencilProgramSkinned");
m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/ShieldStencilSkinned.vert.glsl")));
m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/ShieldStencil.frag.glsl")));
m_ShieldToStencilSkinnedProgram->Compile();
m_ShieldToStencilSkinnedProgram->Link();
GLERROR("Creating Shield Skinned program");
m_FillDepthBufferProgram = ResourceManager::Load<ShaderProgram>("#FillDepthBufferProgram");
m_FillDepthBufferProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/FillDepthBuffer.vert.glsl")));
m_FillDepthBufferProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl")));
m_FillDepthBufferProgram->Compile();
m_FillDepthBufferProgram->Link();
GLERROR("Creating DepthFill program");
m_FillDepthBufferSkinnedProgram = ResourceManager::Load<ShaderProgram>("#FillDepthBufferProgramSkinned");
m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl")));
m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl")));
m_FillDepthBufferSkinnedProgram->Compile();
m_FillDepthBufferSkinnedProgram->Link();
GLERROR("Creating DepthFill program");
}
void DrawFinalPass::Draw(RenderScene& scene)
@@ -65,20 +172,92 @@ void DrawFinalPass::Draw(RenderScene& scene)
if (scene.ClearDepth) {
glClear(GL_DEPTH_BUFFER_BIT);
}
//TODO: Do we need check for this or will it be per scene always?
glClearStencil(0x00);
glClear(GL_STENCIL_BUFFER_BIT);
DrawModelRenderQueues(scene.OpaqueObjects, scene);
//Fill depth buffer
state->StencilMask(0x00);
DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene);
GLERROR("OpaqueObjects");
DrawModelRenderQueues(scene.TransparentObjects, scene);
DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene);
GLERROR("TransparentObjects");
delete state;
//DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle());
//Draw shields to stencil pass
state->StencilFunc(GL_ALWAYS, 1, 0xFF);
state->StencilMask(0xFF);
DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene);
GLERROR("StencilPass");
//Draw Opaque shielded objects
state->StencilFunc(GL_NOTEQUAL, 1, 0xFF);
state->StencilMask(0x00);
DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing
GLERROR("Shielded Opaque object");
//Draw Transparen Shielded objects
DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene); //might need changing
GLERROR("Shielded Transparent objects");
GLERROR("END");
delete state;
DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle());
//Draw the lowres texture that will be shown behind the shield.
stateLowRes->Enable(GL_SCISSOR_TEST);
stateLowRes->Enable(GL_DEPTH_TEST);
//TODO: Viewports and scissor should be in state
glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate);
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glClearStencil(0x00);
glClear(GL_STENCIL_BUFFER_BIT);
//TODO: This should not be here...
stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF);
stateLowRes->StencilMask(0x00);
DrawToDepthBuffer(scene.Jobs.OpaqueObjects, scene);
DrawToDepthBuffer(scene.Jobs.TransparentObjects, scene);
//Draw shields to stencil pass
stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF);
stateLowRes->StencilMask(0xFF);
stateLowRes->Enable(GL_DEPTH_TEST);
DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene);
GLERROR("StencilPass");
glClear(GL_DEPTH_BUFFER_BIT);
stateLowRes->Enable(GL_DEPTH_TEST);
stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF);
stateLowRes->StencilMask(0x00);
DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene);
GLERROR("OpaqueObjects");
DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene);
GLERROR("TransparentObjects");
glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
delete stateLowRes;
}
void DrawFinalPass::ClearBuffer()
{
m_FinalPassFrameBufferLowRes.Bind();
glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate);
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
m_FinalPassFrameBufferLowRes.Unbind();
m_FinalPassFrameBuffer.Bind();
glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_FinalPassFrameBuffer.Unbind();
@@ -110,7 +289,221 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm:
GLERROR("MipMap Texture initialization failed");
}
void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>& job, RenderScene& scene)
void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene)
{
GLuint forwardHandle = m_ForwardPlusProgram->GetHandle();
GLERROR("forwardHandle");
GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle();
GLERROR("explosionHandle");
GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle();
GLERROR("explosionSplatMapHandle");
GLuint forwardSplatHandle = m_ForwardPlusSplatMapProgram->GetHandle();
GLERROR("forwardSplatHandle");
GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle();
GLERROR("forwardSkinnedHandle");
GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle();
GLERROR("explosionSkinnedHandle");
GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle();
GLERROR("explosionSplatMapSkinnedHandle");
GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle();
GLERROR("forwardSplatSkinnedHandle");
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());
for (auto &job : jobs) {
auto explosionEffectJob = std::dynamic_pointer_cast<ExplosionEffectJob>(job);
if (explosionEffectJob) {
switch (explosionEffectJob->Type) {
case RawModel::MaterialType::Basic:
case RawModel::MaterialType::SingleTextures:
{
if (explosionEffectJob->Model->IsSkinned()) {
m_ExplosionEffectSkinnedProgram->Bind();
GLERROR("Bind ExplosionEffectSkinned program");
//bind uniforms
BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene);
//bind textures
BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob);
std::vector<glm::mat4> frameBones;
if (explosionEffectJob->AnimationOffset.animation != nullptr) {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset);
} else {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_ExplosionEffectProgram->Bind();
GLERROR("Bind ExplosionEffect program");
//bind uniforms
BindExplosionUniforms(explosionHandle, explosionEffectJob, scene);
//bind textures
BindExplosionTextures(explosionHandle, explosionEffectJob);
}
break;
}
case RawModel::MaterialType::SplatMapping:
{
if (explosionEffectJob->Model->IsSkinned()) {
m_ExplosionEffectSplatMapSkinnedProgram->Bind();
GLERROR("Bind ExplosionEffectSplatMapSkinned program");
//bind uniforms
BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene);
//bind textures
BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob);
GLERROR("asdasd");
std::vector<glm::mat4> frameBones;
if (explosionEffectJob->AnimationOffset.animation != nullptr) {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset);
} else {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_ExplosionEffectSplatMapProgram->Bind();
GLERROR("Bind ExplosionEffectSplatMap program");
//bind uniforms
//bind uniforms
BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene);
//bind textures
BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob);
GLERROR("asdasd");
}
break;
}
}
glDisable(GL_CULL_FACE);
//draw
glBindVertexArray(explosionEffectJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int)));
glEnable(GL_CULL_FACE);
GLERROR("explosion effect end");
} else {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
//bind forward program
//TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID;
switch (modelJob->Type) {
case RawModel::MaterialType::Basic:
case RawModel::MaterialType::SingleTextures:
{
if (modelJob->Model->IsSkinned()) {
m_ForwardPlusSkinnedProgram->Bind();
GLERROR("Bind ForwardPlusSkinnedProgram");
//bind uniforms
BindModelUniforms(forwardSkinnedHandle, modelJob, scene);
//bind textures
BindModelTextures(forwardSkinnedHandle, modelJob);
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_ForwardPlusProgram->Bind();
GLERROR("Bind ForwardPlusProgram");
//bind uniforms
BindModelUniforms(forwardHandle, modelJob, scene);
//bind textures
BindModelTextures(forwardHandle, modelJob);
}
break;
}
case RawModel::MaterialType::SplatMapping:
{
if (modelJob->Model->IsSkinned()) {
m_ForwardPlusSplatMapSkinnedProgram->Bind();
GLERROR("Bind SplatMap program");
//bind uniforms
BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene);
//bind textures
BindModelTextures(forwardSplatMapSkinnedHandle, modelJob);
GLERROR("asdasd");
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_ForwardPlusSplatMapProgram->Bind();
GLERROR("Bind SplatMap program");
//bind uniforms
BindModelUniforms(forwardSplatHandle, modelJob, scene);
//bind textures
BindModelTextures(forwardSplatHandle, modelJob);
GLERROR("asdasd");
}
break;
}
}
//draw
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int)));
if (GLERROR("models end")) {
continue;
}
}
}
}
}
void DrawFinalPass::DrawShieldToStencilBuffer(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene)
{
for (auto &job : jobs) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
if(modelJob->Model->IsSkinned()) {
m_ShieldToStencilSkinnedProgram->Bind();
GLuint shaderHandle = m_ShieldToStencilSkinnedProgram->GetHandle();
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_ShieldToStencilProgram->Bind();
GLuint shaderHandle = m_ShieldToStencilProgram->GetHandle();
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int)));
if (GLERROR("models end")) {
continue;
}
}
}
}
void DrawFinalPass::DrawShieldedModelRenderQueue(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene)
{
GLuint forwardHandle = m_ForwardPlusProgram->GetHandle();
GLERROR("forwardHandle");
@@ -121,16 +514,15 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO());
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO());
for(auto &job : job)
{
for (auto &job : jobs) {
auto explosionEffectJob = std::dynamic_pointer_cast<ExplosionEffectJob>(job);
if(explosionEffectJob) {
if (explosionEffectJob) {
//Bind program
if(GLERROR("Prebind")) {
if (GLERROR("Prebind")) {
continue;
}
m_ExplosionEffectProgram->Bind();
if(GLERROR("BindProgram")) {
if (GLERROR("BindProgram")) {
continue;
}
@@ -138,24 +530,25 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
//Bind uniforms
BindExplosionUniforms(explosionHandle, explosionEffectJob, scene);
if(GLERROR("BindExplosionUniforms")) {
if (GLERROR("BindExplosionUniforms")) {
continue;
}
if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) {
if (explosionEffectJob->Animation != nullptr) {
std::vector<glm::mat4> frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime);
glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
}
std::vector<glm::mat4> frameBones;
if (explosionEffectJob->AnimationOffset.animation != nullptr) {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset);
} else {
frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations);
}
if(GLERROR("Animation")) {
glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
if (GLERROR("Animation")) {
continue;
}
//bind textures
BindExplosionTextures(explosionEffectJob);
if(GLERROR("BindExplosionTextures")) {
BindExplosionTextures(explosionHandle, explosionEffectJob);
if (GLERROR("BindExplosionTextures")) {
continue;
}
//draw
@@ -163,7 +556,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int)));
glEnable(GL_CULL_FACE);
if(GLERROR("explosion effect end")) {
if (GLERROR("explosion effect end")) {
continue;
}
@@ -178,133 +571,382 @@ void DrawFinalPass::DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>&
BindModelUniforms(forwardHandle, modelJob, scene);
//bind textures
BindModelTextures(modelJob);
BindModelTextures(forwardHandle ,modelJob);
if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) {
if (modelJob->Animation != nullptr) {
std::vector<glm::mat4> frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime);
glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
}
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
//draw
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int)));
if(GLERROR("models end")) {
if (GLERROR("models end")) {
continue;
}
}
}
}
}
void DrawFinalPass::DrawToDepthBuffer(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene)
{
for (auto &job : jobs) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if(modelJob->Model->IsSkinned()) {
m_FillDepthBufferSkinnedProgram->Bind();
GLuint shaderHandle = m_FillDepthBufferSkinnedProgram->GetHandle();
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_FillDepthBufferProgram->Bind();
GLuint shaderHandle = m_FillDepthBufferProgram->GetHandle();
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
}
//draw
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int)));
if (GLERROR("models end")) {
continue;
}
}
}
void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr<ExplosionEffectJob>& job, RenderScene& scene)
{
GLERROR("Bind 1 uniform");
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix));
GLERROR("Bind 2 uniform");
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
GLERROR("Bind 3 uniform");
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
GLERROR("Bind 4 uniform");
glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
GLERROR("Bind 5 uniform");
glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin));
GLERROR("Bind 6 uniform");
glUniform1f(glGetUniformLocation(shaderHandle, "TimeSinceDeath"), job->TimeSinceDeath);
GLERROR("Bind 7 uniform");
glUniform1f(glGetUniformLocation(shaderHandle, "ExplosionDuration"), job->ExplosionDuration);
GLERROR("Bind 8 uniform");
glUniform4fv(glGetUniformLocation(shaderHandle, "EndColor"), 1, glm::value_ptr(job->EndColor));
GLERROR("Bind 9 uniform");
glUniform1i(glGetUniformLocation(shaderHandle, "Randomness"), job->Randomness);
GLERROR("Bind 10 uniform");
glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data());
GLERROR("Bind 11 uniform");
glUniform1f(glGetUniformLocation(shaderHandle, "RandomnessScalar"), job->RandomnessScalar);
GLERROR("Bind 12 uniform");
glUniform2fv(glGetUniformLocation(shaderHandle, "Velocity"), 1, glm::value_ptr(job->Velocity));
GLERROR("Bind 13 uniform");
glUniform1i(glGetUniformLocation(shaderHandle, "ColorByDistance"), job->ColorByDistance);
GLERROR("Bind 14 uniform");
glUniform1i(glGetUniformLocation(shaderHandle, "ExponentialAccelaration"), job->ExponentialAccelaration);
GLERROR("Bind 15 uniform");
glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color));
GLERROR("Bind 16 uniform");
glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor));
GLERROR("Bind 17 uniform");
glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor));
GLERROR("Bind 18 uniform");
glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage);
GLERROR("Bind 19 uniform");
glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor));
GLERROR("END");
}
void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr<ModelJob>& job, RenderScene& scene)
{
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
GLERROR("Bind 1 uniform");
GLint Location_M = glGetUniformLocation(shaderHandle, "M");
glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix));
GLERROR("Bind 2 uniform");
GLint Location_V = glGetUniformLocation(shaderHandle, "V");
glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
GLERROR("Bind 3 uniform");
GLint Location_P = glGetUniformLocation(shaderHandle, "P");
glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
GLERROR("Bind 4 uniform");
glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
GLint Location_ScreenDimensions = glGetUniformLocation(shaderHandle, "ScreenDimensions");
glUniform2f(Location_ScreenDimensions, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height);
GLERROR("Bind 5 uniform");
glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color));
glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor));
glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor));
glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage);
glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor));
GLint Location_FillPercentage = glGetUniformLocation(shaderHandle, "FillPercentage");
glUniform1f(Location_FillPercentage, job->FillPercentage);
GLERROR("Bind 6 uniform");
GLint Location_DiffuseColor = glGetUniformLocation(shaderHandle, "DiffuseColor");
glUniform4fv(Location_DiffuseColor, 1, glm::value_ptr(job->DiffuseColor));
GLERROR("Bind 7 uniform");
GLint Location_FillColor = glGetUniformLocation(shaderHandle, "FillColor");
glUniform4fv(Location_FillColor, 1, glm::value_ptr(job->FillColor));
GLERROR("Bind 8 uniform");
GLint Location_Color = glGetUniformLocation(shaderHandle, "Color");
glUniform4fv(Location_Color, 1, glm::value_ptr(job->Color));
GLERROR("Bind 9 uniform");
GLint Location_AmbientColor = glGetUniformLocation(shaderHandle, "AmbientColor");
glUniform4fv(Location_AmbientColor, 1, glm::value_ptr(scene.AmbientColor));
GLERROR("END");
GLERROR("END");
}
void DrawFinalPass::BindExplosionTextures(std::shared_ptr<ExplosionEffectJob>& job)
void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptr<ExplosionEffectJob>& job)
{
glActiveTexture(GL_TEXTURE0);
if (job->DiffuseTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
}
switch (job->Type) {
case RawModel::MaterialType::SingleTextures:
case RawModel::MaterialType::Basic:
{
glActiveTexture(GL_TEXTURE0);
if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
glActiveTexture(GL_TEXTURE1);
if (job->NormalTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture);
}
glActiveTexture(GL_TEXTURE1);
if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
glActiveTexture(GL_TEXTURE2);
if (job->SpecularTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture);
}
glActiveTexture(GL_TEXTURE2);
if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
glActiveTexture(GL_TEXTURE3);
if (job->IncandescenceTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture);
}
glActiveTexture(GL_TEXTURE3);
if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
break;
}
case RawModel::MaterialType::SplatMapping:
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, job->SplatMap->Texture->m_Texture);
int texturePosition = GL_TEXTURE1;
//Bind 5 diffuse textures
std::string UniformName = "DiffuseUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->DiffuseTexture[i]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
//Bind 5 Normal textures
UniformName = "NormalUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->NormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->NormalTexture[i]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
//Bind 5 Specular textures
UniformName = "SpecularUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->SpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->SpecularTexture[i]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
//Bind 5 Incandescence textures
UniformName = "GlowUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->IncandescenceTexture[i]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
break;
}
}
}
void DrawFinalPass::BindModelTextures(std::shared_ptr<ModelJob>& job)
void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptr<ModelJob>& job)
{
glActiveTexture(GL_TEXTURE0);
if (job->DiffuseTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
}
switch (job->Type) {
case RawModel::MaterialType::SingleTextures:
case RawModel::MaterialType::Basic:
{
glActiveTexture(GL_TEXTURE0);
if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
glActiveTexture(GL_TEXTURE1);
if (job->NormalTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture);
}
glActiveTexture(GL_TEXTURE1);
if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
glActiveTexture(GL_TEXTURE2);
if (job->SpecularTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture);
}
glActiveTexture(GL_TEXTURE2);
if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
glActiveTexture(GL_TEXTURE3);
if (job->IncandescenceTexture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture);
} else {
glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture);
}
glActiveTexture(GL_TEXTURE3);
if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat));
}
else {
glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
break;
}
case RawModel::MaterialType::SplatMapping:
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, job->SplatMap->Texture->m_Texture);
int texturePosition = GL_TEXTURE1;
//Bind 5 diffuse textures
std::string UniformName = "DiffuseUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->DiffuseTexture[i]->UVRepeat));
} else {
glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
//Bind 5 Normal textures
UniformName = "NormalUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->NormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->NormalTexture[i]->UVRepeat));
} else {
glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
//Bind 5 Specular textures
UniformName = "SpecularUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->SpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->SpecularTexture[i]->UVRepeat));
} else {
glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
//Bind 5 Incandescence textures
UniformName = "GlowUVRepeat";
for (unsigned int i = 0; i < 5; i++) {
glActiveTexture(texturePosition);
if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) {
glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->IncandescenceTexture[i]->UVRepeat));
} else {
glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture);
glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f)));
}
texturePosition++;
}
break;
}
}
}
@@ -1,6 +1,7 @@
#include "Rendering/DrawFinalPassState.h"
DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer)
{
BindFramebuffer(frameBuffer);
@@ -8,6 +9,10 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer)
BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Enable(GL_DEPTH_TEST);
Enable(GL_CULL_FACE);
Enable(GL_STENCIL_TEST);
StencilFunc(GL_NOTEQUAL, 1, 0xFF);
StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
StencilMask(0xFF);
ClearColor(glm::vec4(0.f, 0.f, 0.f, 0.f));
}
@@ -15,3 +20,20 @@ DrawFinalPassState::~DrawFinalPassState()
{
}
DrawStencilState::DrawStencilState(GLuint frameBuffer)
{
BindFramebuffer(frameBuffer);
Enable(GL_STENCIL_TEST);
StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
StencilFunc(GL_ALWAYS, 1, 0xFF);
StencilMask(0xFF);
Enable(GL_DEPTH_TEST);
ClearColor(glm::vec4(0.f));
}
DrawStencilState::~DrawStencilState()
{
}
+2 -2
View File
@@ -32,6 +32,6 @@ void DrawScreenQuadPass::Draw(GLuint texture)
glBindVertexArray(m_ScreenQuad->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex);
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
}
+17 -4
View File
@@ -39,10 +39,13 @@ void FrameBuffer::AddResource(std::shared_ptr<BufferResource> resource)
void FrameBuffer::Generate()
{
GLERROR("PRE");
std::vector<GLenum> attachments;
glGenFramebuffers(1, &m_BufferHandle);
glBindFramebuffer(GL_FRAMEBUFFER, m_BufferHandle);
GLERROR("1");
for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) {
switch ((*it)->m_ResourceType) {
@@ -56,20 +59,30 @@ void FrameBuffer::Generate()
GLERROR("FrameBuffer generate: glFramebufferRenderbuffer");
break;
}
GLERROR("2");
if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT) {
if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) {
attachments.push_back((*it)->m_Attachment);
}
GLERROR("Attachment");
}
GLERROR("3");
GLenum* bufferTextures = &attachments[0];
glDrawBuffers(attachments.size(), bufferTextures);
if(GLERROR("4")) {
printf("hello");
}
if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus);
GLERROR("Framebuffer incomplete");
//LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus);
exit(EXIT_FAILURE);
}
GLERROR("END");
}
void FrameBuffer::Bind()
+3 -3
View File
@@ -16,7 +16,7 @@ LightCullingPass::~LightCullingPass()
void LightCullingPass::GenerateNewFrustum(RenderScene& scene)
{
if (scene.PointLightJobs.size() == 0)
if (scene.Jobs.PointLight.size() == 0)
return;
GLERROR("CalculateFrustum Error: Pre");
@@ -83,7 +83,7 @@ void LightCullingPass::FillLightList(RenderScene& scene)
{
m_LightSources.clear();
for(auto &job : scene.PointLightJobs) {
for(auto &job : scene.Jobs.PointLight) {
auto pointLightjob = std::dynamic_pointer_cast<PointLightJob>(job);
if (pointLightjob) {
LightSource p;
@@ -97,7 +97,7 @@ void LightCullingPass::FillLightList(RenderScene& scene)
m_LightSources.push_back(p);
}
}
for(auto &job : scene.DirectionalLightJobs) {
for(auto &job : scene.Jobs.DirectionalLight) {
auto directionalLightJob = std::dynamic_pointer_cast<DirectionalLightJob>(job);
if(directionalLightJob) {
LightSource p;
+91 -19
View File
@@ -5,26 +5,77 @@ Model::Model(std::string fileName)
//Try loading the model asyncronously, if it throws any exceptions then let it propagate back to caller.
m_RawModel = ResourceManager::Load<RawModel, true>(fileName);
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));
}
if (!group.IncandescenceMapPath.empty()) {
group.IncandescenceMap = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(group.IncandescenceMapPath));
}
for (auto& materialProperty : m_RawModel->m_Materials) {
switch (materialProperty.type) {
case RawModel::MaterialType::SingleTextures:
{
RawModel::MaterialSingleTextures* materialSingleTexture = static_cast<RawModel::MaterialSingleTextures*>(materialProperty.material);
if (!materialSingleTexture->ColorMap.TexturePath.empty()) {
materialSingleTexture->ColorMap.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(materialSingleTexture->ColorMap.TexturePath));
}
if (!materialSingleTexture->NormalMap.TexturePath.empty()) {
materialSingleTexture->NormalMap.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(materialSingleTexture->NormalMap.TexturePath));
}
if (!materialSingleTexture->SpecularMap.TexturePath.empty()) {
materialSingleTexture->SpecularMap.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(materialSingleTexture->SpecularMap.TexturePath));
}
if (!materialSingleTexture->IncandescenceMap.TexturePath.empty()) {
materialSingleTexture->IncandescenceMap.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(materialSingleTexture->IncandescenceMap.TexturePath));
}
}
break;
case RawModel::MaterialType::SplatMapping:
{
RawModel::MaterialSplatMapping* materialSplatMapping = static_cast<RawModel::MaterialSplatMapping*>(materialProperty.material);
if (!materialSplatMapping->SplatMap.TexturePath.empty()) {
materialSplatMapping->SplatMap.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(materialSplatMapping->SplatMap.TexturePath));
}
for (auto& texture : materialSplatMapping->ColorMaps)
{
if (!texture.TexturePath.empty()) {
texture.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(texture.TexturePath));
}
else {
texture.Texture = nullptr;
}
}
for (auto& texture : materialSplatMapping->NormalMaps)
{
if (!texture.TexturePath.empty()) {
texture.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(texture.TexturePath));
} else {
texture.Texture = nullptr;
}
}
for (auto& texture : materialSplatMapping->SpecularMaps)
{
if (!texture.TexturePath.empty()) {
texture.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(texture.TexturePath));
}
else {
texture.Texture = nullptr;
}
}
for (auto& texture : materialSplatMapping->IncandescenceMaps)
{
if (!texture.TexturePath.empty()) {
texture.Texture = std::shared_ptr<Texture>(ResourceManager::Load<Texture>(texture.TexturePath));
}
else {
texture.Texture = nullptr;
}
}
}
break;
}
}
// 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);
glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * m_RawModel->VertexSize(), m_RawModel->Vertices(), GL_STATIC_DRAW);
glGenBuffers(1, &ElementBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer);
@@ -35,7 +86,13 @@ Model::Model(std::string fileName)
GLERROR("GLEW: BufferFail4");
glBindBuffer(GL_ARRAY_BUFFER, buffer);
std::vector<int> structSizes = { 3, 3, 3, 3, 2, 4, 4 };
std::vector<int> structSizes;
if (m_RawModel->IsSkinned()) {
structSizes = { 3, 3, 3, 3, 2, 4, 4 };
} else {
structSizes = { 3, 3, 3, 3, 2 };
}
int stride = 0;
for (int size : structSizes) {
stride += size;
@@ -49,8 +106,10 @@ Model::Model(std::string fileName)
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++;
if (m_RawModel->IsSkinned()) {
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");
@@ -59,11 +118,24 @@ Model::Model(std::string fileName)
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
if (m_RawModel->IsSkinned()) {
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
}
GLERROR("GLEW: BufferFail5");
//CreateBuffers();
glm::vec3 mini(INFINITY);
glm::vec3 maxi(-INFINITY);
for (unsigned int i = 0; i < m_RawModel->NumVertices(); i++) {
const auto& v = m_RawModel->Vertices()[i];
mini = glm::min(mini, v.Position);
maxi = glm::max(maxi, v.Position);
}
m_Box = AABB(maxi, mini);
}
Model::~Model()
+174 -20
View File
@@ -41,6 +41,14 @@ void PickingPass::InitializeShaderPrograms()
m_PickingProgram->Compile();
m_PickingProgram->BindFragDataLocation(0, "TextureFragment");
m_PickingProgram->Link();
m_PickingSkinnedProgram = ResourceManager::Load<ShaderProgram>("#PickingSkinnedProgram");
m_PickingSkinnedProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/PickingSkinned.vert.glsl")));
m_PickingSkinnedProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Picking.frag.glsl")));
m_PickingSkinnedProgram->Compile();
m_PickingSkinnedProgram->BindFragDataLocation(0, "TextureFragment");
m_PickingSkinnedProgram->Link();
}
void PickingPass::Draw(RenderScene& scene)
@@ -49,6 +57,7 @@ void PickingPass::Draw(RenderScene& scene)
//TODO: Render: Add code for more jobs than modeljobs.
GLuint shaderHandle = m_PickingProgram->GetHandle();
GLuint shaderSkinnedHandle = m_PickingSkinnedProgram->GetHandle();
m_PickingProgram->Bind();
if (scene.ClearDepth) {
@@ -56,7 +65,7 @@ void PickingPass::Draw(RenderScene& scene)
}
m_Camera = scene.Camera;
for (auto &job : scene.OpaqueObjects) {
for (auto &job : scene.Jobs.OpaqueObjects) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
@@ -83,17 +92,86 @@ void PickingPass::Draw(RenderScene& scene)
m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo;
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
if (modelJob->Model->IsSkinned())
{
m_PickingSkinnedProgram->Bind();
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) {
if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) {
if (modelJob->Animation != nullptr) {
std::vector<glm::mat4> frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime);
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
}
} else {
m_PickingProgram->Bind();
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int)));
}
}
for (auto &job : scene.Jobs.TransparentObjects) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] };
PickingInfo pickInfo;
pickInfo.Entity = modelJob->Entity;
pickInfo.World = modelJob->World;
pickInfo.Camera = scene.Camera;
auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera));
if (color != m_EntityColors.end()) {
pickColor[0] = color->second[0];
pickColor[1] = color->second[1];
} else {
m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]);
if (m_ColorCounter[0] > 255) {
m_ColorCounter[0] = 0;
m_ColorCounter[1] += 1;
} else {
m_ColorCounter[0] += 1;
}
}
m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo;
if (modelJob) {
if (modelJob->Model->IsSkinned()) {
m_PickingSkinnedProgram->Bind();
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_PickingProgram->Bind();
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
}
glBindVertexArray(modelJob->Model->VAO);
@@ -102,7 +180,7 @@ void PickingPass::Draw(RenderScene& scene)
}
}
for (auto &job : scene.TransparentObjects) {
for (auto &job : scene.Jobs.OpaqueShieldedObjects) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
@@ -129,19 +207,95 @@ void PickingPass::Draw(RenderScene& scene)
m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo;
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
if(modelJob->Model->IsSkinned()) {
m_PickingSkinnedProgram->Bind();
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) {
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
if (modelJob->Animation != nullptr) {
std::vector<glm::mat4> frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime);
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
} else {
m_PickingProgram->Bind();
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int)));
}
}
for (auto &job : scene.Jobs.TransparentShieldedObjects) {
auto modelJob = std::dynamic_pointer_cast<ModelJob>(job);
if (modelJob) {
int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] };
PickingInfo pickInfo;
pickInfo.Entity = modelJob->Entity;
pickInfo.World = modelJob->World;
pickInfo.Camera = scene.Camera;
auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera));
if (color != m_EntityColors.end()) {
pickColor[0] = color->second[0];
pickColor[1] = color->second[1];
} else {
m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]);
if (m_ColorCounter[0] > 255) {
m_ColorCounter[0] = 0;
m_ColorCounter[1] += 1;
} else {
m_ColorCounter[0] += 1;
}
}
m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo;
if (modelJob->Model->IsSkinned()) {
m_PickingSkinnedProgram->Bind();
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) {
std::vector<glm::mat4> frameBones;
if (modelJob->AnimationOffset.animation != nullptr) {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset);
} else {
frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations);
}
glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0]));
}
} else {
m_PickingProgram->Bind();
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()));
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1])));
}
glBindVertexArray(modelJob->Model->VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer);
glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int)));
@@ -160,8 +314,8 @@ void PickingPass::ClearPicking()
{
m_PickingColorsToEntity.clear();
m_EntityColors.clear();
m_ColorCounter[0] = 1;
m_ColorCounter[1] = 0;
m_ColorCounter[0] = 0;
m_ColorCounter[1] = 1;
m_PickingBuffer.Bind();
glClearColor(0.f, 0.f, 0.f, 0.f);
+1 -1
View File
@@ -271,7 +271,7 @@ RawModelAssimp::RawModelAssimp(std::string fileName)
skelAnim.Keyframes.push_back(animationFrame);
}
m_Skeleton->Animations[animationName] = skelAnim;
m_Skeleton->Animations[animationName1] = skelAnim;
}
}
+208 -101
View File
@@ -34,13 +34,20 @@ void RawModelCustom::ReadMeshFile(std::string filePath)
ReadMeshFileHeader(offset, fileData);
ReadMesh(offset, fileData, fileByteSize);
}
delete fileData;
delete[] fileData;
}
void RawModelCustom::ReadMeshFileHeader(std::size_t& offset, char* fileData)
{
#ifdef BOOST_LITTLE_ENDIAN
m_Vertices.resize(static_cast<std::size_t>(*(unsigned int*)(fileData + offset)));
hasSkin = *(bool*)(fileData + offset);
offset += sizeof(bool);
if (hasSkin) {
m_SkinedVertices.resize(static_cast<std::size_t>(*(unsigned int*)(fileData + offset)));
}
else {
m_Vertices.resize(static_cast<std::size_t>(*(unsigned int*)(fileData + offset)));
}
offset += sizeof(unsigned int);
m_Indices.resize(static_cast<std::size_t>(*(unsigned int*)(fileData + offset)));
offset += sizeof(unsigned int);
@@ -57,12 +64,19 @@ void RawModelCustom::ReadMesh(std::size_t& offset, char* fileData, const unsigne
void RawModelCustom::ReadVertices(std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
{
#ifdef BOOST_LITTLE_ENDIAN
if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) {
throw Resource::FailedLoadingException("Reading vertices failed");
}
memcpy(&m_Vertices[0], fileData + offset, m_Vertices.size() * sizeof(Vertex));
offset += m_Vertices.size() * sizeof(Vertex);
if (hasSkin) {
if (offset + m_SkinedVertices.size() * sizeof(SkinedVertex) > fileByteSize) {
throw Resource::FailedLoadingException("Reading skined vertices failed");
}
memcpy(&m_SkinedVertices[0], fileData + offset, m_SkinedVertices.size() * sizeof(SkinedVertex));
offset += m_SkinedVertices.size() * sizeof(SkinedVertex);
} else {
if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) {
throw Resource::FailedLoadingException("Reading vertices failed");
}
memcpy(&m_Vertices[0], fileData + offset, m_Vertices.size() * sizeof(Vertex));
offset += m_Vertices.size() * sizeof(Vertex);
}
#else
#endif
}
@@ -102,14 +116,14 @@ void RawModelCustom::ReadMaterialFile(std::string filePath)
if (fileByteSize > 0) {
ReadMaterials(offset, fileData, fileByteSize);
}
delete fileData;
delete[] fileData;
}
void RawModelCustom::ReadMaterials(std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
{
#ifdef BOOST_LITTLE_ENDIAN
unsigned int* numMaterials = (unsigned int*)(fileData);
MaterialGroups.reserve(*numMaterials);
m_Materials.reserve(*numMaterials);
offset += sizeof(unsigned int);
for (unsigned int i = 0; i < *numMaterials; i++) {
@@ -121,83 +135,150 @@ void RawModelCustom::ReadMaterials(std::size_t& offset, char* fileData, const un
void RawModelCustom::ReadMaterialSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
{
MaterialGroup newMaterial;
MaterialProperties newMaterialProperty;
#ifdef BOOST_LITTLE_ENDIAN
if (offset + sizeof(unsigned int) * 4 > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material texture names length failed");
}
if (offset + sizeof(MaterialType) > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material Type failed");
}
MaterialType type = *(MaterialType*)(fileData + offset);
offset += sizeof(MaterialType);
unsigned int* nameLengths = (unsigned int*)(fileData + offset);
offset += sizeof(unsigned int) * 4;
switch (type) {
case MaterialType::Basic:
newMaterialProperty.material = new MaterialBasic();
ReadMaterialBasic(newMaterialProperty.material, offset, fileData, fileByteSize);
break;
case MaterialType::SplatMapping:
newMaterialProperty.material = new MaterialSplatMapping();
ReadMaterialSplatMapping(static_cast<MaterialSplatMapping*>(newMaterialProperty.material), offset, fileData, fileByteSize);
break;
case MaterialType::SingleTextures:
newMaterialProperty.material = new MaterialSingleTextures();
ReadMaterialSingleTexture(static_cast<MaterialSingleTextures*>(newMaterialProperty.material), offset, fileData, fileByteSize);
break;
default:
throw Resource::FailedLoadingException("Material contains an unknown MaterialType");
};
if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed");
}
newMaterial.SpecularExponent = *(float*)(fileData + offset);
offset += sizeof(float);
newMaterial.ReflectionFactor = *(float*)(fileData + offset);
offset += sizeof(float);
memcpy(&newMaterial.DiffuseColor[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
memcpy(&newMaterial.SpecularColor[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
memcpy(&newMaterial.IncandescenceColor[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
newMaterial.StartIndex = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
newMaterial.EndIndex = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
if (nameLengths[0] > 0) {
if (offset + nameLengths[0] > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material texture path failed");
}
newMaterial.TexturePath = "Textures/";
newMaterial.TexturePath += (fileData + offset);
newMaterial.TexturePath += ".png";
offset += nameLengths[0];
}
if (nameLengths[1] > 0) {
if (offset + nameLengths[1] > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material NormalMap path failed");
}
newMaterial.NormalMapPath = "Textures/";
newMaterial.NormalMapPath += (fileData + offset);
newMaterial.NormalMapPath += ".png";
offset += nameLengths[1];
}
if (nameLengths[2] > 0) {
if (offset + nameLengths[2] > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material SpecularMap path failed");
}
newMaterial.SpecularMapPath = "Textures/";
newMaterial.SpecularMapPath += (fileData + offset);
newMaterial.SpecularMapPath += ".png";
offset += nameLengths[2];
}
if (nameLengths[3] > 0) {
if (offset + nameLengths[3] > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material IncandescenceMap path failed");
}
newMaterial.IncandescenceMapPath = "Textures/";
newMaterial.IncandescenceMapPath += (fileData + offset);
newMaterial.IncandescenceMapPath += ".png";
offset += nameLengths[3];
}
newMaterialProperty.type = type;
#else
#endif
MaterialGroups.push_back(newMaterial);
m_Materials.push_back(newMaterialProperty);
}
void RawModelCustom::ReadMaterialBasic(RawModelCustom::MaterialBasic* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
{
if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed");
}
newMaterial->SpecularExponent = *(float*)(fileData + offset);
offset += sizeof(float);
newMaterial->ReflectionFactor = *(float*)(fileData + offset);
offset += sizeof(float);
memcpy(&newMaterial->DiffuseColor[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
memcpy(&newMaterial->SpecularColor[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
memcpy(&newMaterial->IncandescenceColor[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
newMaterial->StartIndex = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
newMaterial->EndIndex = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
}
void RawModelCustom::ReadMaterialSingleTexture(RawModelCustom::MaterialSingleTextures* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
{
ReadMaterialBasic(newMaterial, offset, fileData, fileByteSize);
if (offset + sizeof(unsigned char) * 4 > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material NumOfMaps failed");
}
unsigned char numberOfMaps[4];
memcpy(numberOfMaps, fileData + offset, sizeof(unsigned char) * 4);
offset += sizeof(unsigned char) * 4;
if (numberOfMaps[0] > 0)
{
ReadMaterialTextureProperties(newMaterial->ColorMap, offset, fileData, fileByteSize);
}
if (numberOfMaps[1] > 0)
{
ReadMaterialTextureProperties(newMaterial->SpecularMap, offset, fileData, fileByteSize);
}
if (numberOfMaps[2] > 0)
{
ReadMaterialTextureProperties(newMaterial->NormalMap, offset, fileData, fileByteSize);
}
if (numberOfMaps[3] > 0)
{
ReadMaterialTextureProperties(newMaterial->IncandescenceMap, offset, fileData, fileByteSize);
}
}
void RawModelCustom::ReadMaterialSplatMapping(RawModelCustom::MaterialSplatMapping* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
{
ReadMaterialBasic(newMaterial, offset, fileData, fileByteSize);
ReadMaterialTextureProperties(newMaterial->SplatMap, offset, fileData, fileByteSize);
if (offset + sizeof(unsigned char) * 4 > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material NumOfMaps failed");
}
unsigned char numberOfMaps[4];
memcpy(numberOfMaps, fileData + offset, sizeof(unsigned char) * 4);
offset += sizeof(unsigned char) * 4;
newMaterial->ColorMaps.resize(numberOfMaps[0]);
for (unsigned char i = 0; i < numberOfMaps[0]; i++)
{
ReadMaterialTextureProperties(newMaterial->ColorMaps[i], offset, fileData, fileByteSize);
}
newMaterial->SpecularMaps.resize(numberOfMaps[1]);
for (unsigned char i = 0; i < numberOfMaps[1]; i++)
{
ReadMaterialTextureProperties(newMaterial->SpecularMaps[i], offset, fileData, fileByteSize);
}
newMaterial->NormalMaps.resize(numberOfMaps[2]);
for (unsigned char i = 0; i < numberOfMaps[2]; i++)
{
ReadMaterialTextureProperties(newMaterial->NormalMaps[i], offset, fileData, fileByteSize);
}
newMaterial->IncandescenceMaps.resize(numberOfMaps[3]);
for (unsigned char i = 0; i < numberOfMaps[3]; i++)
{
ReadMaterialTextureProperties(newMaterial->IncandescenceMaps[i], offset, fileData, fileByteSize);
}
}
void RawModelCustom::ReadMaterialTextureProperties(RawModelCustom::TextureProperties& texture, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) {
unsigned int nameLength = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
if (nameLength > 0) {
if (offset + nameLength > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material texture path failed");
}
texture.TexturePath = "Textures/";
texture.TexturePath += (fileData + offset);
texture.TexturePath += ".png";
offset += nameLength;
if (offset + sizeof(glm::vec2) > fileByteSize) {
throw Resource::FailedLoadingException("Reading Material texture UVTiling failed");
}
memcpy(&texture.UVRepeat[0], fileData + offset, sizeof(glm::vec2));
offset += sizeof(glm::vec2);
}
}
void RawModelCustom::ReadAnimationFile(std::string filePath)
@@ -207,7 +288,9 @@ void RawModelCustom::ReadAnimationFile(std::string filePath)
std::ifstream in(filePath.c_str(), std::ios_base::binary | std::ios_base::ate);
if (!in.is_open()) {
//throw Resource::FailedLoadingException("Open animation file failed");
if (hasSkin) {
throw Resource::FailedLoadingException("Open animation file for a skinned mesh failed, unknown stuff will happen");
}
return;
}
@@ -233,7 +316,7 @@ void RawModelCustom::ReadAnimationFile(std::string filePath)
ReadAnimationBindPoses(offset, fileData, fileByteSize);
ReadAnimationClips(offset, fileData, fileByteSize, numAnimations);
}
delete fileData;
delete[] fileData;
}
void RawModelCustom::ReadAnimationBindPoses(std::size_t& offset, char* fileData, const unsigned int& fileByteSize)
@@ -318,32 +401,43 @@ void RawModelCustom::ReadAnimationClipSingle(std::size_t& offset, char* fileData
if (offset + sizeof(float) > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationClip duration failed");
}
newAnimation.Duration = *(float*)(fileData + offset);
offset += sizeof(float);
if (offset + sizeof(unsigned int) > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationClip NrOfKeyframes failed");
throw Resource::FailedLoadingException("Reading AnimationClip numberOfJointFrames failed");
}
unsigned int nrOfKeyframes = *(unsigned int*)(fileData + offset);
unsigned int numberOfJointFrames = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
if (offset + sizeof(unsigned int) > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationClip NrOfJoints failed");
}
unsigned int nrOfJoints = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
for (unsigned int i = 0; i < numberOfJointFrames; i++) {
if (offset + sizeof(unsigned int) > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationClip JointID failed");
}
int jointID = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
newAnimation.Keyframes.reserve(nrOfKeyframes);
for (unsigned int i = 0; i < nrOfKeyframes; i++) {
ReadAnimationKeyFrame(offset, fileData, fileByteSize, nrOfJoints, newAnimation);
if (offset + sizeof(unsigned int) > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationClip numberOFKeyFrames failed");
}
unsigned int numberOFKeyFrames = *(unsigned int*)(fileData + offset);
offset += sizeof(unsigned int);
if (numberOFKeyFrames > 0) {
newAnimation.JointAnimations[jointID].reserve(numberOFKeyFrames);
for (unsigned int j = 0; j < numberOFKeyFrames; j++) {
ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation.JointAnimations[jointID]);
}
}
}
m_Skeleton->Animations[newAnimation.Name] = newAnimation;
//m_Skeleton->Animations[newAnimation.Name].KeyFrameAmount = nrOfKeyframes;
#else
#endif
}
void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int numberOfJoints, Skeleton::Animation& animation)
void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, std::vector<Skeleton::Animation::Keyframe>& animation)
{
Skeleton::Animation::Keyframe newKeyFrame;
@@ -359,17 +453,27 @@ void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData,
newKeyFrame.Time = *(float*)(fileData + offset);
offset += sizeof(float);
if (offset + sizeof(Skeleton::Animation::Keyframe::BoneProperty) * numberOfJoints> fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationKeyFrame joints failed");
if (offset + sizeof(float) * 3 > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationKeyFrame Position failed");
}
memcpy(&newKeyFrame.BoneProperties.Position[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
Skeleton::Animation::Keyframe::BoneProperty newBone;
for (unsigned int i = 0; i < numberOfJoints; i++) {
memcpy(&newBone, (fileData + offset), sizeof(Skeleton::Animation::Keyframe::BoneProperty));
offset += sizeof(Skeleton::Animation::Keyframe::BoneProperty);
newKeyFrame.BoneProperties[newBone.ID] = newBone;
if (offset + sizeof(float) * 4 > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationKeyFrame Rotation failed");
}
animation.Keyframes.push_back(newKeyFrame);
memcpy(&newKeyFrame.BoneProperties.Rotation[0], fileData + offset, sizeof(float) * 4);
offset += sizeof(float) * 4;
if (offset + sizeof(float) * 3 > fileByteSize) {
throw Resource::FailedLoadingException("Reading AnimationKeyFrame Scale failed");
}
memcpy(&newKeyFrame.BoneProperties.Scale[0], fileData + offset, sizeof(float) * 3);
offset += sizeof(float) * 3;
animation.push_back(newKeyFrame);
}
RawModelCustom::~RawModelCustom()
@@ -377,6 +481,9 @@ RawModelCustom::~RawModelCustom()
if (m_Skeleton != nullptr) {
delete m_Skeleton;
}
for (auto material : m_Materials) {
delete material.material;
}
}
#endif
+50 -9
View File
@@ -6,9 +6,10 @@ bool RenderState::Enable(GLenum cap)
//LOG_WARNING("Trying to enable somthing that is already enabled.");
return false;
}
m_ResetFunctions.push_back(std::bind(glDisable, cap));
glEnable(cap);
return !GLERROR("RenderState::Enable");
return !GLERROR("Enable");
}
bool RenderState::Disable(GLenum cap)
@@ -16,9 +17,10 @@ bool RenderState::Disable(GLenum cap)
if (!glIsEnabled(cap)) {
return false;
}
m_ResetFunctions.push_back(std::bind(glEnable, cap));
glDisable(cap);
return !GLERROR("RenderState::Disable");
return !GLERROR("Disable");
}
bool RenderState::CullFace(GLenum mode)
@@ -32,7 +34,7 @@ bool RenderState::CullFace(GLenum mode)
glGetIntegerv(GL_CULL_FACE_MODE, &original);
m_ResetFunctions.push_back(std::bind(glCullFace, original));
glCullFace(mode);
return !GLERROR("RenderState::CullFace");
return !GLERROR("CullFace");
}
bool RenderState::ClearColor(glm::vec4 color)
@@ -41,7 +43,7 @@ bool RenderState::ClearColor(glm::vec4 color)
glGetFloatv(GL_COLOR_CLEAR_VALUE, &original[0]);
m_ResetFunctions.push_back(std::bind(glClearColor, original[0], original[1], original[2], original[3]));
glClearColor(color.r, color.g, color.b, color.a);
return !GLERROR("RenderState::ClearColor");
return !GLERROR("ClearColor");
}
bool RenderState::BindFramebuffer(GLint framebuffer)
@@ -55,7 +57,7 @@ bool RenderState::BindFramebuffer(GLint framebuffer)
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, originalDraw);
});
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
return !GLERROR("RenderState::BindBuffer");
return !GLERROR("BindBuffer");
}
@@ -67,7 +69,7 @@ bool RenderState::BlendEquation(GLenum mode)
glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &originalAlpha);
m_ResetFunctions.push_back(std::bind(glBlendEquationSeparate, originalRGB, originalAlpha));
glBlendEquation(mode);
return !GLERROR("RenderState::BlendEquation");
return !GLERROR("BlendEquation");
}
bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor)
@@ -82,7 +84,46 @@ bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor)
glGetIntegerv(GL_BLEND_DST_ALPHA, &originalDestAlpha);
m_ResetFunctions.push_back(std::bind(glBlendFuncSeparate, originalSrcRGB, originalSrcAlpha, originalDestRGB, originalDestAlpha));
glBlendFunc(sfactor, dfactor);
return !GLERROR("RenderState::BlendFunc");
return !GLERROR("BlendFunc");
}
bool RenderState::StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass)
{
GLint originalSFail;
glGetIntegerv(GL_STENCIL_FAIL, &originalSFail);
GLint originalDPFail;
glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &originalDPFail);
GLint originalDPPass;
glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &originalDPPass);
m_ResetFunctions.push_back(std::bind(glStencilOp, originalSFail, originalDPFail, originalDPPass));
glStencilOp(sfail, dpfail, dppass);
return !GLERROR("StencilOp");
}
bool RenderState::StencilFunc(GLenum func, GLint ref, GLuint mask)
{
GLint originalFunc;
glGetIntegerv(GL_STENCIL_FUNC, &originalFunc);
GLint originalRef;
glGetIntegerv(GL_STENCIL_REF, &originalRef);
GLint originalMask;
glGetIntegerv(GL_STENCIL_VALUE_MASK, &originalMask);
m_ResetFunctions.push_back(std::bind(glStencilFunc, originalFunc, originalRef, originalMask));
glStencilFunc(func, ref, mask);
return !GLERROR("StencilFunc");
}
bool RenderState::StencilMask(GLuint mask)
{
GLint originalMask;
glGetIntegerv(GL_STENCIL_WRITEMASK, &originalMask);
m_ResetFunctions.push_back(std::bind(glStencilMask, mask));
glStencilMask(mask);
return !GLERROR("StencilMask");
}
bool RenderState::DepthMask(GLboolean flag)
@@ -91,12 +132,12 @@ bool RenderState::DepthMask(GLboolean flag)
glGetBooleanv(GL_DEPTH_WRITEMASK, &original);
m_ResetFunctions.push_back(std::bind(glDepthMask, original));
glDepthMask(flag);
return !GLERROR("RenderState::DepthMask");
return !GLERROR("DepthMask");
}
RenderState::~RenderState()
{
for (auto& f : m_ResetFunctions) {
for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) {
f();
}
}
+77 -32
View File
@@ -1,9 +1,12 @@
#include "Rendering/RenderSystem.h"
#include "Collision/Collision.h"
#include "Core/Frustum.h"
RenderSystem::RenderSystem(SystemParams params, const IRenderer* renderer, RenderFrame* renderFrame)
RenderSystem::RenderSystem(SystemParams params, const IRenderer* renderer, RenderFrame* renderFrame, Octree<EntityAABB>* frustumCullOctree)
: System(params)
, m_Renderer(renderer)
, m_RenderFrame(renderFrame)
, m_Octree(frustumCullOctree)
{
EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &RenderSystem::OnSetCamera);
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &RenderSystem::OnInputCommand);
@@ -39,14 +42,15 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity)
return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera);
}
void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& opaqueJobs, std::list<std::shared_ptr<RenderJob>>& transparentJobs)
void RenderSystem::fillModels(RenderScene::Queues &Jobs)
{
auto models = m_World->GetComponents("Model");
if (models == nullptr) {
return;
}
Frustum frustum(m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix());
std::vector<EntityAABB> seenEntities;
m_Octree->ObjectsInFrustum(frustum, seenEntities);
for (auto& cModel : *models) {
for (auto& seenEntity : seenEntities) {
EntityWrapper entity = seenEntity.Entity;
ComponentWrapper cModel = entity["Model"];
bool visible = cModel["Visible"];
if (!visible) {
continue;
@@ -56,17 +60,15 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& opaqueJobs,
continue;
}
EntityWrapper entity(m_World, cModel.EntityID);
// Only render children of a camera if that camera is currently active
if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) {
continue;
}
if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) {
continue;
}
// Hide things parented to local player if they have the HiddenFromLocalPlayer component
if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) {
continue;
}
if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) {
continue;
}
Model* model;
try {
@@ -91,7 +93,9 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& opaqueJobs,
}
glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World);
//Loop through all materialgroups of a model
for (auto matGroup : model->MaterialGroups()) {
//If the model has an explosioneffect component, we will add an explosioneffectjob
if (m_World->HasComponent(cModel.EntityID, "ExplosionEffect")) {
auto explosionEffectComponent = m_World->GetComponent(cModel.EntityID, "ExplosionEffect");
std::shared_ptr<ExplosionEffectJob> explosionEffectJob = std::shared_ptr<ExplosionEffectJob>(new ExplosionEffectJob(
@@ -105,14 +109,33 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& opaqueJobs,
fillColor,
fillPercentage
));
if(explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) {
cModel["Transparent"] = true;
}
if (m_World->HasComponent(cModel.EntityID, "Shield")){
explosionEffectJob->CalculateHash();
Jobs.ShieldObjects.push_back(explosionEffectJob);
} else if (m_World->HasComponent(cModel.EntityID, "Shielded")
|| m_World->HasComponent(cModel.EntityID, "Player")) {
if (cModel["Transparent"]) {
transparentJobs.push_back(explosionEffectJob);
if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) {
cModel["Transparent"] = true;
}
if (cModel["Transparent"]) {
Jobs.TransparentShieldedObjects.push_back(explosionEffectJob);
} else {
explosionEffectJob->CalculateHash();
Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob);
}
} else {
opaqueJobs.push_back(explosionEffectJob);
if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) {
cModel["Transparent"] = true;
}
if (cModel["Transparent"]) {
Jobs.TransparentObjects.push_back(explosionEffectJob);
} else {
explosionEffectJob->CalculateHash();
Jobs.OpaqueObjects.push_back(explosionEffectJob);
}
}
} else {
std::shared_ptr<ModelJob> modelJob = std::shared_ptr<ModelJob>(new ModelJob(
@@ -125,13 +148,33 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& opaqueJobs,
fillColor,
fillPercentage
));
if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) {
cModel["Transparent"] = true;
}
if (cModel["Transparent"]) {
transparentJobs.push_back(modelJob);
if (m_World->HasComponent(cModel.EntityID, "Shield")) {
modelJob->CalculateHash();
Jobs.ShieldObjects.push_back(modelJob);
} else if (m_World->HasComponent(cModel.EntityID, "Shielded")
|| m_World->HasComponent(cModel.EntityID, "Player")) {
if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) {
cModel["Transparent"] = true;
}
if (cModel["Transparent"]) {
Jobs.TransparentShieldedObjects.push_back(modelJob);
} else {
modelJob->CalculateHash();
Jobs.OpaqueShieldedObjects.push_back(modelJob);
}
} else {
opaqueJobs.push_back(modelJob);
if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) {
cModel["Transparent"] = true;
}
if (cModel["Transparent"]) {
Jobs.TransparentObjects.push_back(modelJob);
} else {
modelJob->CalculateHash();
Jobs.OpaqueObjects.push_back(modelJob);
}
}
}
}
@@ -195,7 +238,7 @@ void RenderSystem::fillText(std::list<std::shared_ptr<RenderJob>>& jobs, World*
if (texts == nullptr) {
return;
}
for (auto& textComponent : *texts) {
bool visible = textComponent["Visible"];
if (!visible) {
@@ -250,10 +293,12 @@ void RenderSystem::Update(double dt)
scene.AmbientColor = (glm::vec4)(*cSceneLight->begin())["AmbientColor"];
}
fillModels(scene.OpaqueObjects, scene.TransparentObjects);
fillPointLights(scene.PointLightJobs, m_World);
fillDirectionalLights(scene.DirectionalLightJobs, m_World);
fillText(scene.TextJobs, m_World);
fillModels(scene.Jobs);
fillPointLights(scene.Jobs.PointLight, m_World);
//TODO: Make sure all objects needed are also sorted.
scene.Jobs.OpaqueObjects.sort();
fillDirectionalLights(scene.Jobs.DirectionalLight, m_World);
fillText(scene.Jobs.Text, m_World);
m_RenderFrame->Add(scene);
}
+10 -4
View File
@@ -93,7 +93,7 @@ void Renderer::Update(double dt)
void Renderer::Draw(RenderFrame& frame)
{
ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0Gaussian\0Picking");
ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking");
//clear buffer 0
glClearColor(0.f, 0.f, 0.f, 0.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@@ -120,7 +120,7 @@ void Renderer::Draw(RenderFrame& frame)
}
m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture());
if (m_DebugTextureToDraw == 0) {
m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure);
m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure);
}
if (m_DebugTextureToDraw == 1) {
m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture());
@@ -129,9 +129,15 @@ void Renderer::Draw(RenderFrame& frame)
m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTexture());
}
if (m_DebugTextureToDraw == 3) {
m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture());
m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTextureLowRes());
}
if (m_DebugTextureToDraw == 4) {
m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTextureLowRes());
}
if (m_DebugTextureToDraw == 5) {
m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture());
}
if (m_DebugTextureToDraw == 6) {
m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture());
}
@@ -154,7 +160,7 @@ void Renderer::InitializeTextures()
void Renderer::SortRenderJobsByDepth(RenderScene &scene)
{
//Sort all forward jobs so transparency is good.
scene.TransparentObjects.sort(Renderer::DepthSort);
scene.Jobs.TransparentObjects.sort(Renderer::DepthSort);
}
void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type)
+478 -46
View File
@@ -39,66 +39,494 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name)
}
}
std::vector<glm::mat4> Skeleton::GetFrameBones(const Animation& animation, double time, bool noRootMotion /*= false*/)
std::vector<glm::mat4> Skeleton::GetFrameBones(std::vector<AnimationData> animations, bool noRootMotion /*= false*/)
{
// HACK: Animation wrap-around
while (time < 0) {
time += animation.Duration;
}
while (time > animation.Duration) {
time -= animation.Duration;
}
if (animations.size() <= 0) {
std::vector<glm::mat4> finalMatrices;
for (auto& b : Bones) {
finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix);
}
return finalMatrices;
}
int currentKeyframeIndex = GetKeyframe(animation, time);
std::map<int, glm::mat4> frameBones;
AccumulateBoneTransforms(true, animations, frameBones, RootBone, glm::mat4(1));
const Animation::Keyframe& currentFrame = animation.Keyframes[currentKeyframeIndex];
const Animation::Keyframe& nextFrame = animation.Keyframes[(currentKeyframeIndex + 1) % animation.Keyframes.size()];
double alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time);
//auto animationFrame = Animations[""].Keyframes[frame];
std::map<int, glm::mat4> frameBones;
AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, static_cast<float>(alpha), frameBones, RootBone, glm::mat4(1));
std::vector<glm::mat4> finalMatrices;
for (auto &kv : frameBones) {
finalMatrices.push_back(kv.second);
}
return finalMatrices;
std::vector<glm::mat4> finalMatrices;
for (auto &kv : frameBones) {
finalMatrices.push_back(kv.second);
}
return finalMatrices;
}
void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe &currentFrame, const Animation::Keyframe &nextFrame, float progress, std::map<int, glm::mat4> &boneMatrices, const Bone* bone, glm::mat4 parentMatrix)
std::vector<glm::mat4> Skeleton::GetFrameBones(std::vector<AnimationData> animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/)
{
if (animations.size() <= 0 || animationOffset.animation == nullptr) {
std::vector<glm::mat4> finalMatrices;
for (auto& b : Bones) {
finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix);
}
return finalMatrices;
}
std::map<int, glm::mat4> frameBones;
AccumulateBoneTransforms(true, animations, animationOffset, frameBones, RootBone, glm::mat4(1));
std::vector<glm::mat4> finalMatrices;
for (auto &kv : frameBones) {
finalMatrices.push_back(kv.second);
}
return finalMatrices;
}
/*
void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map<int, glm::mat4>& boneMatrices, const Bone* bone, glm::mat4 parentMatrix)
{
glm::mat4 boneMatrix;
if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) {
Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID);
Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID);
Animation::Keyframe currentFrame;
Animation::Keyframe nextFrame;
glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress;
glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress);
glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress;
if(animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) {
std::vector<Animation::Keyframe> boneKeyFrames = animation->JointAnimations.at(bone->ID);
// Flag for no root motion
if (bone == RootBone && noRootMotion) {
positionInterp.x = 0;
positionInterp.z = 0;
}
if(boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone
for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame
if (time >= boneKeyFrames.at(index).Time) {
currentFrame = boneKeyFrames.at(index);
nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size());
break;
}
}
float progress;
if(nextFrame.Index == 0) {
progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time);
} else {
progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time);
}
boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp));
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
} else {
if (bone->Parent) {
boneMatrix = parentMatrix; // * glm::inverse(bone->OffsetMatrix);
if (progress > 1.0f || progress < 0.0f) {
LOG_INFO("Progress: %f", progress);
progress = glm::clamp(progress, 0.0f, 1.0f);
}
Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties;
Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties;
glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress;
glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress);
glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress;
// Flag for no root motion
if (bone == RootBone && noRootMotion) {
positionInterp.x = 0;
positionInterp.z = 0;
}
boneMatrix = parentMatrix *(glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp));
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
} else { // 1 keyframes for the current bone
currentFrame = boneKeyFrames.at(0);
boneMatrix = parentMatrix *(glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale));
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
}
boneMatrices[bone->ID] = boneMatrix; // * bone->OffsetMatrix;
}
} else { // 0 keyframes for the current bone
for (auto &child : bone->Children) {
std::string name = child->Name;
AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, progress, boneMatrices, child, boneMatrix);
}
// LOG_INFO("%s Has no keyframe", bone->Name.c_str());
if (bone->Parent) {
boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix;
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
} else {
boneMatrix = glm::inverse(bone->OffsetMatrix);
boneMatrices[bone->ID] = parentMatrix;
}
}
for (auto &child : bone->Children) {
AccumulateBoneTransforms(noRootMotion, animation, time, boneMatrices, child, boneMatrix);
}
}
*/
void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector<AnimationData> animations, std::map<int, glm::mat4>& boneMatrices, const Bone* bone, glm::mat4 parentMatrix)
{
glm::mat4 boneMatrix;
std::vector<JointFrameTransform> JointTransforms;
for (const AnimationData animationData : animations) {
const Animation* animation = animationData.animation;
const float time = animationData.time;
JointFrameTransform jointTransform;
jointTransform.Weight = animationData.weight;;
if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) {
std::vector<Animation::Keyframe> boneKeyFrames = animation->JointAnimations.at(bone->ID);
Animation::Keyframe currentFrame;
Animation::Keyframe nextFrame;
if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone
for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame
if (time >= boneKeyFrames.at(index).Time) {
currentFrame = boneKeyFrames.at(index);
nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size());
break;
}
}
float progress;
if (nextFrame.Index == 0) {
progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time);
} else {
progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time);
}
if (progress > 1.0f || progress < 0.0f) {
LOG_INFO("Progress: %f", progress);
progress = glm::clamp(progress, 0.0f, 1.0f);
}
Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties;
Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties;
jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress;
jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress);
jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress;
// Flag for no root motion
if (bone == RootBone && noRootMotion) {
jointTransform.PositionInterp.x = 0;
jointTransform.PositionInterp.z = 0;
}
JointTransforms.push_back(jointTransform);
} else { // 1 keyframes for the current bone
currentFrame = boneKeyFrames.at(0);
jointTransform.PositionInterp = currentFrame.BoneProperties.Position;
jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation;
jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale;
JointTransforms.push_back(jointTransform);
}
} else { // 0 keyframes for the current bone
}
}
if(JointTransforms.size() <= 0) {
if (bone->Parent) {
boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix;
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
} else {
boneMatrix = glm::inverse(bone->OffsetMatrix);
boneMatrices[bone->ID] = parentMatrix;
}
} else if (JointTransforms.size() == 1) {
boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp));
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
} else {
glm::vec3 finalPosInterp;
glm::quat finalRotInterp;
glm::vec3 finalScaleInterp;
float totalWeight = 0;
for (JointFrameTransform jointTransform : JointTransforms) {
totalWeight += jointTransform.Weight;
}
for (JointFrameTransform jointTransform : JointTransforms)
{
if(jointTransform.Weight == 1.0f) {
finalPosInterp = jointTransform.PositionInterp;
finalRotInterp = jointTransform.RotationInterp;
finalScaleInterp = jointTransform.ScaleInterp;
break;
} else {
finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight);
finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight));
finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight);
}
}
boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp));
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
}
for (auto &child : bone->Children) {
AccumulateBoneTransforms(noRootMotion, animations, boneMatrices, child, boneMatrix);
}
}
void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector<AnimationData> animations, AnimationOffset animationOffset, std::map<int, glm::mat4>& boneMatrices, const Bone* bone, glm::mat4 parentMatrix)
{
glm::mat4 boneMatrix;
std::vector<JointFrameTransform> JointTransforms;
for (const AnimationData animationData : animations) {
const Animation* animation = animationData.animation;
const float time = animationData.time;
JointFrameTransform jointTransform;
jointTransform.Weight = animationData.weight;;
if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) {
std::vector<Animation::Keyframe> boneKeyFrames = animation->JointAnimations.at(bone->ID);
Animation::Keyframe currentFrame;
Animation::Keyframe nextFrame;
if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone
for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame
if (time >= boneKeyFrames.at(index).Time) {
currentFrame = boneKeyFrames.at(index);
nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size());
break;
}
}
float progress;
if (nextFrame.Index == 0) {
progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time);
} else {
progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time);
}
if (progress > 1.0f || progress < 0.0f) {
LOG_INFO("Progress: %f", progress);
progress = glm::clamp(progress, 0.0f, 1.0f);
}
Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties;
Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties;
jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress;
jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress);
jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress;
// Flag for no root motion
if (bone == RootBone && noRootMotion) {
jointTransform.PositionInterp.x = 0;
jointTransform.PositionInterp.z = 0;
}
JointTransforms.push_back(jointTransform);
} else { // 1 keyframes for the current bone
currentFrame = boneKeyFrames.at(0);
jointTransform.PositionInterp = currentFrame.BoneProperties.Position;
jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation;
jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale;
JointTransforms.push_back(jointTransform);
}
} else { // 0 keyframes for the current bone
}
}
glm::mat4 offset = GetOffsetTransform(bone, animationOffset);
if (JointTransforms.size() == 0) {
if (bone->Parent) {
if (offset != glm::mat4(1)) {
boneMatrix = parentMatrix * offset;// *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix));
} else {
boneMatrix = parentMatrix *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix));
}
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
} else {
boneMatrix = offset * glm::inverse(bone->OffsetMatrix);
boneMatrices[bone->ID] = parentMatrix;
}
} else {
glm::vec3 finalPosInterp;
glm::quat finalRotInterp;
glm::vec3 finalScaleInterp;
float totalWeight = 0;
for (JointFrameTransform jointTransform : JointTransforms) {
totalWeight += jointTransform.Weight;
}
for (JointFrameTransform jointTransform : JointTransforms) {
if (jointTransform.Weight == 1.0f) {
finalPosInterp = jointTransform.PositionInterp;
finalRotInterp = jointTransform.RotationInterp;
finalScaleInterp = jointTransform.ScaleInterp;
break;
} else {
finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight);
finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight));
finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight);
}
}
if (offset != glm::mat4(1)) {
boneMatrix = parentMatrix * ((glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) + offset);
} else {
boneMatrix = parentMatrix * (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp));
}
boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix;
}
for (auto &child : bone->Children) {
AccumulateBoneTransforms(noRootMotion, animations, animationOffset, boneMatrices, child, boneMatrix);
}
}
glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset)
{
const Animation* animation = animationOffset.animation;
float time = animationOffset.time;
glm::vec3 position = glm::vec3(0);
glm::quat rotation = glm::quat();
glm::vec3 scale = glm::vec3(1);
if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) {
std::vector<Animation::Keyframe> boneKeyFrames = animation->JointAnimations.at(bone->ID);
Animation::Keyframe currentFrame;
Animation::Keyframe nextFrame;
if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone
for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame
if (time >= boneKeyFrames.at(index).Time) {
currentFrame = boneKeyFrames.at(index);
nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size());
break;
}
}
float progress;
if (nextFrame.Index == 0) {
progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time);
} else {
progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time);
}
if (progress > 1.0f || progress < 0.0f) {
LOG_INFO("Progress: %f", progress);
progress = glm::clamp(progress, 0.0f, 1.0f);
}
Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties;
Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties;
position = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress;
rotation = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress);
scale = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress;
} else { // 1 keyframes for the current bone
currentFrame = boneKeyFrames.at(0);
position = currentFrame.BoneProperties.Position;
rotation = currentFrame.BoneProperties.Rotation;
scale = currentFrame.BoneProperties.Scale;
}
}
return (glm::translate(position) * glm::toMat4(rotation) * glm::scale(scale));
}
glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix)
{
glm::mat4 boneMatrix;
Animation::Keyframe currentFrame;
Animation::Keyframe nextFrame;
if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) {
std::vector<Animation::Keyframe> boneKeyFrames = animation->JointAnimations.at(bone->ID);
if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone
for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame
if (time >= boneKeyFrames.at(index).Time) {
currentFrame = boneKeyFrames.at(index);
nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size());
break;
}
}
float progress;
if (nextFrame.Index == 0) {
progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time);
} else {
progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time);
}
if (progress > 1.0f || progress < 0.0f) {
LOG_INFO("Progress %f", progress);
progress = glm::clamp(progress, 0.0f, 1.0f);
}
Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties;
Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties;
glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress;
glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress);
glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress;
boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * childMatrix;
} else { // 1 keyframes for the current bone
currentFrame = boneKeyFrames.at(0);
boneMatrix = (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)) * childMatrix;
}
} else { // 0 keyframes for the current bone
if (bone->Parent) {
boneMatrix = bone->Parent->OffsetMatrix * glm::inverse(bone->OffsetMatrix) * childMatrix;
} else {
boneMatrix = glm::inverse(bone->OffsetMatrix) * childMatrix;
}
}
if (bone->Parent) {
return GetBoneTransform(bone->Parent, animation, time, boneMatrix);
} else {
return boneMatrix;
}
}
int Skeleton::GetBoneID(std::string name)
@@ -134,11 +562,13 @@ void Skeleton::PrintSkeleton(const Bone* bone, int depthCount)
int Skeleton::GetKeyframe(const Animation& animation, double time)
{
/*
if (time < 0) {
time = 0;
}
if (time >= animation.Duration) {
return animation.Keyframes.size() - 1;
return animation..size() - 1;
}
for (int keyframe = 0; keyframe < animation.Keyframes.size(); ++keyframe) {
@@ -146,6 +576,8 @@ int Skeleton::GetKeyframe(const Animation& animation, double time)
return (keyframe - 1) % animation.Keyframes.size();
}
}
*/
return 0;
}
+1 -1
View File
@@ -35,7 +35,7 @@ void TextPass::Draw(RenderScene& scene, FrameBuffer& frameBuffer)
{
GLERROR("Derp1");
TextPassState* state = new TextPassState(frameBuffer.GetHandle());
for (auto &job : scene.TextJobs) {
for (auto &job : scene.Jobs.Text) {
auto textJob = std::dynamic_pointer_cast<TextJob>(job);
if (textJob) {
+374
View File
@@ -0,0 +1,374 @@
#include "Sound/SoundManager.h"
SoundManager::SoundManager(World* world, EventBroker* eventBroker)
{
ConfigFile* config = ResourceManager::Load<ConfigFile>("Config.ini");
m_EventBroker = eventBroker;
m_World = world;
m_BGMVolumeChannel = config->Get<float>("Sound.BGMVolume", 1.f);
m_SFXVolumeChannel = config->Get<float>("Sound.SFXVolume", 1.f);
initOpenAL();
alSpeedOfSound(340.29f);
alDistanceModel(AL_LINEAR_DISTANCE);
alDopplerFactor(1);
EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnEntity, &SoundManager::OnPlaySoundOnEntity);
EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnPosition, &SoundManager::OnPlaySoundOnPosition);
EVENT_SUBSCRIBE_MEMBER(m_EPlayBackgroundMusic, &SoundManager::OnPlayBackgroundMusic);
EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundManager::OnStopSound);
EVENT_SUBSCRIBE_MEMBER(m_EPauseSound, &SoundManager::OnPauseSound);
EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundManager::OnContinueSound);
EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundManager::OnSetBGMGain);
EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundManager::OnSetSFXGain);
EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundManager::OnPause);
EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundManager::OnResume);
EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundManager::OnComponentAttached);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundManager::OnPlayerSpawned);
EVENT_SUBSCRIBE_MEMBER(m_EPlayQueueOnEntity, &SoundManager::OnPlayQueueOnEntity);
}
SoundManager::~SoundManager()
{
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 SoundManager::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 SoundManager::Update(double dt)
{
m_EventBroker->Process<SoundManager>();
deleteInactiveEmitters(); // can be optimized with "EEntityDeleted"
updateEmitters(dt);
updateListener(dt);
// Editor debug info
ImGui::SliderFloat("BGM", &m_BGMVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f);
ImGui::SliderFloat("SFX", &m_SFXVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f);
}
void SoundManager::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 SoundManager::updateEmitters(double dt)
{
std::unordered_map<EntityID, Source*>::iterator it;
for (it = m_Sources.begin(); it != m_Sources.end(); it++) {
// Get previous pos
if (!m_World->ValidEntity(it->first)) {
return;
}
if (!m_World->HasComponent(it->first, "SoundEmitter"))
return;
glm::vec3 previousPos;
alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z);
// Get next pos
if (!m_World->HasComponent(it->first, "Transform"))
return;
if (!m_World->ValidEntity(m_World->GetParent(it->first))) {
return;
}
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);
auto emitter = m_World->GetComponent(it->first, "SoundEmitter");
setSoundProperties(it->second, &emitter);
// 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 SoundManager::updateListener(double dt)
{
// Should only be one listener.
auto listenerComponents = m_World->GetComponents("Listener");
if (listenerComponents == nullptr || !m_LocalPlayer.Valid()) {
return;
}
for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) {
EntityWrapper listener(m_World, (*it).EntityID);
if (!listener.Valid()) {
break;
}
if (listener.IsChildOf(m_LocalPlayer) || listener == m_LocalPlayer) {
glm::vec3 previousPos;
alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos
glm::vec3 nextPos = Transform::AbsolutePosition(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(listener)));
break;
}
}
}
Source* SoundManager::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 SoundManager::playSound(Source* source)
{
alSourcei(source->ALsource, AL_BUFFER, source->SoundResource->Buffer());
alSourcePlay(source->ALsource);
}
void SoundManager::playQueue(QueuedBuffers qb)
{
for (int i = 0; i < qb.second.size(); i++) {
alSourceQueueBuffers(qb.first, 1, &qb.second[i]);
}
alSourcePlay(qb.first);
}
void SoundManager::stopSound(Source* source)
{
alSourceStop(source->ALsource);
}
bool SoundManager::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e)
{
Source* source = createSource(e.FilePath);
source->Type = SoundType::SFX;
EntityID child = m_World->CreateEntity(e.EmitterID);
m_World->AttachComponent(child, "Transform");
m_World->AttachComponent(child, "SoundEmitter");
m_Sources[child] = source;
playSound(source);
return false;
}
bool SoundManager::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;
source->Type = SoundType::SFX;
m_Sources[emitterID] = source;
playSound(source);
return true;
}
bool SoundManager::OnPauseSound(const Events::PauseSound & e)
{
alSourcePause(m_Sources[e.EmitterID]->ALsource);
return true;
}
bool SoundManager::OnStopSound(const Events::StopSound & e)
{
alSourceStop(m_Sources[e.EmitterID]->ALsource);
return true;
}
bool SoundManager::OnContinueSound(const Events::ContinueSound & e)
{
alSourcePlay(m_Sources[e.EmitterID]->ALsource);
return true;
}
bool SoundManager::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e)
{
auto listenerComponents = m_World->GetComponents("Listener");
for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) {
if ((*it).EntityID != m_LocalPlayer.ID) {
break;
}
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;
setSoundProperties(source, &emitter);
m_Sources[emitterChild] = source;
playSound(source);
}
return true;
}
bool SoundManager::OnSetBGMGain(const Events::SetBGMGain & e)
{
m_BGMVolumeChannel = e.Gain;
return true;
}
bool SoundManager::OnSetSFXGain(const Events::SetSFXGain & e)
{
m_SFXVolumeChannel = e.Gain;
return true;
}
bool SoundManager::OnComponentAttached(const Events::ComponentAttached & e)
{
if (e.Component.Info.Name == "SoundEmitter") {
auto component = m_World->GetComponent(e.Entity.ID, "SoundEmitter");
Source* source = createSource(component["FilePath"]);
m_Sources[e.Entity.ID] = source;
}
return false;
}
bool SoundManager::OnPause(const Events::Pause & e)
{
for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) {
alSourcePause(it->second->ALsource);
}
return false;
}
bool SoundManager::OnResume(const Events::Resume &e)
{
for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) {
alSourcePlay(it->second->ALsource);
}
return false;
}
bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned &e)
{
if (e.PlayerID == -1) { // Local player
m_LocalPlayer = e.Player;
return true;
}
return false;
}
bool SoundManager::OnPlayQueueOnEntity(const Events::PlayQueueOnEntity &e)
{
Source* source = createSource(*e.FilePaths.begin());
std::vector<ALuint> buffers;
buffers.push_back(source->SoundResource->Buffer());
source->Type = SoundType::BGM;
std::vector<std::string>::const_iterator it;
for (it = e.FilePaths.begin() + 1; it != e.FilePaths.end(); it++) {
buffers.push_back(ResourceManager::Load<Sound>(*it)->Buffer());
}
playQueue(QueuedBuffers(source->ALsource, buffers));
return true;
}
ALenum SoundManager::getSourceState(ALuint source)
{
ALenum state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
return state;
}
void SoundManager::setGain(Source * source, float gain)
{
alSourcef(source->ALsource, AL_GAIN, gain);
}
void SoundManager::setSoundProperties(Source* source, ComponentWrapper* soundComponent)
{
float gain = (source->Type == SoundType::SFX) ? m_SFXVolumeChannel : m_BGMVolumeChannel;
alSourcef(source->ALsource, AL_GAIN, (float)(double)(*soundComponent)["Gain"] * gain);
alSourcef(source->ALsource, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]);
alSourcei(source->ALsource, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO
alSourcef(source->ALsource, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]);
alSourcef(source->ALsource, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]);
alSourcef(source->ALsource, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]);
}
void SoundManager::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.");
}
}
void SoundManager::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);
}
-308
View File
@@ -1,308 +0,0 @@
#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;
if (it->second->Type == SoundType::SFX) {
gain = m_SFXVolumeChannel;
} else if (it->second->Type == SoundType::BGM) {
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.mesh"; // 360NoScope UnitCube
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.");
}
}