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
+38
@@ -0,0 +1,38 @@
|
||||
//go:build !ios
|
||||
|
||||
package shader
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/msl"
|
||||
)
|
||||
|
||||
// code gives fx p's code for the Metal renderer, and returns where the
|
||||
// uniforms' lanes lie in its buffer and the buffer's size: the whole
|
||||
// library, whose tail (ShaderSource in package metal) calls shaderMain.
|
||||
// It starts making the library and its pipeline, which take Metal 0.1 s
|
||||
// each the first time, on a goroutine of its own, which the renderers
|
||||
// then share. What the shader reads of a quad of those one draw draws
|
||||
// (DrawInstances) comes from the instance drawing it, in the slots of an
|
||||
// effect's parameters (gpu.Builder).
|
||||
func code(p *shaderir.Program, fx *scene.Effect) ([]int, int) {
|
||||
fx.Metal.Source = metal.ShaderSource(msl.Fragment(p, "shaderFragment", shader.InstanceUniform) + `
|
||||
float4 shaderMain(constant Uniforms& uniforms, texture2d<float> T0, texture2d<float> T1, texture2d<float> T2, texture2d<float> T3, float2 p, float4 rect, thread const Inst& i) {
|
||||
// grad.z is 2 for a quad of those one draw draws.
|
||||
bool many = i.grad.z > 1.5f;
|
||||
float4 none = float4(0.0f);
|
||||
array<float4, 5> instance;
|
||||
instance[0] = many ? i.inner : none;
|
||||
instance[1] = many ? i.color : none;
|
||||
instance[2] = many ? i.color2 : none;
|
||||
instance[3] = many ? i.border : none;
|
||||
instance[4] = many ? float4(i.grad.w, i.grad.xy, 1.0f) : none;
|
||||
return shaderFragment(uniforms, T0, T1, T2, T3, instance, float4(p, 0.0f, 1.0f), (p - rect.xy) / uniforms.U2);
|
||||
}
|
||||
`)
|
||||
metal.PrecompileShader(fx.Metal.Source)
|
||||
return msl.UniformLanes(p)
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
//go:build !(darwin && !ios) && !windows
|
||||
|
||||
package shader
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/glsl"
|
||||
)
|
||||
|
||||
// code gives fx p's code for the OpenGL and WebGL 2 renderer, as an
|
||||
// effect's, with the uniforms in the std140 block ShaderUniforms and the
|
||||
// images in the samplers T0 to T3, and returns where the uniforms' lanes
|
||||
// lie in the block and its size. The renderer draws with GL's y going up,
|
||||
// which negates dFdy, and keeps canvases' rows going up, which it tells
|
||||
// the shader in uShaderFlipRows. What it reads of a quad of those one
|
||||
// draw draws (DrawInstances) comes from the instance drawing it, in the
|
||||
// slots of an effect's parameters (gpu.Builder).
|
||||
func code(p *shaderir.Program, fx *scene.Effect) ([]int, int) {
|
||||
fx.GLSL = glsl.Fragment(p, "shaderFragment", glsl.Options{FlipY: "true", Block: "ShaderUniforms", FlipRows: "uShaderFlipRows", Instance: shader.InstanceUniform}) + `
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
// p4.z is 1 for a mask glyph, its positions from the box's corner in
|
||||
// p4.xy, and 2 for a quad of those one draw draws.
|
||||
bool many = e.p4.z > 1.5;
|
||||
vec4 none = vec4(0.0);
|
||||
shaderInstance[0] = many ? e.p0 : none;
|
||||
shaderInstance[1] = many ? e.p1 : none;
|
||||
shaderInstance[2] = many ? e.p2 : none;
|
||||
shaderInstance[3] = many ? e.p3 : none;
|
||||
shaderInstance[4] = many ? vec4(e.p4.w, e.p4.xy, 1.0) : none;
|
||||
return shaderFragment(vec4(p, 0.0, 1.0), (p - (e.p4.z > 0.5 && !many ? e.p4.xy : e.rect.xy)) / U2);
|
||||
}
|
||||
`
|
||||
return glsl.UniformLanes(p)
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package shader
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/hlsl"
|
||||
)
|
||||
|
||||
// code gives fx p's code for the Direct3D renderer, as an effect's, with
|
||||
// the uniforms in the cbuffer of register b2 and the images in registers
|
||||
// t6 to t9, after the renderer's own, and returns where the uniforms'
|
||||
// lanes lie in the cbuffer and its size. It starts compiling the code,
|
||||
// which takes Direct3D's compiler from a tenth of a second to more than
|
||||
// one, on a goroutine of its own, which the renderers of all windows then
|
||||
// share, with a cache on disk for the next launches. What the shader
|
||||
// reads of a quad of those one draw draws (DrawInstances) comes from the
|
||||
// instance drawing it, in the slots of an effect's parameters
|
||||
// (gpu.Builder).
|
||||
func code(p *shaderir.Program, fx *scene.Effect) ([]int, int) {
|
||||
fx.HLSL.Source = hlsl.Fragment(p, "shaderFragment", 2, 6, shader.InstanceUniform) + `
|
||||
float4 effect(float2 p, Effect e) {
|
||||
// p4.z is 1 for a mask glyph, its positions from the box's corner in
|
||||
// p4.xy, and 2 for a quad of those one draw draws.
|
||||
bool many = e.p4.z > 1.5;
|
||||
float4 none = float4(0, 0, 0, 0);
|
||||
shaderInstance[0] = many ? e.p0 : none;
|
||||
shaderInstance[1] = many ? e.p1 : none;
|
||||
shaderInstance[2] = many ? e.p2 : none;
|
||||
shaderInstance[3] = many ? e.p3 : none;
|
||||
shaderInstance[4] = many ? float4(e.p4.w, e.p4.xy, 1) : none;
|
||||
return shaderFragment(float4(p, 0, 1), (p - (e.p4.z > 0.5 && !many ? e.p4.xy : e.rect.xy)) / U2);
|
||||
}
|
||||
`
|
||||
d3d11.PrecompileEffect(fx.HLSL.Source)
|
||||
return hlsl.UniformLanes(p)
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
//go:build !ios
|
||||
|
||||
package shader
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
)
|
||||
|
||||
// TestMetal checks that Metal draws a shader, its uniforms and its
|
||||
// images, a bitmap and a canvas, as the CPU does.
|
||||
func TestMetal(t *testing.T) {
|
||||
s := MustCompile(testSource)
|
||||
sc := testScene(s)
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal", pix, sc.Width*4, sc)
|
||||
}
|
||||
|
||||
// TestMetalBools checks that Metal reads bools at the end of its struct of
|
||||
// uniforms, a byte each.
|
||||
func TestMetalBools(t *testing.T) {
|
||||
sc := boolScene()
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal-bools", pix, sc.Width*4, sc)
|
||||
}
|
||||
|
||||
// TestMetalDfdy checks that dfdy grows downward on Metal.
|
||||
func TestMetalDfdy(t *testing.T) {
|
||||
pix, err := metal.RenderOffscreen(dfdyScene())
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
checkDfdy(t, pix, 40*4)
|
||||
}
|
||||
|
||||
// TestMetalMasked checks that Metal fills mask glyphs with a shader, as
|
||||
// text and paths, as the CPU does.
|
||||
func TestMetalMasked(t *testing.T) {
|
||||
sc := maskedScene(MustCompile(maskedSource))
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal-masked", pix, sc.Width*4, sc)
|
||||
}
|
||||
|
||||
// TestMetalEffect checks that Metal draws an effect's shader from its
|
||||
// content, as the CPU does.
|
||||
func TestMetalEffect(t *testing.T) {
|
||||
for name, sc := range effectScenes(MustCompile(effectSource)) {
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal-effect-"+name, pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMetalBackdropEndsAtDrawn checks that Metal ends a backdrop at the
|
||||
// edge of what a frame draws (Scene.Drawn), as the CPU does.
|
||||
func TestMetalBackdropEndsAtDrawn(t *testing.T) {
|
||||
for name, scs := range edgeBackdrops() {
|
||||
sc := scs[1]
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal-backdrop-drawn-"+name, pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMetalBackdrop checks that Metal gives a shader its backdrop, as the
|
||||
// CPU does.
|
||||
func TestMetalBackdrop(t *testing.T) {
|
||||
for name, sc := range backdropCases() {
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal-backdrop-"+name, pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMetalInstances checks that Metal draws the quads of one draw
|
||||
// (DrawInstances), each with its data and index, as the CPU does.
|
||||
func TestMetalInstances(t *testing.T) {
|
||||
sc := instancesScene(MustCompile(instancesSource))
|
||||
pix, err := metal.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-metal-instances", pix, sc.Width*4, sc)
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
//go:build (amd64 || arm64) && !android
|
||||
|
||||
package shader
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gl"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
)
|
||||
|
||||
// TestOpenGL checks that OpenGL 3.3 and OpenGL ES 3.0 draw a shader, its
|
||||
// uniforms and its images, a bitmap and a canvas, as the CPU does.
|
||||
func TestOpenGL(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := MustCompile(testSource)
|
||||
for _, es := range []bool{false, true} {
|
||||
sc := testScene(s)
|
||||
o, err := gl.NewOffscreen(es, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Log(o.Info())
|
||||
pix, err := o.Render(sc)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := "ui-shader-gl"
|
||||
if es {
|
||||
name += "-es"
|
||||
}
|
||||
gputest.Compare(t, name, pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenGLBools checks that OpenGL reads bool uniforms as the CPU does.
|
||||
func TestOpenGLBools(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
sc := boolScene()
|
||||
o, err := gl.NewOffscreen(false, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
defer o.Release()
|
||||
pix, err := o.Render(sc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-gl-bools", pix, sc.Width*4, sc)
|
||||
}
|
||||
|
||||
// TestOpenGLDfdy checks that dfdy grows downward on OpenGL, in a canvas
|
||||
// and in the frame, whose rows go up.
|
||||
func TestOpenGLDfdy(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
sc := dfdyScene()
|
||||
o, err := gl.NewOffscreen(es, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
pix, err := o.Render(sc)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checkDfdy(t, pix, sc.Width*4)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenGLMasked checks that OpenGL fills mask glyphs with a shader, as
|
||||
// text and paths, as the CPU does.
|
||||
func TestOpenGLMasked(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
sc := maskedScene(MustCompile(maskedSource))
|
||||
o, err := gl.NewOffscreen(es, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
pix, err := o.Render(sc)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-gl-masked", pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenGLEffect checks that OpenGL draws an effect's shader from its
|
||||
// content, as the CPU does.
|
||||
func TestOpenGLEffect(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
for name, sc := range effectScenes(MustCompile(effectSource)) {
|
||||
o, err := gl.NewOffscreen(es, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
pix, err := o.Render(sc)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-gl-effect-"+name, pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenGLBackdrop checks that OpenGL gives a shader its backdrop, as
|
||||
// the CPU does.
|
||||
func TestOpenGLBackdrop(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
for name, sc := range backdropCases() {
|
||||
o, err := gl.NewOffscreen(es, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
pix, err := o.Render(sc)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-gl-backdrop-"+name, pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenGLInstances checks that OpenGL draws the quads of one draw
|
||||
// (DrawInstances), each with its data and index, as the CPU does.
|
||||
func TestOpenGLInstances(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, es := range []bool{false, true} {
|
||||
sc := instancesScene(MustCompile(instancesSource))
|
||||
o, err := gl.NewOffscreen(es, sc.Width, sc.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
pix, err := o.Render(sc)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-gl-instances", pix, sc.Width*4, sc)
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package shader
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
)
|
||||
|
||||
// TestDirect3D checks that Direct3D 11 draws a shader, its uniforms and
|
||||
// its images, a bitmap and a canvas, as the CPU does.
|
||||
func TestDirect3D(t *testing.T) {
|
||||
s := MustCompile(testSource)
|
||||
if _, err := d3d11.CompileEffect(s.fx.HLSL.Source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := testScene(s)
|
||||
pix, stride, err := d3d11.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-d3d11", pix, stride, sc)
|
||||
}
|
||||
|
||||
// TestDirect3DBools checks that Direct3D reads bool uniforms as the CPU
|
||||
// does.
|
||||
func TestDirect3DBools(t *testing.T) {
|
||||
sc := boolScene()
|
||||
pix, stride, err := d3d11.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-d3d11-bools", pix, stride, sc)
|
||||
}
|
||||
|
||||
// TestDirect3DDfdy checks that dfdy grows downward on Direct3D 11.
|
||||
func TestDirect3DDfdy(t *testing.T) {
|
||||
pix, stride, err := d3d11.RenderOffscreen(dfdyScene())
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
checkDfdy(t, pix, stride)
|
||||
}
|
||||
|
||||
// TestDirect3DMasked checks that Direct3D fills mask glyphs with a shader,
|
||||
// as text and paths, as the CPU does.
|
||||
func TestDirect3DMasked(t *testing.T) {
|
||||
sc := maskedScene(MustCompile(maskedSource))
|
||||
pix, stride, err := d3d11.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-d3d11-masked", pix, stride, sc)
|
||||
}
|
||||
|
||||
// TestDirect3DEffect checks that Direct3D draws an effect's shader from
|
||||
// its content, as the CPU does.
|
||||
func TestDirect3DEffect(t *testing.T) {
|
||||
for name, sc := range effectScenes(MustCompile(effectSource)) {
|
||||
pix, stride, err := d3d11.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-d3d11-effect-"+name, pix, stride, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDirect3DBackdrop checks that Direct3D gives a shader its backdrop,
|
||||
// as the CPU does.
|
||||
func TestDirect3DBackdrop(t *testing.T) {
|
||||
for name, sc := range backdropCases() {
|
||||
pix, stride, err := d3d11.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-d3d11-backdrop-"+name, pix, stride, sc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDirect3DInstances checks that Direct3D 11 draws the quads of one
|
||||
// draw (DrawInstances), each with its data and index, as the CPU does.
|
||||
func TestDirect3DInstances(t *testing.T) {
|
||||
s := MustCompile(instancesSource)
|
||||
if _, err := d3d11.CompileEffect(s.fx.HLSL.Source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := instancesScene(s)
|
||||
pix, stride, err := d3d11.RenderOffscreen(sc)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "ui-shader-d3d11-instances", pix, stride, sc)
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package shader_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
"github.com/egoist/mygo/ui/shader"
|
||||
)
|
||||
|
||||
// instancesSource draws a quad from its data, or from its uniforms when
|
||||
// drawn alone (Draw), where instanceData and instanceIndex are 0: a color,
|
||||
// stripes as many as its index plus one across its rectangle, and a ring
|
||||
// at its edge.
|
||||
var instancesSource = `package main
|
||||
|
||||
var Color vec4
|
||||
var Index int
|
||||
|
||||
func stripes(pos vec2) float {
|
||||
i := Index + instanceIndex()
|
||||
return step(0.5, fract(pos.x/rectSize().x*float(i+1)))
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
c := Color + vec4(instanceData(0), instanceData(1), instanceData(2), instanceData(3))
|
||||
c.rgb *= mix(0.5, 1.0, stripes(pos))
|
||||
d := min(min(pos.x, pos.y), min(rectSize().x-pos.x, rectSize().y-pos.y))
|
||||
if d < 2 {
|
||||
c.rgb = vec3(instanceData(4) + Color.a*0.25)
|
||||
}
|
||||
return c
|
||||
}
|
||||
`
|
||||
|
||||
// instancesQuads are quads that overlap, between pixels at scale 1.5, with
|
||||
// their colors and, after, the gray of their rings, a quarter of their
|
||||
// alpha, as Color gives it drawn alone.
|
||||
func instancesQuads() ([]ui.Rect, []float32) {
|
||||
var rects []ui.Rect
|
||||
var data []float32
|
||||
for i := range 12 {
|
||||
x, y := 6.3+float32(i%4)*41.7, 5.6+float32(i/4)*27.9
|
||||
rects = append(rects, ui.Rect{X: x, Y: y, W: 50.4, H: 31.1})
|
||||
k := float32(i) / 11
|
||||
data = append(data, k, 1-k, 0.5, 1, 0.25)
|
||||
}
|
||||
// Half transparent, over the others.
|
||||
rects = append(rects, ui.Rect{X: 40.2, Y: 30.7, W: 90.5, H: 40.3})
|
||||
data = append(data, 0.2, 0.1, 0.4, 0.5, 0.125)
|
||||
return rects, data
|
||||
}
|
||||
|
||||
// drawQuads draws the quads in a box rotated by turn, each alone (Draw)
|
||||
// or all in one draw (DrawInstances).
|
||||
func drawQuads(s *shader.Shader, alone bool, turn float32) func(c *ui.Context) {
|
||||
rects, data := instancesQuads()
|
||||
const stride = 5
|
||||
return func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Rotate(turn).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
if !alone {
|
||||
s.DrawInstances(p, shader.Instances{Rects: rects, Data: data, Stride: stride}, shader.Options{Radius: 6})
|
||||
return
|
||||
}
|
||||
for i, q := range rects {
|
||||
d := data[i*stride:]
|
||||
s.Draw(p, q, shader.Options{Radius: 6, Uniforms: map[string]any{
|
||||
"Color": d[:4], "Index": i,
|
||||
}})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The CPU draws the quads of one DrawInstances as it draws each alone with
|
||||
// Draw, pixel for pixel: their rectangles, corners, data, indices and
|
||||
// order, under a transform too.
|
||||
func TestDrawInstancesAsDraws(t *testing.T) {
|
||||
s := shader.MustCompile(instancesSource)
|
||||
for _, turn := range []float32{0, 7} {
|
||||
images := [2][]byte{}
|
||||
for k, alone := range []bool{true, false} {
|
||||
tt := ui.NewTester(drawQuads(s, alone, turn), 200, 100)
|
||||
tt.SetScale(1.5)
|
||||
images[k] = tt.Image().Pix
|
||||
}
|
||||
if !bytes.Equal(images[0], images[1]) {
|
||||
n := 0
|
||||
for i := range images[0] {
|
||||
if images[0][i] != images[1][i] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
t.Errorf("rotated %v°: DrawInstances differs from Draw in %d bytes", turn, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each quad's shader reads its own data and index, and its rectangle's
|
||||
// size; the data of none reaches another.
|
||||
func TestDrawInstancesData(t *testing.T) {
|
||||
s := shader.MustCompile(`package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
if instanceIndex() == 2 && rectSize().x == 30 {
|
||||
return vec4(0, 0, 1, 1)
|
||||
}
|
||||
return vec4(instanceData(0), instanceData(15), instanceData(16), 1)
|
||||
}
|
||||
`)
|
||||
data := make([]float32, 3*16)
|
||||
data[0], data[16+15], data[32+15] = 1, 1, 1
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
s.DrawInstances(p, shader.Instances{
|
||||
Rects: []ui.Rect{{X: 0, Y: 0, W: 20, H: 20}, {X: 20, Y: 0, W: 20, H: 20}, {X: 40, Y: 0, W: 30, H: 20}},
|
||||
Data: data,
|
||||
Stride: 16,
|
||||
}, shader.Options{})
|
||||
// Alone, a shader reads no instance.
|
||||
s.Draw(p, ui.Rect{X: 0, Y: 30, W: 30, H: 20}, shader.Options{})
|
||||
})
|
||||
}
|
||||
img := ui.NewTester(view, 80, 60).Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
for _, c := range []struct {
|
||||
x, y int
|
||||
want [4]uint8
|
||||
}{
|
||||
{10, 10, [4]uint8{255, 0, 0, 255}}, // instance 0: data[0]
|
||||
{30, 10, [4]uint8{0, 255, 0, 255}}, // instance 1: its data[15]
|
||||
{55, 10, [4]uint8{0, 0, 255, 255}}, // instance 2, 30 DIPs wide
|
||||
{15, 40, [4]uint8{0, 0, 0, 255}}, // Draw: no data
|
||||
{75, 10, [4]uint8{255, 255, 255, 255}}, // nothing drawn
|
||||
} {
|
||||
if got := at(c.x, c.y); got != c.want {
|
||||
t.Errorf("at (%d, %d): %v, want %v", c.x, c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DrawInstances draws at most MaxInstances quads, with at most
|
||||
// MaxInstanceStride floats each, of as many as the quads need, and no
|
||||
// shader reading its backdrop; it draws nothing for no quads.
|
||||
func TestDrawInstancesCaps(t *testing.T) {
|
||||
s := shader.MustCompile("package main\nfunc Fragment(dst vec4, pos vec2) vec4 { return vec4(instanceData(0)) }\n")
|
||||
backdrop := shader.MustCompile("package main\nfunc Fragment(dst vec4, pos vec2) vec4 { return backdropAt(pos) }\n")
|
||||
if shader.MaxInstanceStride != 16 || shader.MaxInstances != 1<<16 {
|
||||
t.Errorf("the caps are %d floats and %d instances, not those the documentation gives", shader.MaxInstanceStride, shader.MaxInstances)
|
||||
}
|
||||
rect := ui.Rect{W: 1, H: 1}
|
||||
many := make([]ui.Rect, shader.MaxInstances+1)
|
||||
for _, c := range []struct {
|
||||
s *shader.Shader
|
||||
in shader.Instances
|
||||
want string
|
||||
}{
|
||||
{s, shader.Instances{Rects: []ui.Rect{rect}, Data: make([]float32, 17), Stride: 17}, "stride is 17"},
|
||||
{s, shader.Instances{Rects: []ui.Rect{rect}, Stride: -1}, "stride is -1"},
|
||||
{s, shader.Instances{Rects: many}, "beyond 65536"},
|
||||
{s, shader.Instances{Rects: []ui.Rect{rect, rect}, Data: make([]float32, 3), Stride: 2}, "3 floats of data for 2"},
|
||||
{backdrop, shader.Instances{Rects: []ui.Rect{rect}}, "reading its backdrop"},
|
||||
{s, shader.Instances{Rects: many[:shader.MaxInstances], Data: make([]float32, shader.MaxInstances*16), Stride: 16}, ""},
|
||||
{s, shader.Instances{}, ""},
|
||||
} {
|
||||
var got any
|
||||
ui.NewTester(func(ctx *ui.Context) {
|
||||
ui.Box(ctx).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
defer func() { got = recover() }()
|
||||
c.s.DrawInstances(p, c.in, shader.Options{})
|
||||
})
|
||||
}, 4, 4).Image()
|
||||
switch {
|
||||
case c.want == "" && got != nil:
|
||||
t.Errorf("%d instances of %d: %v, want no panic", len(c.in.Rects), c.in.Stride, got)
|
||||
case c.want != "" && !strings.Contains(fmt.Sprint(got), c.want):
|
||||
t.Errorf("%d instances of %d: %v, want a panic saying %q", len(c.in.Rects), c.in.Stride, got, c.want)
|
||||
}
|
||||
}
|
||||
// The last of MaxInstances quads draws, its index whole.
|
||||
last := shader.MustCompile(fmt.Sprintf("package main\nfunc Fragment(dst vec4, pos vec2) vec4 { return vec4(0, step(%d, float(instanceIndex())), instanceData(0), 1) }\n", shader.MaxInstances-1))
|
||||
quads, data := many[:shader.MaxInstances], make([]float32, shader.MaxInstances)
|
||||
quads[len(quads)-1], data[len(data)-1] = ui.Rect{W: 4, H: 4}, 1
|
||||
img := ui.NewTester(func(ctx *ui.Context) {
|
||||
ui.Box(ctx).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
last.DrawInstances(p, shader.Instances{Rects: quads, Data: data, Stride: 1}, shader.Options{})
|
||||
})
|
||||
}, 4, 4).Image()
|
||||
if got := [4]uint8(img.Pix[:4]); got != [4]uint8{0, 255, 255, 255} {
|
||||
t.Errorf("the last of %d quads: %v, want cyan, its index and data", shader.MaxInstances, got)
|
||||
}
|
||||
}
|
||||
+440
@@ -0,0 +1,440 @@
|
||||
package shader
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
)
|
||||
|
||||
// testSource reads two images, one exactly and one sampled, and uniforms
|
||||
// of each kind, as the renderers must alike.
|
||||
const testSource = `package main
|
||||
|
||||
var Seed uint
|
||||
var Tint vec4
|
||||
var Count int
|
||||
var Spots [3]vec3
|
||||
var Turn mat2
|
||||
|
||||
// Bools last: Metal's take a byte each, at the end of its struct.
|
||||
var On, Off, Third bool
|
||||
|
||||
func pcg(v uint) uint {
|
||||
s := v*747796405 + 2891336453
|
||||
w := ((s >> ((s >> 28) + 4)) ^ s) * 277803737
|
||||
return (w >> 22) ^ w
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
q := Turn * (pos - rectSize()/2)
|
||||
glow := 0.0
|
||||
for i := 0; i < Count; i++ {
|
||||
d := distance(q, Spots[i].xy)
|
||||
glow += exp(-d*d/(Spots[i].z*Spots[i].z))
|
||||
}
|
||||
h := float(pcg(uint(int(pos.x/4))*0x9E3779B9^pcg(uint(int(pos.y/4))^Seed))>>8) / 16777216.0
|
||||
a := image0At(pos * pixelScale() / 2)
|
||||
b := image1Sample(pos / rectSize() * image1Size())
|
||||
c := mix(a, b, 0.5)*0.6 + Tint*clamp(glow, 0, 1)*0.3 + vec4(h*0.1)
|
||||
if On && !Off && Third {
|
||||
c.g += 0.1
|
||||
}
|
||||
return c
|
||||
}
|
||||
`
|
||||
|
||||
// testScene returns a scene of s over a gray frame at scale 2, reading a
|
||||
// gradient bitmap and a canvas of three rectangles, which differs top to
|
||||
// bottom and left to right, as a renderer keeping its rows going up must
|
||||
// show it.
|
||||
func testScene(s *Shader) *scene.Scene {
|
||||
const scale = 2
|
||||
grad := image.NewRGBA(image.Rect(0, 0, 64, 40))
|
||||
for y := range 40 {
|
||||
for x := range 64 {
|
||||
grad.Set(x, y, color.RGBA{uint8(x * 4), uint8(y * 6), 128, 255})
|
||||
}
|
||||
}
|
||||
canvas := scene.NewCanvas(20, 12)
|
||||
canvas.Scene.Ops = []scene.Op{
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{W: 10, H: 6}, Color: scene.Color{R: 220, G: 40, B: 40, A: 255}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 10, W: 10, H: 6}, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{Y: 6, W: 20, H: 6}, Color: scene.Color{R: 30, G: 160, B: 60, A: 255}},
|
||||
}
|
||||
images := [4]*scene.Image{scene.NewImage(grad), canvas}
|
||||
|
||||
r := scene.Rect{X: 8, Y: 6, W: 224, H: 108}
|
||||
words := make([]uint32, s.words)
|
||||
for i, img := range images {
|
||||
if img != nil {
|
||||
words[2*i], words[2*i+1] = math.Float32bits(float32(img.W)), math.Float32bits(float32(img.H))
|
||||
}
|
||||
}
|
||||
words[scaleWord-2], words[scaleWord-1] = math.Float32bits(r.W/scale), math.Float32bits(r.H/scale)
|
||||
words[scaleWord] = math.Float32bits(scale)
|
||||
values := map[string]any{
|
||||
"Seed": uint32(0x3fa1c2d9),
|
||||
"Tint": []float32{1, 0.8, 0.2, 1},
|
||||
"Count": 2,
|
||||
"Spots": []float32{-20, 0, 18, 25, 10, 12, 0, 0, 1},
|
||||
"Turn": []float32{0.8, 0.6, -0.6, 0.8},
|
||||
"On": true,
|
||||
"Off": false,
|
||||
"Third": true,
|
||||
}
|
||||
for name, v := range values {
|
||||
u := s.uniforms[name]
|
||||
kind := u.t.Scalar()
|
||||
if u.t.Main == shaderir.Array {
|
||||
kind = u.t.Sub[0].Scalar()
|
||||
}
|
||||
set(words[u.word:u.word+u.n], kind, name, v)
|
||||
}
|
||||
sc := &scene.Scene{Width: 240, Height: 120, Clear: scene.Color{R: 240, G: 240, B: 240, A: 255}}
|
||||
sc.Ops = append(sc.Ops, scene.Op{Kind: scene.OpEffect, Rect: r, Radii: [4]float32{16, 16, 16, 16}})
|
||||
sc.Effects = append(sc.Effects, scene.EffectOp{Effect: s.fx, Uniforms: words, Images: images})
|
||||
return sc
|
||||
}
|
||||
|
||||
// dfdySource is green where y grows downward on the screen, as the
|
||||
// position's does, and red elsewhere: GPUs differ in which way their
|
||||
// window's y goes.
|
||||
const dfdySource = `package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
if dfdy(pos.y) > 0 {
|
||||
return vec4(0, 1, 0, 1)
|
||||
}
|
||||
return vec4(1, 0, 0, 1)
|
||||
}
|
||||
`
|
||||
|
||||
// dfdyScene returns a scene of dfdySource in a canvas, and the canvas
|
||||
// shown, as renderers flip canvases: dfdy must be positive in both.
|
||||
func dfdyScene() *scene.Scene {
|
||||
s := MustCompile(dfdySource)
|
||||
words := make([]uint32, s.words)
|
||||
words[scaleWord] = math.Float32bits(1)
|
||||
canvas := scene.NewCanvas(16, 16)
|
||||
canvas.Scene.Ops = []scene.Op{{Kind: scene.OpEffect, Rect: scene.Rect{W: 16, H: 16}}}
|
||||
canvas.Scene.Effects = []scene.EffectOp{{Effect: s.fx, Uniforms: words}}
|
||||
sc := &scene.Scene{Width: 40, Height: 20}
|
||||
sc.Ops = []scene.Op{
|
||||
{Kind: scene.OpEffect, Rect: scene.Rect{W: 20, H: 20}},
|
||||
{Kind: scene.OpImage, Rect: scene.Rect{X: 22, Y: 2, W: 16, H: 16}, Image: canvas, Src: scene.Rect{W: 16, H: 16}},
|
||||
}
|
||||
sc.Effects = []scene.EffectOp{{Effect: s.fx, Uniforms: words}}
|
||||
sc.Canvases = []*scene.Image{canvas}
|
||||
return sc
|
||||
}
|
||||
|
||||
// checkDfdy checks that the window's pixel (10, 10) and the canvas's
|
||||
// (30, 10) are green, in BGRA or RGBA rows of stride bytes.
|
||||
func checkDfdy(t *testing.T, pix []byte, stride int) {
|
||||
t.Helper()
|
||||
for _, x := range []int{10, 30} {
|
||||
p := pix[10*stride+4*x:][:4]
|
||||
if p[1] < 200 || p[0] > 50 && p[2] > 50 {
|
||||
t.Errorf("pixel (%d, 10) is %v, want green: dfdy goes the wrong way", x, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// boolSource reads only bools besides the bridge's uniforms, which leaves
|
||||
// Metal's struct aligned to 8, the bools in its last bytes.
|
||||
const boolSource = `package main
|
||||
|
||||
var A, B, C bool
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
v := vec4(0, 0, 0, 1)
|
||||
if A {
|
||||
v.r = 1
|
||||
}
|
||||
if B {
|
||||
v.g = 1
|
||||
}
|
||||
if C {
|
||||
v.b = 1
|
||||
}
|
||||
return v
|
||||
}
|
||||
`
|
||||
|
||||
// boolScene returns a scene of boolSource with A, B and C true: white.
|
||||
func boolScene() *scene.Scene {
|
||||
s := MustCompile(boolSource)
|
||||
words := make([]uint32, s.words)
|
||||
words[scaleWord] = math.Float32bits(1)
|
||||
for _, name := range []string{"A", "B", "C"} {
|
||||
set(words[s.uniforms[name].word:][:1], shaderir.Bool, name, true)
|
||||
}
|
||||
sc := &scene.Scene{Width: 20, Height: 20}
|
||||
sc.Ops = []scene.Op{{Kind: scene.OpEffect, Rect: scene.Rect{W: 20, H: 20}}}
|
||||
sc.Effects = []scene.EffectOp{{Effect: s.fx, Uniforms: words}}
|
||||
return sc
|
||||
}
|
||||
|
||||
// maskedScene returns a scene of s filling mask glyphs, discs of a mask
|
||||
// atlas: a row of them, straight, and another rotated, its positions from
|
||||
// the corner of the row's box, as text and paths a shader fills.
|
||||
func maskedScene(s *Shader) *scene.Scene {
|
||||
atlas := scene.NewAtlas(1, 64, 64)
|
||||
disc := make([]byte, 16*16)
|
||||
for y := range 16 {
|
||||
for x := range 16 {
|
||||
dx, dy := float64(x)-7.5, float64(y)-7.5
|
||||
disc[y*16+x] = byte(255 * max(0, min(1, 7.5-math.Sqrt(dx*dx+dy*dy))))
|
||||
}
|
||||
}
|
||||
u, v, _ := atlas.Alloc(16, 16)
|
||||
atlas.Put(u, v, 16, 16, disc, 16)
|
||||
sc := &scene.Scene{Width: 240, Height: 120, Clear: scene.Color{R: 240, G: 240, B: 240, A: 255}, MaskAtlas: atlas,
|
||||
Text: scene.TextParams{GammaRatios: scene.GammaRatios(1.8), Contrast: 1}}
|
||||
words := make([]uint32, s.words)
|
||||
words[scaleWord-2], words[scaleWord-1] = math.Float32bits(200), math.Float32bits(16)
|
||||
words[scaleWord] = math.Float32bits(1)
|
||||
rotate := scene.Affine{Set: true, A: 0.94, B: 0.34, C: -0.34, D: 0.94, X: 40, Y: 50}
|
||||
for row, m := range []scene.Affine{{}, rotate} {
|
||||
start := int32(len(sc.Glyphs))
|
||||
for i := range 12 {
|
||||
sc.Glyphs = append(sc.Glyphs, scene.Glyph{X: 10 + float32(i*17), Y: 10 + float32(row*20), W: 16, H: 16,
|
||||
U: uint16(u), V: uint16(v), UW: 16, VH: 16, Color: scene.Color{R: 255, G: 255, B: 255, A: 255}})
|
||||
}
|
||||
sc.Ops = append(sc.Ops, scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{X: 10, Y: 10 + float32(row*20), W: 220, H: 17},
|
||||
Transform: m, Start: int32(len(sc.Effects))})
|
||||
sc.Effects = append(sc.Effects, scene.EffectOp{Effect: s.fx, Uniforms: words,
|
||||
Glyphs: [2]int32{start, int32(len(sc.Glyphs))}, Origin: [2]float32{10, 10 + float32(row*20)}})
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
// maskedSource colors by position, across the box it fills.
|
||||
const maskedSource = `package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
t := clamp(pos.x/rectSize().x, 0, 1)
|
||||
return vec4(1-t, 0.3*(pos.y/16), t, 1)
|
||||
}
|
||||
`
|
||||
|
||||
// effectSource moves its content in a wave, and tints it by position.
|
||||
const effectSource = `package main
|
||||
|
||||
func DistortionEffect(pos vec2) vec2 {
|
||||
return pos + vec2(3*sin(pos.y/5), 4*sin(pos.x/9))
|
||||
}
|
||||
`
|
||||
|
||||
// effectScene returns a scene of s, an effect's shader, drawing content
|
||||
// of three rectangles in a canvas, the effect's box inset in it by 6
|
||||
// pixels, as Element.Effect draws an element.
|
||||
func effectScene(s *Shader) *scene.Scene { return effectSceneIn(s, 112, 52) }
|
||||
|
||||
// effectScenes are effectScene's, and the same content in the corner of
|
||||
// a larger canvas, as Element.Effect keeps one as the element's size
|
||||
// changes: what the larger canvas holds beyond the content's 112×52
|
||||
// pixels, an opaque square, reads as transparent, and draws nothing.
|
||||
func effectScenes(s *Shader) map[string]*scene.Scene {
|
||||
return map[string]*scene.Scene{"exact": effectSceneIn(s, 112, 52), "larger canvas": effectSceneIn(s, 176, 64)}
|
||||
}
|
||||
|
||||
// effectSceneIn is effectScene with a canvas of w×h pixels, of which the
|
||||
// content is the top left 112×52.
|
||||
func effectSceneIn(s *Shader, w, h int) *scene.Scene {
|
||||
content := scene.NewCanvas(w, h)
|
||||
if w > 112 {
|
||||
content.Scene.Ops = append(content.Scene.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 112, Y: 0, W: float32(w - 112), H: float32(h)}, Color: scene.Color{R: 255, A: 255}})
|
||||
}
|
||||
content.Scene.Ops = append(content.Scene.Ops, []scene.Op{
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 6, Y: 6, W: 50, H: 20}, Color: scene.Color{R: 220, G: 40, B: 40, A: 255}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 56, Y: 6, W: 50, H: 20}, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}, Radii: [4]float32{8, 8, 8, 8}},
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: 6, Y: 26, W: 100, H: 20}, Color: scene.Color{R: 30, G: 160, B: 60, A: 200}},
|
||||
}...)
|
||||
words := make([]uint32, s.words)
|
||||
words[2*shader.LayerImage], words[2*shader.LayerImage+1] = math.Float32bits(112), math.Float32bits(52)
|
||||
words[scaleWord-2], words[scaleWord-1] = math.Float32bits(100), math.Float32bits(40)
|
||||
words[scaleWord] = math.Float32bits(1)
|
||||
words[insetWord], words[insetWord+1] = math.Float32bits(6), math.Float32bits(6)
|
||||
sc := &scene.Scene{Width: 240, Height: 120, Clear: scene.Color{R: 240, G: 240, B: 240, A: 255}}
|
||||
sc.Ops = append(sc.Ops, scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{X: 20, Y: 30, W: 112, H: 52}})
|
||||
var images [4]*scene.Image
|
||||
images[shader.LayerImage] = content
|
||||
sc.Effects = append(sc.Effects, scene.EffectOp{Effect: s.fx, Uniforms: words, Images: images})
|
||||
return sc
|
||||
}
|
||||
|
||||
// backdropSource inverts what is behind it, and dims it toward the right.
|
||||
const backdropSource = `package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
b := backdropSample(pos + vec2(0, 3*sin(pos.x/8)))
|
||||
k := 1 - 0.5*pos.x/rectSize().x
|
||||
return vec4((b.a-b.rgb)*k, b.a)
|
||||
}
|
||||
`
|
||||
|
||||
// backdropScene returns a scene of s over stripes, reading its backdrop
|
||||
// blurred by blur pixels, its op under m, with the bridge's words as
|
||||
// Painter.EffectBackdrop sets them at scale 1.
|
||||
func backdropScene(s *Shader, blur float32, m scene.Affine) *scene.Scene {
|
||||
return backdropSceneIn(s, blur, m, scene.Rect{X: 40, Y: 30, W: 150, H: 60}, 240, 120)
|
||||
}
|
||||
|
||||
// backdropSceneIn is backdropScene with the shader filling r, in a frame
|
||||
// of w×h pixels, of which the stripes take the top left 240×120: a
|
||||
// larger frame holds an opaque square beyond them, and says they are what
|
||||
// is drawn (Scene.Drawn), as an effect's layer larger than its content.
|
||||
func backdropSceneIn(s *Shader, blur float32, m scene.Affine, r scene.Rect, w, h int) *scene.Scene {
|
||||
sc := &scene.Scene{Width: w, Height: h, Clear: scene.Color{R: 250, G: 250, B: 250, A: 255}}
|
||||
if w > 240 || h > 120 {
|
||||
sc.Drawn = image.Pt(240, 120)
|
||||
sc.Ops = append(sc.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 240, W: float32(w - 240), H: float32(h)}, Color: scene.Color{R: 255, A: 255}})
|
||||
}
|
||||
for i := range 12 {
|
||||
c := scene.Color{R: uint8(40 + 18*i), G: uint8(200 - 15*i), B: 90, A: 255}
|
||||
sc.Ops = append(sc.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i * 20), Y: 0, W: 10, H: 120}, Color: c})
|
||||
}
|
||||
bk := sc.BackdropOf(m.Bounds(r), blur, sc.Width, sc.Height)
|
||||
tw, th := bk.Size()
|
||||
words := make([]uint32, s.words)
|
||||
f := func(i int, v float32) { words[i] = math.Float32bits(v) }
|
||||
f(2*shader.BackdropImage, float32(tw))
|
||||
f(2*shader.BackdropImage+1, float32(th))
|
||||
f(scaleWord-2, r.W)
|
||||
f(scaleWord-1, r.H)
|
||||
f(scaleWord, 1)
|
||||
a, b, c, d, x, y := float32(1), float32(0), float32(0), float32(1), float32(0), float32(0)
|
||||
if m.Set {
|
||||
a, b, c, d, x, y = m.A, m.B, m.C, m.D, m.X, m.Y
|
||||
}
|
||||
for k, v := range [3]float32{a, c, a*r.X + c*r.Y + x} {
|
||||
f(row0Word+k, v)
|
||||
}
|
||||
for k, v := range [3]float32{b, d, b*r.X + d*r.Y + y} {
|
||||
f(row1Word+k, v)
|
||||
}
|
||||
f(areaWord, float32(bk.Area.Min.X))
|
||||
f(areaWord+1, float32(bk.Area.Min.Y))
|
||||
f(areaWord+2, float32(bk.Down))
|
||||
sc.Ops = append(sc.Ops, scene.Op{Kind: scene.OpEffect, Rect: r, Radii: [4]float32{12, 12, 12, 12}, Transform: m, Start: int32(len(sc.Effects))})
|
||||
sc.Effects = append(sc.Effects, scene.EffectOp{Effect: s.fx, Uniforms: words, Blur: blur})
|
||||
return sc
|
||||
}
|
||||
|
||||
// backdropCases are the backdrops the GPU tests draw: sharp, blurred, and
|
||||
// under a rotation.
|
||||
func backdropCases() map[string]*scene.Scene {
|
||||
s := MustCompile(backdropSource)
|
||||
rotate := scene.Translation(115, 60).Mul(scene.Rotation(12)).Mul(scene.Translation(-115, -60))
|
||||
return map[string]*scene.Scene{"sharp": backdropScene(s, 0, scene.Affine{}), "blurred": backdropScene(s, 6, scene.Affine{}), "rotated": backdropScene(s, 3, rotate)}
|
||||
}
|
||||
|
||||
// TestEffectLargerCanvas checks that an effect drawn from the corner of a
|
||||
// larger canvas draws as from a canvas of the content's size: what the
|
||||
// canvas holds beyond the content does not show.
|
||||
func TestEffectLargerCanvas(t *testing.T) {
|
||||
s := MustCompile(effectSource)
|
||||
render := func(sc *scene.Scene) *raster.Image {
|
||||
img := raster.NewImage(sc.Width, sc.Height)
|
||||
raster.Render(img, sc)
|
||||
return img
|
||||
}
|
||||
exact, larger := render(effectSceneIn(s, 112, 52)), render(effectSceneIn(s, 176, 64))
|
||||
if !bytes.Equal(exact.Pix, larger.Pix) {
|
||||
t.Error("an effect from a larger canvas draws otherwise")
|
||||
}
|
||||
}
|
||||
|
||||
// edgeBackdrops are a backdrop at the right edge of the stripes, sharp and
|
||||
// blurred, in a frame of their size and in a larger one that holds an
|
||||
// opaque square beyond them, which the backdrop reads as beyond the frame.
|
||||
func edgeBackdrops() map[string][2]*scene.Scene {
|
||||
s := MustCompile(backdropSource)
|
||||
r := scene.Rect{X: 150, Y: 30, W: 90, H: 60}
|
||||
out := map[string][2]*scene.Scene{}
|
||||
for name, blur := range map[string]float32{"sharp": 0, "blurred": 6} {
|
||||
out[name] = [2]*scene.Scene{backdropSceneIn(s, blur, scene.Affine{}, r, 240, 120), backdropSceneIn(s, blur, scene.Affine{}, r, 304, 128)}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TestBackdropEndsAtDrawn checks that a backdrop in a frame larger than
|
||||
// what it draws (Scene.Drawn) ends at the edge of that, as in a frame of
|
||||
// its size: what lies beyond does not show through.
|
||||
func TestBackdropEndsAtDrawn(t *testing.T) {
|
||||
for name, scs := range edgeBackdrops() {
|
||||
exact, larger := raster.NewImage(240, 120), raster.NewImage(304, 128)
|
||||
raster.Render(exact, scs[0])
|
||||
raster.Render(larger, scs[1])
|
||||
for y := range 120 {
|
||||
if !bytes.Equal(exact.Pix[y*exact.Stride:][:4*240], larger.Pix[y*larger.Stride:][:4*240]) {
|
||||
t.Errorf("%s: row %d differs in the larger frame", name, y)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// instancesSource draws a quad of those one draw draws (DrawInstances)
|
||||
// from its data: a color, rings as many as its fifth float around its
|
||||
// center, lighter the later it is drawn. The rings shade smoothly: a hard
|
||||
// edge would flip pixels where the GPU's floats round apart from the
|
||||
// CPU's.
|
||||
const instancesSource = `package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
c := vec4(instanceData(0), instanceData(1), instanceData(2), instanceData(3))
|
||||
d := length(pos - rectSize()/2) / length(rectSize()/2)
|
||||
ring := 0.8 + 0.2*cos(6.2831853*d*instanceData(4))
|
||||
k := float(instanceIndex()) / 10
|
||||
return vec4(mix(c.rgb*ring, vec3(1), 0.3*k), 1) * c.a
|
||||
}
|
||||
`
|
||||
|
||||
// instancesScene returns a scene of s drawing quads in one draw
|
||||
// (DrawInstances) at scale 2, overlapping: a row as it is, rounded, and
|
||||
// one rotated and faded. It has the renderers draw such quads, as painting
|
||||
// them does.
|
||||
func instancesScene(s *Shader) *scene.Scene {
|
||||
gpu.EnableInstances()
|
||||
raster.EnableInstances()
|
||||
const scale = 2
|
||||
words := make([]uint32, s.words)
|
||||
words[scaleWord] = math.Float32bits(scale)
|
||||
sc := &scene.Scene{Width: 240, Height: 120, Clear: scene.Color{R: 240, G: 240, B: 240, A: 255}}
|
||||
rotate := scene.Affine{Set: true, A: 0.99, B: 0.12, C: -0.12, D: 0.99, X: 8, Y: -12}
|
||||
for row, m := range []scene.Affine{{}, rotate} {
|
||||
const stride = 5
|
||||
var quads []uint32
|
||||
var bounds scene.Rect
|
||||
for i := range 10 {
|
||||
q := scene.Rect{X: 6 + float32(i*21), Y: 6 + float32(row*50), W: 34, H: 40}
|
||||
k := float32(i) / 9
|
||||
for _, v := range []float32{q.X, q.Y, q.W, q.H, q.W / scale, q.H / scale, k, 1 - k, 0.4, 1 - 0.05*float32(row), 2 + float32(i)} {
|
||||
quads = append(quads, math.Float32bits(v))
|
||||
}
|
||||
if i == 0 {
|
||||
bounds = q
|
||||
}
|
||||
bounds.W = q.X + q.W - bounds.X
|
||||
}
|
||||
op := scene.Op{Kind: scene.OpEffect, Rect: bounds, Transform: m, Start: int32(len(sc.Effects))}
|
||||
if row == 0 {
|
||||
op.Radii = [4]float32{8, 8, 8, 8}
|
||||
} else {
|
||||
op.Opacity = 0.8
|
||||
}
|
||||
sc.Ops = append(sc.Ops, op)
|
||||
sc.Effects = append(sc.Effects, scene.EffectOp{Effect: s.fx, Uniforms: words, Instances: quads, InstanceWords: scene.InstanceHead + stride})
|
||||
}
|
||||
return sc
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package shader
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Uniforms take numbers of any of Go's kinds, alone, in slices and in
|
||||
// arrays, and integers keep their low 32 bits.
|
||||
func TestSet(t *testing.T) {
|
||||
f := math.Float32bits
|
||||
for _, c := range []struct {
|
||||
kind shaderir.BasicType
|
||||
n int
|
||||
v any
|
||||
want []uint32
|
||||
}{
|
||||
{shaderir.Float, 9, [9]float32{1, 2, 3, 4, 5, 6, 7, 8, 9}, []uint32{f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9)}},
|
||||
{shaderir.Float, 4, [4]float64{0.5, 1, 2, 3}, []uint32{f(0.5), f(1), f(2), f(3)}},
|
||||
{shaderir.Int, 2, [2]int{-1, 7}, []uint32{0xFFFFFFFF, 7}},
|
||||
{shaderir.Uint, 1, int64(-1), []uint32{0xFFFFFFFF}},
|
||||
{shaderir.Uint, 1, uint32(0x9E3779B9), []uint32{0x9E3779B9}},
|
||||
{shaderir.Int, 1, uint32(0xFFFFFFFF), []uint32{0xFFFFFFFF}},
|
||||
{shaderir.Bool, 3, []bool{true, false, true}, []uint32{1, 0, 1}},
|
||||
{shaderir.Uint, 2, []uint8{3, 255}, []uint32{3, 255}},
|
||||
{shaderir.Float, 1, 3, []uint32{f(3)}},
|
||||
{shaderir.Float, 4, ui.Color{R: 255, A: 255}, []uint32{f(1), 0, 0, f(1)}},
|
||||
} {
|
||||
lanes := make([]uint32, c.n)
|
||||
set(lanes, c.kind, "X", c.v)
|
||||
for i := range c.want {
|
||||
if lanes[i] != c.want[i] {
|
||||
t.Errorf("%T %v: lanes %#x, want %#x", c.v, c.v, lanes, c.want)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("a string set a uniform")
|
||||
}
|
||||
}()
|
||||
set(make([]uint32, 1), shaderir.Float, "X", "1")
|
||||
}
|
||||
Vendored
+639
@@ -0,0 +1,639 @@
|
||||
// Package shader draws with shaders an app writes: fragment shaders in
|
||||
// Go's syntax, which run on the GPU, whichever renderer draws the window
|
||||
// (Metal, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can.
|
||||
//
|
||||
// A shader is a Go file of package main whose function Fragment returns
|
||||
// the color of a pixel, premultiplied, from its position:
|
||||
//
|
||||
// package main
|
||||
//
|
||||
// var Time float
|
||||
//
|
||||
// func Fragment(dst vec4, pos vec2) vec4 {
|
||||
// v := 0.5 + 0.5*sin(pos.x/20+Time)
|
||||
// return vec4(v, v, 1, 1)
|
||||
// }
|
||||
//
|
||||
// dst is the pixel's center in pixels of the window (or the canvas drawn
|
||||
// into), and pos the same point in DIPs from the top left corner of the
|
||||
// rectangle the shader fills. The language is Ebitengine's Kage, whose
|
||||
// compiler MyGo's is forked from: Go's syntax with the types bool, int,
|
||||
// uint, float, vec2 to vec4, ivec2 to ivec4, uvec2 to uvec4, mat2 to mat4
|
||||
// and arrays of them, GLSL's built-in functions (sin, mix, smoothstep,
|
||||
// dot, ...), functions of its own, if, and for loops. Exported variables
|
||||
// at the package level are uniforms, which Options.Uniforms sets by name,
|
||||
// or Values by variables looked up once (Shader.Uniform).
|
||||
//
|
||||
// A shader reads up to four images, bitmaps or canvases (ui.Canvas),
|
||||
// through these functions, in the images' pixels from their top left
|
||||
// corners:
|
||||
//
|
||||
// image0At(p vec2) vec4 // the pixel at p, transparent outside
|
||||
// image0Sample(p vec2) vec4 // blended between the pixels around p
|
||||
// image0Size() vec2 // the size in pixels
|
||||
//
|
||||
// and image1At to image3At and so on. rectSize returns the size of the
|
||||
// rectangle the shader fills, in DIPs, and pixelScale the pixels a DIP.
|
||||
//
|
||||
// A shader that draws into a canvas makes the input of another, as the
|
||||
// passes of an effect: one computes a field into a small canvas, the next
|
||||
// reads it to draw the window.
|
||||
//
|
||||
// DrawInstances draws many quads in one call, as node editors, strokes,
|
||||
// notes and particles need: each a rectangle with up to 16 floats of its
|
||||
// own, which its shader reads with these, 0 for Draw:
|
||||
//
|
||||
// instanceIndex() int // the quad's index among those drawn
|
||||
// instanceData(i int) float // float i of the quad's own
|
||||
package shader
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"math"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/interp"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Shader is a compiled shader, which draws in any window, from any
|
||||
// goroutine's views.
|
||||
type Shader struct {
|
||||
prog *interp.Program
|
||||
fx *scene.Effect
|
||||
uniforms map[string]uniform
|
||||
words int
|
||||
kind kind
|
||||
backdrop bool // it reads its backdrop
|
||||
}
|
||||
|
||||
// kind is what a shader draws, by its entry point.
|
||||
type kind uint8
|
||||
|
||||
const (
|
||||
fragment kind = iota // Fragment: a fill
|
||||
colorEffect
|
||||
distortionEffect
|
||||
layerEffect
|
||||
)
|
||||
|
||||
// entries are the entry points of the kinds, and the Fragment that calls
|
||||
// an effect's, from its content (layerAt, layerSample).
|
||||
var entries = [...]struct{ name, wrap string }{
|
||||
fragment: {"Fragment", ""},
|
||||
colorEffect: {"ColorEffect", "return ColorEffect(q, layerAt(q))"},
|
||||
distortionEffect: {"DistortionEffect", "return layerSample(DistortionEffect(q))"},
|
||||
layerEffect: {"LayerEffect", "return LayerEffect(q)"},
|
||||
}
|
||||
|
||||
// uniform is a uniform variable of a shader: its type, and its lanes in
|
||||
// the words of the uniforms.
|
||||
type uniform struct {
|
||||
t shaderir.Type
|
||||
word, n int
|
||||
}
|
||||
|
||||
// The bridge's uniforms, which Draw sets: the images' sizes, the
|
||||
// rectangle's size, the pixels a DIP, where an effect's box lies in its
|
||||
// content, its backdrop, and the instance drawn, which renderers set for
|
||||
// each instance (DrawInstances), the first words.
|
||||
var bridge = []string{shader.ImageSizesUniform, shader.RectSizeUniform, shader.ScaleUniform, shader.LayerInsetUniform,
|
||||
shader.BackdropRow0Uniform, shader.BackdropRow1Uniform, shader.BackdropAreaUniform, shader.InstanceUniform}
|
||||
|
||||
// The words of the bridge's uniforms, which Compile checks.
|
||||
const (
|
||||
scaleWord = 2*shader.MaxImages + 2
|
||||
insetWord = scaleWord + 1
|
||||
row0Word = insetWord + 2
|
||||
row1Word = row0Word + 3
|
||||
areaWord = row1Word + 3
|
||||
instanceWord = areaWord + 4
|
||||
bridgeWords = instanceWord + 4*(shader.MaxInstanceData/4+1)
|
||||
)
|
||||
|
||||
// bridgeWordsAt are where the bridge's uniforms start, in its order.
|
||||
var bridgeWordsAt = []int{0, scaleWord - 2, scaleWord, insetWord, row0Word, row1Word, areaWord, instanceWord}
|
||||
|
||||
// readsBackdrop finds a shader reading its backdrop.
|
||||
var readsBackdrop = regexp.MustCompile(`\bbackdrop(At|Sample)\b`)
|
||||
|
||||
// backdropImage reads a shader's backdrop, which its own images leave
|
||||
// free.
|
||||
var backdropImage = regexp.MustCompile(`\bimage` + fmt.Sprint(shader.BackdropImage) + `(At|Sample|Size)\b`)
|
||||
|
||||
// layerImage reads an effect's content, which its own images leave free.
|
||||
var layerImage = regexp.MustCompile(`\bimage` + fmt.Sprint(shader.LayerImage) + `(At|Sample|Size)\b`)
|
||||
|
||||
// kindOf returns the kind of the shader of src by its entry point, of
|
||||
// which it must have one.
|
||||
func kindOf(src string) (kind, error) {
|
||||
f, err := parser.ParseFile(token.NewFileSet(), "", src, parser.SkipObjectResolution)
|
||||
if err != nil {
|
||||
return 0, nil // Compile reports it
|
||||
}
|
||||
var found []kind
|
||||
for _, d := range f.Decls {
|
||||
if fn, ok := d.(*ast.FuncDecl); ok && fn.Recv == nil {
|
||||
for k, e := range entries {
|
||||
if fn.Name.Name == e.name {
|
||||
found = append(found, kind(k))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(found) == 0:
|
||||
return 0, nil // Compile reports the missing Fragment
|
||||
case len(found) > 1:
|
||||
return 0, fmt.Errorf("shader: %s and %s: a shader has one entry point", entries[found[0]].name, entries[found[1]].name)
|
||||
}
|
||||
k := found[0]
|
||||
if k != fragment && layerImage.MatchString(src) {
|
||||
return 0, fmt.Errorf("shader: an effect's shader reads image0 to image%d: image%d is its content (layerAt, layerSample)", shader.LayerImage-1, shader.LayerImage)
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// Compile compiles a shader, src the source of a Go file as the package's
|
||||
// documentation describes. It reports the errors of the source with their
|
||||
// lines.
|
||||
func Compile(src string) (*Shader, error) {
|
||||
k, err := kindOf(src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
full := src
|
||||
if k != fragment {
|
||||
// An effect's entry point, called with the content.
|
||||
// An effect draws over all of its content, its positions from the
|
||||
// corner of the element's box within it.
|
||||
full += "\nfunc Fragment(dst vec4, pos vec2) vec4 {\n\tq := pos - " + shader.LayerInsetUniform + "/pixelScale()\n\t" + entries[k].wrap + "\n}\n"
|
||||
}
|
||||
p, err := shader.CompileFragment([]byte(full))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i, name := range bridge {
|
||||
if i >= len(p.UniformNames) || p.UniformNames[i] != name {
|
||||
return nil, fmt.Errorf("shader: the uniforms start with %v, not %v", p.UniformNames, bridge)
|
||||
}
|
||||
}
|
||||
backdrop := readsBackdrop.MatchString(src)
|
||||
if backdrop && backdropImage.MatchString(src) {
|
||||
return nil, fmt.Errorf("shader: a shader reading its backdrop reads image%d no more: it holds the backdrop (backdropAt, backdropSample)", shader.BackdropImage)
|
||||
}
|
||||
prog, err := interp.New(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &Shader{prog: prog, uniforms: map[string]uniform{}, kind: k, backdrop: backdrop}
|
||||
for i, n := range interp.UniformWords(p) {
|
||||
if i < len(bridgeWordsAt) && s.words != bridgeWordsAt[i] {
|
||||
return nil, fmt.Errorf("shader: the bridge's %s at word %d, not %d", p.UniformNames[i], s.words, bridgeWordsAt[i])
|
||||
}
|
||||
s.uniforms[p.UniformNames[i]] = uniform{t: p.Uniforms[i], word: s.words, n: n}
|
||||
s.words += n
|
||||
}
|
||||
s.fx = &scene.Effect{Name: "shader", Backdrop: backdrop, Pixels: func() scene.EffectPixels { return &pixels{prog: prog, backdrop: backdrop} }}
|
||||
lanes, size := code(p, s.fx)
|
||||
l := &scene.ShaderLayout{Size: size}
|
||||
for _, at := range lanes {
|
||||
l.Lanes = append(l.Lanes, int32(at))
|
||||
}
|
||||
s.fx.Shader = l
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// MustCompile is Compile for a shader known to compile, as a package's
|
||||
// variable: it panics when it does not.
|
||||
func MustCompile(src string) *Shader {
|
||||
s, err := Compile(src)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Options are what a shader draws with.
|
||||
type Options struct {
|
||||
// Uniforms are the values of the shader's uniform variables, by name:
|
||||
// a number of any of Go's kinds (bool, an integer, a float) for one of
|
||||
// a scalar type, or a slice or an array of numbers, or a ui.Color (its
|
||||
// components from 0 to 1, not premultiplied), for a vector, a matrix
|
||||
// (by columns) or an array (elements in order); a variable missing is
|
||||
// zero, and a name the shader has not is left out. Integers set ints
|
||||
// and uints by their low 32 bits, as Go converts them.
|
||||
Uniforms map[string]any
|
||||
// Values, unless nil, are values of the shader's uniform variables set
|
||||
// by Uniform (Shader.NewValues), with no map and no conversions each
|
||||
// frame; Uniforms then sets the variables it names over them.
|
||||
Values *Values
|
||||
// Images are the images image0 to image3 read: bitmaps, or canvases'
|
||||
// (ui.Canvas.Bitmap); nil for none, which reads as transparent.
|
||||
Images [4]*ui.Bitmap
|
||||
// Radius rounds the corners of the rectangle, in DIPs.
|
||||
Radius float32
|
||||
// MaxSampleOffset is how far, at most, across and down in DIPs, an
|
||||
// effect (Effect) reads its content away from the pixel it draws, as
|
||||
// a distortion moves pixels: the content renders that much beyond the
|
||||
// element's box, as its shadows, the effect draws over all of it, and
|
||||
// it reads as transparent further away.
|
||||
MaxSampleOffset ui.Point
|
||||
// BackdropBlur, for a shader reading its backdrop (backdropAt,
|
||||
// backdropSample), is the standard deviation of the backdrop's blur,
|
||||
// in DIPs, 0 for none.
|
||||
BackdropBlur float32
|
||||
}
|
||||
|
||||
// Draw fills r with the shader, in DIPs of p, as p's other drawings are:
|
||||
// clipped, transformed and faded with the painter.
|
||||
func (s *Shader) Draw(p *ui.Painter, r ui.Rect, o Options) {
|
||||
s.must(fragment)
|
||||
p.ShaderEffect(s.fx, r, o.Radius, s.input(p, r, r, o, ui.Point{}))
|
||||
}
|
||||
|
||||
// MaxInstanceStride is how many floats of its own an instance gives its
|
||||
// shader at most (Instances.Stride), and MaxInstances how many instances
|
||||
// one DrawInstances draws at most.
|
||||
const (
|
||||
MaxInstanceStride = shader.MaxInstanceData
|
||||
MaxInstances = 1 << 16
|
||||
)
|
||||
|
||||
// Instances are the quads DrawInstances draws: Rects[i], in DIPs, with
|
||||
// Data[i*Stride:(i+1)*Stride], the floats instance i gives its shader
|
||||
// (instanceData), Stride from 0 to MaxInstanceStride.
|
||||
type Instances struct {
|
||||
Rects []ui.Rect
|
||||
Data []float32
|
||||
Stride int
|
||||
}
|
||||
|
||||
// DrawInstances draws many quads with the shader in one call: each of
|
||||
// in.Rects as Draw fills a rectangle alone, pos from its corner and
|
||||
// rectSize its size, with in.Stride floats of its own, which the shader
|
||||
// reads with instanceData(i), and its index among them, instanceIndex().
|
||||
// The GPU's renderers draw them all with one instanced draw; the CPU's
|
||||
// draws each as Draw would. o applies to every quad, Radius rounding each.
|
||||
// It panics for more than MaxInstances quads, a Stride beyond
|
||||
// MaxInstanceStride, Data of another length than len(in.Rects)*Stride, or
|
||||
// a shader reading its backdrop, which draws one rectangle (Draw).
|
||||
func (s *Shader) DrawInstances(p *ui.Painter, in Instances, o Options) {
|
||||
s.must(fragment)
|
||||
switch {
|
||||
case s.backdrop:
|
||||
panic("shader: a shader reading its backdrop draws one rectangle (Draw), not instances")
|
||||
case in.Stride < 0 || in.Stride > MaxInstanceStride:
|
||||
panic(fmt.Sprintf("shader: an instance's stride is %d floats, not from 0 to %d", in.Stride, MaxInstanceStride))
|
||||
case len(in.Rects) > MaxInstances:
|
||||
panic(fmt.Sprintf("shader: %d instances in one draw, beyond %d", len(in.Rects), MaxInstances))
|
||||
case len(in.Data) != len(in.Rects)*in.Stride:
|
||||
panic(fmt.Sprintf("shader: %d floats of data for %d instances of %d", len(in.Data), len(in.Rects), in.Stride))
|
||||
case len(in.Rects) == 0:
|
||||
return
|
||||
}
|
||||
p.ShaderInstances(s.fx, in.Rects, in.Data, in.Stride, o.Radius, s.input(p, ui.Rect{}, ui.Rect{}, o, ui.Point{}))
|
||||
}
|
||||
|
||||
// Fill paints the text, paths and icons that fn paints with p with the
|
||||
// shader in place of their colors, as a gradient fills them: each pixel
|
||||
// the shader's color times the shape's coverage, the shader filling box,
|
||||
// in DIPs, whose corner its positions start from and whose size rectSize
|
||||
// returns. Emoji keep their colors, and the rest fn paints, as rectangles
|
||||
// and images, paints as it would. Options.Radius does not apply.
|
||||
func (s *Shader) Fill(p *ui.Painter, box ui.Rect, o Options, fn func()) {
|
||||
s.must(fragment)
|
||||
if s.backdrop {
|
||||
panic("shader: a shader reading its backdrop fills rectangles (Draw), not shapes (Fill)")
|
||||
}
|
||||
p.ShaderFill(s.fx, box, s.input(p, box, box, o, ui.Point{}), fn)
|
||||
}
|
||||
|
||||
// FillPath fills path with the shader (non-zero winding), the shader
|
||||
// filling the path's box (Path.Bounds).
|
||||
func (s *Shader) FillPath(p *ui.Painter, path *ui.Path, o Options) {
|
||||
s.Fill(p, path.Bounds(), o, func() { p.FillPath(path, white) })
|
||||
}
|
||||
|
||||
// StrokePath strokes the outline of path with the shader, width DIPs
|
||||
// wide, with round joins and caps, the shader filling the path's box
|
||||
// (Path.Bounds) grown by half the width.
|
||||
func (s *Shader) StrokePath(p *ui.Painter, path *ui.Path, width float32, o Options) {
|
||||
b := path.Bounds()
|
||||
h := width / 2
|
||||
s.Fill(p, ui.Rect{X: b.X - h, Y: b.Y - h, W: b.W + width, H: b.H + width}, o, func() { p.StrokePath(path, width, white) })
|
||||
}
|
||||
|
||||
// Text draws a line of text with its top-left corner at (x, y), size DIPs
|
||||
// tall, filled with the shader, which fills the text's box.
|
||||
func (s *Shader) Text(p *ui.Painter, x, y float32, text string, size float32, o Options) {
|
||||
w, h := p.MeasureText(0, ui.Span{Text: text, Size: size})
|
||||
s.Fill(p, ui.Rect{X: x, Y: y, W: w, H: h}, o, func() { p.Text(x, y, text, size, white) })
|
||||
}
|
||||
|
||||
// Effect returns the shader drawing an element with o, for
|
||||
// ui.Element.Effect: the shader of an effect, whose entry point reads the
|
||||
// element's content, rendered with its children, in DIPs from the corner
|
||||
// of its box, as SwiftUI's effects do:
|
||||
//
|
||||
// // The content's colors, changed pixel by pixel (colorEffect).
|
||||
// func ColorEffect(pos vec2, color vec4) vec4
|
||||
//
|
||||
// // Where to read the content for the pixel at pos (distortionEffect),
|
||||
// // transparent beyond it.
|
||||
// func DistortionEffect(pos vec2) vec2
|
||||
//
|
||||
// // The pixel's color, from the content read anywhere with layerAt(p),
|
||||
// // its pixel at p, or layerSample(p), blended between pixels
|
||||
// // (layerEffect).
|
||||
// func LayerEffect(pos vec2) vec4
|
||||
//
|
||||
// rectSize returns the size of the element's box. An effect's shader
|
||||
// reads images 0 to 2 of its own (image3 is the content), and moves
|
||||
// pixels at most o.MaxSampleOffset away. It panics for a shader whose
|
||||
// entry point is Fragment, which Draw and Fill draw.
|
||||
func (s *Shader) Effect(o Options) Effect {
|
||||
if s.kind == fragment {
|
||||
panic("shader: Effect of a shader of Fragment: an effect's has ColorEffect, DistortionEffect or LayerEffect")
|
||||
}
|
||||
return Effect{s: s, o: o}
|
||||
}
|
||||
|
||||
// Effect is a shader drawing an element in place of the element as it is
|
||||
// (ui.Element.Effect), as Shader.Effect returns.
|
||||
type Effect struct {
|
||||
s *Shader
|
||||
o Options
|
||||
}
|
||||
|
||||
// EffectMargin returns how far the effect reads its content beyond the
|
||||
// element's box, its MaxSampleOffset.
|
||||
func (fx Effect) EffectMargin() ui.Point { return fx.o.MaxSampleOffset }
|
||||
|
||||
// PaintEffect paints the element from its content, the box's corner at
|
||||
// inset in the content's pixels: the shader over all of the content, the
|
||||
// box and the margin around it, reading the content as its last image.
|
||||
func (fx Effect) PaintEffect(p *ui.Painter, box ui.Rect, content *ui.Bitmap, inset ui.Point) {
|
||||
if fx.s == nil || content == nil {
|
||||
return
|
||||
}
|
||||
o := fx.o
|
||||
o.Images[shader.LayerImage] = content
|
||||
s := p.Scale()
|
||||
w, h := content.Size()
|
||||
area := ui.Rect{X: box.X - inset.X/s, Y: box.Y - inset.Y/s, W: float32(w) / s, H: float32(h) / s}
|
||||
p.ShaderEffect(fx.s.fx, area, 0, fx.s.input(p, box, area, o, inset))
|
||||
}
|
||||
|
||||
// must panics unless s is a shader of kind k.
|
||||
func (s *Shader) must(k kind) {
|
||||
if s.kind != k {
|
||||
panic(fmt.Sprintf("shader: a shader of %s draws through Effect, not Draw or Fill", entries[s.kind].name))
|
||||
}
|
||||
}
|
||||
|
||||
// wideColor is a color of a uniform in extended sRGB, outside sRGB.
|
||||
type wideColor struct {
|
||||
u uniform
|
||||
c [4]float32
|
||||
}
|
||||
|
||||
// input returns what the shader reads drawn with o in r, the box it
|
||||
// fills, over area, the box's corner at inset in pixels from area's: the words of
|
||||
// the uniforms' lanes, the bridge's first, in the frame's words, and those
|
||||
// a wide gamut reads, when colors differ there.
|
||||
func (s *Shader) input(p *ui.Painter, r, area ui.Rect, o Options, inset ui.Point) ui.ShaderInput {
|
||||
words := p.EffectWords(s.words)
|
||||
if v := o.Values; v != nil {
|
||||
if v.s != s {
|
||||
panic("shader: Options.Values of another shader")
|
||||
}
|
||||
copy(words[bridgeWords:], v.words[bridgeWords:])
|
||||
}
|
||||
for i, b := range o.Images {
|
||||
if b != nil {
|
||||
w, h := b.Size()
|
||||
words[2*i], words[2*i+1] = math.Float32bits(float32(w)), math.Float32bits(float32(h))
|
||||
}
|
||||
}
|
||||
words[scaleWord-2], words[scaleWord-1] = math.Float32bits(r.W), math.Float32bits(r.H)
|
||||
words[scaleWord] = math.Float32bits(p.Scale())
|
||||
words[insetWord], words[insetWord+1] = math.Float32bits(inset.X), math.Float32bits(inset.Y)
|
||||
var blur float32
|
||||
if s.backdrop {
|
||||
blur = max(o.BackdropBlur, 0) * p.Scale()
|
||||
bk := p.EffectBackdrop(area, blur, inset)
|
||||
i := shader.BackdropImage
|
||||
words[2*i], words[2*i+1] = math.Float32bits(float32(bk.W)), math.Float32bits(float32(bk.H))
|
||||
for k, x := range bk.ToFrame[0] {
|
||||
words[row0Word+k] = math.Float32bits(x)
|
||||
}
|
||||
for k, x := range bk.ToFrame[1] {
|
||||
words[row1Word+k] = math.Float32bits(x)
|
||||
}
|
||||
words[areaWord], words[areaWord+1], words[areaWord+2] = math.Float32bits(bk.Origin[0]), math.Float32bits(bk.Origin[1]), math.Float32bits(bk.Down)
|
||||
}
|
||||
var mapColors []colorValue
|
||||
for name, v := range o.Uniforms {
|
||||
u, ok := s.uniforms[name]
|
||||
if !ok || name[0] == '_' {
|
||||
continue
|
||||
}
|
||||
if c, ok := v.(ui.Color); ok && (u.t.Main == shaderir.Vec3 || u.t.Main == shaderir.Vec4) {
|
||||
mapColors = append(mapColors, colorValue{u, c})
|
||||
continue
|
||||
}
|
||||
kind := u.t.Scalar()
|
||||
if u.t.Main == shaderir.Array {
|
||||
kind = u.t.Sub[0].Scalar()
|
||||
}
|
||||
set(words[u.word:u.word+u.n], kind, name, v)
|
||||
}
|
||||
in := ui.ShaderInput{Uniforms: words, Images: o.Images, Blur: blur}
|
||||
// Colors, in sRGB, and outside it, in extended sRGB, for a wide gamut.
|
||||
var buf [8]wideColor
|
||||
wide := buf[:0]
|
||||
var set []colorValue
|
||||
if o.Values != nil {
|
||||
set = o.Values.colors
|
||||
}
|
||||
for _, list := range [2][]colorValue{set, mapColors} {
|
||||
for _, cv := range list {
|
||||
srgb, w := p.EffectColor(cv.c)
|
||||
writeColor(words[cv.u.word:cv.u.word+cv.u.n], srgb)
|
||||
if w != srgb {
|
||||
wide = append(wide, wideColor{cv.u, w})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(wide) > 0 {
|
||||
in.WideUniforms = p.EffectWords(s.words)
|
||||
copy(in.WideUniforms, words)
|
||||
for _, x := range wide {
|
||||
writeColor(in.WideUniforms[x.u.word:x.u.word+x.u.n], x.c)
|
||||
}
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// set writes value v of uniform name into its lanes, as numbers of kind:
|
||||
// a number, a slice or an array of numbers of any of Go's kinds, or a
|
||||
// ui.Color. Integers convert to int and uint keeping their low 32 bits, as
|
||||
// Go converts them; floats drop their fraction.
|
||||
func set(lanes []uint32, kind shaderir.BasicType, name string, v any) {
|
||||
if c, ok := v.(ui.Color); ok {
|
||||
for i, x := range [4]uint8{c.R, c.G, c.B, c.A} {
|
||||
if i < len(lanes) {
|
||||
lanes[i] = lane(kind, reflect.ValueOf(float64(x)/255))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
rv := reflect.ValueOf(v)
|
||||
switch rv.Kind() {
|
||||
case reflect.Slice, reflect.Array:
|
||||
for i := 0; i < rv.Len() && i < len(lanes); i++ {
|
||||
if !number(rv.Index(i)) {
|
||||
panic(fmt.Sprintf("shader: the uniform %s is set to a %T, not numbers", name, v))
|
||||
}
|
||||
lanes[i] = lane(kind, rv.Index(i))
|
||||
}
|
||||
default:
|
||||
if !rv.IsValid() || !number(rv) {
|
||||
panic(fmt.Sprintf("shader: the uniform %s is set to a %T, not a number, numbers or a ui.Color", name, v))
|
||||
}
|
||||
if len(lanes) > 0 {
|
||||
lanes[0] = lane(kind, rv)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// number reports whether x is a bool, an integer or a float.
|
||||
func number(x reflect.Value) bool {
|
||||
switch x.Kind() {
|
||||
case reflect.Bool, reflect.Float32, reflect.Float64,
|
||||
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// lane returns the number x as a lane of kind.
|
||||
func lane(kind shaderir.BasicType, x reflect.Value) uint32 {
|
||||
var i int64
|
||||
var f float64
|
||||
switch x.Kind() {
|
||||
case reflect.Bool:
|
||||
if x.Bool() {
|
||||
i, f = 1, 1
|
||||
}
|
||||
case reflect.Float32, reflect.Float64:
|
||||
f = x.Float()
|
||||
i = int64(f)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
i, f = int64(x.Uint()), float64(x.Uint())
|
||||
default:
|
||||
i, f = x.Int(), float64(x.Int())
|
||||
}
|
||||
switch kind {
|
||||
case shaderir.Float:
|
||||
return math.Float32bits(float32(f))
|
||||
case shaderir.Bool:
|
||||
if f != 0 {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
return uint32(i)
|
||||
}
|
||||
|
||||
// pixels draws a shader on the CPU, with the interpreter.
|
||||
type pixels struct {
|
||||
prog *interp.Program
|
||||
in interp.Inputs
|
||||
rect scene.Rect
|
||||
scale float32
|
||||
// words are the uniforms' words for the quad readied, of those one
|
||||
// draw draws, what it reads of its instance among them.
|
||||
words []uint32
|
||||
// backdrop tells that the shader reads its backdrop, as its image
|
||||
// shader.BackdropImage, the texels of bd.
|
||||
backdrop bool
|
||||
bd sync.Once
|
||||
}
|
||||
|
||||
func (x *pixels) Begin(op *scene.EffectOp, rect scene.Rect, radii [4]float32) {
|
||||
x.rect = rect
|
||||
x.in.Uniforms = op.Uniforms
|
||||
x.in.Images = x.in.Images[:0]
|
||||
for _, img := range op.Images {
|
||||
if img == nil || len(img.Pixels()) < 4*img.W*img.H { // a released bitmap's come back
|
||||
x.in.Images = append(x.in.Images, nil)
|
||||
} else {
|
||||
x.in.Images = append(x.in.Images, sceneImage{img})
|
||||
}
|
||||
}
|
||||
x.bd = sync.Once{}
|
||||
x.scale = 1
|
||||
if len(op.Uniforms) > scaleWord {
|
||||
x.scale = math.Float32frombits(op.Uniforms[scaleWord])
|
||||
}
|
||||
if op.InstanceCount() > 0 && len(op.Uniforms) >= bridgeWords {
|
||||
// A quad of those one draw draws, which the renderer readies
|
||||
// alone (scene.EffectOp.Instance), as the GPU's instance holds it.
|
||||
x.words = append(x.words[:0], op.Uniforms...)
|
||||
inst := x.words[instanceWord:bridgeWords]
|
||||
clear(inst)
|
||||
copy(inst[:shader.MaxInstanceData], op.InstanceData(0))
|
||||
_, size := op.InstanceRect(0)
|
||||
for k, v := range [4]float32{float32(op.Instance), size[0], size[1], 1} {
|
||||
inst[shader.MaxInstanceData+k] = math.Float32bits(v)
|
||||
}
|
||||
x.in.Uniforms = x.words
|
||||
}
|
||||
}
|
||||
|
||||
func (x *pixels) Color(px, py float32, b *scene.BackdropImage) [4]float32 {
|
||||
if x.backdrop && b != nil {
|
||||
// The first color's backdrop, every color's, which cores ask for
|
||||
// at once.
|
||||
x.bd.Do(func() { x.in.Images[shader.BackdropImage] = backdropTexels{b} })
|
||||
}
|
||||
c, ok := x.prog.Color(&x.in, [4]float32{px, py, 0, 1}, (px-x.rect.X)/x.scale, (py-x.rect.Y)/x.scale)
|
||||
if !ok {
|
||||
return [4]float32{}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// backdropTexels are the texels of an effect's backdrop as the
|
||||
// interpreter reads them, as the GPU renderers' backdrop textures hold
|
||||
// them.
|
||||
type backdropTexels struct{ b *scene.BackdropImage }
|
||||
|
||||
func (t backdropTexels) Size() (int, int) { return t.b.W, t.b.H }
|
||||
|
||||
func (t backdropTexels) At(x, y int) [4]float32 { return [4]float32(t.b.Pix[4*(y*t.b.W+x):][:4]) }
|
||||
|
||||
// sceneImage is an image of a scene as the interpreter reads it.
|
||||
type sceneImage struct{ img *scene.Image }
|
||||
|
||||
func (s sceneImage) Size() (int, int) { return s.img.W, s.img.H }
|
||||
|
||||
func (s sceneImage) At(x, y int) [4]float32 {
|
||||
p := s.img.Pix[4*(y*s.img.W+x):][:4]
|
||||
return [4]float32{float32(p[0]) / 255, float32(p[1]) / 255, float32(p[2]) / 255, float32(p[3]) / 255}
|
||||
}
|
||||
|
||||
// white is the color the shapes a shader fills are painted with, whose
|
||||
// coverage it multiplies.
|
||||
var white = ui.Color{R: 255, G: 255, B: 255, A: 255}
|
||||
+450
@@ -0,0 +1,450 @@
|
||||
package shader_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
"github.com/egoist/mygo/ui/shader"
|
||||
)
|
||||
|
||||
// A shader fills its rectangle, rounded, with what it computes from its
|
||||
// uniforms, a position in DIPs and a bitmap; the window shows it.
|
||||
func TestDraw(t *testing.T) {
|
||||
s := shader.MustCompile(`package main
|
||||
|
||||
var Color vec4
|
||||
var Split float
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
if pos.x < Split {
|
||||
return Color
|
||||
}
|
||||
return image0At(vec2(0))
|
||||
}
|
||||
`)
|
||||
red := ui.NewBitmap(solid(2, 2, 255, 0, 0))
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
s.Draw(p, ui.Rect{X: 10, Y: 10, W: 100, H: 40}, shader.Options{
|
||||
Uniforms: map[string]any{"Color": []float32{0, 0, 1, 1}, "Split": 50, "Unknown": 1},
|
||||
Images: [4]*ui.Bitmap{red},
|
||||
Radius: 8,
|
||||
})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 100)
|
||||
tt.SetScale(2)
|
||||
img := tt.Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
if got := at(2*30, 2*30); got != [4]uint8{0, 0, 255, 255} {
|
||||
t.Errorf("left of Split: %v, want blue", got)
|
||||
}
|
||||
if got := at(2*90, 2*30); got != [4]uint8{255, 0, 0, 255} {
|
||||
t.Errorf("right of Split: %v, want the bitmap's red", got)
|
||||
}
|
||||
if got := at(2*10+1, 2*10+1); got != at(2, 2) {
|
||||
t.Errorf("the rounded corner shows %v, want the background", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A shader reads a bitmap that released its pixels (issue #664): the CPU
|
||||
// renderer decodes them again.
|
||||
func TestDrawReleasedBitmap(t *testing.T) {
|
||||
s := shader.MustCompile("package main\n\nfunc Fragment(dst vec4, pos vec2) vec4 {\n\treturn image0At(vec2(0))\n}\n")
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, solid(2, 2, 255, 0, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
red, err := ui.DecodeBitmap(buf.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
red.ReleasePixels()
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
s.Draw(p, ui.Rect{W: 40, H: 40}, shader.Options{Images: [4]*ui.Bitmap{red}})
|
||||
})
|
||||
}, 50, 50)
|
||||
img := tt.Image()
|
||||
if o := img.PixOffset(20, 20); [4]uint8(img.Pix[o:o+4]) != [4]uint8{255, 0, 0, 255} {
|
||||
t.Errorf("a released bitmap reads %v, want red", img.Pix[o:o+4])
|
||||
}
|
||||
}
|
||||
|
||||
// Compile reports where a shader is wrong; Draw panics on a uniform set to
|
||||
// a value of no number.
|
||||
func TestErrors(t *testing.T) {
|
||||
_, err := shader.Compile("package main\n\nfunc Fragment(dst vec4, pos vec2) vec4 {\n\treturn 1 + true\n}\n")
|
||||
if err == nil || !strings.Contains(err.Error(), "4:") {
|
||||
t.Errorf("error %v, want one at line 4", err)
|
||||
}
|
||||
if _, err := shader.Compile("package main\n"); err == nil {
|
||||
t.Error("a shader without Fragment compiled")
|
||||
}
|
||||
s := shader.MustCompile("package main\n\nvar X float\n\nfunc Fragment(dst vec4, pos vec2) vec4 {\n\treturn vec4(X)\n}\n")
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Error("a uniform set to a string drew")
|
||||
}
|
||||
}()
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
s.Draw(p, r, shader.Options{Uniforms: map[string]any{"X": "1"}})
|
||||
})
|
||||
}, 50, 50)
|
||||
tt.Frame()
|
||||
}
|
||||
|
||||
func solid(w, h int, r, g, b uint8) *image.RGBA {
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for i := 0; i < len(img.Pix); i += 4 {
|
||||
img.Pix[i], img.Pix[i+1], img.Pix[i+2], img.Pix[i+3] = r, g, b, 255
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
// FillPath, StrokePath and Text paint shapes with a shader in place of a
|
||||
// color, its positions across the shape's box; the rest of the window
|
||||
// keeps its own pixels.
|
||||
func TestFill(t *testing.T) {
|
||||
s := shader.MustCompile(`package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
if pos.x < rectSize().x/2 {
|
||||
return vec4(1, 0, 0, 1)
|
||||
}
|
||||
return vec4(0, 0, 1, 1)
|
||||
}
|
||||
`)
|
||||
var circle ui.Path
|
||||
circle.Circle(50, 50, 40)
|
||||
var line ui.Path
|
||||
line.MoveTo(110, 20).LineTo(190, 20)
|
||||
var textW float32
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
s.FillPath(p, &circle, shader.Options{})
|
||||
s.StrokePath(p, &line, 8, shader.Options{})
|
||||
s.Text(p, 110, 50, "MMMM", 24, shader.Options{})
|
||||
textW, _ = p.MeasureText(0, ui.Span{Text: "MMMM", Size: 24})
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 100)
|
||||
img := tt.Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
red, blue, white := [4]uint8{255, 0, 0, 255}, [4]uint8{0, 0, 255, 255}, [4]uint8{255, 255, 255, 255}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
x, y int
|
||||
want [4]uint8
|
||||
}{
|
||||
{"the circle's left", 30, 50, red},
|
||||
{"the circle's right", 70, 50, blue},
|
||||
{"outside the circle", 15, 15, white},
|
||||
{"the stroke's left", 120, 20, red},
|
||||
{"the stroke's right", 180, 20, blue},
|
||||
{"above the stroke", 150, 12, white},
|
||||
} {
|
||||
if got := at(c.x, c.y); got != c.want {
|
||||
t.Errorf("%s: %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
// The text's ink: reddish on the left of its box, bluish on the right.
|
||||
var left, right [3]int
|
||||
mid := 110 + int(textW/2)
|
||||
for y := 50; y < 85; y++ {
|
||||
for x := 110; x < 110+int(textW) && x < 200; x++ {
|
||||
p := at(x, y)
|
||||
if p == white {
|
||||
continue
|
||||
}
|
||||
if p[1] > p[0] || p[1] > p[2] {
|
||||
t.Fatalf("text at (%d, %d) is %v, not the shader's colors", x, y, p)
|
||||
}
|
||||
if x < mid-2 {
|
||||
left[0] += int(p[0]) - int(p[2])
|
||||
} else if x > mid+2 {
|
||||
right[0] += int(p[2]) - int(p[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
if left[0] <= 0 || right[0] <= 0 {
|
||||
t.Errorf("text not filled across its box: left %d, right %d", left[0], right[0])
|
||||
}
|
||||
}
|
||||
|
||||
var _ ui.Effect = shader.Effect{}
|
||||
|
||||
// Effects draw an element from its content: a ColorEffect changes its
|
||||
// colors, a DistortionEffect moves its pixels, transparent beyond what
|
||||
// renders, and a LayerEffect reads it anywhere; the window around the
|
||||
// element keeps its own pixels.
|
||||
func TestEffects(t *testing.T) {
|
||||
invert := shader.MustCompile(`package main
|
||||
|
||||
func ColorEffect(pos vec2, color vec4) vec4 {
|
||||
return vec4(color.a-color.rgb, color.a)
|
||||
}
|
||||
`)
|
||||
shift := shader.MustCompile(`package main
|
||||
|
||||
var By float
|
||||
|
||||
func DistortionEffect(pos vec2) vec2 {
|
||||
return pos - vec2(By, 0)
|
||||
}
|
||||
`)
|
||||
mirror := shader.MustCompile(`package main
|
||||
|
||||
func LayerEffect(pos vec2) vec4 {
|
||||
return layerAt(vec2(rectSize().x-pos.x, pos.y))
|
||||
}
|
||||
`)
|
||||
// A box red on its left half and green on its right.
|
||||
halves := func(c *ui.Context, fx shader.Effect) {
|
||||
ui.Row(c).Width(80).Height(40).Effect(fx).Children(func() {
|
||||
ui.Box(c).Width(40).Height(40).Background(ui.RGB(255, 0, 0))
|
||||
ui.Box(c).Width(40).Height(40).Background(ui.RGB(0, 255, 0))
|
||||
})
|
||||
}
|
||||
view := func(c *ui.Context) {
|
||||
ui.Column(c).Fill().Background(ui.RGB(255, 255, 255)).Gap(10).Padding(10).Children(func() {
|
||||
halves(c, invert.Effect(shader.Options{}))
|
||||
halves(c, shift.Effect(shader.Options{Uniforms: map[string]any{"By": 20}, MaxSampleOffset: ui.Point{X: 20}}))
|
||||
halves(c, mirror.Effect(shader.Options{}))
|
||||
})
|
||||
}
|
||||
tt := ui.NewTester(view, 200, 200)
|
||||
img := tt.Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
red, green, white := [4]uint8{255, 0, 0, 255}, [4]uint8{0, 255, 0, 255}, [4]uint8{255, 255, 255, 255}
|
||||
cyan, magenta := [4]uint8{0, 255, 255, 255}, [4]uint8{255, 0, 255, 255}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
x, y int
|
||||
want [4]uint8
|
||||
}{
|
||||
{"inverted left", 20, 30, cyan},
|
||||
{"inverted right", 70, 30, magenta},
|
||||
{"beside the inverted box", 120, 30, white},
|
||||
{"shifted: transparent where nothing moved in", 15, 80, white},
|
||||
{"shifted: red moved right", 45, 80, red},
|
||||
{"shifted: green", 75, 80, green},
|
||||
{"mirrored left", 20, 130, green},
|
||||
{"mirrored right", 70, 130, red},
|
||||
} {
|
||||
if got := at(c.x, c.y); got != c.want {
|
||||
t.Errorf("%s: %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An effect draws a transformed element as transformed: its content in
|
||||
// the element's own space, the effect over its box.
|
||||
func TestEffectTransformed(t *testing.T) {
|
||||
invert := shader.MustCompile(`package main
|
||||
|
||||
func ColorEffect(pos vec2, color vec4) vec4 {
|
||||
return vec4(color.a-color.rgb, color.a)
|
||||
}
|
||||
`)
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Padding(50).Children(func() {
|
||||
ui.Box(c).Width(100).Height(20).Background(ui.RGB(255, 0, 0)).Rotate(90).
|
||||
Effect(invert.Effect(shader.Options{}))
|
||||
})
|
||||
}
|
||||
img := ui.NewTester(view, 200, 200).Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
// Rotated about its center (100, 60): upright, 20 wide, 100 tall.
|
||||
if got := at(100, 25); got != [4]uint8{0, 255, 255, 255} {
|
||||
t.Errorf("inside the rotated box: %v, want cyan", got)
|
||||
}
|
||||
if got := at(140, 60); got != [4]uint8{255, 255, 255, 255} {
|
||||
t.Errorf("where the box was before rotating: %v, want white", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A shader has one entry point, of a kind that decides how it draws; an
|
||||
// effect's leaves image3 to its content.
|
||||
func TestKinds(t *testing.T) {
|
||||
for _, c := range []struct{ src, want string }{
|
||||
{"package main\nfunc Fragment() vec4 { return vec4(1) }\nfunc LayerEffect(pos vec2) vec4 { return vec4(1) }\n", "one entry point"},
|
||||
{"package main\nfunc LayerEffect(pos vec2) vec4 { return image3At(pos) }\n", "image3 is its content"},
|
||||
} {
|
||||
if _, err := shader.Compile(c.src); err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Errorf("Compile(%q) = %v, want an error with %q", c.src, err, c.want)
|
||||
}
|
||||
}
|
||||
effect := shader.MustCompile("package main\nfunc LayerEffect(pos vec2) vec4 { return layerAt(pos) }\n")
|
||||
fill := shader.MustCompile("package main\nfunc Fragment() vec4 { return vec4(1) }\n")
|
||||
mustPanic := func(name string, fn func()) {
|
||||
t.Helper()
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
t.Errorf("%s did not panic", name)
|
||||
}
|
||||
}()
|
||||
fn()
|
||||
}
|
||||
mustPanic("Effect of a Fragment shader", func() { fill.Effect(shader.Options{}) })
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
mustPanic("Draw of an effect's shader", func() { effect.Draw(p, r, shader.Options{}) })
|
||||
})
|
||||
}
|
||||
ui.NewTester(view, 10, 10).Image()
|
||||
}
|
||||
|
||||
// Values set uniforms by variables looked up once, which the map's names
|
||||
// then override; setters check the variable's type and shader.
|
||||
func TestValues(t *testing.T) {
|
||||
s := shader.MustCompile(`package main
|
||||
|
||||
var Left vec4
|
||||
var Right vec4
|
||||
var Split float
|
||||
var Flip bool
|
||||
var Steps [2]int
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
x := pos.x
|
||||
if Flip {
|
||||
x = rectSize().x - x
|
||||
}
|
||||
if x < Split + float(Steps[0]+Steps[1]) {
|
||||
return Left
|
||||
}
|
||||
return Right
|
||||
}
|
||||
`)
|
||||
left, right, split, flip, steps := s.Uniform("Left"), s.Uniform("Right"), s.Uniform("Split"), s.Uniform("Flip"), s.Uniform("Steps")
|
||||
v := s.NewValues().Color(left, ui.RGB(255, 0, 0)).Vec4(right, 0, 0, 1, 1).Float(split, 20).Ints(steps, 5, 5).Bool(flip, false)
|
||||
var allocs float64
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Background(ui.RGB(255, 255, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
s.Draw(p, ui.Rect{X: 0, Y: 0, W: 100, H: 20}, shader.Options{Values: v})
|
||||
s.Draw(p, ui.Rect{X: 0, Y: 30, W: 100, H: 20}, shader.Options{Values: v, Uniforms: map[string]any{"Flip": true}})
|
||||
allocs = testing.AllocsPerRun(50, func() { s.Draw(p, ui.Rect{X: 0, Y: 60, W: 100, H: 20}, shader.Options{Values: v}) })
|
||||
})
|
||||
}
|
||||
img := ui.NewTester(view, 100, 80).Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
red, blue := [4]uint8{255, 0, 0, 255}, [4]uint8{0, 0, 255, 255}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
x, y int
|
||||
want [4]uint8
|
||||
}{
|
||||
{"left of the split", 25, 10, red},
|
||||
{"right of the split", 35, 10, blue},
|
||||
{"flipped by the map", 25, 40, blue},
|
||||
{"flipped, far right", 75, 40, red},
|
||||
} {
|
||||
if got := at(c.x, c.y); got != c.want {
|
||||
t.Errorf("%s: %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
if allocs != 0 {
|
||||
t.Errorf("Draw with Values allocates %v times", allocs)
|
||||
}
|
||||
|
||||
mustPanic := func(name, want string, fn func()) {
|
||||
t.Helper()
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil || !strings.Contains(fmt.Sprint(r), want) {
|
||||
t.Errorf("%s: panicked with %v, want %q", name, r, want)
|
||||
}
|
||||
}()
|
||||
fn()
|
||||
}
|
||||
other := shader.MustCompile("package main\nvar Split float\nfunc Fragment() vec4 { return vec4(Split) }\n")
|
||||
mustPanic("unknown variable", "no uniform variable Nope", func() { s.Uniform("Nope") })
|
||||
mustPanic("bridge variable", "no uniform variable", func() { s.Uniform("__scale") })
|
||||
mustPanic("wrong type", "not a float", func() { v.Float(right, 1) })
|
||||
mustPanic("too many", "5 numbers", func() { v.Floats(right, 1, 2, 3, 4, 5) })
|
||||
mustPanic("other shader", "not a uniform variable of the values' shader", func() { v.Float(other.Uniform("Split"), 1) })
|
||||
}
|
||||
|
||||
// A shader reads what the window drew behind it, blurred as asked, from
|
||||
// Draw and from an element's effect.
|
||||
func TestBackdrop(t *testing.T) {
|
||||
invert := shader.MustCompile(`package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
b := backdropAt(pos)
|
||||
return vec4(b.a-b.rgb, b.a)
|
||||
}
|
||||
`)
|
||||
tint := shader.MustCompile(`package main
|
||||
|
||||
func ColorEffect(pos vec2, color vec4) vec4 {
|
||||
b := backdropSample(pos)
|
||||
return mix(b, color, color.a*0.5)
|
||||
}
|
||||
`)
|
||||
view := func(c *ui.Context) {
|
||||
ui.Column(c).Fill().Children(func() {
|
||||
ui.Row(c).Height(50).Children(func() {
|
||||
ui.Box(c).Width(50).FillHeight().Background(ui.RGB(255, 0, 0))
|
||||
ui.Box(c).Width(50).FillHeight().Background(ui.RGB(0, 0, 255)).Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
// Over the red to the left too.
|
||||
invert.Draw(p, ui.Rect{X: r.X - 25, Y: r.Y + 10, W: 50, H: 30}, shader.Options{})
|
||||
})
|
||||
})
|
||||
ui.Box(c).Height(50).Background(ui.RGB(0, 255, 0)).Children(func() {
|
||||
ui.Box(c).Width(40).Height(40).Background(ui.RGB(255, 255, 255)).Effect(tint.Effect(shader.Options{BackdropBlur: 2}))
|
||||
})
|
||||
})
|
||||
}
|
||||
img := ui.NewTester(view, 100, 100).Image()
|
||||
at := func(x, y int) [4]uint8 {
|
||||
o := img.PixOffset(x, y)
|
||||
return [4]uint8(img.Pix[o : o+4])
|
||||
}
|
||||
if got := at(35, 25); got != [4]uint8{0, 255, 255, 255} {
|
||||
t.Errorf("the inverted red: %v, want cyan", got)
|
||||
}
|
||||
if got := at(65, 25); got != [4]uint8{255, 255, 0, 255} {
|
||||
t.Errorf("the inverted blue: %v, want yellow", got)
|
||||
}
|
||||
if got := at(10, 25); got != [4]uint8{255, 0, 0, 255} {
|
||||
t.Errorf("beside the shader: %v, want red", got)
|
||||
}
|
||||
// White over green, half and half: light green.
|
||||
if got := at(20, 70); got[0] < 100 || got[0] > 160 || got[1] != 255 || got[2] < 100 || got[2] > 160 {
|
||||
t.Errorf("the effect over the green: %v, want white mixed half into green", got)
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r == nil || !strings.Contains(fmt.Sprint(r), "not shapes") {
|
||||
t.Errorf("Fill of a shader reading its backdrop: %v, want a panic", r)
|
||||
}
|
||||
}()
|
||||
ui.NewTester(func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
var path ui.Path
|
||||
invert.FillPath(p, path.Circle(5, 5, 4), shader.Options{})
|
||||
})
|
||||
}, 10, 10).Image()
|
||||
}
|
||||
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
package shader
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Uniform is a uniform variable of a shader, found by its name once
|
||||
// (Shader.Uniform), which Values sets.
|
||||
type Uniform struct {
|
||||
s *Shader
|
||||
name string
|
||||
u uniform
|
||||
}
|
||||
|
||||
// Uniform returns the shader's uniform variable name, which Values sets
|
||||
// by: look it up once, as a package variable or as the view starts. It
|
||||
// panics when the shader has no such variable, as a name misspelled.
|
||||
func (s *Shader) Uniform(name string) Uniform {
|
||||
u, ok := s.uniforms[name]
|
||||
if !ok || name == "" || name[0] == '_' {
|
||||
panic(fmt.Sprintf("shader: no uniform variable %s", name))
|
||||
}
|
||||
return Uniform{s: s, name: name, u: u}
|
||||
}
|
||||
|
||||
// Values are the values of a shader's uniform variables, which
|
||||
// Options.Values draws with, as Flutter's FragmentShader and Skia's
|
||||
// SkRuntimeShaderBuilder hold them: set them once or each frame, by
|
||||
// Uniform, and draw with them as often as needed; drawing copies them.
|
||||
// Variables not set are zero. The setters panic for a variable of another
|
||||
// type or another shader, and return v.
|
||||
type Values struct {
|
||||
s *Shader
|
||||
words []uint32
|
||||
colors []colorValue
|
||||
}
|
||||
|
||||
// colorValue is a color set to a vector (Values.Color), which a wide
|
||||
// gamut draws in extended sRGB.
|
||||
type colorValue struct {
|
||||
u uniform
|
||||
c ui.Color
|
||||
}
|
||||
|
||||
// NewValues returns values for the shader's uniform variables, all zero.
|
||||
func (s *Shader) NewValues() *Values {
|
||||
return &Values{s: s, words: make([]uint32, s.words)}
|
||||
}
|
||||
|
||||
// check panics unless u is a variable of v's shader of a type ok accepts,
|
||||
// named what.
|
||||
func (v *Values) check(u Uniform, what string, ok func(t shaderir.Type) bool) {
|
||||
if u.s != v.s {
|
||||
panic(fmt.Sprintf("shader: %s is not a uniform variable of the values' shader", u.name))
|
||||
}
|
||||
if !ok(u.u.t) {
|
||||
panic(fmt.Sprintf("shader: %s is a %s, not %s", u.name, u.u.t.String(), what))
|
||||
}
|
||||
}
|
||||
|
||||
func is(m shaderir.BasicType) func(shaderir.Type) bool {
|
||||
return func(t shaderir.Type) bool { return t.Main == m }
|
||||
}
|
||||
|
||||
// lanesOf accepts the types whose lanes are numbers of kind k: scalars,
|
||||
// vectors, matrices and arrays of them.
|
||||
func lanesOf(k shaderir.BasicType) func(shaderir.Type) bool {
|
||||
return func(t shaderir.Type) bool {
|
||||
if t.Main == shaderir.Array {
|
||||
t = t.Sub[0]
|
||||
}
|
||||
return t.Scalar() == k
|
||||
}
|
||||
}
|
||||
|
||||
// Float sets a float.
|
||||
func (v *Values) Float(u Uniform, x float32) *Values {
|
||||
v.check(u, "a float", is(shaderir.Float))
|
||||
v.words[u.u.word] = math.Float32bits(x)
|
||||
return v
|
||||
}
|
||||
|
||||
// Vec2 sets a vec2.
|
||||
func (v *Values) Vec2(u Uniform, x, y float32) *Values {
|
||||
v.check(u, "a vec2", is(shaderir.Vec2))
|
||||
v.floats(u, x, y)
|
||||
return v
|
||||
}
|
||||
|
||||
// Vec3 sets a vec3.
|
||||
func (v *Values) Vec3(u Uniform, x, y, z float32) *Values {
|
||||
v.check(u, "a vec3", is(shaderir.Vec3))
|
||||
v.floats(u, x, y, z)
|
||||
return v
|
||||
}
|
||||
|
||||
// Vec4 sets a vec4.
|
||||
func (v *Values) Vec4(u Uniform, x, y, z, w float32) *Values {
|
||||
v.check(u, "a vec4", is(shaderir.Vec4))
|
||||
v.floats(u, x, y, z, w)
|
||||
return v
|
||||
}
|
||||
|
||||
// Floats sets the components of a vector, a matrix (by columns) or an
|
||||
// array of floats or of them (elements in order), from the first; it
|
||||
// panics for more numbers than the variable holds.
|
||||
func (v *Values) Floats(u Uniform, xs ...float32) *Values {
|
||||
v.check(u, "of floats", lanesOf(shaderir.Float))
|
||||
v.floats(u, xs...)
|
||||
return v
|
||||
}
|
||||
|
||||
func (v *Values) floats(u Uniform, xs ...float32) {
|
||||
v.fits(u, len(xs))
|
||||
for i, x := range xs {
|
||||
v.words[u.u.word+i] = math.Float32bits(x)
|
||||
}
|
||||
}
|
||||
|
||||
// Int sets an int.
|
||||
func (v *Values) Int(u Uniform, x int32) *Values {
|
||||
v.check(u, "an int", is(shaderir.Int))
|
||||
v.words[u.u.word] = uint32(x)
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints sets the components of an ivec or an array of ints or of them, as
|
||||
// Floats does.
|
||||
func (v *Values) Ints(u Uniform, xs ...int32) *Values {
|
||||
v.check(u, "of ints", lanesOf(shaderir.Int))
|
||||
v.fits(u, len(xs))
|
||||
for i, x := range xs {
|
||||
v.words[u.u.word+i] = uint32(x)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Uint sets a uint.
|
||||
func (v *Values) Uint(u Uniform, x uint32) *Values {
|
||||
v.check(u, "a uint", is(shaderir.Uint))
|
||||
v.words[u.u.word] = x
|
||||
return v
|
||||
}
|
||||
|
||||
// Uints sets the components of a uvec or an array of uints or of them, as
|
||||
// Floats does.
|
||||
func (v *Values) Uints(u Uniform, xs ...uint32) *Values {
|
||||
v.check(u, "of uints", lanesOf(shaderir.Uint))
|
||||
v.fits(u, len(xs))
|
||||
copy(v.words[u.u.word:], xs)
|
||||
return v
|
||||
}
|
||||
|
||||
// Bool sets a bool.
|
||||
func (v *Values) Bool(u Uniform, b bool) *Values {
|
||||
v.check(u, "a bool", is(shaderir.Bool))
|
||||
v.words[u.u.word] = 0
|
||||
if b {
|
||||
v.words[u.u.word] = 1
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Color sets a vec3 or vec4 to c's components, from 0 to 1, not
|
||||
// premultiplied: its sRGB ones, or, where the window draws a wide gamut,
|
||||
// those of a color outside sRGB in extended sRGB (below 0 or above 1).
|
||||
func (v *Values) Color(u Uniform, c ui.Color) *Values {
|
||||
v.check(u, "a vec3 or vec4", func(t shaderir.Type) bool { return t.Main == shaderir.Vec3 || t.Main == shaderir.Vec4 })
|
||||
writeColor(v.words[u.u.word:u.u.word+u.u.n], straightSRGB(c))
|
||||
for i := range v.colors {
|
||||
if v.colors[i].u.word == u.u.word {
|
||||
v.colors[i].c = c
|
||||
return v
|
||||
}
|
||||
}
|
||||
v.colors = append(v.colors, colorValue{u.u, c})
|
||||
return v
|
||||
}
|
||||
|
||||
// fits panics unless u holds n numbers.
|
||||
func (v *Values) fits(u Uniform, n int) {
|
||||
if n > u.u.n {
|
||||
panic(fmt.Sprintf("shader: %d numbers for %s, a %s of %d", n, u.name, u.u.t.String(), u.u.n))
|
||||
}
|
||||
}
|
||||
|
||||
// straightSRGB returns c's sRGB components, from 0 to 1.
|
||||
func straightSRGB(c ui.Color) [4]float32 {
|
||||
return [4]float32{float32(c.R) / 255, float32(c.G) / 255, float32(c.B) / 255, float32(c.A) / 255}
|
||||
}
|
||||
|
||||
// writeColor writes the components of a color into the lanes of a vec3
|
||||
// or vec4.
|
||||
func writeColor(lanes []uint32, c [4]float32) {
|
||||
for i := range lanes {
|
||||
lanes[i] = math.Float32bits(c[i])
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package shader
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// A color outside sRGB sets its uniform in extended sRGB for a wide
|
||||
// gamut, beside the nearest sRGB color; one inside sets it once.
|
||||
func TestWideColors(t *testing.T) {
|
||||
s := MustCompile("package main\nvar Tint vec4\nfunc Fragment() vec4 { return Tint }\n")
|
||||
tint := s.Uniform("Tint")
|
||||
vivid := ui.Oklch(0.7, 0.3, 30) // beyond sRGB's reds
|
||||
var narrow, wide ui.ShaderInput
|
||||
view := func(c *ui.Context) {
|
||||
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
|
||||
narrow = s.input(p, r, r, Options{Values: s.NewValues().Color(tint, ui.RGB(255, 0, 0))}, ui.Point{})
|
||||
wide = s.input(p, r, r, Options{Uniforms: map[string]any{"Tint": vivid}}, ui.Point{})
|
||||
})
|
||||
}
|
||||
ui.NewTester(view, 10, 10).Image()
|
||||
if narrow.WideUniforms != nil {
|
||||
t.Errorf("an sRGB color has wide words")
|
||||
}
|
||||
if wide.WideUniforms == nil {
|
||||
t.Fatalf("a color outside sRGB has no wide words")
|
||||
}
|
||||
w := tint.u.word
|
||||
srgbRed := math.Float32frombits(wide.Uniforms[w])
|
||||
wideRed, wideGreen := math.Float32frombits(wide.WideUniforms[w]), math.Float32frombits(wide.WideUniforms[w+1])
|
||||
if srgbRed > 1 || wideRed <= 1 && wideGreen >= 0 {
|
||||
t.Errorf("red %v in sRGB, %v %v in extended sRGB: want the latter outside 0 to 1", srgbRed, wideRed, wideGreen)
|
||||
}
|
||||
for i := range wide.Uniforms {
|
||||
if (i < w || i >= w+4) && wide.Uniforms[i] != wide.WideUniforms[i] {
|
||||
t.Errorf("word %d differs for a wide gamut", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The renderers bind the backdrop where the bridge reads it.
|
||||
func TestBackdropImage(t *testing.T) {
|
||||
if gpu.BackdropImage != shader.BackdropImage {
|
||||
t.Fatalf("renderers bind the backdrop as image %d, shaders read image %d", gpu.BackdropImage, shader.BackdropImage)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user