mln-rs-runtime 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! Vulkan backend glue for targets, rings, surfaces, and devices.

use std::ffi::CStr;
use std::sync::Arc;

use mln_gfx::{ExportKind, ExportedRing, RendererBackend as _, SyncKind, SyncKinds, Window};
use mln_style::error::Error;

use crate::render::gfx_error;
use crate::render::local::{
    BackendRef, Borrowed, Exported, FramesInit, Gfx, LocalBackend, Target, gfx, no_surface, overlay_of, presenting,
};
use crate::render::target::{
    Adapter, BorrowedRing, DepthStencilFormat, Device, FrameDepth, FrameTexture, FrameTextureKind, NativeTexture,
    RingKind, Surface, SurfaceKind, SurfaceOverlay, SurfaceType,
};

impl BorrowedRing {
    /// A ring of the host's Vulkan images.
    #[must_use]
    pub fn vulkan(images: mln_vulkan::BorrowedImages) -> BorrowedRing {
        BorrowedRing { kind: RingKind::Vulkan(images) }
    }
}

impl Surface {
    /// The host's `VkSurfaceKHR`, which a session on the Vulkan device
    /// whose instance made it presents to. The surface stays the host's.
    #[must_use]
    pub fn vulkan(surface: mln_vulkan::HostSurface) -> Surface {
        Surface::of(SurfaceKind::Vulkan(surface))
    }
}

pub(in super::super) fn native_texture(
    image: u64,
    view: u64,
    format: i32,
    layout: i32,
    device: &mln_vulkan::Device,
) -> FrameTextureKind {
    use mln_vulkan::ash::vk::Handle as _;
    FrameTextureKind::Vulkan { image, view, device: device.raw().device.as_raw(), format, layout }
}

pub(in super::super) fn ring_depth_stencil_format(images: &mln_vulkan::BorrowedImages) -> Option<DepthStencilFormat> {
    let depth = images.depth.as_ref()?;
    mln_vulkan::device::depth_stencil_format(depth.format)
}

pub(in super::super) fn ring_same_texture(
    images: &mln_vulkan::BorrowedImages,
    slot: usize,
    others: &mln_vulkan::BorrowedImages,
    other_slot: usize,
) -> bool {
    images.images.get(slot).zip(others.images.get(other_slot)).is_some_and(|(image, other)| image.image == other.image)
}

pub(in super::super) fn ring_texture(
    images: &mln_vulkan::BorrowedImages,
    slot: usize,
    device: &mln_vulkan::Device,
) -> Option<FrameTexture> {
    use mln_vulkan::ash::vk::Handle as _;
    let depth = images.depth.as_ref().and_then(|depth| {
        depth.images.get(slot).map(|image| FrameDepth {
            texture: NativeTexture::Vulkan {
                image: image.image.as_raw(),
                view: image.view.as_raw(),
                format: depth.format.as_raw(),
                layout: depth.final_layout.as_raw(),
            },
            export: None,
        })
    });
    images.images.get(slot).map(|image| FrameTexture {
        size: images.size,
        kind: FrameTextureKind::Vulkan {
            image: image.image.as_raw(),
            view: image.view.as_raw(),
            device: device.raw().device.as_raw(),
            format: images.format.as_raw(),
            layout: images.final_layout.as_raw(),
        },
        native: None,
        depth,
    })
}

/// The Vulkan instance extension that makes the surfaces of `surface`'s type.
pub(in super::super) fn surface_extension(surface: SurfaceType) -> Option<&'static CStr> {
    use mln_vulkan::ash::khr;
    match surface {
        SurfaceType::MetalLayer => None,
        SurfaceType::Win32 => Some(khr::win32_surface::NAME),
        SurfaceType::Xlib => Some(khr::xlib_surface::NAME),
        SurfaceType::Xcb => Some(khr::xcb_surface::NAME),
        SurfaceType::Wayland => Some(khr::wayland_surface::NAME),
        SurfaceType::AndroidNdk => Some(khr::android_surface::NAME),
        SurfaceType::OhosNdk => Some(mln_vulkan::device::OHOS_SURFACE),
    }
}

pub(in super::super) fn create_device(adapter: Option<Adapter>) -> Result<Device, Error> {
    match adapter {
        None => mln_vulkan::Device::new(None),
        Some(Adapter::Index(index)) => mln_vulkan::Device::new(Some(index)),
        Some(Adapter::Uuid(uuid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Uuid(uuid)),
        Some(Adapter::Luid(luid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Luid(luid)),
    }
    .map(Device::Vulkan)
    .map_err(gfx_error)
}

pub(in super::super) fn borrowed_sync_kinds(
    device: &mln_vulkan::Device,
    images: &mln_vulkan::BorrowedImages,
) -> Result<(SyncKinds, SyncKinds), Error> {
    images.check(device).map_err(gfx_error)?;
    Ok(device.sync_kinds())
}

pub(in super::super) fn export_plan(
    device: &mln_vulkan::Device,
    ring: &ExportedRing,
) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
    let kind = mln_vulkan::exported_target::plan(device, ring).map_err(gfx_error)?;
    let (producer, consumer) = mln_vulkan::exported_target::sync_kinds(device);
    Ok((kind, producer, consumer))
}

fn overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
    overlay_of(overlay, |overlay| match overlay {
        SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
        other => Err(other),
    })
}

impl LocalBackend for mln_vulkan::RendererBackend {
    type RingTextures = mln_vulkan::BorrowedImages;

    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
        if let RingKind::Vulkan(images) = ring { Some(images) } else { None }
    }

    fn by_type(&self) -> BackendRef<'_> {
        BackendRef::Vulkan(self)
    }

    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
        Ok(Box::new(mln_vulkan::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
    }

    fn exported(
        &mut self,
        _device: &Device,
        ring: &ExportedRing,
        kind: ExportKind,
        size: mln_gfx::Size,
        producer: SyncKind,
    ) -> Result<Box<dyn Exported<Self>>, Error> {
        Ok(Box::new(mln_vulkan::ExportedTarget::new(self, ring, kind, size, producer).map_err(gfx_error)?))
    }

    fn surface(
        &mut self,
        surface: Surface,
        surface_overlay: Option<SurfaceOverlay>,
        size: mln_gfx::Size,
    ) -> Result<Target<Self>, Error> {
        let surface_overlay = overlay(surface_overlay)?;
        let mut target = match surface.kind {
            SurfaceKind::Window(window) => {
                mln_vulkan::SurfaceTarget::new(self, window, size, surface.cap_frame_rate).map_err(gfx_error)?
            }
            SurfaceKind::Vulkan(host) => {
                mln_vulkan::SurfaceTarget::on_host_surface(self, host, size, surface.cap_frame_rate)
                    .map_err(gfx_error)?
            }
            _ => return Err(no_surface()),
        };
        target.set_overlay(self.gpu(), surface_overlay);
        Ok(Box::new(target))
    }
}

pub(in super::super) fn new_gfx(device: &mln_vulkan::Device, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
    gfx(mln_vulkan::RendererBackend::new(device).map_err(gfx_error)?, init)
}

pub(in super::super) fn window_surface_gfx(
    device: &mln_vulkan::Device,
    window: Arc<dyn Window>,
    surface_overlay: Option<SurfaceOverlay>,
    size: mln_gfx::Size,
    cap_frame_rate: bool,
) -> Result<Box<dyn Gfx>, Error> {
    let surface_overlay = overlay(surface_overlay)?;
    let (mut backend, mut target) =
        mln_vulkan::SurfaceTarget::with_backend(device, window, size, cap_frame_rate).map_err(gfx_error)?;
    target.set_overlay(backend.gpu(), surface_overlay);
    Ok(presenting(backend, target))
}

pub(in super::super) fn host_surface_gfx(
    device: &mln_vulkan::Device,
    kind: SurfaceKind,
    surface_overlay: Option<SurfaceOverlay>,
    size: mln_gfx::Size,
    cap_frame_rate: bool,
) -> Result<Box<dyn Gfx>, Error> {
    gfx(
        mln_vulkan::RendererBackend::presenting(device).map_err(gfx_error)?,
        FramesInit::Surface(Surface { kind, cap_frame_rate }, surface_overlay, size),
    )
}