feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+192
@@ -0,0 +1,192 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Transformed content inside a stationary rounded card used to allocate a whole-card mask on every animation frame.
|
||||
func TestStationaryRoundedClipUsesFrameCoordinates(t *testing.T) {
|
||||
transforms := []struct {
|
||||
name string
|
||||
m scene.Affine
|
||||
}{
|
||||
{"scale", scene.Scaling(0.85, 0.9)},
|
||||
{"rotate", scene.Translation(30, 25).Mul(scene.Rotation(12))},
|
||||
{"perspective", scene.Projective(1, 0, 0, 1, 20, 15, 0.001, 0.0004)},
|
||||
}
|
||||
for _, transform := range transforms {
|
||||
for _, inner := range []bool{false, true} {
|
||||
name := transform.name
|
||||
if inner {
|
||||
name += "/integer-child"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
outer := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 256, H: 256}}
|
||||
card := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 10, W: 200, H: 150}, Radii: [4]float32{17, 17, 17, 17}}
|
||||
ops := []scene.Op{outer, card}
|
||||
wantScissor := Scissor{10, 10, 210, 160}
|
||||
if inner {
|
||||
ops = append(ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 120, H: 100}})
|
||||
wantScissor = Scissor{20, 20, 140, 120}
|
||||
}
|
||||
ops = append(ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 20, W: 100, H: 80}, Color: scene.Color{R: 255, A: 255}, Transform: transform.m})
|
||||
if inner {
|
||||
ops = append(ops, scene.Op{Kind: scene.OpPopClip})
|
||||
}
|
||||
ops = append(ops, scene.Op{Kind: scene.OpPopClip}, scene.Op{Kind: scene.OpPopClip})
|
||||
b := Builder{NoCull: true, NoFold: true}
|
||||
defer b.Release()
|
||||
uploads := 0
|
||||
b.Build(&scene.Scene{Width: 256, Height: 256, Ops: ops}, func(img *scene.Image) uintptr { uploads++; return uintptr(img.ID()) })
|
||||
if uploads != 0 || len(b.maskSlots) != 0 || len(b.Instances) == 0 {
|
||||
t.Fatalf("stationary card uploaded %d masks, retained %d, drew %d instances", uploads, len(b.maskSlots), len(b.Instances))
|
||||
}
|
||||
wantClip := [4]float32{10, 10, 200, 150}
|
||||
wantRadii := scene.Corners(card.Rect, card.Radii, card.Continuous)
|
||||
for _, in := range b.Instances {
|
||||
if in.Transform1[3] != 0 || in.Clip != wantClip || in.ClipRadii != wantRadii {
|
||||
t.Fatalf("analytic clip mode %v rect %v radii %v, want 0 %v %v", in.Transform1[3], in.Clip, in.ClipRadii, wantClip, wantRadii)
|
||||
}
|
||||
}
|
||||
for _, batch := range b.Batches {
|
||||
if batch.ClipMask != 0 || batch.Scissor != wantScissor {
|
||||
t.Fatalf("analytic card lost exact hard scissor: mask %v scissor %v, want %v", batch.ClipMask, batch.Scissor, wantScissor)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Analytic single-card clipping must retain pixel masks when clips need combined coverage or separate coordinate systems.
|
||||
func TestComplexClipRetainsCoverageMask(t *testing.T) {
|
||||
for _, name := range []string{"fractional-child", "fractional-ancestor", "multiple-rounded", "continuous-card", "transformed-clip", "gradient-mask", "image-mask"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
outer := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 256, H: 256}}
|
||||
card := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 10, W: 200, H: 150}, Radii: [4]float32{17, 17, 17, 17}}
|
||||
child := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 120, H: 100}}
|
||||
switch name {
|
||||
case "continuous-card":
|
||||
card.Continuous = true
|
||||
case "fractional-child":
|
||||
child.Rect.X += 0.25
|
||||
case "fractional-ancestor":
|
||||
outer.Rect.X = 20.25 // this edge actually reaches into the rounded corner
|
||||
case "multiple-rounded":
|
||||
child.Radii = [4]float32{8, 8, 8, 8}
|
||||
case "transformed-clip":
|
||||
child.Transform = scene.Rotation(5)
|
||||
case "gradient-mask":
|
||||
card.Paint, card.Color, card.Color2, card.Gradient = scene.PaintLinear, scene.Color{A: 0}, scene.Color{A: 255}, [4]float32{10, 10, 210, 10}
|
||||
case "image-mask":
|
||||
card.Image = scene.NewImageRGBA(2, 1, []byte{0, 0, 0, 128, 0, 0, 0, 255})
|
||||
card.Src = scene.Rect{W: 2, H: 1}
|
||||
}
|
||||
fill := scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 20, W: 100, H: 80}, Color: scene.Color{R: 255, A: 255}, Transform: scene.Scaling(0.85, 0.9)}
|
||||
ops := []scene.Op{outer, card, child, fill, {Kind: scene.OpPopClip}, {Kind: scene.OpPopClip}, {Kind: scene.OpPopClip}}
|
||||
b := Builder{NoCull: true, NoFold: true}
|
||||
defer b.Release()
|
||||
uploads := 0
|
||||
b.Build(&scene.Scene{Width: 256, Height: 256, Ops: ops}, func(img *scene.Image) uintptr { uploads++; return uintptr(img.ID()) })
|
||||
if uploads == 0 || len(b.maskSlots) == 0 || len(b.Instances) == 0 {
|
||||
t.Fatalf("complex clip lost its mask: uploads %d retained %d instances %d", uploads, len(b.maskSlots), len(b.Instances))
|
||||
}
|
||||
for _, in := range b.Instances {
|
||||
if in.Transform1[3] != 1 && in.Transform1[3] != 2 {
|
||||
t.Fatalf("complex clip uses analytic mode %v", in.Transform1[3])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A fractional lyrics viewport used to turn its rounded player card into two large pixel masks, even after clipping off whole corners.
|
||||
func TestStationaryClipReducesCoverageChain(t *testing.T) {
|
||||
for _, name := range []string{"lyrics", "left", "top", "right", "bottom", "asymmetric", "distant-fractional", "opaque-rounded-parent"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
card := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 200, H: 160}, Radii: [4]float32{10, 10, 10, 10}}
|
||||
hard := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 256, H: 224}}
|
||||
want, radii := card.Rect, card.Radii
|
||||
switch name {
|
||||
case "lyrics":
|
||||
hard.Rect = scene.Rect{X: 70, Y: 0.25, W: 180, H: 140}
|
||||
want, radii = scene.Rect{X: 70, Y: 20, W: 150, H: 120.25}, [4]float32{0, 10, 0, 0}
|
||||
case "left":
|
||||
hard.Rect.X, hard.Rect.W = 50.25, 200
|
||||
want, radii = scene.Rect{X: 50.25, Y: 20, W: 169.75, H: 160}, [4]float32{0, 10, 10, 0}
|
||||
case "top":
|
||||
hard.Rect.Y, hard.Rect.H = 50.25, 170
|
||||
want, radii = scene.Rect{X: 20, Y: 50.25, W: 200, H: 129.75}, [4]float32{0, 0, 10, 10}
|
||||
case "right":
|
||||
hard.Rect.W = 180.25
|
||||
want, radii = scene.Rect{X: 20, Y: 20, W: 160.25, H: 160}, [4]float32{10, 0, 0, 10}
|
||||
case "bottom":
|
||||
hard.Rect.H = 140.25
|
||||
want, radii = scene.Rect{X: 20, Y: 20, W: 200, H: 120.25}, [4]float32{10, 10, 0, 0}
|
||||
case "asymmetric":
|
||||
card.Radii, hard.Rect.X, hard.Rect.W = [4]float32{8, 12, 16, 20}, 70.25, 180
|
||||
want, radii = scene.Rect{X: 70.25, Y: 20, W: 149.75, H: 160}, [4]float32{0, 12, 16, 0}
|
||||
case "distant-fractional":
|
||||
hard.Rect.X = 0.25
|
||||
case "opaque-rounded-parent":
|
||||
card.Rect, card.Radii = scene.Rect{W: 256, H: 224}, [4]float32{10, 10, 10, 10}
|
||||
hard.Rect, hard.Radii = scene.Rect{X: 50.25, Y: 50.25, W: 150, H: 100}, [4]float32{8, 8, 8, 8}
|
||||
want, radii = hard.Rect, hard.Radii
|
||||
}
|
||||
s := &scene.Scene{Width: 256, Height: 224, Ops: []scene.Op{card, hard,
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{W: 256, H: 224}, Color: scene.Color{A: 255}, Transform: scene.Scaling(1.01, 1.01)},
|
||||
{Kind: scene.OpPopClip}, {Kind: scene.OpPopClip},
|
||||
}}
|
||||
b := Builder{NoCull: true, NoFold: true}
|
||||
defer b.Release()
|
||||
uploads := 0
|
||||
b.Build(s, func(img *scene.Image) uintptr { uploads++; return uintptr(img.ID()) })
|
||||
if uploads != 0 || len(b.Instances) == 0 {
|
||||
t.Fatalf("reducible clip uploaded %d masks and drew %d instances", uploads, len(b.Instances))
|
||||
}
|
||||
for _, in := range b.Instances {
|
||||
if in.Transform1[3] != 0 || in.Clip != rect(want) || in.ClipRadii != radii {
|
||||
t.Fatalf("wrong reduced clip: rect=%v radii=%v mode=%v, want %v %v", in.Clip, in.ClipRadii, in.Transform1[3], rect(want), radii)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Edges whose partial coverages multiply must keep a mask; intersecting their rectangles would brighten their antialiasing.
|
||||
func TestOverlappingAntialiasingKeepsClipMask(t *testing.T) {
|
||||
for _, name := range []string{"duplicate-fractional", "near-fractional", "cuts-corner", "duplicate-rounded", "thin-strip", "continuous-cut"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
card := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 200, H: 160}, Radii: [4]float32{20, 20, 20, 20}}
|
||||
hard := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 70.25, Y: 0, W: 180, H: 220}}
|
||||
switch name {
|
||||
case "duplicate-fractional", "near-fractional":
|
||||
card.Rect.X, hard.Rect = 20.25, scene.Rect{X: 20.25, Y: 0, W: 230, H: 220}
|
||||
if name == "near-fractional" {
|
||||
hard.Rect.X = 20.5
|
||||
}
|
||||
case "cuts-corner":
|
||||
hard.Rect.X = 25.25
|
||||
case "duplicate-rounded":
|
||||
hard = card
|
||||
case "thin-strip":
|
||||
card.Rect.W, hard.Rect = 0.75, scene.Rect{X: 20.25, Y: 0, W: 0.5, H: 220}
|
||||
case "continuous-cut":
|
||||
card.Continuous = true
|
||||
}
|
||||
s := &scene.Scene{Width: 256, Height: 224, Ops: []scene.Op{card, hard,
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{W: 256, H: 224}, Color: scene.Color{A: 255}, Transform: scene.Scaling(1.01, 1.01)},
|
||||
{Kind: scene.OpPopClip}, {Kind: scene.OpPopClip},
|
||||
}}
|
||||
b := Builder{NoCull: true, NoFold: true}
|
||||
defer b.Release()
|
||||
uploads := 0
|
||||
b.Build(s, func(img *scene.Image) uintptr { uploads++; return uintptr(img.ID()) })
|
||||
if uploads == 0 || len(b.Instances) == 0 {
|
||||
t.Fatalf("overlapping antialiasing lost its mask: uploads=%d instances=%d", uploads, len(b.Instances))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Bands. A border-only fill (addFill) writes nothing where the coverages of
|
||||
// its outer and inner edges are both 1, nor outside its outer edge, and a
|
||||
// shadow (addShadow) nothing inside the box casting it. Cut around one
|
||||
// rectangle (addAround), a ring with large corners keeps most of what it
|
||||
// shades for nothing: the core of a circle is less than the square inside
|
||||
// it, and the shaders evaluate the ring's shape in every pixel of its box
|
||||
// to draw a line a pixel wide. So such a shape is cut into bands of rows
|
||||
// instead, each drawing only the columns between where its outer edge may
|
||||
// reach and where its inner one certainly covers, on either side: what is
|
||||
// shaded grows with the ring's length, not its area. The bands of the rows
|
||||
// across its corners are as many as pay for their draw calls (bandCost);
|
||||
// the pixels are the same either way. Shapes with continuous corners, whose
|
||||
// curves the shaders compute otherwise, are still cut around one rectangle.
|
||||
|
||||
// bandCost is what a draw call of its own costs, in pixels shaded: as
|
||||
// shadowSplitMin, below which a shadow is not split.
|
||||
const bandCost = shadowSplitMin
|
||||
|
||||
// bandMargin is how far, in pixels, from the edge of a shape a pixel is
|
||||
// taken to be covered by 0 or 1, beyond the pixel's half that antialiasing
|
||||
// reaches (coverage is 0.5 less the distance to the edge), as shadowCore.
|
||||
const bandMargin = 2
|
||||
|
||||
// rounded is a rectangle with circular corners of radii (top left, top
|
||||
// right, bottom right, bottom left), fitted (scene.Corners), as the
|
||||
// shaders' sdRoundRect takes it: each quarter of the rectangle has its
|
||||
// corner's radius.
|
||||
type rounded struct {
|
||||
r scene.Rect
|
||||
radii [4]float32
|
||||
}
|
||||
|
||||
// span returns the columns that the shape, grown by t (shrunk when
|
||||
// negative), covers at row y, and false for none: grown by t, a corner's
|
||||
// radius grows by t too, to 0 at least.
|
||||
func (s *rounded) span(y, t float32) (l, r float32, ok bool) {
|
||||
x0, y0, x1, y1 := s.r.X-t, s.r.Y-t, s.r.X+s.r.W+t, s.r.Y+s.r.H+t
|
||||
if y < y0 || y > y1 || x1 <= x0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
top := y < s.r.Y+s.r.H/2
|
||||
left, right := s.radii[3], s.radii[2]
|
||||
if top {
|
||||
left, right = s.radii[0], s.radii[1]
|
||||
}
|
||||
dy := y - y0 // from the nearer of the top and the bottom
|
||||
if !top {
|
||||
dy = y1 - y
|
||||
}
|
||||
in := func(radius float32) float32 {
|
||||
rho := max(radius+t, 0) // the corner's radius grown by t
|
||||
if dy >= rho {
|
||||
return 0
|
||||
}
|
||||
d := rho - dy
|
||||
return rho - float32(math.Sqrt(float64(max(rho*rho-d*d, 0))))
|
||||
}
|
||||
l, r = x0+in(left), x1-in(right)
|
||||
return l, r, l < r
|
||||
}
|
||||
|
||||
// widest returns the columns the shape, grown by t, covers at some row
|
||||
// between y0 and y1: those at the row nearest its middle, the widest of a
|
||||
// convex shape.
|
||||
func (s *rounded) widest(y0, y1, t float32) (l, r float32, ok bool) {
|
||||
return s.span(min(max(s.r.Y+s.r.H/2, y0), y1), t)
|
||||
}
|
||||
|
||||
// narrowest returns the columns the shape, shrunk by t, covers at every
|
||||
// row between y0 and y1: those it covers at both, as it is convex.
|
||||
func (s *rounded) narrowest(y0, y1, t float32) (l, r float32, ok bool) {
|
||||
l0, r0, ok0 := s.span(y0, -t)
|
||||
l1, r1, ok1 := s.span(y1, -t)
|
||||
l, r = max(l0, l1), min(r0, r1)
|
||||
return l, r, ok0 && ok1 && l < r
|
||||
}
|
||||
|
||||
// band is a band of rows from top to bottom, of which the columns from
|
||||
// left to right are drawn, less those from holeL to holeR.
|
||||
type band struct {
|
||||
top, bottom, left, right, holeL, holeR int32
|
||||
}
|
||||
|
||||
// strips returns the scissor rectangles of the band, empty where none.
|
||||
func (bd band) strips() (out [2]Scissor) {
|
||||
if bd.holeL >= bd.holeR {
|
||||
out[0] = Scissor{bd.left, bd.top, bd.right, bd.bottom}
|
||||
return out
|
||||
}
|
||||
out[0] = Scissor{bd.left, bd.top, bd.holeL, bd.bottom}
|
||||
out[1] = Scissor{bd.holeR, bd.top, bd.right, bd.bottom}
|
||||
return out
|
||||
}
|
||||
|
||||
// bandsCost returns what drawing the bands costs, in pixels (see bandCost).
|
||||
func bandsCost(bands []band) int64 {
|
||||
var c int64
|
||||
for _, bd := range bands {
|
||||
for _, st := range bd.strips() {
|
||||
if !st.Empty() {
|
||||
c += st.area() + bandCost
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// planBands plans, into b.bands, bands of the rows of whole drawing an
|
||||
// instance that writes nothing within all of holes, shrunk by bandMargin
|
||||
// (where they all cover by 1), nor, unless outer is nil, outside outer
|
||||
// grown by it; and returns false when drawing whole costs less.
|
||||
func (b *Builder) planBands(whole Scissor, outer *rounded, holes []rounded) bool {
|
||||
const m = bandMargin
|
||||
b.bands = b.bands[:0]
|
||||
if whole.area() <= bandCost || len(holes) == 0 {
|
||||
return false // two draw calls cost more than it
|
||||
}
|
||||
top, bottom := whole.Top, whole.Bottom
|
||||
if outer != nil {
|
||||
top = max(top, int32(math.Floor(float64(outer.r.Y-m))))
|
||||
bottom = min(bottom, int32(math.Ceil(float64(outer.r.Y+outer.r.H+m))))
|
||||
}
|
||||
// The rows where the holes may hide columns, and the rows across their
|
||||
// corners, at the top and the bottom: all of them, then those shown.
|
||||
hTop, hBottom := int32(math.MinInt32), int32(math.MaxInt32)
|
||||
var rTop, rBottom float32
|
||||
for i := range holes {
|
||||
h := &holes[i]
|
||||
hTop = max(hTop, int32(math.Ceil(float64(h.r.Y+m))))
|
||||
hBottom = min(hBottom, int32(math.Floor(float64(h.r.Y+h.r.H-m))))
|
||||
rTop = max(rTop, h.radii[0], h.radii[1])
|
||||
rBottom = max(rBottom, h.radii[2], h.radii[3])
|
||||
}
|
||||
if top >= bottom {
|
||||
return true // nothing to draw
|
||||
}
|
||||
// What bands could leave out at most, the holes' rectangle and what
|
||||
// lies outside outer's, near its corners: a hole takes four draw calls
|
||||
// or more, three more than drawing whole, so less than two never pays.
|
||||
hole := whole
|
||||
for i := range holes {
|
||||
h := &holes[i].r
|
||||
hole = hole.intersect(Scissor{int32(math.Ceil(float64(h.X + m))), int32(math.Ceil(float64(h.Y + m))),
|
||||
int32(math.Floor(float64(h.X + h.W - m))), int32(math.Floor(float64(h.Y + h.H - m)))})
|
||||
}
|
||||
saved := hole.area()
|
||||
if outer != nil {
|
||||
o := &outer.r
|
||||
in := whole.intersect(Scissor{int32(math.Floor(float64(o.X - m))), int32(math.Floor(float64(o.Y - m))),
|
||||
int32(math.Ceil(float64(o.X + o.W + m))), int32(math.Ceil(float64(o.Y + o.H + m)))})
|
||||
saved += whole.area() - in.area()
|
||||
for _, r := range outer.radii {
|
||||
saved += int64((r + m) * (r + m))
|
||||
}
|
||||
}
|
||||
if saved <= 2*bandCost {
|
||||
return false
|
||||
}
|
||||
mTop := hTop + int32(math.Ceil(float64(rTop)))
|
||||
mBottom := hBottom - int32(math.Ceil(float64(rBottom)))
|
||||
if mTop > mBottom {
|
||||
mTop = (mTop + mBottom) / 2
|
||||
mBottom = mTop
|
||||
}
|
||||
clamp := func(y int32) int32 { return min(max(y, top), bottom) }
|
||||
hTop, hBottom, mTop, mBottom = clamp(hTop), clamp(hBottom), clamp(mTop), clamp(mBottom)
|
||||
plan := func(out []band, k int32) []band {
|
||||
add := func(y0, y1 int32) {
|
||||
if y0 >= y1 {
|
||||
return
|
||||
}
|
||||
bd := band{top: y0, bottom: y1, left: whole.Left, right: whole.Right}
|
||||
fy0, fy1 := float32(y0), float32(y1)
|
||||
if outer != nil {
|
||||
l, r, ok := outer.widest(fy0, fy1, m)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
bd.left = max(bd.left, int32(math.Floor(float64(l))))
|
||||
bd.right = min(bd.right, int32(math.Ceil(float64(r))))
|
||||
}
|
||||
if y0 >= hTop && y1 <= hBottom {
|
||||
hl, hr, ok := float32(math.Inf(-1)), float32(math.Inf(1)), true
|
||||
for i := range holes {
|
||||
l, r, in := holes[i].narrowest(fy0, fy1, m)
|
||||
hl, hr, ok = max(hl, l), min(hr, r), ok && in
|
||||
}
|
||||
if ok {
|
||||
bd.holeL = max(int32(math.Ceil(float64(hl))), bd.left)
|
||||
bd.holeR = min(int32(math.Floor(float64(hr))), bd.right)
|
||||
}
|
||||
}
|
||||
if bd.left < bd.right {
|
||||
out = append(out, bd)
|
||||
}
|
||||
}
|
||||
if hTop >= hBottom {
|
||||
add(top, bottom)
|
||||
return out
|
||||
}
|
||||
add(top, hTop)
|
||||
for i := range k {
|
||||
add(hTop+(mTop-hTop)*i/k, hTop+(mTop-hTop)*(i+1)/k)
|
||||
}
|
||||
add(mTop, mBottom)
|
||||
for i := range k {
|
||||
add(mBottom+(hBottom-mBottom)*i/k, mBottom+(hBottom-mBottom)*(i+1)/k)
|
||||
}
|
||||
add(hBottom, bottom)
|
||||
return out
|
||||
}
|
||||
// As many bands across the corners as pay for their draw calls: twice
|
||||
// as many while that costs less, each of minBandRows rows or more.
|
||||
best, found := whole.area()+bandCost, false
|
||||
last := int64(math.MaxInt64)
|
||||
rows := max(mTop-hTop, hBottom-mBottom)
|
||||
for k := int32(1); k <= 32 && (k == 1 || rows/k >= minBandRows); k *= 2 {
|
||||
b.bandsTry = plan(b.bandsTry[:0], k)
|
||||
c := bandsCost(b.bandsTry)
|
||||
if c < best {
|
||||
best, found = c, true
|
||||
b.bands, b.bandsTry = b.bandsTry, b.bands
|
||||
}
|
||||
if c >= last {
|
||||
break
|
||||
}
|
||||
last = c
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// minBandRows is the fewest rows a band across corners has: fewer pay for
|
||||
// their draw calls only in shapes larger than windows.
|
||||
const minBandRows = 8
|
||||
|
||||
// addBands appends in as the strips of the bands planBands planned, each
|
||||
// with a scissor rectangle of its own, cut as addAround does.
|
||||
func (b *Builder) addBands(in Instance, m scene.Affine) {
|
||||
defer b.scissorBatches(Scissor{}, false)
|
||||
for _, bd := range b.bands {
|
||||
for _, st := range bd.strips() {
|
||||
if st.Empty() {
|
||||
continue
|
||||
}
|
||||
b.scissorBatches(st, true)
|
||||
b.addCut(in, 0, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkBuildSprites turns the scene of a 2D game's frame at 1920×1080
|
||||
// into instances: tiles 3 times as large under 300 sprites, all of one
|
||||
// sheet, which make one draw call.
|
||||
func BenchmarkBuildSprites(b *testing.B) { benchBuild(b, 3, 3, 300) }
|
||||
|
||||
// BenchmarkBuildSpritesZoomedOut is the same game zoomed out to tiles 1.5
|
||||
// times as large, under 1,000 sprites: about 7,000 instances.
|
||||
func BenchmarkBuildSpritesZoomedOut(b *testing.B) { benchBuild(b, 1.5, 3, 1000) }
|
||||
|
||||
func benchBuild(b *testing.B, scale float32, layers, sprites int) {
|
||||
s := gputest.SpriteScene(1920, 1080, scale, layers, sprites)
|
||||
var bld Builder
|
||||
image := func(*scene.Image) uintptr { return 1 }
|
||||
for b.Loop() {
|
||||
bld.Build(s, image)
|
||||
}
|
||||
b.ReportMetric(float64(len(bld.Instances)), "instances")
|
||||
b.ReportMetric(float64(len(bld.Batches)), "batches")
|
||||
}
|
||||
|
||||
// BenchmarkBuildTranslatedBoxes turns 600 rounded boxes casting shadows,
|
||||
// each under a translation, into instances, the translations folded into
|
||||
// them (BenchmarkBuildTranslatedBoxesUnfolded: under their transforms).
|
||||
func BenchmarkBuildTranslatedBoxes(b *testing.B) { benchBuildBoxes(b, true, false) }
|
||||
|
||||
func BenchmarkBuildTranslatedBoxesUnfolded(b *testing.B) { benchBuildBoxes(b, true, true) }
|
||||
|
||||
// BenchmarkBuildBoxes turns the same boxes placed without transforms into
|
||||
// instances.
|
||||
func BenchmarkBuildBoxes(b *testing.B) { benchBuildBoxes(b, false, false) }
|
||||
|
||||
func benchBuildBoxes(b *testing.B, translated, noFold bool) {
|
||||
s := gputest.BoxesScene(1280, 800, 600, translated)
|
||||
bld := Builder{Classes: true, ClipSkip: true, NoFold: noFold}
|
||||
image := func(*scene.Image) uintptr { return 1 }
|
||||
for b.Loop() {
|
||||
bld.Build(s, image)
|
||||
}
|
||||
b.ReportMetric(float64(len(bld.Instances)), "instances")
|
||||
b.ReportMetric(float64(len(bld.Batches)), "batches")
|
||||
}
|
||||
|
||||
// BenchmarkDiffRows compares a frame of a list of 200 rows at 3456×2000
|
||||
// with the last (scene.Differ), as Metal's renderer does before drawing
|
||||
// what changed: unchanged, and with one row's badge changing color, and
|
||||
// BenchmarkBuildRows builds it, for comparison.
|
||||
func BenchmarkDiffRows(b *testing.B) {
|
||||
for _, change := range []bool{false, true} {
|
||||
name := "unchanged"
|
||||
if change {
|
||||
name = "one_row"
|
||||
}
|
||||
b.Run(name, func(b *testing.B) {
|
||||
s := gputest.RowsScene(3456, 2000, 200)
|
||||
d := scene.Differ{Reach: 2}
|
||||
d.Diff(s)
|
||||
d.Remember(s)
|
||||
for i := 0; b.Loop(); i++ {
|
||||
if change {
|
||||
s.Ops[len(s.Ops)/2].Color.R = byte(i)
|
||||
}
|
||||
d.Diff(s)
|
||||
d.Remember(s)
|
||||
}
|
||||
b.ReportMetric(float64(len(s.Ops)), "ops")
|
||||
b.ReportMetric(float64(len(s.Glyphs)), "glyphs")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBuildRows(b *testing.B) {
|
||||
s := gputest.RowsScene(3456, 2000, 200)
|
||||
bld := Builder{Classes: true, ClipSkip: true, Opaque: true}
|
||||
image := func(*scene.Image) uintptr { return 1 }
|
||||
for b.Loop() {
|
||||
bld.Build(s, image)
|
||||
}
|
||||
b.ReportMetric(float64(len(bld.Instances)), "instances")
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Continuous corners (negative radii) cost Metal's shader far more than
|
||||
// circular ones: a fill's coverage near them is their value and its two
|
||||
// derivatives, and a blurred shadow finds, for each of its four rows of
|
||||
// samples, where the curve is by regula falsi. A batch holding any of them
|
||||
// draws with a pipeline holding that code, which every fragment of the batch
|
||||
// pays for, curved or not. Yet the curves shape only the pixels near the
|
||||
// corners: elsewhere the shader computes exactly what it computes for a
|
||||
// rectangle with square corners, by the same code (see cornerLines). So a
|
||||
// large shape with continuous corners is drawn as a nine-patch, as
|
||||
// compositors draw rounded rectangles: its corners as the shape, each
|
||||
// piece with a scissor rectangle of its own, and the rest, a cross, as its
|
||||
// twin with square corners, in batches of a pipeline without the curves.
|
||||
// The pixels are identical.
|
||||
|
||||
// contExtent is how far from its corner the curve of a continuous corner of
|
||||
// radius 1 leaves the edges (the shaders' contExtent).
|
||||
const contExtent = 1.528665
|
||||
|
||||
// pieceCost is what a piece of a nine-patch costs, a draw call of its own
|
||||
// (no piece shares a batch: each has a scissor rectangle of its own), in
|
||||
// pixels of the twin: on an M5 a draw call costs about 1.2 µs of the CPU
|
||||
// and the GPU, and a pixel drawn by the twin rather than the shape about
|
||||
// 0.08 ns less, by the overhead of the curves' code in a pipeline. A pixel
|
||||
// of a shadow in the rows its curve shapes, between its corners, saves
|
||||
// curvedWeight times more: the curve is found there for each sample, by
|
||||
// regula falsi (0.5 ns a pixel).
|
||||
const (
|
||||
pieceCost = 16384
|
||||
curvedWeight = 6
|
||||
)
|
||||
|
||||
// SplitCorners makes the builder draw large shapes with continuous corners
|
||||
// as nine-patches (see addCorners), for a renderer whose shader draws them
|
||||
// (Metal's), and cut clips with continuous corners in that shader where it
|
||||
// cuts circular ones (analyticClip). Only through it do apps link that
|
||||
// code, which the other renderers' apps never run.
|
||||
func (b *Builder) SplitCorners() { b.cutCorners, b.contClips = (*Builder).addCorners, true }
|
||||
|
||||
// addCut appends in, a fill, a shadow or an image, within the current
|
||||
// clip's or split's scissor rectangle: as a nine-patch where the builder
|
||||
// splits corners (addCorners), else whole.
|
||||
func (b *Builder) addCut(in Instance, image uintptr, m scene.Affine) {
|
||||
if b.cutCorners != nil && !b.NoCornerSplit {
|
||||
b.cutCorners(b, in, image, m)
|
||||
return
|
||||
}
|
||||
b.add(in, image, m)
|
||||
}
|
||||
|
||||
// cornerLines returns where the pixels lie that the continuous corners
|
||||
// of radii (positive) of the rectangle r cannot reach: the columns from
|
||||
// Left to Right and the rows from Top to Bottom, each as far in, from the
|
||||
// sides, as the curves reach (contExtent times the radius) and, by reachX
|
||||
// and reachY, beyond. A pixel in neither is in one of the corners' boxes,
|
||||
// which reach out of the rectangle to the frame's edges. The shaders compute
|
||||
// a corner's curve only at a pixel within its box (contValue tests u and v
|
||||
// against e), and anywhere else the area of the pixel in the rectangle, as
|
||||
// for square corners.
|
||||
func cornerLines(r scene.Rect, radii [4]float32, reachX, reachY float32) Scissor {
|
||||
e := func(i, j int) float32 { return contExtent*max(abs32(radii[i]), abs32(radii[j])) + 1 }
|
||||
return Scissor{
|
||||
Left: int32(math.Ceil(float64(r.X + e(0, 3) + reachX))),
|
||||
Top: int32(math.Ceil(float64(r.Y + e(0, 1) + reachY))),
|
||||
Right: int32(math.Floor(float64(r.X + r.W - e(1, 2) - reachX))),
|
||||
Bottom: int32(math.Floor(float64(r.Y + r.H - e(2, 3) - reachY))),
|
||||
}
|
||||
}
|
||||
|
||||
func abs32(v float32) float32 {
|
||||
if v < 0 {
|
||||
return -v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func continuous(r [4]float32) bool { return r[0] < 0 || r[1] < 0 || r[2] < 0 || r[3] < 0 }
|
||||
|
||||
// cornersOf returns, for a fill, an image or a shadow with continuous
|
||||
// corners, not transformed, where it and its twin with square corners (no
|
||||
// radii, on its border's inner edge or its caster neither) draw the same,
|
||||
// as the lines that bound those pixels (see cornerLines), the pixels its
|
||||
// quad covers, as the vertex shader grows it, and how much more a pixel
|
||||
// of the twin between the corners saves than one between the bands of
|
||||
// rows across them; ok is false for any other instance.
|
||||
//
|
||||
// A fill's twin computes its border's inner edge the same way too, whose
|
||||
// curves lie within the outer ones' boxes: each of its corners is a
|
||||
// border's width or more in from the outer one, and its radius smaller by
|
||||
// the larger of the two widths (scene.InnerRadii).
|
||||
//
|
||||
// A shadow's blur, of standard deviation sigma, takes all its corners as
|
||||
// the largest (boxShadow), and the curve shapes the rows of its samples
|
||||
// that lie within the curve's reach of the top or the bottom, the samples
|
||||
// reaching 3 sigma from the pixel. At a pixel whose samples all lie outside
|
||||
// those rows the shader finds the sides straight, as for square corners;
|
||||
// at one in those rows but 9 sigma or more from where the curve can put the
|
||||
// sides, the blurred edges are exactly 0 and 1 (erf2 rounds to ±1 from about
|
||||
// 7.7 sigma), wherever the curve puts them. The box casting it, cut out of
|
||||
// the shadow, is a fill's coverage.
|
||||
func cornersOf(in *Instance, m scene.Affine) (free, quad Scissor, weight int64, ok bool) {
|
||||
shadow := in.Params[0] == 1
|
||||
if m.Set || !continuous(in.Radii) && !(shadow && continuous(in.Inner)) {
|
||||
return Scissor{}, Scissor{}, 0, false
|
||||
}
|
||||
r := scene.Rect{X: in.Rect[0], Y: in.Rect[1], W: in.Rect[2], H: in.Rect[3]}
|
||||
grow := func(e float32) Scissor {
|
||||
return Scissor{int32(math.Floor(float64(r.X - e))), int32(math.Floor(float64(r.Y - e))),
|
||||
int32(math.Ceil(float64(r.X + r.W + e))), int32(math.Ceil(float64(r.Y + r.H + e)))}
|
||||
}
|
||||
if !shadow {
|
||||
return cornerLines(r, in.Radii, 0, 0), grow(1), 1, true
|
||||
}
|
||||
sigma := in.Params[2]
|
||||
corner := max(abs32(in.Radii[0]), abs32(in.Radii[1]), abs32(in.Radii[2]), abs32(in.Radii[3]))
|
||||
free = cornerLines(r, [4]float32{corner, corner, corner, corner}, 9*sigma, 3*sigma)
|
||||
if in.UV[2] > 0 && in.UV[3] > 0 {
|
||||
free = free.intersect(cornerLines(scene.Rect{X: in.UV[0], Y: in.UV[1], W: in.UV[2], H: in.UV[3]}, in.Inner, 0, 0))
|
||||
}
|
||||
return free, grow(3*sigma + 1), curvedWeight, true
|
||||
}
|
||||
|
||||
// addCorners appends in as a nine-patch within the batches' scissor
|
||||
// rectangle, when the pixels its twin draws save more than the draw calls
|
||||
// of the pieces cost (pieceCost): its corners as it is and the rest as its
|
||||
// twin. The band of rows between the corners is all the twin's; each band
|
||||
// of rows across them is the shape's, or, where enough lies between the
|
||||
// corners, the shape's at its ends and the twin's between. Small shapes,
|
||||
// whose pixels are near their corners, stay whole, and join their
|
||||
// neighbors' batches (see joinLast).
|
||||
func (b *Builder) addCorners(in Instance, image uintptr, m scene.Affine) {
|
||||
f, quad, weight, ok := cornersOf(&in, m)
|
||||
if !ok {
|
||||
b.add(in, image, m)
|
||||
return
|
||||
}
|
||||
cur := &b.stack[len(b.stack)-1]
|
||||
region := b.batchScissor(cur).intersect(quad)
|
||||
if f.Top > f.Bottom {
|
||||
// Every row is near a corner: either band can hold those between.
|
||||
f.Top = f.Bottom
|
||||
}
|
||||
top := Scissor{region.Left, region.Top, region.Right, f.Top}.intersect(region)
|
||||
mid := Scissor{region.Left, f.Top, region.Right, f.Bottom}.intersect(region)
|
||||
bottom := Scissor{region.Left, f.Bottom, region.Right, region.Bottom}.intersect(region)
|
||||
var pieces [7]Scissor // the shape's, then the twin's
|
||||
var twin [7]bool
|
||||
n := 0
|
||||
piece := func(s Scissor, t bool) {
|
||||
if !s.Empty() {
|
||||
pieces[n], twin[n] = s, t
|
||||
n++
|
||||
}
|
||||
}
|
||||
saved := mid.area()
|
||||
var between [2]Scissor
|
||||
for i, band := range [2]Scissor{top, bottom} {
|
||||
c := Scissor{f.Left, band.Top, f.Right, band.Bottom}.intersect(band)
|
||||
left := Scissor{band.Left, band.Top, c.Left, band.Bottom}
|
||||
right := Scissor{c.Right, band.Top, band.Right, band.Bottom}
|
||||
// Splitting the band adds its ends' draw calls.
|
||||
if c.Empty() || c.area()*weight <= pieceCost*int64(min(1, left.area())+min(1, right.area())) {
|
||||
piece(band, false)
|
||||
continue
|
||||
}
|
||||
piece(left, false)
|
||||
piece(right, false)
|
||||
between[i] = c
|
||||
saved += c.area() * weight
|
||||
}
|
||||
piece(mid, true)
|
||||
piece(between[0], true)
|
||||
piece(between[1], true)
|
||||
if n == 0 || saved <= pieceCost*int64(n-1) {
|
||||
b.add(in, image, m)
|
||||
return
|
||||
}
|
||||
sq := in
|
||||
sq.Radii, sq.Inner = [4]float32{}, [4]float32{}
|
||||
split, splitScissor := b.split, b.splitScissor
|
||||
defer b.scissorBatches(splitScissor, split)
|
||||
for i, s := range pieces[:n] {
|
||||
b.scissorBatches(s, true)
|
||||
if twin[i] {
|
||||
b.add(sq, image, m)
|
||||
} else {
|
||||
b.add(in, image, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Occlusion culling. A later opaque fill replaces what the ops before it
|
||||
// drew inside the part of its shape where its coverage is exactly 1, and
|
||||
// blending it leaves nothing of the destination (the destination times
|
||||
// one minus the source's alpha, plus the source), so an op whose pixels all
|
||||
// lie in that part never shows. Windows stack such fills (a page, a panel
|
||||
// on it, a card on that), and a renderer shading every layer of a window
|
||||
// spends its fill rate on pixels that are overwritten: 1.9 ms of GPU time
|
||||
// for each full-window layer on an M1 Pro at 3456×2000.
|
||||
//
|
||||
// planCull finds those ops in a pass over the scene backwards, which keeps
|
||||
// the few largest occluders seen so far, and Build leaves the ops out. The
|
||||
// result is identical to drawing them; the rules that make it so are in
|
||||
// occluderOf and visibleOf.
|
||||
|
||||
// cullOccluders is how many occluders the backward pass keeps. The largest
|
||||
// cover the most; a bound keeps the pass linear in the ops.
|
||||
const cullOccluders = 8
|
||||
|
||||
// cullMargin returns how far, in pixels, the antialiased edge of an op with
|
||||
// the transform m reaches out of its rectangle: a pixel whose center is
|
||||
// within half a pixel of the edge is covered in part, and the shader draws
|
||||
// one more around a quad it maps. A transformed quad is grown by the map's
|
||||
// reach in the shader (see its vertex stage), a pixel or two.
|
||||
func cullMargin(m scene.Affine) float32 {
|
||||
if m.Set {
|
||||
return 3
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
type cullInfo struct {
|
||||
// vis holds what the op can change: its bounds within its clip's
|
||||
// scissor rectangle. Empty for ops that cannot be culled.
|
||||
vis Scissor
|
||||
// occ is the part of the frame the op, as an occluder, certainly
|
||||
// covers whole: empty unless it qualifies.
|
||||
occ Scissor
|
||||
// barrier tells that the op reads the frame drawn so far (an effect
|
||||
// with a backdrop), so what comes after it cannot hide what came
|
||||
// before.
|
||||
barrier bool
|
||||
}
|
||||
|
||||
// shadowSupport returns the rectangle, in the shadow's own units, outside
|
||||
// which the shadow op draws nothing: its box (the caster's, for an inner
|
||||
// shadow), grown by the blur. The vertex shaders grow the quad of a shadow by
|
||||
// 3 sigma + 1 = 1.5 blur + 1 before mapping it, and the blur is evaluated in
|
||||
// those units, so a transform scales the reach with the rest of the shape:
|
||||
// the margin is added here, before the map, not in device pixels after it.
|
||||
// 2 blur + 1 has slack over the shader's growth. addShadow's reach (3 sigma)
|
||||
// is the same bound, as the shader has it.
|
||||
func shadowSupport(op *scene.Op) scene.Rect {
|
||||
r := op.Rect
|
||||
if op.Inset {
|
||||
r = op.Cast
|
||||
}
|
||||
// Negative blur is a hard shadow, as Build clamps its sigma to zero.
|
||||
g := 2*max(op.Blur, 0) + 1
|
||||
return scene.Rect{X: r.X - g, Y: r.Y - g, W: r.W + 2*g, H: r.H + 2*g}
|
||||
}
|
||||
|
||||
// planCull sets b.culled to the ops that later opaque fills cover whole.
|
||||
func (b *Builder) planCull(s *scene.Scene) {
|
||||
n := len(s.Ops)
|
||||
if cap(b.culled) < n {
|
||||
b.culled = make([]bool, n)
|
||||
}
|
||||
b.culled = b.culled[:n]
|
||||
clear(b.culled)
|
||||
b.Culled = 0
|
||||
if b.NoCull || n < 2 {
|
||||
return
|
||||
}
|
||||
// Sprite and glyph-only scenes have nothing that can hide an earlier op.
|
||||
// Avoid their bounds pass and per-op planning storage entirely. This is
|
||||
// deliberately conservative: clipping and wide alpha are checked below.
|
||||
candidate := false
|
||||
for i := range s.Ops {
|
||||
op := &s.Ops[i]
|
||||
if op.Kind == scene.OpFill && op.Paint == scene.PaintSolid && op.Color.A == 255 &&
|
||||
!op.Transform.Set && (op.Opacity == 0 || op.Opacity == 1) {
|
||||
candidate = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !candidate {
|
||||
return
|
||||
}
|
||||
if cap(b.plan) < n {
|
||||
b.plan = make([]cullInfo, n)
|
||||
}
|
||||
plan := b.plan[:n]
|
||||
clear(plan)
|
||||
|
||||
// Forwards: what each op can change, and what it certainly covers,
|
||||
// with the clips as Build keeps them.
|
||||
root := clip{rect: scene.Rect{X: -1e6, Y: -1e6, W: 2e6, H: 2e6}, bounds: scene.Rect{W: float32(s.Width), H: float32(s.Height)},
|
||||
scissor: Scissor{0, 0, int32(s.Width), int32(s.Height)}, maskSlot: -1}
|
||||
stack := append(b.planStack[:0], root)
|
||||
haveOccluder := false
|
||||
for i := range s.Ops {
|
||||
op := &s.Ops[i]
|
||||
cur := &stack[len(stack)-1]
|
||||
switch op.Kind {
|
||||
case scene.OpPushClip:
|
||||
stack = append(stack, b.pushed(s, cur, op, i))
|
||||
case scene.OpPopClip:
|
||||
if len(stack) > 1 {
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
case scene.OpEffect:
|
||||
if int(op.Start) < len(s.Effects) && s.Effects[op.Start].Effect != nil && s.Effects[op.Start].Effect.Backdrop {
|
||||
plan[i].barrier = true
|
||||
}
|
||||
case scene.OpFill:
|
||||
if op.Rect.Empty() {
|
||||
continue
|
||||
}
|
||||
plan[i].vis = visibleOf(cur.scissor, op.Transform.Bounds(op.Rect), cullMargin(op.Transform))
|
||||
plan[i].occ = b.occluderOf(s, op, cur)
|
||||
haveOccluder = haveOccluder || !plan[i].occ.Empty()
|
||||
case scene.OpShadow:
|
||||
if op.Rect.Empty() && !(op.Inset && !op.Cast.Empty()) {
|
||||
continue
|
||||
}
|
||||
plan[i].vis = visibleOf(cur.scissor, op.Transform.Bounds(shadowSupport(op)), cullMargin(op.Transform))
|
||||
case scene.OpHole, scene.OpImage:
|
||||
if !op.Rect.Empty() {
|
||||
plan[i].vis = visibleOf(cur.scissor, op.Transform.Bounds(op.Rect), cullMargin(op.Transform))
|
||||
}
|
||||
case scene.OpGlyphs:
|
||||
// The run's quads are measured in the backward pass, when
|
||||
// an occluder can hide them.
|
||||
plan[i].vis = cur.scissor
|
||||
}
|
||||
}
|
||||
b.planStack = stack[:0]
|
||||
if !haveOccluder {
|
||||
return
|
||||
}
|
||||
|
||||
// Backwards: an op inside an occluder after it is left out.
|
||||
var occ [cullOccluders]Scissor
|
||||
var area [cullOccluders]int64
|
||||
count := 0
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
op := &s.Ops[i]
|
||||
pi := &plan[i]
|
||||
if pi.barrier {
|
||||
count = 0
|
||||
continue
|
||||
}
|
||||
if count > 0 {
|
||||
vis := pi.vis
|
||||
if op.Kind == scene.OpGlyphs {
|
||||
vis = glyphsVisible(s, op, pi.vis)
|
||||
}
|
||||
if !vis.Empty() {
|
||||
for k := 0; k < count; k++ {
|
||||
if occ[k].contains(vis) {
|
||||
b.culled[i] = true
|
||||
b.Culled++
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if pi.occ.Empty() {
|
||||
continue
|
||||
}
|
||||
a := pi.occ.area()
|
||||
if count < cullOccluders {
|
||||
occ[count], area[count] = pi.occ, a
|
||||
count++
|
||||
continue
|
||||
}
|
||||
small := 0
|
||||
for k := 1; k < count; k++ {
|
||||
if area[k] < area[small] {
|
||||
small = k
|
||||
}
|
||||
}
|
||||
if a > area[small] {
|
||||
occ[small], area[small] = pi.occ, a
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s Scissor) contains(o Scissor) bool {
|
||||
return s.Left <= o.Left && s.Top <= o.Top && s.Right >= o.Right && s.Bottom >= o.Bottom
|
||||
}
|
||||
|
||||
// visibleOf returns the pixels that something within bounds, grown by margin
|
||||
// for its antialiased edge, can change within the scissor rectangle sc.
|
||||
func visibleOf(sc Scissor, bounds scene.Rect, margin float32) Scissor {
|
||||
if sc.Empty() {
|
||||
return Scissor{}
|
||||
}
|
||||
x0 := math.Max(math.Floor(float64(bounds.X-margin)), float64(sc.Left))
|
||||
y0 := math.Max(math.Floor(float64(bounds.Y-margin)), float64(sc.Top))
|
||||
x1 := math.Min(math.Ceil(float64(bounds.X+bounds.W+margin)), float64(sc.Right))
|
||||
y1 := math.Min(math.Ceil(float64(bounds.Y+bounds.H+margin)), float64(sc.Bottom))
|
||||
if !(x1 > x0 && y1 > y0) { // also NaN
|
||||
return Scissor{}
|
||||
}
|
||||
return Scissor{int32(x0), int32(y0), int32(x1), int32(y1)}
|
||||
}
|
||||
|
||||
// glyphsVisible returns what a run of glyphs, an OpGlyphs, can change: the
|
||||
// union of its glyphs' quads within the scissor rectangle sc of its clip.
|
||||
func glyphsVisible(s *scene.Scene, op *scene.Op, sc Scissor) Scissor {
|
||||
if sc.Empty() || op.Start < 0 || int(op.End) > len(s.Glyphs) || op.Start >= op.End {
|
||||
return Scissor{}
|
||||
}
|
||||
var u scene.Rect
|
||||
first := true
|
||||
margin := float32(0)
|
||||
for _, g := range s.Glyphs[op.Start:op.End] {
|
||||
m := op.Transform.Mul(g.Transform)
|
||||
margin = max(margin, cullMargin(m))
|
||||
r := m.Bounds(scene.Rect{X: float32(math.Round(float64(g.X))), Y: float32(math.Round(float64(g.Y))), W: float32(g.UW), H: float32(g.VH)})
|
||||
if first {
|
||||
u, first = r, false
|
||||
continue
|
||||
}
|
||||
x0, y0 := min(u.X, r.X), min(u.Y, r.Y)
|
||||
x1, y1 := max(u.X+u.W, r.X+r.W), max(u.Y+u.H, r.Y+r.H)
|
||||
u = scene.Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}
|
||||
}
|
||||
if first {
|
||||
return Scissor{}
|
||||
}
|
||||
return visibleOf(sc, u, margin)
|
||||
}
|
||||
|
||||
// occluderOf returns the pixels that the fill op, within cur, certainly
|
||||
// paints with its own opaque color, or the empty rectangle. That takes a
|
||||
// solid paint of alpha 1 and opacity 1, untransformed (so that the
|
||||
// coverage is the plain rectangle's), under a clip that is a plain
|
||||
// rectangle too (no mask, no rounded corners: their antialiased edge
|
||||
// covers by less than 1). It excludes the antialiased edge and the curves
|
||||
// of the corners, as a shadow's caster does (shadowCore), and a border's
|
||||
// width, so the part left is all the fill's color; except for the sides
|
||||
// of a rectangle that lie outside the scissor rectangle, where no edge
|
||||
// shows.
|
||||
func (b *Builder) occluderOf(s *scene.Scene, op *scene.Op, cur *clip) Scissor {
|
||||
if op.Transform.Set || op.Paint != scene.PaintSolid || op.Color.A != 255 || (op.Opacity != 0 && op.Opacity != 1) ||
|
||||
cur.masked || cur.radii != [4]float32{} || cur.scissor.Empty() {
|
||||
return Scissor{}
|
||||
}
|
||||
if w := b.wideOf(s, op.Wide); w != nil && w.Set&scene.WideColor != 0 && w.Color[3] != 1 {
|
||||
return Scissor{}
|
||||
}
|
||||
radii := scene.Corners(op.Rect, op.Radii, op.Continuous)
|
||||
core := shadowCore(op.Rect, radii, op.Continuous)
|
||||
bw := [4]float32{}
|
||||
if op.BorderColor.A != 0 {
|
||||
bw = op.Border
|
||||
}
|
||||
if scene.HasBorder(bw) {
|
||||
w := int32(math.Ceil(float64(max(bw[0], bw[1], bw[2], bw[3]))))
|
||||
core = Scissor{core.Left + w, core.Top + w, core.Right - w, core.Bottom - w}
|
||||
}
|
||||
if radii == [4]float32{} {
|
||||
// A rectangle with square corners whose side lies at or beyond the
|
||||
// scissor rectangle (a layer as large as the window) has no edge
|
||||
// to antialias there: each pixel of the scissor rectangle is inside
|
||||
// it, and covered by 1 exactly.
|
||||
r, sc := op.Rect, cur.scissor
|
||||
if r.X <= float32(sc.Left) && bw[3] == 0 {
|
||||
core.Left = sc.Left
|
||||
}
|
||||
if r.Y <= float32(sc.Top) && bw[0] == 0 {
|
||||
core.Top = sc.Top
|
||||
}
|
||||
if r.X+r.W >= float32(sc.Right) && bw[1] == 0 {
|
||||
core.Right = sc.Right
|
||||
}
|
||||
if r.Y+r.H >= float32(sc.Bottom) && bw[2] == 0 {
|
||||
core.Bottom = sc.Bottom
|
||||
}
|
||||
}
|
||||
// The clip's rectangle covers whole the pixels inside it.
|
||||
inner := Scissor{
|
||||
int32(math.Ceil(float64(cur.rect.X))), int32(math.Ceil(float64(cur.rect.Y))),
|
||||
int32(math.Floor(float64(cur.rect.X + cur.rect.W))), int32(math.Floor(float64(cur.rect.Y + cur.rect.H))),
|
||||
}
|
||||
return core.intersect(cur.scissor).intersect(inner)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Fractional viewports can remove whole card corners without a mask, while overlapping antialiasing must keep its original pixel coverage.
|
||||
func TestReducedClipCoverageMatchesCPU(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
hwnd, err := newHiddenWindow(256, 224)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
t.Skip("Direct3D 11 unavailable:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for _, name := range []string{"lyrics", "left", "top", "right", "bottom", "asymmetric", "opaque-rounded-parent", "duplicate-fractional", "near-fractional", "outside-fractional", "cuts-corner", "duplicate-rounded", "continuous-card", "continuous-cut", "asymmetric-midpoint"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
card := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 200, H: 160}, Radii: [4]float32{10, 10, 10, 10}}
|
||||
hard := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 256, H: 224}}
|
||||
wantMask := false
|
||||
switch name {
|
||||
case "continuous-card":
|
||||
card.Continuous, wantMask = true, true
|
||||
case "lyrics":
|
||||
// The measured opening card and lyrics viewport, scaled by 1/8.
|
||||
card.Rect, card.Radii = scene.Rect{X: 26.25, Y: 73.25, W: 175.875, H: 118.125}, [4]float32{0.8283625, 0.8283625, 0.8283625, 0.8283625}
|
||||
hard.Rect = scene.Rect{X: 120.25, Y: 27.189285, W: 153.5, H: 159.25}
|
||||
case "left":
|
||||
hard.Rect.X, hard.Rect.W = 50.25, 200
|
||||
case "top":
|
||||
hard.Rect.Y, hard.Rect.H = 50.25, 170
|
||||
case "right":
|
||||
hard.Rect.W = 180.25
|
||||
case "bottom":
|
||||
hard.Rect.H = 140.25
|
||||
case "asymmetric":
|
||||
card.Radii, hard.Rect.X = [4]float32{8, 12, 16, 20}, 70.25
|
||||
case "opaque-rounded-parent":
|
||||
card.Rect, card.Radii = scene.Rect{W: 256, H: 224}, [4]float32{10, 10, 10, 10}
|
||||
hard.Rect, hard.Radii = scene.Rect{X: 50.25, Y: 50.25, W: 150, H: 100}, [4]float32{8, 8, 8, 8}
|
||||
case "duplicate-fractional", "near-fractional", "outside-fractional":
|
||||
card.Rect.X, hard.Rect.X, wantMask = 20.25, 20.25, true
|
||||
if name == "near-fractional" {
|
||||
hard.Rect.X = 20.5
|
||||
} else if name == "outside-fractional" {
|
||||
hard.Rect.X = 20.125
|
||||
}
|
||||
case "cuts-corner":
|
||||
hard.Rect.X, wantMask = 25.25, true
|
||||
case "duplicate-rounded":
|
||||
hard, wantMask = card, true
|
||||
case "continuous-cut":
|
||||
card.Continuous, hard.Rect.X, wantMask = true, 70.25, true
|
||||
case "asymmetric-midpoint":
|
||||
card.Radii, hard.Rect.W, wantMask = [4]float32{70, 0, 0, 0}, 140.25, true
|
||||
}
|
||||
for _, transform := range []scene.Affine{{}, scene.Scaling(1.01, 1.01), scene.Rotation(11), scene.Projective(1, 0, 0, 1, 0, 0, 0.001, 0.0004)} {
|
||||
if name == "continuous-card" && !transform.Set {
|
||||
continue // the existing untransformed path uses the shader
|
||||
}
|
||||
s := &scene.Scene{Width: 256, Height: 224, Clear: scene.Color{A: 255}, Ops: []scene.Op{card, hard,
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: -200, Y: -200, W: 2000, H: 2000}, Color: scene.Color{R: 255, G: 255, B: 255, A: 255}, Transform: transform},
|
||||
{Kind: scene.OpPopClip}, {Kind: scene.OpPopClip},
|
||||
}}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if (len(r.images) > 0) != wantMask {
|
||||
t.Fatalf("transform=%v: mask textures=%d, want mask=%t", transform, len(r.images), wantMask)
|
||||
}
|
||||
pix, stride, err := r.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(ref, s)
|
||||
maxDiff, total := 0, 0
|
||||
for y := range s.Height {
|
||||
for x := range s.Width {
|
||||
diff := int(pix[y*stride+4*x]) - int(ref.Pix[y*ref.Stride+4*x])
|
||||
if diff < 0 {
|
||||
diff = -diff
|
||||
}
|
||||
maxDiff, total = max(maxDiff, diff), total+diff
|
||||
}
|
||||
}
|
||||
if maxDiff > 2 || float64(total)/float64(s.Width*s.Height) > 0.03 {
|
||||
t.Fatalf("transform=%v: clip coverage differs from CPU: max=%d mean=%f", transform, maxDiff, float64(total)/float64(s.Width*s.Height))
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// A stationary or translated rounded card clips its content and hard children without uploading a whole-card mask.
|
||||
func TestRoundedCardClipsTransformedContentWithoutMask(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
hwnd, err := newHiddenWindow(192, 160)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
t.Skip("Direct3D 11 unavailable:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for _, moved := range []bool{false, true} {
|
||||
move := scene.Affine{}
|
||||
if moved {
|
||||
move = scene.Translation(5, 7)
|
||||
}
|
||||
for _, inner := range []bool{false, true} {
|
||||
for _, transform := range []scene.Affine{{}, scene.Scaling(1.01, 1.01), scene.Rotation(11), scene.Projective(1, 0, 0, 1, 20, 15, 0.001, 0.0004)} {
|
||||
s := &scene.Scene{Width: 192, Height: 160, Clear: scene.Color{A: 255}}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 13, Y: 11, W: 133, H: 117}, Radii: [4]float32{19, 19, 19, 19}, Transform: move})
|
||||
if inner {
|
||||
// #1418: a hard child reaching into its rounded parent's
|
||||
// bottom corners must retain those corners; #1420 also
|
||||
// folds a shared translation into the clips' frame positions.
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 13, Y: 70, W: 133, H: 58}, Transform: move})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 190, H: 150}, Color: scene.Color{R: 255, G: 255, B: 255, A: 255}, Transform: transform})
|
||||
if inner {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(r.images) != 0 {
|
||||
t.Fatalf("moved=%t inner=%t transform=%v: rounded card uploaded %d mask textures", moved, inner, transform, len(r.images))
|
||||
}
|
||||
pix, stride, err := r.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(ref, s)
|
||||
maxDiff, totalDiff := 0, 0
|
||||
for y := range s.Height {
|
||||
for x := range s.Width {
|
||||
// This grayscale fixture has equal RGB channels in BGRA and RGBA.
|
||||
d := int(pix[y*stride+4*x]) - int(ref.Pix[y*ref.Stride+4*x])
|
||||
if d < 0 {
|
||||
d = -d
|
||||
}
|
||||
maxDiff = max(maxDiff, d)
|
||||
totalDiff += d
|
||||
}
|
||||
}
|
||||
if maxDiff > 20 || float64(totalDiff)/float64(s.Width*s.Height) > 0.2 {
|
||||
t.Fatalf("moved=%t inner=%t transform=%v: rounded coverage differs from CPU: max=%d mean=%f", moved, inner, transform, maxDiff, float64(totalDiff)/float64(s.Width*s.Height))
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkRenderSprites draws frames of a 2D game at 1920×1080
|
||||
// (gputest's SpriteScene: 1,872 sprites of one sheet) and reads each
|
||||
// back, which waits for it; with WARP where no GPU runs it, as on CI.
|
||||
func BenchmarkRenderSprites(b *testing.B) {
|
||||
benchRender(b, gputest.SpriteScene(1920, 1080, 3, 3, 300))
|
||||
}
|
||||
|
||||
// BenchmarkRenderEmpty draws frames of nothing at 1920×1080: what the
|
||||
// sprites' frames spend besides them.
|
||||
func BenchmarkRenderEmpty(b *testing.B) {
|
||||
benchRender(b, &scene.Scene{Width: 1920, Height: 1080, Clear: scene.Color{A: 255}})
|
||||
}
|
||||
|
||||
func benchRender(b *testing.B, s *scene.Scene) {
|
||||
hwnd, err := newHiddenWindow(s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer r.Release()
|
||||
for b.Loop() {
|
||||
if err := r.draw(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if _, _, err := r.read(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Canvases draw into textures as the CPU renderer draws them into pixels,
|
||||
// once each: the second frame draws none anew, and shows them the same.
|
||||
func TestCanvases(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.CanvasScene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for frame := range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-canvas", pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame == 0 {
|
||||
s.Canvases = nil
|
||||
}
|
||||
}
|
||||
if len(r.canvases) != 3 {
|
||||
t.Errorf("%d canvas textures, want 3", len(r.canvases))
|
||||
}
|
||||
}
|
||||
|
||||
// A transient canvas's texture stays while frames draw it, and goes once
|
||||
// they stop, though the canvas is still about; another canvas's stays
|
||||
// until it is collected.
|
||||
func TestTransientCanvas(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 64, 64))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
layer, kept := scene.NewCanvas(64, 64), scene.NewCanvas(64, 64)
|
||||
layer.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64, Canvases: []*scene.Image{layer, kept}}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] == nil || r.canvases[kept.ID()] == nil {
|
||||
t.Fatal("a sweep after the frame that drew them freed a canvas's texture")
|
||||
}
|
||||
r.frame++ // a frame that draws neither
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] != nil || r.canvases[kept.ID()] == nil {
|
||||
t.Errorf("transient canvas kept %v, other kept %v", r.canvases[layer.ID()] != nil, r.canvases[kept.ID()] != nil)
|
||||
}
|
||||
runtime.KeepAlive(layer)
|
||||
runtime.KeepAlive(kept)
|
||||
}
|
||||
|
||||
// Frames that present sweep the textures of earlier frames' transient
|
||||
// canvases even when every frame between them changes nothing: those
|
||||
// count as frames too, and sweeping only at multiples of 120 frames, an
|
||||
// animation that drew every other frame presented none of them, and kept
|
||||
// a texture for each of its frames' canvases.
|
||||
func TestSweepBetweenUnchangedFrames(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 64, 64))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 3 * sweepEvery {
|
||||
c := scene.NewCanvas(16, 16)
|
||||
c.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64, Canvases: []*scene.Image{c}}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.frame++ // a frame that changes nothing, and presents nothing
|
||||
}
|
||||
if n := len(r.canvases); n > sweepEvery {
|
||||
t.Errorf("%d canvas textures after %d frames drawn, want at most %d", n, 3*sweepEvery, sweepEvery)
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
// The shaders of the classes of batches (gpu.Class), after shader.hlsl, whose
|
||||
// functions they share, with CLASSES defined, a bit (1 << gpu.Class) for each
|
||||
// class they draw, and PLAIN, FILL, SHADOW, GLYPH, SUBPIXEL and IMAGE, each 1 if
|
||||
// they draw it, as FXC's preprocessor cannot test the bits. A class's instances
|
||||
// are not transformed, so these leave out the general shader's coordinates, and
|
||||
// pass on only what their paths read; flow control skips what a fragment needs
|
||||
// not, and only subpixel glyphs write a second color for dual-source blending:
|
||||
// the others blend by their alpha, which is that color for them. They draw the
|
||||
// pixels the general shader does.
|
||||
//
|
||||
// `go generate` compiles them to DXBC (shaders.go) on Windows.
|
||||
|
||||
struct ClassOut {
|
||||
float4 pos : SV_Position;
|
||||
float4 pt : PIXEL; // the position in pixels, and the texture coordinates
|
||||
#if PLAIN || FILL || SHADOW || IMAGE
|
||||
nointerpolation float4 rect : RECT;
|
||||
#endif
|
||||
nointerpolation float4 radii : RADII;
|
||||
#if FILL || SHADOW || GLYPH || SUBPIXEL
|
||||
nointerpolation float4 inner : INNER;
|
||||
#endif
|
||||
nointerpolation float4 color : COLOR0;
|
||||
#if FILL || GLYPH || SUBPIXEL
|
||||
nointerpolation float4 color2 : COLOR1;
|
||||
nointerpolation float4 grad : GRAD;
|
||||
#endif
|
||||
#if FILL
|
||||
nointerpolation float4 border : COLOR2;
|
||||
#endif
|
||||
#if FILL || SHADOW || IMAGE
|
||||
nointerpolation float4 widths : WIDTHS;
|
||||
#endif
|
||||
nointerpolation float4 clip : CLIP;
|
||||
nointerpolation float4 clipRadii : CLIPR;
|
||||
// The kind, plus 8 times how the clip applies (gpu.Instance's
|
||||
// Transform1.w); the rest as gpu.Instance's Params.
|
||||
nointerpolation float4 params : PARAMS;
|
||||
};
|
||||
|
||||
ClassOut classvs(uint vid : SV_VertexID, Inst i) {
|
||||
float2 corner = float2(vid & 1, vid >> 1);
|
||||
float kind = i.params.x;
|
||||
float e = kind < 0.5 ? 1 : kind < 1.5 ? 3 * i.params.z + 1 : 0;
|
||||
float4 r = float4(i.rect.xy - e, i.rect.zw + 2 * e);
|
||||
float2 p = r.xy + corner * r.zw;
|
||||
ClassOut o;
|
||||
o.pos = float4(p / viewport * float2(2, -2) + float2(-1, 1), 0, 1);
|
||||
o.pt.xy = p;
|
||||
o.pt.zw = i.uv.xy + (p - i.rect.xy) / i.rect.zw * (i.uv.zw - i.uv.xy);
|
||||
#if PLAIN || FILL || SHADOW || IMAGE
|
||||
o.rect = i.rect;
|
||||
#endif
|
||||
o.radii = i.radii;
|
||||
#if FILL || SHADOW || GLYPH || SUBPIXEL
|
||||
o.inner = i.inner;
|
||||
#endif
|
||||
o.color = i.color;
|
||||
#if FILL || GLYPH || SUBPIXEL
|
||||
o.color2 = i.color2;
|
||||
o.grad = i.grad;
|
||||
#endif
|
||||
#if FILL
|
||||
o.border = i.border;
|
||||
#endif
|
||||
#if FILL || SHADOW || IMAGE
|
||||
o.widths = i.uv;
|
||||
#endif
|
||||
o.clip = i.clip;
|
||||
o.clipRadii = i.clipRadii;
|
||||
// A square clip holding the whole quad, and what a fragment's pixel reaches
|
||||
// beyond it, covers its fragments by 1: none computes that (3).
|
||||
float mode = i.transform1.w;
|
||||
if (mode < 0.5 && !any(i.clipRadii) && all(i.clip.xy <= r.xy - 1) && all(i.clip.xy + i.clip.zw >= r.xy + r.zw + 1)) {
|
||||
mode = 3;
|
||||
}
|
||||
o.params = float4(kind + 8 * mode, i.params.yzw);
|
||||
return o;
|
||||
}
|
||||
|
||||
struct ClassPS {
|
||||
float4 color : SV_Target0;
|
||||
#if SUBPIXEL
|
||||
float4 alpha : SV_Target1;
|
||||
#endif
|
||||
};
|
||||
|
||||
// classClip returns how much of the fragment the clip covers, mode saying how
|
||||
// it applies.
|
||||
float classClip(ClassOut i, float mode) {
|
||||
float2 p = i.pt.xy;
|
||||
[branch] if (mode > 2.5) {
|
||||
return 1;
|
||||
} else if (mode < 0.5) {
|
||||
return rectCoverage(p, i.clip, i.clipRadii);
|
||||
} else if (mode > 1.5) {
|
||||
return rectCoverage(p, i.clip, float4(0, 0, 0, 0)) * clipTex.SampleLevel(samp, (p - i.clipRadii.xy) / i.clipRadii.zw, 0).a;
|
||||
}
|
||||
return clipTex.SampleLevel(samp, (p - i.clip.xy) / i.clip.zw, 0).a;
|
||||
}
|
||||
|
||||
// IS tells whether an instance of class c is one a test finds, which needs no
|
||||
// test when the shader draws only that class.
|
||||
#define IS(c, test) (CLASSES == (1 << c) || (test))
|
||||
|
||||
ClassPS classps(ClassOut i) {
|
||||
float2 p = i.pt.xy;
|
||||
float mode = floor(i.params.x / 8);
|
||||
float kind = i.params.x - 8 * mode;
|
||||
float4 res = float4(0, 0, 0, 0);
|
||||
ClassPS o;
|
||||
#if IMAGE
|
||||
float2 dtex = fwidth(i.pt.zw);
|
||||
#endif
|
||||
#if FILL
|
||||
[branch] if (kind < 0.5) { // plain ones as well, when the shader draws both
|
||||
float outer = rectCoverage(p, i.rect, i.radii);
|
||||
// params.y: 1 dashes the border, 2 paints it with the gradient (the
|
||||
// inside with plain color), 3 both.
|
||||
bool borderPaint = i.params.y > 1.5;
|
||||
float4 pc = paint(p, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
res = (borderPaint ? premul(i.color) : pc) * outer;
|
||||
float4 bw = i.widths; // top, right, bottom, left
|
||||
[branch] if (any(bw > 0)) {
|
||||
float4 ir = float4(i.rect.xy + bw.wx, i.rect.zw - bw.yz - bw.wx);
|
||||
float innerCov = 0;
|
||||
if (ir.z > 0 && ir.w > 0) {
|
||||
innerCov = rectCoverage(p, ir, i.inner);
|
||||
}
|
||||
float bc = saturate(outer - innerCov);
|
||||
float dashed = i.params.y - (borderPaint ? 2 : 0);
|
||||
[branch] if (dashed > 0.5) {
|
||||
bc *= dash(p, i.rect, bw);
|
||||
}
|
||||
float4 b = (borderPaint ? pc * float4(i.border.rgb * i.border.a, i.border.a) : premul(i.border)) * bc;
|
||||
res = b + res * (1 - b.a);
|
||||
}
|
||||
}
|
||||
#elif PLAIN
|
||||
[branch] if (IS(1, kind < 0.5)) {
|
||||
res = premul(i.color) * rectCoverage(p, i.rect, i.radii);
|
||||
}
|
||||
#endif
|
||||
#if SHADOW
|
||||
[branch] if (IS(3, kind > 0.5 && kind < 1.5)) {
|
||||
float sigma = i.params.z;
|
||||
[branch] if (i.params.y > 0.5) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float hole = 0;
|
||||
[branch] if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
float corner = max(max(i.inner.x, i.inner.y), max(i.inner.z, i.inner.w));
|
||||
[branch] if (sigma > 0) {
|
||||
hole = boxShadow(p, i.widths, sigma, corner);
|
||||
} else {
|
||||
hole = rectCoverage(p, i.widths, i.inner);
|
||||
}
|
||||
}
|
||||
res = premul(i.color) * (rectCoverage(p, i.rect, i.radii) * (1 - hole));
|
||||
} else {
|
||||
// Outside the box casting it, where the blur is worth computing.
|
||||
float outside = 1;
|
||||
[branch] if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
outside = 1 - rectCoverage(p, i.widths, i.inner);
|
||||
}
|
||||
float s = 0;
|
||||
[branch] if (outside > 0) {
|
||||
float corner = max(max(i.radii.x, i.radii.y), max(i.radii.z, i.radii.w));
|
||||
[branch] if (sigma > 0) {
|
||||
s = boxShadow(p, i.rect, sigma, corner);
|
||||
} else {
|
||||
s = rectCoverage(p, i.rect, i.radii);
|
||||
}
|
||||
}
|
||||
res = premul(i.color) * (s * outside);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if GLYPH
|
||||
[branch] if (IS(4, kind > 1.5 && kind < 2.5)) {
|
||||
float4 c = premul(i.color);
|
||||
[branch] if (i.params.z > 0.5) {
|
||||
c = paint(p, i.params.z, float4(0, 0, 0, 0), i.color, i.color2, i.grad);
|
||||
}
|
||||
res = c * textCoverage(maskTex.SampleLevel(samp, i.pt.zw, 0).r, unpremul(c), i.inner.x, i.inner.y, i.radii);
|
||||
}
|
||||
#endif
|
||||
#if IMAGE
|
||||
[branch] if (kind > 2.5 && kind < 3.5) {
|
||||
res = colorTex.SampleLevel(samp, i.pt.zw, 0) * i.color.a;
|
||||
} else if (kind > 3.5 && kind < 4.5) {
|
||||
[branch] if (i.params.y > 1.5) {
|
||||
// A frame of video: its luma and its chroma, converted.
|
||||
float code = i.params.y - 2;
|
||||
float gray = code > 7.5 ? 1 : 0;
|
||||
float2 cs = chromaScale();
|
||||
res = float4(yuvToRGB(sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex).r,
|
||||
sampleImage(chromaTex, i.pt.zw * cs, i.widths * cs.xyxy, i.params.z, dtex * cs).rg,
|
||||
code - 8 * gray),
|
||||
1);
|
||||
if (gray > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex);
|
||||
if (i.params.y > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
}
|
||||
res = tint(res, i.color) * rectCoverage(p, i.rect, i.radii);
|
||||
}
|
||||
#endif
|
||||
#if SUBPIXEL
|
||||
[branch] if (IS(5, kind > 4.5)) {
|
||||
float4 c = premul(i.color);
|
||||
[branch] if (i.params.z > 0.5) {
|
||||
c = paint(p, i.params.z, float4(0, 0, 0, 0), i.color, i.color2, i.grad);
|
||||
}
|
||||
float3 straight = unpremul(c);
|
||||
float3 a = subpixelCoverage(colorTex.SampleLevel(samp, i.pt.zw, 0).rgb, straight, i.inner.x, i.inner.y, i.radii);
|
||||
float3 w = a * c.a * classClip(i, mode) * i.params.w;
|
||||
float wa = (w.r + w.g + w.b) / 3;
|
||||
o.color = float4(straight * w, wa);
|
||||
o.alpha = float4(w, wa);
|
||||
return o;
|
||||
}
|
||||
#endif
|
||||
o.color = res * (classClip(i, mode) * i.params.w);
|
||||
#if SUBPIXEL
|
||||
o.alpha = o.color.aaaa;
|
||||
#endif
|
||||
return o;
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// drawClasses draws s with a new renderer that set changes, and returns its
|
||||
// pixels.
|
||||
func drawClasses(t *testing.T, s *scene.Scene, set func(r *Renderer)) []byte {
|
||||
t.Helper()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
set(r)
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, _ := r.readBack(t)
|
||||
return pix
|
||||
}
|
||||
|
||||
// compareToGeneral fails when a channel of pix differs from the general
|
||||
// shader's by more than a level: compilers round a result at a tie either way.
|
||||
func compareToGeneral(t *testing.T, name string, pix, general []byte) {
|
||||
t.Helper()
|
||||
for i := range pix {
|
||||
if d := int(pix[i]) - int(general[i]); d < -1 || d > 1 {
|
||||
t.Fatalf("%s: byte %d is %d, and %d with the general shader", name, i, pix[i], general[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassesDrawAsTheGeneralShader draws scenes with the shaders of the
|
||||
// classes of their batches and with the general shader, and with each class
|
||||
// drawn by the shader holding them all, which tells kinds apart.
|
||||
func TestClassesDrawAsTheGeneralShader(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, sc := range []struct {
|
||||
name string
|
||||
s *scene.Scene
|
||||
}{{"scene", gputest.Scene()}, {"card", gputest.BorderedCardScene(false)}} {
|
||||
general := drawClasses(t, sc.s, func(r *Renderer) { r.b.NoClasses = true })
|
||||
compareToGeneral(t, sc.name, drawClasses(t, sc.s, func(r *Renderer) {}), general)
|
||||
compareToGeneral(t, sc.name+" joined", drawClasses(t, sc.s, func(r *Renderer) {
|
||||
all := r.classPipeFor(classShaders[len(classShaders)-1].classes)
|
||||
for c := gpu.ClassPlain; c < gpu.NumClasses; c++ {
|
||||
r.classes[1<<c] = all
|
||||
}
|
||||
}), general)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassPipelines checks what batches draw with: only the shaders holding
|
||||
// subpixel glyphs blend with a second color, and the shaders of a set of
|
||||
// classes are those of the first set holding it.
|
||||
func TestClassPipelines(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 16, 16))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
vs, ps, blend := r.pipeline(&gpu.Batch{Class: gpu.ClassPlain})
|
||||
if vs == r.vs || ps == r.ps || blend != r.overBlend {
|
||||
t.Fatal("a plain fill does not draw with its class's shaders, blended by its alpha")
|
||||
}
|
||||
if _, _, blend := r.pipeline(&gpu.Batch{Class: gpu.ClassPlain, Hole: true}); blend != r.overHoleBlend {
|
||||
t.Fatal("a plain hole does not blend by its alpha")
|
||||
}
|
||||
if _, _, blend := r.pipeline(&gpu.Batch{Class: gpu.ClassSubpixel}); blend != r.blend {
|
||||
t.Fatal("a subpixel glyph does not blend with a second color")
|
||||
}
|
||||
if vs, ps, blend := r.pipeline(&gpu.Batch{}); vs != r.vs || ps != r.ps || blend != r.blend {
|
||||
t.Fatal("the general class does not draw with the general shader")
|
||||
}
|
||||
if _, ps, _ := r.pipeline(&gpu.Batch{Joined: 1<<gpu.ClassPlain | 1<<gpu.ClassShadow}); ps == r.ps {
|
||||
t.Fatal("joined batches draw with the general shader")
|
||||
}
|
||||
// A set no shaders are made for draws with those of the set holding all.
|
||||
_, ps1, blend1 := r.pipeline(&gpu.Batch{Joined: 1<<gpu.ClassFill | 1<<gpu.ClassGlyph})
|
||||
_, ps2, _ := r.pipeline(&gpu.Batch{Joined: 1<<gpu.ClassImage | 1<<gpu.ClassShadow})
|
||||
if ps1 == r.ps || ps1 != ps2 || blend1 != r.blend {
|
||||
t.Fatal("the set holding all classes does not draw what no other holds")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFrameCostFits checks that a frame that takes much of a refresh has the
|
||||
// next ones build ahead, and that later ones of little cost end that.
|
||||
func TestFrameCostFits(t *testing.T) {
|
||||
c := frameCost{period: 16 * time.Millisecond}
|
||||
if !c.fits() {
|
||||
t.Fatal("no frames yet, and frames do not fit")
|
||||
}
|
||||
c.add(2 * time.Millisecond)
|
||||
if !c.fits() {
|
||||
t.Fatal("a frame of 2 ms of 16 does not fit")
|
||||
}
|
||||
c.add(14 * time.Millisecond)
|
||||
if c.fits() {
|
||||
t.Fatal("a frame of 14 ms of 16 fits")
|
||||
}
|
||||
frames := 0
|
||||
for ; !c.fits(); frames++ {
|
||||
c.add(2 * time.Millisecond)
|
||||
}
|
||||
if frames < 2 || frames > 60 {
|
||||
t.Fatalf("%d frames after a heavy one until frames fit", frames)
|
||||
}
|
||||
unknown := frameCost{}
|
||||
if unknown.refreshPeriod() != minRefresh {
|
||||
t.Fatal("no default refresh period")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFrameCostWithoutReady checks that a frame no Ready started, as a resize's
|
||||
// drawn at once, counts no main-thread time: counted from the last frame Ready
|
||||
// started, a drag of seconds would have frames build ahead long after it.
|
||||
func TestFrameCostWithoutReady(t *testing.T) {
|
||||
var c frameCost
|
||||
c.start = time.Now().Add(-3 * time.Second)
|
||||
if d := c.took(); d < 3*time.Second {
|
||||
t.Fatalf("a frame Ready started took %v", d)
|
||||
}
|
||||
if d := c.took(); d >= 0 {
|
||||
t.Fatalf("the next frame, which no Ready started, took %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFittingFrameWaitsForComposition checks a frame that fits: it presents at
|
||||
// once, with nothing left pending, and the next waits for the window manager's
|
||||
// composition, whose end wakes it, once the screen has room.
|
||||
func TestFittingFrameWaitsForComposition(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(f func(_, _ time.Duration)) { awaitRefresh = f }(awaitRefresh)
|
||||
composed := make(chan struct{})
|
||||
bounds := make(chan [2]time.Duration, 1)
|
||||
awaitRefresh = func(least, most time.Duration) {
|
||||
bounds <- [2]time.Duration{least, most}
|
||||
<-composed
|
||||
}
|
||||
defer func(ms uintptr) { latencyTimeout = ms }(latencyTimeout)
|
||||
latencyTimeout = 50 // a window that never shows signals no room
|
||||
|
||||
s := gputest.NewChanging(1).Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(f func()) { posted <- f })
|
||||
r.cost.period = 16 * time.Millisecond
|
||||
// However the first frame got there, the second is what the test is about.
|
||||
for r.lat.ready(); !r.lat.ready(); {
|
||||
r.lat.waitThen(func() { posted <- func() {} })
|
||||
wait.For(t, "room", posted)()
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.pending {
|
||||
t.Fatal("a frame that fits waits to present")
|
||||
}
|
||||
if b := wait.For(t, "the wait for the composition", bounds); b != [2]time.Duration{8 * time.Millisecond, 32 * time.Millisecond} {
|
||||
t.Fatalf("waits within %v", b)
|
||||
}
|
||||
woke := make(chan struct{}, 1)
|
||||
if r.Ready(func() { woke <- struct{}{} }) {
|
||||
t.Fatal("the next frame is ready before the composition")
|
||||
}
|
||||
close(composed)
|
||||
for len(woke) == 0 {
|
||||
wait.For(t, "the composition's end, then room", posted)()
|
||||
}
|
||||
r.cost.estimate = time.Hour // the second frame builds ahead
|
||||
if !r.Ready(func() {}) {
|
||||
t.Fatal("a frame that does not fit waits before it builds")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFrameThatWaitedDoesNotKeepNextOnesWaiting checks that a frame that fits but
|
||||
// waited to present, as the screen had no room as it drew, has the next wait for
|
||||
// the composition: woken at once, that would draw before the screen has room and
|
||||
// wait too, and so would every one after it, each a refresh late for good.
|
||||
func TestFrameThatWaitedDoesNotKeepNextOnesWaiting(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(f func(_, _ time.Duration)) { awaitRefresh = f }(awaitRefresh)
|
||||
composed := make(chan struct{})
|
||||
awaitRefresh = func(_, _ time.Duration) { <-composed }
|
||||
defer func(ms uintptr) { latencyTimeout = ms }(latencyTimeout)
|
||||
latencyTimeout = 50 // a window that never shows signals no room
|
||||
|
||||
s := gputest.NewChanging(1).Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(f func()) { posted <- f })
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
woke := make(chan struct{}, 1)
|
||||
r.wake = func() { woke <- struct{}{} }
|
||||
r.pending = true
|
||||
r.presentPending()
|
||||
if !r.refreshing {
|
||||
t.Fatal("the next frame does not wait for the composition")
|
||||
}
|
||||
if len(woke) != 0 {
|
||||
t.Fatal("the next frame woke before the composition")
|
||||
}
|
||||
close(composed)
|
||||
for len(woke) == 0 {
|
||||
wait.For(t, "the composition's end, then room", posted)()
|
||||
}
|
||||
}
|
||||
|
||||
// TestDwmFlushedShared checks that waits for a refresh share the call under
|
||||
// way: at most one thread waits, whatever frames come meanwhile.
|
||||
func TestDwmFlushedShared(t *testing.T) {
|
||||
a, b := dwmFlushed(), dwmFlushed()
|
||||
if a != b {
|
||||
// The first may have returned at once: then the next is a new wait.
|
||||
select {
|
||||
case <-a:
|
||||
default:
|
||||
t.Fatal("two calls under way")
|
||||
}
|
||||
}
|
||||
wait.For(t, "the window manager", a)
|
||||
}
|
||||
+2002
File diff suppressed because it is too large.
Load diff
+444
@@ -0,0 +1,444 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"slices"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// hiddenWindow creates a window that never shows, for a swap chain.
|
||||
func hiddenWindow(t *testing.T, w, h int) uintptr {
|
||||
hwnd, err := newHiddenWindow(w, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { destroyWindow(hwnd) })
|
||||
return hwnd
|
||||
}
|
||||
|
||||
// readBack copies the back buffer to memory: BGRA rows and their stride.
|
||||
func (r *Renderer) readBack(t *testing.T) ([]byte, int) {
|
||||
pix, stride, err := r.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pix, stride
|
||||
}
|
||||
|
||||
func TestDrawsAsTheCPURenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
// With the shaders compiled ahead of time, and with those compiled
|
||||
// from shader.hlsl when the renderer starts, as when they are older.
|
||||
for _, compile := range []bool{false, true} {
|
||||
compileShaders = compile
|
||||
s := gputest.Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
compileShaders = false
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
// Twice: the second frame updates what the first uploaded.
|
||||
for frame := range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11", pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatalf("frame %d: %v", frame, err)
|
||||
}
|
||||
}
|
||||
|
||||
s = gputest.TransformedScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-affine", pix, stride, s)
|
||||
}
|
||||
s = gputest.PerspectiveScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-perspective", pix, stride, s)
|
||||
}
|
||||
s = gputest.BehindOriginScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-behind-origin", pix, stride, s)
|
||||
}
|
||||
for i, s := range gputest.TranslatedScenes() {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-translated"+[]string{"", "-between-pixels"}[i], pix, stride, s)
|
||||
}
|
||||
s = gputest.MaskedClipScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-masked-clips", pix, stride, s)
|
||||
}
|
||||
s = gputest.CornerClipScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-corner-clips", pix, stride, s)
|
||||
}
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// TestBorderedCardDrawsAsTheCPURenderer draws the card of #531 (a large
|
||||
// opaque card with a border of 2 pixels at scale 2, and a small button like
|
||||
// it) with round corners, as Direct3D draws continuous ones, and requires the
|
||||
// CPU renderer's pixels along their straight edges, exactly.
|
||||
func TestBorderedCardDrawsAsTheCPURenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.BorderedCardScene(false)
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.CompareStraightEdges(t, "d3d11-bordered-card", pix, stride, s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResizeSettles checks that while the window changes size the swap
|
||||
// chain draws into part of larger buffers, resized only when the window
|
||||
// outgrows them, and that once the settle timer asked for a frame, the
|
||||
// frame gives it buffers of the window's size again. A swap chain that
|
||||
// stretches its frames over the window shows that part of its buffers; one
|
||||
// for composition or an unscaled one (#855), which would stretch the part
|
||||
// over the buffers' size, magnifying the frame (#892), shows them whole,
|
||||
// and an unscaled one the content's background beyond the frame.
|
||||
func TestResizeSettles(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(d time.Duration) { settleDelay = d }(settleDelay)
|
||||
settleDelay = 50 * time.Millisecond
|
||||
for _, newRenderer := range []func(uintptr) (*Renderer, error){New, NewComposed} {
|
||||
r, err := newRenderer(hiddenWindow(t, 200, 150))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
resizeSettles(t, r)
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
|
||||
func resizeSettles(t *testing.T, r *Renderer) {
|
||||
t.Helper()
|
||||
kind := "window"
|
||||
if r.composed {
|
||||
kind = "composition"
|
||||
}
|
||||
bg := scene.Color{R: 24, G: 24, B: 27, A: 255}
|
||||
frame := func(w, h int) {
|
||||
t.Helper()
|
||||
if err := r.draw(&scene.Scene{Width: w, Height: h, Background: bg}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.unscaled {
|
||||
// What the buffers hold beyond the frame shows where the
|
||||
// window grows before the next frame presents.
|
||||
pix, stride, err := r.readPart(r.bw, r.bh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range [][2]int{{r.bw - 1, r.bh - 1}, {w, 0}, {r.bw - 1, 0}, {0, h}, {w - 1, r.bh - 1}} {
|
||||
if p[0] < w && p[1] < h || p[0] >= r.bw || p[1] >= r.bh {
|
||||
continue // in the frame, or beyond the buffers
|
||||
}
|
||||
px := pix[p[1]*stride+p[0]*4:]
|
||||
if got := [3]byte{px[2], px[1], px[0]}; got != [3]byte{bg.R, bg.G, bg.B} {
|
||||
t.Fatalf("%s: a %dx%d frame in %dx%d buffers: pixel %v beyond it is %v; want the background %v", kind, w, h, r.bw, r.bh, p, got, bg)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.swapChain2 == 0 {
|
||||
return
|
||||
}
|
||||
const scGetSourceSize = 30 // IDXGISwapChain2
|
||||
var sw, sh uint32
|
||||
call(r.swapChain2, scGetSourceSize, uintptr(unsafe.Pointer(&sw)), uintptr(unsafe.Pointer(&sh)))
|
||||
want := [2]int{r.w, r.h}
|
||||
if r.composed || r.unscaled {
|
||||
want = [2]int{r.bw, r.bh}
|
||||
}
|
||||
if got := [2]int{int(sw), int(sh)}; got != want {
|
||||
t.Fatalf("%s: a %dx%d frame in %dx%d buffers shows %dx%d of them; want %dx%d", kind, w, h, r.bw, r.bh, sw, sh, want[0], want[1])
|
||||
}
|
||||
}
|
||||
frame(200, 150)
|
||||
if r.swapChain2 == 0 {
|
||||
t.Skip("no IDXGISwapChain2")
|
||||
}
|
||||
if r.bw != 200 || r.bh != 150 || r.resizing {
|
||||
t.Fatalf("%s: first frame: buffers %dx%d, resizing %v; want 200x150 and not resizing", kind, r.bw, r.bh, r.resizing)
|
||||
}
|
||||
frame(220, 160)
|
||||
bw, bh := r.bw, r.bh
|
||||
if !r.resizing || bw <= 220 || bh <= 160 {
|
||||
t.Fatalf("%s: resized: buffers %dx%d, resizing %v; want larger than 220x160 and resizing", kind, bw, bh, r.resizing)
|
||||
}
|
||||
frame(230, 155)
|
||||
if r.bw != bw || r.bh != bh || r.w != 230 || r.h != 155 {
|
||||
t.Fatalf("%s: resized within the buffers: buffers %dx%d drawing %dx%d; want %dx%d drawing 230x155", kind, r.bw, r.bh, r.w, r.h, bw, bh)
|
||||
}
|
||||
// The timer fires as messages are dispatched.
|
||||
user32 := syscall.NewLazyDLL("user32.dll")
|
||||
peek, dispatch := user32.NewProc("PeekMessageW"), user32.NewProc("DispatchMessageW")
|
||||
var msg [64]byte
|
||||
for deadline := time.Now().Add(wait.Guard); settling[r.hwnd]; time.Sleep(time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("%s: the settle timer did not fire", kind)
|
||||
}
|
||||
for {
|
||||
if ok, _, _ := peek.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, 1); ok == 0 {
|
||||
break
|
||||
}
|
||||
dispatch.Call(uintptr(unsafe.Pointer(&msg)))
|
||||
}
|
||||
}
|
||||
frame(230, 155)
|
||||
if r.bw != 230 || r.bh != 155 || r.resizing {
|
||||
t.Fatalf("%s: settled: buffers %dx%d, resizing %v; want 230x155 and not resizing", kind, r.bw, r.bh, r.resizing)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBeyondFrame checks the parts of a swap chain's buffers beyond the
|
||||
// frame, which an unscaled one fills with the content's background.
|
||||
func TestBeyondFrame(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
w, h, bw, bh int
|
||||
want []gpu.Scissor
|
||||
}{
|
||||
{200, 150, 200, 150, nil},
|
||||
{200, 150, 314, 251, []gpu.Scissor{{Left: 200, Right: 314, Bottom: 251}, {Top: 150, Right: 200, Bottom: 251}}},
|
||||
{200, 150, 200, 251, []gpu.Scissor{{Top: 150, Right: 200, Bottom: 251}}},
|
||||
{200, 150, 314, 150, []gpu.Scissor{{Left: 200, Right: 314, Bottom: 150}}},
|
||||
} {
|
||||
parts, n := beyondFrame(c.w, c.h, c.bw, c.bh)
|
||||
if got := parts[:n]; !slices.Equal(got, c.want) {
|
||||
t.Errorf("beyondFrame(%d, %d, %d, %d) = %v; want %v", c.w, c.h, c.bw, c.bh, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwapChainBackground checks that the window's swap chain shows its
|
||||
// frames unscaled, and the scene's background beyond them (#222): where the
|
||||
// window grew before the frame of its size presents, DWM shows that, not
|
||||
// black.
|
||||
func TestSwapChainBackground(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 200, 150))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
const scGetDesc1, scGetBackgroundColor = 18, 26 // IDXGISwapChain1
|
||||
for _, bg := range []scene.Color{{R: 255, G: 255, B: 255, A: 255}, {R: 24, G: 24, B: 27, A: 255}, {}} {
|
||||
if err := r.draw(&scene.Scene{Width: 200, Height: 150, Background: bg}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var desc swapChainDesc1
|
||||
call(r.swapChain, scGetDesc1, uintptr(unsafe.Pointer(&desc)))
|
||||
if desc.Scaling != scalingNone {
|
||||
t.Fatalf("the swap chain scales frames as %d; want DXGI_SCALING_NONE", desc.Scaling)
|
||||
}
|
||||
var got [4]float32
|
||||
call(r.swapChain, scGetBackgroundColor, uintptr(unsafe.Pointer(&got)))
|
||||
want := [4]float32{float32(bg.R) / 255, float32(bg.G) / 255, float32(bg.B) / 255, 1}
|
||||
if bg.A == 0 {
|
||||
want = [4]float32{0, 0, 0, 1}
|
||||
}
|
||||
for i := range 3 {
|
||||
if d := got[i] - want[i]; d < -0.002 || d > 0.002 {
|
||||
t.Fatalf("background %v: the swap chain shows %v beyond the frame; want %v", bg, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// releaseImages arms every image of a scene to keep only the renderer's
|
||||
// copy of its pixels: the restore re-makes them from a copy it took, and
|
||||
// dropped counts the uploads and drops them again.
|
||||
func releaseImages(s *scene.Scene, restores, drops *int) int {
|
||||
armed := 0
|
||||
for i := range s.Ops {
|
||||
if img := s.Ops[i].Image; img != nil && img.Scene == nil && img.Restore == nil {
|
||||
pix := slices.Clone(img.Pix)
|
||||
img.Restore = func() []byte { *restores++; return pix }
|
||||
img.Dropped = func() { *drops++; img.Pix = nil }
|
||||
armed++
|
||||
}
|
||||
}
|
||||
return armed
|
||||
}
|
||||
|
||||
// TestReleasedImageUploadsFromItsRestore checks issue #664's contract with
|
||||
// the renderer: an image whose pixels an owner dropped uploads them again
|
||||
// from the restore, drawing as before, as a renderer that lost or evicted
|
||||
// its texture does. The first draw takes the new-texture path, which an
|
||||
// eviction after 240 frames takes too.
|
||||
func TestReleasedImageUploadsFromItsRestore(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.Scene()
|
||||
restores, drops := 0, 0
|
||||
armed := releaseImages(s, &restores, &drops)
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restores != 0 {
|
||||
t.Fatalf("%d restores for pixels the first draw had", restores)
|
||||
}
|
||||
if drops != armed {
|
||||
t.Fatalf("%d drops of %d images", drops, armed)
|
||||
}
|
||||
// The CPU renderer the comparison draws with re-makes the pixels of
|
||||
// the images it draws.
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11 released", pix, stride, s)
|
||||
if restores != armed {
|
||||
t.Fatalf("%d restores of %d images in the CPU render", restores, armed)
|
||||
}
|
||||
// The textures stay for the frames that follow: the restore runs no
|
||||
// more, and the dropped pixels go.
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restores != armed || drops != armed {
|
||||
t.Fatalf("%d restores, %d drops after a frame with the textures live", restores, drops)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReleasedImageWithNewRenderer uploads from the restore again in a
|
||||
// renderer of its own, as a device that was made again does.
|
||||
func TestReleasedImageWithNewRenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.Scene()
|
||||
restores, drops := 0, 0
|
||||
armed := releaseImages(s, &restores, &drops)
|
||||
for i := range 2 {
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
if err := r.draw(s); err != nil {
|
||||
r.Release()
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The first renderer uploaded the pixels it had; the second
|
||||
// found them dropped by the first and re-made them.
|
||||
if want := i * armed; restores != want {
|
||||
t.Fatalf("renderer %d: %d restores, want %d", i, restores, want)
|
||||
}
|
||||
if drops != (i+1)*armed {
|
||||
t.Fatalf("renderer %d: %d drops, want %d", i, drops, (i+1)*armed)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11 released, new renderer", pix, stride, s)
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// TestShaderBytecode checks that the shaders compiled ahead of time come
|
||||
// from shader.hlsl as it is, and that the compiler renderers fall back to
|
||||
// compiles it.
|
||||
func TestShaderBytecode(t *testing.T) {
|
||||
if sourceSum() != shaderSum {
|
||||
t.Fatal("shader.hlsl changed since shaders.go was generated: run go generate ./internal/gpu/d3d11 on Windows")
|
||||
}
|
||||
for _, s := range []struct{ entry, target string }{{"vs", "vs_4_0"}, {"ps", "ps_4_0"}} {
|
||||
code, err := compileShader(s.entry, s.target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// DXBC starts with its magic.
|
||||
if len(code) < 4 || string(code[:4]) != "DXBC" {
|
||||
t.Errorf("%s: not DXBC", s.entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestComposed draws into a swap chain for DirectComposition, which shows
|
||||
// on the window with its alpha: frames draw as into the window's own, what
|
||||
// a scene leaves transparent stays so, and once a renderer is released
|
||||
// another composes the window, as after a GPU failure: a window has one
|
||||
// DirectComposition target at most.
|
||||
func TestComposed(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.Scene()
|
||||
hwnd := hiddenWindow(t, s.Width, s.Height)
|
||||
for i := range 2 {
|
||||
r, err := NewComposed(hwnd)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
if err := r.draw(s); err != nil {
|
||||
r.Release()
|
||||
t.Fatalf("renderer %d: %v", i, err)
|
||||
}
|
||||
if r.target == 0 || r.visual == 0 {
|
||||
t.Fatalf("renderer %d: the swap chain shows through no DirectComposition target", i)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11 composed", pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A frame of another size, transparent.
|
||||
if err := r.draw(&scene.Scene{Width: s.Width + 20, Height: s.Height + 10}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pix, _ := r.readBack(t); len(pix) < 4 || pix[0]|pix[1]|pix[2]|pix[3] != 0 {
|
||||
t.Errorf("renderer %d: a transparent frame reads %v", i, pix[:min(len(pix), 4)])
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// changingScenes calls frame with the steps of random scenes changing a
|
||||
// little at a time, over an opaque color and a translucent one, each with
|
||||
// a renderer drawing in part and one drawing whole, both new: each scene
|
||||
// has an atlas of its own.
|
||||
func changingScenes(t *testing.T, seeds uint64, frame func(r, whole *Renderer, s *scene.Scene, step int, what string)) {
|
||||
for seed := range seeds {
|
||||
m := gputest.NewChanging(seed)
|
||||
if seed%3 == 2 {
|
||||
m.Clear = scene.Color{R: 20, G: 40, B: 200, A: 77}
|
||||
}
|
||||
s := m.Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
if r.ctx1 == 0 {
|
||||
r.Release()
|
||||
t.Skip("no Direct3D 11.1")
|
||||
}
|
||||
whole, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
whole.ctx1 = 0 // never in part
|
||||
// No subtests: the windows take their messages on this thread.
|
||||
for step := range 30 {
|
||||
what := fmt.Sprintf("seed %d", seed)
|
||||
if step > 0 {
|
||||
what += ", " + m.Change(s)
|
||||
}
|
||||
frame(r, whole, s, step, what)
|
||||
}
|
||||
r.Release()
|
||||
whole.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// TestPartialFramesMatchWhole draws random scenes changing a little at a
|
||||
// time into a back buffer that keeps what was drawn, as DXGI completes
|
||||
// one presented in part with the last frame, each frame only where it
|
||||
// changed, and requires the bytes of each frame drawn whole.
|
||||
func TestPartialFramesMatchWhole(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
seeds := uint64(20)
|
||||
if testing.Short() {
|
||||
seeds = 5
|
||||
}
|
||||
frames, partial := 0, 0
|
||||
changingScenes(t, seeds, func(r, whole *Renderer, s *scene.Scene, step int, what string) {
|
||||
drawn, err := r.drawFrame(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.held = drawn || r.held // as presenting it does
|
||||
frames++
|
||||
part := "whole"
|
||||
switch r.redrew {
|
||||
case redrewPart:
|
||||
partial++
|
||||
part = r.part.String()
|
||||
case redrewNothing:
|
||||
part = "nothing"
|
||||
}
|
||||
got, _ := r.readBack(t)
|
||||
if err := whole.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := whole.readBack(t)
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("step %d (%s), redrew %s: %d bytes differ from the frame drawn whole", step, what, part, differing(got, want))
|
||||
}
|
||||
})
|
||||
if partial < frames/3 {
|
||||
t.Errorf("%d frames of %d drawn in part", partial, frames)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPresentsInPart presents random scenes changing a little at a time,
|
||||
// each drawn only where it changed, with that as the dirty rectangle, in a
|
||||
// window that shows: DXGI copies the rest from the last frame into the
|
||||
// buffer presented. Once the swap chain flipped again, that buffer, back,
|
||||
// must hold the frame drawn whole.
|
||||
func TestPresentsInPart(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
seeds := uint64(6)
|
||||
if testing.Short() {
|
||||
seeds = 2
|
||||
}
|
||||
// presented holds the frames presented, drawn whole.
|
||||
var presented [][]byte
|
||||
partial := 0
|
||||
changingScenes(t, seeds, func(r, whole *Renderer, s *scene.Scene, step int, what string) {
|
||||
if step == 0 {
|
||||
const swShowNoActivate = 4
|
||||
user32.NewProc("ShowWindow").Call(r.hwnd, swShowNoActivate)
|
||||
presented = presented[:0]
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch r.redrew {
|
||||
case redrewNothing:
|
||||
return // nothing presented: the swap chain did not flip
|
||||
case redrewPart:
|
||||
partial++
|
||||
}
|
||||
if err := whole.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := whole.readBack(t)
|
||||
presented = append(presented, want)
|
||||
// The back buffer now holds the frame presented before, as DXGI
|
||||
// completed it.
|
||||
if n := len(presented); n >= 2 {
|
||||
if got, _ := r.readBack(t); !bytes.Equal(got, presented[n-2]) {
|
||||
t.Fatalf("step %d (%s): the frame before, presented, differs in %d bytes from it drawn whole", step, what, differing(got, presented[n-2]))
|
||||
}
|
||||
}
|
||||
})
|
||||
if partial == 0 {
|
||||
t.Error("no frame was presented in part")
|
||||
}
|
||||
}
|
||||
|
||||
func differing(a, b []byte) (n int) {
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//go:build windows
|
||||
|
||||
// Package device creates Direct3D 11 devices: the device of package d3d11's
|
||||
// renderer, and that of the Windows backend, which shows the controls of
|
||||
// windows with a material through DirectComposition without the renderer.
|
||||
// It depends on nothing of MyGo, so apps that draw no native UI link none
|
||||
// of the renderer.
|
||||
package device
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var procD3D11CreateDevice = syscall.NewLazyDLL(SystemDir() + `\d3d11.dll`).NewProc("D3D11CreateDevice")
|
||||
|
||||
// SystemDir returns the system directory, which system DLLs load from,
|
||||
// never from the application directory or the search path.
|
||||
func SystemDir() string {
|
||||
buf := make([]uint16, 260)
|
||||
n, _, _ := syscall.NewLazyDLL("kernel32.dll").NewProc("GetSystemDirectoryW").Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
||||
if n == 0 || int(n) > len(buf) {
|
||||
return `C:\Windows\System32`
|
||||
}
|
||||
return syscall.UTF16ToString(buf[:n])
|
||||
}
|
||||
|
||||
// New creates a Direct3D 11 device and its immediate context, on the GPU
|
||||
// or, when there is none, with Windows' software rasterizer (WARP), which
|
||||
// software reports. The caller releases the device and the context.
|
||||
func New() (device, context uintptr, software bool, err error) {
|
||||
return create(0, hardware, warp)
|
||||
}
|
||||
|
||||
// NewOnGPU is New for a device on the GPU only: it fails where New would
|
||||
// make one with WARP.
|
||||
func NewOnGPU() (device, context uintptr, err error) {
|
||||
device, context, _, err = create(0, hardware)
|
||||
return device, context, err
|
||||
}
|
||||
|
||||
// NewForVideo is New for a device that decodes and converts video, as
|
||||
// Media Foundation's: one that supports Direct3D's video API where the
|
||||
// GPU has it, else as New.
|
||||
func NewForVideo() (device, context uintptr, software bool, err error) {
|
||||
const videoSupport = 0x800
|
||||
if d, c, sw, err := create(videoSupport, hardware, warp); err == nil {
|
||||
return d, c, sw, nil
|
||||
}
|
||||
return create(0, hardware, warp)
|
||||
}
|
||||
|
||||
// The drivers create tries, in order.
|
||||
const hardware, warp = 1, 5
|
||||
|
||||
func create(flags uintptr, drivers ...uintptr) (device, context uintptr, software bool, err error) {
|
||||
if err := procD3D11CreateDevice.Find(); err != nil {
|
||||
return 0, 0, false, err
|
||||
}
|
||||
levels := []uint32{0xb000, 0xa100, 0xa000} // 11_0, 10_1, 10_0
|
||||
const bgraSupport = 0x20
|
||||
var hr uintptr
|
||||
for _, driver := range drivers {
|
||||
var level uint32
|
||||
hr, _, _ = procD3D11CreateDevice.Call(0, driver, 0, bgraSupport|flags,
|
||||
uintptr(unsafe.Pointer(&levels[0])), uintptr(len(levels)), 7,
|
||||
uintptr(unsafe.Pointer(&device)), uintptr(unsafe.Pointer(&level)), uintptr(unsafe.Pointer(&context)))
|
||||
if int32(uint32(hr)) >= 0 {
|
||||
return device, context, driver == warp, nil
|
||||
}
|
||||
}
|
||||
return 0, 0, false, fmt.Errorf("d3d11: cannot create a device: %#x", uint32(hr))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//go:build windows
|
||||
|
||||
package device
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// IID_IDXGIDevice
|
||||
var iidIDXGIDevice = [16]byte{0xfa, 0x77, 0xec, 0x54, 0x77, 0x13, 0xe6, 0x44, 0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}
|
||||
|
||||
// call calls method i of the COM interface obj.
|
||||
func call(obj uintptr, i int, args ...uintptr) uintptr {
|
||||
vtbl := *(*uintptr)(*(*unsafe.Pointer)(unsafe.Pointer(&obj)))
|
||||
fn := *(*uintptr)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&vtbl)), i*int(unsafe.Sizeof(uintptr(0)))))
|
||||
r, _, _ := syscall.SyscallN(fn, append([]uintptr{obj}, args...)...)
|
||||
return r
|
||||
}
|
||||
|
||||
// TestNew checks that New gives a device and a context, and that the device
|
||||
// is a DXGI device, which DirectComposition needs.
|
||||
func TestNew(t *testing.T) {
|
||||
device, context, software, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer call(device, 2)
|
||||
defer call(context, 2)
|
||||
if device == 0 || context == 0 {
|
||||
t.Fatalf("device %#x, context %#x", device, context)
|
||||
}
|
||||
var dxgi uintptr
|
||||
if hr := call(device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice)), uintptr(unsafe.Pointer(&dxgi))); int32(uint32(hr)) < 0 {
|
||||
t.Fatalf("the device is no DXGI device: %#x", uint32(hr))
|
||||
}
|
||||
call(dxgi, 2)
|
||||
t.Logf("software (WARP): %v", software)
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
// The head and the tail of an effect's pixel shader (scene.Effect): after
|
||||
// shader.hlsl with EFFECT defined, the head declares what an effect reads,
|
||||
// the effect's source follows, then the tail, after the line "// effect",
|
||||
// draws its instances with it (effectps): the rounded rectangle, or, with
|
||||
// 1 in params.y, a mask glyph a shader's effect fills.
|
||||
|
||||
Texture2D backdropTex : register(t3);
|
||||
|
||||
// What an effect reads of its instance.
|
||||
struct Effect {
|
||||
float4 rect; // x, y, width, height in pixels
|
||||
float4 radii; // top-left, top-right, bottom-right, bottom-left, circular
|
||||
float4 p0, p1, p2, p3, p4;
|
||||
float4 area; // where the backdrop's area starts in the frame, and its size in texels
|
||||
float down; // the size of the squares the backdrop averages
|
||||
float4 transform0, transform1, transform2;
|
||||
};
|
||||
|
||||
float2 framePoint(Effect e, float2 q) {
|
||||
float3 h = float3(dot(e.transform0.xyz, float3(q, 1.0)), dot(e.transform1.xyz, float3(q, 1.0)),
|
||||
dot(float3(e.transform2.xy, 1.0 - 2.0 * e.transform2.z), float3(q, 1.0)));
|
||||
return h.xy / h.z;
|
||||
}
|
||||
|
||||
float3 backdropAt(int2 p, int2 size) { return backdropTex.Load(int3(clamp(p, int2(0, 0), size - 1), 0)).rgb; }
|
||||
|
||||
// sampleBackdrop returns the backdrop at q, in the frame's pixels,
|
||||
// premultiplied, filtered bilinearly from its texels as
|
||||
// scene.BackdropImage.Sample does.
|
||||
float3 sampleBackdrop(Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float3 top = backdropAt(p, size) * (1 - w.x) + backdropAt(p + int2(1, 0), size) * w.x;
|
||||
float3 bot = backdropAt(p + int2(0, 1), size) * (1 - w.x) + backdropAt(p + int2(1, 1), size) * w.x;
|
||||
return top * (1 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
// effect
|
||||
|
||||
PSOut effectps(VSOut i) {
|
||||
Frame fr = frameOf(i);
|
||||
Effect e;
|
||||
e.rect = i.rect;
|
||||
e.radii = abs(i.radii);
|
||||
e.p0 = i.inner;
|
||||
e.p1 = i.color;
|
||||
e.p2 = i.color2;
|
||||
e.p3 = i.border;
|
||||
e.p4 = i.grad;
|
||||
e.area = i.widths;
|
||||
e.down = i.params.z;
|
||||
e.transform0 = i.transform0;
|
||||
e.transform1 = i.transform1;
|
||||
e.transform2 = i.transform2;
|
||||
float4 res;
|
||||
if (i.params.y > 0.5) {
|
||||
// A mask glyph a shader fills (scene.EffectOp.Glyphs), as ps
|
||||
// draws one, its paint the shader's color.
|
||||
float4 c = effect(i.pt.xy, e);
|
||||
float glyphCov = i.transform0.w > 0.5 ? localCoverage(i.pt.xy, i.rect, float4(0, 0, 0, 0), 1, fr) : 1;
|
||||
res = c * (textCoverage(sampleLocal(maskTex, i.pt.zw, i.widths, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov * clipCoverage(i) * i.params.w);
|
||||
} else {
|
||||
res = effect(i.pt.xy, e) *
|
||||
(localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr) * clipCoverage(i) * i.params.w);
|
||||
}
|
||||
PSOut o;
|
||||
o.color = res;
|
||||
o.alpha = res.aaaa;
|
||||
return o;
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// PrecompileEffect starts compiling the pixel shader of an effect whose
|
||||
// shader is src, which nothing compiled ahead of time, on a goroutine of
|
||||
// its own: the renderers then draw it with that code, waiting for the
|
||||
// compilation if it has not finished, rather than each compiling it on
|
||||
// its first draw. The code is kept on disk too, for the next launches.
|
||||
// Package ui/shader calls it as it compiles a shader, which links the
|
||||
// cache into apps that draw shaders only.
|
||||
func PrecompileEffect(src string) {
|
||||
effects.once.Do(func() {
|
||||
effects.byKey = map[string]*effectEntry{}
|
||||
effects.sem = make(chan struct{}, max(1, runtime.NumCPU()-1))
|
||||
effects.dir = effectCacheDir()
|
||||
code := effects.code
|
||||
sharedEffectCode.Store(&code)
|
||||
})
|
||||
e := effects.entry(src)
|
||||
go func() {
|
||||
effects.sem <- struct{}{}
|
||||
defer func() { <-effects.sem }()
|
||||
e.run()
|
||||
}()
|
||||
}
|
||||
|
||||
// sharedEffectCode returns the code of an effect's pixel shader from the
|
||||
// cache, once PrecompileEffect made it, from any goroutine.
|
||||
var sharedEffectCode atomic.Pointer[func(src string) ([]byte, error)]
|
||||
|
||||
// compileEffectCode compiles the pixel shader of an effect whose code
|
||||
// compiled ahead of time does not match its source: CompileEffect, until
|
||||
// PrecompileEffect shares the code between the renderers.
|
||||
func compileEffectCode(src string) ([]byte, error) {
|
||||
if f := sharedEffectCode.Load(); f != nil {
|
||||
return (*f)(src)
|
||||
}
|
||||
return CompileEffect(src)
|
||||
}
|
||||
|
||||
// effectCache is the code of effects' pixel shaders, by their source.
|
||||
type effectCache struct {
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
byKey map[string]*effectEntry
|
||||
sem chan struct{} // the compilations on goroutines of their own
|
||||
dir string // where the code is kept, "" for nowhere
|
||||
}
|
||||
|
||||
// effects is the cache PrecompileEffect and the renderers share.
|
||||
var effects effectCache
|
||||
|
||||
// effectEntry is the code of an effect's pixel shader, compiled once.
|
||||
type effectEntry struct {
|
||||
c *effectCache
|
||||
src string
|
||||
once sync.Once
|
||||
code []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// entry returns the entry of src, created the first time.
|
||||
func (c *effectCache) entry(src string) *effectEntry {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if e := c.byKey[src]; e != nil {
|
||||
return e
|
||||
}
|
||||
e := &effectEntry{c: c, src: src}
|
||||
c.byKey[src] = e
|
||||
return e
|
||||
}
|
||||
|
||||
// code returns the code of src, compiling it unless a goroutine is, then
|
||||
// waiting for it.
|
||||
func (c *effectCache) code(src string) ([]byte, error) {
|
||||
e := c.entry(src)
|
||||
e.run()
|
||||
return e.code, e.err
|
||||
}
|
||||
|
||||
// effectFlags names how effects' code compiles in the names of the files
|
||||
// keeping it: the target and the flags of compile.
|
||||
const effectFlags = "ps_4_0 effectps O3 IEEE\n"
|
||||
|
||||
// run compiles e once, or reads its code from the disk.
|
||||
func (e *effectEntry) run() {
|
||||
e.once.Do(func() {
|
||||
full := EffectSource(e.src)
|
||||
var path string
|
||||
if e.c.dir != "" {
|
||||
path = filepath.Join(e.c.dir, gpu.SourceSum(effectFlags+full)+".dxbc")
|
||||
if b, err := os.ReadFile(path); err == nil && validDXBC(b) {
|
||||
now := time.Now()
|
||||
os.Chtimes(path, now, now) // the least recently used go first
|
||||
e.code = b
|
||||
return
|
||||
}
|
||||
}
|
||||
e.code, e.err = compile(full, "effectps", "ps_4_0")
|
||||
if e.err == nil && path != "" {
|
||||
saveEffectCode(path, e.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// validDXBC reports whether b looks like whole DXBC bytecode: its magic,
|
||||
// and the size its header gives. Direct3D checks its checksum.
|
||||
func validDXBC(b []byte) bool {
|
||||
return len(b) >= 32 && string(b[:4]) == "DXBC" && int(binary.LittleEndian.Uint32(b[24:])) == len(b)
|
||||
}
|
||||
|
||||
// effectCacheDir returns the directory keeping effects' code: one for the
|
||||
// user, as Windows' own shader cache (D3DSCache) is, since the files'
|
||||
// names are the SHA-256 of what they compiled from.
|
||||
func effectCacheDir() string {
|
||||
dir, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(dir, "MyGo", "ShaderCache")
|
||||
}
|
||||
|
||||
// effectCacheSize is how much code the cache keeps, in bytes, before it
|
||||
// removes the files least recently used, as sources change while an app
|
||||
// is developed.
|
||||
const effectCacheSize = 32 << 20
|
||||
|
||||
// saveEffectCode writes code to path, through a temporary file renamed
|
||||
// as another process may be reading it, and trims the cache. It does
|
||||
// without the cache on any error.
|
||||
func saveEffectCode(path string, code []byte) {
|
||||
dir := filepath.Dir(path)
|
||||
if os.MkdirAll(dir, 0o755) != nil {
|
||||
return
|
||||
}
|
||||
f, err := os.CreateTemp(dir, "*.tmp")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = f.Write(code)
|
||||
if f.Close() != nil || err != nil || os.Rename(f.Name(), path) != nil {
|
||||
os.Remove(f.Name())
|
||||
return
|
||||
}
|
||||
trimEffectCache(dir)
|
||||
}
|
||||
|
||||
// trimEffectCache removes the files of dir least recently used while
|
||||
// they weigh more than effectCacheSize.
|
||||
func trimEffectCache(dir string) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
type file struct {
|
||||
name string
|
||||
size int64
|
||||
used time.Time
|
||||
}
|
||||
var files []file
|
||||
var total int64
|
||||
for _, de := range entries {
|
||||
info, err := de.Info()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
files = append(files, file{de.Name(), info.Size(), info.ModTime()})
|
||||
total += info.Size()
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].used.Before(files[j].used) })
|
||||
for _, f := range files {
|
||||
if total <= effectCacheSize {
|
||||
break
|
||||
}
|
||||
if os.Remove(filepath.Join(dir, f.name)) == nil {
|
||||
total -= f.size
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testEffect = "float4 effect(float2 p, Effect e) { return float4(e.p0.rgb, 1); }\n"
|
||||
|
||||
// TestEffectCache checks that an effect's code compiles once for all its
|
||||
// users, as CompileEffect compiles it, and that a later launch reads it
|
||||
// from the disk.
|
||||
func TestEffectCache(t *testing.T) {
|
||||
want, err := CompileEffect(testEffect)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
c := &effectCache{byKey: map[string]*effectEntry{}, dir: dir}
|
||||
got, err := c.code(testEffect)
|
||||
if err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("code: %d bytes, %v; want %d bytes", len(got), err, len(want))
|
||||
}
|
||||
if again, _ := c.code(testEffect); &again[0] != &got[0] {
|
||||
t.Error("the code compiled again")
|
||||
}
|
||||
files, _ := filepath.Glob(filepath.Join(dir, "*.dxbc"))
|
||||
if len(files) != 1 {
|
||||
t.Fatalf("files kept: %v", files)
|
||||
}
|
||||
// A file that is not whole compiles again.
|
||||
os.WriteFile(files[0], want[:len(want)/2], 0o644)
|
||||
if got, _ := (&effectCache{byKey: map[string]*effectEntry{}, dir: dir}).code(testEffect); !bytes.Equal(got, want) {
|
||||
t.Error("a broken file was read")
|
||||
}
|
||||
// The next launch reads the file.
|
||||
marked := append([]byte(nil), want...)
|
||||
marked[len(marked)-1] ^= 1
|
||||
os.WriteFile(files[0], marked, 0o644)
|
||||
if got, _ := (&effectCache{byKey: map[string]*effectEntry{}, dir: dir}).code(testEffect); !bytes.Equal(got, marked) {
|
||||
t.Error("the file was not read")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrimEffectCache checks that the cache removes the files least
|
||||
// recently used beyond its size.
|
||||
func TestTrimEffectCache(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
big := make([]byte, effectCacheSize/2)
|
||||
for i, name := range []string{"a", "b", "c"} {
|
||||
path := filepath.Join(dir, name)
|
||||
os.WriteFile(path, big, 0o644)
|
||||
at := time.Unix(int64(1000*(3-i)), 0) // a is the newest
|
||||
os.Chtimes(path, at, at)
|
||||
}
|
||||
trimEffectCache(dir)
|
||||
for name, kept := range map[string]bool{"a": true, "b": true, "c": false} {
|
||||
if _, err := os.Stat(filepath.Join(dir, name)); (err == nil) != kept {
|
||||
t.Errorf("%s: kept %v, want %v", name, err == nil, kept)
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
//go:build ignore
|
||||
|
||||
// Gen compiles shader.hlsl and classes.hlsl to DXBC with the system's d3dcompiler_47.dll
|
||||
// and writes shaders.go, so that apps need no shader compiler. It runs on
|
||||
// Windows: go generate ./internal/gpu/d3d11
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"log"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// classSets are the classes that get shaders of their own, from those holding
|
||||
// least: each class, what small batches join most (shadows with the fills
|
||||
// casting them, fills with labels), and everything, for the rest.
|
||||
var classSets = []uint32{
|
||||
set(gpu.ClassPlain),
|
||||
set(gpu.ClassImage),
|
||||
set(gpu.ClassShadow),
|
||||
set(gpu.ClassPlain, gpu.ClassShadow),
|
||||
set(gpu.ClassGlyph),
|
||||
set(gpu.ClassSubpixel),
|
||||
set(gpu.ClassPlain, gpu.ClassGlyph),
|
||||
set(gpu.ClassPlain, gpu.ClassSubpixel),
|
||||
set(gpu.ClassFill),
|
||||
set(gpu.ClassPlain, gpu.ClassFill, gpu.ClassShadow, gpu.ClassGlyph, gpu.ClassSubpixel, gpu.ClassImage),
|
||||
}
|
||||
|
||||
func set(classes ...gpu.Class) (s uint32) {
|
||||
for _, c := range classes {
|
||||
s |= 1 << c
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// classDefines is that of shader.go, which this program cannot import, as it
|
||||
// makes a file of its package.
|
||||
func classDefines(cl uint32) string {
|
||||
s := fmt.Sprintf("#define CLASSES %d\n", cl)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
class gpu.Class
|
||||
}{{"PLAIN", gpu.ClassPlain}, {"FILL", gpu.ClassFill}, {"SHADOW", gpu.ClassShadow}, {"GLYPH", gpu.ClassGlyph}, {"SUBPIXEL", gpu.ClassSubpixel}, {"IMAGE", gpu.ClassImage}} {
|
||||
s += fmt.Sprintf("#define %s %d\n", c.name, cl>>c.class&1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func main() {
|
||||
src, err := os.ReadFile("shader.hlsl")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
classes, err := os.ReadFile("classes.hlsl")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
compiler := syscall.NewLazyDLL("d3dcompiler_47.dll").NewProc("D3DCompile")
|
||||
compile := func(src []byte, entry, target string) []byte {
|
||||
var blob, errs uintptr
|
||||
name, _ := syscall.BytePtrFromString("shader.hlsl")
|
||||
e, _ := syscall.BytePtrFromString(entry)
|
||||
t, _ := syscall.BytePtrFromString(target)
|
||||
// IEEE strictness avoids the native optimizer's stack overflow on
|
||||
// transformed coverage sampling while retaining level 3 optimization.
|
||||
const optimize3IEEE = 1<<15 | 1<<13
|
||||
hr, _, _ := compiler.Call(uintptr(unsafe.Pointer(&src[0])), uintptr(len(src)), uintptr(unsafe.Pointer(name)),
|
||||
0, 0, uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(t)), optimize3IEEE, 0,
|
||||
uintptr(unsafe.Pointer(&blob)), uintptr(unsafe.Pointer(&errs)))
|
||||
if int32(hr) < 0 {
|
||||
msg := "unknown error"
|
||||
if errs != 0 {
|
||||
msg = string(blobBytes(errs))
|
||||
}
|
||||
log.Fatalf("%s: %s", entry, msg)
|
||||
}
|
||||
return append([]byte(nil), blobBytes(blob)...)
|
||||
}
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "// Code generated by gen.go from shader.hlsl and classes.hlsl; DO NOT EDIT.\n\n//go:build windows\n\npackage d3d11\n\n")
|
||||
fmt.Fprintf(&b, "// shaderSum is the SHA-256 of the shader.hlsl and the classes.hlsl\n// the shaders were compiled from.\nconst shaderSum = %q\n\n", gpu.SourceSum(string(src)+string(classes)))
|
||||
for _, s := range []struct{ name, entry, target string }{{"vertexShader", "vs", "vs_4_0"}, {"pixelShader", "ps", "ps_4_0"},
|
||||
{"passVertexShader", "passvs", "vs_4_0"}, {"downShader", "downps", "ps_4_0"}, {"blurShader", "blurps", "ps_4_0"}} {
|
||||
b.WriteString(gpu.GoBytes(s.name, compile(src, s.entry, s.target)) + "\n")
|
||||
}
|
||||
b.WriteString("// classShaders are the shaders of classes.hlsl, from those holding least: a\n// batch draws with the first that holds its classes.\nvar classShaders = []classShader{\n")
|
||||
var vars bytes.Buffer
|
||||
for _, cl := range classSets {
|
||||
full := append([]byte(classDefines(cl)+string(src)+"\n"), classes...)
|
||||
fmt.Fprintf(&vars, "%s\n%s\n", gpu.GoBytes(fmt.Sprintf("classVS%d", cl), compile(full, "classvs", "vs_4_0")), gpu.GoBytes(fmt.Sprintf("classPS%d", cl), compile(full, "classps", "ps_4_0")))
|
||||
fmt.Fprintf(&b, "\t{%d, classVS%d, classPS%d},\n", cl, cl, cl)
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
b.Write(vars.Bytes())
|
||||
out, err := format.Source(b.Bytes())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile("shaders.go", out, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// blobBytes returns the contents of an ID3DBlob.
|
||||
func blobBytes(blob uintptr) []byte {
|
||||
call := func(i int) uintptr {
|
||||
vtbl := *(*uintptr)(unsafe.Pointer(blob))
|
||||
fn := *(*uintptr)(unsafe.Pointer(vtbl + uintptr(i)*unsafe.Sizeof(uintptr(0))))
|
||||
r, _, _ := syscall.SyscallN(fn, blob)
|
||||
return r
|
||||
}
|
||||
p, n := call(3), call(4)
|
||||
return unsafe.Slice((*byte)(unsafe.Pointer(p)), n)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// The shared builder's culling and scissors must preserve every pixel,
|
||||
// including nested clip masks and canvases drawn into textures, as with
|
||||
// OpenGL (see the gl package's test of the same name).
|
||||
func TestGeometryOptimizationsPreservePixels(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
type fixture struct {
|
||||
name string
|
||||
s *scene.Scene
|
||||
}
|
||||
var cases []fixture
|
||||
for _, c := range gputest.CullCases() {
|
||||
cases = append(cases, fixture{"cull/" + c.Name, c.Scene})
|
||||
}
|
||||
for _, c := range gputest.RingCases() {
|
||||
cases = append(cases, fixture{"ring/" + c.Name, c.Scene})
|
||||
}
|
||||
for i, c := range gputest.ShadowCases() {
|
||||
cases = append(cases, fixture{fmt.Sprintf("shadow/%d", i), gputest.ShadowPanelScene(c)})
|
||||
}
|
||||
for _, c := range gputest.MaskedCases() {
|
||||
cases = append(cases, fixture{"masked/" + c.Name, c.Scene})
|
||||
}
|
||||
cases = append(cases,
|
||||
fixture{"transformed", gputest.TransformedScene()},
|
||||
fixture{"perspective", gputest.PerspectiveScene()},
|
||||
fixture{"translated", gputest.TranslatedScenes()[0]},
|
||||
fixture{"translated-between-pixels", gputest.TranslatedScenes()[1]},
|
||||
fixture{"masked-clips", gputest.MaskedClipScene()},
|
||||
fixture{"corner-clips", gputest.CornerClipScene()},
|
||||
fixture{"wide-colors", gputest.WideScene()},
|
||||
fixture{"canvases", gputest.CanvasScene()},
|
||||
)
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
r, err := New(hiddenWindow(t, c.s.Width, c.s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.draw(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := r.readBack(t)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.b.NoCull, r.b.NoShadowSplit, r.b.NoRingSplit = true, true, true
|
||||
for _, canvas := range r.canvases {
|
||||
canvas.b.NoCull, canvas.b.NoShadowSplit, canvas.b.NoRingSplit = true, true, true
|
||||
}
|
||||
// Draw every canvas again under the reference policy, rather
|
||||
// than comparing against its already optimized texture.
|
||||
c.s.EachCanvas(func(img *scene.Image) { img.Changed() })
|
||||
if err := r.draw(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := r.readBack(t); !bytes.Equal(got, want) {
|
||||
t.Fatal("culling or split scissors changed pixels")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
)
|
||||
|
||||
// The swap chain's frame latency object keeps one frame waiting ahead of
|
||||
// the screen without Present blocking the main thread: DXGI signals it as
|
||||
// the screen takes a frame, and a frame presents only once a wait on it
|
||||
// succeeded. A frame drawn when it is not signaled yet presents later
|
||||
// (pending), as a goroutine waiting on it has the main thread present it,
|
||||
// rather than block in Present until the screen takes the last; frames
|
||||
// paced by the display wait meanwhile (Ready), as they would have. Every
|
||||
// present takes one wait's success, its token, so the object's count
|
||||
// stays that of the frames the screen can take.
|
||||
//
|
||||
// All that keeps a frame a refresh or more from the screen, built ahead and
|
||||
// queued. So frames that the last ones show will make the refresh without
|
||||
// (frameCost.fits) build once the window manager composed the last (DwmFlush) and
|
||||
// the screen has room, and present at once, with sync interval 0, to show at its
|
||||
// next composition: none queues, and input shows about a refresh sooner. Heavier
|
||||
// frames build ahead, as the one the GPU draws meanwhile leaves the main thread
|
||||
// free to build the next: they keep the display's pace, a refresh later.
|
||||
|
||||
// frameCost estimates what a frame costs from when it may start to when the GPU
|
||||
// has drawn it, by the time the main thread took to draw it and the GPU's
|
||||
// timestamps of it, which come in a frame or so later.
|
||||
type frameCost struct {
|
||||
// queries holds the timestamps of the last frames: next is where the next
|
||||
// frame's go, and each is busy until it was read.
|
||||
queries [4]frameQuery
|
||||
next int
|
||||
// start is when the frame being built could start, and estimate the costs
|
||||
// of the last frames, the highest held and fading.
|
||||
start time.Time
|
||||
estimate time.Duration
|
||||
// period is the display's refresh period.
|
||||
period time.Duration
|
||||
}
|
||||
|
||||
type frameQuery struct {
|
||||
disjoint, t0, t1 uintptr
|
||||
busy bool
|
||||
// main is the main thread's part of the frame, or -1 when no Ready started
|
||||
// it, as a resize's frame drawn at once: its cost is not known.
|
||||
main time.Duration
|
||||
}
|
||||
|
||||
// A frame that takes more of a refresh than fitShare may miss it when building
|
||||
// late; its estimate fades by costFade a frame.
|
||||
const (
|
||||
fitShare = 3.0 / 4
|
||||
costFade = 0.95
|
||||
)
|
||||
|
||||
// fits reports whether frames take little enough of a refresh to build once the
|
||||
// screen has room for them.
|
||||
func (c *frameCost) fits() bool {
|
||||
return float64(c.estimate) < fitShare*float64(c.refreshPeriod())
|
||||
}
|
||||
|
||||
// refreshPeriod returns the display's refresh period, a 60 Hz one when it is not
|
||||
// known.
|
||||
func (c *frameCost) refreshPeriod() time.Duration {
|
||||
if c.period == 0 {
|
||||
return minRefresh
|
||||
}
|
||||
return c.period
|
||||
}
|
||||
|
||||
// makeQueries makes the queries, reporting whether it could: frames otherwise
|
||||
// count as not fitting.
|
||||
func (c *frameCost) makeQueries(device uintptr) bool {
|
||||
const queryTimestamp, queryTimestampDisjoint = 2, 3
|
||||
make1 := func(kind uint32, out *uintptr) bool {
|
||||
desc := [2]uint32{kind, 0}
|
||||
return !failed(call(device, devCreateQuery, uintptr(unsafe.Pointer(&desc)), uintptr(unsafe.Pointer(out))))
|
||||
}
|
||||
for i := range c.queries {
|
||||
q := &c.queries[i]
|
||||
if !make1(queryTimestampDisjoint, &q.disjoint) || !make1(queryTimestamp, &q.t0) || !make1(queryTimestamp, &q.t1) {
|
||||
c.release()
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *frameCost) release() {
|
||||
for i := range c.queries {
|
||||
q := &c.queries[i]
|
||||
free(&q.t1)
|
||||
free(&q.t0)
|
||||
free(&q.disjoint)
|
||||
q.busy = false
|
||||
}
|
||||
}
|
||||
|
||||
// begin notes that the GPU starts drawing a frame, unless all queries wait to be
|
||||
// read, which skips timing it. It comes after the frame's clear: the GPU reaches
|
||||
// that once the window manager gave the buffer back, which is no work of the
|
||||
// frame's, up to a refresh after the last.
|
||||
func (c *frameCost) begin(ctx uintptr) *frameQuery {
|
||||
q := &c.queries[c.next]
|
||||
if q.disjoint == 0 || q.busy {
|
||||
return nil
|
||||
}
|
||||
call(ctx, ctxBegin, q.disjoint)
|
||||
call(ctx, ctxEnd, q.t0)
|
||||
return q
|
||||
}
|
||||
|
||||
// end notes that the GPU finishes drawing the frame of q and, for its main
|
||||
// thread's part, that it took since start, which only this frame takes.
|
||||
func (c *frameCost) end(ctx uintptr, q *frameQuery) {
|
||||
call(ctx, ctxEnd, q.t1)
|
||||
call(ctx, ctxEnd, q.disjoint)
|
||||
q.busy = true
|
||||
q.main = c.took()
|
||||
c.next = (c.next + 1) % len(c.queries)
|
||||
}
|
||||
|
||||
// took returns how long the main thread took on the frame since start, and
|
||||
// forgets start: a frame no Ready started, as the ones a resize draws at once,
|
||||
// would count all the time since the last that one did, seconds of a drag, and
|
||||
// have frames build ahead long after. Its cost is not known (-1).
|
||||
func (c *frameCost) took() time.Duration {
|
||||
if c.start.IsZero() {
|
||||
return -1
|
||||
}
|
||||
d := time.Since(c.start)
|
||||
c.start = time.Time{}
|
||||
return d
|
||||
}
|
||||
|
||||
// read takes in the timestamps that came, oldest first, without waiting.
|
||||
func (c *frameCost) read(ctx uintptr) {
|
||||
const doNotFlush = 1
|
||||
for range c.queries {
|
||||
// The oldest is the one after the last begun.
|
||||
q := &c.queries[c.next]
|
||||
for i := range c.queries {
|
||||
q = &c.queries[(c.next+i)%len(c.queries)]
|
||||
if q.busy {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !q.busy {
|
||||
return
|
||||
}
|
||||
var clock struct {
|
||||
Frequency uint64
|
||||
Disjoint int32
|
||||
_ int32
|
||||
}
|
||||
var t0, t1 uint64
|
||||
if call(ctx, ctxGetData, q.disjoint, uintptr(unsafe.Pointer(&clock)), unsafe.Sizeof(clock), doNotFlush) != 0 ||
|
||||
call(ctx, ctxGetData, q.t0, uintptr(unsafe.Pointer(&t0)), 8, doNotFlush) != 0 ||
|
||||
call(ctx, ctxGetData, q.t1, uintptr(unsafe.Pointer(&t1)), 8, doNotFlush) != 0 {
|
||||
return
|
||||
}
|
||||
q.busy = false
|
||||
if q.main >= 0 && clock.Disjoint == 0 && clock.Frequency != 0 && t1 >= t0 {
|
||||
c.add(q.main + time.Duration(float64(t1-t0)/float64(clock.Frequency)*float64(time.Second)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add takes in what a frame cost.
|
||||
func (c *frameCost) add(cost time.Duration) {
|
||||
c.estimate = max(cost, time.Duration(float64(c.estimate)*costFade))
|
||||
}
|
||||
|
||||
// readPeriod reads the display's refresh period from the window manager; it
|
||||
// stays what it was when that fails.
|
||||
func (c *frameCost) readPeriod() {
|
||||
if p := dwmPeriod(); p != 0 {
|
||||
c.period = p
|
||||
}
|
||||
}
|
||||
|
||||
// dwmPeriod returns the display's refresh period as the window manager
|
||||
// tells it, 0 when it does not; tests replace it.
|
||||
var dwmPeriod = func() time.Duration {
|
||||
// DWM_TIMING_INFO, packed: its size, then the refresh rate's numerator and
|
||||
// denominator.
|
||||
var info [292]byte
|
||||
*(*uint32)(unsafe.Pointer(&info[0])) = uint32(len(info))
|
||||
if hr, _, _ := procDwmGetCompositionTimingInfo.Call(0, uintptr(unsafe.Pointer(&info[0]))); failed(hr) {
|
||||
return 0
|
||||
}
|
||||
num, den := *(*uint32)(unsafe.Pointer(&info[4])), *(*uint32)(unsafe.Pointer(&info[8]))
|
||||
if num == 0 || den == 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(float64(time.Second) * float64(den) / float64(num))
|
||||
}
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL(device.SystemDir() + `\kernel32.dll`)
|
||||
procWaitForObject = kernel32.NewProc("WaitForSingleObject")
|
||||
procCloseHandle = kernel32.NewProc("CloseHandle")
|
||||
)
|
||||
|
||||
// latencyTimeout is the longest a wait on the object takes, in
|
||||
// milliseconds: the screen takes a frame each refresh, but takes none while
|
||||
// the window shows nowhere, when a frame presents without its token.
|
||||
var latencyTimeout uintptr = 1000
|
||||
|
||||
const (
|
||||
waitObject0 = 0
|
||||
// swapChainWaitable is DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT.
|
||||
swapChainWaitable = 0x40
|
||||
)
|
||||
|
||||
type latency struct {
|
||||
// handle is the object, 0 without one: frames then present at once.
|
||||
handle uintptr
|
||||
|
||||
mu sync.Mutex
|
||||
// token tells that a wait succeeded that no present took yet; waiting
|
||||
// that a goroutine waits on the object, which done tells the end of,
|
||||
// and then what it calls; lapsed that the goroutine's wait timed out,
|
||||
// so the present it calls on does not wait again, on the main thread.
|
||||
token, waiting, lapsed bool
|
||||
done chan struct{}
|
||||
then func()
|
||||
}
|
||||
|
||||
// waitObject waits on the object, at most ms milliseconds, and reports
|
||||
// whether it was signaled.
|
||||
func (l *latency) waitObject(ms uintptr) bool {
|
||||
r, _, _ := procWaitForObject.Call(l.handle, ms)
|
||||
return r == waitObject0
|
||||
}
|
||||
|
||||
// ready reports whether a present can take its token at once, waiting for
|
||||
// nothing.
|
||||
func (l *latency) ready() bool {
|
||||
if l.handle == 0 {
|
||||
return true
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !l.token && !l.waiting {
|
||||
l.token = l.waitObject(0)
|
||||
}
|
||||
// A wait that lapsed is a present that waits for nothing (take).
|
||||
return l.token || l.lapsed
|
||||
}
|
||||
|
||||
// waitThen has a goroutine wait for the object and call then, on its own
|
||||
// goroutine, once it is signaled (or after latencyTimeout).
|
||||
func (l *latency) waitThen(then func()) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.then = then
|
||||
if l.waiting {
|
||||
return
|
||||
}
|
||||
l.waiting, l.done = true, make(chan struct{})
|
||||
go func() {
|
||||
signaled := l.waitObject(latencyTimeout)
|
||||
l.mu.Lock()
|
||||
l.token = l.token || signaled
|
||||
l.lapsed = !l.token
|
||||
l.waiting = false
|
||||
then := l.then
|
||||
l.then = nil
|
||||
close(l.done)
|
||||
l.mu.Unlock()
|
||||
if then != nil {
|
||||
then()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// take takes the token a present needs, waiting for it on the calling
|
||||
// thread (a resize's frame, one waited for): at most latencyTimeout, after
|
||||
// which the frame presents without one. A present whose goroutine's wait
|
||||
// timed out already waited as long, while the window shows nowhere, and
|
||||
// presents without waiting again.
|
||||
func (l *latency) take() {
|
||||
if l.handle == 0 {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
done, waiting := l.done, l.waiting
|
||||
l.mu.Unlock()
|
||||
if waiting {
|
||||
<-done
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !l.token && !l.lapsed {
|
||||
l.waitObject(latencyTimeout)
|
||||
}
|
||||
l.token, l.lapsed = false, false
|
||||
}
|
||||
|
||||
// release waits for a goroutine waiting on the object and closes it.
|
||||
func (l *latency) release() {
|
||||
if l.handle == 0 {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
done, waiting := l.done, l.waiting
|
||||
l.then = nil
|
||||
l.mu.Unlock()
|
||||
if waiting {
|
||||
<-done
|
||||
}
|
||||
procCloseHandle.Call(l.handle)
|
||||
l.handle, l.token = 0, false
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
var (
|
||||
procCreateSemaphore = kernel32.NewProc("CreateSemaphoreW")
|
||||
procReleaseSemaphore = kernel32.NewProc("ReleaseSemaphore")
|
||||
)
|
||||
|
||||
// TestFrameLatencyTokens checks the frame latency object's tokens, with a
|
||||
// semaphore standing in for DXGI's: a present is ready when the object is
|
||||
// signaled, holding its token until a present takes it; otherwise a
|
||||
// goroutine waits for it and calls on; a present drawn at once waits for
|
||||
// that goroutine; and each present takes one, so the count stays the
|
||||
// frames the screen can take.
|
||||
func TestFrameLatencyTokens(t *testing.T) {
|
||||
h, _, err := procCreateSemaphore.Call(0, 0, 8, 0)
|
||||
if h == 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := latency{handle: h}
|
||||
defer l.release()
|
||||
signal := func() { procReleaseSemaphore.Call(h, 1, 0) }
|
||||
|
||||
if l.ready() {
|
||||
t.Fatal("ready before the screen took a frame")
|
||||
}
|
||||
woke := make(chan struct{}, 2)
|
||||
l.waitThen(func() { woke <- struct{}{} })
|
||||
l.waitThen(func() { woke <- struct{}{} }) // the same wait
|
||||
if l.ready() {
|
||||
t.Fatal("ready while waiting")
|
||||
}
|
||||
signal()
|
||||
wait.For(t, "the wait's end", woke)
|
||||
if len(woke) != 0 {
|
||||
t.Fatal("one wait called on twice")
|
||||
}
|
||||
if !l.ready() || !l.ready() {
|
||||
t.Fatal("not ready with the token")
|
||||
}
|
||||
// A present takes it: the next is not ready.
|
||||
l.take()
|
||||
if l.ready() {
|
||||
t.Fatal("ready after a present took the token")
|
||||
}
|
||||
// A present drawn at once waits for the goroutine waiting.
|
||||
l.waitThen(nil)
|
||||
go signal()
|
||||
l.take()
|
||||
if l.token || l.waiting {
|
||||
t.Fatalf("after a present drawn at once: token %v, waiting %v", l.token, l.waiting)
|
||||
}
|
||||
// Signaled when asked: ready at once, with no goroutine.
|
||||
signal()
|
||||
if !l.ready() || l.waiting {
|
||||
t.Fatal("not ready at once when signaled")
|
||||
}
|
||||
l.take()
|
||||
// Every success taken: the count is back to none.
|
||||
if l.waitObject(0) {
|
||||
t.Fatal("the object's count drifted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLapsedWaitPresentsAtOnce checks that a present whose goroutine's
|
||||
// wait on the object timed out, as it does while the window shows
|
||||
// nowhere, takes no token and does not wait for one again on the main
|
||||
// thread, which would stall it a whole timeout more for each such frame.
|
||||
func TestLapsedWaitPresentsAtOnce(t *testing.T) {
|
||||
defer func(ms uintptr) { latencyTimeout = ms }(latencyTimeout)
|
||||
latencyTimeout = 400
|
||||
h, _, err := procCreateSemaphore.Call(0, 0, 8, 0)
|
||||
if h == 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := latency{handle: h}
|
||||
defer l.release()
|
||||
|
||||
woke := make(chan struct{}, 1)
|
||||
l.waitThen(func() { woke <- struct{}{} })
|
||||
wait.For(t, "the wait's timeout", woke)
|
||||
start := time.Now()
|
||||
l.take()
|
||||
if d := time.Since(start); d >= 200*time.Millisecond {
|
||||
t.Fatalf("the present waited %v again after a lapsed wait", d)
|
||||
}
|
||||
if l.token || l.lapsed {
|
||||
t.Fatalf("after the present: token %v, lapsed %v", l.token, l.lapsed)
|
||||
}
|
||||
// The next present that the screen has room for takes its token as
|
||||
// before.
|
||||
procReleaseSemaphore.Call(h, 1, 0)
|
||||
if !l.ready() {
|
||||
t.Fatal("not ready when signaled")
|
||||
}
|
||||
l.take()
|
||||
if l.waitObject(0) {
|
||||
t.Fatal("the object's count drifted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnchangedFrameWaitsForRefresh checks that a frame that changes
|
||||
// nothing, and so presents nothing, still has the next wait for the
|
||||
// display (Ready), until the refresh it waits for comes: an animation
|
||||
// whose frames move less than a pixel keeps the display's pace rather
|
||||
// than draw as fast as the main thread can (#608).
|
||||
func TestUnchangedFrameWaitsForRefresh(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
refresh := make(chan struct{})
|
||||
defer func(f func(_, _ time.Duration)) { awaitRefresh = f }(awaitRefresh)
|
||||
awaitRefresh = func(_, _ time.Duration) { <-refresh }
|
||||
|
||||
s := gputest.NewChanging(1).Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
if r.ctx1 == 0 {
|
||||
t.Skip("no Direct3D 11.1")
|
||||
}
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(f func()) { posted <- f })
|
||||
r.cost.estimate = time.Hour // frames that go through the frame latency object
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for r.pending {
|
||||
wait.For(t, "the first frame's present", posted)() // once the screen has room
|
||||
}
|
||||
if !r.Ready(func() {}) {
|
||||
t.Fatal("not ready after a frame presented")
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.redrew != redrewNothing {
|
||||
t.Fatal("the same scene drew again")
|
||||
}
|
||||
woke := make(chan struct{}, 2)
|
||||
if r.Ready(func() { woke <- struct{}{} }) {
|
||||
t.Fatal("ready at once after a frame that changed nothing")
|
||||
}
|
||||
// The next frame that changes nothing waits for the same refresh.
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refresh <- struct{}{}
|
||||
wait.For(t, "the refresh's end", posted)()
|
||||
wait.For(t, "the wake", woke)
|
||||
if !r.Ready(func() { woke <- struct{}{} }) {
|
||||
t.Fatal("not ready after the refresh")
|
||||
}
|
||||
if len(woke) != 0 || len(posted) != 0 {
|
||||
t.Fatal("woken twice")
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// RenderOffscreen draws s with a renderer of its own into a window that
|
||||
// never shows, and returns the premultiplied BGRA rows of its back buffer
|
||||
// and their stride: for tests, as packages drawing effects have.
|
||||
func RenderOffscreen(s *scene.Scene) ([]byte, int, error) {
|
||||
hwnd, err := newHiddenWindow(s.Width, s.Height)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.draw(s); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return r.read()
|
||||
}
|
||||
|
||||
// newHiddenWindow creates a window that never shows, for a swap chain.
|
||||
func newHiddenWindow(w, h int) (uintptr, error) {
|
||||
class, _ := syscall.UTF16PtrFromString("STATIC")
|
||||
const wsPopup = 0x80000000
|
||||
hwnd, _, err := user32.NewProc("CreateWindowExW").Call(0, uintptr(unsafe.Pointer(class)), 0, wsPopup, 0, 0, uintptr(w), uintptr(h), 0, 0, 0, 0)
|
||||
if hwnd == 0 {
|
||||
return 0, fmt.Errorf("d3d11: cannot create a window: %w", err)
|
||||
}
|
||||
return hwnd, nil
|
||||
}
|
||||
|
||||
func destroyWindow(hwnd uintptr) { user32.NewProc("DestroyWindow").Call(hwnd) }
|
||||
|
||||
// read copies the back buffer to memory: BGRA rows and their stride.
|
||||
func (r *Renderer) read() ([]byte, int, error) { return r.readPart(r.w, r.h) }
|
||||
|
||||
// readPart copies the w×h pixels at the top left of the back buffer to
|
||||
// memory, as read.
|
||||
func (r *Renderer) readPart(w, h int) ([]byte, int, error) {
|
||||
var back, staging uintptr
|
||||
if hr := call(r.swapChain, scGetBuffer, 0, uintptr(unsafe.Pointer(&iidID3D11Texture2D)), uintptr(unsafe.Pointer(&back))); failed(hr) {
|
||||
return nil, 0, fmt.Errorf("d3d11: no back buffer: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&back)
|
||||
const usageStaging, cpuAccessRead, mapRead, ctxCopyResource = 3, 0x20000, 1, 47
|
||||
desc := texture2DDesc{Width: uint32(r.bw), Height: uint32(r.bh), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm,
|
||||
SampleCount: 1, Usage: usageStaging, CPUAccessFlags: cpuAccessRead}
|
||||
if hr := call(r.device, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&staging))); failed(hr) {
|
||||
return nil, 0, fmt.Errorf("d3d11: no staging texture: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&staging)
|
||||
call(r.ctx, ctxCopyResource, staging, back)
|
||||
var m mapped
|
||||
if hr := call(r.ctx, ctxMap, staging, 0, mapRead, 0, uintptr(unsafe.Pointer(&m))); failed(hr) {
|
||||
return nil, 0, fmt.Errorf("d3d11: cannot map: %#x", uint32(hr))
|
||||
}
|
||||
defer call(r.ctx, ctxUnmap, staging, 0)
|
||||
pix := make([]byte, w*h*4)
|
||||
for y := range h {
|
||||
copy(pix[y*w*4:], unsafe.Slice((*byte)(ptr(m.Data+uintptr(y)*uintptr(m.RowPitch))), w*4))
|
||||
}
|
||||
return pix, w * 4, nil
|
||||
}
|
||||
|
||||
// Offscreen draws scenes into a window that never shows, timing each on
|
||||
// the GPU, for measurements (BenchmarkStressFrameGPU).
|
||||
type Offscreen struct {
|
||||
r *Renderer
|
||||
hwnd uintptr
|
||||
disjoint, t0, t1 uintptr
|
||||
}
|
||||
|
||||
// NewOffscreen returns an Offscreen drawing frames of w×h pixels.
|
||||
func NewOffscreen(w, h int) (*Offscreen, error) {
|
||||
hwnd, err := newHiddenWindow(w, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
destroyWindow(hwnd)
|
||||
return nil, err
|
||||
}
|
||||
o := &Offscreen{r: r, hwnd: hwnd}
|
||||
const queryTimestamp, queryTimestampDisjoint = 2, 3
|
||||
for _, q := range []struct {
|
||||
kind uint32
|
||||
out *uintptr
|
||||
}{{queryTimestampDisjoint, &o.disjoint}, {queryTimestamp, &o.t0}, {queryTimestamp, &o.t1}} {
|
||||
desc := [2]uint32{q.kind, 0}
|
||||
if hr := call(r.device, devCreateQuery, uintptr(unsafe.Pointer(&desc)), uintptr(unsafe.Pointer(q.out))); failed(hr) {
|
||||
o.Release()
|
||||
return nil, fmt.Errorf("d3d11: cannot create a query: %#x", uint32(hr))
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// Render draws s whole and returns the time the GPU spent drawing it, once
|
||||
// it is done.
|
||||
func (o *Offscreen) Render(s *scene.Scene) (time.Duration, error) {
|
||||
ctx := o.r.ctx
|
||||
call(ctx, ctxBegin, o.disjoint)
|
||||
call(ctx, ctxEnd, o.t0)
|
||||
if err := o.r.draw(s); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
call(ctx, ctxEnd, o.t1)
|
||||
call(ctx, ctxEnd, o.disjoint)
|
||||
call(ctx, ctxFlush)
|
||||
var clock struct {
|
||||
Frequency uint64
|
||||
Disjoint int32
|
||||
_ int32
|
||||
}
|
||||
var start, end uint64
|
||||
get := func(q uintptr, out unsafe.Pointer, size uintptr) {
|
||||
// S_FALSE, 1, until the GPU gets there.
|
||||
for call(ctx, ctxGetData, q, uintptr(out), size, 0) == 1 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
get(o.disjoint, unsafe.Pointer(&clock), unsafe.Sizeof(clock))
|
||||
get(o.t0, unsafe.Pointer(&start), 8)
|
||||
get(o.t1, unsafe.Pointer(&end), 8)
|
||||
if clock.Disjoint != 0 || clock.Frequency == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return time.Duration(float64(end-start) / float64(clock.Frequency) * float64(time.Second)), nil
|
||||
}
|
||||
|
||||
// Release frees what the Offscreen holds.
|
||||
func (o *Offscreen) Release() {
|
||||
free(&o.t1)
|
||||
free(&o.t0)
|
||||
free(&o.disjoint)
|
||||
o.r.Release()
|
||||
destroyWindow(o.hwnd)
|
||||
}
|
||||
|
||||
// Frames draws frames one after another into a window that never shows,
|
||||
// for videos (plugins/render): Draw draws one and copies it into a
|
||||
// staging texture kept from frame to frame, without waiting for the GPU;
|
||||
// Read waits for it and copies its pixels.
|
||||
type Frames struct {
|
||||
r *Renderer
|
||||
hwnd uintptr
|
||||
staging uintptr
|
||||
w, h int
|
||||
}
|
||||
|
||||
// NewFrames returns a Frames drawing frames of w×h pixels.
|
||||
func NewFrames(w, h int) (*Frames, error) {
|
||||
hwnd, err := newHiddenWindow(w, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
destroyWindow(hwnd)
|
||||
return nil, err
|
||||
}
|
||||
return &Frames{r: r, hwnd: hwnd}, nil
|
||||
}
|
||||
|
||||
// Software reports whether the frames draw with WARP, Windows' software
|
||||
// rasterizer, for a system without a GPU.
|
||||
func (f *Frames) Software() bool { return f.r.warp }
|
||||
|
||||
// Name returns the description of the adapter, as "NVIDIA GeForce RTX 4070".
|
||||
func (f *Frames) Name() string {
|
||||
var dxgiDev, adapter uintptr
|
||||
if failed(call(f.r.device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice)), uintptr(unsafe.Pointer(&dxgiDev)))) {
|
||||
return ""
|
||||
}
|
||||
defer free(&dxgiDev)
|
||||
if failed(call(dxgiDev, dxgiDevGetAdapter, uintptr(unsafe.Pointer(&adapter)))) {
|
||||
return ""
|
||||
}
|
||||
defer free(&adapter)
|
||||
// DXGI_ADAPTER_DESC begins with its description, in 128 WCHARs.
|
||||
var desc [512]byte
|
||||
const adapterGetDesc = 8
|
||||
if failed(call(adapter, adapterGetDesc, uintptr(unsafe.Pointer(&desc[0])))) {
|
||||
return ""
|
||||
}
|
||||
return syscall.UTF16ToString(unsafe.Slice((*uint16)(unsafe.Pointer(&desc[0])), 128))
|
||||
}
|
||||
|
||||
// Draw draws s whole, and copies it for Read.
|
||||
func (f *Frames) Draw(s *scene.Scene) error {
|
||||
r := f.r
|
||||
if err := r.draw(s); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.staging == 0 || f.w != r.bw || f.h != r.bh {
|
||||
free(&f.staging)
|
||||
const usageStaging, cpuAccessRead = 3, 0x20000
|
||||
desc := texture2DDesc{Width: uint32(r.bw), Height: uint32(r.bh), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm,
|
||||
SampleCount: 1, Usage: usageStaging, CPUAccessFlags: cpuAccessRead}
|
||||
if hr := call(r.device, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&f.staging))); failed(hr) {
|
||||
return fmt.Errorf("d3d11: no staging texture: %#x", uint32(hr))
|
||||
}
|
||||
f.w, f.h = r.bw, r.bh
|
||||
}
|
||||
var back uintptr
|
||||
if hr := call(r.swapChain, scGetBuffer, 0, uintptr(unsafe.Pointer(&iidID3D11Texture2D)), uintptr(unsafe.Pointer(&back))); failed(hr) {
|
||||
return fmt.Errorf("d3d11: no back buffer: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&back)
|
||||
const ctxCopyResource = 47
|
||||
call(r.ctx, ctxCopyResource, f.staging, back)
|
||||
call(r.ctx, ctxFlush)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read copies the pixels of the frame Draw drew last, w×h, into dst:
|
||||
// premultiplied BGRA rows from the top, 4×w bytes each. It waits for the
|
||||
// GPU to finish the frame.
|
||||
func (f *Frames) Read(dst []byte, w, h int) error {
|
||||
if f.staging == 0 || w > f.w || h > f.h || len(dst) < 4*w*h {
|
||||
return errors.New("d3d11: no frame to read, or too small a buffer")
|
||||
}
|
||||
const mapRead = 1
|
||||
var m mapped
|
||||
if hr := call(f.r.ctx, ctxMap, f.staging, 0, mapRead, 0, uintptr(unsafe.Pointer(&m))); failed(hr) {
|
||||
return fmt.Errorf("d3d11: cannot map: %#x", uint32(hr))
|
||||
}
|
||||
defer call(f.r.ctx, ctxUnmap, f.staging, 0)
|
||||
for y := range h {
|
||||
copy(dst[y*w*4:(y+1)*w*4], unsafe.Slice((*byte)(ptr(m.Data+uintptr(y)*uintptr(m.RowPitch))), w*4))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release frees what the Frames hold.
|
||||
func (f *Frames) Release() {
|
||||
free(&f.staging)
|
||||
f.r.Release()
|
||||
destroyWindow(f.hwnd)
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
)
|
||||
|
||||
//go:embed shader.hlsl
|
||||
var shaderSource string
|
||||
|
||||
// effectSource is the head and the tail of an effect's pixel shader,
|
||||
// around the line "// effect" (see EffectSource).
|
||||
//
|
||||
//go:embed effect.hlsl
|
||||
var effectSource string
|
||||
|
||||
//go:embed classes.hlsl
|
||||
var classSource string
|
||||
|
||||
// sourceSum is the SHA-256 of the source of the shaders of shaders.go.
|
||||
func sourceSum() string { return gpu.SourceSum(shaderSource + classSource) }
|
||||
|
||||
// classShader is what batches of some classes draw with, compiled ahead of
|
||||
// time: the vertex and pixel shaders of classes.hlsl with CLASSES defined.
|
||||
type classShader struct {
|
||||
classes uint32
|
||||
vs, ps []byte
|
||||
}
|
||||
|
||||
// classDefines returns what classes.hlsl needs defined for the classes cl (a
|
||||
// bit, 1 << gpu.Class, for each), as gen.go compiles it.
|
||||
func classDefines(cl uint32) string {
|
||||
s := fmt.Sprintf("#define CLASSES %d\n", cl)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
class gpu.Class
|
||||
}{{"PLAIN", gpu.ClassPlain}, {"FILL", gpu.ClassFill}, {"SHADOW", gpu.ClassShadow}, {"GLYPH", gpu.ClassGlyph}, {"SUBPIXEL", gpu.ClassSubpixel}, {"IMAGE", gpu.ClassImage}} {
|
||||
s += fmt.Sprintf("#define %s %d\n", c.name, cl>>c.class&1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// compileClass compiles the shaders of the classes cl from their sources, for
|
||||
// shaders.go older than them.
|
||||
func compileClass(cl uint32) (vs, ps []byte, err error) {
|
||||
src := classDefines(cl) + shaderSource + "\n" + classSource
|
||||
if vs, err = compile(src, "classvs", "vs_4_0"); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if ps, err = compile(src, "classps", "ps_4_0"); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return vs, ps, nil
|
||||
}
|
||||
|
||||
// EffectSource returns the source of an effect's pixel shader: shader.hlsl
|
||||
// with EFFECT defined, the head of effect.hlsl, the effect's shader (see
|
||||
// scene.Effect), and the tail, which draws its instances with it
|
||||
// (effectps). Effects compile it ahead of time with CompileEffect.
|
||||
func EffectSource(src string) string {
|
||||
head, tail, _ := strings.Cut(effectSource, "\n// effect\n")
|
||||
return "#define EFFECT\n" + shaderSource + "\n" + head + "\n" + src + "\n" + tail
|
||||
}
|
||||
|
||||
// CompileEffect compiles the pixel shader of an effect whose shader is
|
||||
// src, with the compiler Windows has, as go generate does for code
|
||||
// compiled ahead of time.
|
||||
func CompileEffect(src string) ([]byte, error) {
|
||||
return compile(EffectSource(src), "effectps", "ps_4_0")
|
||||
}
|
||||
|
||||
// compileShaders makes shaderCode compile shader.hlsl even when the
|
||||
// bytecode of shaders.go comes from it, for tests.
|
||||
var compileShaders bool
|
||||
|
||||
// shaders is the bytecode of the shader's functions: the instances' vertex
|
||||
// and pixel shaders, and the passes computing backdrops (see package gpu).
|
||||
type shaders struct {
|
||||
vs, ps, passVS, down, blur []byte
|
||||
}
|
||||
|
||||
// shaderCode returns the bytecode of the shaders: that compiled ahead of
|
||||
// time into shaders.go, or, when shader.hlsl or classes.hlsl changed since (go generate
|
||||
// ./internal/gpu/d3d11 was not run), that compiled now from shader.hlsl,
|
||||
// with the compiler Windows has.
|
||||
func shaderCode() (code shaders, err error) {
|
||||
if sourceSum() == shaderSum && !compileShaders {
|
||||
return shaders{vertexShader, pixelShader, passVertexShader, downShader, blurShader}, nil
|
||||
}
|
||||
for _, f := range []struct {
|
||||
code *[]byte
|
||||
entry, target string
|
||||
}{{&code.vs, "vs", "vs_4_0"}, {&code.ps, "ps", "ps_4_0"}, {&code.passVS, "passvs", "vs_4_0"}, {&code.down, "downps", "ps_4_0"}, {&code.blur, "blurps", "ps_4_0"}} {
|
||||
if *f.code, err = compileShader(f.entry, f.target); err != nil {
|
||||
return shaders{}, err
|
||||
}
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
||||
// procD3DCompile is the shader compiler of Windows 10 and later, which gen.go
|
||||
// compiles shaders.go with too.
|
||||
var procD3DCompile = syscall.NewLazyDLL(device.SystemDir() + `\d3dcompiler_47.dll`).NewProc("D3DCompile")
|
||||
|
||||
// compileShader compiles the function entry of shader.hlsl for target, as
|
||||
// gen.go does.
|
||||
func compileShader(entry, target string) ([]byte, error) {
|
||||
return compile(shaderSource, entry, target)
|
||||
}
|
||||
|
||||
// compile compiles the function entry of source for target.
|
||||
func compile(source, entry, target string) ([]byte, error) {
|
||||
if err := procD3DCompile.Find(); err != nil {
|
||||
return nil, fmt.Errorf("d3d11: no shader compiler: %w", err)
|
||||
}
|
||||
src := []byte(source)
|
||||
name, _ := syscall.BytePtrFromString("shader.hlsl")
|
||||
e, _ := syscall.BytePtrFromString(entry)
|
||||
t, _ := syscall.BytePtrFromString(target)
|
||||
// IEEE strictness avoids the native optimizer's stack overflow on
|
||||
// transformed coverage sampling while retaining level 3 optimization.
|
||||
const optimize3IEEE = 1<<15 | 1<<13
|
||||
var blob, errs uintptr
|
||||
hr, _, _ := procD3DCompile.Call(uintptr(unsafe.Pointer(&src[0])), uintptr(len(src)), uintptr(unsafe.Pointer(name)),
|
||||
0, 0, uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(t)), optimize3IEEE, 0,
|
||||
uintptr(unsafe.Pointer(&blob)), uintptr(unsafe.Pointer(&errs)))
|
||||
if errs != 0 {
|
||||
defer free(&errs)
|
||||
}
|
||||
if failed(hr) || blob == 0 {
|
||||
msg := "unknown error"
|
||||
if errs != 0 {
|
||||
msg = string(blobBytes(errs))
|
||||
}
|
||||
return nil, fmt.Errorf("d3d11: cannot compile the %s shader: %s", entry, msg)
|
||||
}
|
||||
defer free(&blob)
|
||||
return append([]byte(nil), blobBytes(blob)...), nil
|
||||
}
|
||||
|
||||
// blobBytes returns the contents of an ID3DBlob, until it is released.
|
||||
func blobBytes(blob uintptr) []byte {
|
||||
const blobGetBufferPointer, blobGetBufferSize = 3, 4
|
||||
p, n := call(blob, blobGetBufferPointer), call(blob, blobGetBufferSize)
|
||||
return unsafe.Slice((*byte)(ptr(p)), n)
|
||||
}
|
||||
+654
@@ -0,0 +1,654 @@
|
||||
// The one shader of the Direct3D 11 renderer: every scene op is an
|
||||
// instanced quad, and the pixel shader computes the coverage of rounded
|
||||
// rectangles, borders, gradients, stripes and shadows from signed
|
||||
// distances, as the software renderer (internal/raster) does, with the
|
||||
// passes computing the backdrops of effects (passvs, downps and blurps).
|
||||
// The pixel shaders of effects (scene.Effect) take its start, with EFFECT
|
||||
// defined, before effect.hlsl. Colors are straight (not
|
||||
// premultiplied) and blending happens in sRGB space, as in browsers, with a
|
||||
// second color for the source's alpha of each channel, which subpixel
|
||||
// glyphs need.
|
||||
//
|
||||
// `go generate` compiles it to DXBC (shaders.go) on Windows.
|
||||
|
||||
cbuffer Globals : register(b0) {
|
||||
float2 viewport;
|
||||
float2 pad;
|
||||
};
|
||||
|
||||
struct Inst {
|
||||
float4 rect : RECT; // x, y, width, height in pixels
|
||||
float4 radii : RADII; // top-left, top-right, bottom-right, bottom-left
|
||||
float4 inner : INNER; // radii of the border's inner edge, of the box casting a shadow, or of an inner shadow's hole
|
||||
float4 color : COLOR0;
|
||||
float4 color2 : COLOR1; // gradient end
|
||||
float4 border : COLOR2; // border color
|
||||
float4 grad : GRAD; // gradient start and end points, or stripes
|
||||
float4 uv : UV; // texture rectangle, normalized, border widths, the box casting a shadow, or an inner shadow's hole
|
||||
float4 clip : CLIP; // the innermost clip rectangle
|
||||
float4 clipRadii : CLIPR;
|
||||
float4 transform0 : TRANSFORM0;
|
||||
float4 transform1 : TRANSFORM1;
|
||||
float4 transform2 : TRANSFORM2; // the projective row's g and h, and 1 where its constant is -1
|
||||
float4 params : PARAMS; // kind, dashed or grayscale, sigma or paint, opacity
|
||||
};
|
||||
|
||||
struct VSOut {
|
||||
float4 pos : SV_Position;
|
||||
float4 pt : PIXEL; // the position in pixels, and the texture coordinates
|
||||
nointerpolation float4 rect : RECT;
|
||||
nointerpolation float4 radii : RADII;
|
||||
nointerpolation float4 inner : INNER;
|
||||
nointerpolation float4 color : COLOR0;
|
||||
nointerpolation float4 color2 : COLOR1;
|
||||
nointerpolation float4 border : COLOR2;
|
||||
nointerpolation float4 grad : GRAD;
|
||||
nointerpolation float4 widths : WIDTHS;
|
||||
nointerpolation float4 clip : CLIP;
|
||||
nointerpolation float4 clipRadii : CLIPR;
|
||||
nointerpolation float4 params : PARAMS;
|
||||
nointerpolation float4 transform0 : TRANSFORM0;
|
||||
nointerpolation float4 transform1 : TRANSFORM1;
|
||||
nointerpolation float4 transform2 : TRANSFORM2;
|
||||
};
|
||||
|
||||
// frameH returns the frame point of local p, in homogeneous coordinates.
|
||||
float3 frameH(Inst i, float2 p) {
|
||||
return float3(dot(i.transform0.xyz, float3(p, 1)), dot(i.transform1.xyz, float3(p, 1)),
|
||||
dot(float3(i.transform2.xy, 1 - 2 * i.transform2.z), float3(p, 1)));
|
||||
}
|
||||
|
||||
VSOut vs(uint vid : SV_VertexID, Inst i) {
|
||||
float2 corner = float2(vid & 1, vid >> 1);
|
||||
float4 r = i.rect;
|
||||
float kind = i.params.x;
|
||||
if (kind < 0.5 || kind > 5.5) { // fills and effects
|
||||
r = float4(r.xy - 1, r.zw + 2);
|
||||
} else if (kind < 1.5) {
|
||||
float e = 3 * i.params.z + 1;
|
||||
r = float4(r.xy - e, r.zw + 2 * e);
|
||||
}
|
||||
float3 h = frameH(i, r.xy + corner * r.zw);
|
||||
if (i.transform0.w > 0.5 && h.z > 0) {
|
||||
// A pixel's reach at this corner, by the map's Jacobian there.
|
||||
float2 s = h.xy / h.z;
|
||||
float a = (i.transform0.x - s.x * i.transform2.x) / h.z, c = (i.transform0.y - s.x * i.transform2.y) / h.z;
|
||||
float b = (i.transform1.x - s.y * i.transform2.x) / h.z, d = (i.transform1.y - s.y * i.transform2.y) / h.z;
|
||||
float2 e = float2(abs(d) + abs(c), abs(b) + abs(a)) / abs(a * d - b * c);
|
||||
r = float4(r.xy - e, r.zw + 2 * e);
|
||||
}
|
||||
float2 p = r.xy + corner * r.zw;
|
||||
h = frameH(i, p);
|
||||
VSOut o;
|
||||
o.pos = float4(h.xy / viewport * float2(2, -2) + h.z * float2(-1, 1), 0, h.z);
|
||||
o.pt.xy = p;
|
||||
o.pt.zw = i.uv.xy + (p - i.rect.xy) / i.rect.zw * (i.uv.zw - i.uv.xy);
|
||||
o.rect = i.rect;
|
||||
o.radii = i.radii;
|
||||
o.inner = i.inner;
|
||||
o.color = i.color;
|
||||
o.color2 = i.color2;
|
||||
o.border = i.border;
|
||||
o.grad = i.grad;
|
||||
o.widths = i.uv;
|
||||
o.clip = i.clip;
|
||||
o.clipRadii = i.clipRadii;
|
||||
o.params = i.params;
|
||||
o.transform0 = i.transform0;
|
||||
o.transform1 = i.transform1;
|
||||
o.transform2 = i.transform2;
|
||||
return o;
|
||||
}
|
||||
|
||||
// The color and, for dual-source blending, the source's alpha of each
|
||||
// channel.
|
||||
struct PSOut {
|
||||
float4 color : SV_Target0;
|
||||
float4 alpha : SV_Target1;
|
||||
};
|
||||
|
||||
Texture2D maskTex : register(t0);
|
||||
Texture2D colorTex : register(t1);
|
||||
Texture2D imageTex : register(t2);
|
||||
Texture2D clipTex : register(t5);
|
||||
SamplerState samp : register(s0);
|
||||
|
||||
float sdRoundRect(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0 ? (q.y < 0 ? radii.x : radii.w) : (q.y < 0 ? radii.y : radii.z);
|
||||
float2 a = abs(q) - h + r;
|
||||
return length(max(a, 0)) + min(max(a.x, a.y), 0) - r;
|
||||
}
|
||||
|
||||
float coverage(float d) { return saturate(0.5 - d); }
|
||||
|
||||
// rectCoverage returns how much of the pixel at p a rounded rectangle
|
||||
// covers: by the distance to its edge near rounded corners, and exactly,
|
||||
// the area of the pixel inside it, near square ones.
|
||||
float rectCoverage(float2 p, float4 rect, float4 radii) {
|
||||
float2 q = p - rect.xy - rect.zw * 0.5;
|
||||
float r = q.x < 0 ? (q.y < 0 ? radii.x : radii.w) : (q.y < 0 ? radii.y : radii.z);
|
||||
if (r > 0) {
|
||||
return coverage(sdRoundRect(p, rect, radii));
|
||||
}
|
||||
float2 c = saturate(min(rect.xy + rect.zw, p + 0.5) - max(rect.xy, p - 0.5));
|
||||
return c.x * c.y;
|
||||
}
|
||||
|
||||
// Frame is where a fragment is in the frame, s, and, when its instance's
|
||||
// map is projective (persp), the columns of the map back, up to a factor.
|
||||
struct Frame {
|
||||
float2 s;
|
||||
float3 c0, c1, c2;
|
||||
bool persp;
|
||||
};
|
||||
Frame frameOf(VSOut v) {
|
||||
Frame f;
|
||||
f.persp = any(v.transform2.xy != 0);
|
||||
// In perspective, the pixel's center; else the frame point of the
|
||||
// local one, which the affine map moves linearly: Direct3D 10's shaders
|
||||
// pass on 16 values at most.
|
||||
f.s = f.persp ? v.pos.xy : float2(dot(v.transform0.xyz, float3(v.pt.xy, 1)), dot(v.transform1.xyz, float3(v.pt.xy, 1)));
|
||||
float3 r0 = v.transform0.xyz, r1 = v.transform1.xyz, r2 = float3(v.transform2.xy, 1 - 2 * v.transform2.z);
|
||||
f.c0 = cross(r1, r2);
|
||||
f.c1 = cross(r2, r0);
|
||||
f.c2 = cross(r0, r1);
|
||||
return f;
|
||||
}
|
||||
// localOf returns the point of the instance that shows at the frame's s.
|
||||
float2 localOf(Frame f, float2 s) {
|
||||
float3 q = f.c0 * s.x + f.c1 * s.y + f.c2;
|
||||
return q.xy / q.z;
|
||||
}
|
||||
// perspectiveCoverage is localCoverage in perspective: each sample where
|
||||
// the CPU renderer takes it.
|
||||
float perspectiveCoverage(float4 rect, float4 radii, Frame fr) {
|
||||
float2 p = localOf(fr, fr.s);
|
||||
float2 a = localOf(fr, fr.s + float2(0.5, 0.5)) - p, b = localOf(fr, fr.s + float2(0.5, -0.5)) - p;
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1;
|
||||
if (d > reach)
|
||||
return 0;
|
||||
float n = 0;
|
||||
[loop] for (int y = 0; y < 4; y++)[loop] for (int x = 0; x < 4; x++) {
|
||||
float2 q = localOf(fr, fr.s + float2((float(x) + 0.5) / 4 - 0.5, (float(y) + 0.5) / 4 - 0.5));
|
||||
n += sdRoundRect(q, rect, radii) <= 0 ? 1 : 0;
|
||||
}
|
||||
return n / 16;
|
||||
}
|
||||
float localCoverage(float2 p, float4 rect, float4 radii, float affine, Frame fr) {
|
||||
if (affine < 0.5)
|
||||
return rectCoverage(p, rect, radii);
|
||||
float2 dx = ddx(p), dy = ddy(p), a = (dx + dy) * 0.5, b = (dx - dy) * 0.5;
|
||||
if (fr.persp)
|
||||
return perspectiveCoverage(rect, radii, fr);
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1;
|
||||
if (d > reach)
|
||||
return 0;
|
||||
float n = 0;
|
||||
[loop] for (int y = 0; y < 4; y++)[loop] for (int x = 0; x < 4; x++) {
|
||||
float2 q = p + dx * ((float(x) + 0.5) / 4 - 0.5) + dy * ((float(y) + 0.5) / 4 - 0.5);
|
||||
n += sdRoundRect(q, rect, radii) <= 0 ? 1 : 0;
|
||||
}
|
||||
return n / 16;
|
||||
}
|
||||
float clipCoverage(VSOut i) {
|
||||
Frame fr = frameOf(i);
|
||||
float2 world = fr.s;
|
||||
if (i.transform1.w < 0.5)
|
||||
return rectCoverage(world, i.clip, i.clipRadii);
|
||||
if (i.transform1.w > 1.5)
|
||||
return localCoverage(i.pt.xy, i.clip, float4(0, 0, 0, 0), i.transform0.w, fr) *
|
||||
clipTex.Sample(samp, (world - i.clipRadii.xy) / i.clipRadii.zw).a;
|
||||
return clipTex.Sample(samp, (world - i.clip.xy) / i.clip.zw).a;
|
||||
}
|
||||
float4 sampleLocal(Texture2D t, float2 uv, float4 src, float affine) {
|
||||
if (affine > 0.5) {
|
||||
uint w, h;
|
||||
t.GetDimensions(w, h);
|
||||
float2 halfPixel = 0.5 / float2(w, h);
|
||||
uv = clamp(uv, src.xy + halfPixel, src.zw - halfPixel);
|
||||
}
|
||||
return t.Sample(samp, uv);
|
||||
}
|
||||
|
||||
// sampleImage samples an image held inside src, which is reversed along
|
||||
// an axis it flips, so that a part of a sheet shows none of its
|
||||
// neighbors; where pixelated is set, as pixel art draws, each texel a
|
||||
// square of its color whose edges blend with the next only across the
|
||||
// pixel they cross (Ebitengine's FilterPixelated): nearest where it shows
|
||||
// at whole multiples of its size, and texels of even widths with smooth
|
||||
// edges at any other. dtex is the fwidth of uv, taken where every
|
||||
// fragment of the quad takes it.
|
||||
float4 sampleImage(Texture2D t, float2 uv, float4 src, float pixelated, float2 dtex) {
|
||||
uint w, h;
|
||||
t.GetDimensions(w, h);
|
||||
float2 size = float2(w, h);
|
||||
float2 lo = min(src.xy, src.zw), hi = max(src.xy, src.zw);
|
||||
if (pixelated > 0.5) {
|
||||
float2 tc = uv * size - 0.5;
|
||||
float2 i = floor(tc);
|
||||
float2 f = saturate((tc - i - 0.5) / clamp(dtex * size, 1e-5, 1.0) + 0.5);
|
||||
uv = (i + f + 0.5) / size;
|
||||
}
|
||||
return t.Sample(samp, clamp(uv, lo + 0.5 / size, hi - 0.5 / size));
|
||||
}
|
||||
|
||||
// tint multiplies premultiplied c by straight color t.
|
||||
float4 tint(float4 c, float4 t) { return c * float4(t.rgb * t.a, t.a); }
|
||||
|
||||
float4 premul(float4 c) { return float4(c.rgb * c.a, c.a); }
|
||||
|
||||
float3 unpremul(float4 c) { return c.a > 0 ? c.rgb / c.a : float3(0, 0, 0); }
|
||||
|
||||
// textCoverage corrects the coverage a of a glyph of straight color c as
|
||||
// Direct2D blends text (scene.TextCoverage): it enhances the contrast,
|
||||
// the more the darker c is, and corrects for gamma with the ratios g.
|
||||
float textCoverage(float a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3 - 4 * dot(c, float3(0.30, 0.59, 0.11))) + boost;
|
||||
a = a * (k + 1) / (a * k + 1);
|
||||
float f = dot(c, float3(0.25, 0.5, 0.25));
|
||||
return saturate(a + a * (1 - a) * ((g.x * f + g.y) * a + (g.z * f + g.w)));
|
||||
}
|
||||
|
||||
// What follows is the renderer's own; effects (effect.hlsl) take what is
|
||||
// above.
|
||||
#ifndef EFFECT
|
||||
|
||||
// The chroma of an image that is a frame of video in NV12, whose luma
|
||||
// imageTex holds (gpu.ImageYUV).
|
||||
Texture2D chromaTex : register(t11);
|
||||
|
||||
// chromaScale is what scales coordinates of the luma to those of the
|
||||
// chroma, which covers twice its size in luma: a column or row more than
|
||||
// an odd size has.
|
||||
float2 chromaScale() {
|
||||
uint lw, lh, cw, ch;
|
||||
imageTex.GetDimensions(lw, lh);
|
||||
chromaTex.GetDimensions(cw, ch);
|
||||
return float2(lw, lh) / (2 * float2(cw, ch));
|
||||
}
|
||||
|
||||
// yuvToRGB converts the samples of a frame of video in YCbCr to RGB, as
|
||||
// scene.YUVMatrix.YUVToRGB does: m is the matrix, 0 to 2 for BT.601, 709
|
||||
// and 2020 in the limited range, plus 3 for the full range.
|
||||
float3 yuvToRGB(float y, float2 c, float m) {
|
||||
float full = m > 2.5 ? 1 : 0;
|
||||
float std = m - 3 * full;
|
||||
float2 k = std < 0.5 ? float2(0.299, 0.114) : std < 1.5 ? float2(0.2126, 0.0722) : float2(0.2627, 0.0593);
|
||||
c -= 128.0 / 255.0;
|
||||
if (full < 0.5) {
|
||||
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
|
||||
c *= 255.0 / 224.0;
|
||||
}
|
||||
float r = y + 2 * (1 - k.x) * c.y;
|
||||
float b = y + 2 * (1 - k.y) * c.x;
|
||||
float g = (y - k.x * r - k.y * b) / (1 - k.x - k.y);
|
||||
return saturate(float3(r, g, b));
|
||||
}
|
||||
|
||||
// subpixelCoverage does the same for each subpixel of a subpixel glyph.
|
||||
float3 subpixelCoverage(float3 a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3 - 4 * dot(c, float3(0.30, 0.59, 0.11))) + boost;
|
||||
a = a * (k + 1) / (a * k + 1);
|
||||
return saturate(a + a * (1 - a) * ((g.x * c + g.y) * a + (g.z * c + g.w)));
|
||||
}
|
||||
|
||||
float2 erf2(float2 x) {
|
||||
float2 s = sign(x), a = abs(x);
|
||||
x = 1 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
|
||||
x *= x;
|
||||
return s - s / (x * x);
|
||||
}
|
||||
|
||||
float gaussian(float x, float sigma) { return exp(-(x * x) / (2 * sigma * sigma)) / (2.50662827463 * sigma); }
|
||||
|
||||
// The blurred rounded box of Evan Wallace: exact along x, four samples
|
||||
// along y.
|
||||
float shadowX(float x, float y, float sigma, float corner, float2 h) {
|
||||
float delta = min(h.y - corner - abs(y), 0);
|
||||
float curved = h.x - corner + sqrt(max(0, corner * corner - delta * delta));
|
||||
float2 integral = 0.5 + 0.5 * erf2((x + float2(-curved, curved)) * (sqrt(0.5) / sigma));
|
||||
return integral.y - integral.x;
|
||||
}
|
||||
|
||||
float boxShadow(float2 p, float4 rect, float sigma, float corner) {
|
||||
float2 h = rect.zw * 0.5;
|
||||
p -= rect.xy + h;
|
||||
float low = p.y - h.y, high = p.y + h.y;
|
||||
float start = clamp(-3 * sigma, low, high);
|
||||
float end = clamp(3 * sigma, low, high);
|
||||
float step = (end - start) / 4;
|
||||
float y = start + step * 0.5;
|
||||
float v = 0;
|
||||
for (int k = 0; k < 4; k++) {
|
||||
v += shadowX(p.x, p.y - y, sigma, corner, h) * gaussian(y, sigma) * step;
|
||||
y += step;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
float3 toLinear(float3 c) { return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4); }
|
||||
|
||||
float3 toSRGB(float3 c) { return c <= 0.0031308 ? c * 12.92 : 1.055 * pow(max(c, 0), 1.0 / 2.4) - 0.055; }
|
||||
|
||||
float3 cbrt3(float3 v) { return sign(v) * pow(abs(v), 1.0 / 3.0); }
|
||||
|
||||
float3 oklab(float3 srgb) {
|
||||
float3 c = toLinear(srgb);
|
||||
float3 lms = cbrt3(float3(0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b,
|
||||
0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b,
|
||||
0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b));
|
||||
return float3(0.2104542553 * lms.x + 0.7936177850 * lms.y - 0.0040720468 * lms.z,
|
||||
1.9779984951 * lms.x - 2.4285922050 * lms.y + 0.4505937099 * lms.z,
|
||||
0.0259040371 * lms.x + 0.7827717662 * lms.y - 0.8086757660 * lms.z);
|
||||
}
|
||||
|
||||
float3 fromOklab(float3 lab) {
|
||||
float3 lms = float3(lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z,
|
||||
lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z,
|
||||
lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z);
|
||||
lms = lms * lms * lms;
|
||||
return toSRGB(float3(4.0767416621 * lms.x - 3.3077115913 * lms.y + 0.2309699292 * lms.z,
|
||||
-1.2684380046 * lms.x + 2.6097574011 * lms.y - 0.3413193965 * lms.z,
|
||||
-0.0041960863 * lms.x - 0.7034186147 * lms.y + 1.7076147010 * lms.z));
|
||||
}
|
||||
|
||||
// The stops of the frame's gradients (gpu.Builder.Stops): two texels each,
|
||||
// the color, straight sRGB, then its place and its color in Oklab.
|
||||
Texture2D stopsTex : register(t10);
|
||||
|
||||
// stop returns texel k of the stops.
|
||||
float4 stop(int k) {
|
||||
return stopsTex.Load(int3(k % 1024, k / 1024, 0));
|
||||
}
|
||||
|
||||
// stopsAt returns the color at t of the gradient whose stops stopsTex
|
||||
// holds from first, n of them (gpu.Builder.Stops): the first stop's
|
||||
// before it, the last's after it, and between two the colors of both
|
||||
// mixed, premultiplied, in sRGB, or in Oklab, as internal/raster's stopsAt.
|
||||
float4 stopsAt(float4 c2, float t, bool lab) {
|
||||
int first = int(c2.x);
|
||||
int n = int(c2.y);
|
||||
if (n <= 0) {
|
||||
return float4(0, 0, 0, 0);
|
||||
}
|
||||
float4 a = stop(2 * first);
|
||||
float4 ap = stop(2 * first + 1);
|
||||
if (t <= ap.x) {
|
||||
return premul(a);
|
||||
}
|
||||
float4 last = stop(2 * (first + n - 1));
|
||||
float4 lastp = stop(2 * (first + n - 1) + 1);
|
||||
if (t >= lastp.x) {
|
||||
return premul(last);
|
||||
}
|
||||
float4 b = last;
|
||||
float4 bp = lastp;
|
||||
for (int i = 1; i < n - 1; i++) {
|
||||
float4 c = stop(2 * (first + i));
|
||||
float4 cp = stop(2 * (first + i) + 1);
|
||||
if (t < cp.x) {
|
||||
b = c;
|
||||
bp = cp;
|
||||
break;
|
||||
}
|
||||
a = c;
|
||||
ap = cp;
|
||||
}
|
||||
float f = saturate((t - ap.x) / max(bp.x - ap.x, 1e-6));
|
||||
float alpha = lerp(a.a, b.a, f);
|
||||
if (!lab) {
|
||||
return float4(lerp(a.rgb * a.a, b.rgb * b.a, f), alpha);
|
||||
}
|
||||
if (alpha <= 0) {
|
||||
return float4(0, 0, 0, 0);
|
||||
}
|
||||
return float4(saturate(fromOklab(lerp(ap.yzw * a.a, bp.yzw * b.a, f) / alpha)) * alpha, alpha);
|
||||
}
|
||||
|
||||
// paint returns the premultiplied color at p of plain color, a gradient
|
||||
// mixed in sRGB (1) or Oklab (2), stripes (3), or a gradient of stops,
|
||||
// linear (4, 5), conic (6, 7) or radial (8, 9), mixed in sRGB or in
|
||||
// Oklab, as scene.Paint says.
|
||||
float4 paint(float2 p, float mode, float4 rect, float4 c1, float4 c2, float4 g) {
|
||||
if (mode < 0.5) {
|
||||
return premul(c1);
|
||||
}
|
||||
if (mode > 3.5) {
|
||||
float t;
|
||||
if (mode < 5.5) {
|
||||
float2 d = g.zw - g.xy;
|
||||
t = dot(p - g.xy, d) / max(dot(d, d), 0.0001);
|
||||
} else if (mode < 7.5) {
|
||||
float2 d = p - g.xy;
|
||||
t = (atan2(d.x, -d.y) - g.z) * 0.15915494309189535;
|
||||
t -= floor(t);
|
||||
} else {
|
||||
t = length(p - g.xy) / max(g.z, 0.0001);
|
||||
}
|
||||
return stopsAt(c2, t, mode > 4.5 && mode < 5.5 || mode > 6.5 && mode < 7.5 || mode > 8.5);
|
||||
}
|
||||
if (mode < 2.5) {
|
||||
float2 d = g.zw - g.xy;
|
||||
float t = saturate(dot(p - g.xy, d) / max(dot(d, d), 0.0001));
|
||||
float a = lerp(c1.a, c2.a, t);
|
||||
if (mode < 1.5) {
|
||||
return float4(lerp(c1.rgb * c1.a, c2.rgb * c2.a, t), a);
|
||||
}
|
||||
float3 lab = lerp(oklab(c1.rgb) * c1.a, oklab(c2.rgb) * c2.a, t);
|
||||
return a > 0 ? float4(saturate(fromOklab(lab / a)) * a, a) : float4(0, 0, 0, 0);
|
||||
}
|
||||
float s = dot(p - rect.xy, g.xy);
|
||||
float phase = s - g.w * floor(s / g.w);
|
||||
float cov = coverage(min(max(-phase, phase - g.z), g.w - phase));
|
||||
return premul(c1) * cov + premul(c2) * (1 - cov);
|
||||
}
|
||||
|
||||
// dash returns how much of a dashed border shows at p: each side, which
|
||||
// the pixel belongs to when it is nearest that side's edge in widths of
|
||||
// its border, has an odd number of dashes and gaps of equal length, about
|
||||
// three widths, starting and ending with a dash.
|
||||
float dash(float2 p, float4 rect, float4 w) {
|
||||
float2 q = p - rect.xy;
|
||||
float dt = w.x > 0 ? q.y / w.x : 1e9;
|
||||
float dr = w.y > 0 ? (rect.z - q.x) / w.y : 1e9;
|
||||
float db = w.z > 0 ? (rect.w - q.y) / w.z : 1e9;
|
||||
float dl = w.w > 0 ? q.x / w.w : 1e9;
|
||||
float s, len, bw;
|
||||
if (dt <= dr && dt <= db && dt <= dl) {
|
||||
s = q.x;
|
||||
len = rect.z;
|
||||
bw = w.x;
|
||||
} else if (dr <= db && dr <= dl) {
|
||||
s = q.y;
|
||||
len = rect.w;
|
||||
bw = w.y;
|
||||
} else if (db <= dl) {
|
||||
s = rect.z - q.x;
|
||||
len = rect.z;
|
||||
bw = w.z;
|
||||
} else {
|
||||
s = rect.w - q.y;
|
||||
len = rect.w;
|
||||
bw = w.w;
|
||||
}
|
||||
// n - 1 is how many periods of a dash and a gap, six widths, fit in
|
||||
// len: GPUs divide less exactly than CPUs, and may count one too few
|
||||
// or too many where len is a whole number of periods, as sides often
|
||||
// are, so the count is checked by multiplying back.
|
||||
float n = max(1, floor((len / (3 * bw) + 1) * 0.5 + 0.5));
|
||||
float period = 6 * bw;
|
||||
n += n * period <= len ? 1 : 0;
|
||||
n -= (n - 1) * period > len ? 1 : 0;
|
||||
float seg = len / (2 * n - 1);
|
||||
float k = floor(s / seg);
|
||||
float f = s - k * seg;
|
||||
float edge = min(f, seg - f);
|
||||
return coverage(k - 2 * floor(k * 0.5) < 0.5 ? -edge : edge);
|
||||
}
|
||||
|
||||
PSOut ps(VSOut i) {
|
||||
Frame fr = frameOf(i);
|
||||
float2 dtex = fwidth(i.pt.zw);
|
||||
float kind = i.params.x;
|
||||
float4 res;
|
||||
float glyphCov = i.transform0.w > 0.5 ? localCoverage(i.pt.xy, i.rect, float4(0, 0, 0, 0), 1, fr) : 1;
|
||||
if (kind < 0.5) {
|
||||
float outer = localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr);
|
||||
// params.y: 1 dashes the border, 2 paints it with the gradient (the
|
||||
// inside with plain color), 3 both.
|
||||
bool borderPaint = i.params.y > 1.5;
|
||||
float4 pc = paint(i.pt.xy, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
res = (borderPaint ? premul(i.color) : pc) * outer;
|
||||
float4 bw = i.widths; // top, right, bottom, left
|
||||
if (any(bw > 0)) {
|
||||
float4 ir = float4(i.rect.xy + bw.wx, i.rect.zw - bw.yz - bw.wx);
|
||||
float innerCov = (ir.z > 0 && ir.w > 0) ? localCoverage(i.pt.xy, ir, i.inner, i.transform0.w, fr) : 0;
|
||||
float bc = saturate(outer - innerCov);
|
||||
float dashed = i.params.y - (borderPaint ? 2 : 0);
|
||||
if (dashed > 0.5) {
|
||||
bc *= dash(i.pt.xy, i.rect, bw);
|
||||
}
|
||||
float4 b = (borderPaint ? pc * float4(i.border.rgb * i.border.a, i.border.a) : premul(i.border)) * bc;
|
||||
res = b + res * (1 - b.a);
|
||||
}
|
||||
} else if (kind < 1.5 && i.params.y > 0.5) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float sigma = i.params.z;
|
||||
float hole = 0;
|
||||
if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
float corner = max(max(i.inner.x, i.inner.y), max(i.inner.z, i.inner.w));
|
||||
hole = sigma > 0 ? boxShadow(i.pt.xy, i.widths, sigma, corner)
|
||||
: localCoverage(i.pt.xy, i.widths, i.inner, i.transform0.w, fr);
|
||||
}
|
||||
res = premul(i.color) * (localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr) * (1 - hole));
|
||||
} else if (kind < 1.5) {
|
||||
float sigma = i.params.z;
|
||||
float corner = max(max(i.radii.x, i.radii.y), max(i.radii.z, i.radii.w));
|
||||
float s = sigma > 0 ? boxShadow(i.pt.xy, i.rect, sigma, corner)
|
||||
: localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr);
|
||||
if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
s *= 1 - localCoverage(i.pt.xy, i.widths, i.inner, i.transform0.w, fr); // outside the box casting it
|
||||
}
|
||||
res = premul(i.color) * s;
|
||||
} else if (kind < 2.5) {
|
||||
float4 c = paint(i.pt.xy, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
res = c *
|
||||
textCoverage(sampleLocal(maskTex, i.pt.zw, i.widths, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
} else if (kind < 3.5) {
|
||||
res = sampleLocal(colorTex, i.pt.zw, i.widths, i.transform0.w) * i.color.a * glyphCov;
|
||||
} else if (kind < 4.5) {
|
||||
if (i.params.y > 1.5) {
|
||||
// A frame of video: its luma and its chroma, converted.
|
||||
float code = i.params.y - 2;
|
||||
float gray = code > 7.5 ? 1 : 0;
|
||||
float2 cs = chromaScale();
|
||||
res = float4(yuvToRGB(sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex).r,
|
||||
sampleImage(chromaTex, i.pt.zw * cs, i.widths * cs.xyxy, i.params.z, dtex * cs).rg,
|
||||
code - 8 * gray),
|
||||
1);
|
||||
if (gray > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex);
|
||||
if (i.params.y > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
}
|
||||
res = tint(res, i.color) * localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr);
|
||||
} else {
|
||||
float4 c = paint(i.pt.xy, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
float3 straight = unpremul(c);
|
||||
if (i.transform0.w > 0.5) {
|
||||
float3 rgb = sampleLocal(colorTex, i.pt.zw, i.widths, 1).rgb;
|
||||
res = c * textCoverage((rgb.r + rgb.g + rgb.b) / 3, straight, i.inner.x, i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
PSOut gray;
|
||||
gray.color = res * clipCoverage(i) * i.params.w;
|
||||
gray.alpha = gray.color.aaaa;
|
||||
return gray;
|
||||
}
|
||||
float3 a = subpixelCoverage(sampleLocal(colorTex, i.pt.zw, i.widths, i.transform0.w).rgb, straight,
|
||||
i.inner.x, i.inner.y, i.radii);
|
||||
float3 w = a * c.a * clipCoverage(i) * i.params.w;
|
||||
float wa = (w.r + w.g + w.b) / 3;
|
||||
PSOut so;
|
||||
so.color = float4(straight * w, wa);
|
||||
so.alpha = float4(w, wa);
|
||||
return so;
|
||||
}
|
||||
float clip = clipCoverage(i);
|
||||
PSOut o;
|
||||
o.color = res * (clip * i.params.w);
|
||||
o.alpha = o.color.aaaa;
|
||||
return o;
|
||||
}
|
||||
|
||||
// The passes computing the backdrop of an effect draw a quad over their
|
||||
// target, scissored to the texels they compute.
|
||||
cbuffer PassConstants : register(b1) {
|
||||
int2 passOrigin; // down: the first pixel of the area read, in the frame
|
||||
int2 passLimit; // the last texel that may be read: in the frame for down
|
||||
int2 passShift; // down: subtracted from frame pixels to read the source
|
||||
int2 passDir; // blur: along rows (1, 0) or columns (0, 1)
|
||||
int passDown; // down: the size of the squares averaged
|
||||
int passRadius; // blur: how far it reaches each way
|
||||
float passSigma; // blur: its standard deviation, 0 for none
|
||||
int passMode; // 1: transparent beyond the area or the texels (gpu.PassClear)
|
||||
};
|
||||
|
||||
Texture2D passSrc : register(t4);
|
||||
|
||||
float4 passvs(uint vid : SV_VertexID) : SV_Position {
|
||||
float2 corner = float2(vid & 1, vid >> 1);
|
||||
return float4(corner * 2 - 1, 0, 1);
|
||||
}
|
||||
|
||||
// down averages the square of the area that texel stands for, repeating
|
||||
// the area's last pixels past its far edges, or, for an image blurred
|
||||
// (mode 1), reading them as transparent.
|
||||
float4 downps(float4 pos : SV_Position) : SV_Target {
|
||||
int2 o = passOrigin + int2(pos.xy) * passDown;
|
||||
float4 c = float4(0, 0, 0, 0);
|
||||
for (int y = 0; y < passDown; y++) {
|
||||
for (int x = 0; x < passDown; x++) {
|
||||
int2 at = o + int2(x, y);
|
||||
if ((passMode & 1) != 0 && (at.x > passLimit.x || at.y > passLimit.y)) {
|
||||
continue;
|
||||
}
|
||||
c += passSrc.Load(int3(min(at, passLimit) - passShift, 0));
|
||||
}
|
||||
}
|
||||
return c * (1.0 / float(passDown * passDown));
|
||||
}
|
||||
|
||||
// blur blurs along a row or a column, clamping at its ends, or, for an
|
||||
// image blurred (mode 1), transparent beyond them.
|
||||
float4 blurps(float4 pos : SV_Position) : SV_Target {
|
||||
int2 at = int2(pos.xy);
|
||||
float4 c = float4(0, 0, 0, 0);
|
||||
float sum = 0;
|
||||
for (int o = -passRadius; o <= passRadius; o++) {
|
||||
float x = float(o);
|
||||
float w = passSigma > 0 ? exp(-(x * x) / (2 * passSigma * passSigma)) : 1;
|
||||
int2 q = at + passDir * o;
|
||||
sum += w;
|
||||
if ((passMode & 1) != 0 && (any(q < int2(0, 0)) || any(q > passLimit))) {
|
||||
continue;
|
||||
}
|
||||
c += passSrc.Load(int3(clamp(q, int2(0, 0), passLimit), 0)) * w;
|
||||
}
|
||||
return c / sum;
|
||||
}
|
||||
|
||||
#endif
|
||||
+18851
File diff suppressed because it is too large.
Load diff
+281
@@ -0,0 +1,281 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
)
|
||||
|
||||
// The renderers of a process share one Direct3D 11 device and its
|
||||
// immediate context (#1517): a device costs the driver tens of megabytes,
|
||||
// which a device for each window would cost each window. So do what never
|
||||
// changes once made, the shaders, the input layout and the states, while
|
||||
// each renderer keeps its swap chain and what its frames change: its
|
||||
// buffers, textures and queries. The device goes with the last renderer
|
||||
// holding it.
|
||||
//
|
||||
// Renderers draw on the main thread, one frame at a time, so the context
|
||||
// they share needs no lock of theirs, and each frame binds all the state it
|
||||
// draws with. The device is multithread protected all the same
|
||||
// (ID3D10Multithread): Direct3D then serializes each call to the context
|
||||
// with DXGI's calls on the device's swap chains, so that a swap chain may
|
||||
// present or resize its buffers on another thread while other windows draw.
|
||||
//
|
||||
// When the GPU device is removed (a driver update, a GPU reset), a
|
||||
// renderer's next present fails and the window makes another renderer
|
||||
// (ui's windowHost.render): the first one made finds the device removed
|
||||
// and makes a new one, which the renderers made after it share. The others
|
||||
// find the device they hold replaced as they next draw (Render), and fail
|
||||
// so that their windows make them again on the new one, as they would on
|
||||
// a device of their own that failed. A device made with WARP, for want of
|
||||
// a GPU, is replaced the same way as a renderer is made once the GPU can
|
||||
// make one again, as ui does from time to time while drawing in software.
|
||||
|
||||
// sharedDevice is the device renderers share, with what they draw with
|
||||
// that never changes.
|
||||
type sharedDevice struct {
|
||||
device, ctx, ctx1, factory uintptr
|
||||
warp bool
|
||||
// refs counts the renderers holding the device.
|
||||
refs int
|
||||
|
||||
vs, ps, layout uintptr
|
||||
blend, holeBlend, overBlend, overHoleBlend uintptr
|
||||
raster, samp uintptr
|
||||
passVS, downPS, blurPS uintptr
|
||||
classes [1 << gpu.NumClasses]*classPipe
|
||||
compileClasses bool
|
||||
}
|
||||
|
||||
// devices holds the device new renderers share, nil before the first or
|
||||
// after the last renderer released it, or when it was found removed.
|
||||
var devices struct {
|
||||
sync.Mutex
|
||||
current *sharedDevice
|
||||
}
|
||||
|
||||
// errDeviceReplaced is Render's error for a renderer whose device another
|
||||
// one replaced, removed or drawing with WARP.
|
||||
var errDeviceReplaced = errors.New("d3d11: the device shared by the windows was made again")
|
||||
|
||||
// deviceRemoved reports whether the GPU device of d was removed; tests
|
||||
// replace it.
|
||||
var deviceRemoved = func(d *sharedDevice) bool {
|
||||
const devGetDeviceRemovedReason = 39
|
||||
return call(d.device, devGetDeviceRemovedReason) != 0
|
||||
}
|
||||
|
||||
// newDeviceOnGPU makes a device on the GPU only, for one drawing with WARP
|
||||
// to be replaced; tests replace it.
|
||||
var newDeviceOnGPU = device.NewOnGPU
|
||||
|
||||
// acquireDevice returns the device new renderers share, which the caller
|
||||
// releases with releaseDevice: the current one, or a new one where there
|
||||
// is none, it was removed, or it draws with WARP and the GPU can make one
|
||||
// now.
|
||||
func acquireDevice() (*sharedDevice, error) {
|
||||
devices.Lock()
|
||||
defer devices.Unlock()
|
||||
d := devices.current
|
||||
if d != nil && deviceRemoved(d) {
|
||||
devices.current, d = nil, nil
|
||||
}
|
||||
if d != nil && d.warp {
|
||||
if dev, ctx, err := newDeviceOnGPU(); err == nil {
|
||||
if n, err := newSharedDevice(dev, ctx, false); err == nil {
|
||||
devices.current, d = n, n
|
||||
}
|
||||
}
|
||||
}
|
||||
if d == nil {
|
||||
dev, ctx, warp, err := device.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d, err = newSharedDevice(dev, ctx, warp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
devices.current = d
|
||||
}
|
||||
d.refs++
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// releaseDevice lets go of d, freeing it with the last renderer holding it.
|
||||
func releaseDevice(d *sharedDevice) {
|
||||
devices.Lock()
|
||||
defer devices.Unlock()
|
||||
if d.refs--; d.refs > 0 {
|
||||
return
|
||||
}
|
||||
if devices.current == d {
|
||||
devices.current = nil
|
||||
}
|
||||
d.free()
|
||||
}
|
||||
|
||||
// replaced reports whether renderers made now share another device than d.
|
||||
func (d *sharedDevice) replaced() bool {
|
||||
devices.Lock()
|
||||
defer devices.Unlock()
|
||||
return devices.current != d
|
||||
}
|
||||
|
||||
// newSharedDevice makes what renderers draw with on the device dev, whose
|
||||
// immediate context is ctx; it releases both when it fails.
|
||||
func newSharedDevice(dev, ctx uintptr, warp bool) (*sharedDevice, error) {
|
||||
d := &sharedDevice{device: dev, ctx: ctx, warp: warp}
|
||||
if err := d.init(); err != nil {
|
||||
d.free()
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
var iidID3D10Multithread = guid{0x9b7e4e00, 0x342c, 0x4106, [8]byte{0xa1, 0x9f, 0x4f, 0x27, 0x04, 0xf6, 0x89, 0xf0}}
|
||||
|
||||
func (d *sharedDevice) init() error {
|
||||
const setMultithreadProtected = 5 // ID3D10Multithread
|
||||
var mt uintptr
|
||||
if !failed(call(d.device, 0, uintptr(unsafe.Pointer(&iidID3D10Multithread)), uintptr(unsafe.Pointer(&mt)))) {
|
||||
call(mt, setMultithreadProtected, 1)
|
||||
free(&mt)
|
||||
}
|
||||
// The factory that made the device's adapter makes the swap chains.
|
||||
var dxgiDev, adapter uintptr
|
||||
if failed(call(d.device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice)), uintptr(unsafe.Pointer(&dxgiDev)))) {
|
||||
return errors.New("d3d11: no DXGI device")
|
||||
}
|
||||
defer free(&dxgiDev)
|
||||
// One frame queued ahead of the screen, not three: a frame shows the
|
||||
// input of when it was drawn while frames follow each other, as when
|
||||
// scrolling or animating.
|
||||
var dxgiDev1 uintptr
|
||||
if !failed(call(d.device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice1)), uintptr(unsafe.Pointer(&dxgiDev1)))) {
|
||||
call(dxgiDev1, dxgiDevSetMaxLatency, 1)
|
||||
free(&dxgiDev1)
|
||||
}
|
||||
if noPartial || failed(call(d.ctx, 0, uintptr(unsafe.Pointer(&iidID3D11DeviceContext1)), uintptr(unsafe.Pointer(&d.ctx1)))) {
|
||||
d.ctx1 = 0
|
||||
}
|
||||
if failed(call(dxgiDev, dxgiDevGetAdapter, uintptr(unsafe.Pointer(&adapter)))) {
|
||||
return errors.New("d3d11: no adapter")
|
||||
}
|
||||
defer free(&adapter)
|
||||
if failed(call(adapter, dxgiGetParent, uintptr(unsafe.Pointer(&iidIDXGIFactory2)), uintptr(unsafe.Pointer(&d.factory)))) {
|
||||
return errors.New("d3d11: DXGI 1.2 is required")
|
||||
}
|
||||
|
||||
// The shaders compiled ahead of time, or from shader.hlsl when they are
|
||||
// older or a test asks (compileShaders), as the device is made.
|
||||
code, err := shaderCode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.compileClasses = sourceSum() != shaderSum || compileShaders
|
||||
vsCode := code.vs
|
||||
for _, s := range []struct {
|
||||
code []byte
|
||||
out *uintptr
|
||||
vtbl int
|
||||
name string
|
||||
}{{code.vs, &d.vs, devCreateVertexShader, "vertex"}, {code.ps, &d.ps, devCreatePixelShader, "pixel"},
|
||||
{code.passVS, &d.passVS, devCreateVertexShader, "pass vertex"}, {code.down, &d.downPS, devCreatePixelShader, "down"},
|
||||
{code.blur, &d.blurPS, devCreatePixelShader, "blur"}} {
|
||||
if len(s.code) == 0 || failed(call(d.device, s.vtbl, uintptr(unsafe.Pointer(&s.code[0])), uintptr(len(s.code)), 0, uintptr(unsafe.Pointer(s.out)))) {
|
||||
return fmt.Errorf("d3d11: cannot create the %s shader", s.name)
|
||||
}
|
||||
}
|
||||
names := []string{"RECT", "RADII", "INNER", "COLOR", "COLOR", "COLOR", "GRAD", "UV", "CLIP", "CLIPR", "PARAMS", "TRANSFORM", "TRANSFORM", "TRANSFORM"}
|
||||
indices := []uint32{0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 1, 2}
|
||||
elems := make([]inputElement, len(names))
|
||||
cstr := make([][]byte, len(names))
|
||||
for i, n := range names {
|
||||
cstr[i] = append([]byte(n), 0)
|
||||
elems[i] = inputElement{SemanticName: &cstr[i][0], SemanticIndex: indices[i], Format: formatR32G32B32A32Float,
|
||||
AlignedByteOffset: uint32(16 * i), InputSlotClass: 1, InstanceDataStepRate: 1}
|
||||
}
|
||||
if failed(call(d.device, devCreateInputLayout, uintptr(unsafe.Pointer(&elems[0])), uintptr(len(elems)),
|
||||
uintptr(unsafe.Pointer(&vsCode[0])), uintptr(len(vsCode)), uintptr(unsafe.Pointer(&d.layout)))) {
|
||||
return errors.New("d3d11: cannot create the input layout")
|
||||
}
|
||||
|
||||
// Dual-source blending: the destination times one minus the shader's
|
||||
// second color, the source's alpha of each channel (D3D11_BLEND_ONE,
|
||||
// D3D11_BLEND_INV_SRC1_COLOR and D3D11_BLEND_INV_SRC1_ALPHA).
|
||||
bd := blendDesc{}
|
||||
bd.RenderTarget[0] = rtBlend{BlendEnable: 1, SrcBlend: 2, DestBlend: 17, BlendOp: 1, SrcBlendAlpha: 2, DestBlendAlpha: 19, BlendOpAlpha: 1, WriteMask: 0xf}
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.blend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state")
|
||||
}
|
||||
// Holes take none of the source (D3D11_BLEND_ZERO).
|
||||
bd.RenderTarget[0].SrcBlend, bd.RenderTarget[0].SrcBlendAlpha = 1, 1
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.holeBlend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state of holes")
|
||||
}
|
||||
// One color: its alpha is the source's (D3D11_BLEND_INV_SRC_ALPHA).
|
||||
bd.RenderTarget[0].SrcBlend, bd.RenderTarget[0].DestBlend, bd.RenderTarget[0].SrcBlendAlpha, bd.RenderTarget[0].DestBlendAlpha = 2, 6, 2, 6
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.overBlend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state of one color")
|
||||
}
|
||||
bd.RenderTarget[0].SrcBlend, bd.RenderTarget[0].SrcBlendAlpha = 1, 1
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.overHoleBlend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state of holes of one color")
|
||||
}
|
||||
rd := rasterizerDesc{FillMode: 3, CullMode: 1, DepthClip: 1, Scissor: 1}
|
||||
if failed(call(d.device, devCreateRasterizerState, uintptr(unsafe.Pointer(&rd)), uintptr(unsafe.Pointer(&d.raster)))) {
|
||||
return errors.New("d3d11: cannot create the rasterizer state")
|
||||
}
|
||||
sd := samplerDesc{Filter: 0x15, AddressU: 3, AddressV: 3, AddressW: 3, ComparisonFunc: 1, MaxLOD: math.MaxFloat32}
|
||||
if failed(call(d.device, devCreateSamplerState, uintptr(unsafe.Pointer(&sd)), uintptr(unsafe.Pointer(&d.samp)))) {
|
||||
return errors.New("d3d11: cannot create the sampler")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *sharedDevice) free() {
|
||||
if d.ctx != 0 {
|
||||
call(d.ctx, ctxClearState)
|
||||
call(d.ctx, ctxFlush)
|
||||
}
|
||||
for _, s := range classShaders {
|
||||
if p := d.classes[s.classes]; p != nil {
|
||||
free(&p.vs)
|
||||
free(&p.ps)
|
||||
}
|
||||
}
|
||||
d.classes = [len(d.classes)]*classPipe{}
|
||||
for _, p := range []*uintptr{&d.samp, &d.raster, &d.overHoleBlend, &d.overBlend, &d.holeBlend, &d.blend, &d.layout,
|
||||
&d.blurPS, &d.downPS, &d.passVS, &d.ps, &d.vs, &d.factory, &d.ctx1, &d.ctx, &d.device} {
|
||||
free(p)
|
||||
}
|
||||
}
|
||||
|
||||
// useDevice has r draw on d, with what d holds.
|
||||
func (r *Renderer) useDevice(d *sharedDevice) {
|
||||
r.dev = d
|
||||
r.device, r.ctx, r.ctx1, r.factory, r.warp = d.device, d.ctx, d.ctx1, d.factory, d.warp
|
||||
r.vs, r.ps, r.layout = d.vs, d.ps, d.layout
|
||||
r.blend, r.holeBlend, r.overBlend, r.overHoleBlend = d.blend, d.holeBlend, d.overBlend, d.overHoleBlend
|
||||
r.raster, r.samp = d.raster, d.samp
|
||||
r.passVS, r.downPS, r.blurPS = d.passVS, d.downPS, d.blurPS
|
||||
r.classes, r.compileClasses = &d.classes, d.compileClasses
|
||||
}
|
||||
|
||||
// dropDevice has r let go of its device, which it no longer draws on.
|
||||
func (r *Renderer) dropDevice() {
|
||||
if r.dev == nil {
|
||||
return
|
||||
}
|
||||
d := r.dev
|
||||
r.useDevice(&sharedDevice{})
|
||||
r.dev, r.classes = nil, nil
|
||||
releaseDevice(d)
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// newRendererFor makes a renderer drawing s into a window of its own.
|
||||
func newRendererFor(t *testing.T, s *scene.Scene) *Renderer {
|
||||
t.Helper()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// drawAndCompare draws s whole with r, requires the CPU renderer's pixels,
|
||||
// and presents it.
|
||||
func drawAndCompare(t *testing.T, name string, r *Renderer, s *scene.Scene) {
|
||||
t.Helper()
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, name, pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenderersShareTheDevice checks that the renderers of two windows draw
|
||||
// on one device and its context, with the same shaders and states, each
|
||||
// into its own swap chain, their frames taking turns; that one released
|
||||
// leaves the other drawing; and that the device goes with the last.
|
||||
func TestRenderersShareTheDevice(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s1, s2 := gputest.Scene(), gputest.CornerClipScene()
|
||||
r1 := newRendererFor(t, s1)
|
||||
r2 := newRendererFor(t, s2)
|
||||
defer r2.Release()
|
||||
if r1.dev != r2.dev || r1.device != r2.device || r1.ctx != r2.ctx {
|
||||
r1.Release()
|
||||
t.Fatal("the renderers of two windows draw on devices of their own")
|
||||
}
|
||||
d := r1.dev
|
||||
if d.refs != 2 {
|
||||
t.Errorf("the device counts %d renderers, want 2", d.refs)
|
||||
}
|
||||
if r1.vs != r2.vs || r1.ps != r2.ps || r1.layout != r2.layout || r1.blend != r2.blend || r1.samp != r2.samp || r1.classes != r2.classes {
|
||||
t.Error("the renderers do not share the shaders and states of their device")
|
||||
}
|
||||
if r1.cbuf == r2.cbuf || r1.passCB == r2.passCB {
|
||||
t.Error("the renderers share the buffers their frames change")
|
||||
}
|
||||
for frame := range 2 {
|
||||
drawAndCompare(t, "d3d11 shared, first window", r1, s1)
|
||||
drawAndCompare(t, "d3d11 shared, second window", r2, s2)
|
||||
if frame == 0 {
|
||||
// The swap chains are made with the first frame.
|
||||
if r1.swapChain == 0 || r2.swapChain == 0 {
|
||||
t.Fatal("no swap chain")
|
||||
}
|
||||
if r1.swapChain == r2.swapChain {
|
||||
t.Error("the renderers share a swap chain")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r1.Release()
|
||||
if d.refs != 1 || d.device == 0 || r2.device != d.device {
|
||||
t.Fatalf("releasing a renderer freed the device the other draws on (%d renderers)", d.refs)
|
||||
}
|
||||
for range 2 {
|
||||
drawAndCompare(t, "d3d11 shared, after the other window closed", r2, s2)
|
||||
}
|
||||
if r2.dev.replaced() {
|
||||
t.Error("the device of the remaining renderer counts as replaced")
|
||||
}
|
||||
|
||||
r2.Release()
|
||||
if d.refs != 0 || d.device != 0 {
|
||||
t.Errorf("the device outlives its last renderer (%d renderers)", d.refs)
|
||||
}
|
||||
devices.Lock()
|
||||
current := devices.current
|
||||
devices.Unlock()
|
||||
if current != nil {
|
||||
t.Error("new renderers would share a device no renderer holds")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemovedDeviceIsMadeAgain checks that a renderer made after the device
|
||||
// was removed, as one a window makes after a failed frame, makes a new
|
||||
// device, which the renderers made after it share; that the renderers
|
||||
// holding the old one fail their next frame, so that their windows make
|
||||
// them again, on the new one; and that the old device goes with the last of
|
||||
// them.
|
||||
func TestRemovedDeviceIsMadeAgain(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s1, s2 := gputest.Scene(), gputest.CornerClipScene()
|
||||
r1 := newRendererFor(t, s1)
|
||||
r2 := newRendererFor(t, s2)
|
||||
old := r1.dev
|
||||
defer func(f func(*sharedDevice) bool) { deviceRemoved = f }(deviceRemoved)
|
||||
deviceRemoved = func(d *sharedDevice) bool { return d == old }
|
||||
|
||||
// The first window to fail makes its renderer again.
|
||||
if err := r1.Render(s1); err != nil {
|
||||
t.Fatalf("a frame failed before the device was replaced: %v", err)
|
||||
}
|
||||
r1.Release()
|
||||
r1 = newRendererFor(t, s1)
|
||||
defer r1.Release()
|
||||
if r1.dev == old {
|
||||
t.Fatal("a renderer made after the device was removed draws on it")
|
||||
}
|
||||
if old.refs != 1 || old.device == 0 {
|
||||
t.Fatalf("the removed device has %d renderers", old.refs)
|
||||
}
|
||||
drawAndCompare(t, "d3d11 on the device made again", r1, s1)
|
||||
|
||||
// The other window's next frame fails, and its renderer made again
|
||||
// shares the new device.
|
||||
if err := r2.Render(s2); !errors.Is(err, errDeviceReplaced) {
|
||||
t.Fatalf("a frame on the removed device: %v, want %v", err, errDeviceReplaced)
|
||||
}
|
||||
r2.Release()
|
||||
if old.refs != 0 || old.device != 0 {
|
||||
t.Errorf("the removed device outlives its last renderer (%d renderers)", old.refs)
|
||||
}
|
||||
r2 = newRendererFor(t, s2)
|
||||
defer r2.Release()
|
||||
if r2.dev != r1.dev {
|
||||
t.Fatal("the renderers made again draw on devices of their own")
|
||||
}
|
||||
drawAndCompare(t, "d3d11 made again, first window", r1, s1)
|
||||
drawAndCompare(t, "d3d11 made again, second window", r2, s2)
|
||||
if r1.dev.refs != 2 {
|
||||
t.Errorf("the new device counts %d renderers, want 2", r1.dev.refs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceOnWARPGivesWayToTheGPU checks that renderers share a device
|
||||
// made with WARP while the GPU can make none, and that a renderer made once
|
||||
// it can makes a device on it, which the renderers on WARP then give way
|
||||
// to, as a window drawing in software tries for the GPU from time to time.
|
||||
func TestDeviceOnWARPGivesWayToTheGPU(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(f func() (uintptr, uintptr, error)) { newDeviceOnGPU = f }(newDeviceOnGPU)
|
||||
s := gputest.Scene()
|
||||
r1 := newRendererFor(t, s)
|
||||
defer func() { r1.Release() }()
|
||||
if r1.dev.warp {
|
||||
t.Skip("no GPU: the device is WARP's")
|
||||
}
|
||||
// It stands for a device made with WARP.
|
||||
r1.dev.warp = true
|
||||
|
||||
newDeviceOnGPU = func() (uintptr, uintptr, error) { return 0, 0, errors.New("no GPU") }
|
||||
r2 := newRendererFor(t, s)
|
||||
if r2.dev != r1.dev {
|
||||
r2.Release()
|
||||
t.Fatal("a renderer made while the GPU can make no device does not share the one on WARP")
|
||||
}
|
||||
r2.Release()
|
||||
|
||||
newDeviceOnGPU = device.NewOnGPU
|
||||
r2 = newRendererFor(t, s)
|
||||
defer r2.Release()
|
||||
if r2.dev == r1.dev || r2.dev.warp {
|
||||
t.Fatal("a renderer made once the GPU can make a device draws with WARP")
|
||||
}
|
||||
drawAndCompare(t, "d3d11 back on the GPU", r2, s)
|
||||
if err := r1.Render(s); !errors.Is(err, errDeviceReplaced) {
|
||||
t.Fatalf("a frame on WARP once the GPU is back: %v, want %v", err, errDeviceReplaced)
|
||||
}
|
||||
r1.Release()
|
||||
r1 = newRendererFor(t, s)
|
||||
if r1.dev != r2.dev {
|
||||
t.Fatal("a renderer made again after drawing with WARP does not share the device on the GPU")
|
||||
}
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Uncapped (MYGO_UNCAPPED, package pacing), a frame presents as soon as it
|
||||
// is drawn, and the next draws at once: the swap chain is made without the
|
||||
// frame latency object, so that no frame waits for the screen to have room
|
||||
// (latency.go), and every frame presents with sync interval 0, none waiting
|
||||
// for DWM to compose the last (waitComposed) nor, when it changed nothing,
|
||||
// for the next refresh (waitRefresh). Where the system shows frames torn
|
||||
// (DXGI_FEATURE_PRESENT_ALLOW_TEARING, Windows 10 1703 on with a driver
|
||||
// that can), the window's swap chain allows tearing and its frames present
|
||||
// with it, flipping to the screen mid-refresh once DWM gives the window the
|
||||
// display (independent flip, as a borderless window covering the screen
|
||||
// has); a window DWM composes still shows the newest frame at each refresh.
|
||||
// A swap chain for composition (NewComposed) has no tearing: its frames
|
||||
// present with sync interval 0 all the same.
|
||||
//
|
||||
// While the window changes size, from its first change until the swap
|
||||
// chain settles (resize, settleDelay), frames present paced
|
||||
// (presentsUncapped), as without MYGO_UNCAPPED: none with tearing, a frame
|
||||
// of a new size waiting for DWM to show it (Render, waitShown), the others
|
||||
// each waiting for the composition that shows it (waitComposed), and one
|
||||
// that changed nothing for the next refresh (waitRefresh). Uncapped, a live
|
||||
// resize had one present take 2 s, on a Radeon 780M and a 59 Hz display,
|
||||
// with the window resized every 50 ms while it animated, and frames then
|
||||
// came at 92 to 95 a second, about two a composition besides the resize's,
|
||||
// where paced frames took no more than a refresh. The resize's buffers are
|
||||
// larger than the window and shown clipped, so DWM composes the window and
|
||||
// flips none of its frames to the screen torn: frames presented faster than
|
||||
// DWM composes only queue for it, filling the buffers, while DWM resizes the
|
||||
// window, and the frame of the next size, which waits for DWM to show it,
|
||||
// waits behind them. Paced, at most one frame a composition reaches DWM.
|
||||
// Before ResizeBuffers, no view of the buffers stays bound (unbindBuffers),
|
||||
// as DXGI asks.
|
||||
//
|
||||
// Unlike a paced frame of a new size, which calls DwmFlush on the main
|
||||
// thread and returns once DWM composed, an uncapped one waits for DWM at
|
||||
// most two refreshes, DwmFlush called on another thread (awaitRefresh,
|
||||
// shared with waitComposed's): every wait of an uncapped frame on DWM is
|
||||
// bounded. With that wait unbounded, a resize the app made with
|
||||
// SetWindowPos every 50 ms still had one present take 2.0 s, at its first
|
||||
// frame or after its last change, on the Radeon 780M, though its other
|
||||
// frames presented paced, while the same resize without MYGO_UNCAPPED,
|
||||
// and a drag of the window's edge uncapped, had none. The frame of a new size draws
|
||||
// within SetWindowPos (WM_SIZE), and its DwmFlush was the only wait of an
|
||||
// uncapped frame with no bound: it returns at DWM's next composition,
|
||||
// which frames flipped to the screen torn, as the uncapped ones before the
|
||||
// resize, do not bring about, and DWM may itself wait on the window's
|
||||
// thread while the window changes size; 2 s exactly looks like the end of
|
||||
// such a wait. A frame that waits for DWM no longer than two refreshes,
|
||||
// and then returns to the window's messages, leaves DWM nothing to wait
|
||||
// on, and a composition missed costs it two refreshes.
|
||||
//
|
||||
// Nor does Present itself wait long on the main thread while the window
|
||||
// changes size. With the frame of a new size's wait bounded, the
|
||||
// SetWindowPos resize still had one present take 2.0 s in 2 runs of 12 on
|
||||
// the Radeon 780M, once a second into the resize and once after its last
|
||||
// change, both of a frame not of a new size that redrew part of the last
|
||||
// (Present1 with dirty rectangles, sync interval 0, no flags). Such a
|
||||
// frame's wait for its composition is bounded and off the main thread; on
|
||||
// the main thread it calls nothing that may wait long but Present and,
|
||||
// every sweepEvery frames, DwmGetCompositionTimingInfo (readPeriod). Paced,
|
||||
// a frame presents only once the frame latency object said the swap chain
|
||||
// has room for it (latency.go), so its Present has nothing to wait for;
|
||||
// uncapped, there is no such object, and Present waits for room itself:
|
||||
// for the GPU to finish the frame before (one frame queued at most), which
|
||||
// waits for DWM to give its buffer back. DWM held up by the resize keeps
|
||||
// the buffers it holds, a frame drawn once the wait for its composition
|
||||
// timed out queues behind them, and Present then waits on DWM, which may
|
||||
// itself wait on the window's thread; that is the likeliest 2 s, though
|
||||
// nothing measured it. So while the window changes size, uncapped frames
|
||||
// present with DXGI_PRESENT_DO_NOT_WAIT (presentFlags), with which Present
|
||||
// returns DXGI_ERROR_WAS_STILL_DRAWING where it would wait. Present is tried
|
||||
// again for a refresh at most (showSoon), as long as the GPU or DWM take to
|
||||
// make room unless held up; after that the frame waits, unpresented
|
||||
// (holdFrame): the main thread goes back to the window's messages, the
|
||||
// frame after waits for it (Ready), and it presents after the next
|
||||
// composition, or two refreshes, tried as before (presentHeld). A frame
|
||||
// drawn meanwhile, as one of a new size within SetWindowPos, takes its
|
||||
// place, drawn whole as none showed it. A frame of a new size that Present
|
||||
// refuses for a refresh waits so too, its wait for DWM to show it
|
||||
// (waitShown) left out, rather than wait in Present within SetWindowPos,
|
||||
// where DWM may wait on the window's thread: the window shows the last
|
||||
// frame at its new size until it presents, a composition or two later,
|
||||
// which WARP on a busy CI runner does too. A frame waits so maxHeld at
|
||||
// most: without that bound, on the Radeon 780M, 2 runs of 30 SetWindowPos
|
||||
// resizes held their last frame, and nothing drew for the 2 to 3.5 s the
|
||||
// app ran on: the frame after waited for it, which DXGI never took with
|
||||
// the flag, tried after each composition.
|
||||
//
|
||||
// A frame held maxHeld presents as it would without the flag, waiting in
|
||||
// Present as long as DXGI has it, but on another goroutine (presentAside,
|
||||
// goAside), and after it, until DXGI takes a frame at once with the swap
|
||||
// chain settled (gaveUp), frames present paced, with the flag, and the
|
||||
// buffers resize, to settle the swap chain or for a size they do not hold,
|
||||
// on another goroutine too (resizeAside). While such a call is under way,
|
||||
// the main thread makes none to the device's context nor the swap chain,
|
||||
// which it may not while another thread does: it goes back to the
|
||||
// window's messages, a frame drawn meanwhile, as one of a new size within
|
||||
// SetWindowPos, is put off, the window showing the last frame, the frame
|
||||
// after waits for the call (Ready), and Release waits for it to return,
|
||||
// releaseWait at most, past which it leaves the GPU objects to the
|
||||
// process's end: DXGI may send the window a message meanwhile.
|
||||
// Once it returned, the frame after draws, at once if one waits, or once
|
||||
// the window asks for one (askFrame), as the settle timer's may have been
|
||||
// put off. DXGI refusing frames was not ended by anything the app did
|
||||
// without waiting. Giving the held frame up, never presented, and drawing
|
||||
// the frames after (bac8b96): in the one run of 40 where frames were given
|
||||
// up on, three in a row after the last change, the frame that then
|
||||
// settled the swap chain took 994 ms in Render on the main thread, in
|
||||
// ResizeBuffers or the Present without the flag after it, and frames came
|
||||
// again after it. Waiting on neither (0338404), as the frame that would
|
||||
// resize the buffers was put off until DXGI took a frame with the flag,
|
||||
// probed by presenting the frame last drawn with it, and an event query
|
||||
// said the GPU drew the frames before: in 4 runs of 70, every frame after
|
||||
// the give-ups, 167 of them over the 4 s watched, was put off, nothing
|
||||
// presenting and nothing resizing, the window showing a stale frame. The
|
||||
// stats could not tell which of the two waits held, as a frame put off
|
||||
// said the same for both; the code holds no fault in either (the probe
|
||||
// presents with the flag, and a success clears the wait; the query ended
|
||||
// after the frames drawn, GetData's S_OK told from S_FALSE), and neither
|
||||
// had a bound, so what ended them was DXGI or the GPU moving on by
|
||||
// itself, which they did not. That the probe was refused throughout is
|
||||
// the likelier, as DXGI refused the held frames for seconds before
|
||||
// maxHeld; nothing measured it. A call that waits for DXGI, made off the
|
||||
// main thread, ends that state as the 994 ms frame did, while the window
|
||||
// keeps taking its messages, which DWM may wait on as the window changes
|
||||
// size. Nothing can end such a call sooner, and it has no bound of the
|
||||
// app's; the waits seen, 994 ms and the 2 s presents above, all ended by
|
||||
// themselves, and the window takes its messages meanwhile. Frame stats
|
||||
// tell how many times Present said it was still drawing, a frame left to
|
||||
// present later, a frame put off while a call waits on another thread
|
||||
// ("put off while Present waits on another thread", or ResizeBuffers),
|
||||
// the frame after it ("after Present waited on another thread"), and one
|
||||
// paced until DXGI takes a frame at once. Nor does the main thread read
|
||||
// the refresh period from DWM uncapped, which may wait for it: another
|
||||
// goroutine does (readPeriodAside), and none while the window changes
|
||||
// size, as the period does not change with it. A swap chain that takes no
|
||||
// DXGI_PRESENT_DO_NOT_WAIT (DXGI_ERROR_INVALID_CALL) presents without it,
|
||||
// waiting as before (noWaitRefused).
|
||||
//
|
||||
// With two buffers, a frame presented with sync interval 0 that DWM has not
|
||||
// shown yet holds one and the screen the other, and the next frame waits
|
||||
// for the screen to give its buffer back, at the next refresh: the swap
|
||||
// chain has three (uncappedBuffers), so that a frame replaces the one
|
||||
// queued, which DWM drops. The device's frame latency, one frame queued at
|
||||
// most (init), still keeps the main thread from running ahead of the GPU:
|
||||
// Present blocks for it, and the GPU's pace is the frames'.
|
||||
const (
|
||||
// swapChainTearing is DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING, and
|
||||
// presentTearing DXGI_PRESENT_ALLOW_TEARING.
|
||||
swapChainTearing = 0x800
|
||||
presentTearing = 0x200
|
||||
// factory5CheckFeatureSupport is IDXGIFactory5::CheckFeatureSupport,
|
||||
// and featureTearing DXGI_FEATURE_PRESENT_ALLOW_TEARING.
|
||||
factory5CheckFeatureSupport = 28
|
||||
featureTearing = 0
|
||||
// uncappedBuffers is how many buffers an uncapped swap chain has at
|
||||
// least.
|
||||
uncappedBuffers = 3
|
||||
// presentDoNotWait is DXGI_PRESENT_DO_NOT_WAIT, with which Present
|
||||
// returns DXGI_ERROR_WAS_STILL_DRAWING rather than wait, and
|
||||
// dxgiErrorInvalidCall DXGI_ERROR_INVALID_CALL, which it returns where
|
||||
// the flag is not taken.
|
||||
presentDoNotWait = 0x8
|
||||
dxgiErrorWasStillDrawing = 0x887a000a
|
||||
dxgiErrorInvalidCall = 0x887a0001
|
||||
)
|
||||
|
||||
// errStillDrawing is what show returns when Present, with
|
||||
// DXGI_PRESENT_DO_NOT_WAIT, would have waited: the frame is not presented.
|
||||
var errStillDrawing = errors.New("d3d11: the swap chain has no room for the frame yet")
|
||||
|
||||
var iidIDXGIFactory5 = guid{0x7632e1f5, 0xee65, 0x4dca, [8]byte{0x87, 0xfd, 0x84, 0xcd, 0x75, 0xf8, 0x83, 0x8d}}
|
||||
|
||||
// tearingSupported reports whether the system shows frames presented with
|
||||
// tearing, as the factory's IDXGIFactory5 (DXGI 1.5) tells.
|
||||
func tearingSupported(factory uintptr) bool {
|
||||
var f5 uintptr
|
||||
if failed(call(factory, 0, uintptr(unsafe.Pointer(&iidIDXGIFactory5)), uintptr(unsafe.Pointer(&f5)))) {
|
||||
return false
|
||||
}
|
||||
defer free(&f5)
|
||||
var allow int32 // BOOL
|
||||
if failed(call(f5, factory5CheckFeatureSupport, featureTearing, uintptr(unsafe.Pointer(&allow)), unsafe.Sizeof(allow))) {
|
||||
return false
|
||||
}
|
||||
return allow != 0
|
||||
}
|
||||
|
||||
// swapChainFlags returns the flags the swap chain is made and resized
|
||||
// with: the frame latency object's, or uncapped, tearing's where it
|
||||
// presents with tearing.
|
||||
func (r *Renderer) swapChainFlags() uint32 {
|
||||
switch {
|
||||
case !r.uncapped:
|
||||
return swapChainWaitable
|
||||
case r.tearing:
|
||||
return swapChainTearing
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// presentFlags returns the flags of a present after sync vertical blanks:
|
||||
// tearing's for one at once (sync 0), where the swap chain allows it and
|
||||
// frames present uncapped; uncapped, when frames present paced, as while
|
||||
// the window changes size, DXGI_PRESENT_DO_NOT_WAIT, where the frame can
|
||||
// present later (post) and the swap chain takes it.
|
||||
func (r *Renderer) presentFlags(sync uintptr) uintptr {
|
||||
switch {
|
||||
case sync == 0 && r.tearing && r.presentsUncapped():
|
||||
return presentTearing
|
||||
case r.uncapped && !r.presentsUncapped() && r.post != nil && !r.noWaitRefused:
|
||||
return presentDoNotWait
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// showSoon presents the back buffer with DXGI_PRESENT_DO_NOT_WAIT, trying
|
||||
// again for at most a refresh while Present would wait, as for the GPU to
|
||||
// finish the last frame or DWM to give a buffer back, which takes that
|
||||
// long at most when DWM is not held up; then it returns errStillDrawing,
|
||||
// and the frame waits (holdFrame).
|
||||
func (r *Renderer) showSoon(sync uintptr) error {
|
||||
deadline := time.Now().Add(r.cost.refreshPeriod())
|
||||
for {
|
||||
err := r.show(sync)
|
||||
if err != errStillDrawing {
|
||||
return err
|
||||
}
|
||||
r.refused++
|
||||
if !time.Now().Before(deadline) {
|
||||
return err
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// holdFrame returns err, a present's, but for errStillDrawing: the frame
|
||||
// drawn, which Present refused, then presents after the next composition,
|
||||
// or a refresh or two, from refreshed (presentHeld), while the main thread
|
||||
// goes back to the window's messages, and the frame after waits for that
|
||||
// (Ready). A frame drawn before, as one of a new size within SetWindowPos,
|
||||
// takes its place (Render), and one that waited too long presents on
|
||||
// another goroutine (presentHeld).
|
||||
func (r *Renderer) holdFrame(err error) error {
|
||||
if err != errStillDrawing {
|
||||
return err
|
||||
}
|
||||
// The GPU draws the frame meanwhile.
|
||||
call(r.ctx, ctxFlush)
|
||||
r.unpresented = true
|
||||
if r.heldAt.IsZero() {
|
||||
r.heldAt = time.Now()
|
||||
}
|
||||
r.waitComposed()
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxHeld is how long a frame waits to present at most (presentHeld);
|
||||
// tests change it.
|
||||
var maxHeld = 100 * time.Millisecond
|
||||
|
||||
// askFrame has the window ask for a frame, as the settle timer does
|
||||
// (armSettle); tests replace it.
|
||||
var askFrame = func(hwnd uintptr) { procInvalidateRect.Call(hwnd, 0, 0) }
|
||||
|
||||
// presentHeld presents the frame Present refused (holdFrame), or has it
|
||||
// wait again, and reports whether the frame after can draw now. A frame
|
||||
// that waited maxHeld presents without DXGI_PRESENT_DO_NOT_WAIT, on
|
||||
// another goroutine (presentAside), and the frame after waits for it; until
|
||||
// DXGI takes a frame at once, frames present paced, and the buffers
|
||||
// resize on another goroutine too (gaveUp).
|
||||
func (r *Renderer) presentHeld() bool {
|
||||
r.unpresented = false
|
||||
if time.Since(r.heldAt) >= maxHeld {
|
||||
r.gaveUp = true
|
||||
r.presentAside()
|
||||
return false
|
||||
}
|
||||
err := r.present(0)
|
||||
if err == nil {
|
||||
// The frame after waits for the composition that shows it.
|
||||
r.waitComposed()
|
||||
return false
|
||||
}
|
||||
if err = r.holdFrame(err); err == nil {
|
||||
return false
|
||||
}
|
||||
if r.failed == nil {
|
||||
r.failed = err // the next frame finds it
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// presentsUncapped reports whether frames present without waiting for the
|
||||
// display: uncapped (MYGO_UNCAPPED), but while the window changes size, or
|
||||
// after a frame that waited maxHeld until DXGI takes one at once (gaveUp),
|
||||
// when they present paced.
|
||||
func (r *Renderer) presentsUncapped() bool {
|
||||
return r.uncapped && !r.resizing && !r.gaveUp
|
||||
}
|
||||
|
||||
// errAside is what buffers returns when another goroutine resizes the
|
||||
// buffers (resizeAside): the frame is put off.
|
||||
var errAside = errors.New("d3d11: the buffers resize on another thread")
|
||||
|
||||
// presentAside presents the frame drawn, which Present refused for
|
||||
// maxHeld, as it would without DXGI_PRESENT_DO_NOT_WAIT, waiting as long
|
||||
// as DXGI has it wait, on another goroutine (goAside).
|
||||
func (r *Renderer) presentAside() {
|
||||
sc, flags, params := r.swapChain, r.presentFlags(0)&^presentDoNotWait, r.presentParams()
|
||||
r.goAside("Present", func() uintptr { return presentCall(sc, 0, flags, params) }, func(hr uintptr) error {
|
||||
if failed(hr) {
|
||||
return fmt.Errorf("d3d11: present failed: %#x", uint32(hr))
|
||||
}
|
||||
r.held = r.ctx1 != 0 && uint32(hr) != dxgiStatusOccluded
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// resizeAside makes the swap chain's n buffers bw×bh pixels, showing w×h
|
||||
// of them, as buffers does, ResizeBuffers called on another goroutine
|
||||
// (goAside), the views of the buffers released before.
|
||||
func (r *Renderer) resizeAside(w, h, bw, bh, n int) {
|
||||
sc, flags := r.swapChain, uintptr(r.swapChainFlags())
|
||||
r.goAside("ResizeBuffers", func() uintptr { return resizeBuffersCall(sc, uintptr(n), uintptr(bw), uintptr(bh), flags) }, func(hr uintptr) error {
|
||||
if failed(hr) {
|
||||
return fmt.Errorf("d3d11: cannot resize the swap chain: %#x", uint32(hr))
|
||||
}
|
||||
return r.viewBuffers(w, h, bw, bh)
|
||||
})
|
||||
}
|
||||
|
||||
// goAside has another goroutine run fn, a call to the swap chain named
|
||||
// what, which may wait for DWM, and then runs done with what it returned
|
||||
// on the main thread (post). Meanwhile, the main thread makes no call to the
|
||||
// device's context nor the swap chain: a frame is put off (Render), the
|
||||
// frame after waits (Ready), and Release waits for fn (releaseWait). Once it
|
||||
// did, the frame after draws, at once if one waits, or once the window
|
||||
// asks for one (askFrame).
|
||||
func (r *Renderer) goAside(what string, fn func() uintptr, done func(hr uintptr) error) {
|
||||
ended, post := make(chan struct{}), r.post
|
||||
r.aside, r.asideEnded = what, ended
|
||||
go func() {
|
||||
hr := fn()
|
||||
close(ended)
|
||||
post(func() {
|
||||
if r.asideEnded != ended {
|
||||
return // released meanwhile
|
||||
}
|
||||
r.aside, r.asideEnded, r.asideDone = "", nil, what
|
||||
if err := done(hr); err != nil && r.failed == nil {
|
||||
r.failed = err // the next frame finds it
|
||||
}
|
||||
if r.wake != nil {
|
||||
r.woke()
|
||||
return
|
||||
}
|
||||
askFrame(r.hwnd)
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// readPeriodAside reads the display's refresh period from DWM on another
|
||||
// goroutine, as DwmGetCompositionTimingInfo may wait for it, and sets it on
|
||||
// the main thread (post). Without post, it reads it at once.
|
||||
func (r *Renderer) readPeriodAside() {
|
||||
if r.post == nil {
|
||||
r.cost.readPeriod()
|
||||
return
|
||||
}
|
||||
if r.readingPeriod {
|
||||
return
|
||||
}
|
||||
r.readingPeriod = true
|
||||
post := r.post
|
||||
go func() {
|
||||
p := dwmPeriod()
|
||||
post(func() {
|
||||
r.readingPeriod = false
|
||||
if p != 0 {
|
||||
r.cost.period = p
|
||||
}
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// unbindBuffers unbinds the render target views of the swap chain's
|
||||
// buffers from the device context and submits the commands drawing into
|
||||
// them, before ResizeBuffers, which needs no reference to the buffers
|
||||
// left: a view bound to the context is one. The context waits for the GPU
|
||||
// to be done with them by itself.
|
||||
func (r *Renderer) unbindBuffers() {
|
||||
call(r.ctx, ctxOMSetRenderTargets, 0, 0, 0)
|
||||
r.drawing = 0
|
||||
call(r.ctx, ctxFlush)
|
||||
}
|
||||
+1275
File diff suppressed because it is too large.
Load diff
+180
@@ -0,0 +1,180 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Frames of video (scene.Surface) reach the GPU as the decoder left them:
|
||||
// a texture in BGRA that Media Foundation drew on a device of its own and
|
||||
// shares by an NT handle (Surface.Native), which the renderer opens on
|
||||
// its device once and reads under the texture's keyed mutex, or planes in
|
||||
// memory, which it uploads, NV12's luma and chroma into textures of their
|
||||
// own that the shader converts.
|
||||
|
||||
const (
|
||||
devOpenSharedResource1 = 48 // ID3D11Device1
|
||||
keyedAcquireSync = 8 // IDXGIKeyedMutex
|
||||
keyedReleaseSync = 9
|
||||
formatR8G8Unorm = 49
|
||||
// acquireTimeout is how long, in ms, a frame waits for the decoder to
|
||||
// finish writing a frame of video into a shared texture.
|
||||
acquireTimeout = 100
|
||||
waitTimeout = 0x102
|
||||
)
|
||||
|
||||
var (
|
||||
iidID3D11Device1 = guid{0xa04bfb29, 0x08ef, 0x43d6, [8]byte{0xa4, 0x9c, 0xa9, 0xbd, 0xbd, 0xcb, 0xe6, 0x86}}
|
||||
iidIDXGIKeyedMutex = guid{0x9d8e1289, 0xd7b3, 0x465f, [8]byte{0x81, 0x26, 0x25, 0x0e, 0x34, 0x9a, 0xf8, 0x5d}}
|
||||
)
|
||||
|
||||
// sharedTexture is a texture a decoder shares, opened on the renderer's
|
||||
// device.
|
||||
type sharedTexture struct {
|
||||
texture
|
||||
mutex uintptr // IDXGIKeyedMutex
|
||||
}
|
||||
|
||||
// videoState is what the renderer keeps of frames of video.
|
||||
type videoState struct {
|
||||
device1 uintptr // ID3D11Device1, for OpenSharedResource1
|
||||
shared map[uint64]*sharedTexture
|
||||
// acquired are the keyed mutexes the frame being drawn holds, released
|
||||
// once its draws are issued (releaseShared).
|
||||
acquired []uintptr
|
||||
}
|
||||
|
||||
// surfaceView returns the view of the texture of a frame of video: its
|
||||
// luma, for NV12 in memory, whose chroma chromaView returns.
|
||||
func (r *Renderer) surfaceView(img *scene.Image, s *scene.Surface) uintptr {
|
||||
if s.Native != 0 {
|
||||
return r.sharedView(s)
|
||||
}
|
||||
t := r.images[img.ID()]
|
||||
cw, ch := (img.W+1)/2, (img.H+1)/2
|
||||
if t != nil && (t.chroma == nil || t.w != img.W || t.h != img.H) {
|
||||
freeTexture(t)
|
||||
t = nil
|
||||
}
|
||||
if t == nil {
|
||||
t = &texture{chroma: &texture{}}
|
||||
if r.planeTexture(t, img.W, img.H, formatR8Unorm, s.Planes[0]) != nil ||
|
||||
r.planeTexture(t.chroma, cw, ch, formatR8G8Unorm, s.Planes[1]) != nil {
|
||||
freeTexture(t)
|
||||
delete(r.images, img.ID())
|
||||
return 0
|
||||
}
|
||||
t.ver = img.Version()
|
||||
r.images[img.ID()] = t
|
||||
} else if t.ver != img.Version() {
|
||||
call(r.ctx, ctxUpdateSubresource, t.tex, 0, 0, uintptr(unsafe.Pointer(&s.Planes[0].Pix[0])), uintptr(s.Planes[0].Stride), 0)
|
||||
call(r.ctx, ctxUpdateSubresource, t.chroma.tex, 0, 0, uintptr(unsafe.Pointer(&s.Planes[1].Pix[0])), uintptr(s.Planes[1].Stride), 0)
|
||||
t.ver = img.Version()
|
||||
}
|
||||
t.lastFrame = r.frame
|
||||
return t.srv
|
||||
}
|
||||
|
||||
// planeTexture makes t a texture of a plane of w×h texels in memory.
|
||||
func (r *Renderer) planeTexture(t *texture, w, h int, format uint32, p scene.Plane) error {
|
||||
if err := r.newTexture(t, w, h, format, nil, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
call(r.ctx, ctxUpdateSubresource, t.tex, 0, 0, uintptr(unsafe.Pointer(&p.Pix[0])), uintptr(p.Stride), 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
// chromaView returns the view of the chroma of a frame of video in NV12,
|
||||
// after imageView returned that of its luma, or 0.
|
||||
func (r *Renderer) chromaView(img *scene.Image) uintptr {
|
||||
if t := r.images[img.ID()]; t != nil && t.chroma != nil {
|
||||
return t.chroma.srv
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// sharedView opens the texture a decoder shares, once, and acquires its
|
||||
// keyed mutex for the frame, which releaseShared releases once its draws
|
||||
// are issued: the GPU then reads it after the decoder's writes, and the
|
||||
// decoder writes it again after the frame's reads.
|
||||
func (r *Renderer) sharedView(s *scene.Surface) uintptr {
|
||||
v := &r.video
|
||||
t := v.shared[s.NativeID]
|
||||
if t == nil {
|
||||
if v.device1 == 0 && failed(call(r.device, 0, uintptr(unsafe.Pointer(&iidID3D11Device1)), uintptr(unsafe.Pointer(&v.device1)))) {
|
||||
v.device1 = 0
|
||||
return 0
|
||||
}
|
||||
t = &sharedTexture{}
|
||||
if failed(call(v.device1, devOpenSharedResource1, s.Native, uintptr(unsafe.Pointer(&iidID3D11Texture2D)), uintptr(unsafe.Pointer(&t.tex)))) {
|
||||
return 0
|
||||
}
|
||||
if failed(call(t.tex, 0, uintptr(unsafe.Pointer(&iidIDXGIKeyedMutex)), uintptr(unsafe.Pointer(&t.mutex)))) ||
|
||||
failed(call(r.device, devCreateShaderResourceView, t.tex, 0, uintptr(unsafe.Pointer(&t.srv)))) {
|
||||
free(&t.mutex)
|
||||
free(&t.srv)
|
||||
free(&t.tex)
|
||||
return 0
|
||||
}
|
||||
if v.shared == nil {
|
||||
v.shared = map[uint64]*sharedTexture{}
|
||||
}
|
||||
v.shared[s.NativeID] = t
|
||||
}
|
||||
if t.lastFrame != r.frame || !v.holds(t.mutex) {
|
||||
hr := call(t.mutex, keyedAcquireSync, 0, acquireTimeout)
|
||||
if failed(hr) || hr == waitTimeout {
|
||||
return 0
|
||||
}
|
||||
v.acquired = append(v.acquired, t.mutex)
|
||||
}
|
||||
t.lastFrame = r.frame
|
||||
return t.srv
|
||||
}
|
||||
|
||||
func (v *videoState) holds(mutex uintptr) bool {
|
||||
for _, m := range v.acquired {
|
||||
if m == mutex {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// releaseShared releases the keyed mutexes of the shared textures the
|
||||
// frame read, its draws issued.
|
||||
func (r *Renderer) releaseShared() {
|
||||
for _, m := range r.video.acquired {
|
||||
call(m, keyedReleaseSync, 0)
|
||||
}
|
||||
r.video.acquired = r.video.acquired[:0]
|
||||
}
|
||||
|
||||
// sweepShared closes the shared textures no frame read for a while.
|
||||
func (r *Renderer) sweepShared(all bool) {
|
||||
for key, t := range r.video.shared {
|
||||
if all || r.frame-t.lastFrame > 240 {
|
||||
free(&t.mutex)
|
||||
free(&t.srv)
|
||||
free(&t.tex)
|
||||
delete(r.video.shared, key)
|
||||
}
|
||||
}
|
||||
if all {
|
||||
free(&r.video.device1)
|
||||
}
|
||||
}
|
||||
|
||||
// freeTexture frees an image's texture, and its chroma's.
|
||||
func freeTexture(t *texture) {
|
||||
free(&t.srv)
|
||||
free(&t.tex)
|
||||
if t.chroma != nil {
|
||||
free(&t.chroma.srv)
|
||||
free(&t.chroma.tex)
|
||||
t.chroma = nil
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"syscall"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestDrawsVideoAsTheCPURenderer draws frames of video in NV12 from their
|
||||
// planes in memory, which the shader converts as the CPU renderer does,
|
||||
// then frames in BGRA that another device drew into textures it shares,
|
||||
// as Media Foundation does, which the renderer reads where they are.
|
||||
func TestDrawsVideoAsTheCPURenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.VideoScene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 2 {
|
||||
for _, op := range s.Ops {
|
||||
op.Image.Changed()
|
||||
}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-video", pix, stride, s)
|
||||
}
|
||||
for _, op := range s.Ops {
|
||||
if tex := r.images[op.Image.ID()]; tex == nil || tex.chroma == nil {
|
||||
t.Fatal("a frame of video drew from RGBA, not its planes")
|
||||
}
|
||||
}
|
||||
|
||||
// The frames converted to BGRA, in textures of another device.
|
||||
dev, ctx, _, err := device.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer free(&dev)
|
||||
defer free(&ctx)
|
||||
var shared []uintptr
|
||||
defer func() {
|
||||
for _, h := range shared {
|
||||
syscall.CloseHandle(syscall.Handle(h))
|
||||
}
|
||||
}()
|
||||
done := map[*scene.Image]bool{}
|
||||
for i, op := range s.Ops {
|
||||
img := op.Image
|
||||
if done[img] {
|
||||
continue
|
||||
}
|
||||
done[img] = true
|
||||
rgba := img.Surface.RGBA(nil, img.W, img.H)
|
||||
bgra := make([]byte, len(rgba))
|
||||
for k := 0; k < len(rgba); k += 4 {
|
||||
bgra[k], bgra[k+1], bgra[k+2], bgra[k+3] = rgba[k+2], rgba[k+1], rgba[k], rgba[k+3]
|
||||
}
|
||||
h := newSharedTexture(t, dev, ctx, img.W, img.H, bgra)
|
||||
shared = append(shared, h)
|
||||
img.Surface = &scene.Surface{Format: scene.SurfaceBGRA, Native: h, NativeID: uint64(i + 1)}
|
||||
img.Restore = func() []byte { return rgba }
|
||||
img.Pix = nil
|
||||
img.Changed()
|
||||
}
|
||||
for range 3 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-video-shared", pix, stride, s)
|
||||
}
|
||||
if len(r.video.shared) != len(shared) {
|
||||
t.Fatalf("the renderer opened %d shared textures, not %d", len(r.video.shared), len(shared))
|
||||
}
|
||||
if len(r.video.acquired) != 0 {
|
||||
t.Fatal("the frame kept the keyed mutexes of the textures it read")
|
||||
}
|
||||
}
|
||||
|
||||
// newSharedTexture returns the NT handle of a w×h texture in BGRA of dev with
|
||||
// a keyed mutex, holding pix, which dev wrote under the mutex.
|
||||
func newSharedTexture(t *testing.T, dev, ctx uintptr, w, h int, pix []byte) uintptr {
|
||||
const (
|
||||
miscSharedKeyedMutex = 0x100
|
||||
miscSharedNTHandle = 0x800
|
||||
sharedRead = 0x80000000
|
||||
sharedWrite = 1
|
||||
createSharedHandle = 13 // IDXGIResource1
|
||||
)
|
||||
iidIDXGIResource1 := guid{0x30961379, 0x4609, 0x4a41, [8]byte{0x99, 0x8e, 0x54, 0xfe, 0x56, 0x7e, 0xe0, 0xc1}}
|
||||
desc := texture2DDesc{Width: uint32(w), Height: uint32(h), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm, SampleCount: 1,
|
||||
Usage: usageDefault, BindFlags: bindShaderResource, MiscFlags: miscSharedKeyedMutex | miscSharedNTHandle}
|
||||
var tex, mutex, res uintptr
|
||||
if hr := call(dev, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&tex))); failed(hr) {
|
||||
t.Fatalf("cannot create a shared texture: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&tex)
|
||||
if failed(call(tex, 0, uintptr(unsafe.Pointer(&iidIDXGIKeyedMutex)), uintptr(unsafe.Pointer(&mutex)))) {
|
||||
t.Fatal("no keyed mutex")
|
||||
}
|
||||
defer free(&mutex)
|
||||
call(mutex, keyedAcquireSync, 0, 1000)
|
||||
call(ctx, ctxUpdateSubresource, tex, 0, 0, uintptr(unsafe.Pointer(&pix[0])), uintptr(4*w), 0)
|
||||
call(mutex, keyedReleaseSync, 0)
|
||||
call(ctx, ctxFlush)
|
||||
if failed(call(tex, 0, uintptr(unsafe.Pointer(&iidIDXGIResource1)), uintptr(unsafe.Pointer(&res)))) {
|
||||
t.Fatal("no IDXGIResource1")
|
||||
}
|
||||
defer free(&res)
|
||||
var handle uintptr
|
||||
if hr := call(res, createSharedHandle, 0, sharedRead|sharedWrite, 0, uintptr(unsafe.Pointer(&handle))); failed(hr) {
|
||||
t.Fatalf("cannot share the texture: %#x", uint32(hr))
|
||||
}
|
||||
return handle
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"slices"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Partial redraws. A frame that changes little of a window (a caret
|
||||
// blinking, a spinner turning, a button under the pointer) redraws only
|
||||
// what changed (scene.Differ), into a buffer that holds an earlier frame:
|
||||
// what changed since that one, in rectangles apart from each other, each
|
||||
// cleared to the frame's color and drawn scissored to it, over the rest
|
||||
// kept as it was (loaded, not cleared). A spinner in one corner and a
|
||||
// progress bar in the other redraw only themselves, not all between. A
|
||||
// surface's swap chain shows its buffers in turn, so a buffer the renderer
|
||||
// gets holds the frame drawn into it some frames ago, as EGL's buffer age
|
||||
// says: Ages keeps, for each buffer, what changed since it was drawn.
|
||||
|
||||
// maxAges is how many buffers Ages tracks, the most a swap chain has (a
|
||||
// CAMetalLayer three) and one more.
|
||||
const maxAges = 4
|
||||
|
||||
// maxRects is how many rectangles a part of a frame has at most, as
|
||||
// scene.Differ's damage: each batch meeting several draws once for each.
|
||||
const maxRects = 8
|
||||
|
||||
// Ages keeps what changed in the frames of a window since each buffer of
|
||||
// its swap chain was drawn, by an identity of the buffer (the texture of a
|
||||
// CAMetalLayer's drawable).
|
||||
type Ages struct {
|
||||
// Forget, unless nil, is called with each buffer Ages stops tracking.
|
||||
Forget func(id uintptr)
|
||||
bufs [maxAges]age
|
||||
n int
|
||||
frame uint64
|
||||
// taken is what Take returned last.
|
||||
taken []image.Rectangle
|
||||
}
|
||||
|
||||
type age struct {
|
||||
id uintptr
|
||||
// changed is what changed since the buffer was drawn, unless whole, in
|
||||
// rectangles apart from each other (addRect).
|
||||
changed []image.Rectangle
|
||||
whole bool
|
||||
// used is the frame the buffer was last drawn in.
|
||||
used uint64
|
||||
}
|
||||
|
||||
// Add notes a new frame, which changed the rectangles changed of the last,
|
||||
// or everything when whole.
|
||||
func (a *Ages) Add(changed []image.Rectangle, whole bool) {
|
||||
a.frame++
|
||||
for i := range a.bufs[:a.n] {
|
||||
b := &a.bufs[i]
|
||||
b.whole = b.whole || whole
|
||||
if b.whole {
|
||||
b.changed = b.changed[:0]
|
||||
continue
|
||||
}
|
||||
for _, r := range changed {
|
||||
b.changed = addRect(b.changed, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Take returns what changed in the frames since buffer id was drawn, the
|
||||
// buffer the frame is drawn into, in rectangles apart from each other
|
||||
// valid until the next Take, and false when that is unknown (the buffer
|
||||
// is new, or everything may have changed): the frame draws it whole. It
|
||||
// then holds the frame.
|
||||
func (a *Ages) Take(id uintptr) (changed []image.Rectangle, known bool) {
|
||||
for i := range a.bufs[:a.n] {
|
||||
b := &a.bufs[i]
|
||||
if b.id == id {
|
||||
a.taken = append(a.taken[:0], b.changed...)
|
||||
known = !b.whole
|
||||
b.changed, b.whole, b.used = b.changed[:0], false, a.frame
|
||||
return a.taken, known
|
||||
}
|
||||
}
|
||||
// A new buffer takes the place of the one drawn least recently.
|
||||
i := a.n
|
||||
if a.n == maxAges {
|
||||
i = 0
|
||||
for j := range a.bufs {
|
||||
if a.bufs[j].used < a.bufs[i].used {
|
||||
i = j
|
||||
}
|
||||
}
|
||||
if a.Forget != nil {
|
||||
a.Forget(a.bufs[i].id)
|
||||
}
|
||||
} else {
|
||||
a.n++
|
||||
}
|
||||
a.bufs[i] = age{id: id, used: a.frame, changed: a.bufs[i].changed[:0]}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Reset forgets every buffer, as a swap chain makes new ones.
|
||||
func (a *Ages) Reset() {
|
||||
if a.Forget != nil {
|
||||
for i := range a.bufs[:a.n] {
|
||||
a.Forget(a.bufs[i].id)
|
||||
}
|
||||
}
|
||||
for i := range a.bufs {
|
||||
a.bufs[i] = age{changed: a.bufs[i].changed[:0]}
|
||||
}
|
||||
a.n = 0
|
||||
}
|
||||
|
||||
// addRect adds r to rects, rectangles apart from each other, and returns
|
||||
// them: r takes in those it overlaps or nearly meets, and past maxRects,
|
||||
// the two whose union grows least become it.
|
||||
func addRect(rects []image.Rectangle, r image.Rectangle) []image.Rectangle {
|
||||
if r.Empty() {
|
||||
return rects
|
||||
}
|
||||
for i := 0; i < len(rects); {
|
||||
if rects[i].Inset(-8).Overlaps(r) {
|
||||
r = r.Union(rects[i])
|
||||
rects = slices.Delete(rects, i, i+1)
|
||||
i = 0
|
||||
continue
|
||||
}
|
||||
i++
|
||||
}
|
||||
rects = append(rects, r)
|
||||
if len(rects) <= maxRects {
|
||||
return rects
|
||||
}
|
||||
bi, bj, best := 0, 1, -1
|
||||
for i := range rects {
|
||||
for j := i + 1; j < len(rects); j++ {
|
||||
grows := pixels(rects[i].Union(rects[j])) - pixels(rects[i]) - pixels(rects[j])
|
||||
if best < 0 || grows < best {
|
||||
bi, bj, best = i, j, grows
|
||||
}
|
||||
}
|
||||
}
|
||||
u := rects[bi].Union(rects[bj])
|
||||
rects = slices.Delete(rects, bj, bj+1)
|
||||
rects = slices.Delete(rects, bi, bi+1)
|
||||
return addRect(rects, u)
|
||||
}
|
||||
|
||||
func pixels(r image.Rectangle) int { return r.Dx() * r.Dy() }
|
||||
|
||||
// Part is the part of a frame to redraw: rectangles apart from each other,
|
||||
// none when nothing changed.
|
||||
type Part struct {
|
||||
Rects []Scissor
|
||||
// rects, grown and next are Partial's.
|
||||
rects, grown, next []image.Rectangle
|
||||
}
|
||||
|
||||
// Bounds returns the rectangle around the part's.
|
||||
func (p *Part) Bounds() Scissor {
|
||||
var u image.Rectangle
|
||||
for _, s := range p.Rects {
|
||||
u = u.Union(image.Rect(int(s.Left), int(s.Top), int(s.Right), int(s.Bottom)))
|
||||
}
|
||||
return Scissor{int32(u.Min.X), int32(u.Min.Y), int32(u.Max.X), int32(u.Max.Y)}
|
||||
}
|
||||
|
||||
// String describes the part, for FrameInfo.
|
||||
func (p *Part) String() string {
|
||||
b := p.Bounds()
|
||||
s := fmt.Sprintf("%d×%d at %d,%d", b.Right-b.Left, b.Bottom-b.Top, b.Left, b.Top)
|
||||
if len(p.Rects) > 1 {
|
||||
n := 0
|
||||
for _, r := range p.Rects {
|
||||
n += int(r.Right-r.Left) * int(r.Bottom-r.Top)
|
||||
}
|
||||
s = fmt.Sprintf("%d rectangles of %d pixels in %s", len(p.Rects), n, s)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Set makes p the part of a w×h frame to redraw, given what changed in the
|
||||
// buffer drawn into (Ages.Take, or scene.Differ.Diff), grown by grow (the
|
||||
// backdrops of effects, scene.Differ.AddBackdrops), and returns false when
|
||||
// the frame is better drawn whole: past half the frame together, drawing
|
||||
// it whole costs about the same.
|
||||
func (p *Part) Set(changed []image.Rectangle, w, h int, grow func([]image.Rectangle) []image.Rectangle) bool {
|
||||
frame := image.Rect(0, 0, w, h)
|
||||
p.rects = p.rects[:0]
|
||||
for _, r := range changed {
|
||||
p.rects = addRect(p.rects, r.Intersect(frame))
|
||||
}
|
||||
// Grown until what it grows by is in it: a backdrop an effect reads
|
||||
// must be within one rectangle, drawn before the effect reads it.
|
||||
for grow != nil && len(p.rects) > 0 {
|
||||
p.grown = grow(append(p.grown[:0], p.rects...))
|
||||
p.next = p.next[:0]
|
||||
for _, r := range p.grown {
|
||||
p.next = addRect(p.next, r.Intersect(frame))
|
||||
}
|
||||
p.rects, p.next = p.next, p.rects
|
||||
if within(p.rects, p.next) {
|
||||
break
|
||||
}
|
||||
}
|
||||
n := 0
|
||||
p.Rects = p.Rects[:0]
|
||||
for _, r := range p.rects {
|
||||
n += pixels(r)
|
||||
p.Rects = append(p.Rects, Scissor{int32(r.Min.X), int32(r.Min.Y), int32(r.Max.X), int32(r.Max.Y)})
|
||||
}
|
||||
return 2*n < w*h
|
||||
}
|
||||
|
||||
// within reports whether each rectangle of rects is within one of in.
|
||||
func within(rects, in []image.Rectangle) bool {
|
||||
for _, r := range rects {
|
||||
if !slices.ContainsFunc(in, r.In) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Intersect returns the pixels both s and o take.
|
||||
func (s Scissor) Intersect(o Scissor) Scissor { return s.intersect(o) }
|
||||
|
||||
// Has reports whether Ages tracks buffer id.
|
||||
func (a *Ages) Has(id uintptr) bool {
|
||||
for i := range a.bufs[:a.n] {
|
||||
if a.bufs[i].id == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Pipelines keeps, for each op of the frames a renderer builds, a hash of
|
||||
// the pipelines (shaders, blending) its instances draw with. An op drawn
|
||||
// with others than in the last frame (a batch specialized for other
|
||||
// classes as batching changed around it, a pipeline made meanwhile, a
|
||||
// clip cut by a mask) draws a unit in the last place apart here and
|
||||
// there, which a frame drawn whole would change too: its bounds count as
|
||||
// changed.
|
||||
type Pipelines struct {
|
||||
keys, last []uint64
|
||||
}
|
||||
|
||||
// Damage hashes the pipelines of the ops b built, pipe(i) being batch i's,
|
||||
// and adds to damage, what changed since the last frame drawn as d found
|
||||
// (unless not known), the bounds of the ops d matches with an op of the
|
||||
// last frame drawn with other pipelines, and returns it.
|
||||
func (p *Pipelines) Damage(b *Builder, pipe func(i int) uint64, d *scene.Differ, damage []image.Rectangle, known bool) []image.Rectangle {
|
||||
n := len(b.OpStart) - 1
|
||||
p.keys = slices.Grow(p.keys[:0], n)[:n]
|
||||
clear(p.keys)
|
||||
op := 0
|
||||
for i, bt := range b.Batches {
|
||||
lo, hi := int32(bt.Start), int32(bt.Start+bt.Count)
|
||||
for op < n && b.OpStart[op+1] <= lo {
|
||||
op++
|
||||
}
|
||||
key := pipe(i)
|
||||
for k := op; k < n && b.OpStart[k] < hi; k++ {
|
||||
if b.OpStart[k+1] > b.OpStart[k] {
|
||||
p.keys[k] = (p.keys[k] ^ key) * 1099511628211
|
||||
}
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
return damage
|
||||
}
|
||||
bounds := d.Bounds()
|
||||
for j, key := range p.keys {
|
||||
if i, ok := d.Match(j); ok && i < len(p.last) && p.last[i] != key {
|
||||
damage = append(damage, bounds[j])
|
||||
}
|
||||
}
|
||||
return damage
|
||||
}
|
||||
|
||||
// Remember keeps the hashes of the frame Damage was given last, drawn, to
|
||||
// compare the next with.
|
||||
func (p *Pipelines) Remember() { p.keys, p.last = p.last, p.keys }
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAges(t *testing.T) {
|
||||
var forgot []uintptr
|
||||
a := Ages{Forget: func(id uintptr) { forgot = append(forgot, id) }}
|
||||
caret := image.Rect(10, 10, 12, 30)
|
||||
clock := image.Rect(100, 0, 140, 20)
|
||||
both := fmt.Sprint([]image.Rectangle{caret, clock})
|
||||
// Three buffers in turn, each new: drawn whole.
|
||||
for id := uintptr(1); id <= 3; id++ {
|
||||
a.Add([]image.Rectangle{caret}, false)
|
||||
if _, known := a.Take(id); known {
|
||||
t.Fatalf("buffer %d, new, is known", id)
|
||||
}
|
||||
}
|
||||
// Buffer 1 lacks the two frames drawn since it was: the caret's, apart
|
||||
// from the clock's.
|
||||
a.Add([]image.Rectangle{clock}, false)
|
||||
if got, known := a.Take(1); !known || fmt.Sprint(got) != both {
|
||||
t.Errorf("buffer 1 lacks %v (known %v), want %v", got, known, both)
|
||||
}
|
||||
// Buffer 2 lacks the frame drawn into 3, the clock's and nothing.
|
||||
a.Add(nil, false)
|
||||
if got, known := a.Take(2); !known || fmt.Sprint(got) != both {
|
||||
t.Errorf("buffer 2 lacks %v (known %v), want %v", got, known, both)
|
||||
}
|
||||
// A frame changing everything makes every buffer drawn whole.
|
||||
a.Add(nil, true)
|
||||
if _, known := a.Take(3); known {
|
||||
t.Error("buffer 3 is known after a frame changing everything")
|
||||
}
|
||||
a.Add([]image.Rectangle{caret}, false)
|
||||
if _, known := a.Take(1); known {
|
||||
t.Error("buffer 1 is known after a frame changing everything")
|
||||
}
|
||||
// A fifth buffer takes the place of the one drawn least recently.
|
||||
a.Take(4)
|
||||
a.Take(5)
|
||||
if len(forgot) != 1 || forgot[0] != 2 {
|
||||
t.Errorf("forgot %v, want [2]", forgot)
|
||||
}
|
||||
a.Reset()
|
||||
if len(forgot) != 5 || a.Has(1) {
|
||||
t.Errorf("after Reset, forgot %v and tracks buffer 1: %v", forgot, a.Has(1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddRect(t *testing.T) {
|
||||
var rects []image.Rectangle
|
||||
// Rectangles apart stay apart; one meeting two takes them in.
|
||||
rects = addRect(rects, image.Rect(0, 0, 10, 10))
|
||||
rects = addRect(rects, image.Rect(50, 0, 60, 10))
|
||||
if len(rects) != 2 {
|
||||
t.Fatalf("two apart: %v", rects)
|
||||
}
|
||||
rects = addRect(rects, image.Rect(5, 5, 55, 8))
|
||||
if fmt.Sprint(rects) != fmt.Sprint([]image.Rectangle{image.Rect(0, 0, 60, 10)}) {
|
||||
t.Errorf("one meeting both: %v", rects)
|
||||
}
|
||||
// Past maxRects, the two nearest become one, and none overlap.
|
||||
rects = rects[:0]
|
||||
for i := range maxRects + 1 {
|
||||
rects = addRect(rects, image.Rect(i*100, 0, i*100+10, 10))
|
||||
}
|
||||
rects = addRect(rects, image.Rect(1000, 0, 1010, 10)) // nearest the last
|
||||
if len(rects) != maxRects {
|
||||
t.Fatalf("%d rectangles, want %d: %v", len(rects), maxRects, rects)
|
||||
}
|
||||
for i, r := range rects {
|
||||
for _, o := range rects[i+1:] {
|
||||
if r.Overlaps(o) {
|
||||
t.Errorf("%v overlaps %v", r, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartial(t *testing.T) {
|
||||
var p Part
|
||||
// Within the frame.
|
||||
if !p.Set([]image.Rectangle{image.Rect(-5, 10, 20, 30)}, 100, 100, nil) || fmt.Sprint(p.Rects) != "[{0 10 20 30}]" {
|
||||
t.Errorf("Set = %v", p.Rects)
|
||||
}
|
||||
// Two corners stay apart.
|
||||
if !p.Set([]image.Rectangle{image.Rect(0, 0, 10, 10), image.Rect(90, 90, 100, 100)}, 100, 100, nil) || fmt.Sprint(p.Rects) != "[{0 0 10 10} {90 90 100 100}]" {
|
||||
t.Errorf("two corners: %v", p.Rects)
|
||||
}
|
||||
// Half the frame or more, together, is drawn whole.
|
||||
if p.Set([]image.Rectangle{image.Rect(0, 0, 100, 30), image.Rect(0, 60, 100, 80)}, 100, 100, nil) {
|
||||
t.Error("half the frame drawn in part")
|
||||
}
|
||||
// Nothing changed in the frame: nothing to draw.
|
||||
if !p.Set([]image.Rectangle{image.Rect(200, 0, 210, 10)}, 100, 100, nil) || len(p.Rects) != 0 {
|
||||
t.Errorf("outside: %v", p.Rects)
|
||||
}
|
||||
// Grown until what it grows by is in it: a backdrop from 40 to 60
|
||||
// meets the area, an effect reading one from 0 to 45 then meets that.
|
||||
grow := func(d []image.Rectangle) []image.Rectangle {
|
||||
for _, b := range []image.Rectangle{image.Rect(40, 0, 60, 10), image.Rect(0, 0, 45, 10)} {
|
||||
for _, r := range d {
|
||||
if r.Overlaps(b) {
|
||||
d = append(d, b)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
if !p.Set([]image.Rectangle{image.Rect(50, 0, 55, 5), image.Rect(80, 80, 90, 90)}, 100, 100, grow) || fmt.Sprint(p.Rects) != "[{80 80 90 90} {0 0 60 10}]" {
|
||||
t.Errorf("grown: %v, want [{80 80 90 90} {0 0 60 10}]", p.Rects)
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkRenderSprites draws frames of a 2D game at 1280×720 (gputest's
|
||||
// SpriteScene, tiles 2 times as large: about 1,800 sprites of one sheet)
|
||||
// and reads each back, which waits for it. Where no GPU runs it, Mesa's
|
||||
// llvmpipe draws on the CPU, so the time is mostly its own.
|
||||
func BenchmarkRenderSprites(b *testing.B) {
|
||||
benchRender(b, gputest.SpriteScene(1280, 720, 2, 3, 300))
|
||||
}
|
||||
|
||||
// BenchmarkRenderEmpty draws frames of nothing at 1280×720: what the
|
||||
// sprites' frames spend besides them.
|
||||
func BenchmarkRenderEmpty(b *testing.B) {
|
||||
benchRender(b, &scene.Scene{Width: 1280, Height: 720, Clear: scene.Color{A: 255}})
|
||||
}
|
||||
|
||||
func benchRender(b *testing.B, s *scene.Scene) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
o, err := NewOffscreen(false, s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer o.Release()
|
||||
for b.Loop() {
|
||||
if _, err := o.Render(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkVideoFrameRGBA draws a new 1920×1080 frame of video each
|
||||
// frame the way video drew before frames had surfaces: converted to RGBA
|
||||
// on the CPU (as a decoder in Go would, or the CPU renderer does) and
|
||||
// uploaded, 8 MB a frame.
|
||||
func BenchmarkVideoFrameRGBA(b *testing.B) {
|
||||
img := gputest.NV12Frame(1920, 1080, scene.BT709)
|
||||
rgb := scene.NewImageRGBA(1920, 1080, nil)
|
||||
s := videoBenchScene(rgb)
|
||||
benchVideo(b, s, func() {
|
||||
rgb.Pix = img.Surface.RGBA(rgb.Pix, 1920, 1080)
|
||||
rgb.Changed()
|
||||
})
|
||||
}
|
||||
|
||||
// BenchmarkVideoFrameNV12 draws a new 1920×1080 frame of video each frame
|
||||
// from its NV12 planes, as GStreamer leaves them: 3 MB uploaded, and
|
||||
// converted in the shader.
|
||||
func BenchmarkVideoFrameNV12(b *testing.B) {
|
||||
img := gputest.NV12Frame(1920, 1080, scene.BT709)
|
||||
s := videoBenchScene(img)
|
||||
benchVideo(b, s, img.Changed)
|
||||
}
|
||||
|
||||
func videoBenchScene(img *scene.Image) *scene.Scene {
|
||||
return &scene.Scene{Width: 1280, Height: 720, Clear: scene.Color{A: 255}, Ops: []scene.Op{{
|
||||
Kind: scene.OpImage, Rect: scene.Rect{W: 1280, H: 720}, Image: img, Src: scene.Rect{W: 1920, H: 1080},
|
||||
}}}
|
||||
}
|
||||
|
||||
func benchVideo(b *testing.B, s *scene.Scene, next func()) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
o, err := NewOffscreen(false, s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer o.Release()
|
||||
b.SetBytes(1920 * 1080 * 4)
|
||||
for b.Loop() {
|
||||
next()
|
||||
if _, err := o.Render(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Canvases draw into textures as the CPU renderer draws them into pixels,
|
||||
// shown the right way up although GL's rows go up, and once each.
|
||||
func TestCanvases(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.CanvasScene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
for frame := range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-canvas", read(), s.Width*4, s)
|
||||
if frame == 0 {
|
||||
s.Canvases = nil
|
||||
}
|
||||
}
|
||||
if len(r.canvases) != 3 {
|
||||
t.Errorf("%d canvas textures, want 3", len(r.canvases))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A transient canvas's texture stays while frames draw it, and goes once
|
||||
// they stop, though the canvas is still about; another canvas's stays
|
||||
// until it is collected.
|
||||
func TestTransientCanvas(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
offscreen(t, api.es, 64, 64)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
layer, kept := scene.NewCanvas(64, 64), scene.NewCanvas(64, 64)
|
||||
layer.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64, Canvases: []*scene.Image{layer, kept}}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] == nil || r.canvases[kept.ID()] == nil {
|
||||
t.Fatal("a sweep after the frame that drew them freed a canvas's texture")
|
||||
}
|
||||
r.frame++ // a frame that draws neither
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] != nil || r.canvases[kept.ID()] == nil {
|
||||
t.Errorf("transient canvas kept %v, other kept %v", r.canvases[layer.ID()] != nil, r.canvases[kept.ID()] != nil)
|
||||
}
|
||||
runtime.KeepAlive(layer)
|
||||
runtime.KeepAlive(kept)
|
||||
})
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestPartialFramesMatchWhole draws random scenes changing a little at a
|
||||
// time into a framebuffer that keeps what was drawn, as a GtkGLArea's,
|
||||
// each frame only where it changed, and requires the bytes of each frame
|
||||
// drawn whole, over an opaque color and a translucent one. Now and then
|
||||
// the framebuffer loses what it held, as GTK makes the area's buffers
|
||||
// anew, which Invalidate tells.
|
||||
func TestPartialFramesMatchWhole(t *testing.T) {
|
||||
seeds := uint64(12)
|
||||
if testing.Short() {
|
||||
seeds = 6
|
||||
}
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
read := offscreen(t, api.es, 320, 240)
|
||||
var outer int32
|
||||
glGetIntegerv(glFramebufferBinding, &outer)
|
||||
// The frames drawn whole go into a framebuffer of their own.
|
||||
tex := newTexture(glRGBA8, glRGBA, 320, 240, nil, 0)
|
||||
var fb uint32
|
||||
glGenFramebuffers(1, &fb)
|
||||
glBindFramebuffer(glFramebuffer, fb)
|
||||
glFramebufferTexture2D(glFramebuffer, glColorAttachment0, glTexture2D, tex, 0)
|
||||
defer func() {
|
||||
glDeleteFramebuffers(1, &fb)
|
||||
glDeleteTextures(1, &tex)
|
||||
}()
|
||||
frames, partial := 0, 0
|
||||
for seed := range seeds {
|
||||
m := gputest.NewChanging(seed)
|
||||
if seed%3 == 2 {
|
||||
m.Clear = scene.Color{R: 20, G: 40, B: 200, A: 77}
|
||||
}
|
||||
s := m.Scene()
|
||||
// Renderers of their own, as each scene has an atlas of its own.
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Partial = true
|
||||
whole, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for step := range 30 {
|
||||
what := "first"
|
||||
if step > 0 {
|
||||
what = m.Change(s)
|
||||
}
|
||||
if step%11 == 10 {
|
||||
// GTK made the buffers anew: what they hold is undefined.
|
||||
glBindFramebuffer(glFramebuffer, uint32(outer))
|
||||
glClearColor(1, 0, 1, 1)
|
||||
glClear(glColorBufferBit)
|
||||
r.Invalidate()
|
||||
what += ", invalidated"
|
||||
}
|
||||
glBindFramebuffer(glFramebuffer, uint32(outer))
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := read()
|
||||
frames++
|
||||
part := "whole"
|
||||
if r.redrew != redrewWhole {
|
||||
partial++
|
||||
part = r.part.String()
|
||||
}
|
||||
glBindFramebuffer(glFramebuffer, fb)
|
||||
if err := whole.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := read()
|
||||
if !bytes.Equal(got, want) {
|
||||
n := 0
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
t.Fatalf("seed %d, step %d (%s), redrew %s: %d bytes differ from the frame drawn whole", seed, step, what, part, n)
|
||||
}
|
||||
}
|
||||
r.Release()
|
||||
whole.Release()
|
||||
}
|
||||
if partial < frames/3 {
|
||||
t.Errorf("%d frames of %d drawn in part", partial, frames)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPartialFramesApart checks that two changes in opposite corners, a
|
||||
// spinner's and a progress bar's, redraw two rectangles, not all between,
|
||||
// and the bytes of the frame drawn whole.
|
||||
func TestPartialFramesApart(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
read := offscreen(t, api.es, 320, 240)
|
||||
s := gputest.NewChanging(5).Scene()
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 4, Y: 4, W: 12, H: 12}, Radii: scene.Uniform(6), Color: scene.Color{R: 200, A: 255}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 250, Y: 226, W: 60, H: 6}, Radii: scene.Uniform(3), Color: scene.Color{B: 200, A: 255}})
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
r.Partial = true
|
||||
whole, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer whole.Release()
|
||||
for step := range 4 {
|
||||
if step > 0 {
|
||||
n := len(s.Ops)
|
||||
s.Ops[n-2].Color.G += 60
|
||||
s.Ops[n-1].Rect.W -= 7
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := read()
|
||||
if step > 0 && (r.redrew != redrewPart || len(r.part.Rects) != 2) {
|
||||
t.Errorf("step %d redrew %v: %s", step, r.redrew, r.part.String())
|
||||
}
|
||||
if err := whole.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, read()) {
|
||||
t.Fatalf("step %d, redrew %s: differs from the frame drawn whole", step, r.part.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// The head and the tail of an effect's fragment shader (scene.Effect):
|
||||
// after shader.glsl with EFFECT defined, the head declares what an effect
|
||||
// reads, the effect's source follows, then the tail, after the line
|
||||
// "// effect", draws its instances with it.
|
||||
|
||||
uniform sampler2D uBackdrop;
|
||||
|
||||
// What an effect reads of its instance.
|
||||
struct Effect {
|
||||
vec4 rect; // x, y, width, height in pixels
|
||||
vec4 radii; // top-left, top-right, bottom-right, bottom-left, circular
|
||||
vec4 p0, p1, p2, p3, p4;
|
||||
vec4 area; // where the backdrop's area starts in the frame, and its size in texels
|
||||
float down; // the size of the squares the backdrop averages
|
||||
vec4 transform0, transform1, transform2;
|
||||
};
|
||||
|
||||
vec2 framePoint(Effect e, vec2 q) {
|
||||
vec3 h = vec3(dot(e.transform0.xyz, vec3(q, 1.0)), dot(e.transform1.xyz, vec3(q, 1.0)),
|
||||
dot(vec3(e.transform2.xy, 1.0 - 2.0 * e.transform2.z), vec3(q, 1.0)));
|
||||
return h.xy / h.z;
|
||||
}
|
||||
|
||||
vec3 backdropAt(ivec2 p, ivec2 size) { return texelFetch(uBackdrop, clamp(p, ivec2(0), size - 1), 0).rgb; }
|
||||
|
||||
// sampleBackdrop returns the backdrop at q, in the frame's pixels,
|
||||
// premultiplied, filtered bilinearly from its texels as
|
||||
// scene.BackdropImage.Sample does.
|
||||
vec3 sampleBackdrop(Effect e, vec2 q) {
|
||||
q = framePoint(e, q);
|
||||
vec2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
vec2 f = floor(u);
|
||||
vec2 w = u - f;
|
||||
ivec2 p = ivec2(f);
|
||||
ivec2 size = ivec2(e.area.zw);
|
||||
vec3 top = backdropAt(p, size) * (1.0 - w.x) + backdropAt(p + ivec2(1, 0), size) * w.x;
|
||||
vec3 bot = backdropAt(p + ivec2(0, 1), size) * (1.0 - w.x) + backdropAt(p + ivec2(1, 1), size) * w.x;
|
||||
return top * (1.0 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
// effect
|
||||
|
||||
void main() {
|
||||
Frame fr = frameOf();
|
||||
vec2 p = vPoint.xy;
|
||||
Effect e = Effect(vRect, abs(vRadii), vInner, vColor, vColor2, vBorder, vGrad, vWidths, vParams.z,
|
||||
vTransform0, vTransform1, vTransform2);
|
||||
if (vParams.y > 0.5) {
|
||||
// A mask glyph a shader fills (scene.EffectOp.Glyphs), as the
|
||||
// renderer's own shader draws one, its paint the shader's color.
|
||||
vec4 c = effect(p, e);
|
||||
float glyphCov = vTransform0.w > 0.5 ? localCoverage(p, vRect, vec4(0.0), 1.0, fr) : 1.0;
|
||||
fragColor = c * (textCoverage(sampleLocal(uMask, vPoint.zw, vWidths, vTransform0.w).r, unpremul(c), vInner.x,
|
||||
vInner.y, vRadii) *
|
||||
glyphCov * clipCoverage() * vParams.w);
|
||||
} else {
|
||||
fragColor = effect(p, e) * (localCoverage(p, vRect, vRadii, vTransform0.w, fr) * clipCoverage() * vParams.w);
|
||||
}
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// EGL's functions, which make the contexts of OpenGL ES and the surfaces
|
||||
// of the windows they draw into, on Android.
|
||||
var (
|
||||
eglGetDisplay func(id uintptr) uintptr
|
||||
eglInitialize func(display uintptr, major, minor *int32) uint32
|
||||
eglChooseConfig func(display uintptr, attribs *int32, configs *uintptr, size int32, n *int32) uint32
|
||||
eglCreateContext func(display, config, share uintptr, attribs *int32) uintptr
|
||||
eglCreateWindowSurface func(display, config, window uintptr, attribs *int32) uintptr
|
||||
eglMakeCurrent func(display, draw, read, context uintptr) uint32
|
||||
eglSwapBuffers func(display, surface uintptr) uint32
|
||||
eglDestroySurface func(display, surface uintptr) uint32
|
||||
eglDestroyContext func(display, context uintptr) uint32
|
||||
eglGetCurrentContext func() uintptr
|
||||
eglGetError func() int32
|
||||
)
|
||||
|
||||
const (
|
||||
eglNone = 0x3038
|
||||
eglRenderableType = 0x3040
|
||||
eglOpenGLES3Bit = 0x40
|
||||
eglSurfaceType = 0x3033
|
||||
eglWindowBit = 0x4
|
||||
eglRedSize = 0x3024
|
||||
eglGreenSize = 0x3023
|
||||
eglBlueSize = 0x3022
|
||||
eglAlphaSize = 0x3021
|
||||
eglContextVersion = 0x3098
|
||||
)
|
||||
|
||||
func loadEGL() error {
|
||||
lib, err := purego.Dlopen("libEGL.so", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gl: cannot load libEGL: %w", err)
|
||||
}
|
||||
for name, f := range map[string]any{
|
||||
"eglGetDisplay": &eglGetDisplay, "eglInitialize": &eglInitialize, "eglChooseConfig": &eglChooseConfig,
|
||||
"eglCreateContext": &eglCreateContext, "eglCreateWindowSurface": &eglCreateWindowSurface,
|
||||
"eglMakeCurrent": &eglMakeCurrent, "eglSwapBuffers": &eglSwapBuffers, "eglDestroySurface": &eglDestroySurface,
|
||||
"eglDestroyContext": &eglDestroyContext, "eglGetCurrentContext": &eglGetCurrentContext, "eglGetError": &eglGetError,
|
||||
} {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
return fmt.Errorf("gl: libEGL lacks %s", name)
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Window is a window's surface (an ANativeWindow) and the context of
|
||||
// OpenGL ES 3 that draws into it.
|
||||
type Window struct {
|
||||
display, context, surface uintptr
|
||||
}
|
||||
|
||||
// NewWindow makes a context and a surface for an ANativeWindow, the
|
||||
// context current.
|
||||
func NewWindow(native uintptr) (*Window, error) {
|
||||
if native == 0 {
|
||||
return nil, errors.New("gl: no window")
|
||||
}
|
||||
if err := load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w := &Window{display: eglGetDisplay(0)}
|
||||
if w.display == 0 || eglInitialize(w.display, nil, nil) == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL has no display (%#x)", eglGetError())
|
||||
}
|
||||
attribs := []int32{eglRenderableType, eglOpenGLES3Bit, eglSurfaceType, eglWindowBit,
|
||||
eglRedSize, 8, eglGreenSize, 8, eglBlueSize, 8, eglAlphaSize, 8, eglNone}
|
||||
var config uintptr
|
||||
var n int32
|
||||
if eglChooseConfig(w.display, &attribs[0], &config, 1, &n) == 0 || n == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL has no configuration of OpenGL ES 3 (%#x)", eglGetError())
|
||||
}
|
||||
ctxAttribs := []int32{eglContextVersion, 3, eglNone}
|
||||
if w.context = eglCreateContext(w.display, config, 0, &ctxAttribs[0]); w.context == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL cannot make a context (%#x)", eglGetError())
|
||||
}
|
||||
if w.surface = eglCreateWindowSurface(w.display, config, native, nil); w.surface == 0 {
|
||||
eglDestroyContext(w.display, w.context)
|
||||
return nil, fmt.Errorf("gl: EGL cannot make a window's surface (%#x)", eglGetError())
|
||||
}
|
||||
if !w.MakeCurrent() {
|
||||
w.Release()
|
||||
return nil, fmt.Errorf("gl: EGL cannot make the context current (%#x)", eglGetError())
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// MakeCurrent makes the window's context current on this thread, drawing
|
||||
// into its surface.
|
||||
func (w *Window) MakeCurrent() bool {
|
||||
return eglMakeCurrent(w.display, w.surface, w.surface, w.context) != 0
|
||||
}
|
||||
|
||||
// Swap shows the frame drawn into the surface.
|
||||
func (w *Window) Swap() error {
|
||||
if eglSwapBuffers(w.display, w.surface) == 0 {
|
||||
return fmt.Errorf("gl: EGL cannot show the frame (%#x)", eglGetError())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release lets go of the surface and the context; the ANativeWindow stays
|
||||
// its owner's.
|
||||
func (w *Window) Release() {
|
||||
if w.display == 0 {
|
||||
return
|
||||
}
|
||||
eglMakeCurrent(w.display, 0, 0, 0)
|
||||
if w.surface != 0 {
|
||||
eglDestroySurface(w.display, w.surface)
|
||||
}
|
||||
if w.context != 0 {
|
||||
eglDestroyContext(w.display, w.context)
|
||||
}
|
||||
*w = Window{}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// The shared builder's culling and scissors must preserve every pixel with
|
||||
// both GL APIs, including nested clip masks and canvases drawn into textures.
|
||||
func TestGeometryOptimizationsPreservePixels(t *testing.T) {
|
||||
type fixture struct {
|
||||
name string
|
||||
s *scene.Scene
|
||||
}
|
||||
var cases []fixture
|
||||
for _, c := range gputest.CullCases() {
|
||||
cases = append(cases, fixture{"cull/" + c.Name, c.Scene})
|
||||
}
|
||||
for _, c := range gputest.RingCases() {
|
||||
cases = append(cases, fixture{"ring/" + c.Name, c.Scene})
|
||||
}
|
||||
for i, c := range gputest.ShadowCases() {
|
||||
cases = append(cases, fixture{fmt.Sprintf("shadow/%d", i), gputest.ShadowPanelScene(c)})
|
||||
}
|
||||
for _, c := range gputest.MaskedCases() {
|
||||
cases = append(cases, fixture{"masked/" + c.Name, c.Scene})
|
||||
}
|
||||
cases = append(cases,
|
||||
fixture{"transformed", gputest.TransformedScene()},
|
||||
fixture{"perspective", gputest.PerspectiveScene()},
|
||||
fixture{"translated", gputest.TranslatedScenes()[0]},
|
||||
fixture{"translated-between-pixels", gputest.TranslatedScenes()[1]},
|
||||
fixture{"masked-clips", gputest.MaskedClipScene()},
|
||||
fixture{"corner-clips", gputest.CornerClipScene()},
|
||||
fixture{"wide-colors", gputest.WideScene()},
|
||||
fixture{"canvases", gputest.CanvasScene()},
|
||||
)
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
read := offscreen(t, api.es, c.s.Width, c.s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.Render(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := read()
|
||||
r.b.NoCull, r.b.NoShadowSplit, r.b.NoRingSplit = true, true, true
|
||||
for _, canvas := range r.canvases {
|
||||
canvas.b.NoCull, canvas.b.NoShadowSplit, canvas.b.NoRingSplit = true, true, true
|
||||
}
|
||||
// Render every canvas again under the reference policy, rather
|
||||
// than comparing against its already optimized cached texture.
|
||||
c.s.EachCanvas(func(img *scene.Image) { img.Changed() })
|
||||
if err := r.Render(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); !bytes.Equal(got, want) {
|
||||
t.Fatal("culling or split scissors changed pixels")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+1394
File diff suppressed because it is too large.
Load diff
+144
@@ -0,0 +1,144 @@
|
||||
//go:build js
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"slices"
|
||||
"syscall/js"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// canvas makes the WebGL 2 context of a w×h canvas current, or skips t
|
||||
// where there is no page (Node) or no WebGL 2. read returns its pixels as
|
||||
// the CPU renderer draws them.
|
||||
func canvas(t *testing.T, w, h int) (c *Context, read func() []byte) {
|
||||
doc := js.Global().Get("document")
|
||||
if doc.IsUndefined() {
|
||||
t.Skip("no page to draw in")
|
||||
}
|
||||
el := doc.Call("createElement", "canvas")
|
||||
el.Set("width", w)
|
||||
el.Set("height", h)
|
||||
c, err := NewContext(el)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
c.MakeCurrent()
|
||||
t.Log(versionString(), "dual-source blending:", c.dual)
|
||||
return c, func() []byte {
|
||||
pix, err := ReadFramebuffer(w, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pix
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebGLDrawsAsTheCPURenderer(t *testing.T) {
|
||||
// Browsers without WEBGL_blend_func_extended blend with one color,
|
||||
// which cannot cover the channels of subpixel glyphs apart: the text
|
||||
// of browsers has none (package text's canvas engine).
|
||||
for _, dual := range []bool{true, false} {
|
||||
name := "dual-source blending"
|
||||
if !dual {
|
||||
name = "one color"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
if !dual {
|
||||
withoutSubpixelGlyphs(s)
|
||||
}
|
||||
c, read := canvas(t, s.Width, s.Height)
|
||||
if dual && !c.dual {
|
||||
t.Skip("no WEBGL_blend_func_extended")
|
||||
}
|
||||
c.dual = dual
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if !r.es || r.dual != dual {
|
||||
t.Fatalf("the renderer takes WebGL 2 for OpenGL ES %v, with dual-source blending %v", r.es, r.dual)
|
||||
}
|
||||
// Twice: the second frame updates what the first uploaded.
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "webgl", read(), s.Width*4, s)
|
||||
}
|
||||
for name, s := range map[string]*scene.Scene{"webgl-affine": gputest.TransformedScene(), "webgl-perspective": gputest.PerspectiveScene(), "webgl-behind-origin": gputest.BehindOriginScene(), "webgl-masked-clips": gputest.MaskedClipScene(), "webgl-corner-clips": gputest.CornerClipScene()} {
|
||||
if !dual {
|
||||
withoutSubpixelGlyphs(s)
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, name, read(), s.Width*4, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebGLPresentsFramesDrawnInMemory(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
_, read := canvas(t, s.Width, s.Height)
|
||||
want := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(want, s)
|
||||
var p Presenter
|
||||
// Twice: the second frame reuses the texture.
|
||||
for range 2 {
|
||||
if err := p.Present(want.Pix, want.Stride, want.W, want.H); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); !bytes.Equal(got, want.Pix[:len(got)]) {
|
||||
t.Fatal("the frame presented differs from the frame drawn")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A renewed context, as after the browser restored a lost one, has the
|
||||
// renderer make its objects again.
|
||||
func TestWebGLRenewedContext(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
c, read := canvas(t, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Renew()
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "webgl-renewed", read(), s.Width*4, s)
|
||||
}
|
||||
|
||||
// withoutSubpixelGlyphs leaves the subpixel glyphs out of s.
|
||||
func withoutSubpixelGlyphs(s *scene.Scene) {
|
||||
ops := s.Ops[:0]
|
||||
for _, op := range s.Ops {
|
||||
if op.Kind == scene.OpGlyphs {
|
||||
gs := s.Glyphs[op.Start:op.End]
|
||||
if !slices.ContainsFunc(gs, func(g scene.Glyph) bool { return !g.Subpixel }) {
|
||||
continue
|
||||
}
|
||||
for i := range gs {
|
||||
if gs[i].Subpixel {
|
||||
gs[i].Color = scene.Color{}
|
||||
}
|
||||
}
|
||||
}
|
||||
ops = append(ops, op)
|
||||
}
|
||||
s.Ops = ops
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
)
|
||||
|
||||
// apis are the APIs the renderer draws with: OpenGL 3.3 and OpenGL ES 3.0.
|
||||
var apis = []struct {
|
||||
name string
|
||||
es bool
|
||||
}{{"OpenGL", false}, {"OpenGL ES", true}}
|
||||
|
||||
// offscreen makes a context current on the calling thread, without a
|
||||
// window, with a framebuffer of w×h pixels (see Offscreen), or skips t.
|
||||
// read returns its pixels as the CPU renderer draws them.
|
||||
func offscreen(t *testing.T, es bool, w, h int) (read func() []byte) {
|
||||
runtime.LockOSThread()
|
||||
t.Cleanup(runtime.UnlockOSThread)
|
||||
o, err := NewOffscreen(es, w, h)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Cleanup(o.Release)
|
||||
t.Log(o.Info())
|
||||
return func() []byte {
|
||||
pix, err := ReadFramebuffer(w, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pix
|
||||
}
|
||||
}
|
||||
|
||||
func TestDrawsAsTheCPURenderer(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if r.es != api.es {
|
||||
t.Fatalf("the renderer takes the context for OpenGL ES: %v", r.es)
|
||||
}
|
||||
// Twice: the second frame updates what the first uploaded.
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl", read(), s.Width*4, s)
|
||||
}
|
||||
|
||||
s = gputest.TransformedScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-affine", read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.PerspectiveScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-perspective", read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.BehindOriginScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix := read()
|
||||
gputest.Compare(t, "gl-behind-origin", pix, s.Width*4, s)
|
||||
if p := pix[370*s.Width*4+160*4:][:4]; p[1] > 100 {
|
||||
t.Errorf("the card turned far from its origin does not show: %v at its center", p)
|
||||
}
|
||||
}
|
||||
for i, s := range gputest.TranslatedScenes() {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-translated"+[]string{"", "-between-pixels"}[i], read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.MaskedClipScene()
|
||||
// Twice: the second frame finds the clips' masks it made.
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-masked-clips", read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.CornerClipScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-corner-clips", read(), s.Width*4, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBorderedCardDrawsAsTheCPURenderer draws the card of #531 (a large
|
||||
// opaque card with a border of 2 pixels at scale 2, and a small button like
|
||||
// it) with round corners, as OpenGL draws continuous ones, and requires the
|
||||
// CPU renderer's pixels along their straight edges, exactly.
|
||||
func TestBorderedCardDrawsAsTheCPURenderer(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.BorderedCardScene(false)
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.CompareStraightEdges(t, "gl-bordered-card", read(), s.Width*4, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresentsFramesDrawnInMemory(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
want := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(want, s)
|
||||
var p Presenter
|
||||
// Twice: the second frame reuses the texture.
|
||||
for range 2 {
|
||||
if err := p.Present(want.Pix, want.Stride, want.W, want.H); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); !bytes.Equal(got, want.Pix[:len(got)]) {
|
||||
t.Fatal("the frame presented differs from the frame drawn")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDrawsVideoAsTheCPURenderer draws frames of video in NV12 from their
|
||||
// planes, which the shader converts as the CPU renderer does.
|
||||
func TestDrawsVideoAsTheCPURenderer(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.VideoScene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
// Twice: the second frame updates the planes in place.
|
||||
for i := range 2 {
|
||||
for _, op := range s.Ops {
|
||||
op.Image.Changed()
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-video", read(), s.Width*4, s)
|
||||
if i == 0 {
|
||||
for _, op := range s.Ops {
|
||||
if t := r.images[op.Image.ID()]; t == nil || t.chroma == 0 {
|
||||
panic("a frame of video drew from RGBA, not its planes")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
package gl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// The functions of OpenGL ES 3 this package calls, from Android's
|
||||
// libGLESv3, and EGL's, which makes the contexts (egl_android.go).
|
||||
var (
|
||||
loadOnce sync.Once
|
||||
errLoad error
|
||||
|
||||
glGetString func(name uint32) uintptr
|
||||
glGetError func() uint32
|
||||
glGetIntegerv func(name uint32, data *int32)
|
||||
glCreateShader func(typ uint32) uint32
|
||||
glShaderSource func(shader uint32, count int32, sources **byte, lengths *int32)
|
||||
glCompileShader func(shader uint32)
|
||||
glGetShaderiv func(shader, name uint32, out *int32)
|
||||
glGetShaderInfoLog func(shader uint32, size int32, length *int32, log *byte)
|
||||
glDeleteShader func(shader uint32)
|
||||
glCreateProgram func() uint32
|
||||
glAttachShader func(program, shader uint32)
|
||||
glLinkProgram func(program uint32)
|
||||
glGetProgramiv func(program, name uint32, out *int32)
|
||||
glGetProgramInfoLog func(program uint32, size int32, length *int32, log *byte)
|
||||
glUseProgram func(program uint32)
|
||||
glDeleteProgram func(program uint32)
|
||||
glGetUniformLocation func(program uint32, name string) int32
|
||||
glGetUniformBlockIndex func(program uint32, name string) uint32
|
||||
glUniformBlockBinding func(program, index, binding uint32)
|
||||
glBindBufferBase func(target, index, buffer uint32)
|
||||
glUniform1i func(location, v int32)
|
||||
glUniform2f func(location int32, x, y float32)
|
||||
glUniform1f func(location int32, v float32)
|
||||
glUniform2i func(location, x, y int32)
|
||||
glUniform4i func(location, x, y, z, w int32)
|
||||
glCopyTexSubImage2D func(target uint32, level, xoff, yoff, x, y, w, h int32)
|
||||
glGenVertexArrays func(n int32, out *uint32)
|
||||
glBindVertexArray func(array uint32)
|
||||
glDeleteVertexArrays func(n int32, arrays *uint32)
|
||||
glGenBuffers func(n int32, out *uint32)
|
||||
glBindBuffer func(target, buffer uint32)
|
||||
glBufferData func(target uint32, size int, data unsafe.Pointer, usage uint32)
|
||||
glDeleteBuffers func(n int32, buffers *uint32)
|
||||
glEnableVertexAttrib func(index uint32)
|
||||
glVertexAttribPointer func(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr)
|
||||
glVertexAttribDivisor func(index, divisor uint32)
|
||||
glGenTextures func(n int32, out *uint32)
|
||||
glBindTexture func(target, texture uint32)
|
||||
glActiveTexture func(unit uint32)
|
||||
glTexImage2D func(target uint32, level, internalFormat, w, h, border int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexSubImage2D func(target uint32, level, x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexParameteri func(target, name uint32, v int32)
|
||||
glDeleteTextures func(n int32, textures *uint32)
|
||||
glPixelStorei func(name uint32, v int32)
|
||||
glViewport func(x, y, w, h int32)
|
||||
glScissor func(x, y, w, h int32)
|
||||
glEnable func(cap uint32)
|
||||
glDisable func(cap uint32)
|
||||
glBlendFunc func(src, dst uint32)
|
||||
glBlendFuncSeparate func(srcRGB, dstRGB, srcAlpha, dstAlpha uint32)
|
||||
glClearColor func(r, g, b, a float32)
|
||||
glClear func(mask uint32)
|
||||
glDrawArraysInstanced func(mode uint32, first, count, instances int32)
|
||||
glReadPixels func(x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glGenFramebuffers func(n int32, out *uint32)
|
||||
glBindFramebuffer func(target, fb uint32)
|
||||
glFramebufferTexture2D func(target, attachment, texTarget, texture uint32, level int32)
|
||||
glCheckFramebufferState func(target uint32) uint32
|
||||
glDeleteFramebuffers func(n int32, fbs *uint32)
|
||||
glBlitFramebuffer func(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1 int32, mask, filter uint32)
|
||||
)
|
||||
|
||||
// glExtensions is GL_EXTENSIONS, for glGetString.
|
||||
const glExtensions = 0x1F03
|
||||
|
||||
func load() error {
|
||||
loadOnce.Do(func() {
|
||||
lib, err := purego.Dlopen("libGLESv3.so", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
errLoad = fmt.Errorf("gl: cannot load libGLESv3: %w", err)
|
||||
return
|
||||
}
|
||||
var missing []string
|
||||
gl := func(f any, name string) {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
missing = append(missing, name)
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
gl(&glGetString, "glGetString")
|
||||
gl(&glGetError, "glGetError")
|
||||
gl(&glGetIntegerv, "glGetIntegerv")
|
||||
gl(&glCreateShader, "glCreateShader")
|
||||
gl(&glShaderSource, "glShaderSource")
|
||||
gl(&glCompileShader, "glCompileShader")
|
||||
gl(&glGetShaderiv, "glGetShaderiv")
|
||||
gl(&glGetShaderInfoLog, "glGetShaderInfoLog")
|
||||
gl(&glDeleteShader, "glDeleteShader")
|
||||
gl(&glCreateProgram, "glCreateProgram")
|
||||
gl(&glAttachShader, "glAttachShader")
|
||||
gl(&glLinkProgram, "glLinkProgram")
|
||||
gl(&glGetProgramiv, "glGetProgramiv")
|
||||
gl(&glGetProgramInfoLog, "glGetProgramInfoLog")
|
||||
gl(&glUseProgram, "glUseProgram")
|
||||
gl(&glDeleteProgram, "glDeleteProgram")
|
||||
gl(&glGetUniformLocation, "glGetUniformLocation")
|
||||
gl(&glGetUniformBlockIndex, "glGetUniformBlockIndex")
|
||||
gl(&glUniformBlockBinding, "glUniformBlockBinding")
|
||||
gl(&glBindBufferBase, "glBindBufferBase")
|
||||
gl(&glUniform1i, "glUniform1i")
|
||||
gl(&glUniform2f, "glUniform2f")
|
||||
gl(&glUniform1f, "glUniform1f")
|
||||
gl(&glUniform2i, "glUniform2i")
|
||||
gl(&glUniform4i, "glUniform4i")
|
||||
gl(&glCopyTexSubImage2D, "glCopyTexSubImage2D")
|
||||
gl(&glGenVertexArrays, "glGenVertexArrays")
|
||||
gl(&glBindVertexArray, "glBindVertexArray")
|
||||
gl(&glDeleteVertexArrays, "glDeleteVertexArrays")
|
||||
gl(&glGenBuffers, "glGenBuffers")
|
||||
gl(&glBindBuffer, "glBindBuffer")
|
||||
gl(&glBufferData, "glBufferData")
|
||||
gl(&glDeleteBuffers, "glDeleteBuffers")
|
||||
gl(&glEnableVertexAttrib, "glEnableVertexAttribArray")
|
||||
gl(&glVertexAttribPointer, "glVertexAttribPointer")
|
||||
gl(&glVertexAttribDivisor, "glVertexAttribDivisor")
|
||||
gl(&glGenTextures, "glGenTextures")
|
||||
gl(&glBindTexture, "glBindTexture")
|
||||
gl(&glActiveTexture, "glActiveTexture")
|
||||
gl(&glTexImage2D, "glTexImage2D")
|
||||
gl(&glTexSubImage2D, "glTexSubImage2D")
|
||||
gl(&glTexParameteri, "glTexParameteri")
|
||||
gl(&glDeleteTextures, "glDeleteTextures")
|
||||
gl(&glPixelStorei, "glPixelStorei")
|
||||
gl(&glViewport, "glViewport")
|
||||
gl(&glScissor, "glScissor")
|
||||
gl(&glEnable, "glEnable")
|
||||
gl(&glDisable, "glDisable")
|
||||
gl(&glBlendFunc, "glBlendFunc")
|
||||
gl(&glBlendFuncSeparate, "glBlendFuncSeparate")
|
||||
gl(&glClearColor, "glClearColor")
|
||||
gl(&glClear, "glClear")
|
||||
gl(&glDrawArraysInstanced, "glDrawArraysInstanced")
|
||||
gl(&glReadPixels, "glReadPixels")
|
||||
gl(&glGenFramebuffers, "glGenFramebuffers")
|
||||
gl(&glBindFramebuffer, "glBindFramebuffer")
|
||||
gl(&glFramebufferTexture2D, "glFramebufferTexture2D")
|
||||
gl(&glCheckFramebufferState, "glCheckFramebufferStatus")
|
||||
gl(&glDeleteFramebuffers, "glDeleteFramebuffers")
|
||||
gl(&glBlitFramebuffer, "glBlitFramebuffer")
|
||||
if len(missing) > 0 {
|
||||
errLoad = fmt.Errorf("gl: libGLESv3 lacks %s", strings.Join(missing, ", "))
|
||||
return
|
||||
}
|
||||
errLoad = loadEGL()
|
||||
})
|
||||
return errLoad
|
||||
}
|
||||
|
||||
func currentContext() uintptr {
|
||||
if eglGetCurrentContext == nil {
|
||||
return 0
|
||||
}
|
||||
return eglGetCurrentContext()
|
||||
}
|
||||
|
||||
func goString(p uintptr) string {
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
var b []byte
|
||||
for i := uintptr(0); ; i++ {
|
||||
c := *(*byte)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&p)), i))
|
||||
if c == 0 {
|
||||
return string(b)
|
||||
}
|
||||
b = append(b, c)
|
||||
}
|
||||
}
|
||||
|
||||
// contextVersion returns the version of the current context, major × 10 +
|
||||
// minor: always OpenGL ES on Android, as "OpenGL ES 3.2 ...".
|
||||
func contextVersion() (version int32, es bool) {
|
||||
v := strings.TrimPrefix(versionString(), "OpenGL ES ")
|
||||
var major, minor int32
|
||||
fmt.Sscanf(v, "%d.%d", &major, &minor)
|
||||
return major*10 + minor, true
|
||||
}
|
||||
|
||||
// hasExtension reports whether the current context has an extension.
|
||||
func hasExtension(name string) bool {
|
||||
for _, e := range strings.Fields(goString(glGetString(glExtensions))) {
|
||||
if e == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// hasContext reports whether a context is current.
|
||||
func hasContext() bool { return currentContext() != 0 }
|
||||
|
||||
// versionString describes the current context's version, for errors.
|
||||
func versionString() string { return goString(glGetString(glVersion)) }
|
||||
|
||||
// rendererString names the current context's renderer.
|
||||
func rendererString() string { return goString(glGetString(glRenderer)) }
|
||||
|
||||
// setShaderSource sets the source of a shader.
|
||||
func setShaderSource(s uint32, src string) {
|
||||
b := append([]byte(src), 0)
|
||||
p := &b[0]
|
||||
glShaderSource(s, 1, &p, nil)
|
||||
}
|
||||
|
||||
// shaderLog and programLog return what compiling a shader or linking a
|
||||
// program logged.
|
||||
func shaderLog(s uint32) string { return infoLog(s, glGetShaderiv, glGetShaderInfoLog) }
|
||||
func programLog(p uint32) string { return infoLog(p, glGetProgramiv, glGetProgramInfoLog) }
|
||||
|
||||
func infoLog(obj uint32, get func(uint32, uint32, *int32), read func(uint32, int32, *int32, *byte)) string {
|
||||
var n int32
|
||||
get(obj, glInfoLogLength, &n)
|
||||
if n <= 1 {
|
||||
return "no log"
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
read(obj, n, nil, &buf[0])
|
||||
return strings.TrimSpace(string(buf[:n-1]))
|
||||
}
|
||||
|
||||
// uploadElement is for browsers' video elements, which Android has none of.
|
||||
func uploadElement(uintptr) bool { return false }
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
//go:build js
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"syscall/js"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/media"
|
||||
)
|
||||
|
||||
// Context is the WebGL 2 context of a canvas, which renderers draw with
|
||||
// while it is current (MakeCurrent), as a GL context on Linux. WebGL names
|
||||
// its objects by JavaScript objects, GL by numbers: the package numbers
|
||||
// them, and the functions GL's renderer calls (glCreateShader, …) take and
|
||||
// return those numbers.
|
||||
type Context struct {
|
||||
v js.Value
|
||||
id uintptr
|
||||
// dual tells that the context has WEBGL_blend_func_extended, enabled.
|
||||
dual bool
|
||||
// The pixel store's unpacking, which uploads read Go's pixels by.
|
||||
unpackAlign, unpackRow int32
|
||||
// scratch is a Uint8Array that Go's bytes are copied into for WebGL
|
||||
// to read, grown as needed.
|
||||
scratch js.Value
|
||||
size int
|
||||
}
|
||||
|
||||
var (
|
||||
// cur is the current context.
|
||||
cur *Context
|
||||
// objects are the WebGL objects by their numbers, which their
|
||||
// property objectKey holds too; locations the uniform locations.
|
||||
objects = map[uint32]js.Value{}
|
||||
locations = []js.Value{}
|
||||
lastName uint32
|
||||
lastID uintptr
|
||||
// errLoad is load's error on Linux; the browser has nothing to load.
|
||||
errLoad error
|
||||
)
|
||||
|
||||
// objectKey is the property of a WebGL object holding its number.
|
||||
const objectKey = "__mygo"
|
||||
|
||||
// NewContext makes the WebGL 2 context of canvas, which draws premultiplied
|
||||
// colors without depth, stencil or antialiasing, as frames need: the
|
||||
// renderer cuts shapes' edges itself. Its drawing buffer keeps what was
|
||||
// drawn, so that frames draw only what changed (Renderer.Partial). It
|
||||
// fails where the browser has no WebGL 2, or will not make a context for
|
||||
// the canvas.
|
||||
func NewContext(canvas js.Value) (*Context, error) {
|
||||
attrs := map[string]any{
|
||||
"alpha": true, "premultipliedAlpha": true, "antialias": false, "depth": false, "stencil": false,
|
||||
"preserveDrawingBuffer": true, "powerPreference": "default",
|
||||
}
|
||||
v := canvas.Call("getContext", "webgl2", attrs)
|
||||
if v.IsNull() || v.IsUndefined() {
|
||||
return nil, errors.New("gl: the browser has no WebGL 2")
|
||||
}
|
||||
c := &Context{v: v, unpackAlign: 4}
|
||||
c.Renew()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Renew numbers the context anew, as after the browser restored it once it
|
||||
// was lost: renderers then make their objects again, the old ones gone
|
||||
// with the context.
|
||||
func (c *Context) Renew() {
|
||||
lastID++
|
||||
c.id = lastID
|
||||
c.dual = !c.v.Call("getExtension", "WEBGL_blend_func_extended").IsNull()
|
||||
c.unpackAlign, c.unpackRow = 4, 0
|
||||
}
|
||||
|
||||
// ID returns the context's number, which changes with Renew.
|
||||
func (c *Context) ID() uintptr { return c.id }
|
||||
|
||||
// Lost reports whether the browser took the context away.
|
||||
func (c *Context) Lost() bool { return c.v.Call("isContextLost").Bool() }
|
||||
|
||||
// MakeCurrent makes c the context renderers draw with.
|
||||
func (c *Context) MakeCurrent() { cur = c }
|
||||
|
||||
func load() error {
|
||||
if cur == nil {
|
||||
return errors.New("gl: no WebGL context is current")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func currentContext() uintptr {
|
||||
if cur == nil {
|
||||
return 0
|
||||
}
|
||||
return cur.id
|
||||
}
|
||||
|
||||
func hasContext() bool { return cur != nil }
|
||||
|
||||
func contextVersion() (version int32, es bool) { return 30, true }
|
||||
|
||||
func hasExtension(name string) bool {
|
||||
return name == "GL_EXT_blend_func_extended" && cur.dual
|
||||
}
|
||||
|
||||
func versionString() string { return cur.v.Call("getParameter", glVersion).String() }
|
||||
|
||||
// rendererString names the context's renderer: as the browser names it
|
||||
// (Firefox, the GPU's, sanitized), or, where that is WebGL's own name
|
||||
// (Chrome and Safari), as the GPU's driver does, should the browser tell
|
||||
// (WEBGL_debug_renderer_info, which Firefox deprecates).
|
||||
func rendererString() string {
|
||||
const unmaskedRenderer = 0x9246
|
||||
name := cur.v.Call("getParameter", glRenderer).String()
|
||||
if name == "WebKit WebGL" && !cur.v.Call("getExtension", "WEBGL_debug_renderer_info").IsNull() {
|
||||
if v := cur.v.Call("getParameter", unmaskedRenderer); v.Type() == js.TypeString {
|
||||
return v.String()
|
||||
}
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func call(name string, args ...any) js.Value { return cur.v.Call(name, args...) }
|
||||
|
||||
// name numbers a new WebGL object.
|
||||
func name(v js.Value) uint32 {
|
||||
if v.IsNull() {
|
||||
return 0
|
||||
}
|
||||
lastName++
|
||||
objects[lastName] = v
|
||||
v.Set(objectKey, lastName)
|
||||
return lastName
|
||||
}
|
||||
|
||||
// object returns the WebGL object of a number, null for 0.
|
||||
func object(n uint32) js.Value {
|
||||
if n == 0 {
|
||||
return js.Null()
|
||||
}
|
||||
if v, ok := objects[n]; ok {
|
||||
return v
|
||||
}
|
||||
return js.Null()
|
||||
}
|
||||
|
||||
// number returns the number of a WebGL object, 0 for null.
|
||||
func number(v js.Value) uint32 {
|
||||
if v.IsNull() || v.IsUndefined() {
|
||||
return 0
|
||||
}
|
||||
return uint32(v.Get(objectKey).Int())
|
||||
}
|
||||
|
||||
func deleteObjects(fn string, n int32, names *uint32) {
|
||||
for _, k := range unsafe.Slice(names, n) {
|
||||
if v, ok := objects[k]; ok {
|
||||
call(fn, v)
|
||||
delete(objects, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func genObjects(fn string, n int32, out *uint32) {
|
||||
names := unsafe.Slice(out, n)
|
||||
for i := range names {
|
||||
names[i] = name(call(fn))
|
||||
}
|
||||
}
|
||||
|
||||
// jsBytes copies n bytes at p into the scratch array, for WebGL to read.
|
||||
func jsBytes(p unsafe.Pointer, n int) js.Value {
|
||||
c := cur
|
||||
if c.size < n {
|
||||
c.size = max(n, 2*c.size, 1<<16)
|
||||
c.scratch = js.Global().Get("Uint8Array").New(c.size)
|
||||
}
|
||||
js.CopyBytesToJS(c.scratch, unsafe.Slice((*byte)(p), n))
|
||||
return c.scratch
|
||||
}
|
||||
|
||||
// uploadSize returns how many bytes an upload of w×h pixels reads, with
|
||||
// the pixel store's unpacking.
|
||||
func uploadSize(w, h int32, format uint32) int {
|
||||
bpp := int32(4)
|
||||
switch format {
|
||||
case glRed:
|
||||
bpp = 1
|
||||
case glRG:
|
||||
bpp = 2
|
||||
}
|
||||
row := w
|
||||
if cur.unpackRow > 0 {
|
||||
row = cur.unpackRow
|
||||
}
|
||||
a := cur.unpackAlign
|
||||
stride := (row*bpp + a - 1) / a * a
|
||||
return int((h-1)*stride + w*bpp)
|
||||
}
|
||||
|
||||
func setShaderSource(s uint32, src string) { call("shaderSource", object(s), src) }
|
||||
|
||||
func shaderLog(s uint32) string { return call("getShaderInfoLog", object(s)).String() }
|
||||
func programLog(p uint32) string { return call("getProgramInfoLog", object(p)).String() }
|
||||
|
||||
func glGetError() uint32 { return uint32(call("getError").Int()) }
|
||||
|
||||
func glGetIntegerv(param uint32, data *int32) {
|
||||
v := call("getParameter", param)
|
||||
switch param {
|
||||
case glFramebufferBinding:
|
||||
*data = int32(number(v))
|
||||
default:
|
||||
*data = int32(v.Int())
|
||||
}
|
||||
}
|
||||
|
||||
func glCreateShader(typ uint32) uint32 { return name(call("createShader", typ)) }
|
||||
func glCompileShader(s uint32) { call("compileShader", object(s)) }
|
||||
func glDeleteShader(s uint32) { deleteObjects("deleteShader", 1, &s) }
|
||||
|
||||
func glGetShaderiv(s, param uint32, out *int32) {
|
||||
*out = boolInt(call("getShaderParameter", object(s), param).Truthy())
|
||||
}
|
||||
|
||||
func glCreateProgram() uint32 { return name(call("createProgram")) }
|
||||
func glAttachShader(program, s uint32) { call("attachShader", object(program), object(s)) }
|
||||
func glLinkProgram(program uint32) { call("linkProgram", object(program)) }
|
||||
func glUseProgram(program uint32) { call("useProgram", object(program)) }
|
||||
func glDeleteProgram(program uint32) { deleteObjects("deleteProgram", 1, &program) }
|
||||
func glBindVertexArray(array uint32) { call("bindVertexArray", object(array)) }
|
||||
func glBindBuffer(target, buffer uint32) { call("bindBuffer", target, object(buffer)) }
|
||||
|
||||
func glGetProgramiv(program, param uint32, out *int32) {
|
||||
*out = boolInt(call("getProgramParameter", object(program), param).Truthy())
|
||||
}
|
||||
|
||||
func glGetUniformLocation(program uint32, uniform string) int32 {
|
||||
v := call("getUniformLocation", object(program), uniform)
|
||||
if v.IsNull() {
|
||||
return -1
|
||||
}
|
||||
locations = append(locations, v)
|
||||
return int32(len(locations) - 1)
|
||||
}
|
||||
|
||||
func glGetUniformBlockIndex(program uint32, block string) uint32 {
|
||||
return uint32(call("getUniformBlockIndex", object(program), block).Int())
|
||||
}
|
||||
|
||||
func glUniformBlockBinding(program, index, binding uint32) {
|
||||
call("uniformBlockBinding", object(program), index, binding)
|
||||
}
|
||||
|
||||
func glBindBufferBase(target, index, buffer uint32) {
|
||||
call("bindBufferBase", target, index, object(buffer))
|
||||
}
|
||||
|
||||
func location(l int32) js.Value {
|
||||
if l < 0 || int(l) >= len(locations) {
|
||||
return js.Null()
|
||||
}
|
||||
return locations[l]
|
||||
}
|
||||
|
||||
func glUniform1i(l, v int32) { call("uniform1i", location(l), v) }
|
||||
func glUniform2f(l int32, x, y float32) { call("uniform2f", location(l), x, y) }
|
||||
func glUniform1f(l int32, v float32) { call("uniform1f", location(l), v) }
|
||||
func glUniform2i(l, x, y int32) { call("uniform2i", location(l), x, y) }
|
||||
func glUniform4i(l, x, y, z, w int32) { call("uniform4i", location(l), x, y, z, w) }
|
||||
|
||||
func glCopyTexSubImage2D(target uint32, level, xoff, yoff, x, y, w, h int32) {
|
||||
call("copyTexSubImage2D", target, level, xoff, yoff, x, y, w, h)
|
||||
}
|
||||
|
||||
func glGenVertexArrays(n int32, out *uint32) { genObjects("createVertexArray", n, out) }
|
||||
func glDeleteVertexArrays(n int32, arrays *uint32) { deleteObjects("deleteVertexArray", n, arrays) }
|
||||
func glGenBuffers(n int32, out *uint32) { genObjects("createBuffer", n, out) }
|
||||
func glDeleteBuffers(n int32, buffers *uint32) { deleteObjects("deleteBuffer", n, buffers) }
|
||||
func glGenTextures(n int32, out *uint32) { genObjects("createTexture", n, out) }
|
||||
func glDeleteTextures(n int32, textures *uint32) { deleteObjects("deleteTexture", n, textures) }
|
||||
func glGenFramebuffers(n int32, out *uint32) { genObjects("createFramebuffer", n, out) }
|
||||
func glDeleteFramebuffers(n int32, fbs *uint32) { deleteObjects("deleteFramebuffer", n, fbs) }
|
||||
|
||||
func glBufferData(target uint32, size int, data unsafe.Pointer, usage uint32) {
|
||||
if data == nil {
|
||||
call("bufferData", target, size, usage)
|
||||
return
|
||||
}
|
||||
call("bufferData", target, jsBytes(data, size), usage, 0, size)
|
||||
}
|
||||
|
||||
func glEnableVertexAttrib(index uint32) { call("enableVertexAttribArray", index) }
|
||||
|
||||
func glVertexAttribPointer(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr) {
|
||||
call("vertexAttribPointer", index, size, typ, normalized, stride, offset)
|
||||
}
|
||||
|
||||
func glVertexAttribDivisor(index, divisor uint32) { call("vertexAttribDivisor", index, divisor) }
|
||||
func glBindTexture(target, texture uint32) { call("bindTexture", target, object(texture)) }
|
||||
func glActiveTexture(unit uint32) { call("activeTexture", unit) }
|
||||
|
||||
func glTexImage2D(target uint32, level, internalFormat, w, h, border int32, format, typ uint32, pix unsafe.Pointer) {
|
||||
if pix == nil {
|
||||
call("texImage2D", target, level, internalFormat, w, h, border, format, typ, js.Null())
|
||||
return
|
||||
}
|
||||
call("texImage2D", target, level, internalFormat, w, h, border, format, typ, jsPixels(pix, w, h, format, typ), 0)
|
||||
}
|
||||
|
||||
func glTexSubImage2D(target uint32, level, x, y, w, h int32, format, typ uint32, pix unsafe.Pointer) {
|
||||
call("texSubImage2D", target, level, x, y, w, h, format, typ, jsPixels(pix, w, h, format, typ), 0)
|
||||
}
|
||||
|
||||
// jsPixels returns the pixels of an upload as WebGL takes them: bytes, or
|
||||
// for floats (glFloat) a Float32Array over them.
|
||||
func jsPixels(pix unsafe.Pointer, w, h int32, format, typ uint32) js.Value {
|
||||
n := uploadSize(w, h, format)
|
||||
if typ != glFloat {
|
||||
return jsBytes(pix, n)
|
||||
}
|
||||
b := jsBytes(pix, 4*n)
|
||||
return js.Global().Get("Float32Array").New(b.Get("buffer"), 0, n)
|
||||
}
|
||||
|
||||
func glTexParameteri(target, param uint32, v int32) { call("texParameteri", target, param, v) }
|
||||
|
||||
func glPixelStorei(param uint32, v int32) {
|
||||
switch param {
|
||||
case glUnpackAlignment:
|
||||
cur.unpackAlign = v
|
||||
case glUnpackRowLength:
|
||||
cur.unpackRow = v
|
||||
}
|
||||
call("pixelStorei", param, v)
|
||||
}
|
||||
|
||||
func glViewport(x, y, w, h int32) { call("viewport", x, y, w, h) }
|
||||
func glScissor(x, y, w, h int32) { call("scissor", x, y, w, h) }
|
||||
func glEnable(capability uint32) { call("enable", capability) }
|
||||
func glDisable(capability uint32) { call("disable", capability) }
|
||||
func glBlendFunc(src, dst uint32) { call("blendFunc", src, dst) }
|
||||
func glClearColor(r, g, b, a float32) { call("clearColor", r, g, b, a) }
|
||||
func glClear(mask uint32) { call("clear", mask) }
|
||||
func glBindFramebuffer(target, fb uint32) { call("bindFramebuffer", target, object(fb)) }
|
||||
func glCheckFramebufferState(target uint32) uint32 {
|
||||
return uint32(call("checkFramebufferStatus", target).Int())
|
||||
}
|
||||
|
||||
func glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha uint32) {
|
||||
call("blendFuncSeparate", srcRGB, dstRGB, srcAlpha, dstAlpha)
|
||||
}
|
||||
|
||||
func glDrawArraysInstanced(mode uint32, first, count, instances int32) {
|
||||
call("drawArraysInstanced", mode, first, count, instances)
|
||||
}
|
||||
|
||||
func glReadPixels(x, y, w, h int32, format, typ uint32, pix unsafe.Pointer) {
|
||||
bpp := int32(4)
|
||||
if format == glRed {
|
||||
bpp = 1
|
||||
}
|
||||
n := int(w * h * bpp)
|
||||
arr := js.Global().Get("Uint8Array").New(n)
|
||||
call("readPixels", x, y, w, h, format, typ, arr)
|
||||
js.CopyBytesToGo(unsafe.Slice((*byte)(pix), n), arr)
|
||||
}
|
||||
|
||||
func glFramebufferTexture2D(target, attachment, texTarget, texture uint32, level int32) {
|
||||
call("framebufferTexture2D", target, attachment, texTarget, object(texture), level)
|
||||
}
|
||||
|
||||
func glBlitFramebuffer(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1 int32, mask, filter uint32) {
|
||||
call("blitFramebuffer", sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, mask, filter)
|
||||
}
|
||||
|
||||
func boolInt(b bool) int32 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// uploadElement uploads the picture of the video element of a surface's
|
||||
// Native into the bound texture, of its size, GPU to GPU, reporting
|
||||
// whether there was one.
|
||||
func uploadElement(native uintptr) bool {
|
||||
el := media.ElementOf(native)
|
||||
if el.IsUndefined() || el.Get("readyState").Int() < 2 { // HAVE_CURRENT_DATA
|
||||
return false
|
||||
}
|
||||
call("texSubImage2D", glTexture2D, 0, 0, 0, glRGBA, glUnsignedByte, el)
|
||||
return true
|
||||
}
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// The functions of libepoxy and GL this package calls.
|
||||
var (
|
||||
loadOnce sync.Once
|
||||
errLoad error
|
||||
|
||||
epoxyGLVersion func() int32
|
||||
epoxyIsDesktopGL func() bool
|
||||
epoxyHasExtension func(name string) bool
|
||||
currentGDKContext func() uintptr // gdk_gl_context_get_current, when GDK is loaded
|
||||
|
||||
// GTK's functions of a GtkGLArea's context, when GTK is loaded
|
||||
// (MakeAreaCurrent).
|
||||
gdkClearCurrent func() // gdk_gl_context_clear_current
|
||||
gtkAreaContext func(area uintptr) uintptr // gtk_gl_area_get_context
|
||||
gtkAreaMakeCurrent func(area uintptr) // gtk_gl_area_make_current
|
||||
gtkAreaAttach func(area uintptr) // gtk_gl_area_attach_buffers
|
||||
|
||||
glGetString func(name uint32) uintptr
|
||||
glGetError func() uint32
|
||||
glGetIntegerv func(name uint32, data *int32)
|
||||
glCreateShader func(typ uint32) uint32
|
||||
glShaderSource func(shader uint32, count int32, sources **byte, lengths *int32)
|
||||
glCompileShader func(shader uint32)
|
||||
glGetShaderiv func(shader, name uint32, out *int32)
|
||||
glGetShaderInfoLog func(shader uint32, size int32, length *int32, log *byte)
|
||||
glDeleteShader func(shader uint32)
|
||||
glCreateProgram func() uint32
|
||||
glAttachShader func(program, shader uint32)
|
||||
glLinkProgram func(program uint32)
|
||||
glGetProgramiv func(program, name uint32, out *int32)
|
||||
glGetProgramInfoLog func(program uint32, size int32, length *int32, log *byte)
|
||||
glUseProgram func(program uint32)
|
||||
glDeleteProgram func(program uint32)
|
||||
glGetUniformLocation func(program uint32, name string) int32
|
||||
glGetUniformBlockIndex func(program uint32, name string) uint32
|
||||
glUniformBlockBinding func(program, index, binding uint32)
|
||||
glBindBufferBase func(target, index, buffer uint32)
|
||||
glUniform1i func(location, v int32)
|
||||
glUniform2f func(location int32, x, y float32)
|
||||
glUniform1f func(location int32, v float32)
|
||||
glUniform2i func(location, x, y int32)
|
||||
glUniform4i func(location, x, y, z, w int32)
|
||||
glCopyTexSubImage2D func(target uint32, level, xoff, yoff, x, y, w, h int32)
|
||||
glGenVertexArrays func(n int32, out *uint32)
|
||||
glBindVertexArray func(array uint32)
|
||||
glDeleteVertexArrays func(n int32, arrays *uint32)
|
||||
glGenBuffers func(n int32, out *uint32)
|
||||
glBindBuffer func(target, buffer uint32)
|
||||
glBufferData func(target uint32, size int, data unsafe.Pointer, usage uint32)
|
||||
glDeleteBuffers func(n int32, buffers *uint32)
|
||||
glEnableVertexAttrib func(index uint32)
|
||||
glVertexAttribPointer func(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr)
|
||||
glVertexAttribDivisor func(index, divisor uint32)
|
||||
glGenTextures func(n int32, out *uint32)
|
||||
glBindTexture func(target, texture uint32)
|
||||
glActiveTexture func(unit uint32)
|
||||
glTexImage2D func(target uint32, level, internalFormat, w, h, border int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexSubImage2D func(target uint32, level, x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexParameteri func(target, name uint32, v int32)
|
||||
glDeleteTextures func(n int32, textures *uint32)
|
||||
glPixelStorei func(name uint32, v int32)
|
||||
glViewport func(x, y, w, h int32)
|
||||
glScissor func(x, y, w, h int32)
|
||||
glEnable func(cap uint32)
|
||||
glDisable func(cap uint32)
|
||||
glBlendFunc func(src, dst uint32)
|
||||
glBlendFuncSeparate func(srcRGB, dstRGB, srcAlpha, dstAlpha uint32)
|
||||
glClearColor func(r, g, b, a float32)
|
||||
glClear func(mask uint32)
|
||||
glDrawArraysInstanced func(mode uint32, first, count, instances int32)
|
||||
glReadPixels func(x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glGenFramebuffers func(n int32, out *uint32)
|
||||
glBindFramebuffer func(target, fb uint32)
|
||||
glFramebufferTexture2D func(target, attachment, texTarget, texture uint32, level int32)
|
||||
glCheckFramebufferState func(target uint32) uint32
|
||||
glDeleteFramebuffers func(n int32, fbs *uint32)
|
||||
glBlitFramebuffer func(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1 int32, mask, filter uint32)
|
||||
)
|
||||
|
||||
func load() error {
|
||||
loadOnce.Do(func() {
|
||||
lib, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
errLoad = fmt.Errorf("gl: cannot load libepoxy: %w", err)
|
||||
return
|
||||
}
|
||||
var missing []string
|
||||
fn := func(f any, name string) {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
missing = append(missing, name)
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
// libepoxy exports a pointer for each GL function, to a stub that
|
||||
// finds the function of the current context when first called.
|
||||
gl := func(f any, name string) {
|
||||
sym, err := purego.Dlsym(lib, "epoxy_"+name)
|
||||
if err != nil || sym == 0 {
|
||||
missing = append(missing, name)
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(f, **(**uintptr)(unsafe.Pointer(&sym)))
|
||||
}
|
||||
fn(&epoxyGLVersion, "epoxy_gl_version")
|
||||
fn(&epoxyIsDesktopGL, "epoxy_is_desktop_gl")
|
||||
fn(&epoxyHasExtension, "epoxy_has_gl_extension")
|
||||
gl(&glGetString, "glGetString")
|
||||
gl(&glGetError, "glGetError")
|
||||
gl(&glGetIntegerv, "glGetIntegerv")
|
||||
gl(&glCreateShader, "glCreateShader")
|
||||
gl(&glShaderSource, "glShaderSource")
|
||||
gl(&glCompileShader, "glCompileShader")
|
||||
gl(&glGetShaderiv, "glGetShaderiv")
|
||||
gl(&glGetShaderInfoLog, "glGetShaderInfoLog")
|
||||
gl(&glDeleteShader, "glDeleteShader")
|
||||
gl(&glCreateProgram, "glCreateProgram")
|
||||
gl(&glAttachShader, "glAttachShader")
|
||||
gl(&glLinkProgram, "glLinkProgram")
|
||||
gl(&glGetProgramiv, "glGetProgramiv")
|
||||
gl(&glGetProgramInfoLog, "glGetProgramInfoLog")
|
||||
gl(&glUseProgram, "glUseProgram")
|
||||
gl(&glDeleteProgram, "glDeleteProgram")
|
||||
gl(&glGetUniformLocation, "glGetUniformLocation")
|
||||
gl(&glGetUniformBlockIndex, "glGetUniformBlockIndex")
|
||||
gl(&glUniformBlockBinding, "glUniformBlockBinding")
|
||||
gl(&glBindBufferBase, "glBindBufferBase")
|
||||
gl(&glUniform1i, "glUniform1i")
|
||||
gl(&glUniform2f, "glUniform2f")
|
||||
gl(&glUniform1f, "glUniform1f")
|
||||
gl(&glUniform2i, "glUniform2i")
|
||||
gl(&glUniform4i, "glUniform4i")
|
||||
gl(&glCopyTexSubImage2D, "glCopyTexSubImage2D")
|
||||
gl(&glGenVertexArrays, "glGenVertexArrays")
|
||||
gl(&glBindVertexArray, "glBindVertexArray")
|
||||
gl(&glDeleteVertexArrays, "glDeleteVertexArrays")
|
||||
gl(&glGenBuffers, "glGenBuffers")
|
||||
gl(&glBindBuffer, "glBindBuffer")
|
||||
gl(&glBufferData, "glBufferData")
|
||||
gl(&glDeleteBuffers, "glDeleteBuffers")
|
||||
gl(&glEnableVertexAttrib, "glEnableVertexAttribArray")
|
||||
gl(&glVertexAttribPointer, "glVertexAttribPointer")
|
||||
gl(&glVertexAttribDivisor, "glVertexAttribDivisor")
|
||||
gl(&glGenTextures, "glGenTextures")
|
||||
gl(&glBindTexture, "glBindTexture")
|
||||
gl(&glActiveTexture, "glActiveTexture")
|
||||
gl(&glTexImage2D, "glTexImage2D")
|
||||
gl(&glTexSubImage2D, "glTexSubImage2D")
|
||||
gl(&glTexParameteri, "glTexParameteri")
|
||||
gl(&glDeleteTextures, "glDeleteTextures")
|
||||
gl(&glPixelStorei, "glPixelStorei")
|
||||
gl(&glViewport, "glViewport")
|
||||
gl(&glScissor, "glScissor")
|
||||
gl(&glEnable, "glEnable")
|
||||
gl(&glDisable, "glDisable")
|
||||
gl(&glBlendFunc, "glBlendFunc")
|
||||
gl(&glBlendFuncSeparate, "glBlendFuncSeparate")
|
||||
gl(&glClearColor, "glClearColor")
|
||||
gl(&glClear, "glClear")
|
||||
gl(&glDrawArraysInstanced, "glDrawArraysInstanced")
|
||||
gl(&glReadPixels, "glReadPixels")
|
||||
gl(&glGenFramebuffers, "glGenFramebuffers")
|
||||
gl(&glBindFramebuffer, "glBindFramebuffer")
|
||||
gl(&glFramebufferTexture2D, "glFramebufferTexture2D")
|
||||
gl(&glCheckFramebufferState, "glCheckFramebufferStatus")
|
||||
gl(&glDeleteFramebuffers, "glDeleteFramebuffers")
|
||||
gl(&glBlitFramebuffer, "glBlitFramebuffer")
|
||||
if len(missing) > 0 {
|
||||
errLoad = fmt.Errorf("gl: libepoxy lacks %s", strings.Join(missing, ", "))
|
||||
return
|
||||
}
|
||||
direct(lib)
|
||||
// GDK is loaded in apps, where its context tells when GTK
|
||||
// realized the area again; tests make contexts of their own.
|
||||
if sym, err := purego.Dlsym(purego.RTLD_DEFAULT, "gdk_gl_context_get_current"); err == nil && sym != 0 {
|
||||
purego.RegisterFunc(¤tGDKContext, sym)
|
||||
}
|
||||
gtk := map[string]any{
|
||||
"gdk_gl_context_clear_current": &gdkClearCurrent, "gtk_gl_area_get_context": >kAreaContext,
|
||||
"gtk_gl_area_make_current": >kAreaMakeCurrent, "gtk_gl_area_attach_buffers": >kAreaAttach,
|
||||
}
|
||||
for name, f := range gtk {
|
||||
sym, err := purego.Dlsym(purego.RTLD_DEFAULT, name)
|
||||
if err != nil || sym == 0 {
|
||||
gdkClearCurrent = nil // all or none
|
||||
break
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
})
|
||||
return errLoad
|
||||
}
|
||||
|
||||
// direct calls the GL functions a frame calls for each batch with
|
||||
// purego.SyscallN, through libepoxy's pointer to each: a function
|
||||
// RegisterFunc made builds its arguments with reflection on every call,
|
||||
// which cost more than the call itself, and a frame makes hundreds.
|
||||
func direct(lib uintptr) {
|
||||
ptr := func(name string) *uintptr {
|
||||
sym, err := purego.Dlsym(lib, "epoxy_"+name)
|
||||
if err != nil || sym == 0 {
|
||||
return nil
|
||||
}
|
||||
return *(**uintptr)(unsafe.Pointer(&sym))
|
||||
}
|
||||
b := func(v bool) uintptr {
|
||||
if v {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
if p := ptr("glVertexAttribPointer"); p != nil {
|
||||
glVertexAttribPointer = func(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr) {
|
||||
purego.SyscallN(*p, uintptr(index), uintptr(size), uintptr(typ), b(normalized), uintptr(stride), offset)
|
||||
}
|
||||
}
|
||||
if p := ptr("glScissor"); p != nil {
|
||||
glScissor = func(x, y, w, h int32) { purego.SyscallN(*p, uintptr(x), uintptr(y), uintptr(w), uintptr(h)) }
|
||||
}
|
||||
if p := ptr("glDrawArraysInstanced"); p != nil {
|
||||
glDrawArraysInstanced = func(mode uint32, first, count, instances int32) {
|
||||
purego.SyscallN(*p, uintptr(mode), uintptr(first), uintptr(count), uintptr(instances))
|
||||
}
|
||||
}
|
||||
if p := ptr("glActiveTexture"); p != nil {
|
||||
glActiveTexture = func(unit uint32) { purego.SyscallN(*p, uintptr(unit)) }
|
||||
}
|
||||
if p := ptr("glBindTexture"); p != nil {
|
||||
glBindTexture = func(target, texture uint32) { purego.SyscallN(*p, uintptr(target), uintptr(texture)) }
|
||||
}
|
||||
if p := ptr("glUseProgram"); p != nil {
|
||||
glUseProgram = func(program uint32) { purego.SyscallN(*p, uintptr(program)) }
|
||||
}
|
||||
if p := ptr("glBindBuffer"); p != nil {
|
||||
glBindBuffer = func(target, buffer uint32) { purego.SyscallN(*p, uintptr(target), uintptr(buffer)) }
|
||||
}
|
||||
if p := ptr("glEnable"); p != nil {
|
||||
glEnable = func(c uint32) { purego.SyscallN(*p, uintptr(c)) }
|
||||
}
|
||||
if p := ptr("glDisable"); p != nil {
|
||||
glDisable = func(c uint32) { purego.SyscallN(*p, uintptr(c)) }
|
||||
}
|
||||
if p := ptr("glBlendFunc"); p != nil {
|
||||
glBlendFunc = func(src, dst uint32) { purego.SyscallN(*p, uintptr(src), uintptr(dst)) }
|
||||
}
|
||||
if p := ptr("glBlendFuncSeparate"); p != nil {
|
||||
glBlendFuncSeparate = func(srcRGB, dstRGB, srcAlpha, dstAlpha uint32) {
|
||||
purego.SyscallN(*p, uintptr(srcRGB), uintptr(dstRGB), uintptr(srcAlpha), uintptr(dstAlpha))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MakeAreaCurrent makes the context of a GtkGLArea current again, with the
|
||||
// area's framebuffer bound, when it no longer is during the area's render
|
||||
// signal, and reports whether OpenGL has a current context after. GTK
|
||||
// makes the area's context current before the signal, but what a frame
|
||||
// runs before it draws, as a window that a button's action creates, shows
|
||||
// or hides, can leave another context current, or none: GDK's
|
||||
// gdk_window_hide clears the current context of the window it hides, and
|
||||
// disposing a context makes EGL's current one none. GDK remembers the
|
||||
// context it last made current and does nothing when asked for it again,
|
||||
// so the area's context is made current again past that memory: cleared
|
||||
// first, then made current.
|
||||
func MakeAreaCurrent(area uintptr) bool {
|
||||
if load() != nil {
|
||||
return false
|
||||
}
|
||||
if area == 0 || gdkClearCurrent == nil || currentGDKContext == nil {
|
||||
return hasContext()
|
||||
}
|
||||
ctx, has := gtkAreaContext(area), hasContext()
|
||||
if !needsRestore(ctx, currentGDKContext(), has) {
|
||||
return has
|
||||
}
|
||||
gdkClearCurrent()
|
||||
gtkAreaMakeCurrent(area)
|
||||
gtkAreaAttach(area)
|
||||
return hasContext()
|
||||
}
|
||||
|
||||
// needsRestore reports whether the context of a GtkGLArea, area, must be
|
||||
// made current again before drawing into the area: GDK has another
|
||||
// context current, current, or OpenGL none at all, has false, whatever
|
||||
// GDK thinks. An area without a context has none to make current.
|
||||
func needsRestore(area, current uintptr, has bool) bool {
|
||||
return area != 0 && (current != area || !has)
|
||||
}
|
||||
|
||||
func currentContext() uintptr {
|
||||
if currentGDKContext == nil {
|
||||
return 0
|
||||
}
|
||||
return currentGDKContext()
|
||||
}
|
||||
|
||||
func goString(p uintptr) string {
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
var b []byte
|
||||
for i := uintptr(0); ; i++ {
|
||||
c := *(*byte)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&p)), i))
|
||||
if c == 0 {
|
||||
return string(b)
|
||||
}
|
||||
b = append(b, c)
|
||||
}
|
||||
}
|
||||
|
||||
// contextVersion returns the version of the current context, major × 10 +
|
||||
// minor, and whether it is OpenGL ES.
|
||||
func contextVersion() (version int32, es bool) { return epoxyGLVersion(), !epoxyIsDesktopGL() }
|
||||
|
||||
// hasExtension reports whether the current context has an extension.
|
||||
func hasExtension(name string) bool { return epoxyHasExtension(name) }
|
||||
|
||||
// hasContext reports whether a context is current, which GDK may think one
|
||||
// is when OpenGL does not: libepoxy aborts the first call of most GL
|
||||
// functions without one. glGetString it finds without.
|
||||
func hasContext() bool { return glGetString(glVersion) != 0 }
|
||||
|
||||
// versionString describes the current context's version, for errors.
|
||||
func versionString() string { return goString(glGetString(glVersion)) }
|
||||
|
||||
// rendererString names the current context's renderer.
|
||||
func rendererString() string { return goString(glGetString(glRenderer)) }
|
||||
|
||||
// setShaderSource sets the source of a shader.
|
||||
func setShaderSource(s uint32, src string) {
|
||||
b := append([]byte(src), 0)
|
||||
p := &b[0]
|
||||
glShaderSource(s, 1, &p, nil)
|
||||
}
|
||||
|
||||
// shaderLog and programLog return what compiling a shader or linking a
|
||||
// program logged.
|
||||
func shaderLog(s uint32) string { return infoLog(s, glGetShaderiv, glGetShaderInfoLog) }
|
||||
func programLog(p uint32) string { return infoLog(p, glGetProgramiv, glGetProgramInfoLog) }
|
||||
|
||||
func infoLog(obj uint32, get func(uint32, uint32, *int32), read func(uint32, int32, *int32, *byte)) string {
|
||||
var n int32
|
||||
get(obj, glInfoLogLength, &n)
|
||||
if n <= 1 {
|
||||
return "no log"
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
read(obj, n, nil, &buf[0])
|
||||
return strings.TrimSpace(string(buf[:n-1]))
|
||||
}
|
||||
|
||||
// uploadElement is for browsers' video elements, which Linux has none of.
|
||||
func uploadElement(uintptr) bool { return false }
|
||||
@@ -0,0 +1,40 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gl
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNeedsRestore(t *testing.T) {
|
||||
const area, other = 0x10, 0x20
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
area, current uintptr
|
||||
has, want bool
|
||||
}{
|
||||
{"the area's, current", area, area, true, false},
|
||||
{"another window's", area, other, true, true},
|
||||
{"none, cleared", area, 0, false, true},
|
||||
{"GDK's, stale", area, area, false, true},
|
||||
{"none in GDK alone", area, 0, true, true},
|
||||
{"an area without a context", 0, other, false, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := needsRestore(c.area, c.current, c.has); got != c.want {
|
||||
t.Errorf("needsRestore = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without GTK, as in tests, MakeAreaCurrent changes nothing.
|
||||
func TestMakeAreaCurrentWithoutGTK(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
if gdkClearCurrent != nil {
|
||||
t.Skip("GTK is loaded")
|
||||
}
|
||||
if MakeAreaCurrent(0x10) {
|
||||
t.Error("a context is current without one made")
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// EGL enumerations.
|
||||
const (
|
||||
eglPlatformSurfaceless = 0x31DD // EGL_PLATFORM_SURFACELESS_MESA
|
||||
eglNone = 0x3038
|
||||
eglRenderableType = 0x3040
|
||||
eglOpenGLBit = 0x0008
|
||||
eglSurfaceType = 0x3033
|
||||
eglPbufferBit = 0x0001
|
||||
eglOpenGLAPI = 0x30A2
|
||||
eglOpenGLESAPI = 0x30A0
|
||||
eglOpenGLES3Bit = 0x0040 // EGL_OPENGL_ES3_BIT_KHR
|
||||
eglContextMajorVersion = 0x3098
|
||||
eglContextMinorVersion = 0x30FB
|
||||
eglContextProfileMask = 0x30FD
|
||||
eglContextCoreProfileBit = 0x1
|
||||
)
|
||||
|
||||
// Offscreen is a GL context without a window, current on the thread that
|
||||
// made it, which must stay locked to it, with a framebuffer bound: for
|
||||
// drawing scenes in tests, as packages drawing effects do. EGL makes it
|
||||
// with Mesa's surfaceless platform, which draws with llvmpipe without a
|
||||
// GPU.
|
||||
type Offscreen struct {
|
||||
display, context uintptr
|
||||
fb, tex uint32
|
||||
w, h int
|
||||
release func()
|
||||
r *Renderer
|
||||
// scratch holds the framebuffer's rows as GL reads them (Read).
|
||||
scratch []byte
|
||||
}
|
||||
|
||||
// NewOffscreen makes an OpenGL 3.3 context, or with es an OpenGL ES 3.0
|
||||
// one, current on the calling thread, and binds a framebuffer of w×h
|
||||
// pixels.
|
||||
func NewOffscreen(es bool, w, h int) (_ *Offscreen, err error) {
|
||||
lib, err := purego.Dlopen("libEGL.so.1", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gl: no EGL: %w", err)
|
||||
}
|
||||
var (
|
||||
getPlatformDisplay func(platform uint32, native uintptr, attribs unsafe.Pointer) uintptr
|
||||
initialize func(display uintptr, major, minor *int32) uint32
|
||||
bindAPI func(api uint32) uint32
|
||||
chooseConfig func(display uintptr, attribs *int32, configs *uintptr, size int32, n *int32) uint32
|
||||
createContext func(display, config, share uintptr, attribs *int32) uintptr
|
||||
makeCurrent func(display, draw, read, context uintptr) uint32
|
||||
destroyContext func(display, context uintptr) uint32
|
||||
terminate func(display uintptr) uint32
|
||||
)
|
||||
for name, fn := range map[string]any{
|
||||
"eglGetPlatformDisplay": &getPlatformDisplay, "eglInitialize": &initialize, "eglBindAPI": &bindAPI,
|
||||
"eglChooseConfig": &chooseConfig, "eglCreateContext": &createContext, "eglMakeCurrent": &makeCurrent,
|
||||
"eglDestroyContext": &destroyContext, "eglTerminate": &terminate,
|
||||
} {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL has no %s", name)
|
||||
}
|
||||
purego.RegisterFunc(fn, sym)
|
||||
}
|
||||
// A variable of its own, not a named result: returning an error would
|
||||
// set that to nil before the undoing below runs.
|
||||
off := &Offscreen{w: w, h: h}
|
||||
var undo []func()
|
||||
off.release = func() {
|
||||
for i := len(undo) - 1; i >= 0; i-- {
|
||||
undo[i]()
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
off.release()
|
||||
}
|
||||
}()
|
||||
display := getPlatformDisplay(eglPlatformSurfaceless, 0, nil)
|
||||
if display == 0 || initialize(display, nil, nil) == 0 {
|
||||
return nil, errors.New("gl: no surfaceless EGL display")
|
||||
}
|
||||
undo = append(undo, func() { terminate(display) })
|
||||
api, bit, contextAttribs := uint32(eglOpenGLAPI), int32(eglOpenGLBit), []int32{eglContextMajorVersion, 3, eglContextMinorVersion, 3, eglContextProfileMask, eglContextCoreProfileBit, eglNone}
|
||||
if es {
|
||||
api, bit, contextAttribs = eglOpenGLESAPI, eglOpenGLES3Bit, []int32{eglContextMajorVersion, 3, eglContextMinorVersion, 0, eglNone}
|
||||
}
|
||||
bindAPI(api)
|
||||
// Configurations are for windows unless asked otherwise.
|
||||
configAttribs := []int32{eglRenderableType, bit, eglSurfaceType, eglPbufferBit, eglNone}
|
||||
var config uintptr
|
||||
var n int32
|
||||
if chooseConfig(display, &configAttribs[0], &config, 1, &n) == 0 || n == 0 {
|
||||
return nil, errors.New("gl: no EGL configuration for the API")
|
||||
}
|
||||
context := createContext(display, config, 0, &contextAttribs[0])
|
||||
if context == 0 {
|
||||
return nil, errors.New("gl: no context of the version")
|
||||
}
|
||||
undo = append(undo, func() {
|
||||
makeCurrent(display, 0, 0, 0)
|
||||
destroyContext(display, context)
|
||||
})
|
||||
if makeCurrent(display, 0, 0, context) == 0 {
|
||||
return nil, errors.New("gl: cannot make the context current without a surface")
|
||||
}
|
||||
if err := load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
off.tex = newTexture(glRGBA8, glRGBA, w, h, nil, 0)
|
||||
glGenFramebuffers(1, &off.fb)
|
||||
glBindFramebuffer(glFramebuffer, off.fb)
|
||||
glFramebufferTexture2D(glFramebuffer, glColorAttachment0, glTexture2D, off.tex, 0)
|
||||
undo = append(undo, func() {
|
||||
if off.r != nil {
|
||||
off.r.Release()
|
||||
}
|
||||
glBindFramebuffer(glFramebuffer, 0)
|
||||
glDeleteFramebuffers(1, &off.fb)
|
||||
glDeleteTextures(1, &off.tex)
|
||||
})
|
||||
if status := glCheckFramebufferState(glFramebuffer); status != glFramebufferDone {
|
||||
return nil, fmt.Errorf("gl: framebuffer incomplete: %#x", status)
|
||||
}
|
||||
return off, nil
|
||||
}
|
||||
|
||||
// Info names the context's version and renderer.
|
||||
func (o *Offscreen) Info() string {
|
||||
return goString(glGetString(glVersion)) + ", " + goString(glGetString(glRenderer))
|
||||
}
|
||||
|
||||
// Render draws s, which must be as large as the framebuffer, with a
|
||||
// renderer of its own, and returns its pixels as the CPU renderer draws
|
||||
// them: premultiplied BGRA rows from the top.
|
||||
func (o *Offscreen) Render(s *scene.Scene) ([]byte, error) {
|
||||
if o.r == nil {
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.r = r
|
||||
}
|
||||
if err := o.r.Render(s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ReadFramebuffer(o.w, o.h)
|
||||
}
|
||||
|
||||
// Draw draws s, which must be as large as the framebuffer, with a
|
||||
// renderer of its own, without reading it back: Read does, for videos
|
||||
// (plugins/render), which build the next frame meanwhile.
|
||||
func (o *Offscreen) Draw(s *scene.Scene) error {
|
||||
if o.r == nil {
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.r = r
|
||||
}
|
||||
if err := o.r.Render(s); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read copies the framebuffer into dst, as the CPU renderer draws:
|
||||
// premultiplied BGRA rows from the top, 4×width bytes each.
|
||||
func (o *Offscreen) Read(dst []byte) error {
|
||||
n := 4 * o.w * o.h
|
||||
if len(dst) < n {
|
||||
return errors.New("gl: too small a buffer")
|
||||
}
|
||||
if len(o.scratch) != n {
|
||||
o.scratch = make([]byte, n)
|
||||
}
|
||||
glPixelStorei(glPackAlignment, 1)
|
||||
glReadPixels(0, 0, int32(o.w), int32(o.h), glRGBA, glUnsignedByte, unsafe.Pointer(&o.scratch[0]))
|
||||
glPixelStorei(glPackAlignment, 4)
|
||||
if e := glGetError(); e != glNoError {
|
||||
return fmt.Errorf("gl: reading the framebuffer failed (error %#x)", e)
|
||||
}
|
||||
// GL's rows go up, and its bytes are RGBA.
|
||||
row := 4 * o.w
|
||||
for y := range o.h {
|
||||
src, out := o.scratch[row*(o.h-1-y):][:row], dst[row*y:][:row]
|
||||
for x := 0; x < row; x += 4 {
|
||||
out[x], out[x+1], out[x+2], out[x+3] = src[x+2], src[x+1], src[x], src[x+3]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release deletes the context and what it holds.
|
||||
func (o *Offscreen) Release() { o.release() }
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestNewOffscreenFailsWithItsError checks that a setup failing after EGL
|
||||
// loaded returns its error, rather than panicking as it undoes what it
|
||||
// did: a framebuffer of 0×0 is incomplete, and without libepoxy loading
|
||||
// fails, both after the display and the context.
|
||||
func TestNewOffscreenFailsWithItsError(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
o, err := NewOffscreen(false, 0, 0)
|
||||
if err == nil {
|
||||
o.Release()
|
||||
t.Skip("a framebuffer of 0×0 is complete here")
|
||||
}
|
||||
if o != nil {
|
||||
t.Errorf("NewOffscreen returned %v with the error %v", o, err)
|
||||
}
|
||||
t.Log(err)
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
//go:build (linux && !android && (amd64 || arm64)) || js || android
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// errNoContext is the error of drawing without a current context.
|
||||
var errNoContext = errors.New("gl: no current context")
|
||||
|
||||
// Presenter shows frames drawn in memory in the bound framebuffer: what a
|
||||
// GtkGLArea shows when its content draws on the CPU after all, as when the
|
||||
// GL renderer fails. GTK shows only what OpenGL draws into a GtkGLArea.
|
||||
type Presenter struct {
|
||||
context uintptr
|
||||
tex, fb uint32
|
||||
w, h int
|
||||
rgba []byte
|
||||
}
|
||||
|
||||
// Present copies premultiplied BGRA rows of stride bytes, width×height
|
||||
// pixels, into the bound framebuffer, which is that size. The context
|
||||
// current must be the one of the last call, or a new one.
|
||||
func (p *Presenter) Present(pix []byte, stride, width, height int) error {
|
||||
if err := load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if width <= 0 || height <= 0 || len(pix) < stride*(height-1)+4*width {
|
||||
return nil
|
||||
}
|
||||
if !hasContext() {
|
||||
return errNoContext
|
||||
}
|
||||
if c := currentContext(); c != p.context {
|
||||
// A new context: the old one took the texture with it.
|
||||
p.context, p.tex, p.fb, p.w, p.h = c, 0, 0, 0, 0
|
||||
}
|
||||
// GL reads RGBA; frames in memory are BGRA.
|
||||
n := 4 * width * height
|
||||
if cap(p.rgba) < n {
|
||||
p.rgba = make([]byte, n)
|
||||
}
|
||||
rgba := p.rgba[:n]
|
||||
for y := range height {
|
||||
src, dst := pix[y*stride:][:4*width], rgba[4*width*y:][:4*width]
|
||||
for x := 0; x < 4*width; x += 4 {
|
||||
dst[x], dst[x+1], dst[x+2], dst[x+3] = src[x+2], src[x+1], src[x], src[x+3]
|
||||
}
|
||||
}
|
||||
var target int32
|
||||
glGetIntegerv(glFramebufferBinding, &target)
|
||||
if p.tex == 0 || p.w != width || p.h != height {
|
||||
if p.tex != 0 {
|
||||
glDeleteTextures(1, &p.tex)
|
||||
}
|
||||
p.tex = newTexture(glRGBA8, glRGBA, width, height, nil, 0)
|
||||
if p.fb == 0 {
|
||||
glGenFramebuffers(1, &p.fb)
|
||||
}
|
||||
glBindFramebuffer(glReadFramebuffer, p.fb)
|
||||
glFramebufferTexture2D(glReadFramebuffer, glColorAttachment0, glTexture2D, p.tex, 0)
|
||||
p.w, p.h = width, height
|
||||
}
|
||||
glActiveTexture(glTexture0)
|
||||
glBindTexture(glTexture2D, p.tex)
|
||||
unpack(4*width, glRGBA8)
|
||||
glTexSubImage2D(glTexture2D, 0, 0, 0, int32(width), int32(height), glRGBA, glUnsignedByte, unsafe.Pointer(&rgba[0]))
|
||||
unpackReset()
|
||||
glBindTexture(glTexture2D, 0)
|
||||
glBindFramebuffer(glReadFramebuffer, p.fb)
|
||||
glBindFramebuffer(glDrawFramebuffer, uint32(target))
|
||||
glDisable(glScissorTest)
|
||||
// Rows go down in memory and up in GL: the copy flips them.
|
||||
w, h := int32(width), int32(height)
|
||||
glBlitFramebuffer(0, 0, w, h, 0, h, w, 0, glColorBufferBit, glNearest)
|
||||
glBindFramebuffer(glFramebuffer, uint32(target))
|
||||
if e := glGetError(); e != glNoError {
|
||||
return fmt.Errorf("gl: presenting a frame failed (error %#x)", e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
//go:build (linux && !android && (amd64 || arm64)) || js || android
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// ReadFramebuffer returns the pixels of the bound framebuffer, width×height,
|
||||
// as the CPU renderer draws them: premultiplied BGRA rows from the top. Tests
|
||||
// compare them.
|
||||
func ReadFramebuffer(width, height int) ([]byte, error) {
|
||||
if err := load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if width <= 0 || height <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
pix := make([]byte, 4*width*height)
|
||||
glPixelStorei(glPackAlignment, 1)
|
||||
glReadPixels(0, 0, int32(width), int32(height), glRGBA, glUnsignedByte, unsafe.Pointer(&pix[0]))
|
||||
glPixelStorei(glPackAlignment, 4)
|
||||
if e := glGetError(); e != glNoError {
|
||||
return nil, fmt.Errorf("gl: reading the framebuffer failed (error %#x)", e)
|
||||
}
|
||||
// GL's rows go up, and its bytes are RGBA.
|
||||
out := make([]byte, len(pix))
|
||||
for y := range height {
|
||||
src, dst := pix[4*width*(height-1-y):][:4*width], out[4*width*y:][:4*width]
|
||||
for x := 0; x < 4*width; x += 4 {
|
||||
dst[x], dst[x+1], dst[x+2], dst[x+3] = src[x+2], src[x+1], src[x], src[x+3]
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
+741
@@ -0,0 +1,741 @@
|
||||
// The one shader of the OpenGL renderer, as shader.metal is the Metal one
|
||||
// and shader.hlsl the Direct3D one: every scene op is an instanced quad,
|
||||
// and the fragment shader computes the coverage of rounded rectangles,
|
||||
// borders, gradients, stripes and shadows from signed distances, as the
|
||||
// CPU renderer (internal/raster) does. Colors are straight (not premultiplied)
|
||||
// and blending happens in sRGB space, as in browsers. The renderer
|
||||
// compiles it when it starts, as GLSL 3.30 or GLSL ES 3.00, with VERTEX or
|
||||
// FRAGMENT defined, and the passes computing the backdrops of effects with
|
||||
// PASS_VERTEX and DOWN or BLUR. The fragment shaders of effects
|
||||
// (scene.Effect) take the start of its fragment part, with EFFECT
|
||||
// defined, before effect.glsl.
|
||||
|
||||
#ifdef VERTEX
|
||||
|
||||
// One instance per op, as internal/gpu builds them.
|
||||
layout(location = 0) in vec4 aRect; // x, y, width, height in pixels
|
||||
layout(location = 1) in vec4 aRadii; // top-left, top-right, bottom-right, bottom-left
|
||||
layout(location = 2) in vec4 aInner; // radii of the border's inner edge, of the box casting a shadow, or of an inner shadow's hole
|
||||
layout(location = 3) in vec4 aColor;
|
||||
layout(location = 4) in vec4 aColor2; // gradient end
|
||||
layout(location = 5) in vec4 aBorder; // border color
|
||||
layout(location = 6) in vec4 aGrad; // gradient start and end points, or stripes
|
||||
layout(location = 7) in vec4 aUV; // texture rectangle, normalized, border widths, the box casting a shadow, or an inner shadow's hole
|
||||
layout(location = 8) in vec4 aClip; // the innermost clip rectangle
|
||||
layout(location = 9) in vec4 aClipRadii;
|
||||
layout(location = 10) in vec4 aParams; // kind, dashed or grayscale, sigma or paint, opacity
|
||||
|
||||
layout(location = 11) in vec4 aTransform0;
|
||||
layout(location = 12) in vec4 aTransform1;
|
||||
layout(location = 13) in vec4 aTransform2; // the projective row's g and h, and 1 where its constant is -1
|
||||
|
||||
uniform vec2 uSize;
|
||||
|
||||
// The frame point times its projective divisor, and the divisor: they
|
||||
// interpolate in perspective to what divides into the frame point.
|
||||
out vec3 vWorld;
|
||||
flat out vec4 vTransform0;
|
||||
flat out vec4 vTransform1;
|
||||
flat out vec4 vTransform2;
|
||||
out vec4 vPoint; // the position in pixels, and the texture coordinates
|
||||
flat out vec4 vRect;
|
||||
flat out vec4 vRadii;
|
||||
flat out vec4 vInner;
|
||||
flat out vec4 vColor;
|
||||
flat out vec4 vColor2;
|
||||
flat out vec4 vBorder;
|
||||
flat out vec4 vGrad;
|
||||
flat out vec4 vWidths;
|
||||
flat out vec4 vClip;
|
||||
flat out vec4 vClipRadii;
|
||||
flat out vec4 vParams;
|
||||
|
||||
// frameH returns the frame point of local p, in homogeneous coordinates.
|
||||
vec3 frameH(vec2 p) {
|
||||
return vec3(dot(aTransform0.xyz, vec3(p, 1.0)), dot(aTransform1.xyz, vec3(p, 1.0)),
|
||||
dot(vec3(aTransform2.xy, 1.0 - 2.0 * aTransform2.z), vec3(p, 1.0)));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
||||
vec4 r = aRect;
|
||||
float kind = aParams.x;
|
||||
if (kind < 0.5 || kind > 5.5) { // fills and effects
|
||||
r = vec4(r.xy - 1.0, r.zw + 2.0);
|
||||
} else if (kind < 1.5) {
|
||||
float e = 3.0 * aParams.z + 1.0;
|
||||
r = vec4(r.xy - e, r.zw + 2.0 * e);
|
||||
}
|
||||
vec3 h = frameH(r.xy + corner * r.zw);
|
||||
if (aTransform0.w > 0.5 && h.z > 0.0) {
|
||||
// A pixel's reach at this corner, by the map's Jacobian there.
|
||||
vec2 s = h.xy / h.z;
|
||||
float a = (aTransform0.x - s.x * aTransform2.x) / h.z, c = (aTransform0.y - s.x * aTransform2.y) / h.z;
|
||||
float b = (aTransform1.x - s.y * aTransform2.x) / h.z, d = (aTransform1.y - s.y * aTransform2.y) / h.z;
|
||||
vec2 e = vec2(abs(d) + abs(c), abs(b) + abs(a)) / abs(a * d - b * c);
|
||||
r = vec4(r.xy - e, r.zw + 2.0 * e);
|
||||
}
|
||||
vec2 p = r.xy + corner * r.zw;
|
||||
h = frameH(p);
|
||||
gl_Position = vec4(h.xy / uSize * vec2(2.0, -2.0) + h.z * vec2(-1.0, 1.0), 0.0, h.z);
|
||||
vPoint = vec4(p, aUV.xy + (p - aRect.xy) / aRect.zw * (aUV.zw - aUV.xy));
|
||||
vWorld = h;
|
||||
vTransform0 = aTransform0;
|
||||
vTransform1 = aTransform1;
|
||||
vTransform2 = aTransform2;
|
||||
vRect = aRect;
|
||||
vRadii = aRadii;
|
||||
vInner = aInner;
|
||||
vColor = aColor;
|
||||
vColor2 = aColor2;
|
||||
vBorder = aBorder;
|
||||
vGrad = aGrad;
|
||||
vWidths = aUV;
|
||||
vClip = aClip;
|
||||
vClipRadii = aClipRadii;
|
||||
vParams = aParams;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(FRAGMENT) || defined(EFFECT)
|
||||
|
||||
in vec3 vWorld;
|
||||
flat in vec4 vTransform0;
|
||||
flat in vec4 vTransform1;
|
||||
flat in vec4 vTransform2;
|
||||
in vec4 vPoint;
|
||||
flat in vec4 vRect;
|
||||
flat in vec4 vRadii;
|
||||
flat in vec4 vInner;
|
||||
flat in vec4 vColor;
|
||||
flat in vec4 vColor2;
|
||||
flat in vec4 vBorder;
|
||||
flat in vec4 vGrad;
|
||||
flat in vec4 vWidths;
|
||||
flat in vec4 vClip;
|
||||
flat in vec4 vClipRadii;
|
||||
flat in vec4 vParams;
|
||||
|
||||
uniform sampler2D uMask;
|
||||
uniform sampler2D uColor;
|
||||
uniform sampler2D uImage;
|
||||
uniform sampler2D uClipMask;
|
||||
// The stops of the frame's gradients (gpu.Builder.Stops): two texels each,
|
||||
// the color, straight sRGB, then its place and its color in Oklab.
|
||||
uniform highp sampler2D uStops;
|
||||
uniform vec2 uSize; // the frame's size in pixels
|
||||
|
||||
// The color and, for dual-source blending, the source's alpha of each
|
||||
// channel. Without it, subpixel glyphs take the mean of their subpixels.
|
||||
#ifdef DUAL
|
||||
layout(location = 0, index = 0) out vec4 fragColor;
|
||||
layout(location = 0, index = 1) out vec4 fragAlpha;
|
||||
#else
|
||||
out vec4 fragColor;
|
||||
#endif
|
||||
|
||||
float sdRoundRect(vec2 p, vec4 rect, vec4 radii) {
|
||||
vec2 h = rect.zw * 0.5;
|
||||
vec2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0 ? (q.y < 0.0 ? radii.x : radii.w) : (q.y < 0.0 ? radii.y : radii.z);
|
||||
vec2 a = abs(q) - h + r;
|
||||
return length(max(a, vec2(0.0))) + min(max(a.x, a.y), 0.0) - r;
|
||||
}
|
||||
|
||||
float coverage(float d) { return clamp(0.5 - d, 0.0, 1.0); }
|
||||
|
||||
// rectCoverage returns how much of the pixel at p a rounded rectangle
|
||||
// covers: by the distance to its edge near rounded corners, and exactly,
|
||||
// the area of the pixel inside it, near square ones.
|
||||
float rectCoverage(vec2 p, vec4 rect, vec4 radii) {
|
||||
vec2 q = p - rect.xy - rect.zw * 0.5;
|
||||
float r = q.x < 0.0 ? (q.y < 0.0 ? radii.x : radii.w) : (q.y < 0.0 ? radii.y : radii.z);
|
||||
if (r > 0.0) {
|
||||
return coverage(sdRoundRect(p, rect, radii));
|
||||
}
|
||||
vec2 c = clamp(min(rect.xy + rect.zw, p + 0.5) - max(rect.xy, p - 0.5), 0.0, 1.0);
|
||||
return c.x * c.y;
|
||||
}
|
||||
|
||||
// Frame is where a fragment is in the frame, s, and, when its instance's
|
||||
// map is projective (persp), the columns of the map back, up to a factor.
|
||||
struct Frame {
|
||||
vec2 s;
|
||||
vec3 c0, c1, c2;
|
||||
bool persp;
|
||||
};
|
||||
Frame frameOf() {
|
||||
Frame f;
|
||||
f.persp = any(notEqual(vTransform2.xy, vec2(0.0)));
|
||||
// In perspective, the pixel's center, as interpolating drifts: the
|
||||
// frame's y goes down, the window's up.
|
||||
f.s = f.persp ? vec2(gl_FragCoord.x, uSize.y - gl_FragCoord.y) : vWorld.xy / vWorld.z;
|
||||
vec3 r0 = vTransform0.xyz, r1 = vTransform1.xyz, r2 = vec3(vTransform2.xy, 1.0 - 2.0 * vTransform2.z);
|
||||
f.c0 = cross(r1, r2);
|
||||
f.c1 = cross(r2, r0);
|
||||
f.c2 = cross(r0, r1);
|
||||
return f;
|
||||
}
|
||||
// localOf returns the point of the instance that shows at the frame's s.
|
||||
vec2 localOf(Frame f, vec2 s) {
|
||||
vec3 q = f.c0 * s.x + f.c1 * s.y + f.c2;
|
||||
return q.xy / q.z;
|
||||
}
|
||||
// perspectiveCoverage is localCoverage in perspective: each sample where
|
||||
// the CPU renderer takes it.
|
||||
float perspectiveCoverage(vec4 rect, vec4 radii, Frame fr) {
|
||||
vec2 p = localOf(fr, fr.s);
|
||||
vec2 a = localOf(fr, fr.s + vec2(0.5, 0.5)) - p, b = localOf(fr, fr.s + vec2(0.5, -0.5)) - p;
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2.0;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0;
|
||||
if (d > reach)
|
||||
return 0.0;
|
||||
float n = 0.0;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
vec2 q = localOf(fr, fr.s + vec2((float(x) + 0.5) / 4.0 - 0.5, (float(y) + 0.5) / 4.0 - 0.5));
|
||||
n += sdRoundRect(q, rect, radii) <= 0.0 ? 1.0 : 0.0;
|
||||
}
|
||||
return n / 16.0;
|
||||
}
|
||||
float localCoverage(vec2 p, vec4 rect, vec4 radii, float affine, Frame fr) {
|
||||
if (affine < 0.5)
|
||||
return rectCoverage(p, rect, radii);
|
||||
vec2 dx = dFdx(p), dy = dFdy(p), a = (dx + dy) * 0.5, b = (dx - dy) * 0.5;
|
||||
if (fr.persp)
|
||||
return perspectiveCoverage(rect, radii, fr);
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2.0;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0;
|
||||
if (d > reach)
|
||||
return 0.0;
|
||||
float n = 0.0;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
vec2 q = p + dx * ((float(x) + 0.5) / 4.0 - 0.5) + dy * ((float(y) + 0.5) / 4.0 - 0.5);
|
||||
n += sdRoundRect(q, rect, radii) <= 0.0 ? 1.0 : 0.0;
|
||||
}
|
||||
return n / 16.0;
|
||||
}
|
||||
float clipCoverage() {
|
||||
Frame fr = frameOf();
|
||||
vec2 world = fr.s;
|
||||
if (vTransform1.w < 0.5)
|
||||
return rectCoverage(world, vClip, vClipRadii);
|
||||
if (vTransform1.w > 1.5)
|
||||
return localCoverage(vPoint.xy, vClip, vec4(0.0), vTransform0.w, fr) *
|
||||
texture(uClipMask, (world - vClipRadii.xy) / vClipRadii.zw).a;
|
||||
return texture(uClipMask, (world - vClip.xy) / vClip.zw).a;
|
||||
}
|
||||
vec4 sampleLocal(sampler2D t, vec2 uv, vec4 src, float affine) {
|
||||
if (affine > 0.5) {
|
||||
vec2 halfPixel = 0.5 / vec2(textureSize(t, 0));
|
||||
uv = clamp(uv, src.xy + halfPixel, src.zw - halfPixel);
|
||||
}
|
||||
return texture(t, uv);
|
||||
}
|
||||
|
||||
// sampleImage samples an image held inside src, which is reversed along
|
||||
// an axis it flips, so that a part of a sheet shows none of its
|
||||
// neighbors; where pixelated is set, as pixel art draws, each texel a
|
||||
// square of its color whose edges blend with the next only across the
|
||||
// pixel they cross (Ebitengine's FilterPixelated): nearest where it shows
|
||||
// at whole multiples of its size, and texels of even widths with smooth
|
||||
// edges at any other. dtex is the fwidth of uv, taken where every
|
||||
// fragment of the quad takes it.
|
||||
vec4 sampleImage(sampler2D t, vec2 uv, vec4 src, float pixelated, vec2 dtex) {
|
||||
vec2 size = vec2(textureSize(t, 0));
|
||||
vec2 lo = min(src.xy, src.zw), hi = max(src.xy, src.zw);
|
||||
if (pixelated > 0.5) {
|
||||
vec2 tc = uv * size - 0.5;
|
||||
vec2 i = floor(tc);
|
||||
vec2 f = clamp((tc - i - 0.5) / clamp(dtex * size, 1e-5, 1.0) + 0.5, 0.0, 1.0);
|
||||
uv = (i + f + 0.5) / size;
|
||||
}
|
||||
return texture(t, clamp(uv, lo + 0.5 / size, hi - 0.5 / size));
|
||||
}
|
||||
|
||||
// tint multiplies premultiplied c by straight color t.
|
||||
vec4 tint(vec4 c, vec4 t) { return c * vec4(t.rgb * t.a, t.a); }
|
||||
|
||||
vec4 premul(vec4 c) { return vec4(c.rgb * c.a, c.a); }
|
||||
|
||||
vec3 unpremul(vec4 c) { return c.a > 0.0 ? c.rgb / c.a : vec3(0.0); }
|
||||
|
||||
// textCoverage corrects the coverage a of a glyph of straight color c as
|
||||
// Direct2D blends text (scene.TextCoverage): it enhances the contrast,
|
||||
// the more the darker c is, and corrects for gamma with the ratios g.
|
||||
float textCoverage(float a, vec3 c, float contrast, float boost, vec4 g) {
|
||||
float k = contrast * clamp(3.0 - 4.0 * dot(c, vec3(0.30, 0.59, 0.11)), 0.0, 1.0) + boost;
|
||||
a = a * (k + 1.0) / (a * k + 1.0);
|
||||
float f = dot(c, vec3(0.25, 0.5, 0.25));
|
||||
return clamp(a + a * (1.0 - a) * ((g.x * f + g.y) * a + (g.z * f + g.w)), 0.0, 1.0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// What follows is the renderer's own; effects (effect.glsl) take what is
|
||||
// above.
|
||||
#ifdef FRAGMENT
|
||||
|
||||
// The chroma of an image that is a frame of video in NV12, whose luma
|
||||
// uImage holds (gpu.ImageYUV).
|
||||
uniform sampler2D uChroma;
|
||||
|
||||
// yuvToRGB converts the samples of a frame of video in YCbCr to RGB, as
|
||||
// scene.YUVMatrix.YUVToRGB does: m is the matrix, 0 to 2 for BT.601, 709
|
||||
// and 2020 in the limited range, plus 3 for the full range.
|
||||
vec3 yuvToRGB(float y, vec2 c, float m) {
|
||||
float full = m > 2.5 ? 1.0 : 0.0;
|
||||
float std = m - 3.0 * full;
|
||||
vec2 k = std < 0.5 ? vec2(0.299, 0.114) : std < 1.5 ? vec2(0.2126, 0.0722) : vec2(0.2627, 0.0593);
|
||||
c -= 128.0 / 255.0;
|
||||
if (full < 0.5) {
|
||||
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
|
||||
c *= 255.0 / 224.0;
|
||||
}
|
||||
float r = y + 2.0 * (1.0 - k.x) * c.y;
|
||||
float b = y + 2.0 * (1.0 - k.y) * c.x;
|
||||
float g = (y - k.x * r - k.y * b) / (1.0 - k.x - k.y);
|
||||
return clamp(vec3(r, g, b), 0.0, 1.0);
|
||||
}
|
||||
|
||||
// subpixelCoverage does the same for each subpixel of a subpixel glyph.
|
||||
vec3 subpixelCoverage(vec3 a, vec3 c, float contrast, float boost, vec4 g) {
|
||||
float k = contrast * clamp(3.0 - 4.0 * dot(c, vec3(0.30, 0.59, 0.11)), 0.0, 1.0) + boost;
|
||||
a = a * (k + 1.0) / (a * k + 1.0);
|
||||
return clamp(a + a * (1.0 - a) * ((g.x * c + g.y) * a + (g.z * c + g.w)), vec3(0.0), vec3(1.0));
|
||||
}
|
||||
|
||||
// erf2 approximates the error function (Abramowitz and Stegun 7.1.27).
|
||||
vec2 erf2(vec2 x) {
|
||||
vec2 s = sign(x);
|
||||
vec2 a = abs(x);
|
||||
x = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
|
||||
x *= x;
|
||||
return s - s / (x * x);
|
||||
}
|
||||
|
||||
float gaussian(float x, float sigma) {
|
||||
return exp(-(x * x) / (2.0 * sigma * sigma)) / (2.50662827463 * sigma);
|
||||
}
|
||||
|
||||
// The blurred rounded box of Evan Wallace: exact along x, four samples
|
||||
// along y.
|
||||
float shadowX(float x, float y, float sigma, float corner, vec2 h) {
|
||||
float delta = min(h.y - corner - abs(y), 0.0);
|
||||
float curved = h.x - corner + sqrt(max(0.0, corner * corner - delta * delta));
|
||||
vec2 integral = 0.5 + 0.5 * erf2((x + vec2(-curved, curved)) * (sqrt(0.5) / sigma));
|
||||
return integral.y - integral.x;
|
||||
}
|
||||
|
||||
float boxShadow(vec2 p, vec4 rect, float sigma, float corner) {
|
||||
vec2 h = rect.zw * 0.5;
|
||||
p -= rect.xy + h;
|
||||
float low = p.y - h.y;
|
||||
float high = p.y + h.y;
|
||||
float y0 = clamp(-3.0 * sigma, low, high);
|
||||
float y1 = clamp(3.0 * sigma, low, high);
|
||||
float dy = (y1 - y0) / 4.0;
|
||||
float y = y0 + dy * 0.5;
|
||||
float v = 0.0;
|
||||
for (int k = 0; k < 4; k++) {
|
||||
v += shadowX(p.x, p.y - y, sigma, corner, h) * gaussian(y, sigma) * dy;
|
||||
y += dy;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
vec3 toLinear(vec3 c) {
|
||||
return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, lessThanEqual(c, vec3(0.04045)));
|
||||
}
|
||||
|
||||
vec3 toSRGB(vec3 c) {
|
||||
return mix(1.055 * pow(max(c, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055, c * 12.92,
|
||||
lessThanEqual(c, vec3(0.0031308)));
|
||||
}
|
||||
|
||||
vec3 cbrt3(vec3 v) { return sign(v) * pow(abs(v), vec3(1.0 / 3.0)); }
|
||||
|
||||
vec3 oklab(vec3 srgb) {
|
||||
vec3 c = toLinear(srgb);
|
||||
vec3 lms = cbrt3(vec3(0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b,
|
||||
0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b,
|
||||
0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b));
|
||||
return vec3(0.2104542553 * lms.x + 0.7936177850 * lms.y - 0.0040720468 * lms.z,
|
||||
1.9779984951 * lms.x - 2.4285922050 * lms.y + 0.4505937099 * lms.z,
|
||||
0.0259040371 * lms.x + 0.7827717662 * lms.y - 0.8086757660 * lms.z);
|
||||
}
|
||||
|
||||
vec3 fromOklab(vec3 lab) {
|
||||
vec3 lms = vec3(lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z,
|
||||
lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z,
|
||||
lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z);
|
||||
lms = lms * lms * lms;
|
||||
return toSRGB(vec3(4.0767416621 * lms.x - 3.3077115913 * lms.y + 0.2309699292 * lms.z,
|
||||
-1.2684380046 * lms.x + 2.6097574011 * lms.y - 0.3413193965 * lms.z,
|
||||
-0.0041960863 * lms.x - 0.7034186147 * lms.y + 1.7076147010 * lms.z));
|
||||
}
|
||||
|
||||
// stop returns texel k of the stops.
|
||||
vec4 stop(int k) {
|
||||
return texelFetch(uStops, ivec2(k % 1024, k / 1024), 0);
|
||||
}
|
||||
|
||||
// stopsAt returns the color at t of the gradient whose stops uStops holds
|
||||
// from first, n of them (gpu.Builder.Stops): the first stop's before it,
|
||||
// the last's after it, and between two the colors of both mixed,
|
||||
// premultiplied, in sRGB, or in Oklab, as internal/raster's stopsAt.
|
||||
vec4 stopsAt(vec4 c2, float t, bool lab) {
|
||||
int first = int(c2.x);
|
||||
int n = int(c2.y);
|
||||
if (n <= 0) {
|
||||
return vec4(0.0);
|
||||
}
|
||||
vec4 a = stop(2 * first);
|
||||
vec4 ap = stop(2 * first + 1);
|
||||
if (t <= ap.x) {
|
||||
return premul(a);
|
||||
}
|
||||
vec4 last = stop(2 * (first + n - 1));
|
||||
vec4 lastp = stop(2 * (first + n - 1) + 1);
|
||||
if (t >= lastp.x) {
|
||||
return premul(last);
|
||||
}
|
||||
vec4 b = last;
|
||||
vec4 bp = lastp;
|
||||
for (int i = 1; i < n - 1; i++) {
|
||||
vec4 c = stop(2 * (first + i));
|
||||
vec4 cp = stop(2 * (first + i) + 1);
|
||||
if (t < cp.x) {
|
||||
b = c;
|
||||
bp = cp;
|
||||
break;
|
||||
}
|
||||
a = c;
|
||||
ap = cp;
|
||||
}
|
||||
float f = clamp((t - ap.x) / max(bp.x - ap.x, 1e-6), 0.0, 1.0);
|
||||
float alpha = mix(a.a, b.a, f);
|
||||
if (!lab) {
|
||||
return vec4(mix(a.rgb * a.a, b.rgb * b.a, f), alpha);
|
||||
}
|
||||
if (alpha <= 0.0) {
|
||||
return vec4(0.0);
|
||||
}
|
||||
return vec4(clamp(fromOklab(mix(ap.yzw * a.a, bp.yzw * b.a, f) / alpha), 0.0, 1.0) * alpha, alpha);
|
||||
}
|
||||
|
||||
// paint returns the premultiplied color at p of plain color, a gradient
|
||||
// mixed in sRGB (1) or Oklab (2), stripes (3), or a gradient of stops,
|
||||
// linear (4, 5), conic (6, 7) or radial (8, 9), mixed in sRGB or in
|
||||
// Oklab, as scene.Paint says.
|
||||
vec4 paint(vec2 p, float mode, vec4 rect, vec4 c1, vec4 c2, vec4 g) {
|
||||
if (mode < 0.5) {
|
||||
return premul(c1);
|
||||
}
|
||||
if (mode > 3.5) {
|
||||
float t;
|
||||
if (mode < 5.5) {
|
||||
vec2 d = g.zw - g.xy;
|
||||
t = dot(p - g.xy, d) / max(dot(d, d), 0.0001);
|
||||
} else if (mode < 7.5) {
|
||||
vec2 d = p - g.xy;
|
||||
t = (atan(d.x, -d.y) - g.z) * 0.15915494309189535;
|
||||
t -= floor(t);
|
||||
} else {
|
||||
t = length(p - g.xy) / max(g.z, 0.0001);
|
||||
}
|
||||
return stopsAt(c2, t, mode > 4.5 && mode < 5.5 || mode > 6.5 && mode < 7.5 || mode > 8.5);
|
||||
}
|
||||
if (mode < 2.5) {
|
||||
vec2 d = g.zw - g.xy;
|
||||
float t = clamp(dot(p - g.xy, d) / max(dot(d, d), 0.0001), 0.0, 1.0);
|
||||
float a = mix(c1.a, c2.a, t);
|
||||
if (mode < 1.5) {
|
||||
return vec4(mix(c1.rgb * c1.a, c2.rgb * c2.a, t), a);
|
||||
}
|
||||
vec3 lab = mix(oklab(c1.rgb) * c1.a, oklab(c2.rgb) * c2.a, t);
|
||||
return a > 0.0 ? vec4(clamp(fromOklab(lab / a), 0.0, 1.0) * a, a) : vec4(0.0);
|
||||
}
|
||||
float s = dot(p - rect.xy, g.xy);
|
||||
float phase = s - g.w * floor(s / g.w);
|
||||
float cov = coverage(min(max(-phase, phase - g.z), g.w - phase));
|
||||
return premul(c1) * cov + premul(c2) * (1.0 - cov);
|
||||
}
|
||||
|
||||
// dash returns how much of a dashed border shows at p: each side, which
|
||||
// the pixel belongs to when it is nearest that side's edge in widths of
|
||||
// its border, has an odd number of dashes and gaps of equal length, about
|
||||
// three widths, starting and ending with a dash.
|
||||
float dash(vec2 p, vec4 rect, vec4 w) {
|
||||
vec2 q = p - rect.xy;
|
||||
float dt = w.x > 0.0 ? q.y / w.x : 1e9;
|
||||
float dr = w.y > 0.0 ? (rect.z - q.x) / w.y : 1e9;
|
||||
float db = w.z > 0.0 ? (rect.w - q.y) / w.z : 1e9;
|
||||
float dl = w.w > 0.0 ? q.x / w.w : 1e9;
|
||||
float s;
|
||||
float len;
|
||||
float bw;
|
||||
if (dt <= dr && dt <= db && dt <= dl) {
|
||||
s = q.x;
|
||||
len = rect.z;
|
||||
bw = w.x;
|
||||
} else if (dr <= db && dr <= dl) {
|
||||
s = q.y;
|
||||
len = rect.w;
|
||||
bw = w.y;
|
||||
} else if (db <= dl) {
|
||||
s = rect.z - q.x;
|
||||
len = rect.z;
|
||||
bw = w.z;
|
||||
} else {
|
||||
s = rect.w - q.y;
|
||||
len = rect.w;
|
||||
bw = w.w;
|
||||
}
|
||||
// n - 1 is how many periods of a dash and a gap, six widths, fit in
|
||||
// len: GPUs divide less exactly than CPUs, and may count one too few
|
||||
// or too many where len is a whole number of periods, as sides often
|
||||
// are, so the count is checked by multiplying back.
|
||||
float n = max(1.0, floor((len / (3.0 * bw) + 1.0) * 0.5 + 0.5));
|
||||
float period = 6.0 * bw;
|
||||
n += n * period <= len ? 1.0 : 0.0;
|
||||
n -= (n - 1.0) * period > len ? 1.0 : 0.0;
|
||||
float seg = len / (2.0 * n - 1.0);
|
||||
float k = floor(s / seg);
|
||||
float f = s - k * seg;
|
||||
float edge = min(f, seg - f);
|
||||
return coverage(k - 2.0 * floor(k * 0.5) < 0.5 ? -edge : edge);
|
||||
}
|
||||
|
||||
void main() {
|
||||
Frame fr = frameOf();
|
||||
vec2 p = vPoint.xy;
|
||||
vec2 tex = vPoint.zw;
|
||||
vec2 dtex = fwidth(tex);
|
||||
float kind = vParams.x;
|
||||
vec4 res;
|
||||
float glyphCov = vTransform0.w > 0.5 ? localCoverage(p, vRect, vec4(0.0), 1.0, fr) : 1.0;
|
||||
float clip = clipCoverage();
|
||||
// The dispatch below is a chain of ifs with early returns, not one else-if chain:
|
||||
// an else-if chain here fails to link in ANGLE's D3D11 backend on Windows (an
|
||||
// empty info log, and every WebGL context in the page is lost; Firefox's headless
|
||||
// build exits at the link). See https://issues.chromium.org/issues/573007971 and
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=2081240. The shape is load-bearing.
|
||||
if (kind < 0.5) {
|
||||
float outer = localCoverage(p, vRect, vRadii, vTransform0.w, fr);
|
||||
// vParams.y: 1 dashes the border, 2 paints it with the gradient (the
|
||||
// inside with plain color), 3 both.
|
||||
bool borderPaint = vParams.y > 1.5;
|
||||
vec4 pc = paint(p, vParams.z, vRect, vColor, vColor2, vGrad);
|
||||
res = (borderPaint ? premul(vColor) : pc) * outer;
|
||||
vec4 bw = vWidths; // top, right, bottom, left
|
||||
if (any(greaterThan(bw, vec4(0.0)))) {
|
||||
vec4 ir = vec4(vRect.xy + bw.wx, vRect.zw - bw.yz - bw.wx);
|
||||
float innerCov = (ir.z > 0.0 && ir.w > 0.0) ? localCoverage(p, ir, vInner, vTransform0.w, fr) : 0.0;
|
||||
float bc = clamp(outer - innerCov, 0.0, 1.0);
|
||||
float dashed = vParams.y - (borderPaint ? 2.0 : 0.0);
|
||||
if (dashed > 0.5) {
|
||||
bc *= dash(p, vRect, bw);
|
||||
}
|
||||
vec4 b = (borderPaint ? pc * vec4(vBorder.rgb * vBorder.a, vBorder.a) : premul(vBorder)) * bc;
|
||||
res = b + res * (1.0 - b.a);
|
||||
}
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 1.5 && vParams.y > 0.5) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float sigma = vParams.z;
|
||||
float hole = 0.0;
|
||||
if (vWidths.z > 0.0 && vWidths.w > 0.0) {
|
||||
float corner = max(max(vInner.x, vInner.y), max(vInner.z, vInner.w));
|
||||
hole = sigma > 0.0 ? boxShadow(p, vWidths, sigma, corner) : localCoverage(p, vWidths, vInner, vTransform0.w, fr);
|
||||
}
|
||||
res = premul(vColor) * (localCoverage(p, vRect, vRadii, vTransform0.w, fr) * (1.0 - hole));
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 1.5) {
|
||||
float sigma = vParams.z;
|
||||
float corner = max(max(vRadii.x, vRadii.y), max(vRadii.z, vRadii.w));
|
||||
float s =
|
||||
sigma > 0.0 ? boxShadow(p, vRect, sigma, corner) : localCoverage(p, vRect, vRadii, vTransform0.w, fr);
|
||||
if (vWidths.z > 0.0 && vWidths.w > 0.0) {
|
||||
s *= 1.0 - localCoverage(p, vWidths, vInner, vTransform0.w, fr); // outside the box casting it
|
||||
}
|
||||
res = premul(vColor) * s;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 2.5) {
|
||||
vec4 c = paint(p, vParams.z, vRect, vColor, vColor2, vGrad);
|
||||
res = c *
|
||||
textCoverage(sampleLocal(uMask, tex, vWidths, vTransform0.w).r, unpremul(c), vInner.x, vInner.y,
|
||||
vRadii) *
|
||||
glyphCov;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 3.5) {
|
||||
res = sampleLocal(uColor, tex, vWidths, vTransform0.w) * vColor.a * glyphCov;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 4.5) {
|
||||
if (vParams.y > 1.5) {
|
||||
// A frame of video: its luma and its chroma, converted.
|
||||
float code = vParams.y - 2.0;
|
||||
float gray = code > 7.5 ? 1.0 : 0.0;
|
||||
// The chroma covers twice its size in luma, a column or row
|
||||
// more than an odd size has.
|
||||
vec2 cs = vec2(textureSize(uImage, 0)) / (2.0 * vec2(textureSize(uChroma, 0)));
|
||||
res = vec4(yuvToRGB(sampleImage(uImage, tex, vWidths, vParams.z, dtex).r,
|
||||
sampleImage(uChroma, tex * cs, vWidths * cs.xyxy, vParams.z, dtex * cs).rg,
|
||||
code - 8.0 * gray),
|
||||
1.0);
|
||||
if (gray > 0.5) {
|
||||
res.rgb = vec3(dot(res.rgb, vec3(0.2126, 0.7152, 0.0722)));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(uImage, tex, vWidths, vParams.z, dtex);
|
||||
if (vParams.y > 0.5) {
|
||||
res.rgb = vec3(dot(res.rgb, vec3(0.2126, 0.7152, 0.0722)));
|
||||
}
|
||||
}
|
||||
res = tint(res, vColor) * localCoverage(p, vRect, vRadii, vTransform0.w, fr);
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
{
|
||||
vec4 c = paint(p, vParams.z, vRect, vColor, vColor2, vGrad);
|
||||
vec3 straight = unpremul(c);
|
||||
if (vTransform0.w > 0.5) {
|
||||
vec3 rgb = sampleLocal(uColor, tex, vWidths, 1.0).rgb;
|
||||
res = c * textCoverage((rgb.r + rgb.g + rgb.b) / 3.0, straight, vInner.x, vInner.y, vRadii) *
|
||||
glyphCov;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
vec3 a = subpixelCoverage(sampleLocal(uColor, tex, vWidths, vTransform0.w).rgb, straight, vInner.x,
|
||||
vInner.y, vRadii);
|
||||
vec3 w = a * c.a * clip * vParams.w;
|
||||
float wa = (w.r + w.g + w.b) / 3.0;
|
||||
#ifdef DUAL
|
||||
fragColor = vec4(straight * w, wa);
|
||||
fragAlpha = vec4(w, wa);
|
||||
#else
|
||||
fragColor = vec4(straight * wa, wa);
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// The passes computing the backdrop of an effect draw a quad over their
|
||||
// target, scissored to the texels they compute, and address texels by
|
||||
// their index in memory, so that the rows of their textures go down as
|
||||
// the frame's rows do.
|
||||
#ifdef PASS_VERTEX
|
||||
|
||||
void main() {
|
||||
vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
||||
gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef DOWN
|
||||
|
||||
// down averages the square of the area that texel stands for, repeating
|
||||
// the area's last pixels past its far edges, or, for an image blurred
|
||||
// (uMode & 1), reading them as transparent. The area of the frame (from
|
||||
// uOrigin to uLimit) is copied to uSrc from the bottom row up: the row y
|
||||
// of the frame is uShift.y - y there, and the column x is x - uShift.x;
|
||||
// an image whose rows go down (uMode & 2) has its row y at y - uShift.y.
|
||||
uniform sampler2D uSrc;
|
||||
uniform ivec2 uOrigin;
|
||||
uniform ivec2 uLimit;
|
||||
uniform ivec2 uShift;
|
||||
uniform int uDown;
|
||||
uniform int uMode;
|
||||
|
||||
out vec4 passColor;
|
||||
|
||||
void main() {
|
||||
ivec2 o = uOrigin + ivec2(gl_FragCoord.xy) * uDown;
|
||||
vec4 c = vec4(0.0);
|
||||
for (int y = 0; y < uDown; y++) {
|
||||
for (int x = 0; x < uDown; x++) {
|
||||
ivec2 at = o + ivec2(x, y);
|
||||
if ((uMode & 1) != 0 && (at.x > uLimit.x || at.y > uLimit.y)) {
|
||||
continue;
|
||||
}
|
||||
at = min(at, uLimit);
|
||||
int row = (uMode & 2) != 0 ? at.y - uShift.y : uShift.y - at.y;
|
||||
c += texelFetch(uSrc, ivec2(at.x - uShift.x, row), 0);
|
||||
}
|
||||
}
|
||||
passColor = c * (1.0 / float(uDown * uDown));
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef BLUR
|
||||
|
||||
// blur blurs along a row or a column, clamping at its ends, or, for an
|
||||
// image blurred (uMode & 1), transparent beyond them.
|
||||
uniform sampler2D uSrc;
|
||||
uniform ivec2 uLimit;
|
||||
uniform ivec2 uDir;
|
||||
uniform int uRadius;
|
||||
uniform float uSigma;
|
||||
uniform int uMode;
|
||||
|
||||
out vec4 passColor;
|
||||
|
||||
void main() {
|
||||
ivec2 at = ivec2(gl_FragCoord.xy);
|
||||
vec4 c = vec4(0.0);
|
||||
float sum = 0.0;
|
||||
for (int o = -uRadius; o <= uRadius; o++) {
|
||||
float x = float(o);
|
||||
float w = uSigma > 0.0 ? exp(-(x * x) / (2.0 * uSigma * uSigma)) : 1.0;
|
||||
ivec2 q = at + uDir * o;
|
||||
sum += w;
|
||||
if ((uMode & 1) != 0 && (any(lessThan(q, ivec2(0))) || any(greaterThan(q, uLimit)))) {
|
||||
continue;
|
||||
}
|
||||
c += texelFetch(uSrc, clamp(q, ivec2(0), uLimit), 0) * w;
|
||||
}
|
||||
passColor = c / sum;
|
||||
}
|
||||
|
||||
#endif
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// GLX's functions UnsyncGLXSwaps calls, through libepoxy's pointers, as GDK
|
||||
// calls them; nil where libepoxy has no GLX.
|
||||
var glx struct {
|
||||
once sync.Once
|
||||
currentDisplay *uintptr // glXGetCurrentDisplay
|
||||
currentContext *uintptr // glXGetCurrentContext
|
||||
currentDrawn *uintptr // glXGetCurrentDrawable
|
||||
queryContext *uintptr // glXQueryContext
|
||||
intervalEXT *uintptr // glXSwapIntervalEXT
|
||||
intervalMESA *uintptr // glXSwapIntervalMESA
|
||||
hasExtension func(dpy uintptr, screen int32, ext string) bool
|
||||
}
|
||||
|
||||
// glxScreen is GLX_SCREEN, which glXQueryContext tells.
|
||||
const glxScreen = 0x800C
|
||||
|
||||
// UnsyncGLXSwaps sets the swap interval of the GLX drawable current to 0,
|
||||
// so that its swaps wait for no vertical blank, for frames uncapped
|
||||
// (MYGO_UNCAPPED): the backend calls it as GDK paints a window it
|
||||
// composites with OpenGL on X11, with the window's paint context current.
|
||||
// GDK sets 1 there on a display without a compositor, which holds frames
|
||||
// to the display's refreshes, and 0 under a compositor, which paces the
|
||||
// window itself (gdk/x11/gdkglcontext-x11.c); GDK's EGL, on Wayland, swaps
|
||||
// with 0 already. It sets the interval with GLX_EXT_swap_control, else
|
||||
// GLX_MESA_swap_control (GLX_SGI_swap_control takes no 0), and does
|
||||
// nothing without either, or without a context current. GDK sets its own
|
||||
// interval again only when a compositor starts or stops, so a call each
|
||||
// paint keeps 0, which costs nothing once set.
|
||||
func UnsyncGLXSwaps() {
|
||||
if load() != nil {
|
||||
return
|
||||
}
|
||||
g := &glx
|
||||
g.once.Do(func() {
|
||||
lib, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ptr := func(name string) *uintptr {
|
||||
sym, err := purego.Dlsym(lib, "epoxy_"+name)
|
||||
if err != nil || sym == 0 {
|
||||
return nil
|
||||
}
|
||||
return *(**uintptr)(unsafe.Pointer(&sym))
|
||||
}
|
||||
if sym, err := purego.Dlsym(lib, "epoxy_has_glx_extension"); err == nil && sym != 0 {
|
||||
purego.RegisterFunc(&g.hasExtension, sym)
|
||||
}
|
||||
g.currentDisplay, g.currentContext, g.currentDrawn = ptr("glXGetCurrentDisplay"), ptr("glXGetCurrentContext"), ptr("glXGetCurrentDrawable")
|
||||
g.queryContext, g.intervalEXT, g.intervalMESA = ptr("glXQueryContext"), ptr("glXSwapIntervalEXT"), ptr("glXSwapIntervalMESA")
|
||||
})
|
||||
if g.hasExtension == nil || g.currentDisplay == nil || g.currentContext == nil || g.currentDrawn == nil || g.queryContext == nil {
|
||||
return
|
||||
}
|
||||
dpy, _, _ := purego.SyscallN(*g.currentDisplay)
|
||||
ctx, _, _ := purego.SyscallN(*g.currentContext)
|
||||
drawable, _, _ := purego.SyscallN(*g.currentDrawn)
|
||||
if dpy == 0 || ctx == 0 || drawable == 0 {
|
||||
return
|
||||
}
|
||||
var screen int32
|
||||
if r, _, _ := purego.SyscallN(*g.queryContext, dpy, ctx, glxScreen, uintptr(unsafe.Pointer(&screen))); r != 0 {
|
||||
return // not Success
|
||||
}
|
||||
switch {
|
||||
case g.intervalEXT != nil && g.hasExtension(dpy, screen, "GLX_EXT_swap_control"):
|
||||
purego.SyscallN(*g.intervalEXT, dpy, drawable, 0)
|
||||
case g.intervalMESA != nil && g.hasExtension(dpy, screen, "GLX_MESA_swap_control"):
|
||||
purego.SyscallN(*g.intervalMESA, 0)
|
||||
}
|
||||
}
|
||||
Vendored
+1347
File diff suppressed because it is too large.
Load diff
+1426
File diff suppressed because it is too large.
Load diff
+102
@@ -0,0 +1,102 @@
|
||||
package gputest
|
||||
|
||||
import "github.com/egoist/mygo/internal/scene"
|
||||
|
||||
// BoxesScene returns a w×h frame of n rounded boxes of 24 pixels, each
|
||||
// casting a shadow, in rows of 30, as an animation of boxes moving draws
|
||||
// them: under translations (Element.Translate) when translated, else at
|
||||
// the same places without transforms. The places fall between pixels.
|
||||
func BoxesScene(w, h, n int, translated bool) *scene.Scene {
|
||||
scene.FoldTranslations() // as package ui does
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
for i := range n {
|
||||
x, y := 8+float32(i%30)*40+float32(i%7)*0.25, 8+float32(i/30)*38+float32(i%5)*0.2
|
||||
m := scene.Translation(x, y)
|
||||
box := scene.Rect{W: 24, H: 24}
|
||||
if !translated {
|
||||
m, box.X, box.Y = scene.Affine{}, x, y
|
||||
}
|
||||
cast := box
|
||||
cast.Y += 2
|
||||
c := scene.Color{R: uint8(40 + i*7%180), G: uint8(80 + i*13%150), B: uint8(120 + i*3%120), A: 255}
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpShadow, Rect: cast, Radii: scene.Uniform(6), Color: scene.Color{A: 70}, Blur: 8, Transform: m},
|
||||
scene.Op{Kind: scene.OpFill, Rect: box, Radii: scene.Uniform(6), Color: c, Transform: m})
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// RowsScene returns a w×h frame of a list of n rows, as a window of a list
|
||||
// draws them: each a rounded background, a label of glyphs, a rounded
|
||||
// badge and a second label, so that plain fills and glyphs alternate.
|
||||
func RowsScene(w, h, n int) *scene.Scene {
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 250, G: 250, B: 250, A: 255}}
|
||||
atlas, text, glyphs := glyphContent()
|
||||
s.MaskAtlas, s.Text = atlas, text
|
||||
run := func(x, y float32, k int, c scene.Color) {
|
||||
start := len(s.Glyphs)
|
||||
for _, g := range glyphs[:k] {
|
||||
g.X, g.Y, g.Color = g.X-40+x, y, c
|
||||
s.Glyphs = append(s.Glyphs, g)
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpGlyphs, Start: int32(start), End: int32(len(s.Glyphs))})
|
||||
}
|
||||
rowH := float32(h-16) / float32(n)
|
||||
for i := range n {
|
||||
y := 8 + float32(i)*rowH
|
||||
bg := scene.Color{R: 236, G: 238, B: 242, A: 255}
|
||||
if i%2 == 1 {
|
||||
bg = scene.Color{R: 244, G: 245, B: 247, A: 255}
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 8, Y: y, W: float32(w) - 16, H: rowH - 2}, Radii: scene.Uniform(4), Color: bg})
|
||||
run(20, y+1.5, 8+i%5, scene.Color{R: 30, G: 30, B: 34, A: 255})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 260, Y: y + 2, W: 40, H: rowH - 6}, Radii: scene.Uniform(6),
|
||||
Color: scene.Color{R: uint8(60 + i*29%160), G: 120, B: 220, A: 255}})
|
||||
run(320, y+1.5, 4+i%7, scene.Color{R: 110, G: 110, B: 120, A: 255})
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// PanelsScene returns a w×h frame of n cards in rows of 8, as a page of an
|
||||
// app draws them: each a shadowed white card, its content in a rounded
|
||||
// clip, an icon (one of four images), a label of glyphs and a colored
|
||||
// badge. Clips and images change from card to card, so the frame takes
|
||||
// several batches a card, as pages of real windows do.
|
||||
func PanelsScene(w, h, n int) *scene.Scene {
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
atlas, text, glyphs := glyphContent()
|
||||
s.MaskAtlas, s.Text = atlas, text
|
||||
var icons [4]*scene.Image
|
||||
for k := range icons {
|
||||
pix := make([]byte, 16*16*4)
|
||||
for i := 0; i < len(pix); i += 4 {
|
||||
pix[i], pix[i+1], pix[i+2], pix[i+3] = byte(60*k), byte(i/4%16*16), 200, 255
|
||||
}
|
||||
icons[k] = scene.NewImageRGBA(16, 16, pix)
|
||||
}
|
||||
cw, ch := (float32(w)-16)/8, float32(64)
|
||||
for i := range n {
|
||||
x, y := 8+float32(i%8)*cw, 8+float32(i/8)*(ch+8)
|
||||
card := scene.Rect{X: x + 4, Y: y, W: cw - 8, H: ch}
|
||||
cast := card
|
||||
cast.Y += 2
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpShadow, Rect: cast, Radii: scene.Uniform(8), Color: scene.Color{A: 40}, Blur: 6},
|
||||
scene.Op{Kind: scene.OpFill, Rect: card, Radii: scene.Uniform(8), Color: scene.Color{R: 255, G: 255, B: 255, A: 255},
|
||||
Border: scene.Uniform(1), BorderColor: scene.Color{R: 220, G: 222, B: 228, A: 255}},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: card.X + 1, Y: card.Y + 1, W: card.W - 2, H: card.H - 2}, Radii: scene.Uniform(7)},
|
||||
scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: card.X + 10, Y: card.Y + 10, W: 20, H: 20}, Radii: scene.Uniform(4),
|
||||
Image: icons[i%len(icons)], Src: scene.Rect{W: 16, H: 16}})
|
||||
start := len(s.Glyphs)
|
||||
for _, g := range glyphs[:6+i%6] {
|
||||
g.X, g.Y, g.Color = g.X-40+card.X+40, card.Y+12, scene.Color{R: 30, G: 30, B: 34, A: 255}
|
||||
s.Glyphs = append(s.Glyphs, g)
|
||||
}
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpGlyphs, Start: int32(start), End: int32(len(s.Glyphs))},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: card.X + 10, Y: card.Y + 40, W: 36, H: 14}, Radii: scene.Uniform(7),
|
||||
Color: scene.Color{R: uint8(60 + i*29%160), G: 120, B: 220, A: 255}},
|
||||
scene.Op{Kind: scene.OpPopClip})
|
||||
}
|
||||
return s
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package gputest
|
||||
|
||||
import "github.com/egoist/mygo/internal/scene"
|
||||
|
||||
// CanvasScene returns a 120×80 scene showing canvases (scene.NewCanvas): a
|
||||
// 16×12 one drawn with fills, a rounded one, an image and a canvas of its
|
||||
// own, shown 4 times as large pixelated, then smooth and flipped; and a
|
||||
// canvas shown only within another, with nothing new to draw the second
|
||||
// time the renderer draws the scene; and a canvas drawing a conic gradient,
|
||||
// shown blurred, as a view blurred is (ui.Element.Blur).
|
||||
func CanvasScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 120, Height: 80, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
pix := make([]byte, 4*4*4)
|
||||
for i := range 16 {
|
||||
pix[4*i], pix[4*i+1], pix[4*i+2], pix[4*i+3] = byte(i*16), byte(255-i*16), 120, 255
|
||||
}
|
||||
img := scene.NewImageRGBA(4, 4, pix)
|
||||
|
||||
inner := scene.NewCanvas(4, 4)
|
||||
inner.Scene.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 4, H: 4}, Color: scene.Color{R: 250, G: 204, B: 21, A: 255}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 1, Y: 1, W: 2, H: 2}, Color: scene.Color{R: 20, G: 24, B: 32, A: 255}}}
|
||||
|
||||
c := scene.NewCanvas(16, 12)
|
||||
c.Scene.Ops = []scene.Op{
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{W: 16, H: 12}, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 1, Y: 1, W: 6, H: 6}, Radii: [4]float32{3, 3, 3, 3}, Color: scene.Color{R: 220, G: 40, B: 40, A: 200}},
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 9, Y: 1, W: 4, H: 4}, Image: img, Src: scene.Rect{W: 4, H: 4}},
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 2, Y: 7, W: 4, H: 4}, Image: inner, Src: scene.Rect{W: 4, H: 4}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 8, Y: 8, W: 8, H: 4}, Color: scene.Color{R: 255, G: 255, B: 255, A: 128}},
|
||||
}
|
||||
soft := scene.NewCanvas(40, 34)
|
||||
soft.Scene.Stops = []scene.Stop{{Color: scene.Color{R: 220, G: 40, B: 40, A: 255}, At: 0}, {Color: scene.Color{R: 37, G: 99, B: 235, A: 255}, At: 0.6},
|
||||
{Color: scene.Color{R: 220, G: 40, B: 40, A: 255}, At: 1}}
|
||||
soft.Scene.Ops = []scene.Op{
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 6, Y: 6, W: 28, H: 22}, Radii: [4]float32{6, 6, 6, 6}, Paint: scene.PaintConic,
|
||||
Gradient: [4]float32{20, 17, 0.3, 0}, Stops: [2]int32{0, 3}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 14, Y: 2, W: 4, H: 30}, Color: scene.Color{R: 20, G: 24, B: 32, A: 160}},
|
||||
}
|
||||
s.Canvases = []*scene.Image{c, soft}
|
||||
s.Ops = []scene.Op{
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 4, Y: 4, W: 64, H: 48}, Image: c, Src: scene.Rect{W: 16, H: 12}, Pixelated: true},
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 72, Y: 4, W: 44, H: 33}, Image: c, Src: scene.Rect{X: 16, W: -16, H: 12}},
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 74, Y: 42, W: 40, H: 34}, Image: soft, Src: scene.Rect{W: 40, H: 34}, Blur: 2.5},
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 4, Y: 56, W: 40, H: 20}, Image: soft, Src: scene.Rect{X: 0, Y: 34, W: 40, H: -34}, Blur: 5},
|
||||
}
|
||||
return s
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package gputest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BorderedCardScene returns the 756×640 frame of #531, a window of 378×320
|
||||
// DIPs at scale 2: an opaque backdrop, and on it a card of an opaque white
|
||||
// face with a border of 1 DIP (2 pixels) and corners of 12 DIPs (24
|
||||
// pixels), continuous (as macOS draws them) or not, on whole pixels, large
|
||||
// enough for the builder to draw it as an opaque core with pieces around it;
|
||||
// and a button with the same border above it, too small for that. Their
|
||||
// straight edges cover whole pixels, by 1 or 0, so a renderer draws them
|
||||
// exactly as the CPU renderer does (see CompareStraightEdges).
|
||||
func BorderedCardScene(continuous bool) *scene.Scene {
|
||||
backdrop := scene.Color{R: 0xf4, G: 0xf4, B: 0xf6, A: 255}
|
||||
face := scene.Color{R: 255, G: 255, B: 255, A: 255}
|
||||
line := scene.Color{R: 0xe3, G: 0xe3, B: 0xe7, A: 255}
|
||||
s := &scene.Scene{Width: 756, Height: 640}
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 756, H: 640}, Color: backdrop},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 26, Y: 90, W: 730, H: 484}, Radii: [4]float32{24, 24, 24, 24}, Continuous: continuous,
|
||||
Color: face, Border: scene.Uniform(2), BorderColor: line},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 100, Y: 16, W: 200, H: 56}, Radii: [4]float32{16, 16, 16, 16}, Continuous: continuous,
|
||||
Color: face, Border: scene.Uniform(2), BorderColor: line})
|
||||
return s
|
||||
}
|
||||
|
||||
// CompareStraightEdges compares pixels a renderer drew, as Compare does,
|
||||
// and requires more of those away from the corners of the scene's rounded
|
||||
// fills, along their straight edges and inside them, where coverage is
|
||||
// exactly 1 or 0 for shapes on whole pixels: each channel within 2 levels
|
||||
// of the CPU renderer's, at every pixel. It reports the rows (or columns)
|
||||
// that differ, so that a stray line along an edge shows where it is.
|
||||
func CompareStraightEdges(t testing.TB, name string, got []byte, stride int, s *scene.Scene) {
|
||||
t.Helper()
|
||||
Compare(t, name, got, stride, s)
|
||||
want := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(want, s)
|
||||
// The corners' boxes, as far as their curves reach (continuous ones 1.53
|
||||
// times their radius) and the antialiasing a pixel beyond.
|
||||
var corners []image.Rectangle
|
||||
for _, op := range s.Ops {
|
||||
if op.Kind != scene.OpFill || op.Radii == [4]float32{} {
|
||||
continue
|
||||
}
|
||||
r := max(op.Radii[0], op.Radii[1], op.Radii[2], op.Radii[3])
|
||||
e := int(r*1.6) + 3
|
||||
x0, y0 := int(op.Rect.X)-2, int(op.Rect.Y)-2
|
||||
x1, y1 := int(op.Rect.X+op.Rect.W)+2, int(op.Rect.Y+op.Rect.H)+2
|
||||
corners = append(corners, image.Rect(x0, y0, x0+e, y0+e), image.Rect(x1-e, y0, x1, y0+e),
|
||||
image.Rect(x1-e, y1-e, x1, y1), image.Rect(x0, y1-e, x0+e, y1))
|
||||
}
|
||||
off := 0
|
||||
rows := map[int]int{}
|
||||
var first []string
|
||||
for y := range s.Height {
|
||||
for x := range s.Width {
|
||||
p := image.Pt(x, y)
|
||||
loose := false
|
||||
for _, c := range corners {
|
||||
if p.In(c) {
|
||||
loose = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if loose {
|
||||
continue
|
||||
}
|
||||
g := got[y*stride+4*x:][:4]
|
||||
w := want.Pix[y*want.Stride+4*x:][:4]
|
||||
d := 0
|
||||
for c := range 4 {
|
||||
d = max(d, absInt(int(g[c])-int(w[c])))
|
||||
}
|
||||
if d > 2 {
|
||||
off++
|
||||
rows[y]++
|
||||
if len(first) < 8 {
|
||||
first = append(first, fmt.Sprintf("%v: BGRA %x, want %x", p, g, w))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if off > 0 {
|
||||
ys := slices.Sorted(maps.Keys(rows))
|
||||
var where []string
|
||||
for _, y := range ys[:min(len(ys), 16)] {
|
||||
where = append(where, fmt.Sprintf("row %d: %d", y, rows[y]))
|
||||
}
|
||||
t.Errorf("%s: %d pixels away from the corners differ from the CPU renderer's by more than 2, in %d rows (%s); first %s",
|
||||
name, off, len(rows), strings.Join(where, ", "), strings.Join(first, "; "))
|
||||
}
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
package gputest
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Changing makes random scenes and changes them a little at a time, as the
|
||||
// frames of an app do, for the tests of renderers drawing only what
|
||||
// changed: fills (with continuous corners too), shadows, glyphs, images,
|
||||
// gradients, effects reading their backdrops, clips (one nested in
|
||||
// another, transformed, now and then), transforms, and colors outside the
|
||||
// sRGB gamut.
|
||||
type Changing struct {
|
||||
rnd *rand.Rand
|
||||
atlas *scene.Atlas
|
||||
img *scene.Image
|
||||
// masks are rectangles of the atlas holding something.
|
||||
masks [][4]uint16
|
||||
// Clear is the color scenes start with.
|
||||
Clear scene.Color
|
||||
}
|
||||
|
||||
// NewChanging returns a maker of scenes from seed.
|
||||
func NewChanging(seed uint64) *Changing {
|
||||
m := &Changing{rnd: rand.New(rand.NewPCG(seed, 11)), atlas: scene.NewAtlas(1, 128, 128),
|
||||
Clear: scene.Color{R: 250, G: 250, B: 250, A: 255}}
|
||||
for range 6 {
|
||||
w, h := 4+m.rnd.IntN(12), 4+m.rnd.IntN(12)
|
||||
x, y, ok := m.atlas.Alloc(w, h)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
m.atlas.Put(x, y, w, h, m.pixels(w*h), w)
|
||||
m.masks = append(m.masks, [4]uint16{uint16(x), uint16(y), uint16(w), uint16(h)})
|
||||
}
|
||||
m.img = scene.NewImageRGBA(8, 8, m.pixels(8*8*4))
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Changing) pixels(n int) []byte {
|
||||
p := make([]byte, n)
|
||||
for i := range p {
|
||||
p[i] = byte(m.rnd.IntN(256))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (m *Changing) color() scene.Color {
|
||||
return scene.Color{R: uint8(m.rnd.IntN(256)), G: uint8(m.rnd.IntN(256)), B: uint8(m.rnd.IntN(256)), A: uint8(64 + m.rnd.IntN(192))}
|
||||
}
|
||||
|
||||
func (m *Changing) rect() scene.Rect {
|
||||
return scene.Rect{X: m.rnd.Float32()*300 - 10, Y: m.rnd.Float32()*220 - 10, W: 2 + m.rnd.Float32()*90, H: 2 + m.rnd.Float32()*70}
|
||||
}
|
||||
|
||||
// transform returns no transform mostly, else a translation, a rotation or
|
||||
// a scaling.
|
||||
func (m *Changing) transform() scene.Affine {
|
||||
switch m.rnd.IntN(8) {
|
||||
case 0:
|
||||
return scene.Translation(m.rnd.Float32()*20-10, m.rnd.Float32()*20-10)
|
||||
case 1:
|
||||
return scene.Translation(150, 110).Mul(scene.Rotation(m.rnd.Float32()*40 - 20)).Mul(scene.Translation(-150, -110))
|
||||
case 2:
|
||||
return scene.Scaling(0.8+m.rnd.Float32()*0.4, 0.8+m.rnd.Float32()*0.4)
|
||||
}
|
||||
return scene.Affine{}
|
||||
}
|
||||
|
||||
// wide gives op colors outside the sRGB gamut, now and then.
|
||||
func (m *Changing) wide(s *scene.Scene, op *scene.Op) {
|
||||
if m.rnd.IntN(4) != 0 {
|
||||
return
|
||||
}
|
||||
s.Wide = append(s.Wide, scene.WideColors{Color: [4]float32{-0.2 + m.rnd.Float32()*0.1, 1.1, -0.1, 1}, Set: scene.WideColor})
|
||||
op.Wide = uint16(len(s.Wide))
|
||||
}
|
||||
|
||||
// op returns a random operation that draws.
|
||||
func (m *Changing) op(s *scene.Scene) scene.Op {
|
||||
var op scene.Op
|
||||
switch m.rnd.IntN(8) {
|
||||
case 0, 1:
|
||||
r := m.rnd.Float32() * 12
|
||||
op = scene.Op{Kind: scene.OpFill, Rect: m.rect(), Radii: scene.Uniform(r), Color: m.color(),
|
||||
Border: scene.Uniform(float32(m.rnd.IntN(3))), BorderColor: m.color(), Continuous: m.rnd.IntN(3) == 0}
|
||||
if m.rnd.IntN(4) == 0 {
|
||||
op.Paint, op.Color2 = scene.PaintLinear, m.color()
|
||||
op.Gradient = [4]float32{op.Rect.X, op.Rect.Y, op.Rect.X + op.Rect.W, op.Rect.Y + op.Rect.H}
|
||||
}
|
||||
m.wide(s, &op)
|
||||
case 2:
|
||||
op = scene.Op{Kind: scene.OpShadow, Rect: m.rect(), Radii: scene.Uniform(4), Color: m.color(), Blur: m.rnd.Float32() * 16}
|
||||
case 3, 4:
|
||||
start := int32(len(s.Glyphs))
|
||||
for range 1 + m.rnd.IntN(3) {
|
||||
k := m.masks[m.rnd.IntN(len(m.masks))]
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: float32(m.rnd.IntN(300)), Y: float32(m.rnd.IntN(220)),
|
||||
W: float32(k[2]), H: float32(k[3]), U: k[0], V: k[1], UW: k[2], VH: k[3], Color: m.color()})
|
||||
}
|
||||
op = scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs))}
|
||||
case 5:
|
||||
op = scene.Op{Kind: scene.OpImage, Rect: m.rect(), Image: m.img, Src: scene.Rect{W: 8, H: 8}}
|
||||
default:
|
||||
r := m.rnd.Float32() * 20
|
||||
fx := scene.EffectOp{Effect: LensEffect, Blur: float32(m.rnd.IntN(4)) * 3}
|
||||
if m.rnd.IntN(3) == 0 {
|
||||
fx.Effect = TintEffect
|
||||
}
|
||||
fx.Params[0] = [4]float32{m.rnd.Float32() * 4}
|
||||
c := m.color()
|
||||
fx.Params[1] = [4]float32{float32(c.R) / 255, float32(c.G) / 255, float32(c.B) / 255, float32(c.A) / 255}
|
||||
s.Effects = append(s.Effects, fx)
|
||||
return scene.Op{Kind: scene.OpEffect, Rect: m.rect(), Radii: scene.Uniform(r), Start: int32(len(s.Effects) - 1)}
|
||||
}
|
||||
op.Transform = m.transform()
|
||||
return op
|
||||
}
|
||||
|
||||
// Scene returns a scene of 320×240 pixels.
|
||||
func (m *Changing) Scene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 240, Clear: m.Clear, MaskAtlas: m.atlas,
|
||||
Text: scene.TextParams{GammaRatios: scene.GammaRatios(1.8), Contrast: 1}}
|
||||
for range 12 {
|
||||
s.Ops = append(s.Ops, m.op(s))
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: m.rect(), Radii: scene.Uniform(6)})
|
||||
for range 6 {
|
||||
s.Ops = append(s.Ops, m.op(s))
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
for range 6 {
|
||||
s.Ops = append(s.Ops, m.op(s))
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Change changes s a little, as a frame of an app would, and says how.
|
||||
func (m *Changing) Change(s *scene.Scene) string {
|
||||
// Drawing operations, which can change freely, unlike clips.
|
||||
var drawing []int
|
||||
for i, op := range s.Ops {
|
||||
if op.Kind != scene.OpPushClip && op.Kind != scene.OpPopClip {
|
||||
drawing = append(drawing, i)
|
||||
}
|
||||
}
|
||||
i := drawing[m.rnd.IntN(len(drawing))]
|
||||
op := &s.Ops[i]
|
||||
switch m.rnd.IntN(10) {
|
||||
case 0:
|
||||
op.Color = m.color()
|
||||
return "color"
|
||||
case 1:
|
||||
if op.Kind == scene.OpGlyphs {
|
||||
s.Glyphs[op.Start].X += 3
|
||||
return "glyph moved"
|
||||
}
|
||||
op.Rect.X += m.rnd.Float32()*20 - 10
|
||||
return "moved"
|
||||
case 2:
|
||||
s.Ops = append(s.Ops[:i+1], s.Ops[i:]...)
|
||||
s.Ops[i] = m.op(s)
|
||||
return "inserted"
|
||||
case 3:
|
||||
if len(drawing) > 4 {
|
||||
s.Ops = append(s.Ops[:i], s.Ops[i+1:]...)
|
||||
return "deleted"
|
||||
}
|
||||
return "nothing"
|
||||
case 4:
|
||||
for j := range s.Ops {
|
||||
if s.Ops[j].Kind == scene.OpPushClip {
|
||||
s.Ops[j].Rect = m.rect()
|
||||
}
|
||||
}
|
||||
return "clip moved"
|
||||
case 5:
|
||||
// New pixels where glyphs are, as a transient mask of the next
|
||||
// frame takes the place of the last one's.
|
||||
k := m.masks[m.rnd.IntN(len(m.masks))]
|
||||
m.atlas.Put(int(k[0]), int(k[1]), int(k[2]), int(k[3]), m.pixels(int(k[2])*int(k[3])), int(k[2]))
|
||||
return "atlas pixels"
|
||||
case 6:
|
||||
copy(m.img.Pix, m.pixels(len(m.img.Pix)))
|
||||
m.img.Changed()
|
||||
return "image pixels"
|
||||
case 7:
|
||||
op.Transform = m.transform()
|
||||
return "transform"
|
||||
case 8:
|
||||
if op.Wide != 0 {
|
||||
s.Wide[op.Wide-1].Color[0] = -0.3 + m.rnd.Float32()*0.2
|
||||
return "wide color"
|
||||
}
|
||||
if op.Kind == scene.OpEffect {
|
||||
s.Effects[op.Start].Params[0][0] = m.rnd.Float32() * 4
|
||||
return "effect"
|
||||
}
|
||||
return "nothing"
|
||||
case 9:
|
||||
return m.nest(s)
|
||||
default:
|
||||
return "nothing"
|
||||
}
|
||||
}
|
||||
|
||||
// nest takes the clip nested in the scene's, moved by a translation, out
|
||||
// of s, or puts one in, with a fill: the renderers then cut what the
|
||||
// outer clip holds with a mask, as it holds a transformed clip, rather
|
||||
// than in the shader, which draws its edge a unit in the last place
|
||||
// apart, so all it holds changes.
|
||||
func (m *Changing) nest(s *scene.Scene) string {
|
||||
for k := range s.Ops {
|
||||
if s.Ops[k].Kind != scene.OpPushClip || !s.Ops[k].Transform.Set {
|
||||
continue
|
||||
}
|
||||
end := k + 1
|
||||
for end < len(s.Ops) && s.Ops[end].Kind != scene.OpPopClip {
|
||||
end++
|
||||
}
|
||||
s.Ops = append(s.Ops[:k], s.Ops[min(end+1, len(s.Ops)):]...)
|
||||
return "nested clip out"
|
||||
}
|
||||
// Before the outer clip's end.
|
||||
at := -1
|
||||
for k, op := range s.Ops {
|
||||
if op.Kind == scene.OpPopClip {
|
||||
at = k
|
||||
break
|
||||
}
|
||||
}
|
||||
if at < 0 {
|
||||
return "nothing"
|
||||
}
|
||||
inner := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 60, H: 40}, Radii: scene.Uniform(4),
|
||||
Transform: scene.Translation(m.rnd.Float32()*240, m.rnd.Float32()*180)}
|
||||
fill := scene.Op{Kind: scene.OpFill, Rect: m.rect(), Color: m.color()}
|
||||
s.Ops = append(s.Ops[:at], append([]scene.Op{inner, fill, {Kind: scene.OpPopClip}}, s.Ops[at:]...)...)
|
||||
return "nested clip in"
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package gputest
|
||||
|
||||
import "github.com/egoist/mygo/internal/scene"
|
||||
|
||||
// CornerClipScene has clips that reach into the rounded corners of a clip
|
||||
// around them, whose corners must cut what they hold (#1418), at the size
|
||||
// of the reference scene (Scene): first a card as package ui draws it at
|
||||
// scale 2, rounded and clipped, holding a column that clips too and fills
|
||||
// the card's bottom; then a card holding a pane with a clip nested in it
|
||||
// at its bottom, a rounded clip in its corner, and one in its middle, away
|
||||
// from the corners.
|
||||
func CornerClipScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 740, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
add := func(ops ...scene.Op) { s.Ops = append(s.Ops, ops...) }
|
||||
r4 := func(v float32) [4]float32 { return [4]float32{v, v, v, v} }
|
||||
white := scene.Color{R: 255, G: 255, B: 255, A: 255}
|
||||
pop := scene.Op{Kind: scene.OpPopClip}
|
||||
|
||||
card := scene.Rect{X: 10, Y: 20, W: 300, H: 240}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: card, Radii: r4(20), Color: white},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 12, Y: 22, W: 296, H: 236}, Radii: r4(18)},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 12, Y: 102, W: 296, H: 156}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 12, Y: 102, W: 296, H: 156}, Color: scene.Color{G: 122, B: 255, A: 255}},
|
||||
pop, pop,
|
||||
scene.Op{Kind: scene.OpFill, Rect: card, Radii: r4(20), Border: scene.Uniform(2), BorderColor: scene.Color{R: 180, G: 180, B: 180, A: 255}})
|
||||
|
||||
card = scene.Rect{X: 10, Y: 300, W: 300, H: 280}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: card, Radii: r4(24), Color: white},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: card, Radii: r4(24)},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 300, W: 110, H: 280}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 10, Y: 300, W: 110, H: 280}, Color: scene.Color{R: 210, G: 214, B: 224, A: 255}},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 500, W: 110, H: 80}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 490, W: 130, H: 100}, Color: scene.Color{R: 220, G: 40, B: 40, A: 255}},
|
||||
pop, pop,
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 230, Y: 420, W: 80, H: 160}, Radii: r4(10)},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 220, Y: 410, W: 100, H: 180}, Color: scene.Color{R: 30, G: 160, B: 90, A: 255}},
|
||||
pop,
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 140, Y: 340, W: 80, H: 160}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 130, Y: 330, W: 100, H: 180}, Color: scene.Color{R: 250, G: 204, B: 21, A: 255}},
|
||||
pop, pop)
|
||||
return s
|
||||
}
|
||||
|
||||
// ContinuousCornerClipScene has clips with square corners against the
|
||||
// sides of a clip with continuous corners, whose curves must cut what they
|
||||
// hold (#1511), as package ui draws an app's rounded frame on macOS: first
|
||||
// a frame holding a sidebar that clips, against its left side, a toolbar
|
||||
// that clips, in its top right corner, and content that does not clip;
|
||||
// then a card holding a pane whose edge is between pixels, and a rounded
|
||||
// clip in its corner, which a mask cuts.
|
||||
func ContinuousCornerClipScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 640, Height: 420, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
add := func(ops ...scene.Op) {
|
||||
for _, op := range ops {
|
||||
op.Continuous = op.Radii != [4]float32{}
|
||||
s.Ops = append(s.Ops, op)
|
||||
}
|
||||
}
|
||||
white := scene.Color{R: 255, G: 255, B: 255, A: 255}
|
||||
pop := scene.Op{Kind: scene.OpPopClip}
|
||||
|
||||
frame := scene.Rect{X: 16, Y: 16, W: 608, H: 240}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: frame, Radii: scene.Uniform(14), Color: white},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 18, Y: 18, W: 604, H: 236}, Radii: scene.Uniform(12)},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 18, Y: 18, W: 180, H: 236}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 0, W: 200, H: 280}, Color: scene.Color{R: 210, G: 214, B: 224, A: 255}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 10, Y: 200, W: 60, H: 70}, Color: scene.Color{R: 220, G: 40, B: 40, A: 255}},
|
||||
pop,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 190, Y: 10, W: 450, H: 260}, Color: scene.Color{G: 122, B: 255, A: 255}},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 198, Y: 18, W: 424, H: 40}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 190, Y: 10, W: 450, H: 60}, Color: scene.Color{R: 30, G: 160, B: 90, A: 255}},
|
||||
pop, pop,
|
||||
scene.Op{Kind: scene.OpFill, Rect: frame, Radii: scene.Uniform(14), Border: scene.Uniform(2), BorderColor: scene.Color{R: 180, G: 180, B: 180, A: 255}})
|
||||
|
||||
card := scene.Rect{X: 16, Y: 280, W: 608, H: 124}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: card, Radii: scene.Uniform(16), Color: white},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: card, Radii: scene.Uniform(16)},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 16, Y: 280, W: 120.5, H: 124}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 270, W: 160, H: 150}, Color: scene.Color{R: 250, G: 204, B: 21, A: 255}},
|
||||
pop,
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 488, Y: 344, W: 136, H: 60}, Radii: scene.Uniform(8)},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 480, Y: 330, W: 160, H: 90}, Color: scene.Color{R: 30, G: 160, B: 90, A: 255}},
|
||||
pop, pop)
|
||||
return s
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
package gputest
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// CullCases are scenes of overlapping fills and what they hide: text,
|
||||
// images, shadows and fills under opaque panels, with square, round and
|
||||
// continuous corners; panels that do not hide what is under them
|
||||
// (translucent, transformed, at half opacity, gradients, clipped to less,
|
||||
// rounded clips, an effect reading what is under them); layers as large as
|
||||
// the frame; and an occluder in the clear color.
|
||||
func CullCases() []CullCase {
|
||||
white := scene.Color{R: 255, G: 255, B: 255, A: 255}
|
||||
paper := scene.Color{R: 246, G: 247, B: 249, A: 255}
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
|
||||
// base returns a scene with a mask atlas holding a disc, an image, and
|
||||
// the helpers adding ops.
|
||||
type builder struct {
|
||||
s *scene.Scene
|
||||
u, v uint16
|
||||
img *scene.Image
|
||||
}
|
||||
base := func(clear scene.Color) *builder {
|
||||
s := &scene.Scene{Width: 400, Height: 300, Clear: clear,
|
||||
Text: scene.TextParams{GammaRatios: scene.GammaRatios(1.8), Contrast: 1, SubpixelContrast: 0.5}}
|
||||
s.MaskAtlas = scene.NewAtlas(1, 64, 64)
|
||||
disc := make([]byte, 16*16)
|
||||
for y := range 16 {
|
||||
for x := range 16 {
|
||||
dx, dy := float64(x)-7.5, float64(y)-7.5
|
||||
disc[y*16+x] = byte(255 * clamp(7.5-math.Sqrt(dx*dx+dy*dy)))
|
||||
}
|
||||
}
|
||||
x, y, _ := s.MaskAtlas.Alloc(16, 16)
|
||||
s.MaskAtlas.Put(x, y, 16, 16, disc, 16)
|
||||
pix := make([]byte, 8*8*4)
|
||||
for i := 0; i < len(pix); i += 4 {
|
||||
pix[i], pix[i+1], pix[i+2], pix[i+3] = byte(i), byte(255-i), 160, 255
|
||||
}
|
||||
return &builder{s: s, u: uint16(x), v: uint16(y), img: scene.NewImageRGBA(8, 8, pix)}
|
||||
}
|
||||
add := func(b *builder, op scene.Op) { b.s.Ops = append(b.s.Ops, op) }
|
||||
fill := func(b *builder, r scene.Rect, radius float32, c scene.Color) {
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: r, Radii: r4(radius), Color: c})
|
||||
}
|
||||
text := func(b *builder, x, y float32, n int) {
|
||||
start := int32(len(b.s.Glyphs))
|
||||
for i := range n {
|
||||
b.s.Glyphs = append(b.s.Glyphs, scene.Glyph{X: x + float32(i*14), Y: y, W: 16, H: 16, U: b.u, V: b.v, UW: 16, VH: 16, Color: ink})
|
||||
}
|
||||
add(b, scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(b.s.Glyphs))})
|
||||
}
|
||||
image := func(b *builder, r scene.Rect) {
|
||||
add(b, scene.Op{Kind: scene.OpImage, Rect: r, Image: b.img, Src: scene.Rect{W: 8, H: 8}})
|
||||
}
|
||||
rect := func(x, y, w, h float32) scene.Rect { return scene.Rect{X: x, Y: y, W: w, H: h} }
|
||||
var out []CullCase
|
||||
cs := func(name string, b *builder, culled int) { out = append(out, CullCase{name, b.s, culled}) }
|
||||
|
||||
// Stacked panels: text, an image, a shadow and a fill under an opaque
|
||||
// panel with square corners, which lies on the page, as large as the
|
||||
// frame. 4 ops are hidden: the glyphs, the image, the shadow and the fill.
|
||||
b := base(scene.Color{A: 255})
|
||||
fill(b, rect(0, 0, 400, 300), 0, paper)
|
||||
text(b, 60, 60, 5)
|
||||
image(b, rect(100, 100, 40, 40))
|
||||
add(b, scene.Op{Kind: scene.OpShadow, Rect: rect(150, 120, 60, 40), Radii: r4(8), Color: scene.Color{A: 90}, Blur: 12})
|
||||
fill(b, rect(40.5, 40.25, 200, 150), 0, red)
|
||||
fill(b, rect(20, 20, 300, 240), 0, white)
|
||||
fill(b, rect(180, 100, 160, 120), 0, blue)
|
||||
text(b, 200, 130, 4)
|
||||
cs("stacked panels", b, 4)
|
||||
|
||||
// Rounded and continuous corners: a card hides what lies inside its
|
||||
// curves, the glyphs; the small fills near its corners stay, and so does
|
||||
// the large fill under it.
|
||||
for _, cont := range []bool{false, true} {
|
||||
b = base(paper)
|
||||
fill(b, rect(10, 10, 380, 280), 0, blue)
|
||||
fill(b, rect(60, 60, 20, 20), 0, red)
|
||||
fill(b, rect(320, 220, 30, 30), 0, red)
|
||||
text(b, 140, 130, 3)
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(50, 50, 300, 200), Radii: r4(40), Continuous: cont, Color: white})
|
||||
name := "rounded card"
|
||||
if cont {
|
||||
name = "continuous card"
|
||||
}
|
||||
cs(name, b, 1)
|
||||
}
|
||||
|
||||
// A translucent panel, one at half opacity, a gradient and a
|
||||
// transformed one hide nothing.
|
||||
b = base(paper)
|
||||
text(b, 60, 60, 4)
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(20, 20, 200, 100), Color: scene.Color{R: 255, G: 255, B: 255, A: 200}})
|
||||
text(b, 60, 140, 4)
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(20, 120, 200, 100), Color: white, Opacity: 0.5})
|
||||
text(b, 240, 60, 4)
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(230, 20, 150, 100), Color: red, Color2: blue, Paint: scene.PaintLinear, Gradient: [4]float32{230, 0, 380, 0}})
|
||||
text(b, 240, 160, 4)
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(230, 130, 150, 100), Color: white, Transform: scene.Translation(2, 3).Mul(scene.Scaling(1, 1.01))})
|
||||
cs("panels that hide nothing", b, 0)
|
||||
|
||||
// Transformed content under a panel is hidden all the same, by its
|
||||
// bounds, and the panel's own transform is what stops it from hiding.
|
||||
b = base(paper)
|
||||
start := int32(len(b.s.Glyphs))
|
||||
b.s.Glyphs = append(b.s.Glyphs, scene.Glyph{X: 60, Y: 60, W: 16, H: 16, U: b.u, V: b.v, UW: 16, VH: 16, Color: ink})
|
||||
add(b, scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(b.s.Glyphs)), Transform: scene.Scaling(1.5, 1.2)})
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(100, 100, 40, 40), Radii: r4(6), Color: red, Transform: scene.Scaling(1.1, 1).Mul(scene.Translation(3, 2))})
|
||||
fill(b, rect(20, 20, 300, 240), 0, white)
|
||||
cs("transformed content", b, 2)
|
||||
|
||||
// A wide translucent border is not the fill's color: glyphs under it stay.
|
||||
b = base(paper)
|
||||
text(b, 25, 25, 4)
|
||||
add(b, scene.Op{Kind: scene.OpFill, Rect: rect(20, 20, 200, 100), Color: white, Border: scene.Uniform(30), BorderColor: scene.Color{R: 255, A: 100}})
|
||||
cs("wide translucent border", b, 0)
|
||||
|
||||
// A clip: an opaque layer hides what lies in the clip, drawn before or
|
||||
// after the clip, and in the layer; the page, which the clip does not
|
||||
// reach, and text on it stay.
|
||||
b = base(paper)
|
||||
fill(b, rect(0, 0, 400, 300), 0, blue)
|
||||
text(b, 40, 40, 3)
|
||||
add(b, scene.Op{Kind: scene.OpPushClip, Rect: rect(30.5, 30, 200, 100)})
|
||||
text(b, 60, 60, 3)
|
||||
fill(b, rect(100, 90, 50, 80), 0, red)
|
||||
fill(b, rect(0, 0, 400, 300), 0, white)
|
||||
add(b, scene.Op{Kind: scene.OpPopClip})
|
||||
text(b, 260, 200, 3)
|
||||
cs("clipped occluder", b, 3)
|
||||
|
||||
// A clip with a fractional edge antialiases it, and shows what is under.
|
||||
b = base(paper)
|
||||
text(b, 60, 100, 3)
|
||||
add(b, scene.Op{Kind: scene.OpPushClip, Rect: rect(30, 30, 200, 70.5)})
|
||||
fill(b, rect(0, 0, 400, 300), 0, white)
|
||||
add(b, scene.Op{Kind: scene.OpPopClip})
|
||||
cs("fractional clip edge", b, 0)
|
||||
|
||||
b = base(paper)
|
||||
add(b, scene.Op{Kind: scene.OpPushClip, Rect: rect(30, 30, 200, 100), Radii: r4(20)})
|
||||
text(b, 60, 60, 3)
|
||||
fill(b, rect(0, 0, 400, 300), 0, white) // under a rounded clip: antialiased edge, hides nothing
|
||||
add(b, scene.Op{Kind: scene.OpPopClip})
|
||||
cs("rounded clip", b, 0)
|
||||
|
||||
// A panel and what only partly lies under it.
|
||||
b = base(paper)
|
||||
text(b, 25, 60, 6) // reaches out of the panel at 20..100? starts at 25, ends ~109
|
||||
fill(b, rect(20, 20, 85, 200), 0, white)
|
||||
cs("glyphs partly exposed", b, 0)
|
||||
|
||||
// An effect reading what is under it, reaching out of the panel on top.
|
||||
b = base(paper)
|
||||
fill(b, rect(60, 60, 60, 60), 0, red)
|
||||
fx := scene.EffectOp{Effect: LensEffect, Blur: 4}
|
||||
fx.Params[0] = [4]float32{2}
|
||||
fx.Params[1] = [4]float32{0.5, 0.5, 1, 0.3}
|
||||
add(b, scene.Op{Kind: scene.OpEffect, Rect: rect(40, 40, 120, 120), Radii: r4(20), Start: 0})
|
||||
b.s.Effects = append(b.s.Effects, fx)
|
||||
fill(b, rect(30, 30, 100, 100), 0, white)
|
||||
cs("effect between", b, 0)
|
||||
|
||||
// An occluder in the clear color hides what is under it all the same.
|
||||
b = base(paper)
|
||||
text(b, 60, 60, 4)
|
||||
image(b, rect(100, 100, 40, 40))
|
||||
fill(b, rect(30, 30, 200, 150), 10, paper)
|
||||
cs("occluder in the clear color", b, 2)
|
||||
|
||||
// Layers as large as the frame; hole and shadows under them.
|
||||
b = base(scene.Color{A: 255})
|
||||
fill(b, rect(0, 0, 400, 300), 0, blue)
|
||||
add(b, scene.Op{Kind: scene.OpShadow, Rect: rect(100, 100, 100, 100), Radii: r4(10), Color: scene.Color{A: 120}, Blur: 20})
|
||||
add(b, scene.Op{Kind: scene.OpHole, Rect: rect(100, 100, 100, 100)})
|
||||
fill(b, rect(-10, -10, 420, 320), 0, white)
|
||||
fill(b, rect(0, 0, 400, 300), 0, paper)
|
||||
cs("frame sized layers", b, 4)
|
||||
|
||||
// A hole after an opaque fill, and an opaque fill after a hole.
|
||||
b = base(paper)
|
||||
fill(b, rect(20, 20, 200, 200), 0, blue)
|
||||
add(b, scene.Op{Kind: scene.OpHole, Rect: rect(110, 110, 20, 20), Radii: r4(4)})
|
||||
fill(b, rect(100, 100, 100, 100), 0, red)
|
||||
add(b, scene.Op{Kind: scene.OpHole, Rect: rect(120, 120, 20, 20)})
|
||||
fill(b, rect(110, 110, 30, 30), 0, white)
|
||||
cs("holes", b, 1)
|
||||
|
||||
// Nested panels, each lying on a larger one drawn later: all but the
|
||||
// last are hidden.
|
||||
b = base(paper)
|
||||
for i := 18; i >= 0; i-- {
|
||||
fill(b, rect(float32(i*8), float32(i*8), 400-float32(i*16), 300-float32(i*16)), 0, scene.Color{R: byte(40 + i*10), G: 100, B: 200, A: 255})
|
||||
}
|
||||
cs("nested panels", b, 18)
|
||||
return out
|
||||
}
|
||||
|
||||
// FillScene returns a w×h scene of plain fills, the kind most of a window
|
||||
// is made of: layers as large as the frame, panels with square and round
|
||||
// corners at fractional places, rows in a clip that holds some whole and
|
||||
// cuts others, fills of every opacity, a gradient, a border and a transformed
|
||||
// fill among them, over the clear color. Sizes at or above 2048 pixels take
|
||||
// the interpolated coordinates across binades of float32.
|
||||
func FillScene(w, h int) *scene.Scene {
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 12, G: 10, B: 9, A: 255}}
|
||||
fw, fh := float32(w), float32(h)
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
add := func(op scene.Op) { s.Ops = append(s.Ops, op) }
|
||||
shade := func(i int) scene.Color {
|
||||
return scene.Color{R: byte(20 + i*37%200), G: byte(10 + i*53%220), B: byte(40 + i*71%200), A: 255}
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: fw, H: fh}, Color: shade(1)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: fw / 6, Y: 16.25, W: fw * 2 / 3, H: fh - 40.5}, Radii: r4(24), Color: shade(2)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: fw/6 + 2, Y: 154, W: fw*2/3 - 4, H: fh - 190}, Color: shade(3)})
|
||||
// Rows in a clip: some inside it, one cut at each end.
|
||||
cx, cy, cw, ch := fw/6+2, float32(154), fw*2/3-4, fh-190
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: cx + 10.5, Y: cy + 20.25, W: cw - 21, H: ch - 40}})
|
||||
for i := range 40 {
|
||||
y := cy + 10 + float32(i)*(ch-20)/40
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: cx + 5.5, Y: y, W: cw - 11, H: (ch-20)/40 - 1.5}, Color: shade(i + 4)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: cx + 30, Y: y + 2, W: cw / 3, H: 6.5}, Radii: r4(3), Color: shade(i + 9), Opacity: 0.5 + float32(i%3)/6})
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
// A rounded clip, and an op touching its edge.
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: cx + 40, Y: cy + 40, W: 300, H: 200}, Radii: r4(20)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: cx + 30, Y: cy + 100, W: 400, H: 60}, Color: shade(50)})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: cx + 400, Y: cy + 30, W: 200, H: 80}, Color: shade(60), Color2: shade(61), Paint: scene.PaintLinear, Gradient: [4]float32{cx + 400, 0, cx + 600, 0}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: cx + 400, Y: cy + 130, W: 200, H: 80}, Radii: r4(12), Color: shade(62), Border: scene.Uniform(2), BorderColor: shade(63)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: cx + 400, Y: cy + 230, W: 200, H: 80}, Color: shade(64), Transform: scene.Scaling(1.01, 1)})
|
||||
// The edges of the frame: fills reaching and passing it.
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: -5, Y: fh - 30, W: fw + 10, H: 30}, Color: shade(70)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: fw - 20, Y: 0, W: 20, H: fh}, Color: shade(71), Opacity: 0.4})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 0, W: fw, H: 1.5}, Color: shade(72)})
|
||||
return s
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package gputest
|
||||
|
||||
import "github.com/egoist/mygo/internal/scene"
|
||||
|
||||
// Effects for the renderers' tests, as plugins define theirs (see
|
||||
// scene.Effect). LensEffect shows its backdrop, sampled further right
|
||||
// within 8 pixels of its edge, by p0.x pixels a pixel, mixed with the
|
||||
// straight color p1 by its alpha; TintEffect paints p1 alone, reading no
|
||||
// backdrop.
|
||||
var (
|
||||
LensEffect = &scene.Effect{
|
||||
Name: "lens",
|
||||
Backdrop: true,
|
||||
Metal: scene.EffectCode{Source: `
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
float d = max(8.0f + sdRoundRect(p, e.rect, e.radii), 0.0f) * e.p0.x;
|
||||
float3 c = sampleBackdrop(backdrop, e, p + float2(d, 0.0f));
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
return float4(c, 1.0f);
|
||||
}`},
|
||||
HLSL: scene.EffectCode{Source: `
|
||||
float4 effect(float2 p, Effect e) {
|
||||
float d = max(8 + sdRoundRect(p, e.rect, e.radii), 0) * e.p0.x;
|
||||
float3 c = sampleBackdrop(e, p + float2(d, 0));
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
return float4(c, 1);
|
||||
}`},
|
||||
GLSL: `
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
float d = max(8.0 + sdRoundRect(p, e.rect, e.radii), 0.0) * e.p0.x;
|
||||
vec3 c = sampleBackdrop(e, p + vec2(d, 0.0));
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
return vec4(c, 1.0);
|
||||
}`,
|
||||
Pixels: func() scene.EffectPixels { return &testPixels{} },
|
||||
}
|
||||
TintEffect = &scene.Effect{
|
||||
Name: "tint",
|
||||
Metal: scene.EffectCode{Source: `
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
return float4(e.p1.rgb * e.p1.a, e.p1.a);
|
||||
}`},
|
||||
HLSL: scene.EffectCode{Source: `
|
||||
float4 effect(float2 p, Effect e) {
|
||||
return float4(e.p1.rgb * e.p1.a, e.p1.a);
|
||||
}`},
|
||||
GLSL: `
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
return vec4(e.p1.rgb * e.p1.a, e.p1.a);
|
||||
}`,
|
||||
Pixels: func() scene.EffectPixels { return &testPixels{} },
|
||||
}
|
||||
)
|
||||
|
||||
// testPixels draws LensEffect and TintEffect on the CPU.
|
||||
type testPixels struct {
|
||||
op *scene.EffectOp
|
||||
rect scene.Rect
|
||||
radii [4]float32
|
||||
}
|
||||
|
||||
func (t *testPixels) Begin(op *scene.EffectOp, rect scene.Rect, radii [4]float32) {
|
||||
t.op, t.rect, t.radii = op, rect, radii
|
||||
}
|
||||
|
||||
func (t *testPixels) Color(x, y float32, b *scene.BackdropImage) [4]float32 {
|
||||
tint := t.op.Params[1]
|
||||
if b == nil {
|
||||
return [4]float32{tint[0] * tint[3], tint[1] * tint[3], tint[2] * tint[3], tint[3]}
|
||||
}
|
||||
d := max(8+scene.SDRoundRect(t.rect, t.radii, x, y), 0) * t.op.Params[0][0]
|
||||
c := b.Sample(x+d, y)
|
||||
for i := range c {
|
||||
c[i] += (tint[i] - c[i]) * tint[3]
|
||||
}
|
||||
return [4]float32{c[0], c[1], c[2], 1}
|
||||
}
|
||||
+838
@@ -0,0 +1,838 @@
|
||||
// Package gputest has what the tests of the GPU renderers share: a scene
|
||||
// that draws every kind of operation, and a comparison of what a renderer
|
||||
// drew with what the CPU renderer draws, which the renderers must match.
|
||||
package gputest
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Scene returns a 320×600 scene with fills, borders of every width and
|
||||
// dashed, gradients mixed in sRGB and Oklab, stripes, shadows, blurred or
|
||||
// not, and cut by the boxes casting them, inner shadows, a hole, nested
|
||||
// rounded clips, glyphs from both atlases and subpixel ones, plain and in
|
||||
// gradients, with Direct2D's gamma and contrast, images, in color and in
|
||||
// gray, and effects, reading their backdrop blurred at each size or not,
|
||||
// over each other, clipped and at the frame's edge, or reading none.
|
||||
func Scene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 740, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255},
|
||||
Text: scene.TextParams{GammaRatios: scene.GammaRatios(1.8), Contrast: 1, SubpixelContrast: 0.5}}
|
||||
mask := scene.NewAtlas(1, 64, 64)
|
||||
color := scene.NewAtlas(4, 64, 32)
|
||||
s.MaskAtlas, s.ColorAtlas = mask, color
|
||||
// A disc and a ring as glyph masks, and a color glyph.
|
||||
disc := make([]byte, 16*16)
|
||||
ring := make([]byte, 12*12)
|
||||
for y := range 16 {
|
||||
for x := range 16 {
|
||||
dx, dy := float64(x)-7.5, float64(y)-7.5
|
||||
disc[y*16+x] = byte(255 * clamp(7.5-math.Sqrt(dx*dx+dy*dy)))
|
||||
if x < 12 && y < 12 {
|
||||
ex, ey := float64(x)-5.5, float64(y)-5.5
|
||||
d := math.Sqrt(ex*ex + ey*ey)
|
||||
ring[y*12+x] = byte(255 * clamp(1.5-math.Abs(d-4)))
|
||||
}
|
||||
}
|
||||
}
|
||||
dx, dy, _ := mask.Alloc(16, 16)
|
||||
mask.Put(dx, dy, 16, 16, disc, 16)
|
||||
rx, ry, _ := mask.Alloc(12, 12)
|
||||
mask.Put(rx, ry, 12, 12, ring, 12)
|
||||
emoji := make([]byte, 10*10*4)
|
||||
for i := 0; i < len(emoji); i += 4 {
|
||||
k := i / 4
|
||||
// Premultiplied: half transparent in the corner rows.
|
||||
a := byte(255)
|
||||
if k < 10 || k >= 90 {
|
||||
a = 128
|
||||
}
|
||||
emoji[i], emoji[i+1], emoji[i+2], emoji[i+3] = byte(uint16(240)*uint16(a)/255), byte(uint16(160)*uint16(a)/255), byte(uint16(20)*uint16(a)/255), a
|
||||
}
|
||||
cx, cy, _ := color.Alloc(10, 10)
|
||||
color.Put(cx, cy, 10, 10, emoji, 40)
|
||||
// A subpixel disc: its red subpixels a third of a pixel left of its
|
||||
// green ones, its blue ones a third right.
|
||||
lcd := make([]byte, 16*16*4)
|
||||
for y := range 16 {
|
||||
for x := range 16 {
|
||||
for c := range 3 {
|
||||
dx, dy := float64(x)-7.5+float64(c-1)/3, float64(y)-7.5
|
||||
lcd[(y*16+x)*4+c] = byte(255 * clamp(6.5-math.Sqrt(dx*dx+dy*dy)))
|
||||
}
|
||||
}
|
||||
}
|
||||
lx, ly, _ := color.Alloc(16, 16)
|
||||
color.Put(lx, ly, 16, 16, lcd, 64)
|
||||
pix := make([]byte, 8*8*4)
|
||||
for y := range 8 {
|
||||
for x := range 8 {
|
||||
i := (y*8 + x) * 4
|
||||
pix[i], pix[i+1], pix[i+2], pix[i+3] = byte(x*32), byte(y*32), 160, 255
|
||||
}
|
||||
}
|
||||
img := scene.NewImageRGBA(8, 8, pix)
|
||||
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
add := func(op scene.Op) { s.Ops = append(s.Ops, op) }
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 20, Y: 24, W: 120, H: 80}, Radii: r4(12), Color: scene.Color{A: 90}, Blur: 16})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 20, W: 120, H: 80}, Radii: r4(12), Color: scene.Color{R: 255, G: 255, B: 255, A: 255},
|
||||
Border: scene.Uniform(1), BorderColor: scene.Color{R: 200, G: 204, B: 210, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 160.5, Y: 20.25, W: 140, H: 30}, Radii: [4]float32{15, 4, 15, 4},
|
||||
Color: red, Color2: blue, Paint: scene.PaintLinear, Gradient: [4]float32{160, 20, 300, 50}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 170, Y: 60, W: 60, H: 40}, Color: scene.Color{R: 37, G: 99, B: 235, A: 128}, Border: scene.Uniform(3), BorderColor: red, Radii: r4(8)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 240, Y: 60, W: 40, H: 40}, Radii: r4(20), Color: blue, Opacity: 0.5})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 120, W: 200, H: 100}, Radii: r4(16)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 110, W: 320, H: 130}, Color: scene.Color{R: 230, G: 236, B: 250, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 100, Y: 130, W: 200, H: 70}})
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 120, Y: 150, W: 60, H: 30}, Radii: r4(6), Color: scene.Color{B: 80, A: 140}, Blur: 10})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 90, Y: 140, W: 50, H: 50}, Color: red, Radii: r4(4)})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
start := int32(len(s.Glyphs))
|
||||
for i := range 6 {
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: float32(30 + i*20), Y: 200, W: 16, H: 16, U: uint16(dx), V: uint16(dy), UW: 16, VH: 16, Color: ink},
|
||||
scene.Glyph{X: float32(32 + i*20), Y: 182, W: 12, H: 12, U: uint16(rx), V: uint16(ry), UW: 12, VH: 12, Color: blue})
|
||||
}
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: 160, Y: 180, W: 10, H: 10, U: uint16(cx), V: uint16(cy), UW: 10, VH: 10, Color: scene.Color{A: 255}, Colored: true})
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs))})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 240, Y: 120, W: 8, H: 8}, Image: img, Src: scene.Rect{W: 8, H: 8}})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 240, Y: 140, W: 64, H: 64}, Radii: r4(10), Image: img, Src: scene.Rect{W: 8, H: 8}})
|
||||
// Pixel art: the whole image 2.5 times as large, each pixel a square of
|
||||
// its own color with smooth edges, and a part of it four times, with
|
||||
// none.
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 256, Y: 118, W: 20, H: 20}, Image: img, Src: scene.Rect{W: 8, H: 8}, Pixelated: true})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 284, Y: 120, W: 16, H: 16}, Image: img, Src: scene.Rect{X: 2, Y: 3, W: 4, H: 4}, Pixelated: true})
|
||||
// Sprites: a part flipped across both axes and tinted, pixelated, and
|
||||
// one flipped across one, smooth, showing none of the pixels around.
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 284, Y: 60, W: 16, H: 16}, Image: img, Src: scene.Rect{X: 6, Y: 7, W: -4, H: -4}, Pixelated: true,
|
||||
Color: scene.Color{R: 255, G: 200, B: 80, A: 220}})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 284, Y: 80, W: 20, H: 20}, Image: img, Src: scene.Rect{X: 7, Y: 1, W: -5, H: 5}})
|
||||
|
||||
// Borders of different widths, dashed ones, Oklab gradients, stripes,
|
||||
// glyphs in gradients and a gray image.
|
||||
yellow := scene.Color{R: 250, G: 204, B: 21, A: 255}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 240, W: 60, H: 30}, Radii: r4(10), Color: scene.Color{R: 255, G: 255, B: 255, A: 255},
|
||||
Border: [4]float32{1, 4, 2, 0}, BorderColor: ink})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 90, Y: 240, W: 60, H: 30}, Radii: r4(8), Border: scene.Uniform(2), BorderColor: blue, Dashed: true})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 160, Y: 240, W: 70, H: 30}, Color: yellow, Border: [4]float32{0, 0, 3, 1}, BorderColor: red, Dashed: true})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 240, Y: 240, W: 64, H: 30}, Radii: r4(4), Color: blue, Color2: yellow, Paint: scene.PaintOklab, Gradient: [4]float32{240, 0, 304, 0}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 280, W: 80, H: 30}, Color: red, Color2: scene.Color{}, Paint: scene.PaintLinear, Gradient: [4]float32{20, 0, 100, 0}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 110, Y: 280, W: 80, H: 30}, Radii: r4(6), Color: scene.Color{R: 37, G: 99, B: 235, A: 200}, Color2: yellow,
|
||||
Paint: scene.PaintStripes, Gradient: [4]float32{0.7071, -0.7071, 3, 8}, Border: scene.Uniform(1), BorderColor: ink})
|
||||
start = int32(len(s.Glyphs))
|
||||
for i := range 3 {
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: float32(200 + i*18), Y: 288, W: 16, H: 16, U: uint16(dx), V: uint16(dy), UW: 16, VH: 16, Color: ink})
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs)), Paint: scene.PaintOklab, Color: red, Color2: blue, Gradient: [4]float32{200, 288, 252, 304}})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 270, Y: 280, W: 32, H: 32}, Radii: r4(6), Image: img, Src: scene.Rect{W: 8, H: 8}, Grayscale: true})
|
||||
|
||||
// Shadows that show only outside the boxes casting them: under a
|
||||
// translucent card, without blur, and alone.
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 320, W: 320, H: 60}, Color: yellow})
|
||||
card := scene.Rect{X: 20, Y: 330, W: 90, H: 36}
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 20, Y: 334, W: 90, H: 36}, Radii: r4(10), Color: scene.Color{A: 120}, Blur: 12, Cast: card, CastRadii: r4(10)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: card, Radii: r4(10), Color: scene.Color{R: 255, G: 255, B: 255, A: 140}})
|
||||
card = scene.Rect{X: 130.5, Y: 330.25, W: 70, H: 30}
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 133.5, Y: 333.25, W: 70, H: 30}, Radii: r4(8), Color: ink, Cast: card, CastRadii: r4(8)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: card, Radii: r4(8), Color: scene.Color{R: 37, G: 99, B: 235, A: 90}})
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 218, Y: 334, W: 84, H: 32}, Radii: r4(16), Color: red, Blur: 6,
|
||||
Cast: scene.Rect{X: 220, Y: 334, W: 80, H: 28}, CastRadii: r4(14)})
|
||||
// A hole through them, rounded and cut by a rounded clip, under a
|
||||
// translucent fill and its shadow, as a web view under a popover.
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 210, Y: 322, W: 104, H: 56}, Radii: r4(12)})
|
||||
add(scene.Op{Kind: scene.OpHole, Rect: scene.Rect{X: 246.5, Y: 326.25, W: 80, H: 40}, Radii: r4(10)})
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 270, Y: 344, W: 34, H: 30}, Radii: r4(6), Color: scene.Color{A: 100}, Blur: 8})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 270, Y: 340, W: 34, H: 30}, Radii: r4(6), Color: scene.Color{R: 37, G: 99, B: 235, A: 140}})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
// A hole at half opacity, as a web view in a page fading in.
|
||||
add(scene.Op{Kind: scene.OpHole, Rect: scene.Rect{X: 112.5, Y: 354.5, W: 60, H: 20}, Radii: r4(6), Opacity: 0.5})
|
||||
|
||||
// Subpixel glyphs, dark on white and light on dark, half transparent,
|
||||
// in a gradient, and clipped; thin mask glyphs, dark and light.
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 380, W: 160, H: 30}, Color: scene.Color{R: 255, G: 255, B: 255, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 160, Y: 380, W: 160, H: 30}, Color: scene.Color{R: 24, G: 24, B: 27, A: 255}})
|
||||
sub := func(x float32, c scene.Color) scene.Glyph {
|
||||
return scene.Glyph{X: x, Y: 387, W: 16, H: 16, U: uint16(lx), V: uint16(ly), UW: 16, VH: 16, Color: c, Subpixel: true}
|
||||
}
|
||||
start = int32(len(s.Glyphs))
|
||||
s.Glyphs = append(s.Glyphs, sub(8, ink), sub(28, blue), sub(48, scene.Color{R: 20, G: 24, B: 32, A: 128}),
|
||||
sub(168, scene.Color{R: 255, G: 255, B: 255, A: 255}), sub(188, yellow), sub(208, scene.Color{R: 113, G: 113, B: 122, A: 255}),
|
||||
scene.Glyph{X: 68, Y: 387, W: 16, H: 16, U: uint16(dx), V: uint16(dy), UW: 16, VH: 16, Color: ink, Thin: true},
|
||||
scene.Glyph{X: 228, Y: 387, W: 16, H: 16, U: uint16(dx), V: uint16(dy), UW: 16, VH: 16, Color: scene.Color{R: 244, G: 244, B: 245, A: 255}, Thin: true})
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs))})
|
||||
start = int32(len(s.Glyphs))
|
||||
s.Glyphs = append(s.Glyphs, sub(92, ink), sub(110, ink), sub(128, ink))
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs)), Paint: scene.PaintLinear, Color: red, Color2: blue, Gradient: [4]float32{92, 387, 144, 403}})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 250, Y: 384, W: 40, H: 22}, Radii: r4(8)})
|
||||
start = int32(len(s.Glyphs))
|
||||
s.Glyphs = append(s.Glyphs, sub(248, scene.Color{R: 255, G: 255, B: 255, A: 255}), sub(266, scene.Color{R: 255, G: 255, B: 255, A: 255}), sub(284, red))
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs))})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
|
||||
// Panes of glass over stripes, a gradient and glyphs.
|
||||
for i := range 8 {
|
||||
c := []scene.Color{red, blue, yellow, ink}[i%4]
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 40), Y: 410, W: 20, H: 130}, Color: c})
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 470, W: 320, H: 20}, Color: red, Color2: blue, Paint: scene.PaintOklab, Gradient: [4]float32{0, 0, 320, 0}})
|
||||
start = int32(len(s.Glyphs))
|
||||
for i := range 14 {
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: float32(6 + i*22), Y: 516, W: 16, H: 16, U: uint16(dx), V: uint16(dy), UW: 16, VH: 16, Color: ink})
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs))})
|
||||
// Effects over them: reading their backdrop blurred at a quarter of
|
||||
// the size, over each other at the same size, unblurred, clipped and
|
||||
// half transparent at full size, past the frame's edge at half the
|
||||
// size; and one reading none.
|
||||
effect := func(e *scene.Effect, r scene.Rect, radii [4]float32, blur, shift float32, tint scene.Color, opacity float32) {
|
||||
fx := scene.EffectOp{Effect: e, Blur: blur}
|
||||
fx.Params[0] = [4]float32{shift}
|
||||
fx.Params[1] = [4]float32{float32(tint.R) / 255, float32(tint.G) / 255, float32(tint.B) / 255, float32(tint.A) / 255}
|
||||
add(scene.Op{Kind: scene.OpEffect, Rect: r, Radii: radii, Start: int32(len(s.Effects)), Opacity: opacity})
|
||||
s.Effects = append(s.Effects, fx)
|
||||
}
|
||||
white := scene.Color{R: 255, G: 255, B: 255, A: 90}
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 12, Y: 424, W: 140, H: 44}, Radii: r4(22), Color: scene.Color{A: 40}, Blur: 16,
|
||||
Cast: scene.Rect{X: 12, Y: 420, W: 140, H: 44}, CastRadii: r4(22)})
|
||||
effect(LensEffect, scene.Rect{X: 12, Y: 420, W: 140, H: 44}, r4(22), 8, 2, white, 0)
|
||||
effect(LensEffect, scene.Rect{X: 120, Y: 446, W: 60, H: 60}, r4(30), 12, 3, white, 0)
|
||||
effect(LensEffect, scene.Rect{X: 190.5, Y: 418.25, W: 110, H: 50}, r4(16), 0, 1.5, scene.Color{R: 37, G: 99, B: 235, A: 120}, 0)
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30, Y: 480, W: 200, H: 50}, Radii: r4(12)})
|
||||
effect(LensEffect, scene.Rect{X: 40, Y: 476, W: 240, H: 44}, [4]float32{22, 6, 22, 6}, 3, 1, scene.Color{A: 60}, 0.7)
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
effect(LensEffect, scene.Rect{X: 284, Y: 494, W: 50, H: 50}, r4(14), 6, 2, white, 0)
|
||||
effect(TintEffect, scene.Rect{X: 250, Y: 420, W: 30, H: 30}, r4(8), 0, 0, scene.Color{R: 220, G: 40, B: 40, A: 160}, 0)
|
||||
|
||||
// Inner shadows: a hairline blurred along the edge of a dark card,
|
||||
// offset and spread, without blur, and with no hole left.
|
||||
inset := func(box scene.Rect, radius float32, hole scene.Rect, holeRadius float32, c scene.Color, blur float32) {
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: box, Radii: r4(radius), Color: scene.Color{R: 39, G: 39, B: 42, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpShadow, Inset: true, Rect: hole, Radii: r4(holeRadius), Color: c, Blur: blur, Cast: box, CastRadii: r4(radius)})
|
||||
}
|
||||
inset(scene.Rect{X: 10, Y: 548, W: 90, H: 44}, 10, scene.Rect{X: 10, Y: 548, W: 90, H: 44}, 10, scene.Color{R: 255, G: 255, B: 255, A: 120}, 2)
|
||||
inset(scene.Rect{X: 110.5, Y: 548.25, W: 90, H: 44}, 14, scene.Rect{X: 117.5, Y: 556.25, W: 82, H: 36}, 10, yellow, 8)
|
||||
inset(scene.Rect{X: 210, Y: 548, W: 50, H: 44}, 12, scene.Rect{X: 216, Y: 555, W: 38, H: 30}, 6, red, 0)
|
||||
inset(scene.Rect{X: 270, Y: 548, W: 40, H: 44}, 20, scene.Rect{}, 0, blue, 6)
|
||||
|
||||
// Gradients of stops: conic, in sRGB with a hard stop and in Oklab,
|
||||
// linear, half transparent and to transparent, radial, off center
|
||||
// with a hard stop and in Oklab to transparent, painting borders,
|
||||
// plain and dashed, and glyphs; and images blurred, at full size and a
|
||||
// quarter of it.
|
||||
stops := func(st ...scene.Stop) [2]int32 {
|
||||
a := int32(len(s.Stops))
|
||||
s.Stops = append(s.Stops, st...)
|
||||
return [2]int32{a, int32(len(s.Stops))}
|
||||
}
|
||||
green := scene.Color{R: 34, G: 197, B: 94, A: 255}
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 10, Y: 605, W: 60, H: 60}, Radii: r4(30), Paint: scene.PaintConic,
|
||||
Gradient: [4]float32{40, 635, 0.4, 0}, Stops: stops(scene.Stop{Color: red, At: 0}, scene.Stop{Color: yellow, At: 0.3}, scene.Stop{Color: blue, At: 0.3}, scene.Stop{Color: green, At: 0.7}, scene.Stop{Color: red, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 80.5, Y: 605.25, W: 60, H: 60}, Radii: r4(8), Paint: scene.PaintConicOklab,
|
||||
Gradient: [4]float32{100, 625, -1, 0}, Stops: stops(scene.Stop{Color: blue, At: 0.1}, scene.Stop{Color: yellow, At: 0.5}, scene.Stop{Color: red, At: 0.9})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 150, Y: 605, W: 70, H: 25}, Radii: r4(6), Paint: scene.PaintLinearStops,
|
||||
Gradient: [4]float32{150, 605, 220, 630}, Stops: stops(scene.Stop{Color: red, At: 0.1}, scene.Stop{Color: scene.Color{R: 37, G: 99, B: 235, A: 120}, At: 0.5}, scene.Stop{Color: yellow, At: 0.9})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 150, Y: 637, W: 70, H: 25}, Paint: scene.PaintLinearStopsOklab,
|
||||
Gradient: [4]float32{150, 0, 220, 0}, Stops: stops(scene.Stop{Color: blue, At: 0}, scene.Stop{Color: green, At: 0.6}, scene.Stop{Color: scene.Color{}, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 230.5, Y: 605.25, W: 80, H: 60}, Radii: r4(14), Color: scene.Color{R: 255, G: 255, B: 255, A: 120},
|
||||
Border: scene.Uniform(6), BorderColor: scene.Color{R: 255, G: 255, B: 255, A: 255}, BorderPaint: true, Paint: scene.PaintConicOklab,
|
||||
Gradient: [4]float32{270, 635, 0, 0}, Stops: stops(scene.Stop{Color: red, At: 0}, scene.Stop{Color: blue, At: 0.5}, scene.Stop{Color: red, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 230, Y: 670, W: 80, H: 30}, Radii: r4(6), Border: scene.Uniform(3),
|
||||
BorderColor: scene.Color{R: 255, G: 255, B: 255, A: 200}, BorderPaint: true, Dashed: true, Paint: scene.PaintLinearStops,
|
||||
Gradient: [4]float32{230, 0, 310, 0}, Stops: stops(scene.Stop{Color: green, At: 0}, scene.Stop{Color: red, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 200, Y: 704, W: 50, H: 32}, Radii: r4(8), Paint: scene.PaintRadial,
|
||||
Gradient: [4]float32{213, 714, 26.3, 0}, Stops: stops(scene.Stop{Color: yellow, At: 0}, scene.Stop{Color: red, At: 0.5}, scene.Stop{Color: blue, At: 0.5}, scene.Stop{Color: green, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 256.5, Y: 704.25, W: 56, H: 32}, Radii: r4(16), Paint: scene.PaintRadialOklab,
|
||||
Gradient: [4]float32{284.5, 720.25, 30, 0}, Stops: stops(scene.Stop{Color: scene.Color{R: 255, G: 255, B: 255, A: 255}, At: 0.1}, scene.Stop{Color: scene.Color{R: 37, G: 99, B: 235, A: 140}, At: 0.6}, scene.Stop{Color: scene.Color{}, At: 1})})
|
||||
start = int32(len(s.Glyphs))
|
||||
for i := range 3 {
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: float32(10 + i*18), Y: 676, W: 16, H: 16, U: uint16(dx), V: uint16(dy), UW: 16, VH: 16, Color: ink})
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs)), Paint: scene.PaintConic,
|
||||
Gradient: [4]float32{36, 684, 0, 0}, Stops: stops(scene.Stop{Color: red, At: 0}, scene.Stop{Color: blue, At: 0.5}, scene.Stop{Color: yellow, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 70, Y: 672, W: 48, H: 48}, Image: img, Src: scene.Rect{W: 8, H: 8}, Blur: 1.2})
|
||||
big := make([]byte, 64*64*4)
|
||||
for y := range 64 {
|
||||
for x := range 64 {
|
||||
i := (y*64 + x) * 4
|
||||
if x >= 16 && x < 48 && y >= 20 && y < 44 {
|
||||
big[i], big[i+1], big[i+2], big[i+3] = 220, 40, 40, 255
|
||||
} else if (x/8+y/8)%2 == 0 && x > 4 && x < 60 && y > 4 && y < 60 {
|
||||
big[i], big[i+1], big[i+2], big[i+3] = 18, 50, 117, 128
|
||||
}
|
||||
}
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 130, Y: 672, W: 64, H: 64}, Radii: r4(8), Image: scene.NewImageRGBA(64, 64, big), Src: scene.Rect{W: 64, H: 64}, Blur: 12})
|
||||
return s
|
||||
}
|
||||
|
||||
// Compare compares pixels a renderer drew, premultiplied BGRA rows of
|
||||
// stride bytes, with what the CPU renderer draws of s. Antialiased edges
|
||||
// and interpolated images may differ a little; anything else fails t. With
|
||||
// MYGO_GPU_PNG naming a directory, it saves both images there.
|
||||
func Compare(t testing.TB, name string, got []byte, stride int, s *scene.Scene) {
|
||||
t.Helper()
|
||||
want := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(want, s)
|
||||
worst, off := 0, 0
|
||||
worstAt := image.Point{}
|
||||
for y := range s.Height {
|
||||
for x := range s.Width {
|
||||
g := got[y*stride+4*x:][:4]
|
||||
w := want.Pix[y*want.Stride+4*x:][:4]
|
||||
d := 0
|
||||
for c := range 4 {
|
||||
d = max(d, absInt(int(g[c])-int(w[c])))
|
||||
}
|
||||
if d > worst {
|
||||
worst, worstAt = d, image.Pt(x, y)
|
||||
}
|
||||
if d > 2 {
|
||||
off++
|
||||
}
|
||||
}
|
||||
}
|
||||
if dir := os.Getenv("MYGO_GPU_PNG"); dir != "" {
|
||||
g := &raster.Image{W: s.Width, H: s.Height, Stride: stride, Pix: got}
|
||||
save(t, filepath.Join(dir, name+".png"), g)
|
||||
save(t, filepath.Join(dir, name+"-cpu.png"), want)
|
||||
}
|
||||
// One pixel in two hundred may differ by more than 2 of 255, none by
|
||||
// more than 24.
|
||||
if worst > 24 || off*200 > s.Width*s.Height {
|
||||
t.Errorf("%s: %d pixels differ from the CPU renderer's by more than 2, the most by %d at %v", name, off, worst, worstAt)
|
||||
}
|
||||
}
|
||||
|
||||
func save(t testing.TB, path string, m *raster.Image) {
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
img := &image.RGBA{Pix: m.RGBA(), Stride: 4 * m.W, Rect: image.Rect(0, 0, m.W, m.H)}
|
||||
if err := png.Encode(f, img); err != nil {
|
||||
t.Fatal(fmt.Errorf("%s: %w", path, err))
|
||||
}
|
||||
}
|
||||
|
||||
func clamp(v float64) float64 { return max(0, min(1, v)) }
|
||||
|
||||
func absInt(v int) int {
|
||||
if v < 0 {
|
||||
return -v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// ContinuousScene returns a 320×70 scene with continuous corners, which
|
||||
// only the renderers of macOS draw (scene.Op.Continuous): a card with a
|
||||
// border, its shadow and an inner one, a pill, a circle, which stays one,
|
||||
// sides too short for their corners' curves, one with an inner shadow
|
||||
// without blur, a corner reaching past the middle of its sides, a clip and
|
||||
// an image, a shadow without blur, cut by the box casting it, and an effect
|
||||
// reading its backdrop.
|
||||
func ContinuousScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 70, Clear: scene.Color{R: 236, G: 238, B: 242, A: 255}}
|
||||
pix := make([]byte, 8*8*4)
|
||||
for y := range 8 {
|
||||
for x := range 8 {
|
||||
i := (y*8 + x) * 4
|
||||
pix[i], pix[i+1], pix[i+2], pix[i+3] = byte(x*32), byte(y*32), 160, 255
|
||||
}
|
||||
}
|
||||
img := scene.NewImageRGBA(8, 8, pix)
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
yellow := scene.Color{R: 250, G: 204, B: 21, A: 255}
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
add := func(op scene.Op) {
|
||||
op.Continuous = true
|
||||
s.Ops = append(s.Ops, op)
|
||||
}
|
||||
card := scene.Rect{X: 10, Y: 8, W: 70, H: 44}
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 10, Y: 12, W: 70, H: 44}, Radii: r4(14), Color: scene.Color{A: 110}, Blur: 10,
|
||||
Cast: card, CastRadii: r4(14)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: card, Radii: r4(14), Color: scene.Color{R: 255, G: 255, B: 255, A: 255},
|
||||
Border: scene.Uniform(2), BorderColor: blue})
|
||||
pad, padRadii := scene.InnerRadii(card, r4(14), scene.Uniform(2))
|
||||
add(scene.Op{Kind: scene.OpShadow, Inset: true, Rect: scene.Rect{X: pad.X + 3, Y: pad.Y + 5, W: pad.W - 2, H: pad.H - 2}, Radii: [4]float32{11, 11, 11, 11},
|
||||
Color: scene.Color{R: 220, G: 40, B: 40, A: 160}, Blur: 8, Cast: pad, CastRadii: padRadii})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 88.5, Y: 10.25, W: 70, H: 22}, Radii: r4(999), Color: red, Color2: blue,
|
||||
Paint: scene.PaintLinear, Gradient: [4]float32{88, 10, 158, 32}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 88, Y: 38, W: 24, H: 24}, Radii: r4(12), Color: ink})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 118, Y: 38, W: 40, H: 24}, Radii: r4(10), Color: blue, Border: scene.Uniform(1), BorderColor: ink})
|
||||
add(scene.Op{Kind: scene.OpShadow, Inset: true, Rect: scene.Rect{X: 120, Y: 41, W: 36, H: 20}, Radii: r4(8), Color: yellow,
|
||||
Cast: scene.Rect{X: 119, Y: 39, W: 38, H: 22}, CastRadii: r4(9)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 166.5, Y: 8.25, W: 40, H: 54}, Radii: [4]float32{26, 6, 0, 0}, Color: red})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 214, Y: 6, W: 50, H: 58}, Radii: r4(16)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 204, Y: 0, W: 70, H: 70}, Color: yellow})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 222, Y: 14, W: 34, H: 34}, Radii: r4(9), Image: img, Src: scene.Rect{W: 8, H: 8}})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
card = scene.Rect{X: 272.5, Y: 10.25, W: 40, H: 40}
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 275.5, Y: 14.25, W: 40, H: 40}, Radii: r4(12), Color: ink, Cast: card, CastRadii: r4(12)})
|
||||
// An effect reading its backdrop, over the pill and the card.
|
||||
fx := scene.EffectOp{Effect: LensEffect, Blur: 4}
|
||||
fx.Params[0] = [4]float32{2}
|
||||
fx.Params[1] = [4]float32{1, 1, 1, 0.35}
|
||||
add(scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{X: 60, Y: 18, W: 70, H: 30}, Radii: r4(15), Start: int32(len(s.Effects))})
|
||||
s.Effects = append(s.Effects, fx)
|
||||
return s
|
||||
}
|
||||
|
||||
// ShadowCase is a panel with a stack of shadows cast by it, as an elevated
|
||||
// surface has: its corner radius, the blur, spread and offset of each layer.
|
||||
type ShadowCase struct {
|
||||
Radius float32
|
||||
Continuous bool
|
||||
// Blur, Spread and DY describe each layer.
|
||||
Blur, Spread, DY []float32
|
||||
}
|
||||
|
||||
// ShadowPanelScene returns a 480×360 scene with a panel of 340×220 that casts
|
||||
// the shadows of c, each shown only outside the panel (Cast), as kit surfaces
|
||||
// draw them, and a fill over the panel.
|
||||
func ShadowPanelScene(c ShadowCase) *scene.Scene {
|
||||
s := &scene.Scene{Width: 480, Height: 360, Clear: scene.Color{R: 240, G: 241, B: 244, A: 255}}
|
||||
panel := scene.Rect{X: 70, Y: 60, W: 340, H: 220}
|
||||
radii := [4]float32{c.Radius, c.Radius, c.Radius, c.Radius}
|
||||
for i := range c.Blur {
|
||||
sp := c.Spread[i]
|
||||
box := scene.Rect{X: panel.X - sp, Y: panel.Y - sp + c.DY[i], W: panel.W + 2*sp, H: panel.H + 2*sp}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpShadow, Rect: box, Radii: radii, Continuous: c.Continuous,
|
||||
Color: scene.Color{A: 60}, Blur: c.Blur[i], Cast: panel, CastRadii: radii})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: panel, Radii: radii, Continuous: c.Continuous,
|
||||
Color: scene.Color{R: 255, G: 255, B: 255, A: 255}})
|
||||
return s
|
||||
}
|
||||
|
||||
// ShadowCases are panels of several radii, blurs, spreads and offsets,
|
||||
// among them an offset larger than the blur and a shadow that does not reach
|
||||
// out of the panel.
|
||||
func ShadowCases() []ShadowCase {
|
||||
return []ShadowCase{
|
||||
{Radius: 0, Blur: []float32{2, 24}, Spread: []float32{0, 0}, DY: []float32{1, 12}},
|
||||
{Radius: 12, Blur: []float32{2, 6, 12, 24}, Spread: []float32{0, -1, -3, -6}, DY: []float32{1, 3, 6, 12}},
|
||||
{Radius: 40, Blur: []float32{16}, Spread: []float32{0}, DY: []float32{4}},
|
||||
{Radius: 16, Continuous: true, Blur: []float32{12, 30}, Spread: []float32{2, 0}, DY: []float32{3, 8}},
|
||||
{Radius: 8, Blur: []float32{4}, Spread: []float32{-2}, DY: []float32{40}},
|
||||
{Radius: 60, Blur: []float32{8, 0}, Spread: []float32{0, 5}, DY: []float32{0, 0}},
|
||||
{Radius: 30, Blur: []float32{60}, Spread: []float32{-40}, DY: []float32{-10}},
|
||||
{Radius: 110, Blur: []float32{80, 6}, Spread: []float32{20, 0}, DY: []float32{0, 2}}, // a pill
|
||||
}
|
||||
}
|
||||
|
||||
// RingCase is a scene of border-only fills (a transparent solid color and a
|
||||
// border), over content that shows when one of them wrongly changes a pixel.
|
||||
type RingCase struct {
|
||||
Name string
|
||||
Scene *scene.Scene
|
||||
// Split is whether the builder draws the first ring around its core.
|
||||
Split bool
|
||||
}
|
||||
|
||||
// RingCases are border-only fills at the size of panels (the shaders shade
|
||||
// their cores for nothing unless the builder draws around them): square,
|
||||
// round and continuous corners, uneven widths and radii, a dashed border,
|
||||
// fractional places, borders under clips, translucent and opaque border
|
||||
// colors, at half opacity, one with a border wider than half the panel,
|
||||
// and fills that are not split: a gradient, a translucent color, a
|
||||
// transformed fill, a small one and a thin one.
|
||||
func RingCases() []RingCase {
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
paper := scene.Color{R: 246, G: 247, B: 249, A: 255}
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
// content returns a 480×360 scene of fills, a shadow and a glyph run,
|
||||
// which the ring is drawn over, and the clip to push, if any.
|
||||
content := func() *scene.Scene {
|
||||
s := &scene.Scene{Width: 480, Height: 360, Clear: scene.Color{R: 30, G: 34, B: 40, A: 255},
|
||||
Text: scene.TextParams{GammaRatios: scene.GammaRatios(1.8), Contrast: 1, SubpixelContrast: 0.5}}
|
||||
s.MaskAtlas, s.Text, s.Glyphs = glyphContent()
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 10, Y: 10, W: 460, H: 340}, Radii: r4(20), Color: paper},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 100, Y: 80, W: 200, H: 120}, Color: blue, Color2: red, Paint: scene.PaintLinear, Gradient: [4]float32{100, 0, 300, 0}},
|
||||
scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 160, Y: 160, W: 160, H: 100}, Radii: r4(12), Color: scene.Color{A: 120}, Blur: 24})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpGlyphs, Start: 0, End: int32(len(s.Glyphs))})
|
||||
return s
|
||||
}
|
||||
var out []RingCase
|
||||
add := func(name string, split bool, clip *scene.Op, ops ...scene.Op) {
|
||||
s := content()
|
||||
if clip != nil {
|
||||
s.Ops = append(s.Ops, *clip)
|
||||
}
|
||||
s.Ops = append(s.Ops, ops...)
|
||||
if clip != nil {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
}
|
||||
out = append(out, RingCase{name, s, split})
|
||||
}
|
||||
ring := func(r scene.Rect, radii [4]float32, w [4]float32, c scene.Color) scene.Op {
|
||||
return scene.Op{Kind: scene.OpFill, Rect: r, Radii: radii, Border: w, BorderColor: c}
|
||||
}
|
||||
panel := scene.Rect{X: 20, Y: 20, W: 440, H: 320}
|
||||
half := scene.Color{R: 255, G: 255, B: 255, A: 90}
|
||||
add("square 1px", true, nil, ring(panel, [4]float32{}, scene.Uniform(1), half))
|
||||
add("square 2px opaque", true, nil, ring(panel, [4]float32{}, scene.Uniform(2), red))
|
||||
add("rounded", true, nil, ring(panel, r4(16), scene.Uniform(2), half))
|
||||
add("continuous", true, nil, func() scene.Op {
|
||||
op := ring(panel, r4(24), scene.Uniform(2), half)
|
||||
op.Continuous = true
|
||||
return op
|
||||
}())
|
||||
add("uneven widths and radii", true, nil, ring(panel, [4]float32{30, 0, 8, 20}, [4]float32{1, 3, 2, 5}, half))
|
||||
add("uneven continuous", true, nil, func() scene.Op {
|
||||
op := ring(panel, [4]float32{30, 6, 8, 20}, [4]float32{3, 1, 4, 2}, half)
|
||||
op.Continuous = true
|
||||
return op
|
||||
}())
|
||||
add("fractional place", true, nil, ring(scene.Rect{X: 20.5, Y: 20.25, W: 439.3, H: 320.6}, r4(12), scene.Uniform(1.5), half))
|
||||
add("dashed", true, nil, func() scene.Op {
|
||||
op := ring(panel, r4(10), scene.Uniform(2), blue)
|
||||
op.Dashed = true
|
||||
return op
|
||||
}())
|
||||
add("half opacity", true, nil, func() scene.Op {
|
||||
op := ring(panel, r4(10), scene.Uniform(3), blue)
|
||||
op.Opacity = 0.5
|
||||
return op
|
||||
}())
|
||||
add("wide border", true, nil, ring(panel, r4(40), scene.Uniform(60), half))
|
||||
add("clipped", true, &scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30, Y: 30, W: 300, H: 280}}, ring(panel, r4(16), scene.Uniform(2), half))
|
||||
add("fractional clip", true, &scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30.5, Y: 30.25, W: 300.4, H: 280.7}}, ring(panel, r4(16), scene.Uniform(2), half))
|
||||
add("rounded clip", true, &scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30, Y: 30, W: 300, H: 280}, Radii: r4(30)}, ring(panel, r4(16), scene.Uniform(2), half))
|
||||
add("frame edges", true, nil, ring(scene.Rect{X: -10, Y: -10, W: 500, H: 380}, r4(12), scene.Uniform(2), half))
|
||||
add("two rings", true, nil, ring(panel, r4(16), scene.Uniform(2), half), ring(scene.Rect{X: 30, Y: 30, W: 420, H: 300}, r4(8), scene.Uniform(1), red))
|
||||
add("circle", true, nil, ring(scene.Rect{X: 90.5, Y: 30.25, W: 300, H: 300}, r4(150), scene.Uniform(1), half))
|
||||
add("pill", true, nil, ring(scene.Rect{X: 40, Y: 120, W: 400, H: 100}, r4(50), scene.Uniform(2), red))
|
||||
add("uneven round", true, nil, ring(panel, [4]float32{150, 20, 90, 0}, [4]float32{1, 3, 2, 5}, half))
|
||||
// Grooves rippling out of a record across a card, as a music app's:
|
||||
// circles a pixel wide or less, most larger than the card, clipped by it.
|
||||
func() {
|
||||
var grooves []scene.Op
|
||||
for i := range 12 {
|
||||
rad := 30 + float32(i)*50
|
||||
w := float32(1)
|
||||
if i%2 == 1 {
|
||||
w = 0.7
|
||||
}
|
||||
grooves = append(grooves, ring(scene.Rect{X: 360 - rad, Y: 180.5 - rad, W: 2 * rad, H: 2 * rad}, r4(rad), scene.Uniform(w), half))
|
||||
}
|
||||
add("grooves", true, &scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 60, W: 440, H: 240}, Radii: r4(16)}, grooves...)
|
||||
}()
|
||||
add("a fill with a border", false, nil, func() scene.Op {
|
||||
op := ring(panel, r4(16), scene.Uniform(2), half)
|
||||
op.Color = scene.Color{R: 255, G: 255, B: 255, A: 1}
|
||||
return op
|
||||
}())
|
||||
add("gradient", false, nil, func() scene.Op {
|
||||
op := ring(panel, r4(16), scene.Uniform(2), half)
|
||||
op.Paint, op.Color, op.Color2, op.Gradient = scene.PaintLinear, scene.Color{A: 0}, scene.Color{R: 255, A: 200}, [4]float32{20, 0, 460, 0}
|
||||
return op
|
||||
}())
|
||||
add("transformed", false, nil, func() scene.Op {
|
||||
op := ring(panel, r4(16), scene.Uniform(2), half)
|
||||
op.Transform = scene.Scaling(0.98, 0.98)
|
||||
return op
|
||||
}())
|
||||
add("small", false, nil, ring(scene.Rect{X: 100, Y: 100, W: 40, H: 30}, r4(6), scene.Uniform(1), half))
|
||||
add("thin", false, nil, ring(scene.Rect{X: 20, Y: 20, W: 440, H: 6}, r4(2), scene.Uniform(1), half))
|
||||
add("border fills the panel", false, nil, ring(scene.Rect{X: 20, Y: 20, W: 100, H: 100}, [4]float32{}, scene.Uniform(60), half))
|
||||
return out
|
||||
}
|
||||
|
||||
// OpaqueScene returns a w×h scene (at least 600×500) of opaque fills large
|
||||
// enough for the builder to draw as cores without blending, over content that
|
||||
// shows if one is wrong: translucent shadows, glyphs and half transparent
|
||||
// fills under them, and fills with square, round and continuous corners, a
|
||||
// translucent border, fractional places, edges at the frame's, rectangular
|
||||
// clips with whole and fractional edges, and some that are not cores (half
|
||||
// opacity, a gradient, a rounded clip, a transformed fill).
|
||||
func OpaqueScene(w, h int) *scene.Scene {
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 30, G: 34, B: 40, A: 255}}
|
||||
s.MaskAtlas, s.Text, s.Glyphs = glyphContent()
|
||||
fw, fh := float32(w), float32(h)
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
add := func(op scene.Op) { s.Ops = append(s.Ops, op) }
|
||||
color := func(i int) scene.Color {
|
||||
return scene.Color{R: byte(20 + i*37%200), G: byte(10 + i*53%220), B: byte(40 + i*71%200), A: 255}
|
||||
}
|
||||
under := func(x, y float32) {
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: x, Y: y, W: 160, H: 100}, Radii: r4(12), Color: scene.Color{A: 140}, Blur: 20})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: x + 20, Y: y + 20, W: 200, H: 80}, Color: scene.Color{R: 255, G: 90, B: 20, A: 160}})
|
||||
add(scene.Op{Kind: scene.OpGlyphs, Start: 0, End: int32(len(s.Glyphs))})
|
||||
}
|
||||
under(fw/6, 80)
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: fw, H: fh}, Color: color(1)})
|
||||
under(fw/6, 100)
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 40, Y: 30.25, W: fw - 80.5, H: fh - 60}, Radii: r4(24), Continuous: true, Color: color(2),
|
||||
Border: scene.Uniform(2), BorderColor: scene.Color{R: 255, G: 255, B: 255, A: 70}})
|
||||
under(fw/3, 200)
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 60.5, Y: 70, W: fw - 140, H: fh - 140.5}, Color: color(3)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 100, Y: 90, W: fw/2 + 0.5, H: fh/2 - 3.25}, Radii: r4(12), Color: color(4)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: fw / 3, Y: 120, W: fw / 2, H: fh / 2}, Radii: [4]float32{40, 0, 16, 5}, Color: color(5)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: -5, Y: fh - 130, W: fw + 10, H: 130}, Color: color(6)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 0, W: 150, H: fh}, Color: color(7)})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 200, Y: 150, W: fw - 300, H: fh - 250}})
|
||||
under(260, 200)
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 190, Y: 140, W: fw - 280, H: fh - 230}, Color: color(8)})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 210.5, Y: 160.25, W: fw - 320.5, H: fh - 270.25}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 190, Y: 140, W: fw - 280, H: fh - 230}, Color: color(9)})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 220, Y: 170, W: fw - 340, H: fh - 290}, Radii: r4(30)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 190, Y: 140, W: fw - 280, H: fh - 230}, Color: color(10)})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 250, Y: 200, W: 300, H: 200}, Color: color(11), Opacity: 0.5})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 250, Y: 200, W: 300, H: 200}, Color: color(12), Color2: color(13), Paint: scene.PaintLinear, Gradient: [4]float32{250, 0, 550, 0}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 260, Y: 210, W: 280, H: 180}, Color: color(14), Transform: scene.Scaling(1.01, 1)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 300, Y: 250, W: 120, H: 90}, Color: color(15)}) // small: not a core
|
||||
return s
|
||||
}
|
||||
|
||||
// CullCase is a scene of ops, some of them under later opaque fills, and how
|
||||
// many of them a renderer may leave out, which must change no pixel. The
|
||||
// identity tests use it as a named scene.
|
||||
type CullCase struct {
|
||||
Name string
|
||||
Scene *scene.Scene
|
||||
// Culled is how many ops the shared builder leaves out.
|
||||
Culled int
|
||||
}
|
||||
|
||||
// glyphContent returns a mask atlas holding a disc, the text parameters, and a run
|
||||
// of twelve glyphs of it, for scenes that draw text.
|
||||
func glyphContent() (*scene.Atlas, scene.TextParams, []scene.Glyph) {
|
||||
atlas := scene.NewAtlas(1, 64, 64)
|
||||
disc := make([]byte, 16*16)
|
||||
for y := range 16 {
|
||||
for x := range 16 {
|
||||
dx, dy := float64(x)-7.5, float64(y)-7.5
|
||||
disc[y*16+x] = byte(255 * clamp(7.5-math.Sqrt(dx*dx+dy*dy)))
|
||||
}
|
||||
}
|
||||
x, y, _ := atlas.Alloc(16, 16)
|
||||
atlas.Put(x, y, 16, 16, disc, 16)
|
||||
var glyphs []scene.Glyph
|
||||
for i := range 12 {
|
||||
glyphs = append(glyphs, scene.Glyph{X: 40 + float32(i*16), Y: 120, W: 16, H: 16, U: uint16(x), V: uint16(y), UW: 16, VH: 16, Color: scene.Color{A: 255}})
|
||||
}
|
||||
return atlas, scene.TextParams{GammaRatios: scene.GammaRatios(1.8), Contrast: 1, SubpixelContrast: 0.5}, glyphs
|
||||
}
|
||||
|
||||
// Transformed returns a copy of s with a one pixel transformed fill drawn
|
||||
// first, which makes the builder give rounded and rotated clips masks (a scene
|
||||
// with any transformed op has them), so that every case also runs with masked
|
||||
// clips.
|
||||
func Transformed(s *scene.Scene) *scene.Scene {
|
||||
c := *s
|
||||
c.Ops = append([]scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{X: 1, Y: 1, W: 3, H: 3}, Color: scene.Color{R: 200, A: 255}, Transform: scene.Scaling(1.01, 1)}}, s.Ops...)
|
||||
return &c
|
||||
}
|
||||
|
||||
// MaskedCase is a named scene whose clips are masked.
|
||||
type MaskedCase struct {
|
||||
Name string
|
||||
Scene *scene.Scene
|
||||
}
|
||||
|
||||
// MaskedCases are scenes with rounded, continuous and rotated clips (which
|
||||
// are masks in a scene with a transformed op) holding what the builder
|
||||
// draws in pieces or as cores: a border-only ring, a shadow cast by a box, large
|
||||
// opaque fills, plain fills, glyphs and holes, with content after them in the
|
||||
// same clip that reaches the clip's corners.
|
||||
func MaskedCases() []MaskedCase {
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
build := func(name string, clip scene.Op, inner func(add func(scene.Op))) MaskedCase {
|
||||
s := &scene.Scene{Width: 600, Height: 500, Clear: scene.Color{R: 240, G: 240, B: 240, A: 255}}
|
||||
s.MaskAtlas, s.Text, s.Glyphs = glyphContent()
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 5, Y: 5, W: 10, H: 10}, Color: scene.Color{R: 200, A: 255}, Transform: scene.Scaling(1.01, 1)})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 600, H: 500}, Color: scene.Color{R: 90, G: 120, B: 200, A: 255}})
|
||||
clip.Kind = scene.OpPushClip
|
||||
s.Ops = append(s.Ops, clip)
|
||||
inner(func(op scene.Op) { s.Ops = append(s.Ops, op) })
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 0, W: 600, H: 120}, Color: scene.Color{G: 160, A: 200}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 400, W: 600, H: 100}, Color: scene.Color{R: 160, A: 255}},
|
||||
scene.Op{Kind: scene.OpGlyphs, Start: 0, End: int32(len(s.Glyphs))},
|
||||
scene.Op{Kind: scene.OpPopClip})
|
||||
return MaskedCase{name, s}
|
||||
}
|
||||
ring := func(add func(scene.Op)) {
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 30, Y: 20, W: 540, H: 460}, Radii: r4(20), Border: scene.Uniform(3), BorderColor: scene.Color{B: 200, A: 255}})
|
||||
}
|
||||
shadow := func(add func(scene.Op)) {
|
||||
add(scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 60, Y: 60, W: 400, H: 300}, Radii: r4(12), Color: scene.Color{A: 120}, Blur: 20,
|
||||
Cast: scene.Rect{X: 60, Y: 60, W: 400, H: 300}, CastRadii: r4(12)})
|
||||
}
|
||||
opaque := func(add func(scene.Op)) {
|
||||
add(scene.Op{Kind: scene.OpHole, Rect: scene.Rect{X: 200, Y: 200, W: 40, H: 40}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 20, W: 560, H: 460}, Color: scene.Color{R: 250, G: 250, B: 250, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 50, Y: 50, W: 300, H: 300}, Radii: r4(16), Color: scene.Color{R: 30, G: 200, B: 90, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpHole, Rect: scene.Rect{X: 100, Y: 100, W: 40, H: 40}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 80, Y: 80, W: 200, H: 200}, Color: scene.Color{R: 10, B: 90, A: 255}})
|
||||
}
|
||||
all := func(add func(scene.Op)) { shadow(add); ring(add); opaque(add) }
|
||||
rounded := scene.Op{Rect: scene.Rect{X: 40, Y: 30, W: 520, H: 440}, Radii: r4(40)}
|
||||
continuous := scene.Op{Rect: scene.Rect{X: 40, Y: 30, W: 520, H: 440}, Radii: r4(40), Continuous: true}
|
||||
rotated := scene.Op{Rect: scene.Rect{X: 40, Y: 30, W: 520, H: 440}, Transform: scene.Rotation(3)}
|
||||
return []MaskedCase{
|
||||
build("masked ring", rounded, ring), build("masked shadow", rounded, shadow), build("masked opaque", rounded, opaque),
|
||||
build("masked continuous", continuous, all), build("masked rotated", rotated, all), build("masked everything", rounded, all),
|
||||
}
|
||||
}
|
||||
|
||||
// WideScene returns a 600×500 scene with colors outside the sRGB gamut
|
||||
// (Scene.Wide, Op.Wide, Glyph.Wide) in large opaque fills, a ring, a gradient
|
||||
// glyph run inside a continuous rounded clip, and plain fills, which the
|
||||
// float16 targets of Metal keep and the others draw as their nearest sRGB
|
||||
// colors.
|
||||
func WideScene() *scene.Scene {
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
s := &scene.Scene{Width: 600, Height: 500, Clear: scene.Color{R: 30, G: 34, B: 40, A: 255}}
|
||||
s.MaskAtlas, s.Text, s.Glyphs = glyphContent()
|
||||
s.Wide = []scene.WideColors{
|
||||
{Color: [4]float32{-0.25, 1.1, -0.1, 1}, Set: scene.WideColor},
|
||||
{Color: [4]float32{1.15, -0.2, -0.1, 1}, Color2: [4]float32{-0.2, 0.3, 1.2, 1}, Set: scene.WideColor | scene.WideColor2},
|
||||
{Border: [4]float32{1.2, 0.2, -0.1, 0.5}, Set: scene.WideBorder},
|
||||
{Color: [4]float32{0.2, 1.2, 0.3, 0.5}, Set: scene.WideColor},
|
||||
}
|
||||
green, red := scene.Color{G: 255, A: 255}, scene.Color{R: 255, A: 255}
|
||||
s.Glyphs = append([]scene.Glyph(nil), s.Glyphs...)
|
||||
for i := range s.Glyphs {
|
||||
s.Glyphs[i].Wide = 1
|
||||
}
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 600, H: 500}, Color: green, Wide: 1},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 30, Y: 30, W: 540, H: 440}, Radii: r4(24), Continuous: true, Color: green, Wide: 1,
|
||||
Border: scene.Uniform(3), BorderColor: scene.Color{R: 255, A: 255}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 20, W: 560, H: 460}, Radii: r4(16), Border: scene.Uniform(2), BorderColor: scene.Color{B: 255, A: 200}, Wide: 3},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 100, Y: 100, W: 300, H: 200}, Paint: scene.PaintOklab, Gradient: [4]float32{100, 0, 400, 0}, Color: green, Color2: red, Wide: 2},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 150, Y: 150, W: 300, H: 250}, Color: scene.Color{R: 60, G: 60, B: 255, A: 128}, Wide: 4},
|
||||
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 60, Y: 60, W: 400, H: 300}, Radii: r4(30), Continuous: true},
|
||||
scene.Op{Kind: scene.OpGlyphs, Start: 0, End: int32(len(s.Glyphs)), Paint: scene.PaintOklab, Gradient: [4]float32{40, 0, 240, 0}, Color: green, Color2: red, Wide: 2},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 70, Y: 200, W: 380, H: 100}, Color: red, Wide: 1},
|
||||
scene.Op{Kind: scene.OpPopClip})
|
||||
return s
|
||||
}
|
||||
|
||||
// WithoutNewPaints returns s without what shaders older than gradients of
|
||||
// stops draw differently: ops painting with stops (scene.Stop), borders
|
||||
// painted with a gradient (Op.BorderPaint) and images blurred, for tests
|
||||
// that compare a renderer with an earlier copy of its shader.
|
||||
func WithoutNewPaints(s *scene.Scene) *scene.Scene {
|
||||
out := *s
|
||||
out.Ops = nil
|
||||
for _, op := range s.Ops {
|
||||
if op.Paint.HasStops() || op.BorderPaint || op.Kind == scene.OpImage && op.Blur > 0 {
|
||||
continue
|
||||
}
|
||||
out.Ops = append(out.Ops, op)
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
// Continuously returns a copy of s whose ops all have continuous corners
|
||||
// (scene.Op.Continuous): fills, shadows, images, holes, effects and clips.
|
||||
func Continuously(s *scene.Scene) *scene.Scene {
|
||||
c := *s
|
||||
c.Ops = append([]scene.Op(nil), s.Ops...)
|
||||
for i := range c.Ops {
|
||||
c.Ops[i].Continuous = true
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
// CardsScene returns a w×h scene of cards with continuous corners (as
|
||||
// macOS draws them) at the sizes of panels, which the builder draws as
|
||||
// nine-patches: each casting a soft shadow and a tight one, at places
|
||||
// between pixels, with radii from 4 to 60 and uneven ones; a card with a
|
||||
// border, a dashed border, a gradient, a translucent color, a border
|
||||
// only, a large image, an inner shadow, a hard shadow, a shadow offset
|
||||
// beyond its blur, one under a rounded clip and one under a continuous
|
||||
// clip.
|
||||
func CardsScene(w, h int) *scene.Scene {
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 240, G: 241, B: 244, A: 255}}
|
||||
pix := make([]byte, 32*32*4)
|
||||
for y := range 32 {
|
||||
for x := range 32 {
|
||||
i := (y*32 + x) * 4
|
||||
pix[i], pix[i+1], pix[i+2], pix[i+3] = byte(x*8), byte(y*8), 160, 255
|
||||
}
|
||||
}
|
||||
img := scene.NewImageRGBA(32, 32, pix)
|
||||
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
radii := [][4]float32{r4(4), r4(12), r4(24), r4(60), {30, 8, 0, 16}, r4(18), r4(999), r4(10), r4(36), {0, 40, 40, 0}, r4(16), r4(20)}
|
||||
cols := 4
|
||||
cw, ch := (float32(w)-40)/float32(cols)-30, (float32(h)-40)/3-30
|
||||
white := scene.Color{R: 255, G: 255, B: 255, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
for i, r := range radii {
|
||||
card := scene.Rect{X: 35 + float32(i%cols)*(cw+30) + float32(i%3)*0.25, Y: 35 + float32(i/cols)*(ch+30) + float32(i%5)*0.2, W: cw, H: ch}
|
||||
if i == 6 {
|
||||
card.H = ch / 2 // a pill
|
||||
}
|
||||
sh := card
|
||||
sh.Y += 4
|
||||
blur := float32(24)
|
||||
switch i {
|
||||
case 7:
|
||||
blur = 0 // hard
|
||||
case 8:
|
||||
sh.Y += 40 // offset beyond the blur
|
||||
blur = 8
|
||||
}
|
||||
fill := scene.Op{Kind: scene.OpFill, Rect: card, Radii: r, Color: white, Continuous: true}
|
||||
switch i {
|
||||
case 1:
|
||||
fill.Border, fill.BorderColor = scene.Uniform(1.5), blue
|
||||
case 2:
|
||||
fill.Border, fill.BorderColor, fill.Dashed = scene.Uniform(2), blue, true
|
||||
case 3:
|
||||
fill.Paint, fill.Color2, fill.Gradient = scene.PaintLinear, blue, [4]float32{card.X, card.Y, card.X + card.W, card.Y + card.H}
|
||||
case 4:
|
||||
fill.Color = scene.Color{R: 255, G: 255, B: 255, A: 160}
|
||||
case 5:
|
||||
fill.Color, fill.Border, fill.BorderColor = scene.Color{}, [4]float32{1, 3, 2, 4}, blue
|
||||
}
|
||||
if i == 10 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: card.X - 20, Y: card.Y - 10, W: card.W + 40, H: card.H}, Radii: r4(30)})
|
||||
}
|
||||
if i == 11 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: card.X + 10, Y: card.Y - 30, W: card.W, H: card.H}, Radii: r4(30), Continuous: true})
|
||||
}
|
||||
// The soft shadow is opaque, so that the least difference shows.
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpShadow, Rect: sh, Radii: r, Color: scene.Color{A: 255}, Blur: blur, Cast: card, CastRadii: r, Continuous: true},
|
||||
scene.Op{Kind: scene.OpShadow, Rect: card, Radii: r, Color: scene.Color{A: 40}, Blur: 3, Cast: card, CastRadii: r, Continuous: true},
|
||||
fill)
|
||||
switch i {
|
||||
case 0:
|
||||
// On whole pixels: the CPU renderer samples images between them
|
||||
// differently.
|
||||
in := scene.Rect{X: float32(math.Round(float64(card.X + 20))), Y: float32(math.Round(float64(card.Y + 20))),
|
||||
W: float32(math.Round(float64(card.W - 40))), H: float32(math.Round(float64(card.H - 40)))}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpImage, Rect: in, Radii: r4(20), Image: img, Src: scene.Rect{W: 32, H: 32}, Continuous: true})
|
||||
case 9:
|
||||
in := scene.Rect{X: card.X + 10, Y: card.Y + 10, W: card.W - 20, H: card.H - 20}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpShadow, Inset: true, Rect: in, Radii: r4(12), Color: scene.Color{R: 220, G: 40, B: 40, A: 160},
|
||||
Blur: 16, Cast: card, CastRadii: r, Continuous: true})
|
||||
case 10, 11:
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package gputest
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// MaskedClipScene has clips masked by gradients, linear of two colors and
|
||||
// of stops, radial and conic, and by an image (a path's coverage),
|
||||
// with fills, a shadow and an image inside, a clip within a masked one,
|
||||
// rounded or not, a masked clip turned, and one only moved, by whole
|
||||
// pixels and between them, which renderers fold; all of them again,
|
||||
// scaled, under the reference scene's size (Scene); and part of an image
|
||||
// over a rounded clip.
|
||||
func MaskedClipScene() *scene.Scene {
|
||||
scene.FoldTranslations() // as package ui does
|
||||
s := &scene.Scene{Width: 320, Height: 740, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
add := func(ops ...scene.Op) { s.Ops = append(s.Ops, ops...) }
|
||||
r4 := func(v float32) [4]float32 { return [4]float32{v, v, v, v} }
|
||||
red, blue := scene.Color{R: 220, G: 40, B: 40, A: 255}, scene.Color{R: 40, G: 60, B: 220, A: 255}
|
||||
black, clear := scene.Color{A: 255}, scene.Color{}
|
||||
stops := func(st ...scene.Stop) [2]int32 {
|
||||
a := int32(len(s.Stops))
|
||||
s.Stops = append(s.Stops, st...)
|
||||
return [2]int32{a, int32(len(s.Stops))}
|
||||
}
|
||||
content := func(x, y float32, m scene.Affine) {
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: x, Y: y, W: 90, H: 80}, Color: red, Transform: m},
|
||||
scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: x + 20, Y: y + 18, W: 40, H: 30}, Radii: r4(6), Blur: 8, Color: scene.Color{A: 160}, Transform: m},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: x + 20, Y: y + 15, W: 50, H: 40}, Radii: r4(10), Color: blue,
|
||||
Border: scene.Uniform(2), BorderColor: scene.Color{R: 250, G: 250, B: 250, A: 255}, Transform: m})
|
||||
}
|
||||
// Two colors along a line, faded out to the right.
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 10, W: 90, H: 80}, Paint: scene.PaintLinear,
|
||||
Color: black, Color2: clear, Gradient: [4]float32{20, 0, 90, 0}})
|
||||
content(10, 10, scene.Affine{})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
// Stops fading the top and the bottom, in a rounded clip, with a
|
||||
// clip inside, and a rounded one inside that.
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 110, Y: 10, W: 90, H: 80}, Radii: r4(14), Paint: scene.PaintLinearStops,
|
||||
Gradient: [4]float32{0, 10, 0, 90}, Stops: stops(scene.Stop{Color: clear, At: 0}, scene.Stop{Color: black, At: 0.25},
|
||||
scene.Stop{Color: black, At: 0.75}, scene.Stop{Color: clear, At: 1})})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 115, Y: 5, W: 70, H: 95}})
|
||||
content(110, 10, scene.Affine{})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 150, Y: 40, W: 40, H: 40}, Radii: r4(12)})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 140, Y: 30, W: 60, H: 60}, Color: scene.Color{G: 160, B: 90, A: 255}})
|
||||
add(scene.Op{Kind: scene.OpPopClip}, scene.Op{Kind: scene.OpPopClip}, scene.Op{Kind: scene.OpPopClip})
|
||||
// Radial and conic.
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 210, Y: 10, W: 90, H: 80}, Paint: scene.PaintRadial,
|
||||
Gradient: [4]float32{255, 50, 45, 0}, Stops: stops(scene.Stop{Color: black, At: 0.4}, scene.Stop{Color: clear, At: 1})})
|
||||
content(210, 10, scene.Affine{})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 100, W: 90, H: 80}, Paint: scene.PaintConic,
|
||||
Gradient: [4]float32{55, 140, 0.3, 0}, Stops: stops(scene.Stop{Color: clear, At: 0}, scene.Stop{Color: black, At: 1})})
|
||||
content(10, 100, scene.Affine{})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
// A disc's coverage, as a path's mask, with an image inside.
|
||||
const d = 64
|
||||
pix := make([]byte, 4*d*d)
|
||||
for y := range d {
|
||||
for x := range d {
|
||||
dx, dy := float64(x)+0.5-d/2, float64(y)+0.5-d/2
|
||||
pix[4*(y*d+x)+3] = byte(255 * clamp(d/2-1-math.Sqrt(dx*dx+dy*dy)))
|
||||
}
|
||||
}
|
||||
disc := scene.NewImageRGBA(d, d, pix)
|
||||
img := make([]byte, 4*8*8)
|
||||
for i := 0; i < len(img); i += 4 {
|
||||
img[i], img[i+1], img[i+2], img[i+3] = byte(i*4), 120, byte(255-i*4), 255
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 120, Y: 108, W: d, H: d}, Image: disc, Src: scene.Rect{W: d, H: d}})
|
||||
content(110, 100, scene.Affine{})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 160, Y: 140, W: 40, H: 40}, Image: scene.NewImageRGBA(8, 8, img), Src: scene.Rect{W: 8, H: 8}})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
// Turned.
|
||||
turn := scene.Translation(255, 140).Mul(scene.Rotation(12)).Mul(scene.Translation(-255, -140))
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 215, Y: 105, W: 80, H: 70}, Radii: r4(10), Paint: scene.PaintLinear,
|
||||
Color: clear, Color2: black, Gradient: [4]float32{215, 105, 295, 175}, Transform: turn})
|
||||
content(210, 100, turn)
|
||||
add(scene.Op{Kind: scene.OpPopClip, Transform: turn})
|
||||
// Moved by whole pixels, and between them, the gradient and the image
|
||||
// with the clip.
|
||||
for i, m := range []scene.Affine{scene.Translation(3, 2), scene.Translation(-4.25, 1.75)} {
|
||||
x := 10 + 110*float32(i)
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: x, Y: 200, W: 90, H: 80}, Paint: scene.PaintLinearStops,
|
||||
Gradient: [4]float32{x, 0, x + 90, 0}, Stops: stops(scene.Stop{Color: clear, At: 0.1}, scene.Stop{Color: black, At: 0.6}), Transform: m})
|
||||
content(x, 200, m)
|
||||
add(scene.Op{Kind: scene.OpPopClip, Transform: m})
|
||||
}
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 230, Y: 208, W: d, H: d}, Image: disc, Src: scene.Rect{W: d, H: d}, Transform: scene.Translation(2.5, -1.25)})
|
||||
content(220, 200, scene.Translation(2.5, -1.25))
|
||||
add(scene.Op{Kind: scene.OpPopClip, Transform: scene.Translation(2.5, -1.25)})
|
||||
// Scaled, the masks with the clips.
|
||||
n, grow := len(s.Ops), scene.Translation(0, 300).Mul(scene.Scaling(1.2, 1.4))
|
||||
for _, op := range s.Ops[:n] {
|
||||
op.Transform = grow.Mul(op.Transform)
|
||||
add(op)
|
||||
}
|
||||
// Part of an image's alpha over a rounded clip, as an element's
|
||||
// layers of masks under its ClipInset (ui's Masks): the disc's middle,
|
||||
// stretched.
|
||||
add(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 696, W: 90, H: 40}, Radii: r4(8), Image: disc, Src: scene.Rect{X: 8, Y: 16, W: 48, H: 32}})
|
||||
add(scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 690, W: 110, H: 50}, Color: red})
|
||||
add(scene.Op{Kind: scene.OpPopClip})
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package gputest
|
||||
|
||||
import "github.com/egoist/mygo/internal/scene"
|
||||
|
||||
// SpriteScene returns a w×h frame of a 2D game: layers of tiles of 16
|
||||
// pixels drawn scale times as large, pixelated, from one sheet, covering
|
||||
// the frame, and sprites of 16×32 over them, all ops of one image. With
|
||||
// scale 3 at 1920×1080, three layers and 300 sprites, it draws 1,872
|
||||
// sprites, about what a top-down farming game draws.
|
||||
func SpriteScene(w, h int, scale float32, layers, sprites int) *scene.Scene {
|
||||
s := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 40, G: 44, B: 52, A: 255}}
|
||||
// A sheet of 8×8 tiles of 16 pixels, each of its own colors.
|
||||
const tiles, tile = 8, 16
|
||||
pix := make([]byte, tiles*tile*tiles*tile*4)
|
||||
for y := range tiles * tile {
|
||||
for x := range tiles * tile {
|
||||
i := (y*tiles*tile + x) * 4
|
||||
tx, ty := x/tile, y/tile
|
||||
pix[i] = byte(tx*32 + x%tile*2)
|
||||
pix[i+1] = byte(ty*32 + y%tile*2)
|
||||
pix[i+2] = byte((tx + ty) * 16)
|
||||
pix[i+3] = 255
|
||||
}
|
||||
}
|
||||
sheet := scene.NewImageRGBA(tiles*tile, tiles*tile, pix)
|
||||
size := tile * scale
|
||||
cols, rows := int(float32(w)/size)+1, int(float32(h)/size)+1
|
||||
for l := range layers {
|
||||
for r := range rows {
|
||||
for c := range cols {
|
||||
k := (r*cols + c + l*7) % (tiles * tiles)
|
||||
src := scene.Rect{X: float32(k%tiles) * tile, Y: float32(k/tiles) * tile, W: tile, H: tile}
|
||||
if l > 0 && (r+c+l)%3 != 0 {
|
||||
continue // upper layers cover a third
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: float32(c) * size, Y: float32(r) * size, W: size, H: size},
|
||||
Image: sheet, Src: src, Pixelated: true})
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range sprites {
|
||||
x := float32(i*97%max(w-int(size), 1)) + 0.5
|
||||
y := float32(i*61%max(h-int(2*size), 1)) + 0.25
|
||||
src := scene.Rect{X: float32(i%tiles) * tile, Y: 0, W: tile, H: 2 * tile}
|
||||
if i%2 == 1 {
|
||||
src.X, src.W = src.X+src.W, -src.W // facing left
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: x, Y: y, W: size, H: 2 * size}, Image: sheet, Src: src, Pixelated: true})
|
||||
}
|
||||
return s
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package gputest
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TransformedScene exercises all primitives and effects under affine
|
||||
// composition, with nested transformed clips and an inline glyph transform.
|
||||
func TransformedScene() *scene.Scene {
|
||||
s := Scene()
|
||||
s.Clear = scene.Color{R: 100, G: 120, B: 160, A: 80}
|
||||
m := scene.Translation(25, 20).Mul(scene.Rotation(4)).Mul(scene.Scaling(0.8, 0.9))
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Transform = m
|
||||
}
|
||||
if len(s.Glyphs) > 0 {
|
||||
s.Glyphs[0].Transform = scene.Rotation(15)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// PerspectiveScene exercises all primitives and effects seen in
|
||||
// perspective: the scene turned 20 degrees about its vertical center line,
|
||||
// seen from 900 pixels, as RotationY and Perspective make it, with a
|
||||
// skewed glyph and a nested clip turned the other way.
|
||||
func PerspectiveScene() *scene.Scene {
|
||||
s := Scene()
|
||||
s.Clear = scene.Color{R: 100, G: 120, B: 160, A: 80}
|
||||
turn := func(degrees, d, cx, cy float32) scene.Affine {
|
||||
sin, cos := math.Sincos(float64(degrees) * math.Pi / 180)
|
||||
m := scene.Projective(float32(cos), 0, 0, 1, 0, 0, float32(sin)/d, 0)
|
||||
return scene.Translation(cx, cy).Mul(m).Mul(scene.Translation(-cx, -cy))
|
||||
}
|
||||
m := turn(20, 900, float32(s.Width)/2, float32(s.Height)/2)
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Transform = m
|
||||
}
|
||||
if len(s.Glyphs) > 0 {
|
||||
s.Glyphs[0].Transform = scene.Matrix(1, 0, 0.3, 1, 0, 0)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// BehindOriginScene is a card far from its drawing's origin, turned over
|
||||
// in perspective around its center, which the frame shows at (160, 370):
|
||||
// the origin is behind the viewer, past the turned plane's horizon
|
||||
// (scene.Affine.Behind), the card in front (#1406). A rounded clip, its
|
||||
// shadow, a border and a gradient turn with it; red shows at the frame's
|
||||
// center.
|
||||
func BehindOriginScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 740, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
sin, cos := math.Sincos(-60 * math.Pi / 180)
|
||||
turn := scene.Projective(1, 0, 0, float32(cos), 0, 0, 0, float32(-sin)/600)
|
||||
m := scene.Translation(160, 370).Mul(turn).Mul(scene.Translation(-1050, -1050))
|
||||
r4 := func(v float32) [4]float32 { return [4]float32{v, v, v, v} }
|
||||
red, blue := scene.Color{R: 220, G: 40, B: 40, A: 255}, scene.Color{R: 40, G: 60, B: 220, A: 255}
|
||||
s.Ops = []scene.Op{
|
||||
{Kind: scene.OpShadow, Rect: scene.Rect{X: 1000, Y: 1004, W: 100, H: 100}, Radii: r4(12), Blur: 6, Color: scene.Color{A: 120}, Transform: m},
|
||||
{Kind: scene.OpPushClip, Rect: scene.Rect{X: 1000, Y: 1000, W: 100, H: 100}, Radii: r4(12), Transform: m},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 990, Y: 990, W: 120, H: 120}, Color: blue, Color2: red, Paint: scene.PaintLinear,
|
||||
Gradient: [4]float32{1000, 1000, 1100, 1000}, Transform: m},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 1030, Y: 1030, W: 40, H: 40}, Radii: r4(8), Color: red,
|
||||
Border: scene.Uniform(3), BorderColor: scene.Color{R: 250, G: 250, B: 250, A: 255}, Transform: m},
|
||||
{Kind: scene.OpPopClip, Transform: m},
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// AxisClipScene is content under a hard clip that a pose scales and moves
|
||||
// (a scroll view in a panel that is entering): the clip edges fall in the middle
|
||||
// of pixels (the CPU renderer samples a pixel on a 4x4 grid, so its
|
||||
// coverage is exact there).
|
||||
func AxisClipScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 200, Height: 160, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
m := scene.Translation(7.5, 5.5).Mul(scene.Scaling(.5, .5))
|
||||
red, blue := scene.Color{R: 220, G: 40, B: 40, A: 255}, scene.Color{R: 40, G: 60, B: 220, A: 255}
|
||||
s.Ops = []scene.Op{
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 5, Y: 5, W: 120, H: 100}, Radii: [4]float32{14, 14, 14, 14}, Color: blue, Transform: m},
|
||||
{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 12, W: 80, H: 60}, Transform: m},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{W: 200, H: 160}, Color: red, Transform: m},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 40, Y: 30, W: 90, H: 70}, Radii: [4]float32{20, 20, 20, 20}, Color: blue, Transform: m},
|
||||
{Kind: scene.OpPopClip, Transform: m},
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// TranslatedScenes are the reference scene moved by translations, by
|
||||
// whole pixels and between them (not by halves: the centers of pixels
|
||||
// would fall on the seam of a conic gradient, which renderers round
|
||||
// apart), which renderers fold into the geometry
|
||||
// of its fills, shadows, images and (by whole pixels) glyphs, its clips
|
||||
// and effects keeping theirs (scene.TranslationFolder).
|
||||
func TranslatedScenes() []*scene.Scene {
|
||||
scene.FoldTranslations() // as package ui does
|
||||
var ss []*scene.Scene
|
||||
for _, m := range []scene.Affine{scene.Translation(12, 7), scene.Translation(-6.25, 4.25)} {
|
||||
s := Scene()
|
||||
s.Clear = scene.Color{R: 100, G: 120, B: 160, A: 80}
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Transform = m
|
||||
}
|
||||
ss = append(ss, s)
|
||||
}
|
||||
return ss
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package gputest
|
||||
|
||||
import "github.com/egoist/mygo/internal/scene"
|
||||
|
||||
// NV12Frame returns a w×h frame of video in NV12 with the matrix m, its
|
||||
// planes in memory with rows padded past their width, as decoders pad
|
||||
// them: bars of saturated colors over a gradient of luma, which the
|
||||
// renderers sample as planes and the CPU renderer converts (Restore).
|
||||
func NV12Frame(w, h int, m scene.YUVMatrix) *scene.Image {
|
||||
ls, cs := w+13, 2*((w+1)/2)+6
|
||||
cw, ch := (w+1)/2, (h+1)/2
|
||||
luma, chroma := make([]byte, ls*h), make([]byte, cs*ch)
|
||||
for y := range h {
|
||||
for x := range w {
|
||||
luma[y*ls+x] = byte(16 + (219*x)/max(w-1, 1))
|
||||
}
|
||||
}
|
||||
// Six bars of chroma, Cb and Cr from 16 to 240.
|
||||
bars := [][2]byte{{240, 128}, {16, 240}, {128, 16}, {240, 240}, {16, 16}, {90, 200}}
|
||||
for y := range ch {
|
||||
for x := range cw {
|
||||
c := bars[x*len(bars)/cw]
|
||||
if y < ch/4 {
|
||||
c = [2]byte{128, 128} // gray
|
||||
}
|
||||
chroma[y*cs+2*x], chroma[y*cs+2*x+1] = c[0], c[1]
|
||||
}
|
||||
}
|
||||
return SurfaceImage(&scene.Surface{
|
||||
Format: scene.SurfaceNV12,
|
||||
Matrix: m,
|
||||
Planes: [2]scene.Plane{{Pix: luma, Stride: ls}, {Pix: chroma, Stride: cs}},
|
||||
}, w, h)
|
||||
}
|
||||
|
||||
// SurfaceImage returns an image showing s, whose pixels convert it.
|
||||
func SurfaceImage(s *scene.Surface, w, h int) *scene.Image {
|
||||
img := scene.NewImageRGBA(w, h, nil)
|
||||
img.Surface = s
|
||||
img.Restore = func() []byte { return s.RGBA(nil, w, h) }
|
||||
return img
|
||||
}
|
||||
|
||||
// VideoScene draws frames of video in NV12 of each matrix, scaled,
|
||||
// rounded, faded and in grayscale, as video elements show them.
|
||||
func VideoScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 360, Height: 260, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
|
||||
add := func(op scene.Op) { s.Ops = append(s.Ops, op) }
|
||||
for i, m := range []scene.YUVMatrix{scene.BT601, scene.BT709, scene.BT2020, scene.BT601 + scene.FullRange, scene.BT709 + scene.FullRange, scene.BT2020 + scene.FullRange} {
|
||||
img := NV12Frame(96, 54, m)
|
||||
x, y := float32(8+(i%3)*116), float32(8+(i/3)*72)
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: x, Y: y, W: 96, H: 54}, Image: img, Src: scene.Rect{W: 96, H: 54}})
|
||||
}
|
||||
big := NV12Frame(64, 36, scene.BT709)
|
||||
// Scaled up, with rounded corners, faded, and in grayscale.
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 8, Y: 160, W: 160, H: 90}, Radii: [4]float32{12, 12, 12, 12}, Image: big, Src: scene.Rect{W: 64, H: 36}})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 184, Y: 160, W: 80, H: 45}, Image: big, Src: scene.Rect{W: 64, H: 36}, Opacity: 0.5})
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 272, Y: 160, W: 80, H: 45}, Image: big, Src: scene.Rect{W: 64, H: 36}, Grayscale: true})
|
||||
// An odd size, whose chroma has a half sample at its edges.
|
||||
add(scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 184, Y: 216, W: 37, H: 21}, Image: NV12Frame(37, 21, scene.BT601), Src: scene.Rect{W: 37, H: 21}})
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkRenderBatches draws scenes whose ops interleave the classes of
|
||||
// the shader (gpu.Class) and scenes of long runs of one class, with the
|
||||
// renderer's batches ("joined"), with the batches of each class apart
|
||||
// however small ("apart", gpu.Builder.NoJoin) and with every batch in the
|
||||
// general class ("general"): ns/op is the time of a frame, GPU-ms what the GPU spent on
|
||||
// it, and batches how many draw calls it took.
|
||||
func BenchmarkRenderBatches(b *testing.B) {
|
||||
cases := []struct {
|
||||
name string
|
||||
s func() *scene.Scene
|
||||
}{
|
||||
{"boxes", func() *scene.Scene { return gputest.BoxesScene(1280, 800, 600, false) }},
|
||||
{"translated boxes", func() *scene.Scene { return gputest.BoxesScene(1280, 800, 600, true) }},
|
||||
{"rows", func() *scene.Scene { return gputest.RowsScene(1280, 800, 40) }},
|
||||
{"fills", func() *scene.Scene { return gputest.FillScene(3456, 2000) }},
|
||||
{"opaque", func() *scene.Scene { return gputest.OpaqueScene(3456, 2000) }},
|
||||
}
|
||||
for _, c := range cases {
|
||||
for _, mode := range []string{"joined", "apart", "general"} {
|
||||
b.Run(c.name+"/"+mode, func(b *testing.B) {
|
||||
benchRenderWith(b, c.s(), func(r *Renderer) { r.b.NoJoin, r.b.NoClasses = mode == "apart", mode == "general" })
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkRenderSprites draws frames of a 2D game at 1920×1080
|
||||
// (gputest's SpriteScene: 1,872 sprites of one sheet) into one texture,
|
||||
// waiting for each: ns/op is the time of a frame, GPU-ms what the GPU
|
||||
// spent on it, by its command buffer's timestamps, and encode-ms what the
|
||||
// CPU spent encoding it.
|
||||
func BenchmarkRenderSprites(b *testing.B) {
|
||||
benchRender(b, gputest.SpriteScene(1920, 1080, 3, 3, 300))
|
||||
}
|
||||
|
||||
// BenchmarkRenderSpritesZoomedOut draws the game zoomed out: about 7,000
|
||||
// sprites.
|
||||
func BenchmarkRenderSpritesZoomedOut(b *testing.B) {
|
||||
benchRender(b, gputest.SpriteScene(1920, 1080, 1.5, 3, 1000))
|
||||
}
|
||||
|
||||
// BenchmarkRenderEmpty draws frames of nothing at 1920×1080: what the
|
||||
// others spend besides their sprites.
|
||||
func BenchmarkRenderEmpty(b *testing.B) {
|
||||
benchRender(b, &scene.Scene{Width: 1920, Height: 1080, Clear: scene.Color{A: 255}})
|
||||
}
|
||||
|
||||
func benchRender(b *testing.B, s *scene.Scene) { benchRenderWith(b, s, nil) }
|
||||
|
||||
// benchRenderWith is benchRender with the renderer set up by setup, if not
|
||||
// nil, and the batches of the frame reported.
|
||||
func benchRenderWith(b *testing.B, s *scene.Scene, setup func(*Renderer)) {
|
||||
o, err := NewOffscreen(s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip("no Metal:", err)
|
||||
}
|
||||
defer o.Release()
|
||||
if setup != nil {
|
||||
setup(o.r)
|
||||
}
|
||||
var gpu, encoded time.Duration
|
||||
for b.Loop() {
|
||||
d, err := o.Render(s)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
gpu += d
|
||||
encoded += o.Encoded()
|
||||
}
|
||||
b.ReportMetric(gpu.Seconds()*1000/float64(b.N), "GPU-ms")
|
||||
b.ReportMetric(encoded.Seconds()*1000/float64(b.N), "encode-ms")
|
||||
if setup != nil {
|
||||
b.ReportMetric(float64(len(o.r.b.Batches)), "batches")
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkRenderBoxes draws 600 rounded boxes casting shadows at
|
||||
// 1280×800, and BenchmarkRenderTranslatedBoxes the same boxes under
|
||||
// translations, as an animation moves them.
|
||||
func BenchmarkRenderBoxes(b *testing.B) { benchRender(b, gputest.BoxesScene(1280, 800, 600, false)) }
|
||||
|
||||
func BenchmarkRenderTranslatedBoxes(b *testing.B) {
|
||||
benchRender(b, gputest.BoxesScene(1280, 800, 600, true))
|
||||
}
|
||||
|
||||
// BenchmarkRenderCards draws a dashboard of twelve cards with continuous
|
||||
// corners at 2560×1600 (gputest.CardsScene), each casting two shadows,
|
||||
// which the builder draws as nine-patches (gpu.Builder.SplitCorners).
|
||||
func BenchmarkRenderCards(b *testing.B) { benchRender(b, gputest.CardsScene(2560, 1600)) }
|
||||
|
||||
// BenchmarkRenderPanels draws a page of 96 cards at 2560×1600
|
||||
// (gputest.PanelsScene): clips and images change from card to card, so a
|
||||
// frame takes hundreds of batches, and encode-ms is mostly their cost.
|
||||
func BenchmarkRenderPanels(b *testing.B) {
|
||||
benchRenderWith(b, gputest.PanelsScene(2560, 1600, 96), func(*Renderer) {})
|
||||
}
|
||||
|
||||
// BenchmarkVideoFrameRGBA draws a new 1920×1080 frame of video each frame,
|
||||
// as video drew before frames had surfaces: converted to RGBA on the CPU,
|
||||
// as a decoder in Go would, and uploaded, 8 MB a frame.
|
||||
func BenchmarkVideoFrameRGBA(b *testing.B) {
|
||||
img := gputest.NV12Frame(1920, 1080, scene.BT709)
|
||||
rgb := scene.NewImageRGBA(1920, 1080, nil)
|
||||
benchVideo(b, videoBenchScene(rgb), func() {
|
||||
rgb.Pix = img.Surface.RGBA(rgb.Pix, 1920, 1080)
|
||||
rgb.Changed()
|
||||
})
|
||||
}
|
||||
|
||||
// BenchmarkVideoFrameNV12 draws a new 1920×1080 frame of video each frame
|
||||
// from its NV12 planes in memory, as ui.Bitmap.UpdateYUV gives them: 3 MB
|
||||
// uploaded, and converted in the shader.
|
||||
func BenchmarkVideoFrameNV12(b *testing.B) {
|
||||
img := gputest.NV12Frame(1920, 1080, scene.BT709)
|
||||
benchVideo(b, videoBenchScene(img), img.Changed)
|
||||
}
|
||||
|
||||
func videoBenchScene(img *scene.Image) *scene.Scene {
|
||||
return &scene.Scene{Width: 1280, Height: 720, Clear: scene.Color{A: 255}, Ops: []scene.Op{{
|
||||
Kind: scene.OpImage, Rect: scene.Rect{W: 1280, H: 720}, Image: img, Src: scene.Rect{W: 1920, H: 1080},
|
||||
}}}
|
||||
}
|
||||
|
||||
// benchVideo draws s after next changed its frame, each time, reporting
|
||||
// what the GPU and the encoding spent as benchRender does.
|
||||
func benchVideo(b *testing.B, s *scene.Scene, next func()) {
|
||||
o, err := NewOffscreen(s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip("no Metal:", err)
|
||||
}
|
||||
defer o.Release()
|
||||
b.SetBytes(1920 * 1080 * 4)
|
||||
var gpu, encoded time.Duration
|
||||
for b.Loop() {
|
||||
next()
|
||||
d, err := o.Render(s)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
gpu += d
|
||||
encoded += o.Encoded()
|
||||
}
|
||||
b.ReportMetric(gpu.Seconds()*1000/float64(b.N), "GPU-ms")
|
||||
b.ReportMetric(encoded.Seconds()*1000/float64(b.N), "encode-ms")
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Canvases draw into textures as the CPU renderer draws them into pixels,
|
||||
// once each: the second frame draws none anew, and shows them the same.
|
||||
func TestCanvases(t *testing.T) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
s := gputest.CanvasScene()
|
||||
for frame := range 2 {
|
||||
pix, err := r.renderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "metal-canvas", pix, s.Width*4, s)
|
||||
if frame == 0 {
|
||||
s.Canvases = nil // drawn: only shown from now on
|
||||
}
|
||||
}
|
||||
if len(r.canvases) != 3 {
|
||||
t.Errorf("%d canvas textures, want 3", len(r.canvases))
|
||||
}
|
||||
}
|
||||
|
||||
// A transient canvas's texture stays while frames draw it, and goes once
|
||||
// they stop, though the canvas is still about; another canvas's stays
|
||||
// until it is collected.
|
||||
func TestTransientCanvas(t *testing.T) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
layer, kept := scene.NewCanvas(64, 64), scene.NewCanvas(64, 64)
|
||||
layer.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64}
|
||||
s.Canvases = []*scene.Image{layer, kept}
|
||||
if _, err := r.renderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] == nil || r.canvases[kept.ID()] == nil {
|
||||
t.Fatal("a sweep after the frame that drew them freed a canvas's texture")
|
||||
}
|
||||
r.frame++ // a frame that draws neither
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] != nil || r.canvases[kept.ID()] == nil {
|
||||
t.Errorf("transient canvas kept %v, other kept %v", r.canvases[layer.ID()] != nil, r.canvases[kept.ID()] != nil)
|
||||
}
|
||||
runtime.KeepAlive(layer)
|
||||
runtime.KeepAlive(kept)
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CompileLibrary compiles Metal Shading Language into a Metal library with
|
||||
// Xcode's metal tools, for code compiled ahead of time: go generate runs
|
||||
// it, for the renderer's shader (shaderlib.go) and effects' (EffectSource).
|
||||
func CompileLibrary(src string) ([]byte, error) {
|
||||
return CompileLibraryFor(src, "macosx", "-mmacosx-version-min=12.0")
|
||||
}
|
||||
|
||||
// CompileLibraryFor compiles a Metal library for an SDK of Xcode's
|
||||
// (macosx, iphoneos, iphonesimulator), whose oldest version the flag gives,
|
||||
// as "-mios-version-min=17.0": a library loads only on its own platform.
|
||||
func CompileLibraryFor(src, sdk, minVersion string) ([]byte, error) {
|
||||
dir, err := os.MkdirTemp("", "metal")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
in, air, lib := filepath.Join(dir, "shader.metal"), filepath.Join(dir, "shader.air"), filepath.Join(dir, "shader.metallib")
|
||||
if err := os.WriteFile(in, []byte(src), 0o644); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"-sdk", sdk, "metal", "-c", in, "-o", air, minVersion},
|
||||
{"-sdk", sdk, "metallib", air, "-o", lib},
|
||||
} {
|
||||
if out, err := exec.Command("xcrun", args...).CombinedOutput(); err != nil {
|
||||
return nil, fmt.Errorf("metal: %s: %v\n%s", args[2], err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
}
|
||||
return os.ReadFile(lib)
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestPartialFramesMatchWhole draws random scenes changing a little at a
|
||||
// time into three targets in turn, as a CAMetalLayer's drawables are,
|
||||
// each frame only where it changed since its target was drawn, and
|
||||
// requires the bytes of each frame drawn whole: in BGRA8 and float16
|
||||
// targets, over an opaque color and a translucent one.
|
||||
func TestPartialFramesMatchWhole(t *testing.T) {
|
||||
seeds := uint64(60)
|
||||
if testing.Short() {
|
||||
seeds = 10
|
||||
}
|
||||
for _, wide := range []bool{false, true} {
|
||||
frames, partial := 0, 0
|
||||
for seed := range seeds {
|
||||
// A renderer of their own, as each has an atlas of its own.
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
m := gputest.NewChanging(seed)
|
||||
if seed%3 == 2 {
|
||||
m.Clear = scene.Color{R: 20, G: 40, B: 200, A: 77}
|
||||
}
|
||||
s := m.Scene()
|
||||
t.Run(fmt.Sprintf("wide=%v/seed=%d", wide, seed), func(t *testing.T) {
|
||||
partial += partialFrames(t, r, s, wide, 30, func(int) string { return m.Change(s) })
|
||||
frames += 30
|
||||
})
|
||||
r.Release()
|
||||
}
|
||||
// Many frames change a little, though much of so small a scene:
|
||||
// those after the first three, one for each target, are drawn in
|
||||
// part but where they change half of it.
|
||||
if partial < frames/3 {
|
||||
t.Errorf("wide %v: %d frames of %d drawn in part", wide, partial, frames)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// partialFrames draws frames of s, changed by change before each but the
|
||||
// first, into three targets in turn, each only where it changed, and
|
||||
// requires the bytes of each frame drawn whole; it returns how many were
|
||||
// drawn in part.
|
||||
func partialFrames(t *testing.T, r *Renderer, s *scene.Scene, wide bool, frames int, change func(step int) string) (partial int) {
|
||||
t.Helper()
|
||||
format, bpp := uint(pixelFormatBGRA8Unorm), 4
|
||||
r.cur, r.wide = &r.formats[0], wide
|
||||
if wide {
|
||||
if !r.SetWide(true) {
|
||||
t.Skip("no float16 drawables")
|
||||
}
|
||||
r.cur, format, bpp = &r.formats[1], pixelFormatRGBA16Float, 8
|
||||
}
|
||||
cur := r.cur
|
||||
r.forgetFrames()
|
||||
defer r.forgetFrames()
|
||||
var targets [3]id
|
||||
pool(func() {
|
||||
for i := range targets {
|
||||
targets[i] = r.newTexture(s.Width, s.Height, format, usageRenderTarget|usageShaderRead, nil, 0)
|
||||
}
|
||||
})
|
||||
defer pool(func() {
|
||||
for i := range targets {
|
||||
release(&targets[i])
|
||||
}
|
||||
})
|
||||
read := func(tex id) (raw []byte, err error) {
|
||||
cb := send(r.queue, "commandBuffer")
|
||||
blit := send(cb, "blitCommandEncoder")
|
||||
send(blit, "synchronizeResource:", tex)
|
||||
send(blit, "endEncoding")
|
||||
send(cb, "commit")
|
||||
send(cb, "waitUntilCompleted")
|
||||
raw = make([]byte, s.Width*s.Height*bpp)
|
||||
msgGetBytes(tex, sel("getBytes:bytesPerRow:fromRegion:mipmapLevel:"), unsafe.Pointer(&raw[0]), uint(s.Width*bpp),
|
||||
mtlRegion{W: uint(s.Width), H: uint(s.Height), D: 1}, 0)
|
||||
return raw, nil
|
||||
}
|
||||
for step := range frames {
|
||||
what := "first"
|
||||
if step > 0 {
|
||||
what = change(step)
|
||||
}
|
||||
var got []byte
|
||||
var err error
|
||||
var part string
|
||||
pool(func() {
|
||||
r.waitLast()
|
||||
r.cur = cur
|
||||
tex := targets[step%len(targets)]
|
||||
r.diff.Wide = wide
|
||||
damage, known := r.diff.Diff(s)
|
||||
cb, e := r.drawFrame(s, damage, known, func() id { return tex })
|
||||
if e != nil {
|
||||
err = e
|
||||
return
|
||||
}
|
||||
part = "whole"
|
||||
if r.redrew == redrewPart {
|
||||
partial++
|
||||
part = r.part.String()
|
||||
}
|
||||
send(cb, "commit")
|
||||
send(cb, "waitUntilCompleted")
|
||||
if int(send(cb, "status")) == statusError {
|
||||
err = errors.New("the frame failed")
|
||||
return
|
||||
}
|
||||
got, err = read(tex)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := renderRaw(t, r, s, wide)
|
||||
if n := differing(got, want); n != 0 {
|
||||
var at []string
|
||||
for i := range got {
|
||||
if got[i] != want[i] && len(at) < 6 {
|
||||
px := i / bpp
|
||||
at = append(at, fmt.Sprintf("(%d,%d)c%d %d≠%d", px%s.Width, px/s.Width, i%bpp, got[i], want[i]))
|
||||
}
|
||||
}
|
||||
t.Fatalf("step %d (%s), redrew %s: %d bytes differ from the frame drawn whole, at %v", step, what, part, n, at)
|
||||
}
|
||||
}
|
||||
return partial
|
||||
}
|
||||
|
||||
// TestPartialFramesOfOneChange checks that a caret blinking redraws its own
|
||||
// box alone once each target was drawn whole.
|
||||
func TestPartialFramesOfOneChange(t *testing.T) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
m := gputest.NewChanging(5)
|
||||
s := m.Scene()
|
||||
caret := scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 100, Y: 100, W: 2, H: 18}, Color: scene.Color{A: 255}}
|
||||
s.Ops = append(s.Ops, caret)
|
||||
var areas []string
|
||||
redrew := func() string {
|
||||
if r.redrew != redrewPart {
|
||||
return "whole"
|
||||
}
|
||||
a := r.part.Bounds()
|
||||
return fmt.Sprintf("%d×%d", a.Right-a.Left, a.Bottom-a.Top)
|
||||
}
|
||||
partialFrames(t, r, s, false, 8, func(step int) string {
|
||||
areas = append(areas, redrew())
|
||||
if step%2 == 1 {
|
||||
s.Ops[len(s.Ops)-1].Color.A = 0
|
||||
} else {
|
||||
s.Ops[len(s.Ops)-1].Color.A = 255
|
||||
}
|
||||
return fmt.Sprint("caret ", step%2)
|
||||
})
|
||||
areas = append(areas, redrew())
|
||||
// The three targets drawn whole, then each the caret's box, grown by
|
||||
// the reach of the GPU's quads.
|
||||
want := []string{"whole", "whole", "whole", "6×22", "6×22", "6×22", "6×22", "6×22"}
|
||||
if fmt.Sprint(areas) != fmt.Sprint(want) {
|
||||
t.Errorf("redrew %v, want %v", areas, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPartialFramesApart checks that two changes in opposite corners, a
|
||||
// spinner's and a progress bar's, redraw two rectangles once each target
|
||||
// was drawn whole, not all between, with the bytes of the frame drawn
|
||||
// whole.
|
||||
func TestPartialFramesApart(t *testing.T) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
s := gputest.NewChanging(5).Scene()
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 4, Y: 4, W: 12, H: 12}, Radii: scene.Uniform(6), Color: scene.Color{R: 200, A: 255}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(s.Width) - 70, Y: float32(s.Height) - 14, W: 60, H: 6}, Radii: scene.Uniform(3), Color: scene.Color{B: 200, A: 255}})
|
||||
var rects []int
|
||||
partialFrames(t, r, s, false, 7, func(step int) string {
|
||||
if r.redrew == redrewPart {
|
||||
rects = append(rects, len(r.part.Rects))
|
||||
}
|
||||
n := len(s.Ops)
|
||||
s.Ops[n-2].Color.G += 30
|
||||
s.Ops[n-1].Rect.W -= 5
|
||||
return fmt.Sprint("spinner and progress ", step)
|
||||
})
|
||||
if r.redrew == redrewPart {
|
||||
rects = append(rects, len(r.part.Rects))
|
||||
}
|
||||
// The three targets drawn whole, then each two rectangles.
|
||||
if fmt.Sprint(rects) != "[2 2 2 2]" {
|
||||
t.Errorf("redrew rectangles %v, want [2 2 2 2]", rects)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// The head and the tail of an effect's library (scene.Effect): after
|
||||
// shader.metal with EFFECT defined, the head declares what an effect
|
||||
// reads, the effect's source follows, then the tail, after the line
|
||||
// "// effect", draws its instances with it.
|
||||
|
||||
// What an effect reads of its instance.
|
||||
struct Effect {
|
||||
float4 rect; // x, y, width, height in pixels
|
||||
float4 radii; // top-left, top-right, bottom-right, bottom-left, circular
|
||||
float4 p0, p1, p2, p3, p4;
|
||||
float4 area; // where the backdrop's area starts in the frame, and its size in texels
|
||||
float down; // the size of the squares the backdrop averages
|
||||
bool wide; // the target keeps colors outside the sRGB gamut, in extended sRGB
|
||||
float4 transform0, transform1, transform2;
|
||||
};
|
||||
|
||||
float2 framePoint(Effect e, float2 q) {
|
||||
float3 h = float3(dot(e.transform0.xyz, float3(q, 1.0)), dot(e.transform1.xyz, float3(q, 1.0)),
|
||||
dot(float3(e.transform2.xy, 1.0 - 2.0 * e.transform2.z), float3(q, 1.0)));
|
||||
return h.xy / h.z;
|
||||
}
|
||||
|
||||
float3 backdropAt(texture2d<float> t, int2 p, int2 size) {
|
||||
return t.read(uint2(clamp(p, int2(0), size - 1))).rgb;
|
||||
}
|
||||
|
||||
// sampleBackdrop returns the backdrop at q, in the frame's pixels,
|
||||
// premultiplied, filtered bilinearly from its texels as
|
||||
// scene.BackdropImage.Sample does.
|
||||
float3 sampleBackdrop(texture2d<float> t, Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5f;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float3 top = backdropAt(t, p, size) * (1.0f - w.x) + backdropAt(t, p + int2(1, 0), size) * w.x;
|
||||
float3 bot =
|
||||
backdropAt(t, p + int2(0, 1), size) * (1.0f - w.x) + backdropAt(t, p + int2(1, 1), size) * w.x;
|
||||
return top * (1.0f - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
// effect
|
||||
|
||||
fragment PSOut effect_ps(VSOut v [[stage_in]], const device Inst *insts [[buffer(0)]],
|
||||
constant float4 &globals [[buffer(1)]], texture2d<float> backdrop [[texture(3)]],
|
||||
texture2d<float> clipTex [[texture(4)]], sampler samp [[sampler(0)]]) {
|
||||
Inst i = insts[v.inst];
|
||||
Frame fr = frameOf(v, i);
|
||||
// The shape's corners are continuous where its radii are negative,
|
||||
// which the effect takes as circular.
|
||||
Effect e = {i.rect, abs(i.radii), i.inner, i.color, i.color2, i.border,
|
||||
i.grad, i.uv, i.params.z, globals.z > 0.5f, i.transform0, i.transform1, i.transform2};
|
||||
float4 res = effect(v.p, e, backdrop) * (localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr) *
|
||||
clipCoverage(v, i, clipTex, samp) * i.params.w);
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// BenchmarkRenderFillRate measures GPU timestamp duration for large opaque
|
||||
// layers, border-only rings and stacked shadows at Retina window size.
|
||||
// Like BenchmarkRenderSprites, it waits for each offscreen frame; it does
|
||||
// not measure drawable waits, presentation latency or frames in flight.
|
||||
func BenchmarkRenderFillRate(b *testing.B) {
|
||||
const w, h = 3456, 2000
|
||||
fill := func(r scene.Rect, c scene.Color) scene.Op { return scene.Op{Kind: scene.OpFill, Rect: r, Color: c} }
|
||||
background := fill(scene.Rect{W: w, H: h}, scene.Color{R: 20, G: 22, B: 28, A: 255})
|
||||
var layers []scene.Op
|
||||
for i := range 6 {
|
||||
d := float32(i)
|
||||
layers = append(layers, fill(scene.Rect{X: d, Y: d, W: w - 2*d, H: h - 2*d}, scene.Color{R: byte(20 + i), G: 22, B: 28, A: 255}))
|
||||
}
|
||||
panel := scene.Rect{X: 576, Y: 48, W: 2800, H: 1856}
|
||||
radii := scene.Uniform(24)
|
||||
card := fill(panel, scene.Color{R: 30, G: 32, B: 38, A: 255})
|
||||
card.Radii = radii
|
||||
card.Continuous = true
|
||||
ring := fill(panel, scene.Color{})
|
||||
ring.Radii = radii
|
||||
ring.Continuous = true
|
||||
ring.Border = scene.Uniform(2)
|
||||
ring.BorderColor = scene.Color{A: 100}
|
||||
shadows := []scene.Op{background, fill(scene.Rect{W: w, H: h}, scene.Color{A: 100})}
|
||||
for _, blur := range []float32{6, 16, 32, 64} {
|
||||
shadows = append(shadows, scene.Op{Kind: scene.OpShadow, Rect: panel, Radii: radii, Cast: panel, CastRadii: radii, Blur: blur, Color: scene.Color{A: 60}})
|
||||
}
|
||||
shadows = append(shadows, card)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ops []scene.Op
|
||||
}{
|
||||
{"nested_layers", layers}, {"border_ring", []scene.Op{background, card, ring}}, {"shadow_panel", shadows},
|
||||
} {
|
||||
b.Run(tc.name, func(b *testing.B) {
|
||||
benchRender(b, &scene.Scene{Width: w, Height: h, Clear: scene.Color{A: 255}, Ops: tc.ops})
|
||||
})
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Frames draws frames one after another without a layer, for videos
|
||||
// (plugins/render): into a texture of its own, whose pixels Read copies,
|
||||
// or into IOSurfaces of the caller's, as the CVPixelBuffers an encoder
|
||||
// takes, without a copy. A frame is committed without waiting for the
|
||||
// GPU, which draws it while the caller builds the next one; Wait waits
|
||||
// for it.
|
||||
//
|
||||
// Frames is not safe for concurrent use.
|
||||
type Frames struct {
|
||||
r *Renderer
|
||||
// tex is the texture Draw draws into, of w×h pixels.
|
||||
tex id
|
||||
w, h int
|
||||
// last is the command buffer of the last frame, retained until Wait
|
||||
// sees it done, and surface the texture wrapping the IOSurface it drew
|
||||
// into, released then too.
|
||||
last, surface id
|
||||
}
|
||||
|
||||
// NewFrames returns a Frames on the system's default GPU.
|
||||
func NewFrames() (*Frames, error) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f := &Frames{r: r}
|
||||
pool(func() { err = r.initGPU() })
|
||||
if err != nil {
|
||||
r.Release()
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Name returns the name of the GPU, as "Apple M2".
|
||||
func (f *Frames) Name() (name string) {
|
||||
pool(func() { name = goString(send(f.r.device, "name")) })
|
||||
return name
|
||||
}
|
||||
|
||||
// Draw draws s into the Frames' own texture, after waiting for the frame
|
||||
// before, whose pixels the caller read. Read copies its pixels once Wait
|
||||
// returned.
|
||||
func (f *Frames) Draw(s *scene.Scene) (err error) {
|
||||
pool(func() {
|
||||
if err = f.wait(); err != nil {
|
||||
return
|
||||
}
|
||||
if f.tex == 0 || f.w != s.Width || f.h != s.Height {
|
||||
release(&f.tex)
|
||||
f.r.cur = &f.r.formats[0]
|
||||
if f.tex = f.r.newTexture(s.Width, s.Height, pixelFormatBGRA8Unorm, usageRenderTarget|usageShaderRead, nil, 0); f.tex == 0 {
|
||||
err = errors.New("metal: cannot create a target")
|
||||
return
|
||||
}
|
||||
f.w, f.h = s.Width, s.Height
|
||||
}
|
||||
err = f.commit(s, f.tex, true)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// DrawSurface draws s into surface, an IOSurfaceRef of s's size in BGRA,
|
||||
// as a CVPixelBuffer's from a pool, after waiting for the frame before.
|
||||
// The surface holds the frame once Wait returned.
|
||||
func (f *Frames) DrawSurface(s *scene.Scene, surface uintptr) (err error) {
|
||||
pool(func() {
|
||||
if err = f.wait(); err != nil {
|
||||
return
|
||||
}
|
||||
desc := send(class("MTLTextureDescriptor"), "texture2DDescriptorWithPixelFormat:width:height:mipmapped:",
|
||||
pixelFormatBGRA8Unorm, uintptr(s.Width), uintptr(s.Height), 0)
|
||||
send(desc, "setUsage:", usageRenderTarget|usageShaderRead)
|
||||
tex := send(f.r.device, "newTextureWithDescriptor:iosurface:plane:", desc, surface, 0)
|
||||
if tex == 0 {
|
||||
err = errors.New("metal: cannot draw into the IOSurface")
|
||||
return
|
||||
}
|
||||
f.surface = tex
|
||||
f.r.cur = &f.r.formats[0]
|
||||
if err = f.commit(s, tex, false); err != nil {
|
||||
release(&f.surface)
|
||||
}
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// commit encodes s into target and commits it, keeping its command
|
||||
// buffer for Wait; read synchronizes a managed texture for the CPU.
|
||||
func (f *Frames) commit(s *scene.Scene, target id, read bool) error {
|
||||
cb, err := f.r.encode(s, target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if read {
|
||||
blit := send(cb, "blitCommandEncoder")
|
||||
send(blit, "synchronizeResource:", target)
|
||||
send(blit, "endEncoding")
|
||||
}
|
||||
send(cb, "commit")
|
||||
f.r.track(cb)
|
||||
f.last = send(cb, "retain")
|
||||
f.r.sweepIfDue()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Wait waits for the GPU to finish the last frame drawn.
|
||||
func (f *Frames) Wait() (err error) {
|
||||
pool(func() { err = f.wait() })
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *Frames) wait() error {
|
||||
if f.last == 0 {
|
||||
return nil
|
||||
}
|
||||
send(f.last, "waitUntilCompleted")
|
||||
var err error
|
||||
if int(send(f.last, "status")) == statusError {
|
||||
err = fmt.Errorf("metal: the frame failed: %s", describe(send(f.last, "error")))
|
||||
}
|
||||
release(&f.last)
|
||||
release(&f.surface)
|
||||
return err
|
||||
}
|
||||
|
||||
// Read copies the pixels of the frame Draw drew last into dst, once Wait
|
||||
// returned: premultiplied BGRA rows from the top, 4×width bytes each.
|
||||
func (f *Frames) Read(dst []byte) error {
|
||||
if f.tex == 0 || len(dst) < f.w*f.h*4 {
|
||||
return errors.New("metal: no frame to read, or too small a buffer")
|
||||
}
|
||||
pool(func() {
|
||||
msgGetBytes(f.tex, sel("getBytes:bytesPerRow:fromRegion:mipmapLevel:"), unsafe.Pointer(&dst[0]), uint(f.w*4),
|
||||
mtlRegion{W: uint(f.w), H: uint(f.h), D: 1}, 0)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release waits for the GPU, and frees the texture and the renderer.
|
||||
func (f *Frames) Release() {
|
||||
pool(func() {
|
||||
f.wait()
|
||||
release(&f.surface)
|
||||
release(&f.tex)
|
||||
})
|
||||
f.r.Release()
|
||||
}
|
||||
|
||||
// goString returns the text of an NSString.
|
||||
func goString(str id) string {
|
||||
if str == 0 {
|
||||
return ""
|
||||
}
|
||||
p := send(str, "UTF8String")
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
n := 0
|
||||
for *(*byte)(ptr(p + uintptr(n))) != 0 {
|
||||
n++
|
||||
}
|
||||
return string(unsafe.Slice((*byte)(ptr(p)), n))
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
//go:build ignore
|
||||
|
||||
// Gen compiles shader.metal into a Metal library with Xcode's metal tools
|
||||
// and writes shaderlib.go, so that renderers start without compiling the
|
||||
// shader, which takes over 100 ms until Metal has cached it. It runs on
|
||||
// macOS with Xcode: go generate ./internal/gpu/metal
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
)
|
||||
|
||||
func main() {
|
||||
src, err := os.ReadFile("shader.metal")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
sum := gpu.SourceSum(string(src))
|
||||
compile := func(sdk, min string) []byte {
|
||||
code, err := metal.CompileLibraryFor(string(src), sdk, min)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return code
|
||||
}
|
||||
// macOS 12 and iOS 17 are the oldest MyGo runs on.
|
||||
write("shaderlib.go", "darwin && !ios", sum, map[string][]byte{"shaderLibrary": compile("macosx", "-mmacosx-version-min=12.0")})
|
||||
// A library loads only on its platform: iOS devices' and the
|
||||
// simulator's differ, and the app takes its own (shaderlib_ios.go).
|
||||
write("shaderlib_ios_gen.go", "ios", sum, map[string][]byte{
|
||||
"shaderLibraryDevice": compile("iphoneos", "-mios-version-min=17.0"),
|
||||
"shaderLibrarySimulator": compile("iphonesimulator", "-mios-simulator-version-min=17.0"),
|
||||
})
|
||||
}
|
||||
|
||||
func write(file, constraint, sum string, libs map[string][]byte) {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "// Code generated by gen.go from shader.metal; DO NOT EDIT.\n\n//go:build %s\n\npackage metal\n\n", constraint)
|
||||
fmt.Fprintf(&b, "// shaderLibrarySum is the SHA-256 of the shader.metal the libraries were\n// compiled from.\nconst shaderLibrarySum = %q\n\n", sum)
|
||||
for _, name := range []string{"shaderLibrary", "shaderLibraryDevice", "shaderLibrarySimulator"} {
|
||||
if code, ok := libs[name]; ok {
|
||||
b.WriteString(gpu.GoBytes(name, code))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
}
|
||||
out, err := format.Source(b.Bytes())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, out, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestGlyphProbeJoinedEdges checks that batches joining small rounded
|
||||
// fills, with ordinary and continuous corners, and glyphs at fractional
|
||||
// positions draw the pixels of the general shader, and of the classes'
|
||||
// batches kept apart, keeping the atlas unchanged across each comparison.
|
||||
// A Radeon Pro 560 dropped glyph pixels there until sampleLocal sampled
|
||||
// level 0 explicitly (#649).
|
||||
func TestGlyphProbeJoinedEdges(t *testing.T) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
needSpecialized(t, r)
|
||||
atlas := scene.NewAtlas(1, 128, 128)
|
||||
mask := make([]byte, 32*32)
|
||||
for y := range 32 {
|
||||
for x := range 32 {
|
||||
d := math.Hypot(float64(x)-15.5, float64(y)-15.5)
|
||||
coverage := math.Min(1, math.Max(0, 1.5-math.Abs(d-12)))
|
||||
mask[y*32+x] = byte(255 * coverage)
|
||||
}
|
||||
}
|
||||
u, v, _ := atlas.Alloc(32, 32)
|
||||
atlas.Put(u, v, 32, 32, mask, 32)
|
||||
positions := []float32{0, 0.2, 0.4, 0.5, 0.6, 0.8}
|
||||
cases, joinedFrames, largest := 0, 0, 0
|
||||
for _, dx := range positions {
|
||||
for _, dy := range positions {
|
||||
for _, continuous := range []bool{false, true} {
|
||||
s := &scene.Scene{Width: 960, Height: 640, Scale: 2,
|
||||
Clear: scene.Color{R: 41, G: 42, B: 45, A: 255}, MaskAtlas: atlas}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip,
|
||||
Rect: scene.Rect{X: 2 + dx, Y: 2 + dy, W: 950, H: 630}, Radii: scene.Uniform(8)})
|
||||
for row := range 8 {
|
||||
for col := range 12 {
|
||||
x, y := 10+float32(col)*77+dx, 10+float32(row)*76+dy
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill,
|
||||
Rect: scene.Rect{X: x, Y: y, W: 52, H: 48}, Radii: scene.Uniform(8),
|
||||
Continuous: continuous, Color: scene.Color{R: 47, G: 50, B: 55, A: 255}})
|
||||
start := int32(len(s.Glyphs))
|
||||
s.Glyphs = append(s.Glyphs, scene.Glyph{X: x + 10, Y: y + 8, W: 32, H: 32,
|
||||
U: uint16(u), V: uint16(v), UW: 32, VH: 32,
|
||||
Color: scene.Color{R: 154, G: 160, B: 166, A: 255}})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpGlyphs, Start: start, End: start + 1})
|
||||
}
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
r.b.NoClasses, r.b.NoJoin = true, false
|
||||
want := renderRaw(t, r, s, false)
|
||||
for _, apart := range []bool{false, true} {
|
||||
r.b.NoClasses, r.b.NoJoin = false, apart
|
||||
got := renderRaw(t, r, s, false)
|
||||
for _, b := range r.b.Batches {
|
||||
if b.Joined != 0 {
|
||||
joinedFrames++
|
||||
break
|
||||
}
|
||||
}
|
||||
different, maximum := 0, 0
|
||||
for i := range got {
|
||||
delta := int(got[i]) - int(want[i])
|
||||
if delta < 0 {
|
||||
delta = -delta
|
||||
}
|
||||
if delta != 0 {
|
||||
different++
|
||||
maximum = max(maximum, delta)
|
||||
}
|
||||
}
|
||||
largest = max(largest, maximum)
|
||||
if maximum > 2 {
|
||||
t.Errorf("dx=%g dy=%g continuous=%t apart=%t: %d bytes differ; largest channel delta=%d", dx, dy, continuous, apart, different, maximum)
|
||||
}
|
||||
}
|
||||
cases++
|
||||
}
|
||||
}
|
||||
}
|
||||
if joinedFrames == 0 {
|
||||
t.Fatal("no mixed batch was exercised")
|
||||
}
|
||||
t.Logf("%d scenes, %d frames containing joined batches, largest channel delta=%d", cases, joinedFrames, largest)
|
||||
}
|
||||
+2203
File diff suppressed because it is too large.
Load diff
+1426
File diff suppressed because it is too large.
Load diff
+110
@@ -0,0 +1,110 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// RenderOffscreen draws s with a renderer of its own into a texture,
|
||||
// without a layer, and returns its premultiplied BGRA rows: for tests, as
|
||||
// packages drawing effects have.
|
||||
func RenderOffscreen(s *scene.Scene) ([]byte, error) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer r.Release()
|
||||
return r.renderOffscreen(s)
|
||||
}
|
||||
|
||||
// Offscreen draws frames with a renderer of its own into a texture,
|
||||
// without a layer, waiting for each and timing it on the GPU: for
|
||||
// benchmarks, as those of package ui drawing its frames.
|
||||
type Offscreen struct {
|
||||
r *Renderer
|
||||
tex id
|
||||
w, h int
|
||||
// encoded is how long encoding the last frame took on the CPU.
|
||||
encoded time.Duration
|
||||
}
|
||||
|
||||
var msgDouble func(obj id, sel uintptr) float64
|
||||
|
||||
// NewOffscreen returns an Offscreen drawing frames of w×h pixels.
|
||||
func NewOffscreen(w, h int) (*Offscreen, error) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if msgDouble == nil {
|
||||
purego.RegisterFunc(&msgDouble, msgSend)
|
||||
}
|
||||
o := &Offscreen{r: r}
|
||||
pool(func() { err = o.target(w, h) })
|
||||
if err != nil {
|
||||
o.Release()
|
||||
return nil, err
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// target makes the texture drawn into w×h pixels.
|
||||
func (o *Offscreen) target(w, h int) error {
|
||||
if o.tex != 0 && o.w == w && o.h == h {
|
||||
return nil
|
||||
}
|
||||
release(&o.tex)
|
||||
o.r.cur = &o.r.formats[0]
|
||||
o.tex = o.r.newTexture(w, h, pixelFormatBGRA8Unorm, usageRenderTarget|usageShaderRead, nil, 0)
|
||||
if o.tex == 0 {
|
||||
return errors.New("metal: cannot create a target")
|
||||
}
|
||||
o.w, o.h = w, h
|
||||
return nil
|
||||
}
|
||||
|
||||
// Render draws s, a texture of its size taking the place of one of
|
||||
// another, waits for the GPU to finish it, and returns the time the GPU
|
||||
// spent on it, by its command buffer's timestamps.
|
||||
func (o *Offscreen) Render(s *scene.Scene) (gpu time.Duration, err error) {
|
||||
pool(func() {
|
||||
r := o.r
|
||||
r.waitLast()
|
||||
if err = o.target(s.Width, s.Height); err != nil {
|
||||
return
|
||||
}
|
||||
var cb id
|
||||
start := time.Now()
|
||||
if cb, err = r.encode(s, o.tex); err != nil {
|
||||
return
|
||||
}
|
||||
o.encoded = time.Since(start)
|
||||
send(cb, "commit")
|
||||
send(cb, "waitUntilCompleted")
|
||||
if int(send(cb, "status")) == statusError {
|
||||
err = fmt.Errorf("metal: the frame failed: %s", describe(send(cb, "error")))
|
||||
return
|
||||
}
|
||||
secs := msgDouble(cb, uintptr(sel("GPUEndTime"))) - msgDouble(cb, uintptr(sel("GPUStartTime")))
|
||||
gpu = time.Duration(secs * float64(time.Second))
|
||||
})
|
||||
return gpu, err
|
||||
}
|
||||
|
||||
// Encoded returns how long the CPU took to encode the last frame Render
|
||||
// drew: building its instances (gpu.Builder), uploading what changed in
|
||||
// its atlases, and encoding its passes, before committing them.
|
||||
func (o *Offscreen) Encoded() time.Duration { return o.encoded }
|
||||
|
||||
// Release frees the texture and the renderer.
|
||||
func (o *Offscreen) Release() {
|
||||
pool(func() { release(&o.tex) })
|
||||
o.r.Release()
|
||||
}
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// The pipelines of the classes of batches (gpu.Class) are specialized from the
|
||||
// shader at creation, which costs a compile of up to 120 ms. A frame never
|
||||
// waits for one: pipeFor returns the general pipeline, which draws the same
|
||||
// pixels, until a worker goroutine has made the specialized one, and a cache
|
||||
// shared by every renderer of a device keeps them, so that a second window
|
||||
// finds them made. GPUs older than Metal's Mac2 family (canSpecialize) have
|
||||
// none: every batch draws with the general pipeline, and nothing compiles
|
||||
// behind the frames.
|
||||
|
||||
// pipeKey names a pipeline: the pixel format of the target, the classes of
|
||||
// its batches (gpu.Batch.Classes: one, or those of joined batches) and
|
||||
// whether its instances have continuous corners, and how it blends.
|
||||
type pipeKey struct {
|
||||
format uint
|
||||
classes uint32
|
||||
cont bool
|
||||
mode blendMode
|
||||
}
|
||||
|
||||
// deviceKey is a pipeline of a device in the cache of all renderers.
|
||||
type deviceKey struct {
|
||||
device id
|
||||
pipeKey
|
||||
}
|
||||
|
||||
// pipeCache holds the specialized pipelines of each device, never released:
|
||||
// they are small, and a device lives as long as the process does.
|
||||
var pipeCache = struct {
|
||||
sync.Mutex
|
||||
m map[deviceKey]id
|
||||
}{m: map[deviceKey]id{}}
|
||||
|
||||
// syncPipelines makes pipeFor build a missing pipeline at once, for tests that
|
||||
// compare the specialized pipelines with the general ones and need them made.
|
||||
var syncPipelines bool
|
||||
|
||||
// pipeState is a renderer's pipelines of the classes and the worker making them.
|
||||
type pipeState struct {
|
||||
mu sync.Mutex
|
||||
ready map[pipeKey]id
|
||||
queued map[pipeKey]bool
|
||||
work chan pipeKey
|
||||
wg sync.WaitGroup
|
||||
closed bool
|
||||
sync bool // build in pipeFor, see syncPipelines
|
||||
warmed [2]bool // by format
|
||||
owned []id // pipelines of renderers that do not use the cache
|
||||
nbuilt int // pipelines the worker made, for tests
|
||||
nfailed int
|
||||
|
||||
beforeBuild func() // test hook, set before the first frame starts the worker
|
||||
// fallbacks counts the batches of the frame being encoded that drew with
|
||||
// the general pipeline because the specialized one was not made yet
|
||||
// (touched by the encoding goroutine only).
|
||||
fallbacks int
|
||||
}
|
||||
|
||||
// warmSet returns the pipelines that frames most likely draw with in a target of
|
||||
// format: every class with and without continuous corners drawn over what is
|
||||
// there, and the plain and other fills drawn as opaque cores (which float16
|
||||
// targets do not use, and which shadows do not need), and the classes that
|
||||
// small batches join most (gpu.Batch.Joined): shadows with the fills casting
|
||||
// them, and fills with their labels. A device that does not specialize warms
|
||||
// none.
|
||||
func (r *Renderer) warmSet(format uint) (keys []pipeKey) {
|
||||
for _, cl := range []uint32{1 << gpu.ClassPlain, 1 << gpu.ClassGlyph, 1 << gpu.ClassImage, 1 << gpu.ClassFill, 1 << gpu.ClassShadow, 1 << gpu.ClassSubpixel,
|
||||
1<<gpu.ClassShadow | 1<<gpu.ClassPlain, 1<<gpu.ClassPlain | 1<<gpu.ClassGlyph} {
|
||||
for _, cont := range []bool{false, true} {
|
||||
if r.specializable(format, cl, blendOver) {
|
||||
keys = append(keys, pipeKey{format, cl, cont, blendOver})
|
||||
}
|
||||
if (cl == 1<<gpu.ClassPlain || cl == 1<<gpu.ClassFill) && r.specializable(format, cl, blendNone) {
|
||||
keys = append(keys, pipeKey{format, cl, cont, blendNone})
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// specializable reports whether batches of the classes cl (gpu.Batch.Classes)
|
||||
// blended as mode draw with a specialized pipeline in targets of format.
|
||||
func (r *Renderer) specializable(format uint, cl uint32, mode blendMode) bool {
|
||||
if !r.canSpecialize || cl&(1<<gpu.ClassGeneral) != 0 || cl >= 1<<gpu.NumClasses {
|
||||
return false
|
||||
}
|
||||
if format == pixelFormatRGBA16Float {
|
||||
// A shadow's blur (erf, exp) compiles to results one unit in the last
|
||||
// place of a half apart in float16 targets, at a pixel in a scene, so
|
||||
// shadows keep the general function there; opaque cores are blended
|
||||
// there (see makePipelines).
|
||||
return cl&(1<<gpu.ClassShadow) == 0 && mode != blendNone
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// startPipelines starts the worker that makes pipelines, if it is not running,
|
||||
// and has it warm the likely ones of f's format.
|
||||
func (r *Renderer) startPipelines(f *formatState) {
|
||||
p := &r.pipes
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.closed {
|
||||
return
|
||||
}
|
||||
if p.work == nil {
|
||||
p.ready, p.queued = map[pipeKey]id{}, map[pipeKey]bool{}
|
||||
p.work = make(chan pipeKey, 128)
|
||||
p.sync = syncPipelines
|
||||
p.wg.Add(1)
|
||||
go r.pipelineWorker()
|
||||
}
|
||||
i := 0
|
||||
if f.format == pixelFormatRGBA16Float {
|
||||
i = 1
|
||||
}
|
||||
if p.warmed[i] || p.sync {
|
||||
return
|
||||
}
|
||||
p.warmed[i] = true
|
||||
for _, k := range r.warmSet(f.format) {
|
||||
r.enqueueLocked(k)
|
||||
}
|
||||
}
|
||||
|
||||
// enqueueLocked asks the worker for the pipeline k, unless it is made or asked
|
||||
// for. It never blocks: a full queue drops the request, which the next frame
|
||||
// makes again.
|
||||
func (r *Renderer) enqueueLocked(k pipeKey) {
|
||||
p := &r.pipes
|
||||
if p.closed || p.queued[k] || p.ready[k] != 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case p.work <- k:
|
||||
p.queued[k] = true
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// pipelineWorker makes the pipelines asked for, until the renderer is released.
|
||||
func (r *Renderer) pipelineWorker() {
|
||||
defer r.pipes.wg.Done()
|
||||
for k := range r.pipes.work {
|
||||
r.pipes.mu.Lock()
|
||||
closed := r.pipes.closed
|
||||
r.pipes.mu.Unlock()
|
||||
if closed {
|
||||
return // Release waits for the active compile, not the warmup backlog.
|
||||
}
|
||||
pool(func() { r.buildPipeline(k) })
|
||||
}
|
||||
}
|
||||
|
||||
// buildPipeline makes the pipeline k, or takes it from the cache of the device,
|
||||
// and publishes it.
|
||||
func (r *Renderer) buildPipeline(k pipeKey) {
|
||||
p := &r.pipes
|
||||
if p.beforeBuild != nil {
|
||||
p.beforeBuild()
|
||||
}
|
||||
dk := deviceKey{r.device, k}
|
||||
cacheable := r.source == ""
|
||||
var pipe id
|
||||
if cacheable {
|
||||
pipeCache.Lock()
|
||||
pipe = pipeCache.m[dk]
|
||||
pipeCache.Unlock()
|
||||
}
|
||||
var err error
|
||||
if pipe == 0 {
|
||||
pipe, err = r.newClassPipeline(r.lib, "ps", k.format, k.mode, k.classes, k.cont)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "%v: drawing with the general shader\n", err)
|
||||
} else if cacheable {
|
||||
pipeCache.Lock()
|
||||
if cached := pipeCache.m[dk]; cached != 0 {
|
||||
// Another window finished the same pipeline while this one compiled.
|
||||
release(&pipe)
|
||||
pipe = cached
|
||||
} else {
|
||||
pipeCache.m[dk] = pipe
|
||||
}
|
||||
pipeCache.Unlock()
|
||||
}
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
delete(p.queued, k)
|
||||
if err != nil {
|
||||
p.nfailed++
|
||||
p.ready[k] = ^id(0) // tried: draws with the general pipeline
|
||||
return
|
||||
}
|
||||
if !cacheable {
|
||||
// Owned by this renderer: released with it.
|
||||
p.owned = append(p.owned, pipe)
|
||||
}
|
||||
p.nbuilt++
|
||||
p.ready[k] = pipe
|
||||
}
|
||||
|
||||
// pipeFor returns the pipeline of f that draws batches of the classes cl
|
||||
// (gpu.Batch.Classes) blended as mode says. It never waits for a compile: until the specialized pipeline is
|
||||
// made, by the worker or by another renderer of the device, it is the general one,
|
||||
// which draws the same pixels.
|
||||
func (r *Renderer) pipeFor(f *formatState, cl uint32, continuous bool, mode blendMode) id {
|
||||
if mode == blendNone && r.coresBlend(f.format) {
|
||||
mode = blendOver // see makePipelines
|
||||
}
|
||||
general := f.pipeline
|
||||
switch mode {
|
||||
case blendHole:
|
||||
general = f.holePipe
|
||||
case blendNone:
|
||||
general = f.opaquePipe
|
||||
}
|
||||
if !r.specializable(f.format, cl, mode) {
|
||||
return general
|
||||
}
|
||||
k := pipeKey{f.format, cl, continuous, mode}
|
||||
p := &r.pipes
|
||||
p.mu.Lock()
|
||||
pipe, known := p.ready[k]
|
||||
closed := p.closed
|
||||
p.mu.Unlock()
|
||||
if known {
|
||||
if pipe == ^id(0) {
|
||||
return general
|
||||
}
|
||||
return pipe
|
||||
}
|
||||
if closed || r.lib == 0 {
|
||||
return general
|
||||
}
|
||||
p.fallbacks++ // until a pipeline is found made, below, or made in sync mode
|
||||
if p.sync {
|
||||
r.buildPipeline(k)
|
||||
p.mu.Lock()
|
||||
pipe = p.ready[k]
|
||||
p.mu.Unlock()
|
||||
p.fallbacks--
|
||||
if pipe == 0 || pipe == ^id(0) {
|
||||
return general
|
||||
}
|
||||
return pipe
|
||||
}
|
||||
// Another renderer of the device may have made it.
|
||||
pipeCache.Lock()
|
||||
pipe = pipeCache.m[deviceKey{r.device, k}]
|
||||
pipeCache.Unlock()
|
||||
p.mu.Lock()
|
||||
if pipe != 0 && r.source == "" {
|
||||
p.ready[k] = pipe
|
||||
} else {
|
||||
r.enqueueLocked(k)
|
||||
pipe = 0
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if pipe != 0 {
|
||||
p.fallbacks--
|
||||
}
|
||||
return or(pipe, general)
|
||||
}
|
||||
|
||||
// stopPipelines ends the worker and waits for it, before the library it uses
|
||||
// is released.
|
||||
func (r *Renderer) stopPipelines() {
|
||||
p := &r.pipes
|
||||
p.mu.Lock()
|
||||
if p.work != nil && !p.closed {
|
||||
close(p.work)
|
||||
}
|
||||
p.closed = true
|
||||
p.mu.Unlock()
|
||||
p.wg.Wait()
|
||||
for i := range p.owned {
|
||||
release(&p.owned[i])
|
||||
}
|
||||
p.owned = nil
|
||||
}
|
||||
|
||||
// pipelineCounts returns how many specialized pipelines the worker made and how
|
||||
// many failed to build, for tests.
|
||||
func (r *Renderer) pipelineCounts() (built, failed int) {
|
||||
r.pipes.mu.Lock()
|
||||
defer r.pipes.mu.Unlock()
|
||||
return r.pipes.nbuilt, r.pipes.nfailed
|
||||
}
|
||||
|
||||
// usedSpecialized reports whether the pipeline k is made, and is a specialized
|
||||
// one, not the general pipeline a failed build falls back to, for tests.
|
||||
func (r *Renderer) usedSpecialized(k pipeKey) bool {
|
||||
r.pipes.mu.Lock()
|
||||
defer r.pipes.mu.Unlock()
|
||||
p := r.pipes.ready[k]
|
||||
return p != 0 && p != ^id(0)
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// PrecompileShader starts making what a shader of package ui/shader draws
|
||||
// with, whose library's source is src (ShaderSource), on a goroutine of
|
||||
// its own, with the system's default GPU: its library, which Metal
|
||||
// compiles from the source in about 0.1 s, and its pipeline for windows
|
||||
// of 8-bit color, about as long again. Renderers on that GPU then draw
|
||||
// with them, waiting for what is left, rather than make them on the
|
||||
// shader's first draw. Metal keeps both on disk for the next launches.
|
||||
// Package ui/shader calls it as it compiles a shader.
|
||||
func PrecompileShader(src string) {
|
||||
shaders.once.Do(func() {
|
||||
shaders.byKey = map[string]*shaderEntry{}
|
||||
shaders.sem = make(chan struct{}, max(1, runtime.NumCPU()-1))
|
||||
if load() == nil {
|
||||
shaders.device = createDevice() // owned, for the program's life
|
||||
}
|
||||
})
|
||||
if shaders.device == 0 {
|
||||
return
|
||||
}
|
||||
shaders.mu.Lock()
|
||||
if shaders.byKey[src] != nil {
|
||||
shaders.mu.Unlock()
|
||||
return
|
||||
}
|
||||
e := &shaderEntry{done: make(chan struct{})}
|
||||
shaders.byKey[src] = e
|
||||
shaders.mu.Unlock()
|
||||
go func() {
|
||||
shaders.sem <- struct{}{}
|
||||
defer func() { <-shaders.sem }()
|
||||
defer close(e.done)
|
||||
pool(func() { e.make(src) })
|
||||
}()
|
||||
}
|
||||
|
||||
// shaders holds what PrecompileShader made, by source.
|
||||
var shaders struct {
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
byKey map[string]*shaderEntry
|
||||
sem chan struct{} // the goroutines making them at once
|
||||
device id
|
||||
}
|
||||
|
||||
// shaderEntry is what PrecompileShader made of a source: its library and
|
||||
// pipeline (owned), or why not, once done is closed.
|
||||
type shaderEntry struct {
|
||||
done chan struct{}
|
||||
lib, pipe id
|
||||
err error
|
||||
}
|
||||
|
||||
// precompiledFormat is the format of the pipeline PrecompileShader makes:
|
||||
// that of windows that draw no wide gamut.
|
||||
const precompiledFormat = pixelFormatBGRA8Unorm
|
||||
|
||||
func (e *shaderEntry) make(src string) {
|
||||
var errObj id
|
||||
e.lib = send(shaders.device, "newLibraryWithSource:options:error:", nsString(src), 0, uintptr(unsafe.Pointer(&errObj)))
|
||||
if e.lib == 0 {
|
||||
e.err = fmt.Errorf("metal: cannot compile the shader: %s", describe(errObj))
|
||||
return
|
||||
}
|
||||
r := &Renderer{device: shaders.device}
|
||||
e.pipe, _ = r.newPipeline(e.lib, "shader_ps", precompiledFormat, blendOver)
|
||||
}
|
||||
|
||||
// sharedShader returns what PrecompileShader made of src for a renderer
|
||||
// on device drawing format, waiting for it, retained: its library, and its
|
||||
// pipeline when made for format (0 otherwise). ok is false when it made
|
||||
// nothing for src on device.
|
||||
func sharedShader(device id, src string, format uint) (lib, pipe id, ok bool) {
|
||||
if device == 0 || device != shaders.device {
|
||||
return 0, 0, false
|
||||
}
|
||||
shaders.mu.Lock()
|
||||
e := shaders.byKey[src]
|
||||
shaders.mu.Unlock()
|
||||
if e == nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
<-e.done
|
||||
if e.lib == 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
lib = send(e.lib, "retain")
|
||||
if format == precompiledFormat && e.pipe != 0 {
|
||||
pipe = send(e.pipe, "retain")
|
||||
}
|
||||
return lib, pipe, true
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"image"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// A presenter fetches the layer's next drawable on a thread of its own,
|
||||
// after each frame presented as soon as drawn, so that the main thread
|
||||
// never waits for the display. nextDrawable blocks while the layer's
|
||||
// drawables are all in use, as the display holds them until its next
|
||||
// refreshes: a frame following another would wait most of a refresh,
|
||||
// with the main thread able to do nothing else. Instead, a frame that
|
||||
// comes while the presenter fetches is built and waits (pendingFrame),
|
||||
// and the main thread draws it into the drawable once the presenter has
|
||||
// it; frames paced by the display wait for that (Ready).
|
||||
//
|
||||
// The main thread waits for a fetch in flight before changing the layer
|
||||
// (its drawables' size or format, presenting with the transaction,
|
||||
// trimming), so a fetch never races those, and frames presented with the
|
||||
// transaction take their drawable themselves, as a live resize's must.
|
||||
// Waiting on a channel, the thread costs nothing while frames stop.
|
||||
type presenter struct {
|
||||
layer id
|
||||
fetch chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
done sync.Cond
|
||||
// drawable is the one fetched, retained, until a frame takes it;
|
||||
// fetching tells that the thread is fetching one, and wake what it
|
||||
// calls once it has (Ready).
|
||||
drawable id
|
||||
fetching bool
|
||||
wake func()
|
||||
started bool
|
||||
}
|
||||
|
||||
// qosUserInteractive is QOS_CLASS_USER_INTERACTIVE, the main thread's.
|
||||
const qosUserInteractive = 0x21
|
||||
|
||||
var (
|
||||
qosOnce sync.Once
|
||||
setQoS func(class uint32, priority int32) int32
|
||||
// nextDrawable returns the layer's next drawable, autoreleased; tests
|
||||
// replace it.
|
||||
nextDrawable = func(layer id) id { return send(layer, "nextDrawable") }
|
||||
)
|
||||
|
||||
// start has the thread fetch the next drawable, unless it is or has one.
|
||||
func (p *presenter) start(layer id) {
|
||||
p.mu.Lock()
|
||||
if p.fetching || p.drawable != 0 {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
p.fetching = true
|
||||
if !p.started {
|
||||
p.started = true
|
||||
p.layer = layer
|
||||
p.done.L = &p.mu
|
||||
p.fetch = make(chan struct{}, 1)
|
||||
go p.run()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
p.fetch <- struct{}{}
|
||||
}
|
||||
|
||||
func (p *presenter) run() {
|
||||
// The autorelease pools belong to the thread.
|
||||
runtime.LockOSThread()
|
||||
qosOnce.Do(func() {
|
||||
if h, err := purego.Dlopen("/usr/lib/libSystem.B.dylib", purego.RTLD_GLOBAL|purego.RTLD_NOW); err == nil {
|
||||
purego.RegisterLibFunc(&setQoS, h, "pthread_set_qos_class_self_np")
|
||||
}
|
||||
})
|
||||
if setQoS != nil {
|
||||
setQoS(qosUserInteractive, 0)
|
||||
}
|
||||
for range p.fetch {
|
||||
pool, _, _ := purego.SyscallN(poolPush)
|
||||
d := nextDrawable(p.layer)
|
||||
if d != 0 {
|
||||
send(d, "retain")
|
||||
}
|
||||
purego.SyscallN(poolPop, pool)
|
||||
p.mu.Lock()
|
||||
p.drawable, p.fetching = d, false
|
||||
wake := p.wake
|
||||
p.wake = nil
|
||||
p.done.Broadcast()
|
||||
p.mu.Unlock()
|
||||
if wake != nil {
|
||||
wake()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ready reports whether a frame can take a drawable at once, as none is
|
||||
// being fetched; otherwise wake runs once one is, on the presenter's
|
||||
// thread.
|
||||
func (p *presenter) ready(wake func()) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if !p.fetching {
|
||||
return true
|
||||
}
|
||||
p.wake = wake
|
||||
return false
|
||||
}
|
||||
|
||||
// wait waits for a fetch in flight.
|
||||
func (p *presenter) wait() {
|
||||
p.mu.Lock()
|
||||
for p.fetching {
|
||||
p.done.Wait()
|
||||
}
|
||||
p.wake = nil
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// take returns the drawable fetched, retained, or 0, once no fetch is in
|
||||
// flight.
|
||||
func (p *presenter) take() id {
|
||||
p.wait()
|
||||
p.mu.Lock()
|
||||
d := p.drawable
|
||||
p.drawable = 0
|
||||
p.mu.Unlock()
|
||||
return d
|
||||
}
|
||||
|
||||
// drain lets go of the drawable fetched, once no fetch is in flight.
|
||||
func (p *presenter) drain() {
|
||||
if d := p.take(); d != 0 {
|
||||
send(d, "release")
|
||||
}
|
||||
}
|
||||
|
||||
// stop drains the presenter and ends its thread.
|
||||
func (p *presenter) stop() {
|
||||
p.drain()
|
||||
p.mu.Lock()
|
||||
if p.started {
|
||||
close(p.fetch)
|
||||
p.started = false
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// A pendingFrame is a frame built while its drawable was being fetched,
|
||||
// to draw into it once the presenter has it: its command buffer, retained,
|
||||
// holding what the frame drew before the drawable (canvases, blurred
|
||||
// images), and what drawing the rest takes of its scene, which the
|
||||
// content may build anew meanwhile (a capture).
|
||||
type pendingFrame struct {
|
||||
cb id
|
||||
// size and clear are the scene's, and whole tells that its effects
|
||||
// read their backdrops, which drawing in part would add to the area
|
||||
// drawn: it is drawn whole.
|
||||
size scene.Scene
|
||||
whole bool
|
||||
}
|
||||
|
||||
// SetPost gives the renderer post, which runs a function on the main
|
||||
// thread from any goroutine: a frame following another builds while its
|
||||
// drawable is being fetched, and draws once the presenter has it, through
|
||||
// post. Without it, frames wait for their drawable.
|
||||
func (r *Renderer) SetPost(post func(func())) {
|
||||
r.post = post
|
||||
finish := func() {
|
||||
pool(func() {
|
||||
// A frame not paced may have drawn the frame pending this was
|
||||
// posted for, and another may be pending, whose drawable is
|
||||
// being fetched: its fetch posts again once done, rather than
|
||||
// the main thread waiting for it.
|
||||
if r.pending.cb == 0 || !r.pre.ready(r.fetched) {
|
||||
return
|
||||
}
|
||||
if err := r.finishPending(true); err != nil {
|
||||
r.err = err
|
||||
r.wakeContent() // the next frame finds the error
|
||||
}
|
||||
})
|
||||
}
|
||||
r.fetched = func() { post(finish) }
|
||||
}
|
||||
|
||||
// layerChanges reports whether drawing s at scale changes the layer, its
|
||||
// drawables' size or format.
|
||||
func (r *Renderer) layerChanges(s *scene.Scene, scale float64) bool {
|
||||
return r.layerWide != r.wide || s.Width != r.w || s.Height != r.h || scale != r.scale || r.trimmed ||
|
||||
msgRect(r.superlayer, sel("bounds")) != r.bounds
|
||||
}
|
||||
|
||||
// stash builds the frame s, which changed damage since the last one, to
|
||||
// draw once its drawable comes (finishPending).
|
||||
func (r *Renderer) stash(s *scene.Scene, damage []image.Rectangle, known bool) error {
|
||||
cb, _, err := r.prepare(s)
|
||||
if err != nil {
|
||||
r.forgetFrames()
|
||||
return err
|
||||
}
|
||||
damage = r.pipelineDamage(damage, known)
|
||||
r.ages.Add(damage, !known)
|
||||
r.pending = pendingFrame{cb: send(cb, "retain"), whole: len(s.Effects) > 0}
|
||||
r.pending.size.Width, r.pending.size.Height, r.pending.size.Clear = s.Width, s.Height, s.Clear
|
||||
r.diff.Remember(s)
|
||||
r.pipelines.Remember()
|
||||
return nil
|
||||
}
|
||||
|
||||
// finishPending draws the frame pending into its drawable, waiting for it
|
||||
// when called before the presenter has it, and presents it, then has the
|
||||
// presenter fetch the next frame's drawable if prefetch.
|
||||
func (r *Renderer) finishPending(prefetch bool) error {
|
||||
p := r.pending
|
||||
r.pending = pendingFrame{}
|
||||
defer r.wakeContent()
|
||||
drawable := r.prefetched()
|
||||
if drawable == 0 {
|
||||
drawable = send(r.layer, "nextDrawable")
|
||||
}
|
||||
if drawable == 0 {
|
||||
// None came within a second: the frame is skipped, what it drew
|
||||
// before its drawable committed.
|
||||
r.forgetFrames()
|
||||
send(p.cb, "commit")
|
||||
r.track(p.cb)
|
||||
release(&p.cb)
|
||||
return nil
|
||||
}
|
||||
tex := send(drawable, "texture")
|
||||
backdrops := func(d []image.Rectangle) []image.Rectangle { return d }
|
||||
if p.whole {
|
||||
backdrops = nil
|
||||
}
|
||||
if err := r.drawBuilt(p.cb, &p.size, tex, &r.drawState, r.partIn(p.size.Width, p.size.Height, tex, backdrops)); err != nil {
|
||||
r.forgetFrames()
|
||||
release(&p.cb)
|
||||
return err
|
||||
}
|
||||
send(p.cb, "presentDrawable:", drawable)
|
||||
send(p.cb, "commit")
|
||||
if prefetch {
|
||||
r.pre.start(r.layer)
|
||||
}
|
||||
r.track(p.cb)
|
||||
release(&p.cb)
|
||||
r.lastRender = time.Now()
|
||||
r.armTrim()
|
||||
r.sweepIfDue()
|
||||
return nil
|
||||
}
|
||||
|
||||
// dropPending drops the frame pending, committing what it drew before its
|
||||
// drawable: the next draws whole. What Ready was given meanwhile runs, as
|
||||
// the frame waiting for this one, which never comes, can draw now.
|
||||
func (r *Renderer) dropPending() {
|
||||
if r.pending.cb == 0 {
|
||||
return
|
||||
}
|
||||
r.forgetFrames()
|
||||
send(r.pending.cb, "commit")
|
||||
r.track(r.pending.cb)
|
||||
release(&r.pending.cb)
|
||||
r.pending = pendingFrame{}
|
||||
r.wakeContent()
|
||||
}
|
||||
|
||||
// wakeContent runs what Ready was given while a frame was pending.
|
||||
func (r *Renderer) wakeContent() {
|
||||
if w := r.wake; w != nil {
|
||||
r.wake = nil
|
||||
w()
|
||||
}
|
||||
}
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// TestPresenter checks the presenter's fetches: a frame is not ready while
|
||||
// one is in flight, the presenter wakes the window once it has the
|
||||
// drawable, and taking or draining one waits for a fetch in flight.
|
||||
func TestPresenter(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Objective-C runtime:", err)
|
||||
}
|
||||
gate := make(chan struct{})
|
||||
fetched := 0
|
||||
nextDrawable = func(id) id {
|
||||
<-gate
|
||||
fetched++
|
||||
return send(send(class("NSObject"), "new"), "autorelease")
|
||||
}
|
||||
defer func() { nextDrawable = func(layer id) id { return send(layer, "nextDrawable") } }()
|
||||
var p presenter
|
||||
defer p.stop()
|
||||
|
||||
if !p.ready(nil) {
|
||||
t.Fatal("not ready before any fetch")
|
||||
}
|
||||
p.start(0)
|
||||
woke := make(chan struct{})
|
||||
if p.ready(func() { close(woke) }) {
|
||||
t.Fatal("ready while a fetch is in flight")
|
||||
}
|
||||
gate <- struct{}{}
|
||||
wait.For(t, "the presenter's wake", woke)
|
||||
if !p.ready(nil) {
|
||||
t.Fatal("not ready once fetched")
|
||||
}
|
||||
// A fetched drawable is kept until taken: starting again fetches none.
|
||||
p.start(0)
|
||||
d := p.take()
|
||||
if d == 0 || fetched != 1 {
|
||||
t.Fatalf("took %#x after %d fetches", d, fetched)
|
||||
}
|
||||
pool(func() { send(d, "release") })
|
||||
|
||||
// Taking waits for the fetch in flight, as draining does.
|
||||
p.start(0)
|
||||
go func() { gate <- struct{}{} }()
|
||||
if d = p.take(); d == 0 || fetched != 2 {
|
||||
t.Fatalf("took %#x after %d fetches", d, fetched)
|
||||
}
|
||||
pool(func() { send(d, "release") })
|
||||
p.start(0)
|
||||
go func() { gate <- struct{}{} }()
|
||||
p.drain()
|
||||
if fetched != 3 || p.drawable != 0 || p.fetching {
|
||||
t.Fatalf("drained after %d fetches: drawable %#x, fetching %v", fetched, p.drawable, p.fetching)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrefetchedFrames renders frames following each other into a layer:
|
||||
// the first, changing the layer, takes its drawable on the main thread;
|
||||
// each after presents as soon as drawn and has the presenter fetch the
|
||||
// next frame's, which that frame takes; a frame resizing the layer drains
|
||||
// it.
|
||||
func TestPrefetchedFrames(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
var layer id
|
||||
pool(func() { layer = send(class("CALayer"), "new") })
|
||||
if layer == 0 {
|
||||
t.Skip("no Core Animation")
|
||||
}
|
||||
defer pool(func() { release(&layer) })
|
||||
r, err := New(uintptr(layer))
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
var fetched int
|
||||
next := nextDrawable
|
||||
nextDrawable = func(l id) id { fetched++; return next(l) }
|
||||
defer func() { nextDrawable = next }()
|
||||
frame := func(w, i int) {
|
||||
t.Helper()
|
||||
s := &scene.Scene{}
|
||||
s.Reset(w, 32, scene.Color{A: 255})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i), W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}})
|
||||
r.pre.wait()
|
||||
parked := drawableID(r.pre.drawable)
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.pre.wait()
|
||||
if parked != 0 && drawableID(r.pre.drawable) == parked {
|
||||
t.Fatalf("frame %d did not take the drawable fetched for it", i)
|
||||
}
|
||||
if !r.pre.ready(nil) {
|
||||
t.Fatalf("frame %d: not ready after the fetch", i)
|
||||
}
|
||||
}
|
||||
frame(64, 0)
|
||||
if r.synced == false || r.pre.started {
|
||||
t.Fatalf("the first frame: synced %v, presenter started %v", r.synced, r.pre.started)
|
||||
}
|
||||
for i := 1; i <= 5; i++ {
|
||||
frame(64, i)
|
||||
if r.pre.drawable == 0 {
|
||||
t.Fatalf("frame %d: no drawable fetched for the next", i)
|
||||
}
|
||||
}
|
||||
// The presenter fetched after each frame but the first, which
|
||||
// presented with the transaction.
|
||||
if fetched != 5 {
|
||||
t.Errorf("%d fetches after 6 frames, want 5", fetched)
|
||||
}
|
||||
frame(96, 6)
|
||||
if r.pre.drawable != 0 || !r.synced {
|
||||
t.Errorf("a resize: drawable fetched %#x, synced %v", r.pre.drawable, r.synced)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPendingFrames renders a frame while its drawable is being fetched:
|
||||
// it is built at once and waits, frames paced by the display are not
|
||||
// ready meanwhile, and the presenter has it drawn on the main thread
|
||||
// (post) once it has the drawable; a frame not paced, as a resize's,
|
||||
// draws the pending one first.
|
||||
func TestPendingFrames(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
var layer id
|
||||
pool(func() { layer = send(class("CALayer"), "new") })
|
||||
if layer == 0 {
|
||||
t.Skip("no Core Animation")
|
||||
}
|
||||
defer pool(func() { release(&layer) })
|
||||
r, err := New(uintptr(layer))
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(fn func()) { posted <- fn })
|
||||
gate := make(chan struct{})
|
||||
next := nextDrawable
|
||||
nextDrawable = func(l id) id { <-gate; return next(l) }
|
||||
defer func() { nextDrawable = next }()
|
||||
frame := func(w, i int) {
|
||||
t.Helper()
|
||||
s := &scene.Scene{}
|
||||
s.Reset(w, 32, scene.Color{A: 255})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i), W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}})
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
frame(64, 0) // with the transaction: no fetch after
|
||||
frame(64, 1) // takes its drawable, then the presenter fetches the next
|
||||
if !r.pre.fetching {
|
||||
t.Fatal("no drawable being fetched after a frame presented as soon as drawn")
|
||||
}
|
||||
frame(64, 2) // built, waiting for the fetch
|
||||
if r.pending.cb == 0 {
|
||||
t.Fatal("the frame did not wait for the drawable being fetched")
|
||||
}
|
||||
woke := false
|
||||
if r.Ready(func() { woke = true }) {
|
||||
t.Fatal("ready while a frame waits")
|
||||
}
|
||||
gate <- struct{}{} // the fetch ends
|
||||
finish := wait.For(t, "the post", posted)
|
||||
finish()
|
||||
if r.pending.cb != 0 || !woke {
|
||||
t.Fatalf("after the drawable came: pending %v, woke %v", r.pending.cb != 0, woke)
|
||||
}
|
||||
if !r.Ready(nil) {
|
||||
t.Fatal("not ready once drawn")
|
||||
}
|
||||
// A frame waiting is drawn first by a frame not paced, as a resize's.
|
||||
frame(64, 3)
|
||||
if r.pending.cb == 0 {
|
||||
t.Fatal("the frame did not wait")
|
||||
}
|
||||
go func() { gate <- struct{}{} }()
|
||||
frame(96, 4)
|
||||
if r.pending.cb != 0 || !r.synced || r.pre.fetching {
|
||||
t.Fatalf("a resize: pending %v, synced %v, fetching %v", r.pending.cb != 0, r.synced, r.pre.fetching)
|
||||
}
|
||||
close(gate)
|
||||
// The post of the fetch the resize waited for finds nothing pending.
|
||||
select {
|
||||
case fn := <-posted:
|
||||
fn()
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// drawableID returns the identity of drawable d, or 0 for none: its
|
||||
// address may come back for another.
|
||||
func drawableID(d id) uintptr {
|
||||
if d == 0 {
|
||||
return 0
|
||||
}
|
||||
return send(d, "drawableID")
|
||||
}
|
||||
|
||||
// TestDroppedPendingFrame checks that a frame waiting for its drawable,
|
||||
// dropped as the drawables are trimmed or the renderer let go, wakes what
|
||||
// waited for it (Ready): the frame paced by the display waiting draws
|
||||
// then, rather than never.
|
||||
func TestDroppedPendingFrame(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
var layer id
|
||||
pool(func() { layer = send(class("CALayer"), "new") })
|
||||
if layer == 0 {
|
||||
t.Skip("no Core Animation")
|
||||
}
|
||||
defer pool(func() { release(&layer) })
|
||||
r, err := New(uintptr(layer))
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
r.SetPost(func(func()) {})
|
||||
gate := make(chan struct{})
|
||||
next := nextDrawable
|
||||
nextDrawable = func(l id) id { <-gate; return next(l) }
|
||||
defer func() { nextDrawable = next }()
|
||||
frame := func(i int) {
|
||||
t.Helper()
|
||||
s := &scene.Scene{}
|
||||
s.Reset(64, 32, scene.Color{A: 255})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i), W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}})
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
frame(0) // with the transaction: no fetch after
|
||||
frame(1) // takes its drawable, then the presenter fetches the next
|
||||
frame(2) // built, waiting for the fetch
|
||||
if r.pending.cb == 0 {
|
||||
t.Fatal("the frame did not wait for the drawable being fetched")
|
||||
}
|
||||
woke := false
|
||||
if r.Ready(func() { woke = true }) {
|
||||
t.Fatal("ready while a frame waits")
|
||||
}
|
||||
pool(r.dropPending)
|
||||
if r.pending.cb != 0 || !woke {
|
||||
t.Fatalf("dropped: pending %v, woke %v", r.pending.cb != 0, woke)
|
||||
}
|
||||
close(gate)
|
||||
r.pre.drain()
|
||||
}
|
||||
|
||||
// TestPendingFramesSweep checks that frames drawn once their drawable
|
||||
// comes (finishPending) free the textures of the transient canvases of
|
||||
// frames before, as frames drawn at once do. Only these swept, so an
|
||||
// animation, whose frames mostly wait for their drawable, kept a texture
|
||||
// for every frame's transient canvases: hundreds of megabytes on the GPU
|
||||
// within seconds of a player's moving lyrics.
|
||||
func TestPendingFramesSweep(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
var layer id
|
||||
pool(func() { layer = send(class("CALayer"), "new") })
|
||||
if layer == 0 {
|
||||
t.Skip("no Core Animation")
|
||||
}
|
||||
defer pool(func() { release(&layer) })
|
||||
r, err := New(uintptr(layer))
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(fn func()) { posted <- fn })
|
||||
gate := make(chan struct{})
|
||||
next := nextDrawable
|
||||
nextDrawable = func(l id) id { <-gate; return next(l) }
|
||||
defer func() { nextDrawable = next }()
|
||||
frame := func(i int) {
|
||||
t.Helper()
|
||||
s := &scene.Scene{}
|
||||
s.Reset(64, 32, scene.Color{A: 255})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i % 56), W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}})
|
||||
c := scene.NewCanvas(16, 16)
|
||||
c.Transient = true
|
||||
s.Canvases = []*scene.Image{c}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
frame(0) // with the transaction: no fetch after
|
||||
frame(1) // takes its drawable, then the presenter fetches the next
|
||||
for i := 2; i < 2+3*sweepEvery; i++ {
|
||||
frame(i) // built, waiting for the fetch
|
||||
if r.pending.cb == 0 {
|
||||
t.Fatalf("frame %d did not wait for its drawable", i)
|
||||
}
|
||||
gate <- struct{}{} // the fetch ends
|
||||
finish := wait.For(t, "the post", posted)
|
||||
finish()
|
||||
}
|
||||
if n := len(r.canvases); n > sweepEvery+1 {
|
||||
t.Errorf("%d canvas textures after %d frames waiting for their drawables, want at most %d", n, 3*sweepEvery, sweepEvery+1)
|
||||
}
|
||||
close(gate)
|
||||
r.pre.drain()
|
||||
}
|
||||
|
||||
// TestStalePost checks that the post of a fetch whose frame pending a
|
||||
// frame not paced drew meanwhile neither blocks the main thread for the
|
||||
// next frame's drawable, being fetched, nor draws that frame before it
|
||||
// comes: the next fetch posts it.
|
||||
func TestStalePost(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
var layer id
|
||||
pool(func() { layer = send(class("CALayer"), "new") })
|
||||
if layer == 0 {
|
||||
t.Skip("no Core Animation")
|
||||
}
|
||||
defer pool(func() { release(&layer) })
|
||||
r, err := New(uintptr(layer))
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(fn func()) { posted <- fn })
|
||||
gate := make(chan struct{})
|
||||
next := nextDrawable
|
||||
nextDrawable = func(l id) id { <-gate; return next(l) }
|
||||
defer func() { nextDrawable = next }()
|
||||
defer close(gate)
|
||||
frame := func(i int) {
|
||||
t.Helper()
|
||||
s := &scene.Scene{}
|
||||
s.Reset(64, 32, scene.Color{A: 255})
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i), W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}})
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
frame(0) // with the transaction: no fetch after
|
||||
frame(1) // takes its drawable, then the presenter fetches the next
|
||||
frame(2) // built, waiting for the fetch
|
||||
gate <- struct{}{}
|
||||
stale := wait.For(t, "the post", posted)
|
||||
// A frame not paced draws the one pending, the presenter fetches the
|
||||
// next drawable, and this frame waits for it.
|
||||
frame(3)
|
||||
if r.pending.cb == 0 || !r.pre.fetching {
|
||||
t.Fatalf("pending %v, fetching %v", r.pending.cb != 0, r.pre.fetching)
|
||||
}
|
||||
stale() // would wait for the fetch, the gate closed
|
||||
if r.pending.cb == 0 {
|
||||
t.Fatal("the stale post drew the frame pending")
|
||||
}
|
||||
gate <- struct{}{}
|
||||
finish := wait.For(t, "the post of the next fetch", posted)
|
||||
finish()
|
||||
if r.pending.cb != 0 {
|
||||
t.Fatal("the frame pending was not drawn once its drawable came")
|
||||
}
|
||||
}
|
||||
+822
@@ -0,0 +1,822 @@
|
||||
// The one shader of the Metal renderer, as shader.hlsl is the Direct3D
|
||||
// one: every scene op is an instanced quad, and the fragment shader
|
||||
// computes the coverage of rounded rectangles, borders, gradients, stripes
|
||||
// and shadows from signed distances, as the CPU renderer (internal/raster)
|
||||
// does. Colors are straight (not premultiplied) and blending happens in
|
||||
// sRGB space, as in browsers, with a second color for the source's alpha
|
||||
// of each channel, which subpixel glyphs need. go generate compiles it
|
||||
// into shaderlib.go. The libraries of effects (scene.Effect) take its
|
||||
// start, with EFFECT defined, before effect.metal.
|
||||
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
// Function constants specialize the fragment function for the instances a
|
||||
// batch holds (gpu.Class), so that the code of paths it never takes, and the
|
||||
// registers they would need, are not in its pipeline: the general function
|
||||
// holds them all, and a plain fill, most of what a window draws, runs several
|
||||
// times faster without them. A constant left undefined (effect pipelines,
|
||||
// libraries compiled before they existed) is true: the general function.
|
||||
// Indices 0 to 7 are reserved for these constants in every library that includes this
|
||||
// file (effects do): an effect's own function constants must start at 8.
|
||||
constant bool kTransformed_ [[function_constant(0)]]; // instances under a transform
|
||||
constant bool kContinuous_ [[function_constant(1)]]; // continuous corners
|
||||
constant bool kPlain_ [[function_constant(2)]]; // plain fills: solid, no border
|
||||
constant bool kFill_ [[function_constant(3)]]; // other fills: gradients, borders, stripes
|
||||
constant bool kShadow_ [[function_constant(4)]]; // shadows
|
||||
constant bool kGlyph_ [[function_constant(5)]]; // mask glyphs
|
||||
constant bool kSubpixel_ [[function_constant(6)]]; // subpixel glyphs
|
||||
constant bool kImage_ [[function_constant(7)]]; // images and color glyphs
|
||||
constant bool kTransformed = is_function_constant_defined(kTransformed_) ? kTransformed_ : true;
|
||||
constant bool kContinuous = is_function_constant_defined(kContinuous_) ? kContinuous_ : true;
|
||||
constant bool kPlain = is_function_constant_defined(kPlain_) ? kPlain_ : true;
|
||||
constant bool kFill = is_function_constant_defined(kFill_) ? kFill_ : true;
|
||||
constant bool kShadow = is_function_constant_defined(kShadow_) ? kShadow_ : true;
|
||||
constant bool kGlyph = is_function_constant_defined(kGlyph_) ? kGlyph_ : true;
|
||||
constant bool kSubpixel = is_function_constant_defined(kSubpixel_) ? kSubpixel_ : true;
|
||||
constant bool kImage = is_function_constant_defined(kImage_) ? kImage_ : true;
|
||||
// kGeneral: the function takes more than the plain fill's path.
|
||||
constant bool kGeneral = kTransformed || kFill || kShadow || kGlyph || kSubpixel || kImage;
|
||||
|
||||
// One instance per op, as internal/gpu builds them.
|
||||
struct Inst {
|
||||
float4 rect; // x, y, width, height in pixels
|
||||
float4 radii; // top-left, top-right, bottom-right, bottom-left
|
||||
float4 inner; // radii of the border's inner edge, of the box casting a shadow, or of an inner shadow's hole
|
||||
float4 color;
|
||||
float4 color2; // gradient end
|
||||
float4 border; // border color
|
||||
float4 grad; // gradient start and end points, or stripes
|
||||
float4 uv; // texture rectangle, normalized, border widths, the box casting a shadow, or an inner shadow's hole
|
||||
float4 clip; // the innermost clip rectangle
|
||||
float4 clipRadii;
|
||||
float4 params; // kind, dashed or grayscale, sigma or paint, opacity
|
||||
float4 transform0, transform1; // local-to-frame rows, AA and clip-mask flags
|
||||
float4 transform2; // the projective row's g and h, and 1 where its constant is -1
|
||||
};
|
||||
|
||||
// The color and, for dual-source blending, the source's alpha of each
|
||||
// channel.
|
||||
struct PSOut {
|
||||
float4 color [[color(0), index(0)]];
|
||||
float4 alpha [[color(0), index(1)]];
|
||||
};
|
||||
|
||||
struct VSOut {
|
||||
float4 pos [[position]];
|
||||
float2 p;
|
||||
// The frame point times its projective divisor, and the divisor: they
|
||||
// interpolate in perspective to what divides into the frame point.
|
||||
float3 world;
|
||||
float2 tex;
|
||||
uint inst [[flat]];
|
||||
};
|
||||
|
||||
// frameH returns the frame point of local p, in homogeneous coordinates.
|
||||
float3 frameH(Inst i, float2 p) {
|
||||
return float3(dot(i.transform0.xyz, float3(p, 1.0f)), dot(i.transform1.xyz, float3(p, 1.0f)),
|
||||
dot(float3(i.transform2.xy, 1.0f - 2.0f * i.transform2.z), float3(p, 1.0f)));
|
||||
}
|
||||
|
||||
// globals holds the frame's width and height in pixels, and 1 in z when
|
||||
// its target keeps colors outside the sRGB gamut (extended sRGB, float16).
|
||||
vertex VSOut vs(uint vid [[vertex_id]], uint iid [[instance_id]], const device Inst *insts [[buffer(0)]],
|
||||
constant float4 &globals [[buffer(1)]]) {
|
||||
Inst i = insts[iid];
|
||||
float2 corner = float2(float(vid & 1u), float(vid >> 1u));
|
||||
float4 r = i.rect;
|
||||
float kind = i.params.x;
|
||||
if (kind < 0.5f || kind > 5.5f) { // fills and effects
|
||||
r = float4(r.xy - 1.0f, r.zw + 2.0f);
|
||||
} else if (kind < 1.5f) {
|
||||
float e = 3.0f * i.params.z + 1.0f;
|
||||
r = float4(r.xy - e, r.zw + 2.0f * e);
|
||||
}
|
||||
float3 h = frameH(i, r.xy + corner * r.zw);
|
||||
if (i.transform0.w > 0.5f && h.z > 0.0f) {
|
||||
// A pixel's reach at this corner, by the map's Jacobian there.
|
||||
float2 s = h.xy / h.z;
|
||||
float a = (i.transform0.x - s.x * i.transform2.x) / h.z, c = (i.transform0.y - s.x * i.transform2.y) / h.z;
|
||||
float b = (i.transform1.x - s.y * i.transform2.x) / h.z, d = (i.transform1.y - s.y * i.transform2.y) / h.z;
|
||||
float2 e = float2(abs(d) + abs(c), abs(b) + abs(a)) / abs(a * d - b * c);
|
||||
r = float4(r.xy - e, r.zw + 2.0f * e);
|
||||
}
|
||||
float2 p = r.xy + corner * r.zw;
|
||||
h = frameH(i, p);
|
||||
VSOut o;
|
||||
o.pos = float4(h.xy / globals.xy * float2(2.0f, -2.0f) + h.z * float2(-1.0f, 1.0f), 0.0f, h.z);
|
||||
o.p = p;
|
||||
o.world = h;
|
||||
o.tex = i.uv.xy + (p - i.rect.xy) / i.rect.zw * (i.uv.zw - i.uv.xy);
|
||||
o.inst = iid;
|
||||
return o;
|
||||
}
|
||||
|
||||
float sdRoundRect(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5f;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0f ? (q.y < 0.0f ? radii.x : radii.w) : (q.y < 0.0f ? radii.y : radii.z);
|
||||
float2 a = abs(q) - h + r;
|
||||
return length(max(a, float2(0.0f))) + min(max(a.x, a.y), 0.0f) - r;
|
||||
}
|
||||
|
||||
float coverage(float d) { return saturate(0.5f - d); }
|
||||
|
||||
// Continuous corners are Core Animation's, as internal/raster/corner.go
|
||||
// explains: a corner of radius r whose curve leaves the edges e from it,
|
||||
// blended toward a quarter circle by cx along its horizontal edge and cy
|
||||
// along its vertical one, its curve's box ending at eff as clamped.
|
||||
constant float contExtent = 1.528665f;
|
||||
|
||||
struct ContCorner {
|
||||
float r, e, eff, cx, cy;
|
||||
};
|
||||
|
||||
// contCorner returns the corner of radius r of a rectangle w×h sharing
|
||||
// its horizontal edge with a corner of radius rh, its vertical one with
|
||||
// one of radius rv.
|
||||
ContCorner contCorner(float r, float rh, float rv, float w, float h) {
|
||||
ContCorner c;
|
||||
c.r = r;
|
||||
c.e = contExtent * r;
|
||||
c.cx = saturate((contExtent - w / max(r + rh, 1e-6f)) / (contExtent - 1.0f));
|
||||
c.cy = saturate((contExtent - h / max(r + rv, 1e-6f)) / (contExtent - 1.0f));
|
||||
c.eff = c.e + (r - c.e) * max(c.cx, c.cy);
|
||||
return c;
|
||||
}
|
||||
|
||||
// contDist returns the corner's value at the point u inside its vertical
|
||||
// edge and v inside its horizontal one: about the signed distance to its
|
||||
// edge near it.
|
||||
float contDist(ContCorner c, float u, float v) {
|
||||
float2 a = max(0.0f, 1.0f - float2(u, v) / c.e);
|
||||
float l = length(a);
|
||||
float hi = max(a.x, a.y);
|
||||
float rho = hi > 0.0f ? min(min(a.x, a.y) / hi, 1.0f) : 0.0f;
|
||||
float p = (((-0.926054f * rho + 3.15601f) * rho - 3.64122f) * rho + 1.26803f) * rho + 0.268531f;
|
||||
float f1 = l + 1.0f - 1.0f / (1.0f - rho * rho * min(l, 1.0f) * p);
|
||||
float f2 = length(max(0.0f, a * contExtent - (contExtent - 1.0f))) * 0.654166f + 0.345834f;
|
||||
float s = a.y > a.x ? 1.0f : -1.0f;
|
||||
float w = saturate(0.5f - s + s * rho);
|
||||
float fx = f1 + (f2 - f1) * c.cx, fy = f1 + (f2 - f1) * c.cy;
|
||||
return min(max(c.eff - u, c.eff - v), 0.0f) + c.e * (fx + (fy - fx) * w - 1.0f);
|
||||
}
|
||||
|
||||
// contInset returns how far inside its vertical edge the corner's edge is
|
||||
// v inside its horizontal one, which lies between the quarter circles of
|
||||
// radius r and e, by regula falsi (Illinois).
|
||||
float contInset(ContCorner c, float v) {
|
||||
if (v >= c.e || c.r <= 0.0f) {
|
||||
return 0.0f;
|
||||
}
|
||||
float lo = v < c.r ? c.r - sqrt(v * (2.0f * c.r - v)) : 0.0f;
|
||||
float hi = c.e - sqrt(v * (2.0f * c.e - v));
|
||||
float dlo = contDist(c, lo, v), dhi = contDist(c, hi, v);
|
||||
if (dlo <= 0.0f) {
|
||||
return lo;
|
||||
}
|
||||
if (dhi >= 0.0f) {
|
||||
return hi;
|
||||
}
|
||||
int side = 0;
|
||||
for (int n = 0; n < 5; n++) {
|
||||
float m = (lo * dhi - hi * dlo) / (dhi - dlo);
|
||||
float dm = contDist(c, m, v);
|
||||
if (dm > 0.0f) {
|
||||
lo = m;
|
||||
dlo = dm;
|
||||
if (side == 1) {
|
||||
dhi *= 0.5f;
|
||||
}
|
||||
side = 1;
|
||||
} else {
|
||||
hi = m;
|
||||
dhi = dm;
|
||||
if (side == -1) {
|
||||
dlo *= 0.5f;
|
||||
}
|
||||
side = -1;
|
||||
}
|
||||
}
|
||||
return (lo * dhi - hi * dlo) / (dhi - dlo);
|
||||
}
|
||||
|
||||
// areaCoverage returns the area of the pixel at p inside the rectangle,
|
||||
// near square corners: exact for lines thinner than a pixel too.
|
||||
float areaCoverage(float2 p, float4 rect) {
|
||||
float2 c = saturate(min(rect.xy + rect.zw, p + 0.5f) - max(rect.xy, p - 0.5f));
|
||||
return c.x * c.y;
|
||||
}
|
||||
|
||||
// contValue returns the value of a rectangle with continuous corners c at
|
||||
// p, the largest of its corners' and its signed distance, and whether a
|
||||
// corner's curve reaches p.
|
||||
float contValue(float2 p, float4 rect, thread const ContCorner *c, thread bool &curved) {
|
||||
float4 d = float4(p - rect.xy, rect.xy + rect.zw - p); // left, top, right, bottom
|
||||
float4 u = d.xzzx, v = d.yyww;
|
||||
float value = max(max(-d.x, -d.y), max(-d.z, -d.w));
|
||||
curved = false;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
if (c[i].r > 0.0f && u[i] < c[i].e && v[i] < c[i].e) {
|
||||
value = max(value, contDist(c[i], u[i], v[i]));
|
||||
curved = true;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// contCoverage is rectCoverage with continuous corners of radii r: away
|
||||
// from their curves, the area of the pixel inside the rectangle; near
|
||||
// them, the value over the sum of its derivatives, as Core Animation
|
||||
// antialiases.
|
||||
float contCoverage(float2 p, float4 rect, float4 r) {
|
||||
ContCorner c[4] = {
|
||||
contCorner(r.x, r.y, r.w, rect.z, rect.w),
|
||||
contCorner(r.y, r.x, r.z, rect.z, rect.w),
|
||||
contCorner(r.z, r.w, r.y, rect.z, rect.w),
|
||||
contCorner(r.w, r.z, r.x, rect.z, rect.w),
|
||||
};
|
||||
bool curved, ignored;
|
||||
float d = contValue(p, rect, c, curved);
|
||||
if (!curved) {
|
||||
return areaCoverage(p, rect);
|
||||
}
|
||||
if (abs(d) > 2.0f) {
|
||||
return d < 0.0f ? 1.0f : 0.0f;
|
||||
}
|
||||
const float h = 1.0f / 16.0f;
|
||||
float dx = contValue(p + float2(h, 0.0f), rect, c, ignored);
|
||||
float dy = contValue(p + float2(0.0f, h), rect, c, ignored);
|
||||
return saturate(0.5f - d * h / max(abs(dx - d) + abs(dy - d), 1e-6f));
|
||||
}
|
||||
|
||||
// rectCoverage returns how much of the pixel at p a rounded rectangle
|
||||
// covers: by the distance to its edge near rounded corners, and exactly,
|
||||
// the area of the pixel inside it, near square ones. Negative radii are
|
||||
// continuous corners.
|
||||
float rectCoverage(float2 p, float4 rect, float4 radii) {
|
||||
if (kContinuous && any(radii < 0.0f)) {
|
||||
return contCoverage(p, rect, -radii);
|
||||
}
|
||||
float2 q = p - rect.xy - rect.zw * 0.5f;
|
||||
float r = q.x < 0.0f ? (q.y < 0.0f ? radii.x : radii.w) : (q.y < 0.0f ? radii.y : radii.z);
|
||||
if (r > 0.0f) {
|
||||
return coverage(sdRoundRect(p, rect, radii));
|
||||
}
|
||||
return areaCoverage(p, rect);
|
||||
}
|
||||
|
||||
// Coverage is integrated in device space, matching the CPU compositor.
|
||||
float localValue(float2 p, float4 rect, float4 r) {
|
||||
if (!kContinuous || !any(r < 0.0f))
|
||||
return sdRoundRect(p, rect, r);
|
||||
r = abs(r);
|
||||
ContCorner c[4] = {contCorner(r.x, r.y, r.w, rect.z, rect.w), contCorner(r.y, r.x, r.z, rect.z, rect.w),
|
||||
contCorner(r.z, r.w, r.y, rect.z, rect.w), contCorner(r.w, r.z, r.x, rect.z, rect.w)};
|
||||
bool curved;
|
||||
return contValue(p, rect, c, curved);
|
||||
}
|
||||
// Frame is where a fragment is in the frame, s, and, when its instance's
|
||||
// map is projective (persp), the columns of the map back, up to a factor.
|
||||
struct Frame {
|
||||
float2 s;
|
||||
float3 c0, c1, c2;
|
||||
bool persp;
|
||||
};
|
||||
Frame frameOf(VSOut v, Inst i) {
|
||||
Frame f;
|
||||
if (!kTransformed || i.transform0.w < 0.5f) {
|
||||
// Not transformed: the frame point is the interpolated one, and
|
||||
// nothing reads the map back.
|
||||
f.s = v.world.xy / v.world.z;
|
||||
f.c0 = f.c1 = f.c2 = float3(0.0f);
|
||||
f.persp = false;
|
||||
return f;
|
||||
}
|
||||
f.persp = any(i.transform2.xy != 0.0f);
|
||||
// In perspective, the pixel's center, as interpolating drifts.
|
||||
f.s = f.persp ? v.pos.xy : v.world.xy / v.world.z;
|
||||
float3 r0 = i.transform0.xyz, r1 = i.transform1.xyz, r2 = float3(i.transform2.xy, 1.0f - 2.0f * i.transform2.z);
|
||||
f.c0 = cross(r1, r2);
|
||||
f.c1 = cross(r2, r0);
|
||||
f.c2 = cross(r0, r1);
|
||||
return f;
|
||||
}
|
||||
// localOf returns the point of the instance that shows at the frame's s.
|
||||
float2 localOf(Frame f, float2 s) {
|
||||
float3 q = f.c0 * s.x + f.c1 * s.y + f.c2;
|
||||
return q.xy / q.z;
|
||||
}
|
||||
float localCoverage(float2 p, float4 rect, float4 radii, float affine, Frame fr) {
|
||||
if (!kTransformed || affine < 0.5f)
|
||||
return rectCoverage(p, rect, radii);
|
||||
float2 dx = dfdx(p), dy = dfdy(p);
|
||||
if (fr.persp) {
|
||||
// In perspective, each sample where the CPU renderer takes it.
|
||||
p = localOf(fr, fr.s);
|
||||
dx = localOf(fr, fr.s + float2(0.5f, 0.5f)) - p;
|
||||
dy = localOf(fr, fr.s + float2(0.5f, -0.5f)) - p;
|
||||
float reach = max(abs(dx.x) + abs(dx.y), abs(dy.x) + abs(dy.y)) * 2.0f;
|
||||
float d = localValue(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0f;
|
||||
if (d > reach)
|
||||
return 0.0f;
|
||||
float n = 0.0f;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
float2 q = localOf(fr, fr.s + float2((float(x) + 0.5f) / 4.0f - 0.5f, (float(y) + 0.5f) / 4.0f - 0.5f));
|
||||
n += localValue(q, rect, radii) <= 0.0f ? 1.0f : 0.0f;
|
||||
}
|
||||
return n / 16.0f;
|
||||
}
|
||||
float2 a = (dx + dy) * 0.5f, b = (dx - dy) * 0.5f;
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2.0f;
|
||||
float d = localValue(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0f;
|
||||
if (d > reach)
|
||||
return 0.0f;
|
||||
float n = 0.0f;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
float2 q = p + dx * ((float(x) + 0.5f) / 4.0f - 0.5f) + dy * ((float(y) + 0.5f) / 4.0f - 0.5f);
|
||||
n += localValue(q, rect, radii) <= 0.0f ? 1.0f : 0.0f;
|
||||
}
|
||||
return n / 16.0f;
|
||||
}
|
||||
float clipCoverage(VSOut v, Inst i, texture2d<float> mask, sampler samp) {
|
||||
if (i.transform1.w > 2.5f)
|
||||
return 1.0f; // the builder found the clip's rectangle to hold the whole quad
|
||||
Frame fr = frameOf(v, i);
|
||||
float2 world = fr.s;
|
||||
if (i.transform1.w < 0.5f)
|
||||
return rectCoverage(world, i.clip, i.clipRadii);
|
||||
if (i.transform1.w > 1.5f)
|
||||
return localCoverage(v.p, i.clip, float4(0.0f), i.transform0.w, fr) *
|
||||
mask.sample(samp, (world - i.clipRadii.xy) / i.clipRadii.zw).a;
|
||||
return mask.sample(samp, (world - i.clip.xy) / i.clip.zw).a;
|
||||
}
|
||||
float4 sampleLocal(texture2d<float> t, sampler samp, float2 uv, float4 src, float affine) {
|
||||
if (kTransformed && affine > 0.5f) {
|
||||
float2 halfPixel = 0.5f / float2(t.get_width(), t.get_height());
|
||||
uv = clamp(uv, src.xy + halfPixel, src.zw - halfPixel);
|
||||
}
|
||||
// The atlases have one mip level, so level 0 is what implicit sampling
|
||||
// picks; saying so keeps the Radeon Pro 560 from dropping glyph pixels
|
||||
// in batches that join continuous corners with glyphs (#649).
|
||||
return t.sample(samp, uv, level(0.0f));
|
||||
}
|
||||
|
||||
// sampleImage samples an image held inside src, which is reversed along
|
||||
// an axis it flips, so that a part of a sheet shows none of its
|
||||
// neighbors; where pixelated is set, as pixel art draws, each texel a
|
||||
// square of its color whose edges blend with the next only across the
|
||||
// pixel they cross (Ebitengine's FilterPixelated): nearest where it shows
|
||||
// at whole multiples of its size, and texels of even widths with smooth
|
||||
// edges at any other. dtex is the fwidth of uv, taken where every
|
||||
// fragment of the quad takes it.
|
||||
float4 sampleImage(texture2d<float> t, sampler samp, float2 uv, float4 src, float pixelated, float2 dtex) {
|
||||
float2 size = float2(t.get_width(), t.get_height());
|
||||
float2 lo = min(src.xy, src.zw), hi = max(src.xy, src.zw);
|
||||
if (pixelated > 0.5f) {
|
||||
float2 tc = uv * size - 0.5f;
|
||||
float2 i = floor(tc);
|
||||
float2 f = saturate((tc - i - 0.5f) / clamp(dtex * size, 1e-5f, 1.0f) + 0.5f);
|
||||
uv = (i + f + 0.5f) / size;
|
||||
}
|
||||
return t.sample(samp, clamp(uv, lo + 0.5f / size, hi - 0.5f / size));
|
||||
}
|
||||
|
||||
// tint multiplies premultiplied c by straight color t.
|
||||
float4 tint(float4 c, float4 t) { return c * float4(t.rgb * t.a, t.a); }
|
||||
|
||||
float4 premul(float4 c) { return float4(c.rgb * c.a, c.a); }
|
||||
|
||||
float3 unpremul(float4 c) { return c.a > 0.0f ? c.rgb / c.a : float3(0.0f); }
|
||||
|
||||
// textCoverage corrects the coverage a of a glyph of straight color c as
|
||||
// Direct2D blends text (scene.TextCoverage): it enhances the contrast,
|
||||
// the more the darker c is, and corrects for gamma with the ratios g.
|
||||
float textCoverage(float a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3.0f - 4.0f * dot(c, float3(0.30f, 0.59f, 0.11f))) + boost;
|
||||
a = a * (k + 1.0f) / (a * k + 1.0f);
|
||||
float f = dot(c, float3(0.25f, 0.5f, 0.25f));
|
||||
return saturate(a + a * (1.0f - a) * ((g.x * f + g.y) * a + (g.z * f + g.w)));
|
||||
}
|
||||
|
||||
// What follows is the renderer's own; effects (effect.metal) take what is
|
||||
// above.
|
||||
#ifndef EFFECT
|
||||
|
||||
// yuvToRGB converts the samples of a frame of video in YCbCr to RGB, as
|
||||
// scene.YUVMatrix.YUVToRGB does: m is the matrix, 0 to 2 for BT.601, 709
|
||||
// and 2020 in the limited range, plus 3 for the full range.
|
||||
float3 yuvToRGB(float y, float2 c, float m) {
|
||||
float full = m > 2.5f ? 1.0f : 0.0f;
|
||||
float std = m - 3.0f * full;
|
||||
float2 k = std < 0.5f ? float2(0.299f, 0.114f) : std < 1.5f ? float2(0.2126f, 0.0722f) : float2(0.2627f, 0.0593f);
|
||||
c -= 128.0f / 255.0f;
|
||||
if (full < 0.5f) {
|
||||
y = (y - 16.0f / 255.0f) * (255.0f / 219.0f);
|
||||
c *= 255.0f / 224.0f;
|
||||
}
|
||||
float r = y + 2.0f * (1.0f - k.x) * c.y;
|
||||
float b = y + 2.0f * (1.0f - k.y) * c.x;
|
||||
float g = (y - k.x * r - k.y * b) / (1.0f - k.x - k.y);
|
||||
return saturate(float3(r, g, b));
|
||||
}
|
||||
|
||||
// subpixelCoverage does the same for each subpixel of a subpixel glyph.
|
||||
float3 subpixelCoverage(float3 a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3.0f - 4.0f * dot(c, float3(0.30f, 0.59f, 0.11f))) + boost;
|
||||
a = a * (k + 1.0f) / (a * k + 1.0f);
|
||||
return saturate(a + a * (1.0f - a) * ((g.x * c + g.y) * a + (g.z * c + g.w)));
|
||||
}
|
||||
|
||||
// erf2 approximates the error function (Abramowitz and Stegun 7.1.27).
|
||||
float2 erf2(float2 x) {
|
||||
float2 s = sign(x);
|
||||
float2 a = abs(x);
|
||||
x = 1.0f + (0.278393f + (0.230389f + 0.078108f * (a * a)) * a) * a;
|
||||
x *= x;
|
||||
return s - s / (x * x);
|
||||
}
|
||||
|
||||
float gaussian(float x, float sigma) {
|
||||
return exp(-(x * x) / (2.0f * sigma * sigma)) / (2.50662827463f * sigma);
|
||||
}
|
||||
|
||||
// The blurred rounded box of Evan Wallace: exact along x, four samples
|
||||
// along y; cc is its continuous corner, if any.
|
||||
float shadowX(float x, float y, float sigma, float corner, float2 h, bool continuous, ContCorner cc) {
|
||||
float curved;
|
||||
if (continuous) {
|
||||
float v = h.y - abs(y);
|
||||
curved = v < cc.e ? h.x - contInset(cc, v) : h.x;
|
||||
} else {
|
||||
float delta = min(h.y - corner - abs(y), 0.0f);
|
||||
curved = h.x - corner + sqrt(max(0.0f, corner * corner - delta * delta));
|
||||
}
|
||||
float2 integral = 0.5f + 0.5f * erf2((x + float2(-curved, curved)) * (sqrt(0.5f) / sigma));
|
||||
return integral.y - integral.x;
|
||||
}
|
||||
|
||||
float boxShadow(float2 p, float4 rect, float sigma, float4 radii) {
|
||||
float4 r = abs(radii);
|
||||
float corner = max(max(r.x, r.y), max(r.z, r.w));
|
||||
bool continuous = kContinuous && any(radii < 0.0f) && corner > 0.0f;
|
||||
ContCorner cc = contCorner(corner, corner, corner, rect.z, rect.w);
|
||||
float2 h = rect.zw * 0.5f;
|
||||
p -= rect.xy + h;
|
||||
float low = p.y - h.y;
|
||||
float high = p.y + h.y;
|
||||
float from = clamp(-3.0f * sigma, low, high);
|
||||
float to = clamp(3.0f * sigma, low, high);
|
||||
float dy = (to - from) / 4.0f;
|
||||
float y = from + dy * 0.5f;
|
||||
float v = 0.0f;
|
||||
for (int n = 0; n < 4; n++) {
|
||||
v += shadowX(p.x, p.y - y, sigma, corner, h, continuous, cc) * gaussian(y, sigma) * dy;
|
||||
y += dy;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// toLinear and toSRGB mirror the curve around zero, as extended sRGB does,
|
||||
// for the components of wide colors.
|
||||
float3 toLinear(float3 c) {
|
||||
float3 a = abs(c);
|
||||
return sign(c) * select(pow((a + 0.055f) / 1.055f, float3(2.4f)), a / 12.92f, a <= 0.04045f);
|
||||
}
|
||||
|
||||
float3 toSRGB(float3 c) {
|
||||
float3 a = abs(c);
|
||||
return sign(c) * select(1.055f * pow(a, float3(1.0f / 2.4f)) - 0.055f, a * 12.92f, a <= 0.0031308f);
|
||||
}
|
||||
|
||||
float3 cbrt3(float3 v) { return sign(v) * pow(abs(v), float3(1.0f / 3.0f)); }
|
||||
|
||||
float3 oklab(float3 srgb) {
|
||||
float3 c = toLinear(srgb);
|
||||
float3 lms = cbrt3(float3(0.4122214708f * c.r + 0.5363325363f * c.g + 0.0514459929f * c.b,
|
||||
0.2119034982f * c.r + 0.6806995451f * c.g + 0.1073969566f * c.b,
|
||||
0.0883024619f * c.r + 0.2817188376f * c.g + 0.6299787005f * c.b));
|
||||
return float3(0.2104542553f * lms.x + 0.7936177850f * lms.y - 0.0040720468f * lms.z,
|
||||
1.9779984951f * lms.x - 2.4285922050f * lms.y + 0.4505937099f * lms.z,
|
||||
0.0259040371f * lms.x + 0.7827717662f * lms.y - 0.8086757660f * lms.z);
|
||||
}
|
||||
|
||||
float3 fromOklab(float3 lab) {
|
||||
float3 lms = float3(lab.x + 0.3963377774f * lab.y + 0.2158037573f * lab.z,
|
||||
lab.x - 0.1055613458f * lab.y - 0.0638541728f * lab.z,
|
||||
lab.x - 0.0894841775f * lab.y - 1.2914855480f * lab.z);
|
||||
lms = lms * lms * lms;
|
||||
return toSRGB(float3(4.0767416621f * lms.x - 3.3077115913f * lms.y + 0.2309699292f * lms.z,
|
||||
-1.2684380046f * lms.x + 2.6097574011f * lms.y - 0.3413193965f * lms.z,
|
||||
-0.0041960863f * lms.x - 0.7034186147f * lms.y + 1.7076147010f * lms.z));
|
||||
}
|
||||
|
||||
// stopsAt returns the color at t of the gradient whose stops stops holds
|
||||
// from first, n of them (gpu.Builder.Stops): the first stop's before it,
|
||||
// the last's after it, and between two the colors of both mixed,
|
||||
// premultiplied, in sRGB, or in Oklab, as internal/raster's stopsAt.
|
||||
float4 stopsAt(texture2d<float> stops, float4 c2, float t, bool oklab, bool wide) {
|
||||
int first = int(c2.x), n = int(c2.y);
|
||||
if (n <= 0) {
|
||||
return float4(0.0f);
|
||||
}
|
||||
int k = 2 * first;
|
||||
float4 a = stops.read(uint2(k % 1024, k / 1024)), ap = stops.read(uint2((k + 1) % 1024, (k + 1) / 1024));
|
||||
if (t <= ap.x) {
|
||||
return premul(a);
|
||||
}
|
||||
k = 2 * (first + n - 1);
|
||||
float4 last = stops.read(uint2(k % 1024, k / 1024)), lastp = stops.read(uint2((k + 1) % 1024, (k + 1) / 1024));
|
||||
if (t >= lastp.x) {
|
||||
return premul(last);
|
||||
}
|
||||
float4 b = last, bp = lastp;
|
||||
for (int i = 1; i < n - 1; i++) {
|
||||
k = 2 * (first + i);
|
||||
float4 c = stops.read(uint2(k % 1024, k / 1024)), cp = stops.read(uint2((k + 1) % 1024, (k + 1) / 1024));
|
||||
if (t < cp.x) {
|
||||
b = c;
|
||||
bp = cp;
|
||||
break;
|
||||
}
|
||||
a = c;
|
||||
ap = cp;
|
||||
}
|
||||
float f = saturate((t - ap.x) / max(bp.x - ap.x, 1e-6f));
|
||||
float alpha = mix(a.a, b.a, f);
|
||||
if (!oklab) {
|
||||
return float4(mix(a.rgb * a.a, b.rgb * b.a, f), alpha);
|
||||
}
|
||||
if (alpha <= 0.0f) {
|
||||
return float4(0.0f);
|
||||
}
|
||||
float3 rgb = fromOklab(mix(ap.yzw * a.a, bp.yzw * b.a, f) / alpha);
|
||||
return float4((wide ? rgb : saturate(rgb)) * alpha, alpha);
|
||||
}
|
||||
|
||||
// paint returns the premultiplied color at p of plain color, a gradient
|
||||
// mixed in sRGB (1) or Oklab (2), stripes (3), or a gradient of stops,
|
||||
// linear (4, 5), conic (6, 7) or radial (8, 9), mixed in sRGB or in
|
||||
// Oklab, as scene.Paint says. In a target that keeps colors outside the
|
||||
// sRGB gamut (wide, extended sRGB), an Oklab gradient keeps those its mix
|
||||
// has, which others clamp.
|
||||
float4 paint(float2 p, float mode, float4 rect, float4 c1, float4 c2, float4 g, bool wide, texture2d<float> stops) {
|
||||
if (mode < 0.5f) {
|
||||
return premul(c1);
|
||||
}
|
||||
if (mode > 3.5f) {
|
||||
float t;
|
||||
if (mode < 5.5f) {
|
||||
float2 d = g.zw - g.xy;
|
||||
t = dot(p - g.xy, d) / max(dot(d, d), 0.0001f);
|
||||
} else if (mode < 7.5f) {
|
||||
float2 d = p - g.xy;
|
||||
t = (atan2(d.x, -d.y) - g.z) * 0.15915494309189535f;
|
||||
t -= floor(t);
|
||||
} else {
|
||||
t = length(p - g.xy) / max(g.z, 0.0001f);
|
||||
}
|
||||
return stopsAt(stops, c2, t, mode > 4.5f && mode < 5.5f || mode > 6.5f && mode < 7.5f || mode > 8.5f, wide);
|
||||
}
|
||||
if (mode < 2.5f) {
|
||||
float2 d = g.zw - g.xy;
|
||||
float t = saturate(dot(p - g.xy, d) / max(dot(d, d), 0.0001f));
|
||||
float a = mix(c1.a, c2.a, t);
|
||||
if (mode < 1.5f) {
|
||||
return float4(mix(c1.rgb * c1.a, c2.rgb * c2.a, t), a);
|
||||
}
|
||||
float3 lab = mix(oklab(c1.rgb) * c1.a, oklab(c2.rgb) * c2.a, t);
|
||||
if (a <= 0.0f) {
|
||||
return float4(0.0f);
|
||||
}
|
||||
float3 rgb = fromOklab(lab / a);
|
||||
return float4((wide ? rgb : saturate(rgb)) * a, a);
|
||||
}
|
||||
float s = dot(p - rect.xy, g.xy);
|
||||
float phase = s - g.w * floor(s / g.w);
|
||||
float cov = coverage(min(max(-phase, phase - g.z), g.w - phase));
|
||||
return premul(c1) * cov + premul(c2) * (1.0f - cov);
|
||||
}
|
||||
|
||||
// dash returns how much of a dashed border shows at p: each side, which
|
||||
// the pixel belongs to when it is nearest that side's edge in widths of
|
||||
// its border, has an odd number of dashes and gaps of equal length, about
|
||||
// three widths, starting and ending with a dash.
|
||||
float dash(float2 p, float4 rect, float4 w) {
|
||||
float2 q = p - rect.xy;
|
||||
float dt = w.x > 0.0f ? q.y / w.x : 1e9f;
|
||||
float dr = w.y > 0.0f ? (rect.z - q.x) / w.y : 1e9f;
|
||||
float db = w.z > 0.0f ? (rect.w - q.y) / w.z : 1e9f;
|
||||
float dl = w.w > 0.0f ? q.x / w.w : 1e9f;
|
||||
float s, len, bw;
|
||||
if (dt <= dr && dt <= db && dt <= dl) {
|
||||
s = q.x;
|
||||
len = rect.z;
|
||||
bw = w.x;
|
||||
} else if (dr <= db && dr <= dl) {
|
||||
s = q.y;
|
||||
len = rect.w;
|
||||
bw = w.y;
|
||||
} else if (db <= dl) {
|
||||
s = rect.z - q.x;
|
||||
len = rect.z;
|
||||
bw = w.z;
|
||||
} else {
|
||||
s = rect.w - q.y;
|
||||
len = rect.w;
|
||||
bw = w.w;
|
||||
}
|
||||
// n - 1 is how many periods of a dash and a gap, six widths, fit in
|
||||
// len: GPUs divide less exactly than CPUs, and may count one too few
|
||||
// or too many where len is a whole number of periods, as sides often
|
||||
// are, so the count is checked by multiplying back.
|
||||
float n = max(1.0f, floor((len / (3.0f * bw) + 1.0f) * 0.5f + 0.5f));
|
||||
float period = 6.0f * bw;
|
||||
n += n * period <= len ? 1.0f : 0.0f;
|
||||
n -= (n - 1.0f) * period > len ? 1.0f : 0.0f;
|
||||
float seg = len / (2.0f * n - 1.0f);
|
||||
float k = floor(s / seg);
|
||||
float f = s - k * seg;
|
||||
float edge = min(f, seg - f);
|
||||
return coverage(k - 2.0f * floor(k * 0.5f) < 0.5f ? -edge : edge);
|
||||
}
|
||||
|
||||
fragment PSOut ps(VSOut v [[stage_in]], const device Inst *insts [[buffer(0)]],
|
||||
constant float4 &globals [[buffer(1)]], texture2d<float> maskTex [[texture(0)]],
|
||||
texture2d<float> colorTex [[texture(1)]], texture2d<float> imageTex [[texture(2)]],
|
||||
texture2d<float> clipTex [[texture(4)]], texture2d<float> stopsTex [[texture(9)]],
|
||||
texture2d<float> chromaTex [[texture(10)]], sampler samp [[sampler(0)]]) {
|
||||
Inst i = insts[v.inst];
|
||||
float2 dtex = fwidth(v.tex);
|
||||
float kind = i.params.x;
|
||||
// A plain fill (solid, not transformed, no border) is the first case of the
|
||||
// chain below, without what the other kinds need before it.
|
||||
float4 res = float4(0.0f);
|
||||
if (kPlain && (!kGeneral || (kind < 0.5f && i.transform0.w < 0.5f && i.params.z < 0.5f && !any(i.uv > 0.0f)))) {
|
||||
res = premul(i.color) * rectCoverage(v.p, i.rect, i.radii);
|
||||
} else if (kGeneral) {
|
||||
Frame fr = frameOf(v, i);
|
||||
bool wide = globals.z > 0.5f;
|
||||
float glyphCov = kTransformed && i.transform0.w > 0.5f ? localCoverage(v.p, i.rect, float4(0.0f), 1.0f, fr) : 1.0f;
|
||||
if (kFill && kind < 0.5f) {
|
||||
float outer = localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr);
|
||||
// params.y: 1 dashes the border, 2 paints it with the gradient
|
||||
// (the inside with plain color), 3 both.
|
||||
bool borderPaint = i.params.y > 1.5f;
|
||||
float4 pc = paint(v.p, i.params.z, i.rect, i.color, i.color2, i.grad, wide, stopsTex);
|
||||
res = (borderPaint ? premul(i.color) : pc) * outer;
|
||||
float4 bw = i.uv; // top, right, bottom, left
|
||||
if (any(bw > 0.0f)) {
|
||||
float4 ir = float4(i.rect.xy + bw.wx, i.rect.zw - bw.yz - bw.wx);
|
||||
float innerCov =
|
||||
(ir.z > 0.0f && ir.w > 0.0f) ? localCoverage(v.p, ir, i.inner, i.transform0.w, fr) : 0.0f;
|
||||
float bc = saturate(outer - innerCov);
|
||||
float dashed = i.params.y - (borderPaint ? 2.0f : 0.0f);
|
||||
if (dashed > 0.5f) {
|
||||
bc *= dash(v.p, i.rect, bw);
|
||||
}
|
||||
float4 b = (borderPaint ? pc * float4(i.border.rgb * i.border.a, i.border.a) : premul(i.border)) * bc;
|
||||
res = b + res * (1.0f - b.a);
|
||||
}
|
||||
} else if (kShadow && kind < 1.5f && i.params.y > 0.5f) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float sigma = i.params.z;
|
||||
float hole = 0.0f;
|
||||
if (i.uv.z > 0.0f && i.uv.w > 0.0f) {
|
||||
hole = sigma > 0.0f ? boxShadow(v.p, i.uv, sigma, i.inner)
|
||||
: localCoverage(v.p, i.uv, i.inner, i.transform0.w, fr);
|
||||
}
|
||||
res = premul(i.color) * (localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr) * (1.0f - hole));
|
||||
} else if (kShadow && kind < 1.5f) {
|
||||
float sigma = i.params.z;
|
||||
float s = sigma > 0.0f ? boxShadow(v.p, i.rect, sigma, i.radii)
|
||||
: localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr);
|
||||
if (i.uv.z > 0.0f && i.uv.w > 0.0f) {
|
||||
s *= 1.0f - localCoverage(v.p, i.uv, i.inner, i.transform0.w, fr); // outside the box casting it
|
||||
}
|
||||
res = premul(i.color) * s;
|
||||
} else if (kGlyph && kind < 2.5f) {
|
||||
float4 c = paint(v.p, i.params.z, i.rect, i.color, i.color2, i.grad, wide, stopsTex);
|
||||
res = c *
|
||||
textCoverage(sampleLocal(maskTex, samp, v.tex, i.uv, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
} else if (kImage && kind < 3.5f) {
|
||||
res = sampleLocal(colorTex, samp, v.tex, i.uv, i.transform0.w) * i.color.a * glyphCov;
|
||||
} else if (kImage && kind < 4.5f) {
|
||||
if (i.params.y > 1.5f) {
|
||||
// A frame of video: its luma and its chroma (texture 10),
|
||||
// converted.
|
||||
float code = i.params.y - 2.0f;
|
||||
float gray = code > 7.5f ? 1.0f : 0.0f;
|
||||
// The chroma covers twice its size in luma, a column or
|
||||
// row more than an odd size has.
|
||||
float2 cs = float2(imageTex.get_width(), imageTex.get_height()) /
|
||||
(2.0f * float2(chromaTex.get_width(), chromaTex.get_height()));
|
||||
res = float4(yuvToRGB(sampleImage(imageTex, samp, v.tex, i.uv, i.params.z, dtex).r,
|
||||
sampleImage(chromaTex, samp, v.tex * cs, i.uv * cs.xyxy, i.params.z, dtex * cs).rg,
|
||||
code - 8.0f * gray),
|
||||
1.0f);
|
||||
if (gray > 0.5f) {
|
||||
res.rgb = float3(dot(res.rgb, float3(0.2126f, 0.7152f, 0.0722f)));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(imageTex, samp, v.tex, i.uv, i.params.z, dtex);
|
||||
if (i.params.y > 0.5f) {
|
||||
res.rgb = float3(dot(res.rgb, float3(0.2126f, 0.7152f, 0.0722f)));
|
||||
}
|
||||
}
|
||||
res = tint(res, i.color) * localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr);
|
||||
} else if (kSubpixel) {
|
||||
float4 c = paint(v.p, i.params.z, i.rect, i.color, i.color2, i.grad, wide, stopsTex);
|
||||
float3 straight = unpremul(c);
|
||||
if (kTransformed && i.transform0.w > 0.5f) {
|
||||
float3 rgb = sampleLocal(colorTex, samp, v.tex, i.uv, 1.0f).rgb;
|
||||
res = c * textCoverage((rgb.r + rgb.g + rgb.b) / 3.0f, straight, i.inner.x, i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
res *= clipCoverage(v, i, clipTex, samp) * i.params.w;
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
float3 a = subpixelCoverage(sampleLocal(colorTex, samp, v.tex, i.uv, i.transform0.w).rgb, straight,
|
||||
i.inner.x, i.inner.y, i.radii);
|
||||
float3 w = a * c.a * clipCoverage(v, i, clipTex, samp) * i.params.w;
|
||||
float wa = (w.r + w.g + w.b) / 3.0f;
|
||||
return PSOut{float4(straight * w, wa), float4(w, wa)};
|
||||
}
|
||||
}
|
||||
float clip = clipCoverage(v, i, clipTex, samp);
|
||||
res *= clip * i.params.w;
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
|
||||
// The passes computing the backdrop of an effect draw a quad over their
|
||||
// target, scissored to the texels they compute.
|
||||
// A pass computing the backdrop of an effect (see package gpu).
|
||||
struct Pass {
|
||||
int2 origin; // down: the first pixel of the area read, in the frame
|
||||
int2 limit; // the last texel that may be read: in the frame for down
|
||||
int2 shift; // down: subtracted from frame pixels to read the source
|
||||
int2 dir; // blur: along rows (1, 0) or columns (0, 1)
|
||||
int down; // down: the size of the squares averaged
|
||||
int radius; // blur: how far it reaches each way
|
||||
float sigma; // blur: its standard deviation, 0 for none
|
||||
int mode; // 1: transparent beyond the area or the texels (gpu.PassClear)
|
||||
};
|
||||
|
||||
struct PassVSOut {
|
||||
float4 pos [[position]];
|
||||
};
|
||||
|
||||
vertex PassVSOut passVS(uint vid [[vertex_id]]) {
|
||||
float2 corner = float2(float(vid & 1u), float(vid >> 1u));
|
||||
PassVSOut o;
|
||||
o.pos = float4(corner * 2.0f - 1.0f, 0.0f, 1.0f);
|
||||
return o;
|
||||
}
|
||||
|
||||
// down averages the square of the area that texel stands for, repeating
|
||||
// the area's last pixels past its far edges, or, for an image blurred
|
||||
// (mode 1), reading them as transparent.
|
||||
fragment float4 down(PassVSOut v [[stage_in]], texture2d<float> src [[texture(0)]],
|
||||
constant Pass &p [[buffer(0)]]) {
|
||||
int2 o = p.origin + int2(v.pos.xy) * p.down;
|
||||
float4 c = float4(0.0f);
|
||||
for (int y = 0; y < p.down; y++) {
|
||||
for (int x = 0; x < p.down; x++) {
|
||||
int2 at = o + int2(x, y);
|
||||
if ((p.mode & 1) != 0 && (at.x > p.limit.x || at.y > p.limit.y)) {
|
||||
continue;
|
||||
}
|
||||
c += src.read(uint2(min(at, p.limit) - p.shift));
|
||||
}
|
||||
}
|
||||
return c * (1.0f / float(p.down * p.down));
|
||||
}
|
||||
|
||||
// blur blurs along a row or a column, clamping at its ends, or, for an
|
||||
// image blurred (mode 1), transparent beyond them.
|
||||
fragment float4 blur(PassVSOut v [[stage_in]], texture2d<float> src [[texture(0)]],
|
||||
constant Pass &p [[buffer(0)]]) {
|
||||
int2 at = int2(v.pos.xy);
|
||||
float4 c = float4(0.0f);
|
||||
float sum = 0.0f;
|
||||
for (int o = -p.radius; o <= p.radius; o++) {
|
||||
float x = float(o);
|
||||
float w = p.sigma > 0.0f ? exp(-(x * x) / (2.0f * p.sigma * p.sigma)) : 1.0f;
|
||||
int2 q = at + p.dir * o;
|
||||
sum += w;
|
||||
if ((p.mode & 1) != 0 && (any(q < int2(0)) || any(q > p.limit))) {
|
||||
continue;
|
||||
}
|
||||
c += src.read(uint2(clamp(q, int2(0), p.limit))) * w;
|
||||
}
|
||||
return c / sum;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
// The tail of a shader's library (package ui/shader), after the head of
|
||||
// effect.metal and the shader's code, which ends with shaderMain: Metal
|
||||
// has no global variables, so a shader's uniforms (buffer 2) and images
|
||||
// (textures 5 to 8) come to the fragment function, which passes them on.
|
||||
// Instances with 1 in params.y are mask glyphs it fills, read from the
|
||||
// mask atlas (texture 0). shaderMain reads what the shader reads of a
|
||||
// quad of those one draw draws (DrawInstances) from the instance.
|
||||
|
||||
fragment PSOut shader_ps(VSOut v [[stage_in]], const device Inst *insts [[buffer(0)]],
|
||||
constant float4 &globals [[buffer(1)]], constant Uniforms &uniforms [[buffer(2)]],
|
||||
texture2d<float> T0 [[texture(5)]], texture2d<float> T1 [[texture(6)]],
|
||||
texture2d<float> T2 [[texture(7)]], texture2d<float> T3 [[texture(8)]],
|
||||
texture2d<float> clipTex [[texture(4)]], texture2d<float> maskTex [[texture(0)]],
|
||||
sampler samp [[sampler(0)]]) {
|
||||
Inst i = insts[v.inst];
|
||||
Frame fr = frameOf(v, i);
|
||||
if (i.params.y > 0.5f) {
|
||||
// A mask glyph the shader fills (scene.EffectOp.Glyphs), as ps
|
||||
// draws one, its paint the shader's color, its positions from
|
||||
// the box's corner in i.grad.
|
||||
float4 c = shaderMain(uniforms, T0, T1, T2, T3, v.p, float4(i.grad.xy, i.rect.zw), i);
|
||||
float glyphCov = i.transform0.w > 0.5f ? localCoverage(v.p, i.rect, float4(0.0f), 1.0f, fr) : 1.0f;
|
||||
float4 res = c *
|
||||
(textCoverage(sampleLocal(maskTex, samp, v.tex, i.uv, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov * clipCoverage(v, i, clipTex, samp) * i.params.w);
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
float4 res = shaderMain(uniforms, T0, T1, T2, T3, v.p, i.rect, i) *
|
||||
(localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr) * clipCoverage(v, i, clipTex, samp) * i.params.w);
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
+3217
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
package metal
|
||||
|
||||
import "os"
|
||||
|
||||
// shaderLibrary is the library compiled for where the app runs: the
|
||||
// simulator sets SIMULATOR_DEVICE_NAME in its apps' environment.
|
||||
var shaderLibrary = func() []byte {
|
||||
if os.Getenv("SIMULATOR_DEVICE_NAME") != "" {
|
||||
return shaderLibrarySimulator
|
||||
}
|
||||
return shaderLibraryDevice
|
||||
}()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,665 @@
|
||||
// The one shader of the Metal renderer, as shader.hlsl is the Direct3D
|
||||
// one: every scene op is an instanced quad, and the fragment shader
|
||||
// computes the coverage of rounded rectangles, borders, gradients, stripes
|
||||
// and shadows from signed distances, as the CPU renderer (internal/raster)
|
||||
// does. Colors are straight (not premultiplied) and blending happens in
|
||||
// sRGB space, as in browsers, with a second color for the source's alpha
|
||||
// of each channel, which subpixel glyphs need. go generate compiles it
|
||||
// into shaderlib.go. The libraries of effects (scene.Effect) take its
|
||||
// start, with EFFECT defined, before effect.metal.
|
||||
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
|
||||
// One instance per op, as internal/gpu builds them.
|
||||
struct Inst {
|
||||
float4 rect; // x, y, width, height in pixels
|
||||
float4 radii; // top-left, top-right, bottom-right, bottom-left
|
||||
float4 inner; // radii of the border's inner edge, of the box casting a shadow, or of an inner shadow's hole
|
||||
float4 color;
|
||||
float4 color2; // gradient end
|
||||
float4 border; // border color
|
||||
float4 grad; // gradient start and end points, or stripes
|
||||
float4 uv; // texture rectangle, normalized, border widths, the box casting a shadow, or an inner shadow's hole
|
||||
float4 clip; // the innermost clip rectangle
|
||||
float4 clipRadii;
|
||||
float4 params; // kind, dashed or grayscale, sigma or paint, opacity
|
||||
float4 transform0, transform1; // local-to-frame rows, AA and clip-mask flags
|
||||
float4 transform2; // the projective row's g and h
|
||||
};
|
||||
|
||||
// The color and, for dual-source blending, the source's alpha of each
|
||||
// channel.
|
||||
struct PSOut {
|
||||
float4 color [[color(0), index(0)]];
|
||||
float4 alpha [[color(0), index(1)]];
|
||||
};
|
||||
|
||||
struct VSOut {
|
||||
float4 pos [[position]];
|
||||
float2 p;
|
||||
// The frame point times its projective divisor, and the divisor: they
|
||||
// interpolate in perspective to what divides into the frame point.
|
||||
float3 world;
|
||||
float2 tex;
|
||||
uint inst [[flat]];
|
||||
};
|
||||
|
||||
// frameH returns the frame point of local p, in homogeneous coordinates.
|
||||
float3 frameH(Inst i, float2 p) {
|
||||
return float3(dot(i.transform0.xyz, float3(p, 1.0f)), dot(i.transform1.xyz, float3(p, 1.0f)),
|
||||
dot(float3(i.transform2.xy, 1.0f), float3(p, 1.0f)));
|
||||
}
|
||||
|
||||
// globals holds the frame's width and height in pixels, and 1 in z when
|
||||
// its target keeps colors outside the sRGB gamut (extended sRGB, float16).
|
||||
vertex VSOut vs(uint vid [[vertex_id]], uint iid [[instance_id]], const device Inst *insts [[buffer(0)]],
|
||||
constant float4 &globals [[buffer(1)]]) {
|
||||
Inst i = insts[iid];
|
||||
float2 corner = float2(float(vid & 1u), float(vid >> 1u));
|
||||
float4 r = i.rect;
|
||||
float kind = i.params.x;
|
||||
if (kind < 0.5f || kind > 5.5f) { // fills and effects
|
||||
r = float4(r.xy - 1.0f, r.zw + 2.0f);
|
||||
} else if (kind < 1.5f) {
|
||||
float e = 3.0f * i.params.z + 1.0f;
|
||||
r = float4(r.xy - e, r.zw + 2.0f * e);
|
||||
}
|
||||
float3 h = frameH(i, r.xy + corner * r.zw);
|
||||
if (i.transform0.w > 0.5f && h.z > 0.0f) {
|
||||
// A pixel's reach at this corner, by the map's Jacobian there.
|
||||
float2 s = h.xy / h.z;
|
||||
float a = (i.transform0.x - s.x * i.transform2.x) / h.z, c = (i.transform0.y - s.x * i.transform2.y) / h.z;
|
||||
float b = (i.transform1.x - s.y * i.transform2.x) / h.z, d = (i.transform1.y - s.y * i.transform2.y) / h.z;
|
||||
float2 e = float2(abs(d) + abs(c), abs(b) + abs(a)) / abs(a * d - b * c);
|
||||
r = float4(r.xy - e, r.zw + 2.0f * e);
|
||||
}
|
||||
float2 p = r.xy + corner * r.zw;
|
||||
h = frameH(i, p);
|
||||
VSOut o;
|
||||
o.pos = float4(h.xy / globals.xy * float2(2.0f, -2.0f) + h.z * float2(-1.0f, 1.0f), 0.0f, h.z);
|
||||
o.p = p;
|
||||
o.world = h;
|
||||
o.tex = i.uv.xy + (p - i.rect.xy) / i.rect.zw * (i.uv.zw - i.uv.xy);
|
||||
o.inst = iid;
|
||||
return o;
|
||||
}
|
||||
|
||||
float sdRoundRect(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5f;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0f ? (q.y < 0.0f ? radii.x : radii.w) : (q.y < 0.0f ? radii.y : radii.z);
|
||||
float2 a = abs(q) - h + r;
|
||||
return length(max(a, float2(0.0f))) + min(max(a.x, a.y), 0.0f) - r;
|
||||
}
|
||||
|
||||
float coverage(float d) { return saturate(0.5f - d); }
|
||||
|
||||
// Continuous corners are Core Animation's, as internal/raster/corner.go
|
||||
// explains: a corner of radius r whose curve leaves the edges e from it,
|
||||
// blended toward a quarter circle by cx along its horizontal edge and cy
|
||||
// along its vertical one, its curve's box ending at eff as clamped.
|
||||
constant float contExtent = 1.528665f;
|
||||
|
||||
struct ContCorner {
|
||||
float r, e, eff, cx, cy;
|
||||
};
|
||||
|
||||
// contCorner returns the corner of radius r of a rectangle w×h sharing
|
||||
// its horizontal edge with a corner of radius rh, its vertical one with
|
||||
// one of radius rv.
|
||||
ContCorner contCorner(float r, float rh, float rv, float w, float h) {
|
||||
ContCorner c;
|
||||
c.r = r;
|
||||
c.e = contExtent * r;
|
||||
c.cx = saturate((contExtent - w / max(r + rh, 1e-6f)) / (contExtent - 1.0f));
|
||||
c.cy = saturate((contExtent - h / max(r + rv, 1e-6f)) / (contExtent - 1.0f));
|
||||
c.eff = c.e + (r - c.e) * max(c.cx, c.cy);
|
||||
return c;
|
||||
}
|
||||
|
||||
// contDist returns the corner's value at the point u inside its vertical
|
||||
// edge and v inside its horizontal one: about the signed distance to its
|
||||
// edge near it.
|
||||
float contDist(ContCorner c, float u, float v) {
|
||||
float2 a = max(0.0f, 1.0f - float2(u, v) / c.e);
|
||||
float l = length(a);
|
||||
float hi = max(a.x, a.y);
|
||||
float rho = hi > 0.0f ? min(min(a.x, a.y) / hi, 1.0f) : 0.0f;
|
||||
float p = (((-0.926054f * rho + 3.15601f) * rho - 3.64122f) * rho + 1.26803f) * rho + 0.268531f;
|
||||
float f1 = l + 1.0f - 1.0f / (1.0f - rho * rho * min(l, 1.0f) * p);
|
||||
float f2 = length(max(0.0f, a * contExtent - (contExtent - 1.0f))) * 0.654166f + 0.345834f;
|
||||
float s = a.y > a.x ? 1.0f : -1.0f;
|
||||
float w = saturate(0.5f - s + s * rho);
|
||||
float fx = f1 + (f2 - f1) * c.cx, fy = f1 + (f2 - f1) * c.cy;
|
||||
return min(max(c.eff - u, c.eff - v), 0.0f) + c.e * (fx + (fy - fx) * w - 1.0f);
|
||||
}
|
||||
|
||||
// contInset returns how far inside its vertical edge the corner's edge is
|
||||
// v inside its horizontal one, which lies between the quarter circles of
|
||||
// radius r and e, by regula falsi (Illinois).
|
||||
float contInset(ContCorner c, float v) {
|
||||
if (v >= c.e || c.r <= 0.0f) {
|
||||
return 0.0f;
|
||||
}
|
||||
float lo = v < c.r ? c.r - sqrt(v * (2.0f * c.r - v)) : 0.0f;
|
||||
float hi = c.e - sqrt(v * (2.0f * c.e - v));
|
||||
float dlo = contDist(c, lo, v), dhi = contDist(c, hi, v);
|
||||
if (dlo <= 0.0f) {
|
||||
return lo;
|
||||
}
|
||||
if (dhi >= 0.0f) {
|
||||
return hi;
|
||||
}
|
||||
int side = 0;
|
||||
for (int n = 0; n < 5; n++) {
|
||||
float m = (lo * dhi - hi * dlo) / (dhi - dlo);
|
||||
float dm = contDist(c, m, v);
|
||||
if (dm > 0.0f) {
|
||||
lo = m;
|
||||
dlo = dm;
|
||||
if (side == 1) {
|
||||
dhi *= 0.5f;
|
||||
}
|
||||
side = 1;
|
||||
} else {
|
||||
hi = m;
|
||||
dhi = dm;
|
||||
if (side == -1) {
|
||||
dlo *= 0.5f;
|
||||
}
|
||||
side = -1;
|
||||
}
|
||||
}
|
||||
return (lo * dhi - hi * dlo) / (dhi - dlo);
|
||||
}
|
||||
|
||||
// areaCoverage returns the area of the pixel at p inside the rectangle,
|
||||
// near square corners: exact for lines thinner than a pixel too.
|
||||
float areaCoverage(float2 p, float4 rect) {
|
||||
float2 c = saturate(min(rect.xy + rect.zw, p + 0.5f) - max(rect.xy, p - 0.5f));
|
||||
return c.x * c.y;
|
||||
}
|
||||
|
||||
// contValue returns the value of a rectangle with continuous corners c at
|
||||
// p, the largest of its corners' and its signed distance, and whether a
|
||||
// corner's curve reaches p.
|
||||
float contValue(float2 p, float4 rect, thread const ContCorner *c, thread bool &curved) {
|
||||
float4 d = float4(p - rect.xy, rect.xy + rect.zw - p); // left, top, right, bottom
|
||||
float4 u = d.xzzx, v = d.yyww;
|
||||
float value = max(max(-d.x, -d.y), max(-d.z, -d.w));
|
||||
curved = false;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
if (c[i].r > 0.0f && u[i] < c[i].e && v[i] < c[i].e) {
|
||||
value = max(value, contDist(c[i], u[i], v[i]));
|
||||
curved = true;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// contCoverage is rectCoverage with continuous corners of radii r: away
|
||||
// from their curves, the area of the pixel inside the rectangle; near
|
||||
// them, the value over the sum of its derivatives, as Core Animation
|
||||
// antialiases.
|
||||
float contCoverage(float2 p, float4 rect, float4 r) {
|
||||
ContCorner c[4] = {
|
||||
contCorner(r.x, r.y, r.w, rect.z, rect.w),
|
||||
contCorner(r.y, r.x, r.z, rect.z, rect.w),
|
||||
contCorner(r.z, r.w, r.y, rect.z, rect.w),
|
||||
contCorner(r.w, r.z, r.x, rect.z, rect.w),
|
||||
};
|
||||
bool curved, ignored;
|
||||
float d = contValue(p, rect, c, curved);
|
||||
if (!curved) {
|
||||
return areaCoverage(p, rect);
|
||||
}
|
||||
if (abs(d) > 2.0f) {
|
||||
return d < 0.0f ? 1.0f : 0.0f;
|
||||
}
|
||||
const float h = 1.0f / 16.0f;
|
||||
float dx = contValue(p + float2(h, 0.0f), rect, c, ignored);
|
||||
float dy = contValue(p + float2(0.0f, h), rect, c, ignored);
|
||||
return saturate(0.5f - d * h / max(abs(dx - d) + abs(dy - d), 1e-6f));
|
||||
}
|
||||
|
||||
// rectCoverage returns how much of the pixel at p a rounded rectangle
|
||||
// covers: by the distance to its edge near rounded corners, and exactly,
|
||||
// the area of the pixel inside it, near square ones. Negative radii are
|
||||
// continuous corners.
|
||||
float rectCoverage(float2 p, float4 rect, float4 radii) {
|
||||
if (any(radii < 0.0f)) {
|
||||
return contCoverage(p, rect, -radii);
|
||||
}
|
||||
float2 q = p - rect.xy - rect.zw * 0.5f;
|
||||
float r = q.x < 0.0f ? (q.y < 0.0f ? radii.x : radii.w) : (q.y < 0.0f ? radii.y : radii.z);
|
||||
if (r > 0.0f) {
|
||||
return coverage(sdRoundRect(p, rect, radii));
|
||||
}
|
||||
return areaCoverage(p, rect);
|
||||
}
|
||||
|
||||
// Coverage is integrated in device space, matching the CPU compositor.
|
||||
float localValue(float2 p, float4 rect, float4 r) {
|
||||
if (!any(r < 0.0f))
|
||||
return sdRoundRect(p, rect, r);
|
||||
r = abs(r);
|
||||
ContCorner c[4] = {contCorner(r.x, r.y, r.w, rect.z, rect.w), contCorner(r.y, r.x, r.z, rect.z, rect.w),
|
||||
contCorner(r.z, r.w, r.y, rect.z, rect.w), contCorner(r.w, r.z, r.x, rect.z, rect.w)};
|
||||
bool curved;
|
||||
return contValue(p, rect, c, curved);
|
||||
}
|
||||
// Frame is where a fragment is in the frame, s, and, when its instance's
|
||||
// map is projective (persp), the columns of the map back, up to a factor.
|
||||
struct Frame {
|
||||
float2 s;
|
||||
float3 c0, c1, c2;
|
||||
bool persp;
|
||||
};
|
||||
Frame frameOf(VSOut v, Inst i) {
|
||||
Frame f;
|
||||
f.persp = any(i.transform2.xy != 0.0f);
|
||||
// In perspective, the pixel's center, as interpolating drifts.
|
||||
f.s = f.persp ? v.pos.xy : v.world.xy / v.world.z;
|
||||
float3 r0 = i.transform0.xyz, r1 = i.transform1.xyz, r2 = float3(i.transform2.xy, 1.0f);
|
||||
f.c0 = cross(r1, r2);
|
||||
f.c1 = cross(r2, r0);
|
||||
f.c2 = cross(r0, r1);
|
||||
return f;
|
||||
}
|
||||
// localOf returns the point of the instance that shows at the frame's s.
|
||||
float2 localOf(Frame f, float2 s) {
|
||||
float3 q = f.c0 * s.x + f.c1 * s.y + f.c2;
|
||||
return q.xy / q.z;
|
||||
}
|
||||
float localCoverage(float2 p, float4 rect, float4 radii, float affine, Frame fr) {
|
||||
if (affine < 0.5f)
|
||||
return rectCoverage(p, rect, radii);
|
||||
float2 dx = dfdx(p), dy = dfdy(p);
|
||||
if (fr.persp) {
|
||||
// In perspective, each sample where the CPU renderer takes it.
|
||||
p = localOf(fr, fr.s);
|
||||
dx = localOf(fr, fr.s + float2(0.5f, 0.5f)) - p;
|
||||
dy = localOf(fr, fr.s + float2(0.5f, -0.5f)) - p;
|
||||
float reach = max(abs(dx.x) + abs(dx.y), abs(dy.x) + abs(dy.y)) * 2.0f;
|
||||
float d = localValue(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0f;
|
||||
if (d > reach)
|
||||
return 0.0f;
|
||||
float n = 0.0f;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
float2 q = localOf(fr, fr.s + float2((float(x) + 0.5f) / 4.0f - 0.5f, (float(y) + 0.5f) / 4.0f - 0.5f));
|
||||
n += localValue(q, rect, radii) <= 0.0f ? 1.0f : 0.0f;
|
||||
}
|
||||
return n / 16.0f;
|
||||
}
|
||||
float2 a = (dx + dy) * 0.5f, b = (dx - dy) * 0.5f;
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2.0f;
|
||||
float d = localValue(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0f;
|
||||
if (d > reach)
|
||||
return 0.0f;
|
||||
float n = 0.0f;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
float2 q = p + dx * ((float(x) + 0.5f) / 4.0f - 0.5f) + dy * ((float(y) + 0.5f) / 4.0f - 0.5f);
|
||||
n += localValue(q, rect, radii) <= 0.0f ? 1.0f : 0.0f;
|
||||
}
|
||||
return n / 16.0f;
|
||||
}
|
||||
float clipCoverage(VSOut v, Inst i, texture2d<float> mask, sampler samp) {
|
||||
Frame fr = frameOf(v, i);
|
||||
float2 world = fr.s;
|
||||
if (i.transform1.w < 0.5f)
|
||||
return rectCoverage(world, i.clip, i.clipRadii);
|
||||
if (i.transform1.w > 1.5f)
|
||||
return localCoverage(v.p, i.clip, float4(0.0f), i.transform0.w, fr) *
|
||||
mask.sample(samp, (world - i.clipRadii.xy) / i.clipRadii.zw).a;
|
||||
return mask.sample(samp, (world - i.clip.xy) / i.clip.zw).a;
|
||||
}
|
||||
float4 sampleLocal(texture2d<float> t, sampler samp, float2 uv, float4 src, float affine) {
|
||||
if (affine > 0.5f) {
|
||||
float2 halfPixel = 0.5f / float2(t.get_width(), t.get_height());
|
||||
uv = clamp(uv, src.xy + halfPixel, src.zw - halfPixel);
|
||||
}
|
||||
return t.sample(samp, uv);
|
||||
}
|
||||
|
||||
// sampleImage samples an image held inside src, which is reversed along
|
||||
// an axis it flips, so that a part of a sheet shows none of its
|
||||
// neighbors; where pixelated is set, as pixel art draws, each texel a
|
||||
// square of its color whose edges blend with the next only across the
|
||||
// pixel they cross (Ebitengine's FilterPixelated): nearest where it shows
|
||||
// at whole multiples of its size, and texels of even widths with smooth
|
||||
// edges at any other. dtex is the fwidth of uv, taken where every
|
||||
// fragment of the quad takes it.
|
||||
float4 sampleImage(texture2d<float> t, sampler samp, float2 uv, float4 src, float pixelated, float2 dtex) {
|
||||
float2 size = float2(t.get_width(), t.get_height());
|
||||
float2 lo = min(src.xy, src.zw), hi = max(src.xy, src.zw);
|
||||
if (pixelated > 0.5f) {
|
||||
float2 tc = uv * size - 0.5f;
|
||||
float2 i = floor(tc);
|
||||
float2 f = saturate((tc - i - 0.5f) / clamp(dtex * size, 1e-5f, 1.0f) + 0.5f);
|
||||
uv = (i + f + 0.5f) / size;
|
||||
}
|
||||
return t.sample(samp, clamp(uv, lo + 0.5f / size, hi - 0.5f / size));
|
||||
}
|
||||
|
||||
// tint multiplies premultiplied c by straight color t.
|
||||
float4 tint(float4 c, float4 t) { return c * float4(t.rgb * t.a, t.a); }
|
||||
|
||||
float4 premul(float4 c) { return float4(c.rgb * c.a, c.a); }
|
||||
|
||||
float3 unpremul(float4 c) { return c.a > 0.0f ? c.rgb / c.a : float3(0.0f); }
|
||||
|
||||
// What follows is the renderer's own; effects (effect.metal) take what is
|
||||
// above.
|
||||
#ifndef EFFECT
|
||||
|
||||
// textCoverage corrects the coverage a of a glyph of straight color c as
|
||||
// Direct2D blends text (scene.TextCoverage): it enhances the contrast,
|
||||
// the more the darker c is, and corrects for gamma with the ratios g.
|
||||
float textCoverage(float a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3.0f - 4.0f * dot(c, float3(0.30f, 0.59f, 0.11f))) + boost;
|
||||
a = a * (k + 1.0f) / (a * k + 1.0f);
|
||||
float f = dot(c, float3(0.25f, 0.5f, 0.25f));
|
||||
return saturate(a + a * (1.0f - a) * ((g.x * f + g.y) * a + (g.z * f + g.w)));
|
||||
}
|
||||
|
||||
// subpixelCoverage does the same for each subpixel of a subpixel glyph.
|
||||
float3 subpixelCoverage(float3 a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3.0f - 4.0f * dot(c, float3(0.30f, 0.59f, 0.11f))) + boost;
|
||||
a = a * (k + 1.0f) / (a * k + 1.0f);
|
||||
return saturate(a + a * (1.0f - a) * ((g.x * c + g.y) * a + (g.z * c + g.w)));
|
||||
}
|
||||
|
||||
// erf2 approximates the error function (Abramowitz and Stegun 7.1.27).
|
||||
float2 erf2(float2 x) {
|
||||
float2 s = sign(x);
|
||||
float2 a = abs(x);
|
||||
x = 1.0f + (0.278393f + (0.230389f + 0.078108f * (a * a)) * a) * a;
|
||||
x *= x;
|
||||
return s - s / (x * x);
|
||||
}
|
||||
|
||||
float gaussian(float x, float sigma) {
|
||||
return exp(-(x * x) / (2.0f * sigma * sigma)) / (2.50662827463f * sigma);
|
||||
}
|
||||
|
||||
// The blurred rounded box of Evan Wallace: exact along x, four samples
|
||||
// along y; cc is its continuous corner, if any.
|
||||
float shadowX(float x, float y, float sigma, float corner, float2 h, bool continuous, ContCorner cc) {
|
||||
float curved;
|
||||
if (continuous) {
|
||||
float v = h.y - abs(y);
|
||||
curved = v < cc.e ? h.x - contInset(cc, v) : h.x;
|
||||
} else {
|
||||
float delta = min(h.y - corner - abs(y), 0.0f);
|
||||
curved = h.x - corner + sqrt(max(0.0f, corner * corner - delta * delta));
|
||||
}
|
||||
float2 integral = 0.5f + 0.5f * erf2((x + float2(-curved, curved)) * (sqrt(0.5f) / sigma));
|
||||
return integral.y - integral.x;
|
||||
}
|
||||
|
||||
float boxShadow(float2 p, float4 rect, float sigma, float4 radii) {
|
||||
float4 r = abs(radii);
|
||||
float corner = max(max(r.x, r.y), max(r.z, r.w));
|
||||
bool continuous = any(radii < 0.0f) && corner > 0.0f;
|
||||
ContCorner cc = contCorner(corner, corner, corner, rect.z, rect.w);
|
||||
float2 h = rect.zw * 0.5f;
|
||||
p -= rect.xy + h;
|
||||
float low = p.y - h.y;
|
||||
float high = p.y + h.y;
|
||||
float from = clamp(-3.0f * sigma, low, high);
|
||||
float to = clamp(3.0f * sigma, low, high);
|
||||
float dy = (to - from) / 4.0f;
|
||||
float y = from + dy * 0.5f;
|
||||
float v = 0.0f;
|
||||
for (int n = 0; n < 4; n++) {
|
||||
v += shadowX(p.x, p.y - y, sigma, corner, h, continuous, cc) * gaussian(y, sigma) * dy;
|
||||
y += dy;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
// toLinear and toSRGB mirror the curve around zero, as extended sRGB does,
|
||||
// for the components of wide colors.
|
||||
float3 toLinear(float3 c) {
|
||||
float3 a = abs(c);
|
||||
return sign(c) * select(pow((a + 0.055f) / 1.055f, float3(2.4f)), a / 12.92f, a <= 0.04045f);
|
||||
}
|
||||
|
||||
float3 toSRGB(float3 c) {
|
||||
float3 a = abs(c);
|
||||
return sign(c) * select(1.055f * pow(a, float3(1.0f / 2.4f)) - 0.055f, a * 12.92f, a <= 0.0031308f);
|
||||
}
|
||||
|
||||
float3 cbrt3(float3 v) { return sign(v) * pow(abs(v), float3(1.0f / 3.0f)); }
|
||||
|
||||
float3 oklab(float3 srgb) {
|
||||
float3 c = toLinear(srgb);
|
||||
float3 lms = cbrt3(float3(0.4122214708f * c.r + 0.5363325363f * c.g + 0.0514459929f * c.b,
|
||||
0.2119034982f * c.r + 0.6806995451f * c.g + 0.1073969566f * c.b,
|
||||
0.0883024619f * c.r + 0.2817188376f * c.g + 0.6299787005f * c.b));
|
||||
return float3(0.2104542553f * lms.x + 0.7936177850f * lms.y - 0.0040720468f * lms.z,
|
||||
1.9779984951f * lms.x - 2.4285922050f * lms.y + 0.4505937099f * lms.z,
|
||||
0.0259040371f * lms.x + 0.7827717662f * lms.y - 0.8086757660f * lms.z);
|
||||
}
|
||||
|
||||
float3 fromOklab(float3 lab) {
|
||||
float3 lms = float3(lab.x + 0.3963377774f * lab.y + 0.2158037573f * lab.z,
|
||||
lab.x - 0.1055613458f * lab.y - 0.0638541728f * lab.z,
|
||||
lab.x - 0.0894841775f * lab.y - 1.2914855480f * lab.z);
|
||||
lms = lms * lms * lms;
|
||||
return toSRGB(float3(4.0767416621f * lms.x - 3.3077115913f * lms.y + 0.2309699292f * lms.z,
|
||||
-1.2684380046f * lms.x + 2.6097574011f * lms.y - 0.3413193965f * lms.z,
|
||||
-0.0041960863f * lms.x - 0.7034186147f * lms.y + 1.7076147010f * lms.z));
|
||||
}
|
||||
|
||||
// paint returns the premultiplied color at p of plain color, a gradient
|
||||
// mixed in sRGB (1) or Oklab (2), or stripes (3), as scene.Paint says. In a
|
||||
// target that keeps colors outside the sRGB gamut (wide, extended sRGB), an
|
||||
// Oklab gradient keeps those its mix has, which others clamp.
|
||||
float4 paint(float2 p, float mode, float4 rect, float4 c1, float4 c2, float4 g, bool wide) {
|
||||
if (mode < 0.5f) {
|
||||
return premul(c1);
|
||||
}
|
||||
if (mode < 2.5f) {
|
||||
float2 d = g.zw - g.xy;
|
||||
float t = saturate(dot(p - g.xy, d) / max(dot(d, d), 0.0001f));
|
||||
float a = mix(c1.a, c2.a, t);
|
||||
if (mode < 1.5f) {
|
||||
return float4(mix(c1.rgb * c1.a, c2.rgb * c2.a, t), a);
|
||||
}
|
||||
float3 lab = mix(oklab(c1.rgb) * c1.a, oklab(c2.rgb) * c2.a, t);
|
||||
if (a <= 0.0f) {
|
||||
return float4(0.0f);
|
||||
}
|
||||
float3 rgb = fromOklab(lab / a);
|
||||
return float4((wide ? rgb : saturate(rgb)) * a, a);
|
||||
}
|
||||
float s = dot(p - rect.xy, g.xy);
|
||||
float phase = s - g.w * floor(s / g.w);
|
||||
float cov = coverage(min(max(-phase, phase - g.z), g.w - phase));
|
||||
return premul(c1) * cov + premul(c2) * (1.0f - cov);
|
||||
}
|
||||
|
||||
// dash returns how much of a dashed border shows at p: each side, which
|
||||
// the pixel belongs to when it is nearest that side's edge in widths of
|
||||
// its border, has an odd number of dashes and gaps of equal length, about
|
||||
// three widths, starting and ending with a dash.
|
||||
float dash(float2 p, float4 rect, float4 w) {
|
||||
float2 q = p - rect.xy;
|
||||
float dt = w.x > 0.0f ? q.y / w.x : 1e9f;
|
||||
float dr = w.y > 0.0f ? (rect.z - q.x) / w.y : 1e9f;
|
||||
float db = w.z > 0.0f ? (rect.w - q.y) / w.z : 1e9f;
|
||||
float dl = w.w > 0.0f ? q.x / w.w : 1e9f;
|
||||
float s, len, bw;
|
||||
if (dt <= dr && dt <= db && dt <= dl) {
|
||||
s = q.x;
|
||||
len = rect.z;
|
||||
bw = w.x;
|
||||
} else if (dr <= db && dr <= dl) {
|
||||
s = q.y;
|
||||
len = rect.w;
|
||||
bw = w.y;
|
||||
} else if (db <= dl) {
|
||||
s = rect.z - q.x;
|
||||
len = rect.z;
|
||||
bw = w.z;
|
||||
} else {
|
||||
s = rect.w - q.y;
|
||||
len = rect.w;
|
||||
bw = w.w;
|
||||
}
|
||||
// n - 1 is how many periods of a dash and a gap, six widths, fit in
|
||||
// len: GPUs divide less exactly than CPUs, and may count one too few
|
||||
// or too many where len is a whole number of periods, as sides often
|
||||
// are, so the count is checked by multiplying back.
|
||||
float n = max(1.0f, floor((len / (3.0f * bw) + 1.0f) * 0.5f + 0.5f));
|
||||
float period = 6.0f * bw;
|
||||
n += n * period <= len ? 1.0f : 0.0f;
|
||||
n -= (n - 1.0f) * period > len ? 1.0f : 0.0f;
|
||||
float seg = len / (2.0f * n - 1.0f);
|
||||
float k = floor(s / seg);
|
||||
float f = s - k * seg;
|
||||
float edge = min(f, seg - f);
|
||||
return coverage(k - 2.0f * floor(k * 0.5f) < 0.5f ? -edge : edge);
|
||||
}
|
||||
|
||||
fragment PSOut ps(VSOut v [[stage_in]], const device Inst *insts [[buffer(0)]],
|
||||
constant float4 &globals [[buffer(1)]], texture2d<float> maskTex [[texture(0)]],
|
||||
texture2d<float> colorTex [[texture(1)]], texture2d<float> imageTex [[texture(2)]],
|
||||
texture2d<float> clipTex [[texture(4)]], sampler samp [[sampler(0)]]) {
|
||||
Inst i = insts[v.inst];
|
||||
Frame fr = frameOf(v, i);
|
||||
float2 dtex = fwidth(v.tex);
|
||||
float kind = i.params.x;
|
||||
bool wide = globals.z > 0.5f;
|
||||
float4 res;
|
||||
float glyphCov = i.transform0.w > 0.5f ? localCoverage(v.p, i.rect, float4(0.0f), 1.0f, fr) : 1.0f;
|
||||
if (kind < 0.5f) {
|
||||
float outer = localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr);
|
||||
res = paint(v.p, i.params.z, i.rect, i.color, i.color2, i.grad, wide) * outer;
|
||||
float4 bw = i.uv; // top, right, bottom, left
|
||||
if (any(bw > 0.0f)) {
|
||||
float4 ir = float4(i.rect.xy + bw.wx, i.rect.zw - bw.yz - bw.wx);
|
||||
float innerCov =
|
||||
(ir.z > 0.0f && ir.w > 0.0f) ? localCoverage(v.p, ir, i.inner, i.transform0.w, fr) : 0.0f;
|
||||
float bc = saturate(outer - innerCov);
|
||||
if (i.params.y > 0.5f) {
|
||||
bc *= dash(v.p, i.rect, bw);
|
||||
}
|
||||
float4 b = premul(i.border) * bc;
|
||||
res = b + res * (1.0f - b.a);
|
||||
}
|
||||
} else if (kind < 1.5f && i.params.y > 0.5f) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float sigma = i.params.z;
|
||||
float hole = 0.0f;
|
||||
if (i.uv.z > 0.0f && i.uv.w > 0.0f) {
|
||||
hole = sigma > 0.0f ? boxShadow(v.p, i.uv, sigma, i.inner)
|
||||
: localCoverage(v.p, i.uv, i.inner, i.transform0.w, fr);
|
||||
}
|
||||
res = premul(i.color) * (localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr) * (1.0f - hole));
|
||||
} else if (kind < 1.5f) {
|
||||
float sigma = i.params.z;
|
||||
float s = sigma > 0.0f ? boxShadow(v.p, i.rect, sigma, i.radii)
|
||||
: localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr);
|
||||
if (i.uv.z > 0.0f && i.uv.w > 0.0f) {
|
||||
s *= 1.0f - localCoverage(v.p, i.uv, i.inner, i.transform0.w, fr); // outside the box casting it
|
||||
}
|
||||
res = premul(i.color) * s;
|
||||
} else if (kind < 2.5f) {
|
||||
float4 c = paint(v.p, i.params.z, i.rect, i.color, i.color2, i.grad, wide);
|
||||
res = c *
|
||||
textCoverage(sampleLocal(maskTex, samp, v.tex, i.uv, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
} else if (kind < 3.5f) {
|
||||
res = sampleLocal(colorTex, samp, v.tex, i.uv, i.transform0.w) * i.color.a * glyphCov;
|
||||
} else if (kind < 4.5f) {
|
||||
res = sampleImage(imageTex, samp, v.tex, i.uv, i.params.z, dtex);
|
||||
if (i.params.y > 0.5f) {
|
||||
res.rgb = float3(dot(res.rgb, float3(0.2126f, 0.7152f, 0.0722f)));
|
||||
}
|
||||
res = tint(res, i.color) * localCoverage(v.p, i.rect, i.radii, i.transform0.w, fr);
|
||||
} else {
|
||||
float4 c = paint(v.p, i.params.z, i.rect, i.color, i.color2, i.grad, wide);
|
||||
float3 straight = unpremul(c);
|
||||
if (i.transform0.w > 0.5f) {
|
||||
float3 rgb = sampleLocal(colorTex, samp, v.tex, i.uv, 1.0f).rgb;
|
||||
res = c * textCoverage((rgb.r + rgb.g + rgb.b) / 3.0f, straight, i.inner.x, i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
res *= clipCoverage(v, i, clipTex, samp) * i.params.w;
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
float3 a = subpixelCoverage(sampleLocal(colorTex, samp, v.tex, i.uv, i.transform0.w).rgb, straight,
|
||||
i.inner.x, i.inner.y, i.radii);
|
||||
float3 w = a * c.a * clipCoverage(v, i, clipTex, samp) * i.params.w;
|
||||
float wa = (w.r + w.g + w.b) / 3.0f;
|
||||
return PSOut{float4(straight * w, wa), float4(w, wa)};
|
||||
}
|
||||
float clip = clipCoverage(v, i, clipTex, samp);
|
||||
res *= clip * i.params.w;
|
||||
return PSOut{res, res.aaaa};
|
||||
}
|
||||
|
||||
// The passes computing the backdrop of an effect draw a quad over their
|
||||
// target, scissored to the texels they compute.
|
||||
// A pass computing the backdrop of an effect (see package gpu).
|
||||
struct Pass {
|
||||
int2 origin; // down: the first pixel of the area read, in the frame
|
||||
int2 limit; // the last texel that may be read: in the frame for down
|
||||
int2 shift; // down: subtracted from frame pixels to read the source
|
||||
int2 dir; // blur: along rows (1, 0) or columns (0, 1)
|
||||
int down; // down: the size of the squares averaged
|
||||
int radius; // blur: how far it reaches each way
|
||||
float sigma; // blur: its standard deviation, 0 for none
|
||||
float pad;
|
||||
};
|
||||
|
||||
struct PassVSOut {
|
||||
float4 pos [[position]];
|
||||
};
|
||||
|
||||
vertex PassVSOut passVS(uint vid [[vertex_id]]) {
|
||||
float2 corner = float2(float(vid & 1u), float(vid >> 1u));
|
||||
PassVSOut o;
|
||||
o.pos = float4(corner * 2.0f - 1.0f, 0.0f, 1.0f);
|
||||
return o;
|
||||
}
|
||||
|
||||
// down averages the square of the area that texel stands for, repeating
|
||||
// the area's last pixels past its far edges.
|
||||
fragment float4 down(PassVSOut v [[stage_in]], texture2d<float> src [[texture(0)]],
|
||||
constant Pass &p [[buffer(0)]]) {
|
||||
int2 o = p.origin + int2(v.pos.xy) * p.down;
|
||||
float4 c = float4(0.0f);
|
||||
for (int y = 0; y < p.down; y++) {
|
||||
for (int x = 0; x < p.down; x++) {
|
||||
c += src.read(uint2(min(o + int2(x, y), p.limit) - p.shift));
|
||||
}
|
||||
}
|
||||
return c * (1.0f / float(p.down * p.down));
|
||||
}
|
||||
|
||||
// blur blurs along a row or a column, clamping at its ends.
|
||||
fragment float4 blur(PassVSOut v [[stage_in]], texture2d<float> src [[texture(0)]],
|
||||
constant Pass &p [[buffer(0)]]) {
|
||||
int2 at = int2(v.pos.xy);
|
||||
float4 c = float4(0.0f);
|
||||
float sum = 0.0f;
|
||||
for (int o = -p.radius; o <= p.radius; o++) {
|
||||
float x = float(o);
|
||||
float w = p.sigma > 0.0f ? exp(-(x * x) / (2.0f * p.sigma * p.sigma)) : 1.0f;
|
||||
c += src.read(uint2(clamp(at + p.dir * o, int2(0), p.limit))) * w;
|
||||
sum += w;
|
||||
}
|
||||
return c / sum;
|
||||
}
|
||||
|
||||
#endif
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
//go:build darwin
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Frames of video (scene.Surface) reach the GPU as the decoder left them:
|
||||
// a CVPixelBuffer backed by an IOSurface (Surface.Native), which a
|
||||
// CVMetalTextureCache wraps as a texture for each of its planes without a
|
||||
// copy, or planes in memory, which are uploaded. CoreVideo is loaded with
|
||||
// the first frame of video, so that windows showing none do not map it.
|
||||
|
||||
const pixelFormatRG8Unorm = 30
|
||||
|
||||
var (
|
||||
cvOnce sync.Once
|
||||
cvErr error
|
||||
|
||||
cvMetalTextureCacheCreate func(allocator, attrs, device, texAttrs uintptr, out *uintptr) int32
|
||||
cvMetalTextureCacheCreateTextureFromImage func(allocator, cache, image, attrs uintptr, format uint, w, h, plane uint, out *uintptr) int32
|
||||
cvMetalTextureGetTexture func(tex uintptr) uintptr
|
||||
cvMetalTextureCacheFlush func(cache uintptr, options uint64)
|
||||
cvPixelBufferGetWidthOfPlane func(buf uintptr, plane uint) uint
|
||||
cvPixelBufferGetHeightOfPlane func(buf uintptr, plane uint) uint
|
||||
cvPixelBufferGetWidth func(buf uintptr) uint
|
||||
cvPixelBufferGetHeight func(buf uintptr) uint
|
||||
)
|
||||
|
||||
func loadCoreVideo() error {
|
||||
cvOnce.Do(func() {
|
||||
h, err := purego.Dlopen("/System/Library/Frameworks/CoreVideo.framework/CoreVideo", purego.RTLD_GLOBAL|purego.RTLD_NOW)
|
||||
if err != nil {
|
||||
cvErr = err
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if v := recover(); v != nil {
|
||||
cvErr = v.(error)
|
||||
}
|
||||
}()
|
||||
purego.RegisterLibFunc(&cvMetalTextureCacheCreate, h, "CVMetalTextureCacheCreate")
|
||||
purego.RegisterLibFunc(&cvMetalTextureCacheCreateTextureFromImage, h, "CVMetalTextureCacheCreateTextureFromImage")
|
||||
purego.RegisterLibFunc(&cvMetalTextureGetTexture, h, "CVMetalTextureGetTexture")
|
||||
purego.RegisterLibFunc(&cvMetalTextureCacheFlush, h, "CVMetalTextureCacheFlush")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetWidthOfPlane, h, "CVPixelBufferGetWidthOfPlane")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetHeightOfPlane, h, "CVPixelBufferGetHeightOfPlane")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetWidth, h, "CVPixelBufferGetWidth")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetHeight, h, "CVPixelBufferGetHeight")
|
||||
})
|
||||
return cvErr
|
||||
}
|
||||
|
||||
// videoState is what the renderer keeps of frames of video: the texture
|
||||
// cache, and the CVMetalTextures (CF objects) that frames in flight read,
|
||||
// released once the frame of their slot completed.
|
||||
type videoState struct {
|
||||
cache uintptr
|
||||
// held are the CVMetalTextures given up while the frame of a slot was
|
||||
// built, which frames in flight may read still: released once that
|
||||
// slot's frame completed (waitSlot), which the queue finishes after
|
||||
// those before it.
|
||||
held [ringSize][]uintptr
|
||||
}
|
||||
|
||||
// surfaceTexture returns the texture of a frame of video: its luma, for
|
||||
// NV12, whose chroma chromaTexture returns.
|
||||
func (r *Renderer) surfaceTexture(img *scene.Image, s *scene.Surface) id {
|
||||
t := r.images[img.ID()]
|
||||
if t != nil && t.ver == img.Version() && t.w == img.W && t.h == img.H && (t.chroma != 0 || s.Format != scene.SurfaceNV12) {
|
||||
t.lastFrame = r.frame
|
||||
return t.tex
|
||||
}
|
||||
if s.Native != 0 {
|
||||
if r.wrapSurface(img, s) {
|
||||
t = r.images[img.ID()]
|
||||
t.lastFrame = r.frame
|
||||
return t.tex
|
||||
}
|
||||
return 0
|
||||
}
|
||||
// Planes in memory: uploaded into textures of their own.
|
||||
cw, ch := (img.W+1)/2, (img.H+1)/2
|
||||
if t != nil && (t.cv != [2]uintptr{} || t.chroma == 0 || t.w != img.W || t.h != img.H) {
|
||||
r.dropTexture(t)
|
||||
delete(r.images, img.ID())
|
||||
t = nil
|
||||
}
|
||||
if t == nil {
|
||||
luma := r.newTexture(img.W, img.H, pixelFormatR8Unorm, usageShaderRead, s.Planes[0].Pix, s.Planes[0].Stride)
|
||||
chroma := r.newTexture(cw, ch, pixelFormatRG8Unorm, usageShaderRead, s.Planes[1].Pix, s.Planes[1].Stride)
|
||||
if luma == 0 || chroma == 0 {
|
||||
release(&luma)
|
||||
release(&chroma)
|
||||
return 0
|
||||
}
|
||||
t = &texture{tex: luma, chroma: chroma, w: img.W, h: img.H, ver: img.Version()}
|
||||
r.images[img.ID()] = t
|
||||
} else {
|
||||
r.waitLast() // frames in flight read these textures
|
||||
replace := sel("replaceRegion:mipmapLevel:withBytes:bytesPerRow:")
|
||||
msgReplaceRegion(t.tex, replace, mtlRegion{W: uint(img.W), H: uint(img.H), D: 1}, 0, unsafe.Pointer(&s.Planes[0].Pix[0]), uint(s.Planes[0].Stride))
|
||||
msgReplaceRegion(t.chroma, replace, mtlRegion{W: uint(cw), H: uint(ch), D: 1}, 0, unsafe.Pointer(&s.Planes[1].Pix[0]), uint(s.Planes[1].Stride))
|
||||
t.ver = img.Version()
|
||||
}
|
||||
t.lastFrame = r.frame
|
||||
return t.tex
|
||||
}
|
||||
|
||||
// wrapSurface makes the textures of a frame in a CVPixelBuffer, without a
|
||||
// copy, the image's: its luma and chroma for NV12, else its BGRA.
|
||||
func (r *Renderer) wrapSurface(img *scene.Image, s *scene.Surface) bool {
|
||||
if loadCoreVideo() != nil {
|
||||
return false
|
||||
}
|
||||
v := &r.video
|
||||
if v.cache == 0 {
|
||||
if cvMetalTextureCacheCreate(0, 0, r.device, 0, &v.cache) != 0 {
|
||||
v.cache = 0
|
||||
return false
|
||||
}
|
||||
}
|
||||
var cv [2]uintptr
|
||||
wrap := func(plane uint, format uint, w, h uint) bool {
|
||||
return cvMetalTextureCacheCreateTextureFromImage(0, v.cache, s.Native, 0, format, w, h, plane, &cv[plane]) == 0 && cv[plane] != 0
|
||||
}
|
||||
ok := false
|
||||
if s.Format == scene.SurfaceNV12 {
|
||||
ok = wrap(0, pixelFormatR8Unorm, cvPixelBufferGetWidthOfPlane(s.Native, 0), cvPixelBufferGetHeightOfPlane(s.Native, 0)) &&
|
||||
wrap(1, pixelFormatRG8Unorm, cvPixelBufferGetWidthOfPlane(s.Native, 1), cvPixelBufferGetHeightOfPlane(s.Native, 1))
|
||||
} else {
|
||||
ok = wrap(0, pixelFormatBGRA8Unorm, cvPixelBufferGetWidth(s.Native), cvPixelBufferGetHeight(s.Native))
|
||||
}
|
||||
if !ok {
|
||||
for _, c := range cv {
|
||||
if c != 0 {
|
||||
purego.SyscallN(cfRelease, c)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if old := r.images[img.ID()]; old != nil {
|
||||
r.dropTexture(old)
|
||||
}
|
||||
t := &texture{w: img.W, h: img.H, ver: img.Version(), cv: cv}
|
||||
t.tex = cvMetalTextureGetTexture(cv[0])
|
||||
if cv[1] != 0 {
|
||||
t.chroma = cvMetalTextureGetTexture(cv[1])
|
||||
}
|
||||
r.images[img.ID()] = t
|
||||
return true
|
||||
}
|
||||
|
||||
// chromaTexture returns the texture of the chroma of a frame of video in
|
||||
// NV12, after imageTexture returned that of its luma, or 0.
|
||||
func (r *Renderer) chromaTexture(img *scene.Image) uintptr {
|
||||
if t := r.images[img.ID()]; t != nil {
|
||||
return t.chroma
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// dropTexture frees an image's textures: at once those the renderer
|
||||
// made, and those wrapping a CVPixelBuffer once the frames in flight,
|
||||
// which may read them, completed.
|
||||
func (r *Renderer) dropTexture(t *texture) {
|
||||
if t.cv != [2]uintptr{} {
|
||||
for _, c := range t.cv {
|
||||
if c != 0 {
|
||||
r.video.held[r.inUse] = append(r.video.held[r.inUse], c)
|
||||
}
|
||||
}
|
||||
t.cv, t.tex, t.chroma = [2]uintptr{}, 0, 0
|
||||
return
|
||||
}
|
||||
release(&t.tex)
|
||||
release(&t.chroma)
|
||||
}
|
||||
|
||||
// releaseHeld releases the CVMetalTextures given up while the frame of a
|
||||
// slot was built, once it completed.
|
||||
func (r *Renderer) releaseHeld(slot int) {
|
||||
held := r.video.held[slot]
|
||||
for _, c := range held {
|
||||
purego.SyscallN(cfRelease, c)
|
||||
}
|
||||
r.video.held[slot] = held[:0]
|
||||
if len(held) > 0 && r.video.cache != 0 {
|
||||
cvMetalTextureCacheFlush(r.video.cache, 0)
|
||||
}
|
||||
}
|
||||
|
||||
// releaseVideo frees what frames of video left, the frames in flight
|
||||
// done.
|
||||
func (r *Renderer) releaseVideo() {
|
||||
for i := range r.video.held {
|
||||
r.releaseHeld(i)
|
||||
}
|
||||
if r.video.cache != 0 {
|
||||
purego.SyscallN(cfRelease, r.video.cache)
|
||||
r.video.cache = 0
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestDrawsVideoAsTheCPURenderer draws frames of video in NV12 from their
|
||||
// planes in memory, then from CVPixelBuffers backed by IOSurfaces, which
|
||||
// the renderer samples where they are, as the shader converts them as
|
||||
// the CPU renderer does.
|
||||
func TestDrawsVideoAsTheCPURenderer(t *testing.T) {
|
||||
r, err := newRenderer()
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
s := gputest.VideoScene()
|
||||
for range 2 {
|
||||
for _, op := range s.Ops {
|
||||
op.Image.Changed()
|
||||
}
|
||||
pix, err := r.renderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "metal-video", pix, s.Width*4, s)
|
||||
}
|
||||
for _, op := range s.Ops {
|
||||
if tex := r.images[op.Image.ID()]; tex == nil || tex.chroma == 0 {
|
||||
t.Fatal("a frame of video drew from RGBA, not its planes")
|
||||
}
|
||||
}
|
||||
|
||||
// The same frames in CVPixelBuffers.
|
||||
if err := loadCoreVideo(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var bufs []uintptr
|
||||
defer func() {
|
||||
for _, b := range bufs {
|
||||
purego.SyscallN(cfRelease, b)
|
||||
}
|
||||
}()
|
||||
done := map[*scene.Image]bool{}
|
||||
for _, op := range s.Ops {
|
||||
img := op.Image
|
||||
if done[img] {
|
||||
continue
|
||||
}
|
||||
done[img] = true
|
||||
b := pixelBuffer(t, img)
|
||||
bufs = append(bufs, b)
|
||||
img.Surface = &scene.Surface{Format: img.Surface.Format, Matrix: img.Surface.Matrix, Native: b, Planes: img.Surface.Planes}
|
||||
img.Changed()
|
||||
}
|
||||
for range 3 {
|
||||
pix, err := r.renderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "metal-video-iosurface", pix, s.Width*4, s)
|
||||
}
|
||||
for _, op := range s.Ops {
|
||||
if tex := r.images[op.Image.ID()]; tex == nil || tex.cv[1] == 0 {
|
||||
t.Fatal("a frame in a CVPixelBuffer was not wrapped as textures")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pixelBuffer returns a CVPixelBuffer backed by an IOSurface holding the
|
||||
// planes of img's surface, in NV12 of the video range ('420v'), as
|
||||
// AVFoundation's decoders give them.
|
||||
func pixelBuffer(t *testing.T, img *scene.Image) uintptr {
|
||||
cv, err := purego.Dlopen("/System/Library/Frameworks/CoreVideo.framework/CoreVideo", purego.RTLD_GLOBAL|purego.RTLD_NOW)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cf, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_GLOBAL|purego.RTLD_NOW)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
create func(alloc uintptr, w, h uint, format uint32, attrs uintptr, out *uintptr) int32
|
||||
lock func(buf uintptr, flags uint64) int32
|
||||
unlock func(buf uintptr, flags uint64) int32
|
||||
base func(buf uintptr, plane uint) unsafe.Pointer
|
||||
stride func(buf uintptr, plane uint) uint
|
||||
dictCreate func(alloc uintptr, keys, values *uintptr, n int, kcb, vcb uintptr) uintptr
|
||||
)
|
||||
purego.RegisterLibFunc(&create, cv, "CVPixelBufferCreate")
|
||||
purego.RegisterLibFunc(&lock, cv, "CVPixelBufferLockBaseAddress")
|
||||
purego.RegisterLibFunc(&unlock, cv, "CVPixelBufferUnlockBaseAddress")
|
||||
purego.RegisterLibFunc(&base, cv, "CVPixelBufferGetBaseAddressOfPlane")
|
||||
purego.RegisterLibFunc(&stride, cv, "CVPixelBufferGetBytesPerRowOfPlane")
|
||||
purego.RegisterLibFunc(&dictCreate, cf, "CFDictionaryCreate")
|
||||
sym := func(h uintptr, name string) uintptr {
|
||||
p, err := purego.Dlsym(h, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return *(*uintptr)(ptr(p))
|
||||
}
|
||||
keyCB, _ := purego.Dlsym(cf, "kCFTypeDictionaryKeyCallBacks")
|
||||
valueCB, _ := purego.Dlsym(cf, "kCFTypeDictionaryValueCallBacks")
|
||||
empty := dictCreate(0, nil, nil, 0, keyCB, valueCB)
|
||||
defer purego.SyscallN(cfRelease, empty)
|
||||
keys := []uintptr{sym(cv, "kCVPixelBufferIOSurfacePropertiesKey"), sym(cv, "kCVPixelBufferMetalCompatibilityKey")}
|
||||
values := []uintptr{empty, sym(cf, "kCFBooleanTrue")}
|
||||
attrs := dictCreate(0, &keys[0], &values[0], len(keys), keyCB, valueCB)
|
||||
defer purego.SyscallN(cfRelease, attrs)
|
||||
var buf uintptr
|
||||
const format420v = 0x34323076
|
||||
if create(0, uint(img.W), uint(img.H), format420v, attrs, &buf) != 0 {
|
||||
t.Fatal("cannot create a CVPixelBuffer")
|
||||
}
|
||||
lock(buf, 0)
|
||||
s := img.Surface
|
||||
rows := [2]int{img.H, (img.H + 1) / 2}
|
||||
widths := [2]int{img.W, 2 * ((img.W + 1) / 2)}
|
||||
for p := range 2 {
|
||||
dst := unsafe.Slice((*byte)(base(buf, uint(p))), int(stride(buf, uint(p)))*rows[p])
|
||||
for y := range rows[p] {
|
||||
copy(dst[y*int(stride(buf, uint(p))):][:widths[p]], s.Planes[p].Pix[y*s.Planes[p].Stride:][:widths[p]])
|
||||
}
|
||||
}
|
||||
unlock(buf, 0)
|
||||
return buf
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//go:build darwin && !ios
|
||||
|
||||
package metal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestZoomedFrames renders the frames of content zoomed 2 times on a
|
||||
// screen of scale 2: the layer keeps the screen's scale, the frames
|
||||
// changing a little draw in part, and a frame changing the zoom alone
|
||||
// changes the layer not.
|
||||
func TestZoomedFrames(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
var layer id
|
||||
pool(func() { layer = send(class("CALayer"), "new") })
|
||||
if layer == 0 {
|
||||
t.Skip("no Core Animation")
|
||||
}
|
||||
defer pool(func() { release(&layer) })
|
||||
r, err := New(uintptr(layer))
|
||||
if err != nil {
|
||||
unavailable(t, err)
|
||||
}
|
||||
defer r.Release()
|
||||
frame := func(i int, scale, zoom float32) {
|
||||
t.Helper()
|
||||
s := &scene.Scene{}
|
||||
s.Reset(128, 64, scene.Color{A: 255})
|
||||
s.Scale, s.Zoom = scale, zoom
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(4 * i), W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}})
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.pre.wait()
|
||||
r.waitLast()
|
||||
}
|
||||
partial := 0
|
||||
for i := range 8 {
|
||||
frame(i, 4, 2)
|
||||
if r.scale != 2 {
|
||||
t.Fatalf("frame %d: the layer's scale is %v, want the screen's, 2", i, r.scale)
|
||||
}
|
||||
if r.redrew == redrewPart {
|
||||
partial++
|
||||
}
|
||||
}
|
||||
if partial == 0 {
|
||||
t.Error("no zoomed frame drew in part")
|
||||
}
|
||||
frame(8, 2, 0)
|
||||
if r.scale != 2 {
|
||||
t.Errorf("unzoomed, the layer's scale is %v, want 2", r.scale)
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package gpu
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Summary describes the last scene built, for logs (MYGO_FRAME_STATS): how
|
||||
// many instances in how many batches, how many ops were left out as covered,
|
||||
// how many fills drew as opaque cores, and the batches of each class.
|
||||
func (b *Builder) Summary() string {
|
||||
var classes [NumClasses]int
|
||||
opaque := 0
|
||||
for i := range b.Batches {
|
||||
classes[b.Batches[i].Class]++
|
||||
if b.Batches[i].Opaque {
|
||||
opaque++
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%d instances in %d batches (%d opaque; by class general %d, plain %d, fill %d, shadow %d, glyph %d, subpixel %d, image %d), %d ops culled, %d opaque cores",
|
||||
len(b.Instances), len(b.Batches), opaque, classes[ClassGeneral], classes[ClassPlain], classes[ClassFill], classes[ClassShadow], classes[ClassGlyph],
|
||||
classes[ClassSubpixel], classes[ClassImage], b.Culled, b.OpaqueCores)
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
//go:build !js
|
||||
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Browsers compile their shaders as they load (internal/gpu/gl), none ahead
|
||||
// of time: builds for them leave SourceSum out, with crypto/sha256.
|
||||
|
||||
// SourceSum returns the SHA-256, in hex, of a shader's source as the
|
||||
// repository holds it, with LF line endings, which shaders compiled ahead
|
||||
// of time record: the source matches them however it was checked out, as
|
||||
// with CRLF endings on Windows.
|
||||
func SourceSum(src string) string {
|
||||
sum := sha256.Sum256([]byte(strings.ReplaceAll(src, "\r\n", "\n")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
//go:build !js
|
||||
|
||||
package gpu
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSourceSum(t *testing.T) {
|
||||
lf, crlf := "float4 ps() {\n\treturn 1;\n}\n", "float4 ps() {\r\n\treturn 1;\r\n}\r\n"
|
||||
if SourceSum(lf) != SourceSum(crlf) {
|
||||
t.Error("a checkout with CRLF line endings has another sum")
|
||||
}
|
||||
if SourceSum(lf) == SourceSum(lf+" ") || len(SourceSum(lf)) != 64 {
|
||||
t.Error("the sum does not tell sources apart")
|
||||
}
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
package gpu
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"image"
|
||||
"math"
|
||||
"slices"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// clipMaskSlot is a retained clip mask. Masks outlive the frames that
|
||||
// don't use them, up to idleMaskBytes of them, so a transform that comes
|
||||
// and goes finds its masks again instead of rasterizing them.
|
||||
type clipMaskSlot struct {
|
||||
// shapes are the clips the mask is of, their stops in stops, and area
|
||||
// the frame pixels it covers: the clip's scissor rectangle, or more
|
||||
// for a clip that grows (maskArea).
|
||||
shapes []scene.ClipShape
|
||||
stops []scene.Stop
|
||||
area image.Rectangle
|
||||
image *scene.Image
|
||||
// frame is the last frame that used the mask, and slot the clip's
|
||||
// place among that frame's masked clips.
|
||||
frame uint64
|
||||
slot int
|
||||
}
|
||||
|
||||
// idleMaskBytes is how much memory the masks no clip of the frame uses
|
||||
// keep, the least recently used dropped first.
|
||||
const idleMaskBytes = 32 << 20
|
||||
|
||||
func (b *Builder) prepare(in *Instance, m scene.Affine, c *clip) bool {
|
||||
b.preparedMask = 0
|
||||
if c.scissor.Empty() || in.Rect[2] <= 0 || in.Rect[3] <= 0 {
|
||||
return false
|
||||
}
|
||||
if _, ok := m.Inverse(); !ok {
|
||||
return false
|
||||
}
|
||||
in.Transform0, in.Transform1, in.Transform2 = [4]float32{1, 0, 0, 0}, [4]float32{0, 1, 0, 0}, [4]float32{}
|
||||
if m.Set {
|
||||
in.Transform0 = [4]float32{m.A, m.C, m.X, 1}
|
||||
in.Transform1 = [4]float32{m.B, m.D, m.Y, 0}
|
||||
in.Transform2 = [4]float32{m.G, m.H, 0, 0}
|
||||
if m.Behind {
|
||||
in.Transform2[2] = 1 // the divisor's constant term is -1
|
||||
}
|
||||
}
|
||||
in.Clip, in.ClipRadii = rect(c.rect), c.radii
|
||||
if !c.masked {
|
||||
return true
|
||||
}
|
||||
// Stationary clips can often reduce to one rounded rectangle, even
|
||||
// around scaled content or a fractional scrolling viewport. Evaluate
|
||||
// that geometry in the shader instead of rasterizing a window-sized mask.
|
||||
if !c.moved && !c.masks {
|
||||
if rounded, ok := b.analyticClip(); ok {
|
||||
in.Clip, in.ClipRadii = rect(rounded.rect), rounded.radii
|
||||
return true
|
||||
}
|
||||
}
|
||||
// A hard clip sharing the drawing's coordinates is cheap to evaluate in
|
||||
// the fragment shader. Keep the rounded ancestor's mask stationary even
|
||||
// when a text input or custom clipped drawing moves within it. Drawing
|
||||
// that a translation of the clip's moved shares them too, folded into
|
||||
// the frame's (scene.TranslationFolder): the clip's rectangle moves.
|
||||
// So does drawing that nothing transforms, or that a translation only
|
||||
// moves, in a clip in the frame's coordinates (as a clip only moved
|
||||
// is, scene.MovedClip), whose rectangle moves the other way: as a
|
||||
// pane reaching into the rounded corners of the frame around it
|
||||
// (markEnclosing), which then needs no mask of its own.
|
||||
shared, dx, dy := c.shape.Transform == m && m.Set, float32(0), float32(0)
|
||||
if tx, ty, moved := m.Translation(); !c.shape.Transform.Set && (!m.Set || moved) {
|
||||
dx, dy, shared = -tx, -ty, true
|
||||
}
|
||||
if c.shape.Radii == [4]float32{} && !c.shape.Masks() && shared && len(b.stack) > 1 {
|
||||
parent := &b.stack[len(b.stack)-2]
|
||||
if parent.masked {
|
||||
b.preparedMask = b.clipTexture(parent, b.clipShapes[:len(b.clipShapes)-1])
|
||||
if b.preparedMask == 0 {
|
||||
return false
|
||||
}
|
||||
in.Clip = rect(c.rect)
|
||||
in.Clip[0], in.Clip[1] = in.Clip[0]+dx, in.Clip[1]+dy
|
||||
in.ClipRadii = areaRect(parent.maskArea)
|
||||
in.Transform1[3] = 2
|
||||
return true
|
||||
}
|
||||
}
|
||||
b.preparedMask = b.clipTexture(c, b.clipShapes)
|
||||
if b.preparedMask == 0 {
|
||||
return false
|
||||
}
|
||||
in.Clip = areaRect(c.maskArea)
|
||||
in.ClipRadii = [4]float32{}
|
||||
in.Transform1[3] = 1
|
||||
return true
|
||||
}
|
||||
|
||||
// analyticClip removes clips that cover every pixel of the scissor, then
|
||||
// represents the remaining coverage with one rectangle and its corners.
|
||||
// Overlapping antialiased edges still need their multiplied pixel mask.
|
||||
func (b *Builder) analyticClip() (clip, bool) {
|
||||
var rounded, hard *clip
|
||||
sc := b.stack[len(b.stack)-1].scissor
|
||||
area := scene.Rect{X: float32(sc.Left), Y: float32(sc.Top), W: float32(sc.Right - sc.Left), H: float32(sc.Bottom - sc.Top)}
|
||||
for i := range b.stack {
|
||||
c := &b.stack[i]
|
||||
// Only Metal's shader evaluates continuous corners (SplitCorners):
|
||||
// the other renderers, which never draw them in an app, keep the
|
||||
// mask. On Metal, a pane against the side of a rounded frame, as a
|
||||
// sidebar, cuts the frame's curves in the shader rather than with a
|
||||
// mask of the whole frame (#1511).
|
||||
if continuous(c.radii) && !b.contClips {
|
||||
return clip{}, false
|
||||
}
|
||||
if c.radii == [4]float32{} && integerClip(c.rect) {
|
||||
continue // the batch scissor implements these edges exactly
|
||||
}
|
||||
if clipOpaqueWithin(c, area) {
|
||||
continue
|
||||
}
|
||||
if c.radii != [4]float32{} {
|
||||
if rounded != nil {
|
||||
return clip{}, false
|
||||
}
|
||||
rounded = c
|
||||
} else {
|
||||
if hard != nil {
|
||||
return clip{}, false
|
||||
}
|
||||
hard = c
|
||||
}
|
||||
}
|
||||
if rounded == nil {
|
||||
if hard != nil {
|
||||
return *hard, true
|
||||
}
|
||||
return clip{rect: area}, true
|
||||
}
|
||||
if hard != nil {
|
||||
return intersectAnalyticClip(*rounded, hard.rect)
|
||||
}
|
||||
return *rounded, true
|
||||
}
|
||||
|
||||
func integerClip(r scene.Rect) bool {
|
||||
for _, v := range [4]float32{r.X, r.Y, r.X + r.W, r.Y + r.H} {
|
||||
if v != float32(math.Floor(float64(v))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// clipCornerBounds conservatively encloses each curve and its
|
||||
// antialiasing: a continuous one (negative radius) reaches contExtent
|
||||
// times its radius from its corner, where the shader stops evaluating it
|
||||
// (contValue).
|
||||
func clipCornerBounds(c *clip) [4]scene.Rect {
|
||||
r := c.rect
|
||||
var boxes [4]scene.Rect
|
||||
for i, radius := range c.radii {
|
||||
if radius == 0 {
|
||||
continue
|
||||
}
|
||||
reach := radius + 1
|
||||
if radius < 0 {
|
||||
reach = -radius*contExtent + 1
|
||||
}
|
||||
box := scene.Rect{X: r.X, Y: r.Y, W: reach, H: reach}
|
||||
if i == 1 || i == 2 {
|
||||
box.X = r.X + r.W - reach
|
||||
}
|
||||
if i == 2 || i == 3 {
|
||||
box.Y = r.Y + r.H - reach
|
||||
}
|
||||
boxes[i] = box
|
||||
}
|
||||
return boxes
|
||||
}
|
||||
|
||||
// clipOpaqueWithin proves that a clip contributes coverage 1 to every
|
||||
// integer pixel box in area; merely containing the pixel centers is unsafe.
|
||||
func clipOpaqueWithin(c *clip, area scene.Rect) bool {
|
||||
r := c.rect
|
||||
if area.X < r.X || area.Y < r.Y || area.X+area.W > r.X+r.W || area.Y+area.H > r.Y+r.H {
|
||||
return false
|
||||
}
|
||||
for _, box := range clipCornerBounds(c) {
|
||||
if !box.Intersect(area).Empty() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// intersectAnalyticClip trims away whole corners, as a fractional lyrics
|
||||
// viewport trims its player card. Cutting a curve or multiplying partial
|
||||
// coverages cannot be represented by a single rounded rectangle.
|
||||
func intersectAnalyticClip(c clip, hard scene.Rect) (clip, bool) {
|
||||
r := c.rect.Intersect(hard)
|
||||
if r.W < 1 || r.H < 1 {
|
||||
return clip{}, false
|
||||
}
|
||||
before := [4]float32{c.rect.X, c.rect.Y, c.rect.X + c.rect.W, c.rect.Y + c.rect.H}
|
||||
after := [4]float32{r.X, r.Y, r.X + r.W, r.Y + r.H}
|
||||
edges := [4]float32{hard.X, hard.Y, hard.X + hard.W, hard.Y + hard.H}
|
||||
for i, edge := range edges {
|
||||
old := float64(before[i])
|
||||
if i < 2 {
|
||||
if edge <= before[i] && float64(edge) > math.Floor(old) || edge > before[i] && math.Floor(float64(edge)) < math.Ceil(old) {
|
||||
return clip{}, false
|
||||
}
|
||||
} else if edge >= before[i] && float64(edge) < math.Ceil(old) || edge < before[i] && math.Ceil(float64(edge)) > math.Floor(old) {
|
||||
return clip{}, false
|
||||
}
|
||||
}
|
||||
pixels := scene.Rect{X: float32(math.Floor(float64(r.X))), Y: float32(math.Floor(float64(r.Y)))}
|
||||
pixels.W, pixels.H = float32(math.Ceil(float64(r.X+r.W)))-pixels.X, float32(math.Ceil(float64(r.Y+r.H)))-pixels.Y
|
||||
for i, box := range clipCornerBounds(&c) {
|
||||
sides := [4][2]int{{0, 1}, {2, 1}, {2, 3}, {0, 3}}[i]
|
||||
if after[sides[0]] != before[sides[0]] || after[sides[1]] != before[sides[1]] {
|
||||
if !box.Intersect(pixels).Empty() {
|
||||
return clip{}, false
|
||||
}
|
||||
c.radii[i] = 0
|
||||
} else if box.W > r.W/2 || box.H > r.H/2 {
|
||||
// Moving a surviving curve across the new midpoint would change
|
||||
// which corner the shader evaluates there. A continuous curve
|
||||
// keeps its shape too, which depends on the sides and its
|
||||
// neighbors' radii only where they are shorter than
|
||||
// contExtent times the radii they join (the shader's
|
||||
// contCorner): a side the cut leaves is as long as before, with
|
||||
// the same neighbor, and one it shortens is still twice this
|
||||
// box long, its neighbor cut away beyond it.
|
||||
return clip{}, false
|
||||
}
|
||||
}
|
||||
c.rect = r
|
||||
return c, true
|
||||
}
|
||||
|
||||
func (b *Builder) clipTexture(c *clip, shapes []scene.ClipShape) uintptr {
|
||||
if c.maskTexture != 0 {
|
||||
return c.maskTexture
|
||||
}
|
||||
area := image.Rect(int(c.scissor.Left), int(c.scissor.Top), int(c.scissor.Right), int(c.scissor.Bottom))
|
||||
// The mask of the same clip, in this frame or an earlier one; else
|
||||
// the one the clip in its place had last frame, which it most likely
|
||||
// is, changed; else a new one.
|
||||
found, reuse := -1, -1
|
||||
for i := range b.maskSlots {
|
||||
m := &b.maskSlots[i]
|
||||
// A mask of more of the frame than the clip's scissor rectangle
|
||||
// holds the same coverage there.
|
||||
if area.In(m.area) && slices.EqualFunc(m.shapes, shapes, func(a, b scene.ClipShape) bool { return a.Same(&b) }) {
|
||||
found = i
|
||||
break
|
||||
}
|
||||
if reuse < 0 && m.frame == b.frame-1 && m.slot == c.maskSlot {
|
||||
reuse = i
|
||||
}
|
||||
}
|
||||
if found < 0 {
|
||||
found = reuse
|
||||
if found < 0 {
|
||||
found = len(b.maskSlots)
|
||||
b.maskSlots = append(b.maskSlots, clipMaskSlot{})
|
||||
}
|
||||
m := &b.maskSlots[found]
|
||||
m.area = maskArea(area, m.image, b.stack[0].scissor)
|
||||
m.image = raster.ClipMask(m.image, shapes, m.area)
|
||||
m.keep(shapes)
|
||||
}
|
||||
m := &b.maskSlots[found]
|
||||
m.frame, m.slot = b.frame, c.maskSlot
|
||||
c.maskArea = m.area
|
||||
c.maskTexture = b.imageTexture(m.image)
|
||||
return c.maskTexture
|
||||
}
|
||||
|
||||
// maskArea returns the frame pixels to rasterize a clip's mask into,
|
||||
// for a clip whose scissor rectangle is area, given had, the mask the
|
||||
// clip in its place had last frame. A new mask covers area. Otherwise
|
||||
// the mask keeps had's size, placed where area fits in it, so that a
|
||||
// clip that changes reuses its mask's memory and texture instead of
|
||||
// allocating both again on every frame of its animation. A card growing
|
||||
// out of a cover to fill the window allocated 190 MB in 40 frames
|
||||
// (egoist/mygo-music#55). A side that outgrows it doubles, up to the
|
||||
// frame's size, and a clip that shrinks to less than a quarter of it
|
||||
// takes its own size.
|
||||
func maskArea(area image.Rectangle, had *scene.Image, frame Scissor) image.Rectangle {
|
||||
if had == nil || had.W <= 0 || had.H <= 0 {
|
||||
return area
|
||||
}
|
||||
w, h := area.Dx(), area.Dy()
|
||||
if 4*w*h < had.W*had.H {
|
||||
return area
|
||||
}
|
||||
grow := func(n, was, most int) int {
|
||||
if n <= was {
|
||||
return was
|
||||
}
|
||||
return max(n, min(2*was, most))
|
||||
}
|
||||
w, h = grow(w, had.W, int(frame.Right-frame.Left)), grow(h, had.H, int(frame.Bottom-frame.Top))
|
||||
// Within the frame where it fits, rather than rasterizing what is off
|
||||
// it.
|
||||
place := func(lo, hi, n int, end int32) int {
|
||||
return max(min(lo, int(end)-n), hi-n)
|
||||
}
|
||||
x, y := place(area.Min.X, area.Max.X, w, frame.Right), place(area.Min.Y, area.Max.Y, h, frame.Bottom)
|
||||
return image.Rect(x, y, x+w, y+h)
|
||||
}
|
||||
|
||||
// areaRect returns area, a mask's frame pixels, as the shaders take it:
|
||||
// its origin and size, which map frame pixels to the mask's texels.
|
||||
func areaRect(area image.Rectangle) [4]float32 {
|
||||
return [4]float32{float32(area.Min.X), float32(area.Min.Y), float32(area.Dx()), float32(area.Dy())}
|
||||
}
|
||||
|
||||
// keep keeps shapes as the mask's, with copies of their stops, which
|
||||
// the scene's are not from frame to frame.
|
||||
func (m *clipMaskSlot) keep(shapes []scene.ClipShape) {
|
||||
m.shapes = append(m.shapes[:0], shapes...)
|
||||
m.stops = m.stops[:0]
|
||||
for _, c := range shapes {
|
||||
m.stops = append(m.stops, c.Stops...)
|
||||
}
|
||||
at := 0
|
||||
for i := range m.shapes {
|
||||
if st := m.shapes[i].Stops; st != nil {
|
||||
m.shapes[i].Stops = m.stops[at : at+len(st) : at+len(st)]
|
||||
at += len(st)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dropIdleMasks drops the least recently used masks this frame didn't use
|
||||
// beyond idle bytes of them.
|
||||
func (b *Builder) dropIdleMasks(idle int) {
|
||||
slices.SortFunc(b.maskSlots, func(x, y clipMaskSlot) int { return cmp.Compare(y.frame, x.frame) })
|
||||
for i := range b.maskSlots {
|
||||
m := &b.maskSlots[i]
|
||||
if m.frame == b.frame {
|
||||
continue
|
||||
}
|
||||
// The memory a mask keeps, which may be more than its pixels
|
||||
// take up: Resize reuses it for smaller ones.
|
||||
if idle -= cap(m.image.Pix); idle < 0 {
|
||||
clear(b.maskSlots[i:])
|
||||
b.maskSlots = b.maskSlots[:i]
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user