diff --git a/include/mbgl/shaders/vulkan/shader_program.hpp b/include/mbgl/shaders/vulkan/shader_program.hpp index e4afb9f30..e07d52ce8 100644 --- a/include/mbgl/shaders/vulkan/shader_program.hpp +++ b/include/mbgl/shaders/vulkan/shader_program.hpp @@ -45,6 +45,7 @@ struct TextureInfo { namespace vulkan { class RenderableResource; class RendererBackend; +class Context; class ShaderProgram; using UniqueShaderProgram = std::unique_ptr; @@ -78,10 +79,11 @@ public: protected: std::string shaderName; RendererBackend& backend; + Context& context; vk::UniqueShaderModule vertexShader; vk::UniqueShaderModule fragmentShader; - std::unordered_map pipelines; + std::shared_ptr> pipelines; VertexAttributeArray vertexAttributes; VertexAttributeArray instanceAttributes; diff --git a/include/mbgl/vulkan/context.hpp b/include/mbgl/vulkan/context.hpp index 8a3d06091..bc230f877 100644 --- a/include/mbgl/vulkan/context.hpp +++ b/include/mbgl/vulkan/context.hpp @@ -151,15 +151,12 @@ public: private: struct FrameResources { vk::UniqueCommandBuffer commandBuffer; - - vk::UniqueSemaphore acquireSurfaceSemaphore; vk::UniqueFence flightFrameFence; std::vector> deletionQueue; - FrameResources(vk::UniqueCommandBuffer& cb, vk::UniqueSemaphore&& surf, vk::UniqueFence&& flight) + FrameResources(vk::UniqueCommandBuffer& cb, vk::UniqueFence&& flight) : commandBuffer(std::move(cb)), - acquireSurfaceSemaphore(std::move(surf)), flightFrameFence(std::move(flight)) {} void runDeletionQueue(Context&); diff --git a/include/mbgl/vulkan/renderable_resource.hpp b/include/mbgl/vulkan/renderable_resource.hpp index 35a2337c0..b9411ff64 100644 --- a/include/mbgl/vulkan/renderable_resource.hpp +++ b/include/mbgl/vulkan/renderable_resource.hpp @@ -58,7 +58,8 @@ public: uint32_t getAcquiredImageIndex() const { return acquiredImageIndex; }; void setAcquiredImageIndex(uint32_t index) { acquiredImageIndex = index; }; const vk::Image getAcquiredImage() const; - const vk::Semaphore& getAcquiredSemaphore() const; + const vk::Semaphore& getAcquireSemaphore() const; + const vk::Semaphore& getPresentSemaphore() const; bool hasSurfaceTransformSupport() const; bool didSurfaceTransformUpdate() const; @@ -87,7 +88,8 @@ protected: std::vector swapchainImages; std::vector swapchainImageViews; std::vector swapchainFramebuffers; - std::vector swapchainSemaphores; + std::vector acquireSemaphores; + std::vector presentSemaphores; vk::Format colorFormat{vk::Format::eUndefined}; UniqueImageAllocation depthAllocation; diff --git a/include/mbgl/vulkan/renderer_backend.hpp b/include/mbgl/vulkan/renderer_backend.hpp index ab6aca0ce..b3283088d 100644 --- a/include/mbgl/vulkan/renderer_backend.hpp +++ b/include/mbgl/vulkan/renderer_backend.hpp @@ -4,6 +4,7 @@ #include #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1 +#define VULKAN_HPP_NO_DEFAULT_DISPATCHER #ifdef _WIN32 #define VK_USE_PLATFORM_WIN32_KHR @@ -39,6 +40,7 @@ public: void initShaders(gfx::ShaderRegistry&, const ProgramParameters& programParameters) override; void init(); + const vk::DispatchLoaderDynamic& getDispatcher() const { return dispatcher; } const vk::UniqueInstance& getInstance() const { return instance; } const vk::PhysicalDevice& getPhysicalDevice() const { return physicalDevice; } const vk::UniqueDevice& getDevice() const { return device; } @@ -60,7 +62,8 @@ public: device->setDebugUtilsObjectNameEXT(vk::DebugUtilsObjectNameInfoEXT() .setObjectType(object.objectType) .setObjectHandle(handle) - .setPObjectName(name.c_str())); + .setPObjectName(name.c_str()), + dispatcher); #endif } @@ -94,6 +97,8 @@ protected: protected: vk::DynamicLoader dynamicLoader; + vk::DispatchLoaderDynamic dispatcher; + vk::UniqueInstance instance; vk::UniqueDebugUtilsMessengerEXT debugUtilsCallback; vk::UniqueDebugReportCallbackEXT debugReportCallback; diff --git a/platform/android/MapLibreAndroid/src/cpp/android_vulkan_renderer_backend.cpp b/platform/android/MapLibreAndroid/src/cpp/android_vulkan_renderer_backend.cpp index 043bc5c4f..3101843ba 100644 --- a/platform/android/MapLibreAndroid/src/cpp/android_vulkan_renderer_backend.cpp +++ b/platform/android/MapLibreAndroid/src/cpp/android_vulkan_renderer_backend.cpp @@ -24,7 +24,8 @@ public: void createPlatformSurface() override { auto& backendImpl = static_cast(backend); const vk::AndroidSurfaceCreateInfoKHR createInfo({}, backendImpl.getWindow()); - surface = backendImpl.getInstance()->createAndroidSurfaceKHRUnique(createInfo); + surface = backendImpl.getInstance()->createAndroidSurfaceKHRUnique( + createInfo, nullptr, backendImpl.getDispatcher()); const int apiLevel = android_get_device_api_level(); if (apiLevel < __ANDROID_API_Q__) { diff --git a/platform/android/MapLibreAndroidTestApp/src/androidTest/java/org/maplibre/android/testapp/activity/SequentialActivityTest.kt b/platform/android/MapLibreAndroidTestApp/src/androidTest/java/org/maplibre/android/testapp/activity/SequentialActivityTest.kt new file mode 100644 index 000000000..6e1b4d6f9 --- /dev/null +++ b/platform/android/MapLibreAndroidTestApp/src/androidTest/java/org/maplibre/android/testapp/activity/SequentialActivityTest.kt @@ -0,0 +1,96 @@ +package org.maplibre.android.testapp.activity + +import android.app.Activity +import android.content.pm.PackageManager +import androidx.test.core.app.ActivityScenario +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.Parameterized + +@RunWith(Parameterized::class) +class SequentialActivityTest(private val activity: Class) { + + companion object { + // app currently has 100+ activities + private const val USE_ALL_ACTIVITIES = true + private const val ACTIVITY_DURATION = 5000L + + // ignores for both activity lists + private val ignoredActivities = listOf( + FeatureOverviewActivity::class.java, + org.maplibre.android.testapp.activity.benchmark.BenchmarkActivity::class.java, + org.maplibre.android.testapp.activity.telemetry.PerformanceMeasurementActivity::class.java, + + // need style updates + org.maplibre.android.testapp.activity.turf.MapSnapshotterWithinExpression::class.java, + org.maplibre.android.testapp.activity.turf.WithinExpressionActivity::class.java, + org.maplibre.android.testapp.activity.style.HeatmapLayerActivity::class.java, + ) + + // activity list used when USE_ALL_ACTIVITIES is disabled + private val activityList = listOf( + org.maplibre.android.testapp.activity.annotation.BulkMarkerActivity::class.java, + org.maplibre.android.testapp.activity.camera.CameraAnimatorActivity::class.java, + org.maplibre.android.testapp.activity.customlayer.CustomLayerActivity::class.java, + org.maplibre.android.testapp.activity.events.ObserverActivity::class.java, + org.maplibre.android.testapp.activity.feature.QuerySourceFeaturesActivity::class.java, + org.maplibre.android.testapp.activity.fragment.MapFragmentActivity::class.java, + org.maplibre.android.testapp.activity.imagegenerator.SnapshotActivity::class.java, + org.maplibre.android.testapp.activity.infowindow.InfoWindowActivity::class.java, + org.maplibre.android.testapp.activity.location.LocationComponentActivationActivity::class.java, + org.maplibre.android.testapp.activity.maplayout.DebugModeActivity::class.java, + org.maplibre.android.testapp.activity.offline.OfflineActivity::class.java, + org.maplibre.android.testapp.activity.options.MapOptionsXmlActivity::class.java, + org.maplibre.android.testapp.activity.render.RenderTestActivity::class.java, + org.maplibre.android.testapp.activity.snapshot.MapSnapshotterActivity::class.java, + org.maplibre.android.testapp.activity.sources.VectorTileActivity::class.java, + org.maplibre.android.testapp.activity.storage.UrlTransformActivity::class.java, + org.maplibre.android.testapp.activity.style.AnimatedImageSourceActivity::class.java, + org.maplibre.android.testapp.activity.turf.WithinExpressionActivity::class.java, + ) + + private fun getAllActivities() : List { + val context = InstrumentationRegistry.getInstrumentation().targetContext + + val packageInfo = context.packageManager.getPackageInfo( + context.packageName, + PackageManager.GET_ACTIVITIES + ) + + val activities = packageInfo.activities + .filter { info -> + info.name.startsWith("org.maplibre.android.testapp.activity") + } + .mapNotNull { info -> + try { + Class.forName(info.name) + } catch (_: ClassNotFoundException) { } + } + + return activities + } + + @JvmStatic + @Parameterized.Parameters(name = "{index}: Activity {0}") + fun activities() : List { + return if (USE_ALL_ACTIVITIES) { + getAllActivities().filter { it !in ignoredActivities } + } else { + activityList.filter { it !in ignoredActivities } + } + } + } + + @Test + fun launchActivity() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + + val scenario = ActivityScenario.launch(activity) + instrumentation.waitForIdleSync() + + Thread.sleep(ACTIVITY_DURATION) + + scenario.close() + } +} diff --git a/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/render/RenderTestActivity.kt b/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/render/RenderTestActivity.kt index 959dd48a3..23e3088f2 100644 --- a/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/render/RenderTestActivity.kt +++ b/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/render/RenderTestActivity.kt @@ -32,7 +32,7 @@ class RenderTestActivity : AppCompatActivity() { private val renderResultMap: MutableMap = HashMap() private var renderTestDefinitions: List? = null private var onRenderTestCompletionListener: OnRenderTestCompletionListener? = null - private lateinit var mapSnapshotter: MapSnapshotter + private var mapSnapshotter: MapSnapshotter? = null private var imageView: ImageView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -46,7 +46,7 @@ class RenderTestActivity : AppCompatActivity() { override fun onStop() { super.onStop() - mapSnapshotter.cancel() + mapSnapshotter?.cancel() } // @@ -119,7 +119,7 @@ class RenderTestActivity : AppCompatActivity() { private fun render(renderTestDefinition: RenderTestDefinition, testSize: Int) { Timber.d("Render test %s,%s", renderTestDefinition.name, renderTestDefinition.category) mapSnapshotter = RenderTestSnapshotter(this, renderTestDefinition.toOptions()) - mapSnapshotter.start( + mapSnapshotter?.start( object : MapSnapshotter.SnapshotReadyCallback { override fun onSnapshotReady(snapshot: MapSnapshot) { imageView!!.setImageBitmap(snapshot.bitmap) diff --git a/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/style/GridSourceActivity.kt b/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/style/GridSourceActivity.kt index 39cb401ed..715366a81 100644 --- a/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/style/GridSourceActivity.kt +++ b/platform/android/MapLibreAndroidTestApp/src/main/java/org/maplibre/android/testapp/activity/style/GridSourceActivity.kt @@ -16,6 +16,7 @@ import org.maplibre.android.style.layers.* import org.maplibre.android.style.sources.CustomGeometrySource import org.maplibre.android.style.sources.GeometryTileProvider import org.maplibre.android.testapp.R +import org.maplibre.android.testapp.styles.TestStyles import java.util.* import kotlin.math.ceil import kotlin.math.floor @@ -102,7 +103,7 @@ class GridSourceActivity : AppCompatActivity(), OnMapReadyCallback { ) map.setStyle( Style.Builder() - .fromUri(Style.getPredefinedStyles()[0].url) + .fromUri(TestStyles.DEMOTILES) .withLayer(layer!!) .withSource(source!!) ) diff --git a/platform/glfw/glfw_vulkan_backend.cpp b/platform/glfw/glfw_vulkan_backend.cpp index 482ca467b..25e736c4c 100644 --- a/platform/glfw/glfw_vulkan_backend.cpp +++ b/platform/glfw/glfw_vulkan_backend.cpp @@ -20,16 +20,17 @@ public: std::vector getDeviceExtensions() override { return {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; } void createPlatformSurface() override { - auto& glfwBackend = static_cast(backend); + auto& backendImpl = static_cast(backend); VkSurfaceKHR surface_; VkResult result = glfwCreateWindowSurface( - glfwBackend.getInstance().get(), glfwBackend.getWindow(), nullptr, &surface_); + backendImpl.getInstance().get(), backendImpl.getWindow(), nullptr, &surface_); if (result != VK_SUCCESS) throw std::runtime_error("Failed to create glfw window surface"); - surface = vk::UniqueSurfaceKHR( - surface_, vk::ObjectDestroy(glfwBackend.getInstance().get())); + surface = vk::UniqueSurfaceKHR(surface_, + vk::ObjectDestroy( + backendImpl.getInstance().get(), nullptr, backendImpl.getDispatcher())); } void bind() override {} diff --git a/src/mbgl/shaders/vulkan/shader_program.cpp b/src/mbgl/shaders/vulkan/shader_program.cpp index b4d000bba..15207646f 100644 --- a/src/mbgl/shaders/vulkan/shader_program.cpp +++ b/src/mbgl/shaders/vulkan/shader_program.cpp @@ -35,7 +35,10 @@ ShaderProgram::ShaderProgram(shaders::BuiltIn shaderID, gfx::ContextObserver& observer) : ShaderProgramBase(), shaderName(name), - backend(backend_) { + backend(backend_), + context(static_cast(backend.getContext())) { + pipelines = std::make_shared>(); + std::string defineStr = programParameters.getDefinesString() + "\n\n"; for (const auto& define : additionalDefines) { defineStr += "#define " + define.first + " " + define.second + "\n"; @@ -102,11 +105,12 @@ ShaderProgram::ShaderProgram(shaders::BuiltIn shaderID, if (vertexSpirv.empty() || fragmentSpirv.empty()) return; const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); vertexShader = device->createShaderModuleUnique( - vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), vertexSpirv)); + vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), vertexSpirv), nullptr, dispatcher); fragmentShader = device->createShaderModuleUnique( - vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), fragmentSpirv)); + vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), fragmentSpirv), nullptr, dispatcher); backend.setDebugName(vertexShader.get(), shaderName + ".vert"); backend.setDebugName(fragmentShader.get(), shaderName + ".frag"); @@ -114,10 +118,16 @@ ShaderProgram::ShaderProgram(shaders::BuiltIn shaderID, observer.onPostCompileShader(shaderID, gfx::Backend::Type::Metal, defineStr); } -ShaderProgram::~ShaderProgram() noexcept = default; +ShaderProgram::~ShaderProgram() noexcept { + if (pipelines->empty()) { + return; + } + + context.enqueueDeletion([pipelines = std::move(pipelines)](auto&) mutable { pipelines.reset(); }); +} const vk::UniquePipeline& ShaderProgram::getPipeline(const PipelineInfo& pipelineInfo) { - auto& pipeline = pipelines[pipelineInfo.hash()]; + auto& pipeline = pipelines->operator[](pipelineInfo.hash()); if (pipeline) return pipeline; const auto vertexInputState = vk::PipelineVertexInputStateCreateInfo() @@ -194,7 +204,7 @@ const vk::UniquePipeline& ShaderProgram::getPipeline(const PipelineInfo& pipelin const vk::PipelineDynamicStateCreateInfo dynamicState({}, dynamicValues); const auto& device = backend.getDevice(); - auto& context = static_cast(backend.getContext()); + const auto& dispatcher = backend.getDispatcher(); const auto& pipelineLayout = pipelineInfo.usePushConstants ? context.getPushConstantPipelineLayout() : context.getGeneralPipelineLayout(); @@ -222,7 +232,7 @@ const vk::UniquePipeline& ShaderProgram::getPipeline(const PipelineInfo& pipelin .setLayout(pipelineLayout.get()) .setRenderPass(pipelineInfo.renderPass); - pipeline = std::move(device->createGraphicsPipelineUnique(nullptr, pipelineCreateInfo).value); + pipeline = std::move(device->createGraphicsPipelineUnique(nullptr, pipelineCreateInfo, nullptr, dispatcher).value); backend.setDebugName(pipeline.get(), shaderName + "_pipeline"); return pipeline; diff --git a/src/mbgl/vulkan/buffer_resource.cpp b/src/mbgl/vulkan/buffer_resource.cpp index 4e3c32665..2f6c1a282 100644 --- a/src/mbgl/vulkan/buffer_resource.cpp +++ b/src/mbgl/vulkan/buffer_resource.cpp @@ -171,6 +171,11 @@ void BufferResource::update(const void* newData, std::size_t updateSize, std::si } uint8_t* data = static_cast(bufferAllocation->mappedBuffer) + getVulkanBufferOffset() + offset; + + if (memcmp(data, newData, updateSize) == 0) { + return; + } + std::memcpy(data, newData, updateSize); auto& stats = context.renderingStats(); diff --git a/src/mbgl/vulkan/context.cpp b/src/mbgl/vulkan/context.cpp index 508426276..df44808f8 100644 --- a/src/mbgl/vulkan/context.cpp +++ b/src/mbgl/vulkan/context.cpp @@ -77,6 +77,7 @@ Context::~Context() noexcept { void Context::initFrameResources() { const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); const auto frameCount = backend.getMaxFrames(); descriptorPoolMap.emplace(DescriptorSetType::Global, @@ -99,19 +100,18 @@ void Context::initFrameResources() { const vk::CommandBufferAllocateInfo allocateInfo( backend.getCommandPool().get(), vk::CommandBufferLevel::ePrimary, frameCount); - auto commandBuffers = backend.getDevice()->allocateCommandBuffersUnique(allocateInfo); + auto commandBuffers = device->allocateCommandBuffersUnique(allocateInfo, dispatcher); frameResources.reserve(frameCount); for (uint32_t index = 0; index < frameCount; ++index) { - frameResources.emplace_back(commandBuffers[index], - device->createSemaphoreUnique({}), - device->createFenceUnique(vk::FenceCreateInfo(vk::FenceCreateFlagBits::eSignaled))); + frameResources.emplace_back( + commandBuffers[index], + device->createFenceUnique(vk::FenceCreateInfo(vk::FenceCreateFlagBits::eSignaled), nullptr, dispatcher)); const auto& frame = frameResources.back(); backend.setDebugName(frame.commandBuffer.get(), "FrameCommandBuffer_" + std::to_string(index)); - backend.setDebugName(frame.acquireSurfaceSemaphore.get(), "AcquireSurfaceSemaphore_" + std::to_string(index)); backend.setDebugName(frame.flightFrameFence.get(), "FrameFence_" + std::to_string(index)); } @@ -134,7 +134,7 @@ void Context::initFrameResources() { } void Context::destroyResources() { - backend.getDevice()->waitIdle(); + backend.getDevice()->waitIdle(backend.getDispatcher()); for (auto& frame : frameResources) { frame.runDeletionQueue(*this); @@ -172,22 +172,23 @@ void Context::submitOneTimeCommand(const std::functionallocateCommandBuffersUnique(allocateInfo); + const auto& dispatcher = backend.getDispatcher(); + const auto& commandBuffers = device->allocateCommandBuffersUnique(allocateInfo, dispatcher); auto& commandBuffer = commandBuffers.front(); backend.setDebugName(commandBuffer.get(), "OneTimeSubmitCommandBuffer"); - commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); + commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit), dispatcher); function(commandBuffer); - commandBuffer->end(); + commandBuffer->end(dispatcher); const auto submitInfo = vk::SubmitInfo().setCommandBuffers(commandBuffer.get()); - const auto& fence = device->createFenceUnique(vk::FenceCreateInfo(vk::FenceCreateFlags())); - backend.getGraphicsQueue().submit(submitInfo, fence.get()); + const auto& fence = device->createFenceUnique(vk::FenceCreateInfo(vk::FenceCreateFlags()), nullptr, dispatcher); + backend.getGraphicsQueue().submit(submitInfo, fence.get(), dispatcher); constexpr uint64_t timeout = std::numeric_limits::max(); - const vk::Result waitFenceResult = device->waitForFences(1, &fence.get(), VK_TRUE, timeout); + const vk::Result waitFenceResult = device->waitForFences(1, &fence.get(), VK_TRUE, timeout, dispatcher); if (waitFenceResult != vk::Result::eSuccess) { mbgl::Log::Error(mbgl::Event::Render, "OneTimeCommand - Wait fence failed"); } @@ -209,18 +210,24 @@ void Context::requestSurfaceUpdate(bool useDelay) { void Context::waitFrame() const { MLN_TRACE_FUNC(); const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); auto& frame = frameResources[frameResourceIndex]; constexpr uint64_t timeout = std::numeric_limits::max(); - const vk::Result waitFenceResult = device->waitForFences(1, &frame.flightFrameFence.get(), VK_TRUE, timeout); + const vk::Result waitFenceResult = device->waitForFences( + 1, &frame.flightFrameFence.get(), VK_TRUE, timeout, dispatcher); if (waitFenceResult != vk::Result::eSuccess) { mbgl::Log::Error(mbgl::Event::Render, "Wait fence failed"); } } + void Context::beginFrame() { MLN_TRACE_FUNC(); + frameResourceIndex = (frameResourceIndex + 1) % frameResources.size(); + const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); auto& renderableResource = backend.getDefaultRenderable().getResource(); const auto& platformSurface = renderableResource.getPlatformSurface(); @@ -273,7 +280,11 @@ void Context::beginFrame() { MLN_TRACE_ZONE(acquireNextImageKHR); try { const vk::ResultValue acquireImageResult = device->acquireNextImageKHR( - renderableResource.getSwapchain().get(), timeout, frame.acquireSurfaceSemaphore.get(), nullptr); + renderableResource.getSwapchain().get(), + timeout, + renderableResource.getAcquireSemaphore(), + nullptr, + dispatcher); if (acquireImageResult.result == vk::Result::eSuccess) { renderableResource.setAcquiredImageIndex(acquireImageResult.value); @@ -292,20 +303,19 @@ void Context::beginFrame() { renderableResource.setAcquiredImageIndex(frameResourceIndex); } - frame.commandBuffer->reset(vk::CommandBufferResetFlagBits::eReleaseResources); - frame.commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); + frame.commandBuffer->reset(vk::CommandBufferResetFlagBits::eReleaseResources, dispatcher); + frame.commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit), dispatcher); backend.getThreadPool().runRenderJobs(); } -void Context::endFrame() { - frameResourceIndex = (frameResourceIndex + 1) % frameResources.size(); -} +void Context::endFrame() {} void Context::submitFrame() { MLN_TRACE_FUNC(); + const auto& dispatcher = backend.getDispatcher(); const auto& frame = frameResources[frameResourceIndex]; - frame.commandBuffer->end(); + frame.commandBuffer->end(dispatcher); const auto& device = backend.getDevice(); const auto& graphicsQueue = backend.getGraphicsQueue(); @@ -317,29 +327,29 @@ void Context::submitFrame() { auto submitInfo = vk::SubmitInfo().setCommandBuffers(frame.commandBuffer.get()); if (platformSurface) { - submitInfo.setSignalSemaphores(renderableResource.getAcquiredSemaphore()) - .setWaitSemaphores(frame.acquireSurfaceSemaphore.get()) + submitInfo.setSignalSemaphores(renderableResource.getPresentSemaphore()) + .setWaitSemaphores(renderableResource.getAcquireSemaphore()) .setWaitDstStageMask(waitStageMask); } - const vk::Result resetFenceResult = device->resetFences(1, &frame.flightFrameFence.get()); + const vk::Result resetFenceResult = device->resetFences(1, &frame.flightFrameFence.get(), dispatcher); if (resetFenceResult != vk::Result::eSuccess) { mbgl::Log::Error(mbgl::Event::Render, "Reset fence failed"); } - graphicsQueue.submit(submitInfo, frame.flightFrameFence.get()); + graphicsQueue.submit(submitInfo, frame.flightFrameFence.get(), dispatcher); // present rendered frame if (platformSurface) { const auto acquiredImage = renderableResource.getAcquiredImageIndex(); const auto presentInfo = vk::PresentInfoKHR() .setSwapchains(renderableResource.getSwapchain().get()) - .setWaitSemaphores(renderableResource.getAcquiredSemaphore()) + .setWaitSemaphores(renderableResource.getPresentSemaphore()) .setImageIndices(acquiredImage); try { const auto& presentQueue = backend.getPresentQueue(); - const vk::Result presentResult = presentQueue.presentKHR(presentInfo); + const vk::Result presentResult = presentQueue.presentKHR(presentInfo, dispatcher); if (presentResult == vk::Result::eSuboptimalKHR) { requestSurfaceUpdate(); } @@ -538,6 +548,7 @@ bool Context::renderTileClippingMasks(gfx::RenderPass& renderPass, .setFormat(PipelineInfo::vulkanFormat(ShaderClass::attributes[0].dataType))); } + const auto& dispatcher = backend.getDispatcher(); auto& shaderImpl = static_cast(*clipping.shader); auto& renderPassImpl = static_cast(renderPass); auto& commandBuffer = renderPassImpl.getEncoder().getCommandBuffer(); @@ -546,21 +557,21 @@ bool Context::renderTileClippingMasks(gfx::RenderPass& renderPass, const auto& pipeline = shaderImpl.getPipeline(clipping.pipelineInfo); - commandBuffer->bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.get()); + commandBuffer->bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.get(), dispatcher); clipping.pipelineInfo.setDynamicValues(backend, commandBuffer); const std::array vertexBuffers = {clipping.vertexBuffer->getVulkanBuffer()}; const std::array offset = {0}; - commandBuffer->bindVertexBuffers(0, vertexBuffers, offset); - commandBuffer->bindIndexBuffer(clipping.indexBuffer->getVulkanBuffer(), 0, vk::IndexType::eUint16); + commandBuffer->bindVertexBuffers(0, vertexBuffers, offset, dispatcher); + commandBuffer->bindIndexBuffer(clipping.indexBuffer->getVulkanBuffer(), 0, vk::IndexType::eUint16, dispatcher); auto& renderableResource = renderPassImpl.getDescriptor().renderable.getResource(); const float rad = renderableResource.getRotation(); const mat4 rotationMat = {cos(rad), -sin(rad), 0, 0, sin(rad), cos(rad), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; for (const auto& tileInfo : tileUBOs) { - commandBuffer->setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, tileInfo.stencil_ref); + commandBuffer->setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, tileInfo.stencil_ref, dispatcher); mat4 matrix; matrix::multiply(matrix, rotationMat, tileInfo.matrix); @@ -571,8 +582,9 @@ bool Context::renderTileClippingMasks(gfx::RenderPass& renderPass, vk::ShaderStageFlags() | vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0, sizeof(matrixf), - &matrixf); - commandBuffer->drawIndexed(clipping.indexCount, 1, 0, 0, 0); + &matrixf, + dispatcher); + commandBuffer->drawIndexed(clipping.indexCount, 1, 0, 0, 0, dispatcher); } stats.numDrawCalls++; @@ -633,7 +645,8 @@ void Context::buildUniformDescriptorSetLayout(vk::UniqueDescriptorSetLayout& lay } const auto descriptorSetLayoutCreateInfo = vk::DescriptorSetLayoutCreateInfo().setBindings(bindings); - layout = backend.getDevice()->createDescriptorSetLayoutUnique(descriptorSetLayoutCreateInfo); + layout = backend.getDevice()->createDescriptorSetLayoutUnique( + descriptorSetLayoutCreateInfo, nullptr, backend.getDispatcher()); backend.setDebugName(layout.get(), name); } @@ -650,7 +663,7 @@ void Context::buildImageDescriptorSetLayout() { const auto descriptorSetLayoutCreateInfo = vk::DescriptorSetLayoutCreateInfo().setBindings(bindings); drawableImageDescriptorSetLayout = backend.getDevice()->createDescriptorSetLayoutUnique( - descriptorSetLayoutCreateInfo); + descriptorSetLayoutCreateInfo, nullptr, backend.getDispatcher()); backend.setDebugName(drawableImageDescriptorSetLayout.get(), "ImageDescriptorSetLayout"); } @@ -694,7 +707,9 @@ const vk::UniquePipelineLayout& Context::getGeneralPipelineLayout() { }; generalPipelineLayout = backend.getDevice()->createPipelineLayoutUnique( - vk::PipelineLayoutCreateInfo().setPushConstantRanges(pushConstant).setSetLayouts(layouts)); + vk::PipelineLayoutCreateInfo().setPushConstantRanges(pushConstant).setSetLayouts(layouts), + nullptr, + backend.getDispatcher()); backend.setDebugName(generalPipelineLayout.get(), "PipelineLayout_general"); @@ -708,7 +723,7 @@ const vk::UniquePipelineLayout& Context::getPushConstantPipelineLayout() { const auto pushConstant = vk::PushConstantRange().setSize(sizeof(matf4)).setStageFlags(stages); pushConstantPipelineLayout = backend.getDevice()->createPipelineLayoutUnique( - vk::PipelineLayoutCreateInfo().setPushConstantRanges(pushConstant)); + vk::PipelineLayoutCreateInfo().setPushConstantRanges(pushConstant), nullptr, backend.getDispatcher()); backend.setDebugName(pushConstantPipelineLayout.get(), "PipelineLayout_pushConstants"); diff --git a/src/mbgl/vulkan/descriptor_set.cpp b/src/mbgl/vulkan/descriptor_set.cpp index ae30ba05e..1cfcbe727 100644 --- a/src/mbgl/vulkan/descriptor_set.cpp +++ b/src/mbgl/vulkan/descriptor_set.cpp @@ -33,7 +33,8 @@ DescriptorSet::~DescriptorSet() { } void DescriptorSet::createDescriptorPool(DescriptorPoolGrowable& growablePool) { - const auto& device = context.getBackend().getDevice(); + const auto& backend = context.getBackend(); + const auto& device = backend.getDevice(); const uint32_t maxSets = static_cast(growablePool.maxSets * std::pow(growablePool.growFactor, growablePool.pools.size())); @@ -60,7 +61,8 @@ void DescriptorSet::createDescriptorPool(DescriptorPoolGrowable& growablePool) { const auto descriptorPoolInfo = vk::DescriptorPoolCreateInfo(poolFlags).setPoolSizes(sizes).setMaxSets(maxSets); - growablePool.pools.emplace_back(device->createDescriptorPoolUnique(descriptorPoolInfo), maxSets); + growablePool.pools.emplace_back( + device->createDescriptorPoolUnique(descriptorPoolInfo, nullptr, backend.getDispatcher()), maxSets); growablePool.currentPoolIndex = static_cast(growablePool.pools.size() - 1); }; @@ -71,10 +73,11 @@ void DescriptorSet::allocate() { return; } - const auto& device = context.getBackend().getDevice(); + const auto& backend = context.getBackend(); + const auto& device = backend.getDevice(); const auto& descriptorSetLayout = context.getDescriptorSetLayout(type); auto& growablePool = context.getDescriptorPool(type); - const std::vector layouts(context.getBackend().getMaxFrames(), descriptorSetLayout); + const std::vector layouts(backend.getMaxFrames(), descriptorSetLayout); if (growablePool.currentPoolIndex == -1 || (growablePool.current().unusedSets.empty() && growablePool.current().remainingSets < layouts.size())) { @@ -112,9 +115,9 @@ void DescriptorSet::allocate() { } else #endif { - descriptorSets = device->allocateDescriptorSets(vk::DescriptorSetAllocateInfo() - .setDescriptorPool(growablePool.current().pool.get()) - .setSetLayouts(layouts)); + descriptorSets = device->allocateDescriptorSets( + vk::DescriptorSetAllocateInfo().setDescriptorPool(growablePool.current().pool.get()).setSetLayouts(layouts), + backend.getDispatcher()); growablePool.current().remainingSets -= descriptorSets.size(); } @@ -127,6 +130,7 @@ void DescriptorSet::markDirty() { void DescriptorSet::bind(CommandEncoder& encoder) { MLN_TRACE_FUNC(); + const auto& backend = encoder.getContext().getBackend(); auto& commandBuffer = encoder.getCommandBuffer(); const uint8_t index = context.getCurrentFrameResourceIndex(); @@ -135,7 +139,8 @@ void DescriptorSet::bind(CommandEncoder& encoder) { context.getGeneralPipelineLayout().get(), static_cast(type), descriptorSets[index], - nullptr); + nullptr, + backend.getDispatcher()); } UniformDescriptorSet::UniformDescriptorSet(Context& context_, DescriptorSetType type_) @@ -154,7 +159,8 @@ void UniformDescriptorSet::update(const gfx::UniformBufferArray& uniforms, return; } - const auto& device = context.getBackend().getDevice(); + const auto& backend = context.getBackend(); + const auto& device = backend.getDevice(); for (size_t index = 0; index < descriptorStorageCount + descriptorUniformCount; ++index) { vk::DescriptorBufferInfo descriptorBufferInfo; @@ -180,7 +186,7 @@ void UniformDescriptorSet::update(const gfx::UniformBufferArray& uniforms, .setDstBinding(static_cast(index)) .setDstSet(descriptorSets[frameIndex]); - device->updateDescriptorSets(writeDescriptorSet, nullptr); + device->updateDescriptorSets(writeDescriptorSet, nullptr, backend.getDispatcher()); } dirty[frameIndex] = false; @@ -205,7 +211,8 @@ void ImageDescriptorSet::update(const std::array(id)) .setDstSet(descriptorSets[frameIndex]); - device->updateDescriptorSets(writeDescriptorSet, nullptr); + device->updateDescriptorSets(writeDescriptorSet, nullptr, backend.getDispatcher()); } dirty[frameIndex] = false; diff --git a/src/mbgl/vulkan/drawable.cpp b/src/mbgl/vulkan/drawable.cpp index 2fedddc32..a063b1a34 100644 --- a/src/mbgl/vulkan/drawable.cpp +++ b/src/mbgl/vulkan/drawable.cpp @@ -244,6 +244,7 @@ void Drawable::draw(PaintParameters& parameters) const { } auto& context = static_cast(parameters.context); + auto& dispatcher = context.getBackend().getDispatcher(); auto& renderPass_ = static_cast(*parameters.renderPass); auto& encoder = renderPass_.getEncoder(); auto& commandBuffer = encoder.getCommandBuffer(); @@ -258,7 +259,8 @@ void Drawable::draw(PaintParameters& parameters) const { vk::ShaderStageFlags() | vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0, sizeof(uboIndex), - &uboIndex); + &uboIndex, + dispatcher); if (enableDepth) { if (impl->depthFor3D.has_value()) { @@ -299,19 +301,21 @@ void Drawable::draw(PaintParameters& parameters) const { impl->pipelineInfo.setDynamicValues(context.getBackend(), commandBuffer); const auto& pipeline = shaderImpl.getPipeline(impl->pipelineInfo); - commandBuffer->bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.get()); + commandBuffer->bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.get(), dispatcher); if (segment.indexLength) { commandBuffer->drawIndexed(static_cast(segment.indexLength), static_cast(instances), static_cast(segment.indexOffset), static_cast(segment.vertexOffset), - 0); + 0, + dispatcher); } else { commandBuffer->draw(static_cast(segment.vertexLength), static_cast(instances), static_cast(segment.vertexOffset), - 0); + 0, + dispatcher); } context.renderingStats().numDrawCalls++; @@ -411,14 +415,16 @@ bool Drawable::bindAttributes(CommandEncoder& encoder) const noexcept { if (impl->vulkanVertexBuffers.empty()) return false; + const auto& dispatcher = encoder.getContext().getBackend().getDispatcher(); const auto& commandBuffer = encoder.getCommandBuffer(); - commandBuffer->bindVertexBuffers(0, impl->vulkanVertexBuffers, impl->vulkanVertexOffsets); + commandBuffer->bindVertexBuffers(0, impl->vulkanVertexBuffers, impl->vulkanVertexOffsets, dispatcher); if (impl->indexes) { if (const auto* indexBuffer = static_cast(impl->indexes->getBuffer())) { const auto& indexBufferResource = indexBuffer->buffer->getResource().get(); - commandBuffer->bindIndexBuffer(indexBufferResource.getVulkanBuffer(), 0, vk::IndexType::eUint16); + commandBuffer->bindIndexBuffer( + indexBufferResource.getVulkanBuffer(), 0, vk::IndexType::eUint16, dispatcher); } } diff --git a/src/mbgl/vulkan/offscreen_texture.cpp b/src/mbgl/vulkan/offscreen_texture.cpp index 0e8797af3..24462d0c9 100644 --- a/src/mbgl/vulkan/offscreen_texture.cpp +++ b/src/mbgl/vulkan/offscreen_texture.cpp @@ -101,7 +101,8 @@ public: .setSubpasses(subpass) .setDependencies(subpassDependency); - renderPass = backend.getDevice()->createRenderPassUnique(renderPassCreateInfo); + renderPass = backend.getDevice()->createRenderPassUnique( + renderPassCreateInfo, nullptr, backend.getDispatcher()); const auto framebufferCreateInfo = vk::FramebufferCreateInfo() .setRenderPass(renderPass.get()) @@ -111,7 +112,8 @@ public: .setHeight(extent.height) .setLayers(1); - framebuffer = backend.getDevice()->createFramebufferUnique(framebufferCreateInfo); + framebuffer = backend.getDevice()->createFramebufferUnique( + framebufferCreateInfo, nullptr, backend.getDispatcher()); } private: diff --git a/src/mbgl/vulkan/pipeline.cpp b/src/mbgl/vulkan/pipeline.cpp index db1d2645a..400a871fa 100644 --- a/src/mbgl/vulkan/pipeline.cpp +++ b/src/mbgl/vulkan/pipeline.cpp @@ -408,26 +408,28 @@ std::size_t PipelineInfo::hash() const { } void PipelineInfo::setDynamicValues(const RendererBackend& backend, const vk::UniqueCommandBuffer& buffer) const { + const auto& dispatcher = backend.getDispatcher(); if (dynamicValues.blendConstants.has_value()) { - buffer->setBlendConstants(dynamicValues.blendConstants.value().data()); + buffer->setBlendConstants(dynamicValues.blendConstants.value().data(), dispatcher); } if (stencilTest) { - buffer->setStencilWriteMask(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilWriteMask); - buffer->setStencilCompareMask(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilCompareMask); - buffer->setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilRef); + buffer->setStencilWriteMask(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilWriteMask, dispatcher); + buffer->setStencilCompareMask( + vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilCompareMask, dispatcher); + buffer->setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilRef, dispatcher); } if (backend.getDeviceFeatures().wideLines && wideLines) { - buffer->setLineWidth(dynamicValues.lineWidth); + buffer->setLineWidth(dynamicValues.lineWidth, dispatcher); } #if USE_DYNAMIC_VIEWPORT const vk::Viewport viewport(0.0f, 0.0f, viewExtent.width, viewExtent.height, 0.0f, 1.0f); const vk::Rect2D scissorRect({}, {viewExtent.width, viewExtent.height}); - buffer->setViewport(0, viewport); - buffer->setScissor(0, scissorRect); + buffer->setViewport(0, viewport, dispatcher); + buffer->setScissor(0, scissorRect, dispatcher); #endif } diff --git a/src/mbgl/vulkan/render_pass.cpp b/src/mbgl/vulkan/render_pass.cpp index f82588465..7b1aa9f27 100644 --- a/src/mbgl/vulkan/render_pass.cpp +++ b/src/mbgl/vulkan/render_pass.cpp @@ -30,7 +30,8 @@ RenderPass::RenderPass(CommandEncoder& commandEncoder_, const char* name, const pushDebugGroup(name); - commandEncoder.getCommandBuffer()->beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline); + commandEncoder.getCommandBuffer()->beginRenderPass( + renderPassBeginInfo, vk::SubpassContents::eInline, commandEncoder.getContext().getBackend().getDispatcher()); commandEncoder.context.performCleanup(); } @@ -42,7 +43,7 @@ RenderPass::~RenderPass() { } void RenderPass::endEncoding() { - commandEncoder.getCommandBuffer()->endRenderPass(); + commandEncoder.getCommandBuffer()->endRenderPass(commandEncoder.getContext().getBackend().getDispatcher()); } void RenderPass::clearStencil(uint32_t value) const { @@ -56,7 +57,8 @@ void RenderPass::clearStencil(uint32_t value) const { const auto rect = vk::ClearRect().setBaseArrayLayer(0).setLayerCount(1).setRect( {{0, 0}, {extent.width, extent.height}}); - commandEncoder.getCommandBuffer()->clearAttachments(attach, rect); + commandEncoder.getCommandBuffer()->clearAttachments( + attach, rect, commandEncoder.getContext().getBackend().getDispatcher()); } void RenderPass::pushDebugGroup(const char* name) { diff --git a/src/mbgl/vulkan/renderable_resource.cpp b/src/mbgl/vulkan/renderable_resource.cpp index f9bc99120..025771e6f 100644 --- a/src/mbgl/vulkan/renderable_resource.cpp +++ b/src/mbgl/vulkan/renderable_resource.cpp @@ -6,18 +6,9 @@ namespace mbgl { namespace vulkan { -static bool hasMemoryType(const vk::PhysicalDevice& physicalDevice, const vk::MemoryPropertyFlagBits& type) { - const auto& memoryProps = physicalDevice.getMemoryProperties(); - for (uint32_t i = 0; i < memoryProps.memoryTypeCount; ++i) { - if (memoryProps.memoryTypes[i].propertyFlags & type) { - return true; - } - } - - return false; -} - SurfaceRenderableResource::~SurfaceRenderableResource() { + backend.getDevice()->waitIdle(backend.getDispatcher()); + // specific order swapchainFramebuffers.clear(); renderPass.reset(); @@ -74,8 +65,9 @@ void SurfaceRenderableResource::initColor(uint32_t w, uint32_t h) { void SurfaceRenderableResource::initSwapchain(uint32_t w, uint32_t h) { const auto& physicalDevice = backend.getPhysicalDevice(); const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); - const std::vector& formats = physicalDevice.getSurfaceFormatsKHR(surface.get()); + const std::vector& formats = physicalDevice.getSurfaceFormatsKHR(surface.get(), dispatcher); const auto& formatIt = std::find_if(formats.begin(), formats.end(), [](const vk::SurfaceFormatKHR& format) { return (format.format == vk::Format::eB8G8R8A8Unorm || format.format == vk::Format::eR8G8B8A8Unorm) && format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear; @@ -85,7 +77,8 @@ void SurfaceRenderableResource::initSwapchain(uint32_t w, uint32_t h) { // only vk::PresentModeKHR::eFifo (vsync on) is guaranteed if (presentMode != vk::PresentModeKHR::eFifo) { - const std::vector& presentModes = physicalDevice.getSurfacePresentModesKHR(surface.get()); + const auto& presentModes = physicalDevice.getSurfacePresentModesKHR(surface.get(), dispatcher); + if (std::find(presentModes.begin(), presentModes.end(), presentMode) == presentModes.end()) { mbgl::Log::Error( mbgl::Event::Render, @@ -96,7 +89,7 @@ void SurfaceRenderableResource::initSwapchain(uint32_t w, uint32_t h) { } // pick surface size - capabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface.get()); + capabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface.get(), dispatcher); if (capabilities.currentExtent.width != std::numeric_limits::max()) { extent = capabilities.currentExtent; @@ -154,22 +147,28 @@ void SurfaceRenderableResource::initSwapchain(uint32_t w, uint32_t h) { // update this when recreating swapchainCreateInfo.setOldSwapchain(swapchain.get()); - swapchain = device->createSwapchainKHRUnique(swapchainCreateInfo); - swapchainImages = device->getSwapchainImagesKHR(swapchain.get()); + swapchain = device->createSwapchainKHRUnique(swapchainCreateInfo, nullptr, dispatcher); + swapchainImages = device->getSwapchainImagesKHR(swapchain.get(), dispatcher); colorFormat = swapchainCreateInfo.imageFormat; extent = swapchainCreateInfo.imageExtent; - swapchainSemaphores.reserve(swapchainImages.size()); + acquireSemaphores.reserve(swapchainImages.size()); + presentSemaphores.reserve(swapchainImages.size()); for (uint32_t index = 0; index < swapchainImages.size(); ++index) { - swapchainSemaphores.emplace_back(device->createSemaphoreUnique({})); - backend.setDebugName(swapchainSemaphores.back().get(), "SurfaceSemaphore_" + std::to_string(index)); + acquireSemaphores.emplace_back(device->createSemaphoreUnique({}, nullptr, dispatcher)); + presentSemaphores.emplace_back(device->createSemaphoreUnique({}, nullptr, dispatcher)); + + const auto indexStr = std::to_string(index); + backend.setDebugName(acquireSemaphores.back().get(), "PresentSemaphore_" + indexStr); + backend.setDebugName(presentSemaphores.back().get(), "AcquireSemaphore_" + indexStr); } } void SurfaceRenderableResource::initDepthStencil() { const auto& physicalDevice = backend.getPhysicalDevice(); const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); // check for depth format support const std::vector formats = { @@ -179,7 +178,7 @@ void SurfaceRenderableResource::initDepthStencil() { }; const auto& formatIt = std::find_if(formats.begin(), formats.end(), [&](const auto& format) { - const auto& formatProps = physicalDevice.getFormatProperties(format); + const auto& formatProps = physicalDevice.getFormatProperties(format, dispatcher); return formatProps.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment; }); @@ -190,10 +189,6 @@ void SurfaceRenderableResource::initDepthStencil() { depthFormat = *formatIt; - const bool hasLazyMemory = hasMemoryType(physicalDevice, vk::MemoryPropertyFlagBits::eLazilyAllocated); - const auto memoryUsage = hasLazyMemory ? VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED - : VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; - const auto imageUsage = vk::ImageUsageFlags() | vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment; @@ -210,9 +205,16 @@ void SurfaceRenderableResource::initDepthStencil() { .setInitialLayout(vk::ImageLayout::eUndefined); VmaAllocationCreateInfo allocCreateInfo = {}; - allocCreateInfo.usage = memoryUsage; + allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; + uint32_t lazyMemoryIndex = 0; + uint32_t memoryTypeBits = std::numeric_limits::max(); + if (vmaFindMemoryTypeIndex(backend.getAllocator(), memoryTypeBits, &allocCreateInfo, &lazyMemoryIndex) != + VK_SUCCESS) { + allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; + } + depthAllocation = std::make_unique(backend.getAllocator()); if (!depthAllocation->create(allocCreateInfo, imageCreateInfo)) { mbgl::Log::Error(mbgl::Event::Render, "Vulkan depth texture allocation failed"); @@ -228,7 +230,7 @@ void SurfaceRenderableResource::initDepthStencil() { .setSubresourceRange(vk::ImageSubresourceRange( vk::ImageAspectFlagBits::eDepth | vk::ImageAspectFlagBits::eStencil, 0, 1, 0, 1)); - depthAllocation->imageView = device->createImageViewUnique(imageViewCreateInfo); + depthAllocation->imageView = device->createImageViewUnique(imageViewCreateInfo, nullptr, dispatcher); backend.setDebugName(depthAllocation->image, "SwapchainDepthImage"); backend.setDebugName(depthAllocation->imageView.get(), "SwapchainDepthImageView"); @@ -247,8 +249,13 @@ const vk::Image SurfaceRenderableResource::getAcquiredImage() const { return colorAllocations[acquiredImageIndex]->image; } -const vk::Semaphore& SurfaceRenderableResource::getAcquiredSemaphore() const { - return swapchainSemaphores[acquiredImageIndex].get(); +const vk::Semaphore& SurfaceRenderableResource::getAcquireSemaphore() const { + const auto& context = static_cast(backend.getContext()); + return acquireSemaphores[context.getCurrentFrameResourceIndex()].get(); +} + +const vk::Semaphore& SurfaceRenderableResource::getPresentSemaphore() const { + return presentSemaphores[acquiredImageIndex].get(); } bool SurfaceRenderableResource::hasSurfaceTransformSupport() const { @@ -261,7 +268,7 @@ bool SurfaceRenderableResource::hasSurfaceTransformSupport() const { bool SurfaceRenderableResource::didSurfaceTransformUpdate() const { const auto& physicalDevice = backend.getPhysicalDevice(); - const auto& updatedCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface.get()); + const auto& updatedCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface.get(), backend.getDispatcher()); return capabilities.currentTransform != updatedCapabilities.currentTransform; } @@ -294,6 +301,7 @@ void SurfaceRenderableResource::init(uint32_t w, uint32_t h) { } const auto& device = backend.getDevice(); + const auto& dispatcher = backend.getDispatcher(); // create swapchain image views swapchainImageViews.reserve(swapchainImages.size()); @@ -306,7 +314,7 @@ void SurfaceRenderableResource::init(uint32_t w, uint32_t h) { for (const auto& image : swapchainImages) { imageViewCreateInfo.setImage(image); - swapchainImageViews.push_back(device->createImageViewUnique(imageViewCreateInfo)); + swapchainImageViews.push_back(device->createImageViewUnique(imageViewCreateInfo, nullptr, dispatcher)); const size_t index = swapchainImageViews.size() - 1; backend.setDebugName(image, "SwapchainImage_" + std::to_string(index)); @@ -372,7 +380,7 @@ void SurfaceRenderableResource::init(uint32_t w, uint32_t h) { const auto renderPassCreateInfo = vk::RenderPassCreateInfo().setAttachments(attachments).setSubpasses(subpass).setDependencies(dependencies); - renderPass = device->createRenderPassUnique(renderPassCreateInfo); + renderPass = device->createRenderPassUnique(renderPassCreateInfo, nullptr, dispatcher); // create swapchain framebuffers swapchainFramebuffers.reserve(swapchainImageViews.size()); @@ -388,20 +396,21 @@ void SurfaceRenderableResource::init(uint32_t w, uint32_t h) { const std::array imageViews = {imageView.get(), depthAllocation->imageView.get()}; framebufferCreateInfo.setAttachments(imageViews); - swapchainFramebuffers.push_back(device->createFramebufferUnique(framebufferCreateInfo)); + swapchainFramebuffers.push_back(device->createFramebufferUnique(framebufferCreateInfo, nullptr, dispatcher)); } } void SurfaceRenderableResource::recreateSwapchain() { if (!surface) return; - backend.getDevice()->waitIdle(); + backend.getDevice()->waitIdle(backend.getDispatcher()); swapchainFramebuffers.clear(); renderPass.reset(); swapchainImageViews.clear(); swapchainImages.clear(); - swapchainSemaphores.clear(); + acquireSemaphores.clear(); + presentSemaphores.clear(); init(extent.width, extent.height); } diff --git a/src/mbgl/vulkan/renderer_backend.cpp b/src/mbgl/vulkan/renderer_backend.cpp index a1c7d3ba7..ff9a28d06 100644 --- a/src/mbgl/vulkan/renderer_backend.cpp +++ b/src/mbgl/vulkan/renderer_backend.cpp @@ -34,8 +34,6 @@ #include #endif -VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE - #ifdef ENABLE_VMA_DEBUG #define VMA_DEBUG_MARGIN 16 @@ -138,7 +136,7 @@ std::vector RendererBackend::getDeviceExtensions() { std::vector RendererBackend::getDebugExtensions() { std::vector extensions; - const auto& availableExtensions = vk::enumerateInstanceExtensionProperties(); + const auto& availableExtensions = vk::enumerateInstanceExtensionProperties(nullptr, dispatcher); debugUtilsEnabled = checkAvailability( availableExtensions, {VK_EXT_DEBUG_UTILS_EXTENSION_NAME}, [](const vk::ExtensionProperties& value) { @@ -169,14 +167,14 @@ void RendererBackend::beginDebugLabel([[maybe_unused]] const vk::CommandBuffer& [[maybe_unused]] const std::array& color) const { #ifdef ENABLE_VULKAN_VALIDATION if (!debugUtilsEnabled) return; - buffer.beginDebugUtilsLabelEXT(vk::DebugUtilsLabelEXT().setPLabelName(name).setColor(color)); + buffer.beginDebugUtilsLabelEXT(vk::DebugUtilsLabelEXT().setPLabelName(name).setColor(color), dispatcher); #endif } void RendererBackend::endDebugLabel([[maybe_unused]] const vk::CommandBuffer& buffer) const { #ifdef ENABLE_VULKAN_VALIDATION if (!debugUtilsEnabled) return; - buffer.endDebugUtilsLabelEXT(); + buffer.endDebugUtilsLabelEXT(dispatcher); #endif } @@ -184,7 +182,7 @@ void RendererBackend::insertDebugLabel([[maybe_unused]] const vk::CommandBuffer& [[maybe_unused]] const char* name) const { #ifdef ENABLE_VULKAN_VALIDATION if (!debugUtilsEnabled) return; - buffer.insertDebugUtilsLabelEXT(vk::DebugUtilsLabelEXT().setPLabelName(name)); + buffer.insertDebugUtilsLabelEXT(vk::DebugUtilsLabelEXT().setPLabelName(name), dispatcher); #endif } @@ -337,7 +335,7 @@ void RendererBackend::initDebug() { vk::DebugUtilsMessengerCreateInfoEXT().setMessageSeverity(severity).setMessageType(type).setPfnUserCallback( vkDebugUtilsCallback); - debugUtilsCallback = instance->createDebugUtilsMessengerEXTUnique(createInfo); + debugUtilsCallback = instance->createDebugUtilsMessengerEXTUnique(createInfo, nullptr, dispatcher); if (!debugUtilsCallback) { mbgl::Log::Error(mbgl::Event::Render, "Failed to register Vulkan debug utils callback"); @@ -352,7 +350,7 @@ void RendererBackend::initDebug() { const auto createInfo = vk::DebugReportCallbackCreateInfoEXT().setFlags(flags).setPfnCallback( vkDebugReportCallback); - debugReportCallback = instance->createDebugReportCallbackEXTUnique(createInfo); + debugReportCallback = instance->createDebugReportCallbackEXTUnique(createInfo, nullptr, dispatcher); if (!debugReportCallback) { mbgl::Log::Error(mbgl::Event::Render, "Failed to register Vulkan debug report callback"); @@ -372,8 +370,12 @@ void RendererBackend::init() { } void RendererBackend::initInstance() { + // VULKAN_HPP_DEFAULT_DISPATCHER is global and can lead to race conditions in multi-map environments + static std::mutex vkDefaultDispatchLoaderMutex; + std::lock_guard lock(vkDefaultDispatchLoaderMutex); + // initialize minimal set of function pointers - VULKAN_HPP_DEFAULT_DISPATCHER.init(dynamicLoader); + dispatcher.init(dynamicLoader); // Vulkan 1.1 on Android is supported on 71% of devices (compared to 1.3 with 6%) as of April 23 2024 // https://vulkan.gpuinfo.org/ @@ -388,7 +390,7 @@ void RendererBackend::initInstance() { const auto& layers = getLayers(); - bool layersAvailable = checkAvailability(vk::enumerateInstanceLayerProperties(), + bool layersAvailable = checkAvailability(vk::enumerateInstanceLayerProperties(dispatcher), layers, [](const vk::LayerProperties& value) { return value.layerName.data(); }); @@ -401,9 +403,9 @@ void RendererBackend::initInstance() { auto extensions = getInstanceExtensions(); bool extensionsAvailable = checkAvailability( - vk::enumerateInstanceExtensionProperties(), extensions, [](const vk::ExtensionProperties& value) { - return value.extensionName.data(); - }); + vk::enumerateInstanceExtensionProperties(nullptr, dispatcher), + extensions, + [](const vk::ExtensionProperties& value) { return value.extensionName.data(); }); #ifdef ENABLE_VULKAN_VALIDATION const auto& debugExtensions = getDebugExtensions(); @@ -427,10 +429,10 @@ void RendererBackend::initInstance() { mbgl::Log::Error(mbgl::Event::Render, "Vulkan extensions not found"); } - instance = vk::createInstanceUnique(createInfo); + instance = vk::createInstanceUnique(createInfo, nullptr, dispatcher); // initialize function pointers for instance - VULKAN_HPP_DEFAULT_DISPATCHER.init(instance.get()); + dispatcher.init(instance.get()); #ifdef ENABLE_VULKAN_VALIDATION // enable validation layer callback @@ -445,32 +447,31 @@ void RendererBackend::initSurface() { void RendererBackend::initAllocator() { VmaVulkanFunctions functions = {}; - functions.vkGetInstanceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetInstanceProcAddr; - functions.vkGetDeviceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetDeviceProcAddr; + functions.vkGetInstanceProcAddr = dispatcher.vkGetInstanceProcAddr; + functions.vkGetDeviceProcAddr = dispatcher.vkGetDeviceProcAddr; - functions.vkGetPhysicalDeviceProperties = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetPhysicalDeviceProperties; - functions.vkGetPhysicalDeviceMemoryProperties = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetPhysicalDeviceMemoryProperties; - functions.vkAllocateMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkAllocateMemory; - functions.vkFreeMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkFreeMemory; - functions.vkMapMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkMapMemory; - functions.vkUnmapMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkUnmapMemory; - functions.vkFlushMappedMemoryRanges = VULKAN_HPP_DEFAULT_DISPATCHER.vkFlushMappedMemoryRanges; - functions.vkInvalidateMappedMemoryRanges = VULKAN_HPP_DEFAULT_DISPATCHER.vkInvalidateMappedMemoryRanges; - functions.vkBindBufferMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindBufferMemory; - functions.vkBindImageMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindImageMemory; - functions.vkGetBufferMemoryRequirements = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetBufferMemoryRequirements; - functions.vkGetImageMemoryRequirements = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetImageMemoryRequirements; - functions.vkCreateBuffer = VULKAN_HPP_DEFAULT_DISPATCHER.vkCreateBuffer; - functions.vkDestroyBuffer = VULKAN_HPP_DEFAULT_DISPATCHER.vkDestroyBuffer; - functions.vkCreateImage = VULKAN_HPP_DEFAULT_DISPATCHER.vkCreateImage; - functions.vkDestroyImage = VULKAN_HPP_DEFAULT_DISPATCHER.vkDestroyImage; - functions.vkCmdCopyBuffer = VULKAN_HPP_DEFAULT_DISPATCHER.vkCmdCopyBuffer; - functions.vkGetBufferMemoryRequirements2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetBufferMemoryRequirements2KHR; - functions.vkGetImageMemoryRequirements2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetImageMemoryRequirements2KHR; - functions.vkBindBufferMemory2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindBufferMemory2KHR; - functions.vkBindImageMemory2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindImageMemory2KHR; - functions.vkGetPhysicalDeviceMemoryProperties2KHR = - VULKAN_HPP_DEFAULT_DISPATCHER.vkGetPhysicalDeviceMemoryProperties2KHR; + functions.vkGetPhysicalDeviceProperties = dispatcher.vkGetPhysicalDeviceProperties; + functions.vkGetPhysicalDeviceMemoryProperties = dispatcher.vkGetPhysicalDeviceMemoryProperties; + functions.vkAllocateMemory = dispatcher.vkAllocateMemory; + functions.vkFreeMemory = dispatcher.vkFreeMemory; + functions.vkMapMemory = dispatcher.vkMapMemory; + functions.vkUnmapMemory = dispatcher.vkUnmapMemory; + functions.vkFlushMappedMemoryRanges = dispatcher.vkFlushMappedMemoryRanges; + functions.vkInvalidateMappedMemoryRanges = dispatcher.vkInvalidateMappedMemoryRanges; + functions.vkBindBufferMemory = dispatcher.vkBindBufferMemory; + functions.vkBindImageMemory = dispatcher.vkBindImageMemory; + functions.vkGetBufferMemoryRequirements = dispatcher.vkGetBufferMemoryRequirements; + functions.vkGetImageMemoryRequirements = dispatcher.vkGetImageMemoryRequirements; + functions.vkCreateBuffer = dispatcher.vkCreateBuffer; + functions.vkDestroyBuffer = dispatcher.vkDestroyBuffer; + functions.vkCreateImage = dispatcher.vkCreateImage; + functions.vkDestroyImage = dispatcher.vkDestroyImage; + functions.vkCmdCopyBuffer = dispatcher.vkCmdCopyBuffer; + functions.vkGetBufferMemoryRequirements2KHR = dispatcher.vkGetBufferMemoryRequirements2KHR; + functions.vkGetImageMemoryRequirements2KHR = dispatcher.vkGetImageMemoryRequirements2KHR; + functions.vkBindBufferMemory2KHR = dispatcher.vkBindBufferMemory2KHR; + functions.vkBindImageMemory2KHR = dispatcher.vkBindImageMemory2KHR; + functions.vkGetPhysicalDeviceMemoryProperties2KHR = dispatcher.vkGetPhysicalDeviceMemoryProperties2KHR; VmaAllocatorCreateInfo allocatorCreateInfo = {}; @@ -493,16 +494,16 @@ void RendererBackend::initDevice() { const auto& isPhysicalDeviceCompatible = [&](const vk::PhysicalDevice& candidate) -> bool { bool extensionsAvailable = checkAvailability( - candidate.enumerateDeviceExtensionProperties(), extensions, [](const vk::ExtensionProperties& value) { - return value.extensionName.data(); - }); + candidate.enumerateDeviceExtensionProperties(nullptr, dispatcher), + extensions, + [](const vk::ExtensionProperties& value) { return value.extensionName.data(); }); if (!extensionsAvailable) return false; graphicsQueueIndex = -1; presentQueueIndex = -1; - const auto& queues = candidate.getQueueFamilyProperties(); + const auto& queues = candidate.getQueueFamilyProperties(dispatcher); // Use to test on specific GPU type (if multiple) // if (candidate.getProperties().deviceType != vk::PhysicalDeviceType::eIntegratedGpu) return false; @@ -513,7 +514,7 @@ void RendererBackend::initDevice() { if (queue.queueCount == 0) continue; if (queue.queueFlags & vk::QueueFlagBits::eGraphics) graphicsQueueIndex = i; - if (surface && candidate.getSurfaceSupportKHR(i, surface)) presentQueueIndex = i; + if (surface && candidate.getSurfaceSupportKHR(i, surface, dispatcher)) presentQueueIndex = i; if (graphicsQueueIndex != -1 && (!surface || presentQueueIndex != -1)) break; } @@ -521,15 +522,15 @@ void RendererBackend::initDevice() { if (graphicsQueueIndex == -1 || (surface && presentQueueIndex == -1)) return false; if (surface) { - if (candidate.getSurfaceFormatsKHR(surface).empty()) return false; - if (candidate.getSurfacePresentModesKHR(surface).empty()) return false; + if (candidate.getSurfaceFormatsKHR(surface, dispatcher).empty()) return false; + if (candidate.getSurfacePresentModesKHR(surface, dispatcher).empty()) return false; } return true; }; const auto& pickPhysicalDevice = [&]() { - const auto& physicalDevices = instance->enumeratePhysicalDevices(); + const auto& physicalDevices = instance->enumeratePhysicalDevices(dispatcher); if (physicalDevices.empty()) throw std::runtime_error("No Vulkan compatible GPU found"); for (const auto& candidate : physicalDevices) { @@ -541,7 +542,7 @@ void RendererBackend::initDevice() { if (!physicalDevice) throw std::runtime_error("No suitable GPU found"); - physicalDeviceProperties = physicalDevice.getProperties(); + physicalDeviceProperties = physicalDevice.getProperties(dispatcher); }; pickPhysicalDevice(); @@ -555,7 +556,7 @@ void RendererBackend::initDevice() { if (surface && graphicsQueueIndex != presentQueueIndex) queueCreateInfos.emplace_back(vk::DeviceQueueCreateFlags(), presentQueueIndex, 1, &queuePriority); - [[maybe_unused]] const auto& supportedDeviceFeatures = physicalDevice.getFeatures(); + [[maybe_unused]] const auto& supportedDeviceFeatures = physicalDevice.getFeatures(dispatcher); physicalDeviceFeatures = vk::PhysicalDeviceFeatures(); // TODO @@ -588,13 +589,13 @@ void RendererBackend::initDevice() { // this is not needed for newer implementations createInfo.setPEnabledLayerNames(layers); - device = physicalDevice.createDeviceUnique(createInfo); + device = physicalDevice.createDeviceUnique(createInfo, nullptr, dispatcher); // optional function pointer specialization for device - VULKAN_HPP_DEFAULT_DISPATCHER.init(device.get()); + dispatcher.init(device.get()); - graphicsQueue = device->getQueue(graphicsQueueIndex, 0); - if (presentQueueIndex != -1) presentQueue = device->getQueue(presentQueueIndex, 0); + graphicsQueue = device->getQueue(graphicsQueueIndex, 0, dispatcher); + if (presentQueueIndex != -1) presentQueue = device->getQueue(presentQueueIndex, 0, dispatcher); } void RendererBackend::initSwapchain() { @@ -618,11 +619,11 @@ void RendererBackend::initSwapchain() { void RendererBackend::initCommandPool() { const vk::CommandPoolCreateInfo createInfo(vk::CommandPoolCreateFlagBits::eResetCommandBuffer, graphicsQueueIndex); - commandPool = device->createCommandPoolUnique(createInfo); + commandPool = device->createCommandPoolUnique(createInfo, nullptr, dispatcher); } void RendererBackend::destroyResources() { - if (device) device->waitIdle(); + if (device) device->waitIdle(dispatcher); context.reset(); commandPool.reset(); diff --git a/src/mbgl/vulkan/texture2d.cpp b/src/mbgl/vulkan/texture2d.cpp index 235848d77..09b272adb 100644 --- a/src/mbgl/vulkan/texture2d.cpp +++ b/src/mbgl/vulkan/texture2d.cpp @@ -159,7 +159,8 @@ void Texture2D::uploadSubRegion(const void* pixelData, if (!imageAllocation) return; - const auto& allocator = context.getBackend().getAllocator(); + const auto& backend = context.getBackend(); + const auto& allocator = backend.getAllocator(); const auto bufferInfo = vk::BufferCreateInfo() .setSize(static_cast(size_.width) * size_.height * getPixelStride()) @@ -192,7 +193,8 @@ void Texture2D::uploadSubRegion(const void* pixelData, .setImageOffset(vk::Offset3D(xOffset, yOffset)) .setImageExtent(vk::Extent3D(size_.width, size_.height, 1)); - buffer->copyBufferToImage(bufferAllocation->buffer, imageAllocation->image, imageLayout, region); + buffer->copyBufferToImage( + bufferAllocation->buffer, imageAllocation->image, imageLayout, region, backend.getDispatcher()); if (samplerState.mipmapped && textureUsage == Texture2DUsage::ShaderInput) { generateMips(buffer); @@ -346,7 +348,8 @@ void Texture2D::createTexture() { .setSubresourceRange( {vk::ImageAspectFlagBits::eColor, 0, imageCreateInfo.mipLevels, 0, 1}); - imageAllocation->imageView = backend.getDevice()->createImageViewUnique(imageViewCreateInfo); + imageAllocation->imageView = backend.getDevice()->createImageViewUnique( + imageViewCreateInfo, nullptr, backend.getDispatcher()); } // if the image is used as an attachment @@ -368,6 +371,8 @@ void Texture2D::createTexture() { void Texture2D::createSampler() { destroySampler(); + const auto& backend = context.getBackend(); + const auto filter = vulkanFilter(samplerState.filter); const auto addressModeU = vulkanAddressMode(samplerState.wrapU); const auto addressModeV = vulkanAddressMode(samplerState.wrapV); @@ -385,11 +390,11 @@ void Texture2D::createSampler() { samplerCreateInfo.setMipmapMode(vk::SamplerMipmapMode::eLinear); } - if (samplerState.maxAnisotropy != 1 && context.getBackend().getDeviceFeatures().samplerAnisotropy) { + if (samplerState.maxAnisotropy != 1 && backend.getDeviceFeatures().samplerAnisotropy) { samplerCreateInfo.setAnisotropyEnable(true).setMaxAnisotropy(samplerState.maxAnisotropy); } - sampler = context.getBackend().getDevice()->createSampler(samplerCreateInfo); + sampler = backend.getDevice()->createSampler(samplerCreateInfo, nullptr, backend.getDispatcher()); samplerStateDirty = false; lastModified = util::MonotonicTimer::now(); @@ -409,7 +414,7 @@ void Texture2D::destroyTexture() { void Texture2D::destroySampler() { if (sampler) { context.enqueueDeletion([sampler_ = std::move(sampler)](auto& context_) mutable { - context_.getBackend().getDevice()->destroySampler(sampler_); + context_.getBackend().getDevice()->destroySampler(sampler_, nullptr, context_.getBackend().getDispatcher()); }); sampler = nullptr; @@ -427,8 +432,13 @@ void Texture2D::transitionToTransferLayout(const vk::UniqueCommandBuffer& buffer .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setSubresourceRange({vk::ImageAspectFlagBits::eColor, 0, getMipLevels(), 0, 1}); - buffer->pipelineBarrier( - vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, nullptr, barrier); + buffer->pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eTransfer, + {}, + nullptr, + nullptr, + barrier, + context.getBackend().getDispatcher()); imageLayout = barrier.newLayout; } @@ -449,7 +459,8 @@ void Texture2D::transitionToShaderReadLayout(const vk::UniqueCommandBuffer& buff {}, nullptr, nullptr, - barrier); + barrier, + context.getBackend().getDispatcher()); imageLayout = barrier.newLayout; } @@ -465,8 +476,13 @@ void Texture2D::transitionToGeneralLayout(const vk::UniqueCommandBuffer& buffer) .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED) .setSubresourceRange({vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}); - buffer->pipelineBarrier( - vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, nullptr, barrier); + buffer->pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eTransfer, + {}, + nullptr, + nullptr, + barrier, + context.getBackend().getDispatcher()); imageLayout = barrier.newLayout; } @@ -491,8 +507,12 @@ void Texture2D::copyImage(vk::Image image) { .setExtent({size.width, size.height, 1}); transitionToTransferLayout(commandBuffer); - commandBuffer->copyImage( - image, vk::ImageLayout::eTransferSrcOptimal, imageAllocation->image, imageLayout, copyInfo); + commandBuffer->copyImage(image, + vk::ImageLayout::eTransferSrcOptimal, + imageAllocation->image, + imageLayout, + copyInfo, + context.getBackend().getDispatcher()); transitionToGeneralLayout(commandBuffer); }); } @@ -505,7 +525,8 @@ std::shared_ptr Texture2D::readImage() { // check for offset/padding const auto& device = context.getBackend().getDevice(); const auto& layout = device->getImageSubresourceLayout(imageAllocation->image, - vk::ImageSubresource(vk::ImageAspectFlagBits::eColor, 0, 0)); + vk::ImageSubresource(vk::ImageAspectFlagBits::eColor, 0, 0), + context.getBackend().getDispatcher()); imageData->resize(size); const auto& imageSize = getDataSize(); @@ -544,6 +565,8 @@ void Texture2D::generateMips(const vk::UniqueCommandBuffer& buffer) { return; } + const auto& dispatcher = context.getBackend().getDispatcher(); + int32_t mipWidth = size.width; int32_t mipHeight = size.height; @@ -562,8 +585,13 @@ void Texture2D::generateMips(const vk::UniqueCommandBuffer& buffer) { .setSrcAccessMask(vk::AccessFlagBits::eTransferWrite) .setDstAccessMask(vk::AccessFlagBits::eTransferRead); - buffer->pipelineBarrier( - vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, nullptr, barrier); + buffer->pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eTransfer, + {}, + nullptr, + nullptr, + barrier, + dispatcher); const auto blit = vk::ImageBlit() .setSrcOffsets({vk::Offset3D{0, 0, 0}, {mipWidth, mipHeight, 1}}) @@ -576,7 +604,8 @@ void Texture2D::generateMips(const vk::UniqueCommandBuffer& buffer) { imageAllocation->image, barrier.oldLayout, blit, - vk::Filter::eLinear); + vk::Filter::eLinear, + dispatcher); barrier.setOldLayout(vk::ImageLayout::eTransferSrcOptimal) .setNewLayout(vk::ImageLayout::eShaderReadOnlyOptimal) @@ -588,7 +617,8 @@ void Texture2D::generateMips(const vk::UniqueCommandBuffer& buffer) { {}, nullptr, nullptr, - barrier); + barrier, + dispatcher); mipWidth = std::max(1, mipWidth / 2); mipHeight = std::max(1, mipHeight / 2); @@ -607,7 +637,8 @@ void Texture2D::generateMips(const vk::UniqueCommandBuffer& buffer) { {}, nullptr, nullptr, - barrier); + barrier, + dispatcher); imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; }