packages feed

keid-core-0.2.0.0: src/Engine/Vulkan/Pipeline/External.hs

{-# LANGUAGE AllowAmbiguousTypes #-} -- for observeField
{-# LANGUAGE UndecidableInstances #-}

module Engine.Vulkan.Pipeline.External
  ( Process
  , spawn
  , spawnReflect
  , spawnReflect_

  , loadConfig
  , loadConfigReflect

  , Observer

  , newObserverGraphics
  , observeGraphics
  , bindGraphics

  , newObserverCompute
  , observeCompute

  , type (^)
  , Params
  , ConfigureGraphics
  , ConfigureCompute
  , Observers
  , observeField

  , dumpPipelines
  ) where

import RIO

import Control.Monad.Trans.Resource (ResourceT)
import Data.List (maximum)
import Data.Tagged (Tagged(..))
import GHC.Stack (withFrozenCallStack)
import RIO.ByteString qualified as ByteString
import RIO.Directory (createDirectoryIfMissing, getModificationTime, doesFileExist)
import RIO.FilePath ((</>), (<.>))
import RIO.Map qualified as Map
import RIO.Text qualified as Text
import RIO.Time (UTCTime, getCurrentTime)
import UnliftIO.Resource (MonadResource, ReleaseKey)
import UnliftIO.Resource qualified as Resource
import Vulkan.Core10 qualified as Vk
import Vulkan.Utils.Pipeline.Specialization (Specialization)

import Render.Code (Code(..))
import Engine.SpirV.Reflect qualified as Reflect
import Engine.Types (StageFrameRIO, StageRIO)
import Engine.Vulkan.DescSets (Compatible)
import Engine.Vulkan.Pipeline.Compute (Compute)
import Engine.Vulkan.Pipeline.Compute qualified as Compute
import Engine.Vulkan.Pipeline.Graphics qualified as Graphics
import Engine.Vulkan.Pipeline.Stages (StageInfo(..))
import Engine.Vulkan.Types (Bound, DsLayoutBindings)
import Engine.Worker qualified as Worker
import Render.Target (HasRendering)

type Process config = Worker.Timed () config

spawn
  :: ( Foldable stages
     , MonadReader env m
     , HasLogFunc env
     , MonadResource m
     , MonadUnliftIO m
     )
  => (stages (Maybe FilePath) -> m stuff)
  -> Text
  -> stages (Maybe FilePath)
  -> (stuff -> config)
  -> m (Process config)
spawn loader label stageFiles makeConfig =
  Worker.spawnTimed startActive dtF initF stepF ()
  where
    startActive = True

    dtF = Left 1e6

    initF () = do
      logDebug $ "Starting pipeline watch on " <> display label

      result <- loader stageFiles
      initialTime <- getCurrentTime
      pure (makeConfig result, initialTime)

    stepF oldTime () = do
      checkTime oldTime (catMaybes $ toList stageFiles) >>= \case
        Nothing ->
          -- logDebug $ "Skipping pipeline update from " <> display label
          pure (Nothing, oldTime)
        Just newTime -> do
          logInfo $ "Updating pipeline from " <> display label
          try (loader stageFiles) >>= \case
            Left (SomeException err) -> do
              logError $ displayShow err
              pure (Nothing, newTime)
            Right result ->
              pure
                ( Just $ makeConfig result
                , newTime
                )

spawnReflect
  :: ( MonadResource m
     , MonadUnliftIO m
     , MonadReader env m
     , HasLogFunc env
     , StageInfo stages
     )
  => Text
  -> stages (Maybe FilePath)
  -> (stages (Maybe ByteString) -> config)
  -> m (Process config)
spawnReflect = spawn loadConfigReflect

{- | The worker that only keeps the loaded data without further processing.

Can be used to share the loaded data.
-}
spawnReflect_
  :: ( MonadResource m
     , MonadUnliftIO m
     , MonadReader env m
     , HasLogFunc env
     , StageInfo stages
     )
  => Text
  -> stages (Maybe FilePath)
  -> m (Process (stages (Maybe ByteString)))
spawnReflect_ name stages = spawn loadConfigReflect name stages id

checkTime
  :: MonadIO io
  => UTCTime
  -> [FilePath]
  -> io (Maybe UTCTime)
checkTime oldTime = fmap collect . traverse getModificationTime
  where
    collect = \case
      [] ->
        Nothing
      (maximum -> maxTime) ->
        if maxTime <= oldTime then
          Nothing
        else
          Just maxTime

loadConfig
  :: ( Traversable stages
     , MonadIO io
     )
  => stages (Maybe FilePath)
  -> io (stages (Maybe ByteString))
loadConfig stageFiles =
  for stageFiles $
    traverse ByteString.readFile

loadConfigReflect
  :: ( StageInfo stages
     , MonadIO io
     )
  => stages (Maybe FilePath)
  -> io (stages (Maybe ByteString))
loadConfigReflect stageFiles = do
  stageCode <- loadConfig stageFiles
  modules <- Reflect.reflect stageCode
  either throwString pure . Reflect.check $
    Reflect.stageProblems modules
  pure stageCode

type Observer pipeline = Worker.ObserverIO (ReleaseKey, pipeline)

newObserverGraphics
  :: ( HasCallStack
     , pipeline ~ Graphics.Pipeline dsl vertices instances
     , Worker.HasOutput worker
     , Specialization (Graphics.Specialization pipeline)
     , HasRendering target
     , Worker.GetOutput worker ~ Graphics.Configure pipeline
     )
  => target
  -> worker
  -> ResourceT (StageRIO rs) (Observer pipeline)
newObserverGraphics target process = do
  initialConfig <- Worker.getOutputData process

  initial <-
    withFrozenCallStack $
     Graphics.allocate
      Nothing
      initialConfig
      target

  Worker.newObserverIO initial

observeGraphics
  :: ( HasRendering target
     , Worker.HasOutput output
     , Worker.GetOutput output ~ Graphics.Configure pipeline
     , pipeline ~ Graphics.Pipeline dsl vertices instances
     , spec ~ Graphics.Specialization pipeline
     , Specialization spec
     , HasCallStack
     )
  => target
  -> Tagged dsl [DsLayoutBindings]
  -> output
  -> Worker.ObserverIO (ReleaseKey, pipeline)
  -> StageFrameRIO rt p fr rs ()
observeGraphics target sceneBinds configP output =
  withFrozenCallStack $ void $!
    Worker.observeIO configP output \old config -> do
      logDebug "Rebuilding pipeline"
      replacePipeline old $
        mapRIO fst $ Graphics.allocate
          Nothing
          ( config
              { Graphics.cDescLayouts = sceneBinds
              }
          )
          target

{-# INLINE bindGraphics #-}
bindGraphics
  :: forall
      pipeline m
      pipeLayout vertices instances
      boundLayout oldVertices oldInstances
  .  ( pipeline ~ Graphics.Pipeline pipeLayout vertices instances
     , MonadUnliftIO m
     , Compatible pipeLayout boundLayout
     )
  => Vk.CommandBuffer
  -> Worker.ObserverIO (ReleaseKey, pipeline)
  -> Bound boundLayout vertices instances m ()
  -> Bound boundLayout oldVertices oldInstances m ()
bindGraphics cb fr action = do
  (_key, pipeline) <- Worker.readObservedIO fr
  Graphics.bind @pipeline cb pipeline action

newObserverCompute
  :: ( config ~ Compute.Configure pipeline ()
     , pipeline ~ Compute.Pipeline dsl Compute Compute
     , HasCallStack
     )
  => Process config
  -> ResourceT (StageRIO rs) (Observer pipeline)
newObserverCompute process = do
  initialConfig <- Worker.getOutputData process

  initial <- withFrozenCallStack $ Compute.allocate initialConfig

  Worker.newObserverIO initial

observeCompute
  :: ( Worker.HasOutput output
     , Worker.GetOutput output ~ config
     , Specialization spec
     , config ~ Compute.Configure pipeline spec
     , pipeline ~ Compute.Pipeline dsl Compute Compute
     )
  => Tagged dsl [DsLayoutBindings]
  -> output
  -> Worker.ObserverIO (ReleaseKey, pipeline)
  -> StageFrameRIO rt p fr rs ()
observeCompute binds configP output =
  void $! Worker.observeIO configP output \old config -> do
    logDebug "Rebuilding pipeline"
    replacePipeline old $
      mapRIO fst $ Compute.allocate config
        { Compute.cDescLayouts = binds
        }

replacePipeline
  :: ( MonadUnliftIO m
     , MonadReader env m
     , HasLogFunc env
     )
  => (ReleaseKey, pipeline)
  -> m (ReleaseKey, pipeline)
  -> m (ReleaseKey, pipeline)
replacePipeline old@(oldKey, _old) allocateNew =
  try allocateNew >>= \case
    Left (SomeException err) -> do
      logError $ "Keeping the previous pipeline: " <> displayShow err
      pure old
    Right new -> do
      Resource.release oldKey
      pure new

-- * HKD wrappers

data ConfigureGraphics p
data ConfigureCompute p
data Observers p
data Params p

type family f ^ p where
  Identity ^ Params p = p
  Identity ^ p = p

  ConfigureGraphics ^ Params p = Worker.Var p
  ConfigureGraphics ^ p = Worker.Var (Graphics.Configure p)

  ConfigureCompute ^ Params p = Worker.Var p
  ConfigureCompute ^ p = Worker.Var (Compute.Configure p ())

  Observers ^ Params p = Worker.ObserverIO p
  Observers ^ p = Observer p

  f ^ p = f p

observeField
  :: forall
      pf
      p
      target
      dsl
      s vs is
      rts ps fr rs
  .   ( p ~ Graphics.Pipeline s vs is
      , Specialization (Graphics.Specialization p)
      , HasRendering target
      )
  => target
  -> Tagged dsl DsLayoutBindings
  -> pf ConfigureGraphics
  -> pf Observers
  -> (forall a . pf a -> a ^ p)
  -> StageFrameRIO rts ps fr rs ()
observeField target binds workers observers field =
  observeGraphics
    target
    (Tagged [unTagged binds])
    (field @ConfigureGraphics workers)
    (field @Observers observers)

dumpPipelines
  :: StageInfo t
  => MonadIO io
  => FilePath
  -> Map Text (t (Maybe Code))
  -> io ()
dumpPipelines prefix pipelines = do
  createDirectoryIfMissing True prefix
  for_ (Map.toList pipelines) \(pipeline, stageCode) -> do
    let stages = (,) <$> stageNames <*> stageCode
    for_ stages \(stage, mcode) ->
      for_ mcode \(Code code) -> do
        let
          file = prefix </> Text.unpack pipeline <.> stage
          bytes = encodeUtf8 code
        exists <- doesFileExist file
        if exists then do
          old <- ByteString.readFile file
          unless (bytes == old) $
            ByteString.writeFile file bytes
        else
          ByteString.writeFile file bytes