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

+238
View File
@@ -0,0 +1,238 @@
package scene
import (
"cmp"
"image"
"slices"
)
// MaxAtlasSize is the largest width and height an Atlas grows to.
const MaxAtlasSize = 4096
// Atlas packs small bitmaps, such as rasterized glyphs, into one larger
// bitmap that renderers keep as a texture. It records which rectangles
// changed so that renderers upload only those. Main thread only.
//
// Lasting bitmaps fill shelves down from the top. Bitmaps a single frame
// draws, such as the masks of animated shapes, fill shelves up from the
// bottom, and ResetTransient frees them all at once, so that they never
// crowd out the lasting ones.
type Atlas struct {
// BPP is the number of bytes per pixel: 1 for coverage masks, 4 for
// premultiplied RGBA.
BPP int
// W and H are the size in pixels; Pix holds rows of W*BPP bytes.
W, H int
Pix []byte
gen uint64
version uint64
log []atlasChange
// Lasting shelves span rows [0, bottom), transient ones [top, H).
shelves, transient []shelf
bottom, top int
}
type atlasChange struct {
version uint64
r image.Rectangle
}
type shelf struct{ y, h, x int }
// atlasLog is how many changes an atlas remembers; a renderer further
// behind uploads the whole atlas.
const atlasLog = 512
// NewAtlas returns an empty w×h atlas of bpp bytes per pixel.
func NewAtlas(bpp, w, h int) *Atlas {
return &Atlas{BPP: bpp, W: w, H: h, Pix: make([]byte, w*h*bpp), gen: 1, top: h}
}
// Generation changes when the atlas is resized, reset or repacked, which
// makes renderers create a new texture and upload all of it.
func (a *Atlas) Generation() uint64 { return a.gen }
// Version increases with every change.
func (a *Atlas) Version() uint64 { return a.version }
// Changes returns the rectangles changed since version, or full when the
// renderer, which last uploaded version of generation gen, must upload
// everything.
func (a *Atlas) Changes(gen, version uint64) (rects []image.Rectangle, full bool) {
if gen != a.gen {
return nil, true
}
if version == a.version {
return nil, false
}
if len(a.log) == 0 || a.log[0].version > version+1 {
return nil, true
}
var union image.Rectangle
for _, c := range a.log {
if c.version > version {
rects = append(rects, c.r)
union = union.Union(c.r)
}
}
// Many small uploads cost more than one larger one.
if len(rects) > 32 {
return []image.Rectangle{union}, false
}
return rects, false
}
// Alloc reserves a lasting w×h rectangle, keeping a pixel of padding to its
// right and below it so that filtering never reads a neighbor. It reports
// false when the atlas is full; the caller then repacks, grows or resets
// it.
func (a *Atlas) Alloc(w, h int) (x, y int, ok bool) {
return a.alloc(&a.shelves, false, w, h)
}
// AllocTransient is Alloc for a rectangle needed until ResetTransient.
func (a *Atlas) AllocTransient(w, h int) (x, y int, ok bool) {
return a.alloc(&a.transient, true, w, h)
}
func (a *Atlas) alloc(shelves *[]shelf, up bool, w, h int) (x, y int, ok bool) {
pw, ph := w+1, h+1
if pw > a.W || ph > a.H {
return 0, 0, false
}
best := -1
for i, s := range *shelves {
if s.h >= ph && s.h <= ph+ph/4+2 && a.W-s.x >= pw && (best < 0 || s.h < (*shelves)[best].h) {
best = i
}
}
if best < 0 {
if a.bottom+ph > a.top {
return 0, 0, false
}
// A shelf a little taller than its first bitmap takes the next
// ones, which are often a little taller (larger text, shapes).
step := max(4, ph/8)
sh := min((ph+step-1)/step*step, a.top-a.bottom)
y := a.bottom
if up {
a.top -= sh
y = a.top
} else {
a.bottom += sh
}
*shelves = append(*shelves, shelf{y: y, h: sh})
best = len(*shelves) - 1
}
s := &(*shelves)[best]
x, y = s.x, s.y
s.x += pw
return x, y, true
}
// ResetTransient frees the rectangles AllocTransient reserved.
func (a *Atlas) ResetTransient() {
a.transient = a.transient[:0]
a.top = a.H
}
// Put copies a w×h bitmap with rows of stride bytes to (x, y), and clears
// the padding after it, which may hold an earlier bitmap's pixels.
func (a *Atlas) Put(x, y, w, h int, src []byte, stride int) {
bpp := a.BPP
row := w * bpp
for j := 0; j < h; j++ {
i := ((y+j)*a.W + x) * bpp
copy(a.Pix[i:][:row], src[j*stride:][:row])
if x+w < a.W {
clear(a.Pix[i+row:][:bpp])
}
}
r := image.Rect(x, y, min(x+w+1, a.W), min(y+h+1, a.H))
if y+h < a.H {
i := ((y+h)*a.W + x) * bpp
clear(a.Pix[i:][:r.Dx()*bpp])
}
a.version++
a.log = append(a.log, atlasChange{a.version, r})
if len(a.log) > atlasLog {
a.log = append(a.log[:0], a.log[len(a.log)-atlasLog/2:]...)
}
}
// Grow doubles the atlas up to MaxAtlasSize, keeping its lasting bitmaps
// where they are; it frees the transient ones. It reports false when the
// atlas is already at its largest.
func (a *Atlas) Grow() bool {
if a.W >= MaxAtlasSize && a.H >= MaxAtlasSize {
return false
}
w, h := min(a.W*2, MaxAtlasSize), min(a.H*2, MaxAtlasSize)
pix := make([]byte, w*h*a.BPP)
for j := 0; j < a.bottom; j++ {
copy(pix[j*w*a.BPP:], a.Pix[j*a.W*a.BPP:(j+1)*a.W*a.BPP])
}
a.W, a.H, a.Pix = w, h, pix
a.ResetTransient()
a.changedAll()
return true
}
// Repack frees the atlas and allocates rects, lasting rectangles of it,
// again, tallest first, moving their pixels along. It returns where each
// went, or false, changing nothing, when they do not fit.
func (a *Atlas) Repack(rects []image.Rectangle) ([]image.Point, bool) {
order := make([]int, len(rects))
for i := range order {
order[i] = i
}
slices.SortFunc(order, func(i, j int) int {
return cmp.Or(cmp.Compare(rects[j].Dy(), rects[i].Dy()), cmp.Compare(rects[j].Dx(), rects[i].Dx()))
})
plan := Atlas{W: a.W, H: a.H, top: a.H}
pos := make([]image.Point, len(rects))
for _, i := range order {
x, y, ok := plan.Alloc(rects[i].Dx(), rects[i].Dy())
if !ok {
return nil, false
}
pos[i] = image.Pt(x, y)
}
saved := make([][]byte, len(rects))
for i, r := range rects {
row := r.Dx() * a.BPP
b := make([]byte, row*r.Dy())
for j := 0; j < r.Dy(); j++ {
copy(b[j*row:][:row], a.Pix[((r.Min.Y+j)*a.W+r.Min.X)*a.BPP:][:row])
}
saved[i] = b
}
clear(a.Pix)
for i, r := range rects {
row := r.Dx() * a.BPP
for j := 0; j < r.Dy(); j++ {
copy(a.Pix[((pos[i].Y+j)*a.W+pos[i].X)*a.BPP:][:row], saved[i][j*row:][:row])
}
}
a.shelves, a.bottom = plan.shelves, plan.bottom
a.ResetTransient()
a.changedAll()
return pos, true
}
// Reset empties the atlas: every allocation becomes invalid.
func (a *Atlas) Reset() {
clear(a.Pix)
a.shelves = a.shelves[:0]
a.bottom = 0
a.ResetTransient()
a.changedAll()
}
// changedAll makes renderers upload the whole atlas.
func (a *Atlas) changedAll() {
a.gen++
a.version++
a.log = a.log[:0]
}
+124
View File
@@ -0,0 +1,124 @@
package scene
import (
"image"
"testing"
)
func TestAtlasZones(t *testing.T) {
a := NewAtlas(1, 128, 128)
lx, ly, ok := a.Alloc(10, 10)
if !ok || lx != 0 || ly != 0 {
t.Fatalf("lasting at %d,%d %v", lx, ly, ok)
}
tx, ty, ok := a.AllocTransient(10, 10)
if !ok || tx != 0 || ty != 128-12 { // shelves round up to 4 rows
t.Fatalf("transient at %d,%d %v", tx, ty, ok)
}
// The zones share the rows between them and never overlap.
var lasting, transient []image.Rectangle
for {
x, y, ok := a.Alloc(20, 20)
if !ok {
break
}
lasting = append(lasting, image.Rect(x, y, x+21, y+21))
x, y, ok = a.AllocTransient(20, 20)
if !ok {
break
}
transient = append(transient, image.Rect(x, y, x+21, y+21))
}
if len(lasting) == 0 || len(transient) == 0 {
t.Fatalf("%d lasting, %d transient", len(lasting), len(transient))
}
for _, l := range lasting {
for _, r := range transient {
if l.Overlaps(r) {
t.Fatalf("%v overlaps %v", l, r)
}
}
}
a.ResetTransient()
if x, y, ok := a.AllocTransient(10, 10); !ok || x != tx || y != ty {
t.Errorf("after ResetTransient at %d,%d %v, want %d,%d", x, y, ok, tx, ty)
}
}
func TestAtlasPutClearsPadding(t *testing.T) {
a := NewAtlas(1, 16, 16)
x, y, _ := a.AllocTransient(3, 3)
a.Put(x, y, 3, 3, []byte{9, 9, 9, 9, 9, 9, 9, 9, 9}, 3)
a.ResetTransient()
x, y, _ = a.AllocTransient(2, 2)
a.Put(x, y, 2, 2, []byte{1, 1, 1, 1}, 2)
for j := range 3 {
for i := range 3 {
want := byte(0)
if i < 2 && j < 2 {
want = 1
}
if got := a.Pix[(y+j)*a.W+x+i]; got != want {
t.Errorf("pixel %d,%d is %d, want %d", i, j, got, want)
}
}
}
rects, full := a.Changes(a.Generation(), a.Version()-1)
if full || len(rects) != 1 || rects[0] != image.Rect(x, y, x+3, y+3) {
t.Errorf("changes %v %v", rects, full)
}
}
func TestAtlasRepackAndGrow(t *testing.T) {
a := NewAtlas(1, 32, 32)
var rects []image.Rectangle
for i := range 6 {
w, h := 4+i, 6-i/2
x, y, ok := a.Alloc(w, h)
if !ok {
t.Fatal("full")
}
pix := make([]byte, w*h)
for k := range pix {
pix[k] = byte(10*i + k%7)
}
a.Put(x, y, w, h, pix, w)
rects = append(rects, image.Rect(x, y, x+w, y+h))
}
kept := []image.Rectangle{rects[1], rects[4], rects[5]}
want := make([][]byte, len(kept))
for i, r := range kept {
for y := r.Min.Y; y < r.Max.Y; y++ {
want[i] = append(want[i], a.Pix[y*a.W+r.Min.X:y*a.W+r.Max.X]...)
}
}
check := func(what string, pos []image.Point) {
t.Helper()
for i, r := range kept {
var got []byte
for y := pos[i].Y; y < pos[i].Y+r.Dy(); y++ {
got = append(got, a.Pix[y*a.W+pos[i].X:y*a.W+pos[i].X+r.Dx()]...)
}
if string(got) != string(want[i]) {
t.Errorf("%s: rectangle %d holds %v, want %v", what, i, got, want[i])
}
}
}
gen := a.Generation()
pos, ok := a.Repack(kept)
if !ok || a.Generation() == gen {
t.Fatalf("Repack: %v, generation %d", ok, a.Generation())
}
check("repacked", pos)
if _, ok := a.Repack([]image.Rectangle{image.Rect(0, 0, 40, 4)}); ok {
t.Error("Repack placed a rectangle wider than the atlas")
}
check("after a failed repack", pos)
if !a.Grow() || a.W != 64 || a.H != 64 {
t.Fatalf("Grow: %dx%d", a.W, a.H)
}
check("grown", pos)
if _, _, ok := a.Alloc(40, 40); !ok {
t.Error("no room after growing")
}
}
+498
View File
@@ -0,0 +1,498 @@
package scene
import (
"image"
"math"
)
// A Differ finds where the successive scenes of a window differ, so that a
// renderer redraws only there: a blinking caret, a ticking clock or a
// button under the pointer redraws only itself.
//
// It compares the operations of two scenes from both ends, so a change in
// the middle of the display list damages the boxes of the operations that
// changed, clipped as they draw, where they drew before and where they
// draw now. Glyphs whose pixels changed in an atlas, and images whose
// pixels changed, count as changed.
type Differ struct {
// Reach is how far, in pixels, a renderer draws beyond the geometry of
// an operation: its antialiased edge, a pixel for the CPU's. Three more
// are added under a transform, whose quads the GPU's renderers grow by
// a pixel or two.
Reach float32
// Wide compares the colors outside the sRGB gamut (Scene.Wide) too, for
// a renderer that draws them; others draw their nearest sRGB colors,
// which the operations hold.
Wide bool
// valid tells that the last scene, of w×h pixels, is remembered to
// compare the next with.
valid bool
w, h int
clear Color
text TextParams
ops []Op
glyphs []Glyph
stops []Stop
effects []EffectOp
wide []WideColors
words []uint32
// bounds is where each operation of the last scene drew, next where
// those of the scene Diff was given draw; versions has the versions of
// the last scene's images.
bounds, next []image.Rectangle
// encloses and encloses2 tell, for each clip of the last scene and of
// the one Diff was given, that it holds an op drawn under a transform
// that does more than move it, or a clip reaching into rounded corners
// (see opBounds).
encloses, encloses2 []bool
pushes []int
corners ClipCorners
versions []uint64
mask, color atlasMark
damage []image.Rectangle
clips []image.Rectangle
// pre and suf are how many ops the scenes Diff compared last share at
// their starts and ends, n and m how many each has (see Match).
pre, suf, n, m int
}
// atlasMark is the state of an atlas a scene drew from.
type atlasMark struct {
atlas *Atlas
gen, version uint64
}
// changes returns the rectangles of a that changed since the mark, or
// false when everything may have.
func (m *atlasMark) changes(a *Atlas) ([]image.Rectangle, bool) {
if a == nil || m.atlas == nil {
return nil, a == m.atlas
}
if a != m.atlas {
return nil, false
}
rects, full := a.Changes(m.gen, m.version)
return rects, !full
}
func (m *atlasMark) set(a *Atlas) {
m.atlas = a
if a != nil {
m.gen, m.version = a.Generation(), a.Version()
}
}
// Invalidate makes the next Diff find that everything changed.
func (d *Differ) Invalidate() { d.valid = false }
// Diff compares s with the last scene Remember kept, and returns the
// rectangles where they differ, at most eight, apart from each other, or
// false when everything may have: none is kept, s is of another size, or
// starts with another color, or its atlases were reset. It finds where
// each operation of s draws as it goes (Bounds). The rectangles are valid
// until the next Diff.
func (d *Differ) Diff(s *Scene) ([]image.Rectangle, bool) {
d.next = d.opBounds(s, d.next[:0])
d.pre, d.suf, d.n, d.m = 0, 0, 0, len(s.Ops)
if !d.valid || s.Width != d.w || s.Height != d.h || s.Clear != d.clear || s.Text != d.text {
return nil, false
}
maskRects, ok := d.mask.changes(s.MaskAtlas)
if !ok {
return nil, false
}
colorRects, ok := d.color.changes(s.ColorAtlas)
if !ok {
return nil, false
}
same := func(i, j int) bool { return d.same(i, s, j, maskRects, colorRects) }
n, m := len(d.ops), len(s.Ops)
pre := 0
for pre < n && pre < m && same(pre, pre) {
pre++
}
suf := 0
for suf < n-pre && suf < m-pre && same(n-1-suf, m-1-suf) {
suf++
}
d.pre, d.suf, d.n, d.m = pre, suf, n, m
d.damage = d.damage[:0]
if n == m {
for k := pre; k < n-suf; k++ {
if !same(k, k) {
d.damage = addRect(d.damage, d.bounds[k])
d.damage = addRect(d.damage, d.next[k])
}
}
} else {
for i := pre; i < n-suf; i++ {
d.damage = addRect(d.damage, d.bounds[i])
}
for j := pre; j < m-suf; j++ {
d.damage = addRect(d.damage, d.next[j])
}
}
return d.damage, true
}
// Match returns the op of the last scene that op j of the scene Diff was
// given last stands for, and false for none: the rest of the ops in the
// same place, when the scenes have as many, that Diff found the same, and
// those it compared as changed, whose places are in the damage already.
// A renderer drawing an op that Match finds differently from the last
// frame (with another pipeline, say) damages its bounds.
func (d *Differ) Match(j int) (int, bool) {
switch {
case j < d.pre:
return j, true
case j >= d.m-d.suf && j < d.m:
return j - d.m + d.n, true
case d.n == d.m && j < d.m:
return j, true
}
return 0, false
}
// Bounds returns where each operation of the scene Diff was given last
// draws, within the clips around it.
func (d *Differ) Bounds() []image.Rectangle { return d.next }
// AddBackdrops adds to damage, rectangles to redraw in s after Diff, the
// effects of s that read their backdrops it meets, with those backdrops,
// and returns it: an effect reads its backdrop after drawing the
// operations before it within the area drawn, which must hold all of it
// for the backdrop to hold none of what the frame drew before. So the
// damage becomes rectangles apart from each other.
func (d *Differ) AddBackdrops(s *Scene, damage []image.Rectangle) []image.Rectangle {
if len(s.Effects) == 0 || len(damage) == 0 {
return damage
}
for changed := true; changed; {
changed = false
for i := range s.Ops {
op := &s.Ops[i]
if op.Kind != OpEffect || int(op.Start) >= len(s.Effects) || d.next[i].Empty() {
continue
}
fx := &s.Effects[op.Start]
if fx.Effect == nil || !fx.Effect.Backdrop {
continue
}
need := s.BackdropOf(op.Transform.Bounds(op.Rect), fx.Blur, s.Width, s.Height).Area.Union(d.next[i])
for _, r := range damage {
if r.Overlaps(need) && !need.In(r) {
damage = addRect(damage, need)
changed = true
break
}
}
}
// Rectangles that overlap become one.
for i := 0; i < len(damage); i++ {
for j := i + 1; j < len(damage); j++ {
if damage[i].Overlaps(damage[j]) {
damage[i] = damage[i].Union(damage[j])
damage = append(damage[:j], damage[j+1:]...)
changed = true
j = i
}
}
}
}
return damage
}
// same reports whether operation i of the last scene draws what operation
// j of s does.
func (d *Differ) same(i int, s *Scene, j int, maskRects, colorRects []image.Rectangle) bool {
a, b := d.ops[i], s.Ops[j]
// Glyphs and effects are compared by what Start and End point at.
sa, sb := a.Start, b.Start
ga, gb := d.glyphs[:0], s.Glyphs[:0]
if a.Kind == OpGlyphs && b.Kind == OpGlyphs {
ga, gb = d.glyphs[a.Start:a.End], s.Glyphs[b.Start:b.End]
} else if a.Kind == OpEffect && b.Kind == OpEffect && int(sa) < len(d.effects) && int(sb) < len(s.Effects) {
// A shader's effect filling mask glyphs.
x, y := d.effects[sa].Glyphs, s.Effects[sb].Glyphs
ga, gb = d.glyphs[x[0]:x[1]], s.Glyphs[y[0]:y[1]]
}
a.Start, a.End, b.Start, b.End = 0, 0, 0, 0
if a.Kind == OpPushClip && d.encloses[i] != d.encloses2[j] {
return false
}
// Gradients' stops are compared by what Stops point at.
if !sameStops(d.stops, a.Stops, s.Stops, b.Stops) {
return false
}
a.Stops, b.Stops = [2]int32{}, [2]int32{}
// The colors outside the sRGB gamut are compared by what Wide points
// at in each scene's own table.
wa, wb := a.Wide, b.Wide
a.Wide, b.Wide = 0, 0
if a != b || !d.sameWide(wa, s, wb) {
return false
}
if !d.sameGlyphs(ga, s, gb, maskRects, colorRects) {
return false
}
switch b.Kind {
case OpImage, OpPushClip:
// A clip's image masks it.
if b.Image != nil && b.Image.Version() != d.versions[i] {
return false
}
case OpEffect:
if int(sa) >= len(d.effects) || int(sb) >= len(s.Effects) || !d.effects[sa].Same(&s.Effects[sb]) {
return false
}
}
return true
}
// sameWide reports whether the colors outside the sRGB gamut that wa
// points at in the last scene are those wb does in s, when they are drawn.
func (d *Differ) sameWide(wa uint16, s *Scene, wb uint16) bool {
if !d.Wide || wa == 0 && wb == 0 {
return true
}
if wa == 0 || wb == 0 || int(wa) > len(d.wide) || int(wb) > len(s.Wide) {
return false
}
return d.wide[wa-1] == s.Wide[wb-1]
}
// sameStops reports whether stops sa[a[0]:a[1]] of the last scene are
// those sb[b[0]:b[1]] of the new one.
func sameStops(sa []Stop, a [2]int32, sb []Stop, b [2]int32) bool {
if a[1]-a[0] != b[1]-b[0] {
return false
}
if a[1] <= a[0] {
return true
}
if int(a[1]) > len(sa) || int(b[1]) > len(sb) || a[0] < 0 || b[0] < 0 {
return false
}
for i := range a[1] - a[0] {
if sa[a[0]+i] != sb[b[0]+i] {
return false
}
}
return true
}
// sameGlyphs reports whether glyphs ga of the last scene draw what gb of
// s do, none of them in an area of the atlases that changed.
func (d *Differ) sameGlyphs(ga []Glyph, s *Scene, gb []Glyph, maskRects, colorRects []image.Rectangle) bool {
if len(ga) != len(gb) {
return false
}
for k := range gb {
g := &gb[k]
if x := ga[k]; x != *g {
wa := x.Wide
x.Wide = g.Wide
if x != *g || !d.sameWide(wa, s, g.Wide) {
return false
}
} else if d.Wide && g.Wide != 0 && !d.sameWide(g.Wide, s, g.Wide) {
return false
}
rects := maskRects
if g.Colored {
rects = colorRects
}
at := image.Rect(int(g.U), int(g.V), int(g.U)+int(g.UW), int(g.V)+int(g.VH))
for _, c := range rects {
if c.Overlaps(at) {
return false
}
}
}
return true
}
// addRect adds a rectangle to damage, merged with one it touches.
func addRect(damage []image.Rectangle, b image.Rectangle) []image.Rectangle {
if b.Empty() {
return damage
}
for i, d := range damage {
if d.Inset(-8).Overlaps(b) {
damage[i] = d.Union(b)
return damage
}
}
damage = append(damage, b)
if len(damage) > 8 {
u := damage[0]
for _, d := range damage[1:] {
u = u.Union(d)
}
damage = append(damage[:0], u)
}
return damage
}
// opBounds appends where each operation of s draws, within the clips
// around it.
func (d *Differ) opBounds(s *Scene, out []image.Rectangle) []image.Rectangle {
clip := image.Rect(0, 0, s.Width, s.Height)
d.clips, d.pushes = d.clips[:0], d.pushes[:0]
d.corners.Reset()
d.encloses2 = append(d.encloses2[:0], make([]bool, len(s.Ops))...)
reach := func(m Affine) float32 {
if m.Set {
return d.Reach + 3
}
return d.Reach
}
for i := range s.Ops {
op := &s.Ops[i]
var b image.Rectangle
corners := false
switch op.Kind {
case OpFill, OpImage, OpEffect, OpHole:
b = outset(op.Transform.Bounds(op.Rect), reach(op.Transform))
case OpShadow:
if op.Inset {
b = outset(op.Transform.Bounds(op.Cast), reach(op.Transform))
} else {
e := 1.5*op.Blur + 1
box := Rect{X: op.Rect.X - e, Y: op.Rect.Y - e, W: op.Rect.W + 2*e, H: op.Rect.H + 2*e}
b = outset(op.Transform.Bounds(box), reach(op.Transform))
}
case OpGlyphs:
// The glyphs without transforms of their own as one box, which
// the op's transform maps, the others each.
x0, y0, x1, y1 := float32(math.MaxFloat32), float32(math.MaxFloat32), float32(-math.MaxFloat32), float32(-math.MaxFloat32)
for _, g := range s.Glyphs[op.Start:op.End] {
// The GPU's renderers draw the bitmap's own size, at a
// whole pixel.
w, h := max(g.W, float32(g.UW)), max(g.H, float32(g.VH))
if !g.Transform.Set {
x0, y0, x1, y1 = min(x0, g.X), min(y0, g.Y), max(x1, g.X+w), max(y1, g.Y+h)
continue
}
m := op.Transform.Mul(g.Transform)
b = b.Union(outset(m.Bounds(Rect{X: g.X, Y: g.Y, W: w, H: h}), reach(m)))
}
switch {
case x0 > x1:
case op.Transform.Set:
b = b.Union(outset(op.Transform.Bounds(Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}), reach(op.Transform)))
default:
b = b.Union(outsetEdges(x0, y0, x1, y1, d.Reach))
}
case OpPushClip:
// A clip that changes changes everything it cuts.
b = outset(op.Transform.Bounds(op.Rect), reach(op.Transform))
d.clips = append(d.clips, clip)
d.pushes = append(d.pushes, i)
clip = clip.Intersect(b)
corners = d.corners.Push(op) >= 0
case OpPopClip:
if len(d.clips) > 0 {
clip = d.clips[len(d.clips)-1]
d.clips = d.clips[:len(d.clips)-1]
d.pushes = d.pushes[:len(d.pushes)-1]
d.corners.Pop()
}
}
// The GPU's renderers cut what a clip holds with a mask once an op
// in it is drawn under a transform that does more than move it
// (Reshaped), and in the shader otherwise, which differ at its
// edge by a unit in the last place: a clip that starts or stops
// holding one changes all it cuts. A clip pushed under such a
// transform is one for the clips around it, not for itself, which
// it was pushed onto already (as gpu.Builder.markEnclosing has it).
// So does a clip that starts or stops holding one that reaches
// into its rounded corners, or those of a clip it is in
// (ClipCorners).
if corners || op.Kind != OpPopClip && Reshaped(s, op) {
j := len(d.pushes) - 1
if op.Kind == OpPushClip {
j--
}
for ; j >= 0 && !d.encloses2[d.pushes[j]]; j-- {
d.encloses2[d.pushes[j]] = true
}
}
out = append(out, b.Intersect(clip))
}
return out
}
// outsetEdges returns the pixels the box from x0, y0 to x1, y1 grown by d
// touches.
func outsetEdges(x0, y0, x1, y1, d float32) image.Rectangle {
return image.Rect(int(math.Floor(float64(x0-d))), int(math.Floor(float64(y0-d))),
int(math.Ceil(float64(x1+d))), int(math.Ceil(float64(y1+d))))
}
func outset(rc Rect, d float32) image.Rectangle {
return image.Rect(int(math.Floor(float64(rc.X-d))), int(math.Floor(float64(rc.Y-d))),
int(math.Ceil(float64(rc.X+rc.W+d))), int(math.Ceil(float64(rc.Y+rc.H+d))))
}
// Remember keeps what Diff needs of s, which Diff was given last, to
// compare the next scene with.
func (d *Differ) Remember(s *Scene) {
d.valid = true
d.w, d.h = s.Width, s.Height
d.clear, d.text = s.Clear, s.Text
if len(d.ops) > len(s.Ops) {
clear(d.ops[len(s.Ops):])
}
d.ops = append(d.ops[:0], s.Ops...)
d.glyphs = append(d.glyphs[:0], s.Glyphs...)
d.stops = append(d.stops[:0], s.Stops...)
d.wide = d.wide[:0]
if d.Wide {
d.wide = append(d.wide, s.Wide...)
}
if len(d.effects) > len(s.Effects) {
clear(d.effects[len(s.Effects):])
}
d.effects = append(d.effects[:0], s.Effects...)
// The uniforms' and the quads' words, which the scene reuses next
// frame (Words), kept apart.
d.words = d.words[:0]
for i := range d.effects {
d.words = append(d.words, d.effects[i].Uniforms...)
d.words = append(d.words, d.effects[i].WideUniforms...)
d.words = append(d.words, d.effects[i].Instances...)
}
at := 0
for i := range d.effects {
fx := &d.effects[i]
n, w, q := len(fx.Uniforms), len(fx.WideUniforms), len(fx.Instances)
fx.Uniforms = d.words[at : at+n : at+n]
if fx.WideUniforms != nil {
fx.WideUniforms = d.words[at+n : at+n+w : at+n+w]
}
if fx.Instances != nil {
fx.Instances = d.words[at+n+w : at+n+w+q : at+n+w+q]
}
at += n + w + q
}
d.bounds, d.next = d.next, d.bounds
d.encloses, d.encloses2 = d.encloses2, d.encloses
d.versions = d.versions[:0]
for i := range s.Ops {
v := uint64(0)
if img := s.Ops[i].Image; img != nil {
v = img.Version()
}
d.versions = append(d.versions, v)
}
d.mask.set(s.MaskAtlas)
d.color.set(s.ColorAtlas)
}
// Release forgets the last scene and lets go of what it kept.
func (d *Differ) Release() {
reach, wide := d.Reach, d.Wide
*d = Differ{Reach: reach, Wide: wide}
}
+152
View File
@@ -0,0 +1,152 @@
package scene
import (
"image"
"math"
"testing"
)
// TestDamageOfNestedTransformedClip checks that a clip under a
// transform that turns it, nested in a rounded one, changes all the
// rounded one cuts as it comes and goes: the GPU's renderers then cut the
// outer clip with a mask rather than in the shader, at its edges a unit in
// the last place apart. A clip only moved changes nothing around it, as
// the renderers cut it as any other.
func TestDamageOfNestedTransformedClip(t *testing.T) {
outer := Op{Kind: OpPushClip, Rect: Rect{X: 10, Y: 10, W: 150, H: 150}, Radii: Uniform(8)}
corner := Op{Kind: OpFill, Rect: Rect{X: 10, Y: 10, W: 20, H: 20}, Color: Color{R: 255, A: 255}}
nested := []Op{
{Kind: OpPushClip, Rect: Rect{W: 40, H: 40}, Transform: Translation(100, 100).Mul(Rotation(10))},
{Kind: OpFill, Rect: Rect{X: 100, Y: 100, W: 20, H: 20}, Color: Color{G: 255, A: 255}},
{Kind: OpPopClip},
}
without := &Scene{Width: 200, Height: 200, Ops: []Op{outer, corner, {Kind: OpPopClip}}}
with := &Scene{Width: 200, Height: 200, Ops: append(append([]Op{outer, corner}, nested...), Op{Kind: OpPopClip})}
for _, frames := range [][2]*Scene{{without, with}, {with, without}} {
d := Differ{Reach: 2}
d.Diff(frames[0])
d.Remember(frames[0])
damage, ok := d.Diff(frames[1])
if !ok {
t.Fatal("no damage found")
}
// The fill in the outer clip's corner, which the inner clip
// does not reach.
at := image.Rect(10, 10, 30, 30)
hit := false
for _, r := range damage {
hit = hit || at.In(r)
}
if !hit {
t.Errorf("%d to %d ops: damage %v misses %v", len(frames[0].Ops), len(frames[1].Ops), damage, at)
}
}
nested[0].Transform = Translation(100.5, 100.25)
with.Ops = append(append([]Op{outer, corner}, nested...), Op{Kind: OpPopClip})
d := Differ{Reach: 2}
d.Diff(without)
d.Remember(without)
damage, _ := d.Diff(with)
for _, r := range damage {
if r.Overlaps(image.Rect(10, 10, 30, 30)) {
t.Errorf("a clip only moved coming: damage %v reaches the outer clip's corner", damage)
}
}
}
// TestDamageOfClipInRoundedCorners checks that a clip reaching into the
// corners of a rounded one changes all the rounded one cuts as it comes
// and goes, which the GPU's renderers then cut with a mask (#1418), and
// that one away from them changes only what it cuts.
func TestDamageOfClipInRoundedCorners(t *testing.T) {
outer := Op{Kind: OpPushClip, Rect: Rect{X: 10, Y: 10, W: 150, H: 150}, Radii: Uniform(8)}
corner := Op{Kind: OpFill, Rect: Rect{X: 10, Y: 10, W: 20, H: 20}, Color: Color{R: 255, A: 255}}
nested := func(r Rect) []Op {
return []Op{{Kind: OpPushClip, Rect: r}, {Kind: OpFill, Rect: r, Color: Color{G: 255, A: 255}}, {Kind: OpPopClip}}
}
without := &Scene{Width: 200, Height: 200, Ops: []Op{outer, corner, {Kind: OpPopClip}}}
at := image.Rect(10, 10, 30, 30)
for _, c := range []struct {
r Rect
corners bool
}{{Rect{X: 10, Y: 120, W: 150, H: 40}, true}, {Rect{X: 60, Y: 60, W: 40, H: 40}, false}} {
with := &Scene{Width: 200, Height: 200, Ops: append(append([]Op{outer, corner}, nested(c.r)...), Op{Kind: OpPopClip})}
for _, frames := range [][2]*Scene{{without, with}, {with, without}} {
d := Differ{Reach: 2}
d.Diff(frames[0])
d.Remember(frames[0])
damage, ok := d.Diff(frames[1])
if !ok {
t.Fatal("no damage found")
}
hit := false
for _, r := range damage {
hit = hit || r.Overlaps(at)
}
if hit != c.corners {
t.Errorf("clip %v, %d to %d ops: damage %v reaches %v: %v", c.r, len(frames[0].Ops), len(frames[1].Ops), damage, at, hit)
}
}
}
}
// A masked clip changes all it cuts when its mask changes: the stops of
// its gradient, or the pixels of its image; and nothing when they are the
// same, in another frame's scene.
func TestDamageOfMaskedClip(t *testing.T) {
img := NewImageRGBA(4, 4, make([]byte, 64))
build := func(alpha uint8) *Scene {
return &Scene{Width: 100, Height: 100, Stops: []Stop{{Color: Color{A: alpha}}, {Color: Color{}, At: 1}}, Ops: []Op{
{Kind: OpPushClip, Rect: Rect{X: 10, Y: 10, W: 40, H: 40}, Paint: PaintLinearStops, Gradient: [4]float32{10, 10, 50, 10}, Stops: [2]int32{0, 2}},
{Kind: OpFill, Rect: Rect{X: 10, Y: 10, W: 40, H: 40}, Color: Color{R: 255, A: 255}},
{Kind: OpPopClip},
{Kind: OpPushClip, Rect: Rect{X: 60, Y: 60, W: 4, H: 4}, Image: img, Src: Rect{W: 4, H: 4}},
{Kind: OpFill, Rect: Rect{X: 60, Y: 60, W: 4, H: 4}, Color: Color{G: 255, A: 255}},
{Kind: OpPopClip},
}}
}
d := Differ{Reach: 1}
d.Diff(build(255))
d.Remember(build(255))
if damage, ok := d.Diff(build(255)); !ok || len(damage) != 0 {
t.Fatalf("the same masks: damage %v, %v", damage, ok)
}
d.Remember(build(255))
if damage, ok := d.Diff(build(128)); !ok || len(damage) != 1 || !image.Rect(10, 10, 50, 50).In(damage[0]) {
t.Errorf("other stops: damage %v, %v", damage, ok)
}
d.Remember(build(128))
img.Changed()
if damage, ok := d.Diff(build(128)); !ok || len(damage) != 1 || !image.Rect(60, 60, 64, 64).In(damage[0]) {
t.Errorf("the image changed: damage %v, %v", damage, ok)
}
}
// An effect painting quads (EffectOp.Instances) damages where it paints
// when a quad's data changes, though the scene reuses its words next
// frame (Words), and nothing when the quads stay the same.
func TestDamageOfInstances(t *testing.T) {
fx := &Effect{Name: "quads"}
words := make([]uint32, 2*(InstanceHead+1))
build := func(data float32) *Scene {
for i, q := range []Rect{{X: 10, Y: 10, W: 20, H: 20}, {X: 50, Y: 40, W: 20, H: 20}} {
w := words[i*(InstanceHead+1):]
for k, v := range []float32{q.X, q.Y, q.W, q.H, q.W, q.H, data} {
w[k] = math.Float32bits(v)
}
}
return &Scene{Width: 100, Height: 100, Words: words,
Ops: []Op{{Kind: OpEffect, Rect: Rect{X: 10, Y: 10, W: 60, H: 50}}},
Effects: []EffectOp{{Effect: fx, Instances: words, InstanceWords: InstanceHead + 1}}}
}
d := Differ{Reach: 1}
d.Diff(build(1))
d.Remember(build(1))
if damage, ok := d.Diff(build(1)); !ok || len(damage) != 0 {
t.Fatalf("the same quads: damage %v, %v", damage, ok)
}
d.Remember(build(1))
if damage, ok := d.Diff(build(2)); !ok || len(damage) != 1 || !image.Rect(10, 10, 70, 60).In(damage[0]) {
t.Errorf("other data: damage %v, %v", damage, ok)
}
}
+360
View File
@@ -0,0 +1,360 @@
package scene
import (
"image"
"math"
"slices"
)
// Effect is a kind of drawing that a package outside the renderers
// defines, as the official plugins do (plugins/glass): a fragment shader
// for each GPU renderer, drawn with a pipeline of its own, and its twin
// for the CPU renderer, which must compute the same colors. An effect
// paints the shape of its OpEffect (Rect rounded by Radii) from its
// parameters, and from its backdrop when it reads one: what the
// operations before it painted around it, blurred (see Backdrop).
//
// Each shader is the source of a function that the renderer puts between
// a head and a tail of its own, which declare what it reads and call it
// (EffectSource in packages metal, d3d11 and gl):
//
// Metal: float4 effect(float2 p, Effect e, texture2d<float> backdrop)
// HLSL: float4 effect(float2 p, Effect e)
// GLSL: vec4 effect(vec2 p, Effect e)
//
// It returns the premultiplied color at the pixel center p, in device
// pixels, of the shape e.rect rounded by e.radii, from the parameters
// e.p0 to e.p4 (EffectOp.Params); the renderer multiplies it by how much
// of the pixel the shape and the clip cover, and by the opacity. The
// shape's corners may be continuous (Op.Continuous), which the renderer
// covers as such, while e.radii, positive, has the effect take them as
// circular. In Metal, e.wide tells that the target keeps colors outside
// the sRGB gamut, in extended sRGB (Scene.Wide), which the effect may then
// take from a parameter holding such a color (ui.Painter.EffectColor).
// sampleBackdrop(e, q) (with the backdrop texture first in Metal) returns
// the backdrop at q, premultiplied, as BackdropImage.Sample does.
type Effect struct {
// Name names the effect in errors.
Name string
// Backdrop tells that the effect reads its backdrop.
Backdrop bool
// Metal and HLSL are the effect's shader in Metal Shading Language
// and HLSL, with the code compiled ahead of time from it; GLSL is its
// shader in GLSL 3.30 and GLSL ES 3.00, which drivers compile.
Metal, HLSL EffectCode
GLSL string
// Pixels makes what draws the effect on the CPU, one for each
// renderer.
Pixels func() EffectPixels
// Shader is set for an effect that a shader of package ui/shader
// draws: its code is the shader's (the Fragment of package shaderir's
// backends, and a function calling it), which reads the words of
// EffectOp.Uniforms in a buffer laid out as Shader says, and the images
// of EffectOp.Images. Metal's is a whole library, with a tail of its
// own (ShaderSource in package metal); the others' go between the
// effects' head and tail.
Shader *ShaderLayout
}
// ShaderLayout is where a shader's uniforms lie in the buffer its code
// reads: the offset in bytes of each word of EffectOp.Uniforms, and the
// buffer's size in bytes, a multiple of 16.
type ShaderLayout struct {
Lanes []int32
Size int
}
// Pack writes words into buf, grown to the layout's size, as the layout
// lays them out, and returns it. A lane takes 4 bytes, but for a bool of
// Metal, which takes 1 and may lie in the last bytes: the bytes that fit
// are written, little end first, and lanes in ascending order write over
// what the one before spilled.
func (l *ShaderLayout) Pack(buf []byte, words []uint32) []byte {
if cap(buf) < l.Size {
buf = make([]byte, l.Size)
}
buf = buf[:l.Size]
clear(buf)
for i, at := range l.Lanes {
if i >= len(words) {
break
}
w := words[i]
for k := 0; k < 4 && int(at)+k < len(buf); k++ {
buf[int(at)+k] = byte(w >> (8 * k))
}
}
return buf
}
// EffectCode is an effect's shader in a language: its source, and the
// code compiled ahead of time from what the renderer makes of it
// (EffectSource), with the SHA-256 of that (gpu.SourceSum). Renderers
// compile the source when the sum no longer matches, as when the
// renderer's head or tail changed since.
type EffectCode struct {
Source string
Compiled []byte
Sum string
}
// EffectOp is the effect of an OpEffect, with its parameters.
type EffectOp struct {
Effect *Effect
// Blur is the standard deviation of the blur of the backdrop, in
// pixels, for an effect that reads its backdrop.
Blur float32
// Params are the effect's own, which its shaders read as e.p0 to e.p4.
Params [5][4]float32
// Uniforms and Images are what a shader's effect reads
// (Effect.Shader): the words of its uniforms' lanes, and up to four
// images, bitmaps or canvases, nil for none.
Uniforms []uint32
Images [4]*Image
// WideUniforms, unless nil, are the words of Uniforms that renderers
// drawing a wide gamut (Scene.Wide) read in its place: colors outside
// the sRGB gamut in extended sRGB, where Uniforms holds the nearest
// sRGB ones.
WideUniforms []uint32
// Glyphs, unless empty, are the mask glyphs Scene.Glyphs[Glyphs[0]:
// Glyphs[1]] that a shader's effect paints instead of the rounded
// rectangle: the shapes of text, paths and icons, which it fills, each
// pixel's color times the glyph's coverage, corrected as text's is
// (TextCoverage) for the color the shader returns. Rect then holds
// them, and Origin is the point its shader's positions start from, the
// top left corner of the box it fills.
Glyphs [2]int32
Origin [2]float32
// Instances, unless empty, are the quads a shader's effect paints
// instead of the rounded rectangle, each rounded by the op's Radii,
// which Rect then holds: InstanceWords words each, the bits of floats
// (InstanceRect), its rectangle in pixels, as Rect, from whose corner
// its shader's positions start, its size in DIPs, which its shader
// reads (rectSize), then its data (instanceData), in Scene.Words.
// Instance is the index of the first, which the CPU renderer, readying
// one quad at a time (EffectPixels), sets.
Instances []uint32
InstanceWords int32
Instance int32
}
// InstanceHead is how many words of each of EffectOp.Instances come before
// its data: its rectangle and its size in DIPs.
const InstanceHead = 6
// MaxInstanceData is how many words of data a quad of EffectOp.Instances
// has at most: the GPU's renderers carry them in the four float4s of an
// effect's parameters (EffectOp.Params) that every instance has.
const MaxInstanceData = 16
// Masked reports whether op paints mask glyphs (Glyphs).
func (op *EffectOp) Masked() bool { return op.Glyphs[1] > op.Glyphs[0] }
// InstanceCount returns how many quads op paints (Instances), or 0.
func (op *EffectOp) InstanceCount() int {
if op.InstanceWords < InstanceHead {
return 0
}
return len(op.Instances) / int(op.InstanceWords)
}
// InstanceRect returns the rectangle of quad i of op, in pixels, and its
// size in DIPs.
func (op *EffectOp) InstanceRect(i int) (Rect, [2]float32) {
w := op.Instances[i*int(op.InstanceWords):][:InstanceHead]
f := func(k int) float32 { return math.Float32frombits(w[k]) }
return Rect{f(0), f(1), f(2), f(3)}, [2]float32{f(4), f(5)}
}
// InstanceData returns the words of the data of quad i of op.
func (op *EffectOp) InstanceData(i int) []uint32 {
n := int(op.InstanceWords)
return op.Instances[i*n+InstanceHead : (i+1)*n]
}
// Same reports whether op draws what o does: the same effect with the same
// parameters, the same uniforms, the same quads (Instances) and no images,
// whose pixels may change. Glyphs are compared by what they point at, which
// the caller does.
func (op *EffectOp) Same(o *EffectOp) bool {
if op.Effect != o.Effect || op.Blur != o.Blur || op.Params != o.Params || len(op.Uniforms) != len(o.Uniforms) ||
op.Masked() != o.Masked() || op.Glyphs[1]-op.Glyphs[0] != o.Glyphs[1]-o.Glyphs[0] || op.Origin != o.Origin ||
op.InstanceWords != o.InstanceWords || op.Instance != o.Instance || !slices.Equal(op.Instances, o.Instances) {
return false
}
for i := range op.Images {
if op.Images[i] != nil || o.Images[i] != nil {
return false
}
}
for i := range op.Uniforms {
if op.Uniforms[i] != o.Uniforms[i] {
return false
}
}
if len(op.WideUniforms) != len(o.WideUniforms) {
return false
}
for i := range op.WideUniforms {
if op.WideUniforms[i] != o.WideUniforms[i] {
return false
}
}
return true
}
// EffectPixels draws an effect on the CPU, for one renderer.
type EffectPixels interface {
// Begin readies drawing op, the shape rect rounded by radii (fitted),
// before its pixels, which several cores may then ask for at once.
Begin(op *EffectOp, rect Rect, radii [4]float32)
// Color returns the premultiplied color of the effect at the pixel
// center (x, y), as its shaders' effect does, over the backdrop b (nil
// for an effect reading none).
Color(x, y float32, b *BackdropImage) [4]float32
}
// Backdrop is what an effect reads of what is behind it: the pixels of
// Area, averaged over squares of Down pixels a side into a smaller image
// (Size), which a Gaussian of standard deviation Sigma (BlurWeight) blurs,
// out to Radius texels each way, first along rows, then along columns.
// Renderers keep each step in 8 bits a channel, rounded to the nearest,
// as textures hold them.
type Backdrop struct {
Area image.Rectangle
Down int
Sigma float32
Radius int
}
// BackdropOf returns the backdrop of a shape r blurred by blur, in a frame
// of w×h pixels: what the blur reaches around it.
//
// Large blurs are computed at a fraction of the size, as browsers do,
// a power of two up to 8 that leaves the blur at least 2 texels: the
// average of each square adds a variance of Down²/12 pixels², which the
// blur leaves out.
func BackdropOf(r Rect, blur float32, w, h int) Backdrop {
blur = max(blur, 0)
down := 1
for down < 8 && blur/float32(2*down) >= 2 {
down *= 2
}
sigma := float32(math.Sqrt(math.Max(float64(blur*blur)-float64(down*down)/12, 0))) / float32(down)
if blur == 0 {
sigma = 0
}
radius := int(math.Ceil(float64(3 * sigma)))
reach := float32(radius*down + down)
area := image.Rect(int(math.Floor(float64(r.X-reach))), int(math.Floor(float64(r.Y-reach))),
int(math.Ceil(float64(r.X+r.W+reach))), int(math.Ceil(float64(r.Y+r.H+reach))))
return Backdrop{Area: area.Intersect(image.Rect(0, 0, w, h)), Down: down, Sigma: sigma, Radius: radius}
}
// ImageBlur returns how an image's area is blurred by blur, the standard
// deviation in its pixels (Op.Blur): averaged over squares of Down pixels
// a side and blurred as a backdrop is (BackdropOf), within the area, which
// it reads as transparent beyond.
func ImageBlur(area image.Rectangle, blur float32) Backdrop {
b := BackdropOf(Rect{}, blur, 0, 0)
b.Area = area
return b
}
// ImageSrc returns where src, a rectangle of an image's pixels within the
// area b blurs, lies in the blurred texels.
func (b Backdrop) ImageSrc(src Rect) Rect {
k := float32(b.Down)
return Rect{X: (src.X - float32(b.Area.Min.X)) / k, Y: (src.Y - float32(b.Area.Min.Y)) / k, W: src.W / k, H: src.H / k}
}
// ImageArea returns the pixels of an image of w×h that src, a rectangle
// of them, touches, which a blur of it reads.
func ImageArea(src Rect, w, h int) image.Rectangle {
if src.W < 0 {
src.X, src.W = src.X+src.W, -src.W
}
if src.H < 0 {
src.Y, src.H = src.Y+src.H, -src.H
}
return image.Rect(int(math.Floor(float64(src.X))), int(math.Floor(float64(src.Y))),
int(math.Ceil(float64(src.X+src.W))), int(math.Ceil(float64(src.Y+src.H)))).Intersect(image.Rect(0, 0, w, h))
}
// Size returns the size of the averaged image, in texels.
func (b Backdrop) Size() (w, h int) {
return (b.Area.Dx() + b.Down - 1) / b.Down, (b.Area.Dy() + b.Down - 1) / b.Down
}
// BlurWeight returns the weight of the texel i texels away in a blur of
// standard deviation sigma, before the weights are divided by their sum.
func BlurWeight(i int, sigma float32) float32 {
if sigma <= 0 {
return 1
}
x := float32(i)
return float32(math.Exp(float64(-(x * x) / (2 * sigma * sigma))))
}
// BackdropImage is a backdrop as the CPU renderer computes it: W×H texels
// of premultiplied RGBA, each channel a byte over 255, as a texture
// reads.
type BackdropImage struct {
Backdrop
// Transform maps local sampling coordinates to the frame.
Transform Affine
W, H int
Pix []float32
}
// Sample returns the backdrop at (x, y), in the frame's pixels,
// premultiplied RGB, filtered bilinearly from its texels and clamped to
// its edges, as the shaders' sampleBackdrop.
func (b *BackdropImage) Sample(x, y float32) [3]float32 {
x, y = b.Transform.Point(x, y)
k := float32(b.Down)
u := (x-float32(b.Area.Min.X))/k - 0.5
v := (y-float32(b.Area.Min.Y))/k - 0.5
fu, fv := float32(math.Floor(float64(u))), float32(math.Floor(float64(v)))
tx, ty := u-fu, v-fv
x0, y0 := min(max(int(fu), 0), b.W-1), min(max(int(fv), 0), b.H-1)
x1, y1 := min(max(int(fu)+1, 0), b.W-1), min(max(int(fv)+1, 0), b.H-1)
p00, p10 := b.Pix[4*(y0*b.W+x0):][:3], b.Pix[4*(y0*b.W+x1):][:3]
p01, p11 := b.Pix[4*(y1*b.W+x0):][:3], b.Pix[4*(y1*b.W+x1):][:3]
var c [3]float32
for i := range c {
top := p00[i]*(1-tx) + p10[i]*tx
bot := p01[i]*(1-tx) + p11[i]*tx
c[i] = top*(1-ty) + bot*ty
}
return c
}
// SDRoundRect returns the signed distance from (px, py) to the edge of
// the rounded rectangle r with radii (fitted), negative inside, as the
// shaders' sdRoundRect.
func SDRoundRect(r Rect, radii [4]float32, px, py float32) float32 {
hx, hy := r.W/2, r.H/2
qx, qy := px-r.X-hx, py-r.Y-hy
var rad float32
switch {
case qx < 0 && qy < 0:
rad = radii[0]
case qx >= 0 && qy < 0:
rad = radii[1]
case qx >= 0:
rad = radii[2]
default:
rad = radii[3]
}
ax, ay := absf(qx)-hx+rad, absf(qy)-hy+rad
mx, my := max(ax, 0), max(ay, 0)
return float32(math.Sqrt(float64(mx*mx+my*my))) + min(max(ax, ay), 0) - rad
}
func absf(v float32) float32 {
if v < 0 {
return -v
}
return v
}
+142
View File
@@ -0,0 +1,142 @@
package scene
import (
"math"
"sync/atomic"
)
// Translation returns how far m moves, when it only translates.
func (m Affine) Translation() (x, y float32, ok bool) {
if !m.Set || m.A != 1 || m.B != 0 || m.C != 0 || m.D != 1 || m.G != 0 || m.H != 0 {
return 0, 0, false
}
return m.X, m.Y, true
}
// TranslationFolder folds the transforms of a scene's ops that only
// translate (an element's Translate, which animations move) into their
// geometry, reusing its memory from scene to scene: renderers then draw
// them as they draw ops without transforms, the GPU's with the shaders of
// those (gpu.Class), not the general one, and the CPU's without sampling
// pixels on a grid. Both renderers fold, so that they keep drawing the
// same pixels.
//
// Renderers fold once FoldTranslations was called, which package ui does
// where it makes translations: apps that never translate carry none of
// the code.
type TranslationFolder struct {
s Scene
ops []Op
glyphs []Glyph
}
// foldFunc is TranslationFolder.fold.
type foldFunc func(f *TranslationFolder, s *Scene) *Scene
// fold is TranslationFolder.fold once FoldTranslations was called. It is
// atomic, as ui.Translation calls FoldTranslations on any goroutine while
// renderers read it on theirs.
var fold atomic.Pointer[foldFunc]
// FoldTranslations makes renderers fold the ops that only translate
// (TranslationFolder), from the next scene they draw. Package ui calls it
// as it builds a view, before drawing it, each frame, and wherever it makes
// a translation, on any goroutine: it sets fold only the first time, and
// costs a load after.
func FoldTranslations() {
if fold.Load() == nil {
f := foldFunc((*TranslationFolder).fold)
fold.CompareAndSwap(nil, &f)
}
}
// Fold returns s, or, when any of its ops only translates, a copy of it
// with those folded: fills and shadows, and images and glyphs moved by
// whole pixels, glyphs without transforms of their own (renderers round
// their places, a glyph's bitmap staying on whole pixels without a
// transform), and clips: their edges are computed where they fall, as a
// fill's, rather than rasterized into a mask each frame the clip moves.
// Effects and holes keep their transforms. The copy holds until the next
// Fold. Before FoldTranslations, it returns s.
func (f *TranslationFolder) Fold(s *Scene) *Scene {
fn := fold.Load()
if fn == nil {
return s
}
return (*fn)(f, s)
}
func (f *TranslationFolder) fold(s *Scene) *Scene {
first := -1
for i := range s.Ops {
if folds(s, &s.Ops[i]) {
first = i
break
}
}
if first < 0 {
return s
}
f.ops = append(f.ops[:0], s.Ops...)
f.s = *s
f.s.Ops = f.ops
copied := false
for i := first; i < len(f.ops); i++ {
op := &f.ops[i]
if !folds(s, op) {
continue
}
x, y := op.Transform.X, op.Transform.Y
op.Transform = Affine{}
op.Rect.X, op.Rect.Y = op.Rect.X+x, op.Rect.Y+y
switch op.Kind {
case OpShadow:
if !op.Cast.Empty() {
op.Cast.X, op.Cast.Y = op.Cast.X+x, op.Cast.Y+y
}
case OpGlyphs:
if !copied {
f.glyphs = append(f.glyphs[:0], s.Glyphs...)
f.s.Glyphs, copied = f.glyphs, true
}
for j := op.Start; j < op.End; j++ {
g := &f.glyphs[j]
g.X = float32(math.Round(float64(g.X))) + x
g.Y = float32(math.Round(float64(g.Y))) + y
}
}
if op.Kind == OpFill || op.Kind == OpGlyphs || op.Kind == OpPushClip {
// The points of gradients, a clip's masking it among them.
op.moveGradient(x, y)
}
}
return &f.s
}
// folds reports whether Fold folds op of s.
func folds(s *Scene, op *Op) bool {
x, y, ok := op.Transform.Translation()
if !ok {
return false
}
whole := x == float32(math.Trunc(float64(x))) && y == float32(math.Trunc(float64(y)))
switch op.Kind {
case OpFill, OpShadow, OpPushClip:
return true
case OpImage:
// Images sample their texels where they fall, which the CPU's
// renderer and the GPU's place apart between pixels.
return whole
case OpGlyphs:
if !whole || op.Start < 0 || op.Start > op.End || op.End > int32(len(s.Glyphs)) {
return false
}
for _, g := range s.Glyphs[op.Start:op.End] {
if g.Transform.Set {
return false
}
}
return true
}
return false
}
+81
View File
@@ -0,0 +1,81 @@
package scene
import (
"sync"
"testing"
)
func TestFoldTranslations(t *testing.T) {
m, between := Translation(10, 20), Translation(0.5, 1)
s := &Scene{Width: 100, Height: 100, Glyphs: []Glyph{{X: 3.4, Y: 5.6}, {X: 1, Y: 1}}, Ops: []Op{
{Kind: OpFill, Rect: Rect{X: 1, Y: 2, W: 3, H: 4}, Paint: PaintLinear, Gradient: [4]float32{0, 0, 3, 4}, Transform: m},
{Kind: OpFill, Rect: Rect{W: 3, H: 4}, Paint: PaintStripes, Gradient: [4]float32{1, 0, 2, 4}, Transform: between},
{Kind: OpShadow, Rect: Rect{W: 5, H: 5}, Cast: Rect{X: 1, W: 4, H: 4}, Transform: m},
{Kind: OpGlyphs, Start: 0, End: 1, Paint: PaintConic, Gradient: [4]float32{1, 1, 2, 0}, Transform: m},
{Kind: OpGlyphs, Start: 1, End: 2, Transform: between},
{Kind: OpImage, Rect: Rect{W: 2, H: 2}, Transform: m},
{Kind: OpImage, Rect: Rect{W: 2, H: 2}, Transform: between},
{Kind: OpPushClip, Rect: Rect{W: 50, H: 50}, Transform: m},
{Kind: OpFill, Rect: Rect{W: 3, H: 4}, Transform: m.Mul(Rotation(10))},
{Kind: OpPopClip},
{Kind: OpPushClip, Rect: Rect{W: 50, H: 50}, Transform: m.Mul(Rotation(10))},
{Kind: OpPopClip},
{Kind: OpFill, Rect: Rect{W: 4, H: 4}, Paint: PaintRadial, Gradient: [4]float32{2, 1, 3, 0}, Transform: m},
}}
var f TranslationFolder
if f.Fold(s) != s {
t.Fatal("folded before FoldTranslations")
}
FoldTranslations()
got := f.Fold(s)
want := []Op{
{Kind: OpFill, Rect: Rect{X: 11, Y: 22, W: 3, H: 4}, Paint: PaintLinear, Gradient: [4]float32{10, 20, 13, 24}},
{Kind: OpFill, Rect: Rect{X: 0.5, Y: 1, W: 3, H: 4}, Paint: PaintStripes, Gradient: [4]float32{1, 0, 2, 4}},
{Kind: OpShadow, Rect: Rect{X: 10, Y: 20, W: 5, H: 5}, Cast: Rect{X: 11, Y: 20, W: 4, H: 4}},
{Kind: OpGlyphs, Rect: Rect{X: 10, Y: 20}, Start: 0, End: 1, Paint: PaintConic, Gradient: [4]float32{11, 21, 2, 0}},
s.Ops[4], // glyphs between pixels
{Kind: OpImage, Rect: Rect{X: 10, Y: 20, W: 2, H: 2}},
s.Ops[6], // an image between pixels
{Kind: OpPushClip, Rect: Rect{X: 10, Y: 20, W: 50, H: 50}}, // a clip's edges are computed where they fall
s.Ops[8], s.Ops[9], s.Ops[10], s.Ops[11],
{Kind: OpFill, Rect: Rect{X: 10, Y: 20, W: 4, H: 4}, Paint: PaintRadial, Gradient: [4]float32{12, 21, 3, 0}}, // its radius kept
}
for i := range want {
if got.Ops[i] != want[i] {
t.Errorf("op %d: %+v, want %+v", i, got.Ops[i], want[i])
}
}
if g := got.Glyphs; g[0].X != 13 || g[0].Y != 26 || g[1] != s.Glyphs[1] {
t.Errorf("glyphs %+v", g)
}
if s.Ops[0].Transform != m || s.Glyphs[0].X != 3.4 {
t.Error("folding changed the scene")
}
plain := &Scene{Ops: []Op{s.Ops[8], s.Ops[10], s.Ops[11]}}
if f.Fold(plain) != plain {
t.Error("a scene without translations was copied")
}
}
// Package ui calls FoldTranslations wherever it makes a translation, on
// any goroutine, while renderers fold on theirs: with -race, this checks
// that they share what FoldTranslations sets safely.
func TestFoldTranslationsConcurrently(t *testing.T) {
s := &Scene{Width: 10, Height: 10, Ops: []Op{{Kind: OpFill, Rect: Rect{W: 1, H: 1}, Transform: Translation(1, 0)}}}
var wg sync.WaitGroup
for range 4 {
wg.Go(func() {
for range 100 {
FoldTranslations()
}
})
}
var f TranslationFolder
for range 100 {
f.Fold(s)
}
wg.Wait()
if f.Fold(s) == s {
t.Error("a translated fill not folded after FoldTranslations")
}
}
+32
View File
@@ -0,0 +1,32 @@
package scene
import "testing"
func TestResizeReusesMemoryUnlessMuchSmaller(t *testing.T) {
m := NewImageRGBA(100, 100, make([]byte, 4*100*100))
big := &m.Pix[0]
// Smaller, down to a quarter of the memory: the same memory.
m.Resize(60, 50)
if m.W != 60 || m.H != 50 || len(m.Pix) != 4*60*50 || &m.Pix[0] != big {
t.Fatalf("resized to %dx%d with %d of %d bytes, want 60x50 in the same memory", m.W, m.H, len(m.Pix), cap(m.Pix))
}
m.Resize(100, 100)
if len(m.Pix) != 4*100*100 || &m.Pix[0] != big {
t.Fatal("growing back within the memory allocated anew")
}
// Under a quarter of it: memory of its own size (#1407).
m.Resize(40, 40)
if len(m.Pix) != 4*40*40 || cap(m.Pix) != 4*40*40 {
t.Fatalf("shrank to %d bytes keeping %d", len(m.Pix), cap(m.Pix))
}
m.Resize(0, 0)
if cap(m.Pix) != 0 {
t.Fatalf("an empty image keeps %d bytes", cap(m.Pix))
}
// A canvas no renderer drew in memory still has no pixels.
c := &Image{Scene: &Scene{}}
c.Resize(10, 10)
if c.Pix != nil || c.W != 10 || c.H != 10 {
t.Fatal("resizing a canvas made its pixels")
}
}
+25
View File
@@ -0,0 +1,25 @@
package scene
import "math"
// Oklab returns c, in sRGB, in the Oklab color space, as the renderers
// mix gradients in it: the CPU's from this, the GPU's from the stops'
// values it gives them, or from the same math in their shaders.
func Oklab(c Color) [3]float32 {
r, g, b := toLinear(float32(c.R)/255), toLinear(float32(c.G)/255), toLinear(float32(c.B)/255)
l := float32(math.Cbrt(float64(0.4122214708*r + 0.5363325363*g + 0.0514459929*b)))
m := float32(math.Cbrt(float64(0.2119034982*r + 0.6806995451*g + 0.1073969566*b)))
s := float32(math.Cbrt(float64(0.0883024619*r + 0.2817188376*g + 0.6299787005*b)))
return [3]float32{
0.2104542553*l + 0.7936177850*m - 0.0040720468*s,
1.9779984951*l - 2.4285922050*m + 0.4505937099*s,
0.0259040371*l + 0.7827717662*m - 0.8086757660*s,
}
}
func toLinear(c float32) float32 {
if c <= 0.04045 {
return c / 12.92
}
return float32(math.Pow(float64((c+0.055)/1.055), 2.4))
}
+624
View File
@@ -0,0 +1,624 @@
// Package scene is the display list the ui package paints a frame into and
// the renderers draw: rounded rectangles with borders and gradients, box
// shadows, glyphs from a shared atlas, images, effects and clips, in paint
// order.
// Geometry is in device pixels with the origin at the top-left corner.
package scene
import (
"image"
"image/draw"
"sync/atomic"
)
// Color is a straight (not premultiplied) sRGB color.
type Color struct{ R, G, B, A uint8 }
// Premul returns the color premultiplied by its alpha, with every component
// between 0 and 1, times opacity.
func (c Color) Premul(opacity float32) [4]float32 {
a := float32(c.A) / 255 * opacity
return [4]float32{float32(c.R) / 255 * a, float32(c.G) / 255 * a, float32(c.B) / 255 * a, a}
}
// WideColors are the colors outside the sRGB gamut of an op or a glyph
// (see Op.Wide): straight RGBA with sRGB-encoded components beyond 0 to 1
// (extended sRGB), for those of Color, Color2 and BorderColor a Set bit
// names, of which a glyph has only Color, times its opacity.
type WideColors struct {
Color, Color2, Border [4]float32
Set WideSet
}
// WideSet says which colors of WideColors replace those of the op.
type WideSet uint8
const (
WideColor WideSet = 1 << iota
WideColor2
WideBorder
)
// Rect is a rectangle in device pixels.
type Rect struct{ X, Y, W, H float32 }
// Empty reports whether the rectangle has no area.
func (r Rect) Empty() bool { return r.W <= 0 || r.H <= 0 }
// Intersect returns the intersection of r and o.
func (r Rect) Intersect(o Rect) Rect {
x0, y0 := max(r.X, o.X), max(r.Y, o.Y)
x1, y1 := min(r.X+r.W, o.X+o.W), min(r.Y+r.H, o.Y+o.H)
if x1 <= x0 || y1 <= y0 {
return Rect{X: x0, Y: y0}
}
return Rect{x0, y0, x1 - x0, y1 - y0}
}
// Contains reports whether the point is inside r.
func (r Rect) Contains(x, y float32) bool {
return x >= r.X && y >= r.Y && x < r.X+r.W && y < r.Y+r.H
}
// Kind is the kind of an Op.
type Kind uint8
const (
// OpFill paints a rounded rectangle with Color, or the Paint of Color
// and Color2, and, where Border is positive, a border of BorderColor
// inside its edges, dashed or not.
OpFill Kind = iota
// OpShadow paints the blurred shadow of a rounded rectangle: Rect and
// Radii are the shadow's box, already offset and spread, Blur its blur
// radius and Color its color. Unless Cast is empty, the shadow shows
// only outside it, the box casting the shadow, as CSS's box-shadow
// does. An Inset shadow shows only inside Cast instead, where Rect,
// the hole it leaves, blurred, does not cover it, as CSS's box-shadow:
// inset does; Rect may then be empty, which leaves no hole.
OpShadow
// OpGlyphs paints Scene.Glyphs[Start:End]. With a gradient Paint, its
// mask glyphs take the gradient from Color to Color2, times Opacity,
// instead of their own colors.
OpGlyphs
// OpImage paints Src of Image into Rect, clipped to Radii, with
// Opacity, in shades of gray if Grayscale, tinted by Color unless it
// is zero (its pixels times its straight color and alpha). A negative
// Src.W or Src.H flips the image along that axis, Src.X or Src.Y then
// being its right or bottom edge; nothing outside Src shows.
OpImage
// OpPushClip clips the following ops to Rect with Radii, intersected
// with the clip in effect, until the matching OpPopClip. Unless
// PaintSolid, the alpha of its Paint, a gradient of Color and Color2
// or of Stops as an OpFill's, masks what it clips too, as CSS's
// mask-image does; so does, with Image, the alpha of Image's Src
// drawn over Rect, as OpImage draws it: a coverage mask, as a path's
// (ClipShape.Masks).
OpPushClip
// OpPopClip restores the clip in effect before the matching OpPushClip.
OpPopClip
// OpEffect paints the rounded rectangle Rect with Radii with an effect,
// Scene.Effects[Start]: shaders of a package outside the renderers (see
// Effect), with Opacity; or, for a shader's effect, mask glyphs, which
// Rect then holds (EffectOp.Glyphs).
OpEffect
// OpHole makes the rounded rectangle Rect with Radii transparent,
// within the clip: what the ops before it painted there is gone, and
// what the window shows under the frame, as a web view, shows through.
// The ops after it paint over it as over any transparent pixels. Below
// full Opacity, what the ops before it painted fades by Opacity
// instead, so what shows through blends over it.
OpHole
)
// Op is one drawing operation. Which fields matter depends on Kind.
type Op struct {
Kind Kind
Rect Rect
// Transform maps this operation's geometry to frame pixels. Clips
// retain the transform with which they were pushed.
Transform Affine
// Radii are the corner radii: top-left, top-right, bottom-right and
// bottom-left.
Radii [4]float32
// Continuous curves the rounded corners of Rect, and of Cast, the way
// Apple draws them (Core Animation's continuous corner curve, SwiftUI's
// rounded rectangles): the curve starts further from the corner and
// bends gradually, instead of as a quarter circle. Corners that are
// round in both directions, as a circle's, stay circular. Only the
// renderers of macOS draw them, the CPU's and Metal's.
Continuous bool
Color Color
// Paint, unless PaintSolid, fills with Color and Color2 as Gradient
// says.
Paint Paint
Color2 Color
// Wide, unless 0, is 1 + the index in Scene.Wide of the op's colors
// outside the sRGB gamut, which the renderers drawing a wide gamut
// draw in place of Color, Color2 and BorderColor; those hold the
// nearest sRGB colors, which every other renderer draws. It fits in
// the room the fields around it leave.
Wide uint16
Gradient [4]float32
// Border holds the widths of the border on the top, right, bottom and
// left; Dashed dashes it.
Border [4]float32
BorderColor Color
Dashed bool
// BorderPaint paints an OpFill's border with Paint, its gradient of
// stops (Paint.HasStops), times BorderColor (opaque white for the
// gradient as it is), and its inside with plain Color.
BorderPaint bool
// Inset makes an OpShadow an inner shadow.
Inset bool
// Blur is an OpShadow's blur, and an OpImage's: the standard deviation
// of a Gaussian blur of the image's Src, in its pixels, before it is
// drawn, transparent beyond Src, as CSS's filter: blur() is. Large
// blurs are computed at a fraction of the size, as backdrops' are
// (BackdropOf).
Blur float32
// Cast is the box casting an OpShadow, with CastRadii.
Cast Rect
CastRadii [4]float32
Start, End int32
// Stops are a gradient's colors with stops (PaintLinearStops and the
// others), Scene.Stops[Stops[0]:Stops[1]].
Stops [2]int32
Image *Image
Src Rect
Grayscale bool
// Pixelated samples an OpImage's nearest pixel, as pixel art draws,
// where it would interpolate between pixels.
Pixelated bool
// Opacity multiplies the op's colors; 0 means 1.
Opacity float32
}
// Paint is what fills an OpFill besides plain Color, or the masks of an
// OpGlyphs (gradients only).
type Paint uint8
const (
PaintSolid Paint = iota
// PaintLinear is a linear gradient from Color at (Gradient[0],
// Gradient[1]) to Color2 at (Gradient[2], Gradient[3]), mixed in sRGB;
// PaintOklab mixes them in Oklab. Both mix premultiplied colors, as
// CSS does.
PaintLinear
PaintOklab
// PaintStripes draws stripes of Color over Color2: Gradient holds the
// unit vector across the stripes, their width and their period, from
// the top-left corner of Rect.
PaintStripes
// PaintLinearStops is a linear gradient of the op's Stops, from
// (Gradient[0], Gradient[1]) at 0 to (Gradient[2], Gradient[3]) at 1,
// mixed in sRGB; PaintLinearStopsOklab mixes them in Oklab.
PaintLinearStops
PaintLinearStopsOklab
// PaintConic is a conic gradient of the op's Stops around
// (Gradient[0], Gradient[1]), from 0 at the angle Gradient[2], in
// radians clockwise from upwards, to 1 a turn later, mixed in sRGB, as
// CSS's conic-gradient() is; PaintConicOklab mixes them in Oklab.
PaintConic
PaintConicOklab
// PaintRadial is a radial gradient of the op's Stops from (Gradient[0],
// Gradient[1]) at 0 to a circle of radius Gradient[2] around it at 1,
// mixed in sRGB, as CSS's radial-gradient() is; PaintRadialOklab mixes
// them in Oklab.
PaintRadial
PaintRadialOklab
)
// Stop is a color of a gradient with stops (Op.Stops), at a place along
// it from 0 to 1. A gradient shows its first color before its first stop
// and its last after its last, and mixes premultiplied colors between, as
// CSS does; stops in order, at most MaxStops of them.
type Stop struct {
Color Color
At float32
}
// MaxStops is how many stops a gradient has at most, which the shaders
// loop through.
const MaxStops = 32
// HasStops reports whether paint takes its colors from the op's Stops.
func (p Paint) HasStops() bool { return p >= PaintLinearStops && p <= PaintRadialOklab }
// Uniform returns the widths of a border as wide on every side.
func Uniform(w float32) [4]float32 { return [4]float32{w, w, w, w} }
// HasBorder reports whether any of the widths is positive.
func HasBorder(w [4]float32) bool { return w[0] > 0 || w[1] > 0 || w[2] > 0 || w[3] > 0 }
// InnerRadii returns the radii of the inner edge of a border of widths w
// (top, right, bottom, left) inside a rounded rectangle r with radii,
// which FitRadii or Corners already fitted: each corner's less the wider
// of its two sides, fitted to the inner rectangle, negative as radii are
// for continuous corners.
func InnerRadii(r Rect, radii, w [4]float32) (Rect, [4]float32) {
inner := Rect{X: r.X + w[3], Y: r.Y + w[0], W: r.W - w[1] - w[3], H: r.H - w[0] - w[2]}
continuous := radii[0] < 0 || radii[1] < 0 || radii[2] < 0 || radii[3] < 0
var out [4]float32
for i, side := range [4][2]int{{0, 3}, {0, 1}, {2, 1}, {2, 3}} {
out[i] = max(abs(radii[i])-max(w[side[0]], w[side[1]]), 0)
}
return inner, Corners(inner, out, continuous)
}
// Glyph is a glyph mask or color glyph copied from an atlas into a frame.
type Glyph struct {
// Transform is applied before its Op's transform, for inline text.
Transform Affine
// X, Y, W and H place the glyph's bitmap, in device pixels.
X, Y, W, H float32
// U, V, UW and VH are the bitmap's rectangle in its atlas.
U, V, UW, VH uint16
// Color tints mask glyphs; color glyphs take its alpha only.
Color Color
// Wide, unless 0, is 1 + the index in Scene.Wide of the glyph's
// color outside the sRGB gamut, as Op.Wide.
Wide uint16
// Colored glyphs come from Scene.ColorAtlas, the others from
// Scene.MaskAtlas.
Colored bool
// Subpixel glyphs come from Scene.ColorAtlas too, but hold the
// coverage of the red, green and blue subpixels of each pixel
// (ClearType), each blending its channel of Color.
Subpixel bool
// Thin glyphs, of fonts too thin for antialiasing such as Courier New,
// take half more contrast whatever their color (see TextCoverage), as
// Direct2D gives them.
Thin bool
}
// TextParams corrects the coverage of mask and subpixel glyphs for the
// gamma and contrast text is blended with, as Direct2D does; the zero
// value leaves it as it is.
type TextParams struct {
// GammaRatios are Direct2D's alpha correction of a gamma (see
// GammaRatios).
GammaRatios [4]float32
// Contrast enhances the contrast of mask glyphs, and SubpixelContrast
// that of subpixel glyphs, the more the darker their color: DirectWrite's
// grayscale enhanced contrast and enhanced contrast.
Contrast, SubpixelContrast float32
}
// GammaRatios returns Direct2D's alpha correction ratios for text blended
// at a gamma between 1 and 2.2, as Windows Terminal computes them.
func GammaRatios(gamma float32) [4]float32 {
// Microsoft's ratios, for gamma 1.0, 1.1, ... 2.2, divided by 4.
table := [13][4]float32{
{0, 0, 0, 0},
{0.0166, -0.0807, 0.2227, -0.0751},
{0.0350, -0.1760, 0.4325, -0.1370},
{0.0543, -0.2821, 0.6302, -0.1876},
{0.0739, -0.3963, 0.8167, -0.2287},
{0.0933, -0.5161, 0.9926, -0.2616},
{0.1121, -0.6395, 1.1588, -0.2877},
{0.1300, -0.7649, 1.3159, -0.3080},
{0.1469, -0.8911, 1.4644, -0.3234},
{0.1627, -1.0170, 1.6051, -0.3347},
{0.1773, -1.1420, 1.7385, -0.3426},
{0.1908, -1.2652, 1.8650, -0.3476},
{0.2031, -1.3864, 1.9851, -0.3501},
}
i := min(max(int(gamma*10+0.5), 10), 22) - 10
const norm13 = float32(float64(0x10000) / (255 * 255) * 4)
const norm24 = float32(float64(0x100) / 255 * 4)
r := table[i]
return [4]float32{norm13 * r[0] / 4, norm24 * r[1] / 4, norm13 * r[2] / 4, norm24 * r[3] / 4}
}
// ThinBoost is the contrast Direct2D adds for thin glyphs.
const ThinBoost = 0.5
// TextCoverage corrects the coverage a of a glyph of straight color c, as
// Direct2D blends text: it enhances the contrast by contrast, the more the
// darker c is, plus boost, and corrects for the gamma of the ratios g.
func TextCoverage(a float32, c [3]float32, contrast, boost float32, g [4]float32) float32 {
k := contrast*min(max(3-4*(0.30*c[0]+0.59*c[1]+0.11*c[2]), 0), 1) + boost
a = a * (k + 1) / (a*k + 1)
f := 0.25*c[0] + 0.5*c[1] + 0.25*c[2]
return min(max(a+a*(1-a)*((g[0]*f+g[1])*a+(g[2]*f+g[3])), 0), 1)
}
// SubpixelCoverage corrects the coverage of each subpixel of a subpixel
// glyph of straight color c, as Direct2D blends ClearType text.
func SubpixelCoverage(a, c [3]float32, contrast, boost float32, g [4]float32) [3]float32 {
k := contrast*min(max(3-4*(0.30*c[0]+0.59*c[1]+0.11*c[2]), 0), 1) + boost
for i := range a {
v := a[i] * (k + 1) / (a[i]*k + 1)
a[i] = min(max(v+v*(1-v)*((g[0]*c[i]+g[1])*v+(g[2]*c[i]+g[3])), 0), 1)
}
return a
}
// Scene is a frame's display list.
type Scene struct {
// Width and Height of the frame in device pixels; Scale is how many
// device pixels a DIP is (0 for 1). Zoom is how much of Scale the
// content's zoom makes (0 for 1): the screen's own scale is
// Scale/Zoom.
Width, Height int
Scale, Zoom float32
// Clear is the color the frame starts with.
Clear Color
// Background is the opaque color the content fills the window with,
// or transparent: what the window shows where no frame of its size
// shows yet, as while it grows. It draws nothing in the frame.
Background Color
Ops []Op
Glyphs []Glyph
// Stops holds the stops of gradients (Op.Stops).
Stops []Stop
// Effects holds the effects of OpEffect operations.
Effects []EffectOp
// Words holds the words of the effects' uniforms (EffectOp.Uniforms
// and WideUniforms), which the frame's painter allocates from
// (Painter.EffectWords), kept from frame to frame.
Words []uint32
// Wide holds the colors outside the sRGB gamut of ops and glyphs (see
// Op.Wide), and those of the parameters of effects, which no op points
// at. Without any, the scene draws the same on every renderer.
Wide []WideColors
// Text corrects the coverage of mask and subpixel glyphs.
Text TextParams
// MaskAtlas holds coverage masks (one byte per pixel), ColorAtlas
// premultiplied RGBA bitmaps such as emoji, and the coverage of
// subpixel glyphs.
MaskAtlas, ColorAtlas *Atlas
// Canvases are the canvases (NewCanvas) drawn anew for this frame,
// which renderers draw before it, whether it shows them or not, while
// the atlases their glyphs point at hold them.
Canvases []*Image
// Drawn, unless zero, is the part of a canvas's frame its content
// takes, from the top left corner, as an effect's layer made larger
// than its content: backdrops end at its edge (BackdropOf), as at the
// edge of a canvas of its size, and nothing is drawn beyond it.
Drawn image.Point
}
// BackdropOf is BackdropOf in s, a frame of w×h pixels, ending at the edge
// of the part Drawn says.
func (s *Scene) BackdropOf(r Rect, blur float32, w, h int) Backdrop {
if s.Drawn != (image.Point{}) {
w, h = min(w, s.Drawn.X), min(h, s.Drawn.Y)
}
return BackdropOf(r, blur, w, h)
}
// EachCanvas calls fn with the canvases the scene draws anew or shows,
// each once, those a canvas shows before it.
func (s *Scene) EachCanvas(fn func(*Image)) {
seen := map[*Image]bool{}
var visit func(c *Image)
visit = func(c *Image) {
if c == nil || c.Scene == nil || seen[c] {
return
}
seen[c] = true
c.Scene.eachShown(visit)
fn(c)
}
for _, c := range s.Canvases {
visit(c)
}
s.eachShown(visit)
}
// eachShown calls fn with the canvases the scene's images show, and its
// shaders read.
func (s *Scene) eachShown(fn func(*Image)) {
for i := range s.Ops {
if op := &s.Ops[i]; op.Kind == OpImage && op.Image != nil && op.Image.Scene != nil {
fn(op.Image)
}
}
for i := range s.Effects {
for _, img := range s.Effects[i].Images {
if img != nil && img.Scene != nil {
fn(img)
}
}
}
}
// Reset empties the scene for another frame, keeping its storage.
func (s *Scene) Reset(width, height int, color Color) {
s.Width, s.Height, s.Clear = width, height, color
s.Drawn = image.Point{}
// Ops and effects can keep images and effect resources alive beyond
// the end of the shorter list the next frame paints.
clear(s.Ops)
s.Ops = s.Ops[:0]
s.Glyphs = s.Glyphs[:0]
s.Stops = s.Stops[:0]
clear(s.Effects)
s.Effects = s.Effects[:0]
s.Wide = s.Wide[:0]
s.Words = s.Words[:0]
clear(s.Canvases)
s.Canvases = s.Canvases[:0]
}
var lastImageID atomic.Uint64
// Image is a bitmap a scene draws. Renderers keep a texture per image and
// upload it again when its version changes.
type Image struct {
id uint64
version uint64
// W and H are the size in pixels; Pix holds premultiplied RGBA rows of
// 4*W bytes.
W, H int
Pix []byte
// Scene, in a canvas (NewCanvas), is what the image shows: renderers
// draw it into the image's texture whenever the version changes,
// rather than upload Pix, which the CPU renderer draws it into, and
// PixVersion is the version Pix holds.
Scene *Scene
PixVersion uint64
// Transient marks a canvas drawn anew in every frame that shows it,
// as an element's effect layer: renderers free its texture once
// frames stop drawing it, rather than once it is collected, which
// the little memory it takes of Go's heap may put off for minutes.
Transient bool
// Restore re-creates Pix when a renderer needs the pixels after an
// owner dropped them, to upload or to draw them again, and Dropped
// runs after a renderer uploaded them, to drop them again. Both are
// nil for images that keep their pixels.
Restore func() []byte
Dropped func()
// GPU, for an image something draws on the GPU (native.Texture),
// gives GPU renderers a texture of their own showing its pixels with
// no copy, which they make again as Version changes. A renderer it
// gives none, as the CPU renderer, draws the pixels Restore reads. An
// interface its owner implements, so that renderers link no code of
// it.
GPU GPUSource
// Surface, unless nil, is a frame of video that renderers sample where
// a decoder left it, rather than upload Pix (see Surface); Restore
// converts it for those that need Pix.
Surface *Surface
}
// GPUSource gives renderers a texture showing an image that something
// draws on the GPU (Image.GPU).
type GPUSource interface {
// GPUTexture returns a new texture of device, of the API api, that
// shows the image's pixels now, which the renderer owns, or 0 where it
// has none for api: the renderer then draws the image's pixels.
GPUTexture(api GPUAPI, device uintptr) uintptr
}
// GPUAPI names the API of a GPU renderer, for a GPUSource.
type GPUAPI uint8
const (
// Metal: device is an id<MTLDevice>, the texture an id<MTLTexture>.
Metal GPUAPI = iota + 1
// Direct3D11: device is an ID3D11Device*, the texture an
// ID3D11ShaderResourceView*.
Direct3D11
// OpenGL: device is 0, in the renderer's context; the texture is a
// texture name.
OpenGL
)
// NewCanvas returns a w×h image that renderers draw from a scene of its
// own, cleared to transparent: render to texture.
func NewCanvas(w, h int) *Image {
return &Image{id: lastImageID.Add(1), version: 1, W: w, H: h, Scene: &Scene{Width: w, Height: h, Scale: 1}}
}
// NewImage converts img to a premultiplied RGBA bitmap.
func NewImage(img image.Image) *Image {
b := img.Bounds()
rgba, ok := img.(*image.RGBA)
if !ok || rgba.Stride != 4*b.Dx() || b.Min != (image.Point{}) {
rgba = image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src)
}
return &Image{id: lastImageID.Add(1), version: 1, W: b.Dx(), H: b.Dy(), Pix: rgba.Pix}
}
// NewImageRGBA wraps premultiplied RGBA pixels of a w×h bitmap.
func NewImageRGBA(w, h int, pix []byte) *Image {
return &Image{id: lastImageID.Add(1), version: 1, W: w, H: h, Pix: pix}
}
// ID identifies the image for texture caches.
func (m *Image) ID() uint64 { return m.id }
// Version changes whenever the pixels change.
func (m *Image) Version() uint64 { return m.version }
// Changed records that Pix was modified.
func (m *Image) Changed() { m.version++ }
// Pixels returns the pixels a renderer uploads or draws, re-creating them
// from Restore when an owner dropped them. The pixels stay then, until
// the owner drops them again or a renderer's upload does (Uploaded).
func (m *Image) Pixels() []byte {
if m.Pix == nil && m.Restore != nil {
m.Pix = m.Restore()
}
return m.Pix
}
// Uploaded tells that a renderer uploaded the pixels, which an owner may
// drop again.
func (m *Image) Uploaded() {
if m.Dropped != nil {
m.Dropped()
}
}
// Resize keeps the image's texture-cache identity while changing its size.
// Renderers replace the backing texture on a size change, so an animated
// clip does not leave a new texture in the cache on every frame.
//
// It reuses the pixels' memory where they fit, unless they take up less
// than a quarter of it: an image that shrank much doesn't keep its
// largest size, as a clip mask that turned would (#1407).
func (m *Image) Resize(w, h int) {
m.W, m.H = w, h
n := 4 * w * h
switch {
case m.Scene != nil && m.Pix == nil:
// A canvas no renderer drew in memory: its pixels are made when
// one does.
case cap(m.Pix) >= n && n >= cap(m.Pix)/4:
m.Pix = m.Pix[:n]
default:
m.Pix = make([]byte, n)
}
m.Changed()
}
// FitRadii scales corner radii down so that adjacent ones fit along each
// side of r, as CSS does; renderers apply it before drawing.
func FitRadii(r Rect, radii [4]float32) [4]float32 {
f := float32(1)
if s := radii[0] + radii[1]; s > r.W && s > 0 {
f = min(f, r.W/s)
}
if s := radii[3] + radii[2]; s > r.W && s > 0 {
f = min(f, r.W/s)
}
if s := radii[0] + radii[3]; s > r.H && s > 0 {
f = min(f, r.H/s)
}
if s := radii[1] + radii[2]; s > r.H && s > 0 {
f = min(f, r.H/s)
}
for i := range radii {
radii[i] = max(radii[i]*f, 0)
}
return radii
}
// Corners returns radii as renderers take them: fitted to r (FitRadii),
// and negative for continuous corners.
func Corners(r Rect, radii [4]float32, continuous bool) [4]float32 {
radii = FitRadii(r, radii)
if continuous {
for i := range radii {
radii[i] = -radii[i]
}
}
return radii
}
func abs(v float32) float32 {
if v < 0 {
return -v
}
return v
}
+155
View File
@@ -0,0 +1,155 @@
package scene
// A Surface is a picture that a system decoder left where it decoded it,
// a frame of video, which renderers sample where it is rather than upload
// as RGBA (Image.Surface). The image showing it keeps W and H, and its
// version changes with each frame; its Pixels, which the CPU renderer
// draws and blurs read, come from its Restore, which converts the frame.
type Surface struct {
// Format is how the pixels are laid out: SurfaceNV12's luma, then
// chroma at half the size both ways, Cb and Cr interleaved, which
// renderers convert to RGB with Matrix as they sample them; or
// SurfaceBGRA, opaque or premultiplied as Image's pixels are.
Format SurfaceFormat
Matrix YUVMatrix
// Planes are the frame in memory, for renderers to upload: the luma
// and the chroma of NV12, or BGRA's one. Nil for a frame only on the
// GPU, as Native has it.
Planes [2]Plane
// Native is the frame on the GPU, as the platform's renderer takes it:
// a CVPixelBufferRef on macOS, which Metal wraps as textures; on
// Windows the NT handle of a shared Direct3D 11 texture in BGRA with a
// keyed mutex, which Direct3D opens on its device once (NativeID) and
// acquires with key 0 around the frames reading it, as the producer
// does around writing it; in browsers the number of the video element
// playing it (media.AddElement), which WebGL uploads from. 0 for
// none. The producer keeps it valid
// while the image shows the surface; renderers keep what they made of
// it until the GPU read it.
Native uintptr
// NativeID identifies Native's texture among all those the producers
// of an app ever share, which renderers open once: a handle's number
// may name another texture once closed.
NativeID uint64
}
// SurfaceFormat is the pixel format of a Surface.
type SurfaceFormat uint8
const (
// SurfaceNV12 is 8-bit YCbCr 4:2:0: a plane of luma, a byte a pixel,
// then a plane of chroma half as wide and high, Cb and Cr a byte each.
SurfaceNV12 SurfaceFormat = iota
// SurfaceBGRA is a plane of 8-bit blue, green, red and alpha.
SurfaceBGRA
)
// Plane is a plane of a Surface in memory: rows of Stride bytes.
type Plane struct {
Pix []byte
Stride int
}
// YUVMatrix is how a Surface's YCbCr converts to RGB: the coefficients of
// a standard, and whether the samples take their full range or the
// limited (video) range, 16 to 235 for luma and 16 to 240 for chroma.
type YUVMatrix uint8
const (
BT601 YUVMatrix = iota
BT709
BT2020
// FullRange is added to a matrix for samples of the full range.
FullRange YUVMatrix = 3
)
// yuvCoeffs are Kr and Kb of each standard.
var yuvCoeffs = [3][2]float32{{0.299, 0.114}, {0.2126, 0.0722}, {0.2627, 0.0593}}
// YUVToRGB converts samples y, cb and cr, 0 to 1, to RGB, 0 to 1 and
// clamped, as the renderers' shaders do (yuvToRGB in each).
func (m YUVMatrix) YUVToRGB(y, cb, cr float32) (r, g, b float32) {
std, full := m%FullRange, m >= FullRange
if std > BT2020 {
std = BT709
}
kr, kb := yuvCoeffs[std][0], yuvCoeffs[std][1]
if full {
cb -= 128.0 / 255
cr -= 128.0 / 255
} else {
y = (y - 16.0/255) * (255.0 / 219)
cb = (cb - 128.0/255) * (255.0 / 224)
cr = (cr - 128.0/255) * (255.0 / 224)
}
r = y + 2*(1-kr)*cr
b = y + 2*(1-kb)*cb
g = (y - kr*r - kb*b) / (1 - kr - kb)
return clamp01(r), clamp01(g), clamp01(b)
}
func clamp01(v float32) float32 { return min(max(v, 0), 1) }
// RGBA converts the surface's planes in memory into premultiplied RGBA,
// 4×W×H bytes, into dst when it has room, as the shaders sample them:
// each pixel's chroma bilinear between the chroma samples around it
// (centered between luma's, as MPEG-1 and JPEG place them). It returns
// nil without planes.
func (s *Surface) RGBA(dst []byte, w, h int) []byte {
if s.Planes[0].Pix == nil || w <= 0 || h <= 0 {
return nil
}
n := 4 * w * h
if cap(dst) < n {
dst = make([]byte, n)
}
dst = dst[:n]
switch s.Format {
case SurfaceBGRA:
p := s.Planes[0]
for y := range h {
src, out := p.Pix[y*p.Stride:][:4*w], dst[4*w*y:][:4*w]
for x := 0; x < 4*w; x += 4 {
out[x], out[x+1], out[x+2], out[x+3] = src[x+2], src[x+1], src[x], src[x+3]
}
}
case SurfaceNV12:
lp, cp := s.Planes[0], s.Planes[1]
cw, ch := (w+1)/2, (h+1)/2
chroma := func(x, y int, k int) float32 {
x, y = min(max(x, 0), cw-1), min(max(y, 0), ch-1)
return float32(cp.Pix[y*cp.Stride+2*x+k]) / 255
}
for y := range h {
// The chroma sample's center is at (2i+1)/2 in luma pixels.
fy := (float32(y)+0.5)/2 - 0.5
y0 := floor(fy)
ty := fy - float32(y0)
for x := range w {
fx := (float32(x)+0.5)/2 - 0.5
x0 := floor(fx)
tx := fx - float32(x0)
var c [2]float32
for k := range 2 {
a := chroma(x0, y0, k)*(1-tx) + chroma(x0+1, y0, k)*tx
b := chroma(x0, y0+1, k)*(1-tx) + chroma(x0+1, y0+1, k)*tx
c[k] = a*(1-ty) + b*ty
}
r, g, b := s.Matrix.YUVToRGB(float32(lp.Pix[y*lp.Stride+x])/255, c[0], c[1])
o := dst[4*(w*y+x):]
o[0], o[1], o[2], o[3] = to8(r), to8(g), to8(b), 255
}
}
}
return dst
}
func floor(v float32) int {
i := int(v)
if float32(i) > v {
i--
}
return i
}
func to8(v float32) byte { return byte(v*255 + 0.5) }
+60
View File
@@ -0,0 +1,60 @@
package scene
import (
"math"
"testing"
)
// TestGammaRatios checks Direct2D's ratios for its default gamma, 1.8, as
// Windows Terminal lists them, and that gammas round to a tenth.
func TestGammaRatios(t *testing.T) {
want := [4]float32{0.148054421, -0.894594550, 1.47590804, -0.324668258}
got := GammaRatios(1.8)
for i := range want {
if math.Abs(float64(got[i]-want[i])) > 1e-6 {
t.Fatalf("GammaRatios(1.8) = %v, want %v", got, want)
}
}
if GammaRatios(1.84) != got || GammaRatios(1) != [4]float32{} || GammaRatios(3) != GammaRatios(2.2) {
t.Error("gammas do not round to the table")
}
}
// TestTextCoverage checks that no correction leaves coverage as it is,
// that coverage stays between 0 and 1 and keeps its ends, and that the
// contrast is enhanced for dark text alone.
func TestTextCoverage(t *testing.T) {
g := GammaRatios(1.8)
black, white := [3]float32{}, [3]float32{1, 1, 1}
for a := float32(0); a <= 1; a += 1.0 / 16 {
if v := TextCoverage(a, black, 0, 0, [4]float32{}); v != a {
t.Fatalf("no correction turns %v into %v", a, v)
}
for _, c := range [][3]float32{black, white, {0.5, 0.2, 0.9}} {
v := TextCoverage(a, c, 1, 0, g)
if v < 0 || v > 1 {
t.Fatalf("coverage %v of %v corrected to %v", a, c, v)
}
s := SubpixelCoverage([3]float32{a, a, a}, c, 0.5, ThinBoost, g)
if s[0] < 0 || s[0] > 1 {
t.Fatalf("subpixel coverage %v of %v corrected to %v", a, c, s)
}
}
}
for _, a := range []float32{0, 1} {
if v := TextCoverage(a, black, 1, 0, g); v != a {
t.Errorf("coverage %v of black corrected to %v", a, v)
}
}
if TextCoverage(0.5, black, 1, 0, g) <= TextCoverage(0.5, black, 0, 0, g) {
t.Error("the contrast of dark text is not enhanced")
}
// Light text takes no contrast, and its gamma correction thickens it.
if TextCoverage(0.5, white, 1, 0, g) != TextCoverage(0.5, white, 0, 0, g) || TextCoverage(0.5, white, 0, 0, g) <= 0.5 {
t.Error("light text")
}
// Thin glyphs take their boost whatever their color.
if TextCoverage(0.5, white, 1, ThinBoost, g) <= TextCoverage(0.5, white, 1, 0, g) {
t.Error("light thin text takes no boost")
}
}
+483
View File
@@ -0,0 +1,483 @@
package scene
import (
"math"
"slices"
)
// ClipShape is a clip in the coordinate system in which it was pushed.
type ClipShape struct {
Rect Rect
Radii [4]float32
Transform Affine
Continuous bool
// Paint, unless PaintSolid, is a gradient whose alpha masks the clip,
// with Gradient, Color, Color2 and Stops, as an OpFill's.
Paint Paint
Gradient [4]float32
Color, Color2 Color
Stops []Stop
// Mask, unless nil, is an image whose alpha in MaskSrc, drawn over
// Rect, masks the clip, as it was at MaskVersion.
Mask *Image
MaskSrc Rect
MaskVersion uint64
}
// ClipShapeOf returns the shape of op, an OpPushClip of a scene with
// stops, moved as MovedClipOp moves it: its Stops are a part of stops.
func ClipShapeOf(op *Op, stops []Stop) ClipShape {
o := MovedClipOp(op)
c := ClipShape{Rect: o.Rect, Radii: o.Radii, Transform: o.Transform, Continuous: o.Continuous}
if o.Paint != PaintSolid {
c.Paint, c.Gradient, c.Color, c.Color2 = o.Paint, o.Gradient, o.Color, o.Color2
if o.Paint.HasStops() {
if a, b := int(o.Stops[0]), int(o.Stops[1]); a >= 0 && b <= len(stops) && a < b {
c.Stops = stops[a:min(b, a+MaxStops)]
} else {
// No stops: the gradient lets nothing through, as it
// fills nothing.
c.Stops = []Stop{}
}
}
}
if o.Image != nil {
c.Mask, c.MaskSrc, c.MaskVersion = o.Image, o.Src, o.Image.Version()
}
return c
}
// Masks reports whether a gradient or an image masks the clip, which
// then lets through less than all of what it holds inside its rounded
// rectangle.
func (c *ClipShape) Masks() bool { return c.Paint != PaintSolid || c.Mask != nil }
// Same reports whether the clips are the same, their stops compared by
// what they hold.
func (c *ClipShape) Same(o *ClipShape) bool {
return c.Rect == o.Rect && c.Radii == o.Radii && c.Transform == o.Transform && c.Continuous == o.Continuous &&
c.Paint == o.Paint && c.Gradient == o.Gradient && c.Color == o.Color && c.Color2 == o.Color2 &&
c.Mask == o.Mask && c.MaskSrc == o.MaskSrc && c.MaskVersion == o.MaskVersion && slices.Equal(c.Stops, o.Stops)
}
// Affine maps drawing coordinates to frame coordinates: an affine map,
// or, when G or H is set, a projective one, which shows a plane turned in
// 3D in perspective, x and y going to
//
// ((A*x + C*y + X) / w, (B*x + D*y + Y) / w), with w = G*x + H*y + 1,
//
// or, when Behind is set, with w = G*x + H*y - 1. What shows is where w is
// positive, in front of the viewer. Behind keeps its sign for a plane whose
// origin, (0, 0), is behind the viewer though what is drawn on it is in
// front: a card turning over in perspective far from the origin, its
// horizon between the card and the origin. Behind is set only with G or H.
//
// The zero value is identity; Set distinguishes a singular matrix
// (including scale zero).
type Affine struct {
A, B, C, D, X, Y float32
G, H float32
Set bool
Behind bool
}
func Matrix(a, b, c, d, x, y float32) Affine { return Projective(a, b, c, d, x, y, 0, 0) }
// Projective returns the projective map of the matrix
//
// | a c x |
// | b d y |
// | g h 1 |
func Projective(a, b, c, d, x, y, g, h float32) Affine {
if a == 1 && b == 0 && c == 0 && d == 1 && x == 0 && y == 0 && g == 0 && h == 0 {
return Affine{}
}
return Affine{a, b, c, d, x, y, g, h, true, false}
}
func Translation(x, y float32) Affine { return Matrix(1, 0, 0, 1, x, y) }
func Scaling(x, y float32) Affine { return Matrix(x, 0, 0, y, 0, 0) }
func Rotation(degrees float32) Affine {
angle := math.Remainder(float64(degrees), 360)
switch angle {
case 0:
return Affine{}
case 90:
return Matrix(0, 1, -1, 0, 0, 0)
case -90:
return Matrix(0, -1, 1, 0, 0, 0)
case 180, -180:
return Matrix(-1, 0, 0, -1, 0, 0)
}
s, c := math.Sincos(angle * math.Pi / 180)
return Matrix(float32(c), float32(s), -float32(s), float32(c), 0, 0)
}
// Perspective reports whether m is projective, not affine.
func (m Affine) Perspective() bool { return m.Set && (m.G != 0 || m.H != 0) }
// MovedClip returns the rectangle of a clip of r under m, and what of m is
// left to apply to it: nothing when m only moves it, as a pose sliding a
// panel in or a card lifting under the pointer does. A clip only moved is
// a rectangle like any other, which renderers cut as they cut those that
// nothing transforms, rather than with a mask of its transformed shape.
func MovedClip(r Rect, m Affine) (Rect, Affine) {
if !m.Set || m.A != 1 || m.B != 0 || m.C != 0 || m.D != 1 || m.G != 0 || m.H != 0 {
return r, m
}
r.X += m.X
r.Y += m.Y
return r, Affine{}
}
// MovedClipOp returns op, an OpPushClip, as MovedClip moves it: its
// rectangle moved, with the points of its gradient, when its transform
// only moves them, the transform then unset.
func MovedClipOp(op *Op) Op {
o := *op
r, m := MovedClip(o.Rect, o.Transform)
if m.Set || !o.Transform.Set {
return o
}
dx, dy := r.X-o.Rect.X, r.Y-o.Rect.Y
o.Rect, o.Transform = r, Affine{}
o.moveGradient(dx, dy)
return o
}
// moveGradient moves the points of the op's gradient by (x, y); stripes
// start from Rect.
func (op *Op) moveGradient(x, y float32) {
switch op.Paint {
case PaintLinear, PaintOklab, PaintLinearStops, PaintLinearStopsOklab:
op.Gradient = [4]float32{op.Gradient[0] + x, op.Gradient[1] + y, op.Gradient[2] + x, op.Gradient[3] + y}
case PaintConic, PaintConicOklab, PaintRadial, PaintRadialOklab:
op.Gradient[0], op.Gradient[1] = op.Gradient[0]+x, op.Gradient[1]+y
}
}
// Reshaped reports whether op of s draws under a transform that does more
// than move it (scales, turns, skews it or shows it in perspective): its
// own, or, for glyphs and an effect masked by glyphs, a glyph's. Drawing
// a transform only moves lies in its clips as it would unmoved, which the
// GPU's renderers cut in the frame's coordinates whatever the transform,
// so the clips around it need no mask (gpu.Builder), and damage tracking has them change no more than
// for drawing not moved (Differ). Clips are the same (MovedClip): a clip
// pushed under a transform that only moves it reshapes none around it.
func Reshaped(s *Scene, op *Op) bool {
if op.Transform.Set && !op.Transform.moves() {
return true
}
start, end := int32(-1), int32(-1)
switch op.Kind {
case OpGlyphs:
start, end = op.Start, op.End
case OpEffect:
// A shader's effect masked by glyphs draws them with their own
// transforms too (EffectOp.Glyphs).
if op.Start >= 0 && int(op.Start) < len(s.Effects) {
start, end = s.Effects[op.Start].Glyphs[0], s.Effects[op.Start].Glyphs[1]
}
}
if start >= 0 && start <= end && int(end) <= len(s.Glyphs) {
for _, g := range s.Glyphs[start:end] {
if g.Transform.Set && !g.Transform.moves() {
return true
}
}
}
return false
}
// ClipCorners follows the clips of a scene, op by op, to find those that
// reach into the rounded corners of a clip around them (Push). The GPU's
// renderers cut drawing with the innermost clip's shape in the shader and
// with the scissor rectangles of the others, which cut no corners: drawing
// in a clip that reaches into those of one around it is cut with a mask of
// the clips instead (gpu.Builder), whose pixels at the clips' edges
// differ from the shader's by a unit in the last place (Differ).
type ClipCorners struct {
open []cornerClip
}
type cornerClip struct {
// area is what the clip and those around it let through, in the
// frame; rect its rectangle, and reach how far from its corners
// their curves and their antialiasing reach, zero for a square
// corner or a clip transformed (which is cut with a mask anyway).
area, rect Rect
reach [4]float32
}
// contReach is how far from its corner the curve of a continuous corner
// of radius 1 leaves the edges.
const contReach = 1.528665
// Reset forgets the clips pushed, for a new scene.
func (c *ClipCorners) Reset() { c.open = c.open[:0] }
// Push enters op, an OpPushClip, and returns the place among the clips
// open around it (0 the outermost) of the innermost whose rounded corners
// what op lets through reaches into, or -1 for none.
func (c *ClipCorners) Push(op *Op) int {
o := MovedClipOp(op)
k := cornerClip{area: o.Transform.Bounds(o.Rect)}
if n := len(c.open); n > 0 {
k.area = k.area.Intersect(c.open[n-1].area)
}
at := -1
for j := len(c.open) - 1; j >= 0 && !k.area.Empty(); j-- {
if c.open[j].cuts(k.area) {
at = j
break
}
}
if !o.Transform.Set {
k.rect = o.Rect
ext := float32(1)
if o.Continuous {
ext = contReach
}
for i, r := range FitRadii(o.Rect, o.Radii) {
if r > 0 {
k.reach[i] = r*ext + 1
}
}
}
c.open = append(c.open, k)
return at
}
// Pop leaves the innermost clip, at an OpPopClip.
func (c *ClipCorners) Pop() {
if n := len(c.open); n > 0 {
c.open = c.open[:n-1]
}
}
// cuts reports whether a, not empty, overlaps a box of a rounded corner
// of the clip, where its curve cuts.
func (k *cornerClip) cuts(a Rect) bool {
r, e := k.rect, k.reach
boxes := [4]Rect{
{r.X, r.Y, e[0], e[0]},
{r.X + r.W - e[1], r.Y, e[1], e[1]},
{r.X + r.W - e[2], r.Y + r.H - e[2], e[2], e[2]},
{r.X, r.Y + r.H - e[3], e[3], e[3]},
}
for i, b := range boxes {
if e[i] > 0 && a.X < b.X+b.W && b.X < a.X+a.W && a.Y < b.Y+b.H && b.Y < a.Y+a.H {
return true
}
}
return false
}
// moves reports whether m only moves what it maps, without scaling,
// turning, skewing it or showing it in perspective.
func (m Affine) moves() bool {
return m.A == 1 && m.B == 0 && m.C == 0 && m.D == 1 && m.G == 0 && m.H == 0
}
// matrix returns m's matrix, by rows.
func (m Affine) matrix() [3][3]float64 {
if !m.Set {
return [3][3]float64{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
}
return [3][3]float64{
{float64(m.A), float64(m.C), float64(m.X)},
{float64(m.B), float64(m.D), float64(m.Y)},
{float64(m.G), float64(m.H), float64(m.constant())},
}
}
// constant returns the constant term of m's divisor w, 1 or, Behind, -1.
func (m Affine) constant() float32 {
if m.Behind {
return -1
}
return 1
}
// fromMatrix returns the map of matrix p, scaled by a positive factor so
// that its last entry is 1 or -1 (Behind), and whether it has one: the
// sign of w, which tells what is in front of the viewer, is p's.
func fromMatrix(p [3][3]float64) (Affine, bool) {
k := p[2][2]
if math.Abs(k) < 1e-12 || math.IsNaN(k) || math.IsInf(k, 0) {
return Affine{}, false
}
behind := k < 0
k = math.Abs(k)
v := [8]float64{p[0][0] / k, p[1][0] / k, p[0][1] / k, p[1][1] / k, p[0][2] / k, p[1][2] / k, p[2][0] / k, p[2][1] / k}
for _, x := range v {
if math.IsNaN(x) || math.IsInf(x, 0) || math.Abs(x) > math.MaxFloat32 {
return Affine{}, false
}
}
m := Projective(float32(v[0]), float32(v[1]), float32(v[2]), float32(v[3]), float32(v[4]), float32(v[5]), float32(v[6]), float32(v[7]))
if behind {
if !m.Perspective() {
// w is -1 everywhere: all of the plane is behind the viewer.
return singular, true
}
m.Behind = true
}
return m, true
}
// singular is a map without an inverse, which shows nothing.
var singular = Affine{Set: true}
// Mul returns m*n: n acts first, then m.
func (m Affine) Mul(n Affine) Affine {
if !m.Set {
return n
}
if !n.Set {
return m
}
if m.moves() && n.moves() {
// As the general product, but for the signs of zeros.
return Matrix(1, 0, 0, 1, n.X+m.X, n.Y+m.Y)
}
if !m.Perspective() && !n.Perspective() {
return Matrix(m.A*n.A+m.C*n.B, m.B*n.A+m.D*n.B,
m.A*n.C+m.C*n.D, m.B*n.C+m.D*n.D,
m.A*n.X+m.C*n.Y+m.X, m.B*n.X+m.D*n.Y+m.Y)
}
a, b := m.matrix(), n.matrix()
var p [3][3]float64
for i := range 3 {
for j := range 3 {
p[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j]
}
}
r, ok := fromMatrix(p)
if !ok {
return singular
}
return r
}
// W returns the projective divisor of (x, y): positive in front of the
// viewer, as all of an affine map's plane is.
func (m Affine) W(x, y float32) float32 {
if !m.Set {
return 1
}
return m.G*x + m.H*y + m.constant()
}
// Point returns where m maps (x, y). A point behind the viewer of a
// projective map (W not positive) goes far away.
func (m Affine) Point(x, y float32) (float32, float32) {
if !m.Set {
return x, y
}
px, py := m.A*x+m.C*y+m.X, m.B*x+m.D*y+m.Y
if m.G == 0 && m.H == 0 {
return px, py
}
w := max(m.W(x, y), 1e-6)
return px / w, py / w
}
// VectorAt returns how far m moves the point (x, y) moved by (dx, dy):
// the same for every point of an affine map.
func (m Affine) VectorAt(x, y, dx, dy float32) (float32, float32) {
if !m.Set {
return dx, dy
}
if m.G == 0 && m.H == 0 {
return m.A*dx + m.C*dy, m.B*dx + m.D*dy
}
x0, y0 := m.Point(x, y)
x1, y1 := m.Point(x+dx, y+dy)
return x1 - x0, y1 - y0
}
func (m Affine) Inverse() (Affine, bool) {
if !m.Set {
return m, true
}
if m.G == 0 && m.H == 0 {
det := float64(m.A)*float64(m.D) - float64(m.B)*float64(m.C)
if det == 0 || math.IsNaN(det) || math.IsInf(det, 0) {
return Affine{}, false
}
a, b, c, d := float32(float64(m.D)/det), float32(-float64(m.B)/det), float32(-float64(m.C)/det), float32(float64(m.A)/det)
n := Matrix(a, b, c, d, -a*m.X-c*m.Y, -b*m.X-d*m.Y)
for _, v := range [6]float32{n.A, n.B, n.C, n.D, n.X, n.Y} {
if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
return Affine{}, false
}
}
return n, true
}
q := m.matrix()
cof := func(r0, r1, c0, c1 int) float64 { return q[r0][c0]*q[r1][c1] - q[r0][c1]*q[r1][c0] }
adj := [3][3]float64{
{cof(1, 2, 1, 2), -cof(0, 2, 1, 2), cof(0, 1, 1, 2)},
{-cof(1, 2, 0, 2), cof(0, 2, 0, 2), -cof(0, 1, 0, 2)},
{cof(1, 2, 0, 1), -cof(0, 2, 0, 1), cof(0, 1, 0, 1)},
}
det := q[0][0]*adj[0][0] + q[0][1]*adj[1][0] + q[0][2]*adj[2][0]
if math.Abs(det) < 1e-12 || math.IsNaN(det) || math.IsInf(det, 0) {
return Affine{}, false
}
// adj is the inverse times det, which fromMatrix drops but for its
// sign: the inverse's w is positive at the points of the frame that
// show what is in front of the viewer.
if det < 0 {
for i := range adj {
for j := range adj[i] {
adj[i][j] = -adj[i][j]
}
}
}
return fromMatrix(adj)
}
func (m Affine) Bounds(r Rect) Rect {
if !m.Set {
return r
}
if m.B == 0 && m.C == 0 && m.G == 0 && m.H == 0 {
// Without rotation, skew or perspective: as from the corners, but
// for the signs of zeros, rounding the products as Point does
// (float32 keeps them from fusing with the sums).
x0, x1 := float32(m.A*r.X)+m.X, float32(m.A*(r.X+r.W))+m.X
y0, y1 := float32(m.D*r.Y)+m.Y, float32(m.D*(r.Y+r.H))+m.Y
x0, x1 = min(x0, x1), max(x0, x1)
y0, y1 = min(y0, y1), max(y0, y1)
return Rect{x0, y0, x1 - x0, y1 - y0}
}
corners := [4][2]float32{{r.X, r.Y}, {r.X + r.W, r.Y}, {r.X, r.Y + r.H}, {r.X + r.W, r.Y + r.H}}
if m.Perspective() {
for _, p := range corners {
if m.W(p[0], p[1]) <= 1e-6 {
// Part of it is behind the viewer: it may show anywhere.
return Rect{-1e6, -1e6, 2e6, 2e6}
}
}
}
x0, y0 := m.Point(r.X, r.Y)
x1, y1 := x0, y0
for _, p := range corners[1:] {
x, y := m.Point(p[0], p[1])
x0, y0, x1, y1 = min(x0, x), min(y0, y), max(x1, x), max(y1, y)
}
return Rect{x0, y0, x1 - x0, y1 - y0}
}
// Pixels expresses a DIP transform in device pixels.
func (m Affine) Pixels(scale float32) Affine {
if m.Set {
m.X *= scale
m.Y *= scale
m.G /= scale
m.H /= scale
}
return m
}
+185
View File
@@ -0,0 +1,185 @@
package scene
import (
"math"
"math/rand/v2"
"testing"
)
func TestAffineCompositionInverseAndSingular(t *testing.T) {
m := Translation(30, 20).Mul(Rotation(90)).Mul(Scaling(2, -3))
x, y := m.Point(4, 5)
if math.Abs(float64(x-45)) > 1e-4 || math.Abs(float64(y-28)) > 1e-4 {
t.Fatalf("composed point %v,%v", x, y)
}
i, ok := m.Inverse()
if !ok {
t.Fatal("invertible matrix rejected")
}
x, y = i.Point(x, y)
if math.Abs(float64(x-4)) > 1e-4 || math.Abs(float64(y-5)) > 1e-4 {
t.Fatalf("inverse point %v,%v", x, y)
}
if _, ok := Scaling(0, 1).Inverse(); ok {
t.Fatal("singular matrix inverted")
}
b := m.Bounds(Rect{W: 4, H: 5})
if math.Abs(float64(b.W-15)) > 1e-4 || math.Abs(float64(b.H-8)) > 1e-4 {
t.Fatalf("bounds %v", b)
}
if (Affine{}).Mul(m) != m || m.Mul(Affine{}) != m {
t.Fatal("zero value is not identity")
}
}
// Bounds and Mul of maps that only move or scale take shortcuts: they
// must give what the corners and the general product give.
func TestAffineShortcutsMatch(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
v := func() float32 {
switch r.IntN(4) {
case 0:
return 0
case 1:
return float32(r.IntN(200) - 100)
}
return (r.Float32() - 0.5) * 2000
}
for range 100000 {
m := Matrix(1, 0, 0, 1, v(), v())
if r.IntN(2) == 0 {
m = Matrix(v()/100, 0, 0, v()/100, v(), v())
}
n := Translation(v(), v())
rect := Rect{v(), v(), v(), v()}
got, want := m.Bounds(rect), cornerBounds(m, rect)
if got != want {
t.Fatalf("%v.Bounds(%v) = %v, corners give %v", m, rect, got, want)
}
if m.moves() && n.Set {
want := Matrix(m.A*n.A+m.C*n.B, m.B*n.A+m.D*n.B, m.A*n.C+m.C*n.D, m.B*n.C+m.D*n.D,
m.A*n.X+m.C*n.Y+m.X, m.B*n.X+m.D*n.Y+m.Y)
if got := m.Mul(n); got != want {
t.Fatalf("%v.Mul(%v) = %v, want %v", m, n, got, want)
}
}
}
}
// cornerBounds is Bounds from the corners, for maps without perspective.
func cornerBounds(m Affine, r Rect) Rect {
if !m.Set {
return r
}
corners := [4][2]float32{{r.X, r.Y}, {r.X + r.W, r.Y}, {r.X, r.Y + r.H}, {r.X + r.W, r.Y + r.H}}
x0, y0 := m.Point(r.X, r.Y)
x1, y1 := x0, y0
for _, p := range corners[1:] {
x, y := m.Point(p[0], p[1])
x0, y0, x1, y1 = min(x0, x), min(y0, y), max(x1, x), max(y1, y)
}
return Rect{x0, y0, x1 - x0, y1 - y0}
}
func TestMovedClip(t *testing.T) {
r := Rect{X: 10, Y: 20, W: 100, H: 50}
if got, m := MovedClip(r, Translation(5, -8)); got != (Rect{X: 15, Y: 12, W: 100, H: 50}) || m.Set {
t.Errorf("moved: %v, left %v", got, m)
}
if got, m := MovedClip(r, Affine{}); got != r || m.Set {
t.Errorf("untransformed: %v, left %v", got, m)
}
for _, m := range []Affine{Scaling(2, 2), Rotation(10), Translation(5, 5).Mul(Scaling(1.5, 1))} {
if got, left := MovedClip(r, m); got != r || left != m {
t.Errorf("%v: %v, left %v, want the clip as it was", m, got, left)
}
}
}
// A plane turned in perspective around a point far from its origin can
// have the origin behind the viewer, past the horizon, while what is
// drawn around that point is in front (#1406). Moving the turn there
// keeps the sign of the divisor: what is in front stays in front, under
// the map and under its inverse, and its bounds are its own.
func TestAffineKeepsWhatIsInFront(t *testing.T) {
// Turned 75 degrees about the horizontal axis, its top toward the
// viewer, seen from 600: w = 1 + y·sin(75°)/600 around the turn's own
// origin, which (62, 650) moves to (0, 0) and back.
s, c := math.Sincos(-75 * math.Pi / 180)
turn := Projective(1, 0, 0, float32(c), 0, 0, 0, float32(-s/600))
m := Translation(62, 650).Mul(turn).Mul(Translation(-62, -650))
if !m.Behind || m.W(0, 0) >= 0 {
t.Fatalf("the origin, behind the viewer, has w %v (%+v)", m.W(0, 0), m)
}
card := Rect{X: 24, Y: 612, W: 76, H: 76}
for _, p := range [][2]float32{{24, 612}, {100, 612}, {24, 688}, {100, 688}, {62, 650}} {
if w := m.W(p[0], p[1]); w <= 0 {
t.Errorf("(%v, %v) of the card is behind the viewer: w %v", p[0], p[1], w)
}
// Where it shows: as the turn has it around its own origin.
x, y := m.Point(p[0], p[1])
wx, wy := turn.Point(p[0]-62, p[1]-650)
if math.Abs(float64(x-wx-62)) > 1e-3 || math.Abs(float64(y-wy-650)) > 1e-3 {
t.Errorf("(%v, %v) shows at %v, %v, not %v, %v", p[0], p[1], x, y, wx+62, wy+650)
}
}
if b := m.Bounds(card); b.W > 2*card.W || b.H > card.H || b.X < card.X-card.W || b.Y < card.Y {
t.Errorf("the card shows within %+v", b)
}
inv, ok := m.Inverse()
if !ok {
t.Fatal("no inverse")
}
x, y := m.Point(80, 640)
if w := inv.W(x, y); w <= 0 {
t.Errorf("the inverse puts what the card shows behind the viewer: w %v", w)
}
if lx, ly := inv.Point(x, y); math.Abs(float64(lx-80)) > 1e-2 || math.Abs(float64(ly-640)) > 1e-2 {
t.Errorf("there and back, (80, 640) is %v, %v", lx, ly)
}
// Composed with more, the sign holds: scaled, and in pixels.
if p := Scaling(2, 2).Mul(m); !p.Behind || p.W(62, 650) <= 0 {
t.Errorf("scaled, the card's center has w %v", p.W(62, 650))
}
if p := m.Pixels(2); !p.Behind || p.W(124, 1300) <= 0 {
t.Errorf("in pixels, the card's center has w %v", p.W(124, 1300))
}
// Moved back to its own origin, the origin is in front again.
if back := Translation(-62, -650).Mul(m).Mul(Translation(62, 650)); back.Behind || math.Abs(float64(back.H-turn.H)) > 1e-6 {
t.Errorf("moved back, %+v, not %+v", back, turn)
}
// All of a plane behind the viewer, w = -1 everywhere: nothing shows.
near := Projective(1, 0, 0, 1, 0, 0, 0, 0.001)
if p := near.Mul(Projective(1, 0, 0, 1, 0, -2000, 0, -0.001)); p != singular {
t.Errorf("all behind the viewer, %+v", p)
}
}
// Reshaped tells drawing a transform only moves from drawing it scales or
// turns, its own transform or its glyphs', as of an effect masked by
// glyphs, which draws them with their transforms too.
func TestReshaped(t *testing.T) {
s := &Scene{
Glyphs: []Glyph{{W: 8, H: 12}, {W: 8, H: 12, Transform: Rotation(3)}, {W: 8, H: 12, Transform: Translation(0.5, 0.25)}},
Effects: []EffectOp{{Glyphs: [2]int32{0, 1}}, {Glyphs: [2]int32{1, 2}}, {Glyphs: [2]int32{2, 3}}},
}
for _, c := range []struct {
name string
op Op
want bool
}{
{"fill moved", Op{Kind: OpFill, Transform: Translation(0, -1.27)}, false},
{"fill turned", Op{Kind: OpFill, Transform: Rotation(3)}, true},
{"fill scaled", Op{Kind: OpFill, Transform: Matrix(2, 0, 0, 2, 0, 0)}, true},
{"glyphs moved", Op{Kind: OpGlyphs, Start: 0, End: 1, Transform: Translation(0, -2.54)}, false},
{"glyph moved", Op{Kind: OpGlyphs, Start: 2, End: 3}, false},
{"glyph turned", Op{Kind: OpGlyphs, Start: 0, End: 2, Transform: Translation(0, -2.54)}, true},
{"effect moved", Op{Kind: OpEffect, Start: 0, Transform: Translation(0.5, 0)}, false},
{"effect's glyph moved", Op{Kind: OpEffect, Start: 2, Transform: Translation(0.5, 0)}, false},
{"effect's glyph turned", Op{Kind: OpEffect, Start: 1, Transform: Translation(0.5, 0)}, true},
} {
if got := Reshaped(s, &c.op); got != c.want {
t.Errorf("%s: Reshaped %v, want %v", c.name, got, c.want)
}
}
}