packages feed

nano-ui-0.2.0.0: lib/NanoUI/Internal/Draw/Shapes.hs

{-# LANGUAGE StrictData #-}

-- | Solid geometry emitters: rects, gradients, images, rounded fills and
-- borders, coverage-AA strokes, lines and triangles.
module NanoUI.Internal.Draw.Shapes
  ( pushRect
  , pushQuadGradient
  , pushImage
  , pushImageRotated
  , pushRoundedRect
  , pushRoundedRectRaw
  , pushRoundedStroke
  , pushCircle
  , pushCircleStroke
  , pushLine
  , pushStrokeAA
  , pushStroke
  , pushFilledTriangle
  , pushPolygonAA
  , pushPolylineAA
  , points3
  ) where

import Control.Monad (when)
import Data.IORef (readIORef)
import Data.Primitive.PrimArray (PrimArray, indexPrimArray, newPrimArray, primArrayFromListN, runPrimArray, sizeofPrimArray, writePrimArray)
import Data.Word (Word32, Word8)
import Foreign.Ptr (Ptr)
import Foreign.Storable (pokeByteOff)
import NanoUI.Internal.Draw.Arena
import NanoUI.Internal.Draw.Types (DrawArena (..), DrawOp (..), LineCap (..), LineJoin (..), Shade (..), glyphAtlasTextureId, indexSize, quadPolygon, shiftDrawOp, vertexSize)
import NanoUI.Internal.Path (idealArcSteps, miterOffset, shoelace)
import NanoUI.Internal.SIMD
import NanoUI.Internal.Types (Color (..), Rect (..), clamp, finite, forUpTo_, onGrid)

{-# INLINE pushRect #-}
pushRect :: DrawArena -> Rect -> Color -> IO ()
pushRect da rect col =
  snapRectOrigin da rect >>= \r -> pushRectRaw da r col

{-# INLINE pushRectRaw #-}
pushRectRaw :: DrawArena -> Rect -> Color -> IO ()
pushRectRaw da r@(Rect _ _ w h) col
  | w <= 0 || h <= 0 = pure ()
  | otherwise = do
      recordOp da (FillRect r col)
      setTexture da glyphAtlasTextureId
      pushQuad da r whitePixel whitePixel whitePixel whitePixel col

-- Quad with a color per corner. GPU interpolates across the two triangles.
-- Corners: top-left, top-right, bottom-right, bottom-left.
pushQuadGradient :: DrawArena -> Rect -> Color -> Color -> Color -> Color -> IO ()
pushQuadGradient da rect@(Rect _ _ w h) tl tr br bl
  | w <= 0 || h <= 0 = pure ()
  | otherwise = do
      Rect px py _ _ <- snapRectOrigin da rect
      recordOp da (FillQuadGradient (Rect px py w h) tl tr br bl)
      setTexture da glyphAtlasTextureId
      let !c0 = unpackColorF tl
          !c1 = unpackColorF tr
          !c2 = unpackColorF br
          !c3 = unpackColorF bl
      withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->
        pokeQuadGradientSIMD vp vOff ip iOff px py w h whitePixel whitePixel c0 c1 c2 c3 baseIdxWord

{-# INLINE pushImage #-}
pushImage :: DrawArena -> Rect -> Int -> Float -> Float -> Float -> Float -> Color -> IO ()
pushImage da rect tex u0 v0 u1 v1 col
  | tex <= 0 = pushRect da rect col
  | otherwise = do
      r <- snapRectOrigin da rect
      setTexture da tex
      pushQuad da r u0 v0 u1 v1 col

-- | 'pushImage' rotated @angle@ radians clockwise about the rect's centre.
-- Not snapped to the pixel grid.
pushImageRotated :: DrawArena -> Rect -> Float -> Int -> Float -> Float -> Float -> Float -> Color -> IO ()
pushImageRotated da (Rect x y w h) angle tex0 u0 v0 u1 v1 col = do
  -- No texture: sample the white pixel, as 'pushRect' does.
  let (!tex, !tu0, !tv0, !tu1, !tv1)
        | tex0 <= 0 = (glyphAtlasTextureId, whitePixel, whitePixel, whitePixel, whitePixel)
        | otherwise = (tex0, u0, v0, u1, v1)
      !(r, g, b, a) = unpackColorF col
      !c = cos angle
      !s = sin angle
      !cx = x + w / 2
      !cy = y + h / 2
      !hw = w / 2
      !hh = h / 2
      -- Rotated corners clockwise from top-left.
      cornerX dx dy = cx + dx * c - dy * s
      cornerY dx dy = cy + dx * s + dy * c
      !x0 = cornerX (-hw) (-hh)
      !y0 = cornerY (-hw) (-hh)
      !x1 = cornerX hw (-hh)
      !y1 = cornerY hw (-hh)
      !x2 = cornerX hw hh
      !y2 = cornerY hw hh
      !x3 = cornerX (-hw) hh
      !y3 = cornerY (-hw) hh
  -- A solid quad records as a shape; an image records as itself
  -- ('NanoUI.Internal.Draw.pushImageOp').
  when (tex0 <= 0) $
    recordOp da $ quadPolygon (primArrayFromListN 8 [x0, y0, x1, y1, x2, y2, x3, y3]) (Flat col)
  setTexture da tex
  withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord ->
    pokeQuadCornersSIMD vp vOff ip iOff x0 y0 x1 y1 x2 y2 x3 y3
      tu0
      tv0
      tu1
      tv1
      r
      g
      b
      a
      baseIdxWord

-- 4 segments per 90° arc, so 'cornerCosSin' has 5 points per quadrant.
cornerSegments :: Int
cornerSegments = 4

-- | How far a stroked arc fades out either side of its solid part, in
-- pixels. A quad's alpha is interpolated across it and read at the middle of
-- each pixel, so a straight side, snapped to the grid, is read at the line's
-- own alpha and comes out at full strength. An arc is not on the grid and
-- never can be: its curve passes between the pixels, and each one is read
-- some way down the fade. A whole pixel of fade on each side, with no solid
-- part between them, leaves the brightest pixel of a hairline arc at about
-- three quarters of the colour the straight sides it joins are drawn in, so
-- a rounded corner reads lighter than its own edges. Half a pixel, with the
-- rest of the width left solid, spends the same ink over a narrower band and
-- gives the pixels nearest the curve the whole of it.
arcFeather :: Float
arcFeather = 0.5

-- | Precomputed unit-circle cos/sin of point @seg@ of rounded-rect corner @q@
-- (top left, then clockwise): each corner's arc is the one before it turned a
-- quarter.
{-# INLINE cornerCosSin #-}
cornerCosSin :: Int -> Int -> (Float, Float)
cornerCosSin q seg =
  case q of
    0 -> (-c, -s)
    1 -> (s, -c)
    2 -> (c, s)
    _ -> (-s, c)
  where
    (c, s) = case seg of
      0 -> (1.0, 0.0)
      1 -> (0.9238795325, 0.3826834324)
      2 -> (0.7071067812, 0.7071067812)
      3 -> (0.3826834324, 0.9238795325)
      _ -> (0.0, 1.0)

-- | Poke one coverage-AA strip with unit normal @(nx, ny)@ into a reservation
-- at vertex offset @vi@ and index offset @ii@ (both relative to @base@/@baseIdx@).
-- Out of line as a top-level worker so 'pushRoundedStrokeRaw' stays small
-- enough for GHC to keep 'concentricOffsetsSIMD' unboxed with zero heap
-- allocation.
{-# NOINLINE pokeStripAt #-}
pokeStripAt ::
  Ptr Word8 ->
  Ptr Word8 ->
  Int ->
  Int ->
  Int ->
  Int ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  Float ->
  IO ()
pokeStripAt !vp !ip !base !baseIdx !vi !ii !x0 !y0 !x1 !y1 !nx !ny !bw !r !g !b !a = do
  let !half = bw * 0.5
      !core = max 0 (half - 0.5)
      !outer = half + 0.5
      !va = fromIntegral (base + vi) :: Word32
  pokeBandVerts vp ((base + vi) * vertexSize) True r g b a $
    concentricOffsetsSIMD x0 y0 nx ny (-outer) (-core) core outer
  pokeBandVerts vp ((base + vi + 4) * vertexSize) True r g b a $
    concentricOffsetsSIMD x1 y1 nx ny (-outer) (-core) core outer
  pokeBandIndices ip ((baseIdx + ii) * indexSize) True va (va + 4)

-- | Poke one cross-section of a coverage-AA band at byte offset @vBase@: four
-- points clear, solid, solid, clear, or with @hasCore@ off three, the two
-- solid ones sharing the second point.
{-# INLINE pokeBandVerts #-}
pokeBandVerts ::
  Ptr Word8 ->
  Int ->
  Bool ->
  Float ->
  Float ->
  Float ->
  Float ->
  ((Float, Float), (Float, Float), (Float, Float), (Float, Float)) ->
  IO ()
pokeBandVerts vp vBase hasCore r g b a ((p0x, p0y), (p1x, p1y), (p2x, p2y), (p3x, p3y)) = do
  pokeVertexSIMD vp vBase p0x p0y r g b 0 whitePixel whitePixel
  pokeVertexSIMD vp (vBase + 32) p1x p1y r g b a whitePixel whitePixel
  when hasCore $
    pokeVertexSIMD vp (vBase + 64) p2x p2y r g b a whitePixel whitePixel
  pokeVertexSIMD vp (vBase + if hasCore then 96 else 64) p3x p3y r g b 0 whitePixel whitePixel

-- | Index the quads between two 'pokeBandVerts' cross-sections starting at
-- vertices @va@ and @vb@, at byte offset @iOff@: three quads, or two without
-- @hasCore@.
{-# INLINE pokeBandIndices #-}
pokeBandIndices :: Ptr Word8 -> Int -> Bool -> Word32 -> Word32 -> IO ()
pokeBandIndices ip iOff hasCore va vb = do
  pokeQuadIndices ip iOff va (va + 1) (vb + 1) vb
  pokeQuadIndices ip (iOff + 24) (va + 1) (va + 2) (vb + 2) (vb + 1)
  when hasCore $
    pokeQuadIndices ip (iOff + 48) (va + 2) (va + 3) (vb + 3) (vb + 2)

{-# INLINE pushRoundedRect #-}
pushRoundedRect :: DrawArena -> Rect -> Float -> Color -> IO ()
pushRoundedRect da rect radius col =
  snapRectOrigin da rect >>= \r -> pushRoundedRectRaw da r radius col

-- | Unsnapped variant used when the rect is already anchored to the snapped
-- device pixel grid, e.g. a mark that must stay concentric with a border that
-- has already snapped its own origin. Re-snapping here would round the
-- off-origin inset (delta = (box - mark)/2) away, and since absolute snapping
-- rides on the fractional part of the widget position the mark would drift
-- off-center by up to a pixel as the widget scrolls.
-- Keep the fused emitter out of its many paint callers: inlining it duplicates
-- the corner loops and increases instruction-cache pressure substantially.
{-# NOINLINE pushRoundedRectRaw #-}
pushRoundedRectRaw :: DrawArena -> Rect -> Float -> Color -> IO ()
pushRoundedRectRaw da (Rect x y w h) radius col
  | w <= 0 || h <= 0 = pure ()
  | otherwise = do
      square <- readIORef (daSquareGeometry da)
      let !rad = min (max 0 radius) (min (w * 0.5) (h * 0.5))
      if square || rad <= 0.5
        then pushRectRaw da (Rect x y w h) col
        else do
          recordOp da (FillRoundedRect (Rect x y w h) rad col)
          setTexture da glyphAtlasTextureId
          let !segs = cornerSegments
              !ring = segs + 1
              !midW = max 0 (w - 2 * rad)
              !midH = max 0 (h - 2 * rad)
              !hasCenter = midW > 0 && midH > 0
              !hasTB = midW > 0
              !hasLR = midH > 0
              !quadCount =
                (if hasCenter then 1 else 0)
                  + (if hasTB then 2 else 0)
                  + (if hasLR then 2 else 0)
              !cornerV = 1 + 2 * ring
              !cornerI = segs * 9
              !needV = quadCount * 4 + 4 * cornerV
              !needI = quadCount * 6 + 4 * cornerI
          (!vp, !ip, !base, !baseIdx) <- reserveRaw da needV needI
          let !(cr, cg, cb, ca) = unpackColorF col
              !u = whitePixel
              pokeQuadAt !vi !ii !qx !qy !qw !qh =
                pokeQuadSIMD
                  vp
                  ((base + vi) * vertexSize)
                  ip
                  ((baseIdx + ii) * indexSize)
                  qx
                  qy
                  qw
                  qh
                  u
                  u
                  u
                  u
                  cr
                  cg
                  cb
                  ca
                  (fromIntegral (base + vi))
              !vi1 = if hasCenter then 4 else 0
              !ii1 = if hasCenter then 6 else 0
              !vi2 = vi1 + (if hasTB then 8 else 0)
              !ii2 = ii1 + (if hasTB then 12 else 0)
              !vi3 = vi2 + (if hasLR then 8 else 0)
              !ii3 = ii2 + (if hasLR then 12 else 0)
          when hasCenter $ pokeQuadAt 0 0 (x + rad) (y + rad) midW midH
          when hasTB $ do
            pokeQuadAt vi1 ii1 (x + rad) y midW rad
            pokeQuadAt (vi1 + 4) (ii1 + 6) (x + rad) (y + h - rad) midW rad
          when hasLR $ do
            pokeQuadAt vi2 ii2 x (y + rad) rad midH
            pokeQuadAt (vi2 + 4) (ii2 + 6) (x + w - rad) (y + rad) rad midH
          pokeCornerTop vp ip base baseIdx rad cr cg cb ca vi3 ii3 (x + rad) (y + rad) 0
          pokeCornerTop vp ip base baseIdx rad cr cg cb ca (vi3 + cornerV) (ii3 + cornerI) (x + w - rad) (y + rad) 1
          pokeCornerTop vp ip base baseIdx rad cr cg cb ca (vi3 + 2 * cornerV) (ii3 + 2 * cornerI) (x + w - rad) (y + h - rad) 2
          pokeCornerTop vp ip base baseIdx rad cr cg cb ca (vi3 + 3 * cornerV) (ii3 + 3 * cornerI) (x + rad) (y + h - rad) 3
          commitRaw da base baseIdx needV needI

-- | One corner of a rounded fill: a fan from the corner centre to the rim
-- and a feathered fringe outside it, as a top-level worker so the fill
-- allocates no closure for it.
{-# NOINLINE pokeCornerTop #-}
pokeCornerTop :: Ptr Word8 -> Ptr Word8 -> Int -> Int -> Float -> Float -> Float -> Float -> Float -> Int -> Int -> Float -> Float -> Int -> IO ()
pokeCornerTop !vp !ip !base !baseIdx !rad !cr !cg !cb !ca !vi !ii !ccx !ccy !q = do
  let !segs = cornerSegments
      !ring = segs + 1
      !u = whitePixel
      !vBase = (base + vi) * vertexSize
      !centerIdx = fromIntegral (base + vi) :: Word32
      !inRad = max 0 (rad - 1.0)
  pokeVertexSIMD vp vBase ccx ccy cr cg cb ca u u
  forUpTo_ (segs + 1) $ \i -> do
    let !(ct, st) = cornerCosSin q i
        !rimI = base + vi + 1 + i
        !outI = base + vi + 1 + ring + i
    pokeVertexSIMD vp (rimI * vertexSize) (ccx + inRad * ct) (ccy + inRad * st) cr cg cb ca u u
    pokeVertexSIMD vp (outI * vertexSize) (ccx + rad * ct) (ccy + rad * st) cr cg cb 0 u u
    when (i > 0) $ do
      let !k = i - 1
          !rim0 = fromIntegral (base + vi + i) :: Word32
          !rim1 = fromIntegral (base + vi + 1 + i) :: Word32
          !out0 = fromIntegral (base + vi + 1 + ring + k) :: Word32
          !out1 = fromIntegral (base + vi + 1 + ring + i) :: Word32
          !fillOff = (baseIdx + ii + k * 3) * indexSize
          !fringeOff = (baseIdx + ii + segs * 3 + k * 6) * indexSize
      pokeByteOff ip fillOff centerIdx
      pokeByteOff ip (fillOff + 4) rim0
      pokeByteOff ip (fillOff + 8) rim1
      pokeQuadIndices ip fringeOff rim0 out0 out1 rim1

-- | A filled circle. The centre snaps to the device pixel grid, not the
-- bounding box's origin: snapping the origin rounds @cx - radius@, so two
-- circles sharing a centre but not a radius would land up to a pixel apart.
{-# INLINE pushCircle #-}
pushCircle :: DrawArena -> Float -> Float -> Float -> Color -> IO ()
pushCircle da cx cy radius col = do
  s <- readIORef (daSnapScale da)
  pushRoundedRectRaw da (circleBox (onGrid s cx) (onGrid s cy) radius) radius col

-- | A circle's outline, its centre snapped as 'pushCircle' snaps it.
{-# INLINE pushCircleStroke #-}
pushCircleStroke :: DrawArena -> Float -> Float -> Float -> Float -> Color -> IO ()
pushCircleStroke da cx cy radius bw col = do
  s <- readIORef (daSnapScale da)
  pushRoundedStrokeRaw da (circleBox (onGrid s cx) (onGrid s cy) radius) radius bw col

circleBox :: Float -> Float -> Float -> Rect
circleBox cx cy radius = Rect (cx - radius) (cy - radius) (2 * radius) (2 * radius)

{-# INLINE pushRoundedStroke #-}
pushRoundedStroke :: DrawArena -> Rect -> Float -> Float -> Color -> IO ()
pushRoundedStroke da rect radius bw col =
  snapRectOrigin da rect >>= \r -> pushRoundedStrokeRaw da r radius bw col

-- | 'pushRoundedStroke' without snapping the origin, for a rect already
-- anchored to the grid; see 'pushRoundedRectRaw'.
{-# NOINLINE pushRoundedStrokeRaw #-}
pushRoundedStrokeRaw :: DrawArena -> Rect -> Float -> Float -> Color -> IO ()
pushRoundedStrokeRaw da (Rect px py w h) radius bw col
  | w <= 0 || h <= 0 || bw <= 0 = pure ()
  | otherwise = do
      setTexture da glyphAtlasTextureId
      square <- readIORef (daSquareGeometry da)
      let !rad = min (max 0 radius) (min (w * 0.5) (h * 0.5))
          !ibw = min bw (min (w * 0.5) (h * 0.5))
      if square
        then pushSquareStroke da px py w h ibw col
        else do
          recordOp da (StrokeRoundedRect (Rect px py w h) rad ibw col)
          let !n = cornerSegments
              -- With square corners the top and bottom run the full width
              -- and the sides fit between them, so each corner is drawn once
              -- (sides meeting at their centre lines would leave its outer
              -- quarter bare and draw the inner one twice); rounded ones end
              -- the sides where the arcs start. A border wider than the
              -- radius fits its sides between the top and bottom too, and a
              -- quad fills the band this leaves beside each arc.
              !corners = rad > 0.5
              !bands = corners && ibw > rad
              !topY = py + ibw / 2
              !leftX = px + ibw / 2
              !x0 = if corners then px + rad else px
              !y0 = if corners && not bands then py + rad else py + ibw
              !midW = max 0 (if corners then w - 2 * rad else w)
              !midH = max 0 (if corners && not bands then h - 2 * rad else h - 2 * ibw)
              !botY = py + h - ibw / 2
              !rightX = px + w - ibw / 2

              !cr = rad - ibw / 2
              !doTB = midW >= 0.001
              !doLR = midH >= 0.001
              !stripCount = (if doTB then 2 else 0) + (if doLR then 2 else 0)
              -- A stroke no wider than the feather has coincident inner/outer
              -- core rings. Share that ring and omit its zero-area triangles
              -- instead of submitting a fourth vertex and a third quad for
              -- every arc segment. A one-pixel hairline has a solid core now
              -- and takes the four-vertex path.
              !core = max 0 ((ibw - arcFeather) * 0.5)
              !hasCore = core > 0
              !arcStride = if hasCore then 4 else 3
              !arcIndices = if hasCore then 18 else 12
              !arcV = (n + 1) * arcStride
              !arcI = n * arcIndices
              !needV = stripCount * 8 + (if corners then 4 * arcV else 0) + (if bands then 16 else 0)
              !needI = stripCount * 18 + (if corners then 4 * arcI else 0) + (if bands then 24 else 0)
          (!vp, !ip, !base, !baseIdx) <- reserveRaw da needV needI
          let !(r, g, b, a) = unpackColorF col
              !viLR = if doTB then 16 else 0
              !iiLR = if doTB then 36 else 0
              !viC = stripCount * 8
              !iiC = stripCount * 18
              !solidCenter = ibw >= rad - 1.0e-4
              !inner = if solidCenter then 0 else max 0 (cr - core)
              !outerR = cr + core
              !innerAA = if solidCenter then 0 else max 0 (inner - arcFeather)
              !outerAA = outerR + arcFeather
          when doTB $ do
            pokeStripAt vp ip base baseIdx 0 0 x0 topY (x0 + midW) topY 0 1 ibw r g b a
            pokeStripAt vp ip base baseIdx 8 18 x0 botY (x0 + midW) botY 0 1 ibw r g b a
          when doLR $ do
            pokeStripAt vp ip base baseIdx viLR iiLR leftX y0 leftX (y0 + midH) (-1) 0 ibw r g b a
            pokeStripAt vp ip base baseIdx (viLR + 8) (iiLR + 18) rightX y0 rightX (y0 + midH) (-1) 0 ibw r g b a
          when corners $ do
            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a viC iiC (px + rad) (py + rad) 0
            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a (viC + arcV) (iiC + arcI) (px + w - rad) (py + rad) 1
            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a (viC + 2 * arcV) (iiC + 2 * arcI) (px + w - rad) (py + h - rad) 2
            pokeArcTop vp ip base baseIdx hasCore innerAA inner outerR outerAA r g b a (viC + 3 * arcV) (iiC + 3 * arcI) (px + rad) (py + h - rad) 3
          when bands $ do
            let band !k !bx !by =
                  let !vi = base + viC + 4 * arcV + 4 * k
                   in pokeQuadSIMD vp (vi * vertexSize) ip ((baseIdx + iiC + 4 * arcI + 6 * k) * indexSize) bx by rad (ibw - rad) whitePixel whitePixel whitePixel whitePixel r g b a (fromIntegral vi)
            band 0 px (py + rad)
            band 1 (px + w - rad) (py + rad)
            band 2 (px + w - rad) (py + h - ibw)
            band 3 px (py + h - ibw)
          commitRaw da base baseIdx needV needI

-- | One corner arc of a rounded stroke, as a top-level worker so the stroke
-- allocates no closure for it.
{-# NOINLINE pokeArcTop #-}
pokeArcTop :: Ptr Word8 -> Ptr Word8 -> Int -> Int -> Bool -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Float -> Int -> Int -> Float -> Float -> Int -> IO ()
pokeArcTop !vp !ip !base !baseIdx !hasCore !innerAA !inner !outerR !outerAA !r !g !b !a !vi !ii !ccx !ccy !q = do
  let !n = cornerSegments
      !arcStride = if hasCore then 4 else 3
      !arcIndices = if hasCore then 18 else 12
  forUpTo_ (n + 1) $ \i -> do
    let !(ct, st) = cornerCosSin q i
    pokeBandVerts vp ((base + vi + i * arcStride) * vertexSize) hasCore r g b a $
      concentricOffsetsSIMD ccx ccy ct st innerAA inner outerR outerAA
  forUpTo_ n $ \i -> do
    let !va = fromIntegral (base + vi + i * arcStride) :: Word32
    pokeBandIndices ip ((baseIdx + ii + i * arcIndices) * indexSize) hasCore va (va + fromIntegral arcStride)

-- | Border of four flat rects inside @(x, y, w, h)@, @t@ thick. The origin is
-- already snapped by the caller; the texture is already selected.
pushSquareStroke :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushSquareStroke da x y w h t col = do
  recording <- getDrawRecordOps da
  let edge qx qy qw qh =
        when (qw > 0 && qh > 0) $ do
          when recording $ recordOpOn da (FillRect (Rect qx qy qw qh) col)
          pushQuad da (Rect qx qy qw qh) whitePixel whitePixel whitePixel whitePixel col
      !innerH = h - 2 * t
  edge x y w t
  edge x (y + h - t) w t
  edge x (y + t) t innerH
  edge (x + w - t) (y + t) t innerH

-- | A line @thickness@ wide with round caps: a coverage-AA strip with a
-- round cap on each end. An axis-aligned line is a plain rect spanning its
-- caps.
{-# INLINE pushLine #-}
pushLine :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushLine da x1 y1 x2 y2 thickness col
  | thickness <= 0 = pure ()
  | otherwise = do
      square <- readIORef (daSquareGeometry da)
      let !r = thickness / 2
          cap cx cy = pushCircle da cx cy r col
      if square
        then pushStroke da x1 y1 x2 y2 thickness col
        else
          if x1 == x2 || y1 == y2
            then pushRect da (Rect (min x1 x2 - r) (min y1 y2 - r) (abs (x2 - x1) + thickness) (abs (y2 - y1) + thickness)) col
            else do
              pushStrokeAA da x1 y1 x2 y2 thickness col
              cap x1 y1
              cap x2 y2

-- | Snap segment endpoints to the arena's device pixel grid before calling @raw@.
{-# INLINE snapStrokeEndpoints #-}
snapStrokeEndpoints ::
  (DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()) ->
  DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
snapStrokeEndpoints raw da x0 y0 x1 y1 bw col
  | bw <= 0 = pure ()
  | otherwise = do
      s <- readIORef (daSnapScale da)
      raw da (onGrid s x0) (onGrid s y0) (onGrid s x1) (onGrid s y1) bw col

-- Coverage-AA strip for a straight segment, the strip a rounded stroke's
-- sides use, without the round caps 'pushLine' adds.
{-# INLINE pushStrokeAA #-}
pushStrokeAA :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushStrokeAA = snapStrokeEndpoints pushStrokeAARaw

-- | Unsnapped variant: the caller already snapped the endpoints.
pushStrokeAARaw :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushStrokeAARaw da x0 y0 x1 y1 bw col = do
  square <- readIORef (daSquareGeometry da)
  if square
    then pushStrokeRaw da x0 y0 x1 y1 bw col
    else case strokeNormal x0 y0 x1 y1 of
      Nothing -> pure ()
      Just (!nx, !ny) -> do
        recordOp da (StrokeLineAA x0 y0 x1 y1 bw col)
        setTexture da glyphAtlasTextureId
        let !(r, g, b, a) = unpackColorF col
        withVertsRaw da 8 18 $ \vp ip base baseIdx ->
          pokeStripAt vp ip base baseIdx 0 0 x0 y0 x1 y1 nx ny bw r g b a

strokeNormal :: Float -> Float -> Float -> Float -> Maybe (Float, Float)
strokeNormal x0 y0 x1 y1 =
  let !dx = x1 - x0
      !dy = y1 - y0
      !len = sqrt (dx * dx + dy * dy)
   in if not (finite len) || len < 0.001 then Nothing else Just (-dy / len, dx / len)

-- One quad per segment. Plots and diagrams use this; pushLine adds round caps.
pushStroke :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushStroke = snapStrokeEndpoints pushStrokeRaw

pushStrokeRaw :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushStrokeRaw da px1 py1 px2 py2 thickness col
  | thickness <= 0 = pure ()
  | otherwise =
      case strokeNormal px1 py1 px2 py2 of
        Nothing -> pure ()
        Just (!nx, !ny) -> do
          recordOp da (Stroke px1 py1 px2 py2 thickness col)
          setTexture da glyphAtlasTextureId
          let !half = thickness * 0.5
              !hx = nx * half
              !hy = ny * half
          withVerts da 4 6 $ \vp ip vOff iOff baseIdxWord -> do
            let !(r, g, b, a) = unpackColorF col
                !u = whitePixel
            pokeQuadCornersSIMD vp vOff ip iOff (px1 + hx) (py1 + hy) (px2 + hx) (py2 + hy) (px2 - hx) (py2 - hy) (px1 - hx) (py1 - hy) u u u u r g b a baseIdxWord

-- | A lone filled triangle with anti-aliased edges; see 'pushPolygonAA'. It
-- moves to put the middle of its width, not its first corner, on the grid,
-- so an arrow symmetric about an upright axis stays symmetric whatever its
-- width, and its first corner's row, which an arrow's flat base passes
-- through, stays sharp.
pushFilledTriangle :: DrawArena -> Float -> Float -> Float -> Float -> Float -> Float -> Color -> IO ()
pushFilledTriangle da x0 y0 x1 y1 x2 y2 col =
  polygonAAFrom
    da
    ((min x0 (min x1 x2) + max x0 (max x1 x2)) * 0.5)
    y0
    (points3 x0 y0 x1 y1 x2 y2)
    triangleRing
    triangleIndices
    (Flat col)

-- | Three points as the flat coordinate array 'pushPolygonAA' and
-- 'pushPolylineAA' take, written straight into the array: a list literal
-- through 'primArrayFromListN' is not fused and boxes every coordinate.
{-# INLINE points3 #-}
points3 :: Float -> Float -> Float -> Float -> Float -> Float -> PrimArray Float
points3 x0 y0 x1 y1 x2 y2 = runPrimArray $ do
  a <- newPrimArray 6
  writePrimArray a 0 x0
  writePrimArray a 1 y0
  writePrimArray a 2 x1
  writePrimArray a 3 y1
  writePrimArray a 4 x2
  writePrimArray a 5 y2
  pure a

triangleIndices :: PrimArray Int
triangleIndices = primArrayFromListN 3 [0, 1, 2]

-- | Ring bounds for a lone triangle: one ring of three points.
triangleRing :: PrimArray Int
triangleRing = primArrayFromListN 2 [0, 3]

-- | Half the width of an anti-aliased edge's fade, in logical pixels: half a
-- device pixel, so an edge on the grid is solid on one side of it and clear
-- on the other.
{-# INLINE edgeFeather #-}
edgeFeather :: Float -> Float
edgeFeather s = if s > 0 then 0.5 / s else 0.5

-- | How far a miter may reach, as a multiple of the offset squared: a
-- join sharper than 120 degrees is cut back to twice the offset instead of
-- shooting off into a spike. Applies to polygon fringes and the inside of
-- stroke corners.
miterLimit :: Float
miterLimit = 4

-- | The offset at a vertex between two edges with unit normals @a@ and @b@,
-- scaled so moving the vertex by @d@ along it moves both edges by @d@. A zero
-- normal (a repeated point) defers to the other.
{-# INLINE miterOf #-}
miterOf :: Float -> Float -> Float -> Float -> (Float, Float)
miterOf ax ay bx by
  | ax == 0 && ay == 0 = (bx, by)
  | bx == 0 && by == 0 = (ax, ay)
  | d2 < 1.0e-6 = (ax, ay)
  | otherwise = let !k = min miterLimit (1 / d2) in (mx * k, my * k)
  where
    !mx = (ax + bx) * 0.5
    !my = (ay + by) * 0.5
    !d2 = mx * mx + my * my

-- | Unit normal of the segment from @(x0, y0)@ to @(x1, y1)@, a quarter turn
-- from its direction, or zero for a zero-length segment.
{-# INLINE segNormal #-}
segNormal :: Float -> Float -> Float -> Float -> (Float, Float)
segNormal x0 y0 x1 y1 =
  let !dx = x1 - x0
      !dy = y1 - y0
      !len = sqrt (dx * dx + dy * dy)
   in if not (finite len) || len < 1.0e-6 then (0, 0) else (-dy / len, dx / len)

-- | Whether a shade is flat or has a colour for each of @n@ points.
shadeCovers :: Shade -> Int -> Bool
shadeCovers sh n = case sh of
  Flat _ -> True
  Shaded cs -> sizeofPrimArray cs >= n

-- | Fill a polygon with holes and anti-aliased edges. @pts@ holds x/y pairs,
-- ring after ring (first point not repeated), then any interior points.
-- @rings@ holds each ring's start index plus the end of the last ring.
-- @tris@ holds index triples covering the polygon.
--
-- The first ring is the outline; the rest are holes wound the opposite way.
-- The polygon moves as a whole to put its first point on the device grid;
-- snapping points individually would bend small shapes. Ring edges fade
-- across one device pixel centred on the edge, so grid-aligned edges stay
-- sharp. Interior points get no fade.
pushPolygonAA :: DrawArena -> PrimArray Float -> PrimArray Int -> PrimArray Int -> Shade -> IO ()
pushPolygonAA da pts rings tris
  | sizeofPrimArray pts < 2 = const (pure ())
  | otherwise = polygonAAFrom da (indexPrimArray pts 0) (indexPrimArray pts 1) pts rings tris

-- | 'pushPolygonAA', moved to put @(rx, ry)@ rather than the first point on
-- the grid.
{-# NOINLINE polygonAAFrom #-}
polygonAAFrom :: DrawArena -> Float -> Float -> PrimArray Float -> PrimArray Int -> PrimArray Int -> Shade -> IO ()
polygonAAFrom da rx ry pts rings tris shade
  | n < 3 || nt < 3 || not ringsValid || not trisValid || area == 0 || not (shadeCovers shade n) = pure ()
  | otherwise = do
      s <- readIORef (daSnapScale da)
      square <- readIORef (daSquareGeometry da)
      setTexture da glyphAtlasTextureId
      let !ox = onGrid s rx - rx
          !oy = onGrid s ry - ry
      recordOp da (shiftDrawOp ox oy (FillPolygon pts rings tris shade))
      let !f = if square then 0 else edgeFeather s
          -- 'segNormal' points into a positive-area ring. Holes wind the
          -- other way, so their normals point out of the fill.
          !out = if area > 0 then -1 else 1
          {-# INLINE normalAt #-}
          normalAt i j =
            let (nx, ny) = segNormal (px i) (py i) (px j) (py j)
             in (nx * out, ny * out)
          -- Square geometry has no fade, so no fringe either.
          !fringe = if square then 0 else nOut
          !flat = case shade of
            Flat c -> unpackColorF c
            Shaded _ -> (0, 0, 0, 0)
          {-# INLINE rgbaAt #-}
          rgbaAt i = case shade of
            Flat _ -> flat
            Shaded cs -> unpackColorF (Color (indexPrimArray cs i))
      withVertsRaw da (n + fringe) (nt + 6 * fringe) $ \vp ip base baseIdx -> do
        forRings $ \from to -> forUpTo_ (to - from) $ \k -> do
          let !i = from + k
              !prev = if k == 0 then to - 1 else i - 1
              !next = if i + 1 >= to then from else i + 1
              (ax, ay) = normalAt prev i
              (bx, by) = normalAt i next
              (mx, my) = miterOf ax ay bx by
              !vx = px i + ox
              !vy = py i + oy
              !(r, g, b, a) = rgbaAt i
          pokeVertexSIMD vp ((base + i) * vertexSize) (vx - f * mx) (vy - f * my) r g b a whitePixel whitePixel
          when (fringe > 0) $
            pokeVertexSIMD vp ((base + n + i) * vertexSize) (vx + f * mx) (vy + f * my) r g b 0 whitePixel whitePixel
        forUpTo_ (n - nOut) $ \k -> do
          let !i = nOut + k
              !(r, g, b, a) = rgbaAt i
          pokeVertexSIMD vp ((base + i) * vertexSize) (px i + ox) (py i + oy) r g b a whitePixel whitePixel
        forUpTo_ nt $ \k ->
          pokeByteOff ip ((baseIdx + k) * indexSize) (fromIntegral (base + indexPrimArray tris k) :: Word32)
        when (fringe > 0) $
          forRings $ \from to -> forUpTo_ (to - from) $ \k -> do
            let !i = from + k
                !j = if i + 1 >= to then from else i + 1
                !inI = fromIntegral (base + i) :: Word32
                !inJ = fromIntegral (base + j) :: Word32
                !m = fromIntegral n :: Word32
            pokeQuadIndices ip ((baseIdx + nt + 6 * i) * indexSize) inI inJ (inJ + m) (inI + m)
  where
    !n = sizeofPrimArray pts `div` 2
    !nt = sizeofPrimArray tris - sizeofPrimArray tris `mod` 3
    !nr = sizeofPrimArray rings - 1
    ringAt r = indexPrimArray rings r
    -- First interior (non-ring) point.
    !nOut = if nr >= 1 then ringAt nr else 0
    ringsValid = nr >= 1 && ringAt 0 == 0 && nOut <= n && and [ringAt r < ringAt (r + 1) | r <- [0 .. nr - 1]]
    trisValid = and [t >= 0 && t < n | k <- [0 .. nt - 1], let t = indexPrimArray tris k]
    forRings body = forUpTo_ nr $ \r -> body (ringAt r) (ringAt (r + 1))
    px i = indexPrimArray pts (2 * i)
    py i = indexPrimArray pts (2 * i + 1)
    -- Outline area; its sign gives the winding.
    !area = shoelace (if nr >= 1 then ringAt 1 else 0) (\i -> (px i, py i))

-- | Stroke a polyline @w@ wide with anti-aliased sides. @pts@ holds x/y
-- pairs; @closed@ joins the last point to the first (do not repeat it).
-- Open ends use @cap@; corners use @join@, with miters longer than @limit@
-- times the width beveled. The inside of corners sharper than 60 degrees is
-- cut back ('miterLimit'). Near-straight corners are always mitered, so a
-- flattened curve costs no more than a straight line.
--
-- The line moves as a whole to put its first point's edges on the device
-- grid, like 'pushPolygonAA', so axis-aligned lines of whole-pixel width are
-- sharp. Lines thinner than the fade draw fainter to keep their ink. Each
-- point has a four-vertex cross-section (faded, solid, solid, faded); round
-- and bevel joins use two, one square to each segment, with the outer
-- corner filled between.
{-# NOINLINE pushPolylineAA #-}
pushPolylineAA :: DrawArena -> PrimArray Float -> Float -> Bool -> LineCap -> LineJoin -> Float -> Shade -> IO ()
pushPolylineAA da pts w closed cap join limit shade
  | n < 2 || not (w > 0) || not (shadeCovers shade n) = pure ()
  | otherwise = do
      s <- readIORef (daSnapScale da)
      square <- readIORef (daSquareGeometry da)
      setTexture da glyphAtlasTextureId
      let !hw = w * 0.5
          !ox = onGrid s (px 0 - hw) + hw - px 0
          !oy = onGrid s (py 0 - hw) + hw - py 0
      recordOp da (shiftDrawOp ox oy (StrokePolyline pts w closed cap join limit shade))
      let !f = if square then 0 else edgeFeather s
          !core = max 0 (hw - f)
          !outer = hw + f
          !thin = if core > 0 then 1 else min 1 (w / outer)
          !flat = case shade of
            Flat c -> let !(r, g, b, a) = unpackColorF c in (r, g, b, a * thin)
            Shaded _ -> (0, 0, 0, 0)
          {-# INLINE colourAt #-}
          colourAt i = case shade of
            Flat _ -> flat
            Shaded cs -> let !(r, g, b, a) = unpackColorF (Color (indexPrimArray cs i)) in (r, g, b, a * thin)
          !segs = if closed then n else n - 1
          -- Upper bound on chords per round join or cap (a half turn).
          !halfTurn = max 2 (arcChords s outer pi)
          !roundJoins = join == RoundJoin
          !roundCaps = cap == RoundCap && not closed
          !maxV = 8 * n + (if roundJoins then 2 * halfTurn * n else 0) + (if roundCaps then 4 * halfTurn else 0)
          !maxI = 18 * segs + 9 * n * (if roundJoins then halfTurn else 1) + (if roundCaps then 18 * halfTurn else 0)
          -- Corners whose miter reaches under 0.1 device pixel past the
          -- side show no join.
          !straightD2 = let q = hw / (hw + 0.1 / max 1 s) in q * q
          {-# INLINE normalAt #-}
          normalAt i =
            let !j = if i + 1 >= n then 0 else i + 1
             in segNormal (px i) (py i) (px j) (py j)
      withVertsReserve da maxV maxI $ \vp ip base baseIdx commit -> do
        let vidx k = fromIntegral (base + k) :: Word32
            vert k x y r g b a = pokeVertexSIMD vp ((base + k) * vertexSize) (x + ox) (y + oy) r g b a whitePixel whitePixel
            -- Cross-section at @(x, y)@: negative side along @(nx, ny)@,
            -- positive side along @(qx, qy)@.
            section v x y nx ny qx qy (r, g, b, a) = do
              vert v (x - nx * outer) (y - ny * outer) r g b 0
              vert (v + 1) (x - nx * core) (y - ny * core) r g b a
              vert (v + 2) (x + qx * core) (y + qy * core) r g b a
              vert (v + 3) (x + qx * outer) (y + qy * outer) r g b 0
            -- Symmetric section (the common case), via SIMD offsets.
            {-# INLINE evenSection #-}
            evenSection v x y mx my (r, g, b, a) =
              pokeBandVerts vp ((base + v) * vertexSize) True r g b a $
                concentricOffsetsSIMD (x + ox) (y + oy) mx my (-outer) (-core) core outer
            {-# INLINE band #-}
            band k va vb = do
              pokeBandIndices ip ((baseIdx + k) * indexSize) True (vidx va) (vidx vb)
              pure (k + 18)
            -- Arc about @(x, y)@ from angle @a0@ through @sweep@ in @chords@
            -- chords: a solid core fanned from vertex @centre@ plus a faded
            -- rim. Endpoints are core/edge vertices @c0@/@o0@ and @c1@/@o1@;
            -- new vertices start at @v@.
            fan v k centre c0 o0 c1 o1 x y a0 sweep chords (r, g, b, a) = do
              forUpTo_ (chords - 1) $ \j0 -> do
                let !t = a0 + sweep * fromIntegral (j0 + 1) / fromIntegral chords
                    !ct = cos t
                    !st = sin t
                vert (v + 2 * j0) (x + ct * core) (y + st * core) r g b a
                vert (v + 2 * j0 + 1) (x + ct * outer) (y + st * outer) r g b 0
              let coreAt j
                    | j == 0 = c0
                    | j == chords = c1
                    | otherwise = v + 2 * (j - 1)
                  edgeAt j
                    | j == 0 = o0
                    | j == chords = o1
                    | otherwise = v + 2 * (j - 1) + 1
              forUpTo_ chords $ \j -> do
                let !o = (baseIdx + k + 9 * j) * indexSize
                pokeByteOff ip o (vidx centre)
                pokeByteOff ip (o + 4) (vidx (coreAt j))
                pokeByteOff ip (o + 8) (vidx (coreAt (j + 1)))
                pokeQuadIndices ip (o + 12) (vidx (coreAt j)) (vidx (edgeAt j)) (vidx (edgeAt (j + 1))) (vidx (coreAt (j + 1)))
              pure (v + 2 * (chords - 1), k + 9 * chords)
            -- Open end with segment normal @(nx, ny)@. A square cap moves the
            -- section half the width out; a round cap adds a fan beyond it.
            -- @dir@ is 1 at the last point, -1 at the first.
            capAt i v k nx ny dir = do
              let !col = colourAt i
                  !reach = if cap == SquareCap then hw * dir else 0
                  !x = px i + ny * reach
                  !y = py i - nx * reach
              evenSection v x y nx ny col
              if cap == RoundCap
                then do
                  (v', k') <- fan (v + 4) k (v + 2) (v + 2) (v + 3) (v + 1) v x y (atan2 ny nx) (negate dir * pi) halfTurn col
                  pure (v, v, v', k')
                else pure (v, v, v + 4, k)
            -- Corner between segments with normals @a@ and @b@. Only corners
            -- 'evenJoin' rejects come here, so both normals are nonzero and
            -- the corner needs more than one even section.
            joinAt i v k ax ay bx by = do
              let !col = colourAt i
                  !x = px i
                  !y = py i
                  -- Inner corner offset, cut back if very sharp.
                  (!ix, !iy) = miterOf ax ay bx by
                  miter = if join == MiterJoin then miterOffset limit ax ay bx by else Nothing
                  -- The outside is the side the next segment turns away from.
                  !turnsPositive = by * ax - bx * ay > 0
                  !outSign = if turnsPositive then -1 else 1
              case miter of
                Just (fx, fy) -> do
                  -- Miter within limit: outside runs to the full point.
                  if turnsPositive then section v x y fx fy ix iy col else section v x y ix iy fx fy col
                  pure (v, v, v + 4, k)
                Nothing -> do
                  let (!centre, !cIn, !oIn, !cOut, !oOut)
                        | turnsPositive = (v + 2, v + 1, v, v + 5, v + 4)
                        | otherwise = (v + 1, v + 2, v + 3, v + 6, v + 7)
                      !ux = outSign * ax
                      !uy = outSign * ay
                      -- Turning the way the corner turns: at a half turn
                      -- the cross product is a signed zero, and atan2 would
                      -- follow its sign back through the stroke instead.
                      !turned = abs (atan2 (ax * by - ay * bx) (ax * bx + ay * by))
                      !sweep = if turnsPositive then turned else negate turned
                      !chords = if join == RoundJoin then arcChords s outer turned else 1
                  if turnsPositive
                    then section v x y ax ay ix iy col >> section (v + 4) x y bx by ix iy col
                    else section v x y ix iy ax ay col >> section (v + 4) x y ix iy bx by col
                  (v', k') <- fan (v + 8) k centre cIn oIn cOut oOut x y (atan2 uy ux) sweep chords col
                  pure (v, v + 4, v', k')
            -- An end's cap faces along the nearest segment of nonzero
            -- length, stepping by @step@ from segment @i@.
            endNormal i step
              | i >= 0 && i < n - 1
              , (0, 0) <- normalAt i =
                  endNormal (i + step) step
              | otherwise = normalAt (max 0 (min (n - 2) i))
            pointAt i v k
              | not closed && i == 0 = let (nx, ny) = endNormal 0 1 in capAt i v k nx ny (-1)
              | not closed && i == n - 1 = let (nx, ny) = endNormal (n - 2) (-1) in capAt i v k nx ny 1
              | otherwise =
                  let (ax, ay) = normalAt (if i == 0 then n - 1 else i - 1)
                      (bx, by) = normalAt i
                   in joinAt i v k ax ay bx by
            loop !i !v !k !prevOut !firstIn
              | i >= n = do
                  k' <- if closed then band k prevOut firstIn else pure k
                  commit v k'
              -- Fast path: one even section, no tuple allocated.
              | closed || (i > 0 && i < n - 1)
              , (ax, ay) <- normalAt (if i == 0 then n - 1 else i - 1)
              , (bx, by) <- normalAt i
              , evenJoin ax ay bx by = do
                  let (mx, my) = miterOf ax ay bx by
                  evenSection v (px i) (py i) mx my (colourAt i)
                  k' <- if i > 0 then band k prevOut v else pure k
                  loop (i + 1) (v + 4) k' v (if i == 0 then v else firstIn)
              | otherwise = do
                  (inV, outV, v', k') <- pointAt i v k
                  k'' <- if i > 0 then band k' prevOut inV else pure k'
                  loop (i + 1) v' k'' outV (if i == 0 then inV else firstIn)
            -- A corner one section can draw: near-straight, or a miter within
            -- its limit that needs no inner cut-back.
            evenJoin ax ay bx by
              | (ax == 0 && ay == 0) || (bx == 0 && by == 0) = True
              | otherwise =
                  let !mx = (ax + bx) * 0.5
                      !my = (ay + by) * 0.5
                      !d2 = mx * mx + my * my
                   in d2 >= straightD2 || (join == MiterJoin && d2 >= 0.25 && d2 * limit * limit >= 1)
        loop 0 0 0 0 0
  where
    !n = sizeofPrimArray pts `div` 2
    px i = indexPrimArray pts (2 * i)
    py i = indexPrimArray pts (2 * i + 1)

-- | Chords needed for @sweep@ radians of an arc of radius @r@ (logical px) at
-- scale @s@, keeping each within a quarter device pixel. Clamped to 1..32.
arcChords :: Float -> Float -> Float -> Int
arcChords s r sweep
  | not (rd > 0.25) || not (finite sweep) = 1
  -- Bounded before rounding, so a huge radius cannot overflow the 'Int'.
  | otherwise = clamp 1 32 (ceiling (min 32 (idealArcSteps 0.25 rd sweep)))
  where
    rd = r * max 1 s