void SpriteRenderer::UpdateBuffer(const GameContext& gameContext)
{
UNREFERENCED_PARAMETER(gameContext);
if (m_BufferSize < m_Sprites.size() || !m_pVertexBuffer)
{
SafeRelease(m_pVertexBuffer);
if (m_BufferSize < m_Sprites.size())
m_BufferSize = int(m_Sprites.size());
D3D11_BUFFER_DESC buffDesc;
buffDesc.Usage = D3D11_USAGE_DYNAMIC;
buffDesc.ByteWidth = sizeof(SpriteVertex) * uint32_t(m_BufferSize);
buffDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
buffDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
buffDesc.MiscFlags = 0;
const auto hr = gameContext.pDevice->CreateBuffer(&buffDesc, nullptr, &m_pVertexBuffer);
if (Logger::LogHResult(hr, L"SpriteRenderer::UpdateBuffer > m_pVertexBuffer creation failed!"))
return;
}
sort(m_Sprites.begin(), m_Sprites.end(), [](const SpriteVertex& v0, const SpriteVertex& v1)
{
return v0.TextureId < v1.TextureId;
});
sort(m_Sprites.begin(), m_Sprites.end(), SpriteSortByDepth);
sort(m_Sprites.begin(), m_Sprites.end(), [](const SpriteVertex& v0, const SpriteVertex& v1)
{
if (v0.TextureId == v1.TextureId)
{
return v0.TransformData.z < v1.TransformData.z;
}
return false;
});
if (!m_pVertexBuffer)
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
gameContext.pDeviceContext->Map(m_pVertexBuffer, 0, D3D11_MAP_WRITE_NO_OVERWRITE, 0, &mappedResource);
memcpy(mappedResource.pData, m_Sprites.data(), sizeof(SpriteVertex) * uint32_t(m_BufferSize));
gameContext.pDeviceContext->Unmap(m_pVertexBuffer, 0);
}
}
void SpriteComponent::Draw(const GameContext& )
{
if (!m_pTexture)
return;
SpriteRenderer::GetInstance()->Draw(m_pTexture
, DirectX::XMFLOAT2(GetGameObject()->GetTransform()->GetPosition().x, GetGameObject()->GetTransform()->GetPosition().y)
, DirectX::XMFLOAT4(1.f, 1.f, 1.f, 1.f)
, DirectX::XMFLOAT2(m_Pivot)
, DirectX::XMFLOAT2(1.f, 1.f)
, QuaternionToEuler(GetGameObject()->GetTransform()->GetRotation()).z);
}