feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+56
@@ -0,0 +1,56 @@
|
||||
# glass
|
||||
|
||||
Liquid Glass for [MyGo](https://github.com/egoist/mygo) apps of native UI,
|
||||
as macOS 26 and later draw it, on every platform: a material that what is
|
||||
under an element shows through, frosted and bent along its edges.
|
||||
|
||||
```go
|
||||
import "github.com/egoist/mygo/plugins/glass"
|
||||
|
||||
ui.Row(c).Padding(8, 16).Radius(22).Material(glass.Glass{}).Children(func() {
|
||||
ui.Text(c, "On glass")
|
||||
})
|
||||
```
|
||||
|
||||
`glass.Group` merges panes of glass that nearly touch into one surface,
|
||||
as AppKit's `NSGlassEffectContainerView` does:
|
||||
|
||||
```go
|
||||
g := glass.NewGroup(c)
|
||||
g.Radius = 22
|
||||
g.Gap(6).Children(func() {
|
||||
g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Cut") }))
|
||||
g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Copy") }))
|
||||
})
|
||||
```
|
||||
|
||||
On macOS 26 and later, `glass.Glass{Native: true}` draws a toolbar over a
|
||||
`ui.WebView` with the system's `NSGlassEffectView`, which samples the page;
|
||||
elsewhere it falls back to the shader. With Reduce Transparency, the
|
||||
materials draw opaque surfaces.
|
||||
|
||||
`glass.ScrollEdge` is macOS's scroll edge effect, which content scrolling
|
||||
under a bar fades (soft) or frosts (hard) under, and `glass.Blur` blurs
|
||||
what is under an element without the glass, evenly or, with a mask,
|
||||
progressively:
|
||||
|
||||
```go
|
||||
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Height(74).PassThrough().Material(glass.ScrollEdge{})
|
||||
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Height(88).PassThrough().
|
||||
Material(glass.Blur{Radius: 6, Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}})
|
||||
```
|
||||
|
||||
See [the documentation](../../docs/plugins/glass.md), and the Glass page of
|
||||
`examples/gallery`.
|
||||
|
||||
The glass and the blur, which a hard scroll edge draws with, are effects
|
||||
of MyGo's renderers (`scene.Effect`): their shaders in Metal Shading
|
||||
Language, HLSL and GLSL (`glass.metal`, `glass.hlsl`, `glass.glsl`, and
|
||||
`blur.*`), and their twins for the CPU renderer (`pixels.go`, `blur.go`),
|
||||
which must draw the same pixels; the tests compare each GPU's drawing
|
||||
with the CPU's.
|
||||
`go generate` compiles the shaders ahead of time where it can: the Metal
|
||||
library on macOS, with Xcode (`shaders_darwin.go`), and the Direct3D
|
||||
bytecode on Windows (`shaders_windows.go`). Renderers compile the source
|
||||
when the code compiled ahead of time is older than it or than their own
|
||||
part of the shader.
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// A level of the blur's effect in GLSL (see scene.Effect), as blur.metal
|
||||
// is in Metal Shading Language and blur.go draws it on the CPU.
|
||||
|
||||
vec4 blurAt(ivec2 p, ivec2 size) { return texelFetch(uBackdrop, clamp(p, ivec2(0), size - 1), 0); }
|
||||
|
||||
vec4 blurSample(Effect e, vec2 q) {
|
||||
q = framePoint(e, q);
|
||||
vec2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
vec2 f = floor(u);
|
||||
vec2 w = u - f;
|
||||
ivec2 p = ivec2(f);
|
||||
ivec2 size = ivec2(e.area.zw);
|
||||
vec4 top = blurAt(p, size) * (1.0 - w.x) + blurAt(p + ivec2(1, 0), size) * w.x;
|
||||
vec4 bot = blurAt(p + ivec2(0, 1), size) * (1.0 - w.x) + blurAt(p + ivec2(1, 1), size) * w.x;
|
||||
return top * (1.0 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
vec2 d = e.p0.zw - e.p0.xy;
|
||||
float l = d.x * d.x + d.y * d.y;
|
||||
float t = 0.0;
|
||||
if (l > 0.0) {
|
||||
t = clamp(((p.x - e.p0.x) * d.x + (p.y - e.p0.y) * d.y) / max(l, 0.0001), 0.0, 1.0);
|
||||
}
|
||||
float blur = e.p1.x * (1.0 - t) + e.p1.y * t;
|
||||
float w = clamp((blur - e.p1.z) / (e.p1.w - e.p1.z), 0.0, 1.0);
|
||||
if (w <= 0.0) {
|
||||
return vec4(0.0);
|
||||
}
|
||||
vec4 c = blurSample(e, p);
|
||||
float lum = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
c.rgb = clamp(lum + (c.rgb - lum) * (1.0 + e.p2.x) + e.p2.y * c.a, vec3(0.0), vec3(c.a));
|
||||
c += (vec4(e.p3.rgb, 1.0) - c) * e.p2.z;
|
||||
return c * w;
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Blur is a backdrop blur, a ui.Material: what was painted under the
|
||||
// element shows through it blurred, with no tint, rim or shadow. With a
|
||||
// Mask, the blur fades along a gradient, a progressive blur, as under a
|
||||
// bar that content scrolls under (ScrollEdge is macOS's own effect there):
|
||||
//
|
||||
// ui.Row(c).Absolute().Top(0).Left(0).Right(0).Height(56).Material(glass.Blur{
|
||||
// Radius: 12,
|
||||
// Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180},
|
||||
// })
|
||||
type Blur struct {
|
||||
// Radius is how much what shows through blurs, in DIPs: the standard
|
||||
// deviation of a Gaussian, as CSS's blur() takes.
|
||||
Radius float32
|
||||
// Mask, if set, varies the blur along a gradient, by the alpha of its
|
||||
// colors, as CSS's mask-image does: what shows through blurs by Radius
|
||||
// where the gradient is opaque, by less where it is translucent, and
|
||||
// not at all where it is transparent. Its colors do not show.
|
||||
Mask *ui.LinearGradient
|
||||
}
|
||||
|
||||
// PaintMaterial paints the blur over box, rounded by radii.
|
||||
func (b Blur) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
paintBlur(p, box, radii, b)
|
||||
}
|
||||
|
||||
// String describes the blur, as the inspector shows it.
|
||||
func (b Blur) String() string {
|
||||
s := fmt.Sprintf("blur(%g)", b.Radius)
|
||||
if m := b.Mask; m != nil {
|
||||
s += fmt.Sprintf(" mask(%g%%→%g%% %g°)", math.Round(float64(m.From.A)/2.55), math.Round(float64(m.To.A)/2.55), m.Angle)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// blurLevel is a step of a blur that varies across its element: what was
|
||||
// painted under it, the levels before included, blurred by blur pixels,
|
||||
// shown where the blur the element wants is more than lo pixels, by how
|
||||
// far it is toward hi, and wholly from hi.
|
||||
//
|
||||
// Blurs add up as their variances do, so after the levels showing
|
||||
// wholly at a pixel, what shows there is blurred by hi pixels of the last
|
||||
// of them: the levels' his double from one level to the next, from at
|
||||
// most finestLevel pixels to the blur's most, and between two, a pixel
|
||||
// shows the blurs of both, mixed, which the eye takes for a blur between
|
||||
// them. A blur that does not vary is one level, which shows everywhere.
|
||||
type blurLevel struct{ blur, lo, hi float32 }
|
||||
|
||||
// finestLevel is the most the first level of a varying blur blurs, in
|
||||
// pixels: it shows mixed with what is not blurred, which at 2 pixels looks
|
||||
// as a blur between them. Against a blur varying per pixel, a first level
|
||||
// of 1 pixel measured no closer, and levels √2 apart rather than 2 closer
|
||||
// within the element but further along its edges, where each level reads
|
||||
// what is around the element unblurred.
|
||||
const finestLevel = 2
|
||||
|
||||
// blurLevels returns the levels of a blur varying from least to most
|
||||
// pixels.
|
||||
func blurLevels(least, most float32) []blurLevel {
|
||||
least = max(least, 0)
|
||||
if most <= least {
|
||||
if least <= 0 {
|
||||
return nil
|
||||
}
|
||||
return []blurLevel{{blur: least, lo: -1, hi: 0}}
|
||||
}
|
||||
// The levels' his, from the most down, halving.
|
||||
his := []float32{most}
|
||||
for h := most; h > finestLevel && h/2 > least; {
|
||||
h /= 2
|
||||
his = append(his, h)
|
||||
}
|
||||
var levels []blurLevel
|
||||
if least > 0 {
|
||||
levels = append(levels, blurLevel{blur: least, lo: -1, hi: 0})
|
||||
}
|
||||
lo := least
|
||||
for i := len(his) - 1; i >= 0; i-- {
|
||||
hi := his[i]
|
||||
levels = append(levels, blurLevel{blur: sqrt(hi*hi - lo*lo), lo: lo, hi: hi})
|
||||
lo = hi
|
||||
}
|
||||
return levels
|
||||
}
|
||||
|
||||
// paintBlur paints the blur b over box, rounded by radii.
|
||||
func paintBlur(p *ui.Painter, box ui.Rect, radii [4]float32, b Blur) {
|
||||
s := p.Scale()
|
||||
if box.W <= 0 || box.H <= 0 {
|
||||
return
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
// What a blur is for, the content under a bar reading through it,
|
||||
// is transparency: the desktop asks for an opaque bar instead.
|
||||
p.FillRadii(box, radii, p.Theme().Background)
|
||||
return
|
||||
}
|
||||
// The rectangle of the element, in pixels, as the painter snaps it.
|
||||
px := scene.Rect{X: round(box.X * s), Y: round(box.Y * s)}
|
||||
px.W, px.H = round((box.X+box.W)*s)-px.X, round((box.Y+box.H)*s)-px.Y
|
||||
blurOps(px, radii == [4]float32{}, b.Radius*s, b.Mask, func(r scene.Rect, fx scene.EffectOp) {
|
||||
p.Effect(fx.Effect, ui.Rect{X: r.X / s, Y: r.Y / s, W: r.W / s, H: r.H / s}, radii, fx.Blur, fx.Params)
|
||||
})
|
||||
}
|
||||
|
||||
// blurOps calls op with the rectangle and the effect of each level
|
||||
// (blurLevels) of a blur of most pixels over r, in pixels, along mask: a
|
||||
// level after another, each where the blur is more than its lo when r is
|
||||
// square, which it then reads only what is under.
|
||||
func blurOps(r scene.Rect, square bool, most float32, mask *ui.LinearGradient, op func(r scene.Rect, fx scene.EffectOp)) {
|
||||
if r.W <= 0 || r.H <= 0 || most <= 0 {
|
||||
return
|
||||
}
|
||||
// The blur at the mask's start and end, along its line.
|
||||
var line [4]float32
|
||||
at0, at1 := most, most
|
||||
if mask != nil {
|
||||
line = maskLine(r, *mask)
|
||||
at0, at1 = most*float32(mask.From.A)/255, most*float32(mask.To.A)/255
|
||||
}
|
||||
for _, l := range blurLevels(min(at0, at1), max(at0, at1)) {
|
||||
lr := r
|
||||
if square && l.lo >= 0 {
|
||||
var ok bool
|
||||
if lr, ok = blurWanted(r, line, at0, at1, l.lo); !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
op(lr, scene.EffectOp{Effect: blurEffect, Blur: l.blur, Params: [5][4]float32{line, {at0, at1, l.lo, l.hi}}})
|
||||
}
|
||||
}
|
||||
|
||||
// maskLine returns where the mask's From and To are, in pixels, as package
|
||||
// ui places a gradient's across the rectangle r (Element.Gradient): along
|
||||
// a line through its middle at the gradient's angle, as long as the
|
||||
// rectangle's corners are apart along it, as CSS's linear-gradient.
|
||||
func maskLine(r scene.Rect, g ui.LinearGradient) [4]float32 {
|
||||
a := float64(g.Angle) * math.Pi / 180
|
||||
dx, dy := float32(math.Sin(a)), float32(-math.Cos(a))
|
||||
half := (abs(r.W*dx) + abs(r.H*dy)) / 2
|
||||
cx, cy := r.X+r.W/2, r.Y+r.H/2
|
||||
x0, y0, x1, y1 := cx-dx*half, cy-dy*half, cx+dx*half, cy+dy*half
|
||||
start, end := g.Start, g.End
|
||||
if start == 0 && end == 0 {
|
||||
end = 1
|
||||
}
|
||||
sx, sy := x0+(x1-x0)*start, y0+(y1-y0)*start
|
||||
ex, ey := x0+(x1-x0)*end, y0+(y1-y0)*end
|
||||
if end-start < 0.5/max(2*half, 1) {
|
||||
// Stops at one place: a hard edge, half a pixel wide.
|
||||
ex, ey = sx+dx*0.5, sy+dy*0.5
|
||||
}
|
||||
return [4]float32{sx, sy, ex, ey}
|
||||
}
|
||||
|
||||
// blurWanted returns the bounds, in whole pixels, of the part of r where
|
||||
// the blur along line, from at0 at its start to at1 at its end, is more
|
||||
// than lo, and whether there is one.
|
||||
func blurWanted(r scene.Rect, line [4]float32, at0, at1, lo float32) (scene.Rect, bool) {
|
||||
if at0 == at1 {
|
||||
return r, at0 > lo
|
||||
}
|
||||
// Along the line, the blur is lo at tc, and more on one side of it:
|
||||
// the side of the half-plane n·p > c.
|
||||
dx, dy := line[2]-line[0], line[3]-line[1]
|
||||
tc := (lo - at0) / (at1 - at0)
|
||||
nx, ny := dx, dy
|
||||
c := line[0]*dx + line[1]*dy + tc*(dx*dx+dy*dy)
|
||||
if at1 < at0 {
|
||||
nx, ny, c = -nx, -ny, -c
|
||||
}
|
||||
corners := [4][2]float32{{r.X, r.Y}, {r.X + r.W, r.Y}, {r.X + r.W, r.Y + r.H}, {r.X, r.Y + r.H}}
|
||||
x0, y0 := float32(math.Inf(1)), float32(math.Inf(1))
|
||||
x1, y1 := float32(math.Inf(-1)), float32(math.Inf(-1))
|
||||
add := func(x, y float32) {
|
||||
x0, y0, x1, y1 = min(x0, x), min(y0, y), max(x1, x), max(y1, y)
|
||||
}
|
||||
for i, a := range corners {
|
||||
b := corners[(i+1)%4]
|
||||
fa, fb := nx*a[0]+ny*a[1]-c, nx*b[0]+ny*b[1]-c
|
||||
if fa > 0 {
|
||||
add(a[0], a[1])
|
||||
}
|
||||
if (fa > 0) != (fb > 0) {
|
||||
k := fa / (fa - fb)
|
||||
add(a[0]+(b[0]-a[0])*k, a[1]+(b[1]-a[1])*k)
|
||||
}
|
||||
}
|
||||
if x0 > x1 || y0 > y1 {
|
||||
return scene.Rect{}, false
|
||||
}
|
||||
x0, y0 = max(floor(x0), r.X), max(floor(y0), r.Y)
|
||||
x1, y1 = min(ceil(x1), r.X+r.W), min(ceil(y1), r.Y+r.H)
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return scene.Rect{}, false
|
||||
}
|
||||
return scene.Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}, true
|
||||
}
|
||||
|
||||
// blurTone is what a level does to the colors it shows, which a blur's
|
||||
// levels leave as they are: saturation more saturation (0 for as is),
|
||||
// offset added to each channel, and mix of the opaque color over it, in
|
||||
// its parameters p2 and p3, as a scroll edge's hard style frosts.
|
||||
type blurTone struct {
|
||||
saturation, offset, mix float32
|
||||
color [3]float32
|
||||
}
|
||||
|
||||
// params returns the tone's parameters, p2 and p3.
|
||||
func (t blurTone) params() (p2, p3 [4]float32) {
|
||||
return [4]float32{t.saturation, t.offset, t.mix}, [4]float32{t.color[0], t.color[1], t.color[2], 1}
|
||||
}
|
||||
|
||||
// blurPixels draws a level of a blur on the CPU, as its shaders do on the
|
||||
// GPU.
|
||||
type blurPixels struct {
|
||||
line, band, tone, color [4]float32
|
||||
}
|
||||
|
||||
// Begin reads the level's mask, band and tone.
|
||||
func (px *blurPixels) Begin(op *scene.EffectOp, _ scene.Rect, _ [4]float32) {
|
||||
px.line, px.band, px.tone, px.color = op.Params[0], op.Params[1], op.Params[2], op.Params[3]
|
||||
}
|
||||
|
||||
// Color returns the color of the level at the pixel center (x, y), as the
|
||||
// shaders' effect does: the backdrop, toned, by how much the level shows
|
||||
// there.
|
||||
func (px *blurPixels) Color(x, y float32, b *scene.BackdropImage) [4]float32 {
|
||||
w := px.weight(x, y)
|
||||
if w <= 0 {
|
||||
return [4]float32{}
|
||||
}
|
||||
c := sampleRGBA(b, x, y)
|
||||
t := &px.tone
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
for i := range 3 {
|
||||
c[i] = min(max(l+(c[i]-l)*(1+t[0])+t[1]*c[3], 0), c[3])
|
||||
}
|
||||
for i := range c {
|
||||
c[i] += (px.color[i] - c[i]) * t[2]
|
||||
}
|
||||
return [4]float32{c[0] * w, c[1] * w, c[2] * w, c[3] * w}
|
||||
}
|
||||
|
||||
// weight returns how much the level shows at (x, y), from 0 to 1: by how
|
||||
// far the blur there, along the mask, is into its band.
|
||||
func (px *blurPixels) weight(x, y float32) float32 {
|
||||
l, band := &px.line, &px.band
|
||||
dx, dy := l[2]-l[0], l[3]-l[1]
|
||||
t := float32(0)
|
||||
if d := dx*dx + dy*dy; d > 0 {
|
||||
t = min(max(((x-l[0])*dx+(y-l[1])*dy)/max(d, 0.0001), 0), 1)
|
||||
}
|
||||
blur := band[0]*(1-t) + band[1]*t
|
||||
return min(max((blur-band[2])/(band[3]-band[2]), 0), 1)
|
||||
}
|
||||
|
||||
// sampleRGBA returns the backdrop at (x, y) with its alpha, premultiplied,
|
||||
// as BackdropImage.Sample does its color, and the shaders' blurSample.
|
||||
func sampleRGBA(b *scene.BackdropImage, x, y float32) [4]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 := floor(u), floor(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):][:4], b.Pix[4*(y0*b.W+x1):][:4]
|
||||
p01, p11 := b.Pix[4*(y1*b.W+x0):][:4], b.Pix[4*(y1*b.W+x1):][:4]
|
||||
var c [4]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
|
||||
}
|
||||
|
||||
func round(v float32) float32 { return float32(math.Round(float64(v))) }
|
||||
func floor(v float32) float32 { return float32(math.Floor(float64(v))) }
|
||||
func ceil(v float32) float32 { return float32(math.Ceil(float64(v))) }
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// A level of the blur's effect in HLSL (see scene.Effect), as blur.metal
|
||||
// is in Metal Shading Language and blur.go draws it on the CPU.
|
||||
|
||||
float4 blurAt(int2 p, int2 size) { return backdropTex.Load(int3(clamp(p, int2(0, 0), size - 1), 0)); }
|
||||
|
||||
float4 blurSample(Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float4 top = blurAt(p, size) * (1 - w.x) + blurAt(p + int2(1, 0), size) * w.x;
|
||||
float4 bot = blurAt(p + int2(0, 1), size) * (1 - w.x) + blurAt(p + int2(1, 1), size) * w.x;
|
||||
return top * (1 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e) {
|
||||
float2 d = e.p0.zw - e.p0.xy;
|
||||
float l = d.x * d.x + d.y * d.y;
|
||||
float t = 0;
|
||||
if (l > 0) {
|
||||
t = saturate(((p.x - e.p0.x) * d.x + (p.y - e.p0.y) * d.y) / max(l, 0.0001));
|
||||
}
|
||||
float blur = e.p1.x * (1 - t) + e.p1.y * t;
|
||||
float w = saturate((blur - e.p1.z) / (e.p1.w - e.p1.z));
|
||||
if (w <= 0) {
|
||||
return float4(0, 0, 0, 0);
|
||||
}
|
||||
float4 c = blurSample(e, p);
|
||||
float lum = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
c.rgb = clamp(lum + (c.rgb - lum) * (1 + e.p2.x) + e.p2.y * c.a, 0, c.a);
|
||||
c += (float4(e.p3.rgb, 1) - c) * e.p2.z;
|
||||
return c * w;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
// A level of the blur's effect in Metal Shading Language (see
|
||||
// scene.Effect and blurLevel), as blur.go draws it on the CPU. p0 is the
|
||||
// mask's line, from its start to its end in pixels; p1 the blur at its
|
||||
// start and at its end, and the level's band, from p1.z to p1.w; p2 and p3
|
||||
// its tone (blurTone): how much more saturated, the offset and how much of
|
||||
// the color p3 over it.
|
||||
|
||||
// blurAt returns the backdrop's texel p, with its alpha, clamped to its
|
||||
// edges.
|
||||
float4 blurAt(texture2d<float> t, int2 p, int2 size) { return t.read(uint2(clamp(p, int2(0), size - 1))); }
|
||||
|
||||
// blurSample returns the backdrop at q with its alpha, as sampleBackdrop
|
||||
// does its color (sampleRGBA).
|
||||
float4 blurSample(texture2d<float> t, Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5f;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float4 top = blurAt(t, p, size) * (1.0f - w.x) + blurAt(t, p + int2(1, 0), size) * w.x;
|
||||
float4 bot = blurAt(t, p + int2(0, 1), size) * (1.0f - w.x) + blurAt(t, p + int2(1, 1), size) * w.x;
|
||||
return top * (1.0f - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
float2 d = e.p0.zw - e.p0.xy;
|
||||
float l = d.x * d.x + d.y * d.y;
|
||||
float t = 0.0f;
|
||||
if (l > 0.0f) {
|
||||
t = clamp(((p.x - e.p0.x) * d.x + (p.y - e.p0.y) * d.y) / max(l, 0.0001f), 0.0f, 1.0f);
|
||||
}
|
||||
float blur = e.p1.x * (1.0f - t) + e.p1.y * t;
|
||||
float w = clamp((blur - e.p1.z) / (e.p1.w - e.p1.z), 0.0f, 1.0f);
|
||||
if (w <= 0.0f) {
|
||||
return float4(0.0f);
|
||||
}
|
||||
float4 c = blurSample(backdrop, e, p);
|
||||
float lum = 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;
|
||||
c.rgb = clamp(lum + (c.rgb - lum) * (1.0f + e.p2.x) + e.p2.y * c.a, 0.0f, c.a);
|
||||
c += (float4(e.p3.rgb, 1.0f) - c) * e.p2.z;
|
||||
return c * w;
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"image"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// TestBlurLevels checks that a varying blur's levels add up to its most,
|
||||
// halving from there down to the finest, and that one that does not vary
|
||||
// is a level showing everywhere.
|
||||
func TestBlurLevels(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
least, most float32
|
||||
n int
|
||||
}{{0, 24, 5}, {0, 2, 1}, {0, 0.5, 1}, {5, 24, 4}, {3, 3, 1}, {0, 0, 0}} {
|
||||
levels := blurLevels(c.least, c.most)
|
||||
if len(levels) != c.n {
|
||||
t.Errorf("%v to %v: %d levels, not %d: %v", c.least, c.most, len(levels), c.n, levels)
|
||||
continue
|
||||
}
|
||||
if c.n == 0 {
|
||||
continue
|
||||
}
|
||||
// The variances add up to the most's.
|
||||
var v float64
|
||||
for _, l := range levels {
|
||||
v += float64(l.blur * l.blur)
|
||||
}
|
||||
if math.Abs(math.Sqrt(v)-float64(max(c.most, c.least))) > 1e-3 {
|
||||
t.Errorf("%v to %v: the levels blur by %v in all: %v", c.least, c.most, math.Sqrt(v), levels)
|
||||
}
|
||||
last := levels[len(levels)-1]
|
||||
if c.most > c.least && last.hi != c.most {
|
||||
t.Errorf("%v to %v: the last level ends at %v", c.least, c.most, last.hi)
|
||||
}
|
||||
for i := 1; i < len(levels); i++ {
|
||||
if levels[i].lo != levels[i-1].hi && levels[i-1].lo >= 0 {
|
||||
t.Errorf("%v to %v: level %d starts at %v, after %v", c.least, c.most, i, levels[i].lo, levels[i-1].hi)
|
||||
}
|
||||
}
|
||||
if first := levels[0]; first.lo >= 0 && first.hi > finestLevel && first.lo == 0 {
|
||||
t.Errorf("%v to %v: the first level blurs by %v, over what is not blurred", c.least, c.most, first.hi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlurWanted checks that a level's rectangle holds every pixel it
|
||||
// shows at, and little more, at any angle of the mask.
|
||||
func TestBlurWanted(t *testing.T) {
|
||||
r := scene.Rect{X: 10, Y: 20, W: 200, H: 80}
|
||||
for _, g := range []ui.LinearGradient{
|
||||
{From: ui.RGB(0, 0, 0), Angle: 180},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 0},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 90, Start: 0.2, End: 0.6},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 30},
|
||||
{From: ui.RGBA(0, 0, 0, 0.3), To: ui.RGB(0, 0, 0), Angle: 225},
|
||||
{From: ui.RGB(0, 0, 0), Angle: 180, Start: 0.5, End: 0.5},
|
||||
} {
|
||||
at0, at1 := 20*float32(g.From.A)/255, 20*float32(g.To.A)/255
|
||||
line := maskLine(r, g)
|
||||
for _, l := range blurLevels(min(at0, at1), max(at0, at1)) {
|
||||
if l.lo < 0 {
|
||||
continue
|
||||
}
|
||||
px := blurPixels{line: line, band: [4]float32{at0, at1, l.lo, l.hi}}
|
||||
got, ok := blurWanted(r, line, at0, at1, l.lo)
|
||||
shown := image.Rectangle{}
|
||||
for y := int(r.Y); y < int(r.Y+r.H); y++ {
|
||||
for x := int(r.X); x < int(r.X+r.W); x++ {
|
||||
if px.weight(float32(x)+0.5, float32(y)+0.5) > 0 {
|
||||
shown = shown.Union(image.Rect(x, y, x+1, y+1))
|
||||
}
|
||||
}
|
||||
}
|
||||
want := image.Rect(int(got.X), int(got.Y), int(got.X+got.W), int(got.Y+got.H))
|
||||
if !ok {
|
||||
want = image.Rectangle{}
|
||||
}
|
||||
if !shown.In(want) {
|
||||
t.Errorf("%+v, level %v: shows at %v, outside %v", g, l, shown, want)
|
||||
}
|
||||
// At most two pixels more on each side, where the edge of the
|
||||
// level, slanted, crosses the pixels' rows between their
|
||||
// centers.
|
||||
if !shown.Empty() && !want.In(shown.Inset(-2)) {
|
||||
t.Errorf("%+v, level %v: %v is much larger than where it shows, %v", g, l, want, shown)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stripes paints black columns period/2 DIPs wide, period apart, over
|
||||
// white: what blurs to gray.
|
||||
func stripes(c *ui.Context, period float32) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
for x := float32(0); x < r.W; x += period {
|
||||
p.Fill(ui.Rect{X: r.X + x, Y: r.Y, W: period / 2, H: r.H}, ui.RGB(0, 0, 0), 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// contrast returns how far apart the darkest and the lightest pixels of
|
||||
// row y are, from column x0 to x1: how much of the stripes shows there.
|
||||
func contrast(img *image.RGBA, y, x0, x1 int) int {
|
||||
lo, hi := 255, 0
|
||||
for x := x0; x < x1; x++ {
|
||||
v := int(img.RGBAAt(x, y).R)
|
||||
lo, hi = min(lo, v), max(hi, v)
|
||||
}
|
||||
return hi - lo
|
||||
}
|
||||
|
||||
func TestBlurBlursWhatIsBehind(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Children(func() {
|
||||
stripes(c, 2)
|
||||
ui.Box(c).Absolute().Left(0).Top(0).Size(200, 30).Material(Blur{Radius: 4})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 60)
|
||||
img := tt.Image()
|
||||
if got := contrast(img, 15, 20, 180); got > 2 {
|
||||
t.Errorf("under the blur, the stripes' contrast is %d", got)
|
||||
}
|
||||
// Stripes average to gray.
|
||||
if g := pixelAt(img, 100, 15)[0]; g < 115 || g > 140 {
|
||||
t.Errorf("under the blur, the stripes are %d", g)
|
||||
}
|
||||
if got := contrast(img, 45, 20, 180); got != 255 {
|
||||
t.Errorf("below the blur, the stripes' contrast is %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressiveBlur(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Children(func() {
|
||||
stripes(c, 8)
|
||||
ui.Box(c).Absolute().Left(0).Top(10).Right(0).Height(80).
|
||||
Material(Blur{Radius: 6, Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 100, 100)
|
||||
tt.SetScale(2)
|
||||
img := tt.Image()
|
||||
// The blur fades from its top, 12 pixels, to nothing at its bottom:
|
||||
// the stripes, 16 pixels apart, show more and more toward its bottom,
|
||||
// and wholly below it.
|
||||
last := -1
|
||||
for y := 20; y < 180; y += 4 {
|
||||
got := contrast(img, y, 40, 160)
|
||||
if got+1 < last {
|
||||
t.Errorf("row %d has a contrast of %d, less than above it (%d)", y, got, last)
|
||||
}
|
||||
last = max(last, got)
|
||||
}
|
||||
if top := contrast(img, 22, 40, 160); top > 1 {
|
||||
t.Errorf("at the top, the stripes' contrast is %d", top)
|
||||
}
|
||||
// Halfway, the blur is 6 pixels, which leaves 6% of the stripes'
|
||||
// first harmonic: e^(-2π²·6²/16²).
|
||||
if mid := contrast(img, 100, 40, 160); mid < 10 || mid > 40 {
|
||||
t.Errorf("halfway, the stripes' contrast is %d", mid)
|
||||
}
|
||||
if low := contrast(img, 176, 40, 160); low < 200 {
|
||||
t.Errorf("at the bottom, the stripes' contrast is %d", low)
|
||||
}
|
||||
if below := contrast(img, 182, 40, 160); below != 255 {
|
||||
t.Errorf("below the blur, the stripes' contrast is %d", below)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlurString(t *testing.T) {
|
||||
if s := (Blur{Radius: 12}).String(); s != "blur(12)" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
b := Blur{Radius: 8, Mask: &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}}
|
||||
if s := b.String(); s != "blur(8) mask(100%→0% 180°)" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// blurOp appends the levels of a blur of most pixels over r to s, along
|
||||
// mask, as paintBlur paints them.
|
||||
func blurOp(s *scene.Scene, r scene.Rect, radii [4]float32, most float32, mask *ui.LinearGradient, opacity float32) {
|
||||
blurOps(r, radii == [4]float32{}, most, mask, func(lr scene.Rect, fx scene.EffectOp) {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: lr, Radii: radii, Start: int32(len(s.Effects)), Opacity: opacity})
|
||||
s.Effects = append(s.Effects, fx)
|
||||
})
|
||||
}
|
||||
|
||||
// blurScene returns a 320×140 scene of blurs over stripes, which the
|
||||
// renderers must draw alike: an even blur, rounded; a progressive blur
|
||||
// from the top, and one at an angle within a rounded clip; a blur with a
|
||||
// plateau, half transparent; a blur over what is partly transparent; and
|
||||
// a hard scroll edge's tone.
|
||||
func blurScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 140}
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
yellow := scene.Color{R: 250, G: 204, B: 21, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 260, H: 140}, Color: scene.Color{R: 246, G: 247, B: 249, A: 255}})
|
||||
for i := range 13 {
|
||||
c := []scene.Color{red, blue, yellow, ink}[i%4]
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 20), W: 8, H: 140}, Color: c})
|
||||
}
|
||||
for i := range 14 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{Y: float32(i * 10), W: 260, H: 2}, Color: ink})
|
||||
}
|
||||
black := ui.RGB(0, 0, 0)
|
||||
blurOp(s, scene.Rect{X: 10, Y: 10, W: 90, H: 50}, r4(14), 6, nil, 0)
|
||||
blurOp(s, scene.Rect{X: 110, Y: 0, W: 120, H: 60}, [4]float32{}, 16, &ui.LinearGradient{From: black, To: ui.Transparent, Angle: 180}, 0)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 70, W: 120, H: 60}, Radii: r4(16)})
|
||||
blurOp(s, scene.Rect{X: 10, Y: 66, W: 140, H: 70}, [4]float32{}, 10, &ui.LinearGradient{From: ui.Transparent, To: black, Angle: 60}, 0)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
blurOp(s, scene.Rect{X: 150.5, Y: 70.25, W: 60, H: 60}, [4]float32{}, 8,
|
||||
&ui.LinearGradient{From: ui.RGBA(0, 0, 0, 0.4), To: black, Angle: 90, Start: 0.3, End: 0.7}, 0.6)
|
||||
blurOp(s, scene.Rect{X: 230, Y: 20, W: 70, H: 100}, r4(10), 5, nil, 0)
|
||||
// A hard scroll edge's tone, over the edge of nothing.
|
||||
p2, p3 := blurTone{saturation: 0.25, offset: 0.03, mix: 0.6, color: [3]float32{0.9, 0.95, 1}}.params()
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{X: 234, Y: 0, W: 86, H: 16}, Start: int32(len(s.Effects))})
|
||||
s.Effects = append(s.Effects, scene.EffectOp{Effect: blurEffect, Blur: 4, Params: [5][4]float32{{}, {4, 4, -1, 0}, p2, p3}})
|
||||
return s
|
||||
}
|
||||
|
||||
// TestBlurScene checks the CPU's drawing of the blurs: what is not under
|
||||
// them shows as it is, what is under the most blurred is a mix of the
|
||||
// stripes, and the nothing beside the stripes stays nothing.
|
||||
func TestBlurScene(t *testing.T) {
|
||||
s := blurScene()
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(img, s)
|
||||
at := func(x, y int) [4]byte {
|
||||
p := img.Pix[y*img.Stride+4*x:]
|
||||
return [4]byte{p[2], p[1], p[0], p[3]}
|
||||
}
|
||||
if p := at(5, 105); p != [4]byte{220, 40, 40, 255} {
|
||||
t.Errorf("outside the blurs: %v", p)
|
||||
}
|
||||
// Over nothing, the blur paints nothing; along the edge of what is
|
||||
// under it, that and nothing blur together, translucent.
|
||||
if p := at(290, 70); p[3] != 0 {
|
||||
t.Errorf("the blur over nothing: %v", p)
|
||||
}
|
||||
if p := at(260, 70); p[3] < 90 || p[3] > 165 {
|
||||
t.Errorf("the blur along the edge of nothing: %v", p)
|
||||
}
|
||||
// Under the top of the progressive blur, the stripes are gone.
|
||||
lo, hi := 255, 0
|
||||
for x := 112; x < 228; x++ {
|
||||
v := int(at(x, 2)[1])
|
||||
lo, hi = min(lo, v), max(hi, v)
|
||||
}
|
||||
if hi-lo > 40 {
|
||||
t.Errorf("under the top of the progressive blur, the row varies from %d to %d", lo, hi)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBlur measures drawing a window with a blur under its toolbar
|
||||
// on the CPU, whole: 1360×720 pixels, stripes under a strip 176 pixels
|
||||
// high blurred by 24 pixels, evenly or fading from the top.
|
||||
func BenchmarkBlur(b *testing.B) {
|
||||
for _, bc := range []struct {
|
||||
name string
|
||||
mask *ui.LinearGradient
|
||||
}{{"even", nil}, {"progressive", &ui.LinearGradient{From: ui.RGB(0, 0, 0), To: ui.Transparent, Angle: 180}}} {
|
||||
b.Run(bc.name, func(b *testing.B) {
|
||||
s := &scene.Scene{Width: 1360, Height: 720, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
|
||||
colors := []scene.Color{{R: 239, G: 68, B: 68, A: 255}, {R: 245, G: 158, B: 11, A: 255}, {R: 16, G: 185, B: 129, A: 255}, {R: 59, G: 130, B: 246, A: 255}}
|
||||
for i := range 17 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 80), W: 40, H: 720}, Color: colors[i%len(colors)]})
|
||||
}
|
||||
blurOp(s, scene.Rect{W: 1360, H: 176}, [4]float32{}, 24, bc.mask, 0)
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
for b.Loop() {
|
||||
raster.Render(img, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package glass
|
||||
|
||||
import "github.com/egoist/mygo/ui"
|
||||
|
||||
// ScrollEdge is the scroll edge effect of macOS 26 and later, a
|
||||
// ui.Material: what macOS draws over content scrolling under a bar of
|
||||
// controls, so that they stand out from it, as SwiftUI's safeAreaBar with
|
||||
// scrollEdgeEffectStyle does. Fill an element over the content's edge
|
||||
// with it, under the bar, as long as the bar and 10 DIPs more when soft,
|
||||
// as long as the bar when hard:
|
||||
//
|
||||
// ui.Box(c).Absolute().Top(0).Left(0).Right(0).Height(74).PassThrough().Material(glass.ScrollEdge{})
|
||||
//
|
||||
// Its looks are macOS 27's, measured from SwiftUI's: the soft edge fades
|
||||
// the content into its background, with no blur; the hard edge frosts it.
|
||||
type ScrollEdge struct {
|
||||
// Hard makes the edge hard: what is under it blurred by about 6 DIPs, its
|
||||
// colors saturated, under 82% of the background, evenly, with a
|
||||
// hairline along its other edge. Soft, it fades the background over
|
||||
// the content, from 85% at the bar's edge to nothing at the other.
|
||||
Hard bool
|
||||
// Bottom puts the bar at the element's bottom, the effect rising from
|
||||
// it, rather than at its top.
|
||||
Bottom bool
|
||||
// Background is what the content scrolls over, which the effect lays
|
||||
// over it; unset, the theme's Background.
|
||||
Background ui.Color
|
||||
}
|
||||
|
||||
// PaintMaterial paints the scroll edge over box, rounded by radii.
|
||||
func (e ScrollEdge) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
if box.W <= 0 || box.H <= 0 {
|
||||
return
|
||||
}
|
||||
bg := e.Background
|
||||
if bg.A == 0 {
|
||||
bg = p.Theme().Background
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
// An opaque bar, in place of what would show through the edge.
|
||||
bg.A = 255
|
||||
p.FillRadii(box, radii, bg)
|
||||
return
|
||||
}
|
||||
if !e.Hard {
|
||||
// The background, its alpha 0.85 at the bar's edge, falling
|
||||
// linearly to 0 at the other, as AppKit's soft pocket replays the
|
||||
// window's background under a gradient mask, in sRGB.
|
||||
g := ui.LinearGradient{From: bg.Alpha(softEdge), To: bg.Alpha(0), Angle: 180}
|
||||
if e.Bottom {
|
||||
g.Angle = 0
|
||||
}
|
||||
fillGradient(p, box, radii, g)
|
||||
return
|
||||
}
|
||||
// Under a hard edge, the content blurred, saturated by 1.25
|
||||
// and lightened by 0.03, as AppKit's HardPocketContentBlur, under the
|
||||
// background at 82.45%, desaturated to 0.947 and lightened by 0.03, as
|
||||
// its HardPocketBackgroundReplay, evenly.
|
||||
s := p.Scale()
|
||||
b := hardEdgeBlur * s
|
||||
c := toned([3]float32{float32(bg.R) / 255, float32(bg.G) / 255, float32(bg.B) / 255}, 0.947, 0.03)
|
||||
p2, p3 := blurTone{saturation: 0.25, offset: 0.03, mix: 0.8245, color: c}.params()
|
||||
p.Effect(blurEffect, box, radii, b, [5][4]float32{{}, {b, b, -1, 0}, p2, p3})
|
||||
// The hairline along the other edge, outside it, half a DIP: black at
|
||||
// 10% in light mode, white at 7% in dark mode.
|
||||
line := ui.RGBA(0, 0, 0, 0.1)
|
||||
if p.Theme().Dark {
|
||||
line = ui.RGBA(255, 255, 255, 0.07)
|
||||
}
|
||||
h := max(0.5, 1/s)
|
||||
line = line.Alpha(0.5 / h)
|
||||
y := box.Y + box.H
|
||||
if e.Bottom {
|
||||
y = box.Y - h
|
||||
}
|
||||
p.Fill(ui.Rect{X: box.X, Y: y, W: box.W, H: h}, line, 0)
|
||||
}
|
||||
|
||||
// String describes the scroll edge, as the inspector shows it.
|
||||
func (e ScrollEdge) String() string {
|
||||
s := "scroll-edge soft"
|
||||
if e.Hard {
|
||||
s = "scroll-edge hard"
|
||||
}
|
||||
if e.Bottom {
|
||||
s += " bottom"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// softEdge is the alpha of the background at a soft scroll edge's bar,
|
||||
// AppKit's; hardEdgeBlur is how much a hard edge blurs, in DIPs: AppKit's
|
||||
// Gaussian of radius 6 spreads an edge 30 pixels from 10% to 90% at a
|
||||
// scale of 2, as the renderers' does at 6.4.
|
||||
const (
|
||||
softEdge = 0.85
|
||||
hardEdgeBlur = 6.4
|
||||
)
|
||||
|
||||
// toned returns c saturated by saturation around its luminance, with
|
||||
// offset added, clamped, as AppKit's color matrices tone.
|
||||
func toned(c [3]float32, saturation, offset float32) [3]float32 {
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
for i := range c {
|
||||
c[i] = min(max(l+(c[i]-l)*saturation+offset, 0), 1)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// fillGradient fills box, rounded by radii, with g: as one rounded
|
||||
// rectangle when its corners are alike, else as a path.
|
||||
func fillGradient(p *ui.Painter, box ui.Rect, radii [4]float32, g ui.LinearGradient) {
|
||||
if radii[0] == radii[1] && radii[1] == radii[2] && radii[2] == radii[3] {
|
||||
p.FillGradient(box, g, radii[0])
|
||||
return
|
||||
}
|
||||
var path ui.Path
|
||||
x0, y0, x1, y1 := box.X, box.Y, box.X+box.W, box.Y+box.H
|
||||
// A cubic Bézier's control points for a quarter circle are k of the
|
||||
// radius from its ends.
|
||||
const k = 0.5523
|
||||
tl, tr, br, bl := radii[0], radii[1], radii[2], radii[3]
|
||||
path.MoveTo(x0+tl, y0).LineTo(x1-tr, y0)
|
||||
path.CubeTo(x1-tr+k*tr, y0, x1, y0+tr-k*tr, x1, y0+tr).LineTo(x1, y1-br)
|
||||
path.CubeTo(x1, y1-br+k*br, x1-br+k*br, y1, x1-br, y1).LineTo(x0+bl, y1)
|
||||
path.CubeTo(x0+bl-k*bl, y1, x0, y1-bl+k*bl, x0, y1-bl).LineTo(x0, y0+tl)
|
||||
path.CubeTo(x0, y0+tl-k*tl, x0+tl-k*tl, y0, x0+tl, y0).Close()
|
||||
p.FillPathGradient(&path, g)
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// edgeOver returns a tester of a window of black content 200 DIPs wide
|
||||
// and 100 high, with the scroll edge e over its top 40 DIPs, or its
|
||||
// bottom 40.
|
||||
func edgeOver(e ScrollEdge) *ui.Tester {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
b := ui.Box(c).Absolute().Left(0).Right(0).Height(40).Material(e)
|
||||
if e.Bottom {
|
||||
b.Bottom(0)
|
||||
} else {
|
||||
b.Top(0)
|
||||
}
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 100)
|
||||
tt.SetScale(2)
|
||||
return tt
|
||||
}
|
||||
|
||||
func TestSoftScrollEdge(t *testing.T) {
|
||||
// The background fades over the content from 85% at the top to
|
||||
// nothing at the edge's bottom, linearly.
|
||||
img := edgeOver(ScrollEdge{}).Image()
|
||||
for _, c := range []struct{ y, want int }{{0, 215}, {40, 108}, {79, 3}, {90, 0}} {
|
||||
if got := pixelAt(img, 100, c.y)[0]; got < c.want-3 || got > c.want+3 {
|
||||
t.Errorf("row %d is %d, not about %d", c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
// From the bottom, the other way.
|
||||
img = edgeOver(ScrollEdge{Bottom: true}).Image()
|
||||
if top, bottom := pixelAt(img, 100, 121)[0], pixelAt(img, 100, 199)[0]; top > 6 || bottom < 210 {
|
||||
t.Errorf("from the bottom, the edge goes from %d to %d", top, bottom)
|
||||
}
|
||||
// Its own background, dark.
|
||||
img = edgeOver(ScrollEdge{Background: ui.RGB(0, 0, 200)}).Image()
|
||||
if p := pixelAt(img, 100, 0); p[0] != 0 || p[2] < 165 || p[2] > 172 {
|
||||
t.Errorf("over a blue background, the top is %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHardScrollEdge(t *testing.T) {
|
||||
// Black content, toned to 0.03, under 82.45% of white: 212, evenly,
|
||||
// over a hairline of black at 10%.
|
||||
tt := edgeOver(ScrollEdge{Hard: true})
|
||||
img := tt.Image()
|
||||
for _, y := range []int{2, 40, 77} {
|
||||
if got := pixelAt(img, 100, y)[0]; got < 210 || got > 213 {
|
||||
t.Errorf("row %d is %d", y, got)
|
||||
}
|
||||
}
|
||||
if got := pixelAt(img, 100, 80)[0]; got != 0 {
|
||||
t.Errorf("the hairline over black is %d", got)
|
||||
}
|
||||
// Over white, the hairline shows: 90% of it.
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(0).Right(0).Top(0).Height(40).Material(ScrollEdge{Hard: true})
|
||||
})
|
||||
}
|
||||
wt := ui.NewTester(view, 200, 100)
|
||||
wt.SetScale(2)
|
||||
if got := pixelAt(wt.Image(), 100, 80)[0]; got < 228 || got > 231 {
|
||||
t.Errorf("the hairline over white is %d", got)
|
||||
}
|
||||
if got := pixelAt(wt.Image(), 100, 81)[0]; got != 255 {
|
||||
t.Errorf("below the hairline, white is %d", got)
|
||||
}
|
||||
// In dark mode, the hairline is white at 7%, over the theme's dark
|
||||
// background.
|
||||
wt.SetDark(true)
|
||||
if got := pixelAt(wt.Image(), 100, 80)[0]; got != 255 {
|
||||
t.Errorf("the dark hairline over white is %d", got)
|
||||
}
|
||||
if got := pixelAt(wt.Image(), 100, 40)[0]; got > 80 {
|
||||
t.Errorf("a dark hard edge over white is %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScrollEdgeString(t *testing.T) {
|
||||
if s := (ScrollEdge{}).String(); s != "scroll-edge soft" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
if s := (ScrollEdge{Hard: true, Bottom: true}).String(); s != "scroll-edge hard bottom" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// The shaders of the glass and of the blur, one for each renderer, which
|
||||
// go generate compiles ahead of time where it can (shaders_darwin.go,
|
||||
// shaders_windows.go).
|
||||
var (
|
||||
//go:embed glass.metal
|
||||
metalSource string
|
||||
//go:embed glass.hlsl
|
||||
hlslSource string
|
||||
//go:embed glass.glsl
|
||||
glslSource string
|
||||
//go:embed blur.metal
|
||||
blurMetalSource string
|
||||
//go:embed blur.hlsl
|
||||
blurHLSLSource string
|
||||
//go:embed blur.glsl
|
||||
blurGLSLSource string
|
||||
)
|
||||
|
||||
// Effect is the glass's effect, which the renderers draw (see
|
||||
// scene.Effect): what is behind the pane, blurred, sampled within the
|
||||
// bezel where the curved surface refracts it (lens), mapped from its
|
||||
// lightness (tone), tinted, and lit along the rim.
|
||||
var Effect = &scene.Effect{
|
||||
Name: "glass",
|
||||
Backdrop: true,
|
||||
Metal: scene.EffectCode{Source: metalSource, Compiled: metalLibrary, Sum: metalSum},
|
||||
HLSL: scene.EffectCode{Source: hlslSource, Compiled: hlslBytecode, Sum: hlslSum},
|
||||
GLSL: glslSource,
|
||||
Pixels: func() scene.EffectPixels { return &pixels{} },
|
||||
}
|
||||
|
||||
// blurEffect is a level of a blur (blurLevel), which the renderers draw:
|
||||
// what is behind it, blurred, by how much the level shows at each pixel,
|
||||
// along the mask.
|
||||
var blurEffect = &scene.Effect{
|
||||
Name: "blur",
|
||||
Backdrop: true,
|
||||
Metal: scene.EffectCode{Source: blurMetalSource, Compiled: blurMetalLibrary, Sum: blurMetalSum},
|
||||
HLSL: scene.EffectCode{Source: blurHLSLSource, Compiled: blurBytecode, Sum: blurHLSLSum},
|
||||
GLSL: blurGLSLSource,
|
||||
Pixels: func() scene.EffectPixels { return &blurPixels{} },
|
||||
}
|
||||
|
||||
// material is a pane of glass, in device pixels: the effect's parameters.
|
||||
//
|
||||
// - blur is the standard deviation of the blur of what shows through;
|
||||
// - bezel is how far from the edge the surface curves, and refraction
|
||||
// how far, at most, the bezel bends what shows through toward the
|
||||
// middle (lens), which mirrors what is just inside the bezel into it;
|
||||
// - low and high are the lightness that black and white, blurred, show
|
||||
// at, along a curve bent by curve (1 for a straight line), and
|
||||
// saturation multiplies how far colors are from their lightness;
|
||||
// - tint colors the glass, straight RGBA, by its alpha, and wideTint
|
||||
// is it in extended sRGB, for a target that keeps colors outside the
|
||||
// sRGB gamut (ui.Painter.EffectColor);
|
||||
// - rim is how much the rim is lit, within about rimWidth of the edge:
|
||||
// the more the edge faces the light coming from the angle light
|
||||
// (radians, clockwise from the right, the opposite side alike), the
|
||||
// lighter, and the less, the darker.
|
||||
type material struct {
|
||||
blur float32
|
||||
bezel, refraction float32
|
||||
low, high, curve, saturation float32
|
||||
tint, wideTint [4]float32
|
||||
rim, rimWidth, light float32
|
||||
}
|
||||
|
||||
// params returns the effect's parameters, as its shaders read them: p0
|
||||
// the bezel, the refraction, the rim and its width; p1 the tint; p2 the
|
||||
// low, high, curve and saturation; p3 the direction of the light; p4 the
|
||||
// wide tint, which only the Metal shader reads.
|
||||
func (m *material) params() [5][4]float32 {
|
||||
return [5][4]float32{
|
||||
{m.bezel, m.refraction, m.rim, m.rimWidth},
|
||||
m.tint,
|
||||
{m.low, m.high, m.curve, m.saturation},
|
||||
{float32(math.Cos(float64(m.light))), float32(math.Sin(float64(m.light)))},
|
||||
m.wideTint,
|
||||
}
|
||||
}
|
||||
|
||||
// lens returns how far, as a fraction of the refraction, the glass bends
|
||||
// what shows through it t pixels inside its edge, within a bezel of width
|
||||
// bezel: the surface's height there is Apple's squircle profile,
|
||||
// ⁴√(1-(1-x)⁴) for x = t/bezel, and light coming straight down bends as it
|
||||
// enters glass of refractive index 1.5 (Snell's law), by the tangent of
|
||||
// the angle it turns, which is √5/2 at most, where the surface is upright.
|
||||
func lens(t, bezel float32) float32 {
|
||||
if bezel <= 0 || t >= bezel {
|
||||
return 0
|
||||
}
|
||||
u := 1 - max(t, 0)/bezel
|
||||
v := 1 - u*u*u*u
|
||||
// The surface's slope is b/a: the sine and cosine of its angle are
|
||||
// b and a over their hypotenuse.
|
||||
a := sqrt(v * sqrt(v))
|
||||
b := u * u * u
|
||||
n := sqrt(a*a + b*b)
|
||||
s, c := b/n, a/n
|
||||
st := s / 1.5
|
||||
ct := sqrt(1 - st*st)
|
||||
return (s*ct - c*st) / (c*ct + s*st) / 1.1180340
|
||||
}
|
||||
|
||||
// normal returns the direction away from the middle of a rounded rectangle
|
||||
// at p, the direction of its edge's normal there, smoothed: as of the
|
||||
// rectangle with corners half again as round, so that it turns gradually
|
||||
// around a corner. It is 0 on the lines through the middle, where two
|
||||
// sides are as near.
|
||||
func normal(px, py float32, r scene.Rect, radii [4]float32) (gx, gy float32) {
|
||||
hx, hy := r.W/2, r.H/2
|
||||
cx, cy := px-r.X-hx, py-r.Y-hy
|
||||
var rad float32
|
||||
switch {
|
||||
case cx < 0 && cy < 0:
|
||||
rad = radii[0]
|
||||
case cx >= 0 && cy < 0:
|
||||
rad = radii[1]
|
||||
case cx >= 0:
|
||||
rad = radii[2]
|
||||
default:
|
||||
rad = radii[3]
|
||||
}
|
||||
rad = min(rad*1.5, hx, hy)
|
||||
qx, qy := abs(cx)-(hx-rad), abs(cy)-(hy-rad)
|
||||
if qx > 0 || qy > 0 {
|
||||
mx, my := max(qx, 0), max(qy, 0)
|
||||
n := sqrt(mx*mx + my*my)
|
||||
return sign(cx) * mx / n, sign(cy) * my / n
|
||||
}
|
||||
if qx > qy {
|
||||
return sign(cx), 0
|
||||
}
|
||||
return 0, sign(cy)
|
||||
}
|
||||
|
||||
// tone maps the premultiplied color c behind the glass to the glass's own,
|
||||
// by its lightness, the luminance of its sRGB components, along the
|
||||
// material's curve, and keeping its colors' distance from it.
|
||||
func tone(c [3]float32, m *material) [3]float32 {
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
return toneAt(c, l, m.low+(m.high-m.low)*(1-pow(max(1-l, 0), m.curve)), m)
|
||||
}
|
||||
|
||||
func toneAt(c [3]float32, l, t float32, m *material) [3]float32 {
|
||||
k := (m.high - m.low) * m.saturation
|
||||
for i := range c {
|
||||
c[i] = min(max(t+(c[i]-l)*k, 0), 1)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func sqrt(v float32) float32 { return float32(math.Sqrt(float64(v))) }
|
||||
func pow(x, y float32) float32 { return float32(math.Pow(float64(x), float64(y))) }
|
||||
|
||||
func abs(v float32) float32 {
|
||||
if v < 0 {
|
||||
return -v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func sign(v float32) float32 {
|
||||
switch {
|
||||
case v > 0:
|
||||
return 1
|
||||
case v < 0:
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// The glass's effect in GLSL (see scene.Effect), as glass.metal is in
|
||||
// Metal Shading Language and pixels.go draws it on the CPU.
|
||||
|
||||
float glassLens(float t, float bezel) {
|
||||
if (bezel <= 0.0 || t >= bezel) {
|
||||
return 0.0;
|
||||
}
|
||||
float u = 1.0 - max(t, 0.0) / bezel;
|
||||
float v = 1.0 - u * u * u * u;
|
||||
float a = sqrt(v * sqrt(v));
|
||||
float b = u * u * u;
|
||||
float n = sqrt(a * a + b * b);
|
||||
float s = b / n;
|
||||
float c = a / n;
|
||||
float st = s / 1.5;
|
||||
float ct = sqrt(1.0 - st * st);
|
||||
return (s * ct - c * st) / (c * ct + s * st) / 1.1180340;
|
||||
}
|
||||
|
||||
vec2 glassNormal(vec2 p, vec4 rect, vec4 radii) {
|
||||
vec2 h = rect.zw * 0.5;
|
||||
vec2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0 ? (q.y < 0.0 ? radii.x : radii.w) : (q.y < 0.0 ? radii.y : radii.z);
|
||||
r = min(r * 1.5, min(h.x, h.y));
|
||||
vec2 a = abs(q) - (h - r);
|
||||
if (a.x > 0.0 || a.y > 0.0) {
|
||||
vec2 m = max(a, vec2(0.0));
|
||||
return sign(q) * m / sqrt(m.x * m.x + m.y * m.y);
|
||||
}
|
||||
return a.x > a.y ? vec2(sign(q.x), 0.0) : vec2(0.0, sign(q.y));
|
||||
}
|
||||
|
||||
vec3 glassTone(vec3 c, vec4 tone) {
|
||||
float l = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
float t = tone.x + (tone.y - tone.x) * (1.0 - pow(max(1.0 - l, 0.0), tone.z));
|
||||
float k = (tone.y - tone.x) * tone.w;
|
||||
return clamp(t + (c - l) * k, 0.0, 1.0);
|
||||
}
|
||||
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
float t = max(-sdRoundRect(p, e.rect, e.radii), 0.0);
|
||||
float bezel = e.p0.x;
|
||||
float rimWidth = e.p0.w;
|
||||
vec2 n = vec2(0.0);
|
||||
if (t < bezel || t < 3.0 * rimWidth) {
|
||||
n = glassNormal(p, e.rect, e.radii);
|
||||
}
|
||||
vec2 q = p;
|
||||
if (t < bezel) {
|
||||
q -= n * (e.p0.y * glassLens(t, bezel));
|
||||
}
|
||||
vec3 c = glassTone(sampleBackdrop(e, q), e.p2);
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
if (e.p0.z > 0.0 && t < 3.0 * rimWidth) {
|
||||
float r = t / rimWidth;
|
||||
float a = e.p0.z * exp(-r * r);
|
||||
float l = abs(n.x * e.p3.x + n.y * e.p3.y);
|
||||
c += (l - c) * a;
|
||||
}
|
||||
return vec4(c, 1.0);
|
||||
}
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
// Package glass draws Liquid Glass in native UI, as macOS 26 and later
|
||||
// draw it (AppKit's NSGlassEffectView), on every platform: what the
|
||||
// elements under it painted shows through, blurred, bent near its edges as
|
||||
// through the rim of a lens, and lit along its hairline rim.
|
||||
// MyGo's renderers draw it with shaders of this package, on the GPU or the
|
||||
// CPU, so it looks the same everywhere.
|
||||
//
|
||||
// ui.Row(c).Padding(8, 16).Radius(22).Material(glass.Glass{})
|
||||
//
|
||||
// ScrollEdge is macOS's scroll edge effect, which content scrolling under
|
||||
// a bar fades or frosts under, and Blur blurs what is under an element
|
||||
// without the glass, evenly or fading along a gradient.
|
||||
package glass
|
||||
|
||||
//go:generate go run ./internal/gen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Glass is Liquid Glass, a ui.Material: Element.Material fills an element
|
||||
// with it, in place of a background, shaped by its Radius. What was
|
||||
// painted under the element shows through it, as content that scrolls
|
||||
// under a bar placed over it with Absolute, and other glass.
|
||||
type Glass struct {
|
||||
// Style is the glass's material.
|
||||
Style Style
|
||||
// Tint colors the glass, by its alpha, as for a prominent button: an
|
||||
// opaque tint lets a little of the glass show, as AppKit's does.
|
||||
Tint ui.Color
|
||||
// Interactive makes the glass grow a little while the element is
|
||||
// pressed, as AppKit's interactive glass does.
|
||||
Interactive bool
|
||||
// Native asks for the system's glass where the window has it (macOS
|
||||
// 26 and later), drawn under the content: it samples what is under the
|
||||
// window's surface, as a ui.WebView's page, not the elements the frame
|
||||
// painted. Elsewhere, and with Reduce Transparency, the shader draws
|
||||
// it.
|
||||
Native bool
|
||||
// Clarity, from 0 to 1, makes panes as large as sidebars clearer,
|
||||
// the content under them reading through: 0, the default, is
|
||||
// macOS's material, as frosty as a control's; 0.5 blurs half as much
|
||||
// and lightens (or darkens) less; 1 is nearly clear. Panes up to 100
|
||||
// DIPs keep their material whatever it is; it takes full effect from
|
||||
// 200. On Clear glass, which barely tones already, it only lights the
|
||||
// rim and curves the bezel.
|
||||
Clarity float32
|
||||
// hover follows the pointer over an interactive glass, from 0 to 1.
|
||||
hover float32
|
||||
}
|
||||
|
||||
// pressKey is the key of an interactive glass's animation.
|
||||
type pressKey struct{}
|
||||
|
||||
// hoverKey is the key of an interactive glass's hover animation.
|
||||
type hoverKey struct{}
|
||||
|
||||
// pressed is an interactive glass as its element is built: how far it
|
||||
// has grown, from 0 to 1, and how far the pointer hovers it.
|
||||
type pressed struct {
|
||||
Glass
|
||||
grow, hover float32
|
||||
}
|
||||
|
||||
// BuildMaterial follows the press and hover of an interactive glass's
|
||||
// element: the glass grows as it is pressed, and lights its rim as the
|
||||
// pointer enters it, within 150 ms, as AppKit's does.
|
||||
func (g Glass) BuildMaterial(e ui.Element) ui.Material {
|
||||
if !g.Interactive {
|
||||
return g
|
||||
}
|
||||
target := float32(0)
|
||||
if e.Pressed() {
|
||||
target = 1
|
||||
}
|
||||
hover := float32(0)
|
||||
if e.Hovered() {
|
||||
hover = 1
|
||||
}
|
||||
return pressed{g, e.Animate(pressKey{}, target, 150*time.Millisecond),
|
||||
e.Animate(hoverKey{}, hover, 120*time.Millisecond)}
|
||||
}
|
||||
|
||||
// Style is the material of Glass.
|
||||
type Style uint8
|
||||
|
||||
const (
|
||||
// Regular frosts what shows through and lightens it, or darkens it in
|
||||
// dark mode, so that what is on the glass reads over anything: for
|
||||
// bars, buttons and panels. Larger panes are frostier.
|
||||
Regular Style = iota
|
||||
// Clear barely blurs nor tones what shows through, for glass over
|
||||
// photos and video, where what is on it brings its own contrast.
|
||||
Clear
|
||||
)
|
||||
|
||||
// NativeGlass asks for the system's glass, which ui places under the
|
||||
// surface, where it has Liquid Glass.
|
||||
func (g Glass) NativeGlass() (ui.NativeGlassSpec, bool) {
|
||||
if !g.Native {
|
||||
return ui.NativeGlassSpec{}, false
|
||||
}
|
||||
style := 0
|
||||
if g.Style == Clear {
|
||||
style = 1
|
||||
}
|
||||
return ui.NativeGlassSpec{Style: style, Tint: g.Tint}, true
|
||||
}
|
||||
|
||||
// PaintMaterial paints the glass over box, rounded by radii.
|
||||
func (g Glass) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
if g.Native && p.NativeGlassSupported() && !p.Preferences().ReduceTransparency {
|
||||
// The system's glass, under the surface, shows through this hole.
|
||||
p.Hole(box, radii)
|
||||
return
|
||||
}
|
||||
paint(p, box, radii, g)
|
||||
}
|
||||
|
||||
// PaintMaterial paints the glass grown by how far it is pressed: as
|
||||
// macOS 27's, measured from NSGlassEffectView, by about 1.1 DIPs left and
|
||||
// right and 0.45 DIPs above and below, whatever its size. AppKit stretches
|
||||
// the content too, a pixel or so, which the children here are not.
|
||||
func (pressed) NativeGlass() (ui.NativeGlassSpec, bool) {
|
||||
return ui.NativeGlassSpec{}, false
|
||||
}
|
||||
|
||||
func (g pressed) PaintMaterial(p *ui.Painter, box ui.Rect, radii [4]float32) {
|
||||
dx, dy := 1.1*g.grow, 0.45*g.grow
|
||||
box = ui.Rect{X: box.X - dx, Y: box.Y - dy, W: box.W + 2*dx, H: box.H + 2*dy}
|
||||
for i := range radii {
|
||||
if radii[i] > 0 {
|
||||
radii[i] += dy
|
||||
}
|
||||
}
|
||||
g.Glass.hover = g.hover
|
||||
paint(p, box, radii, g.Glass)
|
||||
}
|
||||
|
||||
// String describes the glass, as the inspector shows it.
|
||||
func (g Glass) String() string {
|
||||
s := "glass"
|
||||
if g.Style == Clear {
|
||||
s += " clear"
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
s += fmt.Sprintf(" tint(#%02x%02x%02x%02x)", g.Tint.R, g.Tint.G, g.Tint.B, g.Tint.A)
|
||||
}
|
||||
if g.Native {
|
||||
s += " native"
|
||||
}
|
||||
if g.Interactive {
|
||||
s += " interactive"
|
||||
}
|
||||
if g.Clarity > 0 {
|
||||
s += fmt.Sprintf(" clarity(%g)", g.Clarity)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Paint paints a pane of glass shaped as r rounded by radius, in a
|
||||
// drawing (Element.Draw), over what the painter painted before it.
|
||||
func Paint(p *ui.Painter, r ui.Rect, radius float32, g Glass) {
|
||||
paint(p, r, [4]float32{radius, radius, radius, radius}, g)
|
||||
}
|
||||
|
||||
// paint paints a pane of glass over box, rounded by radii.
|
||||
//
|
||||
// Its material follows macOS 27's, measured from NSGlassEffectView: the
|
||||
// regular one maps black to 54% and white to 100% in light mode, and to
|
||||
// 15% and 51% in dark mode, the clear one adds an eighth; larger panes
|
||||
// blur more, up to 10 DIPs; the bezel curves the last 36 DIPs of the
|
||||
// pane, at most half of it, and bends what shows through by up to 1.6
|
||||
// times that, mirroring what is inside it, as AppKit's do; light comes
|
||||
// from above and below, along a rim a pixel wide, and the pane casts no
|
||||
// shadow, as NSGlassEffectView's and the glass bezel's do not. Panes
|
||||
// large as sidebars and inspectors are clearer by the glass's Clarity
|
||||
// (paneMaterial).
|
||||
func paint(p *ui.Painter, box ui.Rect, radii [4]float32, g Glass) {
|
||||
if box.W <= 0 || box.H <= 0 {
|
||||
return
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
paintOpaque(p, box, radii, g)
|
||||
return
|
||||
}
|
||||
mat := paneMaterial(min(box.W, box.H), p.Scale(), g.Clarity, g.Style == Clear, p.Theme().Dark)
|
||||
if p.Preferences().HighContrast {
|
||||
mat.rim = min(mat.rim+0.15, 1)
|
||||
mat.rimWidth = max(mat.rimWidth, 1.5)
|
||||
}
|
||||
if g.hover > 0 {
|
||||
// As the pointer enters an interactive glass, its rim lights and
|
||||
// its surface lifts a little.
|
||||
mat.rim = min(mat.rim+0.18*g.hover, 1)
|
||||
mat.low = min(mat.low+0.02*g.hover, 1)
|
||||
mat.high = min(mat.high+0.02*g.hover, 1)
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
mat.tint, mat.wideTint = p.EffectColor(g.Tint)
|
||||
a := 0.88 * (1 + 0.1*g.hover)
|
||||
mat.tint[3] = min(mat.tint[3]*a, 1)
|
||||
mat.wideTint[3] = min(mat.wideTint[3]*a, 1)
|
||||
}
|
||||
p.Effect(Effect, box, radii, mat.blur, mat.params())
|
||||
}
|
||||
|
||||
// paintOpaque paints g as the opaque surface that the desktop asks for
|
||||
// with Reduce Transparency: the theme's surface, or its background for
|
||||
// clear glass, tinted as g is, without blur, refraction or a rim.
|
||||
func paintOpaque(p *ui.Painter, box ui.Rect, radii [4]float32, g Glass) {
|
||||
t := p.Theme()
|
||||
c := t.Surface
|
||||
if g.Style == Clear {
|
||||
c = t.Background
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
c = c.Mix(g.Tint, float32(g.Tint.A)/255*0.88)
|
||||
}
|
||||
p.FillRadii(box, radii, c)
|
||||
if p.Preferences().HighContrast {
|
||||
p.Stroke(box, t.Border, max(radii[0], radii[1], radii[2], radii[3]), 1)
|
||||
}
|
||||
}
|
||||
|
||||
// paneMaterial is the material of a pane whose shorter side is m DIPs,
|
||||
// at scale s, of clarity k from 0 to 1, clear or regular, in dark mode or
|
||||
// light. Panes up to 100 DIPs, as controls, keep the measured material;
|
||||
// from 200, as sidebars and inspectors, theirs is clarity's; between, it
|
||||
// eases from one to the other. Clarity goes in two straight steps, each
|
||||
// half of it, from the measured material (frost) to a clearer one (mid),
|
||||
// the content under the pane reading through, and on to one nearly clear
|
||||
// (clear): see paneTone.
|
||||
func paneMaterial(m, s, k float32, clear, dark bool) material {
|
||||
f := min(max((m-100)/100, 0), 1)
|
||||
f = f * f * (3 - 2*f) // smoothstep
|
||||
k = min(max(k, 0), 1)
|
||||
if k != k { // NaN
|
||||
k = 0
|
||||
}
|
||||
at := func(v paneTone) float32 { return v.frost + (v.at(k)-v.frost)*f }
|
||||
bezel := min(at(paneBezel), m/2)
|
||||
mat := material{
|
||||
bezel: bezel * s,
|
||||
refraction: 1.6 * bezel * s,
|
||||
rim: at(paneRim),
|
||||
rimWidth: 1,
|
||||
light: math.Pi / 2,
|
||||
}
|
||||
switch {
|
||||
case clear:
|
||||
mat.blur = s
|
||||
mat.low, mat.high, mat.curve, mat.saturation = 0.125, 1.082, 1, 1
|
||||
case dark:
|
||||
mat.blur = min(max(m*0.035, 1), at(paneBlur)) * s
|
||||
mat.low, mat.high, mat.curve, mat.saturation = at(paneDarkLow), at(paneDarkHigh), 2, 2.2
|
||||
default:
|
||||
mat.blur = min(max(m*0.035, 1), at(paneBlur)) * s
|
||||
mat.low, mat.high, mat.curve, mat.saturation = at(paneLightLow), 1, 1.2, 1
|
||||
}
|
||||
return mat
|
||||
}
|
||||
|
||||
// paneTone is a parameter of a large pane's material at clarity 0
|
||||
// (frost, the measured material's), 0.5 (mid) and 1 (clear).
|
||||
type paneTone struct{ frost, mid, clear float32 }
|
||||
|
||||
// at is the parameter at clarity k, from 0 to 1.
|
||||
func (v paneTone) at(k float32) float32 {
|
||||
if k <= 0.5 {
|
||||
return v.frost + (v.mid-v.frost)*k*2
|
||||
}
|
||||
return v.mid + (v.clear-v.mid)*(k-0.5)*2
|
||||
}
|
||||
|
||||
var (
|
||||
// paneBlur is the most the pane blurs, in DIPs.
|
||||
paneBlur = paneTone{10, 5, 2}
|
||||
// paneLightLow is what black maps to in light mode, white to 1.
|
||||
paneLightLow = paneTone{0.541, 0.35, 0.2}
|
||||
// paneDarkLow and paneDarkHigh are what black and white map to in
|
||||
// dark mode.
|
||||
paneDarkLow = paneTone{0.15, 0.15, 0.1}
|
||||
paneDarkHigh = paneTone{0.51, 0.6, 0.85}
|
||||
// paneRim is how bright the rim is lit.
|
||||
paneRim = paneTone{0.35, 0.5, 0.5}
|
||||
// paneBezel is how wide the bezel curves, in DIPs.
|
||||
paneBezel = paneTone{36, 48, 48}
|
||||
)
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// The glass's effect in HLSL (see scene.Effect), as glass.metal is in
|
||||
// Metal Shading Language and pixels.go draws it on the CPU.
|
||||
|
||||
float glassLens(float t, float bezel) {
|
||||
if (bezel <= 0 || t >= bezel) {
|
||||
return 0;
|
||||
}
|
||||
float u = 1 - max(t, 0) / bezel;
|
||||
float v = 1 - u * u * u * u;
|
||||
float a = sqrt(v * sqrt(v));
|
||||
float b = u * u * u;
|
||||
float n = sqrt(a * a + b * b);
|
||||
float s = b / n;
|
||||
float c = a / n;
|
||||
float st = s / 1.5;
|
||||
float ct = sqrt(1 - st * st);
|
||||
return (s * ct - c * st) / (c * ct + s * st) / 1.1180340;
|
||||
}
|
||||
|
||||
float2 glassNormal(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0 ? (q.y < 0 ? radii.x : radii.w) : (q.y < 0 ? radii.y : radii.z);
|
||||
r = min(r * 1.5, min(h.x, h.y));
|
||||
float2 a = abs(q) - (h - r);
|
||||
float2 sq = float2(sign(q));
|
||||
if (a.x > 0 || a.y > 0) {
|
||||
float2 m = max(a, 0);
|
||||
return sq * m / sqrt(m.x * m.x + m.y * m.y);
|
||||
}
|
||||
return a.x > a.y ? float2(sq.x, 0) : float2(0, sq.y);
|
||||
}
|
||||
|
||||
float3 glassTone(float3 c, float4 tone) {
|
||||
float l = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
float t = tone.x + (tone.y - tone.x) * (1 - pow(max(1 - l, 0), tone.z));
|
||||
float k = (tone.y - tone.x) * tone.w;
|
||||
return saturate(t + (c - l) * k);
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e) {
|
||||
float t = max(-sdRoundRect(p, e.rect, e.radii), 0);
|
||||
float bezel = e.p0.x;
|
||||
float rimWidth = e.p0.w;
|
||||
float2 n = float2(0, 0);
|
||||
if (t < bezel || t < 3 * rimWidth) {
|
||||
n = glassNormal(p, e.rect, e.radii);
|
||||
}
|
||||
float2 q = p;
|
||||
if (t < bezel) {
|
||||
q -= n * (e.p0.y * glassLens(t, bezel));
|
||||
}
|
||||
float3 c = glassTone(sampleBackdrop(e, q), e.p2);
|
||||
c += (e.p1.rgb - c) * e.p1.a;
|
||||
if (e.p0.z > 0 && t < 3 * rimWidth) {
|
||||
float r = t / rimWidth;
|
||||
float a = e.p0.z * exp(-r * r);
|
||||
float l = abs(n.x * e.p3.x + n.y * e.p3.y);
|
||||
c += (l - c) * a;
|
||||
}
|
||||
return float4(c, 1);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// The glass's effect in Metal Shading Language (see scene.Effect), as
|
||||
// pixels.go draws it on the CPU. The parameters are those of material:
|
||||
// p0 the bezel, the refraction, the rim and its width; p1 the tint; p2 the
|
||||
// low, high, curve and saturation; p3 the light's direction; p4 the tint in
|
||||
// extended sRGB, for a target that keeps colors outside the sRGB gamut.
|
||||
|
||||
// glassLens returns how far, as a fraction of the refraction, the glass
|
||||
// bends what shows through it t pixels inside its edge (lens).
|
||||
float glassLens(float t, float bezel) {
|
||||
if (bezel <= 0.0f || t >= bezel) {
|
||||
return 0.0f;
|
||||
}
|
||||
float u = 1.0f - max(t, 0.0f) / bezel;
|
||||
float v = 1.0f - u * u * u * u;
|
||||
float a = sqrt(v * sqrt(v));
|
||||
float b = u * u * u;
|
||||
float n = sqrt(a * a + b * b);
|
||||
float s = b / n;
|
||||
float c = a / n;
|
||||
float st = s / 1.5f;
|
||||
float ct = sqrt(1.0f - st * st);
|
||||
return (s * ct - c * st) / (c * ct + s * st) / 1.1180340f;
|
||||
}
|
||||
|
||||
// glassNormal returns the direction of the edge's normal at p, smoothed
|
||||
// (normal).
|
||||
float2 glassNormal(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5f;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0f ? (q.y < 0.0f ? radii.x : radii.w) : (q.y < 0.0f ? radii.y : radii.z);
|
||||
r = min(r * 1.5f, min(h.x, h.y));
|
||||
float2 a = abs(q) - (h - r);
|
||||
if (a.x > 0.0f || a.y > 0.0f) {
|
||||
float2 m = max(a, float2(0.0f));
|
||||
return sign(q) * m / sqrt(m.x * m.x + m.y * m.y);
|
||||
}
|
||||
return a.x > a.y ? float2(sign(q.x), 0.0f) : float2(0.0f, sign(q.y));
|
||||
}
|
||||
|
||||
// glassTone maps the color behind the glass to the glass's (tone).
|
||||
float3 glassTone(float3 c, float4 tone) {
|
||||
float l = 0.2126f * c.r + 0.7152f * c.g + 0.0722f * c.b;
|
||||
float t = tone.x + (tone.y - tone.x) * (1.0f - pow(max(1.0f - l, 0.0f), tone.z));
|
||||
float k = (tone.y - tone.x) * tone.w;
|
||||
return clamp(t + (c - l) * k, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
float t = max(-sdRoundRect(p, e.rect, e.radii), 0.0f);
|
||||
float bezel = e.p0.x;
|
||||
float rimWidth = e.p0.w;
|
||||
float2 n = float2(0.0f);
|
||||
if (t < bezel || t < 3.0f * rimWidth) {
|
||||
n = glassNormal(p, e.rect, e.radii);
|
||||
}
|
||||
float2 q = p;
|
||||
if (t < bezel) {
|
||||
q -= n * (e.p0.y * glassLens(t, bezel));
|
||||
}
|
||||
float3 c = glassTone(sampleBackdrop(backdrop, e, q), e.p2);
|
||||
float4 tint = e.wide ? e.p4 : e.p1;
|
||||
c += (tint.rgb - c) * tint.a;
|
||||
if (e.p0.z > 0.0f && t < 3.0f * rimWidth) {
|
||||
float r = t / rimWidth;
|
||||
float a = e.p0.z * exp(-r * r);
|
||||
float l = abs(n.x * e.p3.x + n.y * e.p3.y);
|
||||
c += (l - c) * a;
|
||||
}
|
||||
return float4(c, 1.0f);
|
||||
}
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"image"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// pixelAt returns the color of img at (x, y).
|
||||
func pixelAt(img *image.RGBA, x, y int) [3]int {
|
||||
p := img.RGBAAt(x, y)
|
||||
return [3]int{int(p.R), int(p.G), int(p.B)}
|
||||
}
|
||||
|
||||
func TestGlassPaintsOverWhatIsBehind(t *testing.T) {
|
||||
g := Glass{}
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(20, 120, 220)).Children(func() {
|
||||
ui.Row(c).Size(200, 44).Radius(22).Material(g).Children(func() {
|
||||
ui.Text(c, "On glass")
|
||||
})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 300, 100)
|
||||
tt.SetScale(2)
|
||||
if !tt.HasText("On glass") {
|
||||
t.Error("the glass's children did not paint")
|
||||
}
|
||||
// The glass lightens the blue behind it, which shows through.
|
||||
light := pixelAt(tt.Image(), 300, 70)
|
||||
if light[0] < 100 || light[2] < light[0] {
|
||||
t.Errorf("light glass over blue is %v", light)
|
||||
}
|
||||
tt.SetDark(true)
|
||||
if dark := pixelAt(tt.Image(), 300, 70); dark[2] >= light[2] || dark[0] >= light[0] {
|
||||
t.Errorf("dark glass over blue is %v, not darker than light glass's %v", dark, light)
|
||||
}
|
||||
tt.SetDark(false)
|
||||
g.Style = Clear
|
||||
tt.Frame()
|
||||
if clear := pixelAt(tt.Image(), 300, 70); clear[0] >= light[0] {
|
||||
t.Errorf("clear glass over blue is %v, not clearer than regular glass's %v", clear, light)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveGlassGrowsWhilePressed(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(50).Top(50).Size(200, 100).Radius(20).Material(Glass{Interactive: true})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 300, 200)
|
||||
tt.SetScale(2)
|
||||
// It grows at once.
|
||||
tt.SetPreferences(ui.Preferences{ReduceMotion: true})
|
||||
// The pixel left of the glass's left edge, in the middle.
|
||||
outside := func() int { return pixelAt(tt.Image(), 99, 200)[0] }
|
||||
before := outside()
|
||||
tt.Press(150, 100)
|
||||
tt.Frame()
|
||||
if grown := outside(); grown <= before+50 {
|
||||
t.Errorf("pressed, the pixel left of the glass is %d, as before (%d)", grown, before)
|
||||
}
|
||||
tt.Release(150, 100)
|
||||
tt.Frame()
|
||||
if after := outside(); after != before {
|
||||
t.Errorf("after the release, the pixel left of the glass is %d, not %d", after, before)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInteractiveGlassLightsOnHover(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(40).Top(30).Size(240, 100).Radius(20).Material(Glass{Interactive: true})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 160)
|
||||
tt.SetScale(2)
|
||||
tt.SetPreferences(ui.Preferences{ReduceMotion: true})
|
||||
tt.Frame()
|
||||
rim := func() int { return pixelAt(tt.Image(), 320, 62)[0] }
|
||||
before := rim()
|
||||
// The pointer enters the glass: its top rim lights.
|
||||
tt.Move(160, 80)
|
||||
tt.Frame()
|
||||
if hovered := rim(); hovered <= before {
|
||||
t.Errorf("the rim is %v while hovered, not lighter than %v", hovered, before)
|
||||
}
|
||||
// Leaving it restores the rim.
|
||||
tt.Move(10, 10)
|
||||
tt.Frame()
|
||||
if after := rim(); after != before {
|
||||
t.Errorf("the rim is %v after the pointer left, not %v", after, before)
|
||||
}
|
||||
}
|
||||
|
||||
// Panes close together merge into one surface; far apart, they do not.
|
||||
func TestGroupMergesNearPanes(t *testing.T) {
|
||||
gap := float32(8)
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
g := NewGroup(c)
|
||||
g.Radius = 22
|
||||
g.Gap(gap).Children(func() {
|
||||
g.Pane(ui.Box(c).Size(80, 44))
|
||||
g.Pane(ui.Box(c).Size(80, 44))
|
||||
})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 100)
|
||||
tt.SetScale(2)
|
||||
// The first pane ends at 80, the second starts at 88: their gap's
|
||||
// middle is 84, which the glass bridges.
|
||||
if p := pixelAt(tt.Image(), 168, 44); p[0] < 30 {
|
||||
t.Errorf("the gap between close panes is %v, not glass", p)
|
||||
}
|
||||
// Far apart, nothing bridges the gap.
|
||||
gap = 40
|
||||
tt.Frame()
|
||||
if p := pixelAt(tt.Image(), 200, 44); p[0] > 10 {
|
||||
t.Errorf("the gap between far panes is %v, not the background", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaintInDrawing(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
Paint(p, ui.Rect{X: 20, Y: 20, W: 100, H: 60}, 20, Glass{})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 120)
|
||||
// Light glass over black is mid gray.
|
||||
if g := pixelAt(tt.Image(), 70, 50); g[0] < 100 || g[0] > 180 {
|
||||
t.Errorf("light glass over black is %v", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestString(t *testing.T) {
|
||||
if s := (Glass{Style: Clear, Tint: ui.RGB(1, 2, 3), Interactive: true}).String(); s != "glass clear tint(#010203ff) interactive" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// With Reduce Transparency, a glass pane, a blur and a scroll edge are
|
||||
// opaque: the theme's surfaces, not what is behind them.
|
||||
func TestReduceTransparency(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(20, 120, 220)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(50).Top(20).Size(200, 60).Radius(12).Material(Glass{})
|
||||
ui.Box(c).Absolute().Left(50).Top(100).Size(200, 40).Radius(8).Material(ScrollEdge{Hard: true})
|
||||
ui.Box(c).Absolute().Left(50).Top(160).Size(200, 40).Radius(8).Material(Blur{Radius: 8})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 220)
|
||||
tt.SetScale(2)
|
||||
glassAt := func() [3]int { return pixelAt(tt.Image(), 300, 100) }
|
||||
before := glassAt()
|
||||
if before[0] > 200 && before[1] > 200 {
|
||||
t.Fatalf("glass before Reduce Transparency is already the surface: %v", before)
|
||||
}
|
||||
tt.SetPreferences(ui.Preferences{ReduceTransparency: true})
|
||||
tt.Frame()
|
||||
theme := ui.LightTheme()
|
||||
surface := [3]int{int(theme.Surface.R), int(theme.Surface.G), int(theme.Surface.B)}
|
||||
background := [3]int{int(theme.Background.R), int(theme.Background.G), int(theme.Background.B)}
|
||||
near := func(got, want [3]int) bool {
|
||||
for i := range got {
|
||||
if got[i] < want[i]-2 || got[i] > want[i]+2 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if got := glassAt(); !near(got, surface) {
|
||||
t.Errorf("glass is %v, not the opaque surface %v", got, surface)
|
||||
}
|
||||
if got := pixelAt(tt.Image(), 300, 240); !near(got, background) {
|
||||
t.Errorf("scroll edge is %v, not the background %v", got, background)
|
||||
}
|
||||
if got := pixelAt(tt.Image(), 300, 360); !near(got, background) {
|
||||
t.Errorf("blur is %v, not the background %v", got, background)
|
||||
}
|
||||
// The desktop's setting back off restores the backdrop.
|
||||
tt.SetPreferences(ui.Preferences{})
|
||||
tt.Frame()
|
||||
if after := glassAt(); near(after, surface) {
|
||||
t.Errorf("glass stayed opaque after Reduce Transparency: %v", after)
|
||||
}
|
||||
}
|
||||
|
||||
// High Contrast lights the glass's rim more.
|
||||
func TestHighContrastGlass(t *testing.T) {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Children(func() {
|
||||
ui.Box(c).Absolute().Left(40).Top(30).Size(240, 100).Radius(20).Material(Glass{})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 320, 160)
|
||||
tt.SetScale(2)
|
||||
tt.Frame()
|
||||
normal := pixelAt(tt.Image(), 320, 62)
|
||||
tt.SetPreferences(ui.Preferences{HighContrast: true})
|
||||
tt.Frame()
|
||||
contrast := pixelAt(tt.Image(), 320, 62)
|
||||
if contrast[0] <= normal[0] {
|
||||
t.Errorf("the rim is %v with high contrast, not lighter than %v", contrast, normal)
|
||||
}
|
||||
}
|
||||
|
||||
// Panes up to 100 DIPs, as controls, keep the measured material,
|
||||
// whatever the clarity; from 200, as sidebars, theirs is the clarity's;
|
||||
// between, it eases from one to the other.
|
||||
func TestPaneMaterial(t *testing.T) {
|
||||
near := func(a, b float32) bool { return a-b < 1e-5 && b-a < 1e-5 }
|
||||
for _, k := range []float32{0, 0.25, 0.5, 1} {
|
||||
for _, m := range []float32{20, 44, 72, 100} {
|
||||
for _, s := range []float32{1, 2} {
|
||||
bezel := min(36, m/2)
|
||||
blur := min(max(m*0.035, 1), 10) * s
|
||||
light := paneMaterial(m, s, k, false, false)
|
||||
if light.blur != blur || light.bezel != bezel*s || light.refraction != 1.6*bezel*s || light.rim != 0.35 ||
|
||||
light.low != 0.541 || light.high != 1 {
|
||||
t.Errorf("light %v DIPs at %vx, clarity %v: %+v", m, s, k, light)
|
||||
}
|
||||
dark := paneMaterial(m, s, k, false, true)
|
||||
if dark.blur != blur || dark.rim != 0.35 || dark.low != 0.15 || dark.high != 0.51 {
|
||||
t.Errorf("dark %v DIPs at %vx, clarity %v: %+v", m, s, k, dark)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range []float32{200, 300, 900} {
|
||||
light, dark := paneMaterial(m, 2, 0.5, false, false), paneMaterial(m, 2, 0.5, false, true)
|
||||
if !near(light.blur, 10) || !near(light.bezel, 96) || !near(light.rim, 0.5) || !near(light.low, 0.35) || light.high != 1 {
|
||||
t.Errorf("light %v DIPs: %+v", m, light)
|
||||
}
|
||||
if !near(dark.blur, 10) || !near(dark.high, 0.6) || dark.low != 0.15 || !near(dark.rim, 0.5) {
|
||||
t.Errorf("dark %v DIPs: %+v", m, dark)
|
||||
}
|
||||
}
|
||||
// Between, every parameter lies between the two and moves one way.
|
||||
prev := paneMaterial(100, 1, 0.5, false, false)
|
||||
for m := float32(110); m <= 200; m += 10 {
|
||||
mat := paneMaterial(m, 1, 0.5, false, false)
|
||||
if mat.low > prev.low || mat.rim < prev.rim || mat.bezel < prev.bezel || mat.low < 0.35 || mat.rim > 0.5 {
|
||||
t.Errorf("%v DIPs: %+v after %+v", m, mat, prev)
|
||||
}
|
||||
prev = mat
|
||||
}
|
||||
if mid := paneMaterial(150, 1, 0.5, false, false); !near(mid.low, (0.541+0.35)/2) || !near(mid.rim, 0.425) {
|
||||
t.Errorf("150 DIPs, half way: %+v", mid)
|
||||
}
|
||||
// Clear glass's tone is the same at any size.
|
||||
if small, large := paneMaterial(60, 1, 0.5, true, false), paneMaterial(400, 1, 0.5, true, false); small.low != large.low || small.high != large.high || small.blur != large.blur {
|
||||
t.Errorf("clear: %+v and %+v", small, large)
|
||||
}
|
||||
}
|
||||
|
||||
// A large pane's clarity runs from the measured material, at 0, through
|
||||
// a clearer one at 0.5, to one nearly clear at 1, every parameter moving
|
||||
// one way; out of range it is the nearest end.
|
||||
func TestPaneClarity(t *testing.T) {
|
||||
near := func(a, b float32) bool { return a-b < 1e-5 && b-a < 1e-5 }
|
||||
type tone struct{ blur, light, darkLow, darkHigh, rim, bezel float32 }
|
||||
at := func(k float32) tone {
|
||||
l, d := paneMaterial(400, 1, k, false, false), paneMaterial(400, 1, k, false, true)
|
||||
if l.blur != d.blur || l.rim != d.rim || l.bezel != d.bezel {
|
||||
t.Errorf("clarity %v: light %+v and dark %+v differ", k, l, d)
|
||||
}
|
||||
return tone{l.blur, l.low, d.low, d.high, l.rim, l.bezel}
|
||||
}
|
||||
same := func(a, b tone) bool {
|
||||
return near(a.blur, b.blur) && near(a.light, b.light) && near(a.darkLow, b.darkLow) &&
|
||||
near(a.darkHigh, b.darkHigh) && near(a.rim, b.rim) && near(a.bezel, b.bezel)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
k float32
|
||||
want tone
|
||||
}{
|
||||
{0, tone{10, 0.541, 0.15, 0.51, 0.35, 36}},
|
||||
{0.25, tone{7.5, 0.4455, 0.15, 0.555, 0.425, 42}},
|
||||
{0.5, tone{5, 0.35, 0.15, 0.6, 0.5, 48}},
|
||||
{0.75, tone{3.5, 0.275, 0.125, 0.725, 0.5, 48}},
|
||||
{1, tone{2, 0.2, 0.1, 0.85, 0.5, 48}},
|
||||
{-1, tone{10, 0.541, 0.15, 0.51, 0.35, 36}},
|
||||
{2, tone{2, 0.2, 0.1, 0.85, 0.5, 48}},
|
||||
} {
|
||||
if got := at(c.k); !same(got, c.want) {
|
||||
t.Errorf("clarity %v: %+v, want %+v", c.k, got, c.want)
|
||||
}
|
||||
}
|
||||
// Clearer, it blurs less, lightens and darkens less, its rim brighter
|
||||
// and its bezel wider, or as before.
|
||||
prev := at(0)
|
||||
for k := float32(0.05); k <= 1.001; k += 0.05 {
|
||||
cur := at(k)
|
||||
if cur.blur > prev.blur || cur.light > prev.light || cur.darkLow > prev.darkLow || cur.darkHigh < prev.darkHigh ||
|
||||
cur.rim < prev.rim || cur.bezel < prev.bezel {
|
||||
t.Errorf("clarity %v: %+v after %+v", k, cur, prev)
|
||||
}
|
||||
prev = cur
|
||||
}
|
||||
// A pane between a control's size and a sidebar's eases toward it.
|
||||
for _, k := range []float32{0, 0.5, 1} {
|
||||
small, mid, large := paneMaterial(100, 1, k, false, false), paneMaterial(150, 1, k, false, false), paneMaterial(200, 1, k, false, false)
|
||||
if !near(mid.low, (small.low+large.low)/2) || !near(mid.rim, (small.rim+large.rim)/2) {
|
||||
t.Errorf("clarity %v, 150 DIPs: %+v, not half way between %+v and %+v", k, mid, small, large)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Glass of a clarity paints a large pane clearer: black under it
|
||||
// lighter in light mode the less clear, the same for small panes.
|
||||
func TestClarityPaints(t *testing.T) {
|
||||
gray := func(k float32, w, h float32) int {
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(0, 0, 0)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
Paint(p, ui.Rect{X: 10, Y: 10, W: w, H: h}, 20, Glass{Clarity: k})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 420, 320)
|
||||
return pixelAt(tt.Image(), int(10+w/2), int(10+h/2))[0]
|
||||
}
|
||||
frost, mid, clear := gray(0, 400, 300), gray(0.5, 400, 300), gray(1, 400, 300)
|
||||
if !(frost > mid && mid > clear) {
|
||||
t.Errorf("black under a large pane at clarity 0, 0.5, 1: %d, %d, %d", frost, mid, clear)
|
||||
}
|
||||
if a, b := gray(0, 100, 60), gray(1, 100, 60); a != b {
|
||||
t.Errorf("black under a small pane at clarity 0 and 1: %d and %d", a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringClarity(t *testing.T) {
|
||||
if s := (Glass{Clarity: 0.5}).String(); s != "glass clarity(0.5)" {
|
||||
t.Errorf("String: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// At clarity 0 every pane, of any size and style, is exactly the
|
||||
// material it was before clarity: the measured one.
|
||||
func TestClarityZero(t *testing.T) {
|
||||
for _, m := range []float32{1, 20, 72, 100, 150, 199, 200, 260, 900, 4000} {
|
||||
for _, s := range []float32{1, 1.5, 2} {
|
||||
bezel := min(36, m/2)
|
||||
want := material{bezel: bezel * s, refraction: 1.6 * bezel * s, rim: 0.35, rimWidth: 1, light: math.Pi / 2}
|
||||
for _, c := range []struct {
|
||||
clear, dark bool
|
||||
blur, low, high, curve, saturation float32
|
||||
}{
|
||||
{true, false, s, 0.125, 1.082, 1, 1},
|
||||
{true, true, s, 0.125, 1.082, 1, 1},
|
||||
{false, true, min(max(m*0.035, 1), 10) * s, 0.15, 0.51, 2, 2.2},
|
||||
{false, false, min(max(m*0.035, 1), 10) * s, 0.541, 1, 1.2, 1},
|
||||
} {
|
||||
w := want
|
||||
w.blur, w.low, w.high, w.curve, w.saturation = c.blur, c.low, c.high, c.curve, c.saturation
|
||||
if got := paneMaterial(m, s, 0, c.clear, c.dark); got != w {
|
||||
t.Errorf("%v DIPs at %vx, clear %v, dark %v: %+v, want %+v", m, s, c.clear, c.dark, got, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On clear glass, clarity leaves the tone as it is and only lights the
|
||||
// rim and curves the bezel.
|
||||
func TestClarityClear(t *testing.T) {
|
||||
frost, clear := paneMaterial(400, 1, 0, true, false), paneMaterial(400, 1, 1, true, false)
|
||||
if frost.blur != clear.blur || frost.low != clear.low || frost.high != clear.high {
|
||||
t.Errorf("tone: %+v and %+v", frost, clear)
|
||||
}
|
||||
if clear.rim != 0.5 || clear.bezel != 48 {
|
||||
t.Errorf("rim and bezel: %+v", clear)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build !ios
|
||||
|
||||
package glass
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
)
|
||||
|
||||
// TestMetal checks that Metal draws the glass as the CPU does.
|
||||
func TestMetal(t *testing.T) {
|
||||
s := testScene()
|
||||
pix, err := metal.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "glass-metal", pix, s.Width*4, s)
|
||||
// With continuous corners, as macOS's.
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Continuous = true
|
||||
}
|
||||
if pix, err = metal.RenderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "glass-metal-continuous", pix, s.Width*4, s)
|
||||
}
|
||||
|
||||
// TestMetalBlur checks that Metal draws the blur as the CPU does.
|
||||
func TestMetalBlur(t *testing.T) {
|
||||
s := blurScene()
|
||||
pix, err := metal.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "blur-metal", pix, s.Width*4, s)
|
||||
for i := range s.Ops {
|
||||
s.Ops[i].Continuous = true
|
||||
}
|
||||
if pix, err = metal.RenderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "blur-metal-continuous", pix, s.Width*4, s)
|
||||
}
|
||||
|
||||
// TestMetalLibrary checks that the libraries compiled ahead of time come
|
||||
// from glass.metal and blur.metal and the renderer's head and tail as
|
||||
// they are.
|
||||
func TestMetalLibrary(t *testing.T) {
|
||||
if gpu.SourceSum(metal.EffectSource(metalSource)) != metalSum {
|
||||
t.Error("glass.metal or the Metal renderer's effect.metal changed since shaders_darwin.go was generated: run go generate ./plugins/glass on macOS")
|
||||
}
|
||||
if gpu.SourceSum(metal.EffectSource(blurMetalSource)) != blurMetalSum {
|
||||
t.Error("blur.metal or the Metal renderer's effect.metal changed since shaders_darwin.go was generated: run go generate ./plugins/glass on macOS")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//go:build (amd64 || arm64) && !android
|
||||
|
||||
package glass
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gl"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestOpenGL checks that OpenGL 3.3 and OpenGL ES 3.0 draw the glass and
|
||||
// the blur as the CPU does.
|
||||
func TestOpenGL(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
for _, sc := range []struct {
|
||||
name string
|
||||
scene func() *scene.Scene
|
||||
}{{"glass-gl", testScene}, {"blur-gl", blurScene}} {
|
||||
s := sc.scene()
|
||||
o, err := gl.NewOffscreen(es, s.Width, s.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Log(o.Info())
|
||||
pix, err := o.Render(s)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, sc.name, pix, s.Width*4, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
)
|
||||
|
||||
// TestDirect3D checks that Direct3D 11 draws the glass as the CPU does.
|
||||
func TestDirect3D(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := testScene()
|
||||
pix, stride, err := d3d11.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
gputest.Compare(t, "glass-d3d11", pix, stride, s)
|
||||
s = blurScene()
|
||||
if pix, stride, err = d3d11.RenderOffscreen(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "blur-d3d11", pix, stride, s)
|
||||
}
|
||||
|
||||
// TestBytecode checks that the bytecode compiled ahead of time comes from
|
||||
// glass.hlsl and blur.hlsl and the renderer's head and tail as they are.
|
||||
func TestBytecode(t *testing.T) {
|
||||
if gpu.SourceSum(d3d11.EffectSource(hlslSource)) != hlslSum {
|
||||
t.Error("glass.hlsl or the Direct3D renderer's effect.hlsl changed since shaders_windows.go was generated: run go generate ./plugins/glass on Windows")
|
||||
}
|
||||
if gpu.SourceSum(d3d11.EffectSource(blurHLSLSource)) != blurHLSLSum {
|
||||
t.Error("blur.hlsl or the Direct3D renderer's effect.hlsl changed since shaders_windows.go was generated: run go generate ./plugins/glass on Windows")
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
"github.com/egoist/mygo/ui/shader"
|
||||
)
|
||||
|
||||
// Group is a row of elements on one pane of glass, whose corners merge
|
||||
// while they are close, as macOS's NSGlassEffectContainerView draws them:
|
||||
//
|
||||
// g := glass.NewGroup(c)
|
||||
// g.Radius = 22
|
||||
// g.Gap(6).Children(func() {
|
||||
// g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Cut") }))
|
||||
// g.Pane(ui.Box(c).Padding(8, 16).Center().Children(func() { ui.Text(c, "Copy") }))
|
||||
// })
|
||||
//
|
||||
// The elements are an ordinary row's; the glass is painted behind them,
|
||||
// one surface over all of them, so that it merges where they nearly touch
|
||||
// instead of showing two panes. The elements keep their own backgrounds,
|
||||
// borders and hit areas.
|
||||
type Group struct {
|
||||
ui.Element
|
||||
// Style is the group's material, as Glass's.
|
||||
Style Style
|
||||
// Tint colors the glass, as Glass's.
|
||||
Tint ui.Color
|
||||
// Clarity makes large groups clearer, as Glass's.
|
||||
Clarity float32
|
||||
// Radius is the corners of each element's pane, in DIPs.
|
||||
Radius float32
|
||||
// Merge is how smoothly panes blend into one surface, in DIPs: 24 by
|
||||
// default, which bridges panes up to about 12 DIPs apart; 0 keeps
|
||||
// them apart.
|
||||
Merge float32
|
||||
// panes are the elements whose boxes the glass covers.
|
||||
panes []ui.Element
|
||||
}
|
||||
|
||||
// NewGroup returns an empty Group, a row, whose Material paints the glass
|
||||
// behind the elements its Pane adds.
|
||||
func NewGroup(c *ui.Context) *Group {
|
||||
g := &Group{Element: ui.Row(c), Merge: 24}
|
||||
g.Element.Material(g)
|
||||
return g
|
||||
}
|
||||
|
||||
// Pane adds e to the group's glass, and returns it.
|
||||
func (g *Group) Pane(e ui.Element) ui.Element {
|
||||
g.panes = append(g.panes, e)
|
||||
return e
|
||||
}
|
||||
|
||||
// PaintMaterial paints the group's glass over the union of its panes.
|
||||
func (g *Group) PaintMaterial(p *ui.Painter, box ui.Rect, _ [4]float32) {
|
||||
if box.W <= 0 || box.H <= 0 || len(g.panes) == 0 {
|
||||
return
|
||||
}
|
||||
rects := make([]ui.Rect, 0, len(g.panes))
|
||||
minSide := float32(math.MaxFloat32)
|
||||
for i := range g.panes {
|
||||
b := g.panes[i].LayoutBounds()
|
||||
if b.W <= 0 || b.H <= 0 {
|
||||
continue
|
||||
}
|
||||
b = ui.Rect{X: b.X - box.X, Y: b.Y - box.Y, W: b.W, H: b.H}
|
||||
rects = append(rects, b)
|
||||
minSide = min(minSide, b.W, b.H)
|
||||
}
|
||||
if len(rects) == 0 {
|
||||
return
|
||||
}
|
||||
if p.Preferences().ReduceTransparency {
|
||||
c := p.Theme().Surface
|
||||
if g.Style == Clear {
|
||||
c = p.Theme().Background
|
||||
}
|
||||
if g.Tint.A > 0 {
|
||||
c = c.Mix(g.Tint, float32(g.Tint.A)/255*0.88)
|
||||
}
|
||||
for _, r := range rects {
|
||||
p.FillRadii(r, [4]float32{g.Radius, g.Radius, g.Radius, g.Radius}, c)
|
||||
}
|
||||
return
|
||||
}
|
||||
mat := paneMaterial(minSide, p.Scale(), g.Clarity, g.Style == Clear, p.Theme().Dark)
|
||||
if p.Preferences().HighContrast {
|
||||
mat.rim = min(mat.rim+0.15, 1)
|
||||
mat.rimWidth = max(mat.rimWidth, 1.5)
|
||||
}
|
||||
tint := [4]float32{0, 0, 0, 0}
|
||||
if g.Tint.A > 0 {
|
||||
tint = [4]float32{float32(g.Tint.R) / 255, float32(g.Tint.G) / 255, float32(g.Tint.B) / 255, float32(g.Tint.A) / 255 * 0.88}
|
||||
}
|
||||
groupShader.Draw(p, box, shader.Options{
|
||||
Uniforms: map[string]any{
|
||||
"Count": len(rects),
|
||||
"Rects": groupRects(rects),
|
||||
"Radii": groupRadii(len(rects), g.Radius),
|
||||
"Bezel": mat.bezel / p.Scale(),
|
||||
"Refraction": mat.refraction / p.Scale(),
|
||||
"Rim": mat.rim,
|
||||
"RimWidth": mat.rimWidth / p.Scale(),
|
||||
"Low": mat.low,
|
||||
"High": mat.high,
|
||||
"Curve": mat.curve,
|
||||
"Saturation": mat.saturation,
|
||||
"Merge": g.Merge,
|
||||
"Tint": tint[:],
|
||||
"Light": []float32{float32(math.Cos(float64(mat.light))), float32(math.Sin(float64(mat.light)))},
|
||||
},
|
||||
BackdropBlur: mat.blur / p.Scale(),
|
||||
})
|
||||
}
|
||||
|
||||
// String describes the group, as the inspector shows it.
|
||||
func (g *Group) String() string {
|
||||
return fmt.Sprintf("glass group(%d)", len(g.panes))
|
||||
}
|
||||
|
||||
// groupRects lays out up to maxGroupPanes rects for the shader, in DIPs.
|
||||
func groupRects(rects []ui.Rect) []float32 {
|
||||
out := make([]float32, maxGroupPanes*4)
|
||||
for i, r := range rects {
|
||||
if i >= maxGroupPanes {
|
||||
break
|
||||
}
|
||||
out[i*4], out[i*4+1], out[i*4+2], out[i*4+3] = r.X, r.Y, r.W, r.H
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func groupRadii(n int, radius float32) []float32 {
|
||||
out := make([]float32, maxGroupPanes)
|
||||
for i := range n {
|
||||
if i >= maxGroupPanes {
|
||||
break
|
||||
}
|
||||
out[i] = radius
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const maxGroupPanes = 8
|
||||
|
||||
// groupShader draws the union of the panes: one bezel around the whole
|
||||
// surface, as the panes merge.
|
||||
var groupShader = shader.MustCompile(`package main
|
||||
|
||||
var Count int
|
||||
var Rects [32]float
|
||||
var Radii [8]float
|
||||
var Merge float
|
||||
var Bezel float
|
||||
var Refraction float
|
||||
var Rim float
|
||||
var RimWidth float
|
||||
var Low float
|
||||
var High float
|
||||
var Curve float
|
||||
var Saturation float
|
||||
var Tint vec4
|
||||
var Light vec2
|
||||
|
||||
func sdPane(p vec2, i int) float {
|
||||
r := vec4(Rects[i*4], Rects[i*4+1], Rects[i*4+2], Rects[i*4+3])
|
||||
h := r.zw / 2
|
||||
rad := min(Radii[i], min(h.x, h.y))
|
||||
q := abs(p - r.xy - h) - (h - vec2(rad, rad))
|
||||
m := max(q, vec2(0, 0))
|
||||
return length(m) + min(max(q.x, q.y), 0.0) - rad
|
||||
}
|
||||
|
||||
func smin(a float, b float, k float) float {
|
||||
if k <= 0.0 {
|
||||
return min(a, b)
|
||||
}
|
||||
h := clamp(0.5+0.5*(b-a)/k, 0.0, 1.0)
|
||||
return mix(b, a, h) - k*h*(1.0-h)
|
||||
}
|
||||
|
||||
func unionSDF(p vec2) float {
|
||||
d := 1.0e9
|
||||
for i := 0; i < 8; i++ {
|
||||
if i < Count {
|
||||
d = smin(d, sdPane(p, i), Merge)
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func normalAt(p vec2) vec2 {
|
||||
e := 1.0 / pixelScale()
|
||||
n := vec2(unionSDF(p+vec2(e, 0))-unionSDF(p-vec2(e, 0)), unionSDF(p+vec2(0, e))-unionSDF(p-vec2(0, e)))
|
||||
l := length(n)
|
||||
if l < 0.00001 {
|
||||
return vec2(0, 1)
|
||||
}
|
||||
return n / l
|
||||
}
|
||||
|
||||
func lens(t float, bezel float) float {
|
||||
if bezel <= 0.0 || t >= bezel {
|
||||
return 0.0
|
||||
}
|
||||
u := 1.0 - max(t, 0.0) / bezel
|
||||
v := 1.0 - u*u*u*u
|
||||
a := sqrt(v * sqrt(v))
|
||||
b := u*u*u
|
||||
n := sqrt(a*a + b*b)
|
||||
s := b / n
|
||||
c := a / n
|
||||
st := s / 1.5
|
||||
ct := sqrt(1.0 - st*st)
|
||||
return (s*ct - c*st) / (c*ct + s*st) / 1.118034
|
||||
}
|
||||
|
||||
func tone(c vec3) vec3 {
|
||||
l := 0.2126*c.r + 0.7152*c.g + 0.0722*c.b
|
||||
t := Low + (High-Low)*(1.0-pow(max(1.0-l, 0.0), Curve))
|
||||
k := (High - Low) * Saturation
|
||||
return clamp(vec3(t, t, t) + (c - vec3(l, l, l))*k, vec3(0, 0, 0), vec3(1, 1, 1))
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
d := unionSDF(pos)
|
||||
a := clamp(0.5-d*pixelScale(), 0.0, 1.0)
|
||||
if a <= 0.0 {
|
||||
return vec4(0, 0, 0, 0)
|
||||
}
|
||||
t := max(-d, 0.0)
|
||||
n := vec2(0, 1)
|
||||
if t < Bezel || t < 3.0*RimWidth {
|
||||
n = normalAt(pos)
|
||||
}
|
||||
q := pos
|
||||
if t < Bezel {
|
||||
q = q - n*(Refraction*lens(t, Bezel))
|
||||
}
|
||||
c := tone(backdropSample(q).rgb)
|
||||
c = c + (Tint.rgb-c)*Tint.a
|
||||
if Rim > 0.0 && t < 3.0*RimWidth {
|
||||
r := t / RimWidth
|
||||
lit := Rim * exp(-r*r)
|
||||
l := abs(dot(n, Light))
|
||||
c = c + (vec3(l, l, l) - c) * lit
|
||||
}
|
||||
return vec4(c.x*a, c.y*a, c.z*a, a)
|
||||
}
|
||||
`)
|
||||
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
)
|
||||
|
||||
// compile compiles the shader file within the Direct3D renderer's head
|
||||
// and tail.
|
||||
func compile(file string) (compiled string, code []byte, err error) {
|
||||
src, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
code, err = d3d11.CompileEffect(string(src))
|
||||
return d3d11.EffectSource(string(src)), code, err
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//go:build !js
|
||||
|
||||
// Command gen compiles the glass's and the blur's shaders ahead of time,
|
||||
// so that renderers start without compiling them: the Metal libraries on
|
||||
// macOS, with Xcode's metal tools, into shaders_darwin.go, and the
|
||||
// Direct3D bytecode on Windows, with the system's d3dcompiler_47.dll, into
|
||||
// shaders_windows.go. Run it on each: go generate ./plugins/glass
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// shader is a shader to compile, and the variables holding its code and
|
||||
// the SHA-256 of what that was compiled from.
|
||||
type shader struct{ file, codeVar, sumVar string }
|
||||
|
||||
func main() {
|
||||
file := "shaders_darwin.go"
|
||||
shaders := []shader{{"glass.metal", "metalLibrary", "metalSum"}, {"blur.metal", "blurMetalLibrary", "blurMetalSum"}}
|
||||
if runtime.GOOS == "windows" {
|
||||
file = "shaders_windows.go"
|
||||
shaders = []shader{{"glass.hlsl", "hlslBytecode", "hlslSum"}, {"blur.hlsl", "blurBytecode", "blurHLSLSum"}}
|
||||
}
|
||||
var names []string
|
||||
for _, sh := range shaders {
|
||||
names = append(names, sh.file)
|
||||
}
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "// Code generated by internal/gen from %s; DO NOT EDIT.\n\n//go:build %s\n\npackage glass\n\n", strings.Join(names, " and "), runtime.GOOS)
|
||||
for _, sh := range shaders {
|
||||
compiled, code, err := compile(sh.file)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Fprintf(&b, "// %s is the SHA-256 of what %s was compiled from: %s\n// within the renderer's head and tail.\nconst %s = %q\n\n", sh.sumVar, sh.codeVar, sh.file, sh.sumVar, gpu.SourceSum(compiled))
|
||||
b.WriteString(gpu.GoBytes(sh.codeVar, code))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
out, err := format.Source(b.Bytes())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, out, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//go:build !ios
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
)
|
||||
|
||||
// compile compiles the shader file within the Metal renderer's head and
|
||||
// tail.
|
||||
func compile(file string) (compiled string, code []byte, err error) {
|
||||
src, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
compiled = metal.EffectSource(string(src))
|
||||
code, err = metal.CompileLibrary(compiled)
|
||||
return compiled, code, err
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !(darwin && !ios) && !windows && !js
|
||||
|
||||
package main
|
||||
|
||||
import "errors"
|
||||
|
||||
func compile(string) (compiled string, code []byte, err error) {
|
||||
return "", nil, errors.New("the glass's shaders compile on macOS and Windows")
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// pixels draws the glass on the CPU, as its shaders do on the GPU.
|
||||
type pixels struct {
|
||||
m material
|
||||
rect scene.Rect
|
||||
radii [4]float32
|
||||
lx, ly float32
|
||||
toneTable [toneSteps + 1]float32
|
||||
toneLinear bool
|
||||
}
|
||||
|
||||
// toneSteps is how many lightnesses the CPU keeps the tone curve at,
|
||||
// between which it is a line, within 3e-5 of the curve: its power makes
|
||||
// it slow on the CPU.
|
||||
const toneSteps = 1024
|
||||
|
||||
// Begin reads the material of op and readies its tone curve.
|
||||
func (px *pixels) Begin(op *scene.EffectOp, rect scene.Rect, radii [4]float32) {
|
||||
p := &op.Params
|
||||
px.m = material{
|
||||
blur: op.Blur,
|
||||
bezel: p[0][0], refraction: p[0][1], rim: p[0][2], rimWidth: p[0][3],
|
||||
tint: p[1],
|
||||
low: p[2][0], high: p[2][1], curve: p[2][2], saturation: p[2][3],
|
||||
}
|
||||
px.lx, px.ly = p[3][0], p[3][1]
|
||||
px.rect, px.radii = rect, radii
|
||||
px.toneLinear = px.m.curve == 1
|
||||
if !px.toneLinear {
|
||||
for i := range px.toneTable {
|
||||
px.toneTable[i] = 1 - pow(1-float32(i)/toneSteps, px.m.curve)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tone is the material's tone from the table.
|
||||
func (px *pixels) tone(c [3]float32) [3]float32 {
|
||||
m := &px.m
|
||||
l := 0.2126*c[0] + 0.7152*c[1] + 0.0722*c[2]
|
||||
var v float32
|
||||
if px.toneLinear {
|
||||
v = min(max(l, 0), 1)
|
||||
} else {
|
||||
x := min(max(l, 0), 1) * toneSteps
|
||||
i := min(int(x), toneSteps-1)
|
||||
f := x - float32(i)
|
||||
v = px.toneTable[i] + (px.toneTable[i+1]-px.toneTable[i])*f
|
||||
}
|
||||
return toneAt(c, l, m.low+(m.high-m.low)*v, m)
|
||||
}
|
||||
|
||||
// Color returns the color of the glass at the pixel center (x, y), as the
|
||||
// shaders' effect does.
|
||||
func (px *pixels) Color(x, y float32, b *scene.BackdropImage) [4]float32 {
|
||||
m := &px.m
|
||||
t := max(-scene.SDRoundRect(px.rect, px.radii, x, y), 0)
|
||||
var nx, ny float32
|
||||
if t < m.bezel || t < 3*m.rimWidth {
|
||||
nx, ny = normal(x, y, px.rect, px.radii)
|
||||
}
|
||||
sx, sy := x, y
|
||||
if t < m.bezel {
|
||||
d := m.refraction * lens(t, m.bezel)
|
||||
sx, sy = x-nx*d, y-ny*d
|
||||
}
|
||||
c := px.tone(b.Sample(sx, sy))
|
||||
for i := range c {
|
||||
c[i] += (m.tint[i] - c[i]) * m.tint[3]
|
||||
}
|
||||
if m.rim > 0 && t < 3*m.rimWidth {
|
||||
q := t / m.rimWidth
|
||||
a := m.rim * float32(math.Exp(float64(-q*q)))
|
||||
l := abs(nx*px.lx + ny*px.ly)
|
||||
for i := range c {
|
||||
c[i] += (l - c[i]) * a
|
||||
}
|
||||
}
|
||||
return [4]float32{c[0], c[1], c[2], 1}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package glass
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// paneOp appends a pane of glass of material m to s.
|
||||
func paneOp(s *scene.Scene, r scene.Rect, radii [4]float32, m material, opacity float32) {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: r, Radii: radii, Start: int32(len(s.Effects)), Opacity: opacity})
|
||||
s.Effects = append(s.Effects, scene.EffectOp{Effect: Effect, Blur: m.blur, Params: m.params()})
|
||||
}
|
||||
|
||||
func r4(r float32) [4]float32 { return [4]float32{r, r, r, r} }
|
||||
|
||||
// testScene returns a 320×140 scene of panes of glass over stripes and a
|
||||
// gradient, which the renderers must draw alike: blurred at a quarter of
|
||||
// the size, over each other, unblurred and tinted, clipped, half
|
||||
// transparent, dark and blurred at full size, and past the frame's edge.
|
||||
func testScene() *scene.Scene {
|
||||
s := &scene.Scene{Width: 320, Height: 140, Clear: scene.Color{R: 246, G: 247, B: 249, A: 255}}
|
||||
red := scene.Color{R: 220, G: 40, B: 40, A: 255}
|
||||
blue := scene.Color{R: 37, G: 99, B: 235, A: 255}
|
||||
yellow := scene.Color{R: 250, G: 204, B: 21, A: 255}
|
||||
ink := scene.Color{R: 20, G: 24, B: 32, A: 255}
|
||||
for i := range 8 {
|
||||
c := []scene.Color{red, blue, yellow, ink}[i%4]
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 40), W: 20, H: 140}, Color: c})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{Y: 60, W: 320, H: 20}, Color: red, Color2: blue,
|
||||
Paint: scene.PaintOklab, Gradient: [4]float32{0, 0, 320, 0}})
|
||||
light := material{low: 0.541, high: 1, curve: 1.2, saturation: 1, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
m := light
|
||||
m.blur, m.bezel, m.refraction = 8, 22, 35
|
||||
paneOp(s, scene.Rect{X: 12, Y: 10, W: 140, H: 44}, r4(22), m, 0)
|
||||
m = light
|
||||
m.blur, m.bezel, m.refraction = 12, 30, 48
|
||||
paneOp(s, scene.Rect{X: 120, Y: 36, W: 60, H: 60}, r4(30), m, 0)
|
||||
m = material{low: 0.125, high: 1.082, curve: 1, saturation: 1, bezel: 16, refraction: 26, tint: [4]float32{0.15, 0.39, 0.92, 0.47},
|
||||
rim: 0.35, rimWidth: 2, light: math.Pi / 4}
|
||||
paneOp(s, scene.Rect{X: 190.5, Y: 8.25, W: 110, H: 50}, r4(16), m, 0)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30, Y: 70, W: 200, H: 50}, Radii: r4(12)})
|
||||
m = material{blur: 3, low: 0.15, high: 0.51, curve: 2, saturation: 2.2, bezel: 20, refraction: 30, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
paneOp(s, scene.Rect{X: 40, Y: 66, W: 240, H: 44}, [4]float32{22, 6, 22, 6}, m, 0.7)
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
m = light
|
||||
m.blur, m.bezel, m.refraction = 6, 16, 24
|
||||
paneOp(s, scene.Rect{X: 284, Y: 94, W: 50, H: 50}, r4(14), m, 0)
|
||||
return s
|
||||
}
|
||||
|
||||
// TestToneTable checks the CPU's tone curve against the curve itself.
|
||||
func TestToneTable(t *testing.T) {
|
||||
for _, m := range []material{
|
||||
{low: 0.541, high: 1, curve: 1.2, saturation: 1},
|
||||
{low: 0.15, high: 0.51, curve: 2, saturation: 2.2},
|
||||
{low: 0.125, high: 1.082, curve: 1, saturation: 1},
|
||||
} {
|
||||
var px pixels
|
||||
op := scene.EffectOp{Effect: Effect, Params: m.params()}
|
||||
px.Begin(&op, scene.Rect{W: 10, H: 10}, [4]float32{})
|
||||
worst := float32(0)
|
||||
for i := range 1000 {
|
||||
c := [3]float32{float32(i%10) / 9, float32(i/10%10) / 9, float32(i/100) / 9}
|
||||
got, want := px.tone(c), tone(c, &m)
|
||||
for k := range got {
|
||||
worst = max(worst, abs(got[k]-want[k]))
|
||||
}
|
||||
}
|
||||
if worst > 1e-4 {
|
||||
t.Errorf("curve %v: the table is %v off the curve", m.curve, worst)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGlassShowsWhatIsBehind checks that the glass lightens what is under
|
||||
// it, bends it near its edge and lights its rim.
|
||||
func TestGlassShowsWhatIsBehind(t *testing.T) {
|
||||
s := testScene()
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(img, s)
|
||||
at := func(x, y int) [4]byte {
|
||||
p := img.Pix[y*img.Stride+4*x:]
|
||||
return [4]byte{p[2], p[1], p[0], p[3]}
|
||||
}
|
||||
// Over the ink stripe (x 120 to 140), the first pane is light gray.
|
||||
if p := at(130, 32); p[0] < 120 || p[0] > 200 {
|
||||
t.Errorf("light glass over ink is %v", p)
|
||||
}
|
||||
// Outside the panes, the stripes show as they are.
|
||||
if p := at(10, 130); p != [4]byte{220, 40, 40, 255} {
|
||||
t.Errorf("outside the glass: %v", p)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkGlass measures drawing a window with panes of glass on the
|
||||
// CPU, whole: 1360×720 pixels, stripes under a bar, a card, a button and
|
||||
// a lens.
|
||||
func BenchmarkGlass(b *testing.B) {
|
||||
s := &scene.Scene{Width: 1360, Height: 720, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
|
||||
colors := []scene.Color{{R: 239, G: 68, B: 68, A: 255}, {R: 245, G: 158, B: 11, A: 255}, {R: 16, G: 185, B: 129, A: 255}, {R: 59, G: 130, B: 246, A: 255}}
|
||||
for i := range 17 {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 80), W: 40, H: 720}, Color: colors[i%len(colors)]})
|
||||
}
|
||||
m := material{low: 0.541, high: 1, curve: 1.2, saturation: 1, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
m.blur, m.bezel, m.refraction = 4, 58, 93
|
||||
paneOp(s, scene.Rect{X: 32, Y: 32, W: 1296, H: 116}, r4(58), m, 0)
|
||||
m.blur, m.bezel, m.refraction = 12, 72, 115
|
||||
paneOp(s, scene.Rect{X: 80, Y: 220, W: 600, H: 170}, r4(56), m, 0)
|
||||
m.blur, m.bezel, m.refraction = 2, 36, 58
|
||||
paneOp(s, scene.Rect{X: 1120, Y: 52, W: 160, H: 72}, r4(36), m, 0)
|
||||
m = material{blur: 2, low: 0.125, high: 1.082, curve: 1, saturation: 1, bezel: 72, refraction: 115, rim: 0.35, rimWidth: 2, light: math.Pi / 2}
|
||||
paneOp(s, scene.Rect{X: 840, Y: 260, W: 280, H: 280}, r4(140), m, 0)
|
||||
img := raster.NewImage(s.Width, s.Height)
|
||||
for b.Loop() {
|
||||
raster.Render(img, s)
|
||||
}
|
||||
}
|
||||
+3248
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,8 @@
|
||||
//go:build !windows
|
||||
|
||||
package glass
|
||||
|
||||
// The Direct3D bytecode compiled ahead of time is for Windows alone.
|
||||
var hlslBytecode, blurBytecode []byte
|
||||
|
||||
const hlslSum, blurHLSLSum = "", ""
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !(darwin && !ios)
|
||||
|
||||
package glass
|
||||
|
||||
// The Metal libraries compiled ahead of time are for macOS alone.
|
||||
var metalLibrary, blurMetalLibrary []byte
|
||||
|
||||
const metalSum, blurMetalSum = "", ""
|
||||
+3610
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user