#include "XCEngine/RHI/OpenGL/OpenGLTextureUnitAllocator.h" #include "XCEngine/RHI/OpenGL/OpenGLTexture.h" #include namespace XCEngine { namespace RHI { OpenGLTextureUnitAllocator::OpenGLTextureUnitAllocator() : m_maxUnits(0) { } OpenGLTextureUnitAllocator::~OpenGLTextureUnitAllocator() { Shutdown(); } void OpenGLTextureUnitAllocator::Initialize(uint32_t maxUnits) { m_maxUnits = maxUnits; m_allocated.resize(maxUnits, false); m_boundTextures.resize(maxUnits, nullptr); } void OpenGLTextureUnitAllocator::Shutdown() { for (uint32_t i = 0; i < m_maxUnits; ++i) { if (m_allocated[i]) { Free(static_cast(i)); } } m_allocated.clear(); m_boundTextures.clear(); m_maxUnits = 0; } int32_t OpenGLTextureUnitAllocator::Allocate() { for (uint32_t i = 0; i < m_maxUnits; ++i) { if (!m_allocated[i]) { m_allocated[i] = true; return static_cast(i); } } return -1; } void OpenGLTextureUnitAllocator::Free(int32_t unit) { if (unit < 0 || unit >= static_cast(m_maxUnits)) { return; } UnbindTexture(unit); m_allocated[unit] = false; } void OpenGLTextureUnitAllocator::BindTexture(int32_t unit, OpenGLTexture* texture) { if (unit < 0 || unit >= static_cast(m_maxUnits)) { return; } glActiveTexture(GL_TEXTURE0 + unit); if (texture) { glBindTexture(static_cast(texture->GetOpenGLType()), texture->GetID()); } else { glBindTexture(GL_TEXTURE_2D, 0); } m_boundTextures[unit] = texture; } void OpenGLTextureUnitAllocator::UnbindTexture(int32_t unit) { if (unit < 0 || unit >= static_cast(m_maxUnits)) { return; } glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(GL_TEXTURE_2D, 0); m_boundTextures[unit] = nullptr; } OpenGLTexture* OpenGLTextureUnitAllocator::GetBoundTexture(int32_t unit) const { if (unit < 0 || unit >= static_cast(m_maxUnits)) { return nullptr; } return m_boundTextures[unit]; } bool OpenGLTextureUnitAllocator::IsAllocated(int32_t unit) const { if (unit < 0 || unit >= static_cast(m_maxUnits)) { return false; } return m_allocated[unit]; } } // namespace RHI } // namespace XCEngine