<commit_before>// Project specific
#include <Game.hpp>
#include <Utility/DynamicLoader/Include/DynamicLoader.hpp>
/// Engine
// Core
#include <DoremiEngine/Core/Include/DoremiEngine.hpp>
#include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp>
#include <DoremiEngine/Core/Include/SharedContext.hpp>
// Physics
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/FluidManager.hpp>
// AI
#include <DoremiEngine/AI/Include/AIModule.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
// GRAPHICS
#include <DoremiEngine/Graphic/Include/GraphicModule.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/DirectXManager.hpp>

/// Game
// handlers
#include <Doremi/Core/Include/InterpolationHandler.hpp>
#include <Doremi/Core/Include/EventHandler/EventHandlerClient.hpp>
#include <Doremi/Core/Include/PlayerHandlerClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityHandlerClient.hpp>
#include <Doremi/Core/Include/AudioHandler.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <Doremi/Core/Include/MenuClasses/MenuHandler.hpp>
#include <Doremi/Core/Include/MenuClasses/MenuGraphicHandler.hpp>
#include <Doremi/Core/Include/NetworkEventSender.hpp>
#include <Doremi/Core/Include/CameraHandler.hpp>
#include <Doremi/Core/Include/PositionCorrectionHandler.hpp>
#include <Doremi/Core/Include/Handler/StateHandler.hpp>
#include <Doremi/Core/Include/PlayerSpawnerHandler.hpp>
#include <Doremi/Core/Include/TimeHandler.hpp>

// Managers
#include <Doremi/Core/Include/Manager/GraphicManager.hpp>
#include <Doremi/Core/Include/Manager/SkeletalAnimationCoreManager.hpp>
#include <Doremi/Core/Include/Network/NetworkManagerClient.hpp>
#include <Doremi/Core/Include/Manager/MovementManagerClient.hpp>
#include <Doremi/Core/Include/Manager/AudioManager.hpp>
#include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp>
#include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp>
#include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp>
#include <Doremi/Core/Include/Manager/JumpManager.hpp>
#include <Doremi/Core/Include/Manager/SkyBoxManager.hpp>
#include <Doremi/Core/Include/Manager/GravityManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleGraphicManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleManager.hpp>
#include <Doremi/Core/Include/Manager/LightManager.hpp>
#include <Doremi/Core/Include/Manager/TriggerManager.hpp>
#include <Doremi/Core/Include/Manager/ExtraDrainSyncManager.hpp>
#include <Doremi/Core/Include/Manager/GroundEffectManagerClient.hpp>
// Components
#include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PlatformPatrolComponent.hpp>
// Events
#include <Doremi/Core/Include/EventHandler/Events/ChangeMenuState.hpp>
// Other stuff
#include <Doremi/Core/Include/TemplateCreator.hpp>
#include <Doremi/Core/Include/LevelLoaderClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp>
#include <Doremi/Core/Include/ScreenSpaceDrawer.hpp>

// Timer
#include <Doremi/Core/Include/Timing/TimerManager.hpp>

// Third party

// Standard libraries
#include <exception>
#include <chrono>
#include <vector>
#include <iostream> //TODOLH remove once all the functionality is implemented in the menusystem

namespace Doremi
{
    using namespace Core;
    GameMain::GameMain() : m_sharedContext(nullptr) {}

    GameMain::~GameMain()
    {
        for(auto& manager : m_managers)
        {
            delete manager;
        }
        m_managers.clear();

        for(auto& manager : m_graphicalManagers)
        {
            delete manager;
        }
        m_graphicalManagers.clear();
    }

    void GameMain::Initialize()
    {
        TIME_FUNCTION_START

        using namespace Core;
        const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine(DoremiEngine::Core::EngineModuleEnum::ALL);
        m_sharedContext = &sharedContext;

        /* This starts the physics handler. Should not be done here, but since this is the general
        code dump, it'll work for now TODOJB*/
        EventHandlerClient::StartupEventHandlerClient();
        EntityHandlerClient::StartupEntityHandlerClient(sharedContext);
        PlayerHandlerClient::StartPlayerHandlerClient(sharedContext);
        InterpolationHandler::StartInterpolationHandler(sharedContext);
        AudioHandler::StartAudioHandler(sharedContext); // Needs to be stareted after event handler
        StateHandler::StartStateHandler(sharedContext);
        CameraHandler::StartCameraHandler(sharedContext);
        PositionCorrectionHandler::StartPositionCorrectionHandler(sharedContext);
        EntityFactory::StartupEntityFactory(sharedContext);
        PlayerSpawnerHandler::StartupPlayerSpawnerHandler(sharedContext);

        // Initialize 2d drawer class
        m_screenRes = m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().GetScreenResolution();
        m_screenSpaceDrawer = new ScreenSpaceDrawer(sharedContext, m_screenRes);

        // Create manager & add manager to list of managers
        AddToGraphicalManagerList(new PressureParticleGraphicManager(sharedContext));
        AddToGraphicalManagerList(new GraphicManager(sharedContext));
        AddToGraphicalManagerList(new SkeletalAnimationCoreManager(sharedContext));
        AddToGraphicalManagerList(new SkyBoxManager(sharedContext));
        AddToManagerList(new AudioManager(sharedContext));
        AddToManagerList(new NetworkManagerClient(sharedContext));
        AddToManagerList(new RigidTransformSyncManager(sharedContext));
        AddToManagerList(new PressureParticleManager(sharedContext));
        AddToManagerList(new LightManager(sharedContext));
        AddToManagerList(new JumpManager(sharedContext));
        AddToManagerList(new GravityManager(sharedContext));
        AddToManagerList(new MovementManagerClient(sharedContext)); // Must be after gravity/jump
        AddToManagerList(new CharacterControlSyncManager(sharedContext)); // Must be after movement
        AddToManagerList(new TriggerManager(sharedContext)); // TODOKO should only be needed on server
        AddToGraphicalManagerList(new ExtraDrainSyncManager(sharedContext));
        AddToGraphicalManagerList(new GroundEffectManagerClient(sharedContext));

        // Initialize menu
        std::vector<string> t_textureNamesForMenuButtons;

        // Use this order when adding buttons. The order of the buttons can be view by hovering Menuhandler initialize under. Place highlighted TODOXX
        // textures under in the same order
        t_textureNamesForMenuButtons.push_back("playbutton2.dds");
        t_textureNamesForMenuButtons.push_back("optionsbutton2.dds");
        t_textureNamesForMenuButtons.push_back("exitbutton2.dds");
        t_textureNamesForMenuButtons.push_back("Fullscreen.dds");
        t_textureNamesForMenuButtons.push_back("playbutton2highlight.dds");
        t_textureNamesForMenuButtons.push_back("optionsbutton2highlight.dds");
        t_textureNamesForMenuButtons.push_back("exitbutton2highlight.dds");
        t_textureNamesForMenuButtons.push_back("FullscreenHighlighted.dds");
        MenuHandler::StartMenuHandler(sharedContext, m_screenRes);
        MenuHandler::GetInstance()->Initialize(t_textureNamesForMenuButtons);

        // initialize menudraw
        MenuGraphicHandler::StartMenuGraphicHandler(sharedContext);

        TemplateCreator::GetInstance()->CreateTemplatesForClient(sharedContext);
        BuildWorld(sharedContext);

        AudioHandler::GetInstance()->SetupContinuousRecording();
        AudioHandler::GetInstance()->StartContinuousRecording();
        AudioHandler::GetInstance()->SetupRepeatableRecording();

        TIME_FUNCTION_STOP
    }

    void GameMain::AddToManagerList(Manager* p_manager) { m_managers.push_back(p_manager); }

    void GameMain::AddToGraphicalManagerList(Manager* p_manager) { m_graphicalManagers.push_back(p_manager); }

    void GameMain::BuildWorld(const DoremiEngine::Core::SharedContext& sharedContext)
    {
        TIME_FUNCTION_START
        Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance();
        Core::LevelLoaderClient t_levelLoader(sharedContext);

        t_levelLoader.LoadLevel("Levels/IntroScene.drm");

        // Create platforms
        for(size_t i = 0; i < 1; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity, DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f), XMFLOAT4(0, 0, 0, 1));
            DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f); // why not pass as parameter in above method?
            DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);

            Core::PlatformPatrolComponent* t_platformPatrolComponent =
                Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PlatformPatrolComponent>(entityID);
            t_platformPatrolComponent->startPosition = position;
            t_platformPatrolComponent->endPosition = DirectX::XMFLOAT3(position.x, position.y + 140, position.z);
        }

        // Create an enemy spawner (only necessary to keep entityIDs aligned with server)
        TIME_FUNCTION_STOP
    }

    void GameMain::Run()
    {
        TIME_FUNCTION_START
        // TODOCM remove for better timer
        // GameLoop is not currently set
        TimeHandler* t_timeHandler = TimeHandler::GetInstance();

        t_timeHandler->PreviousClock = std::chrono::high_resolution_clock::now();

        while(true)
        {
            // Tick time
            t_timeHandler->Tick();

            // Loop as many update-steps we will take this frame
            while(t_timeHandler->ShouldUpdateFrame())
            {
                // Update game based on state
                Update(t_timeHandler->UpdateStepLen);

                // Update interpolation transforms from snapshots
                Core::InterpolationHandler::GetInstance()->UpdateInterpolationTransforms();

                // Deliver events
                static_cast<Core::EventHandlerClient*>(Core::EventHandler::GetInstance())->DeliverEvents();

                // Update accumulator and gametime
                t_timeHandler->UpdateAccumulatorAndGameTime();
            }

            // Update alpha usd for inteprolation
            double alpha = t_timeHandler->GetFrameAlpha();

            // Interpolate the frames here
            Core::InterpolationHandler::GetInstance()->InterpolateFrame(alpha);

            // Update camera after we update positions
            CameraHandler::GetInstance()->UpdateDraw();

            Draw(t_timeHandler->Frame);

            // Escape
            PlayerHandlerClient* t_playerHandler = static_cast<PlayerHandlerClient*>(PlayerHandler::GetInstance());
            InputHandlerClient* inputHandler = t_playerHandler->GetInputHandler();
            if(inputHandler != nullptr)
            {
                if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::ExitGame))
                {
                    break;
                }
            }
        }
        TIME_FUNCTION_STOP
    }

    void GameMain::UpdateGame(double p_deltaTime)
    {
        TIME_FUNCTION_START

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

        CameraHandler::GetInstance()->UpdateInput(p_deltaTime);

        // PlayerHandler::GetInstance()->UpdateAddRemoveObjects();

        TIME_FUNCTION_STOP
    }

    void GameMain::UpdateMenu(double p_deltaTime) {}

    void GameMain::Update(double p_deltaTime)
    {
        TIME_FUNCTION_START
        static_cast<PlayerHandlerClient*>(Core::PlayerHandler::GetInstance())->UpdatePlayerInputs();

        AudioHandler::GetInstance()->Update(p_deltaTime);

        Core::DoremiStates t_state = Core::StateHandler::GetInstance()->GetState();

        switch(t_state)
        {
            case Core::DoremiStates::MAINMENU:
            {
                // Update Menu Logic
                MenuHandler::GetInstance()->Update(p_deltaTime);
                break;
            }
            case Core::DoremiStates::SERVER_BROWSER:
            {

                break;
            }
            case Core::DoremiStates::OPTIONS:
            {
                std::cout << "You clicked options button. It has no effect. State changed back to MAINMENU" << std::endl;
                // State is changed with events TODOXX should be removed from here once options is implemented
                Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                menuEvent->state = Core::DoremiStates::MAINMENU;
                Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
                break;
            }
            case Core::DoremiStates::RUNGAME:
            {
                // Update Game logic
                UpdateGame(p_deltaTime);
                break;
            }
            case Core::DoremiStates::PAUSE:
            {
                // Update Pause Screen
                break;
            }
            case Core::DoremiStates::EXIT:
            {
                std::cout << "You clicked exit its not ver effective state changed back to mainmenu" << std::endl;
                // State is changed with events TODOXX should be removed from here once EXIT is implemented
                Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                menuEvent->state = Core::DoremiStates::MAINMENU;
                Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
                break;
            }
            default:
            {
                break;
            }
        }
        TIME_FUNCTION_STOP
    }

    void GameMain::DrawMenu(double p_deltaTime)
    {

        TIME_FUNCTION_START
        MenuHandler* t_menuHandler = MenuHandler::GetInstance();
        MenuGraphicHandler::GetInstance()->DrawButtons(p_deltaTime, t_menuHandler->GetButtons(), t_menuHandler->GetCurrentButton());
        TIME_FUNCTION_STOP
    }

    void GameMain::DrawGame(double p_deltaTime)
    {
        TIME_FUNCTION_START
        size_t length = m_graphicalManagers.size();
        for(size_t i = 0; i < length; i++)
        {
            m_graphicalManagers.at(i)->Update(p_deltaTime);
        }
        TIME_FUNCTION_STOP
    }

    void GameMain::Draw(double p_deltaTime)
    {
        TIME_FUNCTION_START
        /** TODOLH Detta ska flyttas till en function som i updaten*/
        Core::DoremiStates t_state = Core::StateHandler::GetInstance()->GetState();
        m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().BeginDraw();
        switch(t_state)
        {
            case Core::DoremiStates::RUNGAME:
                // Draw Game
                DrawGame(p_deltaTime);
                break;
            default:
                break;
        }
        // WE always draw 2d stuff
        m_screenSpaceDrawer->Draw();
        TIME_FUNCTION_STOP
    }

    void GameMain::Start()
    {
        TIME_FUNCTION_START
        Initialize();
        Run();
        TIME_FUNCTION_STOP
    }

    void GameMain::Stop() { Doremi::Core::TimerManager::GetInstance().DumpData(*m_sharedContext); }
}<commit_msg>iAdded timings for managers again<commit_after>// Project specific
#include <Game.hpp>
#include <Utility/DynamicLoader/Include/DynamicLoader.hpp>
/// Engine
// Core
#include <DoremiEngine/Core/Include/DoremiEngine.hpp>
#include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp>
#include <DoremiEngine/Core/Include/SharedContext.hpp>
// Physics
#include <DoremiEngine/Physics/Include/CharacterControlManager.hpp>
#include <DoremiEngine/Physics/Include/PhysicsModule.hpp>
#include <DoremiEngine/Physics/Include/RigidBodyManager.hpp>
#include <DoremiEngine/Physics/Include/FluidManager.hpp>
// AI
#include <DoremiEngine/AI/Include/AIModule.hpp>
#include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp>
#include <DoremiEngine/AI/Include/Interface/PotentialField/PotentialFieldActor.hpp>
// GRAPHICS
#include <DoremiEngine/Graphic/Include/GraphicModule.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/DirectXManager.hpp>

/// Game
// handlers
#include <Doremi/Core/Include/InterpolationHandler.hpp>
#include <Doremi/Core/Include/EventHandler/EventHandlerClient.hpp>
#include <Doremi/Core/Include/PlayerHandlerClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityHandlerClient.hpp>
#include <Doremi/Core/Include/AudioHandler.hpp>
#include <Doremi/Core/Include/InputHandlerClient.hpp>
#include <Doremi/Core/Include/MenuClasses/MenuHandler.hpp>
#include <Doremi/Core/Include/MenuClasses/MenuGraphicHandler.hpp>
#include <Doremi/Core/Include/NetworkEventSender.hpp>
#include <Doremi/Core/Include/CameraHandler.hpp>
#include <Doremi/Core/Include/PositionCorrectionHandler.hpp>
#include <Doremi/Core/Include/Handler/StateHandler.hpp>
#include <Doremi/Core/Include/PlayerSpawnerHandler.hpp>
#include <Doremi/Core/Include/TimeHandler.hpp>

// Managers
#include <Doremi/Core/Include/Manager/GraphicManager.hpp>
#include <Doremi/Core/Include/Manager/SkeletalAnimationCoreManager.hpp>
#include <Doremi/Core/Include/Network/NetworkManagerClient.hpp>
#include <Doremi/Core/Include/Manager/MovementManagerClient.hpp>
#include <Doremi/Core/Include/Manager/AudioManager.hpp>
#include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp>
#include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp>
#include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp>
#include <Doremi/Core/Include/Manager/JumpManager.hpp>
#include <Doremi/Core/Include/Manager/SkyBoxManager.hpp>
#include <Doremi/Core/Include/Manager/GravityManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleGraphicManager.hpp>
#include <Doremi/Core/Include/Manager/PressureParticleManager.hpp>
#include <Doremi/Core/Include/Manager/LightManager.hpp>
#include <Doremi/Core/Include/Manager/TriggerManager.hpp>
#include <Doremi/Core/Include/Manager/ExtraDrainSyncManager.hpp>
#include <Doremi/Core/Include/Manager/GroundEffectManagerClient.hpp>
// Components
#include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp>
#include <Doremi/Core/Include/EntityComponent/Components/PlatformPatrolComponent.hpp>
// Events
#include <Doremi/Core/Include/EventHandler/Events/ChangeMenuState.hpp>
// Other stuff
#include <Doremi/Core/Include/TemplateCreator.hpp>
#include <Doremi/Core/Include/LevelLoaderClient.hpp>
#include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp>
#include <Doremi/Core/Include/ScreenSpaceDrawer.hpp>

// Timer
#include <Doremi/Core/Include/Timing/TimerManager.hpp>
#include <Utility/Utilities/Include/Chrono/Timer.hpp>

// Third party

// Standard libraries
#include <exception>
#include <chrono>
#include <vector>
#include <iostream> //TODOLH remove once all the functionality is implemented in the menusystem

namespace Doremi
{
    using namespace Core;
    GameMain::GameMain() : m_sharedContext(nullptr) {}

    GameMain::~GameMain()
    {
        for(auto& manager : m_managers)
        {
            delete manager;
        }
        m_managers.clear();

        for(auto& manager : m_graphicalManagers)
        {
            delete manager;
        }
        m_graphicalManagers.clear();
    }

    void GameMain::Initialize()
    {
        TIME_FUNCTION_START

        using namespace Core;
        const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine(DoremiEngine::Core::EngineModuleEnum::ALL);
        m_sharedContext = &sharedContext;

        /* This starts the physics handler. Should not be done here, but since this is the general
        code dump, it'll work for now TODOJB*/
        EventHandlerClient::StartupEventHandlerClient();
        EntityHandlerClient::StartupEntityHandlerClient(sharedContext);
        PlayerHandlerClient::StartPlayerHandlerClient(sharedContext);
        InterpolationHandler::StartInterpolationHandler(sharedContext);
        AudioHandler::StartAudioHandler(sharedContext); // Needs to be stareted after event handler
        StateHandler::StartStateHandler(sharedContext);
        CameraHandler::StartCameraHandler(sharedContext);
        PositionCorrectionHandler::StartPositionCorrectionHandler(sharedContext);
        EntityFactory::StartupEntityFactory(sharedContext);
        PlayerSpawnerHandler::StartupPlayerSpawnerHandler(sharedContext);

        // Initialize 2d drawer class
        m_screenRes = m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().GetScreenResolution();
        m_screenSpaceDrawer = new ScreenSpaceDrawer(sharedContext, m_screenRes);

        // Create manager & add manager to list of managers
        AddToGraphicalManagerList(new PressureParticleGraphicManager(sharedContext));
        AddToGraphicalManagerList(new GraphicManager(sharedContext));
        AddToGraphicalManagerList(new SkeletalAnimationCoreManager(sharedContext));
        AddToGraphicalManagerList(new SkyBoxManager(sharedContext));
        AddToManagerList(new AudioManager(sharedContext));
        AddToManagerList(new NetworkManagerClient(sharedContext));
        AddToManagerList(new RigidTransformSyncManager(sharedContext));
        AddToManagerList(new PressureParticleManager(sharedContext));
        AddToManagerList(new LightManager(sharedContext));
        AddToManagerList(new JumpManager(sharedContext));
        AddToManagerList(new GravityManager(sharedContext));
        AddToManagerList(new MovementManagerClient(sharedContext)); // Must be after gravity/jump
        AddToManagerList(new CharacterControlSyncManager(sharedContext)); // Must be after movement
        AddToManagerList(new TriggerManager(sharedContext)); // TODOKO should only be needed on server
        AddToGraphicalManagerList(new ExtraDrainSyncManager(sharedContext));
        AddToGraphicalManagerList(new GroundEffectManagerClient(sharedContext));

        // Initialize menu
        std::vector<string> t_textureNamesForMenuButtons;

        // Use this order when adding buttons. The order of the buttons can be view by hovering Menuhandler initialize under. Place highlighted TODOXX
        // textures under in the same order
        t_textureNamesForMenuButtons.push_back("playbutton2.dds");
        t_textureNamesForMenuButtons.push_back("optionsbutton2.dds");
        t_textureNamesForMenuButtons.push_back("exitbutton2.dds");
        t_textureNamesForMenuButtons.push_back("Fullscreen.dds");
        t_textureNamesForMenuButtons.push_back("playbutton2highlight.dds");
        t_textureNamesForMenuButtons.push_back("optionsbutton2highlight.dds");
        t_textureNamesForMenuButtons.push_back("exitbutton2highlight.dds");
        t_textureNamesForMenuButtons.push_back("FullscreenHighlighted.dds");
        MenuHandler::StartMenuHandler(sharedContext, m_screenRes);
        MenuHandler::GetInstance()->Initialize(t_textureNamesForMenuButtons);

        // initialize menudraw
        MenuGraphicHandler::StartMenuGraphicHandler(sharedContext);

        TemplateCreator::GetInstance()->CreateTemplatesForClient(sharedContext);
        BuildWorld(sharedContext);

        AudioHandler::GetInstance()->SetupContinuousRecording();
        AudioHandler::GetInstance()->StartContinuousRecording();
        AudioHandler::GetInstance()->SetupRepeatableRecording();

        TIME_FUNCTION_STOP
    }

    void GameMain::AddToManagerList(Manager* p_manager) { m_managers.push_back(p_manager); }

    void GameMain::AddToGraphicalManagerList(Manager* p_manager) { m_graphicalManagers.push_back(p_manager); }

    void GameMain::BuildWorld(const DoremiEngine::Core::SharedContext& sharedContext)
    {
        TIME_FUNCTION_START
        Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance();
        Core::LevelLoaderClient t_levelLoader(sharedContext);

        t_levelLoader.LoadLevel("Levels/IntroScene.drm");

        // Create platforms
        for(size_t i = 0; i < 1; i++)
        {
            int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity, DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f), XMFLOAT4(0, 0, 0, 1));
            DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(-165.75f, 4.6f, -103.74f); // why not pass as parameter in above method?
            DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1);

            Core::PlatformPatrolComponent* t_platformPatrolComponent =
                Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PlatformPatrolComponent>(entityID);
            t_platformPatrolComponent->startPosition = position;
            t_platformPatrolComponent->endPosition = DirectX::XMFLOAT3(position.x, position.y + 140, position.z);
        }

        // Create an enemy spawner (only necessary to keep entityIDs aligned with server)
        TIME_FUNCTION_STOP
    }

    void GameMain::Run()
    {
        TIME_FUNCTION_START
        // TODOCM remove for better timer
        // GameLoop is not currently set
        TimeHandler* t_timeHandler = TimeHandler::GetInstance();

        t_timeHandler->PreviousClock = std::chrono::high_resolution_clock::now();

        while(true)
        {
            // Tick time
            t_timeHandler->Tick();

            // Loop as many update-steps we will take this frame
            while(t_timeHandler->ShouldUpdateFrame())
            {
                // Update game based on state
                Update(t_timeHandler->UpdateStepLen);

                // Update interpolation transforms from snapshots
                Core::InterpolationHandler::GetInstance()->UpdateInterpolationTransforms();

                // Deliver events
                static_cast<Core::EventHandlerClient*>(Core::EventHandler::GetInstance())->DeliverEvents();

                // Update accumulator and gametime
                t_timeHandler->UpdateAccumulatorAndGameTime();
            }

            // Update alpha usd for inteprolation
            double alpha = t_timeHandler->GetFrameAlpha();

            // Interpolate the frames here
            Core::InterpolationHandler::GetInstance()->InterpolateFrame(alpha);

            // Update camera after we update positions
            CameraHandler::GetInstance()->UpdateDraw();

            Draw(t_timeHandler->Frame);

            // Escape
            PlayerHandlerClient* t_playerHandler = static_cast<PlayerHandlerClient*>(PlayerHandler::GetInstance());
            InputHandlerClient* inputHandler = t_playerHandler->GetInputHandler();
            if(inputHandler != nullptr)
            {
                if(inputHandler->CheckBitMaskInputFromGame((int)UserCommandPlaying::ExitGame))
                {
                    break;
                }
            }
        }
        TIME_FUNCTION_STOP
    }

    void GameMain::UpdateGame(double p_deltaTime)
    {
        TIME_FUNCTION_START

        size_t length = m_managers.size();
        PlayerHandler::GetInstance()->Update(p_deltaTime);
        // AudioHandler::GetInstance()->Update(p_deltaTime);
        // Have all managers update
        for(size_t i = 0; i < length; i++)
        {
            Doremi::Core::TimerManager::GetInstance().StartTimer(m_managers.at(i)->GetName());
            m_managers.at(i)->Update(p_deltaTime);
            Doremi::Core::TimerManager::GetInstance().StopTimer(m_managers.at(i)->GetName());
        }

        CameraHandler::GetInstance()->UpdateInput(p_deltaTime);

        // PlayerHandler::GetInstance()->UpdateAddRemoveObjects();

        TIME_FUNCTION_STOP
    }

    void GameMain::UpdateMenu(double p_deltaTime) {}

    void GameMain::Update(double p_deltaTime)
    {
        TIME_FUNCTION_START
        static_cast<PlayerHandlerClient*>(Core::PlayerHandler::GetInstance())->UpdatePlayerInputs();

        AudioHandler::GetInstance()->Update(p_deltaTime);

        Core::DoremiStates t_state = Core::StateHandler::GetInstance()->GetState();

        switch(t_state)
        {
            case Core::DoremiStates::MAINMENU:
            {
                // Update Menu Logic
                MenuHandler::GetInstance()->Update(p_deltaTime);
                break;
            }
            case Core::DoremiStates::SERVER_BROWSER:
            {

                break;
            }
            case Core::DoremiStates::OPTIONS:
            {
                std::cout << "You clicked options button. It has no effect. State changed back to MAINMENU" << std::endl;
                // State is changed with events TODOXX should be removed from here once options is implemented
                Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                menuEvent->state = Core::DoremiStates::MAINMENU;
                Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
                break;
            }
            case Core::DoremiStates::RUNGAME:
            {
                // Update Game logic
                UpdateGame(p_deltaTime);
                break;
            }
            case Core::DoremiStates::PAUSE:
            {
                // Update Pause Screen
                break;
            }
            case Core::DoremiStates::EXIT:
            {
                std::cout << "You clicked exit its not ver effective state changed back to mainmenu" << std::endl;
                // State is changed with events TODOXX should be removed from here once EXIT is implemented
                Core::ChangeMenuState* menuEvent = new Core::ChangeMenuState();
                menuEvent->state = Core::DoremiStates::MAINMENU;
                Core::EventHandler::GetInstance()->BroadcastEvent(menuEvent);
                break;
            }
            default:
            {
                break;
            }
        }
        TIME_FUNCTION_STOP
    }

    void GameMain::DrawMenu(double p_deltaTime)
    {

        TIME_FUNCTION_START
        MenuHandler* t_menuHandler = MenuHandler::GetInstance();
        MenuGraphicHandler::GetInstance()->DrawButtons(p_deltaTime, t_menuHandler->GetButtons(), t_menuHandler->GetCurrentButton());
        TIME_FUNCTION_STOP
    }

    void GameMain::DrawGame(double p_deltaTime)
    {
        TIME_FUNCTION_START
        size_t length = m_graphicalManagers.size();
        for(size_t i = 0; i < length; i++)
        {
            Doremi::Core::TimerManager::GetInstance().StartTimer(m_managers.at(i)->GetName());
            m_graphicalManagers.at(i)->Update(p_deltaTime);
            Doremi::Core::TimerManager::GetInstance().StopTimer(m_managers.at(i)->GetName());
        }
        TIME_FUNCTION_STOP
    }

    void GameMain::Draw(double p_deltaTime)
    {
        TIME_FUNCTION_START
        /** TODOLH Detta ska flyttas till en function som i updaten*/
        Core::DoremiStates t_state = Core::StateHandler::GetInstance()->GetState();
        m_sharedContext->GetGraphicModule().GetSubModuleManager().GetDirectXManager().BeginDraw();
        switch(t_state)
        {
            case Core::DoremiStates::RUNGAME:
                // Draw Game
                DrawGame(p_deltaTime);
                break;
            default:
                break;
        }
        // WE always draw 2d stuff
        m_screenSpaceDrawer->Draw();
        TIME_FUNCTION_STOP
    }

    void GameMain::Start()
    {
        TIME_FUNCTION_START
        Initialize();
        Run();
        TIME_FUNCTION_STOP
    }

    void GameMain::Stop() { Doremi::Core::TimerManager::GetInstance().DumpData(*m_sharedContext); }
}<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <functional>
#include <exception>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/program_options.hpp>
#include <portaudio.h>
#include <gtk/gtk.h>
using namespace std;
namespace po = boost::program_options;

/* options:
api:
device:
buffer size: in frames
sample rate:
bit depth:
fragment size: in frames
dither:

*/

/* program options */
int sample_rate;
int bit_depth;
int channels;
enum {} api;

/* a frame is, in interleaved pcm audio, a sequence of samples for each channel */
typedef int framecount_t;
framecount_t buffer_size;
framecount_t fragment_size;

typedef int milliseconds_t;
milliseconds_t update_ui_rate;

/* */

int framesize;

std::list<std::string> song_list;

//boost::spsc_queue<char> buffer;

PaStream *stream;

GtkWidget *window;

/* function prototypes */
void init_log(void);
void init_options(void);
void init_gui(void);
void init_portaudio(void);
void enumerate_devices_by_api(int api_idx);

void close_portaudio(void);
void close_log(void);
/* */

int main(int argc, char **argv) {
	init_log();
	gtk_init(&argc, &argv);
	init_options();
	init_gui();
	init_portaudio();

	gtk_main();

	close_portaudio();
	close_log();
	exit(EXIT_SUCCESS);
}

void init_log(void) {
	clog << "\n";
	clog << "ffmpeg version: " << "\n";
	clog << Pa_GetVersionText();
	clog << std::endl;
}

void init_options(void) {
	po::options_description desc("Allowed options");

	desc.add_options()
		("help", "produce help message")
		("sample rate", po::value<int>(), "Set output sample rate")
		("bit depth", po::value<std::string>(), "Set output bit depth")
		("api", po::value<std::string>(), "API to use. It can be alsa, pulseaudio. Empty string uses default.")
		("device", po::value<std::string>(), "Device. It can be alsa, pulseaudio. Empty string uses default.")
;

}

void init_gui(void) {
	GtkBuilder *builder;

	builder = gtk_builder_new();
	gtk_builder_add_from_file(builder, "gui.glade", NULL);
	window = GTK_WIDGET(gtk_builder_get_object(builder, "window1"));
	gtk_builder_connect_signals(builder, NULL);

	g_object_unref(G_OBJECT(builder));

	gtk_widget_show(window);
}

void init_portaudio(void) {
	PaError ret =
	Pa_Initialize();
	if (ret != paNoError) {
		cerr << "Portaudio error: " << Pa_GetErrorText(ret) << "\n";
		exit(EXIT_FAILURE);
	}

	int api_max = Pa_GetHostApiCount();
	if (api_max < 0) { /* if api_max is negative it is actually an error code */
		cerr << "Portaudio error: " << Pa_GetErrorText(api_max) << "\n";
		exit(EXIT_FAILURE);
	}
	if (api_max == 0) {
		cerr << "Error: there is no software for audio output" << "\n";
		exit(EXIT_FAILURE);
	}
	/* container here must be non intrusive, as api_info are internal to portaudio */
	std::vector<const char*> api_names;
	for (int api_idx = 0; api_idx < api_max; api_idx++) {
		const PaHostApiInfo* api_info = Pa_GetHostApiInfo(api_idx);
		api_names.push_back(api_info->name);
	}
	clog << "the system has support for:\n";
		for (auto& an : api_names) clog << " - " << an << "\n";
	for (int api_idx = 0; api_idx < api_max; api_idx++) {
		enumerate_devices_by_api(api_idx);
	}
/*
	PaStreamParameters outputparam;
	outputparam
	ret =
	Pa_OpenStream(&stream, , , (double) sample_rate, paFramesPerBufferUnspecified, , , NULL);
	if (ret != paNoError) {
		cerr << "Portaudio error: " << Pa_GetErrorText(ret) << "\n";
		exit(EXIT_FAILURE);
	}
	clog << "opened device " << "" << "with following parameters:\n";
	clog << " - sample rate: " << sample_rate << " hz." << "\n";
	clog << " - bit depth: " << bit_depth << " bit." << "\n";
	clog << " - channels: " << channels << "." << "\n";
*/
	clog << std::endl;
}

void enumerate_devices_by_api(int api_idx) {
	const PaHostApiInfo* api_info = Pa_GetHostApiInfo(api_idx);
	clog << "detected devices for " << api_info->name << "\n";

	for (int device_idx_api_relative = 0;
	         device_idx_api_relative < api_info->deviceCount;
	         ++device_idx_api_relative)
	{
		int device_idx_absolute = Pa_HostApiDeviceIndexToDeviceIndex(api_idx, device_idx_api_relative);
		const PaDeviceInfo *device_info = Pa_GetDeviceInfo(device_idx_absolute);
		clog << device_idx_api_relative+1 /* count */ << ": " << device_info->name << "\n";
		clog << "default sample rate: " << device_info->defaultSampleRate << " hz\n";
		clog << "number of output channels: " << device_info->maxOutputChannels << "\n";
	}
}

void process(void* out, framecount_t framecount) {

}

void callback(void) {
}

void background(void) {
}

void update_ui(void) {

	//wait(update_ui_rate);
}

void close_portaudio(void) {
	Pa_Terminate();
}

void close_log(void) {
	clog << "bye!" << std::endl;
}
<commit_msg>added (still incomplete) option validation and switching logic<commit_after>#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <functional>
#include <exception>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/program_options.hpp>
#include <portaudio.h>
#include <gtk/gtk.h>
#include <pthread.h>
using namespace std;
namespace po = boost::program_options;

/* options:
api:
device:
buffer size: in frames
sample rate:
bit depth:
fragment size: in frames
dither:

*/

/* program options */
int sample_rate;
int bit_depth;
int channels;
int api_id;

/* a frame is, in interleaved pcm audio, a sequence of samples for each channel */
typedef int framecount_t;
framecount_t buffer_size;
framecount_t fragment_size;

typedef int milliseconds_t;
milliseconds_t update_ui_rate;

/* */

int framesize;

std::list<std::string> song_list;

//boost::spsc_queue<char> buffer;

PaStream *stream;

GtkWidget *window;

/* function prototypes */
void init_log(void);
void init_options(void);
void init_gui(void);
void init_portaudio(void);
void enumerate_devices_by_api(int api_idx);

void close_portaudio(void);
void close_log(void);
/* */

int main(int argc, char **argv) {
	init_log();
	gtk_init(&argc, &argv);
	init_options();
	init_gui();
	init_portaudio();

	gtk_main();

	close_portaudio();
	close_log();
	exit(EXIT_SUCCESS);
}

void init_log(void) {
	clog << "\n";
	clog << "ffmpeg version: " << "\n";
	clog << Pa_GetVersionText();
	clog << std::endl;
}

void init_options(void) {
	po::options_description desc("Allowed options");

	desc.add_options()
		("help", "produce help message")
		("sample rate", po::value<int>(), "Set output sample rate")
		("bit depth", po::value<std::string>(), "Set output bit depth")
		("api", po::value<std::string>(), "API to use. It can be alsa, pulseaudio. Empty string uses default.")
		("device", po::value<std::string>(), "Device. It can be alsa, pulseaudio. Empty string uses default.")
;

	if (sample_rate)

}

void init_gui(void) {
	GtkBuilder *builder;

	builder = gtk_builder_new();
	gtk_builder_add_from_file(builder, "gui.glade", NULL);
	window = GTK_WIDGET(gtk_builder_get_object(builder, "window1"));
	gtk_builder_connect_signals(builder, NULL);

	g_object_unref(G_OBJECT(builder));

	gtk_widget_show(window);
}

void init_portaudio(void) {
	PaError ret =
	Pa_Initialize();
	if (ret != paNoError) {
		cerr << "Portaudio error: " << Pa_GetErrorText(ret) << "\n";
		exit(EXIT_FAILURE);
	}

	int api_max = Pa_GetHostApiCount();
	if (api_max < 0) { /* if api_max is negative it is actually an error code */
		cerr << "Portaudio error: " << Pa_GetErrorText(api_max) << "\n";
		exit(EXIT_FAILURE);
	}
	if (api_max == 0) {
		cerr << "Error: there is no software for audio output" << "\n";
		exit(EXIT_FAILURE);
	}
	std::vector<const char*> api_names;
	std::vector<PaHostApiTypeId> api_ids;
	for (int api_idx = 0; api_idx < api_max; api_idx++) {
		const PaHostApiInfo* api_info = Pa_GetHostApiInfo(api_idx);
		api_names.push_back(api_info->name);
		api_ids.push_back(api_info->typeId);
	}
	clog << "the system has support for:\n";
	for (int api_idx = 0; api_idx < api_max; api_idx++) {
		clog << " - " << api_names[api_idx] << "\n";
	}
	for (int api_idx = 0; api_idx < api_max; api_idx++) {
		enumerate_devices_by_api(api_idx);
	}

	int api = 0;
	if (api_id == 0) {
		api = Pa_GetDefaultHostApi();
		clog << "using default api '" << Pa_GetHostApiInfo(api)->name << "'\n";
	} else { /* check if requested api is in the 'supported by os' list */
		if (auto std::find(api_typeids.begin(), api_typeids.end(), api) == api_typeids.end()) {
			int old_api_idx =  Pa_HostApiTypeIdToHostApiIndex(api);
			const PaHostApiInfo* api_info = Pa_GetHostApiInfo(old_api);
			if (api_info)
			api = Pa_GetDefaultHostApi();
			clog << "warning: requested api '" << "" << "' is not supported by the system. switched to "
			     << Pa_GetHostApiInfo(api)->name << "\n";
		}
	}
	if (device == 0) {
		device = Pa_GetDefaultOutputDevice();
		if (device == paNoDevice) {
			cerr << "portaudio error: no output device\n"
			exit(EXIT_FAILURE);
		}
	}
	if (sample_rate == 0) {
		sample_rate = (int) Pa_GetDeviceInfo(device)->defaultSampleRate;

	}
/*
	PaStreamParameters outputparam;
	outputparam
	ret =
	Pa_OpenStream(&stream, , , (double) sample_rate, paFramesPerBufferUnspecified, , , NULL);
	if (ret != paNoError) {
		cerr << "Portaudio error: " << Pa_GetErrorText(ret) << "\n";
		exit(EXIT_FAILURE);
	}
	clog << "opened device " << "" << "with following parameters:\n";
	clog << " - sample rate: " << sample_rate << " hz." << "\n";
	clog << " - bit depth: " << bit_depth << " bit." << "\n";
	clog << " - channels: " << channels << "." << "\n";
*/
	clog << std::endl;
}

void enumerate_devices_by_api(int api_idx) {
	const PaHostApiInfo* api_info = Pa_GetHostApiInfo(api_idx);
	clog << "detected devices for " << api_info->name << "\n";

	for (int device_idx_api_relative = 0;
	         device_idx_api_relative < api_info->deviceCount;
	         ++device_idx_api_relative)
	{
		int device_idx_absolute = Pa_HostApiDeviceIndexToDeviceIndex(api_idx, device_idx_api_relative);
		const PaDeviceInfo *device_info = Pa_GetDeviceInfo(device_idx_absolute);
		clog << device_idx_api_relative+1 /* count */ << ": " << device_info->name << "\n";
		clog << "default sample rate: " << device_info->defaultSampleRate << " hz\n";
		clog << "number of output channels: " << device_info->maxOutputChannels << "\n";
	}
}

void process(void* out, framecount_t framecount) {

}

void callback(void) {
}

void background(void) {
}

void async(void) {

}

void update_ui(void) {

	//wait(update_ui_rate);
}

void close_portaudio(void) {
	Pa_Terminate();
}

void close_log(void) {
	clog << "bye!" << std::endl;
}
<|endoftext|>


<commit_before>#include "common.h"
#include "store.h"
#include "HdfsSync.h"

#ifdef USE_SCRIBE_HDFS_SYNC
#include "hdfs.h"

using namespace std;
using namespace boost;

const string meta_logfile_prefix = "scribe_meta<new_logfile>: ";

HdfsSync::HdfsSync(const string& category, bool multi_category,
                     bool is_buffer_file)
  : FileStore(category,multi_category,is_buffer_file),
  hdfsHost(""),hdfsPort(0),hdfsPath("/"),hdfs_base_filename(""),hdfs_base_directory("")
{

}

HdfsSync::~HdfsSync()
{

}

void HdfsSync::configure(pStoreConf configuration) {

  FileStore::configure(configuration);

  // Hdfs Sync doesn't use chunk file
  rollPeriod = ROLL_NEVER;
  chunkSize = 0;

  unsigned long inttemp = 0;
  configuration->getUnsigned("add_newlines", inttemp);
  addNewlines = inttemp ? true : false;

  lastSyncTime = time (NULL);

  configuration->getUnsigned("period_length", periodLength);

  configuration->getString("hdfs_dir", hdfsDir);
  if(configuration->getString("hdfs_base_filename", hdfs_base_filename)) {
    hdfs_base_filename.append("_");
  }
  if(configuration->getString("hdfs_base_directory", hdfs_base_directory)) {
    hdfs_base_directory.append("/");
  }

  // Parse HDFS information
  char* hostport = (char *)malloc(hdfsDir.length()+1);
  char* buf;
  char* portStr;
  char* host;

  int ret = 0;

  ret = sscanf(hdfsDir.c_str(), "hdfs://%s", hostport);
  host = strtok_r(hostport, ":", &buf);
  portStr = strtok_r(NULL, "/", &buf);

  ret = sscanf(portStr, "%d", &hdfsPort);
  hdfsHost.append(host);
  hdfsPath.append(buf);
  free(hostport);
}

bool HdfsSync::openInternal(bool incrementFilename, struct tm* current_time) {
  bool success = false;
    LOG_OPER("OPEN INTERNAL");
  if (!current_time) {
    time_t rawtime;
    time(&rawtime);
    current_time = localtime(&rawtime);
  }

  try {
    int suffix = findNewestFile(makeBaseFilename(current_time));

    if (incrementFilename) {
      ++suffix;
    }

    // this is the case where there's no file there and we're not incrementing
    if (suffix < 0) {
      suffix = 0;
    }

    string file = makeFullFilename(suffix, current_time);

    if (rollPeriod == ROLL_DAILY) {
      lastRollTime = current_time->tm_mday;
    } else {  // default to hourly if rollPeriod is garbage
      lastRollTime = current_time->tm_hour;
    }

    bool sync = false;
    string fullFilename;
    string baseFilename;

    if (writeFile) {
      if (writeMeta) {
        writeFile->write(meta_logfile_prefix + file);
      }

      if(writeFile->fileSize())
        sync = true;

      fullFilename = writeFile->getFileName();
      baseFilename = fullFilename;
      int found = fullFilename.find_last_of("/");
      if (found != string::npos)
      {
        baseFilename = fullFilename.substr(found+1);
      }

      writeFile->close();
    }

    writeFile = FileInterface::createFileInterface(fsType, file, isBufferFile);
    if (!writeFile) {
      LOG_OPER("[%s] Failed to create file <%s> of type <%s> for writing",
               categoryHandled.c_str(), file.c_str(), fsType.c_str());
      setStatus("file open error");
      return false;
    }

    success = writeFile->openWrite();

    if (!success) {
      LOG_OPER("[%s] Failed to open file <%s> for writing", categoryHandled.c_str(), file.c_str());
      setStatus("File open error");
    } else {

      /* just make a best effort here, and don't error if it fails */
      if (createSymlink && !isBufferFile) {
        string symlinkName = makeFullSymlink();
        unlink(symlinkName.c_str());
        symlink(file.c_str(), symlinkName.c_str());
      }
      // else it confuses the filename code on reads

      LOG_OPER("[%s] Opened file <%s> for writing", categoryHandled.c_str(), file.c_str());

      currentSize = writeFile->fileSize();
      currentFilename = file;
      eventsWritten = 0;
      setStatus("");

      // copy last file to hdfs server
      if (sync)
      {
          hdfsFS fs = hdfsConnect(hdfsHost.c_str(), hdfsPort);
          if (NULL == fs )
          {
              LOG_OPER("Cannot connect to hdfs://%s:%d",hdfsHost.c_str(), hdfsPort);
          }
          else
          {
              string writePath = hdfsPath + "/" + categoryHandled.c_str() + "/" + hdfs_base_directory.c_str() + hdfs_base_filename.c_str() + baseFilename;
              hdfsFile dstFile = hdfsOpenFile(fs, writePath.c_str(), O_WRONLY, 0, 0, 0);
              if (NULL == dstFile)
              {
                  LOG_OPER("Cannot open file to write : %s",writePath.c_str());
              }
              else
              {
                  char buffer[1024];
                  ifstream file_in(fullFilename.c_str(), ios::in | ios::binary);
                  while (!file_in.eof())
                  {
                    file_in.read(buffer, 1024);
                    tSize num_written_bytes = hdfsWrite(fs, dstFile, (void*)buffer, file_in.gcount());
                  }
                  file_in.close();
                  hdfsCloseFile(fs, dstFile);
                  LOG_OPER("Copied to HDFS hdfs://%s:%d/%s",hdfsHost.c_str(),hdfsPort,writePath.c_str());
                  deleteOldest(current_time);
                  LOG_OPER("[%s] Removing local file <%s> - sync complete", categoryHandled.c_str(), file.c_str());
              }
          }
      }

    }

  } catch(std::exception const& e) {
    LOG_OPER("ERRORR :(");
    /*LOG_OPER("[%s] Failed to create/open file of type <%s> for writing",
             categoryHandled.c_str(), fsType.c_str());
    LOG_OPER("Exception: %s", e.what());
    setStatus("file create/open error");
    */
    return false;
  }
  return success;
}

void HdfsSync::periodicCheck() {

  time_t currentTime;
  time(&currentTime);

  if (!lastSyncTime)
  {
    lastSyncTime = currentTime;
  }

  if ((currentTime - lastSyncTime) / 60 >= periodLength)
  {
    struct tm *timeinfo;
    timeinfo = localtime(&currentTime);
    rotateFile(timeinfo);
    lastSyncTime = currentTime;
  }
}

boost::shared_ptr<Store> HdfsSync::copy(const std::string &category) {
  HdfsSync *store = new HdfsSync(category, multiCategory, isBufferFile);
  shared_ptr<Store> copied = shared_ptr<Store>(store);

  store->addNewlines = addNewlines;
  store->periodLength = periodLength;
  store->hdfsHost = hdfsHost;
  store->hdfsPort = hdfsPort;
  store->hdfsPath = hdfsPath;
  store->hdfs_base_filename = hdfs_base_filename;
  store->hdfs_base_directory = hdfs_base_directory;
  store->copyCommon(this);
  return copied;
}

#endif // USE_SCRIBE_HDFS_SYNC

<commit_msg>Reverted commenting out the error exception line<commit_after>#include "common.h"
#include "store.h"
#include "HdfsSync.h"

#ifdef USE_SCRIBE_HDFS_SYNC
#include "hdfs.h"

using namespace std;
using namespace boost;

const string meta_logfile_prefix = "scribe_meta<new_logfile>: ";

HdfsSync::HdfsSync(const string& category, bool multi_category,
                     bool is_buffer_file)
  : FileStore(category,multi_category,is_buffer_file),
  hdfsHost(""),hdfsPort(0),hdfsPath("/"),hdfs_base_filename(""),hdfs_base_directory("")
{

}

HdfsSync::~HdfsSync()
{

}

void HdfsSync::configure(pStoreConf configuration) {

  FileStore::configure(configuration);

  // Hdfs Sync doesn't use chunk file
  rollPeriod = ROLL_NEVER;
  chunkSize = 0;

  unsigned long inttemp = 0;
  configuration->getUnsigned("add_newlines", inttemp);
  addNewlines = inttemp ? true : false;

  lastSyncTime = time (NULL);

  configuration->getUnsigned("period_length", periodLength);

  configuration->getString("hdfs_dir", hdfsDir);
  if(configuration->getString("hdfs_base_filename", hdfs_base_filename)) {
    hdfs_base_filename.append("_");
  }
  if(configuration->getString("hdfs_base_directory", hdfs_base_directory)) {
    hdfs_base_directory.append("/");
  }

  // Parse HDFS information
  char* hostport = (char *)malloc(hdfsDir.length()+1);
  char* buf;
  char* portStr;
  char* host;

  int ret = 0;

  ret = sscanf(hdfsDir.c_str(), "hdfs://%s", hostport);
  host = strtok_r(hostport, ":", &buf);
  portStr = strtok_r(NULL, "/", &buf);

  ret = sscanf(portStr, "%d", &hdfsPort);
  hdfsHost.append(host);
  hdfsPath.append(buf);
  free(hostport);
}

bool HdfsSync::openInternal(bool incrementFilename, struct tm* current_time) {
  bool success = false;
    LOG_OPER("OPEN INTERNAL");
  if (!current_time) {
    time_t rawtime;
    time(&rawtime);
    current_time = localtime(&rawtime);
  }

  try {
    int suffix = findNewestFile(makeBaseFilename(current_time));

    if (incrementFilename) {
      ++suffix;
    }

    // this is the case where there's no file there and we're not incrementing
    if (suffix < 0) {
      suffix = 0;
    }

    string file = makeFullFilename(suffix, current_time);

    if (rollPeriod == ROLL_DAILY) {
      lastRollTime = current_time->tm_mday;
    } else {  // default to hourly if rollPeriod is garbage
      lastRollTime = current_time->tm_hour;
    }

    bool sync = false;
    string fullFilename;
    string baseFilename;

    if (writeFile) {
      if (writeMeta) {
        writeFile->write(meta_logfile_prefix + file);
      }

      if(writeFile->fileSize())
        sync = true;

      fullFilename = writeFile->getFileName();
      baseFilename = fullFilename;
      int found = fullFilename.find_last_of("/");
      if (found != string::npos)
      {
        baseFilename = fullFilename.substr(found+1);
      }

      writeFile->close();
    }

    writeFile = FileInterface::createFileInterface(fsType, file, isBufferFile);
    if (!writeFile) {
      LOG_OPER("[%s] Failed to create file <%s> of type <%s> for writing",
               categoryHandled.c_str(), file.c_str(), fsType.c_str());
      setStatus("file open error");
      return false;
    }

    success = writeFile->openWrite();

    if (!success) {
      LOG_OPER("[%s] Failed to open file <%s> for writing", categoryHandled.c_str(), file.c_str());
      setStatus("File open error");
    } else {

      /* just make a best effort here, and don't error if it fails */
      if (createSymlink && !isBufferFile) {
        string symlinkName = makeFullSymlink();
        unlink(symlinkName.c_str());
        symlink(file.c_str(), symlinkName.c_str());
      }
      // else it confuses the filename code on reads

      LOG_OPER("[%s] Opened file <%s> for writing", categoryHandled.c_str(), file.c_str());

      currentSize = writeFile->fileSize();
      currentFilename = file;
      eventsWritten = 0;
      setStatus("");

      // copy last file to hdfs server
      if (sync)
      {
          hdfsFS fs = hdfsConnect(hdfsHost.c_str(), hdfsPort);
          if (NULL == fs )
          {
              LOG_OPER("Cannot connect to hdfs://%s:%d",hdfsHost.c_str(), hdfsPort);
          }
          else
          {
              string writePath = hdfsPath + "/" + categoryHandled.c_str() + "/" + hdfs_base_directory.c_str() + hdfs_base_filename.c_str() + baseFilename;
              hdfsFile dstFile = hdfsOpenFile(fs, writePath.c_str(), O_WRONLY, 0, 0, 0);
              if (NULL == dstFile)
              {
                  LOG_OPER("Cannot open file to write : %s",writePath.c_str());
              }
              else
              {
                  char buffer[1024];
                  ifstream file_in(fullFilename.c_str(), ios::in | ios::binary);
                  while (!file_in.eof())
                  {
                    file_in.read(buffer, 1024);
                    tSize num_written_bytes = hdfsWrite(fs, dstFile, (void*)buffer, file_in.gcount());
                  }
                  file_in.close();
                  hdfsCloseFile(fs, dstFile);
                  LOG_OPER("Copied to HDFS hdfs://%s:%d/%s",hdfsHost.c_str(),hdfsPort,writePath.c_str());
                  deleteOldest(current_time);
                  LOG_OPER("[%s] Removing local file <%s> - sync complete", categoryHandled.c_str(), file.c_str());
              }
          }
      }

    }

  } catch(std::exception const& e) {
    LOG_OPER("[%s] Failed to create/open file of type <%s> for writing",
             categoryHandled.c_str(), fsType.c_str());
    LOG_OPER("Exception: %s", e.what());
    setStatus("file create/open error");

    return false;
  }
  return success;
}

void HdfsSync::periodicCheck() {

  time_t currentTime;
  time(&currentTime);

  if (!lastSyncTime)
  {
    lastSyncTime = currentTime;
  }

  if ((currentTime - lastSyncTime) / 60 >= periodLength)
  {
    struct tm *timeinfo;
    timeinfo = localtime(&currentTime);
    rotateFile(timeinfo);
    lastSyncTime = currentTime;
  }
}

boost::shared_ptr<Store> HdfsSync::copy(const std::string &category) {
  HdfsSync *store = new HdfsSync(category, multiCategory, isBufferFile);
  shared_ptr<Store> copied = shared_ptr<Store>(store);

  store->addNewlines = addNewlines;
  store->periodLength = periodLength;
  store->hdfsHost = hdfsHost;
  store->hdfsPort = hdfsPort;
  store->hdfsPath = hdfsPath;
  store->hdfs_base_filename = hdfs_base_filename;
  store->hdfs_base_directory = hdfs_base_directory;
  store->copyCommon(this);
  return copied;
}

#endif // USE_SCRIBE_HDFS_SYNC

<|endoftext|>


<commit_before>#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <iterator>
#include <vector>

struct node {
    bool m_is_free;
    unsigned int m_offset;
    unsigned int m_size;
};

struct memory_manager {
    const std::vector<char> m_buffer;
    std::vector<node> m_list;
};

void show_nodes(const memory_manager& m) {
    std::cout << "[" << std::dec;
    for (auto n : m.m_list) {
        std::cout << "(" << n.m_is_free << "," << n.m_offset << "," << n.m_size << ")";
    }
    std::cout << "]\n";
}

void show_hexa(const memory_manager& m) {
    for (auto n : m.m_buffer) {
        std::cout << std::hex << "[" << static_cast<short>(n) << "]";
    }
    std::cout << "\n";
}

memory_manager initmem(unsigned int max_size) {
    // Initialise les structures de données du gestionnaire.

    return memory_manager{
            std::vector<char>(max_size),
            std::vector<node>{
                node{true, 0, max_size}
            }
        };
}

struct first_fit {
    template<class InputIterator>
    InputIterator operator()(InputIterator first, InputIterator last, unsigned int size) {
        return std::find_if(
            first,
            last,
            [size](node n) { return n.m_is_free && n.m_size >= size; });
    }
};

struct best_fit {
    template<class ForwardIterator>
    ForwardIterator operator()(ForwardIterator first, ForwardIterator last, unsigned int size) {
        ForwardIterator min = last;

        while (first != last) {
            if (first->m_is_free && first->m_size >= size) {
                if (min == last || first->m_size < min->m_size) {
                    min = first;
                }
            }
            ++first;
        }

        return min;
    }
};

struct worst_fit {
    template<class ForwardIterator>
    ForwardIterator operator()(ForwardIterator first, ForwardIterator last, unsigned int size) {
        ForwardIterator max = last;

        while (first != last) {
            if (first->m_is_free && first->m_size >= size) {
                if (max == last || first->m_size > max->m_size) {
                    max = first;
                }
            }
            ++first;
        }

        return max;
    }
};

struct next_fit {
    node last_node = node{false, 0, 0};

    template<class ForwardIterator>
    ForwardIterator operator()(ForwardIterator first, ForwardIterator last, unsigned int size) {
        auto it = std::find(first, last, last_node);

        auto it2 = first_fit()(it, last, size);
        if (it2 != last) {
            last_node = *it2;
            return it2;
        } else {
            auto it3 = first_fit()(first, it, size);
            if (it3 != it) {
                last_node = it3
            }
            return it3;
        }
    }
};

template<class Strategy>
void* alloumem(memory_manager& m, Strategy s, unsigned int size, int fill = 0) {
    // Cette fonction alloue un nouveau bloc de mémoire.

    // alloumem [(false,0,1024), (true,1024,1024), (false,2048,1024)] 512
    //          [(false,0,1024), (false,1024,512), (true,1536,512), (false,2048,1024)]

    auto it = s(std::begin(m.m_list), std::end(m.m_list), size);

    if (it != std::end(m.m_list)) {
        it->m_is_free = false;

        if (it->m_size != size) {
            auto old_size = it->m_size;
            it->m_size = size;
            m.m_list.insert(std::next(it), node{true, it->m_offset + size, old_size - size});
        }

        auto ptr = reinterpret_cast<void*>(const_cast<char*>(m.m_buffer.data() + it->m_offset));
        std::memset(ptr, fill, size);

        return ptr;
    } else {
        return nullptr;
    }
}

void liberemem(memory_manager& m, void* buffer, int fill = 0) {
    // Cette fonction libère un bloc de mémoire similaire à free().

    // liberemem [(false,0,1024), (false,1024,512), (true,1536,512), (false,2048,1024)]
    //           [(false,0,1024), (true,1024,1024), (false,2048,1024)]
    auto buffer_offset = reinterpret_cast<const char*>(buffer) - m.m_buffer.data();

    auto it = std::find_if(
        std::begin(m.m_list),
        std::end(m.m_list),
        [buffer_offset](node n){ return !n.m_is_free && n.m_offset == buffer_offset; });

    if (it != std::end(m.m_list)) {
        // Free the node
        it->m_is_free = true;

        // Merge with the prev and next nodes
        auto first = it->m_offset != 0 && std::prev(it)->m_is_free
            ? std::prev(it)
            : it;
        auto offset = first->m_offset;
        unsigned int size = 0;

        while (first != std::end(m.m_list) && first->m_is_free) {
            size += first->m_size;
            first = m.m_list.erase(first);
        }

        m.m_list.insert(first, node{true, offset, size});

        // Fill the memory with request value
        auto ptr = reinterpret_cast<void*>(const_cast<char*>(m.m_buffer.data() + offset));
        std::memset(ptr, fill, size);
    }
}

unsigned int nbloclibres(const memory_manager& m) {
    // Cette fonction retourne le nombre de blocs de mémoire libres
    return std::count_if(
            std::begin(m.m_list),
            std::end(m.m_list),
            [](const node& n) { return n.m_is_free; });
}

unsigned int nblocalloues(const memory_manager& m) {
    // Cette fonction retourne le nombre de blocs alloués présentement
    return m.m_list.size();
}

unsigned int memlibre(const memory_manager& m) {
    // Combien de mémoire libre (non allouée) au total.

    unsigned int sum = 0;

    for (auto n : m.m_list) {
        if (n.m_is_free) {
            sum += n.m_size;
        }
    }

    return sum;
}

unsigned int mem_pgrand_libre(const memory_manager& m) {
    // Taille du plus grand bloc libre.

    unsigned int max = 0;

    for (auto n : m.m_list) {
        if (n.m_is_free && n.m_size > max) {
            max = n.m_size;
        }
    }

    return max;
}

unsigned int mem_small_free(const memory_manager& m, unsigned int maxTaillePetit) {
    // Combien de petits blocs (plus petits que maxTaillePetit) non alloués y a-t-il présentement en mémoire?
    return std::count_if(
            std::begin(m.m_list),
            std::end(m.m_list),
            [maxTaillePetit](const node& n) { return n.m_is_free && n.m_size < maxTaillePetit; });
}

bool mem_est_alloue(const memory_manager& m, void* pOctet) {
    // Est-ce qu’un octet (byte) particulier est alloué

    for (auto n : m.m_list) {
        auto a = m.m_buffer.data() + n.m_offset;
        auto b = a + n.m_size;
        if (a <= pOctet && pOctet <= b) {
            return !n.m_is_free;
        }
    }

    return false;
}

int main() {
    auto manager = initmem(16);
    auto first_fit_strategy = first_fit{};
    auto best_fit_strategy = best_fit{};
    auto worst_fit_strategy = worst_fit{};
    auto next_fit_strategy = next_fit{};

    assert(16 == mem_pgrand_libre(manager));
    assert(16 == memlibre(manager));
    assert(1 == nblocalloues(manager));
    assert(1 == nbloclibres(manager));
    assert(0 == mem_small_free(manager, 8));
    assert(1 == mem_small_free(manager, 32));

    auto ptr1 = alloumem(manager, first_fit_strategy, 5);
    auto ptr2 = alloumem(manager, first_fit_strategy, 4);
    auto ptr3 = alloumem(manager, first_fit_strategy, 3);
    auto ptr4 = alloumem(manager, first_fit_strategy, 2);
    show_nodes(manager);

    assert(2 == mem_pgrand_libre(manager));
    assert(2 == memlibre(manager));
    assert(5 == nblocalloues(manager));
    assert(1 == nbloclibres(manager));
    assert(1 == mem_small_free(manager, 8));
    assert(1 == mem_small_free(manager, 32));
    assert(true == mem_est_alloue(manager, ptr1));

    liberemem(manager, ptr1);
    liberemem(manager, ptr3);

    show_nodes(manager);
    assert(10 == memlibre(manager));
    assert(5 == nblocalloues(manager));
    assert(3 == nbloclibres(manager));
    assert(3 == mem_small_free(manager, 8));
    assert(3 == mem_small_free(manager, 32));
    assert(false == mem_est_alloue(manager, ptr1));

    liberemem(manager, ptr2);

    show_nodes(manager);
    assert(12 == mem_pgrand_libre(manager));
    assert(14 == memlibre(manager));
    assert(3 == nblocalloues(manager));
    assert(2 == nbloclibres(manager));
    assert(1 == mem_small_free(manager, 8));
    assert(2 == mem_small_free(manager, 32));
}
<commit_msg>Ajout de cas de test pour l'algorithme bestfit et correction d'un bug de synthaxe<commit_after>#include <algorithm>
#include <cassert>
#include <cstring>
#include <iostream>
#include <iterator>
#include <vector>

struct node {
    bool m_is_free;
    unsigned int m_offset;
    unsigned int m_size;
};

struct memory_manager {
    const std::vector<char> m_buffer;
    std::vector<node> m_list;
};

void show_nodes(const memory_manager& m) {
    std::cout << "[" << std::dec;
    for (auto n : m.m_list) {
        std::cout << "(" << n.m_is_free << "," << n.m_offset << "," << n.m_size << ")";
    }
    std::cout << "]\n";
}

void show_hexa(const memory_manager& m) {
    for (auto n : m.m_buffer) {
        std::cout << std::hex << "[" << static_cast<short>(n) << "]";
    }
    std::cout << "\n";
}

memory_manager initmem(unsigned int max_size) {
    // Initialise les structures de données du gestionnaire.

    return memory_manager{
            std::vector<char>(max_size),
            std::vector<node>{
                node{true, 0, max_size}
            }
        };
}

struct first_fit {
    template<class InputIterator>
    InputIterator operator()(InputIterator first, InputIterator last, unsigned int size) {
        return std::find_if(
            first,
            last,
            [size](node n) { return n.m_is_free && n.m_size >= size; });
    }
};

struct best_fit {
    template<class ForwardIterator>
    ForwardIterator operator()(ForwardIterator first, ForwardIterator last, unsigned int size) {
        ForwardIterator min = last;

        while (first != last) {
            if (first->m_is_free && first->m_size >= size) {
                if (min == last || first->m_size < min->m_size) {
                    min = first;
                }
            }
            ++first;
        }

        return min;
    }
};

struct worst_fit {
    template<class ForwardIterator>
    ForwardIterator operator()(ForwardIterator first, ForwardIterator last, unsigned int size) {
        ForwardIterator max = last;

        while (first != last) {
            if (first->m_is_free && first->m_size >= size) {
                if (max == last || first->m_size > max->m_size) {
                    max = first;
                }
            }
            ++first;
        }

        return max;
    }
};

struct next_fit {
    node last_node = node{false, 0, 0};

    template<class ForwardIterator>
    ForwardIterator operator()(ForwardIterator first, ForwardIterator last, unsigned int size) {
        auto it = std::find(first, last, last_node);

        auto it2 = first_fit()(it, last, size);
        if (it2 != last) {
            last_node = *it2;
            return it2;
        } else {
            auto it3 = first_fit()(first, it, size);
            if (it3 != it) {
                last_node = it3;
            }
            return it3;
        }
    }
};

template<class Strategy>
void* alloumem(memory_manager& m, Strategy s, unsigned int size, int fill = 0) {
    // Cette fonction alloue un nouveau bloc de mémoire.

    // alloumem [(false,0,1024), (true,1024,1024), (false,2048,1024)] 512
    //          [(false,0,1024), (false,1024,512), (true,1536,512), (false,2048,1024)]

    auto it = s(std::begin(m.m_list), std::end(m.m_list), size);

    if (it != std::end(m.m_list)) {
        it->m_is_free = false;

        if (it->m_size != size) {
            auto old_size = it->m_size;
            it->m_size = size;
            m.m_list.insert(std::next(it), node{true, it->m_offset + size, old_size - size});
        }

        auto ptr = reinterpret_cast<void*>(const_cast<char*>(m.m_buffer.data() + it->m_offset));
        std::memset(ptr, fill, size);

        return ptr;
    } else {
        return nullptr;
    }
}

void liberemem(memory_manager& m, void* buffer, int fill = 0) {
    // Cette fonction libère un bloc de mémoire similaire à free().

    // liberemem [(false,0,1024), (false,1024,512), (true,1536,512), (false,2048,1024)]
    //           [(false,0,1024), (true,1024,1024), (false,2048,1024)]
    auto buffer_offset = reinterpret_cast<const char*>(buffer) - m.m_buffer.data();

    auto it = std::find_if(
        std::begin(m.m_list),
        std::end(m.m_list),
        [buffer_offset](node n){ return !n.m_is_free && n.m_offset == buffer_offset; });

    if (it != std::end(m.m_list)) {
        // Free the node
        it->m_is_free = true;

        // Merge with the prev and next nodes
        auto first = it->m_offset != 0 && std::prev(it)->m_is_free
            ? std::prev(it)
            : it;
        auto offset = first->m_offset;
        unsigned int size = 0;

        while (first != std::end(m.m_list) && first->m_is_free) {
            size += first->m_size;
            first = m.m_list.erase(first);
        }

        m.m_list.insert(first, node{true, offset, size});

        // Fill the memory with request value
        auto ptr = reinterpret_cast<void*>(const_cast<char*>(m.m_buffer.data() + offset));
        std::memset(ptr, fill, size);
    }
}

unsigned int nbloclibres(const memory_manager& m) {
    // Cette fonction retourne le nombre de blocs de mémoire libres
    return std::count_if(
            std::begin(m.m_list),
            std::end(m.m_list),
            [](const node& n) { return n.m_is_free; });
}

unsigned int nblocalloues(const memory_manager& m) {
    // Cette fonction retourne le nombre de blocs alloués présentement
    return m.m_list.size();
}

unsigned int memlibre(const memory_manager& m) {
    // Combien de mémoire libre (non allouée) au total.

    unsigned int sum = 0;

    for (auto n : m.m_list) {
        if (n.m_is_free) {
            sum += n.m_size;
        }
    }

    return sum;
}

unsigned int mem_pgrand_libre(const memory_manager& m) {
    // Taille du plus grand bloc libre.

    unsigned int max = 0;

    for (auto n : m.m_list) {
        if (n.m_is_free && n.m_size > max) {
            max = n.m_size;
        }
    }

    return max;
}

unsigned int mem_small_free(const memory_manager& m, unsigned int maxTaillePetit) {
    // Combien de petits blocs (plus petits que maxTaillePetit) non alloués y a-t-il présentement en mémoire?
    return std::count_if(
            std::begin(m.m_list),
            std::end(m.m_list),
            [maxTaillePetit](const node& n) { return n.m_is_free && n.m_size < maxTaillePetit; });
}

bool mem_est_alloue(const memory_manager& m, void* pOctet) {
    // Est-ce qu’un octet (byte) particulier est alloué

    for (auto n : m.m_list) {
        auto a = m.m_buffer.data() + n.m_offset;
        auto b = a + n.m_size;
        if (a <= pOctet && pOctet <= b) {
            return !n.m_is_free;
        }
    }

    return false;
}

int main() {
    auto managerFF = initmem(16);
    auto first_fit_strategy = first_fit{};
    auto best_fit_strategy = best_fit{};
    auto worst_fit_strategy = worst_fit{};
    auto next_fit_strategy = next_fit{};

    assert(16 == mem_pgrand_libre(managerFF));
    assert(16 == memlibre(managerFF));
    assert(1 == nblocalloues(managerFF));
    assert(1 == nbloclibres(managerFF));
    assert(0 == mem_small_free(managerFF, 8));
    assert(1 == mem_small_free(managerFF, 32));

    auto ptr1 = alloumem(managerFF, first_fit_strategy, 5);
    auto ptr2 = alloumem(managerFF, first_fit_strategy, 4);
    auto ptr3 = alloumem(managerFF, first_fit_strategy, 3);
    auto ptr4 = alloumem(managerFF, first_fit_strategy, 2);

    std::cout << "first fit sequence" << std::endl;
    show_nodes(managerFF);

    assert(2 == mem_pgrand_libre(managerFF));
    assert(2 == memlibre(managerFF));
    assert(5 == nblocalloues(managerFF));
    assert(1 == nbloclibres(managerFF));
    assert(1 == mem_small_free(managerFF, 8));
    assert(1 == mem_small_free(managerFF, 32));
    assert(true == mem_est_alloue(managerFF, ptr1));
    assert(true == mem_est_alloue(managerFF, ptr2));
    assert(true == mem_est_alloue(managerFF, ptr3));
    assert(true == mem_est_alloue(managerFF, ptr4));

    liberemem(managerFF, ptr1);
    liberemem(managerFF, ptr3);

    show_nodes(managerFF);
    assert(10 == memlibre(managerFF));
    assert(5 == nblocalloues(managerFF));
    assert(3 == nbloclibres(managerFF));
    assert(3 == mem_small_free(managerFF, 8));
    assert(3 == mem_small_free(managerFF, 32));
    assert(false == mem_est_alloue(managerFF, ptr1));
    //assert(true == mem_est_alloue(managerFF, ptr2));
    //assert(false == mem_est_alloue(managerFF, ptr3));
    //assert(true == mem_est_alloue(managerFF, ptr4));

    liberemem(managerFF, ptr2);

    show_nodes(managerFF);
    assert(12 == mem_pgrand_libre(managerFF));
    assert(14 == memlibre(managerFF));
    assert(3 == nblocalloues(managerFF));
    assert(2 == nbloclibres(managerFF));
    assert(1 == mem_small_free(managerFF, 8));
    assert(2 == mem_small_free(managerFF, 32));
    assert(false == mem_est_alloue(managerFF, ptr1));
    assert(false == mem_est_alloue(managerFF, ptr2));
    assert(false == mem_est_alloue(managerFF, ptr3));
    //assert(true == mem_est_alloue(managerFF, ptr4));

    //best fit
    std::cout << "best fit sequence" << std::endl;
    auto managerBF = initmem(16);
    ptr1 = alloumem(managerBF, best_fit_strategy, 5);
    ptr2 = alloumem(managerBF, best_fit_strategy, 4);
    ptr3 = alloumem(managerBF, best_fit_strategy, 3);
    ptr4 = alloumem(managerBF, best_fit_strategy, 2);
    show_nodes(managerBF);

    assert(2 == mem_pgrand_libre(managerBF));
    assert(2 == memlibre(managerBF));
    assert(5 == nblocalloues(managerBF));
    assert(1 == nbloclibres(managerBF));
    assert(1 == mem_small_free(managerBF, 8));
    assert(1 == mem_small_free(managerBF, 32));
    assert(true == mem_est_alloue(managerBF, ptr1));
    assert(true == mem_est_alloue(managerBF, ptr2));
    assert(true == mem_est_alloue(managerBF, ptr3));
    assert(true == mem_est_alloue(managerBF, ptr4));

    liberemem(managerBF, ptr1);
    liberemem(managerBF, ptr3);

    show_nodes(managerBF);
    assert(10 == memlibre(managerBF));
    assert(5 == nblocalloues(managerBF));
    assert(3 == nbloclibres(managerBF));
    assert(3 == mem_small_free(managerBF, 8));
    assert(3 == mem_small_free(managerBF, 32));
    assert(false == mem_est_alloue(managerBF, ptr1));
    //assert(true == mem_est_alloue(managerBF, ptr2));
    //assert(false == mem_est_alloue(managerBF, ptr3));
    //assert(true == mem_est_alloue(managerBF, ptr4));

    liberemem(managerBF, ptr2);
    assert(false == mem_est_alloue(managerBF, ptr2));

    show_nodes(managerBF);
    assert(12 == mem_pgrand_libre(managerBF));
    assert(14 == memlibre(managerBF));
    assert(3 == nblocalloues(managerBF));
    assert(2 == nbloclibres(managerBF));
    assert(1 == mem_small_free(managerBF, 8));
    assert(2 == mem_small_free(managerBF, 32));
    auto ptr5 = alloumem(managerBF, best_fit_strategy, 2);
    show_nodes(managerBF);

}
<|endoftext|>


<commit_before>73fdf9ba-4b02-11e5-9d96-28cfe9171a43<commit_msg>updated some files<commit_after>74095863-4b02-11e5-8013-28cfe9171a43<|endoftext|>


<commit_before>#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <floppy.h>
#include <vector>
#include <math.h>
using namespace std;

double queuedMilliseconds,prev0,fps,responseTime;
int resX,resY,movementX,startFlag;
double movementY;

//... Reshaping settings & rendering parameters.
void reshape(int w, int h)
{

   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glViewport(0, 0, (GLsizei) w, (GLsizei) h);
   glOrtho(0,resX,0,resY,-5,10);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
}

//....  Keyboard input and movement physics
vector<char> inputKey;
double g,v,tmp2;
int cnt;

void gameoverAnimation()
{
	inputKey.push_back('U');
	v=1.2;

}

void movePhysics()
{
int ii;
g=10;
for(ii=0;ii<inputKey.size();ii++)
	{

		if(inputKey[ii]=='U')
			{
				if((movementY+(resY/2)+50)<resY)
				movementY+=4;
				cnt++;
			}
		if(cnt>=10)
			{
				cnt=0;
				inputKey.erase(inputKey.begin()+ii);
			}

	}
if(startFlag==1)
{

//...GRAVITY
if(inputKey.size()==0)
{
// 0.021125
if(gameover==0)
{
tmp2=resY/2;
v=0.65+(abs(movementY)/tmp2)/5;
}
else
{

	if( (inputKey.size()==0 ) && (movementY <- (resY/2) ) )
	{
		gameover=0;
		resetFunc();
	}
}
movementY-= v*v/2*g;

}

}

}

void keyboard (unsigned char key, int x, int y)
{
  startFlag=1;
   switch (key) {
      case 27:
         exit(0);
         break;
 	  case 32:
 	  	if(gameover==0)
		inputKey.push_back('U');
		break;

   }
}

//... keyboard input end.

int main(int argc, char** argv)
{
   //..frame-update setup
   queuedMilliseconds=0;
   prev0=0;
   fps=60;
   responseTime=(1/fps)*1000;

//... Rendering resoultion
   resX=854;resY=480;

   glutInit(&argc, argv);
   glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutGameModeString("10x10");
   display_test:
   if (glutGameModeGet(GLUT_GAME_MODE_POSSIBLE))
    glutEnterGameMode();
   else {
   	 printf("Select Screen Resolution, if you are unsure select Window mode\n"
   	 		"1. 1920x1080\n2. 1600x900\n3. 1280x720\n4. 1368x768 \n"
   	 		"5. 1366x768 \n6. 800x600\n7. 640x480\n8. Window(try to avoid this!)");
   	 int ch;
   	 scanf("%d",&ch);

   	 if(ch==8)
   	 {
     printf("\n*WARNING: The selected resolution not available, "
    	"Enter xrandr in terminal.\nChange parameter in glutGameModeString to available resolution in xrandr.\n"
    	"Currently running in windowmode.\nVsync may not perform correctly resulting in poor performance.\n");
     glutInitWindowSize(1280, 720);
     glutCreateWindow("Floppy Bird");
     glutFullScreen();
     }
    else if(ch==1)
    	glutGameModeString("1920x1080");
    else if(ch==2)
    	glutGameModeString("1600x900");
    else if(ch==3)
    	glutGameModeString("1280x720");
    else if(ch==4)
    	glutGameModeString("1368x768");
    else if(ch==5)
   		glutGameModeString("1366x768");
    else if(ch==6)
    	glutGameModeString("800x600");
    else
    	glutGameModeString("640x480");

    if(ch!=8)
    	goto display_test;
    	}
   glutIgnoreKeyRepeat(1);
   glutDisplayFunc(draw);
   glutIdleFunc(mixedStepLoop);
   glutReshapeFunc(reshape);
   glutKeyboardFunc(keyboard);
   glutMainLoop();
   return 0;
}
<commit_msg>added math.h header<commit_after>#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <floppy.h>
#include <vector>
#include <math.h>

using namespace std;

double queuedMilliseconds,prev0,fps,responseTime;
int resX,resY,movementX,startFlag;
double movementY;

//... Reshaping settings & rendering parameters.
void reshape(int w, int h)
{

   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glViewport(0, 0, (GLsizei) w, (GLsizei) h);
   glOrtho(0,resX,0,resY,-5,10);
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
}

//....  Keyboard input and movement physics
vector<char> inputKey;
double g,v,tmp2;
int cnt;

void gameoverAnimation()
{
	inputKey.push_back('U');
	v=1.2;

}

void movePhysics()
{
int ii;
g=10;
for(ii=0;ii<inputKey.size();ii++)
	{

		if(inputKey[ii]=='U')
			{
				if((movementY+(resY/2)+50)<resY)
				movementY+=4;
				cnt++;
			}
		if(cnt>=10)
			{
				cnt=0;
				inputKey.erase(inputKey.begin()+ii);
			}

	}
if(startFlag==1)
{

//...GRAVITY
if(inputKey.size()==0)
{
// 0.021125
if(gameover==0)
{
tmp2=resY/2;
v=0.65+(abs(movementY)/tmp2)/5;
}
else
{

	if( (inputKey.size()==0 ) && (movementY <- (resY/2) ) )
	{
		gameover=0;
		resetFunc();
	}
}
movementY-= v*v/2*g;

}

}

}

void keyboard (unsigned char key, int x, int y)
{
  startFlag=1;
   switch (key) {
      case 27:
         exit(0);
         break;
 	  case 32:
 	  	if(gameover==0)
		inputKey.push_back('U');
		break;

   }
}

//... keyboard input end.

int main(int argc, char** argv)
{
   //..frame-update setup
   queuedMilliseconds=0;
   prev0=0;
   fps=60;
   responseTime=(1/fps)*1000;

//... Rendering resoultion
   resX=854;resY=480;

   glutInit(&argc, argv);
   glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutGameModeString("10x10");
   display_test:
   if (glutGameModeGet(GLUT_GAME_MODE_POSSIBLE))
    glutEnterGameMode();
   else {
   	 printf("Select Screen Resolution, if you are unsure select Window mode\n"
   	 		"1. 1920x1080\n2. 1600x900\n3. 1280x720\n4. 1368x768 \n"
   	 		"5. 1366x768 \n6. 800x600\n7. 640x480\n8. Window(try to avoid this!)");
   	 int ch;
   	 scanf("%d",&ch);

   	 if(ch==8)
   	 {
     printf("\n*WARNING: The selected resolution not available, "
    	"Enter xrandr in terminal.\nChange parameter in glutGameModeString to available resolution in xrandr.\n"
    	"Currently running in windowmode.\nVsync may not perform correctly resulting in poor performance.\n");
     glutInitWindowSize(1280, 720);
     glutCreateWindow("Floppy Bird");
     glutFullScreen();
     }
    else if(ch==1)
    	glutGameModeString("1920x1080");
    else if(ch==2)
    	glutGameModeString("1600x900");
    else if(ch==3)
    	glutGameModeString("1280x720");
    else if(ch==4)
    	glutGameModeString("1368x768");
    else if(ch==5)
   		glutGameModeString("1366x768");
    else if(ch==6)
    	glutGameModeString("800x600");
    else
    	glutGameModeString("640x480");

    if(ch!=8)
    	goto display_test;
    	}
   glutIgnoreKeyRepeat(1);
   glutDisplayFunc(draw);
   glutIdleFunc(mixedStepLoop);
   glutReshapeFunc(reshape);
   glutKeyboardFunc(keyboard);
   glutMainLoop();
   return 0;
}
<|endoftext|>


<commit_before>#include "xml.h"
#include "multicron.h"
#include "cnproc.h"
#include "inotify.h"
#include "date.h"
#include <iostream>
#include <string>
#include <pcreposix.h>
#include "commands.h"
#include <sys/select.h>

struct event_manager *inotify_module();
struct event_manager *cnproc_module();

bool reload;

int main(int argc, char **argv) {
	int i,j,max;
	reload=true;
	xmlNode root("multicron.xml");
	EventManager **evs=NULL;
	try {
		while(1) {
			if(reload) {
				printf("Let's reload folks!\n");
				reload=false;
				root.Free();
				Cmds::Update();
				while(1) {
					try {
						root=xmlNode("prout.xml");
						break;
					} catch(...) {
						//Let vim/whatever enough time to write the file
						sleep(1);
					}
				}
				if(evs) {
					for(i=0;evs[i];++i)
						delete evs[i];
					free(evs);
				}
				evs=(EventManager**)malloc(4*sizeof(EventManager*));
				evs[0]=new InotifyEvent;
				evs[1]=new CNProcEvent;
				evs[2]=new DateEvent;
				evs[3]=NULL;

				for(i=0;evs[i];++i)
					evs[i]->RefreshConfig(root(evs[i]->name));
			}

			fd_set rfds,wfds,efds;
			FD_ZERO(&rfds);
			FD_ZERO(&wfds);
			FD_ZERO(&efds);
			max=0;

			//Read FDs
			for(i=0;evs[i];++i)
				evs[i]->AddFDs(rfds, EventManager::READ, max);

			//Write FDs
			for(i=0;evs[i];++i)
				evs[i]->AddFDs(rfds, EventManager::WRITE, max);

			//Exception FDs
			for(i=0;evs[i];++i)
				evs[i]->AddFDs(rfds, EventManager::EXCEPTION, max);

			struct timeval tv,tv2;
			tv.tv_sec=1e9;
			tv.tv_usec=0;
			for(i=0;evs[i];++i) {
				tv2=evs[i]->NextTimeout(root(evs[i]->name));
				if(tv2.tv_sec <= tv.tv_sec)
					tv.tv_sec=tv2.tv_sec;

			}

			int ret=select(max+1, &rfds, &wfds, &efds, &tv);

			//Call timeouts
			if(ret==0) {
				for(i=0;evs[i];++i)
					evs[i]->Callback(root(evs[i]->name), -1, EventManager::TIMEOUT);

				continue;
			}

			//Read FDs
			for(i=0;evs[i];++i)
				if(evs[i]->rfds)
					for(j=0;evs[i]->rfds[j]>=0;++j)
						if(FD_ISSET(evs[i]->rfds[j], &rfds))
							evs[i]->Callback(root(evs[i]->name), evs[i]->rfds[j], EventManager::READ);

			//Write FDs
			for(i=0;evs[i];++i)
				if(evs[i]->wfds)
					for(j=0;evs[i]->wfds[j]>=0;++j)
						if(FD_ISSET(evs[i]->wfds[j], &wfds))
							evs[i]->Callback(root(evs[i]->name), evs[i]->wfds[j], EventManager::WRITE);

			//Exception FDs
			for(i=0;evs[i];++i)
				if(evs[i]->efds)
					for(j=0;evs[i]->efds[j]>=0;++j)
						if(FD_ISSET(evs[i]->efds[j], &efds))
							evs[i]->Callback(root(evs[i]->name), evs[i]->efds[j], EventManager::EXCEPTION);

		}
	} catch(const std::string &e) {
		std::cout << e << std::endl;
	}
	return 0;
}

void EventManager::Callback(xmlNode config, int fd, ETYPE event_type) {
}

void EventManager::RefreshConfig(xmlNode config) {
}

struct timeval EventManager::NextTimeout(xmlNode config) {
	struct timeval tv;
	tv.tv_sec=1e9;
	tv.tv_usec=0;
	return tv;
}

void EventManager::AddFDs(fd_set &fds, ETYPE event_type, int &max) const {
	int j;
	int *tfds=NULL;
	switch(event_type) {
		case READ:
			tfds=rfds;
			break;
		case WRITE:
			tfds=wfds;
			break;
		case EXCEPTION:
			tfds=efds;
			break;
		case TIMEOUT:
		default:
			break;
	};

	if(!tfds)
		return;
	for(j=0;tfds[j]>=0;++j) {
		max=(max<tfds[j]) ? tfds[j] : max;
		FD_SET(tfds[j], &fds);
	}

}

EventManager::~EventManager() {
}
<commit_msg>Hope filename is right this time...<commit_after>#include "xml.h"
#include "multicron.h"
#include "cnproc.h"
#include "inotify.h"
#include "date.h"
#include <iostream>
#include <string>
#include <pcreposix.h>
#include "commands.h"
#include <sys/select.h>

struct event_manager *inotify_module();
struct event_manager *cnproc_module();

bool reload;

int main(int argc, char **argv) {
	int i,j,max;
	reload=true;
	xmlNode root("multicron.xml");
	EventManager **evs=NULL;
	try {
		while(1) {
			if(reload) {
				printf("Let's reload folks!\n");
				reload=false;
				root.Free();
				Cmds::Update();
				while(1) {
					try {
						root=xmlNode("multicron.xml");
						break;
					} catch(...) {
						//Let vim/whatever enough time to write the file
						sleep(1);
					}
				}
				if(evs) {
					for(i=0;evs[i];++i)
						delete evs[i];
					free(evs);
				}
				evs=(EventManager**)malloc(4*sizeof(EventManager*));
				evs[0]=new InotifyEvent;
				evs[1]=new CNProcEvent;
				evs[2]=new DateEvent;
				evs[3]=NULL;

				for(i=0;evs[i];++i)
					evs[i]->RefreshConfig(root(evs[i]->name));
			}

			fd_set rfds,wfds,efds;
			FD_ZERO(&rfds);
			FD_ZERO(&wfds);
			FD_ZERO(&efds);
			max=0;

			//Read FDs
			for(i=0;evs[i];++i)
				evs[i]->AddFDs(rfds, EventManager::READ, max);

			//Write FDs
			for(i=0;evs[i];++i)
				evs[i]->AddFDs(rfds, EventManager::WRITE, max);

			//Exception FDs
			for(i=0;evs[i];++i)
				evs[i]->AddFDs(rfds, EventManager::EXCEPTION, max);

			struct timeval tv,tv2;
			tv.tv_sec=1e9;
			tv.tv_usec=0;
			for(i=0;evs[i];++i) {
				tv2=evs[i]->NextTimeout(root(evs[i]->name));
				if(tv2.tv_sec <= tv.tv_sec)
					tv.tv_sec=tv2.tv_sec;

			}

			int ret=select(max+1, &rfds, &wfds, &efds, &tv);

			//Call timeouts
			if(ret==0) {
				for(i=0;evs[i];++i)
					evs[i]->Callback(root(evs[i]->name), -1, EventManager::TIMEOUT);

				continue;
			}

			//Read FDs
			for(i=0;evs[i];++i)
				if(evs[i]->rfds)
					for(j=0;evs[i]->rfds[j]>=0;++j)
						if(FD_ISSET(evs[i]->rfds[j], &rfds))
							evs[i]->Callback(root(evs[i]->name), evs[i]->rfds[j], EventManager::READ);

			//Write FDs
			for(i=0;evs[i];++i)
				if(evs[i]->wfds)
					for(j=0;evs[i]->wfds[j]>=0;++j)
						if(FD_ISSET(evs[i]->wfds[j], &wfds))
							evs[i]->Callback(root(evs[i]->name), evs[i]->wfds[j], EventManager::WRITE);

			//Exception FDs
			for(i=0;evs[i];++i)
				if(evs[i]->efds)
					for(j=0;evs[i]->efds[j]>=0;++j)
						if(FD_ISSET(evs[i]->efds[j], &efds))
							evs[i]->Callback(root(evs[i]->name), evs[i]->efds[j], EventManager::EXCEPTION);

		}
	} catch(const std::string &e) {
		std::cout << e << std::endl;
	}
	return 0;
}

void EventManager::Callback(xmlNode config, int fd, ETYPE event_type) {
}

void EventManager::RefreshConfig(xmlNode config) {
}

struct timeval EventManager::NextTimeout(xmlNode config) {
	struct timeval tv;
	tv.tv_sec=1e9;
	tv.tv_usec=0;
	return tv;
}

void EventManager::AddFDs(fd_set &fds, ETYPE event_type, int &max) const {
	int j;
	int *tfds=NULL;
	switch(event_type) {
		case READ:
			tfds=rfds;
			break;
		case WRITE:
			tfds=wfds;
			break;
		case EXCEPTION:
			tfds=efds;
			break;
		case TIMEOUT:
		default:
			break;
	};

	if(!tfds)
		return;
	for(j=0;tfds[j]>=0;++j) {
		max=(max<tfds[j]) ? tfds[j] : max;
		FD_SET(tfds[j], &fds);
	}

}

EventManager::~EventManager() {
}
<|endoftext|>


<commit_before>54ccc12e-ad5b-11e7-8862-ac87a332f658<commit_msg>compiles now<commit_after>557b621c-ad5b-11e7-bb99-ac87a332f658<|endoftext|>


<commit_before>72cf79b0-4b02-11e5-82cb-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>72dca180-4b02-11e5-bdb1-28cfe9171a43<|endoftext|>