<commit_before>// Project specific
#include <Server.hpp>
#include <Doremi/Core/Include/GameCore.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/TransformComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityHandlerServer.hpp>
#include <Doremi/Core/Include/EventHandler/EventHandler.hpp>
#include <Doremi/Core/Include/EventHandler/Events/EntityCreatedEvent.hpp>
#include <Doremi/Core/Include/PlayerHandler.hpp>
#include <Doremi/Core/Include/Manager/Manager.hpp>
#include <Doremi/Core/Include/Manager/Network/ServerNetworkManager.hpp>
#include <Doremi/Core/Include/Manager/MovementManager.hpp>
#include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp>
#include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp>
#include <Doremi/Core/Include/TemplateCreator.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
#include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp>
#include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/AIModule.hpp>
#include <Doremi/Core/Include/Manager/JumpManager.hpp>
#include <Doremi/Core/Include/Manager/GravityManager.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp>
#include <Doremi/Core/Include/LevelLoaderServer.hpp>
#include <DoremiEngine/Physics/Include/FluidManager.hpp>
// Timer
#include <Utility/Timer/Include/Measure/MeasureTimer.hpp>

// Third party
#include <DirectXMath.h>

// Standard libraries
#include <stdexcept>
#include <exception>
#include <chrono>

namespace Doremi
{
    ServerMain::ServerMain() {}

    ServerMain::~ServerMain() {}

    void ServerMain::Initialize()
    {
        TIME_FUNCTION_START
        const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine(
            DoremiEngine::Core::EngineModuleEnum::NETWORK | DoremiEngine::Core::EngineModuleEnum::PHYSICS | DoremiEngine::Core::EngineModuleEnum::AI);

        /* This starts the physics handler. Should not be done here, but since this is the general
        code dump, it'll work for now TODOJB*/

        Core::EntityHandlerServer::StartupEntityHandlerServer();
        Core::PlayerHandler::StartPlayerHandler(sharedContext);

        ////////////////Example only////////////////
        // Create manager

        // Manager* t_physicsManager = new ExampleManager(sharedContext);
        Core::Manager* t_serverNetworkManager = new Core::ServerNetworkManager(sharedContext);
        Core::Manager* t_movementManager = new Core::MovementManager(sharedContext);
        Core::Manager* t_rigidTransSyndManager = new Core::RigidTransformSyncManager(sharedContext);

        Core::Manager* t_aiPathManager = new Core::AIPathManager(sharedContext);
        Core::Manager* t_charSyncManager = new Core::CharacterControlSyncManager(sharedContext); // TODO check if needed
        Core::Manager* t_jumpManager = new Core::JumpManager(sharedContext);
        Core::Manager* t_gravManager = new Core::GravityManager(sharedContext);

        // Add manager to list of managers
        // Remember to put server last (cause we want on same frame as we update to send data, or at least close togeather)
        // m_managers.push_back(t_physicsManager);
        m_managers.push_back(t_serverNetworkManager);
        m_managers.push_back(t_rigidTransSyndManager);
        m_managers.push_back(t_movementManager);
        m_managers.push_back(t_aiPathManager);
        m_managers.push_back(t_charSyncManager);
        m_managers.push_back(t_jumpManager);
        m_managers.push_back(t_gravManager);

        // GenerateWorld(sharedContext);
        // GenerateWorldServerJawsTest(sharedContext);

        Core::TemplateCreator::GetInstance()->CreateTemplatesForServer(sharedContext);
        SpawnDebugWorld(sharedContext);

        ////////////////End Example////////////////

        // Remove later, needed to see something when we play solo cause of camera interactions with input
        // Doremi::Core::InputHandlerClient* inputHandler = new Doremi::Core::InputHandlerClient(sharedContext);
        // Core::PlayerHandler::GetInstance()->CreateNewPlayer(300, (Doremi::Core::InputHandler*)inputHandler);
        TIME_FUNCTION_STOP
    }

    void ServerMain::SpawnDebugWorld(const DoremiEngine::Core::SharedContext& sharedContext)
    {
        TIME_FUNCTION_START
        Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance();
        Core::LevelLoaderServer* t_levelLoader = new Core::LevelLoaderServer(sharedContext);
        t_levelLoader->LoadLevel("Levels/test.drm");
        // Create entity
        // int playerID = t_entityHandler.CreateEntity(Blueprints::PlayerEntity);

        //// Create the rigid body
        // int materialID = t_entityHandler.GetComponentFromStorage<Core::PhysicsMaterialComponent>(playerID)->p_materialID;
        // DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10, 0);
        // DirectX::XMFLOAT4 orientation = DirectX::XMFLOAT4(0, 0, 0, 1);
        // Core::RigidBodyComponent* bodyComp = t_entityHandler.GetComponentFromStorage<Core::RigidBodyComponent>(playerID);
        /*bodyComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(playerID, position, orientation,
                                                                                DirectX::XMFLOAT3(0.5, 0.5, 0.5), materialID);*/

        // sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(playerID, materialID, position, XMFLOAT2(1, 1));
        // Core::EntityHandler::GetInstance().AddComponent(playerID, (int)ComponentType::CharacterController);

        int entityDebugJaws = t_entityFactory.CreateEntity(Blueprints::JawsDebugEntity);
        Core::TransformComponent* trans = GetComponent<Core::TransformComponent>(entityDebugJaws);
        trans->position = DirectX::XMFLOAT3(-10, 5, 0);

        // TODOKO REMOVE Create debug potentialfields
        for(size_t i = 0; i < 1; i++)
        {
            int entityID = t_entityHandler.CreateEntity(Blueprints::DebugPotentialFieldActor);
            DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 0, 0);
            DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
            int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID;
            Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID);
            rigidComp->p_bodyID =
                sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(entityID, position, orientation, XMFLOAT3(0.5, 0.5, 0.5), matID);

            Core::PotentialFieldComponent* actor = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID);
            actor->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(position, 10, 10, true);
        }

        for(size_t i = 0; i < 5; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity);
            DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10 - (int)i, i * 5);
            DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
            int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID;
            Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID);
            rigidComp->p_bodyID =
                sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation, XMFLOAT3(2, 0.05, 2), matID);
        }

        // Create some enemies
        for(size_t i = 0; i < 8; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::EnemyEntity);
            XMFLOAT3 position = DirectX::XMFLOAT3(0, 7 - (int)i, i * 5);
            XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
            int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID;
            // RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID);
            // rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation,
            //                                                                                XMFLOAT3(0.5, 0.5, 0.5), matID);
            sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(entityID, matID, position, XMFLOAT2(0.1, 0.5));

            Core::PotentialFieldComponent* potentialComponent =
                Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID);
            potentialComponent->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(DirectX::XMFLOAT3(0, 0, 0), -1, 3, false);

            Core::EntityCreatedEvent* AIGroupActorCreated = new Core::EntityCreatedEvent(entityID, Core::EventType::AiGroupActorCreation);
            Core::EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);
        }

        int entityID = t_entityFactory.CreateEntity(Blueprints::ExperimentalPressureParticleEntity);
        DoremiEngine::Physics::ParticleEmitterData emitterData;
        emitterData.m_density = 3;
        emitterData.m_dimensions = XMFLOAT2(0, 0);
        emitterData.m_direction = XMFLOAT4(0, 0, 0, 1);
        emitterData.m_emissionAreaDimensions = XMFLOAT2(0.1, 0.4);
        emitterData.m_emissionRate = 1;
        emitterData.m_launchPressure = 2;
        emitterData.m_position = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(entityID)->position;
        // sharedContext.GetPhysicsModule().GetFluidManager().CreateParticleEmitter(entityID, emitterData);

        // TODO Not using this event atm, because of refac, will need to find some solution
        /*PlayerCreationEvent* playerCreationEvent = new PlayerCreationEvent();
        playerCreationEvent->eventType = Events::PlayerCreation;
        playerCreationEvent->playerEntityID = playerID;*/

        // EventHandler::GetInstance()->BroadcastEvent(playerCreationEvent);

        // for(size_t i = 0; i < 1; i++)
        //{
        //    int entityID = t_entityHandler.CreateEntity(Blueprints::PlatformEntity);
        //    XMFLOAT3 position = DirectX::XMFLOAT3(0, -2 - (int)i, i * 5);
        //    XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
        //    int matID = EntityHandler::GetInstance().GetComponentFromStorage<PhysicsMaterialComponent>(entityID)->p_materialID;
        //    RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID);/*
        //    rigidComp->p_bodyID =
        //        sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(2, 0.05, 2), matID);*/
        //    rigidComp->p_bodyID =
        //        sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(200, 0.05, 200), matID);
        //}
        TIME_FUNCTION_STOP
    }

    void JawsSimulatePhysicsDebug(double deltaTime)
    {
        TIME_FUNCTION_START
        Core::TransformComponent* trans = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(0);

        if(trans->position.x == -10)
        {
            trans->position.y += deltaTime;
            if(trans->position.y > 5)
            {
                trans->position.x = -11;
            }
        }
        else
        {
            trans->position.y -= deltaTime;
            if(trans->position.y < -5)
            {
                trans->position.x = -10;
            }
        }
        DirectX::XMStoreFloat4(&trans->rotation, DirectX::XMQuaternionRotationRollPitchYaw(0, 0, trans->position.y * 1.0f));
        TIME_FUNCTION_STOP
    }

    void ServerMain::Run()
    {
        TIME_FUNCTION_START
        std::chrono::time_point<std::chrono::high_resolution_clock> CurrentClock, PreviousClock;
        PreviousClock = std::chrono::high_resolution_clock::now();

        double Frame = 0;
        double Offset = 0;
        double Accum = 0;
        double GameTime = 0;
        double UpdateStepLen = 0.017;

        while(true)
        {
            CurrentClock = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> duration = (CurrentClock - PreviousClock);
            Frame = duration.count() + Offset;
            Offset = 0;

            // We simulate maximum 250 milliseconds each frame
            // If we would let it be alone we would get mayor stops instead of lesser ones that will slowly catch up
            if(Frame > 0.25f)
            {
                Offset = Frame - 0.25f;
                Frame = 0.25f;
            }

            // Update the previous position with frametime so we can catch up if we slow down
            PreviousClock = CurrentClock;

            // Update Accumulator (how much we will work this frame)
            Accum += Frame;

            // Loop as many update-steps we will take this frame
            while(Accum >= UpdateStepLen)
            {
                // Update Game logic
                JawsSimulatePhysicsDebug(UpdateStepLen); // TODOCM remove
                // Update Game logic
                UpdateGame(UpdateStepLen);

                // Remove time from accumulator
                // Accumulator -= UpdateTimeStepLength;
                Accum -= UpdateStepLen;

                // Add time to start
                GameTime += UpdateStepLen;
            }
        }
        TIME_FUNCTION_STOP
    }

    void ServerMain::UpdateGame(double p_deltaTime)
    {
        TIME_FUNCTION_START
        Core::EventHandler::GetInstance()->DeliverEvents();
        Core::PlayerHandler::GetInstance()->UpdateServer();

        Utility::Timer::MeasureTimer& timer = Utility::Timer::MeasureTimer::GetInstance();
        // Have all managers update
        size_t length = m_managers.size();
        for(size_t i = 0; i < length; i++)
        {
            Utility::Timer::MeasureInfo& info = timer.GetTimer(m_managers.at(i)->GetName());
            info.Reset().Start();
            m_managers.at(i)->Update(p_deltaTime);
            info.Stop();
        }
        TIME_FUNCTION_STOP
    }

    void ServerMain::Start()
    {
        TIME_FUNCTION_START
        Initialize();
        Run();
        TIME_FUNCTION_STOP
    }
}<commit_msg>Entity factory instead of entity manager<commit_after>// Project specific
#include <Server.hpp>
#include <Doremi/Core/Include/GameCore.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/TransformComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityHandlerServer.hpp>
#include <Doremi/Core/Include/EventHandler/EventHandler.hpp>
#include <Doremi/Core/Include/EventHandler/Events/EntityCreatedEvent.hpp>
#include <Doremi/Core/Include/PlayerHandler.hpp>
#include <Doremi/Core/Include/Manager/Manager.hpp>
#include <Doremi/Core/Include/Manager/Network/ServerNetworkManager.hpp>
#include <Doremi/Core/Include/Manager/MovementManager.hpp>
#include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp>
#include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp>
#include <Doremi/Core/Include/TemplateCreator.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
#include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp>
#include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/AIModule.hpp>
#include <Doremi/Core/Include/Manager/JumpManager.hpp>
#include <Doremi/Core/Include/Manager/GravityManager.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp>
#include <Doremi/Core/Include/LevelLoaderServer.hpp>
#include <DoremiEngine/Physics/Include/FluidManager.hpp>
// Timer
#include <Utility/Timer/Include/Measure/MeasureTimer.hpp>

// Third party
#include <DirectXMath.h>

// Standard libraries
#include <stdexcept>
#include <exception>
#include <chrono>

namespace Doremi
{
    ServerMain::ServerMain() {}

    ServerMain::~ServerMain() {}

    void ServerMain::Initialize()
    {
        TIME_FUNCTION_START
        const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine(
            DoremiEngine::Core::EngineModuleEnum::NETWORK | DoremiEngine::Core::EngineModuleEnum::PHYSICS | DoremiEngine::Core::EngineModuleEnum::AI);

        /* This starts the physics handler. Should not be done here, but since this is the general
        code dump, it'll work for now TODOJB*/

        Core::EntityHandlerServer::StartupEntityHandlerServer();
        Core::PlayerHandler::StartPlayerHandler(sharedContext);

        ////////////////Example only////////////////
        // Create manager

        // Manager* t_physicsManager = new ExampleManager(sharedContext);
        Core::Manager* t_serverNetworkManager = new Core::ServerNetworkManager(sharedContext);
        Core::Manager* t_movementManager = new Core::MovementManager(sharedContext);
        Core::Manager* t_rigidTransSyndManager = new Core::RigidTransformSyncManager(sharedContext);

        Core::Manager* t_aiPathManager = new Core::AIPathManager(sharedContext);
        Core::Manager* t_charSyncManager = new Core::CharacterControlSyncManager(sharedContext); // TODO check if needed
        Core::Manager* t_jumpManager = new Core::JumpManager(sharedContext);
        Core::Manager* t_gravManager = new Core::GravityManager(sharedContext);

        // Add manager to list of managers
        // Remember to put server last (cause we want on same frame as we update to send data, or at least close togeather)
        // m_managers.push_back(t_physicsManager);
        m_managers.push_back(t_serverNetworkManager);
        m_managers.push_back(t_rigidTransSyndManager);
        m_managers.push_back(t_movementManager);
        m_managers.push_back(t_aiPathManager);
        m_managers.push_back(t_charSyncManager);
        m_managers.push_back(t_jumpManager);
        m_managers.push_back(t_gravManager);

        // GenerateWorld(sharedContext);
        // GenerateWorldServerJawsTest(sharedContext);

        Core::TemplateCreator::GetInstance()->CreateTemplatesForServer(sharedContext);
        SpawnDebugWorld(sharedContext);

        ////////////////End Example////////////////

        // Remove later, needed to see something when we play solo cause of camera interactions with input
        // Doremi::Core::InputHandlerClient* inputHandler = new Doremi::Core::InputHandlerClient(sharedContext);
        // Core::PlayerHandler::GetInstance()->CreateNewPlayer(300, (Doremi::Core::InputHandler*)inputHandler);
        TIME_FUNCTION_STOP
    }

    void ServerMain::SpawnDebugWorld(const DoremiEngine::Core::SharedContext& sharedContext)
    {
        TIME_FUNCTION_START
        Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance();
        Core::LevelLoaderServer* t_levelLoader = new Core::LevelLoaderServer(sharedContext);
        t_levelLoader->LoadLevel("Levels/test.drm");
        // Create entity
        // int playerID = t_entityHandler.CreateEntity(Blueprints::PlayerEntity);

        //// Create the rigid body
        // int materialID = t_entityHandler.GetComponentFromStorage<Core::PhysicsMaterialComponent>(playerID)->p_materialID;
        // DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10, 0);
        // DirectX::XMFLOAT4 orientation = DirectX::XMFLOAT4(0, 0, 0, 1);
        // Core::RigidBodyComponent* bodyComp = t_entityHandler.GetComponentFromStorage<Core::RigidBodyComponent>(playerID);
        /*bodyComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(playerID, position, orientation,
                                                                                DirectX::XMFLOAT3(0.5, 0.5, 0.5), materialID);*/

        // sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(playerID, materialID, position, XMFLOAT2(1, 1));
        // Core::EntityHandler::GetInstance().AddComponent(playerID, (int)ComponentType::CharacterController);

        int entityDebugJaws = t_entityFactory.CreateEntity(Blueprints::JawsDebugEntity);
        Core::TransformComponent* trans = GetComponent<Core::TransformComponent>(entityDebugJaws);
        trans->position = DirectX::XMFLOAT3(-10, 5, 0);

        // TODOKO REMOVE Create debug potentialfields
        for(size_t i = 0; i < 1; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::DebugPotentialFieldActor);
            DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 0, 0);
            DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
            int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID;
            Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID);
            rigidComp->p_bodyID =
                sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(entityID, position, orientation, XMFLOAT3(0.5, 0.5, 0.5), matID);

            Core::PotentialFieldComponent* actor = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID);
            actor->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(position, 10, 10, true);
        }

        for(size_t i = 0; i < 5; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity);
            DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10 - (int)i, i * 5);
            DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
            int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID;
            Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID);
            rigidComp->p_bodyID =
                sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation, XMFLOAT3(2, 0.05, 2), matID);
        }

        // Create some enemies
        for(size_t i = 0; i < 8; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::EnemyEntity);
            XMFLOAT3 position = DirectX::XMFLOAT3(0, 7 - (int)i, i * 5);
            XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
            int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID;
            // RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID);
            // rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation,
            //                                                                                XMFLOAT3(0.5, 0.5, 0.5), matID);
            sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(entityID, matID, position, XMFLOAT2(0.1, 0.5));

            Core::PotentialFieldComponent* potentialComponent =
                Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID);
            potentialComponent->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(DirectX::XMFLOAT3(0, 0, 0), -1, 3, false);

            Core::EntityCreatedEvent* AIGroupActorCreated = new Core::EntityCreatedEvent(entityID, Core::EventType::AiGroupActorCreation);
            Core::EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated);
        }

        int entityID = t_entityFactory.CreateEntity(Blueprints::ExperimentalPressureParticleEntity);
        DoremiEngine::Physics::ParticleEmitterData emitterData;
        emitterData.m_density = 3;
        emitterData.m_dimensions = XMFLOAT2(0, 0);
        emitterData.m_direction = XMFLOAT4(0, 0, 0, 1);
        emitterData.m_emissionAreaDimensions = XMFLOAT2(0.1, 0.4);
        emitterData.m_emissionRate = 1;
        emitterData.m_launchPressure = 2;
        emitterData.m_position = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(entityID)->position;
        // sharedContext.GetPhysicsModule().GetFluidManager().CreateParticleEmitter(entityID, emitterData);

        // TODO Not using this event atm, because of refac, will need to find some solution
        /*PlayerCreationEvent* playerCreationEvent = new PlayerCreationEvent();
        playerCreationEvent->eventType = Events::PlayerCreation;
        playerCreationEvent->playerEntityID = playerID;*/

        // EventHandler::GetInstance()->BroadcastEvent(playerCreationEvent);

        // for(size_t i = 0; i < 1; i++)
        //{
        //    int entityID = t_entityHandler.CreateEntity(Blueprints::PlatformEntity);
        //    XMFLOAT3 position = DirectX::XMFLOAT3(0, -2 - (int)i, i * 5);
        //    XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);
        //    int matID = EntityHandler::GetInstance().GetComponentFromStorage<PhysicsMaterialComponent>(entityID)->p_materialID;
        //    RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID);/*
        //    rigidComp->p_bodyID =
        //        sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(2, 0.05, 2), matID);*/
        //    rigidComp->p_bodyID =
        //        sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(200, 0.05, 200), matID);
        //}
        TIME_FUNCTION_STOP
    }

    void JawsSimulatePhysicsDebug(double deltaTime)
    {
        TIME_FUNCTION_START
        Core::TransformComponent* trans = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(0);

        if(trans->position.x == -10)
        {
            trans->position.y += deltaTime;
            if(trans->position.y > 5)
            {
                trans->position.x = -11;
            }
        }
        else
        {
            trans->position.y -= deltaTime;
            if(trans->position.y < -5)
            {
                trans->position.x = -10;
            }
        }
        DirectX::XMStoreFloat4(&trans->rotation, DirectX::XMQuaternionRotationRollPitchYaw(0, 0, trans->position.y * 1.0f));
        TIME_FUNCTION_STOP
    }

    void ServerMain::Run()
    {
        TIME_FUNCTION_START
        std::chrono::time_point<std::chrono::high_resolution_clock> CurrentClock, PreviousClock;
        PreviousClock = std::chrono::high_resolution_clock::now();

        double Frame = 0;
        double Offset = 0;
        double Accum = 0;
        double GameTime = 0;
        double UpdateStepLen = 0.017;

        while(true)
        {
            CurrentClock = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> duration = (CurrentClock - PreviousClock);
            Frame = duration.count() + Offset;
            Offset = 0;

            // We simulate maximum 250 milliseconds each frame
            // If we would let it be alone we would get mayor stops instead of lesser ones that will slowly catch up
            if(Frame > 0.25f)
            {
                Offset = Frame - 0.25f;
                Frame = 0.25f;
            }

            // Update the previous position with frametime so we can catch up if we slow down
            PreviousClock = CurrentClock;

            // Update Accumulator (how much we will work this frame)
            Accum += Frame;

            // Loop as many update-steps we will take this frame
            while(Accum >= UpdateStepLen)
            {
                // Update Game logic
                JawsSimulatePhysicsDebug(UpdateStepLen); // TODOCM remove
                // Update Game logic
                UpdateGame(UpdateStepLen);

                // Remove time from accumulator
                // Accumulator -= UpdateTimeStepLength;
                Accum -= UpdateStepLen;

                // Add time to start
                GameTime += UpdateStepLen;
            }
        }
        TIME_FUNCTION_STOP
    }

    void ServerMain::UpdateGame(double p_deltaTime)
    {
        TIME_FUNCTION_START
        Core::EventHandler::GetInstance()->DeliverEvents();
        Core::PlayerHandler::GetInstance()->UpdateServer();

        Utility::Timer::MeasureTimer& timer = Utility::Timer::MeasureTimer::GetInstance();
        // Have all managers update
        size_t length = m_managers.size();
        for(size_t i = 0; i < length; i++)
        {
            Utility::Timer::MeasureInfo& info = timer.GetTimer(m_managers.at(i)->GetName());
            info.Reset().Start();
            m_managers.at(i)->Update(p_deltaTime);
            info.Stop();
        }
        TIME_FUNCTION_STOP
    }

    void ServerMain::Start()
    {
        TIME_FUNCTION_START
        Initialize();
        Run();
        TIME_FUNCTION_STOP
    }
}<|endoftext|>


<commit_before>#include "postprocessing.h"
//osg
#include <osg/Texture2D>
#include <osg/TexEnv>
#include <osg/TexGen>
#include <osg/TextureCubeMap>
#include <osg/TexMat>
#include <osg/Material>
#include <osg/Geode>
#include <osgDB/WriteFile>
#include <osg/CullFace>
#include <osg/TexGenNode>
#include <osgUtil/CullVisitor>
#include <osgGA/StateSetManipulator>
#include <osgDB/FileNameUtils>
#include <stdio.h>
// troen
#include "shaders.h"

#define HALF_PINGPONGTEXTURE_WIDTH true //for performance improvement, set to true
using namespace troen;

// ugly but convenient global statics for shaders
static osg::ref_ptr<osg::Uniform> g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0));

PostProcessing::PostProcessing(osg::ref_ptr<osg::Group> rootNode, int width, int height)
:m_root(rootNode), m_sceneNode(new osg::Group()), m_width(width), m_height(height)
{
	// init textures, will be recreated when screen size changes
	setupTextures(m_width, m_height);

	// create shaders
	shaders::reloadShaders();

	////////////////////////////////////////
	// Multi pass rendering and Ping Pong //
	////////////////////////////////////////

	// 1. gBuffer pass: render color, normal&depth, id buffer
	unsigned int pass = 0;
	m_allCameras.push_back(gBufferPass());
	m_root->addChild(m_allCameras[pass++]);

	// 2. prepare pass: render id buffer as seeds into PONG texture
	TEXTURE_CONTENT pingPong[] = { PING, PONG };
	// start writing into PONG buffer (pass == 1 )

	m_allCameras.push_back(pingPongPass(pass, COLOR, PONG, shaders::SELECT_GLOW_OBJECTS, -1.0));
	m_root->addChild(m_allCameras[pass++]);

	m_allCameras.push_back(pingPongPass(pass, PONG, PING, shaders::HBLUR, -1.0));
	m_root->addChild(m_allCameras[pass++]);

	m_allCameras.push_back(pingPongPass(pass, PING, PONG, shaders::VBLUR, -1.0));
	m_root->addChild(m_allCameras[pass++]);

	m_allCameras.push_back(postProcessingPass());
	m_root->addChild(m_allCameras[m_allCameras.size() - 1]);
}

// sets up textures
void PostProcessing::setupTextures(const unsigned int & width, const unsigned int &height)
{
	//////////////////////////////////////////////////////////////////////////
	// 2D textures as render targets
	//////////////////////////////////////////////////////////////////////////

	int halfedWidth = width / 2;
	int halfedHeight = height / 2;

	// store color, normal & Depth, id in textures
	m_fboTextures.resize(TEXTURE_CONTENT_SIZE);
	for (int i = 0; i<m_fboTextures.size(); i++)
	{
		// only create textures on first run

		if (!m_fboTextures[i].get()) {
			m_fboTextures[i] = new osg::Texture2D();
		}

		if ((i == PING || i == PONG) && HALF_PINGPONGTEXTURE_WIDTH) {
			m_fboTextures[i]->setTextureWidth(halfedWidth);
			m_fboTextures[i]->setTextureHeight(halfedHeight);
		} else {
			m_fboTextures[i]->setTextureWidth(width);
			m_fboTextures[i]->setTextureHeight(height);
		}

		// higher resolution
		if (i == ID)
		{
			m_fboTextures[i]->setInternalFormat(GL_RG);
			m_fboTextures[i]->setSourceFormat(GL_RG);
			m_fboTextures[i]->setSourceType(GL_FLOAT);
		}
		else
		{
			m_fboTextures[i]->setInternalFormat(GL_RGBA);
			m_fboTextures[i]->setSourceFormat(GL_RGBA);
			m_fboTextures[i]->setSourceType(GL_FLOAT);
		}

		m_fboTextures[i]->setBorderWidth(0);
		m_fboTextures[i]->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
		m_fboTextures[i]->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
		m_fboTextures[i]->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER);
		m_fboTextures[i]->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER);
		m_fboTextures[i]->setBorderColor(osg::Vec4d(0.0, 0.0, 0.0, 1.0));
		m_fboTextures[i]->setResizeNonPowerOfTwoHint(true);

		// important to reflect the change in size
		m_fboTextures[i]->dirtyTextureObject();
	}

	// important to reflect the change in size for the FBO
	if (m_allCameras.size() > 0)
	{
		for (size_t i = 0, iEnd = m_allCameras.size(); i<iEnd; i++)
		{
			m_allCameras[i]->setRenderingCache(0);
			if (i  != 0 && i != iEnd - 1 && HALF_PINGPONGTEXTURE_WIDTH)
				// only draw with halfed resolution, if we process the gbuffer + postprocessing pass
				m_allCameras[i]->setViewport(new osg::Viewport(0, 0, halfedWidth, halfedHeight));

		}
	}
}

class NearFarCallback : public osg::NodeCallback
{
	virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
	{

		traverse(node, nv);

		osgUtil::CullVisitor * cv = dynamic_cast<osgUtil::CullVisitor*> (nv);
		if (cv)
		{
			double n = cv->getCalculatedNearPlane();
			double f = cv->getCalculatedFarPlane();

			osg::Matrixd m = *cv->getProjectionMatrix();
			cv->clampProjectionMatrix(m, n, f);

			if (n != m_oldNear || f != m_oldFar)
			{
				m_oldNear = n;
				m_oldFar = f;
				g_nearFarUniform->set(osg::Vec2(n, f));

			}
		}
	}

private:
	double m_oldNear;
	double m_oldFar;
};

// create gbuffer creation camera
osg::ref_ptr<osg::Camera> PostProcessing::gBufferPass()
{

	osg::ref_ptr<osg::Camera> cam = new osg::Camera();
	// output textures
	cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]);
	//cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]);
	cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]);

	// Configure fboCamera to draw fullscreen textured quad
	// black clear color
	cam->setClearColor(osg::Vec4(0.0, 0.0, 0.5, 1.0));
	cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);

	cam->setReferenceFrame(osg::Camera::RELATIVE_RF);
	cam->setRenderOrder(osg::Camera::PRE_RENDER, 0);

	// need to know about near far changes for correct depth
	cam->setCullCallback(new NearFarCallback());
	cam->addChild(m_sceneNode);

	// attach shader program
	//cam->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->addUniform(new osg::Uniform("colorTex", COLOR));
	//cam->getOrCreateStateSet()->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::GBUFFER], osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON);
<<<<<<< HEAD
	cam->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);
=======
	//cam->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);

	g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0));
>>>>>>> 7cb382183590906ebf637ff0b0806e97b150fde0
	cam->getOrCreateStateSet()->addUniform(g_nearFarUniform);

	return cam;
}

class timeUpdate : public osg::Uniform::Callback
{
public:
	virtual void operator()
		(osg::Uniform* uniform, osg::NodeVisitor* nv)
	{
		float time = nv->getFrameStamp()->getReferenceTime();
		uniform->set(time);
	}
};

// create skeleton creation camera
osg::ref_ptr<osg::Camera> PostProcessing::pingPongPass(int order, TEXTURE_CONTENT inputTexture, TEXTURE_CONTENT outputTexture, int shader, int step)
{
	osg::ref_ptr<osg::Camera> camera(new osg::Camera());

	// output textures
	camera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0), m_fboTextures[outputTexture]);

	// Configure fboCamera to draw fullscreen textured quad
	camera->setClearColor(osg::Vec4(0.0, float(float(order) / float(m_allCameras.size())), 0.0, 1.0));
	camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);

	camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
	camera->setRenderOrder(osg::Camera::PRE_RENDER, order);

	// geometry
	osg::Geode* geode(new osg::Geode());
	geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0)));
	geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	camera->addChild(geode);

	// attach shader program
	osg::ref_ptr<osg::StateSet>	state = camera->getOrCreateStateSet();
	state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);

	state->setAttributeAndModes(shaders::m_allShaderPrograms[shader], osg::StateAttribute::ON);

	// add sampler textures
	state->addUniform(new osg::Uniform("inputLayer", inputTexture));
	state->addUniform(new osg::Uniform("idLayer", ID));
	if (step != -1) state->addUniform(new osg::Uniform("currentStep", step));

	// add time uniform
	osg::Uniform* timeU = new osg::Uniform("time", 0.f);
	state->addUniform(timeU);
	timeU->setUpdateCallback(new timeUpdate());

	state->setTextureAttributeAndModes(inputTexture, m_fboTextures[inputTexture], osg::StateAttribute::ON);
	state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);

	return camera.release();
}

// create post processing pass to put it all together
osg::ref_ptr<osg::Camera> PostProcessing::postProcessingPass()
{
	osg::ref_ptr<osg::Camera> postRenderCamera(new osg::Camera());

	// input textures
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]);
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]);
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]);
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + PONG), m_fboTextures[PONG]);

	// configure postRenderCamera to draw fullscreen textured quad
	postRenderCamera->setClearColor(osg::Vec4(0.0, 0.5, 0.0, 1)); // should never see this.
	postRenderCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
	postRenderCamera->setRenderOrder(osg::Camera::POST_RENDER);

	// geometry
	osg::Geode* geode(new osg::Geode());
	geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0)));
	//geode->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON);
	//geode->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON);
	/*geode->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);
	geode->getOrCreateStateSet()->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON);*/
	geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	postRenderCamera->addChild(geode);

	// attach shader program
	osg::ref_ptr<osg::StateSet>	state = postRenderCamera->getOrCreateStateSet();
	state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);

	state->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::POST_PROCESSING], osg::StateAttribute::ON);

	// add samplers
	state->addUniform(new osg::Uniform("sceneLayer", COLOR));
	//state->addUniform(new osg::Uniform("normalDepthLayer", NORMALDEPTH));
	state->addUniform(new osg::Uniform("idLayer", ID));
	state->addUniform(new osg::Uniform("pongLayer", PONG));

	state->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON);
	//state->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON);
	state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);
	state->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON);

	return postRenderCamera;
}

bool PostProcessing::handleGuiEvents(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*)
{
	if (ea.getEventType() == osgGA::GUIEventAdapter::RESIZE)
	{
		// re setup textures to new size
		setupTextures(ea.getWindowWidth(), ea.getWindowHeight());
		return true;
	}
	else return false;
}

<commit_msg>resolve merge conflict<commit_after>#include "postprocessing.h"
//osg
#include <osg/Texture2D>
#include <osg/TexEnv>
#include <osg/TexGen>
#include <osg/TextureCubeMap>
#include <osg/TexMat>
#include <osg/Material>
#include <osg/Geode>
#include <osgDB/WriteFile>
#include <osg/CullFace>
#include <osg/TexGenNode>
#include <osgUtil/CullVisitor>
#include <osgGA/StateSetManipulator>
#include <osgDB/FileNameUtils>
#include <stdio.h>
// troen
#include "shaders.h"

#define HALF_PINGPONGTEXTURE_WIDTH true //for performance improvement, set to true
using namespace troen;

// ugly but convenient global statics for shaders
static osg::ref_ptr<osg::Uniform> g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0));

PostProcessing::PostProcessing(osg::ref_ptr<osg::Group> rootNode, int width, int height)
:m_root(rootNode), m_sceneNode(new osg::Group()), m_width(width), m_height(height)
{
	// init textures, will be recreated when screen size changes
	setupTextures(m_width, m_height);

	// create shaders
	shaders::reloadShaders();

	////////////////////////////////////////
	// Multi pass rendering and Ping Pong //
	////////////////////////////////////////

	// 1. gBuffer pass: render color, normal&depth, id buffer
	unsigned int pass = 0;
	m_allCameras.push_back(gBufferPass());
	m_root->addChild(m_allCameras[pass++]);

	// 2. prepare pass: render id buffer as seeds into PONG texture
	TEXTURE_CONTENT pingPong[] = { PING, PONG };
	// start writing into PONG buffer (pass == 1 )

	m_allCameras.push_back(pingPongPass(pass, COLOR, PONG, shaders::SELECT_GLOW_OBJECTS, -1.0));
	m_root->addChild(m_allCameras[pass++]);

	m_allCameras.push_back(pingPongPass(pass, PONG, PING, shaders::HBLUR, -1.0));
	m_root->addChild(m_allCameras[pass++]);

	m_allCameras.push_back(pingPongPass(pass, PING, PONG, shaders::VBLUR, -1.0));
	m_root->addChild(m_allCameras[pass++]);

	m_allCameras.push_back(postProcessingPass());
	m_root->addChild(m_allCameras[m_allCameras.size() - 1]);
}

// sets up textures
void PostProcessing::setupTextures(const unsigned int & width, const unsigned int &height)
{
	//////////////////////////////////////////////////////////////////////////
	// 2D textures as render targets
	//////////////////////////////////////////////////////////////////////////

	int halfedWidth = width / 2;
	int halfedHeight = height / 2;

	// store color, normal & Depth, id in textures
	m_fboTextures.resize(TEXTURE_CONTENT_SIZE);
	for (int i = 0; i<m_fboTextures.size(); i++)
	{
		// only create textures on first run

		if (!m_fboTextures[i].get()) {
			m_fboTextures[i] = new osg::Texture2D();
		}

		if ((i == PING || i == PONG) && HALF_PINGPONGTEXTURE_WIDTH) {
			m_fboTextures[i]->setTextureWidth(halfedWidth);
			m_fboTextures[i]->setTextureHeight(halfedHeight);
		} else {
			m_fboTextures[i]->setTextureWidth(width);
			m_fboTextures[i]->setTextureHeight(height);
		}

		// higher resolution
		if (i == ID)
		{
			m_fboTextures[i]->setInternalFormat(GL_RG);
			m_fboTextures[i]->setSourceFormat(GL_RG);
			m_fboTextures[i]->setSourceType(GL_FLOAT);
		}
		else
		{
			m_fboTextures[i]->setInternalFormat(GL_RGBA);
			m_fboTextures[i]->setSourceFormat(GL_RGBA);
			m_fboTextures[i]->setSourceType(GL_FLOAT);
		}

		m_fboTextures[i]->setBorderWidth(0);
		m_fboTextures[i]->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
		m_fboTextures[i]->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
		m_fboTextures[i]->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER);
		m_fboTextures[i]->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER);
		m_fboTextures[i]->setBorderColor(osg::Vec4d(0.0, 0.0, 0.0, 1.0));
		m_fboTextures[i]->setResizeNonPowerOfTwoHint(true);

		// important to reflect the change in size
		m_fboTextures[i]->dirtyTextureObject();
	}

	// important to reflect the change in size for the FBO
	if (m_allCameras.size() > 0)
	{
		for (size_t i = 0, iEnd = m_allCameras.size(); i<iEnd; i++)
		{
			m_allCameras[i]->setRenderingCache(0);
			if (i  != 0 && i != iEnd - 1 && HALF_PINGPONGTEXTURE_WIDTH)
				// only draw with halfed resolution, if we process the gbuffer + postprocessing pass
				m_allCameras[i]->setViewport(new osg::Viewport(0, 0, halfedWidth, halfedHeight));

		}
	}
}

class NearFarCallback : public osg::NodeCallback
{
	virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
	{

		traverse(node, nv);

		osgUtil::CullVisitor * cv = dynamic_cast<osgUtil::CullVisitor*> (nv);
		if (cv)
		{
			double n = cv->getCalculatedNearPlane();
			double f = cv->getCalculatedFarPlane();

			osg::Matrixd m = *cv->getProjectionMatrix();
			cv->clampProjectionMatrix(m, n, f);

			if (n != m_oldNear || f != m_oldFar)
			{
				m_oldNear = n;
				m_oldFar = f;
				g_nearFarUniform->set(osg::Vec2(n, f));

			}
		}
	}

private:
	double m_oldNear;
	double m_oldFar;
};

// create gbuffer creation camera
osg::ref_ptr<osg::Camera> PostProcessing::gBufferPass()
{

	osg::ref_ptr<osg::Camera> cam = new osg::Camera();
	// output textures
	cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]);
	//cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]);
	cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]);

	// Configure fboCamera to draw fullscreen textured quad
	// black clear color
	cam->setClearColor(osg::Vec4(0.0, 0.0, 0.5, 1.0));
	cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);

	cam->setReferenceFrame(osg::Camera::RELATIVE_RF);
	cam->setRenderOrder(osg::Camera::PRE_RENDER, 0);

	// need to know about near far changes for correct depth
	cam->setCullCallback(new NearFarCallback());
	cam->addChild(m_sceneNode);

	// attach shader program
	//cam->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->addUniform(new osg::Uniform("colorTex", COLOR));
	//cam->getOrCreateStateSet()->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::GBUFFER], osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON);
	//cam->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);

	g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0));
	cam->getOrCreateStateSet()->addUniform(g_nearFarUniform);

	return cam;
}

class timeUpdate : public osg::Uniform::Callback
{
public:
	virtual void operator()
		(osg::Uniform* uniform, osg::NodeVisitor* nv)
	{
		float time = nv->getFrameStamp()->getReferenceTime();
		uniform->set(time);
	}
};

// create skeleton creation camera
osg::ref_ptr<osg::Camera> PostProcessing::pingPongPass(int order, TEXTURE_CONTENT inputTexture, TEXTURE_CONTENT outputTexture, int shader, int step)
{
	osg::ref_ptr<osg::Camera> camera(new osg::Camera());

	// output textures
	camera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0), m_fboTextures[outputTexture]);

	// Configure fboCamera to draw fullscreen textured quad
	camera->setClearColor(osg::Vec4(0.0, float(float(order) / float(m_allCameras.size())), 0.0, 1.0));
	camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);

	camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
	camera->setRenderOrder(osg::Camera::PRE_RENDER, order);

	// geometry
	osg::Geode* geode(new osg::Geode());
	geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0)));
	geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	camera->addChild(geode);

	// attach shader program
	osg::ref_ptr<osg::StateSet>	state = camera->getOrCreateStateSet();
	state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);

	state->setAttributeAndModes(shaders::m_allShaderPrograms[shader], osg::StateAttribute::ON);

	// add sampler textures
	state->addUniform(new osg::Uniform("inputLayer", inputTexture));
	state->addUniform(new osg::Uniform("idLayer", ID));
	if (step != -1) state->addUniform(new osg::Uniform("currentStep", step));

	// add time uniform
	osg::Uniform* timeU = new osg::Uniform("time", 0.f);
	state->addUniform(timeU);
	timeU->setUpdateCallback(new timeUpdate());

	state->setTextureAttributeAndModes(inputTexture, m_fboTextures[inputTexture], osg::StateAttribute::ON);
	state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);

	return camera.release();
}

// create post processing pass to put it all together
osg::ref_ptr<osg::Camera> PostProcessing::postProcessingPass()
{
	osg::ref_ptr<osg::Camera> postRenderCamera(new osg::Camera());

	// input textures
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]);
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]);
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]);
	//postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + PONG), m_fboTextures[PONG]);

	// configure postRenderCamera to draw fullscreen textured quad
	postRenderCamera->setClearColor(osg::Vec4(0.0, 0.5, 0.0, 1)); // should never see this.
	postRenderCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
	postRenderCamera->setRenderOrder(osg::Camera::POST_RENDER);

	// geometry
	osg::Geode* geode(new osg::Geode());
	geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0)));
	//geode->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON);
	//geode->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON);
	/*geode->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);
	geode->getOrCreateStateSet()->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON);*/
	geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	postRenderCamera->addChild(geode);

	// attach shader program
	osg::ref_ptr<osg::StateSet>	state = postRenderCamera->getOrCreateStateSet();
	state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);

	state->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::POST_PROCESSING], osg::StateAttribute::ON);

	// add samplers
	state->addUniform(new osg::Uniform("sceneLayer", COLOR));
	//state->addUniform(new osg::Uniform("normalDepthLayer", NORMALDEPTH));
	state->addUniform(new osg::Uniform("idLayer", ID));
	state->addUniform(new osg::Uniform("pongLayer", PONG));

	state->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON);
	//state->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON);
	state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON);
	state->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON);

	return postRenderCamera;
}

bool PostProcessing::handleGuiEvents(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*)
{
	if (ea.getEventType() == osgGA::GUIEventAdapter::RESIZE)
	{
		// re setup textures to new size
		setupTextures(ea.getWindowWidth(), ea.getWindowHeight());
		return true;
	}
	else return false;
}

<|endoftext|>


<commit_before>#include "coursestablemanager.h"

coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr)
{
  this->gp = NULL;
  this->us = usrPtr;
  this->courseTBL = ptr;

  /*
     *  Initilizing Table
    */
  courseTBL->setRowCount(0);
  courseTBL->setColumnCount(COURSE_FIELDS);
  QStringList mz;
  mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions");
  courseTBL->setHorizontalHeaderLabels(mz);
  courseTBL->verticalHeader()->setVisible(false);
  courseTBL->setSelectionMode(QAbstractItemView::SingleSelection);
  courseTBL->setShowGrid(true);
  courseTBL->setStyleSheet("QTableView {selection-background-color: red;}");

  /*
     *
    */
  graph = new gradegraph(NULL,gp);
}

coursesTableManager::~coursesTableManager()
{
  courseTBL = NULL;
  delete gp;
  gp = NULL;
}
/**
 * @brief coursesTableManager::insertJceCoursesIntoTable    phrasing the course list to rows in table
 */
void coursesTableManager::insertJceCoursesIntoTable()
{
  for (gradeCourse *c: *gp->getCourses())
    {
      if (us->getInfluenceCourseOnly())
        {
          if (isCourseInfluence(c))
            addRow(c);
        }
      else
        addRow(c);
    }
}
/**
 * @brief coursesTableManager::setCoursesList   creating courses list with given html page
 * @param html
 */
void coursesTableManager::setCoursesList(QString &html)
{
  if (gp != NULL)
    gp->~GradePage();
  gp = new GradePage(html);
}
/**
 * @brief coursesTableManager::changes  when user changes the table manually it updates it
 * @param change    string change
 * @param row       row index
 * @param col       col index
 * @return  if change has been done
 */
bool coursesTableManager::changes(QString change, int row, int col)
{

  bool isNumFlag = true;
  if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL)
    return true;

  int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt();
  for (gradeCourse *c: *gp->getCourses())
    {
      if (c->getSerialNum() == serialCourse)
        {
          switch (col)
            {
            case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST):
              c->setCourseNumInList(change.toInt());
              break;
            case (gradeCourse::CourseScheme::YEAR):
              c->setYear(change.toInt());
              break;
            case (gradeCourse::CourseScheme::SEMESTER):
              c->setSemester(change.toInt());
              break;
            case (gradeCourse::CourseScheme::NAME):
              c->setName(change);
              break;
            case (gradeCourse::CourseScheme::TYPE):
              c->setType(change);
              break;
            case (gradeCourse::CourseScheme::POINTS):
              {
                change.toDouble(&isNumFlag);

                if (!isNumFlag)
                  {
                    courseTBL->item(row,col)->setText(QString::number(c->getPoints()));
                  }
                else
                  c->setPoints(change.toDouble());
                break;
              }
            case (gradeCourse::CourseScheme::HOURS):
              {
                change.toDouble(&isNumFlag);

                if (!isNumFlag)
                  {
                    courseTBL->item(row,col)->setText(QString::number(c->getHours()));
                  }
                else
                  c->setHours(change.toDouble());
                break;
              }
            case (gradeCourse::CourseScheme::GRADE):
              {
                change.toDouble(&isNumFlag);

                if (!isNumFlag)
                  {
                    courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
                  }
                else
                  {
                    if ((change.toDouble() >= 0) && (change.toDouble() <= 100))
                      c->setGrade(change.toDouble());
                    else
                      courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
                  }
                break;
              }
            case (gradeCourse::CourseScheme::ADDITION):
              c->setAdditions(change);
              break;
            }
          break;
        }
    }
  return isNumFlag;

}
/**
 * @brief coursesTableManager::addRow   adds row with given information
 * @param courseToAdd                   if exists, add its information to table
 */
void coursesTableManager::addRow(const gradeCourse *courseToAdd)
{
  int i=1,j=1;

  j = 0;
  QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition;
  const gradeCourse * c;
  if (courseToAdd != NULL)
    {
      c = courseToAdd;
      if (!isCourseAlreadyInserted(c->getSerialNum()))
        {
          courseTBL->setRowCount(courseTBL->rowCount() + 1);
          i = courseTBL->rowCount()-1;

          number = new QTableWidgetItem();
          number->setData(Qt::EditRole, c->getCourseNumInList());
          number->setFlags(number->flags() & ~Qt::ItemIsEditable);

          year = new QTableWidgetItem();
          year->setData(Qt::EditRole,c->getYear());
          year->setFlags(year->flags() & ~Qt::ItemIsEditable);

          semester = new QTableWidgetItem();
          semester->setData(Qt::EditRole,c->getSemester());
          semester->setFlags(semester->flags() & ~Qt::ItemIsEditable);

          serial = new QTableWidgetItem();
          serial->setData(Qt::EditRole,c->getSerialNum());
          serial->setFlags(serial->flags() & ~Qt::ItemIsEditable);

          name = new QTableWidgetItem();
          name->setData(Qt::EditRole,c->getName());
          name->setFlags(name->flags() & ~Qt::ItemIsEditable);

          type = new QTableWidgetItem();
          type->setData(Qt::EditRole, c->getType());
          type->setFlags(type->flags() & ~Qt::ItemIsEditable);

          points = new QTableWidgetItem();
          points->setData(Qt::EditRole, c->getPoints());
          points->setFlags(points->flags() & ~Qt::ItemIsEditable);

          hours = new QTableWidgetItem();
          hours->setData(Qt::EditRole, c->getHours());
          hours->setFlags(hours->flags() & ~Qt::ItemIsEditable);

          grade = new QTableWidgetItem();
          grade->setData(Qt::EditRole,c->getGrade());

          addition = new QTableWidgetItem();
          addition->setData(Qt::EditRole,c->getAddidtions());

          courseTBL->setItem(i,j++,number);
          courseTBL->setItem(i,j++,year);
          courseTBL->setItem(i,j++,semester);
          courseTBL->setItem(i,j++,serial);
          courseTBL->setItem(i,j++,name);
          courseTBL->setItem(i,j++,type);
          courseTBL->setItem(i,j++,points);
          courseTBL->setItem(i,j++,hours);
          courseTBL->setItem(i,j++,grade);
          courseTBL->setItem(i,j,addition);

        }
    }
  else
    {
      qCritical() << Q_FUNC_INFO << "no course to load!";
    }
  courseTBL->resizeColumnsToContents();

}
double coursesTableManager::getAvg()
{
  if (this->gp != NULL)
    return gp->getAvg();
  return 0;
}

void coursesTableManager::showGraph()
{
  if (gp != NULL)
    {
      qDebug() << "Graph Dialog Opened. gp != NULL";
      this->graph->showGraph(gp);
    }
}

void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus)
{
  if (ignoreCourseStatus)
    {
      int i = 0;
      while (i < courseTBL->rowCount())
        {
          if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0)
            courseTBL->removeRow(i--);
          i++;
        }
    }
  else
    {
      if (this->gp != NULL)
        for (gradeCourse *c: *gp->getCourses())
          {
            if (!(isCourseAlreadyInserted(c->getSerialNum())))
              if (c->getPoints() == 0)
                addRow(c);
          }
    }

}

void coursesTableManager::clearTable()
{
  if (courseTBL->rowCount() == 0)
    return;

  int i = 0; //starting point
  while (courseTBL->rowCount() > i)
    {
      gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text());
      courseTBL->removeRow(i);
    }
  gp = NULL;
  courseTBL->repaint();
}

gradeCourse *coursesTableManager::getCourseByRow(int row)
{
  QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text();
  for (gradeCourse *c: *gp->getCourses())
    {
      if (c->getSerialNum() == courseSerial.toDouble())
        return c;
    }
  return NULL;
}

bool coursesTableManager::isCourseAlreadyInserted(double courseID)
{
  int i;
  for (i = courseTBL->rowCount(); i >= 0; --i)
    {
      if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL)
        {
          QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text();
          if (QString::number(courseID) == courseSerial)
            return true;
        }
    }
  return false;
}

bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck)
{
  if (courseToCheck->getPoints() > 0)
    return true;
  return false;

}
<commit_msg>added feature #26<commit_after>#include "coursestablemanager.h"

coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr)
{
  this->gp = NULL;
  this->us = usrPtr;
  this->courseTBL = ptr;

  /*
     *  Initilizing Table
    */
  courseTBL->setRowCount(0);
  courseTBL->setColumnCount(COURSE_FIELDS);
  QStringList mz;
  mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions");
  courseTBL->setHorizontalHeaderLabels(mz);
  courseTBL->verticalHeader()->setVisible(false);
  courseTBL->setSelectionMode(QAbstractItemView::SingleSelection);
  courseTBL->setShowGrid(true);
  courseTBL->setStyleSheet("QTableView {selection-background-color: red;}");

  /*
     *
    */
  graph = new gradegraph(NULL,gp);
}

coursesTableManager::~coursesTableManager()
{
  courseTBL = NULL;
  delete gp;
  gp = NULL;
}
/**
 * @brief coursesTableManager::insertJceCoursesIntoTable    phrasing the course list to rows in table
 */
void coursesTableManager::insertJceCoursesIntoTable()
{
  for (gradeCourse *c: *gp->getCourses())
    {
      if (us->getInfluenceCourseOnly())
        {
          if (isCourseInfluence(c))
            addRow(c);
        }
      else
        addRow(c);
    }
}
/**
 * @brief coursesTableManager::setCoursesList   creating courses list with given html page
 * @param html
 */
void coursesTableManager::setCoursesList(QString &html)
{
  if (gp != NULL)
    gp->~GradePage();
  gp = new GradePage(html);
}
/**
 * @brief coursesTableManager::changes  when user changes the table manually it updates it
 * @param change    string change
 * @param row       row index
 * @param col       col index
 * @return  if change has been done
 */
bool coursesTableManager::changes(QString change, int row, int col)
{

  bool isNumFlag = true;
  if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL)
    return true;

  int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt();
  for (gradeCourse *c: *gp->getCourses())
    {
      if (c->getSerialNum() == serialCourse)
        {
          switch (col)
            {
            case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST):
              c->setCourseNumInList(change.toInt());
              break;
            case (gradeCourse::CourseScheme::YEAR):
              c->setYear(change.toInt());
              break;
            case (gradeCourse::CourseScheme::SEMESTER):
              c->setSemester(change.toInt());
              break;
            case (gradeCourse::CourseScheme::NAME):
              c->setName(change);
              break;
            case (gradeCourse::CourseScheme::TYPE):
              c->setType(change);
              break;
            case (gradeCourse::CourseScheme::POINTS):
              {
                change.toDouble(&isNumFlag);

                if (!isNumFlag)
                  {
                    courseTBL->item(row,col)->setText(QString::number(c->getPoints()));
                  }
                else
                  c->setPoints(change.toDouble());
                break;
              }
            case (gradeCourse::CourseScheme::HOURS):
              {
                change.toDouble(&isNumFlag);

                if (!isNumFlag)
                  {
                    courseTBL->item(row,col)->setText(QString::number(c->getHours()));
                  }
                else
                  c->setHours(change.toDouble());
                break;
              }
            case (gradeCourse::CourseScheme::GRADE):
              {
                change.toDouble(&isNumFlag);

                if (!isNumFlag)
                  {
                    courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
                  }
                else
                  {
                    if ((change.toDouble() >= 0) && (change.toDouble() <= 100))
                      c->setGrade(change.toDouble());
                    else
                      courseTBL->item(row,col)->setText(QString::number(c->getGrade()));
                  }
                break;
              }
            case (gradeCourse::CourseScheme::ADDITION):
              c->setAdditions(change);
              break;
            }
          break;
        }
    }
  return isNumFlag;

}
/**
 * @brief coursesTableManager::addRow   adds row with given information
 * @param courseToAdd                   if exists, add its information to table
 */
void coursesTableManager::addRow(const gradeCourse *courseToAdd)
{
  int i=1,j=1;

  j = 0;
  QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition;
  const gradeCourse * c;
  if (courseToAdd != NULL)
    {
      c = courseToAdd;
      if (!isCourseAlreadyInserted(c->getSerialNum()))
        {
          courseTBL->setRowCount(courseTBL->rowCount() + 1);
          i = courseTBL->rowCount()-1;

          number = new QTableWidgetItem();
          number->setData(Qt::EditRole, c->getCourseNumInList());
          number->setFlags(number->flags() & ~Qt::ItemIsEditable);

          year = new QTableWidgetItem();
          year->setData(Qt::EditRole,c->getYear());
          year->setFlags(year->flags() & ~Qt::ItemIsEditable);

          semester = new QTableWidgetItem();
          semester->setData(Qt::EditRole,c->getSemester());
          semester->setFlags(semester->flags() & ~Qt::ItemIsEditable);

          serial = new QTableWidgetItem();
          serial->setData(Qt::EditRole,c->getSerialNum());
          serial->setFlags(serial->flags() & ~Qt::ItemIsEditable);

          name = new QTableWidgetItem();
          name->setData(Qt::EditRole,c->getName());
          name->setFlags(name->flags() & ~Qt::ItemIsEditable);

          type = new QTableWidgetItem();
          type->setData(Qt::EditRole, c->getType());
          type->setFlags(type->flags() & ~Qt::ItemIsEditable);

          points = new QTableWidgetItem();
          points->setData(Qt::EditRole, c->getPoints());
          points->setFlags(points->flags() & ~Qt::ItemIsEditable);

          hours = new QTableWidgetItem();
          hours->setData(Qt::EditRole, c->getHours());
          hours->setFlags(hours->flags() & ~Qt::ItemIsEditable);

          grade = new QTableWidgetItem();
          grade->setData(Qt::EditRole,c->getGrade());

          addition = new QTableWidgetItem();
          addition->setData(Qt::EditRole,c->getAddidtions());

          courseTBL->setItem(i,j++,number);
          courseTBL->setItem(i,j++,year);
          courseTBL->setItem(i,j++,semester);
          courseTBL->setItem(i,j++,serial);
          courseTBL->setItem(i,j++,name);
          courseTBL->setItem(i,j++,type);
          courseTBL->setItem(i,j++,points);
          courseTBL->setItem(i,j++,hours);
          courseTBL->setItem(i,j,grade);
          if(c->getGrade() < 55 && c->getGrade() != 0)
          {
              courseTBL->item(i, j)->setBackground(Qt::darkRed);
              courseTBL->item(i,j)->setTextColor(Qt::white);
          }
          else if(55 <= c->getGrade() && c->getGrade() < 70 )
          {
              courseTBL->item(i, j)->setBackground(Qt::darkYellow);
              courseTBL->item(i,j)->setTextColor(Qt::white);
          }
//          else if(70 < c->getGrade() && c->getGrade() <= 80 )
//              courseTBL->item(i, j)->setBackground(Qt::darkGreen);  //They Look Bad!!
//          else if(c->getGrade() > 80)
//              courseTBL->item(i, j)->setBackground(Qt::green);

          j++;

          courseTBL->setItem(i,j,addition);

        }
    }
  else
    {
      qCritical() << Q_FUNC_INFO << "no course to load!";
    }
  courseTBL->resizeColumnsToContents();

}
double coursesTableManager::getAvg()
{
  if (this->gp != NULL)
    return gp->getAvg();
  return 0;
}

void coursesTableManager::showGraph()
{
  if (gp != NULL)
    {
      qDebug() << "Graph Dialog Opened. gp != NULL";
      this->graph->showGraph(gp);
    }
}

void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus)
{
  if (ignoreCourseStatus)
    {
      int i = 0;
      while (i < courseTBL->rowCount())
        {
          if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0)
            courseTBL->removeRow(i--);
          i++;
        }
    }
  else
    {
      if (this->gp != NULL)
        for (gradeCourse *c: *gp->getCourses())
          {
            if (!(isCourseAlreadyInserted(c->getSerialNum())))
              if (c->getPoints() == 0)
                addRow(c);
          }
    }

}

void coursesTableManager::clearTable()
{
  if (courseTBL->rowCount() == 0)
    return;

  int i = 0; //starting point
  while (courseTBL->rowCount() > i)
    {
      gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text());
      courseTBL->removeRow(i);
    }
  gp = NULL;
  courseTBL->repaint();
}

gradeCourse *coursesTableManager::getCourseByRow(int row)
{
  QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text();
  for (gradeCourse *c: *gp->getCourses())
    {
      if (c->getSerialNum() == courseSerial.toDouble())
        return c;
    }
  return NULL;
}

bool coursesTableManager::isCourseAlreadyInserted(double courseID)
{
  int i;
  for (i = courseTBL->rowCount(); i >= 0; --i)
    {
      if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL)
        {
          QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text();
          if (QString::number(courseID) == courseSerial)
            return true;
        }
    }
  return false;
}

bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck)
{
  if (courseToCheck->getPoints() > 0)
    return true;
  return false;

}
<|endoftext|>


<commit_before>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include <mapviz_plugins/tf_frame_plugin.h>

// C++ standard libraries
#include <cstdio>
#include <algorithm>
#include <vector>

// QT libraries
#include <QGLWidget>
#include <QPalette>

// ROS libraries
#include <ros/master.h>

#include <mapviz/select_frame_dialog.h>

// Declare plugin
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(mapviz_plugins::TfFramePlugin, mapviz::MapvizPlugin)

namespace mapviz_plugins
{
  TfFramePlugin::TfFramePlugin() : config_widget_(new QWidget())
  {
    ui_.setupUi(config_widget_);

    ui_.color->setColor(Qt::green);

    // Set background white
    QPalette p(config_widget_->palette());
    p.setColor(QPalette::Background, Qt::white);
    config_widget_->setPalette(p);

    // Set status text red
    QPalette p3(ui_.status->palette());
    p3.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p3);

    QObject::connect(ui_.selectframe, SIGNAL(clicked()), this,
                     SLOT(SelectFrame()));
    QObject::connect(ui_.frame, SIGNAL(editingFinished()), this,
                     SLOT(FrameEdited()));
    QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this,
                     SLOT(PositionToleranceChanged(double)));
    QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this,
                     SLOT(BufferSizeChanged(int)));
    QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this,
                     SLOT(SetDrawStyle(QString)));
    QObject::connect(ui_.static_arrow_sizes, SIGNAL(clicked(bool)),
                     this, SLOT(SetStaticArrowSizes(bool)));
    QObject::connect(ui_.arrow_size, SIGNAL(valueChanged(int)),
                     this, SLOT(SetArrowSize(int)));
    connect(ui_.color, SIGNAL(colorEdited(const QColor&)), this,
            SLOT(SetColor(const QColor&)));
  }

  TfFramePlugin::~TfFramePlugin()
  {
  }

  void TfFramePlugin::SelectFrame()
  {
    std::string frame = mapviz::SelectFrameDialog::selectFrame(tf_);
    if (!frame.empty())
    {
      ui_.frame->setText(QString::fromStdString(frame));
      FrameEdited();
    }
  }

  void TfFramePlugin::FrameEdited()
  {
    source_frame_ = ui_.frame->text().toStdString();
    PrintWarning("Waiting for transform.");

    ROS_INFO("Setting target frame to to %s", source_frame_.c_str());

    initialized_ = true;
  }

  void TfFramePlugin::TimerCallback(const ros::TimerEvent& event)
  {
    swri_transform_util::Transform transform;
    if (GetTransform(ros::Time(), transform))
    {
      StampedPoint stamped_point;
      stamped_point.point = transform.GetOrigin();
      stamped_point.orientation = transform.GetOrientation();
      stamped_point.source_frame = target_frame_;
      stamped_point.stamp = transform.GetStamp();
      stamped_point.transformed = false;

      double distance = std::sqrt(
          std::pow(stamped_point.point.x() - points_.back().point.x(), 2) +
          std::pow(stamped_point.point.y() - points_.back().point.y(), 2));

      if (points_.empty() || distance >= position_tolerance_)
      {
        points_.push_back(stamped_point);
      }

      if (buffer_size_ > 0)
      {
        while (static_cast<int>(points_.size()) > buffer_size_)
        {
          points_.pop_front();
        }
      }

      cur_point_ = stamped_point;
    }
  }

  void TfFramePlugin::PrintError(const std::string& message)
  {
    PrintErrorHelper(ui_.status, message);
  }

  void TfFramePlugin::PrintInfo(const std::string& message)
  {
    PrintInfoHelper(ui_.status, message);
  }

  void TfFramePlugin::PrintWarning(const std::string& message)
  {
    PrintWarningHelper(ui_.status, message);
  }

  QWidget* TfFramePlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  bool TfFramePlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = canvas;

    timer_ = node_.createTimer(ros::Duration(0.1),
                               &TfFramePlugin::TimerCallback, this);

    SetColor(ui_.color->color());

    return true;
  }

  void TfFramePlugin::Draw(double x, double y, double scale)
  {
    if (DrawPoints(scale))
    {
      PrintInfo("OK");
    }
  }
  void TfFramePlugin::LoadConfig(const YAML::Node& node,
                                 const std::string& path)
  {
    if (node["frame"])
    {
      node["frame"] >> source_frame_;
      ui_.frame->setText(source_frame_.c_str());
    }

    if (node["color"])
    {
      std::string color;
      node["color"] >> color;
      SetColor(QColor(color.c_str()));
      ui_.color->setColor(color_);
    }

    if (node["draw_style"])
    {
      std::string draw_style;
      node["draw_style"] >> draw_style;

      if (draw_style == "lines")
      {
        draw_style_ = LINES;
        ui_.drawstyle->setCurrentIndex(0);
      }
      else if (draw_style == "points")
      {
        draw_style_ = POINTS;
        ui_.drawstyle->setCurrentIndex(1);
      }
    }

    if (node["position_tolerance"])
    {
      node["position_tolerance"] >> position_tolerance_;
      ui_.positiontolerance->setValue(position_tolerance_);
    }

    if (node["buffer_size"])
    {
      node["buffer_size"] >> buffer_size_;
      ui_.buffersize->setValue(buffer_size_);
    }

    if (node["static_arrow_sizes"])
    {
      bool static_arrow_sizes = node["static_arrow_sizes"].as<bool>();
      ui_.static_arrow_sizes->setChecked(static_arrow_sizes);
      SetStaticArrowSizes(static_arrow_sizes);
    }

    if (node["arrow_size"])
    {
      ui_.arrow_size->setValue(node["arrow_size"].as<int>());
    }

    FrameEdited();
  }

  void TfFramePlugin::SaveConfig(YAML::Emitter& emitter,
                                 const std::string& path)
  {
    emitter << YAML::Key << "frame" << YAML::Value
            << ui_.frame->text().toStdString();
    emitter << YAML::Key << "color" << YAML::Value
            << ui_.color->color().name().toStdString();

    std::string draw_style = ui_.drawstyle->currentText().toStdString();
    emitter << YAML::Key << "draw_style" << YAML::Value << draw_style;

    emitter << YAML::Key << "position_tolerance" <<
               YAML::Value << position_tolerance_;

    emitter << YAML::Key << "buffer_size" << YAML::Value << buffer_size_;

    emitter << YAML::Key << "static_arrow_sizes" << YAML::Value << ui_.static_arrow_sizes->isChecked();

    emitter << YAML::Key << "arrow_size" << YAML::Value << ui_.arrow_size->value();
  }
}
<commit_msg>the option "arrow" was not loaded correctly<commit_after>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include <mapviz_plugins/tf_frame_plugin.h>

// C++ standard libraries
#include <cstdio>
#include <algorithm>
#include <vector>

// QT libraries
#include <QGLWidget>
#include <QPalette>

// ROS libraries
#include <ros/master.h>

#include <mapviz/select_frame_dialog.h>

// Declare plugin
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(mapviz_plugins::TfFramePlugin, mapviz::MapvizPlugin)

namespace mapviz_plugins
{
  TfFramePlugin::TfFramePlugin() : config_widget_(new QWidget())
  {
    ui_.setupUi(config_widget_);

    ui_.color->setColor(Qt::green);

    // Set background white
    QPalette p(config_widget_->palette());
    p.setColor(QPalette::Background, Qt::white);
    config_widget_->setPalette(p);

    // Set status text red
    QPalette p3(ui_.status->palette());
    p3.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p3);

    QObject::connect(ui_.selectframe, SIGNAL(clicked()), this,
                     SLOT(SelectFrame()));
    QObject::connect(ui_.frame, SIGNAL(editingFinished()), this,
                     SLOT(FrameEdited()));
    QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this,
                     SLOT(PositionToleranceChanged(double)));
    QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this,
                     SLOT(BufferSizeChanged(int)));
    QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this,
                     SLOT(SetDrawStyle(QString)));
    QObject::connect(ui_.static_arrow_sizes, SIGNAL(clicked(bool)),
                     this, SLOT(SetStaticArrowSizes(bool)));
    QObject::connect(ui_.arrow_size, SIGNAL(valueChanged(int)),
                     this, SLOT(SetArrowSize(int)));
    QObject::connect(ui_.color, SIGNAL(colorEdited(const QColor&)), this,
                     SLOT(SetColor(const QColor&)));
  }

  TfFramePlugin::~TfFramePlugin()
  {
  }

  void TfFramePlugin::SelectFrame()
  {
    std::string frame = mapviz::SelectFrameDialog::selectFrame(tf_);
    if (!frame.empty())
    {
      ui_.frame->setText(QString::fromStdString(frame));
      FrameEdited();
    }
  }

  void TfFramePlugin::FrameEdited()
  {
    source_frame_ = ui_.frame->text().toStdString();
    PrintWarning("Waiting for transform.");

    ROS_INFO("Setting target frame to to %s", source_frame_.c_str());

    initialized_ = true;
  }

  void TfFramePlugin::TimerCallback(const ros::TimerEvent& event)
  {
    swri_transform_util::Transform transform;
    if (GetTransform(ros::Time(), transform))
    {
      StampedPoint stamped_point;
      stamped_point.point = transform.GetOrigin();
      stamped_point.orientation = transform.GetOrientation();
      stamped_point.source_frame = target_frame_;
      stamped_point.stamp = transform.GetStamp();
      stamped_point.transformed = false;

      double distance = std::sqrt(
          std::pow(stamped_point.point.x() - points_.back().point.x(), 2) +
          std::pow(stamped_point.point.y() - points_.back().point.y(), 2));

      if (points_.empty() || distance >= position_tolerance_)
      {
        points_.push_back(stamped_point);
      }

      if (buffer_size_ > 0)
      {
        while (static_cast<int>(points_.size()) > buffer_size_)
        {
          points_.pop_front();
        }
      }

      cur_point_ = stamped_point;
    }
  }

  void TfFramePlugin::PrintError(const std::string& message)
  {
    PrintErrorHelper(ui_.status, message);
  }

  void TfFramePlugin::PrintInfo(const std::string& message)
  {
    PrintInfoHelper(ui_.status, message);
  }

  void TfFramePlugin::PrintWarning(const std::string& message)
  {
    PrintWarningHelper(ui_.status, message);
  }

  QWidget* TfFramePlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  bool TfFramePlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = canvas;

    timer_ = node_.createTimer(ros::Duration(0.1),
                               &TfFramePlugin::TimerCallback, this);

    SetColor(ui_.color->color());

    return true;
  }

  void TfFramePlugin::Draw(double x, double y, double scale)
  {
    if (DrawPoints(scale))
    {
      PrintInfo("OK");
    }
  }
  void TfFramePlugin::LoadConfig(const YAML::Node& node,
                                 const std::string& path)
  {
    if (node["frame"])
    {
      node["frame"] >> source_frame_;
      ui_.frame->setText(source_frame_.c_str());
    }

    if (node["color"])
    {
      std::string color;
      node["color"] >> color;
      SetColor(QColor(color.c_str()));
      ui_.color->setColor(color_);
    }

    if (node["draw_style"])
    {
      std::string draw_style;
      node["draw_style"] >> draw_style;

      if (draw_style == "lines")
      {
        draw_style_ = LINES;
        ui_.drawstyle->setCurrentIndex(0);
      }
      else if (draw_style == "points")
      {
        draw_style_ = POINTS;
        ui_.drawstyle->setCurrentIndex(1);
      }
      else if (draw_style == "arrows")
      {
        draw_style_ = ARROWS;
        ui_.drawstyle->setCurrentIndex(2);
      }
    }

    if (node["position_tolerance"])
    {
      node["position_tolerance"] >> position_tolerance_;
      ui_.positiontolerance->setValue(position_tolerance_);
    }

    if (node["buffer_size"])
    {
      node["buffer_size"] >> buffer_size_;
      ui_.buffersize->setValue(buffer_size_);
    }

    if (node["static_arrow_sizes"])
    {
      bool static_arrow_sizes = node["static_arrow_sizes"].as<bool>();
      ui_.static_arrow_sizes->setChecked(static_arrow_sizes);
      SetStaticArrowSizes(static_arrow_sizes);
    }

    if (node["arrow_size"])
    {
      ui_.arrow_size->setValue(node["arrow_size"].as<int>());
    }

    FrameEdited();
  }

  void TfFramePlugin::SaveConfig(YAML::Emitter& emitter,
                                 const std::string& path)
  {
    emitter << YAML::Key << "frame" << YAML::Value
            << ui_.frame->text().toStdString();
    emitter << YAML::Key << "color" << YAML::Value
            << ui_.color->color().name().toStdString();

    std::string draw_style = ui_.drawstyle->currentText().toStdString();
    emitter << YAML::Key << "draw_style" << YAML::Value << draw_style;

    emitter << YAML::Key << "position_tolerance" <<
               YAML::Value << position_tolerance_;

    emitter << YAML::Key << "buffer_size" << YAML::Value << buffer_size_;

    emitter << YAML::Key << "static_arrow_sizes" << YAML::Value << ui_.static_arrow_sizes->isChecked();

    emitter << YAML::Key << "arrow_size" << YAML::Value << ui_.arrow_size->value();
  }
}
<|endoftext|>


<commit_before>#include "enemy.h"

Enemy::Enemy(Player* player, float lineOfSight, float forceTowardsPlayer, float forceFromAbstacles, float health, float speed, float damage, int width, int height, unsigned int textureID, b2World * world) : Person::Person(health, speed, damage, width, height, textureID, world)
{
	this->player = player;
	this->lineOfSight = lineOfSight;
	this->forceTowardsPlayer = forceTowardsPlayer;
	this->forceFromObstacles = forceFromAbstacles;
	raycast = new Raycast(world);

	distanceObjects = new B2Entity(width, height, 0, world);
	distanceObjects->CreateCircleCollider(65, true, true);
	distanceObjects->SetDebugColor(glm::vec3(1, 0, 0));
	this->AddChild(distanceObjects);

	/*mirror = new Mirror(false, 45.0f, 120.0f, ResourceManager::GetTexture("mirror")->GetId(), world);
	mirror->localPosition.x = 100;
	mirror->CreateBoxCollider(45.0f, 120.0f, glm::vec2(0.0f, 0.0f), false, false);
	mirror->SetFilter(2);
	AddChild(mirror);*/

	attackRadius = 150.0f;
	sword = new B2Entity(75, 120, ResourceManager::GetTexture("sword")->GetId(), world);
	sword->SetPivot(glm::vec2(0.0f, -0.5f));
	sword->CreateBoxCollider(40, 120, glm::vec2(0, -0.5f), true, true);
	sword->localPosition = glm::vec2(20,34);
	sword->localAngle = glm::radians(110.0f);
	sword->SetFilter(2);
	AddChild(sword);

	redHealthbar = new Sprite(150, 15, 0);
	redHealthbar->SetColor(glm::vec4(1, 0, 0, 1));
	redHealthbar->SetPivot(glm::vec2(0.5f, 0.0f));
	AddChild(redHealthbar);
	greenHealthbar = new Sprite(150, 15, 0);
	greenHealthbar->SetColor(glm::vec4(0, 1, 0, 1));
	greenHealthbar->SetPivot(glm::vec2(0.5f, 0.0f));
	AddChild(greenHealthbar);
}

Enemy::~Enemy()
{
	delete raycast;
	delete distanceObjects;
	//delete mirror;
	delete sword;
	delete redHealthbar;
	delete greenHealthbar;
}

void Enemy::Update(double deltaTime)
{

	glm::vec2 rayDestination = player->GetGlobalPosition() - position;
	rayDestination = glm::normalize(rayDestination);
	rayDestination *= lineOfSight;
	rayDestination += position;
	raycast->Update(position, rayDestination);
	raycast->Draw(glm::vec3(0,1,0));

	glm::vec2 acceleration;
	bool playerHit = false;
	// Check if the first object hitted by the raycast is the player
	std::vector<RaycastHit> hits = raycast->GetHits();
	for (int i = 0; i < hits.size(); i++) {
		B2Entity* b = static_cast<B2Entity*>(hits[i].fixture->GetUserData());
		if (b == player) {
			// hitted player
			lastPositionPlayer = player->GetGlobalPosition();
			if (glm::length(lastPositionPlayer - position) < attackRadius) {
				sword->localAngle -= glm::radians(180.0f) * deltaTime;
				if (sword->localAngle < 0) {//glm::radians(90.0f) * -1) {
					sword->localAngle = glm::radians(110.0f);
				}
				if (sword->Contact(player)) {
					player->Damage(damage * deltaTime);
				}
			}
			else {
				sword->localAngle = glm::radians(110.0f);
				acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer);
			}
			playerHit = true;
			glm::vec2 diff = player->GetGlobalPosition() - position;
			diff = glm::normalize(diff);
			float _angle = glm::atan(diff.y, diff.x);
			localAngle = _angle;
			continue;
		}
		// If the raycast hit is a enemy or a sensor continue with the for loop otheriwse break it
		else if (dynamic_cast<Enemy*>(b) != NULL || hits[i].fixture->IsSensor() || b->GetFilter() == 2) {
			continue;
		}
		break;
	}
	if (!playerHit && glm::length(position - lastPositionPlayer) > 75.0f) {
		acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer);
		glm::vec2 diff = lastPositionPlayer - position;
		diff = glm::normalize(diff);
		float _angle = glm::atan(diff.y, diff.x);
		localAngle = _angle;
	}

	std::vector<B2Entity*> inRangeObjects = distanceObjects->GetAllContacts();
	for (int i = 0; i < inRangeObjects.size(); i++) {
		if (inRangeObjects[i] != this && inRangeObjects[i] != player && inRangeObjects[i]->GetFilter() != 2) {
			// hitted a wall or something
			acceleration += (glm::normalize(position - inRangeObjects[i]->GetGlobalPosition()) * forceFromObstacles);
		}
	}
	if (acceleration.x != 0 || acceleration.y != 0) {
		velocity += acceleration;
		velocity = glm::normalize(velocity);
		velocity *= speed;
		this->localPosition = this->ApplyVelocityB2body(velocity);
	}
}

void Enemy::Draw()
{
	// Update the healthbars
	redHealthbar->UpdateChilderen(NULL, 0);
	greenHealthbar->UpdateChilderen(NULL, 0);
	redHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125);
	greenHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125);
	greenHealthbar->SetWidth(currentHealth / maxHealth * 150);
	// Render
	renderer->Submit(this);
	if (body != nullptr) {
		DebugRenderer::Submit(this);
	}
}
<commit_msg>removed unnecesary lines<commit_after>#include "enemy.h"

Enemy::Enemy(Player* player, float lineOfSight, float forceTowardsPlayer, float forceFromAbstacles, float health, float speed, float damage, int width, int height, unsigned int textureID, b2World * world) : Person::Person(health, speed, damage, width, height, textureID, world)
{
	this->player = player;
	this->lineOfSight = lineOfSight;
	this->forceTowardsPlayer = forceTowardsPlayer;
	this->forceFromObstacles = forceFromAbstacles;
	raycast = new Raycast(world);

	distanceObjects = new B2Entity(width, height, 0, world);
	distanceObjects->CreateCircleCollider(65, true, true);
	this->AddChild(distanceObjects);

	attackRadius = 150.0f;
	sword = new B2Entity(75, 120, ResourceManager::GetTexture("sword")->GetId(), world);
	sword->SetPivot(glm::vec2(0.0f, -0.5f));
	sword->CreateBoxCollider(40, 120, glm::vec2(0, -0.5f), true, true);
	sword->localPosition = glm::vec2(20,34);
	sword->localAngle = glm::radians(110.0f);
	sword->SetFilter(2);
	AddChild(sword);

	redHealthbar = new Sprite(150, 15, 0);
	redHealthbar->SetColor(glm::vec4(1, 0, 0, 1));
	redHealthbar->SetPivot(glm::vec2(0.5f, 0.0f));
	AddChild(redHealthbar);
	greenHealthbar = new Sprite(150, 15, 0);
	greenHealthbar->SetColor(glm::vec4(0, 1, 0, 1));
	greenHealthbar->SetPivot(glm::vec2(0.5f, 0.0f));
	AddChild(greenHealthbar);
}

Enemy::~Enemy()
{
	delete raycast;
	delete distanceObjects;
	//delete mirror;
	delete sword;
	delete redHealthbar;
	delete greenHealthbar;
}

void Enemy::Update(double deltaTime)
{

	glm::vec2 rayDestination = player->GetGlobalPosition() - position;
	rayDestination = glm::normalize(rayDestination);
	rayDestination *= lineOfSight;
	rayDestination += position;
	raycast->Update(position, rayDestination);
	raycast->Draw(glm::vec3(0,1,0));

	glm::vec2 acceleration;
	bool playerHit = false;
	// Check if the first object hitted by the raycast is the player
	std::vector<RaycastHit> hits = raycast->GetHits();
	for (int i = 0; i < hits.size(); i++) {
		B2Entity* b = static_cast<B2Entity*>(hits[i].fixture->GetUserData());
		if (b == player) {
			// hitted player
			lastPositionPlayer = player->GetGlobalPosition();
			if (glm::length(lastPositionPlayer - position) < attackRadius) {
				sword->localAngle -= glm::radians(180.0f) * deltaTime;
				if (sword->localAngle < 0) {//glm::radians(90.0f) * -1) {
					sword->localAngle = glm::radians(110.0f);
				}
				if (sword->Contact(player)) {
					player->Damage(damage * deltaTime);
				}
			}
			else {
				sword->localAngle = glm::radians(110.0f);
				acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer);
			}
			playerHit = true;
			glm::vec2 diff = player->GetGlobalPosition() - position;
			diff = glm::normalize(diff);
			float _angle = glm::atan(diff.y, diff.x);
			localAngle = _angle;
			continue;
		}
		// If the raycast hit is a enemy or a sensor continue with the for loop otheriwse break it
		else if (dynamic_cast<Enemy*>(b) != NULL || hits[i].fixture->IsSensor() || b->GetFilter() == 2) {
			continue;
		}
		break;
	}
	if (!playerHit && glm::length(position - lastPositionPlayer) > 75.0f) {
		acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer);
		glm::vec2 diff = lastPositionPlayer - position;
		diff = glm::normalize(diff);
		float _angle = glm::atan(diff.y, diff.x);
		localAngle = _angle;
	}

	std::vector<B2Entity*> inRangeObjects = distanceObjects->GetAllContacts();
	for (int i = 0; i < inRangeObjects.size(); i++) {
		if (inRangeObjects[i] != this && inRangeObjects[i] != player && inRangeObjects[i]->GetFilter() != 2) {
			// hitted a wall or something
			acceleration += (glm::normalize(position - inRangeObjects[i]->GetGlobalPosition()) * forceFromObstacles);
		}
	}
	if (acceleration.x != 0 || acceleration.y != 0) {
		velocity += acceleration;
		velocity = glm::normalize(velocity);
		velocity *= speed;
		this->localPosition = this->ApplyVelocityB2body(velocity);
	}
}

void Enemy::Draw()
{
	// Update the healthbars
	redHealthbar->UpdateChilderen(NULL, 0);
	greenHealthbar->UpdateChilderen(NULL, 0);
	redHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125);
	greenHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125);
	greenHealthbar->SetWidth(currentHealth / maxHealth * 150);
	// Render
	renderer->Submit(this);
	if (body != nullptr) {
		DebugRenderer::Submit(this);
	}
}
<|endoftext|>