Compare commits

...

3 Commits

Author SHA1 Message Date
Anish Bhobe 297548d2c9 Fully bindless textures. 2025-06-17 22:10:54 +02:00
Anish Bhobe 081e62189f TextureManager added. 2025-06-17 20:53:21 +02:00
Anish Bhobe 43f414a7ae Entities are abstracted into a system. 2025-06-16 21:33:34 +02:00
17 changed files with 1515 additions and 655 deletions

View File

@ -0,0 +1,25 @@
[vk::binding(0, 0)] uniform __DynamicResource<__DynamicResourceKind.Sampler> gTextures[];
public struct RID<T> where T : IOpaqueDescriptor {
private uint internal;
private const static uint INDEX_MASK = 0x0007FFFF;
private const static uint GENERATION_MASK = ~INDEX_MASK;
public property bool hasValue {
get {
return (internal & GENERATION_MASK) > 0;
}
}
public property T value {
get {
// TODO: Check if has value else placeholder.
return gTextures[internal & INDEX_MASK].asOpaqueDescriptor<T>();
}
}
}
public extension <T> T where T: IOpaqueDescriptor {
public typealias RID = RID<T>;
}

View File

@ -1,3 +1,4 @@
import Bindless;
struct VertexOut { struct VertexOut {
float4 outPosition : SV_Position; float4 outPosition : SV_Position;
@ -11,15 +12,13 @@ struct CameraData {
float4x4 proj; float4x4 proj;
}; };
struct PerFrameData { [vk::binding(0, 1)] uniform ConstantBuffer<CameraData> camera;
CameraData camera;
Sampler2D texture;
}
ParameterBlock<PerFrameData> perFrameData; #define INDEX_MASK 0x0007FFFF;
struct PerInstanceData { struct PerInstanceData {
float4x4 transform; float4x4 transform;
Sampler2D.RID textureID;
} }
[[vk::push_constant]] [[vk::push_constant]]
@ -33,8 +32,8 @@ VertexOut VertexMain(
float2 texCoord0, float2 texCoord0,
) { ) {
VertexOut output; VertexOut output;
output.outPosition = mul(perFrameData.camera.proj, mul(perFrameData.camera.view, mul(pcb.transform, float4(position, 1.0f)))); output.outPosition = mul(camera.proj, mul(camera.view, mul(pcb.transform, float4(position, 1.0f))));
output.screenPosition = mul(perFrameData.camera.proj, mul(perFrameData.camera.view, mul(pcb.transform, float4(position, 1.0f)))); output.screenPosition = mul(camera.proj, mul(camera.view, mul(pcb.transform, float4(position, 1.0f))));
output.vertexColor = float4(color, 1.0f); output.vertexColor = float4(color, 1.0f);
output.texCoord0 = texCoord0 * 2.0f; output.texCoord0 = texCoord0 * 2.0f;
return output; return output;
@ -46,6 +45,10 @@ float4 FragmentMain(
float4 interpolatedColors : CoarseColor, float4 interpolatedColors : CoarseColor,
float2 uv0 : TexCoord0, float2 uv0 : TexCoord0,
) : SV_Target0 { ) : SV_Target0 {
return float4(perFrameData.texture.Sample(uv0).rgb, 1.0f) * interpolatedColors; if (let texture = pcb.textureID) {
return float4(texture.Sample(uv0).rgb, 1.0f) * interpolatedColors;
} else {
return interpolatedColors;
}
} }

View File

@ -109,7 +109,7 @@
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard> <LanguageStandard>stdcpp20</LanguageStandard>
<RuntimeTypeInfo>false</RuntimeTypeInfo> <RuntimeTypeInfo>false</RuntimeTypeInfo>
<TreatWarningAsError>true</TreatWarningAsError> <TreatWarningAsError>false</TreatWarningAsError>
<ExceptionHandling>Sync</ExceptionHandling> <ExceptionHandling>Sync</ExceptionHandling>
<MinimalRebuild>false</MinimalRebuild> <MinimalRebuild>false</MinimalRebuild>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
@ -132,7 +132,7 @@
<ConformanceMode>true</ConformanceMode> <ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp20</LanguageStandard> <LanguageStandard>stdcpp20</LanguageStandard>
<RuntimeTypeInfo>false</RuntimeTypeInfo> <RuntimeTypeInfo>false</RuntimeTypeInfo>
<TreatWarningAsError>true</TreatWarningAsError> <TreatWarningAsError>false</TreatWarningAsError>
<ExceptionHandling>/EH-</ExceptionHandling> <ExceptionHandling>/EH-</ExceptionHandling>
<MinimalRebuild>false</MinimalRebuild> <MinimalRebuild>false</MinimalRebuild>
<AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions> <AdditionalOptions>/utf-8 %(AdditionalOptions)</AdditionalOptions>
@ -161,6 +161,7 @@
<Message Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Compiling %(Filename).slang</Message> <Message Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Compiling %(Filename).slang</Message>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).spv</Outputs> <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).spv</Outputs>
</CustomBuild> </CustomBuild>
<None Include="Assets\Shaders\Bindless.slang" />
<None Include="PLAN.md"> <None Include="PLAN.md">
<SubType> <SubType>
</SubType> </SubType>
@ -171,21 +172,25 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="Blaze\AppState.h" /> <ClInclude Include="Blaze\AppState.h" />
<ClInclude Include="Blaze\EntityManager.h" />
<ClInclude Include="Blaze\Frame.h" /> <ClInclude Include="Blaze\Frame.h" />
<ClInclude Include="Blaze\GlobalMemory.h" /> <ClInclude Include="Blaze\GlobalMemory.h" />
<ClInclude Include="Blaze\MacroUtils.h" /> <ClInclude Include="Blaze\MacroUtils.h" />
<ClInclude Include="Blaze\MathUtil.h" /> <ClInclude Include="Blaze\MathUtil.h" />
<ClInclude Include="Blaze\MiscData.h" /> <ClInclude Include="Blaze\MiscData.h" />
<ClInclude Include="Blaze\RenderDevice.h" /> <ClInclude Include="Blaze\RenderDevice.h" />
<ClInclude Include="Blaze\TextureManager.h" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="Blaze\AppState.cpp" /> <ClCompile Include="Blaze\AppState.cpp" />
<ClCompile Include="Blaze\Blaze.cpp" /> <ClCompile Include="Blaze\Blaze.cpp" />
<ClCompile Include="Blaze\EntityManager.cpp" />
<ClCompile Include="Blaze\Frame.cpp" /> <ClCompile Include="Blaze\Frame.cpp" />
<ClCompile Include="Blaze\GlobalMemory.cpp" /> <ClCompile Include="Blaze\GlobalMemory.cpp" />
<ClCompile Include="Blaze\MiscData.cpp" /> <ClCompile Include="Blaze\MiscData.cpp" />
<ClCompile Include="Blaze\RenderDevice.cpp" /> <ClCompile Include="Blaze\RenderDevice.cpp" />
<ClCompile Include="Blaze\StbImpl.cpp" /> <ClCompile Include="Blaze\StbImpl.cpp" />
<ClCompile Include="Blaze\TextureManager.cpp" />
<ClCompile Include="Blaze\VmaImpl.cpp" /> <ClCompile Include="Blaze\VmaImpl.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -45,6 +45,9 @@
<None Include="vcpkg-configuration.json"> <None Include="vcpkg-configuration.json">
<Filter>Resource Files\Config</Filter> <Filter>Resource Files\Config</Filter>
</None> </None>
<None Include="Assets\Shaders\Bindless.slang">
<Filter>Resource Files\Shader Files</Filter>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="Blaze\AppState.h"> <ClInclude Include="Blaze\AppState.h">
@ -68,6 +71,12 @@
<ClInclude Include="Blaze\RenderDevice.h"> <ClInclude Include="Blaze\RenderDevice.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="Blaze\EntityManager.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Blaze\TextureManager.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="Blaze\AppState.cpp"> <ClCompile Include="Blaze\AppState.cpp">
@ -94,6 +103,12 @@
<ClCompile Include="Blaze\VmaImpl.cpp"> <ClCompile Include="Blaze\VmaImpl.cpp">
<Filter>Source Files\HeaderOnlyImpl</Filter> <Filter>Source Files\HeaderOnlyImpl</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="Blaze\EntityManager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Blaze\TextureManager.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Image Include="Assets\Textures\container2.png"> <Image Include="Assets\Textures\container2.png">

View File

@ -2,9 +2,11 @@
#include <SDL3/SDL_log.h> #include <SDL3/SDL_log.h>
#include "EntityManager.h"
#include "GlobalMemory.h" #include "GlobalMemory.h"
#include "MiscData.h" #include "MiscData.h"
#include "RenderDevice.h" #include "RenderDevice.h"
#include "TextureManager.h"
bool AppState::isInit() const bool AppState::isInit() const
{ {
@ -19,12 +21,18 @@ void AppState::destroy()
Take( miscData )->destroy( *renderDevice ); Take( miscData )->destroy( *renderDevice );
Take( entityManager )->destroy();
Take( renderDevice )->destroy(); Take( renderDevice )->destroy();
SDL_DestroyWindow( Take( window ) ); SDL_DestroyWindow( Take( window ) );
} }
AppState::AppState( SDL_Window* window, RenderDevice* renderDevice, MiscData* miscData ) AppState::AppState( SDL_Window* window, RenderDevice* renderDevice, EntityManager* entityManager, MiscData* miscData )
: window{ window }, renderDevice{ renderDevice }, miscData{ miscData }, sprintfBuffer{ 0 } : window{ window }
, renderDevice{ renderDevice }
, entityManager{ entityManager }
, miscData{ miscData }
, sprintfBuffer{ 0 }
{} {}
AppState* AppState_Create( GlobalMemory* memory, uint32_t const width, uint32_t const height ) AppState* AppState_Create( GlobalMemory* memory, uint32_t const width, uint32_t const height )
@ -38,20 +46,37 @@ AppState* AppState_Create( GlobalMemory* memory, uint32_t const width, uint32_t
} }
RenderDevice* renderDevice = RenderDevice_Create( memory, { .window = window } ); RenderDevice* renderDevice = RenderDevice_Create( memory, { .window = window } );
if ( !renderDevice->isInit() ) if ( !renderDevice or !renderDevice->isInit() )
{ {
SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "RenderDevice failed to init" ); SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "RenderDevice failed to init" );
SDL_DestroyWindow( window ); SDL_DestroyWindow( window );
return nullptr; return nullptr;
} }
EntityManager* entityManager = EntityManager_Create( memory, renderDevice, 10 );
if ( !entityManager )
{
SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "EntityManager failed to init" );
renderDevice->destroy();
SDL_DestroyWindow( window );
return nullptr;
}
auto* miscDataAllocation = memory->allocate( sizeof( MiscData ) ); auto* miscDataAllocation = memory->allocate( sizeof( MiscData ) );
MiscData* miscData = new ( miscDataAllocation ) MiscData{}; MiscData* miscData = new ( miscDataAllocation ) MiscData{};
if ( !miscData->init( *renderDevice ) ) return nullptr; if ( !miscData->init( *renderDevice ) )
{
SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "MiscData failed to init" );
entityManager->destroy();
renderDevice->destroy();
SDL_DestroyWindow( window );
return nullptr;
}
auto* allocation = memory->allocate( sizeof( AppState ) ); auto* allocation = memory->allocate( sizeof( AppState ) );
AppState* appState = new ( allocation ) AppState{ window, renderDevice, miscData }; AppState* appState = new ( allocation ) AppState{ window, renderDevice, entityManager, miscData };
return appState; return appState;
} }

View File

@ -2,23 +2,27 @@
#include <cstdint> #include <cstdint>
struct SDL_Window; struct SDL_Window;
struct GlobalMemory; struct GlobalMemory;
struct RenderDevice; struct RenderDevice;
struct EntityManager;
struct TextureManager;
struct MiscData; struct MiscData;
struct AppState struct AppState
{ {
SDL_Window* window; SDL_Window* window;
RenderDevice* renderDevice; RenderDevice* renderDevice;
EntityManager* entityManager;
MiscData* miscData; MiscData* miscData;
char sprintfBuffer[256]; char sprintfBuffer[256];
[[nodiscard]] bool isInit() const; [[nodiscard]] bool isInit() const;
void destroy(); void destroy();
AppState( SDL_Window* window, RenderDevice* renderDevice, MiscData* miscData ); AppState( SDL_Window* window, RenderDevice* renderDevice, EntityManager* entityManager, MiscData* miscData );
AppState( AppState const& other ) = delete; AppState( AppState const& other ) = delete;
AppState( AppState&& other ) noexcept = delete; AppState( AppState&& other ) noexcept = delete;

View File

@ -15,6 +15,7 @@
#include <SDL3/SDL_vulkan.h> #include <SDL3/SDL_vulkan.h>
#include "AppState.h" #include "AppState.h"
#include "EntityManager.h"
#include "Frame.h" #include "Frame.h"
#include "GlobalMemory.h" #include "GlobalMemory.h"
#include "MacroUtils.h" #include "MacroUtils.h"
@ -40,6 +41,66 @@ SDL_AppResult SDL_AppInit( void** appstate, int, char** )
*appstate = AppState_Create( &Blaze::Global::g_Memory, WIDTH, HEIGHT ); *appstate = AppState_Create( &Blaze::Global::g_Memory, WIDTH, HEIGHT );
if ( !*appstate ) return SDL_APP_FAILURE; if ( !*appstate ) return SDL_APP_FAILURE;
AppState& appState = *static_cast<AppState*>( *appstate );
// TODO: Integrate this
// Model Setup
// modelTransform[1].position = { -1.0f, 0.0f, 0.0f };
// modelTransform[1].scale = 1.0f;
// modelTransform[1].rotation =
// DirectX::XMQuaternionRotationAxis( DirectX::XMVectorSet( 1.0f, 0.0f, 0.0f, 0.0f ), 0.0f );
// TL----TR
// | \ |
// | \ |
// | \ |
// BL----BR
//
// BL -> BR -> TL
// TL -> BR -> TR
std::array vertices = {
// Bottom Left
Vertex{
.position = { -1.0f, -1.0f, 0.0f },
.color = { 0.0f, 0.0f, 1.0f },
.texCoord0 = { 0.0f, 0.0f },
},
// Bottom Right
Vertex{
.position = { 1.0f, -1.0f, 0.0f },
.color = { 1.0f, 0.0f, 0.0f },
.texCoord0 = { 1.0f, 0.0f },
},
// Top Left
Vertex{
.position = { -1.0f, 1.0f, 0.0f },
.color = { 0.0f, 1.0f, 0.0f },
.texCoord0 = { 0.0f, 1.0f },
},
// Top Right
Vertex{
.position = { 1.0f, 1.0f, 0.0f },
.color = { 1.0f, 1.0f, 0.0f },
.texCoord0 = { 1.0f, 1.0f },
}
};
Transform modelTransform = {
.position = { 1.0f, 0.0f, 0.0f },
.scale = 1.0f,
.rotation = DirectX::XMQuaternionRotationAxis( DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ), 0.0f ),
};
for ( int i = -3; i <= 3; ++i )
{
modelTransform.position.x = static_cast<float>( i );
appState.entityManager->createEntity(
modelTransform, vertices, i > 0 ? "Assets/Textures/wall.jpg" : "Assets/Textures/container2.png" );
}
return SDL_APP_CONTINUE; return SDL_APP_CONTINUE;
} }
@ -47,11 +108,11 @@ SDL_AppResult SDL_AppIterate( void* appstate )
{ {
AppState& appState = *static_cast<AppState*>( appstate ); AppState& appState = *static_cast<AppState*>( appstate );
RenderDevice& renderDevice = *appState.renderDevice; RenderDevice& renderDevice = *appState.renderDevice;
EntityManager& entityManager = *appState.entityManager;
MiscData& misc = *appState.miscData; MiscData& misc = *appState.miscData;
Frame& currentFrame = renderDevice.frames[renderDevice.frameIndex]; Frame& currentFrame = renderDevice.frames[renderDevice.frameIndex];
VK_CHECK( vkWaitForFences( VK_CHECK( vkWaitForFences( renderDevice.device, 1, &currentFrame.frameReadyToReuse, VK_TRUE, UINT32_MAX ) );
renderDevice.device, 1, &currentFrame.frameReadyToReuse, VK_TRUE, std::numeric_limits<uint32_t>::max() ) );
// All resources of frame 'frameIndex' are free. // All resources of frame 'frameIndex' are free.
// time calc // time calc
@ -70,13 +131,13 @@ SDL_AppResult SDL_AppIterate( void* appstate )
SDL_SetWindowTitle( appState.window, appState.sprintfBuffer ); SDL_SetWindowTitle( appState.window, appState.sprintfBuffer );
} }
for ( Transform& transform : misc.modelTransform ) for ( Entity& entity : entityManager.iter() )
{ {
transform.rotation = DirectX::XMQuaternionMultiply( entity.transform().rotation = DirectX::XMQuaternionMultiply(
DirectX::XMQuaternionRotationAxis( DirectX::XMQuaternionRotationAxis(
DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ), DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ),
DirectX::XMConvertToRadians( 60.0f ) * static_cast<float>( deltaTime ) ), DirectX::XMConvertToRadians( 60.0f ) * static_cast<float>( deltaTime ) ),
transform.rotation ); entity.transform().rotation );
} }
uint32_t currentImageIndex; uint32_t currentImageIndex;
@ -88,6 +149,8 @@ SDL_AppResult SDL_AppIterate( void* appstate )
nullptr, nullptr,
&currentImageIndex ) ); &currentImageIndex ) );
// TODO: Resize Swapchain if required.
VK_CHECK( vkResetFences( renderDevice.device, 1, &currentFrame.frameReadyToReuse ) ); VK_CHECK( vkResetFences( renderDevice.device, 1, &currentFrame.frameReadyToReuse ) );
VK_CHECK( vkResetCommandPool( renderDevice.device, currentFrame.commandPool, 0 ) ); VK_CHECK( vkResetCommandPool( renderDevice.device, currentFrame.commandPool, 0 ) );
@ -155,12 +218,26 @@ SDL_AppResult SDL_AppIterate( void* appstate )
// Render Something? // Render Something?
vkCmdBindPipeline( cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.meshPipeline ); vkCmdBindPipeline( cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.meshPipeline );
VkDeviceSize constexpr offset = 0;
vkCmdBindVertexBuffers( cmd, 0, 1, &misc.vertexBuffer, &offset );
vkCmdBindDescriptorSets( vkCmdBindDescriptorSets(
cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.pipelineLayout, 0, 1, &misc.descriptorSet, 0, nullptr ); cmd,
for ( Transform& localTransform : misc.modelTransform ) VK_PIPELINE_BIND_POINT_GRAPHICS,
misc.pipelineLayout,
0,
1,
&renderDevice.textureManager->descriptorSet(),
0,
nullptr );
vkCmdBindDescriptorSets(
cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.pipelineLayout, 1, 1, &misc.descriptorSet, 0, nullptr );
for ( Entity const& entity : entityManager.iter() )
{ {
VkDeviceSize constexpr offset = 0;
vkCmdBindVertexBuffers( cmd, 0, 1, &entity.mesh().vertexBuffer, &offset );
Transform const& localTransform = entity.transform();
DirectX::XMMATRIX worldTransform; DirectX::XMMATRIX worldTransform;
{ {
auto [x, y, z] = localTransform.position; auto [x, y, z] = localTransform.position;
@ -171,7 +248,14 @@ SDL_AppResult SDL_AppIterate( void* appstate )
} }
vkCmdPushConstants( vkCmdPushConstants(
cmd, misc.pipelineLayout, VK_SHADER_STAGE_ALL_GRAPHICS, 0, sizeof worldTransform, &worldTransform ); cmd, misc.pipelineLayout, VK_SHADER_STAGE_ALL_GRAPHICS, 0, sizeof worldTransform, &worldTransform );
vkCmdDraw( cmd, static_cast<uint32_t>( misc.vertices.size() ), 1, 0, 0 ); vkCmdPushConstants(
cmd,
misc.pipelineLayout,
VK_SHADER_STAGE_ALL_GRAPHICS,
sizeof worldTransform,
sizeof entity.material().texture,
&entity.material().texture );
vkCmdDraw( cmd, entity.mesh().vertexCount, 1, 0, 0 );
} }
} }
vkCmdEndRendering( cmd ); vkCmdEndRendering( cmd );

509
Blaze/EntityManager.cpp Normal file
View File

@ -0,0 +1,509 @@
#include "EntityManager.h"
#include <array>
#include "GlobalMemory.h"
#include "RenderDevice.h"
#include <stb_image.h>
#include "Frame.h"
#include "TextureManager.h"
Entity* EntityManager::createEntity(
Transform const& transform, std::span<Vertex> const vertices, const char* textureFile )
{
ASSERT( pRenderDevice );
RenderDevice& renderDevice = *pRenderDevice;
Mesh mesh;
{
mesh.vertexCount = static_cast<uint32_t>( vertices.size() );
mesh.vertexBufferSize = static_cast<uint32_t>( vertices.size_bytes() );
VkBufferCreateInfo const bufferCreateInfo = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = mesh.vertexBufferSize,
.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
VmaAllocationCreateInfo constexpr allocationCreateInfo = {
.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
.preferredFlags = 0,
.memoryTypeBits = 0,
.pool = nullptr,
.pUserData = nullptr,
.priority = 1.0f,
};
VmaAllocationInfo allocationInfo;
VK_CHECK( vmaCreateBuffer(
pRenderDevice->gpuAllocator,
&bufferCreateInfo,
&allocationCreateInfo,
&mesh.vertexBuffer,
&mesh.vertexBufferAllocation,
&allocationInfo ) );
if ( allocationInfo.pMappedData )
{
memcpy( allocationInfo.pMappedData, vertices.data(), vertices.size_bytes() );
}
}
Material material;
{
VkSampler sampler;
uint32_t width;
uint32_t height;
uint32_t numChannels = 4;
stbi_uc* textureData;
{
int w;
int h;
int nc;
int requestedChannels = static_cast<int>( numChannels );
textureData = stbi_load( textureFile, &w, &h, &nc, requestedChannels );
ASSERT( nc <= requestedChannels );
if ( not textureData )
{
vmaDestroyBuffer( pRenderDevice->gpuAllocator, Take( mesh.vertexBuffer ), Take( mesh.vertexBufferAllocation ) );
SDL_LogError( SDL_LOG_CATEGORY_ERROR, "%s", stbi_failure_reason() );
return nullptr;
}
width = static_cast<uint32_t>( w );
height = static_cast<uint32_t>( h );
}
VkSamplerCreateInfo constexpr samplerCreateInfo = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.magFilter = VK_FILTER_LINEAR,
.minFilter = VK_FILTER_LINEAR,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.mipLodBias = 0.0,
.anisotropyEnable = true,
.maxAnisotropy = 1.0f,
.compareEnable = false,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = VK_LOD_CLAMP_NONE,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
.unnormalizedCoordinates = false,
};
VK_CHECK( vkCreateSampler( renderDevice.device, &samplerCreateInfo, nullptr, &sampler ) );
auto textureOpt = renderDevice.textureManager->createTexture( { width, height, 1 }, sampler );
if ( not textureOpt )
{
vmaDestroyBuffer( pRenderDevice->gpuAllocator, Take( mesh.vertexBuffer ), Take( mesh.vertexBufferAllocation ) );
SDL_LogError( SDL_LOG_CATEGORY_ERROR, "%s", stbi_failure_reason() );
stbi_image_free( textureData );
return nullptr;
}
TextureID texture = std::move( textureOpt.value() );
VkImage textureImage = renderDevice.textureManager->fetchImage( texture ).value();
// Staging Buffer Create
VkBuffer stagingBuffer;
VmaAllocation stagingAllocation;
{
VkBufferCreateInfo const stagingBufferCreateInfo = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = static_cast<VkDeviceSize>( width ) * height * numChannels * sizeof( textureData[0] ),
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
VmaAllocationCreateInfo constexpr stagingAllocationCreateInfo = {
.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
.preferredFlags = 0,
.memoryTypeBits = 0,
.pool = nullptr,
.pUserData = nullptr,
.priority = 1.0f,
};
VmaAllocationInfo allocationInfo;
VK_CHECK( vmaCreateBuffer(
renderDevice.gpuAllocator,
&stagingBufferCreateInfo,
&stagingAllocationCreateInfo,
&stagingBuffer,
&stagingAllocation,
&allocationInfo ) );
if ( allocationInfo.pMappedData )
{
memcpy( allocationInfo.pMappedData, textureData, stagingBufferCreateInfo.size );
}
}
// All data is copied to stagingBuffer, don't need this.
stbi_image_free( textureData );
// Staging -> Texture transfer
{
Frame& frameInUse = renderDevice.frames[renderDevice.frameIndex];
// This should just pass.
VK_CHECK( vkWaitForFences( renderDevice.device, 1, &frameInUse.frameReadyToReuse, VK_TRUE, INT64_MAX ) );
// Reset Frame
VK_CHECK( vkResetFences( renderDevice.device, 1, &frameInUse.frameReadyToReuse ) );
VK_CHECK( vkResetCommandPool( renderDevice.device, frameInUse.commandPool, 0 ) );
VkCommandBufferBeginInfo constexpr beginInfo = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = nullptr,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
.pInheritanceInfo = nullptr,
};
uint32_t mipLevels = TextureManager::calculateRequiredMipLevels( width, height, 1 );
VkImageSubresourceRange const subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipLevels,
.baseArrayLayer = 0,
.layerCount = 1,
};
VkImageMemoryBarrier2 const creationToTransferImageBarrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT,
.srcAccessMask = VK_ACCESS_2_NONE,
.dstStageMask = VK_PIPELINE_STAGE_2_COPY_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = renderDevice.textureManager->fetchImage( texture ).value(),
.subresourceRange = subresourceRange,
};
VkDependencyInfo const creationToTransferDependency = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.dependencyFlags = 0,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = 1,
.pImageMemoryBarriers = &creationToTransferImageBarrier,
};
std::array transferToReadyImageBarriers{
// transferToReadyImageBarrier
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT,
.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = textureImage,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipLevels-1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT,
.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = textureImage,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = mipLevels-1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
}
};
VkDependencyInfo const transferToReadyDependency = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.dependencyFlags = 0,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = static_cast<uint32_t>( transferToReadyImageBarriers.size() ),
.pImageMemoryBarriers = transferToReadyImageBarriers.data(),
};
VkImageSubresourceRange const mipLevelSubresource = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
};
std::array prepareNextMipLevelBarriers{
// prepareNextMipLevelSrcImageBarrier
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = textureImage,
.subresourceRange = mipLevelSubresource,
},
// prepareNextMipLevelDstImageBarrier
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_BLIT_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = textureImage,
.subresourceRange = mipLevelSubresource,
}
};
VkDependencyInfo const prepareNextMipLevelDependency = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.dependencyFlags = 0,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = static_cast<uint32_t>( prepareNextMipLevelBarriers.size() ),
.pImageMemoryBarriers = prepareNextMipLevelBarriers.data(),
};
vkBeginCommandBuffer( frameInUse.commandBuffer, &beginInfo );
{
VkImageSubresourceLayers imageSubresourceLayers = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
};
// TODO: Ensure `bufferRowLength` and `bufferImageHeight` are not required.
VkBufferImageCopy copyRegion = {
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = imageSubresourceLayers,
.imageOffset = { 0, 0, 0 },
.imageExtent = { width, height, 1 }
};
// Start
vkCmdPipelineBarrier2( frameInUse.commandBuffer, &creationToTransferDependency );
// Staging -> Image L0
vkCmdCopyBufferToImage(
frameInUse.commandBuffer,
stagingBuffer,
textureImage,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
&copyRegion );
prepareNextMipLevelBarriers[0].subresourceRange.baseMipLevel = 0;
prepareNextMipLevelBarriers[1].subresourceRange.baseMipLevel = 1;
int32_t mipSrcWidth = static_cast<int32_t>( width );
int32_t mipSrcHeight = static_cast<int32_t>( height );
int32_t mipDstWidth = std::max( mipSrcWidth / 2, 1 );
int32_t mipDstHeight = std::max( mipSrcHeight / 2, 1 );
VkImageSubresourceLayers constexpr mipSubresourceLayers = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
};
VkImageBlit2 imageBlit = {
.sType = VK_STRUCTURE_TYPE_IMAGE_BLIT_2,
.pNext = nullptr,
.srcSubresource = mipSubresourceLayers,
.srcOffsets = { { 0, 0, 0 }, { mipSrcWidth, mipSrcHeight, 1 } },
.dstSubresource = mipSubresourceLayers,
.dstOffsets = { { 0, 0, 0 }, { mipDstWidth, mipDstHeight, 1 } },
};
imageBlit.srcSubresource.mipLevel = 0;
imageBlit.dstSubresource.mipLevel = 1;
imageBlit.srcOffsets[1].x = mipSrcWidth;
imageBlit.srcOffsets[1].y = mipSrcHeight;
imageBlit.dstOffsets[1].x = mipDstWidth;
imageBlit.dstOffsets[1].y = mipDstHeight;
VkBlitImageInfo2 blitInfo = {
.sType = VK_STRUCTURE_TYPE_BLIT_IMAGE_INFO_2,
.pNext = nullptr,
.srcImage = textureImage,
.srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.dstImage = textureImage,
.dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.regionCount = 1,
.pRegions = &imageBlit,
.filter = VK_FILTER_LINEAR,
};
// MipMapping
for ( uint32_t dstMipLevel = 1; dstMipLevel < mipLevels; ++dstMipLevel )
{
vkCmdPipelineBarrier2( frameInUse.commandBuffer, &prepareNextMipLevelDependency );
vkCmdBlitImage2( frameInUse.commandBuffer, &blitInfo );
// Prep for NEXT iteration
mipSrcWidth = mipDstWidth;
mipSrcHeight = mipDstHeight;
mipDstWidth = std::max( mipSrcWidth / 2, 1 );
mipDstHeight = std::max( mipSrcHeight / 2, 1 );
imageBlit.srcSubresource.mipLevel = dstMipLevel;
imageBlit.dstSubresource.mipLevel = dstMipLevel + 1;
imageBlit.srcOffsets[1].x = mipSrcWidth;
imageBlit.srcOffsets[1].y = mipSrcHeight;
imageBlit.dstOffsets[1].x = mipDstWidth;
imageBlit.dstOffsets[1].y = mipDstHeight;
// Prep current mip level as source
prepareNextMipLevelBarriers[0].subresourceRange.baseMipLevel = dstMipLevel;
prepareNextMipLevelBarriers[1].subresourceRange.baseMipLevel = dstMipLevel + 1;
}
// End
vkCmdPipelineBarrier2( frameInUse.commandBuffer, &transferToReadyDependency );
}
vkEndCommandBuffer( frameInUse.commandBuffer );
VkSubmitInfo submitInfo = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreCount = 0,
.pWaitSemaphores = nullptr,
.pWaitDstStageMask = nullptr,
.commandBufferCount = 1,
.pCommandBuffers = &frameInUse.commandBuffer,
.signalSemaphoreCount = 0,
.pSignalSemaphores = nullptr,
};
VK_CHECK( vkQueueSubmit( renderDevice.directQueue, 1, &submitInfo, frameInUse.frameReadyToReuse ) );
// Do not reset this. Else, the frame will never be available to the main loop.
VK_CHECK( vkWaitForFences( renderDevice.device, 1, &frameInUse.frameReadyToReuse, VK_TRUE, UINT64_MAX ) );
renderDevice.frameIndex = ( renderDevice.frameIndex + 1 ) % renderDevice.getNumFrames();
}
vmaDestroyBuffer( renderDevice.gpuAllocator, stagingBuffer, stagingAllocation );
material = { std::move( texture ), sampler };
}
entities[count++] = Entity( transform, mesh, std::move( material ) );
return entities + count;
}
void EntityManager::destroyEntity( Entity* entity )
{
ASSERT( entity );
if ( !entity->isInit() ) return;
VkDevice const device = pRenderDevice->device;
VmaAllocator const allocator = pRenderDevice->gpuAllocator;
vkDestroySampler( device, Take( entity->material().sampler ), nullptr );
pRenderDevice->textureManager->freeTexture( std::move( entity->material().texture ) );
vmaDestroyBuffer( allocator, Take( entity->mesh().vertexBuffer ), Take( entity->mesh().vertexBufferAllocation ) );
// TODO: Leaking descriptor set.
}
void EntityManager::destroy()
{
Entity const* end = entities + capacity;
for ( Entity* iter = entities; iter != end; ++iter )
{
destroyEntity( iter );
}
entities = nullptr;
capacity = 0;
count = 0;
}
EntityManager::~EntityManager()
{
assert( !entities );
}
EntityManager* EntityManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t const capacity )
{
Entity* data = reinterpret_cast<Entity*>( mem->allocate( capacity * sizeof( Entity ), alignof( Entity ) ) );
memset( data, 0, capacity * sizeof( Entity ) );
std::byte* alloc = mem->allocate( sizeof( EntityManager ), alignof( EntityManager ) );
return new ( alloc ) EntityManager{ renderDevice, data, capacity };
}

141
Blaze/EntityManager.h Normal file
View File

@ -0,0 +1,141 @@
#pragma once
#include <cstdint>
#include <volk.h>
#include <vma/vk_mem_alloc.h>
#include <DirectXMath.h>
#include <span>
// TODO: Remove this dependency
#include "TextureManager.h"
struct RenderDevice;
struct GlobalMemory;
struct Vertex
{
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 color;
DirectX::XMFLOAT2 texCoord0;
};
struct Transform
{
DirectX::XMFLOAT3 position;
float scale;
DirectX::XMVECTOR rotation;
};
struct Mesh
{
VkBuffer vertexBuffer;
VmaAllocation vertexBufferAllocation;
uint32_t vertexBufferSize;
uint32_t vertexCount;
};
struct Material
{
TextureID texture;
VkSampler sampler; // TODO: Reuse
};
struct Entity
{
private:
Transform m_transform;
Mesh m_mesh;
Material m_material;
public:
[[nodiscard]] Transform& transform()
{
return m_transform;
}
[[nodiscard]] Transform const& transform() const
{
return m_transform;
}
[[nodiscard]] Mesh& mesh()
{
return m_mesh;
}
[[nodiscard]] Mesh const& mesh() const
{
return m_mesh;
}
[[nodiscard]] Material& material()
{
return m_material;
}
[[nodiscard]] Material const& material() const
{
return m_material;
}
[[nodiscard]] bool isInit() const
{
return m_mesh.vertexBuffer or m_material.texture;
}
Entity( Transform const& transform, Mesh const& mesh, Material&& material )
: m_transform{ transform }, m_mesh{ mesh }, m_material{ std::forward<Material>( material ) }
{}
};
struct EntityManager
{
struct Iterable
{
private:
Entity* m_begin;
Entity* m_end;
public:
Iterable( Entity* begin, uint32_t const count ) : m_begin{ begin }, m_end{ begin + count }
{}
// Iterator
[[nodiscard]] Entity* begin() const
{
return m_begin;
}
[[nodiscard]] Entity* end() const
{
return m_end;
}
};
RenderDevice* pRenderDevice;
Entity* entities;
uint32_t count;
uint32_t capacity;
EntityManager( RenderDevice* renderDevice, Entity* data, uint32_t const capacity )
: pRenderDevice{ renderDevice }, entities{ data }, count{ 0 }, capacity{ capacity }
{}
[[nodiscard]] Iterable iter() const
{
return Iterable{ entities, count };
}
// Make Entities return ID, make it a sparse indexing system.
Entity* createEntity( Transform const& transform, std::span<Vertex> vertices, const char* textureFile );
void destroyEntity( Entity* entity );
void destroy();
~EntityManager();
};
EntityManager* EntityManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t capacity );

View File

@ -24,6 +24,7 @@ std::byte* GlobalMemory::allocate( size_t const size )
assert( size <= available && "No enough space available" ); assert( size <= available && "No enough space available" );
std::byte* retVal = memory; std::byte* retVal = memory;
memset( retVal, 0, size );
memory += size; memory += size;
available -= size; available -= size;
SDL_LogInfo( SDL_LogInfo(

View File

@ -4,6 +4,10 @@
#include <cstdlib> #include <cstdlib>
#include <utility> #include <utility>
#include <SDL3/SDL_log.h>
#define DEPRECATE_JULY_2025
#define G_ASSERT( COND ) \ #define G_ASSERT( COND ) \
do \ do \
{ \ { \

View File

@ -4,9 +4,7 @@
#include <SDL3/SDL_log.h> #include <SDL3/SDL_log.h>
#include <stb_image.h> #include "EntityManager.h" // Refactor away.
#include "Frame.h"
#include "MacroUtils.h" #include "MacroUtils.h"
#include "RenderDevice.h" #include "RenderDevice.h"
@ -41,44 +39,41 @@ bool MiscData::init( RenderDevice const& renderDevice )
VkShaderModule shaderModule; VkShaderModule shaderModule;
VK_CHECK( vkCreateShaderModule( device, &shaderModuleCreateInfo, nullptr, &shaderModule ) ); VK_CHECK( vkCreateShaderModule( device, &shaderModuleCreateInfo, nullptr, &shaderModule ) );
std::array descriptorSetLayoutBindings{ VkDescriptorSetLayoutBinding constexpr perFrameDescriptorBinding{
VkDescriptorSetLayoutBinding{
.binding = 0, .binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
.pImmutableSamplers = nullptr, .pImmutableSamplers = nullptr,
},
VkDescriptorSetLayoutBinding{
.binding = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = nullptr,
},
}; };
VkDescriptorSetLayoutCreateInfo const descriptorSetLayoutCreateInfo = { VkDescriptorSetLayoutCreateInfo perFrameDescriptorSetLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
.flags = 0, .flags = 0,
.bindingCount = static_cast<uint32_t>( descriptorSetLayoutBindings.size() ), .bindingCount = 1,
.pBindings = descriptorSetLayoutBindings.data(), .pBindings = &perFrameDescriptorBinding,
}; };
VK_CHECK( vkCreateDescriptorSetLayout( device, &descriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout ) ); VK_CHECK(
vkCreateDescriptorSetLayout( device, &perFrameDescriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout ) );
VkPushConstantRange const pushConstantRange = { VkPushConstantRange const pushConstantRange = {
.stageFlags = VK_SHADER_STAGE_ALL_GRAPHICS, .stageFlags = VK_SHADER_STAGE_ALL_GRAPHICS,
.offset = 0, .offset = 0,
.size = sizeof( DirectX::XMMATRIX ), .size = sizeof( DirectX::XMMATRIX ) + sizeof( uint32_t ),
};
std::array const descriptorSetLayouts = {
renderDevice.textureManager->descriptorLayout(),
descriptorSetLayout,
}; };
VkPipelineLayoutCreateInfo const pipelineLayoutCreateInfo = { VkPipelineLayoutCreateInfo const pipelineLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
.flags = 0, .flags = 0,
.setLayoutCount = 1, .setLayoutCount = static_cast<uint32_t>( descriptorSetLayouts.size() ),
.pSetLayouts = &descriptorSetLayout, .pSetLayouts = descriptorSetLayouts.data(),
.pushConstantRangeCount = 1, .pushConstantRangeCount = 1,
.pPushConstantRanges = &pushConstantRange, .pPushConstantRanges = &pushConstantRange,
}; };
@ -279,525 +274,6 @@ bool MiscData::init( RenderDevice const& renderDevice )
SDL_free( rawData ); SDL_free( rawData );
} }
// Vertex Buffer Creation
{
vertexBufferSize = sizeof vertices[0] * vertices.size();
// TL----TR
// | \ |
// | \ |
// | \ |
// BL----BR
//
// BL -> BR -> TL
// TL -> BR -> TR
vertices = std::array{
// Bottom Left
Vertex{
.position = { -1.0f, -1.0f, 0.0f },
.color = { 0.0f, 0.0f, 1.0f },
.texCoord0 = { 0.0f, 0.0f },
},
// Bottom Right
Vertex{
.position = { 1.0f, -1.0f, 0.0f },
.color = { 1.0f, 0.0f, 0.0f },
.texCoord0 = { 1.0f, 0.0f },
},
// Top Left
Vertex{
.position = { -1.0f, 1.0f, 0.0f },
.color = { 0.0f, 1.0f, 0.0f },
.texCoord0 = { 0.0f, 1.0f },
},
// Top Right
Vertex{
.position = { 1.0f, 1.0f, 0.0f },
.color = { 1.0f, 1.0f, 0.0f },
.texCoord0 = { 1.0f, 1.0f },
}
};
VkBufferCreateInfo const bufferCreateInfo = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = vertexBufferSize,
.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
VmaAllocationCreateInfo constexpr allocationCreateInfo = {
.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
.preferredFlags = 0,
.memoryTypeBits = 0,
.pool = nullptr,
.pUserData = nullptr,
.priority = 1.0f,
};
VmaAllocationInfo allocationInfo;
VK_CHECK( vmaCreateBuffer(
renderDevice.gpuAllocator,
&bufferCreateInfo,
&allocationCreateInfo,
&vertexBuffer,
&vertexBufferAllocation,
&allocationInfo ) );
if ( allocationInfo.pMappedData )
{
memcpy( allocationInfo.pMappedData, vertices.data(), vertices.size() * sizeof vertices[0] );
}
}
// Texture
{
uint32_t width;
uint32_t height;
uint32_t numChannels = 4;
stbi_uc* textureData;
{
int w;
int h;
int nc;
int requestedChannels = static_cast<int>( numChannels );
textureData = stbi_load( "Assets/Textures/wall.jpg", &w, &h, &nc, requestedChannels );
ASSERT( nc <= requestedChannels );
if ( !textureData )
{
vkDestroyPipeline( device, Take( meshPipeline ), nullptr );
vmaDestroyBuffer( renderDevice.gpuAllocator, Take( vertexBuffer ), Take( vertexBufferAllocation ) );
SDL_LogError( SDL_LOG_CATEGORY_ERROR, "%s", stbi_failure_reason() );
return false;
}
width = static_cast<uint32_t>( w );
height = static_cast<uint32_t>( h );
}
// Calculate mips
uint32_t mipLevels =
1 + static_cast<uint32_t>( floorf( log2f( static_cast<float>( std::max( width, height ) ) ) ) );
VkImageCreateInfo const imageCreateInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = VK_FORMAT_R8G8B8A8_SRGB,
.extent = { .width = width, .height = height, .depth = 1 },
.mipLevels = mipLevels,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
VmaAllocationCreateInfo constexpr allocationCreateInfo = {
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = 0,
.preferredFlags = 0,
.memoryTypeBits = 0,
.pool = nullptr,
.pUserData = nullptr,
.priority = 1.0f,
};
VK_CHECK( vmaCreateImage(
renderDevice.gpuAllocator, &imageCreateInfo, &allocationCreateInfo, &texture, &textureAllocation, nullptr ) );
VkImageSubresourceRange const subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipLevels,
.baseArrayLayer = 0,
.layerCount = 1,
};
VkComponentMapping constexpr componentMapping = {
.r = VK_COMPONENT_SWIZZLE_IDENTITY,
.g = VK_COMPONENT_SWIZZLE_IDENTITY,
.b = VK_COMPONENT_SWIZZLE_IDENTITY,
.a = VK_COMPONENT_SWIZZLE_IDENTITY,
};
VkImageViewCreateInfo const imageViewCreateInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.image = texture,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = imageCreateInfo.format,
.components = componentMapping,
.subresourceRange = subresourceRange,
};
VK_CHECK( vkCreateImageView( device, &imageViewCreateInfo, nullptr, &textureView ) );
VkSamplerCreateInfo constexpr samplerCreateInfo = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.magFilter = VK_FILTER_LINEAR,
.minFilter = VK_FILTER_LINEAR,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
.mipLodBias = 0.0,
.anisotropyEnable = true,
.maxAnisotropy = 1.0f,
.compareEnable = false,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = VK_LOD_CLAMP_NONE,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK,
.unnormalizedCoordinates = false,
};
VK_CHECK( vkCreateSampler( device, &samplerCreateInfo, nullptr, &sampler ) );
// Staging Buffer Create
VkBuffer stagingBuffer;
VmaAllocation stagingAllocation;
{
VkBufferCreateInfo const stagingBufferCreateInfo = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = static_cast<VkDeviceSize>( width ) * height * numChannels * sizeof( textureData[0] ),
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
VmaAllocationCreateInfo constexpr stagingAllocationCreateInfo = {
.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
.preferredFlags = 0,
.memoryTypeBits = 0,
.pool = nullptr,
.pUserData = nullptr,
.priority = 1.0f,
};
VmaAllocationInfo allocationInfo;
VK_CHECK( vmaCreateBuffer(
renderDevice.gpuAllocator,
&stagingBufferCreateInfo,
&stagingAllocationCreateInfo,
&stagingBuffer,
&stagingAllocation,
&allocationInfo ) );
if ( allocationInfo.pMappedData )
{
memcpy( allocationInfo.pMappedData, textureData, stagingBufferCreateInfo.size );
}
}
// All data is copied to stagingBuffer, don't need this.
stbi_image_free( textureData );
// Staging -> Texture transfer
{
Frame& frameInUse = renderDevice.frames[0];
// This should just pass.
VK_CHECK( vkWaitForFences( device, 1, &frameInUse.frameReadyToReuse, VK_TRUE, INT64_MAX ) );
VK_CHECK( vkResetFences( device, 1, &frameInUse.frameReadyToReuse ) );
VkCommandBufferBeginInfo constexpr beginInfo = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = nullptr,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
.pInheritanceInfo = nullptr,
};
VkImageMemoryBarrier2 const creationToTransferImageBarrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT,
.srcAccessMask = VK_ACCESS_2_NONE,
.dstStageMask = VK_PIPELINE_STAGE_2_COPY_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = texture,
.subresourceRange = subresourceRange,
};
VkDependencyInfo const creationToTransferDependency = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.dependencyFlags = 0,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = 1,
.pImageMemoryBarriers = &creationToTransferImageBarrier,
};
std::array transferToReadyImageBarriers{
// transferToReadyImageBarrier
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT,
.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = texture,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipLevels-1,
.baseArrayLayer = 0,
.layerCount = 1,
},
},
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT,
.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = texture,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = mipLevels-1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
}
};
VkDependencyInfo const transferToReadyDependency = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.dependencyFlags = 0,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = static_cast<uint32_t>( transferToReadyImageBarriers.size() ),
.pImageMemoryBarriers = transferToReadyImageBarriers.data(),
};
VkImageSubresourceRange const mipLevelSubresource = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
};
std::array prepareNextMipLevelBarriers{
// prepareNextMipLevelSrcImageBarrier
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = texture,
.subresourceRange = mipLevelSubresource,
},
// prepareNextMipLevelDstImageBarrier
VkImageMemoryBarrier2{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT,
.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_BLIT_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = texture,
.subresourceRange = mipLevelSubresource,
}
};
VkDependencyInfo const prepareNextMipLevelDependency = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.dependencyFlags = 0,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = static_cast<uint32_t>( prepareNextMipLevelBarriers.size() ),
.pImageMemoryBarriers = prepareNextMipLevelBarriers.data(),
};
vkBeginCommandBuffer( frameInUse.commandBuffer, &beginInfo );
{
VkImageSubresourceLayers imageSubresourceLayers = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
};
// TODO: Ensure `bufferRowLength` and `bufferImageHeight` are not required.
VkBufferImageCopy copyRegion = {
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = imageSubresourceLayers,
.imageOffset = { 0, 0, 0 },
.imageExtent = imageCreateInfo.extent
};
// Start
vkCmdPipelineBarrier2( frameInUse.commandBuffer, &creationToTransferDependency );
// Staging -> Image L0
vkCmdCopyBufferToImage(
frameInUse.commandBuffer, stagingBuffer, texture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copyRegion );
prepareNextMipLevelBarriers[0].subresourceRange.baseMipLevel = 0;
prepareNextMipLevelBarriers[1].subresourceRange.baseMipLevel = 1;
int32_t mipSrcWidth = static_cast<int32_t>( width );
int32_t mipSrcHeight = static_cast<int32_t>( height );
int32_t mipDstWidth = std::max( mipSrcWidth / 2, 1 );
int32_t mipDstHeight = std::max( mipSrcHeight / 2, 1 );
VkImageSubresourceLayers constexpr mipSubresourceLayers = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
};
VkImageBlit2 imageBlit = {
.sType = VK_STRUCTURE_TYPE_IMAGE_BLIT_2,
.pNext = nullptr,
.srcSubresource = mipSubresourceLayers,
.srcOffsets = { { 0, 0, 0 }, { mipSrcWidth, mipSrcHeight, 1 } },
.dstSubresource = mipSubresourceLayers,
.dstOffsets = { { 0, 0, 0 }, { mipDstWidth, mipDstHeight, 1 } },
};
imageBlit.srcSubresource.mipLevel = 0;
imageBlit.dstSubresource.mipLevel = 1;
imageBlit.srcOffsets[1].x = mipSrcWidth;
imageBlit.srcOffsets[1].y = mipSrcHeight;
imageBlit.dstOffsets[1].x = mipDstWidth;
imageBlit.dstOffsets[1].y = mipDstHeight;
VkBlitImageInfo2 blitInfo = {
.sType = VK_STRUCTURE_TYPE_BLIT_IMAGE_INFO_2,
.pNext = nullptr,
.srcImage = texture,
.srcImageLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.dstImage = texture,
.dstImageLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.regionCount = 1,
.pRegions = &imageBlit,
.filter = VK_FILTER_LINEAR,
};
// MipMapping
for ( uint32_t dstMipLevel = 1; dstMipLevel < mipLevels; ++dstMipLevel )
{
vkCmdPipelineBarrier2( frameInUse.commandBuffer, &prepareNextMipLevelDependency );
vkCmdBlitImage2( frameInUse.commandBuffer, &blitInfo );
// Prep for NEXT iteration
mipSrcWidth = mipDstWidth;
mipSrcHeight = mipDstHeight;
mipDstWidth = std::max( mipSrcWidth / 2, 1 );
mipDstHeight = std::max( mipSrcHeight / 2, 1 );
imageBlit.srcSubresource.mipLevel = dstMipLevel;
imageBlit.dstSubresource.mipLevel = dstMipLevel + 1;
imageBlit.srcOffsets[1].x = mipSrcWidth;
imageBlit.srcOffsets[1].y = mipSrcHeight;
imageBlit.dstOffsets[1].x = mipDstWidth;
imageBlit.dstOffsets[1].y = mipDstHeight;
// Prep current mip level as source
prepareNextMipLevelBarriers[0].subresourceRange.baseMipLevel = dstMipLevel;
prepareNextMipLevelBarriers[1].subresourceRange.baseMipLevel = dstMipLevel + 1;
}
// End
vkCmdPipelineBarrier2( frameInUse.commandBuffer, &transferToReadyDependency );
}
vkEndCommandBuffer( frameInUse.commandBuffer );
VkSubmitInfo submitInfo = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreCount = 0,
.pWaitSemaphores = nullptr,
.pWaitDstStageMask = nullptr,
.commandBufferCount = 1,
.pCommandBuffers = &frameInUse.commandBuffer,
.signalSemaphoreCount = 0,
.pSignalSemaphores = nullptr,
};
VK_CHECK( vkQueueSubmit( renderDevice.directQueue, 1, &submitInfo, frameInUse.frameReadyToReuse ) );
// Do not reset this. Else, the frame will never be available to the main loop.
VK_CHECK( vkWaitForFences( device, 1, &frameInUse.frameReadyToReuse, VK_TRUE, INT64_MAX ) );
}
vmaDestroyBuffer( renderDevice.gpuAllocator, stagingBuffer, stagingAllocation );
}
// Model Setup
modelTransform[0].position = { 1.0f, 0.0f, 0.0f };
modelTransform[0].scale = 1.0f;
modelTransform[0].rotation =
DirectX::XMQuaternionRotationAxis( DirectX::XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f ), 0.0f );
modelTransform[1].position = { -1.0f, 0.0f, 0.0f };
modelTransform[1].scale = 1.0f;
modelTransform[1].rotation =
DirectX::XMQuaternionRotationAxis( DirectX::XMVectorSet( 1.0f, 0.0f, 0.0f, 0.0f ), 0.0f );
// Camera // Camera
{ {
cameraPosition = DirectX::XMVectorSet( 0.0f, 0.0f, -4.0f, 1.0f ); cameraPosition = DirectX::XMVectorSet( 0.0f, 0.0f, -4.0f, 1.0f );
@ -853,18 +329,18 @@ bool MiscData::init( RenderDevice const& renderDevice )
std::array poolSizes = { std::array poolSizes = {
VkDescriptorPoolSize{ VkDescriptorPoolSize{
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = renderDevice.getNumFrames(), .descriptorCount = 3,
}, },
VkDescriptorPoolSize{ VkDescriptorPoolSize{
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = renderDevice.getNumFrames(), .descriptorCount = 100,
}, },
}; };
VkDescriptorPoolCreateInfo const descriptorPoolCreateInfo = { VkDescriptorPoolCreateInfo const descriptorPoolCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
.flags = 0, .flags = 0,
.maxSets = renderDevice.getNumFrames(), .maxSets = 101,
.poolSizeCount = static_cast<uint32_t>( poolSizes.size() ), .poolSizeCount = static_cast<uint32_t>( poolSizes.size() ),
.pPoolSizes = poolSizes.data(), .pPoolSizes = poolSizes.data(),
}; };
@ -887,12 +363,6 @@ bool MiscData::init( RenderDevice const& renderDevice )
.range = sizeof CameraData, .range = sizeof CameraData,
}; };
VkDescriptorImageInfo const descriptorImageInfo = {
.sampler = sampler,
.imageView = textureView,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
std::array writeDescriptorSets = { std::array writeDescriptorSets = {
VkWriteDescriptorSet{ VkWriteDescriptorSet{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
@ -906,19 +376,6 @@ bool MiscData::init( RenderDevice const& renderDevice )
.pBufferInfo = &descriptorBufferInfo, .pBufferInfo = &descriptorBufferInfo,
.pTexelBufferView = nullptr, .pTexelBufferView = nullptr,
}, },
VkWriteDescriptorSet{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = nullptr,
.dstSet = descriptorSet,
.dstBinding = 1,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &descriptorImageInfo,
.pBufferInfo = nullptr,
.pTexelBufferView = nullptr,
}
}; };
vkUpdateDescriptorSets( vkUpdateDescriptorSets(
@ -998,12 +455,6 @@ void MiscData::destroy( RenderDevice const& renderDevice )
vkDestroyDescriptorPool( device, Take( descriptorPool ), nullptr ); vkDestroyDescriptorPool( device, Take( descriptorPool ), nullptr );
vmaDestroyBuffer( renderDevice.gpuAllocator, Take( cameraUniformBuffer ), Take( cameraUniformBufferAllocation ) ); vmaDestroyBuffer( renderDevice.gpuAllocator, Take( cameraUniformBuffer ), Take( cameraUniformBufferAllocation ) );
vkDestroySampler( device, Take( sampler ), nullptr );
vkDestroyImageView( device, Take( textureView ), nullptr );
vmaDestroyImage( renderDevice.gpuAllocator, Take( texture ), Take( textureAllocation ) );
vmaDestroyBuffer( renderDevice.gpuAllocator, Take( vertexBuffer ), Take( vertexBufferAllocation ) );
vkDestroyPipeline( device, Take( meshPipeline ), nullptr ); vkDestroyPipeline( device, Take( meshPipeline ), nullptr );
vkDestroyPipelineLayout( device, Take( pipelineLayout ), nullptr ); vkDestroyPipelineLayout( device, Take( pipelineLayout ), nullptr );
vkDestroyDescriptorSetLayout( device, Take( descriptorSetLayout ), nullptr ); vkDestroyDescriptorSetLayout( device, Take( descriptorSetLayout ), nullptr );

View File

@ -10,20 +10,6 @@
struct GlobalMemory; struct GlobalMemory;
struct RenderDevice; struct RenderDevice;
struct Vertex
{
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT3 color;
DirectX::XMFLOAT2 texCoord0;
};
struct Transform
{
DirectX::XMFLOAT3 position;
float scale;
DirectX::XMVECTOR rotation;
};
struct MiscData struct MiscData
{ {
struct CameraData struct CameraData
@ -38,20 +24,8 @@ struct MiscData
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout;
VkPipeline meshPipeline; VkPipeline meshPipeline;
VkBuffer vertexBuffer;
VmaAllocation vertexBufferAllocation;
size_t vertexBufferSize;
std::array<Vertex, 4> vertices;
VkImage texture;
VmaAllocation textureAllocation;
VkImageView textureView;
VkSampler sampler;
uint64_t _padding; // TODO: Optimize out? uint64_t _padding; // TODO: Optimize out?
std::array<Transform, 2> modelTransform;
DirectX::XMVECTOR cameraPosition; DirectX::XMVECTOR cameraPosition;
DirectX::XMVECTOR cameraTarget; DirectX::XMVECTOR cameraTarget;
DirectX::XMVECTOR cameraUp; DirectX::XMVECTOR cameraUp;

View File

@ -11,6 +11,7 @@
#include "Frame.h" #include "Frame.h"
#include "GlobalMemory.h" #include "GlobalMemory.h"
#include "MathUtil.h" #include "MathUtil.h"
#include "TextureManager.h"
RenderDevice::~RenderDevice() RenderDevice::~RenderDevice()
{ {
@ -170,13 +171,28 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c
.pQueuePriorities = &priority, .pQueuePriorities = &priority,
}; };
VkPhysicalDeviceVulkan13Features constexpr features13 = { VkPhysicalDeviceVulkan13Features features13 = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
.pNext = nullptr, .pNext = nullptr,
.synchronization2 = true, .synchronization2 = true,
.dynamicRendering = true, .dynamicRendering = true,
}; };
VkPhysicalDeviceVulkan12Features const features12 = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
.pNext = &features13,
.descriptorIndexing = true,
.shaderSampledImageArrayNonUniformIndexing = true,
.shaderStorageImageArrayNonUniformIndexing = true,
.descriptorBindingUniformBufferUpdateAfterBind = true,
.descriptorBindingSampledImageUpdateAfterBind = true,
.descriptorBindingStorageImageUpdateAfterBind = true,
.descriptorBindingUpdateUnusedWhilePending = true,
.descriptorBindingPartiallyBound = true,
.descriptorBindingVariableDescriptorCount = true,
.runtimeDescriptorArray = true,
};
VkPhysicalDeviceFeatures features = { VkPhysicalDeviceFeatures features = {
.depthClamp = true, .depthClamp = true,
.samplerAnisotropy = true, .samplerAnisotropy = true,
@ -186,7 +202,7 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c
VkDeviceCreateInfo const deviceCreateInfo = { VkDeviceCreateInfo const deviceCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.pNext = &features13, .pNext = &features12,
.flags = 0, .flags = 0,
.queueCreateInfoCount = 1, .queueCreateInfoCount = 1,
.pQueueCreateInfos = &queueCreateInfo, .pQueueCreateInfos = &queueCreateInfo,
@ -377,7 +393,9 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c
} }
std::byte* allocation = mem->allocate( sizeof( RenderDevice ), alignof( RenderDevice ) ); std::byte* allocation = mem->allocate( sizeof( RenderDevice ), alignof( RenderDevice ) );
return new ( allocation ) RenderDevice{ if ( not allocation ) return nullptr;
RenderDevice* renderDevice = new ( allocation ) RenderDevice{
instance, instance,
surface, surface,
physicalDeviceInUse, physicalDeviceInUse,
@ -393,23 +411,39 @@ RenderDevice* RenderDevice_Create( GlobalMemory* mem, RenderDevice::CreateInfo c
frames, frames,
swapchainImageCount, swapchainImageCount,
}; };
TextureManager* textureManager = TextureManager_Create( mem, renderDevice, 10000 );
if ( !textureManager )
{
SDL_LogError( SDL_LOG_CATEGORY_APPLICATION, "TextureManager failed to init" );
renderDevice->destroy();
return nullptr;
}
renderDevice->textureManager = textureManager;
ASSERT( renderDevice->textureManager );
return renderDevice;
} }
inline bool RenderDevice::isInit() const inline bool RenderDevice::isInit() const
{ {
return instance and device; return instance and device and textureManager;
} }
void RenderDevice::destroy() void RenderDevice::destroy()
{ {
if ( not isInit() ) return; if ( not isInit() ) return;
for ( Frame& frame : std::span{ frames, swapchainImageCount } ) Take( textureManager )->destroy();
for ( Frame& frame : std::span{ Take( frames ), swapchainImageCount } )
{ {
frame.destroy( *this ); frame.destroy( *this );
} }
for ( auto const& view : std::span{ swapchainViews, swapchainImageCount } ) for ( auto const& view : std::span{ Take( swapchainViews ), swapchainImageCount } )
{ {
vkDestroyImageView( device, view, nullptr ); vkDestroyImageView( device, view, nullptr );
} }
@ -465,4 +499,5 @@ RenderDevice::RenderDevice(
, swapchainViews{ swapchainViews } , swapchainViews{ swapchainViews }
, frames{ frames } , frames{ frames }
, swapchainImageCount{ swapchainImageCount } , swapchainImageCount{ swapchainImageCount }
, textureManager{ nullptr }
{} {}

View File

@ -11,6 +11,7 @@
struct GlobalMemory; struct GlobalMemory;
struct Frame; struct Frame;
struct TextureManager;
/// The Rendering backend abstraction /// The Rendering backend abstraction
/// If this fails to initialize, we crash /// If this fails to initialize, we crash
@ -43,6 +44,8 @@ struct RenderDevice
uint32_t swapchainImageCount; uint32_t swapchainImageCount;
uint32_t frameIndex = 0; uint32_t frameIndex = 0;
TextureManager* textureManager;
[[nodiscard]] bool isInit() const; [[nodiscard]] bool isInit() const;
void destroy(); void destroy();
void waitIdle() const; void waitIdle() const;

339
Blaze/TextureManager.cpp Normal file
View File

@ -0,0 +1,339 @@
#include "TextureManager.h"
#include "GlobalMemory.h"
#include "RenderDevice.h"
std::optional<TextureID> TextureManager::createTexture( VkExtent3D const extent, VkSampler sampler )
{
if ( m_freeList.empty() )
{
return std::nullopt;
}
Texture* textureSlot = reinterpret_cast<Texture*>( m_freeList.popFront() );
ASSERT( m_pRenderDevice );
RenderDevice const& renderDevice = *m_pRenderDevice;
VkFormat const format = VK_FORMAT_R8G8B8A8_SRGB;
VkImage texture;
VmaAllocation textureAllocation;
VkImageView textureView;
uint32_t const mipLevels = calculateRequiredMipLevels( extent.width, extent.height, extent.depth );
VkImageCreateInfo const imageCreateInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = format,
.extent = extent,
.mipLevels = mipLevels,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
VmaAllocationCreateInfo constexpr allocationCreateInfo = {
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
.requiredFlags = 0,
.preferredFlags = 0,
.memoryTypeBits = 0,
.pool = nullptr,
.pUserData = nullptr,
.priority = 1.0f,
};
VK_CHECK( vmaCreateImage(
renderDevice.gpuAllocator, &imageCreateInfo, &allocationCreateInfo, &texture, &textureAllocation, nullptr ) );
VkImageSubresourceRange const subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipLevels,
.baseArrayLayer = 0,
.layerCount = 1,
};
VkComponentMapping constexpr componentMapping = {
.r = VK_COMPONENT_SWIZZLE_IDENTITY,
.g = VK_COMPONENT_SWIZZLE_IDENTITY,
.b = VK_COMPONENT_SWIZZLE_IDENTITY,
.a = VK_COMPONENT_SWIZZLE_IDENTITY,
};
VkImageViewCreateInfo const imageViewCreateInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.image = texture,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = imageCreateInfo.format,
.components = componentMapping,
.subresourceRange = subresourceRange,
};
VK_CHECK( vkCreateImageView( renderDevice.device, &imageViewCreateInfo, nullptr, &textureView ) );
// NOTE: textureSlot preserves index between uses.
uint32_t index = textureSlot->index;
new ( textureSlot ) Texture{
.image = texture,
.allocation = textureAllocation,
.view = textureView,
.extent = extent,
.format = format,
.index = index,
};
uint32_t const innerIndex = index & INDEX_MASK;
// TODO: Batch all writes.
VkDescriptorImageInfo const descriptorImageInfo = {
.sampler = sampler,
.imageView = textureView,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
};
VkWriteDescriptorSet const descriptorWrite = {
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = nullptr,
.dstSet = m_descriptorSet,
.dstBinding = 0,
.dstArrayElement = innerIndex,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &descriptorImageInfo,
.pBufferInfo = nullptr,
.pTexelBufferView = nullptr,
};
vkUpdateDescriptorSets( renderDevice.device, 1, &descriptorWrite, 0, nullptr );
// NOTE: Memory hackery to create TextureID;
return std::move( *reinterpret_cast<TextureID*>( &index ) );
}
bool TextureManager::isValidID( TextureID const& rid ) const
{
uint32_t const index = *reinterpret_cast<uint32_t const*>( &rid );
uint32_t const innerIndex = index & INDEX_MASK;
if ( innerIndex > m_capacity ) return false;
return m_aTextures[innerIndex].index == index;
}
void TextureManager::freeTexture( TextureID&& rid )
{
if ( not isValidID( rid ) ) return;
Texture& texture = fetchTextureUnchecked( rid );
destroyTexture( texture );
auto _ = std::move( rid );
}
std::optional<VkImage> TextureManager::fetchImage( TextureID const& rid )
{
if ( not isValidID( rid ) ) return std::nullopt;
return fetchTextureUnchecked( rid ).image;
}
std::optional<VkImageView> TextureManager::fetchImageView( TextureID const& rid )
{
if ( not isValidID( rid ) ) return std::nullopt;
return fetchTextureUnchecked( rid ).view;
}
VkDescriptorSetLayout const& TextureManager::descriptorLayout() const
{
return m_descriptorSetLayout;
}
VkDescriptorSet const& TextureManager::descriptorSet() const
{
return m_descriptorSet;
}
void TextureManager::destroy()
{
#if defined( _DEBUG )
if ( m_count > 0 )
{
SDL_LogError( SDL_LOG_CATEGORY_ERROR, "%u textures still allocated.", m_count );
}
#endif
ASSERT( m_pRenderDevice );
RenderDevice const& renderDevice = *m_pRenderDevice;
while ( not m_freeList.empty() )
{
Texture* tex = reinterpret_cast<Texture*>( m_freeList.popFront() );
memset( tex, 0, sizeof *tex );
}
for ( Texture& tex : std::span{ m_aTextures, m_count } )
{
destroyTexture( tex );
}
m_descriptorSet = nullptr;
vkDestroyDescriptorPool( renderDevice.device, Take( m_descriptorPool ), nullptr );
vkDestroyDescriptorSetLayout( renderDevice.device, Take( m_descriptorSetLayout ), nullptr );
}
TextureManager::~TextureManager()
{
ASSERT( not m_aTextures );
}
void TextureManager::destroyTexture( Texture& tex )
{
if ( not tex.image ) return;
ASSERT( m_pRenderDevice );
uint32_t const index = tex.index;
uint32_t const innerIndex = index & INDEX_MASK;
uint32_t const generation = ( index & GENERATION_MASK ) >> GENERATION_OFFSET;
RenderDevice const& renderDevice = *m_pRenderDevice;
vkDestroyImageView( renderDevice.device, Take( tex.view ), nullptr );
vmaDestroyImage( renderDevice.gpuAllocator, Take( tex.image ), Take( tex.allocation ) );
tex.extent = {};
tex.format = VK_FORMAT_UNDEFINED;
tex.index = innerIndex | ( generation + 1 ) << GENERATION_OFFSET;
// NOTE: DO NOT EDIT INNER INDEX.
ASSERT( innerIndex == ( tex.index & INDEX_MASK ) and "Index should not be modified" );
ASSERT( tex.index > index and "Generation should increase." );
m_freeList.pushBack( reinterpret_cast<FreeList::Node*>( &tex ) );
}
uint32_t TextureManager::calculateRequiredMipLevels( uint32_t const w, uint32_t const h, uint32_t const d )
{
uint32_t const maxDim = std::max( std::max( w, h ), d );
return 1 + static_cast<uint32_t>( floorf( log2f( static_cast<float>( maxDim ) ) ) );
}
Texture& TextureManager::fetchTextureUnchecked( TextureID const& rid )
{
uint32_t const index = *reinterpret_cast<uint32_t const*>( &rid );
uint32_t const innerIndex = index & INDEX_MASK;
return m_aTextures[innerIndex];
}
TextureManager::TextureManager(
RenderDevice* pRenderDevice,
Texture* aTextures,
uint32_t const capacity,
VkDescriptorSetLayout const setLayout,
VkDescriptorPool const pool,
VkDescriptorSet const descriptorSet )
: m_pRenderDevice{ pRenderDevice }
, m_aTextures{ aTextures }
, m_count{ 0 }
, m_capacity{ capacity }
, m_descriptorSetLayout{ setLayout }
, m_descriptorPool{ pool }
, m_descriptorSet{ descriptorSet }
{
uint32_t i = 0;
for ( Texture& tex : std::span{ m_aTextures, m_capacity } )
{
// Default Generation is 1
tex.index = i++ | ( 1 << GENERATION_OFFSET );
m_freeList.pushFront( reinterpret_cast<FreeList::Node*>( &tex ) );
}
}
TextureManager* TextureManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t const maxCount )
{
Texture* textures = reinterpret_cast<Texture*>( mem->allocate( maxCount * sizeof( Texture ), alignof( Texture ) ) );
if ( not textures ) return nullptr;
VkDescriptorSetLayoutBinding const descriptorSetLayoutBinding{
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = maxCount,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = nullptr,
};
VkDescriptorBindingFlags flags = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT |
VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT |
VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT;
VkDescriptorSetLayoutBindingFlagsCreateInfo const bindlessBinding = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO,
.pNext = nullptr,
.bindingCount = 1,
.pBindingFlags = &flags,
};
VkDescriptorSetLayoutCreateInfo const descriptorSetLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = &bindlessBinding,
.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT,
.bindingCount = 1,
.pBindings = &descriptorSetLayoutBinding,
};
VkDescriptorSetLayout descriptorSetLayout;
VK_CHECK( vkCreateDescriptorSetLayout(
renderDevice->device, &descriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout ) );
VkDescriptorPoolSize const poolSize = {
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = maxCount,
};
VkDescriptorPoolCreateInfo const descriptorPoolCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = nullptr,
.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT,
.maxSets = 1,
.poolSizeCount = 1,
.pPoolSizes = &poolSize,
};
VkDescriptorPool descriptorPool;
VK_CHECK( vkCreateDescriptorPool( renderDevice->device, &descriptorPoolCreateInfo, nullptr, &descriptorPool ) );
VkDescriptorSetAllocateInfo const descriptorSetAllocateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = nullptr,
.descriptorPool = descriptorPool,
.descriptorSetCount = 1,
.pSetLayouts = &descriptorSetLayout,
};
VkDescriptorSet descriptorSet;
VK_CHECK( vkAllocateDescriptorSets( renderDevice->device, &descriptorSetAllocateInfo, &descriptorSet ) );
std::byte* allocation = mem->allocate( sizeof( TextureManager ), alignof( TextureManager ) );
if ( not allocation ) return nullptr;
return new ( allocation )
TextureManager{ renderDevice, textures, maxCount, descriptorSetLayout, descriptorPool, descriptorSet };
}

242
Blaze/TextureManager.h Normal file
View File

@ -0,0 +1,242 @@
#pragma once
#include <optional>
#include <span>
#include <volk.h>
#include <vma/vk_mem_alloc.h>
#include "MacroUtils.h"
#include "RenderDevice.h"
struct GlobalMemory;
struct RenderDevice;
struct FreeListNode
{
FreeListNode* pNext;
FreeListNode* pPrev;
};
struct FreeList
{
using Node = FreeListNode;
struct Iterator
{
FreeListNode* pIter;
Iterator& operator++()
{
pIter = pIter->pNext;
return *this;
}
bool operator==( Iterator const& other ) const
{
return this->pIter == other.pIter;
}
FreeListNode& operator*()
{
return *pIter;
}
};
private:
FreeListNode m_head;
FreeListNode m_tail;
public:
FreeList() : m_head{ .pNext = &m_tail, .pPrev = nullptr }, m_tail{ .pNext = nullptr, .pPrev = &m_head }
{}
void pushBack( Node* pNode )
{
Node* prev = m_tail.pPrev;
// Set prev as previous of pNode
prev->pNext = pNode;
pNode->pPrev = prev;
// Set tail as next of pNode
pNode->pNext = &m_tail;
m_tail.pPrev = pNode;
}
void pushFront( Node* pNode )
{
Node* next = m_head.pNext;
// Set next as next of pNode
next->pPrev = pNode;
pNode->pNext = next;
// Set head as prev of pNode
pNode->pPrev = &m_head;
m_head.pNext = pNode;
}
Node* popFront()
{
ASSERT( not empty() );
Node* element = m_head.pNext;
element->pPrev->pNext = element->pNext;
element->pNext->pPrev = element->pPrev;
return element;
}
[[nodiscard]] bool empty() const
{
return m_head.pNext == &m_tail;
}
Iterator begin()
{
return { m_head.pNext };
}
Iterator end()
{
return { &m_tail };
}
FreeList( FreeList&& ) = delete;
FreeList( FreeList const& ) = delete;
FreeList& operator=( FreeList const& ) = delete;
FreeList& operator=( FreeList&& ) = delete;
~FreeList() = default;
};
template <typename T>
struct RID
{
private:
uint32_t m_index = 0;
explicit RID( uint32_t const index ) : m_index{ index }
{}
public:
RID() = default;
// No copy
RID( RID const& ) = delete;
RID& operator=( RID const& ) = delete;
// Move allowed
RID( RID&& other ) noexcept;
RID& operator=( RID&& other ) noexcept;
static RID null()
{
return {};
}
operator bool() const
{
return m_index == 0;
}
};
template <typename T>
RID<T>::RID( RID&& other ) noexcept : m_index{ other.m_index }
{
other.m_index = 0;
}
template <typename T>
RID<T>& RID<T>::operator=( RID&& other ) noexcept
{
if ( this == &other ) return *this;
m_index = other.m_index;
other.m_index = 0;
return *this;
}
struct Texture
{
VkImage image;
VmaAllocation allocation;
VkImageView view;
VkExtent3D extent;
VkFormat format;
uint32_t index;
};
static_assert( sizeof( Texture ) > sizeof( FreeListNode ) and "Texture is used intrusively by FreeList" );
static_assert(
offsetof( Texture, index ) >= sizeof( FreeListNode ) and "Index should not be overwritten even in invalid state" );
using TextureID = RID<Texture>;
struct TextureManager
{
private:
constexpr static uint32_t INDEX_MASK = 0x0007FFFF;
constexpr static uint32_t GENERATION_MASK = ~INDEX_MASK;
constexpr static uint32_t GENERATION_OFFSET = 19;
static_assert(
( ( GENERATION_MASK >> GENERATION_OFFSET & 0x1 ) == 0x1 ) and
( ( GENERATION_MASK >> ( GENERATION_OFFSET - 1 ) & 0x1 ) != 0x1 ) and "Checks boundary" );
RenderDevice* m_pRenderDevice;
// Texture Manager
Texture* m_aTextures;
uint32_t m_count;
uint32_t m_capacity;
FreeList m_freeList;
// Bindless Descriptor Info
VkDescriptorSetLayout m_descriptorSetLayout;
VkDescriptorPool m_descriptorPool;
VkDescriptorSet m_descriptorSet;
void destroyTexture( Texture& tex );
Texture& fetchTextureUnchecked( TextureID const& rid );
public:
static uint32_t calculateRequiredMipLevels( uint32_t w, uint32_t h, uint32_t d );
[[nodiscard]] bool isValidID( TextureID const& rid ) const;
// [[nodiscard]] std::optional<TextureID> createTexture( VkExtent3D extent );
void freeTexture( TextureID&& rid );
DEPRECATE_JULY_2025
[[nodiscard]] std::optional<TextureID> createTexture( VkExtent3D extent, VkSampler sampler );
DEPRECATE_JULY_2025
std::optional<VkImage> fetchImage( TextureID const& rid );
DEPRECATE_JULY_2025
std::optional<VkImageView> fetchImageView( TextureID const& rid );
[[nodiscard]] VkDescriptorSetLayout const& descriptorLayout() const;
[[nodiscard]] VkDescriptorSet const& descriptorSet() const;
//
TextureManager(
RenderDevice* pRenderDevice,
Texture* aTextures,
uint32_t capacity,
VkDescriptorSetLayout setLayout,
VkDescriptorPool pool,
VkDescriptorSet descriptorSet );
void destroy();
TextureManager( TextureManager const& other ) = delete;
TextureManager( TextureManager&& other ) noexcept = delete;
TextureManager& operator=( TextureManager const& other ) = delete;
TextureManager& operator=( TextureManager&& other ) noexcept = delete;
~TextureManager();
};
TextureManager* TextureManager_Create( GlobalMemory* mem, RenderDevice* renderDevice, uint32_t maxCount );