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

# Conflicts:
#	include/Engine/Common.h
#	include/Engine/Rendering/DrawFinalPass.h
#	include/Engine/Rendering/DrawScenePass.h
#	include/Engine/Rendering/RenderQueue.h
#	include/Engine/Rendering/Renderer.h
#	resources/Shaders/ForwardPlus.frag.glsl
#	resources/Shaders/ForwardPlus.vert.glsl
#	src/Engine/Rendering/DrawFinalPass.cpp
#	src/Engine/Rendering/DrawScenePass.cpp
#	src/Engine/Rendering/RenderSystem.cpp
#	src/Engine/Rendering/Renderer.cpp
#	src/Game/Game.cpp
This commit is contained in:
stiffly
2016-01-25 01:21:15 +01:00
251 changed files with 11834 additions and 3294 deletions
+3 -1
View File
@@ -26,7 +26,9 @@ set(SOURCE_FILES
${SOURCE_FILES}
"Game.cpp"
${SOURCE_FILES_Systems}
${SOURCE_FILES_Events}
${SOURCE_FILES_Events}
)
set(LIBRARIES
+19 -11
View File
@@ -8,6 +8,9 @@
#include "Systems/SpawnerSystem.h"
#include "Systems/PlayerSpawnSystem.h"
#include "Core/EntityFileWriter.h"
#include "Game/Systems/CapturePointSystem.h"
#include "Game/Systems/WeaponSystem.h"
#include "../Engine/Rendering/AnimationSystem.h"
Game::Game(int argc, char* argv[])
{
@@ -18,6 +21,7 @@ Game::Game(int argc, char* argv[])
ResourceManager::RegisterType<Texture>("Texture");
ResourceManager::RegisterType<ShaderProgram>("ShaderProgram");
ResourceManager::RegisterType<EntityFile>("EntityFile");
ResourceManager::RegisterType<Font>("FontFile");
m_Config = ResourceManager::Load<ConfigFile>("Config.ini");
ResourceManager::UseThreading = m_Config->Get<bool>("Multithreading.ResourceLoading", true);
@@ -27,9 +31,8 @@ Game::Game(int argc, char* argv[])
// Create the core event broker
m_EventBroker = new EventBroker();
// Create the renderer
m_Renderer = new Renderer(m_EventBroker, m_World);
m_Renderer = new Renderer(m_EventBroker);
m_Renderer->SetFullscreen(m_Config->Get<bool>("Video.Fullscreen", false));
m_Renderer->SetVSYNC(m_Config->Get<bool>("Video.VSYNC", false));
m_Renderer->SetResolution(Rectangle::Rectangle(
@@ -55,7 +58,7 @@ Game::Game(int argc, char* argv[])
m_FrameStack->Height = m_Renderer->Resolution().Height;
// Create a world
m_World = new World();
m_World = new World(m_EventBroker);
std::string mapToLoad = m_Config->Get<std::string>("Debug.LoadMap", "");
if (!mapToLoad.empty()) {
auto file = ResourceManager::Load<EntityFile>(mapToLoad);
@@ -64,33 +67,37 @@ Game::Game(int argc, char* argv[])
EntityFileParser fp(file);
fp.MergeEntities(m_World);
}
//SO MUCH TEMP PLEASE REMOVE ME OMFG VIKTOR HELP
m_Renderer->m_World = m_World;
// Create Octrees
m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4);
m_OctreeFrustrumCulling = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4);
m_OctreeCollision = new Octree<AABB>(AABB(glm::vec3(-100), glm::vec3(100)), 4);
m_OctreeFrustrumCulling = new Octree<AABB>(AABB(glm::vec3(-100), glm::vec3(100)), 4);
// Create system pipeline
m_SystemPipeline = new SystemPipeline(m_EventBroker);
m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker);
// All systems with orderlevel 0 will be updated first.
unsigned int updateOrderLevel = 0;
m_SystemPipeline->AddSystem<RaptorCopterSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<EditorSystem>(updateOrderLevel, m_Renderer);
m_SystemPipeline->AddSystem<ExplosionEffectSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<HealthSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<PlayerMovementSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<InterpolationSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<SpawnerSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<PlayerSpawnSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<WeaponSystem>(updateOrderLevel, m_Renderer);
// Populate Octree with collidables
++updateOrderLevel;
m_SystemPipeline->AddSystem<CollidableOctreeSystem>(updateOrderLevel, m_OctreeCollision);
m_SystemPipeline->AddSystem<AnimationSystem>(updateOrderLevel);
// Collision and TriggerSystem should update after player.
++updateOrderLevel;
m_SystemPipeline->AddSystem<CollisionSystem>(updateOrderLevel, m_OctreeCollision);
m_SystemPipeline->AddSystem<TriggerSystem>(updateOrderLevel, m_OctreeCollision);
++updateOrderLevel;
m_SystemPipeline->AddSystem<CapturePointSystem>(updateOrderLevel);
m_SystemPipeline->AddSystem<RenderSystem>(updateOrderLevel, m_Renderer, m_RenderFrame);
++updateOrderLevel;
m_SystemPipeline->AddSystem<EditorSystem>(updateOrderLevel, m_Renderer, m_RenderFrame);
// Invoke network
if (m_Config->Get<bool>("Networking.StartNetwork", false)) {
@@ -142,13 +149,14 @@ void Game::Tick()
m_ClientOrServer->Update();
}
// Iterate through systems and update world!
m_SystemPipeline->Update(m_World, dt);
m_EventBroker->Process<SystemPipeline>();
m_SystemPipeline->Update(dt);
debugTick(dt);
m_Renderer->Update(dt);
m_EventBroker->Process<Client>();
m_SoundSystem->Update(dt);
GLERROR("Game::Tick m_RenderQueueFactory->Update");
m_Renderer->Draw(*m_RenderFrame);
m_RenderFrame->Clear();
GLERROR("Game::Tick m_Renderer->Draw");
m_EventBroker->Swap();
m_EventBroker->Clear();
+242
View File
@@ -0,0 +1,242 @@
#include "Systems/CapturePointSystem.h"
#include <algorithm>
CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker)
: System(world, eventBroker)
, PureSystem("CapturePoint")
{
//subscribe/listenTo playerdamage,healthpickup events (using the eventBroker)
EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch);
EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave);
EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured);
}
//here all capturepoints will update their component
//NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt
void CapturePointSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& capturePoint, double dt)
{
if (m_WinnerWasFound) {
return;
}
const int capturePointNumber = capturePoint["CapturePointNumber"];
const bool hasTeamComponent = m_World->HasComponent(capturePoint.EntityID, "Team");
//if point doesnt have a teamComponent yet, add one. since:
//what if capture point has no team -> we cant get/use the team enum from it...
if (!hasTeamComponent) {
m_World->AttachComponent(capturePoint.EntityID, "Team");
ComponentWrapper& teamComponent = m_World->GetComponent(capturePoint.EntityID, "Team");
teamComponent["Team"] = (int)teamComponent["Team"].Enum("Spectator");
}
ComponentWrapper& teamComponent = m_World->GetComponent(capturePoint.EntityID, "Team");
const int redTeam = (int)teamComponent["Team"].Enum("Red");
const int blueTeam = (int)teamComponent["Team"].Enum("Blue");
const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator");
int homePointForTeam = (int)capturePoint["HomePointForTeam"];
if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) {
m_NumberOfCapturePoints = capturePointNumber + 1;//ex 2 -> 0,1,2 = 3
if (homePointForTeam == redTeam) {
m_RedTeamHomeCapturePoint = capturePointNumber;
m_BlueTeamHomeCapturePoint = 0;
} else {
m_BlueTeamHomeCapturePoint = capturePointNumber;
m_RedTeamHomeCapturePoint = 0;
}
}
//if we havent received all capturepoints yet, just return
if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityIDMap.size()) {
m_CapturePointNumberToEntityIDMap.insert(std::make_pair(capturePointNumber, capturePoint.EntityID));
return;
}
//we have all capturepoints now - process stuff
int ownedBy = teamComponent["Team"];
int redTeamPlayersStandingInside = 0;
int blueTeamPlayersStandingInside = 0;
if (entity.HasComponent("Model")) {
//Now sets team color to the capturepoint, or white if it is uncaptured.
entity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 1) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 1) : glm::vec4(1, 1, 1, 1);
}
//calculate next possible capturePoint for both teams
std::map<std::string, int> nextPossibleCapturePoint;
nextPossibleCapturePoint["Red"] = -1;
nextPossibleCapturePoint["Blue"] = -1;
for (size_t i = 0; i < m_NumberOfCapturePoints; i++)
{
if (!m_World->HasComponent(m_CapturePointNumberToEntityIDMap[i], "Team")) {
continue;
}
ComponentWrapper& capturePointOwnedBy = m_World->GetComponent(m_CapturePointNumberToEntityIDMap[i], "Team");
if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint == 0) {
nextPossibleCapturePoint["Red"] = i + 1;
}
if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint == 0) {
nextPossibleCapturePoint["Blue"] = i + 1;
}
}
for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--)
{
if (!m_World->HasComponent(m_CapturePointNumberToEntityIDMap[i], "Team")) {
continue;
}
ComponentWrapper& capturePointOwnedBy = m_World->GetComponent(m_CapturePointNumberToEntityIDMap[i], "Team");
if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint != 0) {
nextPossibleCapturePoint["Red"] = i - 1;
}
if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint != 0) {
nextPossibleCapturePoint["Blue"] = i - 1;
}
}
//reset timers and reset the bool that triggers this
if (m_ResetTimers) {
for (size_t i = 0; i < m_NumberOfCapturePoints; i++)
{
ComponentWrapper& capturePoint = m_World->GetComponent(m_CapturePointNumberToEntityIDMap[i], "CapturePoint");
if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] &&
(int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) {
capturePoint["CaptureTimer"] = 0.0;
}
}
m_ResetTimers = false;
}
//colorize next possible capturepoint
if (nextPossibleCapturePoint["Red"] == capturePointNumber) {
entity["Model"]["Color"] = glm::vec4(1, 1, 0, 1);
}
if (nextPossibleCapturePoint["Blue"] == capturePointNumber) {
entity["Model"]["Color"] = glm::vec4(0, 1, 1, 1);
}
//check how many players are standing inside and are healthy
for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--)
{
auto triggerTouched = m_ETriggerTouchVector[i - 1];
if (std::get<1>(triggerTouched) == capturePoint.EntityID) {
//some player has touched this - lets figure out: what team, health
EntityID playerID = std::get<0>(triggerTouched);
if (!m_World->HasComponent(playerID, "Player")) {
//if a non-player has entered the capturePoint, just erase that event and continue
m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i - 1);
continue;
}
bool hasHealthComponent = m_World->HasComponent(playerID, "Health");
if (hasHealthComponent) {
double currentHealth = m_World->GetComponent(playerID, "Health")["Health"];
//check if player is dead
if ((int)currentHealth == 0) {
continue;
}
}
//check team - spectatorNumber = "no team"
int teamNumber = m_World->GetComponent(playerID, "Team")["Team"];
if (teamNumber == redTeam) {
redTeamPlayersStandingInside++;
} else if (teamNumber == blueTeam) {
blueTeamPlayersStandingInside++;
}
continue;
}
}
//create data to be used in option B
//check so this is the next possible capture point for the take-over team and see if only one team is standing inside it
double timerDeltaChange = 0.0;
int currentTeam = 0;
bool canCapture = false;
if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside == 0) {
timerDeltaChange = redTeamPlayersStandingInside*dt;
currentTeam = redTeam;
canCapture = nextPossibleCapturePoint["Red"] == capturePointNumber;
}
if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside > 0) {
timerDeltaChange = -blueTeamPlayersStandingInside*dt;
currentTeam = blueTeam;
canCapture = nextPossibleCapturePoint["Blue"] == capturePointNumber;
}
if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside == 0) {
//A.nobodys standing inside
//do nothing (?)
} else if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside > 0) {
//C.both teams have players inside
//do nothing (?)
} else {
//B. at most one of the teams have players inside
//if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly
if (ownedBy != currentTeam && canCapture) {
if (abs((double)capturePoint["CaptureTimer"]) < 0.001f) {
LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently.
}
capturePoint["CaptureTimer"] = (double)capturePoint["CaptureTimer"] + timerDeltaChange;
}
//if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0
if ((ownedBy == currentTeam && currentTeam == redTeam && (double)capturePoint["CaptureTimer"] < 0.0) ||
(ownedBy == currentTeam && currentTeam == blueTeam && (double)capturePoint["CaptureTimer"] > 0.0)) {
capturePoint["CaptureTimer"] = (double)capturePoint["CaptureTimer"] + timerDeltaChange;
}
//check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event
if (abs((double)capturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) {
teamComponent["Team"] = currentTeam;
capturePoint["CaptureTimer"] = 0.0;
//publish Captured event
LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently.
Events::Captured e;
e.CapturePointID = capturePoint.EntityID;
e.TeamNumberThatCapturedCapturePoint = currentTeam;
m_EventBroker->Publish(e);
//NextPossibleCapturePoint will be calculated in the next update...
}
}
//check for possible winCondition = check if the homebase is owned by the other team
bool checkForWinner = false;
if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam)
{
checkForWinner = true;
}
if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam)
{
checkForWinner = true;
}
if (checkForWinner && !m_WinnerWasFound)
{
//publish Win event
Events::Win e;
e.TeamThatWon = ownedBy;
m_EventBroker->Publish(e);
m_WinnerWasFound = true;
}
}
bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e)
{
//personEntered = e.Entity, thingEntered = e.Trigger
m_ETriggerTouchVector.push_back(std::make_tuple(e.Entity, e.Trigger));
return true;
}
bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e)
{
for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++)
{
auto triggerTouched = m_ETriggerTouchVector[i];
if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) {
m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i);
break;
}
}
return true;
}
bool CapturePointSystem::OnCaptured(const Events::Captured& e)
{
//reset the timers in the next update since a capture has changed the "nextCapturePoint" for 1-2 teams
m_ResetTimers = true;
return true;
}
+19 -11
View File
@@ -1,7 +1,7 @@
#include "Systems/HealthSystem.h"
HealthSystem::HealthSystem(EventBroker* eventBroker)
: System(eventBroker)
HealthSystem::HealthSystem(World* m_World, EventBroker* eventBroker)
: System(m_World, eventBroker)
, PureSystem("Health")
{
//subscribe/listenTo playerdamage,healthpickup events (using the eventBroker)
@@ -9,10 +9,9 @@ HealthSystem::HealthSystem(EventBroker* eventBroker)
EVENT_SUBSCRIBE_MEMBER(m_EPlayerHealthPickup, &HealthSystem::OnPlayerHealthPickup);
}
void HealthSystem::UpdateComponent(World* world, EntityWrapper& entity, ComponentWrapper& component, double dt)
void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt)
{
//if entityID of health is 9 then the players ID is also 9 (player,health are connected to the same entity)
ComponentWrapper player = world->GetComponent(component.EntityID, "Player");
double maxHealth = (double)component["MaxHealth"];
//process the DeltaHealthVector and change the entitys health accordingly
@@ -20,34 +19,42 @@ void HealthSystem::UpdateComponent(World* world, EntityWrapper& entity, Componen
{
auto deltaHP = m_DeltaHealthVector[i - 1];
//if we have a healthchange for the current player and health is greater than 0, then apply it
if (std::get<0>(deltaHP) == player.EntityID && (double)component["Health"] > 0.0f) {
if (std::get<0>(deltaHP) == component.EntityID && (double)component["Health"] > 0.0f) {
//get the deltaHP value from the tuple and make sure you dont get more than maxHealth
double newHealth = std::min((double)component["Health"] + (double)std::get<1>(deltaHP), maxHealth);
component["Health"] = newHealth;
m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + i - 1);
//check if health is <= 0
if ((double)component["Health"] <= 0.0f) {
component["Health"] = 0.0;
//publish death event
Events::PlayerDeath e;
e.PlayerID = player.EntityID;
e.PlayerID = component.EntityID;
m_EventBroker->Publish(e);
//clear the remaining hpDeltas for the dead player
for (size_t j = m_DeltaHealthVector.size(); j > 0; j--)
{
if (std::get<0>(m_DeltaHealthVector[j - 1]) == player.EntityID)
if (std::get<0>(m_DeltaHealthVector[j - 1]) == component.EntityID)
m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + j - 1);
}
//break the loop if the player is dead
//delete the player and break the loop
m_World->DeleteEntity(entity.ID);
break;
}
}
}
}
bool HealthSystem::OnPlayerDamaged(const Events::PlayerDamage& e)
bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e)
{
//save the changed HP to a vector. it will be taken care of in UpdateComponent
m_DeltaHealthVector.push_back(std::make_tuple(e.PlayerDamagedID, -e.DamageAmount));
ComponentWrapper cHealth = e.Player["Health"];
double& health = cHealth["Health"];
health -= e.Damage;
if (health <= 0.0) {
m_World->DeleteEntity(e.Player.ID);
}
return true;
}
@@ -57,3 +64,4 @@ bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e)
m_DeltaHealthVector.push_back(std::make_tuple(e.PlayerHealedID, e.HealthAmount));
return true;
}
+84
View File
@@ -0,0 +1,84 @@
#include "Systems/InterpolationSystem.h"
InterpolationSystem::InterpolationSystem(World* world, EventBroker* eventBroker)
: System(world, eventBroker)
, PureSystem("Transform")
{
ConfigFile* config = ResourceManager::Load<ConfigFile>("Config.ini");
m_SnapshotInterval = config->Get<float>("Networking.SnapshotInterval", 0.05);
EVENT_SUBSCRIBE_MEMBER(m_EInterpolate, &InterpolationSystem::OnInterpolate);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &InterpolationSystem::OnPlayerSpawned);
}
void InterpolationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt)
{
// Don't interpolate entities that might already have been removed
if (!entity.Valid()) {
return;
}
if (m_NextTransform.find(transform.EntityID) != m_NextTransform.end()) { // Exists in map
m_NextTransform[transform.EntityID].interpolationTime += dt;
Transform sTransform = m_NextTransform[transform.EntityID];
double time = sTransform.interpolationTime;
if (time > m_SnapshotInterval) {
if (m_LastReceivedTransform.find(transform.EntityID) != m_LastReceivedTransform.end()) {
m_NextTransform[transform.EntityID] = m_LastReceivedTransform[transform.EntityID];
m_NextTransform[transform.EntityID].interpolationTime = time - m_SnapshotInterval;
sTransform = m_NextTransform[transform.EntityID];
m_LastReceivedTransform.erase(transform.EntityID);
} else {
m_NextTransform.erase(transform.EntityID);
}
}
if (transform.Info.Name == "Transform") {
bool isLocalPlayer = entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer);
// Position
glm::vec3 nextPosition = sTransform.Position;
glm::vec3 currentPosition = static_cast<glm::vec3>(transform["Position"]);
// HACK: Don't force position for players
if (!isLocalPlayer) {
(glm::vec3&)transform["Position"] += vectorInterpolation<glm::vec3>(currentPosition, nextPosition, sTransform.interpolationTime);
}
// Orientation
// Don't force orientation for players
if (!isLocalPlayer) {
glm::quat nextOrientation = sTransform.Orientation;
glm::quat currentOrientation = glm::quat(static_cast<glm::vec3>(transform["Orientation"]));
(glm::vec3&)transform["Orientation"] = glm::eulerAngles(glm::slerp<float>(currentOrientation, nextOrientation, sTransform.interpolationTime / m_SnapshotInterval));
}
// Scale
glm::vec3 nextScale = sTransform.Scale;
glm::vec3 currentScale = static_cast<glm::vec3>(transform["Scale"]);
(glm::vec3&)transform["Scale"] += vectorInterpolation<glm::vec3>(currentScale, nextScale, sTransform.interpolationTime);
}
}
}
bool InterpolationSystem::OnPlayerSpawned(Events::PlayerSpawned& e)
{
m_LocalPlayer = e.Player;
return true;
}
bool InterpolationSystem::OnInterpolate(const Events::Interpolate & e)
{
Transform transform;
int offset = 0;
// Read the data
memcpy(&transform.Position, e.DataArray.get() + offset, sizeof(glm::vec3));
offset += sizeof(glm::vec3);
glm::vec3 tempOrientation;
memcpy(&tempOrientation, e.DataArray.get() + offset, sizeof(glm::vec3));
transform.Orientation = glm::quat(tempOrientation);
offset += sizeof(glm::vec3);
memcpy(&transform.Scale, e.DataArray.get() + offset, sizeof(glm::vec3));
transform.interpolationTime = 0.0f;
if (m_NextTransform.find(e.Entity) != m_NextTransform.end()) { // Did exist
m_LastReceivedTransform[e.Entity] = transform;
} else { // Did not
m_NextTransform[e.Entity] = transform;
}
return false;
}
+148 -4
View File
@@ -1,16 +1,160 @@
#include "Systems/PlayerMovementSystem.h"
void PlayerMovementSystem::UpdateComponent(World* world, EntityWrapper& entity, ComponentWrapper& component, double dt)
PlayerMovementSystem::PlayerMovementSystem(World* world, EventBroker* eventBroker)
: System(world, eventBroker)
, PureSystem("Player")
{
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned);
}
PlayerMovementSystem::~PlayerMovementSystem()
{
for (auto& kv : m_PlayerInputControllers) {
delete kv.second;
}
}
void PlayerMovementSystem::Update(double dt)
{
for (auto& kv : m_PlayerInputControllers) {
EntityWrapper player = kv.first;
auto& controller = kv.second;
if (!player.Valid()) {
continue;
}
EntityWrapper cameraEntity = player.FirstChildByName("Camera");
if (cameraEntity.Valid()) {
glm::vec3& cameraOrientation = cameraEntity["Transform"]["Orientation"];
cameraOrientation.x += controller->Rotation().x;
// Limit camera pitch so we don't break our necks
cameraOrientation.x = glm::clamp(cameraOrientation.x, -glm::half_pi<float>(), glm::half_pi<float>());
}
ComponentWrapper& cTransform = player["Transform"];
glm::vec3& ori = cTransform["Orientation"];
ori.y += controller->Rotation().y;
float playerMovementSpeed = player["Player"]["MovementSpeed"];
float playerCrouchSpeed = player["Player"]["CrouchSpeed"];
if (player.HasComponent("Physics")) {
ComponentWrapper cPhysics = player["Physics"];
glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori));
float wishSpeed;
if (controller->Crouching()) {
wishSpeed = playerCrouchSpeed;
} else {
wishSpeed = playerMovementSpeed;
}
glm::vec3& velocity = cPhysics["Velocity"];
ImGui::Text("velocity: (%f, %f, %f)", velocity.x, velocity.y, velocity.z);
glm::vec3 groundVelocity(0.f, 0.f, 0.f);
groundVelocity.x = glm::dot(velocity, glm::vec3(1.f, 0.f, 0.f));
groundVelocity.z = glm::dot(velocity, glm::vec3(0.f, 0.f, 1.f));
ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(wishDirection));
ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection));
float currentSpeedProj = glm::dot(groundVelocity, wishDirection);
float addSpeed = wishSpeed - currentSpeedProj;
ImGui::Text("currentSpeedProj: %f", currentSpeedProj);
ImGui::Text("wishSpeed: %f", wishSpeed);
ImGui::Text("addSpeed: %f", addSpeed);
if (addSpeed > 0) {
static float accel = 15.f;
ImGui::InputFloat("accel", &accel);
static float airAccel = 0.5f;
ImGui::InputFloat("airAccel", &airAccel);
float actualAccel = (velocity.y != 0) ? airAccel : accel;
static float surfaceFriction = 5.f;
ImGui::InputFloat("surfaceFriction", &surfaceFriction);
float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction;
accelerationSpeed = glm::min(accelerationSpeed, addSpeed);
velocity += accelerationSpeed * wishDirection;
ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity));
}
if (controller->Jumping() && !controller->Crouching() && velocity.y == 0.f) {
velocity.y += 4.f;
}
//if (player.HasComponent("AABB")) {
// glm::vec3& size = player["AABB"]["Size"];
// if (controller->Crouching()) {
// size = glm::vec3(1.f, 1.f, 1.f);
// } else {
// size = glm::vec3(1.f, 1.6f, 1.f);
// }
//}
// Animations
EntityWrapper playerModel = player.FirstChildByName("PlayerModel");
if (playerModel.Valid()) {
ComponentWrapper cAnimation = playerModel["Animation"];
float movementLength = glm::length(groundVelocity);
if (glm::length(controller->Movement()) > 0.f) {
if (controller->Crouching()) {
cAnimation["Name"] = "Crouch Walk";
(double&)cAnimation["Speed"] = 1.f * -glm::sign(controller->Movement().z);
} else {
cAnimation["Name"] = "Run";
(double&)cAnimation["Speed"] = 2.f * -glm::sign(controller->Movement().z);
}
} else {
if (controller->Crouching()) {
cAnimation["Name"] = "Crouch";
(double&)cAnimation["Speed"] = 1.f;
} else {
cAnimation["Name"] = "Hold Pos";
(double&)cAnimation["Speed"] = 1.f;
}
}
}
}
controller->Reset();
}
}
void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt)
{
ComponentWrapper& cTransform = entity["Transform"];
if (!entity.HasComponent("Physics")) {
return;
}
ComponentWrapper& cPhysics = entity["Physics"];
ComponentWrapper& cPhysics = entity["Physics"];
glm::vec3& velocity = cPhysics["Velocity"];
velocity.y -= 9.82 * dt;
// Ground friction
float speed = glm::length(velocity);
static float groundFriction = 7.f;
ImGui::InputFloat("groundFriction", &groundFriction);
static float airFriction = 0.f;
ImGui::InputFloat("airFriction", &airFriction);
float friction = (velocity.y != 0) ? airFriction : groundFriction;
if (speed > 0) {
float drop = speed * friction * (float)dt;
float multiplier = glm::max(speed - drop, 0.f) / speed;
velocity.x *= multiplier;
velocity.z *= multiplier;
}
if (cPhysics["Gravity"]) {
velocity.y -= 9.82f * (float)dt;
}
glm::vec3& position = cTransform["Position"];
position += velocity * (float)dt;
}
}
bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e)
{
// When a player spawns, create an input controller for them
m_PlayerInputControllers[e.Player] = new FirstPersonInputController<PlayerMovementSystem>(m_EventBroker, e.PlayerID);
return true;
}
+69 -9
View File
@@ -1,28 +1,30 @@
#include "Systems/PlayerSpawnSystem.h"
PlayerSpawnSystem::PlayerSpawnSystem(EventBroker* eventBroker)
: System(eventBroker)
PlayerSpawnSystem::PlayerSpawnSystem(World* m_World, EventBroker* eventBroker)
: System(m_World, eventBroker)
{
EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand);
EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned);
m_NetworkEnabled = ResourceManager::Load<ConfigFile>("Config.ini")->Get("Networking.StartNetwork", false);
}
void PlayerSpawnSystem::Update(World* world, double dt)
void PlayerSpawnSystem::Update(double dt)
{
auto playerSpawns = world->GetComponents("PlayerSpawn");
auto playerSpawns = m_World->GetComponents("PlayerSpawn");
if (playerSpawns == nullptr) {
return;
}
for (auto& team : m_SpawnRequests) {
for (auto& req : m_SpawnRequests) {
for (auto& cPlayerSpawn : *playerSpawns) {
EntityWrapper spawner(world, cPlayerSpawn.EntityID);
EntityWrapper spawner(m_World, cPlayerSpawn.EntityID);
if (!spawner.HasComponent("Spawner")) {
continue;
}
// If the spawner has a team affiliation, check it
if (spawner.HasComponent("Team")) {
if ((int)spawner["Team"]["Team"] != team) {
if ((int)spawner["Team"]["Team"] != req.Team) {
continue;
}
}
@@ -30,7 +32,15 @@ void PlayerSpawnSystem::Update(World* world, double dt)
// Spawn the player!
EntityWrapper player = SpawnerSystem::Spawn(spawner);
// Set the player team affiliation
player["Team"]["Team"] = team;
player["Team"]["Team"] = req.Team;
// Publish a PlayerSpawned event
Events::PlayerSpawned e;
e.PlayerID = req.PlayerID;
e.Player = player;
e.Spawner = spawner;
m_EventBroker->Publish(e);
}
}
m_SpawnRequests.clear();
@@ -42,10 +52,60 @@ bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e)
return false;
}
// Team picks should be processed ONLY server-side!
// Don't make a spawn request if PlayerID is -1, i.e. we're the client.
if (e.PlayerID == -1 && m_NetworkEnabled) {
return false;
}
if (e.Value != 0) {
m_SpawnRequests.push_back((int)e.Value);
SpawnRequest req;
req.PlayerID = e.PlayerID;
req.Team = (ComponentInfo::EnumType)e.Value;
m_SpawnRequests.push_back(req);
}
return true;
}
bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e)
{
// When a player is actually spawned (since the actual spawning is handled on the server)
// Check if a player already exists
if (m_PlayerEntities.count(e.PlayerID) != 0) {
// TODO: Disallow infinite respawning here
m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID);
}
// Store the player for future reference
m_PlayerEntities[e.PlayerID] = e.Player;
// Set the camera to the correct entity
EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera");
if (cameraEntity.Valid()) {
Events::SetCamera e;
e.CameraEntity = cameraEntity;
m_EventBroker->Publish(e);
}
// HACK: Set the player model color to team color
EntityWrapper playerModel = e.Player.FirstChildByName("PlayerModel");
if (playerModel.Valid() && e.Player.HasComponent("Team")) {
ComponentWrapper cTeam = e.Player["Team"];
ComponentWrapper cModel = playerModel["Model"];
if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Red")) {
cModel["Color"] = glm::vec3(1.f, 0.f, 0.f);
} else if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Blue")) {
cModel["Color"] = glm::vec3(0.f, 0.25f, 1.f);
}
}
// TODO: Set the player name to whatever
//EntityWrapper playerName = e.Player.FirstChildByName("PlayerName");
//if (playerName.Valid()) {
// playerName["Text"]["Content"] = ???;
//}
return true;
}
+2 -1
View File
@@ -1,6 +1,7 @@
#include "Systems/SpawnerSystem.h"
SpawnerSystem::SpawnerSystem(EventBroker* eventBroker) : System(eventBroker)
SpawnerSystem::SpawnerSystem(World* world, EventBroker* eventBroker)
: System(world, eventBroker)
{
EVENT_SUBSCRIBE_MEMBER(m_OnSpawnerSpawn, &SpawnerSystem::OnSpawnerSpawn);
}
+87
View File
@@ -0,0 +1,87 @@
#include "Systems/WeaponSystem.h"
WeaponSystem::WeaponSystem(World* world, EventBroker* eventBroker, IRenderer* renderer)
: System(world, eventBroker)
, ImpureSystem()
, m_Renderer(renderer)
{
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &WeaponSystem::OnPlayerSpawned);
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponSystem::OnInputCommand);
EVENT_SUBSCRIBE_MEMBER(m_EShoot, &WeaponSystem::OnShoot);
}
void WeaponSystem::Update(double dt)
{
}
bool WeaponSystem::OnPlayerSpawned(const Events::PlayerSpawned& e)
{
if (e.PlayerID == -1) {
m_LocalPlayer = e.Player;
}
return true;
}
bool WeaponSystem::OnInputCommand(const Events::InputCommand& e)
{
// Only shoot if the player is alive
if (!m_LocalPlayer.Valid()) {
return false;
}
if (e.Command == "PrimaryFire" && e.Value > 0) {
Events::Shoot eShoot;
eShoot.Player = m_LocalPlayer;
m_EventBroker->Publish(eShoot);
}
return true;
}
bool WeaponSystem::OnShoot(const Events::Shoot& eShoot)
{
// TODO: Weapon firing effects here
// Only run further picking code client-side!
if (eShoot.Player != m_LocalPlayer) {
return false;
}
// Screen center, based on current resolution!
// TODO: check if player has enough ammo and if weapon has a cooldown or not
Rectangle screenResolution = m_Renderer->Resolution();
glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2);
// TODO: check if player has enough ammo and if weapon has a cooldown or not
// Pick middle of screen
PickData pickData = m_Renderer->Pick(centerScreen);
if (pickData.Entity == EntityID_Invalid) {
return false;
}
EntityWrapper player(m_World, pickData.Entity);
// Only care about players being hit
if (!player.HasComponent("Player")) {
player = player.FirstParentWithComponent("Player");
}
if (!player.Valid()) {
return false;
}
// Check for friendly fire
EntityWrapper shooter = eShoot.Player;
if ((ComponentInfo::EnumType)player["Team"]["Team"] == (ComponentInfo::EnumType)shooter["Team"]["Team"]) {
return false;
}
// TODO: Weapon damage calculations etc
Events::PlayerDamage ePlayerDamage;
ePlayerDamage.Player = player;
ePlayerDamage.Damage = 100;
m_EventBroker->Publish(ePlayerDamage);
return true;
}