nano-ui-shader (empty) → 0.2.0.0
raw patch · 16 files changed
+4544/−0 lines, 16 filesdep +basedep +bytestringdep +containers
Dependencies added: base, bytestring, containers, hashable, nano-ui, nano-ui-shader, primitive, text, unordered-containers, vector
Files
- CHANGELOG.md +11/−0
- LICENSE +20/−0
- README.md +46/−0
- lib/NanoUI/Shader.hs +256/−0
- lib/NanoUI/Shader/Compose.hs +343/−0
- lib/NanoUI/Shader/Effects.hs +488/−0
- lib/NanoUI/Shader/Expr.hs +1022/−0
- lib/NanoUI/Shader/Internal/Emit/CLike.hs +219/−0
- lib/NanoUI/Shader/Internal/Emit/Glsl.hs +119/−0
- lib/NanoUI/Shader/Internal/Emit/Msl.hs +118/−0
- lib/NanoUI/Shader/Internal/Emit/Spirv.hs +671/−0
- lib/NanoUI/Shader/Internal/Eval/Cpu.hs +320/−0
- lib/NanoUI/Shader/Internal/IR.hs +348/−0
- lib/NanoUI/Shader/Internal/Swizzle.hs +169/−0
- nano-ui-shader.cabal +90/−0
- test/Main.hs +304/−0
+ CHANGELOG.md view
@@ -0,0 +1,11 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++Initial release.++- Pure-Haskell typed fragment shader EDSL (`NanoUI.Shader`, `NanoUI.Shader.Expr`, `NanoUI.Shader.Compose`, `NanoUI.Shader.Effects`) with `OverloadedRecordDot` uniform projections, vector swizzles, and `Generic` std140 uniform packing.+- Multi-target compiler from lowered SSA IR to GLSL 150 (OpenGL 3.2), GLSL ES 300 (WebGL2), SPIR-V 1.0 (Vulkan), Metal Shading Language (MSL), and a pure-Haskell CPU evaluator for headless differential testing.+- Algebraic single-pass shader fusion (`composeColor`, `composeDistort`, `distortThenColor`) and multi-pass chaining (`chainLayer`).+- 21 built-in shaders and effects: 6 leaf surface fills (`meshGradient4`, `radialGlow`, `sdfRoundedBox`, `colorWheelHsv`, `noiseGrain`, `checkerboard`) and 15 subtree effects (`grayscale`, `tint`, `groupOpacity`, `gaussianBlur`, `dropShadow`, `waveDistort`, and more).+- Builds with GHC 9.10 through 9.14 (`base >=4.20 && <4.23`).
+ LICENSE view
@@ -0,0 +1,20 @@+Copyright (c) 2026 goolord++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ README.md view
@@ -0,0 +1,46 @@+# nano-ui-shader++Typed fragment shader EDSL and multi-target compiler for [nano-ui](https://github.com/goolord/nano-ui). Write surface fills, color effects, distortion warps, and multi-pass layer effects once in Haskell, fuse compatible passes algebraically, and compile directly to GLSL 150 (OpenGL 3.2), GLSL ES 300 (WebGL2), SPIR-V (Vulkan / SDL3 GPU), MSL (Metal), and a CPU reference evaluator.++```haskell+{-# LANGUAGE DataKinds, DeriveAnyClass, DeriveGeneric, OverloadedRecordDot #-}++import GHC.Generics (Generic)+import NanoUI+import NanoUI.Shader++data PulseParams = PulseParams+ { ppColor :: !Color+ , ppPhase :: !Float+ , ppRings :: !Float+ }+ deriving (Eq, Generic, Uniforms)++pulseRing :: Shader 'Surface PulseParams+pulseRing = surfaceShader $ \u ctx ->+ let p = ctx.uv *^ 2.0 - vec2 1.0 1.0+ wave = 0.5 + 0.5 * sin (vLength p * u.ppRings - u.ppPhase)+ half = ctx.size *^ 0.5+ edge = sdRoundedBox (ctx.pos - half) half ctx.cornerRadius+ aa = 0.75 / maxE ctx.scale 1.0+ mask = 1.0 - smoothstep (negate aa) aa edge+ in vec4_31 (u.ppColor.rgb *^ wave) (u.ppColor.a * mask)+```++Define shaders at top level so compilation happens once; uniform updates pack into std140 bytes and drive damage diffing without recompiling GPU programs. Render leaf fills with `shaderBox` or `shaderConfigured` (zero offscreen targets), and wrap interactive subtrees with `withShader` or `withShader'`.++## Two tiers and pass fusion++Surface fills (`'Surface`) draw directly into the main render target (`meshGradient4`, `radialGlow`, `sdfRoundedBox`, `colorWheelHsv`, `noiseGrain`, `checkerboard`). Subtree effects (`'ColorEffect`, `'DistortionEffect`, `'LayerEffect`) post-process children over pooled offscreen targets while keeping hit-testing, focus, and scrolling intact (`groupOpacity`, `grayscale`, `tint`, `brightnessContrast`, `colorMatrix`, `vignette`, `scanlines`, `waveDistort`, `rippleDistort`, `pixelate`, `boxBlur`, `gaussianBlur`, `dropShadow`, `outerGlow`, `chromaticAberration`).++Compatible subtree passes fuse into a single GPU program with `composeColor`, `composeDistort`, and `distortThenColor`. Multi-pass chains combine with `chainLayer`.++## Authoring and fallback++Enable `DataKinds` and `OverloadedRecordDot` to project uniform fields (`u.ppColor.rgb`) and vector swizzles (`ctx.uv.yx`). Scalar-vector operators are `(*^)`, `(^*)`, `(/^)`, `(+^)`, and `(-^)`; branchless selection is `selectE`. Use `surfaceShaderM`, `colorEffectM`, `distortionEffectM`, or `layerEffectM` when a shader needs `bind` sharing or bounded `forRange` loops. For hand-written backend shader sources without this EDSL, import `NanoUI.Shader.Raw` from `nano-ui`.++Query live GPU support inside a view with `askShaderCapabilities`. When GPU shaders are unavailable (such as under SDL's software renderer), `shaderConfigured` paints `scFallback` and `withShader` renders its children without the effect.++## Documentation++- [The nano-ui Book: Shaders](https://goolord.github.io/nano-ui/book/advanced/shaders.html): Surface fills, subtree effects, pass fusion, and backend fallback.
+ lib/NanoUI/Shader.hs view
@@ -0,0 +1,256 @@+-- |+-- Module : NanoUI.Shader+-- Description : Typed fragment shader EDSL and multi-target GPU compiler+-- Copyright : (c) 2026 Zachary Churchill+-- License : MIT+-- Maintainer : zacharyachurchill@gmail.com+--+-- Public facade for the @nano-ui-shader@ typed fragment shader EDSL,+-- multi-target compiler (GLSL 150, GLSL ES 300, SPIR-V 1.0, MSL, CPU),+-- algebraic effect fusion, and standard effect library.+--+-- Define shaders at top level so compilation runs once, then draw leaf+-- surfaces with 'NanoUI.shaderBox' or wrap interactive subtrees with+-- 'NanoUI.withShader' from "NanoUI". For hand-written backend shader+-- sources, import "NanoUI.Shader.Raw".+module NanoUI.Shader+ ( -- * Core shader types (re-exported from @nano-ui@)+ Shader+ , ShaderKind (..)+ , IsNodeEffect+ , ShaderCapabilities (..)+ , ShaderConfig (..)+ , defaultShaderConfig+ , contramapShader+ , fixUniform+ , Uniforms (..)+ , V3 (..)+ , V4 (..)+ -- * Compiling shaders+ , surfaceShader+ , surfaceShaderM+ , colorEffect+ , colorEffectM+ , distortionEffect+ , distortionEffectM+ , layerEffect+ , layerEffectM+ -- * Algebraic fusion and multi-pass chaining+ , composeColor+ , composeDistort+ , distortThenColor+ , chainLayer+ -- * Expressions and monadic builder+ , Expr+ , FragM+ , liftExpr+ , bind+ , LoopAcc (..)+ , forRange+ , GpuExpr (..)+ , GpuFloat+ , GpuVec+ , GpuSigned+ , GpuMinMax+ , GpuOrd+ , GpuEq+ -- * Uniform access+ , ExprU+ , UniformLeaf+ , uVal+ , uFst+ , uSnd+ , uFst3+ , uSnd3+ , uThd3+ -- * Fragment context and layer sampling+ , FragCtx (..)+ , Layer+ , sampleLayer+ , sampleLayerUv+ -- * Literals and vector construction+ , floatE+ , intE+ , uintE+ , boolE+ , colorE+ , v2E+ , v3E+ , v4E+ , vec2+ , vec3+ , vec4+ , vec3_21+ , vec4_22+ , vec4_31+ , rgba+ , splat2+ , splat3+ , splat4+ , floatToInt+ , intToFloat+ -- * Scalar and vector math+ , absE+ , signE+ , floorE+ , ceilE+ , fractE+ , modE+ , minE+ , maxE+ , clampE+ , clamp01E+ , mix+ , stepE+ , smoothstep+ , powE+ , atan2E+ , dot+ , cross+ , vLength+ , vDistance+ , normalize+ , (*^)+ , (^*)+ , (/^)+ , (+^)+ , (-^)+ -- * Comparisons and branchless selection+ , (.<)+ , (.<=)+ , (.>)+ , (.>=)+ , (.==)+ , (./=)+ , (.&&)+ , (.||)+ , notE+ , selectE+ -- * 2D SDF, color, and noise helpers+ , sdCircle+ , sdRoundedBox+ , luminanceE+ , withAlphaE+ , hsvToRgbE+ , hash21+ , valueNoise2D+ -- * Standard library effects+ , module NanoUI.Shader.Effects+ ) where++import NanoUI.Internal.Shader+ ( IsNodeEffect+ , Shader+ , ShaderCapabilities (..)+ , ShaderConfig (..)+ , ShaderKind (..)+ , contramapShader+ , defaultShaderConfig+ , fixUniform+ )+import NanoUI.Internal.Uniforms (Uniforms (..), V3 (..), V4 (..))+import NanoUI.Shader.Compose+ ( chainLayer+ , colorEffect+ , colorEffectM+ , composeColor+ , composeDistort+ , distortThenColor+ , distortionEffect+ , distortionEffectM+ , layerEffect+ , layerEffectM+ , surfaceShader+ , surfaceShaderM+ )+import NanoUI.Shader.Effects+import NanoUI.Shader.Expr+ ( Expr+ , ExprU+ , FragCtx (..)+ , FragM+ , GpuEq+ , GpuExpr (..)+ , GpuFloat+ , GpuMinMax+ , GpuOrd+ , GpuSigned+ , GpuVec+ , Layer+ , LoopAcc (..)+ , UniformLeaf+ , absE+ , atan2E+ , bind+ , boolE+ , ceilE+ , clamp01E+ , clampE+ , colorE+ , cross+ , dot+ , floatE+ , floatToInt+ , floorE+ , forRange+ , fractE+ , hash21+ , hsvToRgbE+ , intE+ , intToFloat+ , liftExpr+ , luminanceE+ , maxE+ , minE+ , mix+ , modE+ , normalize+ , notE+ , powE+ , rgba+ , sampleLayer+ , sampleLayerUv+ , sdCircle+ , sdRoundedBox+ , selectE+ , signE+ , smoothstep+ , splat2+ , splat3+ , splat4+ , stepE+ , uFst+ , uFst3+ , uSnd+ , uSnd3+ , uThd3+ , uVal+ , uintE+ , v2E+ , v3E+ , v4E+ , vDistance+ , vLength+ , valueNoise2D+ , vec2+ , vec3+ , vec3_21+ , vec4+ , vec4_22+ , vec4_31+ , withAlphaE+ , (*^)+ , (^*)+ , (/^)+ , (+^)+ , (-^)+ , (.&&)+ , (./=)+ , (.<)+ , (.<=)+ , (.==)+ , (.>)+ , (.>=)+ , (.||)+ )+import NanoUI.Shader.Internal.Swizzle ()
+ lib/NanoUI/Shader/Compose.hs view
@@ -0,0 +1,343 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE TypeApplications #-}++-- | Shader compilation from the EDSL to multi-target 'Shader' values, plus+-- algebraic pass fusion ('composeColor', 'composeDistort', 'distortThenColor')+-- and multi-pass chaining ('chainLayer').+module NanoUI.Shader.Compose+ ( -- * Compiling shaders+ surfaceShader+ , surfaceShaderM+ , colorEffect+ , colorEffectM+ , distortionEffect+ , distortionEffectM+ , layerEffect+ , layerEffectM+ -- * Algebraic fusion and multi-pass chaining+ , composeColor+ , composeDistort+ , distortThenColor+ , chainLayer+ -- * Lowering to IR and backend artifacts+ , compileSurfaceIR+ , compileColorIR+ , compileLayerIR+ , compileIRToProgram+ , compileIRToShader+ ) where++import Data.Bits (shiftR, xor)+import Data.Dynamic (fromDynamic, toDyn)+import Data.Proxy (Proxy (..))+import Data.Word (Word64)+import NanoUI (V2 (..))+import NanoUI.Internal.Shader+ ( CpuFragCtx (..)+ , IsNodeEffect (..)+ , Shader (..)+ , ShaderKind (..)+ , ShaderPass (..)+ , ShaderProgram (..)+ )+import NanoUI.Internal.Uniforms+ ( Uniforms (..)+ , V4+ , packUniformBytes+ , uniformLayout+ , uniformSize+ )+import NanoUI.Shader.Internal.Emit.Glsl (emitGlsl150, emitGlslEs300)+import NanoUI.Shader.Internal.Emit.Msl (emitMsl)+import NanoUI.Shader.Internal.Emit.Spirv (emitSpirv)+import NanoUI.Shader.Internal.Eval.Cpu (evalShaderIRColor)+import NanoUI.Shader.Expr+ ( Expr+ , ExprU (..)+ , FragCtx (..)+ , FragM+ , Layer+ , bind+ , mkFragCtx+ , mkLayer+ , runFragM+ , sampleLayer+ , sampleLayerUv+ )+import NanoUI.Shader.Internal.IR (ShaderIR (..), emptyIRBuilder, hashShaderIR, runIRBuilder)+import System.IO.Unsafe (unsafeDupablePerformIO)++-- | Monomorphic EDSL bodies stored in 'shaderFusion' so compatible effects+-- fuse into a single GPU pass with full CSE and zero extra offscreen targets.+data FusionBody+ = FusionColor !(Int -> FragCtx -> Expr V4 -> FragM (Expr V4))+ | FusionDistort !(Int -> FragCtx -> Expr V2 -> FragM (Expr V2))++-- | Compile a 'ShaderIR' into all four GPU backend payloads (GLSL 150,+-- GLSL ES 300, SPIR-V 1.0, MSL). Fields are lazy on 'ShaderProgram' so a+-- backend only pays for the format it consumes.+compileIRToProgram :: ShaderIR -> ShaderProgram+compileIRToProgram ir =+ ShaderProgram+ { spGlsl150 = Just (emitGlsl150 ir)+ , spGlslEs300 = Just (emitGlslEs300 ir)+ , spSpirv = Just (emitSpirv ir)+ , spMsl = Just (emitMsl ir)+ , spNeedsTex = irNeedsInput ir+ , spUniformLayout = irUniforms ir+ , spUniformBytes = irUniformBytes ir+ }++-- | Build a single-pass 'Shader' from a lowered 'ShaderIR', attaching a+-- pure CPU evaluator and optional fusion metadata.+compileIRToShader ::+ forall k u.+ Uniforms u =>+ (u -> V2) ->+ Maybe FusionBody ->+ ShaderIR ->+ Shader k u+compileIRToShader margin mFusion ir =+ let prog = compileIRToProgram ir+ !h = hashShaderIR ir+ !sz = uniformSize (Proxy :: Proxy u)+ pass =+ ShaderPass+ { spHash = h+ , spProgram = prog+ , spUniformSize = sz+ , spPack = \u mba base -> do+ _ <- pokeUniformAt u mba base 0+ pure ()+ }+ cpuEval u ctx pixelSampler =+ let !uBytes = unsafeDupablePerformIO (packUniformBytes u)+ in evalShaderIRColor ir uBytes ctx pixelSampler+ in Shader+ { shaderHash = h+ , shaderPasses = [pass]+ , shaderMargin = margin+ , shaderCpuEval = Just cpuEval+ , shaderSvgOpacity = Nothing+ , shaderFusion = fmap toDyn mFusion+ }++buildFragIR :: Uniforms u => Proxy u -> FragM (Expr V4) -> ShaderIR+buildFragIR p action =+ let fields = uniformLayout p+ uBytes = uniformSize p+ (outId, b) = runFragM action emptyIRBuilder+ in runIRBuilder fields uBytes b outId++-- | Lower a 'Surface' shader body into 'ShaderIR'.+compileSurfaceIR ::+ forall u.+ Uniforms u =>+ (ExprU u -> FragCtx -> FragM (Expr V4)) ->+ ShaderIR+compileSurfaceIR body = buildFragIR (Proxy :: Proxy u) (body (ExprU 0) mkFragCtx)++-- | Lower a 'ColorEffect' body into 'ShaderIR', reading the current pixel+-- from the subtree texture at @ctx.uv@.+compileColorIR ::+ forall u.+ Uniforms u =>+ (ExprU u -> FragCtx -> Expr V4 -> FragM (Expr V4)) ->+ ShaderIR+compileColorIR body =+ let ctx = mkFragCtx+ layer = mkLayer+ in buildFragIR (Proxy :: Proxy u) $ do+ c0 <- bind (sampleLayerUv layer (uv ctx))+ body (ExprU 0) ctx c0++-- | Lower a 'LayerEffect' body into 'ShaderIR'.+compileLayerIR ::+ forall u.+ Uniforms u =>+ (ExprU u -> FragCtx -> Layer -> FragM (Expr V4)) ->+ ShaderIR+compileLayerIR body = buildFragIR (Proxy :: Proxy u) (body (ExprU 0) mkFragCtx mkLayer)++-- | Compile a pure Tier 1 leaf 'Surface' fragment shader.+surfaceShader ::+ Uniforms u =>+ (ExprU u -> FragCtx -> Expr V4) ->+ Shader 'Surface u+surfaceShader f = surfaceShaderM (\u ctx -> pure (f u ctx))++-- | Compile a monadic Tier 1 leaf 'Surface' fragment shader with explicit+-- 'bind' and 'NanoUI.Shader.Expr.forRange' support.+surfaceShaderM ::+ Uniforms u =>+ (ExprU u -> FragCtx -> FragM (Expr V4)) ->+ Shader 'Surface u+surfaceShaderM body = compileIRToShader (const (V2 0 0)) Nothing (compileSurfaceIR body)++-- | Compile a pure per-pixel 'ColorEffect' (eligible for single-pass fusion+-- via 'composeColor' and 'distortThenColor').+colorEffect ::+ Uniforms u =>+ (ExprU u -> FragCtx -> Expr V4 -> Expr V4) ->+ Shader 'ColorEffect u+colorEffect f = colorEffectM (\u ctx c -> pure (f u ctx c))++-- | Compile a monadic per-pixel 'ColorEffect' (eligible for single-pass fusion).+colorEffectM ::+ Uniforms u =>+ (ExprU u -> FragCtx -> Expr V4 -> FragM (Expr V4)) ->+ Shader 'ColorEffect u+colorEffectM body =+ let fusion = FusionColor (\base ctx c -> body (ExprU base) ctx c)+ in compileIRToShader (const (V2 0 0)) (Just fusion) (compileColorIR body)++-- | Compile a pure coordinate-warp 'DistortionEffect' with an explicit maximum+-- sample offset in logical pixels (eligible for single-pass fusion via+-- 'composeDistort' and 'distortThenColor').+distortionEffect ::+ Uniforms u =>+ (u -> V2) ->+ (ExprU u -> FragCtx -> Expr V2 -> Expr V2) ->+ Shader 'DistortionEffect u+distortionEffect margin f = distortionEffectM margin (\u ctx p -> pure (f u ctx p))++-- | Compile a monadic coordinate-warp 'DistortionEffect' with an explicit+-- maximum sample offset in logical pixels.+distortionEffectM ::+ forall u.+ Uniforms u =>+ (u -> V2) ->+ (ExprU u -> FragCtx -> Expr V2 -> FragM (Expr V2)) ->+ Shader 'DistortionEffect u+distortionEffectM margin body =+ let fusion = FusionDistort (\base ctx p -> body (ExprU base) ctx p)+ ir = compileLayerIR @u $ \u ctx layer -> do+ p' <- body u ctx (pos ctx)+ pure (sampleLayer layer p')+ in compileIRToShader margin (Just fusion) ir++-- | Compile a pure neighborhood-sampling 'LayerEffect' with an explicit+-- maximum sample offset in logical pixels.+layerEffect ::+ Uniforms u =>+ (u -> V2) ->+ (ExprU u -> FragCtx -> Layer -> Expr V4) ->+ Shader 'LayerEffect u+layerEffect margin f = layerEffectM margin (\u ctx layer -> pure (f u ctx layer))++-- | Compile a monadic neighborhood-sampling 'LayerEffect' with explicit+-- 'bind' and 'NanoUI.Shader.Expr.forRange' support.+layerEffectM ::+ Uniforms u =>+ (u -> V2) ->+ (ExprU u -> FragCtx -> Layer -> FragM (Expr V4)) ->+ Shader 'LayerEffect u+layerEffectM margin body = compileIRToShader margin Nothing (compileLayerIR body)++-- | Fuse two 'ColorEffect's into a single fragment pass (0 extra offscreen+-- targets). Falls back to two sequential passes if either input is a raw+-- hand-written shader without EDSL fusion metadata.+composeColor ::+ forall u1 u2.+ (Uniforms u1, Uniforms u2) =>+ Shader 'ColorEffect u1 ->+ Shader 'ColorEffect u2 ->+ Shader 'ColorEffect (u1, u2)+composeColor s1 s2 =+ case (shaderFusion s1 >>= fromDynamic, shaderFusion s2 >>= fromDynamic) of+ (Just (FusionColor f1), Just (FusionColor f2)) ->+ let !n1 = length (uniformLayout (Proxy :: Proxy u1))+ fused base ctx c0 = do+ c1 <- f1 base ctx c0 >>= bind+ f2 (base + n1) ctx c1+ ir = compileColorIR @(u1, u2) (\_ ctx c0 -> fused 0 ctx c0)+ in compileIRToShader (const (V2 0 0)) (Just (FusionColor fused)) ir+ _ -> chainPasses s1 s2++-- | Fuse two 'DistortionEffect's into a single coordinate-warp pass (0 extra+-- offscreen targets). Margins sum conservatively in X and Y.+composeDistort ::+ forall u1 u2.+ (Uniforms u1, Uniforms u2) =>+ Shader 'DistortionEffect u1 ->+ Shader 'DistortionEffect u2 ->+ Shader 'DistortionEffect (u1, u2)+composeDistort s1 s2 =+ case (shaderFusion s1 >>= fromDynamic, shaderFusion s2 >>= fromDynamic) of+ (Just (FusionDistort f1), Just (FusionDistort f2)) ->+ let !n1 = length (uniformLayout (Proxy :: Proxy u1))+ fused base ctx p0 = do+ p1 <- f1 base ctx p0 >>= bind+ f2 (base + n1) ctx p1+ margin (u1, u2) = addV2 (shaderMargin s1 u1) (shaderMargin s2 u2)+ ir = compileLayerIR @(u1, u2) $ \_ ctx layer -> do+ p' <- fused 0 ctx (pos ctx)+ pure (sampleLayer layer p')+ in compileIRToShader margin (Just (FusionDistort fused)) ir+ _ -> chainPasses s1 s2++-- | Fuse a 'DistortionEffect' followed by a 'ColorEffect' into a single+-- 'LayerEffect' pass (warping coordinates before sampling, then applying the+-- color transform with no intermediate offscreen target).+distortThenColor ::+ forall u1 u2.+ (Uniforms u1, Uniforms u2) =>+ Shader 'DistortionEffect u1 ->+ Shader 'ColorEffect u2 ->+ Shader 'LayerEffect (u1, u2)+distortThenColor s1 s2 =+ case (shaderFusion s1 >>= fromDynamic, shaderFusion s2 >>= fromDynamic) of+ (Just (FusionDistort fDist), Just (FusionColor fCol)) ->+ let !n1 = length (uniformLayout (Proxy :: Proxy u1))+ margin (u1, _) = shaderMargin s1 u1+ ir = compileLayerIR @(u1, u2) $ \_ ctx layer -> do+ p' <- fDist 0 ctx (pos ctx)+ c0 <- bind (sampleLayer layer p')+ fCol n1 ctx c0+ in compileIRToShader margin Nothing ir+ _ -> chainLayer s1 s2++-- | Chain any two subtree effects sequentially as multi-pass offscreen+-- rendering (for example, horizontal then vertical separable Gaussian blur).+chainLayer ::+ forall k1 k2 u1 u2.+ (IsNodeEffect k1, IsNodeEffect k2) =>+ Shader k1 u1 ->+ Shader k2 u2 ->+ Shader 'LayerEffect (u1, u2)+chainLayer s1 s2 =+ let !_ = nodeEffectKind (Proxy @k1)+ !_ = nodeEffectKind (Proxy @k2)+ in chainPasses s1 s2++chainPasses :: Shader k1 u1 -> Shader k2 u2 -> Shader k3 (u1, u2)+chainPasses s1 s2 =+ Shader+ { shaderHash = mix64 (shaderHash s1) (shaderHash s2 `xor` 0x434841494e)+ , shaderPasses =+ [p {spPack = \(u1, _) -> spPack p u1} | p <- shaderPasses s1]+ ++ [p {spPack = \(_, u2) -> spPack p u2} | p <- shaderPasses s2]+ , shaderMargin = \(u1, u2) -> addV2 (shaderMargin s1 u1) (shaderMargin s2 u2)+ , shaderCpuEval = case (shaderCpuEval s1, shaderCpuEval s2) of+ (Just e1, Just e2) ->+ Just $ \(u1, u2) ctx sampler ->+ let V2 sw sh' = cfcSize ctx+ pass1 pos@(V2 px py) =+ let uv' = V2 (px / max 1 sw) (py / max 1 sh')+ in e1 u1 ctx {cfcPos = pos, cfcUv = uv'} sampler+ in e2 u2 ctx pass1+ _ -> Nothing+ , shaderSvgOpacity = Nothing+ , shaderFusion = Nothing+ }++addV2 :: V2 -> V2 -> V2+addV2 (V2 ax ay) (V2 bx by) = V2 (ax + bx) (ay + by)++mix64 :: Word64 -> Word64 -> Word64+mix64 a b =+ let !x0 = (a `xor` (b + 0x9e3779b97f4a7c15)) * 0xbf58476d1ce4e5b9+ !x1 = (x0 `xor` (x0 `shiftR` 30)) * 0x94d049bb133111eb+ in x1 `xor` (x1 `shiftR` 31)
+ lib/NanoUI/Shader/Effects.hs view
@@ -0,0 +1,488 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE StrictData #-}++-- | Standard library of typed fragment shaders for @nano-ui@:+--+-- * Tier 1 leaf 'Surface' fills ('meshGradient4', 'radialGlow',+-- 'sdfRoundedBox', 'colorWheelHsv', 'noiseGrain', 'checkerboard')+-- * Fusible 'ColorEffect's ('groupOpacity', 'grayscale', 'tint',+-- 'brightnessContrast', 'colorMatrix', 'vignette', 'scanlines')+-- * Fusible 'DistortionEffect's ('waveDistort', 'rippleDistort', 'pixelate')+-- * Multi-sample and multi-pass 'LayerEffect's ('boxBlur', 'gaussianBlur',+-- 'dropShadow', 'outerGlow', 'chromaticAberration')+module NanoUI.Shader.Effects+ ( -- * Surface shaders+ MeshGradientParams (..)+ , meshGradient4+ , RadialGlowParams (..)+ , radialGlow+ , SdfBoxParams (..)+ , sdfRoundedBox+ , colorWheelHsv+ , NoiseParams (..)+ , noiseGrain+ , CheckerParams (..)+ , checkerboard+ -- * Color effects+ , groupOpacity+ , grayscale+ , TintParams (..)+ , tint+ , BrightnessContrastParams (..)+ , brightnessContrast+ , ColorMatrixParams (..)+ , colorMatrix+ , VignetteParams (..)+ , vignette+ , ScanlineParams (..)+ , scanlines+ -- * Distortion effects+ , WaveParams (..)+ , waveDistort+ , RippleParams (..)+ , rippleDistort+ , pixelate+ -- * Layer effects+ , boxBlur+ , gaussianBlur+ , DropShadowParams (..)+ , dropShadow+ , OuterGlowParams (..)+ , outerGlow+ , chromaticAberration+ ) where++import GHC.Generics (Generic)+import NanoUI.Internal.Shader (Shader (..), ShaderKind (..), contramapShader)+import NanoUI (Color, V2 (..))+import NanoUI.Internal.Uniforms (Uniforms, V3 (..), V4)+import NanoUI.Shader.Compose+ ( chainLayer+ , colorEffect+ , distortionEffect+ , layerEffect+ , layerEffectM+ , surfaceShader+ )+import NanoUI.Shader.Expr+import NanoUI.Shader.Internal.Swizzle ()++-- ---------------------------------------------------------------------------+-- Helpers++-- | Soft anti-aliased rounded-corner coverage mask for a surface node using+-- @ctx.cornerRadius@ and @ctx.scale@.+cornerMask :: FragCtx -> Expr Float+cornerMask ctx =+ let halfSize = ctx.size *^ floatE 0.5+ p = ctx.pos - halfSize+ r = minE ctx.cornerRadius (minE halfSize.x halfSize.y)+ d = sdRoundedBox p halfSize r+ aa = floatE 0.75 / maxE ctx.scale (floatE 1.0)+ mask = floatE 1.0 - smoothstep (negate aa) aa d+ in selectE (ctx.cornerRadius .> floatE 0.0) mask (floatE 1.0)++-- | Porter-Duff source-over compositing in straight-alpha RGBA.+overStraight :: Expr V4 -> Expr V4 -> Expr V4+overStraight src dst =+ let sa = src.a+ da = dst.a+ outA = sa + da * (floatE 1.0 - sa)+ rgb = (src.rgb *^ sa + dst.rgb *^ (da * (floatE 1.0 - sa))) /^ maxE outA (floatE 1.0e-5)+ in vec4_31 rgb outA++-- ---------------------------------------------------------------------------+-- Surface shaders++-- | Corner colors for 'meshGradient4'.+data MeshGradientParams = MeshGradientParams+ { mgTopLeft :: !Color+ , mgTopRight :: !Color+ , mgBottomLeft :: !Color+ , mgBottomRight :: !Color+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Smooth bilinear 4-corner gradient clipped to @ctx.cornerRadius@.+meshGradient4 :: Shader 'Surface MeshGradientParams+meshGradient4 = surfaceShader $ \u ctx ->+ let tx = smoothstep (floatE 0.0) (floatE 1.0) ctx.uv.x+ ty = smoothstep (floatE 0.0) (floatE 1.0) ctx.uv.y+ top = mix u.mgTopLeft u.mgTopRight tx+ bot = mix u.mgBottomLeft u.mgBottomRight tx+ col = mix top bot ty * ctx.color+ in withAlphaE (col.a * cornerMask ctx) col++-- | Parameters for 'radialGlow'.+data RadialGlowParams = RadialGlowParams+ { rgColor :: !Color+ , rgCenter :: !V2+ -- ^ Normalized center in @[0, 1] x [0, 1]@.+ , rgRadius :: !Float+ -- ^ Normalized glow radius (e.g. @0.5@).+ , rgSoftness :: !Float+ -- ^ Edge falloff softness (higher values soften the core).+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Soft radial glow centered at @rgCenter@.+radialGlow :: Shader 'Surface RadialGlowParams+radialGlow = surfaceShader $ \u ctx ->+ let d = vDistance ctx.uv u.rgCenter+ r = maxE u.rgRadius (floatE 1.0e-4)+ t = clamp01E (floatE 1.0 - d / r)+ falloff = powE t (maxE u.rgSoftness (floatE 0.25))+ col = u.rgColor * ctx.color+ in withAlphaE (col.a * falloff * cornerMask ctx) col++-- | Parameters for 'sdfRoundedBox'.+data SdfBoxParams = SdfBoxParams+ { sbFill :: !Color+ , sbBorder :: !Color+ , sbBorderWidth :: !Float+ -- ^ Border width in logical pixels.+ , sbRadius :: !Float+ -- ^ Corner radius in logical pixels (falls back to @ctx.cornerRadius@ when @<= 0@).+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Anti-aliased SDF rounded rectangle with optional inner border.+sdfRoundedBox :: Shader 'Surface SdfBoxParams+sdfRoundedBox = surfaceShader $ \u ctx ->+ let halfSize = ctx.size *^ floatE 0.5+ p = ctx.pos - halfSize+ rReq = selectE (u.sbRadius .> floatE 0.0) u.sbRadius ctx.cornerRadius+ r = minE rReq (minE halfSize.x halfSize.y)+ d = sdRoundedBox p halfSize r+ aa = floatE 0.75 / maxE ctx.scale (floatE 1.0)+ outerMask = floatE 1.0 - smoothstep (negate aa) aa d+ innerMask = floatE 1.0 - smoothstep (negate aa) aa (d + u.sbBorderWidth)+ baseCol = mix u.sbBorder u.sbFill innerMask+ col = selectE (u.sbBorderWidth .> floatE 0.0) baseCol u.sbFill * ctx.color+ in withAlphaE (col.a * outerMask) col++-- | Smooth HSV color wheel parameterized by value (brightness in @[0, 1]@).+colorWheelHsv :: Shader 'Surface Float+colorWheelHsv = surfaceShader $ \u ctx ->+ let p = ctx.uv - vec2 (floatE 0.5) (floatE 0.5)+ r = vLength p * floatE 2.0+ ang = atan2E p.y p.x+ hue = fractE (ang / floatE (2.0 * pi) + floatE 1.0)+ sat = clamp01E r+ rgb = hsvToRgbE hue sat (clamp01E (uVal u))+ aa = floatE 2.0 / maxE (minE ctx.size.x ctx.size.y) (floatE 1.0)+ alpha = floatE 1.0 - smoothstep (floatE 1.0 - aa) (floatE 1.0 + aa) r+ in vec4_31 rgb alpha * ctx.color++-- | Parameters for 'noiseGrain'.+data NoiseParams = NoiseParams+ { npScale :: !Float+ -- ^ Feature size in logical pixels.+ , npTime :: !Float+ -- ^ Animation phase offset.+ , npColorA :: !Color+ , npColorB :: !Color+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Procedural 2-octave 2D value noise surface.+noiseGrain :: Shader 'Surface NoiseParams+noiseGrain = surfaceShader $ \u ctx ->+ let sc = maxE u.npScale (floatE 1.0)+ p = ctx.pos /^ sc + vec2 u.npTime (u.npTime * floatE 0.73)+ n1 = valueNoise2D p+ n2 = valueNoise2D (p *^ floatE 2.03 + vec2 (floatE 17.1) (floatE 31.7))+ v = clamp01E (n1 * floatE 0.65 + n2 * floatE 0.35)+ col = mix u.npColorA u.npColorB v * ctx.color+ in withAlphaE (col.a * cornerMask ctx) col++-- | Parameters for 'checkerboard'.+data CheckerParams = CheckerParams+ { cpCellSize :: !Float+ -- ^ Checker square size in logical pixels.+ , cpColorA :: !Color+ , cpColorB :: !Color+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Crisp logical-pixel checkerboard (commonly used as a transparency backdrop).+checkerboard :: Shader 'Surface CheckerParams+checkerboard = surfaceShader $ \u ctx ->+ let cell = maxE u.cpCellSize (floatE 1.0)+ gx = floorE (ctx.pos.x / cell)+ gy = floorE (ctx.pos.y / cell)+ oddCell = modE (gx + gy) (floatE 2.0) .>= floatE 1.0+ col = selectE oddCell u.cpColorB u.cpColorA * ctx.color+ in withAlphaE (col.a * cornerMask ctx) col++-- ---------------------------------------------------------------------------+-- Color effects (single-pass fusible)++-- | Multiply the entire subtree's alpha as one composited group (avoiding+-- internal double-blending). Also carries 'shaderSvgOpacity' so SVG export+-- emits a native @<g opacity="...">@ group.+groupOpacity :: Shader 'ColorEffect Float+groupOpacity =+ (colorEffect $ \u _ c -> withAlphaE (c.a * clamp01E (uVal u)) c)+ { shaderSvgOpacity = Just (\a -> max 0 (min 1 a))+ }++-- | Desaturate a subtree toward perceptual luminance by strength in @[0, 1]@.+grayscale :: Shader 'ColorEffect Float+grayscale = colorEffect $ \u _ c ->+ let lum = luminanceE c+ gray = vec3 lum lum lum+ in vec4_31 (mix c.rgb gray (clamp01E (uVal u))) c.a++-- | Parameters for 'tint'.+data TintParams = TintParams+ { tpColor :: !Color+ , tpAmount :: !Float+ -- ^ Blend strength in @[0, 1]@.+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Blend subtree RGB toward @tpColor@ by @tpAmount@, preserving alpha.+tint :: Shader 'ColorEffect TintParams+tint = colorEffect $ \u _ c ->+ vec4_31 (mix c.rgb u.tpColor.rgb (clamp01E u.tpAmount)) c.a++-- | Parameters for 'brightnessContrast'.+data BrightnessContrastParams = BrightnessContrastParams+ { bcBrightness :: !Float+ -- ^ Additive offset in @[-1, 1]@ (@0@ is neutral).+ , bcContrast :: !Float+ -- ^ Multiplicative contrast around @0.5@ (@1@ is neutral).+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Adjust brightness and contrast of a subtree.+brightnessContrast :: Shader 'ColorEffect BrightnessContrastParams+brightnessContrast = colorEffect $ \u _ c ->+ let half = vec3 (floatE 0.5) (floatE 0.5) (floatE 0.5)+ adj = (c.rgb - half) *^ u.bcContrast + half +^ u.bcBrightness+ in vec4_31 (clampE adj (vec3 (floatE 0.0) (floatE 0.0) (floatE 0.0)) (vec3 (floatE 1.0) (floatE 1.0) (floatE 1.0))) c.a++-- | 3x3 RGB matrix rows plus additive RGB offset for 'colorMatrix'.+data ColorMatrixParams = ColorMatrixParams+ { cmRowR :: !V3+ , cmRowG :: !V3+ , cmRowB :: !V3+ , cmOffset :: !V3+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Apply an arbitrary 3x3 RGB color matrix and offset (sepia, color-blindness+-- simulation, channel swaps).+colorMatrix :: Shader 'ColorEffect ColorMatrixParams+colorMatrix = colorEffect $ \u _ c ->+ let r = dot c.rgb u.cmRowR + u.cmOffset.x+ g = dot c.rgb u.cmRowG + u.cmOffset.y+ b = dot c.rgb u.cmRowB + u.cmOffset.z+ rgb = clampE (vec3 r g b) (vec3 (floatE 0.0) (floatE 0.0) (floatE 0.0)) (vec3 (floatE 1.0) (floatE 1.0) (floatE 1.0))+ in vec4_31 rgb c.a++-- | Parameters for 'vignette'.+data VignetteParams = VignetteParams+ { vpStrength :: !Float+ -- ^ Edge darkening factor in @[0, 1]@.+ , vpSoftness :: !Float+ -- ^ Falloff width (e.g. @0.4@).+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Radial vignette darkening the corners of a subtree.+vignette :: Shader 'ColorEffect VignetteParams+vignette = colorEffect $ \u ctx c ->+ let d = vDistance ctx.uv (vec2 (floatE 0.5) (floatE 0.5)) * floatE 1.4142135+ soft = maxE u.vpSoftness (floatE 0.05)+ fade = smoothstep (floatE 1.0 - soft) (floatE 1.0) d+ factor = floatE 1.0 - clamp01E u.vpStrength * fade+ in vec4_31 (c.rgb *^ factor) c.a++-- | Parameters for 'scanlines'.+data ScanlineParams = ScanlineParams+ { slPitch :: !Float+ -- ^ Vertical spacing in logical pixels (e.g. @3.0@).+ , slDarken :: !Float+ -- ^ Scanline trough darkening in @[0, 1]@.+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Horizontal CRT scanline modulation.+scanlines :: Shader 'ColorEffect ScanlineParams+scanlines = colorEffect $ \u ctx c ->+ let pitch = maxE u.slPitch (floatE 1.0)+ wave = floatE 0.5 + floatE 0.5 * sin (ctx.pos.y * floatE (2.0 * pi) / pitch)+ factor = floatE 1.0 - clamp01E u.slDarken * (floatE 1.0 - wave)+ in vec4_31 (c.rgb *^ factor) c.a++-- ---------------------------------------------------------------------------+-- Distortion effects (single-pass fusible)++-- | Parameters for 'waveDistort'.+data WaveParams = WaveParams+ { wpAmplitude :: !Float+ -- ^ Horizontal wave displacement in logical pixels.+ , wpFrequency :: !Float+ -- ^ Spatial frequency in radians per logical pixel.+ , wpPhase :: !Float+ -- ^ Animation phase in radians.+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Sinusoidal horizontal wave warp.+waveDistort :: Shader 'DistortionEffect WaveParams+waveDistort =+ distortionEffect+ (\p -> let a = abs (wpAmplitude p) in V2 a 0)+ (\u _ pos -> vec2 (pos.x + u.wpAmplitude * sin (pos.y * u.wpFrequency + u.wpPhase)) pos.y)++-- | Parameters for 'rippleDistort'.+data RippleParams = RippleParams+ { rpCenter :: !V2+ -- ^ Ripple center in logical pixels.+ , rpAmplitude :: !Float+ -- ^ Radial displacement amplitude in logical pixels.+ , rpFrequency :: !Float+ -- ^ Spatial frequency in radians per logical pixel.+ , rpPhase :: !Float+ -- ^ Animation phase in radians.+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Concentric radial water-ripple warp around @rpCenter@.+rippleDistort :: Shader 'DistortionEffect RippleParams+rippleDistort =+ distortionEffect+ (\p -> let a = abs (rpAmplitude p) in V2 a a)+ $ \u _ pos ->+ let delta = pos - u.rpCenter+ dist = vLength delta+ dir = delta /^ maxE dist (floatE 1.0e-4)+ disp = u.rpAmplitude * sin (dist * u.rpFrequency - u.rpPhase)+ in pos + dir *^ disp++-- | Quantize sample coordinates to square mosaic blocks of side @blockSize@+-- logical pixels.+pixelate :: Shader 'DistortionEffect Float+pixelate =+ distortionEffect+ (\sz -> let m = max 0 sz in V2 m m)+ $ \u _ pos ->+ let sz = maxE (uVal u) (floatE 1.0)+ in (floorE (pos /^ sz) + vec2 (floatE 0.5) (floatE 0.5)) *^ sz++-- ---------------------------------------------------------------------------+-- Layer effects (single-pass and multi-pass)++-- | 5x5 uniform box blur scaled by logical pixel radius. Accumulates in+-- premultiplied space and un-premultiplies so blurred edges over transparent+-- offscreen targets avoid dark fringes.+boxBlur :: Shader 'LayerEffect Float+boxBlur =+ layerEffectM (\r -> let m = max 0 r in V2 m m) $ \u ctx layer -> do+ stepPx <- bind (maxE (uVal u) (floatE 0.0) * floatE 0.5)+ acc0 <- bind (vec4 (floatE 0.0) (floatE 0.0) (floatE 0.0) (floatE 0.0))+ total <- forRange (-2) 3 acc0 $ \iy rowAcc ->+ forRange (-2) 3 rowAcc $ \ix colAcc -> do+ let off = vec2 (intToFloat ix * stepPx) (intToFloat iy * stepPx)+ s = sampleLayer layer (ctx.pos + off)+ premul = vec4_31 (s.rgb *^ s.a) s.a+ pure (colAcc + premul)+ let avg = total *^ floatE (1.0 / 25.0)+ straightRgb = avg.rgb /^ maxE avg.a (floatE 1.0e-5)+ pure (vec4_31 straightRgb avg.a)++-- | One 1D 9-tap Gaussian blur pass along axis @(ax, ay)@.+gaussianBlur1D :: Float -> Float -> Shader 'LayerEffect Float+gaussianBlur1D ax ay =+ layerEffectM (\sigma -> let m = max 0 (sigma * 3.0) in V2 (m * abs ax) (m * abs ay)) $ \u ctx layer -> do+ sigma <- bind (maxE (uVal u) (floatE 1.0e-3))+ stepPx <- bind (sigma * floatE 0.75)+ invTwoSig2 <- bind (floatE 0.5 / (sigma * sigma))+ let zero4 = vec4 (floatE 0.0) (floatE 0.0) (floatE 0.0) (floatE 0.0)+ (colSum, wSum) <- forRange (-4) 5 (zero4, floatE 0.0) $ \ik (cAcc, wAcc) -> do+ d <- bind (intToFloat ik * stepPx)+ w <- bind (exp (negate (d * d) * invTwoSig2))+ let off = vec2 (d * floatE ax) (d * floatE ay)+ s = sampleLayer layer (ctx.pos + off)+ premul = vec4_31 (s.rgb *^ s.a) s.a+ pure (cAcc + premul *^ w, wAcc + w)+ let avg = colSum /^ maxE wSum (floatE 1.0e-5)+ straightRgb = avg.rgb /^ maxE avg.a (floatE 1.0e-5)+ pure (vec4_31 straightRgb avg.a)++-- | Separable 2-pass Gaussian blur parameterized by blur sigma in logical+-- pixels (horizontal pass chained with vertical pass).+gaussianBlur :: Shader 'LayerEffect Float+gaussianBlur =+ contramapShader (\sigma -> (sigma, sigma)) $+ chainLayer (gaussianBlur1D 1.0 0.0) (gaussianBlur1D 0.0 1.0)++-- | Parameters for 'dropShadow'.+data DropShadowParams = DropShadowParams+ { dsOffset :: !V2+ -- ^ Shadow offset in logical pixels (positive moves right and down).+ , dsRadius :: !Float+ -- ^ Softness blur radius in logical pixels.+ , dsColor :: !Color+ -- ^ Shadow RGBA color.+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Soft offset drop shadow composited behind the source subtree.+dropShadow :: Shader 'LayerEffect DropShadowParams+dropShadow =+ layerEffectM+ (\p -> V2 (abs (v2X (dsOffset p)) + max 0 (dsRadius p)) (abs (v2Y (dsOffset p)) + max 0 (dsRadius p)))+ $ \u ctx layer -> do+ src <- bind (sampleLayer layer ctx.pos)+ stepPx <- bind (maxE u.dsRadius (floatE 0.0) * floatE 0.5)+ basePos <- bind (ctx.pos - u.dsOffset)+ aSum <- forRange (-2) 3 (floatE 0.0) $ \iy rAcc ->+ forRange (-2) 3 rAcc $ \ix cAcc -> do+ let off = vec2 (intToFloat ix * stepPx) (intToFloat iy * stepPx)+ s = sampleLayer layer (basePos + off)+ pure (cAcc + s.a)+ let shadowA = (aSum * floatE (1.0 / 25.0)) * u.dsColor.a+ shadowCol = vec4_31 u.dsColor.rgb shadowA+ pure (overStraight src shadowCol)++-- | Parameters for 'outerGlow'.+data OuterGlowParams = OuterGlowParams+ { ogRadius :: !Float+ -- ^ Glow spread radius in logical pixels.+ , ogIntensity :: !Float+ -- ^ Glow brightness multiplier.+ , ogColor :: !Color+ }+ deriving (Eq, Show, Generic, Uniforms)++-- | Soft halo glow behind non-transparent edges of the source subtree.+outerGlow :: Shader 'LayerEffect OuterGlowParams+outerGlow =+ layerEffectM (\p -> let r = max 0 (ogRadius p) in V2 r r) $ \u ctx layer -> do+ src <- bind (sampleLayer layer ctx.pos)+ stepPx <- bind (maxE u.ogRadius (floatE 0.0) * floatE 0.5)+ aSum <- forRange (-2) 3 (floatE 0.0) $ \iy rAcc ->+ forRange (-2) 3 rAcc $ \ix cAcc -> do+ let off = vec2 (intToFloat ix * stepPx) (intToFloat iy * stepPx)+ s = sampleLayer layer (ctx.pos + off)+ pure (cAcc + s.a)+ let glowA = clamp01E ((aSum * floatE (1.0 / 25.0)) * u.ogIntensity) * u.ogColor.a+ glowCol = vec4_31 u.ogColor.rgb glowA+ pure (overStraight src glowCol)++-- | Horizontal RGB chromatic aberration split by logical pixel shift.+chromaticAberration :: Shader 'LayerEffect Float+chromaticAberration =+ layerEffect (\shift -> V2 (abs shift) 0) $ \u ctx layer ->+ let d = vec2 (uVal u) (floatE 0.0)+ cR = sampleLayer layer (ctx.pos + d)+ cG = sampleLayer layer ctx.pos+ cB = sampleLayer layer (ctx.pos - d)+ in vec4 cR.r cG.g cB.b cG.a
+ lib/NanoUI/Shader/Expr.hs view
@@ -0,0 +1,1022 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StrictData #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}++-- | Pure-Haskell typed fragment shader EDSL.+--+-- Simple shaders are pure functions @ExprU u -> FragCtx -> Expr V4@ lowered+-- through structural hash-consing (CSE). Iterative shaders (blur kernels,+-- multi-octave noise) can use 'FragM' for explicit SSA 'bind' and bounded+-- 'forRange' loops.+module NanoUI.Shader.Expr+ ( -- * Expressions and monadic builder+ Expr+ , runExpr+ , FragM+ , runFragM+ , liftExpr+ , bind+ , LoopAcc (..)+ , forRange+ , GpuExpr (..)+ , GpuFloat+ , GpuVec+ , GpuSigned+ , GpuMinMax+ , GpuOrd+ , GpuEq+ -- * Uniform access+ , ExprU (..)+ , UniformLeaf (..)+ , uVal+ , uFst+ , uSnd+ , uFst3+ , uSnd3+ , uThd3+ -- * Built-in fragment context and layer sampling+ , FragCtx (..)+ , mkFragCtx+ , Layer+ , mkLayer+ , sampleLayer+ , sampleLayerUv+ -- * Literals and vector construction+ , floatE+ , intE+ , uintE+ , boolE+ , colorE+ , v2E+ , v3E+ , v4E+ , vec2+ , vec3+ , vec4+ , vec3_21+ , vec4_22+ , vec4_31+ , rgba+ , splat2+ , splat3+ , splat4+ , floatToInt+ , intToFloat+ -- * Scalar and vector math+ , absE+ , signE+ , floorE+ , ceilE+ , fractE+ , modE+ , minE+ , maxE+ , clampE+ , clamp01E+ , mix+ , stepE+ , smoothstep+ , powE+ , atan2E+ , dot+ , cross+ , vLength+ , vDistance+ , normalize+ , (*^)+ , (^*)+ , (/^)+ , (+^)+ , (-^)+ -- * Comparisons and branchless selection+ , (.<)+ , (.<=)+ , (.>)+ , (.>=)+ , (.==)+ , (./=)+ , (.&&)+ , (.||)+ , notE+ , selectE+ -- * Common 2D SDF, color, and noise helpers+ , sdCircle+ , sdRoundedBox+ , luminanceE+ , withAlphaE+ , hsvToRgbE+ , hash21+ , valueNoise2D+ ) where++import Data.Bits (shiftR, (.&.))+import Data.Int (Int32)+import Data.Kind (Type)+import Data.Proxy (Proxy (..))+import Data.Word (Word32)+import GHC.Float (castFloatToWord32)+import GHC.Generics+ ( (:*:) (..)+ , C1+ , D1+ , Generic (..)+ , K1 (..)+ , Meta (MetaSel)+ , S1+ , U1+ )+import GHC.Records (HasField (..))+import GHC.TypeLits+ ( ErrorMessage (..)+ , KnownNat+ , Nat+ , Symbol+ , TypeError+ , natVal+ , type (+)+ )+import NanoUI (Color (..), Rect, Size, V2 (..))+import NanoUI.Internal.Uniforms (GpuType (..), V3 (..), V4 (..))+import NanoUI.Shader.Internal.IR+import NanoUI.Shader.Internal.Swizzle (Swizzle (..))++-- | Typed fragment shader expression lowered into 'ShaderIR' at lexical scope+-- depth @d@.+newtype Expr a = Expr (Int -> IRBuilder -> (NodeId, IRBuilder))++-- | Lower an 'Expr' into an 'IRBuilder' at scope depth @d@.+runExpr :: Int -> Expr a -> IRBuilder -> (NodeId, IRBuilder)+runExpr d (Expr f) = f d++-- | Monadic fragment builder for explicit SSA 'bind' and bounded 'forRange'+-- loops.+newtype FragM a = FragM (Int -> IRBuilder -> (a, IRBuilder))++instance Functor FragM where+ fmap f (FragM g) = FragM $ \d b ->+ let (a, b') = g d b+ in (f a, b')++instance Applicative FragM where+ pure a = FragM $ \_ b -> (a, b)+ FragM ff <*> FragM fa = FragM $ \d b ->+ let (f, b1) = ff d b+ (a, b2) = fa d b1+ in (f a, b2)++instance Monad FragM where+ FragM fa >>= k = FragM $ \d b ->+ let (a, b1) = fa d b+ FragM fb = k a+ in fb d b1++-- | Lower a 'FragM' action returning an @Expr V4@ at scope depth 0.+runFragM :: FragM (Expr V4) -> IRBuilder -> (NodeId, IRBuilder)+runFragM (FragM f) b0 =+ let (e, b1) = f 0 b0+ in runExpr 0 e b1++-- | Lift a pure 'Expr' into 'FragM'.+liftExpr :: Expr a -> FragM (Expr a)+liftExpr = pure++-- | Mapping from Haskell shader expression types to 'IRType'.+class GpuExpr a where+ exprIRType :: Proxy a -> IRType++instance GpuExpr Float where exprIRType _ = TFloat+instance GpuExpr Int32 where exprIRType _ = TInt+instance GpuExpr Word32 where exprIRType _ = TUInt+instance GpuExpr Bool where exprIRType _ = TBool+instance GpuExpr V2 where exprIRType _ = TVec2+instance GpuExpr V3 where exprIRType _ = TVec3+instance GpuExpr V4 where exprIRType _ = TVec4++-- | Floating-point scalar and vector expression types.+class GpuExpr a => GpuFloat a+instance GpuFloat Float+instance GpuFloat V2+instance GpuFloat V3+instance GpuFloat V4++-- | Floating-point vector expression types (@V2@, @V3@, @V4@).+class GpuFloat a => GpuVec a+instance GpuVec V2+instance GpuVec V3+instance GpuVec V4++-- | Signed expression types supporting 'absE' and 'signE'.+class GpuExpr a => GpuSigned a+instance GpuSigned Float+instance GpuSigned V2+instance GpuSigned V3+instance GpuSigned V4+instance GpuSigned Int32++-- | Numeric expression types supporting 'minE', 'maxE', and 'clampE'.+class GpuExpr a => GpuMinMax a+instance GpuMinMax Float+instance GpuMinMax V2+instance GpuMinMax V3+instance GpuMinMax V4+instance GpuMinMax Int32+instance GpuMinMax Word32++-- | Ordered scalar expression types supporting @.<@, @.<=@, @.>@, and @.>=@.+class GpuExpr a => GpuOrd a+instance GpuOrd Float+instance GpuOrd Int32+instance GpuOrd Word32++-- | Scalar expression types supporting @.==@ and @./=@.+class GpuExpr a => GpuEq a+instance GpuEq Float+instance GpuEq Int32+instance GpuEq Word32+instance GpuEq Bool++-- | Reference an already-emitted SSA node from scope depth @defDepth@.+refNode :: forall a. GpuExpr a => Int -> NodeId -> Expr a+refNode defDepth nid = Expr $ \curDepth b ->+ if curDepth == defDepth+ then (nid, b)+ else emitNode (exprIRType (Proxy @a)) (OpOuterRef defDepth nid) b++-- | Emit @e@ once in the current scope and return a reference expression that+-- reuses that SSA value everywhere (including inside nested 'forRange' loops).+bind :: forall a. GpuExpr a => Expr a -> FragM (Expr a)+bind e = FragM $ \d b ->+ let (nid, b') = runExpr d e b+ in (refNode d nid, b')++-- | Values that can be carried across iterations of a bounded GPU 'forRange'+-- loop (single 'Expr's or tuples of them).+class LoopAcc s where+ loopAccTypes :: Proxy s -> [IRType]+ loopAccEmit :: Int -> s -> IRBuilder -> ([NodeId], IRBuilder)+ loopAccState :: Int -> Int -> (s, Int)+ loopAccProject :: Int -> NodeId -> Int -> IRBuilder -> (s, Int, IRBuilder)++instance GpuExpr a => LoopAcc (Expr a) where+ loopAccTypes _ = [exprIRType (Proxy @a)]+ loopAccEmit d e b =+ let (nid, b') = runExpr d e b+ in ([nid], b')+ loopAccState lid slot =+ let e = Expr $ \_ b -> emitNode (exprIRType (Proxy @a)) (OpLoopState lid slot) b+ in (e, slot + 1)+ loopAccProject defDepth loopNode slot b0 =+ let (nid, b1) = emitNode (exprIRType (Proxy @a)) (OpLoopResult loopNode slot) b0+ in (refNode defDepth nid, slot + 1, b1)++instance (LoopAcc a, LoopAcc b) => LoopAcc (a, b) where+ loopAccTypes _ = loopAccTypes (Proxy @a) <> loopAccTypes (Proxy @b)+ loopAccEmit d (a, b) ir0 =+ let (na, ir1) = loopAccEmit d a ir0+ (nb, ir2) = loopAccEmit d b ir1+ in (na <> nb, ir2)+ loopAccState lid slot0 =+ let (a, slot1) = loopAccState lid slot0+ (b, slot2) = loopAccState lid slot1+ in ((a, b), slot2)+ loopAccProject defDepth loopNode slot0 b0 =+ let (a, slot1, b1) = loopAccProject defDepth loopNode slot0 b0+ (b, slot2, b2) = loopAccProject defDepth loopNode slot1 b1+ in ((a, b), slot2, b2)++instance (LoopAcc a, LoopAcc b, LoopAcc c) => LoopAcc (a, b, c) where+ loopAccTypes _ = loopAccTypes (Proxy @a) <> loopAccTypes (Proxy @b) <> loopAccTypes (Proxy @c)+ loopAccEmit d (a, b, c) ir0 =+ let (na, ir1) = loopAccEmit d a ir0+ (nb, ir2) = loopAccEmit d b ir1+ (nc, ir3) = loopAccEmit d c ir2+ in (na <> nb <> nc, ir3)+ loopAccState lid slot0 =+ let (a, slot1) = loopAccState lid slot0+ (b, slot2) = loopAccState lid slot1+ (c, slot3) = loopAccState lid slot2+ in ((a, b, c), slot3)+ loopAccProject defDepth loopNode slot0 b0 =+ let (a, slot1, b1) = loopAccProject defDepth loopNode slot0 b0+ (b, slot2, b2) = loopAccProject defDepth loopNode slot1 b1+ (c, slot3, b3) = loopAccProject defDepth loopNode slot2 b2+ in ((a, b, c), slot3, b3)++-- | Bounded GPU loop from @start@ (inclusive) to @end@ (exclusive), threading+-- accumulator state @s@. Emits a structured loop in GLSL, MSL, and SPIR-V.+forRange ::+ forall s.+ LoopAcc s =>+ Int32 ->+ Int32 ->+ s ->+ (Expr Int32 -> s -> FragM s) ->+ FragM s+forRange start end initState stepFn = FragM $ \d b0 ->+ let (initIds, b1) = loopAccEmit d initState b0+ tys = loopAccTypes (Proxy @s)+ innerDepth = d + 1+ (loopNode, b2) = emitLoop start end initIds tys (\lid sub0 ->+ let loopVar = Expr $ \_ sb -> emitNode TInt (OpLoopVar lid) sb+ (stIn, _) = loopAccState lid 0+ FragM bodyAct = stepFn loopVar stIn+ (stOut, sub1) = bodyAct innerDepth sub0+ in loopAccEmit innerDepth stOut sub1+ ) b1+ (resultState, _, b3) = loopAccProject d loopNode 0 b2+ in (resultState, b3)++-- ---------------------------------------------------------------------------+-- OverloadedRecordDot swizzling on Expr V2 / V3 / V4+-- ---------------------------------------------------------------------------++instance (GpuExpr r, Swizzle s v r) => HasField s (Expr v) (Expr r) where+ getField v = Expr $ \d b ->+ let (vid, b1) = runExpr d v b+ idxs = swizzleIndices (Proxy @s) (Proxy @v)+ in emitNode (exprIRType (Proxy @r)) (OpSwizzle vid idxs) b1++-- ---------------------------------------------------------------------------+-- Typed uniform handle ExprU u with OverloadedRecordDot field projection+-- ---------------------------------------------------------------------------++-- | Handle to a shader's uniform record @u@ inside an EDSL body. Carries the+-- starting flattened field index (0 for standalone shaders; offset for fused+-- shaders).+newtype ExprU u = ExprU Int++-- | Mapping from a single primitive Haskell uniform field type to its EDSL+-- expression type and 'GpuType'.+class GpuExpr r => UniformLeaf u r | u -> r where+ leafGpuType :: Proxy u -> GpuType++instance UniformLeaf Float Float where leafGpuType _ = GFloat+instance UniformLeaf Int32 Int32 where leafGpuType _ = GInt32+instance UniformLeaf Word32 Word32 where leafGpuType _ = GUInt32+instance UniformLeaf Bool Bool where leafGpuType _ = GBool+instance UniformLeaf V2 V2 where leafGpuType _ = GVec2+instance UniformLeaf V3 V3 where leafGpuType _ = GVec3+instance UniformLeaf V4 V4 where leafGpuType _ = GVec4+instance UniformLeaf Color V4 where leafGpuType _ = GVec4+instance UniformLeaf Rect V4 where leafGpuType _ = GVec4+instance UniformLeaf Size V2 where leafGpuType _ = GVec2++-- | Read a primitive uniform directly (for shaders parameterized by a single+-- @Float@, @Color@, @V2@, etc., rather than a record).+uVal :: forall u r. UniformLeaf u r => ExprU u -> Expr r+uVal (ExprU base) = Expr $ \_ b ->+ emitNode (exprIRType (Proxy @r)) (OpUniform base (leafGpuType (Proxy @u))) b++-- | Project the first component of a paired uniform handle.+uFst :: ExprU (a, b) -> ExprU a+uFst (ExprU base) = ExprU base++-- | Project the second component of a paired uniform handle.+uSnd :: forall a b. KnownNat (UniformLeafCount a) => ExprU (a, b) -> ExprU b+uSnd (ExprU base) = ExprU (base + fromIntegral (natVal (Proxy @(UniformLeafCount a))))++-- | Project the first component of a 3-tuple uniform handle.+uFst3 :: ExprU (a, b, c) -> ExprU a+uFst3 (ExprU base) = ExprU base++-- | Project the second component of a 3-tuple uniform handle.+uSnd3 :: forall a b c. KnownNat (UniformLeafCount a) => ExprU (a, b, c) -> ExprU b+uSnd3 (ExprU base) = ExprU (base + fromIntegral (natVal (Proxy @(UniformLeafCount a))))++-- | Project the third component of a 3-tuple uniform handle.+uThd3 ::+ forall a b c.+ (KnownNat (UniformLeafCount a), KnownNat (UniformLeafCount b)) =>+ ExprU (a, b, c) ->+ ExprU c+uThd3 (ExprU base) =+ ExprU+ ( base+ + fromIntegral (natVal (Proxy @(UniformLeafCount a)))+ + fromIntegral (natVal (Proxy @(UniformLeafCount b)))+ )++-- | Type-level count of flattened primitive uniform fields in @a@.+type family UniformLeafCount (a :: Type) :: Nat where+ UniformLeafCount () = 0+ UniformLeafCount Float = 1+ UniformLeafCount Int32 = 1+ UniformLeafCount Word32 = 1+ UniformLeafCount Bool = 1+ UniformLeafCount V2 = 1+ UniformLeafCount V3 = 1+ UniformLeafCount V4 = 1+ UniformLeafCount Color = 1+ UniformLeafCount Rect = 1+ UniformLeafCount Size = 1+ UniformLeafCount (a, b) = UniformLeafCount a + UniformLeafCount b+ UniformLeafCount (a, b, c) = UniformLeafCount a + UniformLeafCount b + UniformLeafCount c+ UniformLeafCount r = GFieldCount (Rep r)++type family GFieldCount (f :: Type -> Type) :: Nat where+ GFieldCount U1 = 0+ GFieldCount (D1 _ f) = GFieldCount f+ GFieldCount (C1 _ f) = GFieldCount f+ GFieldCount (S1 _ f) = GFieldCount f+ GFieldCount (f :*: g) = GFieldCount f + GFieldCount g+ GFieldCount (K1 _ a) = UniformLeafCount a++-- | Type-level lookup of record field @name@ inside @Rep u@, returning its+-- flattened field index and Haskell field type.+type family GLookupField (name :: Symbol) (f :: Type -> Type) (off :: Nat) :: Maybe (Nat, Type) where+ GLookupField name (D1 _ f) off = GLookupField name f off+ GLookupField name (C1 _ f) off = GLookupField name f off+ GLookupField name (S1 ('MetaSel ('Just name) _ _ _) (K1 _ a)) off = 'Just '(off, a)+ GLookupField _ (S1 _ _) _ = 'Nothing+ GLookupField name (f :*: g) off =+ AltMaybe (GLookupField name f off) (GLookupField name g (off + GFieldCount f))+ GLookupField _ U1 _ = 'Nothing++type family AltMaybe (a :: Maybe k) (b :: Maybe k) :: Maybe k where+ AltMaybe ('Just x) _ = 'Just x+ AltMaybe 'Nothing y = y++type family RequireField (u :: Type) (name :: Symbol) (m :: Maybe (Nat, Type)) :: (Nat, Type) where+ RequireField _ _ ('Just hit) = hit+ RequireField u name 'Nothing =+ TypeError+ ( 'Text "Uniform record "+ ':<>: 'ShowType u+ ':<>: 'Text " has no field '"+ ':<>: 'Text name+ ':<>: 'Text "'."+ )++type family IsUniformLeaf (a :: Type) :: Bool where+ IsUniformLeaf Float = 'True+ IsUniformLeaf Int32 = 'True+ IsUniformLeaf Word32 = 'True+ IsUniformLeaf Bool = 'True+ IsUniformLeaf V2 = 'True+ IsUniformLeaf V3 = 'True+ IsUniformLeaf V4 = 'True+ IsUniformLeaf Color = 'True+ IsUniformLeaf Rect = 'True+ IsUniformLeaf Size = 'True+ IsUniformLeaf _ = 'False++class ProjectUniform (isLeaf :: Bool) (fieldTy :: Type) (res :: Type) | isLeaf fieldTy -> res where+ projectUniform :: Proxy isLeaf -> Proxy fieldTy -> Int -> res++instance UniformLeaf fieldTy r => ProjectUniform 'True fieldTy (Expr r) where+ projectUniform _ _ fieldIdx = Expr $ \_ b ->+ emitNode (exprIRType (Proxy @r)) (OpUniform fieldIdx (leafGpuType (Proxy @fieldTy))) b++instance ProjectUniform 'False fieldTy (ExprU fieldTy) where+ projectUniform _ _ = ExprU++instance+ ( '(idx, fieldTy) ~ RequireField u name (GLookupField name (Rep u) 0)+ , KnownNat idx+ , isLeaf ~ IsUniformLeaf fieldTy+ , ProjectUniform isLeaf fieldTy res+ ) =>+ HasField name (ExprU u) res+ where+ getField (ExprU base) =+ projectUniform (Proxy @isLeaf) (Proxy @fieldTy) (base + fromIntegral (natVal (Proxy @idx)))++-- ---------------------------------------------------------------------------+-- Fragment context and input layer sampling+-- ---------------------------------------------------------------------------++-- | Built-in per-fragment inputs provided to every shader.+data FragCtx = FragCtx+ { uv :: !(Expr V2)+ -- ^ Normalized coordinates in @[0, 1] x [0, 1]@ over the node's layout rect+ -- (may extend outside @[0, 1]@ inside a 'NanoUI.LayerEffect' bleed margin).+ , pos :: !(Expr V2)+ -- ^ Local logical pixel coordinates relative to the node's top-left corner.+ , size :: !(Expr V2)+ -- ^ Node width and height in logical pixels.+ , origin :: !(Expr V2)+ -- ^ Node top-left origin in logical window pixels.+ , scale :: !(Expr Float)+ -- ^ Device pixels per logical layout unit.+ , cornerRadius :: !(Expr Float)+ -- ^ Corner radius in logical pixels from 'NanoUI.ShaderConfig'.+ , color :: !(Expr V4)+ -- ^ Vertex tint color.+ }++sysExpr :: forall a. GpuExpr a => SysField -> Expr a+sysExpr sf = Expr $ \_ b -> emitNode (exprIRType (Proxy @a)) (OpSys sf) b++-- | Construct the standard 'FragCtx' from the system uniform header and vertex+-- varyings.+mkFragCtx :: FragCtx+mkFragCtx =+ let rect = sysExpr @V4 SysRect+ uvRect = sysExpr @V4 SysUvRect+ meta = sysExpr @V4 SysMeta+ vUv = sysExpr @V2 SysVUv+ vCol = sysExpr @V4 SysVColor+ uvOrigin = swiz2 [0, 1] uvRect+ uvSpan = swiz2 [2, 3] uvRect+ nodeSize = swiz2 [2, 3] rect+ nodeOrigin = swiz2 [0, 1] rect+ localUv = (vUv - uvOrigin) / uvSpan+ localPos = localUv * nodeSize+ in FragCtx+ { uv = localUv+ , pos = localPos+ , size = nodeSize+ , origin = nodeOrigin+ , scale = swiz1 0 meta+ , cornerRadius = swiz1 1 meta+ , color = vCol+ }++swiz1 :: Int -> Expr v -> Expr Float+swiz1 i v = Expr $ \d b ->+ let (vid, b1) = runExpr d v b+ in emitNode TFloat (OpSwizzle vid [i]) b1++swiz2 :: [Int] -> Expr v -> Expr V2+swiz2 is v = Expr $ \d b ->+ let (vid, b1) = runExpr d v b+ in emitNode TVec2 (OpSwizzle vid is) b1++-- | Handle to the rendered offscreen subtree texture inside a 'NanoUI.LayerEffect'.+data Layer = Layer+ { layerUvOrigin :: !(Expr V2)+ , layerUvSpan :: !(Expr V2)+ , layerNodeSize :: !(Expr V2)+ }++-- | Construct the default 'Layer' handle backed by @uInput@.+mkLayer :: Layer+mkLayer =+ let rect = sysExpr @V4 SysRect+ uvRect = sysExpr @V4 SysUvRect+ in Layer+ { layerUvOrigin = swiz2 [0, 1] uvRect+ , layerUvSpan = swiz2 [2, 3] uvRect+ , layerNodeSize = swiz2 [2, 3] rect+ }++-- | Sample the offscreen subtree texture at local logical pixel coordinates+-- (where @(0, 0)@ is the node's top-left corner).+sampleLayer :: Layer -> Expr V2 -> Expr V4+sampleLayer l localPos =+ let normUv = localPos / maxE (vec2 1e-6 1e-6) (layerNodeSize l)+ in sampleLayerUv l normUv++-- | Sample the offscreen subtree texture at node-normalized UV coordinates.+sampleLayerUv :: Layer -> Expr V2 -> Expr V4+sampleLayerUv l normUv =+ let texUv = layerUvOrigin l + normUv * layerUvSpan l+ in Expr $ \d b ->+ let (uid, b1) = runExpr d texUv b+ in emitNode TVec4 (OpSampleInput uid) b1++-- ---------------------------------------------------------------------------+-- Literals and vector construction+-- ---------------------------------------------------------------------------++-- | Float literal expression.+floatE :: Float -> Expr Float+floatE x = Expr $ \_ b -> emitNode TFloat (OpLitFloat (castFloatToWord32 x)) b++-- | Signed 32-bit integer literal expression.+intE :: Int32 -> Expr Int32+intE n = Expr $ \_ b -> emitNode TInt (OpLitInt n) b++-- | Unsigned 32-bit integer literal expression.+uintE :: Word32 -> Expr Word32+uintE w = Expr $ \_ b -> emitNode TUInt (OpLitUInt w) b++-- | Boolean literal expression.+boolE :: Bool -> Expr Bool+boolE c = Expr $ \_ b -> emitNode TBool (OpLitBool c) b++-- | Lift a constant 'Color' to a straight-alpha @Expr V4@ in @[0, 1]@.+colorE :: Color -> Expr V4+colorE (Color w) =+ let inv = 1.0 / 255.0 :: Float+ r = fromIntegral ((w `shiftR` 24) .&. 0xFF) * inv+ g = fromIntegral ((w `shiftR` 16) .&. 0xFF) * inv+ b = fromIntegral ((w `shiftR` 8) .&. 0xFF) * inv+ a = fromIntegral (w .&. 0xFF) * inv+ in vec4 (floatE r) (floatE g) (floatE b) (floatE a)++-- | Lift a constant 'V2'.+v2E :: V2 -> Expr V2+v2E (V2 x y) = vec2 (floatE x) (floatE y)++-- | Lift a constant 'V3'.+v3E :: V3 -> Expr V3+v3E (V3 x y z) = vec3 (floatE x) (floatE y) (floatE z)++-- | Lift a constant 'V4'.+v4E :: V4 -> Expr V4+v4E (V4 x y z w) = vec4 (floatE x) (floatE y) (floatE z) (floatE w)++-- | Construct a 2-vector from two scalars.+vec2 :: Expr Float -> Expr Float -> Expr V2+vec2 x y = Expr $ \d b0 ->+ let (xid, b1) = runExpr d x b0+ (yid, b2) = runExpr d y b1+ in emitNode TVec2 (OpConstruct TVec2 [xid, yid]) b2++-- | Construct a 3-vector from three scalars.+vec3 :: Expr Float -> Expr Float -> Expr Float -> Expr V3+vec3 x y z = Expr $ \d b0 ->+ let (xid, b1) = runExpr d x b0+ (yid, b2) = runExpr d y b1+ (zid, b3) = runExpr d z b2+ in emitNode TVec3 (OpConstruct TVec3 [xid, yid, zid]) b3++-- | Construct a 4-vector from four scalars.+vec4 :: Expr Float -> Expr Float -> Expr Float -> Expr Float -> Expr V4+vec4 x y z w = Expr $ \d b0 ->+ let (xid, b1) = runExpr d x b0+ (yid, b2) = runExpr d y b1+ (zid, b3) = runExpr d z b2+ (wid, b4) = runExpr d w b3+ in emitNode TVec4 (OpConstruct TVec4 [xid, yid, zid, wid]) b4++-- | Construct a 3-vector from a @V2@ and a trailing scalar.+vec3_21 :: Expr V2 -> Expr Float -> Expr V3+vec3_21 xy z = vec3 (swiz1 0 xy) (swiz1 1 xy) z++-- | Construct a 4-vector from two @V2@s.+vec4_22 :: Expr V2 -> Expr V2 -> Expr V4+vec4_22 xy zw = vec4 (swiz1 0 xy) (swiz1 1 xy) (swiz1 0 zw) (swiz1 1 zw)++-- | Construct a 4-vector from a @V3@ and a trailing scalar.+vec4_31 :: Expr V3 -> Expr Float -> Expr V4+vec4_31 rgb a = vec4 (swiz1 0 rgb) (swiz1 1 rgb) (swiz1 2 rgb) a++-- | Construct an RGBA color from RGB @V3@ and alpha.+rgba :: Expr V3 -> Expr Float -> Expr V4+rgba = vec4_31++-- | Broadcast a scalar across a @V2@.+splat2 :: Expr Float -> Expr V2+splat2 x = vec2 x x++-- | Broadcast a scalar across a @V3@.+splat3 :: Expr Float -> Expr V3+splat3 x = vec3 x x x++-- | Broadcast a scalar across a @V4@.+splat4 :: Expr Float -> Expr V4+splat4 x = vec4 x x x x++-- | Truncate a float expression to signed 32-bit integer.+floatToInt :: Expr Float -> Expr Int32+floatToInt = unOpE UFloatToInt++-- | Convert a signed 32-bit integer expression to float.+intToFloat :: Expr Int32 -> Expr Float+intToFloat = unOpE UIntToFloat++-- ---------------------------------------------------------------------------+-- Numeric instances and math operations+-- ---------------------------------------------------------------------------++unOpE :: forall a b. GpuExpr b => UnOp -> Expr a -> Expr b+unOpE op x = Expr $ \d b0 ->+ let (xid, b1) = runExpr d x b0+ in emitNode (exprIRType (Proxy @b)) (OpUnary op xid) b1++binOpE :: forall a b c. GpuExpr c => BinOp -> Expr a -> Expr b -> Expr c+binOpE op x y = Expr $ \d b0 ->+ let (xid, b1) = runExpr d x b0+ (yid, b2) = runExpr d y b1+ in emitNode (exprIRType (Proxy @c)) (OpBinary op xid yid) b2++triOpE :: forall a b c r. GpuExpr r => TriOp -> Expr a -> Expr b -> Expr c -> Expr r+triOpE op x y z = Expr $ \d b0 ->+ let (xid, b1) = runExpr d x b0+ (yid, b2) = runExpr d y b1+ (zid, b3) = runExpr d z b2+ in emitNode (exprIRType (Proxy @r)) (OpTernary op xid yid zid) b3++infixl 7 *^, ^*, /^+infixl 6 +^, -^++-- | Multiply a vector expression by a scalar float expression.+(*^) :: GpuVec v => Expr v -> Expr Float -> Expr v+(*^) = binOpE BMul++-- | Multiply a scalar float expression by a vector expression.+(^*) :: GpuVec v => Expr Float -> Expr v -> Expr v+(^*) = binOpE BMul++-- | Divide a vector expression by a scalar float expression.+(/^) :: GpuVec v => Expr v -> Expr Float -> Expr v+(/^) = binOpE BDiv++-- | Add a scalar float expression to every component of a vector expression.+(+^) :: GpuVec v => Expr v -> Expr Float -> Expr v+(+^) = binOpE BAdd++-- | Subtract a scalar float expression from every component of a vector expression.+(-^) :: GpuVec v => Expr v -> Expr Float -> Expr v+(-^) = binOpE BSub++instance Num (Expr Float) where+ (+) = binOpE BAdd+ (-) = binOpE BSub+ (*) = binOpE BMul+ negate = unOpE UNeg+ abs = unOpE UAbs+ signum = unOpE USign+ fromInteger = floatE . fromInteger++instance Fractional (Expr Float) where+ (/) = binOpE BDiv+ fromRational = floatE . fromRational++instance Floating (Expr Float) where+ pi = floatE pi+ exp = unOpE UExp+ log = unOpE ULog+ sqrt = unOpE USqrt+ (**) = binOpE BPow+ sin = unOpE USin+ cos = unOpE UCos+ tan = unOpE UTan+ asin x = atan2E x (sqrt (maxE (floatE 0) (1 - x * x)))+ acos x = floatE (pi / 2) - asin x+ atan x = atan2E x 1+ sinh x = (exp x - exp (negate x)) * 0.5+ cosh x = (exp x + exp (negate x)) * 0.5+ asinh x = log (x + sqrt (x * x + 1))+ acosh x = log (x + sqrt (x * x - 1))+ atanh x = 0.5 * log ((1 + x) / (1 - x))++instance Num (Expr Int32) where+ (+) = binOpE BAdd+ (-) = binOpE BSub+ (*) = binOpE BMul+ negate = unOpE UNeg+ abs = unOpE UAbs+ signum = unOpE USign+ fromInteger = intE . fromInteger++instance Num (Expr Word32) where+ (+) = binOpE BAdd+ (-) = binOpE BSub+ (*) = binOpE BMul+ negate = unOpE UNeg+ abs = id+ signum u = selectE (u .== uintE 0) (uintE 0) (uintE 1)+ fromInteger = uintE . fromInteger++instance Num (Expr V2) where+ (+) = binOpE BAdd+ (-) = binOpE BSub+ (*) = binOpE BMul+ negate = unOpE UNeg+ abs = unOpE UAbs+ signum = unOpE USign+ fromInteger = splat2 . floatE . fromInteger++instance Fractional (Expr V2) where+ (/) = binOpE BDiv+ fromRational = splat2 . floatE . fromRational++instance Num (Expr V3) where+ (+) = binOpE BAdd+ (-) = binOpE BSub+ (*) = binOpE BMul+ negate = unOpE UNeg+ abs = unOpE UAbs+ signum = unOpE USign+ fromInteger = splat3 . floatE . fromInteger++instance Fractional (Expr V3) where+ (/) = binOpE BDiv+ fromRational = splat3 . floatE . fromRational++instance Num (Expr V4) where+ (+) = binOpE BAdd+ (-) = binOpE BSub+ (*) = binOpE BMul+ negate = unOpE UNeg+ abs = unOpE UAbs+ signum = unOpE USign+ fromInteger = splat4 . floatE . fromInteger++instance Fractional (Expr V4) where+ (/) = binOpE BDiv+ fromRational = splat4 . floatE . fromRational++-- | Componentwise absolute value.+absE :: GpuSigned a => Expr a -> Expr a+absE = unOpE UAbs++-- | Componentwise sign (@-1@, @0@, or @1@).+signE :: GpuSigned a => Expr a -> Expr a+signE = unOpE USign++-- | Componentwise floor.+floorE :: GpuFloat a => Expr a -> Expr a+floorE = unOpE UFloor++-- | Componentwise ceil.+ceilE :: GpuFloat a => Expr a -> Expr a+ceilE = unOpE UCeil++-- | Componentwise fractional part (@x - floor x@).+fractE :: GpuFloat a => Expr a -> Expr a+fractE = unOpE UFract++-- | Floating-point modulo (@x - y * floor(x / y)@).+modE :: GpuFloat a => Expr a -> Expr a -> Expr a+modE = binOpE BMod++-- | Componentwise minimum.+minE :: GpuMinMax a => Expr a -> Expr a -> Expr a+minE = binOpE BMin++-- | Componentwise maximum.+maxE :: GpuMinMax a => Expr a -> Expr a -> Expr a+maxE = binOpE BMax++-- | Componentwise clamp to @[lo, hi]@.+clampE :: GpuMinMax a => Expr a -> Expr a -> Expr a -> Expr a+clampE x lo hi = triOpE TClamp x lo hi++-- | Clamp a float expression to @[0, 1]@.+clamp01E :: Expr Float -> Expr Float+clamp01E x = clampE x 0 1++-- | Linear interpolation @a * (1 - t) + b * t@.+mix :: GpuFloat a => Expr a -> Expr a -> Expr Float -> Expr a+mix = triOpE TMix++-- | Step function @stepE edge x@: @0@ when @x < edge@, else @1@.+stepE :: Expr Float -> Expr Float -> Expr Float+stepE = binOpE BStep++-- | Smooth Hermite interpolation between @edge0@ and @edge1@.+smoothstep :: Expr Float -> Expr Float -> Expr Float -> Expr Float+smoothstep = triOpE TSmoothstep++-- | Componentwise exponentiation.+powE :: GpuFloat a => Expr a -> Expr a -> Expr a+powE = binOpE BPow++-- | Two-argument arctangent @atan2 y x@.+atan2E :: Expr Float -> Expr Float -> Expr Float+atan2E = binOpE BAtan2++-- | Vector dot product.+dot :: forall a. GpuVec a => Expr a -> Expr a -> Expr Float+dot a b =+ let !_ = exprIRType (Proxy @a)+ in binOpE BDot a b++-- | 3D vector cross product.+cross :: Expr V3 -> Expr V3 -> Expr V3+cross = binOpE BCross++-- | Euclidean vector length.+vLength :: forall a. GpuVec a => Expr a -> Expr Float+vLength v =+ let !_ = exprIRType (Proxy @a)+ in Expr $ \d b0 ->+ let (vid, b1) = runExpr d v b0+ in emitNode TFloat (OpLength vid) b1++-- | Euclidean distance between two vectors.+vDistance :: (GpuVec a, Num (Expr a)) => Expr a -> Expr a -> Expr Float+vDistance a b = vLength (a - b)++-- | Unit-length vector in the direction of @v@.+normalize :: forall a. GpuVec a => Expr a -> Expr a+normalize v = Expr $ \d b0 ->+ let (vid, b1) = runExpr d v b0+ in emitNode (exprIRType (Proxy @a)) (OpNormalize vid) b1++-- ---------------------------------------------------------------------------+-- Comparisons and branchless selection+-- ---------------------------------------------------------------------------++infix 4 .<, .<=, .>, .>=, .==, ./=+infixr 3 .&&+infixr 2 .||++ordOp :: forall a. GpuOrd a => BinOp -> Expr a -> Expr a -> Expr Bool+ordOp op a b =+ let !_ = exprIRType (Proxy @a)+ in binOpE op a b++eqOp :: forall a. GpuEq a => BinOp -> Expr a -> Expr a -> Expr Bool+eqOp op a b =+ let !_ = exprIRType (Proxy @a)+ in binOpE op a b++-- | Less-than comparison.+(.<) :: GpuOrd a => Expr a -> Expr a -> Expr Bool+(.<) = ordOp BLt++-- | Less-than-or-equal comparison.+(.<=) :: GpuOrd a => Expr a -> Expr a -> Expr Bool+(.<=) = ordOp BLe++-- | Greater-than comparison.+(.>) :: GpuOrd a => Expr a -> Expr a -> Expr Bool+(.>) = ordOp BGt++-- | Greater-than-or-equal comparison.+(.>=) :: GpuOrd a => Expr a -> Expr a -> Expr Bool+(.>=) = ordOp BGe++-- | Equality comparison.+(.==) :: GpuEq a => Expr a -> Expr a -> Expr Bool+(.==) = eqOp BEq++-- | Inequality comparison.+(./=) :: GpuEq a => Expr a -> Expr a -> Expr Bool+(./=) = eqOp BNeq++-- | Logical conjunction.+(.&&) :: Expr Bool -> Expr Bool -> Expr Bool+(.&&) = binOpE BAnd++-- | Logical disjunction.+(.||) :: Expr Bool -> Expr Bool -> Expr Bool+(.||) = binOpE BOr++-- | Logical negation.+notE :: Expr Bool -> Expr Bool+notE = unOpE UNot++-- | Branchless conditional selection: @selectE cond whenTrue whenFalse@.+selectE :: GpuExpr a => Expr Bool -> Expr a -> Expr a -> Expr a+selectE = triOpE TSelect++-- ---------------------------------------------------------------------------+-- Common 2D SDF, color, and noise helpers+-- ---------------------------------------------------------------------------++-- | Signed distance from point @p@ to a circle of radius @r@ centered at 0.+sdCircle :: Expr V2 -> Expr Float -> Expr Float+sdCircle p r = vLength p - r++-- | Signed distance from point @p@ (centered at 0) to a rounded box of+-- half-extents @halfSize@ and corner radius @r@.+sdRoundedBox :: Expr V2 -> Expr V2 -> Expr Float -> Expr Float+sdRoundedBox p halfSize r =+ let q = absE p - halfSize + splat2 r+ outside = vLength (maxE q (vec2 0 0))+ inside = minE (maxE (swiz1 0 q) (swiz1 1 q)) 0+ in outside + inside - r++-- | Rec.709 perceptual luminance of an RGBA color.+luminanceE :: Expr V4 -> Expr Float+luminanceE col =+ let rgb = vec3 (swiz1 0 col) (swiz1 1 col) (swiz1 2 col)+ in dot rgb (vec3 0.2126 0.7152 0.0722)++-- | Replace a color's alpha channel.+withAlphaE :: Expr Float -> Expr V4 -> Expr V4+withAlphaE a col = vec4 (swiz1 0 col) (swiz1 1 col) (swiz1 2 col) a++-- | Convert HSV @(h in [0,1], s in [0,1], v in [0,1])@ to RGB @V3@.+hsvToRgbE :: Expr Float -> Expr Float -> Expr Float -> Expr V3+hsvToRgbE h s v =+ let k = vec3 1.0 (2.0 / 3.0) (1.0 / 3.0)+ p = absE (fractE (splat3 h + k) * 6.0 - splat3 3.0)+ clamped = clampE (p - splat3 1.0) (splat3 0) (splat3 1)+ in splat3 v * mix (splat3 1) clamped s++-- | Fast deterministic 2D-to-1D hash in @[0, 1)@.+hash21 :: Expr V2 -> Expr Float+hash21 p =+ let p1 = fractE (p * vec2 123.34 456.21)+ p2 = p1 + splat2 (dot p1 (p1 + vec2 45.32 45.32))+ in fractE (swiz1 0 p2 * swiz1 1 p2)++-- | Smooth 2D value noise in @[0, 1]@.+valueNoise2D :: Expr V2 -> Expr Float+valueNoise2D p =+ let i = floorE p+ f = fractE p+ u = f * f * (vec2 3 3 - f * vec2 2 2)+ a = hash21 i+ b = hash21 (i + vec2 1 0)+ c = hash21 (i + vec2 0 1)+ d = hash21 (i + vec2 1 1)+ ux = swiz1 0 u+ uy = swiz1 1 u+ in mix (mix a b ux) (mix c d ux) uy
+ lib/NanoUI/Shader/Internal/Emit/CLike.hs view
@@ -0,0 +1,219 @@+{-# LANGUAGE StrictData #-}++-- | Shared C-like statement, loop, and expression emitter parameterized by a+-- small 'CLikeDialect' for GLSL 150, GLSL ES 300, and Metal Shading Language.+module NanoUI.Shader.Internal.Emit.CLike+ ( CLikeDialect (..)+ , emitCLikeNodes+ , nodeVar+ , intB+ ) where++import Data.Int (Int32)+import Data.Text qualified as T+import Data.Text.Lazy.Builder (Builder)+import Data.Text.Lazy.Builder qualified as TB+import Data.Vector qualified as V+import Data.Word (Word32)+import GHC.Float (castWord32ToFloat)+import NanoUI.Internal.Uniforms (GpuType)+import NanoUI.Shader.Internal.IR+import Numeric (showFFloat)++-- | Dialect differences between GLSL and MSL fragment shaders.+data CLikeDialect = CLikeDialect+ { cdType :: IRType -> Builder+ , cdSysField :: SysField -> Builder+ , cdUniform :: Int -> GpuType -> Builder+ , cdMod :: Builder -> Builder -> Builder+ , cdAtan2 :: Builder -> Builder -> Builder+ , cdSampleInput :: Builder -> Builder+ }++-- | Emit a topologically ordered SSA block at nesting @depth@.+emitCLikeNodes :: CLikeDialect -> Int -> V.Vector (IRType, ExprOp) -> Builder+emitCLikeNodes d depth =+ V.ifoldl' (\acc i (ty, op) -> acc <> emitStmt d depth i ty op) mempty++emitStmt :: CLikeDialect -> Int -> Int -> IRType -> ExprOp -> Builder+emitStmt d depth idx ty op = case op of+ OpLoop lb -> emitLoopStmt d depth idx lb+ _ ->+ indent depth+ <> cdType d ty+ <> " "+ <> nodeVar depth (NodeId idx)+ <> " = "+ <> emitExpr d depth ty op+ <> ";\n"++emitLoopStmt :: CLikeDialect -> Int -> Int -> LoopBody -> Builder+emitLoopStmt d depth idx lb =+ let lid = lbLoopId lb+ ind = indent depth+ initDecls =+ mconcat+ [ ind+ <> cdType d t+ <> " "+ <> loopStateVar lid slot+ <> " = "+ <> nodeVar depth initId+ <> ";\n"+ | (slot, (t, initId)) <- zip [0 :: Int ..] (zip (lbStateTypes lb) (lbInits lb))+ ]+ innerDepth = depth + 1+ indIn = indent innerDepth+ iv = loopIdxVar lid+ bodyStmts = emitCLikeNodes d innerDepth (lbBodyNodes lb)+ updates =+ mconcat+ [ indIn+ <> loopStateVar lid slot+ <> " = "+ <> nodeVar innerDepth nextId+ <> ";\n"+ | (slot, nextId) <- zip [0 :: Int ..] (lbNextStates lb)+ ]+ aliasDecls =+ mconcat+ [ ind+ <> cdType d t+ <> " "+ <> loopOutVar depth idx slot+ <> " = "+ <> loopStateVar lid slot+ <> ";\n"+ | (slot, t) <- zip [0 :: Int ..] (lbStateTypes lb)+ ]+ in initDecls+ <> ind+ <> "for (int "+ <> iv+ <> " = "+ <> int32B (lbStart lb)+ <> "; "+ <> iv+ <> " < "+ <> int32B (lbEnd lb)+ <> "; "+ <> iv+ <> "++) {\n"+ <> bodyStmts+ <> updates+ <> ind+ <> "}\n"+ <> aliasDecls++emitExpr :: CLikeDialect -> Int -> IRType -> ExprOp -> Builder+emitExpr d depth ty op =+ let ref = nodeVar depth+ call1 fn a = fn <> "(" <> ref a <> ")"+ call2 fn a b = fn <> "(" <> ref a <> ", " <> ref b <> ")"+ call3 fn a b c = fn <> "(" <> ref a <> ", " <> ref b <> ", " <> ref c <> ")"+ infix2 sym a b = "(" <> ref a <> sym <> ref b <> ")"+ in case op of+ OpLitFloat bits -> floatB (castWord32ToFloat bits)+ OpLitInt n -> int32B n+ OpLitUInt w -> word32B w <> "u"+ OpLitBool b -> if b then "true" else "false"+ OpSys sf -> cdSysField d sf+ OpUniform i gt -> cdUniform d i gt+ OpConstruct ct args -> cdType d ct <> "(" <> sepComma (map ref args) <> ")"+ OpSwizzle v idxs -> ref v <> "." <> mconcat (map compChar idxs)+ OpUnary uop a -> case uop of+ UNeg -> "(-" <> ref a <> ")"+ UNot -> "(!" <> ref a <> ")"+ UAbs -> call1 "abs" a+ UFloor -> call1 "floor" a+ UCeil -> call1 "ceil" a+ UFract -> call1 "fract" a+ USqrt -> call1 "sqrt" a+ USin -> call1 "sin" a+ UCos -> call1 "cos" a+ UTan -> call1 "tan" a+ UExp -> call1 "exp" a+ ULog -> call1 "log" a+ ULog2 -> call1 "log2" a+ USign -> call1 "sign" a+ UFloatToInt -> call1 "int" a+ UIntToFloat -> call1 "float" a+ OpBinary bop a b -> case bop of+ BAdd -> infix2 " + " a b+ BSub -> infix2 " - " a b+ BMul -> infix2 " * " a b+ BDiv -> infix2 " / " a b+ BMod -> cdMod d (ref a) (ref b)+ BMin -> call2 "min" a b+ BMax -> call2 "max" a b+ BPow -> call2 "pow" a b+ BAtan2 -> cdAtan2 d (ref a) (ref b)+ BStep -> call2 "step" a b+ BEq -> infix2 " == " a b+ BNeq -> infix2 " != " a b+ BLt -> infix2 " < " a b+ BLe -> infix2 " <= " a b+ BGt -> infix2 " > " a b+ BGe -> infix2 " >= " a b+ BAnd -> infix2 " && " a b+ BOr -> infix2 " || " a b+ BDot -> call2 "dot" a b+ BCross -> call2 "cross" a b+ OpTernary top a b c -> case top of+ TMix -> call3 "mix" a b c+ TClamp -> call3 "clamp" a b c+ TSmoothstep -> call3 "smoothstep" a b c+ TSelect -> "(" <> ref a <> " ? " <> ref b <> " : " <> ref c <> ")"+ OpLength a -> call1 "length" a+ OpNormalize a -> call1 "normalize" a+ OpSampleInput uv -> cdSampleInput d (ref uv)+ OpOuterRef outerD nid -> nodeVar outerD nid+ OpLoopVar lid -> loopIdxVar lid+ OpLoopState lid slot -> loopStateVar lid slot+ OpLoop _ -> cdType d ty <> "(0)"+ OpLoopResult (NodeId lidx) slot -> loopOutVar depth lidx slot++-- | Local variable name for an SSA 'NodeId' at loop nesting @depth@.+nodeVar :: Int -> NodeId -> Builder+nodeVar depth (NodeId i) = "v" <> intB depth <> "_" <> intB i++loopIdxVar :: Int -> Builder+loopIdxVar lid = "i_" <> intB lid++loopStateVar :: Int -> Int -> Builder+loopStateVar lid slot = "ls_" <> intB lid <> "_" <> intB slot++loopOutVar :: Int -> Int -> Int -> Builder+loopOutVar depth lidx slot = "lo" <> intB depth <> "_" <> intB lidx <> "_" <> intB slot++compChar :: Int -> Builder+compChar 0 = "x"+compChar 1 = "y"+compChar 2 = "z"+compChar _ = "w"++indent :: Int -> Builder+indent d = TB.fromText (T.replicate (2 * (d + 1)) " ")++sepComma :: [Builder] -> Builder+sepComma [] = mempty+sepComma [x] = x+sepComma (x : xs) = x <> ", " <> sepComma xs++-- | Render an 'Int' to a 'Builder'.+intB :: Int -> Builder+intB = TB.fromString . show++int32B :: Int32 -> Builder+int32B = TB.fromString . show++word32B :: Word32 -> Builder+word32B = TB.fromString . show++floatB :: Float -> Builder+floatB f+ | isNaN f = "0.0"+ | isInfinite f = if f > 0 then "1e38" else "-1e38"+ | otherwise =+ let s = showFFloat Nothing f ""+ in TB.fromString (if '.' `elem` s || 'e' `elem` s || 'E' `elem` s then s else s ++ ".0")
+ lib/NanoUI/Shader/Internal/Emit/Glsl.hs view
@@ -0,0 +1,119 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Pure-Haskell GLSL 150 (OpenGL 3.2, @nano-ui-rgfw@) and GLSL ES 300+-- (WebGL2, @nano-ui-sdl-web@) fragment shader emitters for 'ShaderIR'.+module NanoUI.Shader.Internal.Emit.Glsl+ ( GlslTarget (..)+ , emitGlsl+ , emitGlsl150+ , emitGlslEs300+ ) where++import Data.Text (Text)+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder (Builder)+import Data.Text.Lazy.Builder qualified as TB+import NanoUI.Internal.Uniforms (GpuType (..), UniformField (..))+import NanoUI.Shader.Internal.Emit.CLike (CLikeDialect (..), emitCLikeNodes, intB, nodeVar)+import NanoUI.Shader.Internal.IR++-- | GLSL dialect target.+data GlslTarget+ = Glsl150+ -- ^ OpenGL 3.2 core (@#version 150@, varying @vUV@).+ | GlslEs300+ -- ^ WebGL2 (@#version 300 es@, @precision highp float;@, varying @vUv@).+ deriving (Eq, Show)++-- | Emit an OpenGL 3.2 core GLSL 150 fragment shader from 'ShaderIR'.+emitGlsl150 :: ShaderIR -> Text+emitGlsl150 = emitGlsl Glsl150++-- | Emit a WebGL2 GLSL ES 300 fragment shader from 'ShaderIR'.+emitGlslEs300 :: ShaderIR -> Text+emitGlslEs300 = emitGlsl GlslEs300++-- | Emit GLSL source text for @target@ from 'ShaderIR'.+emitGlsl :: GlslTarget -> ShaderIR -> Text+emitGlsl target ir = TL.toStrict . TB.toLazyText $ mconcat+ [ header+ , uniformBlock (irUniforms ir)+ , if irNeedsInput ir+ then+ "uniform sampler2D uInput;\n"+ <> "vec4 nanoSampleInput(vec2 uv) {\n"+ <> " vec4 s = texture(uInput, uv);\n"+ <> " return vec4(min(s.rgb / max(s.a, 1e-5), vec3(1.0)), s.a);\n"+ <> "}\n"+ else ""+ , "void main() {\n"+ , emitCLikeNodes (glslDialect target) 0 (irNodes ir)+ , " fragColor = " <> nodeVar 0 (irOutput ir) <> ";\n"+ , "}\n"+ ]+ where+ header = case target of+ Glsl150 ->+ "#version 150\n"+ <> "in vec4 vColor;\n"+ <> "in vec2 vUV;\n"+ <> "out vec4 fragColor;\n"+ GlslEs300 ->+ "#version 300 es\n"+ <> "precision highp float;\n"+ <> "in vec4 vColor;\n"+ <> "in vec2 vUv;\n"+ <> "out vec4 fragColor;\n"++glslDialect :: GlslTarget -> CLikeDialect+glslDialect target =+ CLikeDialect+ { cdType = glslType+ , cdSysField = \case+ SysRect -> "uRect"+ SysUvRect -> "uUvRect"+ SysMeta -> "uMeta"+ SysVColor -> "vColor"+ SysVUv -> case target of+ Glsl150 -> "vUV"+ GlslEs300 -> "vUv"+ , cdUniform = \i gt -> case gt of+ GBool -> "(u_" <> intB i <> " != 0)"+ _ -> "u_" <> intB i+ , cdMod = \a b -> "mod(" <> a <> ", " <> b <> ")"+ , cdAtan2 = \a b -> "atan(" <> a <> ", " <> b <> ")"+ , cdSampleInput = \uv -> "nanoSampleInput(" <> uv <> ")"+ }++uniformBlock :: [UniformField] -> Builder+uniformBlock fields =+ "layout(std140) uniform NanoShaderBlock {\n"+ <> " vec4 uRect;\n"+ <> " vec4 uUvRect;\n"+ <> " vec4 uMeta;\n"+ <> mconcat (zipWith emitField [0 :: Int ..] fields)+ <> "};\n"+ where+ emitField i uf =+ " " <> glslUniformType (ufType uf) <> " u_" <> intB i <> ";\n"++glslUniformType :: GpuType -> Builder+glslUniformType gt = case gt of+ GFloat -> "float"+ GInt32 -> "int"+ GUInt32 -> "uint"+ GBool -> "int"+ GVec2 -> "vec2"+ GVec3 -> "vec3"+ GVec4 -> "vec4"++glslType :: IRType -> Builder+glslType ty = case ty of+ TFloat -> "float"+ TInt -> "int"+ TUInt -> "uint"+ TBool -> "bool"+ TVec2 -> "vec2"+ TVec3 -> "vec3"+ TVec4 -> "vec4"
+ lib/NanoUI/Shader/Internal/Emit/Msl.hs view
@@ -0,0 +1,118 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Pure-Haskell Metal Shading Language (MSL) fragment shader emitter for+-- 'ShaderIR', matching SDL 3.4's @SDL_GPURenderState@ Metal interface.+--+-- User uniform fields are emitted with explicit @float _padN@ spacers and+-- @packed_float3@ for @GVec3@ so every field's byte offset matches the core's+-- std140 byte layout exactly.+module NanoUI.Shader.Internal.Emit.Msl+ ( emitMsl+ ) where++import Data.Text (Text)+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder (Builder)+import Data.Text.Lazy.Builder qualified as TB+import NanoUI.Internal.Uniforms (GpuType (..), UniformField (..), gpuTypeSize)+import NanoUI.Shader.Internal.Emit.CLike (CLikeDialect (..), emitCLikeNodes, intB, nodeVar)+import NanoUI.Shader.Internal.IR++-- | Emit an MSL fragment shader with entrypoint @main0@ for SDL 3.4 Metal.+emitMsl :: ShaderIR -> Text+emitMsl ir = TL.toStrict . TB.toLazyText $ mconcat+ [ "#include <metal_stdlib>\n"+ , "using namespace metal;\n"+ , "struct FragIn {\n"+ , " float4 v_color [[user(locn0)]];\n"+ , " float2 v_uv [[user(locn1)]];\n"+ , "};\n"+ , mslUniformStruct (irUniforms ir) (irUniformBytes ir)+ , if irNeedsInput ir+ then+ "inline float4 nanoSampleInput(texture2d<float> tex, sampler samp, float2 uv) {\n"+ <> " float4 s = tex.sample(samp, uv);\n"+ <> " return float4(min(s.rgb / max(s.a, 1e-5f), float3(1.0f)), s.a);\n"+ <> "}\n"+ else ""+ , "fragment float4 main0(\n"+ , " FragIn in [[stage_in]],\n"+ , " constant NanoShaderBlock& u [[buffer(0)]]"+ , if irNeedsInput ir+ then ",\n texture2d<float> uInput [[texture(0)]],\n sampler uSampler [[sampler(0)]]\n"+ else "\n"+ , ") {\n"+ , emitCLikeNodes mslDialect 0 (irNodes ir)+ , " return " <> nodeVar 0 (irOutput ir) <> ";\n"+ , "}\n"+ ]++mslDialect :: CLikeDialect+mslDialect =+ CLikeDialect+ { cdType = mslType+ , cdSysField = \case+ SysRect -> "u.uRect"+ SysUvRect -> "u.uUvRect"+ SysMeta -> "u.uMeta"+ SysVColor -> "in.v_color"+ SysVUv -> "in.v_uv"+ , cdUniform = \i gt -> case gt of+ GBool -> "(u.u_" <> intB i <> " != 0)"+ GVec3 -> "float3(u.u_" <> intB i <> ")"+ _ -> "u.u_" <> intB i+ , cdMod = \a b -> "(" <> a <> " - " <> b <> " * floor(" <> a <> " / " <> b <> "))"+ , cdAtan2 = \a b -> "atan2(" <> a <> ", " <> b <> ")"+ , cdSampleInput = \uv -> "nanoSampleInput(uInput, uSampler, " <> uv <> ")"+ }++-- | Emit @NanoShaderBlock@ with explicit 4-byte padding fields so every user+-- uniform lands at its exact std140 byte offset.+mslUniformStruct :: [UniformField] -> Int -> Builder+mslUniformStruct fields totalUserBytes =+ "struct NanoShaderBlock {\n"+ <> " float4 uRect;\n"+ <> " float4 uUvRect;\n"+ <> " float4 uMeta;\n"+ <> go 0 0 fields+ <> "};\n"+ where+ go :: Int -> Int -> [UniformField] -> Builder+ go !cursor !idx [] = padTo cursor totalUserBytes idx+ go !cursor !idx (uf : rest) =+ let target = ufOffset uf+ pads = padTo cursor target idx+ decl = " " <> mslUniformType (ufType uf) <> " u_" <> intB idx <> ";\n"+ nextCur = target + gpuTypeSize (ufType uf)+ in pads <> decl <> go nextCur (idx + 1) rest++ padTo :: Int -> Int -> Int -> Builder+ padTo cur end tag+ | cur >= end = mempty+ | otherwise =+ let wordsN = (end - cur) `quot` 4+ in mconcat+ [ " float _pad_" <> intB tag <> "_" <> intB k <> ";\n"+ | k <- [0 .. wordsN - 1]+ ]++mslUniformType :: GpuType -> Builder+mslUniformType gt = case gt of+ GFloat -> "float"+ GInt32 -> "int"+ GUInt32 -> "uint"+ GBool -> "int"+ GVec2 -> "float2"+ GVec3 -> "packed_float3"+ GVec4 -> "float4"++mslType :: IRType -> Builder+mslType ty = case ty of+ TFloat -> "float"+ TInt -> "int"+ TUInt -> "uint"+ TBool -> "bool"+ TVec2 -> "float2"+ TVec3 -> "float3"+ TVec4 -> "float4"
+ lib/NanoUI/Shader/Internal/Emit/Spirv.hs view
@@ -0,0 +1,671 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Pure-Haskell SPIR-V 1.0 binary fragment shader emitter for 'ShaderIR',+-- matching SDL 3.4's @SDL_GPURenderState@ Vulkan interface:+--+-- * Fragment inputs: @location 0@ (@vec4 v_color@), @location 1@ (@vec2 v_uv@)+-- * Fragment output: @location 0@ (@vec4 fragColor@)+-- * Sampled input texture (when 'irNeedsInput'): @DescriptorSet 2, Binding 0@+-- * Std140 uniform block: @DescriptorSet 3, Binding 0@+-- * Entry point: @"main"@ with @OriginUpperLeft@+module NanoUI.Shader.Internal.Emit.Spirv+ ( emitSpirv+ , emitSpirvWords+ ) where++import Data.Bits (shiftL, (.|.))+import Data.ByteString (ByteString)+import Data.ByteString.Builder qualified as BSB+import Data.ByteString.Lazy qualified as BSL+import Data.Int (Int32)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Vector (Vector)+import Data.Vector qualified as V+import Data.Word (Word32, Word8)+import GHC.Float (castFloatToWord32)+import NanoUI.Internal.Uniforms (GpuType (..), UniformField (..))+import NanoUI.Shader.Internal.IR++-- ---------------------------------------------------------------------------+-- SPIR-V 1.0 and GLSL.std.450 constants (Khronos specification)++spvMagic, spvVersion10 :: Word32+spvMagic = 0x07230203+spvVersion10 = 0x00010000++-- Core opcodes+opExtInstImport, opExtInst, opMemoryModel, opEntryPoint, opExecutionMode, opCapability :: Word32+(opExtInstImport, opExtInst, opMemoryModel, opEntryPoint, opExecutionMode, opCapability) = (11, 12, 14, 15, 16, 17)++opTypeVoid, opTypeBool, opTypeInt, opTypeFloat, opTypeVector, opTypeImage, opTypeSampledImage, opTypeStruct, opTypePointer, opTypeFunction :: Word32+(opTypeVoid, opTypeBool, opTypeInt, opTypeFloat, opTypeVector, opTypeImage, opTypeSampledImage, opTypeStruct, opTypePointer, opTypeFunction) = (19, 20, 21, 22, 23, 25, 27, 30, 32, 33)++opConstantTrue, opConstantFalse, opConstant, opFunction, opFunctionEnd, opVariable, opLoad, opStore, opAccessChain, opDecorate, opMemberDecorate :: Word32+(opConstantTrue, opConstantFalse, opConstant, opFunction, opFunctionEnd, opVariable, opLoad, opStore, opAccessChain, opDecorate, opMemberDecorate) = (41, 42, 43, 54, 56, 59, 61, 62, 65, 71, 72)++opVectorShuffle, opCompositeConstruct, opCompositeExtract, opImageSampleImplicitLod, opConvertFToS, opConvertSToF :: Word32+(opVectorShuffle, opCompositeConstruct, opCompositeExtract, opImageSampleImplicitLod, opConvertFToS, opConvertSToF) = (79, 80, 81, 87, 110, 111)++opSNegate, opFNegate, opIAdd, opFAdd, opISub, opFSub, opIMul, opFMul, opUDiv, opSDiv, opFDiv, opFMod, opDot :: Word32+(opSNegate, opFNegate, opIAdd, opFAdd, opISub, opFSub, opIMul, opFMul, opUDiv, opSDiv, opFDiv, opFMod, opDot) = (126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 141, 148)++opLogicalEqual, opLogicalNotEqual, opLogicalOr, opLogicalAnd, opLogicalNot, opSelect :: Word32+(opLogicalEqual, opLogicalNotEqual, opLogicalOr, opLogicalAnd, opLogicalNot, opSelect) = (164, 165, 166, 167, 168, 169)++opIEqual, opINotEqual, opUGreaterThan, opSGreaterThan, opUGreaterThanEqual, opSGreaterThanEqual, opULessThan, opSLessThan, opULessThanEqual, opSLessThanEqual :: Word32+(opIEqual, opINotEqual, opUGreaterThan, opSGreaterThan, opUGreaterThanEqual, opSGreaterThanEqual, opULessThan, opSLessThan, opULessThanEqual, opSLessThanEqual) = (170, 171, 172, 173, 174, 175, 176, 177, 178, 179)++opFOrdEqual, opFOrdNotEqual, opFOrdLessThan, opFOrdGreaterThan, opFOrdLessThanEqual, opFOrdGreaterThanEqual :: Word32+(opFOrdEqual, opFOrdNotEqual, opFOrdLessThan, opFOrdGreaterThan, opFOrdLessThanEqual, opFOrdGreaterThanEqual) = (180, 182, 184, 186, 188, 190)++opLoopMerge, opLabel, opBranch, opBranchConditional, opReturn :: Word32+(opLoopMerge, opLabel, opBranch, opBranchConditional, opReturn) = (246, 248, 249, 250, 253)++-- Enums+capShader, execModelFragment, execModeOriginUpperLeft :: Word32+(capShader, execModelFragment, execModeOriginUpperLeft) = (1, 4, 7)++decBlock, decLocation, decBinding, decDescriptorSet, decOffset :: Word32+(decBlock, decLocation, decBinding, decDescriptorSet, decOffset) = (2, 30, 33, 34, 35)++scUniformConstant, scInput, scUniform, scOutput, scFunction :: Word32+(scUniformConstant, scInput, scUniform, scOutput, scFunction) = (0, 1, 2, 3, 7)++-- GLSL.std.450 extended instructions+glslFAbs, glslSAbs, glslFSign, glslSSign, glslFloor, glslCeil, glslFract :: Word32+(glslFAbs, glslSAbs, glslFSign, glslSSign, glslFloor, glslCeil, glslFract) = (4, 5, 6, 7, 8, 9, 10)++glslSin, glslCos, glslTan, glslAtan2, glslPow, glslExp, glslLog, glslLog2, glslSqrt :: Word32+(glslSin, glslCos, glslTan, glslAtan2, glslPow, glslExp, glslLog, glslLog2, glslSqrt) = (13, 14, 15, 25, 26, 27, 28, 30, 31)++glslFMin, glslUMin, glslSMin, glslFMax, glslUMax, glslSMax, glslFClamp, glslUClamp, glslSClamp, glslFMix, glslStep, glslSmoothStep, glslLength, glslCross, glslNormalize :: Word32+(glslFMin, glslUMin, glslSMin, glslFMax, glslUMax, glslSMax, glslFClamp, glslUClamp, glslSClamp, glslFMix, glslStep, glslSmoothStep, glslLength, glslCross, glslNormalize) = (37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 48, 49, 66, 68, 69)++-- ---------------------------------------------------------------------------+-- Builder state & on-demand type/constant memoization++data TypeKey+ = TKVoid+ | TKFnVoid+ | TKIR !IRType+ | TKBVec !Int+ | TKImage2D+ | TKSampledImage2D+ | TKPtr !Word32 !TypeKey+ | TKUboPtr !Word32+ deriving (Eq, Ord)++data ConstKey+ = CKFloat !Word32+ | CKInt !Int32+ | CKUInt !Word32+ | CKBool !Bool+ deriving (Eq, Ord)++data SpvEnv = SpvEnv+ { seNextId :: !Word32+ , seExtGlsl :: !Word32+ , seMainId :: !Word32+ , seEntryLabel :: !Word32+ , seVColorVar :: !Word32+ , seVUvVar :: !Word32+ , seFragOutVar :: !Word32+ , seUboVar :: !Word32+ , seTexVar :: !(Maybe Word32)+ , seTypes :: !(Map TypeKey Word32)+ , seTypeInsts :: ![[Word32]]+ -- ^ Reversed OpType* instructions emitted in section 9 (before constants).+ , seConsts :: !(Map ConstKey Word32)+ , seConstInsts :: ![[Word32]]+ -- ^ Reversed OpConstant* instructions emitted in section 9.+ , seFuncVars :: ![[Word32]]+ -- ^ Reversed function-scope OpVariable instructions emitted at entry.+ , seBody :: ![[Word32]]+ -- ^ Reversed instructions in main's body.+ }++-- | Emit a complete SPIR-V 1.0 binary fragment shader as little-endian bytes.+emitSpirv :: ShaderIR -> ByteString+emitSpirv = BSL.toStrict . BSB.toLazyByteString . foldMap BSB.word32LE . emitSpirvWords++-- | Emit a complete SPIR-V 1.0 binary fragment shader as 32-bit words.+emitSpirvWords :: ShaderIR -> [Word32]+emitSpirvWords ir =+ let (env0, decWords, globalWords) = initModule ir+ (outId, env1) = emitMain ir env0+ (tVoid, env2) = getType TKVoid env1+ (tFnVoid, env3) = getType TKFnVoid env2+ header = [spvMagic, spvVersion10, 0, seNextId env3, 0]+ caps = [inst opCapability [capShader]]+ extImports = [inst opExtInstImport (seExtGlsl env3 : encodeStr "GLSL.std.450")]+ memModel = [inst opMemoryModel [0, 1]]+ entryPts =+ [ inst opEntryPoint $+ [execModelFragment, seMainId env3]+ ++ encodeStr "main"+ ++ [seVColorVar env3, seVUvVar env3, seFragOutVar env3]+ ]+ execModes = [inst opExecutionMode [seMainId env3, execModeOriginUpperLeft]]+ fnStart =+ [ inst opFunction [tVoid, seMainId env3, 0, tFnVoid]+ , inst opLabel [seEntryLabel env3]+ ]+ fnEnd =+ [ inst opStore [seFragOutVar env3, outId]+ , inst opReturn []+ , inst opFunctionEnd []+ ]+ in concat $+ [header]+ ++ caps+ ++ extImports+ ++ memModel+ ++ entryPts+ ++ execModes+ ++ decWords+ ++ reverse (seTypeInsts env3)+ ++ reverse (seConstInsts env3)+ ++ globalWords+ ++ fnStart+ ++ reverse (seFuncVars env3)+ ++ reverse (seBody env3)+ ++ fnEnd++inst :: Word32 -> [Word32] -> [Word32]+inst opcode operands =+ let !wc = fromIntegral (1 + length operands) :: Word32+ in ((wc `shiftL` 16) .|. opcode) : operands++encodeStr :: String -> [Word32]+encodeStr s =+ let bytes = BSL.unpack (BSL.fromStrict (TE.encodeUtf8 (T.pack s))) ++ [0 :: Word8]+ padLen = (4 - (length bytes `rem` 4)) `rem` 4+ pack4 (a : b : c : d : rest) =+ let !w = fromIntegral a .|. (fromIntegral b `shiftL` 8) .|. (fromIntegral c `shiftL` 16) .|. (fromIntegral d `shiftL` 24)+ in w : pack4 rest+ pack4 _ = []+ in pack4 (bytes ++ replicate padLen 0)++allocId :: SpvEnv -> (Word32, SpvEnv)+allocId e = let !i = seNextId e in (i, e {seNextId = i + 1})++emitBody :: [Word32] -> SpvEnv -> SpvEnv+emitBody w e = e {seBody = w : seBody e}++emitRes :: Word32 -> Word32 -> [Word32] -> SpvEnv -> (Word32, SpvEnv)+emitRes opcode tyId args e =+ let (r, e1) = allocId e+ in (r, emitBody (inst opcode (tyId : r : args)) e1)++emitExt :: Word32 -> Word32 -> [Word32] -> SpvEnv -> (Word32, SpvEnv)+emitExt tyId extOp args e = emitRes opExtInst tyId (seExtGlsl e : extOp : args) e++emitLoad :: Word32 -> Word32 -> SpvEnv -> (Word32, SpvEnv)+emitLoad tyId ptrId = emitRes opLoad tyId [ptrId]++emitFuncVar :: IRType -> SpvEnv -> (Word32, SpvEnv)+emitFuncVar ty e0 =+ let (ptrTy, e1) = getType (TKPtr scFunction (TKIR ty)) e0+ (vid, e2) = allocId e1+ in (vid, e2 {seFuncVars = inst opVariable [ptrTy, vid, scFunction] : seFuncVars e2})++-- | Memoized on-demand SPIR-V type allocation.+getType :: TypeKey -> SpvEnv -> (Word32, SpvEnv)+getType key e = case Map.lookup key (seTypes e) of+ Just tid -> (tid, e)+ Nothing ->+ let record tid w e' = (tid, e' {seTypes = Map.insert key tid (seTypes e'), seTypeInsts = w : seTypeInsts e'})+ allocWith build e' = let (tid, e1) = allocId e' in record tid (build tid) e1+ in case key of+ TKVoid -> allocWith (\tid -> inst opTypeVoid [tid]) e+ TKFnVoid ->+ let (tv, e1) = getType TKVoid e+ in allocWith (\tid -> inst opTypeFunction [tid, tv]) e1+ TKIR TBool -> allocWith (\tid -> inst opTypeBool [tid]) e+ TKIR TInt -> allocWith (\tid -> inst opTypeInt [tid, 32, 1]) e+ TKIR TUInt -> allocWith (\tid -> inst opTypeInt [tid, 32, 0]) e+ TKIR TFloat -> allocWith (\tid -> inst opTypeFloat [tid, 32]) e+ TKIR TVec2 -> vecType TFloat 2 e+ TKIR TVec3 -> vecType TFloat 3 e+ TKIR TVec4 -> vecType TFloat 4 e+ TKBVec n -> vecType TBool (fromIntegral n) e+ TKImage2D ->+ let (tf, e1) = getType (TKIR TFloat) e+ in allocWith (\tid -> inst opTypeImage [tid, tf, 1, 0, 0, 0, 1, 0]) e1+ TKSampledImage2D ->+ let (img, e1) = getType TKImage2D e+ in allocWith (\tid -> inst opTypeSampledImage [tid, img]) e1+ TKPtr sc inner ->+ let (innerTy, e1) = getType inner e+ in allocWith (\tid -> inst opTypePointer [tid, sc, innerTy]) e1+ TKUboPtr structId ->+ allocWith (\tid -> inst opTypePointer [tid, scUniform, structId]) e+ where+ vecType elemTy n e0 =+ let (et, e1) = getType (TKIR elemTy) e0+ (tid, e2) = allocId e1+ in (tid, e2 {seTypes = Map.insert key tid (seTypes e2), seTypeInsts = inst opTypeVector [tid, et, n] : seTypeInsts e2})++irTypeId :: IRType -> SpvEnv -> (Word32, SpvEnv)+irTypeId = getType . TKIR++uboFieldIR :: GpuType -> IRType+uboFieldIR gt = case gt of+ GFloat -> TFloat+ GInt32 -> TInt+ GUInt32 -> TUInt+ GBool -> TUInt+ GVec2 -> TVec2+ GVec3 -> TVec3+ GVec4 -> TVec4++constWord :: ConstKey -> SpvEnv -> (Word32, SpvEnv)+constWord key e = case Map.lookup key (seConsts e) of+ Just cid -> (cid, e)+ Nothing ->+ let (ty, build) = case key of+ CKFloat bits -> (TFloat, \t c -> inst opConstant [t, c, bits])+ CKInt n -> (TInt, \t c -> inst opConstant [t, c, fromIntegral n])+ CKUInt u -> (TUInt, \t c -> inst opConstant [t, c, u])+ CKBool True -> (TBool, \t c -> inst opConstantTrue [t, c])+ CKBool False -> (TBool, \t c -> inst opConstantFalse [t, c])+ (tid, e1) = irTypeId ty e+ (cid, e2) = allocId e1+ in (cid, e2 {seConsts = Map.insert key cid (seConsts e2), seConstInsts = build tid cid : seConstInsts e2})++constInt :: Int32 -> SpvEnv -> (Word32, SpvEnv)+constInt = constWord . CKInt++constFloat :: Float -> SpvEnv -> (Word32, SpvEnv)+constFloat = constWord . CKFloat . castFloatToWord32++-- ---------------------------------------------------------------------------+-- Module setup++initModule :: ShaderIR -> (SpvEnv, [[Word32]], [[Word32]])+initModule ir =+ let base0 = SpvEnv 1 0 0 0 0 0 0 0 Nothing Map.empty [] Map.empty [] [] []+ (extGlsl, e1) = allocId base0+ (mainId, e2) = allocId e1+ (entryLabel, e3) = allocId e2+ (vColorVar, e4) = allocId e3+ (vUvVar, e5) = allocId e4+ (fragOutVar, e6) = allocId e5+ (uboVar, e7) = allocId e6+ (pInVec4, e8) = getType (TKPtr scInput (TKIR TVec4)) e7+ (pInVec2, e9) = getType (TKPtr scInput (TKIR TVec2)) e8+ (pOutVec4, e10) = getType (TKPtr scOutput (TKIR TVec4)) e9+ (tVec4, e11) = irTypeId TVec4 e10+ (userTys, e12) = mapAccumEnv (\st uf -> irTypeId (uboFieldIR (ufType uf)) st) e11 (irUniforms ir)+ (uboStruct, e13) = allocId e12+ e14 = e13 {seTypeInsts = inst opTypeStruct (uboStruct : tVec4 : tVec4 : tVec4 : userTys) : seTypeInsts e13}+ (pUbo, e15) = getType (TKUboPtr uboStruct) e14+ (mTexVar, texDecs, texGlobals, e16)+ | irNeedsInput ir =+ let (pSamp, s1) = getType (TKPtr scUniformConstant TKSampledImage2D) e15+ (tVar, s2) = allocId s1+ in ( Just tVar+ , [inst opDecorate [tVar, decDescriptorSet, 2], inst opDecorate [tVar, decBinding, 0]]+ , [inst opVariable [pSamp, tVar, scUniformConstant]]+ , s2+ )+ | otherwise = (Nothing, [], [], e15)+ decs =+ [ inst opDecorate [vColorVar, decLocation, 0]+ , inst opDecorate [vUvVar, decLocation, 1]+ , inst opDecorate [fragOutVar, decLocation, 0]+ , inst opDecorate [uboStruct, decBlock]+ , inst opMemberDecorate [uboStruct, 0, decOffset, 0]+ , inst opMemberDecorate [uboStruct, 1, decOffset, 16]+ , inst opMemberDecorate [uboStruct, 2, decOffset, 32]+ ]+ ++ [ inst opMemberDecorate [uboStruct, fromIntegral (3 + i), decOffset, fromIntegral (48 + ufOffset uf)]+ | (i, uf) <- zip [0 :: Int ..] (irUniforms ir)+ ]+ ++ [inst opDecorate [uboVar, decDescriptorSet, 3], inst opDecorate [uboVar, decBinding, 0]]+ ++ texDecs+ globals =+ [ inst opVariable [pInVec4, vColorVar, scInput]+ , inst opVariable [pInVec2, vUvVar, scInput]+ , inst opVariable [pOutVec4, fragOutVar, scOutput]+ , inst opVariable [pUbo, uboVar, scUniform]+ ]+ ++ texGlobals+ envFinal =+ e16+ { seExtGlsl = extGlsl+ , seMainId = mainId+ , seEntryLabel = entryLabel+ , seVColorVar = vColorVar+ , seVUvVar = vUvVar+ , seFragOutVar = fragOutVar+ , seUboVar = uboVar+ , seTexVar = mTexVar+ }+ in (envFinal, decs, globals)++mapAccumEnv :: (SpvEnv -> a -> (b, SpvEnv)) -> SpvEnv -> [a] -> ([b], SpvEnv)+mapAccumEnv _ e [] = ([], e)+mapAccumEnv f e (x : xs) =+ let (y, e1) = f e x+ (ys, e2) = mapAccumEnv f e1 xs+ in (y : ys, e2)++-- ---------------------------------------------------------------------------+-- SSA block emission++data ScopeCtx = ScopeCtx+ { scFrames :: ![Vector (IRType, Word32)]+ , scLoopVars :: !(Map Int Word32)+ , scLoopStates :: !(Map (Int, Int) (IRType, Word32))+ , scLoopResults :: !(Map Int [(IRType, Word32)])+ }++emitMain :: ShaderIR -> SpvEnv -> (Word32, SpvEnv)+emitMain ir env0 =+ let (vals, env1) = emitBlock (ScopeCtx [] Map.empty Map.empty Map.empty) (irNodes ir) env0+ in (snd (vals V.! unNodeId (irOutput ir)), env1)++emitBlock :: ScopeCtx -> Vector (IRType, ExprOp) -> SpvEnv -> (Vector (IRType, Word32), SpvEnv)+emitBlock scope nodes = go 0 IM.empty Map.empty+ where+ !n = V.length nodes+ go !i !acc !loopRes !e+ | i >= n = (V.generate n (acc IM.!), e)+ | otherwise =+ let (ty, op) = nodes V.! i+ scope' = scope {scLoopResults = loopRes}+ in case op of+ OpLoop lb ->+ let (resList, e1) = emitLoopSpv scope' i acc lb e+ firstVal = case resList of ((_, v) : _) -> v; [] -> 0+ in go (i + 1) (IM.insert i (ty, firstVal) acc) (Map.insert i resList loopRes) e1+ _ ->+ let (vid, e1) = emitOpSpv scope' acc ty op e+ in go (i + 1) (IM.insert i (ty, vid) acc) loopRes e1++emitLoopSpv ::+ ScopeCtx ->+ Int ->+ IntMap (IRType, Word32) ->+ LoopBody ->+ SpvEnv ->+ ([(IRType, Word32)], SpvEnv)+emitLoopSpv scope outerCount curVals lb e0 =+ let lid = lbLoopId lb+ (tInt, e1) = irTypeId TInt e0+ (tBool, e2) = irTypeId TBool e1+ (iVar, e3) = emitFuncVar TInt e2+ (accVars, e4) = mapAccumEnv (flip emitFuncVar) e3 (lbStateTypes lb)+ (startConst, e5) = constInt (lbStart lb) e4+ (endConst, e6) = constInt (lbEnd lb) e5+ (oneConst, e7) = constInt 1 e6+ e8 =+ foldl'+ (\e (vPtr, initNid) -> emitBody (inst opStore [vPtr, snd (curVals IM.! unNodeId initNid)]) e)+ (emitBody (inst opStore [iVar, startConst]) e7)+ (zip accVars (lbInits lb))+ (headerLbl, e9) = allocId e8+ (bodyLbl, e10) = allocId e9+ (contLbl, e11) = allocId e10+ (mergeLbl, e12) = allocId e11+ -- Header+ e13 = emitBody (inst opLabel [headerLbl]) . emitBody (inst opBranch [headerLbl]) $ e12+ (iVal, e14) = emitLoad tInt iVar e13+ (condId, e15) = emitRes opSLessThan tBool [iVal, endConst] e14+ e16 =+ emitBody (inst opLabel [bodyLbl])+ . emitBody (inst opBranchConditional [condId, bodyLbl, mergeLbl])+ . emitBody (inst opLoopMerge [mergeLbl, contLbl, 0])+ $ e15+ -- Body+ (loadedStates, e17) = loadAccVars e16 (zip (lbStateTypes lb) accVars)+ outerVec = V.generate outerCount (curVals IM.!)+ innerScope =+ ScopeCtx+ { scFrames = scFrames scope ++ [outerVec]+ , scLoopVars = Map.insert lid iVal (scLoopVars scope)+ , scLoopStates = foldl' (\m (slot, st) -> Map.insert (lid, slot) st m) (scLoopStates scope) (zip [0 :: Int ..] loadedStates)+ , scLoopResults = Map.empty+ }+ (bodyVals, e18) = emitBlock innerScope (lbBodyNodes lb) e17+ e19 =+ emitBody (inst opLabel [contLbl])+ . emitBody (inst opBranch [contLbl])+ $ foldl'+ (\e (vPtr, nextNid) -> emitBody (inst opStore [vPtr, snd (bodyVals V.! unNodeId nextNid)]) e)+ e18+ (zip accVars (lbNextStates lb))+ -- Continue+ (iCur, e20) = emitLoad tInt iVar e19+ (iNext, e21) = emitRes opIAdd tInt [iCur, oneConst] e20+ e22 =+ emitBody (inst opLabel [mergeLbl])+ . emitBody (inst opBranch [headerLbl])+ . emitBody (inst opStore [iVar, iNext])+ $ e21+ in loadAccVars e22 (zip (lbStateTypes lb) accVars)+ where+ loadAccVars = mapAccumEnv $ \e (t, vPtr) ->+ let (tid, e1) = irTypeId t e+ (val, e2) = emitLoad tid vPtr e1+ in ((t, val), e2)++emitUboMember :: Int32 -> GpuType -> SpvEnv -> (Word32, SpvEnv)+emitUboMember memberIdx gt e0 =+ let fieldIR = uboFieldIR gt+ (idxConst, e1) = constInt memberIdx e0+ (ptrTy, e2) = getType (TKPtr scUniform (TKIR fieldIR)) e1+ (ptrId, e3) = emitRes opAccessChain ptrTy [seUboVar e2, idxConst] e2+ (valTy, e4) = irTypeId fieldIR e3+ (rawId, e5) = emitLoad valTy ptrId e4+ in case gt of+ GBool ->+ let (zeroU, e6) = constWord (CKUInt 0) e5+ (tBool, e7) = irTypeId TBool e6+ in emitRes opINotEqual tBool [rawId, zeroU] e7+ _ -> (rawId, e5)++-- ---------------------------------------------------------------------------+-- Individual instruction lowering++emitOpSpv :: ScopeCtx -> IntMap (IRType, Word32) -> IRType -> ExprOp -> SpvEnv -> (Word32, SpvEnv)+emitOpSpv scope vals ty op e0 = case op of+ OpLitFloat bits -> constWord (CKFloat bits) e0+ OpLitInt n -> constWord (CKInt n) e0+ OpLitUInt u -> constWord (CKUInt u) e0+ OpLitBool b -> constWord (CKBool b) e0+ OpSys sf -> case sf of+ SysRect -> emitUboMember 0 GVec4 e0+ SysUvRect -> emitUboMember 1 GVec4 e0+ SysMeta -> emitUboMember 2 GVec4 e0+ SysVColor -> let (t4, e1) = irTypeId TVec4 e0 in emitLoad t4 (seVColorVar e1) e1+ SysVUv -> let (t2, e1) = irTypeId TVec2 e0 in emitLoad t2 (seVUvVar e1) e1+ OpUniform idx gt -> emitUboMember (fromIntegral (3 + idx)) gt e0+ OpOuterRef depth nid -> (snd ((scFrames scope !! depth) V.! unNodeId nid), e0)+ OpLoopVar lid -> (scLoopVars scope Map.! lid, e0)+ OpLoopState lid slot -> (snd (scLoopStates scope Map.! (lid, slot)), e0)+ OpLoopResult loopNid slot -> (snd ((scLoopResults scope Map.! unNodeId loopNid) !! slot), e0)+ OpLoop _ -> (0, e0)+ OpConstruct outTy args -> emitConstruct vals outTy args e0+ OpSwizzle src cs -> emitSwizzle vals ty src cs e0+ OpUnary uo a -> emitUnary vals ty uo a e0+ OpBinary bo a b -> emitBinary vals ty bo a b e0+ OpTernary to a b c -> emitTernary vals ty to a b c e0+ OpLength a ->+ let (tf, e1) = irTypeId TFloat e0+ in emitExt tf glslLength [snd (vals IM.! unNodeId a)] e1+ OpNormalize a ->+ let (tyId, e1) = irTypeId ty e0+ in emitExt tyId glslNormalize [snd (vals IM.! unNodeId a)] e1+ OpSampleInput uvNid ->+ case seTexVar e0 of+ Just texVar ->+ let (_, uvId) = vals IM.! unNodeId uvNid+ (sampTy, e1) = getType TKSampledImage2D e0+ (tF, e2) = irTypeId TFloat e1+ (tV3, e3) = irTypeId TVec3 e2+ (tV4, e4) = irTypeId TVec4 e3+ (sampId, e5) = emitLoad sampTy texVar e4+ (rawId, e6) = emitRes opImageSampleImplicitLod tV4 [sampId, uvId] e5+ -- Offscreen targets hold premultiplied RGBA; un-premultiply to straight alpha.+ (aId, e7) = emitRes opCompositeExtract tF [rawId, 3] e6+ (epsId, e8) = constFloat 1.0e-5 e7+ (denomId, e9) = emitExt tF glslFMax [aId, epsId] e8+ (denom3Id, e10) = emitRes opCompositeConstruct tV3 [denomId, denomId, denomId] e9+ (rgbId, e11) = emitRes opVectorShuffle tV3 [rawId, rawId, 0, 1, 2] e10+ (divId, e12) = emitRes opFDiv tV3 [rgbId, denom3Id] e11+ (oneId, e13) = constFloat 1.0 e12+ (one3Id, e14) = emitRes opCompositeConstruct tV3 [oneId, oneId, oneId] e13+ (clampedId, e15) = emitExt tV3 glslFMin [divId, one3Id] e14+ in emitRes opCompositeConstruct tV4 [clampedId, aId] e15+ Nothing ->+ let (tV4, e1) = irTypeId TVec4 e0+ (z, e2) = constFloat 0 e1+ in emitRes opCompositeConstruct tV4 [z, z, z, z] e2++-- | Flatten vector arguments to scalar components and handle scalar splat.+emitConstruct :: IntMap (IRType, Word32) -> IRType -> [NodeId] -> SpvEnv -> (Word32, SpvEnv)+emitConstruct vals outTy args e0 =+ let resolved = [vals IM.! unNodeId a | a <- args]+ !outComps = irTypeComps outTy+ (tyId, e1) = irTypeId outTy e0+ in case resolved of+ [(TFloat, sId)] | outComps > 1 ->+ emitRes opCompositeConstruct tyId (replicate outComps sId) e1+ _ ->+ let (scalars, e2) = flattenScalars resolved e1+ in emitRes opCompositeConstruct tyId scalars e2+ where+ flattenScalars [] e = ([], e)+ flattenScalars ((t, vid) : rest) e+ | irTypeComps t == 1 =+ let (rs, e') = flattenScalars rest e+ in (vid : rs, e')+ | otherwise =+ let (tF, e1) = irTypeId TFloat e+ (cs, e2) = mapAccumEnv (\st j -> emitRes opCompositeExtract tF [vid, fromIntegral j] st) e1 [0 .. irTypeComps t - 1]+ (rs, e3) = flattenScalars rest e2+ in (cs ++ rs, e3)++emitSwizzle :: IntMap (IRType, Word32) -> IRType -> NodeId -> [Int] -> SpvEnv -> (Word32, SpvEnv)+emitSwizzle vals outTy src cs e0 =+ let (srcTy, srcId) = vals IM.! unNodeId src+ (tyId, e1) = irTypeId outTy e0+ in case cs of+ [c]+ | irTypeComps srcTy == 1 -> (srcId, e0)+ | otherwise -> emitRes opCompositeExtract tyId [srcId, fromIntegral c] e1+ _+ | irTypeComps srcTy == 1 -> emitRes opCompositeConstruct tyId (replicate (length cs) srcId) e1+ | otherwise -> emitRes opVectorShuffle tyId (srcId : srcId : map fromIntegral cs) e1++-- | Promote a scalar TFloat to match a target vector type via OpCompositeConstruct.+splatTo :: IRType -> (IRType, Word32) -> SpvEnv -> (Word32, SpvEnv)+splatTo targetTy (srcTy, srcId) e+ | srcTy == targetTy = (srcId, e)+ | srcTy == TFloat && irTypeComps targetTy > 1 =+ let (tyId, e1) = irTypeId targetTy e+ in emitRes opCompositeConstruct tyId (replicate (irTypeComps targetTy) srcId) e1+ | otherwise = (srcId, e)++-- | Select signed-int, unsigned-int, or float SPIR-V opcode for @opTy@.+numPick :: IRType -> Word32 -> Word32 -> Word32 -> Word32+numPick TInt s _ _ = s+numPick TUInt _ u _ = u+numPick _ _ _ f = f++emitUnary :: IntMap (IRType, Word32) -> IRType -> UnOp -> NodeId -> SpvEnv -> (Word32, SpvEnv)+emitUnary vals ty uo a e0 =+ let (aTy, aId) = vals IM.! unNodeId a+ (tyId, e1) = irTypeId ty e0+ ext extOp = emitExt tyId extOp [aId] e1+ core opcode = emitRes opcode tyId [aId] e1+ in case uo of+ UNeg -> core (numPick aTy opSNegate opSNegate opFNegate)+ UAbs -> ext (if aTy == TInt then glslSAbs else glslFAbs)+ USign -> ext (if aTy == TInt then glslSSign else glslFSign)+ UNot -> core opLogicalNot+ UFloatToInt -> core opConvertFToS+ UIntToFloat -> core opConvertSToF+ UFloor -> ext glslFloor+ UCeil -> ext glslCeil+ UFract -> ext glslFract+ USqrt -> ext glslSqrt+ USin -> ext glslSin+ UCos -> ext glslCos+ UTan -> ext glslTan+ UExp -> ext glslExp+ ULog -> ext glslLog+ ULog2 -> ext glslLog2++emitBinary :: IntMap (IRType, Word32) -> IRType -> BinOp -> NodeId -> NodeId -> SpvEnv -> (Word32, SpvEnv)+emitBinary vals ty bo a b e0 =+ let av@(aTy, aRaw) = vals IM.! unNodeId a+ bv@(bTy, bRaw) = vals IM.! unNodeId b+ opTy = if irTypeComps aTy >= irTypeComps bTy then aTy else bTy+ (aId, e1) = splatTo opTy av e0+ (bId, e2) = splatTo opTy bv e1+ (tyId, e3) = irTypeId ty e2+ core opcode = emitRes opcode tyId [aId, bId] e3+ ext extOp = emitExt tyId extOp [aId, bId] e3+ eqOp bOp iOp fOp = if opTy == TBool then bOp else numPick opTy iOp iOp fOp+ in case bo of+ BAdd -> core (numPick opTy opIAdd opIAdd opFAdd)+ BSub -> core (numPick opTy opISub opISub opFSub)+ BMul -> core (numPick opTy opIMul opIMul opFMul)+ BDiv -> core (numPick opTy opSDiv opUDiv opFDiv)+ BMod -> core opFMod+ BMin -> ext (numPick opTy glslSMin glslUMin glslFMin)+ BMax -> ext (numPick opTy glslSMax glslUMax glslFMax)+ BPow -> ext glslPow+ BAtan2 -> ext glslAtan2+ BStep -> ext glslStep+ BEq -> core (eqOp opLogicalEqual opIEqual opFOrdEqual)+ BNeq -> core (eqOp opLogicalNotEqual opINotEqual opFOrdNotEqual)+ BLt -> core (numPick opTy opSLessThan opULessThan opFOrdLessThan)+ BLe -> core (numPick opTy opSLessThanEqual opULessThanEqual opFOrdLessThanEqual)+ BGt -> core (numPick opTy opSGreaterThan opUGreaterThan opFOrdGreaterThan)+ BGe -> core (numPick opTy opSGreaterThanEqual opUGreaterThanEqual opFOrdGreaterThanEqual)+ BAnd -> core opLogicalAnd+ BOr -> core opLogicalOr+ BDot ->+ let (tF, eF) = irTypeId TFloat e0+ in emitRes opDot tF [aRaw, bRaw] eF+ BCross ->+ let (tOut, eOut) = irTypeId ty e0+ in emitExt tOut glslCross [aRaw, bRaw] eOut++emitTernary :: IntMap (IRType, Word32) -> IRType -> TriOp -> NodeId -> NodeId -> NodeId -> SpvEnv -> (Word32, SpvEnv)+emitTernary vals ty to a b c e0 =+ let av = vals IM.! unNodeId a+ bv = vals IM.! unNodeId b+ cv = vals IM.! unNodeId c+ (tyId, e1) = irTypeId ty e0+ splatExt extOp =+ let (aId, s1) = splatTo ty av e1+ (bId, s2) = splatTo ty bv s1+ (cId, s3) = splatTo ty cv s2+ in emitExt tyId extOp [aId, bId, cId] s3+ in case to of+ TMix -> splatExt glslFMix+ TClamp -> splatExt (numPick ty glslSClamp glslUClamp glslFClamp)+ TSmoothstep -> splatExt glslSmoothStep+ TSelect ->+ let (_, condRaw) = av+ (bId, e2) = splatTo ty bv e1+ (cId, e3) = splatTo ty cv e2+ -- SPIR-V 1.0 requires a boolean vector condition for vector OpSelect.+ (condId, e4)+ | irTypeComps ty > 1 =+ let !n = irTypeComps ty+ (bvTy, s1) = getType (TKBVec n) e3+ in emitRes opCompositeConstruct bvTy (replicate n condRaw) s1+ | otherwise = (condRaw, e3)+ in emitRes opSelect tyId [condId, bId, cId] e4
+ lib/NanoUI/Shader/Internal/Eval/Cpu.hs view
@@ -0,0 +1,320 @@+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Pure-Haskell CPU reference evaluator for 'ShaderIR'.+--+-- Evaluates the exact same lowered SSA IR emitted to GLSL, MSL, and SPIR-V,+-- enabling headless golden testing, CPU-vs-GPU differential pixel checks, and+-- optional SVG raster fallbacks.+module NanoUI.Shader.Internal.Eval.Cpu+ ( evalShaderIR+ , evalShaderIRColor+ ) where++import Data.Bits (shiftR, (.&.))+import Data.Int (Int32)+import Data.IntMap.Strict (IntMap)+import Data.IntMap.Strict qualified as IM+import Data.Primitive.ByteArray (ByteArray, indexByteArray)+import Data.Vector (Vector)+import Data.Vector qualified as V+import Data.Word (Word32)+import GHC.Float (castWord32ToFloat)+import NanoUI.Internal.Shader (CpuFragCtx (..))+import NanoUI (Color (..), V2 (..), colorRGBA)+import NanoUI.Internal.Uniforms (GpuType (..), UniformField (..))+import NanoUI.Shader.Internal.IR++data Val+ = VF {-# UNPACK #-} !Float+ | VI {-# UNPACK #-} !Int32+ | VU {-# UNPACK #-} !Word32+ | VB !Bool+ | VV2 {-# UNPACK #-} !Float {-# UNPACK #-} !Float+ | VV3 {-# UNPACK #-} !Float {-# UNPACK #-} !Float {-# UNPACK #-} !Float+ | VV4 {-# UNPACK #-} !Float {-# UNPACK #-} !Float {-# UNPACK #-} !Float {-# UNPACK #-} !Float+ | VTuple ![Val]++-- | Evaluate a 'ShaderIR' at fragment context @ctx@ with packed std140 user+-- uniform bytes @uBytes@ and input sampler @sampleTex@ (taking local logical+-- pixel coordinates), returning straight-alpha RGBA floats in @[0, 1]@.+evalShaderIR ::+ ShaderIR ->+ ByteArray ->+ CpuFragCtx ->+ (V2 -> Color) ->+ (Float, Float, Float, Float)+evalShaderIR ir uBytes ctx sampleTex =+ let fields = V.fromList (irUniforms ir)+ vals = evalScope fields uBytes ctx sampleTex [] IM.empty IM.empty (irNodes ir)+ in case vals V.! unNodeId (irOutput ir) of+ VV4 r g b a -> (r, g, b, a)+ _ -> (0, 0, 0, 0)++clamp01 :: Float -> Float+clamp01 x = max 0 (min 1 x)++-- | Like 'evalShaderIR', quantizing the result to an 8-bit straight-alpha+-- 'Color' (clamped to @[0, 1]@).+evalShaderIRColor :: ShaderIR -> ByteArray -> CpuFragCtx -> (V2 -> Color) -> Color+evalShaderIRColor ir uBytes ctx sampleTex =+ let (r, g, b, a) = evalShaderIR ir uBytes ctx sampleTex+ toByte x = round (255 * clamp01 x)+ in colorRGBA (toByte r) (toByte g) (toByte b) (toByte a)++evalScope ::+ Vector UniformField ->+ ByteArray ->+ CpuFragCtx ->+ (V2 -> Color) ->+ [Vector Val] ->+ IntMap Int32 ->+ IntMap [Val] ->+ Vector (IRType, ExprOp) ->+ Vector Val+evalScope fields uBytes ctx sampleTex outerEnvs loopVars loopStates nodes =+ V.constructN (V.length nodes) $ \prefix ->+ let !idx = V.length prefix+ (_, op) = nodes V.! idx+ in evalOp fields uBytes ctx sampleTex outerEnvs loopVars loopStates prefix op++evalOp ::+ Vector UniformField ->+ ByteArray ->+ CpuFragCtx ->+ (V2 -> Color) ->+ [Vector Val] ->+ IntMap Int32 ->+ IntMap [Val] ->+ Vector Val ->+ ExprOp ->+ Val+evalOp fields uBytes ctx sampleTex outerEnvs loopVars loopStates env op =+ let at (NodeId i) = env V.! i+ in case op of+ OpLitFloat bits -> VF (castWord32ToFloat bits)+ OpLitInt n -> VI n+ OpLitUInt w -> VU w+ OpLitBool b -> VB b+ OpSys sf -> case sf of+ SysRect -> let V2 w h = cfcSize ctx in VV4 0 0 w h+ SysUvRect -> VV4 0 0 1 1+ SysMeta -> let V2 w h = cfcSize ctx in VV4 (cfcScale ctx) (cfcCornerRadius ctx) w h+ SysVColor -> colorToVal (cfcColor ctx)+ SysVUv -> let V2 u v = cfcUv ctx in VV2 u v+ OpUniform i gt ->+ let off = ufOffset (fields V.! i)+ wAt o = indexByteArray uBytes (o `shiftR` 2) :: Word32+ fAt o = castWord32ToFloat (wAt o)+ in case gt of+ GFloat -> VF (fAt off)+ GInt32 -> VI (fromIntegral (wAt off))+ GUInt32 -> VU (wAt off)+ GBool -> VB (wAt off /= 0)+ GVec2 -> VV2 (fAt off) (fAt (off + 4))+ GVec3 -> VV3 (fAt off) (fAt (off + 4)) (fAt (off + 8))+ GVec4 -> VV4 (fAt off) (fAt (off + 4)) (fAt (off + 8)) (fAt (off + 12))+ OpConstruct ct args ->+ let comps = concatMap (valFloats . at) args+ in case (ct, comps) of+ (TVec2, [x]) -> VV2 x x+ (TVec2, x : y : _) -> VV2 x y+ (TVec3, [x]) -> VV3 x x x+ (TVec3, x : y : z : _) -> VV3 x y z+ (TVec4, [x]) -> VV4 x x x x+ (TVec4, x : y : z : w : _) -> VV4 x y z w+ _ -> VF 0+ OpSwizzle v idxs ->+ let fs = valFloats (at v)+ pick k = if k < length fs then fs !! k else 0+ in case map pick idxs of+ [x] -> VF x+ [x, y] -> VV2 x y+ [x, y, z] -> VV3 x y z+ [x, y, z, w] -> VV4 x y z w+ _ -> VF 0+ OpUnary uop a -> evalUnary uop (at a)+ OpBinary bop a b -> evalBinary bop (at a) (at b)+ OpTernary top a b c -> evalTernary top (at a) (at b) (at c)+ OpLength a ->+ let fs = valFloats (at a)+ in VF (sqrt (sum (map (\x -> x * x) fs)))+ OpNormalize a ->+ let v = at a+ fs = valFloats v+ len = sqrt (sum (map (\x -> x * x) fs))+ inv = if len > 0 then 1 / len else 0+ in mapFloatVal (* inv) v+ OpSampleInput uvNode ->+ let (u, v) = case at uvNode of+ VV2 x y -> (x, y)+ _ -> (0, 0)+ V2 w h = cfcSize ctx+ in colorToVal (sampleTex (V2 (u * w) (v * h)))+ OpOuterRef d (NodeId nid) ->+ -- outerEnvs is stored outermost-first via append at loop entry.+ (outerEnvs !! d) V.! nid+ OpLoopVar lid -> VI (IM.findWithDefault 0 lid loopVars)+ OpLoopState lid slot -> (IM.findWithDefault [] lid loopStates) !! slot+ OpLoop lb ->+ let lid = lbLoopId lb+ initVals = map at (lbInits lb)+ envsWithMe = outerEnvs ++ [env]+ step !acc !i =+ let lv' = IM.insert lid i loopVars+ ls' = IM.insert lid acc loopStates+ bodyVals = evalScope fields uBytes ctx sampleTex envsWithMe lv' ls' (lbBodyNodes lb)+ in map (\(NodeId nid) -> bodyVals V.! nid) (lbNextStates lb)+ finalVals = foldl' step initVals [lbStart lb .. lbEnd lb - 1]+ in VTuple finalVals+ OpLoopResult ln slot -> case at ln of+ VTuple vs -> vs !! slot+ other -> other++colorToVal :: Color -> Val+colorToVal (Color w) =+ let inv = 1.0 / 255.0 :: Float+ r = fromIntegral ((w `shiftR` 24) .&. 0xFF) * inv+ g = fromIntegral ((w `shiftR` 16) .&. 0xFF) * inv+ b = fromIntegral ((w `shiftR` 8) .&. 0xFF) * inv+ a = fromIntegral (w .&. 0xFF) * inv+ in VV4 r g b a++valFloats :: Val -> [Float]+valFloats v = case v of+ VF x -> [x]+ VV2 x y -> [x, y]+ VV3 x y z -> [x, y, z]+ VV4 x y z w -> [x, y, z, w]+ VI n -> [fromIntegral n]+ VU w -> [fromIntegral w]+ VB b -> [if b then 1 else 0]+ VTuple _ -> []++mapFloatVal :: (Float -> Float) -> Val -> Val+mapFloatVal f v = case v of+ VF x -> VF (f x)+ VV2 x y -> VV2 (f x) (f y)+ VV3 x y z -> VV3 (f x) (f y) (f z)+ VV4 x y z w -> VV4 (f x) (f y) (f z) (f w)+ other -> other++zipFloatVal :: (Float -> Float -> Float) -> Val -> Val -> Val+zipFloatVal f a b = case (a, b) of+ (VF x, VF y) -> VF (f x y)+ (VV2 x1 y1, VV2 x2 y2) -> VV2 (f x1 x2) (f y1 y2)+ (VV3 x1 y1 z1, VV3 x2 y2 z2) -> VV3 (f x1 x2) (f y1 y2) (f z1 z2)+ (VV4 x1 y1 z1 w1, VV4 x2 y2 z2 w2) -> VV4 (f x1 x2) (f y1 y2) (f z1 z2) (f w1 w2)+ (VV2 x1 y1, VF s) -> VV2 (f x1 s) (f y1 s)+ (VV3 x1 y1 z1, VF s) -> VV3 (f x1 s) (f y1 s) (f z1 s)+ (VV4 x1 y1 z1 w1, VF s) -> VV4 (f x1 s) (f y1 s) (f z1 s) (f w1 s)+ (VF s, VV2 x2 y2) -> VV2 (f s x2) (f s y2)+ (VF s, VV3 x2 y2 z2) -> VV3 (f s x2) (f s y2) (f s z2)+ (VF s, VV4 x2 y2 z2 w2) -> VV4 (f s x2) (f s y2) (f s z2) (f s w2)+ _ -> a++evalUnary :: UnOp -> Val -> Val+evalUnary uop v = case uop of+ UNeg -> case v of+ VI n -> VI (negate n)+ VU w -> VU (negate w)+ _ -> mapFloatVal negate v+ UAbs -> case v of+ VI n -> VI (abs n)+ VU w -> VU w+ _ -> mapFloatVal abs v+ UFloor -> mapFloatVal (fromIntegral . (floor :: Float -> Int)) v+ UCeil -> mapFloatVal (fromIntegral . (ceiling :: Float -> Int)) v+ UFract -> mapFloatVal (\x -> x - fromIntegral (floor x :: Int)) v+ USqrt -> mapFloatVal sqrt v+ USin -> mapFloatVal sin v+ UCos -> mapFloatVal cos v+ UTan -> mapFloatVal tan v+ UExp -> mapFloatVal exp v+ ULog -> mapFloatVal log v+ ULog2 -> mapFloatVal (logBase 2) v+ USign -> case v of+ VI n -> VI (signum n)+ VU w -> VU (if w == 0 then 0 else 1)+ _ -> mapFloatVal signum v+ UNot -> case v of+ VB b -> VB (not b)+ _ -> VB False+ UFloatToInt -> case v of+ VF x -> VI (truncate x)+ _ -> VI 0+ UIntToFloat -> case v of+ VI n -> VF (fromIntegral n)+ VU w -> VF (fromIntegral w)+ _ -> VF 0++evalBinary :: BinOp -> Val -> Val -> Val+evalBinary bop a b = case (bop, a, b) of+ (BAdd, VI x, VI y) -> VI (x + y)+ (BSub, VI x, VI y) -> VI (x - y)+ (BMul, VI x, VI y) -> VI (x * y)+ (BDiv, VI x, VI y) -> VI (if y == 0 then 0 else x `quot` y)+ (BAdd, VU x, VU y) -> VU (x + y)+ (BSub, VU x, VU y) -> VU (x - y)+ (BMul, VU x, VU y) -> VU (x * y)+ (BDiv, VU x, VU y) -> VU (if y == 0 then 0 else x `quot` y)+ (BAdd, _, _) -> zipFloatVal (+) a b+ (BSub, _, _) -> zipFloatVal (-) a b+ (BMul, _, _) -> zipFloatVal (*) a b+ (BDiv, _, _) -> zipFloatVal (/) a b+ (BMod, _, _) -> zipFloatVal (\x y -> x - y * fromIntegral (floor (x / y) :: Int)) a b+ (BMin, VI x, VI y) -> VI (min x y)+ (BMax, VI x, VI y) -> VI (max x y)+ (BMin, VU x, VU y) -> VU (min x y)+ (BMax, VU x, VU y) -> VU (max x y)+ (BMin, _, _) -> zipFloatVal min a b+ (BMax, _, _) -> zipFloatVal max a b+ (BPow, _, _) -> zipFloatVal (**) a b+ (BAtan2, VF y, VF x) -> VF (atan2 y x)+ (BStep, VF e, VF x) -> VF (if x < e then 0 else 1)+ (BEq, VF x, VF y) -> VB (x == y)+ (BEq, VI x, VI y) -> VB (x == y)+ (BEq, VU x, VU y) -> VB (x == y)+ (BEq, VB x, VB y) -> VB (x == y)+ (BNeq, VF x, VF y) -> VB (x /= y)+ (BNeq, VI x, VI y) -> VB (x /= y)+ (BNeq, VU x, VU y) -> VB (x /= y)+ (BNeq, VB x, VB y) -> VB (x /= y)+ (BLt, VF x, VF y) -> VB (x < y)+ (BLt, VI x, VI y) -> VB (x < y)+ (BLt, VU x, VU y) -> VB (x < y)+ (BLe, VF x, VF y) -> VB (x <= y)+ (BLe, VI x, VI y) -> VB (x <= y)+ (BLe, VU x, VU y) -> VB (x <= y)+ (BGt, VF x, VF y) -> VB (x > y)+ (BGt, VI x, VI y) -> VB (x > y)+ (BGt, VU x, VU y) -> VB (x > y)+ (BGe, VF x, VF y) -> VB (x >= y)+ (BGe, VI x, VI y) -> VB (x >= y)+ (BGe, VU x, VU y) -> VB (x >= y)+ (BAnd, VB x, VB y) -> VB (x && y)+ (BOr, VB x, VB y) -> VB (x || y)+ (BDot, _, _) -> VF (sum (zipWith (*) (valFloats a) (valFloats b)))+ (BCross, VV3 x1 y1 z1, VV3 x2 y2 z2) ->+ VV3 (y1 * z2 - z1 * y2) (z1 * x2 - x1 * z2) (x1 * y2 - y1 * x2)+ _ -> VF 0++evalTernary :: TriOp -> Val -> Val -> Val -> Val+evalTernary top a b c = case top of+ TMix -> case c of+ VF t -> zipFloatVal (\x y -> x * (1 - t) + y * t) a b+ _ -> a+ TClamp -> case (a, b, c) of+ (VI x, VI lo, VI hi) -> VI (min hi (max lo x))+ (VU x, VU lo, VU hi) -> VU (min hi (max lo x))+ _ ->+ let lo = zipFloatVal max a b+ in zipFloatVal min lo c+ TSmoothstep -> case (a, b, c) of+ (VF e0, VF e1, VF x) ->+ let t = clamp01 ((x - e0) / (e1 - e0))+ in VF (t * t * (3 - 2 * t))+ _ -> VF 0+ TSelect -> case a of+ VB cond -> if cond then b else c+ _ -> c
+ lib/NanoUI/Shader/Internal/IR.hs view
@@ -0,0 +1,348 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE StrictData #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Typed SSA intermediate representation for fragment shaders, with pure+-- structural hash-consing (global value numbering / CSE).+--+-- Every backend emitter (GLSL 150, GLSL ES 300, SPIR-V, MSL) and the CPU+-- reference evaluator consume 'ShaderIR' directly.+module NanoUI.Shader.Internal.IR+ ( NodeId (..)+ , IRType (..)+ , gpuToIRType+ , irTypeComps+ , SysField (..)+ , UnOp (..)+ , BinOp (..)+ , TriOp (..)+ , LoopBody (..)+ , ExprOp (..)+ , ShaderIR (..)+ , IRBuilder+ , emptyIRBuilder+ , runIRBuilder+ , emitNode+ , emitLoop+ , hashShaderIR+ ) where++import Data.Bits (shiftL, xor, (.|.))+import Data.HashMap.Strict (HashMap)+import Data.HashMap.Strict qualified as HM+import Data.Hashable (Hashable (..))+import Data.Int (Int32)+import Data.Vector (Vector)+import Data.Vector qualified as V+import Data.Word (Word32, Word64)+import GHC.Generics (Generic)+import NanoUI.Internal.Uniforms (GpuType (..), UniformField (..))++-- | Index into 'irNodes' (0-based, strictly topologically ordered).+newtype NodeId = NodeId {unNodeId :: Int}+ deriving (Eq, Ord, Show, Generic)+ deriving anyclass (Hashable)++-- | Scalar and vector value types supported in 'ShaderIR'.+data IRType+ = TFloat+ | TInt+ | TUInt+ | TBool+ | TVec2+ | TVec3+ | TVec4+ deriving (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (Hashable)++-- | Map a uniform's 'GpuType' to its 'IRType'.+gpuToIRType :: GpuType -> IRType+gpuToIRType gt = case gt of+ GFloat -> TFloat+ GInt32 -> TInt+ GUInt32 -> TUInt+ GBool -> TBool+ GVec2 -> TVec2+ GVec3 -> TVec3+ GVec4 -> TVec4++-- | Component count of an 'IRType' (1 for scalars, 2..4 for vectors).+irTypeComps :: IRType -> Int+irTypeComps t = case t of+ TFloat -> 1+ TInt -> 1+ TUInt -> 1+ TBool -> 1+ TVec2 -> 2+ TVec3 -> 3+ TVec4 -> 4++-- | Built-in system inputs from the 48-byte uniform header and vertex stage.+data SysField+ = SysRect+ -- ^ @uRect@ (@vec4@): node @(x, y, w, h)@ in logical pixels.+ | SysUvRect+ -- ^ @uUvRect@ (@vec4@): node @(u0, v0, uSpan, vSpan)@ in source target UVs.+ | SysMeta+ -- ^ @uMeta@ (@vec4@): @(dpiScale, cornerRadius, targetW, targetH)@.+ | SysVColor+ -- ^ Interpolated vertex color (@vec4@).+ | SysVUv+ -- ^ Interpolated vertex texture coordinate (@vec2@).+ deriving (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (Hashable)++-- | Unary scalar or componentwise vector operations.+data UnOp+ = UNeg+ | UAbs+ | UFloor+ | UCeil+ | UFract+ | USqrt+ | USin+ | UCos+ | UTan+ | UExp+ | ULog+ | ULog2+ | USign+ | UNot+ | UFloatToInt+ | UIntToFloat+ deriving (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (Hashable)++-- | Binary operations (arithmetic, math, comparisons, vector ops).+data BinOp+ = BAdd+ | BSub+ | BMul+ | BDiv+ | BMod+ | BMin+ | BMax+ | BPow+ | BAtan2+ | BStep+ | BEq+ | BNeq+ | BLt+ | BLe+ | BGt+ | BGe+ | BAnd+ | BOr+ | BDot+ | BCross+ deriving (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (Hashable)++-- | Ternary operations (@mix@, @clamp@, @smoothstep@, branchless @select@).+data TriOp+ = TMix+ | TClamp+ | TSmoothstep+ | TSelect+ deriving (Eq, Ord, Show, Enum, Bounded, Generic)+ deriving anyclass (Hashable)++-- | A self-contained bounded loop body whose SSA nodes may reference+-- 'OpLoopVar', 'OpLoopState', and outer 'NodeId's via 'OpOuterRef'.+data LoopBody = LoopBody+ { lbLoopId :: !Int+ , lbStart :: !Int32+ , lbEnd :: !Int32+ , lbInits :: ![NodeId]+ -- ^ Initial accumulator values from the enclosing scope.+ , lbStateTypes :: ![IRType]+ -- ^ Types of each loop accumulator slot (same length as 'lbInits').+ , lbBodyNodes :: !(Vector (IRType, ExprOp))+ -- ^ Local SSA nodes evaluated on every iteration.+ , lbNextStates :: ![NodeId]+ -- ^ Indices into 'lbBodyNodes' yielding the next iteration's accumulators.+ }+ deriving (Eq, Show, Generic)++instance Hashable LoopBody where+ hashWithSalt s lb =+ s+ `hashWithSalt` lbLoopId lb+ `hashWithSalt` lbStart lb+ `hashWithSalt` lbEnd lb+ `hashWithSalt` lbInits lb+ `hashWithSalt` lbStateTypes lb+ `hashWithSalt` V.toList (lbBodyNodes lb)+ `hashWithSalt` lbNextStates lb++-- | One SSA instruction in 'ShaderIR'. Float literals hash by IEEE 754 bit+-- pattern so @-0.0@ and @0.0@ remain distinct and hashing is exact.+data ExprOp+ = OpLitFloat !Word32+ -- ^ IEEE 754 bit pattern of a 32-bit float literal ('GHC.Float.castFloatToWord32').+ | OpLitInt !Int32+ | OpLitUInt !Word32+ | OpLitBool !Bool+ | OpSys !SysField+ | OpUniform !Int !GpuType+ -- ^ Index into 'irUniforms' and its GPU type.+ | OpConstruct !IRType ![NodeId]+ -- ^ Construct a vector from scalar/vector components (or splat one scalar).+ | OpSwizzle !NodeId ![Int]+ -- ^ Extract 1..4 components (each in @0..3@).+ | OpUnary !UnOp !NodeId+ | OpBinary !BinOp !NodeId !NodeId+ | OpTernary !TriOp !NodeId !NodeId !NodeId+ | OpLength !NodeId+ | OpNormalize !NodeId+ | OpSampleInput !NodeId+ -- ^ Sample @uInput@ at target UV (@TVec2@), returning @TVec4@.+ | OpOuterRef !Int !NodeId+ -- ^ Inside a 'LoopBody', references node 'NodeId' from enclosing scope depth @d@.+ | OpLoopVar !Int+ -- ^ Inside a 'LoopBody', reads the induction variable @i :: TInt@.+ | OpLoopState !Int !Int+ -- ^ Inside a 'LoopBody', reads loop @loopId@'s accumulator slot @k@.+ | OpLoop !LoopBody+ -- ^ Executes a bounded loop and binds its final accumulator tuple.+ | OpLoopResult !NodeId !Int+ -- ^ Projects accumulator slot @k@ from an 'OpLoop' node.+ deriving (Eq, Show, Generic)++instance Hashable ExprOp where+ hashWithSalt s op = case op of+ OpLitFloat w -> s `hashWithSalt` (0 :: Int) `hashWithSalt` w+ OpLitInt n -> s `hashWithSalt` (1 :: Int) `hashWithSalt` n+ OpLitUInt w -> s `hashWithSalt` (2 :: Int) `hashWithSalt` w+ OpLitBool b -> s `hashWithSalt` (3 :: Int) `hashWithSalt` b+ OpSys sf -> s `hashWithSalt` (4 :: Int) `hashWithSalt` sf+ OpUniform idx gt -> s `hashWithSalt` (5 :: Int) `hashWithSalt` idx `hashWithSalt` fromEnum gt+ OpConstruct t args -> s `hashWithSalt` (6 :: Int) `hashWithSalt` t `hashWithSalt` args+ OpSwizzle a cs -> s `hashWithSalt` (7 :: Int) `hashWithSalt` a `hashWithSalt` cs+ OpUnary uo a -> s `hashWithSalt` (8 :: Int) `hashWithSalt` uo `hashWithSalt` a+ OpBinary bo a b -> s `hashWithSalt` (9 :: Int) `hashWithSalt` bo `hashWithSalt` a `hashWithSalt` b+ OpTernary to a b c -> s `hashWithSalt` (10 :: Int) `hashWithSalt` to `hashWithSalt` a `hashWithSalt` b `hashWithSalt` c+ OpLength a -> s `hashWithSalt` (11 :: Int) `hashWithSalt` a+ OpNormalize a -> s `hashWithSalt` (12 :: Int) `hashWithSalt` a+ OpSampleInput a -> s `hashWithSalt` (13 :: Int) `hashWithSalt` a+ OpOuterRef d n -> s `hashWithSalt` (14 :: Int) `hashWithSalt` d `hashWithSalt` n+ OpLoopVar lid -> s `hashWithSalt` (15 :: Int) `hashWithSalt` lid+ OpLoopState lid k -> s `hashWithSalt` (16 :: Int) `hashWithSalt` lid `hashWithSalt` k+ OpLoop lb -> s `hashWithSalt` (17 :: Int) `hashWithSalt` lb+ OpLoopResult n k -> s `hashWithSalt` (18 :: Int) `hashWithSalt` n `hashWithSalt` k++-- | Complete, lowered fragment shader IR ready for code generation or CPU+-- evaluation.+data ShaderIR = ShaderIR+ { irNodes :: !(Vector (IRType, ExprOp))+ -- ^ Topologically ordered SSA nodes.+ , irOutput :: !NodeId+ -- ^ Final output color node (type 'TVec4').+ , irUniforms :: ![UniformField]+ -- ^ Flattened std140 user uniform fields (relative to user block start).+ , irUniformBytes :: !Int+ -- ^ Padded std140 byte count for user uniforms (multiple of 16; 0 for none).+ , irNeedsInput :: !Bool+ -- ^ Whether any instruction samples @uInput@.+ }+ deriving (Eq, Show)++-- | Pure hash-consing SSA DAG builder.+data IRBuilder = IRBuilder+ { irbNodes :: ![(IRType, ExprOp)]+ -- ^ Emitted nodes in reverse order.+ , irbCount :: !Int+ , irbMemo :: !(HashMap (IRType, ExprOp) NodeId)+ -- ^ Structural hash-consing table for global value numbering (CSE).+ , irbNeedsInput :: !Bool+ , irbNextLoopId :: !Int+ }++-- | Start an empty builder.+emptyIRBuilder :: IRBuilder+emptyIRBuilder =+ IRBuilder+ { irbNodes = []+ , irbCount = 0+ , irbMemo = HM.empty+ , irbNeedsInput = False+ , irbNextLoopId = 0+ }++-- | Finalize a builder into a 'ShaderIR'.+runIRBuilder :: [UniformField] -> Int -> IRBuilder -> NodeId -> ShaderIR+runIRBuilder fields uBytes b outId =+ ShaderIR+ { irNodes = V.fromList (reverse (irbNodes b))+ , irOutput = outId+ , irUniforms = fields+ , irUniformBytes = uBytes+ , irNeedsInput = irbNeedsInput b+ }++-- | Emit an SSA node with pure structural hash-consing (CSE).+emitNode :: IRType -> ExprOp -> IRBuilder -> (NodeId, IRBuilder)+emitNode ty op b =+ let !b0 = case op of+ OpSampleInput _ -> b {irbNeedsInput = True}+ _ -> b+ key = (ty, op)+ in case HM.lookup key (irbMemo b0) of+ Just existing -> (existing, b0)+ Nothing ->+ let !nid = NodeId (irbCount b0)+ !b' =+ b0+ { irbNodes = key : irbNodes b0+ , irbCount = irbCount b0 + 1+ , irbMemo = HM.insert key nid (irbMemo b0)+ }+ in (nid, b')++-- | Emit a bounded loop node and allocate its unique loop identifier.+emitLoop ::+ Int32 ->+ Int32 ->+ [NodeId] ->+ [IRType] ->+ (Int -> IRBuilder -> ([NodeId], IRBuilder)) ->+ IRBuilder ->+ (NodeId, IRBuilder)+emitLoop start end inits stateTypes buildBody b =+ let !lid = irbNextLoopId b+ sub0 = emptyIRBuilder {irbNextLoopId = lid + 1}+ (nexts, sub1) = buildBody lid sub0+ lb =+ LoopBody+ { lbLoopId = lid+ , lbStart = start+ , lbEnd = end+ , lbInits = inits+ , lbStateTypes = stateTypes+ , lbBodyNodes = V.fromList (reverse (irbNodes sub1))+ , lbNextStates = nexts+ }+ !b1 =+ b+ { irbNeedsInput = irbNeedsInput b || irbNeedsInput sub1+ , irbNextLoopId = irbNextLoopId sub1+ }+ in emitNode (case stateTypes of (t : _) -> t; [] -> TFloat) (OpLoop lb) b1++-- | Deterministic non-zero 64-bit structural hash of a lowered 'ShaderIR'.+-- Hashing the IR rather than compiled backend strings keeps 'NanoUI.Shader.Raw.ShaderProgram'+-- fields lazy so each backend only compiles the target format it consumes.+hashShaderIR :: ShaderIR -> Word64+hashShaderIR ir =+ let hashWith s =+ s+ `hashWithSalt` irNeedsInput ir+ `hashWithSalt` irUniformBytes ir+ `hashWithSalt` irOutput ir+ `hashWithSalt` [(fromEnum (ufType f), ufOffset f) | f <- irUniforms ir]+ `hashWithSalt` V.toList (irNodes ir)+ !h1 = fromIntegral (hashWith (0x517cc1b7 :: Int)) :: Word64+ !h2 = fromIntegral (hashWith (0x27d4eb2f :: Int)) :: Word64+ !h = (h1 `shiftL` 32) .|. (h2 `xor` (h1 * 0x9e3779b97f4a7c15))+ in if h == 0 then 1 else h
+ lib/NanoUI/Shader/Internal/Swizzle.hs view
@@ -0,0 +1,169 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_HADDOCK not-home #-}++-- | Type-level vector swizzling for @OverloadedRecordDot@ (@v.xy@, @col.bgr@,+-- @v.xyxy@) using GHC 9.10+ 'GHC.TypeLits.UnconsSymbol' and 'GHC.Records.HasField', with+-- custom compile-time 'TypeError' diagnostics and zero Template Haskell.+module NanoUI.Shader.Internal.Swizzle+ ( VecDim+ , SwizzleIndices+ , SwizzleResult+ , KnownIndices (..)+ , Swizzle (..)+ ) where++import Data.Kind (Type)+import Data.Proxy (Proxy (..))+import GHC.TypeLits+ ( ErrorMessage (..)+ , KnownNat+ , Nat+ , Symbol+ , TypeError+ , UnconsSymbol+ , natVal+ , type (<=?)+ )+import NanoUI (V2)+import NanoUI.Internal.Uniforms (V3, V4)++-- | Component dimension of a GPU vector type.+type family VecDim (v :: Type) :: Nat where+ VecDim V2 = 2+ VecDim V3 = 3+ VecDim V4 = 4+ VecDim t =+ TypeError+ ( 'Text "Cannot swizzle value of type "+ ':<>: 'ShowType t+ ':<>: 'Text " (expected V2, V3, or V4)."+ )++-- | Map a swizzle character to @(componentIndex, channelGroup)@, where group 0+-- is @xyzw@ and group 1 is @rgba@.+type family CharComp (c :: Char) :: (Nat, Nat) where+ CharComp 'x' = '(0, 0)+ CharComp 'y' = '(1, 0)+ CharComp 'z' = '(2, 0)+ CharComp 'w' = '(3, 0)+ CharComp 'r' = '(0, 1)+ CharComp 'g' = '(1, 1)+ CharComp 'b' = '(2, 1)+ CharComp 'a' = '(3, 1)+ CharComp c =+ TypeError+ ( 'Text "Invalid swizzle component '"+ ':<>: 'ShowType c+ ':<>: 'Text "' (expected one of x, y, z, w, r, g, b, a)."+ )++-- | Bounds-check a component index against the source vector dimension.+type family CheckBound (dim :: Nat) (idx :: Nat) (c :: Char) :: Nat where+ CheckBound dim idx c = CheckBoundGo (idx <=? dim) dim idx c++type family CheckBoundGo (ok :: Bool) (dim :: Nat) (idx :: Nat) (c :: Char) :: Nat where+ CheckBoundGo 'True dim idx c =+ IfEq idx dim+ ( TypeError+ ( 'Text "Swizzle component '"+ ':<>: 'ShowType c+ ':<>: 'Text "' is out of range for a "+ ':<>: 'ShowType dim+ ':<>: 'Text "-component vector."+ )+ )+ idx+ CheckBoundGo 'False dim _ c =+ TypeError+ ( 'Text "Swizzle component '"+ ':<>: 'ShowType c+ ':<>: 'Text "' is out of range for a "+ ':<>: 'ShowType dim+ ':<>: 'Text "-component vector."+ )++type family IfEq (a :: Nat) (b :: Nat) (yes :: k) (no :: k) :: k where+ IfEq a a yes _ = yes+ IfEq _ _ _ no = no++-- | Ensure all components in a swizzle come from the same channel set+-- (@xyzw@ or @rgba@).+type family CheckGroup (expected :: Nat) (actual :: Nat) (s :: Symbol) :: () where+ CheckGroup g g _ = '()+ CheckGroup _ _ s =+ TypeError+ ( 'Text "Swizzle \""+ ':<>: 'Text s+ ':<>: 'Text "\" mixes xyzw and rgba component sets."+ )++-- | Parse a swizzle 'Symbol' into a list of 1..4 validated component indices.+type family SwizzleIndices (dim :: Nat) (s :: Symbol) :: [Nat] where+ SwizzleIndices dim s = ParseStart dim s (UnconsSymbol s)++type family ParseStart (dim :: Nat) (full :: Symbol) (m :: Maybe (Char, Symbol)) :: [Nat] where+ ParseStart _ full 'Nothing =+ TypeError ('Text "Empty swizzle: " ':<>: 'ShowType full)+ ParseStart dim full ('Just '(c, rest)) =+ ParsePair dim full c (CharComp c) rest++type family ParsePair (dim :: Nat) (full :: Symbol) (c :: Char) (p :: (Nat, Nat)) (rest :: Symbol) :: [Nat] where+ ParsePair dim full c '(idx, grp) rest =+ CheckBound dim idx c ': ParseRest dim full grp (UnconsSymbol rest)++type family ParseRest (dim :: Nat) (full :: Symbol) (grp :: Nat) (m :: Maybe (Char, Symbol)) :: [Nat] where+ ParseRest _ _ _ 'Nothing = '[]+ ParseRest dim full grp ('Just '(c, rest)) =+ ParseRestPair dim full grp c (CharComp c) rest++type family ParseRestPair (dim :: Nat) (full :: Symbol) (grp :: Nat) (c :: Char) (p :: (Nat, Nat)) (rest :: Symbol) :: [Nat] where+ ParseRestPair dim full grp c '(idx, g2) rest =+ SeqUnit (CheckGroup grp g2 full) (CheckBound dim idx c ': ParseRest dim full grp (UnconsSymbol rest))++type family SeqUnit (u :: ()) (x :: k) :: k where+ SeqUnit '() x = x++-- | Result vector/scalar type for a parsed swizzle index list of length 1..4.+type family SwizzleResult (xs :: [Nat]) :: Type where+ SwizzleResult '[_] = Float+ SwizzleResult '[_, _] = V2+ SwizzleResult '[_, _, _] = V3+ SwizzleResult '[_, _, _, _] = V4+ SwizzleResult xs =+ TypeError+ ( 'Text "Swizzle must select 1 to 4 components (got "+ ':<>: 'ShowType xs+ ':<>: 'Text ")."+ )++-- | Reify a type-level list of component indices to runtime @[Int]@.+class KnownIndices (xs :: [Nat]) where+ indicesVal :: Proxy xs -> [Int]++instance KnownIndices '[] where+ indicesVal _ = []++instance (KnownNat x, KnownIndices xs) => KnownIndices (x ': xs) where+ indicesVal _ = fromIntegral (natVal (Proxy @x)) : indicesVal (Proxy @xs)++-- | Helper constraint bundling swizzle validation, result type, and reification.+class (r ~ SwizzleResult (SwizzleIndices (VecDim v) s), KnownIndices (SwizzleIndices (VecDim v) s)) =>+ Swizzle (s :: Symbol) (v :: Type) (r :: Type) where+ swizzleIndices :: Proxy s -> Proxy v -> [Int]++instance+ ( xs ~ SwizzleIndices (VecDim v) s+ , r ~ SwizzleResult xs+ , KnownIndices xs+ ) =>+ Swizzle s v r+ where+ swizzleIndices _ _ = indicesVal (Proxy @xs)
+ nano-ui-shader.cabal view
@@ -0,0 +1,90 @@+cabal-version: 3.4+name: nano-ui-shader+version: 0.2.0.0+synopsis: Typed fragment shader EDSL and multi-target compiler for nano-ui+description:+ A pure-Haskell typed fragment shader EDSL for nano-ui nodes. Author+ surface fills, color effects, distortion warps, and multi-pass layer+ effects once using OverloadedRecordDot swizzles and Generic std140+ uniforms, fuse color/distortion passes algebraically, and compile directly+ to GLSL 150, GLSL ES 300, SPIR-V, MSL, and a CPU reference evaluator.+license: MIT+license-file: LICENSE+author: goolord+maintainer: zacharyachurchill@gmail.com+homepage: https://github.com/goolord/nano-ui+bug-reports: https://github.com/goolord/nano-ui/issues+category: Graphics+build-type: Simple+tested-with: GHC ==9.10.3 || ==9.14.1+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/goolord/nano-ui.git+ subdir: packages/nano-ui-shader++common extensions+ default-language: GHC2024+ default-extensions:+ OverloadedStrings++common warnings+ ghc-options:+ -Wall+ -Wextra+ -Wcompat+ -Widentities+ -Wincomplete-record-updates+ -Wincomplete-uni-patterns+ -Wmissing-export-lists+ -Wmissing-home-modules+ -Wpartial-fields+ -Wredundant-constraints+ -Wunused-packages++library+ import: extensions+ import: warnings+ exposed-modules:+ NanoUI.Shader+ NanoUI.Shader.Expr+ NanoUI.Shader.Compose+ NanoUI.Shader.Effects+ NanoUI.Shader.Internal.IR+ NanoUI.Shader.Internal.Swizzle+ NanoUI.Shader.Internal.Emit.Glsl+ NanoUI.Shader.Internal.Emit.Msl+ NanoUI.Shader.Internal.Emit.Spirv+ NanoUI.Shader.Internal.Eval.Cpu+ other-modules:+ NanoUI.Shader.Internal.Emit.CLike+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ containers >=0.7 && <0.9,+ hashable ^>=1.5,+ nano-ui ^>=0.2,+ primitive ^>=0.9,+ text ^>=2.1,+ unordered-containers ^>=0.2,+ vector ^>=0.13+ hs-source-dirs: lib++test-suite nano-ui-shader-test+ import: extensions+ import: warnings+ type: exitcode-stdio-1.0+ main-is: Main.hs+ if os(windows)+ ghc-options: -optl-mconsole+ build-depends:+ base >=4.20 && <4.23,+ bytestring ^>=0.12,+ nano-ui ^>=0.2,+ nano-ui-shader,+ text ^>=2.1,+ vector ^>=0.13+ hs-source-dirs: test
+ test/Main.hs view
@@ -0,0 +1,304 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedRecordDot #-}++-- | Test suite for @nano-ui-shader@: OverloadedRecordDot swizzling, typed+-- Generic uniform access, CSE, bounded loops, GLSL/MSL/SPIR-V structural+-- validation, algebraic pass fusion, CPU evaluation, and standard effects.+module Main (main) where++import Control.Monad (forM_, when)+import Data.Bits (shiftR, (.&.))+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.Int (Int32)+import Data.Text qualified as T+import Data.Vector qualified as V+import Data.Word (Word32)+import GHC.Generics (Generic)+import NanoUI+ ( Color+ , V2 (..)+ , colorA+ , colorB+ , colorG+ , colorR+ , colorRGBA+ , colorWhite+ )+import NanoUI.Internal.Shader+ ( CpuFragCtx (..)+ , Shader (..)+ , ShaderPass (..)+ , ShaderProgram (..)+ )+import NanoUI.Shader+import NanoUI.Shader.Compose (compileSurfaceIR)+import NanoUI.Shader.Internal.Emit.Glsl (emitGlsl150, emitGlslEs300)+import NanoUI.Shader.Internal.Emit.Msl (emitMsl)+import NanoUI.Shader.Internal.Emit.Spirv (emitSpirvWords)+import NanoUI.Shader.Internal.IR (ShaderIR (..))+import System.Exit (exitFailure)++data InnerUniforms = InnerUniforms+ { iuColor :: !Color+ , iuScale :: !Float+ }+ deriving (Eq, Show, Generic, Uniforms)++data NestedUniforms = NestedUniforms+ { nuInner :: !InnerUniforms+ , nuCount :: !Word32+ }+ deriving (Eq, Show, Generic, Uniforms)++data DemoUniforms = DemoUniforms+ { duTint :: !Color+ , duMix :: !Float+ , duFlag :: !Bool+ , duOffset :: !V2+ , duWeight :: !V3+ , duSteps :: !Int32+ }+ deriving (Eq, Show, Generic, Uniforms)++check :: IORef Int -> String -> Bool -> IO ()+check failed name ok+ | ok = putStrLn ("[PASS] " ++ name)+ | otherwise = do+ putStrLn ("[FAIL] " ++ name)+ modifyIORef' failed (+ 1)++nearByte :: Int -> Int -> Bool+nearByte a b = abs (a - b) <= 2++evalAt :: Shader k u -> u -> V2 -> V2 -> (V2 -> Color) -> Color+evalAt sh u pos@(V2 px py) sz@(V2 sw sh') sampler =+ case shaderCpuEval sh of+ Nothing -> error "missing CPU evaluator"+ Just f ->+ f+ u+ CpuFragCtx+ { cfcUv = V2 (px / max 1 sw) (py / max 1 sh')+ , cfcPos = pos+ , cfcSize = sz+ , cfcScale = 1.0+ , cfcColor = colorWhite+ , cfcCornerRadius = 0.0+ }+ sampler++-- | Structural validator for an emitted SPIR-V 1.0 binary stream.+validateSpirv :: ByteString -> Either String ()+validateSpirv bs+ | BS.length bs < 20 = Left "SPIR-V shorter than 5-word header"+ | BS.length bs `rem` 4 /= 0 = Left "SPIR-V byte length not a multiple of 4"+ | otherwise =+ let ws = unpackWords bs+ in case ws of+ (magic : ver : _gen : bound : schema : body)+ | magic /= 0x07230203 -> Left "bad SPIR-V magic"+ | ver /= 0x00010000 -> Left "unexpected SPIR-V version"+ | bound == 0 -> Left "zero ID bound"+ | schema /= 0 -> Left "non-zero schema word"+ | otherwise -> walkInsts bound False False body+ _ -> Left "truncated SPIR-V header"+ where+ unpackWords b =+ [ let i = k * 4+ b0 = fromIntegral (BS.index b i) :: Word32+ b1 = fromIntegral (BS.index b (i + 1)) :: Word32+ b2 = fromIntegral (BS.index b (i + 2)) :: Word32+ b3 = fromIntegral (BS.index b (i + 3)) :: Word32+ in b0 + b1 * 256 + b2 * 65536 + b3 * 16777216+ | k <- [0 .. BS.length b `quot` 4 - 1]+ ]+ walkInsts _ sawEntry sawEnd []+ | not sawEntry = Left "missing OpEntryPoint"+ | not sawEnd = Left "missing OpFunctionEnd"+ | otherwise = Right ()+ walkInsts bound sawEntry sawEnd (hdr : rest) =+ let wc = fromIntegral (hdr `shiftR` 16) :: Int+ op = hdr .&. 0xFFFF+ in if wc < 1 || wc - 1 > length rest+ then Left ("invalid instruction word count " ++ show wc ++ " for opcode " ++ show op)+ else+ let (_ops, next) = splitAt (wc - 1) rest+ sawEntry' = sawEntry || op == 15+ sawEnd' = sawEnd || op == 56+ in walkInsts bound sawEntry' sawEnd' next++checkAllTargets :: IORef Int -> String -> Shader k u -> IO ()+checkAllTargets failed label sh = do+ let passes = shaderPasses sh+ check failed (label ++ ": non-empty passes") (not (null passes))+ forM_ (zip [1 :: Int ..] passes) $ \(i, p) -> do+ let prog = spProgram p+ tag = label ++ " pass " ++ show i+ check failed (tag ++ ": GLSL 150 header") $+ maybe False ("#version 150" `T.isPrefixOf`) (spGlsl150 prog)+ check failed (tag ++ ": GLSL ES 300 header") $+ maybe False ("#version 300 es" `T.isPrefixOf`) (spGlslEs300 prog)+ check failed (tag ++ ": MSL main0") $+ maybe False ("fragment float4 main0" `T.isInfixOf`) (spMsl prog)+ case spSpirv prog of+ Nothing -> check failed (tag ++ ": SPIR-V present") False+ Just spv -> case validateSpirv spv of+ Right () -> check failed (tag ++ ": SPIR-V valid") True+ Left err -> do+ putStrLn (" SPIR-V error (" ++ tag ++ "): " ++ err)+ check failed (tag ++ ": SPIR-V valid") False++main :: IO ()+main = do+ failed <- newIORef (0 :: Int)++ -- 1. Swizzle + Generic Uniform record + branchless select+ let customSurf :: Shader 'Surface DemoUniforms+ customSurf = surfaceShader $ \u ctx ->+ let uv = ctx.uv.xy+ flipped = uv.yx+ cRgb = selectE u.duFlag u.duTint.rgb u.duTint.bgr+ k = clamp01E (u.duMix + flipped.x * floatE 0.0 + u.duOffset.x * floatE 0.0 + u.duWeight.z * floatE 0.0 + intToFloat u.duSteps * floatE 0.0)+ in vec4_31 (cRgb *^ k) (floatE 1.0)+ checkAllTargets failed "customSurf" customSurf+ let u1 = DemoUniforms (colorRGBA 200 100 50 255) 0.5 True (V2 1 2) (V3 0 0 0) 0+ u2 = u1 {duFlag = False}+ c1 = evalAt customSurf u1 (V2 10 10) (V2 100 100) (const colorWhite)+ c2 = evalAt customSurf u2 (V2 10 10) (V2 100 100) (const colorWhite)+ check failed "swizzle .rgb + select True" $+ nearByte 100 (fromIntegral (colorR c1))+ && nearByte 50 (fromIntegral (colorG c1))+ && nearByte 25 (fromIntegral (colorB c1))+ check failed "swizzle .bgr + select False" $+ nearByte 25 (fromIntegral (colorR c2))+ && nearByte 50 (fromIntegral (colorG c2))+ && nearByte 100 (fromIntegral (colorB c2))++ -- 2. CSE / structural hash-consing collapses duplicate subexpressions+ let irOnce = compileSurfaceIR @() (\_ ctx -> pure (vec4_22 ctx.uv ctx.uv))+ irDup = compileSurfaceIR @() (\_ ctx -> let a = ctx.uv + ctx.uv; b = ctx.uv + ctx.uv in pure (vec4_22 a b))+ irSingle = compileSurfaceIR @() (\_ ctx -> let a = ctx.uv + ctx.uv in pure (vec4_22 a a))+ check failed "CSE collapses duplicate expressions" (V.length (irNodes irDup) == V.length (irNodes irSingle))+ check failed "compileSurfaceIR emits GLSL/MSL/SPIR-V" $+ T.isInfixOf "NanoShaderBlock" (emitGlsl150 irOnce)+ && T.isInfixOf "NanoShaderBlock" (emitGlslEs300 irOnce)+ && T.isInfixOf "NanoShaderBlock" (emitMsl irOnce)+ && length (emitSpirvWords irOnce) > 20++ -- 3. Algebraic fusion pass counts & semantics+ let grayTint = composeColor grayscale tint+ tripleColor = composeColor grayTint vignette+ doubleDistort = composeDistort waveDistort pixelate+ warpAndGray = distortThenColor waveDistort grayscale+ check failed "composeColor fuses into 1 GPU pass" (length (shaderPasses grayTint) == 1)+ check failed "triple composeColor fuses into 1 GPU pass" (length (shaderPasses tripleColor) == 1)+ check failed "composeDistort fuses into 1 GPU pass" (length (shaderPasses doubleDistort) == 1)+ check failed "distortThenColor fuses into 1 GPU pass" (length (shaderPasses warpAndGray) == 1)+ check failed "gaussianBlur uses 2 separable passes" (length (shaderPasses gaussianBlur) == 2)+ checkAllTargets failed "composeColor(grayscale, tint)" grayTint+ checkAllTargets failed "distortThenColor(wave, grayscale)" warpAndGray++ let srcCol = colorRGBA 200 100 0 255+ tp = TintParams (colorRGBA 0 0 255 255) 0.5+ fusedPx = evalAt grayTint (1.0, tp) (V2 50 50) (V2 100 100) (const srcCol)+ step1 = evalAt grayscale 1.0 (V2 50 50) (V2 100 100) (const srcCol)+ step2 = evalAt tint tp (V2 50 50) (V2 100 100) (const step1)+ check failed "fused composeColor matches sequential CPU evaluation" $+ nearByte (fromIntegral (colorR fusedPx)) (fromIntegral (colorR step2))+ && nearByte (fromIntegral (colorG fusedPx)) (fromIntegral (colorG step2))+ && nearByte (fromIntegral (colorB fusedPx)) (fromIntegral (colorB step2))+ && nearByte (fromIntegral (colorA fusedPx)) (fromIntegral (colorA step2))++ -- 4. Standard library compilation + SPIR-V validation + SVG opacity hook+ checkAllTargets failed "meshGradient4" meshGradient4+ checkAllTargets failed "radialGlow" radialGlow+ checkAllTargets failed "sdfRoundedBox" sdfRoundedBox+ checkAllTargets failed "colorWheelHsv" colorWheelHsv+ checkAllTargets failed "noiseGrain" noiseGrain+ checkAllTargets failed "checkerboard" checkerboard+ checkAllTargets failed "groupOpacity" groupOpacity+ checkAllTargets failed "grayscale" grayscale+ checkAllTargets failed "tint" tint+ checkAllTargets failed "brightnessContrast" brightnessContrast+ checkAllTargets failed "colorMatrix" colorMatrix+ checkAllTargets failed "vignette" vignette+ checkAllTargets failed "scanlines" scanlines+ checkAllTargets failed "waveDistort" waveDistort+ checkAllTargets failed "rippleDistort" rippleDistort+ checkAllTargets failed "pixelate" pixelate+ checkAllTargets failed "boxBlur" boxBlur+ checkAllTargets failed "gaussianBlur" gaussianBlur+ checkAllTargets failed "dropShadow" dropShadow+ checkAllTargets failed "outerGlow" outerGlow+ checkAllTargets failed "chromaticAberration" chromaticAberration++ check failed "groupOpacity provides shaderSvgOpacity" $+ case shaderSvgOpacity groupOpacity of+ Just f -> abs (f 0.4 - 0.4) < 1e-4+ Nothing -> False++ -- 5. Bounded loop CPU sanity: boxBlur of uniform green stays uniform green+ let green = colorRGBA 40 200 80 255+ blurred = evalAt boxBlur 4.0 (V2 50 50) (V2 100 100) (const green)+ check failed "boxBlur preserves constant color" $+ nearByte 40 (fromIntegral (colorR blurred))+ && nearByte 200 (fromIntegral (colorG blurred))+ && nearByte 80 (fromIntegral (colorB blurred))+ && nearByte 255 (fromIntegral (colorA blurred))++ let gBlurred = evalAt gaussianBlur 3.0 (V2 50 50) (V2 100 100) (const green)+ check failed "gaussianBlur preserves constant color" $+ nearByte 40 (fromIntegral (colorR gBlurred))+ && nearByte 200 (fromIntegral (colorG gBlurred))+ && nearByte 80 (fromIntegral (colorB gBlurred))+ && nearByte 255 (fromIntegral (colorA gBlurred))++ -- 6. Multi-pass gaussianBlur actually blurs a step edge on CPU (verifies cfcUv propagation)+ let stepImg (V2 px py) =+ if px < 50 && py < 50 then colorRGBA 255 0 0 255 else colorRGBA 0 0 0 255+ stepEdge = evalAt gaussianBlur 4.0 (V2 50 50) (V2 100 100) stepImg+ check failed ("gaussianBlur blurs 2D step edge on CPU (" ++ show (colorR stepEdge) ++ ")") $+ colorR stepEdge > 20 && colorR stepEdge < 200++ -- 7. Scalar-times-vector (^*), Word32 uniforms, nested Generic records, and 3-tuples+ let nestedSh :: Shader 'Surface NestedUniforms+ nestedSh = surfaceShader $ \u _ ->+ let scaled = u.nuInner.iuScale ^* u.nuInner.iuColor.rgb+ clamped = clampE (u.nuCount + uintE 1) (uintE 0) (uintE 10)+ hi = clamped .> uintE 2+ rgb = selectE hi scaled (vec3 0 0 0)+ in vec4_31 rgb 1.0+ checkAllTargets failed "nested + Word32 + (^*) shader" nestedSh+ let nVal = NestedUniforms (InnerUniforms (colorRGBA 200 100 40 255) 0.5) 3+ nPx = evalAt nestedSh nVal (V2 10 10) (V2 50 50) (const colorWhite)+ check failed "nested record + (^*) + Word32 CPU eval" $+ nearByte 100 (fromIntegral (colorR nPx))+ && nearByte 50 (fromIntegral (colorG nPx))+ && nearByte 20 (fromIntegral (colorB nPx))++ let tripleSh :: Shader 'Surface (Float, Float, Float)+ tripleSh = surfaceShader $ \u _ ->+ vec4 (uVal (uFst3 u)) (uVal (uSnd3 u)) (uVal (uThd3 u)) 1.0+ checkAllTargets failed "3-tuple uniform shader" tripleSh+ let tPx = evalAt tripleSh (0.2, 0.4, 0.8) (V2 5 5) (V2 10 10) (const colorWhite)+ check failed "3-tuple uniform CPU eval" $+ nearByte 51 (fromIntegral (colorR tPx))+ && nearByte 102 (fromIntegral (colorG tPx))+ && nearByte 204 (fromIntegral (colorB tPx))++ -- 8. GLSL/MSL emitters include premultiplied-alpha un-premultiply helper+ let (glslBlur, mslBlur) = case shaderPasses boxBlur of+ (p : _) -> (maybe "" id (spGlsl150 (spProgram p)), maybe "" id (spMsl (spProgram p)))+ [] -> ("", "")+ check failed "GLSL un-premultiplies uInput samples" ("nanoSampleInput(" `T.isInfixOf` glslBlur)+ check failed "MSL un-premultiplies uInput samples" ("nanoSampleInput(" `T.isInfixOf` mslBlur)++ n <- readIORef failed+ when (n > 0) $ do+ putStrLn (show n ++ " check(s) failed.")+ exitFailure+ putStrLn "All nano-ui-shader checks passed."