More fine grained locking of vulkan queues when loading a ktx texture

This commit is contained in:
Guillaume Meunier
2025-10-25 10:30:29 +02:00
parent f1b80a1ebd
commit 33a5bf7494
7 changed files with 79 additions and 44 deletions
+44 -10
View File
@@ -176,8 +176,12 @@ ktxVulkanTexture_subAllocatorCallbacks suballocator_callbacks{
return add(allocation);
},
.bindBufferFuncPtr = [](VkBuffer buffer, uint64_t allocation_id) -> VkResult { return vmaBindBufferMemory(vk_allocator::instance(), find(allocation_id), buffer); },
.bindImageFuncPtr = [](VkImage image, uint64_t allocation_id) -> VkResult { return vmaBindImageMemory(vk_allocator::instance(), find(allocation_id), image); },
.bindBufferFuncPtr = [](VkBuffer buffer, uint64_t allocation_id) -> VkResult {
return vmaBindBufferMemory(vk_allocator::instance(), find(allocation_id), buffer);
},
.bindImageFuncPtr = [](VkImage image, uint64_t allocation_id) -> VkResult {
return vmaBindImageMemory(vk_allocator::instance(), find(allocation_id), image);
},
.memoryMapFuncPtr = [](uint64_t allocation_id, uint64_t, VkDeviceSize * map_length, void ** data) -> VkResult {
auto allocation = find(allocation_id);
@@ -283,12 +287,45 @@ int bytes_per_pixel(vk::Format format)
}
} // namespace
image_loader::image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, thread_safe<vk::raii::Queue> & queue, vk::raii::CommandPool & cb_pool) :
image_loader::image_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, thread_safe<vk::raii::Queue> & queue, uint32_t queue_family_index) :
device(device),
queue(queue),
cb_pool(cb_pool)
cb_pool(device,
vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queue_family_index,
})
{
ktxVulkanDeviceInfo_Construct(&vdi, *physical_device, *device, *queue.get_unsafe(), *cb_pool, nullptr);
// Assume we will always use the same queue
static thread_safe<vk::raii::Queue> * q = &queue;
ktxVulkanFunctions vulkan_functions{
.vkGetInstanceProcAddr = &vkGetInstanceProcAddr,
.vkGetDeviceProcAddr = &vkGetDeviceProcAddr,
.vkQueueSubmit = [](VkQueue queue,
uint32_t submitCount,
const VkSubmitInfo * pSubmits,
VkFence fence) -> VkResult {
assert(q and (VkQueue) * q->get_unsafe() == queue);
auto _ = q->lock();
return vkQueueSubmit(queue, submitCount, pSubmits, fence);
},
.vkQueueWaitIdle = [](VkQueue queue) -> VkResult {
// libktx only uses vkQueueWaitIdle when the tiling is not VK_IMAGE_TILING_OPTIMAL
abort();
},
};
ktxVulkanDeviceInfo_ConstructEx(
&vdi,
*application::get_vulkan_instance(),
*physical_device,
*device,
*queue.get_unsafe(),
*cb_pool,
nullptr, // Allocation callbacks
&vulkan_functions);
std::array<std::tuple<vk::Format, ktx_transcode_fmt_e, bool>, 6> formats{{
{vk::Format::eAstc4x4SrgbBlock, KTX_TTF_ASTC_4x4_RGBA, true},
@@ -624,9 +661,9 @@ loaded_image image_loader::do_load_ktx(std::span<const std::byte> bytes, bool sr
if (output_file != "")
{
spdlog::debug("Saving transcoded texture to {}", output_file.native());
std::string writer = "WiVRn";
const char writer[] = "WiVRn";
ktxHashList_DeleteKVPair(&texture->kvDataHead, KTX_WRITER_KEY);
ktxHashList_AddKVPair(&texture->kvDataHead, KTX_WRITER_KEY, (ktx_uint32_t)writer.length() + 1, writer.c_str());
ktxHashList_AddKVPair(&texture->kvDataHead, KTX_WRITER_KEY, sizeof(writer), writer);
err = ktxTexture2_WriteToNamedFile(texture, output_file.c_str());
if (err != KTX_SUCCESS)
@@ -638,9 +675,6 @@ loaded_image image_loader::do_load_ktx(std::span<const std::byte> bytes, bool sr
ktxVulkanTexture vk_texture;
{
auto _ = queue.lock(); // ktxTexture2_VkUploadEx uses the queue internally (in ktxTexture_VkUploadEx_WithSuballocator)
// TODO: patch vkloader.c to accept a mutex
err = ktxTexture2_VkUploadEx_WithSuballocator(texture, &vdi, &vk_texture, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, &libktx_vma_glue::suballocator_callbacks);
}
+2 -2
View File
@@ -47,7 +47,7 @@ struct loaded_image
struct image_loader
{
image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, thread_safe<vk::raii::Queue> & queue, vk::raii::CommandPool & cb_pool);
image_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, thread_safe<vk::raii::Queue> & queue, uint32_t queue_family_index);
image_loader(const image_loader &) = delete;
image_loader & operator=(const image_loader &) = delete;
~image_loader();
@@ -85,7 +85,7 @@ private:
ktxVulkanDeviceInfo vdi;
vk::raii::Device & device;
thread_safe<vk::raii::Queue> & queue;
vk::raii::CommandPool & cb_pool;
vk::raii::CommandPool cb_pool;
std::vector<std::pair<vk::Format, ktx_transcode_fmt_e>> supported_srgb_formats;
std::vector<std::pair<vk::Format, ktx_transcode_fmt_e>> supported_linear_formats;
+1 -1
View File
@@ -205,7 +205,7 @@ imgui_textures::imgui_textures(
descriptor_pool(device, ds_layout, layout_bindings)
{
if (not image_cache)
this->image_cache = std::make_shared<image_cache_type>(physical_device, device, queue, command_pool);
this->image_cache = std::make_shared<image_cache_type>(device, physical_device, queue, queue_family_index);
}
std::vector<std::pair<ImVec2, float>> imgui_context::ray_plane_intersection(const imgui_context::controller_state & in) const
+9 -16
View File
@@ -401,10 +401,7 @@ fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
}
loaded_image do_load_image(
vk::raii::PhysicalDevice & physical_device,
vk::raii::Device & device,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool,
image_loader & loader,
std::span<const std::byte> image_data,
bool srgb,
const std::pmr::string & name,
@@ -415,8 +412,6 @@ loaded_image do_load_image(
case fastgltf::MimeType::JPEG:
case fastgltf::MimeType::PNG:
case fastgltf::MimeType::KTX2: {
// TODO reuse image loader
image_loader loader(physical_device, device, queue, cb_pool);
auto image = loader.load(image_data, srgb, name.c_str(), false /*premultiply*/, output_path);
spdlog::debug("{}: {}x{}, format {}, {} mipmaps, {} bytes", name, image.extent.width, image.extent.height, vk::to_string(image.format), image.num_mipmaps, image.image.size());
@@ -469,7 +464,7 @@ class loader_context
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
thread_safe<vk::raii::Queue> & queue;
vk::raii::CommandPool & cb_pool;
image_loader & loader;
std::vector<utils::mapped_file> loaded_assets;
utils::mapped_file & load_from_asset(const std::filesystem::path & path)
@@ -492,14 +487,14 @@ public:
vk::raii::PhysicalDevice physical_device,
vk::raii::Device & device,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool) :
image_loader & loader) :
base_directory(std::move(base_directory)),
name(std::move(name)),
gltf(gltf),
physical_device(physical_device),
device(device),
queue(queue),
cb_pool(cb_pool)
loader(loader)
{
}
@@ -604,7 +599,7 @@ public:
try
{
utils::mapped_file image_data{cached_texture};
auto image_ptr = std::make_shared<loaded_image>(do_load_image(physical_device, device, queue, cb_pool, image_data, srgb, image_name, ""));
auto image_ptr = std::make_shared<loaded_image>(do_load_image(loader, image_data, srgb, image_name, ""));
return std::shared_ptr<vk::raii::ImageView>(image_ptr, &image_ptr->image_view);
}
catch (std::exception & e)
@@ -617,7 +612,7 @@ public:
}
auto [image_data, mime_type] = visit_source(gltf.images[index].data);
auto image_ptr = std::make_shared<loaded_image>(do_load_image(physical_device, device, queue, cb_pool, image_data, srgb, image_name, cached_texture));
auto image_ptr = std::make_shared<loaded_image>(do_load_image(loader, image_data, srgb, image_name, cached_texture));
return std::shared_ptr<vk::raii::ImageView>(image_ptr, &image_ptr->image_view);
}
@@ -1095,17 +1090,15 @@ std::shared_ptr<entt::registry> scene_loader::operator()(
std::function<void(float)> progress_cb)
{
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queue_family_index,
}};
auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(data.data(), data.size());
if (auto error = data_buffer.error(); error != fastgltf::Error::None)
throw std::system_error((int)error, fastgltf_error_category);
fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), parent_path);
loader_context ctx(parent_path, name, asset, physical_device, device, queue, cb_pool);
image_loader loader{device, physical_device, queue, queue_family_index};
loader_context ctx{parent_path, name, asset, physical_device, device, queue, loader};
#ifndef NDEBUG
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
+15 -10
View File
@@ -112,7 +112,7 @@ vk::Format scene_renderer::find_usable_image_format(
return vk::Format::eUndefined;
}
std::shared_ptr<renderer::texture> scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel, const std::string & name)
std::shared_ptr<renderer::texture> scene_renderer::create_default_texture(image_loader & loader, std::vector<uint8_t> pixel, const std::string & name)
{
vk::Format format;
@@ -132,10 +132,7 @@ std::shared_ptr<renderer::texture> scene_renderer::create_default_texture(vk::ra
__builtin_unreachable();
}
// TODO reuse image loader
image_loader loader(physical_device, device, queue, cb_pool);
auto image = std::make_shared<loaded_image>(loader.load(pixel, vk::Extent3D{1, 1, 1}, format, name));
std::shared_ptr<vk::raii::ImageView> image_view{image, &image->image_view};
return std::make_shared<renderer::texture>(image_view, renderer::sampler_info{});
@@ -143,14 +140,16 @@ std::shared_ptr<renderer::texture> scene_renderer::create_default_texture(vk::ra
std::shared_ptr<renderer::material> scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool)
{
image_loader loader(device, physical_device, queue, queue_family_index);
auto default_material = std::make_shared<renderer::material>();
default_material->name = "default";
default_material->base_color_texture = create_default_texture(cb_pool, {255, 255, 255, 255}, "Default base color");
default_material->metallic_roughness_texture = create_default_texture(cb_pool, {255, 255}, "Default metallic roughness map");
default_material->occlusion_texture = create_default_texture(cb_pool, {255}, "Default occlusion map");
default_material->emissive_texture = create_default_texture(cb_pool, {0, 0, 0, 0}, "Default emissive color");
default_material->normal_texture = create_default_texture(cb_pool, {128, 128, 255, 255}, "Default normal map");
default_material->base_color_texture = create_default_texture(loader, {255, 255, 255, 255}, "Default base color");
default_material->metallic_roughness_texture = create_default_texture(loader, {255, 255}, "Default metallic roughness map");
default_material->occlusion_texture = create_default_texture(loader, {255}, "Default occlusion map");
default_material->emissive_texture = create_default_texture(loader, {0, 0, 0, 0}, "Default emissive color");
default_material->normal_texture = create_default_texture(loader, {128, 128, 255, 255}, "Default normal map");
default_material->buffer = std::make_shared<buffer_allocation>(
device,
@@ -270,12 +269,18 @@ scene_renderer::scene_renderer(
vk::raii::Device & device,
vk::raii::PhysicalDevice physical_device,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool,
uint32_t queue_family_index,
int frames_in_flight) :
physical_device(physical_device),
device(device),
physical_device_properties(physical_device.getProperties()),
queue(queue),
queue_family_index(queue_family_index),
cb_pool(device,
vk::CommandPoolCreateInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queue_family_index,
}),
shader_cache(device),
layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR))
{
+6 -2
View File
@@ -105,12 +105,16 @@ struct hash<output_image_info> : utils::magic_hash<output_image_info>
{};
} // namespace std
struct image_loader;
class scene_renderer
{
vk::raii::PhysicalDevice physical_device;
vk::raii::Device & device;
vk::PhysicalDeviceProperties physical_device_properties;
thread_safe<vk::raii::Queue> & queue;
uint32_t queue_family_index;
vk::raii::CommandPool cb_pool;
// Destination images
struct output_image
@@ -143,7 +147,7 @@ class scene_renderer
vk::raii::PipelineLayout create_pipeline_layout(std::span<vk::DescriptorSetLayout> layouts);
vk::raii::Pipeline create_pipeline(const pipeline_info & info);
std::shared_ptr<renderer::texture> create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel, const std::string & name);
std::shared_ptr<renderer::texture> create_default_texture(image_loader & loader, std::vector<uint8_t> pixel, const std::string & name);
std::shared_ptr<renderer::material> create_default_material(vk::raii::CommandPool & cb_pool);
vk::raii::DescriptorSetLayout create_descriptor_set_layout(std::span<vk::DescriptorSetLayoutBinding> bindings, vk::DescriptorSetLayoutCreateFlags flags = {});
@@ -255,7 +259,7 @@ public:
vk::raii::Device & device,
vk::raii::PhysicalDevice physical_device,
thread_safe<vk::raii::Queue> & queue,
vk::raii::CommandPool & cb_pool,
uint32_t queue_family_index,
int frames_in_flight = 2);
~scene_renderer();
+2 -3
View File
@@ -96,10 +96,9 @@ scene::scene(key, const meta & current_meta, std::span<const vk::Format> support
}
else
{
// TODO: make argument order more consistent
renderer = std::make_shared<scene_renderer>(device, physical_device, queue, commandpool);
renderer = std::make_shared<scene_renderer>(device, physical_device, queue, queue_family_index);
gltf_cache = std::make_shared<gltf_cache_type>(device, physical_device, queue, queue_family_index, renderer->get_default_material(), application::get_cache_path() / "textures");
image_cache = std::make_shared<image_cache_type>(physical_device, device, queue, commandpool);
image_cache = std::make_shared<image_cache_type>(device, physical_device, queue, queue_family_index);
}
}