packages feed

keid-core-0.2.0.0: src/Engine/Vulkan/Swapchain.hs

{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedRecordDot #-}

module Engine.Vulkan.Swapchain
  ( SwapchainResources(..)
  , allocSwapchainResources
  , recreateSwapchainResources
  , threwSwapchainError

  , setDynamic
  , setDynamicFullscreen
  ) where

import RIO

import Data.Bits (zeroBits, (.&.))
import RIO.Vector qualified as V
import UnliftIO.Resource (MonadResource)
import Vulkan.Core10 qualified as Vk
import Vulkan.Extensions.VK_KHR_surface qualified as Khr
import Vulkan.Extensions.VK_KHR_swapchain qualified as Khr
import Vulkan.Utils.FrameGraph.Image (ManagedImage)
import Vulkan.Utils.FrameGraph.Swapchain (forgetSwapchainImages, newSwapchainImages)
import Vulkan.Utils.Misc ((.&&.))
import Vulkan.Utils.Swapchain (Swapchain(..))
import Vulkan.Utils.Swapchain qualified as Utils
import Vulkan.NamedType ((:::))
import Vulkan.Zero (zero)

import Engine.Vulkan.Capabilities qualified as Capabilities
import Engine.Vulkan.Types (HasVulkan(..), HasSwapchain(..), pdiCapabilities)
import Render.Graph (HasSliceRegistry(..))

data SwapchainResources = SwapchainResources
  { srSwapchain     :: Swapchain
  , srTrackedImages :: Vector ManagedImage
  , srMinImageCount :: Word32
  , srDepthFormat   :: Vk.Format
  , srMultisample   :: Vk.SampleCountFlagBits
  , srAnisotropy    :: Float
  }

instance HasSwapchain SwapchainResources where
  getSurfaceExtent  = sExtent . srSwapchain
  getSurfaceFormat  = Khr.format . sFormat . srSwapchain
  getDepthFormat    = srDepthFormat
  getMultisample    = srMultisample
  getAnisotropy     = srAnisotropy
  getSwapchainViews = sImageViews . srSwapchain
  getMinImageCount  = srMinImageCount
  getImageCount     = fromIntegral . V.length . sImages . srSwapchain

allocSwapchainResources
  :: ( MonadResource (RIO env)
     , HasVulkan env
     , HasSliceRegistry env
     , HasLogFunc env
     )
  => Maybe Khr.PresentModeKHR
  -> Vk.SampleCountFlagBits
  -> Khr.SwapchainKHR
  -- ^ Previous swapchain, can be NULL_HANDLE
  -> Vk.Extent2D
  -- ^ If the swapchain size determines the surface size, use this size
  -> Khr.SurfaceKHR
  -> RIO env SwapchainResources
allocSwapchainResources present msaa oldSwapchain windowSize surface = do
  logDebug "Allocating swapchain resources"
  physical <- asks getPhysicalDevice
  device <- asks getDevice
  swapchain <- Utils.allocateSwapchain
    physical
    device
    (swapchainConfig present)
    oldSwapchain
    windowSize
    surface
  resourcesFor msaa swapchain

recreateSwapchainResources
  :: ( MonadResource (RIO env)
     , HasVulkan env
     , HasSliceRegistry env
     , HasLogFunc env
     )
  => Vk.SampleCountFlagBits
  -> Vk.Extent2D
  -> SwapchainResources
  -- ^ The reference to these resources will be dropped
  -> RIO env SwapchainResources
recreateSwapchainResources msaa windowSize old = do
  logDebug "Allocating swapchain resources"
  physical <- asks getPhysicalDevice
  device <- asks getDevice
  registry <- asks getSliceRegistry
  forgetSwapchainImages registry old.srSwapchain
  swapchain <- Utils.recreateSwapchain physical device windowSize old.srSwapchain
  resourcesFor msaa swapchain

swapchainConfig :: Maybe Khr.PresentModeKHR -> Utils.SwapchainConfig
swapchainConfig present = Utils.defaultSwapchainConfig
  { Utils.scDesiredPresentModes =
      maybe (Utils.scDesiredPresentModes Utils.defaultSwapchainConfig) pure present
  , Utils.scSurfaceFormatPreferences =
      [Utils.srgbEncoding]
  }

resourcesFor
  :: ( HasVulkan env
     , HasSliceRegistry env
     , HasLogFunc env
     )
  => Vk.SampleCountFlagBits
  -> Swapchain
  -> RIO env SwapchainResources
resourcesFor msaa swapchain = do
  physical <- asks getPhysicalDevice
  caps <- asks $ pdiCapabilities . getPhysicalDeviceInfo
  surfaceCaps <- Khr.getPhysicalDeviceSurfaceCapabilitiesKHR physical swapchain.sSurface
  registry <- asks getSliceRegistry
  trackedImages <- newSwapchainImages registry swapchain

  depthFormat <- getDepthFormats physical preferDepth >>= \case
    fmt : _rest ->
      pure fmt
    _none ->
      throwString "Unable to find a suitable depth format"

  logDebug $ mconcat
    [ "Swapchain "
    , displayShow swapchain.sExtent
    , " "
    , displayShow swapchain.sFormat
    , " "
    , displayShow swapchain.sPresentMode
    , ", images: "
    , display (V.length swapchain.sImages)
    ]

  pure SwapchainResources
    { srSwapchain     = swapchain
    , srTrackedImages = trackedImages
    , srMinImageCount = requestedImageCount surfaceCaps
    , srDepthFormat   = depthFormat
    , srMultisample   = msaaSamples msaa (Capabilities.capsProperties caps)
    , srAnisotropy    = Capabilities.anisotropyLimit caps
    }

requestedImageCount :: Khr.SurfaceCapabilitiesKHR -> Word32
requestedImageCount surfaceCaps =
  min limit (1 + surfaceCaps.minImageCount)
  where
    limit =
      case surfaceCaps.maxImageCount of
        0 -> maxBound
        n -> n

getDepthFormats
  :: MonadIO io
  => Vk.PhysicalDevice
  -> [Vk.Format]
  -> io [Vk.Format]
getDepthFormats device desiredDepthFormats = do
  properties <- traverse (Vk.getPhysicalDeviceFormatProperties device) desiredDepthFormats
  pure do
    (format, props) <- zip desiredDepthFormats properties
    guard $
      Vk.optimalTilingFeatures props .&&. Vk.FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
    guard $
      Vk.optimalTilingFeatures props .&&. Vk.FORMAT_FEATURE_SAMPLED_IMAGE_BIT
    pure format

preferDepth :: [Vk.Format]
preferDepth =
  [ Vk.FORMAT_D32_SFLOAT
  , Vk.FORMAT_X8_D24_UNORM_PACK32
  , Vk.FORMAT_D16_UNORM
  ]

msaaSamples
  :: Vk.SampleCountFlagBits
  -> Vk.PhysicalDeviceProperties
  -> Vk.SampleCountFlagBits
msaaSamples upperLimit Vk.PhysicalDeviceProperties{limits} =
  case samplesAvailable of
    [] ->
      -- XXX: Something went wrong...
      Vk.SAMPLE_COUNT_1_BIT
    best : _rest ->
      best
  where
    counts =
      Vk.framebufferColorSampleCounts limits .&.
      Vk.framebufferDepthSampleCounts limits

    samplesAvailable = do
      countBit <- msaaCandidates
      guard $ countBit <= upperLimit -- XXX: requested
      guard $ (counts .&. countBit) /= zeroBits -- XXX: capable
      pure countBit

msaaCandidates :: [Vk.SampleCountFlagBits]
msaaCandidates =
  [ Vk.SAMPLE_COUNT_64_BIT -- XXX: extremely unrealistic?
  , Vk.SAMPLE_COUNT_32_BIT -- XXX: unrealistic?
  , Vk.SAMPLE_COUNT_16_BIT -- XXX: possible, but not that impactful
  , Vk.SAMPLE_COUNT_8_BIT
  , Vk.SAMPLE_COUNT_4_BIT -- XXX: Khronos-recommended for rasterizing
  , Vk.SAMPLE_COUNT_2_BIT
  , Vk.SAMPLE_COUNT_1_BIT -- XXX: i.e. "disable", always available
  ]

-- | Catch an ERROR_OUT_OF_DATE_KHR exception and return 'True' if that happened
threwSwapchainError :: MonadUnliftIO f => f () -> f Bool
threwSwapchainError action =
  withRunInIO \run ->
    Utils.threwSwapchainError (run action)

setDynamic
  :: MonadIO io
  => Vk.CommandBuffer
  -> "viewport" ::: Vk.Rect2D
  -> "scissor"  ::: Vk.Rect2D
  -> io ()
setDynamic cb viewrect scissor = do
  Vk.cmdSetViewport cb 0 [viewport]
  Vk.cmdSetScissor cb 0 [scissor]
  where
    viewport = Vk.Viewport
      { x        = realToFrac x
      , y        = realToFrac y
      , width    = realToFrac width
      , height   = realToFrac height
      , minDepth = 0
      , maxDepth = 1
      }
      where
        Vk.Offset2D{x, y} = offset
        Vk.Extent2D{width, height} = extent
        Vk.Rect2D{offset, extent} = viewrect

setDynamicFullscreen
  :: ( HasSwapchain swapchain
     , MonadIO io
     )
  => Vk.CommandBuffer
  -> swapchain
  -> io ()
setDynamicFullscreen cb swapchain = do
  Vk.cmdSetViewport cb
    0
    [ Vk.Viewport
        { x        = 0
        , y        = 0
        , width    = realToFrac width
        , height   = realToFrac height
        , minDepth = 0
        , maxDepth = 1
        }
    ]
  Vk.cmdSetScissor cb 0
    [ Vk.Rect2D
        { offset = zero
        , extent = extent
        }
    ]
  where
    extent@Vk.Extent2D{width, height} =
      getSurfaceExtent swapchain