Compare commits

..

No commits in common. "fd9ceae67d9d327d1cc3f565c08cb986cf0a095f" and "e7d74e6b0f656ce962dc6ceae99c47d726e9d629" have entirely different histories.

21 changed files with 957 additions and 1295 deletions

1
.gitignore vendored
View File

@ -613,4 +613,3 @@ $RECYCLE.BIN/
# Windows shortcuts # Windows shortcuts
*.lnk *.lnk
*.spv

View File

@ -3,38 +3,35 @@
#include <SDL3/SDL_log.h> #include <SDL3/SDL_log.h>
#include "GlobalMemory.h" #include "GlobalMemory.h"
#include "MiscData.h"
#include "RenderDevice.h" #include "RenderDevice.h"
#include "MiscData.h"
bool AppState::isInit() const bool AppState::isInit() const
{ {
return window and renderDevice and renderDevice->isInit(); return window and renderDevice and renderDevice->isInit();
} }
void AppState::destroy() void AppState::cleanup()
{ {
if (!isInit()) return; if (!isInit()) return;
renderDevice->waitIdle(); renderDevice->waitIdle();
Take( miscData )->destroy( *renderDevice ); Take(miscData)->cleanup(*renderDevice);
Take( renderDevice )->destroy(); Take(renderDevice)->cleanup();
SDL_DestroyWindow(Take(window)); SDL_DestroyWindow(Take(window));
} }
AppState::AppState( SDL_Window* window, RenderDevice* renderDevice, MiscData* miscData ) AppState::AppState(SDL_Window* window, RenderDevice* renderDevice, MiscData* miscData): window{ window }
: window{ window }
, renderDevice{ renderDevice } , renderDevice{ renderDevice }
, miscData{ miscData } {} , miscData{ miscData }
{
}
AppState* CreateAppState(GlobalMemory* memory, uint32_t const width, uint32_t const height) AppState* CreateAppState(GlobalMemory* memory, uint32_t const width, uint32_t const height)
{ {
SDL_Window* window = SDL_CreateWindow( SDL_Window* window = SDL_CreateWindow("Blaze Test", static_cast<int>(width), static_cast<int>(height), SDL_WINDOW_VULKAN);
"Blaze Test",
static_cast<int>(width),
static_cast<int>(height),
SDL_WINDOW_VULKAN );
if (!window) if (!window)
{ {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", SDL_GetError()); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", SDL_GetError());
@ -63,5 +60,5 @@ AppState* CreateAppState( GlobalMemory* memory, uint32_t const width, uint32_t c
AppState::~AppState() AppState::~AppState()
{ {
ASSERT( !isInit() ); cleanup();
} }

View File

@ -2,9 +2,8 @@
#include <memory> #include <memory>
struct SDL_Window;
struct GlobalMemory; struct GlobalMemory;
struct SDL_Window;
struct RenderDevice; struct RenderDevice;
struct MiscData; struct MiscData;
@ -14,9 +13,8 @@ struct AppState
RenderDevice* renderDevice; RenderDevice* renderDevice;
MiscData* miscData; MiscData* miscData;
[[nodiscard]] [[nodiscard]] bool isInit() const;
bool isInit() const; void cleanup();
void destroy();
AppState(SDL_Window* window, RenderDevice* renderDevice, MiscData* miscData); AppState(SDL_Window* window, RenderDevice* renderDevice, MiscData* miscData);

View File

@ -10,7 +10,6 @@
#define SDL_MAIN_USE_CALLBACKS 1 #define SDL_MAIN_USE_CALLBACKS 1
#include <memory> #include <memory>
#include <glm/ext/matrix_transform.hpp>
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <SDL3/SDL_main.h> #include <SDL3/SDL_main.h>
#include <SDL3/SDL_filesystem.h> #include <SDL3/SDL_filesystem.h>
@ -57,7 +56,8 @@ SDL_AppResult SDL_AppInit( void** pAppState, int, char** )
Blaze::Global::g_Memory.init(128_MiB); Blaze::Global::g_Memory.init(128_MiB);
*pAppState = CreateAppState(&Blaze::Global::g_Memory, WIDTH, HEIGHT); *pAppState = CreateAppState(&Blaze::Global::g_Memory, WIDTH, HEIGHT);
if ( !*pAppState ) return SDL_APP_FAILURE; if (!*pAppState)
return SDL_APP_FAILURE;
AppState& appState = *static_cast<AppState*>(*pAppState); AppState& appState = *static_cast<AppState*>(*pAppState);
@ -69,8 +69,6 @@ SDL_AppResult SDL_AppInit( void** pAppState, int, char** )
return SDL_APP_CONTINUE; return SDL_APP_CONTINUE;
} }
char g_buf[1000];
SDL_AppResult SDL_AppIterate(void* appstate) SDL_AppResult SDL_AppIterate(void* appstate)
{ {
AppState& appState = *static_cast<AppState*>(appstate); AppState& appState = *static_cast<AppState*>(appstate);
@ -78,36 +76,11 @@ SDL_AppResult SDL_AppIterate( void* appstate )
MiscData& misc = *appState.miscData; MiscData& misc = *appState.miscData;
Frame& currentFrame = renderDevice.frames[renderDevice.frameIndex]; Frame& currentFrame = renderDevice.frames[renderDevice.frameIndex];
VK_CHECK( VK_CHECK(vkWaitForFences(renderDevice.device, 1, &currentFrame.frameReadyToReuse, VK_TRUE, std::numeric_limits<uint32_t>::max()));
vkWaitForFences(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.
uint64_t const previousCounter = misc.previousCounter;
uint64_t const currentCounter = SDL_GetPerformanceCounter();
uint64_t const deltaCount = currentCounter - previousCounter;
uint64_t const perfFreq = SDL_GetPerformanceFrequency();
double const deltaTime = static_cast<double>(deltaCount) / static_cast<double>(perfFreq);
misc.previousCounter = currentCounter;
double deltaTimeMs = deltaTime * 1000.0;
double fps = 1.0 / deltaTime;
auto _ = sprintf_s<1000>( g_buf, "%.2f fps %.5fms %llu -> %llu", fps, deltaTimeMs, previousCounter, currentCounter );
SDL_SetWindowTitle( appState.window, g_buf );
misc.cameraData.modelMatrix = glm::rotate(
misc.cameraData.modelMatrix,
glm::radians( 60.0f ) * static_cast<float>(deltaTime),
glm::vec3{ 0.0f, 1.0f, 0.0f } );
memcpy( misc.cameraUniformBufferPtr, &misc.cameraData, sizeof misc.cameraData );
uint32_t currentImageIndex; uint32_t currentImageIndex;
VK_CHECK( VK_CHECK(vkAcquireNextImageKHR(renderDevice.device, renderDevice.swapchain, std::numeric_limits<uint32_t>::max(), currentFrame.imageAcquiredSemaphore, nullptr, &currentImageIndex));
vkAcquireNextImageKHR(renderDevice.device, renderDevice.swapchain, std::numeric_limits<uint32_t>::max(),
currentFrame.imageAcquiredSemaphore, nullptr, &currentImageIndex) );
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));
@ -175,19 +148,9 @@ SDL_AppResult SDL_AppIterate( void* appstate )
vkCmdSetScissor(cmd, 0, 1, &scissor); vkCmdSetScissor(cmd, 0, 1, &scissor);
// Render Something? // Render Something?
vkCmdBindPipeline( cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.meshPipeline ); vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, misc.trianglePipeline);
VkDeviceSize constexpr offset = 0; vkCmdDraw(cmd, 3, 1, 0, 0);
vkCmdBindVertexBuffers( cmd, 0, 1, &misc.vertexBuffer, &offset );
vkCmdBindDescriptorSets(
cmd,
VK_PIPELINE_BIND_POINT_GRAPHICS,
misc.pipelineLayout,
0,
1,
&misc.descriptorSet,
0,
nullptr );
vkCmdDraw( cmd, static_cast<uint32_t>(misc.vertices.size()), 1, 0, 0 );
} }
vkCmdEndRendering(cmd); vkCmdEndRendering(cmd);
vkCmdPipelineBarrier2(cmd, &misc.renderToPresentDependency); vkCmdPipelineBarrier2(cmd, &misc.renderToPresentDependency);
@ -240,7 +203,7 @@ void SDL_AppQuit( void* appstate, SDL_AppResult )
{ {
AppState* appState = static_cast<AppState*> (appstate); AppState* appState = static_cast<AppState*> (appstate);
appState->destroy(); appState->cleanup();
Blaze::Global::g_Memory.destroy(); Blaze::Global::g_Memory.destroy();
} }

View File

@ -163,7 +163,7 @@
</SubType> </SubType>
</None> </None>
<None Include="README.md" /> <None Include="README.md" />
<CustomBuild Include="Mesh.slang"> <CustomBuild Include="Triangle.slang">
<FileType>Document</FileType> <FileType>Document</FileType>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">slangc %(FullPath) -profile sm_6_6 -target spirv -o %(Filename).spv</Command> <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">slangc %(FullPath) -profile sm_6_6 -target spirv -o %(Filename).spv</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).spv</Outputs> <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).spv</Outputs>
@ -183,6 +183,7 @@
<ClInclude Include="AppState.h" /> <ClInclude Include="AppState.h" />
<ClInclude Include="Frame.h" /> <ClInclude Include="Frame.h" />
<ClInclude Include="GlobalMemory.h" /> <ClInclude Include="GlobalMemory.h" />
<ClInclude Include="MemoryUtils.h" />
<ClInclude Include="MacroUtils.h" /> <ClInclude Include="MacroUtils.h" />
<ClInclude Include="MathUtil.h" /> <ClInclude Include="MathUtil.h" />
<ClInclude Include="MiscData.h" /> <ClInclude Include="MiscData.h" />

View File

@ -58,7 +58,7 @@
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<CustomBuild Include="Mesh.slang"> <CustomBuild Include="Triangle.slang">
<Filter>Shader Files</Filter> <Filter>Shader Files</Filter>
</CustomBuild> </CustomBuild>
</ItemGroup> </ItemGroup>
@ -75,6 +75,9 @@
<ClInclude Include="MathUtil.h"> <ClInclude Include="MathUtil.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="MemoryUtils.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="AppState.h"> <ClInclude Include="AppState.h">
<Filter>Header Files</Filter> <Filter>Header Files</Filter>
</ClInclude> </ClInclude>

View File

@ -45,7 +45,7 @@ Frame::Frame( VkDevice const device, uint32_t const directQueueFamilyIndex )
VK_CHECK(vkCreateFence(device, &fenceCreateInfo, nullptr, &frameReadyToReuse)); VK_CHECK(vkCreateFence(device, &fenceCreateInfo, nullptr, &frameReadyToReuse));
} }
void Frame::destroy( RenderDevice const& renderDevice ) void Frame::cleanup(RenderDevice const& renderDevice)
{ {
if (!isInit()) return; if (!isInit()) return;

View File

@ -17,7 +17,8 @@ struct Frame
Frame(VkDevice device, uint32_t directQueueFamilyIndex); Frame(VkDevice device, uint32_t directQueueFamilyIndex);
void destroy( RenderDevice const& renderDevice ); void cleanup(RenderDevice const& renderDevice);
~Frame(); ~Frame();
}; };

View File

@ -25,13 +25,7 @@ Byte* GlobalMemory::allocate( size_t const size )
Byte* retVal = memory; Byte* retVal = memory;
memory += size; memory += size;
available -= size; available -= size;
SDL_LogInfo( SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "ALLOC: %p -> %p (%llu) (avail: %llu)", reinterpret_cast<void*>(retVal), reinterpret_cast<void*>(memory), size, available);
SDL_LOG_CATEGORY_SYSTEM,
"ALLOC: %p -> %p (%llu) (avail: %llu)",
reinterpret_cast<void*>(retVal),
reinterpret_cast<void*>(memory),
size,
available );
return retVal; return retVal;
} }
@ -63,8 +57,8 @@ GlobalMemory::State GlobalMemory::getState() const
void GlobalMemory::restoreState(State const& state) void GlobalMemory::restoreState(State const& state)
{ {
ASSERT( memory >= state.memory ); //< Behind top of allocator assert(memory >= state.memory); //< Behind top of allocator
ASSERT( memory - (capacity - available) <= state.memory ); //< Ahead of start of allocator assert(memory - (capacity - available) <= state.memory); //< Ahead of start of allocator
SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "RESTORE: %p %llu", reinterpret_cast<void*>(memory), available); SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "RESTORE: %p %llu", reinterpret_cast<void*>(memory), available);
memory = state.memory; memory = state.memory;
available = state.available; available = state.available;

View File

@ -18,13 +18,13 @@ struct GlobalMemory
size_t available; size_t available;
size_t capacity; size_t capacity;
void init( size_t size ); void init(size_t const size);
void destroy(); void destroy();
Byte* allocate( size_t size ); Byte* allocate(size_t const size);
Byte* allocate( size_t size, size_t alignment ); Byte* allocate(size_t const size, size_t const alignment);
// Do not do any permanent allocations after calling this. // Do not do any permanent allocations after calling this.
[[nodiscard]] State getState() const; [[nodiscard]] State getState() const;

10
MemoryUtils.h Normal file
View File

@ -0,0 +1,10 @@
#pragma once
#include <foonathan/memory/memory_arena.hpp>
#include <foonathan/memory/memory_stack.hpp>
#include <foonathan/memory/temporary_allocator.hpp>
using global_allocator_t = foonathan::memory::memory_stack<foonathan::memory::virtual_block_allocator>;
using subsystem_allocator_t = foonathan::memory::memory_stack<foonathan::memory::fixed_block_allocator<global_allocator_t>>;
using temporary_allocator_t = foonathan::memory::temporary_allocator;

View File

@ -6,21 +6,16 @@
#include "MacroUtils.h" #include "MacroUtils.h"
#include "RenderDevice.h" #include "RenderDevice.h"
#include <glm/gtc/matrix_transform.hpp>
void MiscData::init(RenderDevice const& renderDevice) void MiscData::init(RenderDevice const& renderDevice)
{ {
VkDevice const device = renderDevice.device; VkDevice const device = renderDevice.device;
previousCounter = 0;
// Pipeline Creation
{ {
size_t dataSize; size_t dataSize;
void* rawData = SDL_LoadFile( "Mesh.spv", &dataSize ); void* rawData = SDL_LoadFile("Triangle.spv", &dataSize);
ASSERT(dataSize % 4 == 0); ASSERT(dataSize % 4 == 0);
if ( !rawData ) if (not rawData)
{ {
SDL_LogError(SDL_LOG_CATEGORY_SYSTEM, "%s", SDL_GetError()); SDL_LogError(SDL_LOG_CATEGORY_SYSTEM, "%s", SDL_GetError());
abort(); abort();
@ -39,29 +34,12 @@ void MiscData::init( RenderDevice const& renderDevice )
VkShaderModule shaderModule; VkShaderModule shaderModule;
VK_CHECK(vkCreateShaderModule(device, &shaderModuleCreateInfo, nullptr, &shaderModule)); VK_CHECK(vkCreateShaderModule(device, &shaderModuleCreateInfo, nullptr, &shaderModule));
VkDescriptorSetLayoutBinding constexpr descriptorSetLayoutBinding = { VkPipelineLayoutCreateInfo constexpr pipelineLayoutCreateInfo = {
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
.pImmutableSamplers = nullptr,
};
VkDescriptorSetLayoutCreateInfo const descriptorSetLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.bindingCount = 1,
.pBindings = &descriptorSetLayoutBinding,
};
VK_CHECK( vkCreateDescriptorSetLayout(device, &descriptorSetLayoutCreateInfo, nullptr, &descriptorSetLayout) );
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 = 0,
.pSetLayouts = &descriptorSetLayout, .pSetLayouts = nullptr,
.pushConstantRangeCount = 0, .pushConstantRangeCount = 0,
.pPushConstantRanges = nullptr, .pPushConstantRanges = nullptr,
}; };
@ -88,42 +66,21 @@ void MiscData::init( RenderDevice const& renderDevice )
} }
}; };
VkVertexInputBindingDescription constexpr bindingDescription = { VkPipelineVertexInputStateCreateInfo constexpr vertexInputState = {
.binding = 0,
.stride = sizeof( Vertex ),
.inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
};
std::array attributeDescriptions = {
VkVertexInputAttributeDescription{
.location = 0,
.binding = 0,
.format = VK_FORMAT_R32G32B32A32_SFLOAT,
.offset = offsetof( Vertex, position ),
},
VkVertexInputAttributeDescription{
.location = 1,
.binding = 0,
.format = VK_FORMAT_R32G32B32A32_SFLOAT,
.offset = offsetof( Vertex, color ),
},
};
VkPipelineVertexInputStateCreateInfo const vertexInputState = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
.flags = 0, .flags = 0,
.vertexBindingDescriptionCount = 1, .vertexBindingDescriptionCount = 0,
.pVertexBindingDescriptions = &bindingDescription, .pVertexBindingDescriptions = nullptr,
.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()), .vertexAttributeDescriptionCount = 0,
.pVertexAttributeDescriptions = attributeDescriptions.data(), .pVertexAttributeDescriptions = nullptr,
}; };
VkPipelineInputAssemblyStateCreateInfo constexpr inputAssembly = { VkPipelineInputAssemblyStateCreateInfo constexpr inputAssembly = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
.flags = 0, .flags = 0,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
.primitiveRestartEnable = VK_FALSE, .primitiveRestartEnable = VK_FALSE,
}; };
@ -253,191 +210,13 @@ void MiscData::init( RenderDevice const& renderDevice )
.basePipelineIndex = 0, .basePipelineIndex = 0,
}; };
VK_CHECK( vkCreateGraphicsPipelines(device, nullptr, 1, &graphicsPipelineCreateInfo, nullptr, &meshPipeline) ); VK_CHECK(vkCreateGraphicsPipelines(device, nullptr, 1, &graphicsPipelineCreateInfo, nullptr, &trianglePipeline));
vkDestroyShaderModule(device, shaderModule, nullptr); vkDestroyShaderModule(device, shaderModule, nullptr);
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, 1.0f },
.color = { 0.0f, 0.0f, 1.0f, 1.0f },
},
// Bottom Right
Vertex{
.position = { 1.0f, -1.0f, 0.0f, 1.0f },
.color = { 1.0f, 0.0f, 0.0f, 1.0f },
},
// Top Left
Vertex{
.position = { -1.0f, 1.0f, 0.0f, 1.0f },
.color = { 0.0f, 1.0f, 0.0f, 1.0f },
},
// Top Right
Vertex{
.position = { 1.0f, 1.0f, 0.0f, 1.0f },
.color = { 1.0f, 1.0f, 0.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] );
}
}
// Camera
{
cameraPosition = glm::vec3{ 0.0f, 0.0f, -5.0f };
cameraTarget = glm::vec3{ 0.0f, 0.0f, 0.0f };
cameraData.modelMatrix = glm::mat4{ 1.0f };
cameraData.viewMatrix = glm::lookAt( cameraPosition, cameraTarget, glm::vec3{ 0.0f, 1.0f, 0.0f } );
cameraData.projectionMatrix = glm::perspective( glm::radians( 70.0f ), 16.0f / 9.0f, 0.1f, 1000.0f );
cameraUniformBufferSize = sizeof( CameraData );
VkBufferCreateInfo const bufferCreateInfo = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = cameraUniformBufferSize,
.usage = VK_BUFFER_USAGE_UNIFORM_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,
&cameraUniformBuffer,
&cameraUniformBufferAllocation,
&allocationInfo) );
if ( allocationInfo.pMappedData )
{
memcpy( allocationInfo.pMappedData, &cameraData, sizeof cameraData );
cameraUniformBufferPtr = static_cast<uint8_t*>(allocationInfo.pMappedData);
}
}
// Descriptors
{
VkDescriptorPoolSize const poolSize = {
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = renderDevice.getNumFrames(),
};
VkDescriptorPoolCreateInfo const descriptorPoolCreateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.maxSets = renderDevice.getNumFrames(),
.poolSizeCount = 1,
.pPoolSizes = &poolSize,
};
VK_CHECK( vkCreateDescriptorPool(device, &descriptorPoolCreateInfo, nullptr, &descriptorPool) );
VkDescriptorSetAllocateInfo const descriptorSetAllocateInfo = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = nullptr,
.descriptorPool = descriptorPool,
.descriptorSetCount = 1,
.pSetLayouts = &descriptorSetLayout,
};
VK_CHECK( vkAllocateDescriptorSets(device, &descriptorSetAllocateInfo, &descriptorSet) );
VkDescriptorBufferInfo const descriptorBufferInfo = {
.buffer = cameraUniformBuffer,
.offset = 0,
.range = sizeof CameraData,
};
VkWriteDescriptorSet writeDescriptorSet = {
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.pNext = nullptr,
.dstSet = descriptorSet,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.pImageInfo = nullptr,
.pBufferInfo = &descriptorBufferInfo,
.pTexelBufferView = nullptr,
};
vkUpdateDescriptorSets( device, 1, &writeDescriptorSet, 0, nullptr );
}
// Barrier Creation
{
acquireToRenderBarrier = { acquireToRenderBarrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2, .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr, .pNext = nullptr,
@ -500,17 +279,11 @@ void MiscData::init( RenderDevice const& renderDevice )
.pImageMemoryBarriers = &renderToPresentBarrier, .pImageMemoryBarriers = &renderToPresentBarrier,
}; };
} }
}
void MiscData::destroy( RenderDevice const& renderDevice ) void MiscData::cleanup(RenderDevice const& renderDevice)
{ {
VkDevice const device = renderDevice.device; VkDevice const device = renderDevice.device;
vkDestroyDescriptorPool( device, Take( descriptorPool ), nullptr ); vkDestroyPipeline(device, trianglePipeline, nullptr);
vmaDestroyBuffer( renderDevice.gpuAllocator, Take( cameraUniformBuffer ), Take( cameraUniformBufferAllocation ) ); vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vmaDestroyBuffer( renderDevice.gpuAllocator, Take( vertexBuffer ), Take( vertexBufferAllocation ) );
vkDestroyPipeline( device, Take( meshPipeline ), nullptr );
vkDestroyPipelineLayout( device, Take( pipelineLayout ), nullptr );
vkDestroyDescriptorSetLayout( device, Take( descriptorSetLayout ), nullptr );
} }

View File

@ -1,49 +1,13 @@
#pragma once #pragma once
#include <array>
#include <volk.h> #include <volk.h>
#include <vma/vk_mem_alloc.h>
#include <glm/glm.hpp>
struct RenderDevice; struct RenderDevice;
struct Vertex
{
float position[4];
float color[4];
};
struct MiscData struct MiscData
{ {
struct CameraData
{
glm::mat4x4 modelMatrix;
glm::mat4x4 viewMatrix;
glm::mat4x4 projectionMatrix;
};
uint64_t previousCounter;
VkDescriptorSetLayout descriptorSetLayout;
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout;
VkPipeline meshPipeline; VkPipeline trianglePipeline;
VkBuffer vertexBuffer;
VmaAllocation vertexBufferAllocation;
size_t vertexBufferSize;
std::array<Vertex, 4> vertices;
glm::vec3 cameraPosition;
glm::vec3 cameraTarget;
CameraData cameraData;
VkBuffer cameraUniformBuffer;
VmaAllocation cameraUniformBufferAllocation;
size_t cameraUniformBufferSize;
uint8_t* cameraUniformBufferPtr;
VkDescriptorPool descriptorPool;
VkDescriptorSet descriptorSet;
VkImageMemoryBarrier2 acquireToRenderBarrier; VkImageMemoryBarrier2 acquireToRenderBarrier;
VkDependencyInfo acquireToRenderDependency; VkDependencyInfo acquireToRenderDependency;
@ -51,5 +15,5 @@ struct MiscData
VkDependencyInfo renderToPresentDependency; VkDependencyInfo renderToPresentDependency;
void init(RenderDevice const& renderDevice); void init(RenderDevice const& renderDevice);
void destroy( RenderDevice const& renderDevice ); void cleanup(RenderDevice const& renderDevice);
}; };

View File

@ -62,7 +62,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
VkPhysicalDevice physicalDeviceInUse = nullptr; VkPhysicalDevice physicalDeviceInUse = nullptr;
VkDevice device = nullptr; VkDevice device = nullptr;
VmaAllocator gpuAllocator = nullptr; VmaAllocator gpuAllocator = nullptr;
std::optional<uint32_t> directQueueFamilyIndex = std::nullopt; std::optional<uint32_t> directQueueFamilyIndex;
VkQueue directQueue = nullptr; VkQueue directQueue = nullptr;
// Create Device and Queue // Create Device and Queue
{ {
@ -72,8 +72,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
VK_CHECK(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr)); VK_CHECK(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr));
SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Found %u GPUs", physicalDeviceCount); SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Found %u GPUs", physicalDeviceCount);
VkPhysicalDevice* physicalDevices = reinterpret_cast<VkPhysicalDevice*>(mem->allocate( VkPhysicalDevice* physicalDevices = reinterpret_cast<VkPhysicalDevice*>(mem->allocate(sizeof(VkPhysicalDevice) * physicalDeviceCount));
sizeof( VkPhysicalDevice ) * physicalDeviceCount ));
VK_CHECK(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices)); VK_CHECK(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices));
for (VkPhysicalDevice const physicalDevice : std::span{ physicalDevices, physicalDeviceCount }) for (VkPhysicalDevice const physicalDevice : std::span{ physicalDevices, physicalDeviceCount })
@ -85,9 +84,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "GPU: %s", properties.deviceName); SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "GPU: %s", properties.deviceName);
SDL_LogInfo( SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "- API Version %d.%d.%d",
SDL_LOG_CATEGORY_GPU,
"- API Version %d.%d.%d",
VK_API_VERSION_MAJOR(properties.apiVersion), VK_API_VERSION_MAJOR(properties.apiVersion),
VK_API_VERSION_MINOR(properties.apiVersion), VK_API_VERSION_MINOR(properties.apiVersion),
VK_API_VERSION_PATCH(properties.apiVersion)); VK_API_VERSION_PATCH(properties.apiVersion));
@ -105,8 +102,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
uint32_t queueFamilyCount; uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
VkQueueFamilyProperties* queueFamilyProperties = reinterpret_cast<VkQueueFamilyProperties*>(mem->allocate( VkQueueFamilyProperties* queueFamilyProperties = reinterpret_cast<VkQueueFamilyProperties*>(mem->allocate(sizeof(VkQueueFamilyProperties) * queueFamilyCount));
sizeof( VkQueueFamilyProperties ) * queueFamilyCount ));
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilyProperties); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilyProperties);
for (uint32_t queueFamilyIndex = 0; queueFamilyIndex != queueFamilyCount; for (uint32_t queueFamilyIndex = 0; queueFamilyIndex != queueFamilyCount;
@ -137,8 +133,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
} }
VkBool32 isSurfaceSupported; VkBool32 isSurfaceSupported;
VK_CHECK( VK_CHECK(vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface, &isSurfaceSupported));
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamilyIndex, surface, &isSurfaceSupported) );
if (isSurfaceSupported) if (isSurfaceSupported)
{ {
@ -152,6 +147,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
directQueueFamilyIndex = queueFamilyIndex; directQueueFamilyIndex = queueFamilyIndex;
break; break;
} }
} }
mem->restoreState(tempAllocQueueProperties); mem->restoreState(tempAllocQueueProperties);
@ -258,8 +254,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
uint32_t surfaceFormatCount; uint32_t surfaceFormatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDeviceInUse, surface, &surfaceFormatCount, nullptr); vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDeviceInUse, surface, &surfaceFormatCount, nullptr);
VkSurfaceFormatKHR* surfaceFormats = reinterpret_cast<VkSurfaceFormatKHR*>(mem->allocate( VkSurfaceFormatKHR* surfaceFormats = reinterpret_cast<VkSurfaceFormatKHR*>(mem->allocate(sizeof(VkSurfaceFormatKHR*) * surfaceFormatCount));
sizeof( VkSurfaceFormatKHR ) * surfaceFormatCount ));
vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDeviceInUse, surface, &surfaceFormatCount, surfaceFormats); vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDeviceInUse, surface, &surfaceFormatCount, surfaceFormats);
VkSurfaceFormatKHR format = { VkSurfaceFormatKHR format = {
@ -271,18 +266,15 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
if (surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) if (surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
{ {
SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Color Space SRGB Found %d", surfaceFormat.format); SDL_LogInfo(SDL_LOG_CATEGORY_GPU, "Color Space SRGB Found %d", surfaceFormat.format);
if ( surfaceFormat.format == VK_FORMAT_R8G8B8A8_SRGB ) if (surfaceFormat.format == VK_FORMAT_R8G8B8A8_SRGB) {
{
format = surfaceFormat; format = surfaceFormat;
break; break;
} }
if ( surfaceFormat.format == VK_FORMAT_B8G8R8A8_SRGB ) if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_SRGB) {
{
format = surfaceFormat; format = surfaceFormat;
break; break;
} }
if ( surfaceFormat.format == VK_FORMAT_R8G8B8A8_UNORM ) if (surfaceFormat.format == VK_FORMAT_R8G8B8A8_UNORM) {
{
format = surfaceFormat; format = surfaceFormat;
} }
} }
@ -292,8 +284,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
uint32_t presentModeCount; uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDeviceInUse, surface, &presentModeCount, nullptr); vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDeviceInUse, surface, &presentModeCount, nullptr);
VkPresentModeKHR* presentModes = reinterpret_cast<VkPresentModeKHR*>(mem->allocate( VkPresentModeKHR* presentModes = reinterpret_cast<VkPresentModeKHR*>(mem->allocate(sizeof(VkPresentModeKHR*) * presentModeCount));
sizeof( VkPresentModeKHR ) * presentModeCount ));
vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDeviceInUse, surface, &presentModeCount, presentModes); vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDeviceInUse, surface, &presentModeCount, presentModes);
VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR;
@ -342,8 +333,7 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
vkGetSwapchainImagesKHR(device, swapchain, &swapchainImageCount, swapchainImages); vkGetSwapchainImagesKHR(device, swapchain, &swapchainImageCount, swapchainImages);
swapchainViews = reinterpret_cast<VkImageView*>(mem->allocate(sizeof(VkImageView) * swapchainImageCount)); swapchainViews = reinterpret_cast<VkImageView*>(mem->allocate(sizeof(VkImageView) * swapchainImageCount));
for ( uint32_t i = 0; i != swapchainImageCount; ++i ) for (uint32_t i = 0; i != swapchainImageCount; ++i) {
{
VkImageViewCreateInfo const viewCreateInfo = { VkImageViewCreateInfo const viewCreateInfo = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
@ -380,20 +370,9 @@ RenderDevice* CreateRenderDevice( GlobalMemory* mem, RenderDevice::CreateInfo co
Byte* allocation = mem->allocate(sizeof(RenderDevice), alignof(RenderDevice)); Byte* allocation = mem->allocate(sizeof(RenderDevice), alignof(RenderDevice));
return new (allocation) RenderDevice{ return new (allocation) RenderDevice{
instance, instance, surface, physicalDeviceInUse,
surface, device, gpuAllocator, directQueue, directQueueFamilyIndex.value(),
physicalDeviceInUse, swapchainFormat, swapchainExtent, swapchain, swapchainImages, swapchainViews, frames, swapchainImageCount,
device,
gpuAllocator,
directQueue,
directQueueFamilyIndex.value(),
swapchainFormat,
swapchainExtent,
swapchain,
swapchainImages,
swapchainViews,
frames,
swapchainImageCount,
}; };
} }
@ -402,13 +381,14 @@ inline bool RenderDevice::isInit() const
return instance and device; return instance and device;
} }
void RenderDevice::destroy() void RenderDevice::cleanup()
{ {
if ( not isInit() ) return; if (not isInit())
return;
for (Frame& frame : std::span{ frames, swapchainImageCount }) for (Frame& frame : std::span{ frames, swapchainImageCount })
{ {
frame.destroy( *this ); frame.cleanup(*this);
} }
for (auto const& view : std::span{ swapchainViews, swapchainImageCount }) for (auto const& view : std::span{ swapchainViews, swapchainImageCount })
@ -418,7 +398,6 @@ void RenderDevice::destroy()
vkDestroySwapchainKHR(device, Take(swapchain), nullptr); vkDestroySwapchainKHR(device, Take(swapchain), nullptr);
vmaDestroyAllocator( Take( gpuAllocator ) );
vkDestroyDevice(Take(device), nullptr); vkDestroyDevice(Take(device), nullptr);
SDL_Vulkan_DestroySurface(instance, Take(surface), nullptr); SDL_Vulkan_DestroySurface(instance, Take(surface), nullptr);
@ -438,21 +417,10 @@ uint32_t RenderDevice::getNumFrames() const
return swapchainImageCount; return swapchainImageCount;
} }
RenderDevice::RenderDevice( RenderDevice::RenderDevice(VkInstance const instance, VkSurfaceKHR const surface, VkPhysicalDevice const physicalDeviceInUse,
VkInstance const instance, VkDevice const device, VmaAllocator gpuAllocator, VkQueue const directQueue, uint32_t const directQueueFamilyIndex,
VkSurfaceKHR const surface, VkFormat const swapchainFormat, VkExtent2D const swapchainExtent, VkSwapchainKHR const swapchain, VkImage* swapchainImages,
VkPhysicalDevice const physicalDeviceInUse, VkImageView* swapchainViews, Frame* frames, uint32_t const swapchainImageCount)
VkDevice const device,
VmaAllocator const gpuAllocator,
VkQueue const directQueue,
uint32_t const directQueueFamilyIndex,
VkFormat const swapchainFormat,
VkExtent2D const swapchainExtent,
VkSwapchainKHR const swapchain,
VkImage* swapchainImages,
VkImageView* swapchainViews,
Frame* frames,
uint32_t const swapchainImageCount )
: instance{ instance } : instance{ instance }
, surface{ surface } , surface{ surface }
, physicalDeviceInUse{ physicalDeviceInUse } , physicalDeviceInUse{ physicalDeviceInUse }
@ -466,4 +434,6 @@ RenderDevice::RenderDevice(
, swapchainImages{ swapchainImages } , swapchainImages{ swapchainImages }
, swapchainViews{ swapchainViews } , swapchainViews{ swapchainViews }
, frames{ frames } , frames{ frames }
, swapchainImageCount{ swapchainImageCount } {} , swapchainImageCount{ swapchainImageCount }
{
}

View File

@ -44,7 +44,7 @@ struct RenderDevice
uint32_t frameIndex = 0; uint32_t frameIndex = 0;
[[nodiscard]] bool isInit() const; [[nodiscard]] bool isInit() const;
void destroy(); void cleanup();
void waitIdle() const; void waitIdle() const;
[[nodiscard]] uint32_t getNumFrames() const; [[nodiscard]] uint32_t getNumFrames() const;

View File

@ -15,23 +15,13 @@ struct VertexOut {
float4 vertexColor : CoarseColor; float4 vertexColor : CoarseColor;
}; };
struct CameraData {
float4x4 model;
float4x4 view;
float4x4 proj;
};
ParameterBlock<CameraData> camera;
[shader("vertex")] [shader("vertex")]
VertexOut VertexMain( VertexOut VertexMain(
uint vertexId: SV_VertexID, uint vertexId: SV_VertexID
float4 position,
float4 color,
) { ) {
VertexOut output; VertexOut output;
output.outPosition = mul(camera.proj, mul(camera.view, mul(camera.model, position))); output.outPosition = vertexPos[vertexId];
output.vertexColor = color; output.vertexColor = vertexColors[vertexId];
return output; return output;
} }

BIN
Triangle.spv Normal file

Binary file not shown.

View File

@ -3,7 +3,6 @@
"volk", "volk",
"shader-slang", "shader-slang",
"vulkan-memory-allocator", "vulkan-memory-allocator",
"glm",
{ {
"name": "sdl3", "name": "sdl3",
"features": [ "vulkan" ] "features": [ "vulkan" ]