keid-core-0.2.0.0: src/Engine/SpirV/Compile.hs
module Engine.SpirV.Compile
( glsl
, glslStages
, glslPipelines
) where
import RIO
import RIO.ByteString qualified as ByteString
import RIO.Directory (createDirectoryIfMissing, doesFileExist, removeFile)
import RIO.FilePath ((<.>), (</>))
import RIO.Map qualified as Map
import RIO.Process (HasProcessContext, proc, readProcess_)
import RIO.Text qualified as Text
import Render.Code (Code(..), targetEnv)
import Engine.Vulkan.Pipeline.Stages qualified as Stages
glsl
:: ( HasLogFunc env
, HasProcessContext env
)
=> Maybe FilePath
-> Text
-> Text
-> Code
-> RIO env ()
glsl outdir basename stage (Code source) = do
withDir \dir -> do
let
shaderFile = dir </> Text.unpack basename <.> Text.unpack stage
outFile = shaderFile <.> "spv"
argsFile = shaderFile <.> "args"
sourceBytes = encodeUtf8 source
args =
[ "--target-env", targetEnv
, "-S", Text.unpack stage
, "-V", shaderFile
, "-o", outFile
]
argsBytes = encodeUtf8 $ tshow args
sameSource <- hasContents shaderFile sourceBytes
sameArgs <- hasContents argsFile argsBytes
compiled <- doesFileExist outFile
unless (sameSource && sameArgs && compiled) do
when sameArgs $
removeFile argsFile
ByteString.writeFile shaderFile sourceBytes
(out, err) <- proc "glslangValidator" args readProcess_
logDebug $ displayShow (out, err)
ByteString.writeFile argsFile argsBytes
where
withDir action =
case outdir of
Nothing ->
withSystemTempDirectory "keid-shader" action
Just dir -> do
createDirectoryIfMissing True dir
action dir
hasContents :: MonadIO m => FilePath -> ByteString -> m Bool
hasContents path expected = do
exists <- doesFileExist path
if exists then
(== expected) <$> ByteString.readFile path
else
pure False
glslStages
:: ( Stages.StageInfo stages
, HasLogFunc env
, HasProcessContext env
)
=> Maybe FilePath
-> Text
-> stages (Maybe Code)
-> RIO env ()
glslStages outdir basename stages =
for_ (Stages.withLabels stages) \(label, mstage) ->
traverse_ (glsl outdir basename label) mstage
glslPipelines
:: ( Stages.StageInfo stages
, HasLogFunc env
, HasProcessContext env
)
=> Maybe FilePath
-> Map Text (stages (Maybe Code))
-> RIO env ()
glslPipelines outdir = traverse_ compile . Map.toList
where
compile (label, stages) = glslStages outdir label stages