packages feed

keid-core-0.2.0.0: src/Engine/SpirV/Reflect.hs

module Engine.SpirV.Reflect
  ( reflect
  , check

  , stageProblems
  , layoutProblems
  , vertexInputProblems
  ) where

import RIO

import Data.Bits ((.&.))
import Data.SpirV.Reflect.DescriptorBinding (DescriptorBinding)
import Data.SpirV.Reflect.DescriptorBinding qualified as DescriptorBinding
import Data.SpirV.Reflect.Enums.DescriptorType (DescriptorType(..))
import Data.SpirV.Reflect.Enums.Format (Format(..))
import Data.SpirV.Reflect.InterfaceVariable (InterfaceVariable)
import Data.SpirV.Reflect.InterfaceVariable qualified as InterfaceVariable
import Data.SpirV.Reflect.Module (Module)
import Data.SpirV.Reflect.Module qualified as Module
import Data.SpirV.Reflect.Traits qualified as Traits
import Data.Vector qualified as Vector
import Data.Vector.Storable qualified as VectorS
import RIO.List qualified as List
import RIO.Text qualified as Text
import Vulkan.Core10 qualified as Vk
import Vulkan.Utils.SpirV.Descriptors qualified as Descriptors
import Vulkan.Utils.SpirV.Reflect qualified as Reflect
import Vulkan.Utils.SpirV.Stage qualified as Stage

import Engine.Vulkan.Format qualified as Format
import Engine.Vulkan.Pipeline.Stages (StageInfo(..))
import Engine.Vulkan.Pipeline.Stages qualified as Stages
import Engine.Vulkan.Types (DsLayoutBindings)

reflect
  :: ( Traversable stages
     , MonadIO io
     )
  => stages (Maybe ByteString)
  -> io (stages (Maybe Module))
reflect = traverse $ traverse Reflect.reflectBytes

check :: [Text] -> Either String ()
check = \case
  [] ->
    Right ()
  problems ->
    Left . Text.unpack . Text.intercalate "\n" $
      "Shaders do not match:" : map ("  " <>) problems

stageProblems
  :: StageInfo stages
  => stages (Maybe Module)
  -> [Text]
stageProblems stages = linkProblems <> sharedProblems
  where
    active = do
      (label, Just module_) <- toList $ Stages.withLabels stages
      pure (label, module_)

    linkProblems = do
      (producer, consumer) <- zip active (drop 1 active)
      interfaceProblems producer consumer

    sharedProblems =
      map fromString $ lefts
        [ void $ Descriptors.mergedDescriptorSetLayoutInfos modules
        , void $ Descriptors.mergedPushConstantRanges modules
        ]

    modules = map snd active

interfaceProblems :: (Text, Module) -> (Text, Module) -> [Text]
interfaceProblems (outputStage, producer) (inputStage, consumer) = do
  (location, expected) <- consumerInfo.inputs
  let
    input =
      inputStage <> " input" <> variableAt consumer.input_variables location
  case List.lookup location producerInfo.outputs of
    Nothing ->
      pure $ input <> " has no matching " <> outputStage <> " output"
    Just provided -> do
      guard $ provided /= expected
      pure $ mconcat
        [ input
        , " does not match "
        , outputStage
        , " output"
        , variableAt producer.output_variables location
        ]
  where
    consumerInfo = Stage.stageInfoOf consumer
    producerInfo = Stage.stageInfoOf producer

variableAt :: Vector InterfaceVariable -> Word32 -> Text
variableAt variables location =
  foldMap (" " <>) name <> " at location " <> tshow location
  where
    name = Vector.find ((== location) . (.location)) variables >>= (.name)

layoutProblems
  :: StageInfo stages
  => stages (Maybe Module)
  -> [DsLayoutBindings]
  -> Vector Vk.PushConstantRange
  -> [Text]
layoutProblems stages setLayouts pushRanges = do
  (label, stage, Just module_) <- toList $ (,,) <$> stageNames <*> stageFlagBits <*> stages
  descriptorProblems label stage module_ <> pushProblems label stage module_
  where
    descriptorProblems label stage module_ = do
      binding <- toList module_.descriptor_bindings
      guard $ binding.accessed /= 0
      bindingProblems setLayouts label stage binding

    pushProblems label stage module_ = do
      range <- Descriptors.pushConstantRanges module_
      guard . not $ any (covers stage range) pushRanges
      pure $ mconcat
        [ label
        , " push constants at offset "
        , tshow range.offset
        , " with size "
        , tshow range.size
        , " are outside the push constant ranges"
        ]

bindingProblems
  :: [DsLayoutBindings]
  -> Text
  -> Vk.ShaderStageFlagBits
  -> DescriptorBinding
  -> [Text]
bindingProblems setLayouts label stage binding =
  case declared of
    Nothing ->
      pure $ subject <> " is missing from the descriptor set layouts"
    Just layoutBinding -> catMaybes
      [ do
          guard . not $ compatibleDescriptor shaderType layoutBinding.descriptorType
          pure $ mconcat
            [ subject
            , " is "
            , tshow shaderType
            , " but the layout has "
            , tshow layoutBinding.descriptorType
            ]
      , do
          guard $ layoutBinding.stageFlags .&. stage /= stage
          pure $ subject <> " is not visible to the " <> label <> " stage"
      , do
          count <- binding.count
          guard $ count > layoutBinding.descriptorCount
          pure $ mconcat
            [ subject
            , " has "
            , tshow count
            , " descriptors but the layout has "
            , tshow layoutBinding.descriptorCount
            ]
      ]
  where
    subject = mconcat
      [ label
      , " "
      , binding.name
      , " at set "
      , tshow binding.set
      , " binding "
      , tshow binding.binding
      ]

    declared = do
      layoutBindings <- listToMaybe $ drop (fromIntegral binding.set) setLayouts
      fst <$> List.find ((== binding.binding) . (.binding) . fst) layoutBindings

    shaderType =
      case binding.descriptor_type of
        DescriptorType value ->
          Vk.DescriptorType $ fromIntegral value

compatibleDescriptor :: Vk.DescriptorType -> Vk.DescriptorType -> Bool
compatibleDescriptor shaderType layoutType =
  shaderType == layoutType || (shaderType, layoutType) `elem` alternatives
  where
    alternatives =
      [ (Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER, Vk.DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC)
      , (Vk.DESCRIPTOR_TYPE_STORAGE_BUFFER, Vk.DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)
      , (Vk.DESCRIPTOR_TYPE_SAMPLED_IMAGE, Vk.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
      , (Vk.DESCRIPTOR_TYPE_SAMPLER, Vk.DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
      ]

covers :: Vk.ShaderStageFlagBits -> Vk.PushConstantRange -> Vk.PushConstantRange -> Bool
covers stage range declared =
  declared.stageFlags .&. stage == stage &&
  declared.offset <= range.offset &&
  range.offset + range.size <= declared.offset + declared.size

vertexInputProblems
  :: StageInfo stages
  => stages (Maybe Module)
  -> Vector Vk.VertexInputAttributeDescription
  -> [Text]
vertexInputProblems stages attributes =
  case active of
    (label, Vk.SHADER_STAGE_VERTEX_BIT, module_) : _rest -> do
      variable <- toList module_.input_variables
      guard $ isNothing variable.built_in
      location <- take (locations variable) [variable.location ..]
      inputProblems attributes label variable location
    _noVertexStage ->
      []
  where
    active = do
      (label, stage, Just module_) <- toList $ (,,) <$> stageNames <*> stageFlagBits <*> stages
      pure (label, stage, module_)

    locations variable =
      fromIntegral $
        max 1 variable.numeric.matrix.column_count *
        product (VectorS.toList variable.array.dims)

inputProblems
  :: Vector Vk.VertexInputAttributeDescription
  -> Text
  -> InterfaceVariable
  -> Word32
  -> [Text]
inputProblems attributes label variable location =
  case Vector.find ((== location) . (.location)) attributes of
    Nothing ->
      pure $ subject <> " has no vertex attribute"
    Just attribute -> do
      shaderNumeric <- toList $ Format.numericFormat shaderFormat
      attributeNumeric <- toList $ Format.numericFormat attribute.format
      guard $ shaderNumeric /= attributeNumeric
      pure $ mconcat
        [ subject
        , " reads "
        , tshow shaderFormat
        , " from a "
        , tshow attribute.format
        , " attribute"
        ]
  where
    subject = mconcat
      [ label
      , " input"
      , foldMap (" " <>) variable.name
      , " at location "
      , tshow location
      ]

    shaderFormat =
      case variable.format of
        Format value ->
          Vk.Format $ fromIntegral value