#include "../engine/Shared.h"
#include "Global.h"
#include "Instance.h"

#include <cassert>
#include <cstdint>

using namespace Gen;

namespace
{
    SharedData* SharedInstance = nullptr;
    Game::GameInstance* GameInst = nullptr;
} // namespace

namespace Game
{
    SharedData& GetShared()
    {
        assert(SharedInstance != nullptr);
        return *SharedInstance;
    }

    void SetShared(SharedData& instance)
    {
        SharedInstance = &instance;
    }

    GameInstance& GetInstance()
    {
        assert(GameInst != nullptr);
        return *GameInst;
    }

    void SetInstance(Game::GameInstance& instance)
    {
        GameInst = &instance;
    }

    void* AllocateScratch(size_t byteCount, size_t align)
    {
        size_t offset = GetInstance().UsedScratchAmount;
        uint8_t* base = static_cast<uint8_t*>(GetShared().Game.TransientStorage);
        uint8_t* current = base + offset;
        size_t offsetAligned = ((offset + align - 1) / align) * align;
        uint8_t* ptrAligned = base + offsetAligned;
        size_t newOffset = offsetAligned + byteCount;
        if (newOffset > GetShared().Game.TransientStorageSize) return nullptr;
        GetInstance().UsedScratchAmount = newOffset;
        return reinterpret_cast<void*>(ptrAligned);
    }
} // namespace Game
