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

# Conflicts:
#	include/Engine/Network/Client.h
#	include/Engine/Network/Network.h
#	include/Engine/Network/Packet.h
#	include/Engine/Network/Server.h
#	src/Engine/Network/Client.cpp
#	src/Engine/Network/Packet.cpp
#	src/Engine/Network/Server.cpp
#	src/Tests/HealthSystemTest.cpp
This commit is contained in:
Jocke
2016-02-10 17:05:07 +01:00
189 changed files with 10536 additions and 1959 deletions
+19 -1
View File
@@ -28,6 +28,21 @@ bool RayVsAABB(const Ray& ray, const AABB& box);
//Return true if the ray hits the box, also outputs distance from ray origin to intersection point in [outDistance].
bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance);
//Return true if the ray hits the triangle.
bool RayVsTriangle(const Ray& ray,
const glm::vec3& v0,
const glm::vec3& v1,
const glm::vec3& v2,
bool trueOnNegativeDistance = false);
//Return true if the ray hits the triangle, and the distance is less than outDistance.
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 = false);
//Return true if the ray hits any of the triangles in the model. Stops checking when a hit is detected.
bool RayVsModel(const Ray& ray,
const std::vector<RawModel::Vertex>& modelVertices,
@@ -49,9 +64,12 @@ bool RayVsModel(const Ray& ray,
float& outVCoord);
bool AABBvsTriangles(const AABB& box,
const std::vector<RawModel::Vertex>& modelVertices,
const RawModel::Vertex* modelVertices,
const std::vector<unsigned int>& modelIndices,
const glm::mat4& modelMatrix,
glm::vec3& boxVelocity,
float verticalStepHeight,
bool& isOnGround,
glm::vec3& outResolutionVector);
//Return true if the boxes are intersecting.
@@ -1,17 +1,17 @@
#ifndef CollidableOctreeSystem_h__
#define CollidableOctreeSystem_h__
#ifndef FillFrustumOctreeSystem_h__
#define FillFrustumOctreeSystem_h__
#include "../Core/System.h"
#include "../Core/Octree.h"
#include "Collision.h"
#include "EntityAABB.h"
class CollidableOctreeSystem : public ImpureSystem, public PureSystem
class FillFrustumOctreeSystem : public ImpureSystem, public PureSystem
{
public:
CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree<EntityAABB>* octree, const std::string& componentType)
FillFrustumOctreeSystem(World* world, EventBroker* eventBroker, Octree<EntityAABB>* octree)
: System(world, eventBroker)
, PureSystem(componentType)
, PureSystem("Model")
, m_Octree(octree)
{ }
@@ -0,0 +1,25 @@
#ifndef FillOctreeSystem_h__
#define FillOctreeSystem_h__
#include "../Core/System.h"
#include "../Core/Octree.h"
#include "Collision.h"
#include "EntityAABB.h"
class FillOctreeSystem : public ImpureSystem, public PureSystem
{
public:
FillOctreeSystem(World* world, EventBroker* eventBroker, Octree<EntityAABB>* octree, const std::string& fillComponentType)
: System(world, eventBroker)
, PureSystem(fillComponentType)
, m_Octree(octree)
{ }
virtual void Update(double dt) override;
virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override;
private:
Octree<EntityAABB>* m_Octree;
};
#endif
+5
View File
@@ -43,6 +43,11 @@ struct ComponentWrapper
// Specialization for string literals
template <std::size_t N>
void SetField(std::string name, const char(&value)[N]) { Field<std::string>(name) = std::string(value); }
void Copy(ComponentWrapper& destination)
{
memcpy(destination.Data, this->Data, Info.Stride);
}
struct SubscriptProxy
{
+17
View File
@@ -0,0 +1,17 @@
#ifndef EPickupSpawned_h__
#define EPickupSpawned_h__
#include "Core/Event.h"
#include "Core/EntityWrapper.h"
namespace Events
{
struct PickupSpawned : Event
{
EntityWrapper Pickup;
};
}
#endif
+1
View File
@@ -9,6 +9,7 @@ namespace Events
struct PlayerDamage : Event
{
//NOTE: this struct is missing information on what the damageSource is
EntityWrapper Player;
double Damage;
};
+2 -3
View File
@@ -2,7 +2,7 @@
#define EPlayerDeath_h__
#include "EventBroker.h"
#include "../Core/Entity.h"
#include "../Core/EntityWrapper.h"
namespace Events
{
@@ -10,8 +10,7 @@ namespace Events
struct PlayerDeath : Event
{
//KilledBy,KilledByWhat is optional for now. It might be used later in the playerlog-system
EntityID KilledBy;
EntityID PlayerID;
EntityWrapper Player;
std::string KilledByWhat;
};
+6 -6
View File
@@ -2,16 +2,16 @@
#define EPlayerHealthPickup_h__
#include "EventBroker.h"
#include "../Core/Entity.h"
#include "../Core/EntityWrapper.h"
namespace Events
{
struct PlayerHealthPickup : Event
{
double HealthAmount;
EntityID PlayerHealedID;
};
struct PlayerHealthPickup : Event
{
EntityWrapper Player;
double HealthAmount;
};
}
+1
View File
@@ -25,6 +25,7 @@ struct EntityWrapper
const std::string Name();
bool HasComponent(const std::string& componentType);
void AttachComponent(const char* componentName);
EntityWrapper Parent();
EntityWrapper FirstChildByName(const std::string& name);
EntityWrapper FirstParentWithComponent(const std::string& componentType);
+77
View File
@@ -0,0 +1,77 @@
#ifndef Frustum_h__
#define Frustum_h__
#include "../GLM.h"
#include "AABB.h"
#include <bitset>
//A frustum defined by 6 planes.
struct Frustum
{
//Contains points P in: dot(normal, P) + d = 0
struct Plane
{
glm::vec3 Normal;
float Distance;
};
enum class Output
{
Inside,
Outside,
Intersects
};
Plane Planes[6];
Frustum() = default;
Frustum(glm::mat4x4 viewProjMatrix)
{
//Order: Right, left, top, bottom, far, near.
int sign = 1;
for (int i = 0; i < 6; ++i) {
sign = -sign;
int index = i / 2;
Plane& plane = Planes[i];
plane.Normal.x = viewProjMatrix[0].w + sign * viewProjMatrix[0][index];
plane.Normal.y = viewProjMatrix[1].w + sign * viewProjMatrix[1][index];
plane.Normal.z = viewProjMatrix[2].w + sign * viewProjMatrix[2][index];
plane.Distance = viewProjMatrix[3].w + sign * viewProjMatrix[3][index];
float divByNormalLength = 1.0f / glm::length(plane.Normal);
plane.Normal *= divByNormalLength;
plane.Distance *= divByNormalLength;
}
}
Output VsAABB(const AABB& box) const
{
const glm::vec3& maxCorner = box.MaxCorner();
const glm::vec3& minCorner = box.MinCorner();
bool completelyInside = true;
for (const Plane& p : Planes) {
bool anyWasInside = false;
bool anyWasOutside = false;
//If points are on both sides of the plane, we can stop.
for (int i = 0; i < 8 && (!anyWasInside || !anyWasOutside); ++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;
if (glm::dot(p.Normal, corner) > -p.Distance) {
anyWasInside = true;
} else {
anyWasOutside = true;
}
}
if (!anyWasInside) {
return Output::Outside;
}
if (anyWasOutside) {
completelyInside = false;
}
}
return completelyInside ? Output::Inside : Output::Intersects;
}
};
#endif
+1 -1
View File
@@ -102,7 +102,7 @@ public:
m_ExtraMemory.push_back((char*)malloc(m_Stride));
//We should preferably not enter here to avoid performance issues. Set more numMaxElements in constructor instead.
if (!DisableMemoryPool::Value) {
LOG_WARNING("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size());
LOG_DEBUG("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size());
}
return m_ExtraMemory.back();
}
+55 -1
View File
@@ -5,6 +5,7 @@
#include "../Common.h"
#include "AABB.h"
#include "Frustum.h"
//Fwd declarations.
class Ray;
@@ -40,6 +41,8 @@ public:
//The type Box must be AABB, or inherit from AABB.
template<typename Box>
void ObjectsInSameRegion(const Box& box, std::vector<T>& outObjects);
//Get the objects that are inside the frustum, the objects are put in outObjects.
void ObjectsInFrustum(const Frustum& frustum, std::vector<T>& outObjects);
//Empty the tree of all objects, static and dynamic.
void ClearObjects();
//Empty the tree of all dynamic objects. Static objects remain in the tree.
@@ -97,6 +100,8 @@ struct Child
void AddStaticObject(const AABB& box);
template<typename T, typename Box>
void ObjectsInSameRegion(const Box& box, std::vector<T>& outObjects) const;
template<typename T>
void ObjectsInFrustum(const Frustum& frustum, std::vector<T>& outObjects, bool takeAllDontTest) const;
void ClearObjects();
void ClearDynamicObjects();
bool RayCollides(const Ray& ray, Output& data) const;
@@ -111,7 +116,7 @@ struct Child
std::vector<ContainedObject>& m_StaticObjectsRef;
std::vector<ContainedObject>& m_DynamicObjectsRef;
bool hasChildren() const;
inline bool hasChildren() const { return m_Children[0] != nullptr; }
int childIndexContainingPoint(const glm::vec3& point) const;
std::vector<int> childIndicesContainingBox(const AABB& box) const;
};
@@ -154,6 +159,13 @@ void Octree<T>::ObjectsInSameRegion(const Box& box, std::vector<T>& outObjects)
m_Root->ObjectsInSameRegion(box, outObjects);
}
template<typename T>
void Octree<T>::ObjectsInFrustum(const Frustum& frustum, std::vector<T>& outObjects)
{
falsifyObjectChecks();
m_Root->ObjectsInFrustum(frustum, outObjects, false);
}
template<typename T>
void Octree<T>::ClearObjects()
{
@@ -230,4 +242,46 @@ void OctSpace::Child::ObjectsInSameRegion(const Box& box, std::vector<T>& outObj
}
}
template<typename T>
void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector<T>& outObjects, bool takeAllDontTest) const
{
if (hasChildren()) {
for (const Child* c : m_Children) {
Frustum::Output out = Frustum::Output::Inside;
if (!takeAllDontTest) {
out = frustum.VsAABB(c->m_Box);
if (out == Frustum::Output::Outside) {
continue;
}
}
c->ObjectsInFrustum(frustum, outObjects, out == Frustum::Output::Inside);
}
} else {
size_t startIndex = outObjects.size();
int numDuplicates = 0;
outObjects.resize(outObjects.size() + m_StaticObjIndices.size() + m_DynamicObjIndices.size());
for (size_t i = 0; i < m_StaticObjIndices.size(); ++i) {
ContainedObject& obj = m_StaticObjectsRef[m_StaticObjIndices[i]];
if (obj.Checked || frustum.VsAABB(*obj.Box) == Frustum::Output::Outside) {
++numDuplicates;
} else {
obj.Checked = true;
outObjects[startIndex + i - numDuplicates] = *static_cast<T*>(obj.Box.get());
}
}
for (size_t i = 0; i < m_DynamicObjIndices.size(); ++i) {
ContainedObject& obj = m_DynamicObjectsRef[m_DynamicObjIndices[i]];
if (obj.Checked || frustum.VsAABB(*obj.Box) == Frustum::Output::Outside) {
++numDuplicates;
} else {
obj.Checked = true;
outObjects[startIndex + i - numDuplicates] = *static_cast<T*>(obj.Box.get());
}
}
for (size_t i = 0; i < numDuplicates; ++i) {
outObjects.pop_back();
}
}
}
#endif
+4
View File
@@ -7,6 +7,10 @@
class Ray
{
public:
Ray()
: m_Origin(glm::vec3(0.f))
, m_Direction(glm::vec3(0, 0, 1))
{}
Ray(const glm::vec3& origin, const glm::vec3& dir)
: m_Origin(origin)
, m_Direction(glm::normalize(dir))
+10 -7
View File
@@ -200,13 +200,16 @@ static T* ResourceManager::Load(const std::string& resourceName, Resource* paren
}
//If resource has already been cached and completely loaded.
it = m_ResourceCache.find(cacheKey);
if (it != m_ResourceCache.end()) {
if (it->second != nullptr) {
return static_cast<T*>(it->second);
} else {
//Don't return null on failure, exception instead.
throw Resource::FailedLoadingException();
{
boost::lock_guard<decltype(m_Mutex)> guard(m_Mutex);
it = m_ResourceCache.find(cacheKey);
if (it != m_ResourceCache.end()) {
if (it->second != nullptr) {
return static_cast<T*>(it->second);
} else {
//Don't return null on failure, exception instead.
throw Resource::FailedLoadingException();
}
}
}
+1
View File
@@ -18,6 +18,7 @@ glm::vec3 AbsoluteScale(EntityWrapper entity);
glm::vec3 AbsoluteScale(World* world, EntityID entity);
glm::mat4 ModelMatrix(EntityWrapper entity);
glm::mat4 ModelMatrix(EntityID entity, World* world);
glm::vec3 TransformPoint(const glm::vec3& point, const glm::mat4& matrix);
}
@@ -4,6 +4,8 @@
#include "../GLM.h"
#include "../Core/InputController.h"
#include "../Core/ELockMouse.h"
#include "../Game/Events/EDashAbility.h"
#include "InputHandler.h"
template <typename EventContext>
class FirstPersonInputController : public InputController<EventContext>
@@ -25,6 +27,10 @@ public:
virtual bool OnCommand(const Events::InputCommand& e) override;
virtual void Reset();
void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer);
virtual bool AssaultDashDoubleTapped() const { return m_AssaultDashDoubleTapped; }
virtual bool PlayerIsDashing() const { return m_PlayerIsDashing; }
protected:
const int m_PlayerID;
bool m_MouseLocked = false;
@@ -33,6 +39,22 @@ protected:
bool m_Jumping = false;
bool m_DoubleJumping = false;
bool m_Crouching = false;
//assault dash membervariables - needed to calculate the doubletap- and dashlogic
double m_AssaultDashDoubleTapDeltaTime = 0.0;
double m_AssaultDashCoolDownTimer = 0.0;
//i will let m_AssaultDashDoubleTapSensitivityTimer stay hardcoded, its not really a gamevariable (more an inputvariable),
//and its very unlikely that someone wants to change that value
const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f;
std::string m_AssaultDashTapDirection = "";
std::string m_CurrentDirectionVector = "";
bool m_AssaultDashDoubleTapped = false;
bool m_PlayerIsDashing = false;
bool m_ShiftDashing = false;
bool m_ValidDoubleTap = false;
//specialabilitys
bool m_MovementKeyDown = false;
bool m_SpecialAbilityKeyDown = false;
EventRelay<EventContext, Events::LockMouse> m_ELockMouse;
bool OnLockMouse(const Events::LockMouse& e);
@@ -104,6 +126,26 @@ bool FirstPersonInputController<EventContext>::OnCommand(const Events::InputComm
}
}
if (e.Command == "Forward" || e.Command == "Right") {
if (e.Value != 0) {
m_CurrentDirectionVector = e.Command == "Right" ? (e.Value > 0 ? "Right" : "Left") : (e.Value > 0 ? "Forward" : "Backward");
}
//if value = 0 then you have just released this key
if (e.Value != 0) {
m_MovementKeyDown = true;
//if you pressed the same key within m_AssaultDashDoubleTapSensitivityTimer then you have doubletapped it
if (m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer && m_AssaultDashTapDirection == m_CurrentDirectionVector) {
m_ValidDoubleTap = true;
}
} else {
//== 0
m_MovementKeyDown = false;
//you have just released the key, store what key it was and reset the doubletap-sensitivity-timer
m_AssaultDashTapDirection = m_CurrentDirectionVector;
m_AssaultDashDoubleTapDeltaTime = 0.f;
}
}
if (e.Command == "Jump") {
m_Jumping = e.Value > 0;
}
@@ -112,6 +154,19 @@ bool FirstPersonInputController<EventContext>::OnCommand(const Events::InputComm
m_Crouching = e.Value > 0;
}
if (e.Command == "SpecialAbility") {
if (e.Value > 0) {
m_SpecialAbilityKeyDown = true;
} else {
m_SpecialAbilityKeyDown = false;
}
}
if (m_SpecialAbilityKeyDown && m_MovementKeyDown) {
m_ShiftDashing = true;
} else {
m_ShiftDashing = false;
}
return true;
}
@@ -129,4 +184,56 @@ bool FirstPersonInputController<EventContext>::OnLockMouse(const Events::LockMou
return true;
}
template <typename EventContext>
void FirstPersonInputController<EventContext>::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer) {
m_AssaultDashDoubleTapDeltaTime += dt;
m_AssaultDashCoolDownTimer -= dt;
//cooldown = assaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work)
if (m_AssaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) {
m_PlayerIsDashing = true;
} else {
m_PlayerIsDashing = false;
}
//dashing with shift
if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) {
//player is dashing with shift
//the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in!
m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer;
m_AssaultDashDoubleTapped = true;
m_AssaultDashDoubleTapDeltaTime = 0.f;
//moving to the side has priority
return;
}
//dashing with doubletap - check if doubletap to dash enabled
if (ResourceManager::Load<ConfigFile>("Input.ini")->Get<bool>("Keyboard.DoubleTapToDash", false)) {
return;
}
//reset the DoubleTapped state in case we recently doubleTapped (doubletap will only happen during 1 frame)
if (m_AssaultDashDoubleTapped) {
m_AssaultDashDoubleTapped = false;
}
//check if we have received a valid doubletap
if (!m_ValidDoubleTap) {
return;
}
m_ValidDoubleTap = false;
if (!(m_AssaultDashCoolDownTimer <= 0.0f && !isJumping)) {
//if we cant dash at the moment, then just reset the tap-sensitivity-timer
m_AssaultDashDoubleTapDeltaTime = 0.f;
return;
}
//ok, we have a valid tap, lets do it
m_AssaultDashDoubleTapped = true;
m_AssaultDashDoubleTapDeltaTime = 0.f;
m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer;
Events::DashAbility e;
m_EventBroker->Publish(e);
}
#endif
+2 -1
View File
@@ -36,7 +36,7 @@ protected:
std::string address;
int port = 0;
// Sending message to server logic
int bytesRead = -1;
size_t bytesRead = 0;
// Packet loss logic
PacketID m_PacketID = 0;
@@ -67,6 +67,7 @@ protected:
std::vector<Events::InputCommand> m_InputCommandBuffer;
// Private member functions
size_t receive(char* data);
void disconnect();
void parseMessageType(Packet& packet);
void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType);
+1 -1
View File
@@ -29,7 +29,7 @@ protected:
unsigned int m_SaveDataIntervalMs = 1000;
std::clock_t m_SaveDataTimer;
unsigned int m_MaxConnections;
unsigned int m_TimeoutMs;
double m_TimeoutMs;
void logSentData(int bytesSent);
void logReceivedData(int bytesReceived);
void saveToFile();
+8 -8
View File
@@ -3,16 +3,16 @@
#include <vector>
struct NetworkData {
unsigned int TotalTime = 0;
unsigned int TotalDataReceived = 0;
unsigned int TotalDataSent = 0;
unsigned int AmountOfMessagesReceived = 0;
double TotalTime = 0;
size_t TotalDataReceived = 0;
size_t TotalDataSent = 0;
size_t AmountOfMessagesReceived = 0;
unsigned int AmountOfMessagesSent = 0;
// Interval based
unsigned int DataReceivedThisInterval = 0;
unsigned int DataSentThisInterval = 0;
size_t DataReceivedThisInterval = 0;
size_t DataSentThisInterval = 0;
// pair: first=reveived, second=send
std::vector<std::pair<unsigned int, unsigned int>> BandwidthBytes;
std::vector<std::pair<size_t, size_t>> BandwidthBytes;
};
#endif
#endif
+9 -9
View File
@@ -13,7 +13,7 @@ public:
// arg2: PacketID for identifying packet loss.
Packet(MessageType type, unsigned int& packetID);
// Used to create packet from already existing data buffer.
Packet(char* data, const int sizeOfPacket);
Packet(char* data, const size_t sizeOfPacket);
Packet(MessageType type);
~Packet();
void Init(MessageType type, unsigned int& packetID);
@@ -55,19 +55,19 @@ public:
void UpdateSize();
char* ReadData(int SizeOfData);
void ChangePacketID(unsigned int& packetID);
int Size() { return m_Offset; };
size_t Size() { return m_Offset; };
char* Data() { return m_Data; };
MessageType GetMessageType();
unsigned int DataReadSize() { return m_ReturnDataOffset; }
unsigned int MaxSize() { return m_MaxPacketSize; }
unsigned int HeaderSize() { return m_HeaderSize; }
size_t DataReadSize() { return m_ReturnDataOffset; }
size_t MaxSize() { return m_MaxPacketSize; }
size_t HeaderSize() { return m_HeaderSize; }
private:
char* m_Data;
unsigned int m_ReturnDataOffset = 0;
int m_Offset = 0;
unsigned int m_MaxPacketSize = 512;
unsigned int m_HeaderSize = 0;
size_t m_ReturnDataOffset = 0;
size_t m_Offset = 0;
size_t m_MaxPacketSize = 512;
size_t m_HeaderSize = 0;
void resizeData();
void resizeData(int size);
};
+3 -3
View File
@@ -35,15 +35,15 @@ protected:
std::map<PlayerID, PlayerDefinition> m_ConnectedPlayers;
// HACK: Fix INPUTSIZE
char readBuffer[BUFFERSIZE] = { 0 };
int bytesRead = 0;
size_t bytesRead = 0;
// time for previouse message
std::clock_t previousePingMessage = std::clock();
std::clock_t previousSnapshotMessage = std::clock();
std::clock_t timOutTimer = std::clock();
// How often we send messages (milliseconds)
int pingIntervalMs;
int snapshotInterval;
float pingIntervalMs;
float snapshotInterval;
int checkTimeOutInterval = 100;
int m_NextPlayerID = 0;
//Timers
+4 -2
View File
@@ -9,6 +9,7 @@
#include "Rendering/Model.h"
#include "Rendering/EAnimationComplete.h"
#include "Rendering/Skeleton.h"
#include <imgui/imgui.h>
class AnimationSystem : public PureSystem
{
@@ -22,8 +23,9 @@ public:
~AnimationSystem() { }
virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& animationComponent, double dt) override;
private:
float angle = 0.f;
bool b_forward = false;
char bone[100];
};
#endif
@@ -0,0 +1,29 @@
#ifndef BoneAttachmentSystem_h__
#define BoneAttachmentSystem_h__
#include "GLM.h"
#include "Common.h"
#include "Core/System.h"
#include "Core/ResourceManager.h"
#include "Rendering/Model.h"
#include "Rendering/Skeleton.h"
//Needs to be a higher orderlevel than AnimationSystem
class BoneAttachmentSystem : public PureSystem
{
public:
BoneAttachmentSystem(World* world, EventBroker* eventBroker)
: System(world, eventBroker)
, PureSystem("BoneAttachment")
{
}
~BoneAttachmentSystem() { }
virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) override;
private:
};
#endif
@@ -7,6 +7,7 @@
#include "ShaderProgram.h"
//#include "Util/UnorderedMapVec2.h"
#include "Texture.h"
#include "imgui/imgui.h"
class DrawColorCorrectionPass
{
@@ -16,14 +17,13 @@ public:
void InitializeFrameBuffers();
void InitializeShaderPrograms();
void Draw(GLuint sceneTexture, GLuint bloomTexture);
void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure);
private:
const IRenderer* m_Renderer;
ShaderProgram* m_ColorCorrectionProgram;
Model* m_ScreenQuad;
GLfloat m_Exposure;
};
#endif
+30 -3
View File
@@ -22,21 +22,29 @@ public:
//Return the texture that is used in later stages to apply the bloom effect
GLuint BloomTexture() const { return m_BloomTexture; }
GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; }
//Return the texture with diffuse and lighting of the scene.
GLuint SceneTexture() const { return m_SceneTexture; }
GLuint SceneTextureLowRes() const { return m_SceneTextureLowRes; }
//Return the framebuffer used in the scene rendering stage.
FrameBuffer* FinalPassFrameBuffer() { return &m_FinalPassFrameBuffer; }
FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; }
private:
void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const;
void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const;
void DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>& job, RenderScene& scene);
void DrawModelRenderQueues(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene);
void DrawShieldToStencilBuffer(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene);
void DrawShieldedModelRenderQueue(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene);
void DrawToDepthBuffer(std::list<std::shared_ptr<RenderJob>>& jobs, RenderScene& scene);
void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr<ExplosionEffectJob>& job, RenderScene& scene);
void BindModelUniforms(GLuint shaderHandle, std::shared_ptr<ModelJob>& job, RenderScene& scene);
void BindExplosionTextures(std::shared_ptr<ExplosionEffectJob>& job);
void BindModelTextures(std::shared_ptr<ModelJob>& job);
void BindExplosionTextures(GLuint shaderHandle, std::shared_ptr<ExplosionEffectJob>& job);
void BindModelTextures(GLuint shaderHandle, std::shared_ptr<ModelJob>& job);
Texture* m_WhiteTexture;
Texture* m_BlackTexture;
@@ -44,15 +52,34 @@ private:
Texture* m_GreyTexture;
FrameBuffer m_FinalPassFrameBuffer;
FrameBuffer m_FinalPassFrameBufferLowRes;
GLuint m_BloomTexture;
GLuint m_SceneTexture;
GLuint m_BloomTextureLowRes;
GLuint m_SceneTextureLowRes;
GLuint m_DepthBuffer;
GLuint m_DepthBufferLowRes;
//maqke this component based i guess?
GLuint m_ShieldPixelRate = 16;
const IRenderer* m_Renderer;
const LightCullingPass* m_LightCullingPass;
ShaderProgram* m_ForwardPlusProgram;
ShaderProgram* m_ExplosionEffectProgram;
ShaderProgram* m_ExplosionEffectSplatMapProgram;
ShaderProgram* m_ForwardPlusSplatMapProgram;
ShaderProgram* m_ShieldToStencilProgram;
ShaderProgram* m_FillDepthBufferProgram;
ShaderProgram* m_ForwardPlusSkinnedProgram;
ShaderProgram* m_ExplosionEffectSkinnedProgram;
ShaderProgram* m_ExplosionEffectSplatMapSkinnedProgram;
ShaderProgram* m_ForwardPlusSplatMapSkinnedProgram;
ShaderProgram* m_ShieldToStencilSkinnedProgram;
ShaderProgram* m_FillDepthBufferSkinnedProgram;
};
#endif
@@ -12,4 +12,11 @@ private:
};
class DrawStencilState : public RenderState
{
public:
DrawStencilState(GLuint frameBuffer);
~DrawStencilState();
};
#endif
@@ -15,7 +15,7 @@
struct ExplosionEffectJob : ModelJob
{
ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialGroup matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage)
ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage)
: ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage)
{
ExplosionOrigin = (glm::vec3)explosionEffectComponent["ExplosionOrigin"];
+8 -4
View File
@@ -4,6 +4,7 @@
#include "Rendering/RawModelCustom.h"
//#include "Rendering/RawModelAssimp.h"
#include "../OpenGL.h"
#include "Core/AABB.h"
class Model : public ThreadUnsafeResource
{
@@ -14,16 +15,19 @@ private:
public:
~Model();
const std::vector<RawModel::MaterialGroup>& MaterialGroups() const { return m_RawModel->MaterialGroups; }
const std::vector<RawModel::MaterialProperties>& MaterialGroups() const { return m_RawModel->m_Materials; }
const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; }
const std::vector<RawModel::Vertex>& Vertices() const { return m_RawModel->m_Vertices; }
const RawModel::Vertex* Vertices() const { return m_RawModel->Vertices(); }
unsigned int NumberOfVertices() const { return m_RawModel->NumVertices(); }
const AABB& Box() const { return m_Box; }
bool IsSkinned() const { return m_RawModel->IsSkinned(); }
GLuint VAO;
GLuint ElementBuffer;
RawModel* m_RawModel;
private:
AABB m_Box;
GLuint VertexBuffer;
GLuint NormalBuffer;
GLuint TangentNormalsBuffer;
+123 -37
View File
@@ -14,39 +14,98 @@
#include "../Core/World.h"
#include "../Core/Transform.h"
#include "Skeleton.h"
#include "ShaderProgram.h"
struct ModelJob : RenderJob
{
ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialGroup matGroup, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage)
ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage)
: RenderJob()
{
Model = model;
TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0;
if (modelComponent["DiffuseTexture"]) {
DiffuseTexture = matGroup.Texture.get();
} else {
DiffuseTexture = nullptr;
}
if (modelComponent["NormalMap"]) {
NormalTexture = matGroup.NormalMap.get();
} else {
NormalTexture = nullptr;
}
if (modelComponent["SpecularMap"]) {
SpecularTexture = matGroup.SpecularMap.get();
} else {
SpecularTexture = nullptr;
}
if (modelComponent["GlowMap"]) {
IncandescenceTexture = matGroup.IncandescenceMap.get();
} else {
IncandescenceTexture = nullptr;
}
DiffuseColor = matGroup.DiffuseColor;
SpecularColor = matGroup.SpecularColor;
IncandescenceColor = matGroup.IncandescenceColor;
StartIndex = matGroup.StartIndex;
EndIndex = matGroup.EndIndex;
ModelID = model->ResourceID;
Type = matProp.type;
::RawModel::MaterialBasic* matGroup = matProp.material;
switch(matProp.type){
case ::RawModel::MaterialType::Basic:
if (Model->IsSkinned()) {
ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSkinnedProgram")->ResourceID;
}
else {
ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram")->ResourceID;
}
TextureID = 0;
break;
case ::RawModel::MaterialType::SingleTextures:
{
if (Model->IsSkinned()) {
ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSkinnedProgram")->ResourceID;
}
else {
ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram")->ResourceID;
}
::RawModel::MaterialSingleTextures* singleTextures = static_cast<::RawModel::MaterialSingleTextures*>(matProp.material);
TextureID = (singleTextures->ColorMap.Texture) ? singleTextures->ColorMap.Texture->ResourceID : 0;
if (modelComponent["DiffuseTexture"]) {
DiffuseTexture.push_back(&singleTextures->ColorMap);
}
if (modelComponent["NormalMap"]) {
NormalTexture.push_back(&singleTextures->NormalMap);
}
if (modelComponent["SpecularMap"]) {
SpecularTexture.push_back(&singleTextures->SpecularMap);
}
if (modelComponent["GlowMap"]) {
IncandescenceTexture.push_back(&singleTextures->IncandescenceMap);
}
}
break;
case ::RawModel::MaterialType::SplatMapping:
{
if (Model->IsSkinned()) {
ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSplatMapSkinnedProgram")->ResourceID;
}
else {
ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSplatMapProgram")->ResourceID;
}
::RawModel::MaterialSplatMapping* SplatTextures = static_cast<::RawModel::MaterialSplatMapping*>(matProp.material);
SplatMap = &SplatTextures->SplatMap;
TextureID = (SplatTextures->ColorMaps[0].Texture) ? SplatTextures->ColorMaps[0].Texture->ResourceID : 0;
if (modelComponent["DiffuseTexture"]) {
for (auto& texture : SplatTextures->ColorMaps) {
DiffuseTexture.push_back(&texture);
}
}
if (modelComponent["NormalMap"]) {
for (auto& texture : SplatTextures->NormalMaps) {
NormalTexture.push_back(&texture);
}
}
if (modelComponent["SpecularMap"]) {
for (auto& texture : SplatTextures->SpecularMaps) {
SpecularTexture.push_back(&texture);
}
}
if (modelComponent["GlowMap"]) {
for (auto& texture : SplatTextures->IncandescenceMaps) {
IncandescenceTexture.push_back(&texture);
}
}
}
break;
}
DiffuseColor = matGroup->DiffuseColor;
SpecularColor = matGroup->SpecularColor;
IncandescenceColor = matGroup->IncandescenceColor;
StartIndex = matGroup->StartIndex;
EndIndex = matGroup->EndIndex;
Matrix = matrix;
Color = modelComponent["Color"];
Entity = modelComponent.EntityID;
@@ -57,29 +116,56 @@ struct ModelJob : RenderJob
FillColor = fillColor;
FillPercentage = fillPercentage;
Skeleton = Model->m_RawModel->m_Skeleton;
if (world->HasComponent(Entity, "Animation") && Skeleton != nullptr) {
auto animationComponent = world->GetComponent(Entity, "Animation");
Animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["Name"]);
AnimationTime = (double)animationComponent["Time"];
if (Skeleton != nullptr) {
if (world->HasComponent(Entity, "Animation")) {
auto animationComponent = world->GetComponent(Entity, "Animation");
for (int i = 1; i <= 3; i++) {
::Skeleton::AnimationData animationData;
animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]);
if (animationData.animation == nullptr) {
continue;
}
animationData.time = (double)animationComponent["Time" + std::to_string(i)];
animationData.weight = (double)animationComponent["Weight" + std::to_string(i)];
Animations.push_back(animationData);
}
}
if (world->HasComponent(Entity, "AnimationOffset")) {
auto animationOffsetComponent = world->GetComponent(Entity, "AnimationOffset");
AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationOffsetComponent["AnimationName"]);
AnimationOffset.time = (double)animationOffsetComponent["Time"];
} else {
AnimationOffset.animation = nullptr;
}
}
};
unsigned int TextureID;
unsigned int ShaderID;
unsigned int ModelID;
::RawModel::MaterialType Type;
EntityID Entity;
glm::mat4 Matrix;
const Texture* DiffuseTexture;
const Texture* NormalTexture;
const Texture* SpecularTexture;
const Texture* IncandescenceTexture;
const ::RawModel::TextureProperties* SplatMap;
std::vector<const ::RawModel::TextureProperties*> DiffuseTexture;
std::vector<const ::RawModel::TextureProperties*> NormalTexture;
std::vector<const ::RawModel::TextureProperties*> SpecularTexture;
std::vector<const ::RawModel::TextureProperties*> IncandescenceTexture;
float Shininess = 0.f;
glm::vec4 Color;
const ::Model* Model = nullptr;
::Skeleton* Skeleton = nullptr;
const ::Skeleton::Animation* Animation = nullptr;
// const ::Skeleton::Animation* Animation = nullptr;
std::vector<::Skeleton::AnimationData> Animations;
::Skeleton::AnimationOffset AnimationOffset;
float AnimationTime = 0.f;
@@ -95,7 +181,7 @@ struct ModelJob : RenderJob
void CalculateHash() override
{
Hash = TextureID;
Hash = TextureID + ModelID << 10 + ShaderID << 20;
}
};
+1
View File
@@ -40,6 +40,7 @@ private:
const IRenderer* m_Renderer;
ShaderProgram* m_PickingProgram;
ShaderProgram* m_PickingSkinnedProgram;
Camera* m_Camera;
struct PickingInfo
+77 -20
View File
@@ -33,18 +33,27 @@ protected:
public:
~RawModelCustom();
struct Vertex
{
glm::vec3 Position;
glm::vec3 Normal;
glm::vec3 Tangent;
glm::vec3 BiNormal;
glm::vec2 TextureCoords;
struct Vertex
{
glm::vec3 Position;
glm::vec3 Normal;
glm::vec3 Tangent;
glm::vec3 BiNormal;
glm::vec2 TextureCoords;
};
struct SkinedVertex : public Vertex {
glm::vec4 BoneIndices;
glm::vec4 BoneWeights;
};
struct MaterialGroup
struct TextureProperties {
std::string TexturePath;
glm::vec2 UVRepeat;
std::shared_ptr<::Texture> Texture;
};
struct MaterialBasic
{
float SpecularExponent;
float ReflectionFactor;
@@ -54,25 +63,69 @@ public:
unsigned int StartIndex;
unsigned int EndIndex;
//float Transparency;
std::string TexturePath;
std::shared_ptr<::Texture> Texture;
std::string NormalMapPath;
std::shared_ptr<::Texture> NormalMap;
std::string SpecularMapPath;
std::shared_ptr<::Texture> SpecularMap;
std::string IncandescenceMapPath;
std::shared_ptr<::Texture> IncandescenceMap;
};
std::vector<MaterialGroup> MaterialGroups;
struct MaterialSplatMapping : public MaterialBasic
{
TextureProperties SplatMap;
std::vector<TextureProperties> ColorMaps;
std::vector<TextureProperties> NormalMaps;
std::vector<TextureProperties> SpecularMaps;
std::vector<TextureProperties> IncandescenceMaps;
};
struct MaterialSingleTextures : public MaterialBasic
{
TextureProperties ColorMap;
TextureProperties NormalMap;
TextureProperties SpecularMap;
TextureProperties IncandescenceMap;
};
enum class MaterialType { Basic = 1, SplatMapping, SingleTextures };
struct MaterialProperties {
MaterialType type;
MaterialBasic* material;
};
const Vertex* Vertices() const {
if (hasSkin) {
return m_SkinedVertices.data();
} else {
return m_Vertices.data();
}
};
unsigned int VertexSize() const {
if (hasSkin) {
return sizeof(SkinedVertex);
}
else {
return sizeof(Vertex);
}
};
unsigned int NumVertices() const {
if (hasSkin) {
return m_SkinedVertices.size();
} else {
return m_Vertices.size();
}
};
bool IsSkinned() const { return hasSkin; };
std::vector<MaterialProperties> m_Materials;
std::vector<Vertex> m_Vertices;
std::vector<unsigned int> m_Indices;
Skeleton* m_Skeleton = nullptr;
glm::mat4 m_Matrix;
private:
bool hasSkin;
std::vector<Vertex> m_Vertices;
std::vector<SkinedVertex> m_SkinedVertices;
void ReadMeshFile(std::string filePath);
void ReadMeshFileHeader(std::size_t& offset, char* fileData);
@@ -83,13 +136,17 @@ private:
void ReadMaterialFile(std::string filePath);
void ReadMaterials(std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadMaterialSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadMaterialBasic(MaterialBasic* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadMaterialSingleTexture(MaterialSingleTextures* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadMaterialSplatMapping(MaterialSplatMapping* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadMaterialTextureProperties(TextureProperties& texture, std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadAnimationFile(std::string filePath);
void ReadAnimationBindPoses(std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadAnimationJoint(std::size_t& offset, char* fileData, const unsigned int& fileByteSize);
void ReadAnimationClips(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int numberOfClips);
void ReadAnimationClipSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int clipIndex);
void ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, unsigned int numberOfJoints, Skeleton::Animation& animation);
void ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, std::vector<Skeleton::Animation::Keyframe>& animation);
//void CreateSkeleton(std::vector<std::tuple<std::string, glm::mat4>> &boneInfo, std::map<std::string, int> &boneNameMapping, aiNode* node, int parentID);
};
+22 -10
View File
@@ -19,27 +19,39 @@
struct RenderScene
{
::Camera* Camera = nullptr;
std::list<std::shared_ptr<RenderJob>> OpaqueObjects;
std::list<std::shared_ptr<RenderJob>> TransparentObjects;
std::list<std::shared_ptr<RenderJob>> PointLightJobs;
std::list<std::shared_ptr<RenderJob>> TextJobs;
std::list<std::shared_ptr<RenderJob>> DirectionalLightJobs;
struct Queues {
std::list<std::shared_ptr<RenderJob>> OpaqueObjects;
std::list<std::shared_ptr<RenderJob>> TransparentObjects;
std::list<std::shared_ptr<RenderJob>> OpaqueShieldedObjects;
std::list<std::shared_ptr<RenderJob>> TransparentShieldedObjects;
std::list<std::shared_ptr<RenderJob>> ShieldObjects;
std::list<std::shared_ptr<RenderJob>> PointLight;
std::list<std::shared_ptr<RenderJob>> Text;
std::list<std::shared_ptr<RenderJob>> DirectionalLight;
} Jobs;
Rectangle Viewport;
bool ClearDepth = false;
glm::vec4 AmbientColor;
void Clear()
{
OpaqueObjects.clear();
TransparentObjects.clear();
PointLightJobs.clear();
TextJobs.clear();
DirectionalLightJobs.clear();
Jobs.OpaqueObjects.clear();
Jobs.TransparentObjects.clear();
Jobs.OpaqueShieldedObjects.clear();
Jobs.TransparentShieldedObjects.clear();
Jobs.ShieldObjects.clear();
Jobs.Text.clear();
Jobs.DirectionalLight.clear();
}
};
struct RenderFrame
{
public:
//TODO: Getters
GLfloat Gamma = 2.2f;
GLfloat Exposure = 1.f;
void Add(RenderScene &scene)
{
+4
View File
@@ -2,6 +2,7 @@
#define RenderState_h__
#include <functional>
#include <boost/range/adaptor/reversed.hpp>
#include "../Common.h"
#include "../OpenGL.h"
#include "../GLM.h"
@@ -19,6 +20,9 @@ public:
bool BindFramebuffer(GLint framebuffer);
bool BlendEquation(GLenum mode);
bool BlendFunc(GLenum sfactor, GLenum dfactor);
bool StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass);
bool StencilFunc(GLenum func, GLint ref, GLuint mask);
bool StencilMask(GLuint mask);
bool DepthMask(GLboolean flag);
private:
+5 -3
View File
@@ -16,11 +16,13 @@
#include "PointLightJob.h"
#include "../Core/Transform.h"
#include "../Core/EPlayerSpawned.h"
#include "../Core/Octree.h"
#include "../Collision/EntityAABB.h"
class RenderSystem : public ImpureSystem
{
public:
RenderSystem(World* world, EventBroker* eventBrokerer, const IRenderer* renderer, RenderFrame* renderFrame);
RenderSystem(World* world, EventBroker* eventBrokerer, const IRenderer* renderer, RenderFrame* renderFrame, Octree<EntityAABB>* frustumCullOctree);
~RenderSystem();
virtual void Update(double dt) override;
@@ -32,6 +34,7 @@ private:
World* m_World;
EntityWrapper m_CurrentCamera = EntityWrapper::Invalid;
EntityWrapper m_LocalPlayer = EntityWrapper::Invalid;
Octree<EntityAABB>* m_Octree;
EventRelay<RenderSystem, Events::SetCamera> m_ESetCamera;
bool OnSetCamera(Events::SetCamera &event);
@@ -40,14 +43,13 @@ private:
EventRelay<RenderSystem, Events::PlayerSpawned> m_EPlayerSpawned;
bool OnPlayerSpawned(Events::PlayerSpawned& e);
void fillModels(std::list<std::shared_ptr<RenderJob>>& opaqueJobs, std::list<std::shared_ptr<RenderJob>>& transparentJobs);
void fillModels(RenderScene::Queues &jobs);
void fillText(std::list<std::shared_ptr<RenderJob>>& jobs, World* world);
void fillPointLights(std::list<std::shared_ptr<RenderJob>>& jobs, World* world);
void fillDirectionalLights(std::list<std::shared_ptr<RenderJob>>& jobs, World* world);
void fillLight(std::list<std::shared_ptr<RenderJob>>& jobs);
bool isChildOfACamera(EntityWrapper entity);
bool isChildOfCurrentCamera(EntityWrapper entity);
};
#endif
+45 -17
View File
@@ -5,6 +5,7 @@
#include "Common.h"
#include "../GLM.h"
#include <glm/gtx/matrix_decompose.hpp>
#include <imgui/imgui.h>
//struct Bone
//{
@@ -53,22 +54,39 @@ public:
{
struct BoneProperty
{
int ID;
glm::vec3 Position;
glm::quat Rotation;
glm::vec3 Position;
glm::quat Rotation;
glm::vec3 Scale = glm::vec3(1);
};
int Index = 0;
double Time = 0.0;
std::map<int, Keyframe::BoneProperty> BoneProperties;
int Index = 0;
double Time = 0.0;
BoneProperty BoneProperties;
};
std::string Name;
double Duration;
std::vector<Keyframe> Keyframes;
std::string Name;
double Duration;
std::map<int, std::vector<Keyframe>> JointAnimations;
};
struct AnimationData
{
const Animation* animation;
float time;
float weight;
};
struct JointFrameTransform {
glm::vec3 PositionInterp = glm::vec3(0);
glm::quat RotationInterp = glm::quat();
glm::vec3 ScaleInterp = glm::vec3(0);
float Weight;
};
struct AnimationOffset {
const Animation* animation;
float time;
};
Skeleton() { }
~Skeleton();
@@ -82,17 +100,27 @@ public:
int GetBoneID(std::string name);
const Animation* GetAnimation(std::string name);
std::vector<glm::mat4> GetFrameBones(const Animation& animation, double time, bool noRootMotion = false);
void 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);
void PrintSkeleton();
const Animation* GetAnimation(std::string name);
std::vector<glm::mat4> GetFrameBones(std::vector<AnimationData> animations, bool noRootMotion = false);
std::vector<glm::mat4> GetFrameBones(std::vector<AnimationData> animations, AnimationOffset animationOffset, bool noRootMotion = false);
//void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map<int, glm::mat4>& boneMatrices, const Bone* bone, glm::mat4 parentMatrix);
void AccumulateBoneTransforms(bool noRootMotion, std::vector<AnimationData> animations, std::map<int, glm::mat4>& boneMatrices, const Bone* bone, glm::mat4 parentMatrix);
void AccumulateBoneTransforms(bool noRootMotion, std::vector<AnimationData> animations, AnimationOffset animationOffset, std::map<int, glm::mat4>& boneMatrices, const Bone* bone, glm::mat4 parentMatrix);
void PrintSkeleton();
void PrintSkeleton(const Bone* parent, int depthCount);
std::map<std::string, Animation> Animations;
private:
std::map<std::string, Bone*> m_BonesByName;
glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix);
int GetKeyframe(const Animation& animation, double time);
int GetKeyframe(const Animation& animation, double time);
private:
glm::mat4 GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset);
std::map<std::string, Bone*> m_BonesByName;
float aim = 0.f;
};
#endif
+1 -1
View File
@@ -9,7 +9,7 @@ inline bool _GLERROR(const char* info, const char* file, const char* func, unsig
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s, %i, %s", info, error, gluErrorString(error));
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s\nError code: %i, %s\n", info, error, gluErrorString(error));
return true;
}
+18
View File
@@ -0,0 +1,18 @@
#ifndef Events_PlayQueueOnEntity_h__
#define Events_PlayQueueOnEntity_h__
#include "../Core/Event.h"
#include "../Core/EntityWrapper.h"
namespace Events
{
struct PlayQueueOnEntity : public Event
{
EntityWrapper Emitter;
std::vector<std::string> FilePaths;
};
}
#endif
+3
View File
@@ -1,6 +1,9 @@
#ifndef Sound_h__
#define Sound_h__
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include "Core/ResourceManager.h"
class Sound : public Resource
@@ -1,17 +1,23 @@
#ifndef SoundSystem_h__
#define SoundSystem_h__
#ifndef SoundManager_h__
#define SoundManager_h__
#include <unordered_map>
#include <random>
#include "glm/common.hpp"
#include "glm/gtx/rotate_vector.hpp" // Calculate Up vector
#include "OpenAL/al.h"
#include "OpenAL/alc.h"
#include "imgui/imgui.h"
#include "Core/World.h"
#include "Core/EventBroker.h"
#include "../Engine/Core/ResourceManager.h"
#include "../Engine/Core/ConfigFile.h"
#include "Core/Transform.h" // Absolute transform
#include "Sound/Sound.h"
#include "../Engine/Sound/EPlayQueueOnEntity.h"
#include "Sound/EPlaySoundOnEntity.h"
#include "Sound/EPlaySoundOnPosition.h"
#include "Sound/EPlayBackgroundMusic.h"
@@ -20,6 +26,11 @@
#include "Sound/EStopSound.h"
#include "Sound/ESetBGMGain.h"
#include "Sound/ESetSFXGain.h"
#include "Core/EPause.h"
#include "Core/EComponentAttached.h"
#include "../Core/EPlayerSpawned.h"
typedef std::pair<ALuint, std::vector<ALuint>> QueuedBuffers;
enum class SoundType {
SFX,
@@ -34,14 +45,15 @@ struct Source
SoundType Type;
};
class SoundSystem
class SoundManager
{
public:
SoundSystem() { }
SoundSystem(World* world, EventBroker* eventBroker, bool editorMode);
~SoundSystem();
SoundManager() { }
SoundManager(World* world, EventBroker* eventBroker);
~SoundManager();
// Update emitters / listener
void Update(double dt);
private:
// Help functions for working with OpenaAL
void setListenerPos(glm::vec3 pos) { alListener3f(AL_POSITION, pos.x, pos.y, pos.z); };
@@ -56,46 +68,62 @@ private:
// Logic
void initOpenAL();
void updateEmitters(double dt);
void updateListener(double dt);
void deleteInactiveEmitters();
void addNewEmitters(double dt);
Source* createSource(std::string filePath);
void playSound(Source* source);
void stopSound(Source* source);
void stopEmitters();
void updateListener(double dt);
ALenum getSourceState(ALuint source);
void setGain(Source* source, float gain);
void setSoundProperties(ALuint source, ComponentWrapper* soundComponent);
void setSoundProperties(Source* source, ComponentWrapper* soundComponent);
// Specific logic
void playSound(Source* source);
// Need to be the same format (sample rate etc)
void playQueue(QueuedBuffers qb);
void stopSound(Source* source);
Source* createSource(std::string filePath);
std::unordered_map<EntityID, Source*> m_Sources;
// Logic
World* m_World = nullptr;
EventBroker* m_EventBroker = nullptr;
// OpenAL system variables
ALCdevice* m_ALCdevice = nullptr;
ALCcontext* m_ALCcontext = nullptr;
// Logic
World* m_World = nullptr;
EventBroker* m_EventBroker = nullptr;
std::unordered_map<EntityID, Source*> m_Sources;
float m_BGMVolumeChannel = 1.0f;
float m_SFXVolumeChannel = 1.f;
bool m_EditorEnabled = false;
float m_SFXVolumeChannel = 1.0f;
EntityWrapper m_LocalPlayer = EntityWrapper();
// Events
EventRelay<SoundSystem, Events::PlaySoundOnEntity> m_EPlaySoundOnEntity;
EventRelay<SoundManager, Events::PlaySoundOnEntity> m_EPlaySoundOnEntity;
bool OnPlaySoundOnEntity(const Events::PlaySoundOnEntity &e);
EventRelay<SoundSystem, Events::PlaySoundOnPosition> m_EPlaySoundOnPosition;
EventRelay<SoundManager, Events::PlaySoundOnPosition> m_EPlaySoundOnPosition;
bool OnPlaySoundOnPosition(const Events::PlaySoundOnPosition &e);
EventRelay<SoundSystem, Events::PlayBackgroundMusic> m_EPlayBackgroundMusic;
EventRelay<SoundManager, Events::PlayBackgroundMusic> m_EPlayBackgroundMusic;
bool OnPlayBackgroundMusic(const Events::PlayBackgroundMusic &e);
EventRelay<SoundSystem, Events::PauseSound> m_EPauseSound;
EventRelay<SoundManager, Events::PauseSound> m_EPauseSound;
bool OnPauseSound(const Events::PauseSound &e);
EventRelay<SoundSystem, Events::StopSound> m_EStopSound;
EventRelay<SoundManager, Events::StopSound> m_EStopSound;
bool OnStopSound(const Events::StopSound &e);
EventRelay<SoundSystem, Events::ContinueSound> m_EContinueSound;
EventRelay<SoundManager, Events::ContinueSound> m_EContinueSound;
bool OnContinueSound(const Events::ContinueSound &e);
EventRelay<SoundSystem, Events::SetBGMGain> m_ESetBGMGain;
bool OnSetBGMGain(const Events::SetBGMGain &e); // Not tested
EventRelay<SoundSystem, Events::SetSFXGain> m_ESetSFXGain;
bool OnSetSFXGain(const Events::SetSFXGain &e); // Not tested
EventRelay<SoundManager, Events::SetBGMGain> m_ESetBGMGain;
bool OnSetBGMGain(const Events::SetBGMGain &e);
EventRelay<SoundManager, Events::SetSFXGain> m_ESetSFXGain;
bool OnSetSFXGain(const Events::SetSFXGain &e);
EventRelay<SoundManager, Events::ComponentAttached> m_EComponentAttached;
bool OnComponentAttached(const Events::ComponentAttached &e);
EventRelay<SoundManager, Events::Pause> m_EPause;
bool OnPause(const Events::Pause &e);
EventRelay<SoundManager, Events::Resume> m_EResume;
bool OnResume(const Events::Resume &e);
EventRelay<SoundManager, Events::PlayerSpawned> m_EPlayerSpawned;
bool OnPlayerSpawned(const Events::PlayerSpawned &e);
EventRelay<SoundManager, Events::PlayQueueOnEntity> m_EPlayQueueOnEntity;
bool OnPlayQueueOnEntity(const Events::PlayQueueOnEntity &e);
};
#endif