packages feed

mischief-render 0.1.0.0 → 0.1.1.0

raw patch · 25 files changed

+397/−132 lines, 25 filesdep ~mischief-mathPVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependency ranges changed: mischief-math

API changes (from Hackage documentation)

- Mischief.Animation.Spritesheet: [padding] :: Spritesheet -> V2 Int
- Mischief.Animation.Spritesheet: [size] :: Spritesheet -> V2 Int
- Mischief.Render.Core: DefaultSampler :: Sampler -> DefaultSampler
- Mischief.Render.Core: instance Mischief.ECS.Components.Component Mischief.Render.Core.DefaultSampler
- Mischief.Render.Core: newtype DefaultSampler
- Mischief.Shader: -- or not.
- Mischief.Shader: -- | Set whether the relationships this component is used in are exclusive
+ Mischief.Animation.Spritesheet: [cols] :: Spritesheet -> Int
+ Mischief.Animation.Spritesheet: [rows] :: Spritesheet -> Int
+ Mischief.Animation.Spritesheet: [spacing] :: Spritesheet -> V2 Int
+ Mischief.Render: [defaultSampler] :: RenderOptions -> Query System Sampler
+ Mischief.Render: data PixelSampler
+ Mischief.Render: data StandardSampler
+ Mischief.Render: sampler :: (Component a, HasSampler a) => Query System Sampler
+ Mischief.Render: windowToWorldPos :: Entity -> (Float, Float) -> System (Maybe (V2 Float))
+ Mischief.Render.Camera: CameraBackground :: V3 Float -> CameraBackground
+ Mischief.Render.Camera: CameraZoom :: Float -> CameraZoom
+ Mischief.Render.Camera: ProjectionMatrix :: M44 Float -> ProjectionMatrix
+ Mischief.Render.Camera: ViewMatrix :: M44 Float -> ViewMatrix
+ Mischief.Render.Camera: instance Data.Default.Internal.Default Mischief.Render.Camera.CameraBackground
+ Mischief.Render.Camera: instance Data.Default.Internal.Default Mischief.Render.Camera.CameraZoom
+ Mischief.Render.Camera: instance Mischief.ECS.Components.Component Mischief.Render.Camera.CameraBackground
+ Mischief.Render.Camera: instance Mischief.ECS.Components.Component Mischief.Render.Camera.CameraZoom
+ Mischief.Render.Camera: instance Mischief.ECS.Components.Component Mischief.Render.Camera.ProjectionMatrix
+ Mischief.Render.Camera: instance Mischief.ECS.Components.Component Mischief.Render.Camera.ViewMatrix
+ Mischief.Render.Camera: newtype CameraBackground
+ Mischief.Render.Camera: newtype CameraZoom
+ Mischief.Render.Camera: newtype ProjectionMatrix
+ Mischief.Render.Camera: newtype ViewMatrix
+ Mischief.Render.Camera: windowToWorldPos :: Entity -> (Float, Float) -> System (Maybe (V2 Float))
+ Mischief.Render.Material.Definition: [defaultSampler] :: RenderOptions -> Query System Sampler
+ Mischief.Render.Material.Definition: dumpFragment :: Material mat => Text
+ Mischief.Render.Material.Definition: dumpVertex :: Material mat => Text
+ Mischief.Render.Sampler: PixelSampler :: Sampler -> PixelSampler
+ Mischief.Render.Sampler: StandardSampler :: Sampler -> StandardSampler
+ Mischief.Render.Sampler: class HasSampler a
+ Mischief.Render.Sampler: data DefaultSampler
+ Mischief.Render.Sampler: defaultSampler :: Query System Sampler
+ Mischief.Render.Sampler: getSampler :: HasSampler a => a -> Sampler
+ Mischief.Render.Sampler: initSamplers :: OnAdd RenderDevice -> System ()
+ Mischief.Render.Sampler: instance Mischief.ECS.Components.Component Mischief.Render.Sampler.PixelSampler
+ Mischief.Render.Sampler: instance Mischief.ECS.Components.Component Mischief.Render.Sampler.StandardSampler
+ Mischief.Render.Sampler: instance Mischief.ECS.World.PrefType Mischief.Render.Sampler.DefaultSampler (Mischief.ECS.World.Query.Query Mischief.ECS.World.System Mischief.Render.Core.Sampler)
+ Mischief.Render.Sampler: instance Mischief.Render.Sampler.HasSampler Mischief.Render.Sampler.PixelSampler
+ Mischief.Render.Sampler: instance Mischief.Render.Sampler.HasSampler Mischief.Render.Sampler.StandardSampler
+ Mischief.Render.Sampler: newtype PixelSampler
+ Mischief.Render.Sampler: newtype StandardSampler
+ Mischief.Render.Sampler: sampler :: (Component a, HasSampler a) => Query System Sampler
+ Mischief.Shader: (<$>) :: Functor f => (a -> b) -> f a -> f b
+ Mischief.Shader: (<*>) :: Applicative f => f (a -> b) -> f a -> f b
+ Mischief.Shader: (=<<) :: Monad m => (a -> m b) -> m a -> m b
+ Mischief.Shader: (>>=) :: Monad m => m a -> (a -> m b) -> m b
+ Mischief.Shader: infixl 1 >>=
+ Mischief.Shader: infixl 4 <*>
+ Mischief.Shader: infixr 1 =<<
+ Mischief.Shader: select :: forall {k} (a :: Types) (m :: k). SingI a => Expr ('Primitive 'TBool) -> Shader m (Expr a) -> Shader m (Expr a) -> Shader m (Expr a)
+ Mischief.Shader.Functions: (&&) :: Boolean -> Boolean -> Boolean
+ Mischief.Shader.Functions: (/=) :: forall (b :: Types). (Equal a, ChangePrimitive (Expr a) 'TBool ~ b) => Expr a -> Expr a -> Expr b
+ Mischief.Shader.Functions: (<) :: forall (b :: Types). (Comparable a, ChangePrimitive (Expr a) 'TBool ~ b) => Expr a -> Expr a -> Expr b
+ Mischief.Shader.Functions: (<=) :: forall (b :: Types). (Comparable a, ChangePrimitive (Expr a) 'TBool ~ b) => Expr a -> Expr a -> Expr b
+ Mischief.Shader.Functions: (==) :: forall (b :: Types). (Equal a, ChangePrimitive (Expr a) 'TBool ~ b) => Expr a -> Expr a -> Expr b
+ Mischief.Shader.Functions: (>) :: forall (b :: Types). (Comparable a, ChangePrimitive (Expr a) 'TBool ~ b) => Expr a -> Expr a -> Expr b
+ Mischief.Shader.Functions: (>=) :: forall (b :: Types). (Comparable a, ChangePrimitive (Expr a) 'TBool ~ b) => Expr a -> Expr a -> Expr b
+ Mischief.Shader.Functions: (||) :: Boolean -> Boolean -> Boolean
+ Mischief.Shader.Functions: all :: forall (n :: Nat). KnownNat n => Expr ('VectorType n 'TBool) -> Boolean
+ Mischief.Shader.Functions: any :: forall (n :: Nat). KnownNat n => Expr ('VectorType n 'TBool) -> Boolean
+ Mischief.Shader.Functions: class Comparable (a :: Types)
+ Mischief.Shader.Functions: class Equal (a :: Types)
+ Mischief.Shader.Functions: instance (Mischief.Shader.Types.Algebric a GHC.Types.~ 'GHC.Types.True) => Mischief.Shader.Functions.Comparable a
+ Mischief.Shader.Functions: instance (Mischief.Shader.Types.Algebric a GHC.Types.~ 'GHC.Types.True) => Mischief.Shader.Functions.Equal a
+ Mischief.Shader.Functions: instance Mischief.Shader.Functions.Equal ('Mischief.Shader.Internal.Singletons.Primitive 'Mischief.Shader.Internal.Singletons.TBool)
+ Mischief.Shader.Functions: instance Mischief.Shader.Functions.Equal ('Mischief.Shader.Internal.Singletons.VectorType n 'Mischief.Shader.Internal.Singletons.TBool)
+ Mischief.Shader.Functions: pick :: forall {k} (a :: Types) (m :: k). SingI a => [(Boolean, Shader m (Expr a))] -> Shader m (Expr a) -> Shader m (Expr a)
+ Mischief.Shader.Functions: pickM :: forall {k} (a :: Types) (m :: k). SingI a => [(Shader m Boolean, Shader m (Expr a))] -> Shader m (Expr a) -> Shader m (Expr a)
+ Mischief.Shader.Functions: textureDimensions :: Expr 'TTexture -> Vec 2 Uint
+ Mischief.Shader.Functions: type family ChangePrimitive a (b :: PrimitiveTypes) :: Types
- Mischief.Animation.Spritesheet: Spritesheet :: V2 Int -> V2 Int -> V2 Int -> AssetRef Image -> Spritesheet
+ Mischief.Animation.Spritesheet: Spritesheet :: V2 Int -> V2 Int -> Int -> Int -> AssetRef Image -> Spritesheet
- Mischief.Render: RenderOptions :: Clear -> Nat -> RenderOptions
+ Mischief.Render: RenderOptions :: Clear -> Nat -> Query System Sampler -> RenderOptions
- Mischief.Render.Camera: getCameraProjection :: Int -> Int -> Transform -> Matrices CPU
+ Mischief.Render.Camera: getCameraProjection :: Int -> Int -> Transform -> CameraZoom -> Matrices CPU
- Mischief.Render.Material.Definition: RenderOptions :: Clear -> Nat -> RenderOptions
+ Mischief.Render.Material.Definition: RenderOptions :: Clear -> Nat -> Query System Sampler -> RenderOptions
- Mischief.Shader.Functions: dot :: forall (n :: Nat) (a :: PrimitiveTypes). (SingI (Expr ('VectorType n a)), SingI a, SingI n, Algebric ('Primitive a) ~ 'True) => Expr ('VectorType n a) -> Expr ('VectorType n a) -> Expr ('Primitive a)
+ Mischief.Shader.Functions: dot :: forall (n :: Nat) (a :: PrimitiveTypes). (SingI ('VectorType n a), SingI a, SingI n, Algebric ('Primitive a) ~ 'True) => Expr ('VectorType n a) -> Expr ('VectorType n a) -> Expr ('Primitive a)
- Mischief.Shader.Types: type Boolean = Expr 'TBool
+ Mischief.Shader.Types: type Boolean = Expr 'Primitive 'TBool

Files

CHANGELOG.md view
@@ -1,5 +1,12 @@-# Revision history for mischief+# Revision history for mischief-render -## 0.1.0.0 -- YYYY-mm-dd+## 0.1.1.0++* Added `windowToWorldPos` function. +* Added comparisons, `select` and `pick` to shaders, for conditional control flow. +* Added `CameraBackground` and `CameraZoom` components. +* Added a field in the render settings for which default sampler the material will use. Useful for pixel art.  ++## 0.1.0.0   * First version. Released on an unsuspecting world.
examples/Animation.hs view
@@ -5,17 +5,16 @@  import Control.Monad (void, when) import Control.Monad.IO.Class-import Data.Data (Proxy (..)) import Data.Default import Data.Foldable import Data.IORef import Data.Text (Text) import Mischief.Animation (AnimationPlugin, Animator (..), input, shift) import Mischief.Animation.Animations (selAnim)+import Mischief.Animation.Animator (AnimationStatus (..)) import Mischief.Animation.Animator qualified as A import Mischief.Animation.Spritesheet (Animation (..), noAnimation) import Mischief.Assets-import Mischief.Assets.Image import Mischief.ECS import Mischief.ECS.Time qualified as Time import Mischief.Input (InputPlugin)@@ -23,11 +22,9 @@ import Mischief.Input.Keys qualified as Keys import Mischief.Materials.Sprite import Mischief.Math hiding (qd)-import Mischief.Math.Transform (Transform (..)) import Mischief.Math.Transform qualified as Transform-import Mischief.Render.Buffer import Mischief.Render.Camera-import Mischief.Render.Core (RenderDevice, RenderQueue, RenderUpdate)+import Mischief.Render.Core (RenderUpdate) import Mischief.Render.Material (WithMaterial (WithMaterial), renderMaterial) import Mischief.Render.Plugin import Mischief.Render.Sprite.Common@@ -50,7 +47,7 @@     systems moveSprite       & schedule @Update -    systems (renderMaterial @CustomMat def)+    systems (renderMaterial @SpriteMaterial def)       & schedule @RenderUpdate    deps = [dep @RenderPlugin, dep @InputPlugin, dep @TimePlugin, dep @AnimationPlugin, dep @FileWatcherPlugin]@@ -71,15 +68,9 @@       spawn         ( Animator MyAnimator,           def {translation = spritePos},-          WithMaterial @CustomMat+          WithMaterial @SpriteMaterial         ) -    Just device <- res @RenderDevice-    Just queue <- res @RenderQueue-    buffer <- createBuffer @SomeColor device-    insert buffer e-    uploadBuffer queue buffer (SomeColor {color = V3 1 0 0})-     shift (ChangeCharacter c) e  moveSprite :: System ()@@ -113,7 +104,7 @@     input @MyAnimator (\x -> x {walk}) entity      if-      | dir.x < 0 -> insert SpriteFlip {x = True, y = False} entity+      | dir.x < 0 -> insert SpriteFlip {x = False, y = True} entity       | dir.x > 0 -> insert SpriteFlip {x = False, y = False} entity       | otherwise -> pure () @@ -145,7 +136,7 @@    transition Start _ (Just (ChangeCharacter x)) _ = Just $ CA x Idle   transition (CA x _) _ (Just DoJump) _ = Just $ CA x Jump-  transition (CA x Jump) _ _ _ = Just $ CA x Idle+  transition (CA x Jump) _ _ Finished = Just $ CA x Idle   transition (CA x Walk) (I {walk = False}) _ _ = Just $ CA x Idle   transition (CA x Idle) (I {walk = True}) _ _ = Just $ CA x Walk   transition _ _ _ _ = Nothing
examples/Transform.hs view
@@ -2,14 +2,16 @@  module Main where -import Control.Monad (void)+import Control.Monad (void, when) import Data.Text (Text)+import Data.Text qualified as T import Mischief.Animation import Mischief.Assets import Mischief.ECS import Mischief.ECS.Time qualified as Time import Mischief.Input import Mischief.Input.Keys qualified as Keys+import Mischief.Input.Mouse qualified as Mouse import Mischief.Materials.Sprite (SpriteMaterial) import Mischief.Math import Mischief.Math.Transform qualified as Transform@@ -29,7 +31,7 @@     systems setup       & schedule @Startup -    systems move+    systems (move, click)       & schedule @Update      systems (renderMaterial @SpriteMaterial def)@@ -73,6 +75,15 @@       Rel ChildOf green     )     >>= shift (ChangeCharacter Beige)++click :: System ()+click = do+  Just mouse <- res @Mouse+  when (Mouse.justPressed mouse Mouse.Left) $ do+    pos <- Mouse.pos+    Just camera <- single [q|E / With Camera|]+    Just pos <- windowToWorldPos camera pos+    warn $ T.show pos  move :: System () move = do
mischief-render.cabal view
@@ -18,7 +18,7 @@ -- PVP summary:     +-+------- breaking API changes --                  | | +----- non-breaking API additions --                  | | | +--- code changes with no API change-version: 0.1.0.0+version: 0.1.1.0 -- A short (one-line) description of the package. -- synopsis: -- A longer description of the package.@@ -77,6 +77,7 @@     Mischief.Render.Material.Instance     Mischief.Render.Material.Pipeline     Mischief.Render.Plugin+    Mischief.Render.Sampler     Mischief.Render.Sprite     Mischief.Render.Sprite.Common     Mischief.Render.Texture@@ -147,7 +148,7 @@     linear >=1.23.3 && <1.24,     mischief-assets >=0.1.0 && <0.2,     mischief-ecs >=0.2.1 && <0.3,-    mischief-math >=0.1.0 && <0.2,+    mischief-math >=0.1.1 && <0.2,     mischief-sdl >=0.1.0 && <0.2,     mtl >=2.3.1 && <2.4,     primitive >=0.9.1 && <0.10,
src/Mischief/Animation.hs view
@@ -17,6 +17,7 @@  import Control.Monad import Data.Data+import Data.Text qualified as T import GHC.Float (int2Float) import Mischief.Animation.Animations (Animations (..), selAnim) import Mischief.Animation.Animator@@ -56,6 +57,8 @@     spawn_ $ Observer onSetAnimatorState     schedule @Update $ systems progressAnimations     schedule @Update $ systems transitionWhen & after progressAnimations++  deps = [dep @TimePlugin]  onSetAnimator :: OnSet Animator -> System () onSetAnimator OnSet {entity} = do
src/Mischief/Animation/Spritesheet.hs view
@@ -16,21 +16,22 @@  data Spritesheet = Spritesheet   { frameSize :: V2 Int,-    padding :: V2 Int,-    size :: V2 Int,+    spacing :: V2 Int,+    rows :: Int,+    cols :: Int,     image :: AssetRef Image   }   deriving (Component, Show)  noSpritesheet :: KdlRef Spritesheet-noSpritesheet = KdlValue $ Spritesheet {frameSize = V2 0 0, padding = V2 0 0, size = V2 0 0, image = NullRef}+noSpritesheet = KdlValue $ Spritesheet {frameSize = V2 0 0, spacing = V2 0 0, rows = 0, cols = 0, image = NullRef}  sheetCoords :: Int -> Spritesheet -> (V2 Int, V2 Int) sheetCoords index sheet = do-  let boxSize = sheet.padding + sheet.frameSize-  let framesPerRow = sheet.size.x `div` boxSize.x-  let start = V2 (index `mod` framesPerRow) (index `div` framesPerRow)-  (start * (sheet.frameSize + 1), sheet.frameSize)+  -- let boxSize = sheet.padding + sheet.frameSize+  -- let framesPerRow = sheet.size.x `div` boxSize.x+  let start = V2 (index `mod` sheet.cols) (index `div` sheet.cols)+  (start * (sheet.frameSize + sheet.spacing), sheet.frameSize)  data AnimationFrames = RangedFrames Int Int | ManualFrames [Int] deriving (Show) @@ -85,11 +86,12 @@ instance KdlAsset Spritesheet where   decodeKdl path = KDL.children $ do     frameSize <- KDL.node "frameSize"-    padding <- KDL.node "padding"-    size <- KDL.node "size"+    spacing <- KDL.node "spacing"+    rows <- KDL.node "rows"+    cols <- KDL.node "cols"     image <- KDL.nodeWith "image" $ decodeKdl path -    pure $ Spritesheet {frameSize, padding, size, image}+    pure $ Spritesheet {frameSize, spacing, rows, cols, image}  instance Asset Animation where   type Saveable Animation = False
src/Mischief/Materials/Sprite.hs view
@@ -3,10 +3,10 @@ import Mischief.Materials import Mischief.Materials.Time (TimeMaterial, getTime) import Mischief.Render.Camera (CameraMatrices (CameraMatrices), Matrices (..))-import Mischief.Render.Core (DefaultSampler (..)) import Mischief.Render.Image+import Mischief.Render.Sampler import Mischief.Render.Sprite.Common-import Prelude ()+import Prelude ((<$>))  data SpriteData f = SpriteData   { coords :: Field f (Vec 3 Float),@@ -67,7 +67,7 @@   fetch =     FetchBindings       ( \camera -> do-          (DefaultSampler sampler) <- qres @DefaultSampler+          sampler <- defaultSampler           CameraMatrices matrices <- qget camera [qd|CameraMatrices|]           pure (matrices, sampler)       )
src/Mischief/Render.hs view
@@ -20,12 +20,13 @@     module Mischief.Materials,     module Mischief.Render.Layers,     module Mischief.Render.Material.Definition,+    module Mischief.Render.Sampler,   ) where  import Mischief.Materials (CPU, GPU) import Mischief.Render.Buffer (Buffer, createBuffer, maintainBuffer, uploadBuffer)-import Mischief.Render.Camera (Camera (..), OutputTo (..), cameraSwapView, cameraView)+import Mischief.Render.Camera (Camera (..), OutputTo (..), cameraSwapView, cameraView, windowToWorldPos) import Mischief.Render.Core (RenderAdapter, RenderDevice, RenderFirst, RenderLast, RenderPostprocess, RenderPrepare, RenderQueue, RenderTransparent, RenderUpdate) import Mischief.Render.Layers   ( RenderLayers,@@ -65,6 +66,7 @@ import Mischief.Render.Material (WithMaterial (..), renderMaterial, renderSortedMaterial) import Mischief.Render.Material.Definition (Clear (..), RenderOptions (..)) import Mischief.Render.Plugin (RenderPlugin)+import Mischief.Render.Sampler (PixelSampler, StandardSampler, sampler) import Mischief.Render.Sprite.Common (Anchor (..), Sprite (..), SpriteFlip (..), SpriteSlice (..)) import Mischief.SDL.Window @@ -99,4 +101,3 @@ --     * 2.1. [Basics]("Mischief.Render.Tutorial.Basics") --     * 2.2. [Shaders]("Mischief.Render.Tutorial.Shaders") --     * 2.3. [Materials]("Mischief.Render.Tutorial.Materials")--- a
src/Mischief/Render/Camera.hs view
@@ -1,41 +1,33 @@ module Mischief.Render.Camera where -import Codec.Picture import Control.Monad import Control.Monad.IO.Class import Data.Bits-import Data.Default import Data.Foldable-import Data.Maybe (fromMaybe) import Data.Primitive.Ptr (nullPtr)-import Data.Vector.Storable qualified as VS-import Data.Word-import Foreign (with)+import Data.Text qualified as T import Foreign.C.ConstPtr-import GHC.Generics (Generic)-import Linear (V3 (V3), V4 (V4), (!*!))+import Linear (M44, V2 (..), V3 (V3), V4 (V4), inv44, (!*), (!*!), (^*), (^/)) import Mischief.ECS-import Mischief.ECS.Events-import Mischief.ECS.Systems qualified as S import Mischief.Math.Transform+import Mischief.Math.Vec.Orphans.FieldAccessors import Mischief.Render.Buffer import Mischief.Render.Core import Mischief.Render.Layers (RenderLayers) import Mischief.Render.Texture-import Mischief.Render.Texture (createTexture) import Mischief.Render.Texture qualified as Texture import Mischief.SDL.Window import Mischief.Shader (Bufferable, Field) import Mischief.Shader.Internal.State (CPU) import Mischief.Shader.Types qualified as ST-import Mischief.WGPU (wgpuDeviceCreateTexture, wgpuTextureRelease, withWGPUString)+import Mischief.WGPU (wgpuTextureRelease) import Mischief.WGPU.Types.Enums import Mischief.WGPU.Types.General  data Camera = Camera  instance Component Camera where-  required = require @(Transform, RenderLayers)+  required = require @(Transform, RenderLayers, CameraZoom, CameraBackground)  -- | Add this as a relationship between a camera and a window to have the -- camera's output texture be rendered to that window.@@ -46,6 +38,11 @@ instance Component OutputTo where   type IsExclusiveRel OutputTo = True +newtype CameraBackground = CameraBackground (V3 Float) deriving anyclass (Component)++instance Default CameraBackground where+  def = CameraBackground $ V3 0.184313725 0.211764706 0.250980392+ newtype CameraTexture = CameraTexture SwappableTexture  instance Component CameraTexture where@@ -56,6 +53,10 @@         liftIO $ wgpuTextureRelease otherTexture     ] +newtype ViewMatrix = ViewMatrix (M44 Float) deriving anyclass (Component)++newtype ProjectionMatrix = ProjectionMatrix (M44 Float) deriving anyclass (Component)+ newtype CameraMatrices = CameraMatrices (Buffer Matrices) deriving anyclass (Component)  data CameraPlugin@@ -69,24 +70,25 @@       & schedule @Update  updateCameraMatrices :: System ()-updateCameraMatrices = do-  device <- res @RenderDevice-  queue <- res @RenderQueue-  for_ ((,) <$> device <*> queue) go-  where-    go :: (RenderDevice, RenderQueue) -> System ()-    go (device, queue) = do-      cameras <- query [q|Entity, Maybe CameraMatrices, Transform, OutputTo -> (WindowSize) / With Camera|]-      for_ cameras $ \(entity, buffer, transform, From _ (WindowSize w h)) -> do-        buffer <- case buffer of-          Just (CameraMatrices b) -> pure b-          Nothing -> do-            buffer <- createBuffer @Matrices device-            insert (CameraMatrices buffer) entity-            pure buffer+updateCameraMatrices = query_ $ do+  device <- qres @RenderDevice+  queue <- qres @RenderQueue -        uploadBuffer queue buffer (getCameraProjection w h transform)+  (camera, buffer, transform, zoom, From _ (WindowSize w h)) <-+    [q|Entity, Maybe CameraMatrices, Transform, CameraZoom, OutputTo -> (WindowSize) / With Camera|] +  buffer <- case buffer of+    Just (CameraMatrices b) -> pure b+    Nothing -> qlift $ do+      buffer <- createBuffer @Matrices device+      insert (CameraMatrices buffer) camera+      pure buffer++  let matrices = getCameraProjection w h transform zoom+  qlift $ do+    insert (ViewMatrix matrices.view, ProjectionMatrix matrices.projection) camera+    uploadBuffer queue buffer matrices+ onAddCameraOutputTo :: OnAddRel OutputTo -> System () onAddCameraOutputTo (OnAddRel entity target) = updateCameraTexture entity target @@ -128,12 +130,19 @@   deriving stock (Generic)   deriving anyclass (Bufferable) -getCameraProjection :: Int -> Int -> Transform -> Matrices CPU-getCameraProjection w h Transform {translation = pos} = do-  let l = pos.x - (fromIntegral w / 2)-  let r = pos.x + (fromIntegral w / 2)-  let t = pos.y + (fromIntegral h / 2)-  let b = pos.y - (fromIntegral h / 2)+newtype CameraZoom = CameraZoom Float deriving anyclass (Component)++instance Default CameraZoom where+  def = CameraZoom 1++getCameraProjection :: Int -> Int -> Transform -> CameraZoom -> Matrices CPU+getCameraProjection w h Transform {translation = pos} (CameraZoom zoom) = do+  let hw = fromIntegral w / (2 * zoom)+  let hh = fromIntegral h / (2 * zoom)+  let l = pos.x - hw+  let r = pos.x + hw+  let t = pos.y + hh+  let b = pos.y - hh   let n = 0   let f = 100 @@ -180,3 +189,19 @@   qlift $ do     insert (CameraTexture $ SwappableTexture {currentTexture = otherTexture, otherTexture = texture, desc}) camera     createView $ Texture texture desc++-- | Expects a Camera entity and a screen-space position. Outputs that position in world coordinates.+windowToWorldPos :: Entity -> (Float, Float) -> System (Maybe (V2 Float))+windowToWorldPos camera (x, y) = single $ do+  (Rel _ window, ProjectionMatrix proj, ViewMatrix view) <- qget camera [qd|OutputTo -> *, ProjectionMatrix, ViewMatrix|]++  let proj' = inv44 proj+  let view' = inv44 view++  WindowSize {width, height} <- qget window [qd|WindowSize|]++  let ndc = (V4 @Float (x / fromIntegral width) (y / fromIntegral height) 0 1 ^* 2) - 1+  let cameraPos = proj' !* ndc+  let worldPos = view' !* cameraPos++  pure $ V2 worldPos.x (-worldPos.y)
src/Mischief/Render/Core.hs view
@@ -32,7 +32,7 @@  newtype RenderSurface = RenderSurface (Ptr WGPUSurface) -newtype DefaultSampler = DefaultSampler Sampler deriving anyclass (Component)+-- newtype DefaultSampler = DefaultSampler Sampler deriving anyclass (Component)  instance Component RenderSurface where   onRemove =@@ -127,9 +127,6 @@     wgpuSurfaceConfigure surface (ConstPtr config)    insert (RenderSurface surface, WindowFormat format, WindowAlphaMode alphaMode) entity--  sampler <- newSampler (RenderDevice device)-  insertRes $ DefaultSampler sampler  onSetWindowSize :: OnSet WindowSize -> System () onSetWindowSize (OnSet window) = query_ $ do
src/Mischief/Render/Material.hs view
@@ -18,12 +18,14 @@ import Data.Traversable import GHC.TypeLits import Mischief.ECS+import Mischief.ECS.World (setPref) import Mischief.Render.Camera (Camera, CameraTexture (CameraTexture)) import Mischief.Render.Core import Mischief.Render.Layers (RenderLayers) import Mischief.Render.Layers qualified as Layers import Mischief.Render.Material.Definition (Clear, DrawCommand (Draw), Extension (collectExtBindings), FetchBindings (..), Material (IsPhantom, fetch), MaterialType (..), RenderOptions (..), render) import Mischief.Render.Material.Pipeline (qgetPipeline)+import Mischief.Render.Sampler import Mischief.Render.Texture import Mischief.Shader.Internal.Bindings (ErasedBinding (..), ErasedBindingValue (..)) import Unsafe.Coerce (unsafeCoerce)@@ -57,22 +59,24 @@  qrenderMaterial :: forall m. (Material m) => CameraEntity -> RenderLayers -> RenderOptions -> Query System () qrenderMaterial camera layers opts = do-  device <- qres-  queue <- qres-  let ext = Set.toList $ collectExtBindings @'[m]-  let fs = eraseFetches ext-  cams <- qfetchCam camera fs+  qlift $ setPref @DefaultSampler opts.defaultSampler $ query_ $ do+    device <- qres+    queue <- qres+    let ext = Set.toList $ collectExtBindings @'[m]+    let fs = eraseFetches ext+    cams <- qfetchCam camera fs -  commands <- qcollect $ do-    (sprite, layers') <- [q|(Entity, RenderLayers) / With (WithMaterial m)|]-    unless (Layers.intersects layers layers') qstop-    b <- qfetchBindings cams sprite-    pure $ Draw b opts.nvertices+    commands <- qcollect $ do+      (sprite, layers') <- [q|(Entity, RenderLayers) / With (WithMaterial m)|]+      unless (Layers.intersects layers layers') qstop+      b <- qfetchBindings cams sprite+      pure $ Draw b opts.nvertices -  CameraTexture texture <- qget camera [qd|CameraTexture|]-  pipeline <- qgetPipeline @m texture.desc.format-  qlift $ render @m device queue pipeline opts (Texture texture.currentTexture texture.desc) (map (.comp) commands)+    CameraTexture texture <- qget camera [qd|CameraTexture|]+    pipeline <- qgetPipeline @m texture.desc.format +    qlift $ render @m device queue pipeline opts (Texture texture.currentTexture texture.desc) (map (.comp) commands)+ renderSortedMaterial :: forall m a. (Material m, Ord a) => RenderOptions -> (MeshEntity -> Query System a) -> System () renderSortedMaterial opts f = query_ $ do   (camera, layers) <- [q|(Entity, RenderLayers) / With Camera|]@@ -80,26 +84,27 @@  qrenderSortedMaterial :: forall m a. (Material m, Ord a) => (MeshEntity -> Query System a) -> CameraEntity -> RenderLayers -> RenderOptions -> Query System () qrenderSortedMaterial f camera layers opts = do-  device <- qres-  queue <- qres-  let ext = Set.toList $ collectExtBindings @'[m]-  let fs = eraseFetches ext-  cams <- qfetchCam camera fs+  qlift $ setPref @DefaultSampler opts.defaultSampler $ query_ $ do+    device <- qres+    queue <- qres+    let ext = Set.toList $ collectExtBindings @'[m]+    let fs = eraseFetches ext+    cams <- qfetchCam camera fs -  commands <- qcollect $ do-    sprites <- qcollect $ do-      (entity, layers') <- [q|(Entity, RenderLayers) / With (WithMaterial m)|]-      unless (Layers.intersects layers layers') qstop-      qpure entity & qmap (const entity)+    commands <- qcollect $ do+      sprites <- qcollect $ do+        (entity, layers') <- [q|(Entity, RenderLayers) / With (WithMaterial m)|]+        unless (Layers.intersects layers layers') qstop+        qpure entity & qmap (const entity) -    sprite <- fst <$> (qentity . qiter . sortBy (\(From _ a) (From _ b) -> compare a b) =<< mapM (\(From _ e) -> From e <$> f e) sprites)+      sprite <- fst <$> (qentity . qiter . sortBy (\(From _ a) (From _ b) -> compare a b) =<< mapM (\(From _ e) -> From e <$> f e) sprites) -    b <- qfetchBindings cams sprite-    pure $ Draw b opts.nvertices+      b <- qfetchBindings cams sprite+      pure $ Draw b opts.nvertices -  CameraTexture texture <- qget camera [qd|CameraTexture|]-  pipeline <- qgetPipeline @m texture.desc.format-  qlift $ render @m device queue pipeline opts (Texture texture.currentTexture texture.desc) (map (.comp) commands)+    CameraTexture texture <- qget camera [qd|CameraTexture|]+    pipeline <- qgetPipeline @m texture.desc.format+    qlift $ render @m device queue pipeline opts (Texture texture.currentTexture texture.desc) (map (.comp) commands)  data ErasedFetch where   ErasedFetch :: FetchBindings m -> ErasedFetch
src/Mischief/Render/Material/Definition.hs view
@@ -12,6 +12,7 @@ import Data.Map qualified as Map import Data.Set (Set) import Data.Set qualified as Set+import Data.Text (Text) import Data.Text qualified as T import Data.Text.Encoding qualified as T import Foreign (Ptr, nullPtr, with)@@ -21,6 +22,7 @@ import Mischief.ECS import Mischief.Math qualified as Math import Mischief.Render.Core+import Mischief.Render.Sampler (StandardSampler, sampler) import Mischief.Render.Texture import Mischief.Render.TextureFormat import Mischief.Shader hiding (FragmentOutput, VertexOutput)@@ -68,10 +70,10 @@   type Extends a :: [Type]   type Extends a = '[] -  type Extandable a :: Bool+  type Extandable a :: Prelude.Bool   type Extandable a = True -  type IsPhantom a :: Bool+  type IsPhantom a :: Prelude.Bool   type IsPhantom a = False    vertex :: VI a GPU -> Shader a (VO a GPU)@@ -116,7 +118,7 @@   IsExtensionOf a NoMaterial = True   IsExtensionOf a b = IsExtensionOf' '[a] b -type family IsExtensionOf' (m :: [Type]) (target :: Type) :: Bool where+type family IsExtensionOf' (m :: [Type]) (target :: Type) :: Prelude.Bool where   IsExtensionOf' '[] a = False   IsExtensionOf' (a : xs) a = True   IsExtensionOf' (a : xs) t = Or (IsExtensionOf' (Extends a) t) (IsExtensionOf' xs t)@@ -231,7 +233,7 @@       with desc $ \desc -> do         wgpuCommandEncoderBeginRenderPass commandEncoder (ConstPtr desc) -  when (renderPassEncoder == nullPtr) $ error "Couldn't encode render pass."+  when (renderPassEncoder Prelude.== nullPtr) $ error "Couldn't encode render pass."    wgpuRenderPassEncoderSetPipeline renderPassEncoder pipeline   for_ commands $ drawCommand @mat (RenderDevice device) renderPassEncoder bindLayout@@ -242,7 +244,7 @@     let desc = WGPUCommandBufferDescriptor {label, nextInChain = nullPtr}     with desc $ \desc -> wgpuCommandEncoderFinish commandEncoder (ConstPtr desc) -  when (commandBuffer == nullPtr) $ error "Couldn't create command buffer."+  when (commandBuffer Prelude.== nullPtr) $ error "Couldn't create command buffer."    with commandBuffer $ \commandBuffer -> do     wgpuQueueSubmit queue 1 (ConstPtr commandBuffer)@@ -251,16 +253,24 @@   wgpuCommandEncoderRelease commandEncoder   wgpuTextureViewRelease frame +dumpVertex :: forall mat. (Material mat) => Text+dumpVertex = genShader @mat @(VI mat) @(VO mat) "vertex" (Set.toList $ collectBindings @mat) (vertex @mat)++dumpFragment :: forall mat. (Material mat) => Text+dumpFragment = genShader @mat @(VO mat) @FragmentOutput "fragment" (Set.toList $ collectBindings @mat) (convertFrag $ fragment @mat)+ data Clear = DontClear | Clear (Math.V3 Prelude.Float)  data RenderOptions = RenderOptions   { clear :: Clear,-    nvertices :: Nat+    nvertices :: Nat,+    defaultSampler :: Query System Sampler   }  instance Default RenderOptions where   def =     RenderOptions       { clear = DontClear,-        nvertices = 6+        nvertices = 6,+        defaultSampler = sampler @StandardSampler       }
src/Mischief/Render/Material/Pipeline.hs view
@@ -41,7 +41,7 @@   { materialType :: TypeRep,     format :: WGPUTextureFormat   }-  deriving (Eq, Ord)+  deriving (Prelude.Eq, Ord)  newtype PipelineCache = PipelineCache (Map PipelineKey RenderPipeline) deriving anyclass (Component) 
src/Mischief/Render/Plugin.hs view
@@ -26,6 +26,7 @@ import Mischief.Render.Material qualified as Material import Mischief.Render.Material.Definition import Mischief.Render.Material.Pipeline (qgetPipeline)+import Mischief.Render.Sampler (defaultSampler, initSamplers) import Mischief.Render.Sprite (SpritePlugin (..), fetchSpriteBindings) import Mischief.Render.Texture import Mischief.Render.Texture qualified as Texture@@ -65,6 +66,8 @@     void $ spawn $ Observer onAddWindow     void $ spawn $ Observer onSetWindowSize +    void $ spawn $ Observer initSamplers+     systems renderCameras       & schedule @RenderLast @@ -84,7 +87,7 @@       for_ cameras $ \(CameraTexture SwappableTexture {currentTexture = texture}, From _ surface) -> do         format <- getFormat surface adapter         withSurfaceTexture surface (def {Texture.format}) $ \output -> do-          sampler <- newSampler device+          Just sampler <- single defaultSampler           tex <- liftIO $ wgpuTextureCreateView texture (ConstPtr nullPtr)           let command = Draw [ErasedBindingValue Bindings {tex = TextureView tex, sampler}] 3           Just pipeline <- queryOne $ qgetPipeline @DummyFullscreenMaterial format@@ -95,9 +98,9 @@ clearCameras = query_ $ do   device <- qres   queue <- qres-  (CameraTexture SwappableTexture {currentTexture = texture, desc}) <- [q|CameraTexture|]+  (CameraTexture SwappableTexture {currentTexture = texture, desc}, CameraBackground background) <- [q|CameraTexture, CameraBackground|]   pipeline <- qgetPipeline @DummyFullscreenMaterial desc.format-  qlift $ render @ClearMaterial device queue pipeline def {clear = Clear $ V3 0.184313725 0.211764706 0.250980392} (Texture texture desc) []+  qlift $ render @ClearMaterial device queue pipeline def {clear = Clear background} (Texture texture desc) []  withSurfaceTexture :: RenderSurface -> TextureDescriptor -> (Texture -> System a) -> System () withSurfaceTexture (RenderSurface surface) desc f = do
+ src/Mischief/Render/Sampler.hs view
@@ -0,0 +1,88 @@+{-# LANGUAGE AllowAmbiguousTypes #-}++module Mischief.Render.Sampler where++import Control.Monad+import Control.Monad.IO.Class+import Data.Maybe (fromMaybe)+import Data.Primitive.Ptr+import Foreign (with)+import Foreign.C.ConstPtr+import Language.Haskell.TH (Dec (DefaultSigD), Extension (AllowAmbiguousTypes))+import Mischief.ECS+import Mischief.ECS.World (PrefType, getPref)+import Mischief.Render.Core+import Mischief.WGPU+import Mischief.WGPU.Types.Enums+import Mischief.WGPU.Types.General++-- data DefaultSamplerType++-- instance PrefType DefaultSamplerType (Query System Sampler)++class HasSampler a where+  getSampler :: a -> Sampler++newtype StandardSampler = StandardSampler Sampler deriving anyclass (Component)++instance HasSampler StandardSampler where+  getSampler (StandardSampler a) = a++newtype PixelSampler = PixelSampler Sampler deriving anyclass (Component)++instance HasSampler PixelSampler where+  getSampler (PixelSampler a) = a++sampler :: forall a. (Component a, HasSampler a) => Query System Sampler+sampler = getSampler <$> qres @a++data DefaultSampler++instance PrefType DefaultSampler (Query System Sampler)++defaultSampler :: Query System Sampler+defaultSampler = fromMaybe (sampler @StandardSampler) =<< qlift (getPref @DefaultSampler)++initSamplers :: OnAdd RenderDevice -> System ()+initSamplers (OnAdd entity) = do+  Just (RenderDevice device) <- single [q|entity. RenderDevice|]++  standard <- liftIO $ do+    let samplerDesc =+          WGPUSamplerDescriptor+            { addressModeU = wGPUAddressMode_ClampToEdge,+              addressModeV = wGPUAddressMode_ClampToEdge,+              addressModeW = wGPUAddressMode_ClampToEdge,+              magFilter = wGPUFilterMode_Linear,+              minFilter = wGPUFilterMode_Linear,+              mipmapFilter = wGPUMipmapFilterMode_Nearest,+              nextInChain = nullPtr,+              label = WGPUStringView (ConstPtr nullPtr) 0,+              lodMinClamp = 0,+              lodMaxClamp = 32,+              compare = wGPUCompareFunction_Undefined,+              maxAnisotropy = 1+            }+    Sampler <$> with samplerDesc (wgpuDeviceCreateSampler device . ConstPtr)++  insertRes (StandardSampler standard)++  pixel <- liftIO $ do+    let samplerDesc =+          WGPUSamplerDescriptor+            { addressModeU = wGPUAddressMode_ClampToEdge,+              addressModeV = wGPUAddressMode_ClampToEdge,+              addressModeW = wGPUAddressMode_ClampToEdge,+              magFilter = wGPUFilterMode_Nearest,+              minFilter = wGPUFilterMode_Nearest,+              mipmapFilter = wGPUMipmapFilterMode_Nearest,+              nextInChain = nullPtr,+              label = WGPUStringView (ConstPtr nullPtr) 0,+              lodMinClamp = 0,+              lodMaxClamp = 32,+              compare = wGPUCompareFunction_Undefined,+              maxAnisotropy = 1+            }+    Sampler <$> with samplerDesc (wgpuDeviceCreateSampler device . ConstPtr)++  insertRes (PixelSampler pixel)
src/Mischief/Render/Sprite.hs view
@@ -14,6 +14,7 @@ import Mischief.Render.Core import Mischief.Render.Image import Mischief.Render.Material.Definition+import Mischief.Render.Sampler (defaultSampler) import Mischief.Render.Sprite.Common import Mischief.Render.Texture @@ -71,7 +72,7 @@ fetchSpriteBindings =   FetchBindings     ( \camera -> do-        (DefaultSampler sampler) <- qres @DefaultSampler+        sampler <- defaultSampler         CameraMatrices matrices <- qget camera [qd|CameraMatrices|]         pure (matrices, sampler)     )
src/Mischief/Render/Tutorial/Basics.hs view
@@ -16,6 +16,9 @@     -- * Sprites     -- $sprites +    -- * Rendering Pixel-Art+    -- $pixel-art+     -- * [Next Chapter: Shaders]("Mischief.Render.Tutorial.Shaders")   ) where@@ -81,3 +84,12 @@ -- -- Internally, the information from all these components is uploaded into a @'Sprite.SpriteData'@ buffer on each entity, which is bound to the materials -- extending 'Sprite.SpriteMaterial'. It is then used when calling 'Sprite.sampleSprite'.++-- $pixel-art+-- Most materials (including 'Sprite.SpriteMaterial') sample textures using a default sampler which can be changed in the 'RenderOptions'.+--+-- In order to render pixel-art, you can set the default sampler to @PixelSampler@ like so:+--+-- @+-- 'renderMaterial' \@'Sprite.SpriteMaterial' 'def' {'defaultSampler' = 'sampler' \@'PixelSampler'}+-- @
src/Mischief/Render/Tutorial/Start/Start.hs view
@@ -163,8 +163,6 @@ -- @ -- -- @------ @ -- 'spawn_' --   ( 'Sprite' {image}, --     'SpriteSlice' ('V2' 0 387) ('V2' 128 128),
src/Mischief/Shader.hs view
@@ -1,6 +1,7 @@ module Mischief.Shader   ( Shader (..),     var,+    select,     comment,     Bindable,     Bufferable,@@ -27,4 +28,4 @@ import Mischief.Shader.Internal.Params import Mischief.Shader.Internal.State import Mischief.Shader.Types-import Prelude (const, pure, show, undefined, ($), (.), type (~))+import Prelude (const, pure, show, undefined, ($), (.), (<$>), (<*>), (=<<), (>>=), type (~))
src/Mischief/Shader/Functions.hs view
@@ -14,7 +14,7 @@ import Mischief.Shader.Internal.Singletons import Mischief.Shader.Internal.State import Mischief.Shader.Types-import Prelude (Bool (..), undefined, ($), type (~))+import Prelude (Bool (..), error, undefined, ($), type (~))  sample :: Expr TTexture -> Expr TSampler -> Vec 2 Float -> Vec 4 Float sample tex sampler v =@@ -25,6 +25,9 @@       Param v     ] +textureDimensions :: Expr TTexture -> Vec 2 Uint+textureDimensions t = Function "textureDimensions" [Param t]+ unsafeCall :: (SingI a) => Text -> [Param] -> Expr a unsafeCall = Function @@ -107,6 +110,82 @@ (%^) :: (Integral (Primitive a) ~ True) => Expr (Primitive a) -> Expr (VectorType n a) -> Expr (VectorType n a) (%^) = CustomOperator "%" +-- Comparisons++type family ChangePrimitive a b where+  ChangePrimitive (Expr (Primitive a)) b = Primitive b+  ChangePrimitive (Expr (VectorType n a)) b = VectorType n b++class Equal a where+  (==) :: (ChangePrimitive (Expr a) TBool ~ b) => Expr a -> Expr a -> Expr b+  (==) = CustomOperator "=="++  (/=) :: (ChangePrimitive (Expr a) TBool ~ b) => Expr a -> Expr a -> Expr b+  (/=) = CustomOperator "!="++instance {-# OVERLAPPABLE #-} (Algebric a ~ True) => Equal a++instance Equal (Primitive TBool)++instance Equal (VectorType n TBool)++class Comparable a where+  (<) :: (ChangePrimitive (Expr a) TBool ~ b) => Expr a -> Expr a -> Expr b+  (<) = CustomOperator "<"++  (<=) :: (ChangePrimitive (Expr a) TBool ~ b) => Expr a -> Expr a -> Expr b+  (<=) = CustomOperator "<"++  (>) :: (ChangePrimitive (Expr a) TBool ~ b) => Expr a -> Expr a -> Expr b+  (>) = CustomOperator "<"++  (>=) :: (ChangePrimitive (Expr a) TBool ~ b) => Expr a -> Expr a -> Expr b+  (>=) = CustomOperator "<"++instance {-# OVERLAPPABLE #-} (Algebric a ~ True) => Comparable a++all :: (KnownNat n) => Expr (VectorType n TBool) -> Boolean+all x = Function "all" [Param x]++any :: (KnownNat n) => Expr (VectorType n TBool) -> Boolean+any x = Function "any" [Param x]++(&&) :: Boolean -> Boolean -> Boolean+(&&) = CustomOperator "&&"++(||) :: Boolean -> Boolean -> Boolean+(||) = CustomOperator "||"++-- Control Flow Functions++-- | Pass a list of tuples of conditions and branches, and an extra branch that will act as the default.+-- Will return the result of the first branch in the list that has a positive condition. Otherwise the default.+--+-- Follow the same guidelines as for 'select'.+--+-- Example+--+-- @+-- let x = undefined :: Float+-- let y = undefined :: Float+-- let z = undefined :: Float+--+-- r \<- pick+--   [(x \> y, pure $ vec2 5 5),+--    (y \> z, pure $ vec2 6 6)+--   ]+--   (pure $ vec2 1 9)+-- @+pick :: (SingI a) => [(Boolean, Shader m (Expr a))] -> Shader m (Expr a) -> Shader m (Expr a)+pick [] x = x+pick ((b, a) : xs) x = select b a (pick xs x)++pickM :: (SingI a) => [(Shader m Boolean, Shader m (Expr a))] -> Shader m (Expr a) -> Shader m (Expr a)+pickM [] x = x+pickM ((b, a) : xs) x = do+  b' <- b+  select b' a (pickM xs x)+ -- Numeric Functions  abs :: (SingI a, Algebric a ~ True) => Expr a -> Expr a@@ -166,7 +245,7 @@ distance :: (SingI a, Fractional (Expr a) ~ True, VectorOrSingleOf a ~ b) => Expr a -> Expr a -> Expr (Primitive b) distance a b = Function "distance" [Param a, Param b] -dot :: (SingI (Expr (VectorType n a)), SingI a, SingI n, Algebric (Primitive a) ~ True) => Expr (VectorType n a) -> Expr (VectorType n a) -> Expr (Primitive a)+dot :: (SingI (VectorType n a), SingI a, SingI n, Algebric (Primitive a) ~ True) => Expr (VectorType n a) -> Expr (VectorType n a) -> Expr (Primitive a) dot a b = Function "dot" [Param a, Param b]  dot4U8Packed :: Uint -> Uint -> Uint
src/Mischief/Shader/Internal/Bindings.hs view
@@ -5,7 +5,6 @@  import Data.Bifunctor qualified import Data.Data-import Data.Default (Default (def)) import Data.Kind import Data.Primitive.Ptr import Data.Singletons (SingI)@@ -16,16 +15,14 @@ import Foreign.C.ConstPtr import GHC.Generics (Generic (Rep, from), K1 (K1), M1 (M1), U1 (U1), V1 (..), to, (:*:) ((:*:))) import GHC.TypeLits-import Mischief.ECS (System) import Mischief.Render.Buffer (Buffer (..), BufferDescriptor (..)) import Mischief.Render.Core import Mischief.Render.Texture import Mischief.Shader.Internal.Buffers qualified as Buffers import Mischief.Shader.Internal.Singletons import Mischief.Shader.Internal.State-import Mischief.Shader.Types hiding ((<>)) import Mischief.WGPU-import Mischief.WGPU.Opaque (WGPUBindGroup, WGPUBindGroupLayout)+import Mischief.WGPU.Opaque (WGPUBindGroup) import Mischief.WGPU.Types.Enums import Mischief.WGPU.Types.General 
src/Mischief/Shader/Internal/Singletons.hs view
@@ -28,7 +28,7 @@ import GHC.TypeLits import Prelude (Eq) -data PrimitiveTypes = TInt | TFloat | TUInt deriving (Eq)+data PrimitiveTypes = TInt | TFloat | TUInt | TBool deriving (Eq)  data Types where   Primitive :: PrimitiveTypes -> Types@@ -38,7 +38,6 @@   TTexture :: Types   TSampler :: Types   TVoid :: Types-  TBool :: Types   MType :: Types -> Types   deriving (Eq) 
src/Mischief/Shader/Internal/State.hs view
@@ -34,8 +34,12 @@ data Stmt where   Concat :: Stmt -> Stmt -> Stmt   Let :: VarIndex -> Expr a -> Stmt+  LetMut :: VarIndex -> Text -> Stmt+  Assign :: VarIndex -> Expr a -> Stmt   Return :: Expr a -> Stmt   Debug :: Text -> Stmt+  If :: Expr (Primitive TBool) -> Stmt+  Symbol :: Text -> Stmt   Empty :: Stmt  data CustomType a = CustomType@@ -72,8 +76,7 @@   Void :: (SingI a) => Expr a   AppendVecs :: forall (n :: Nat) (m :: Nat) a. (SingI a, PrintVecElements (n + m) a, SingI (VectorType (n + m) a)) => Proxy (VectorType (n + m) a) -> Expr (VectorType n a) -> Expr (VectorType m a) -> Expr (VectorType (n + m) a)   ExtendVec :: forall (n :: Nat) a. (SingI a, PrintVecElements (n + 1) a, SingI (VectorType (n + 1) a)) => Proxy (VectorType (n + 1) a) -> Expr (VectorType n a) -> Expr (Primitive a) -> Expr (VectorType (n + 1) a)-  ConstantBool :: Bool -> Expr TBool-  If :: Expr TBool -> Expr a -> Expr a -> Expr a+  ConstantBool :: Bool -> Expr (Primitive TBool)  data Param where   Param :: (SingI a) => Expr a -> Param@@ -82,7 +85,11 @@   VectorOrSingleOf (VectorType n a) = a   VectorOrSingleOf (Primitive a) = a -instance (SingI a) => Num (Expr (Primitive a)) where+type family NotBool a where+  NotBool TBool = False+  NotBool a = True++instance (SingI a, NotBool a ~ True) => Num (Expr (Primitive a)) where   (+) = Add   (*) = Mult   abs = Abs@@ -93,6 +100,7 @@           TInt -> unsafeCoerce $ ConstantInt (fromInteger i)           TFloat -> unsafeCoerce $ ConstantFloat (fromInteger i)           TUInt -> unsafeCoerce $ ConstantUInt (fromInteger i)+          _ -> error "This should be unreachable"   negate = Neg  instance Fractional (Expr (Primitive TFloat)) where@@ -268,15 +276,18 @@   VectorType 4 TUInt -> "vec4<u32>(" <> exprToWGSL a <> "," <> exprToWGSL b <> ")"   _ -> undefined exprToWGSL (ConstantBool b) = if b then "true" else "false"-exprToWGSL (If bool a b) = "if " <> exprToWGSL bool <> " {" <> exprToWGSL a <> "} else {" <> exprToWGSL b <> "}"  stmtToWGSL :: Stmt -> Text stmtToWGSL Empty = "" stmtToWGSL (Concat Empty a) = stmtToWGSL a stmtToWGSL (Concat a b) = stmtToWGSL a <> "\n" <> stmtToWGSL b stmtToWGSL (Let a b) = "  let " <> nameIndex a <> " = " <> exprToWGSL b <> ";"+stmtToWGSL (LetMut a t) = "  var " <> nameIndex a <> " : " <> t <> ";"+stmtToWGSL (Assign a b) = nameIndex a <> " = " <> exprToWGSL b <> ";" stmtToWGSL (Return a) = "  return " <> exprToWGSL a <> ";" stmtToWGSL (Debug t) = "  //" <> t+stmtToWGSL (If bool) = "  if " <> exprToWGSL bool+stmtToWGSL (Symbol a) = a  -- stmtToWGSL (VLet a b) = "  var " <> nameIndex a <> " = " <> exprToWGSL b <> ";" @@ -326,6 +337,25 @@ var expr = do   index <- newVarIndex   addStmt (Let index expr)+  pure $ Var index++-- | If the condition is true, it will return the result of the first branch, otherwise the second.+--+-- If a branch has logic which isn't common to both branches, you should put as much of it as possible in the branch itself, as anything outside the 'select' will always run no matter the branch.+select :: forall a m. (SingI a) => Expr (Primitive TBool) -> Shader m (Expr a) -> Shader m (Expr a) -> Shader m (Expr a)+select bool (Shader a) (Shader b) = do+  index <- newVarIndex+  addStmt (LetMut index (typeToWGSL (undefined :: Expr a)))+  addStmt (If bool)+  addStmt (Symbol " { ")++  s1 <- get+  let (r1, s2) = runState a s1+  let ast2 = Concat (Concat s2.ast $ Assign index r1) $ Symbol " }\n else {\n"+  let (r2, s3) = runState b s2 {ast = ast2}+  let ast3 = Concat (Concat s3.ast $ Assign index r2) $ Symbol " }\n"++  put s3 {ast = ast3}   pure $ Var index  comment :: Text -> Shader m ()
src/Mischief/Shader/Types.hs view
@@ -59,7 +59,7 @@ (!!) :: (SingI a) => Array (Expr a) -> Uint -> Expr a (!!) = Index -type Boolean = Expr TBool+type Boolean = Expr (Primitive TBool)  type Int = Expr (Primitive TInt) 
test/Main.hs view
@@ -11,9 +11,11 @@ import Mischief.Input import Mischief.Input.Keys qualified as Keys import Mischief.Materials.Sprite+import Mischief.Materials.Sprite (SpriteMaterial) import Mischief.Math hiding (qd) import Mischief.Math.Transform qualified as Transform import Mischief.Render+import Mischief.Render.Material.Definition (dumpFragment)  main :: IO () main = do@@ -26,6 +28,8 @@  instance Plugin MainPlugin where   init = do+    warn $ dumpFragment @SpriteMaterial+     window <- spawn (Window, WindowTitle "Test")     void $ spawn (Camera, Rel OutputTo window)   deps = [dep @RenderPlugin]