keid-core-0.2.0.0: src/Engine/Run.hs
module Engine.Run
( runStack
) where
import RIO
import GHC.Clock (getMonotonicTimeNSec)
import Graphics.UI.GLFW qualified as GLFW
import RIO.App (App(..), appEnv)
import RIO.State (get, put)
import UnliftIO.Resource (ReleaseKey, register, release)
import Vulkan.Utils.RefCounted (releaseRefCounted)
import Vulkan.Utils.Swapchain (Swapchain(sRelease))
import Vulkan.Utils.VulkanContext (RecycledResources)
import Engine.DataRecycler (DataRecycler(..))
import Engine.DataRecycler qualified as DataRecycler
import Engine.Frame qualified as Frame
import Engine.Render (renderFrame)
import Engine.Setup.Window qualified as Window
import Engine.StageSwitch (getNextStage)
import Engine.Types (Frame, GlobalHandles, NextStage(..), StageStack, StackStage(..), Stage(..), StageRIO)
import Engine.Types qualified as Engine
import Engine.Types.Options (optionsRecyclerWait, optionsMaxFPS)
import Engine.Vulkan.Swapchain (SwapchainResources(srSwapchain), threwSwapchainError)
import Engine.Vulkan.Types (waitDeviceIdle)
import Engine.Worker qualified as Worker
import Render.Target (RenderTarget)
runStack :: StageStack -> StageRIO (Maybe SwapchainResources) ()
runStack = \case
[] -> do
logInfo "Stage stack finished"
waitDeviceIdle
get >>= \case
Nothing ->
pure ()
Just oldSR ->
releaseRefCounted (sRelease (srSwapchain oldSR))
next : rest ->
prepare next >>= runPrepared rest
data Prepared where
Prepared
:: RenderTarget rt
=> ReleaseKey
-> App GlobalHandles st
-> Stage rt p rr st
-> Prepared
prepare :: StackStage -> StageRIO (Maybe SwapchainResources) Prepared
prepare = \case
StackStage stage -> do
logInfo $ "Setting up stage " <> display (sTitle stage)
sInitialRS stage >>= enterStage stage
StackStageContinue stKey state stage -> do
logInfo $ "Resuming stage " <> display (sTitle stage)
enterStage stage (stKey, state)
StackStageSetup setup ->
setup >>= prepare
enterStage
:: RenderTarget rt
=> Stage rt p rr st
-> (ReleaseKey, st)
-> StageRIO (Maybe SwapchainResources) Prepared
enterStage stage (key, rs) = do
freshStateVar <- newSomeRef rs
App{..} <- ask
let
stageApp = App
{ appState = freshStateVar
, ..
}
pure $ Prepared key stageApp stage
runPrepared :: StageStack -> Prepared -> StageRIO (Maybe SwapchainResources) ()
runPrepared rest (Prepared stageRelease stageApp stage) = do
setupApp <- ask
oldSR <- get
runRIO stageApp (run setupApp oldSR stageRelease rest stage) >>=
proceed stageRelease rest
type StageResult = (SwapchainResources, StageAction)
proceed :: ReleaseKey -> StageStack -> StageResult -> StageRIO (Maybe SwapchainResources) ()
proceed stageRelease rest (oldSR, stageAction) = do
put (Just oldSR)
case stageAction of
StageDone -> do
releaseStage "Stage done"
runStack rest
StagePop below -> do
releaseStage "Stage done"
runPrepared (drop 1 rest) below
StageReplace nextStage -> do
releaseStage "Stage replaced"
runPrepared rest nextStage
StagePush frozenStage nextStage ->
runPrepared (frozenStage : rest) nextStage
where
releaseStage label = do
logDebug label
releasing <- asyncBound do
release stageRelease
logDebug $ label <> ", released"
void $! register (void $ waitCatch releasing)
run
:: RenderTarget rt
=> App GlobalHandles (Maybe SwapchainResources)
-> Maybe SwapchainResources
-> ReleaseKey
-> StageStack
-> Stage rt p rr st
-> StageRIO st StageResult
run setupApp oldSR stKey rest stage@Stage{..} = do
logInfo $ "Starting stage: " <> display sTitle
recycler <- DataRecycler.new
startFrame <- Frame.initial oldSR (drDump recycler) stage
Engine.GlobalHandles{ghWindow, ghOptions, ghStageSwitch} <- asks appEnv
quit <- liftIO $ GLFW.windowShouldClose ghWindow
if quit then do
logDebug $ "Forcing stage unwind for " <> display sTitle
Frame.drain (drWait recycler) startFrame
pure
( Frame.fSwapchainResources startFrame
, StageDone
)
else do
atomically . void $ tryTakeTMVar ghStageSwitch
logInfo $ "Entering stage loop: " <> display sTitle
startTime <- liftIO getMonotonicTimeNSec
let
loop preparer =
stageLoop
(step preparer stKey rest stage recycler (optionsMaxFPS ghOptions))
(startFrame, Nothing)
(finalFrame, stageAction) <- bracket sBeforeLoop sAfterLoop \_stagePrivates -> do
result@(lastFrame, _action) <-
withPreparer setupApp loop
`onException` idleBeforeUnwind sTitle
Frame.drain (drWait recycler) lastFrame
pure result
endTime <- liftIO getMonotonicTimeNSec
let
frames = Frame.fIndex finalFrame
seconds = fromIntegral (endTime - startTime) / 1e9 :: Double
logInfo $ "Stage finished: " <> display sTitle
logInfo $ "Running time: " <> display seconds
logInfo $ "Average FPS: " <> display (fromIntegral frames / seconds)
releaseRefCounted $ fst (Frame.fStageResources finalFrame)
pure
( Frame.fSwapchainResources finalFrame
, stageAction
)
idleBeforeUnwind :: Text -> StageRIO st ()
idleBeforeUnwind title = do
logDebug $ "Waiting for the device before unwinding " <> display title
waitDeviceIdle `catchAny` \err ->
logError $ "Device wait failed while unwinding " <> display title <> ": " <> displayShow err
data Preparer = Preparer
{ setup :: App GlobalHandles (Maybe SwapchainResources)
, requests :: TMVar StackStage
, prepared :: Async Prepared
}
withPreparer
:: App GlobalHandles (Maybe SwapchainResources)
-> (Preparer -> StageRIO st a)
-> StageRIO st a
withPreparer setup action = do
requests <- newEmptyTMVarIO
withAsyncBound (runRIO setup $ atomically (takeTMVar requests) >>= prepare) \prepared ->
action Preparer{..}
data Switch
= SwitchReplace
| SwitchPushRestart
| SwitchPushFreeze
| SwitchPop
step
:: RenderTarget rt
=> Preparer
-> ReleaseKey
-> StageStack
-> Stage rt p rr st
-> DataRecycler (RecycledResources rr)
-> Maybe Int
-> (Frame rt p rr, Maybe Switch)
-> StageRIO st (LoopAction (Frame rt p rr, Maybe Switch))
step preparer stKey rest stage@Stage{..} DataRecycler{..} maxFPS_ (frame, switching) = do
startTime <- liftIO getMonotonicTimeNSec
liftIO GLFW.pollEvents -- XXX: runs callback processing on a frame budget
-- XXX: hard unwind all the stages, rendering nothing
quit <- liftIO $ GLFW.windowShouldClose (Frame.fWindow frame)
if quit then
pure $ LoopExit StageDone
else
case switching of
Nothing ->
getNextStage >>= \case
Nothing ->
render startTime Nothing
Just Finish ->
case rest of
[] ->
pure $ LoopExit StageDone
below : _rest ->
beginSwitch startTime SwitchPop below
Just (Replace nextStage) ->
beginSwitch startTime SwitchReplace nextStage
Just (PushRestart nextStage) ->
beginSwitch startTime SwitchPushRestart nextStage
Just (PushFreeze nextStage) ->
beginSwitch startTime SwitchPushFreeze nextStage
Just switch ->
poll preparer.prepared >>= \case
Nothing ->
render startTime switching
Just (Left failure) ->
throwIO failure
Just (Right nextStage) ->
LoopExit <$> finishSwitch switch nextStage
where
beginSwitch startTime switch nextStage = do
writeSomeRef preparer.setup.appState . Just $ Frame.fSwapchainResources frame
atomically $ putTMVar preparer.requests nextStage
render startTime $ Just switch
finishSwitch switch nextStage = case switch of
SwitchReplace ->
pure $ StageReplace nextStage
SwitchPop ->
pure $ StagePop nextStage
SwitchPushRestart -> do
logDebug "Restarting stage pushed"
pure $ StagePush (StackStage stage) nextStage
SwitchPushFreeze -> do
logDebug "Frozen stage pushed"
frozen <- freeze stKey stage
pure $ StagePush frozen nextStage
render startTime switching' = do
Engine.GlobalHandles{ghOptions, ghScreenVar, ghWindow, ghWindowSize} <- asks appEnv
needsNewSwapchain <- threwSwapchainError do
let recyclerWait = optionsRecyclerWait ghOptions
rs <- get
Frame.run drDump recyclerWait (renderFrame (sUpdateBuffers rs) \targets pipelines -> sRenderGraph targets pipelines rs) frame
nextFrame <- Frame.advance drWait frame needsNewSwapchain
when needsNewSwapchain do
newSize <- liftIO (Window.getSize ghWindow)
Worker.pushInput ghScreenVar $ const newSize.framebufferExtent
Worker.pushInput ghWindowSize $ const newSize
for_ maxFPS_ \maxFPS -> do
-- Wait until the end of allocated time.
endTime <- liftIO getMonotonicTimeNSec
let
elapsedUS = fromIntegral (endTime - startTime) `div` 1e3
fpsCapUS = 1e6 `div` maxFPS
threadDelay $ fpsCapUS - min fpsCapUS elapsedUS
pure $ LoopNextFrame (nextFrame, switching')
freeze :: RenderTarget rt => ReleaseKey -> Stage rt p rr st -> StageRIO st StackStage
freeze stKey stage = do
st <- get
pure $ StackStageContinue stKey st stage
data StageAction
= StageReplace Prepared
| StagePush StackStage Prepared
| StagePop Prepared
| StageDone
data LoopAction s
= LoopNextFrame s
| LoopExit StageAction
{-# INLINE stageLoop #-}
stageLoop :: ((f, s) -> StageRIO st (LoopAction (f, s))) -> (f, s) -> StageRIO st (f, StageAction)
stageLoop action current@(frame, _state) =
action current >>= \case
LoopNextFrame next ->
stageLoop action next
LoopExit stageAction ->
pure (frame, stageAction)