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:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+36
View File
@@ -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
View File
@@ -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")
}
+64
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
}
+57
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+110
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
+32
View File
@@ -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};
}
File diff suppressed because it is too large. Load diff
+12
View File
@@ -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
View File
@@ -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
View File
@@ -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
}
+59
View File
@@ -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)
}
}