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
@@ -0,0 +1,463 @@
|
||||
package interp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
)
|
||||
|
||||
// convert returns a lane of kind from converts to kind to, as the
|
||||
// shading languages' constructors convert: a float to an integer drops
|
||||
// its fraction, an int and a uint keep their bits, and a bool is 0 or 1.
|
||||
func convert(from, to shaderir.BasicType) func(uint32) uint32 {
|
||||
if from == to {
|
||||
return func(a uint32) uint32 { return a }
|
||||
}
|
||||
switch to {
|
||||
case shaderir.Float:
|
||||
switch from {
|
||||
case shaderir.Int:
|
||||
return func(a uint32) uint32 { return bits(float32(int32(a))) }
|
||||
case shaderir.Uint:
|
||||
return func(a uint32) uint32 { return bits(float32(a)) }
|
||||
case shaderir.Bool:
|
||||
return func(a uint32) uint32 { return bits(float32(a)) }
|
||||
}
|
||||
case shaderir.Int, shaderir.Uint:
|
||||
switch from {
|
||||
case shaderir.Float:
|
||||
return func(a uint32) uint32 {
|
||||
f := float64(f32(a))
|
||||
if math.IsNaN(f) {
|
||||
return 0
|
||||
}
|
||||
if to == shaderir.Uint && f >= 0 {
|
||||
return uint32(int64(min(f, math.MaxUint32)))
|
||||
}
|
||||
return uint32(int32(max(min(f, math.MaxInt32), math.MinInt32)))
|
||||
}
|
||||
default:
|
||||
return func(a uint32) uint32 { return a }
|
||||
}
|
||||
case shaderir.Bool:
|
||||
if from == shaderir.Float {
|
||||
return func(a uint32) uint32 { return boolBits(f32(a) != 0) }
|
||||
}
|
||||
return func(a uint32) uint32 { return boolBits(a != 0) }
|
||||
}
|
||||
panic(fmt.Sprintf("cannot convert %d to %d", from, to))
|
||||
}
|
||||
|
||||
// float1 and float2 are functions of float lanes.
|
||||
type (
|
||||
float1 func(x float64) float64
|
||||
float2 func(x, y float64) float64
|
||||
)
|
||||
|
||||
var unaryFloat = map[shaderir.BuiltinFunc]float1{
|
||||
shaderir.Sin: math.Sin,
|
||||
shaderir.Cos: math.Cos,
|
||||
shaderir.Tan: math.Tan,
|
||||
shaderir.Asin: math.Asin,
|
||||
shaderir.Acos: math.Acos,
|
||||
shaderir.Atan: math.Atan,
|
||||
shaderir.Exp: math.Exp,
|
||||
shaderir.Log: math.Log,
|
||||
shaderir.Exp2: math.Exp2,
|
||||
shaderir.Log2: math.Log2,
|
||||
shaderir.Sqrt: math.Sqrt,
|
||||
shaderir.Inversesqrt: func(x float64) float64 {
|
||||
return 1 / math.Sqrt(x)
|
||||
},
|
||||
shaderir.Floor: math.Floor,
|
||||
shaderir.Ceil: math.Ceil,
|
||||
shaderir.Fract: func(x float64) float64 { return x - math.Floor(x) },
|
||||
shaderir.Radians: func(x float64) float64 { return x * math.Pi / 180 },
|
||||
shaderir.Degrees: func(x float64) float64 { return x * 180 / math.Pi },
|
||||
// The CPU shades a pixel at a time, without its neighbors: the
|
||||
// derivatives are zero.
|
||||
shaderir.Dfdx: func(float64) float64 { return 0 },
|
||||
shaderir.Dfdy: func(float64) float64 { return 0 },
|
||||
shaderir.Fwidth: func(float64) float64 { return 0 },
|
||||
}
|
||||
|
||||
var binaryFloat = map[shaderir.BuiltinFunc]float2{
|
||||
shaderir.Atan2: math.Atan2,
|
||||
shaderir.Pow: math.Pow,
|
||||
shaderir.Mod: func(x, y float64) float64 { return x - y*math.Floor(x/y) },
|
||||
shaderir.Step: func(edge, x float64) float64 {
|
||||
if x < edge {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
},
|
||||
}
|
||||
|
||||
// minMax returns min or max of two lanes of kind.
|
||||
func minMax(f shaderir.BuiltinFunc, kind shaderir.BasicType) func(a, b uint32) uint32 {
|
||||
less := compare(shaderir.LessThanOp, kind)
|
||||
if kind == shaderir.Float {
|
||||
// As GPUs' (IEEE 754's minNum and maxNum), a NaN gives way to the
|
||||
// other operand.
|
||||
return func(a, b uint32) uint32 {
|
||||
x, y := f32(a), f32(b)
|
||||
switch {
|
||||
case x != x:
|
||||
return b
|
||||
case y != y:
|
||||
return a
|
||||
case f == shaderir.Min && y < x, f == shaderir.Max && y > x:
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
}
|
||||
if f == shaderir.Min {
|
||||
return func(a, b uint32) uint32 {
|
||||
if less(b, a) != 0 {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
}
|
||||
return func(a, b uint32) uint32 {
|
||||
if less(a, b) != 0 {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
}
|
||||
|
||||
// builtin compiles a call of a built-in function.
|
||||
func (c *compiler) builtin(fn *function, e *shaderir.Expr) operand {
|
||||
f := e.Exprs[0].BuiltinFunc
|
||||
t := shaderir.TypeOf(e, env{c, fn})
|
||||
var args []operand
|
||||
for i := 1; i < len(e.Exprs); i++ {
|
||||
args = append(args, c.expr(fn, &e.Exprs[i]))
|
||||
}
|
||||
|
||||
switch f {
|
||||
case shaderir.BoolF, shaderir.IntF, shaderir.UintF, shaderir.FloatF,
|
||||
shaderir.Vec2F, shaderir.Vec3F, shaderir.Vec4F,
|
||||
shaderir.IVec2F, shaderir.IVec3F, shaderir.IVec4F,
|
||||
shaderir.UVec2F, shaderir.UVec3F, shaderir.UVec4F,
|
||||
shaderir.Mat2F, shaderir.Mat3F, shaderir.Mat4F:
|
||||
return c.construct(t, args)
|
||||
case shaderir.FrontFacing:
|
||||
return c.constBits(t, 1)
|
||||
case shaderir.TexelAt:
|
||||
return c.texelAt(t, args[0], args[1])
|
||||
case shaderir.Min, shaderir.Max:
|
||||
return c.fold(t, args, minMax(f, t.Scalar()))
|
||||
case shaderir.Abs, shaderir.Sign:
|
||||
return c.absSign(f, t, args[0])
|
||||
case shaderir.Clamp:
|
||||
mn, mx := minMax(shaderir.Max, t.Scalar()), minMax(shaderir.Min, t.Scalar())
|
||||
return c.lanes3(t, args, func(x, lo, hi uint32) uint32 { return mx(mn(x, lo), hi) })
|
||||
case shaderir.Mix:
|
||||
return c.lanes3(t, args, func(a, b, w uint32) uint32 {
|
||||
x, y, k := f32(a), f32(b), f32(w)
|
||||
return bits(x*(1-k) + y*k)
|
||||
})
|
||||
case shaderir.Smoothstep:
|
||||
return c.lanes3(t, args, func(e0, e1, x uint32) uint32 {
|
||||
// Clamped as GPUs clamp: a NaN, as from equal edges, gives 0.
|
||||
k := (f32(x) - f32(e0)) / (f32(e1) - f32(e0))
|
||||
if !(k > 0) {
|
||||
k = 0
|
||||
} else if k > 1 {
|
||||
k = 1
|
||||
}
|
||||
return bits(k * k * (3 - 2*k))
|
||||
})
|
||||
case shaderir.Length:
|
||||
return c.reduce(t, args, func(s *state, v []operand) float64 { return math.Sqrt(dot(s, v[0], v[0])) })
|
||||
case shaderir.Distance:
|
||||
return c.reduce(t, args, func(s *state, v []operand) float64 {
|
||||
var sum float64
|
||||
for i := range v[0].n() {
|
||||
d := float64(f32(s.r[v[0].off+i])) - float64(f32(s.r[v[1].off+i]))
|
||||
sum += d * d
|
||||
}
|
||||
return math.Sqrt(sum)
|
||||
})
|
||||
case shaderir.Dot:
|
||||
return c.reduce(t, args, func(s *state, v []operand) float64 { return dot(s, v[0], v[1]) })
|
||||
case shaderir.Cross:
|
||||
a, b := args[0], args[1]
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a, b)
|
||||
x := func(o operand, i int) float32 { return f32(s.r[o.off+i]) }
|
||||
s.r[o.off] = bits(x(a, 1)*x(b, 2) - x(a, 2)*x(b, 1))
|
||||
s.r[o.off+1] = bits(x(a, 2)*x(b, 0) - x(a, 0)*x(b, 2))
|
||||
s.r[o.off+2] = bits(x(a, 0)*x(b, 1) - x(a, 1)*x(b, 0))
|
||||
}}
|
||||
case shaderir.Normalize:
|
||||
a := args[0]
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a)
|
||||
k := 1 / math.Sqrt(dot(s, a, a))
|
||||
for i := range n {
|
||||
s.r[o.off+i] = bits(float32(float64(f32(s.r[a.off+i])) * k))
|
||||
}
|
||||
}}
|
||||
case shaderir.Faceforward:
|
||||
nv, iv, ref := args[0], args[1], args[2]
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, nv, iv, ref)
|
||||
sign := uint32(0)
|
||||
if dot(s, ref, iv) >= 0 {
|
||||
sign = 0x80000000
|
||||
}
|
||||
for i := range n {
|
||||
s.r[o.off+i] = s.r[nv.off+i] ^ sign
|
||||
}
|
||||
}}
|
||||
case shaderir.Reflect:
|
||||
iv, nv := args[0], args[1]
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, iv, nv)
|
||||
d := dot(s, nv, iv)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = bits(float32(float64(f32(s.r[iv.off+i])) - 2*d*float64(f32(s.r[nv.off+i]))))
|
||||
}
|
||||
}}
|
||||
case shaderir.Refract:
|
||||
iv, nv, eta := args[0], args[1], args[2]
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, iv, nv, eta)
|
||||
d := dot(s, nv, iv)
|
||||
k := float64(f32(s.r[eta.off]))
|
||||
q := 1 - k*k*(1-d*d)
|
||||
for i := range n {
|
||||
if q < 0 {
|
||||
s.r[o.off+i] = 0
|
||||
continue
|
||||
}
|
||||
v := k*float64(f32(s.r[iv.off+i])) - (k*d+math.Sqrt(q))*float64(f32(s.r[nv.off+i]))
|
||||
s.r[o.off+i] = bits(float32(v))
|
||||
}
|
||||
}}
|
||||
case shaderir.Transpose:
|
||||
a := args[0]
|
||||
o := c.alloc(t)
|
||||
n := t.MatrixSize()
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a)
|
||||
for col := range n {
|
||||
for row := range n {
|
||||
s.r[o.off+row*n+col] = s.r[a.off+col*n+row]
|
||||
}
|
||||
}
|
||||
}}
|
||||
}
|
||||
if g, ok := unaryFloat[f]; ok {
|
||||
a := args[0]
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = bits(float32(g(float64(f32(s.r[a.off+i])))))
|
||||
}
|
||||
}}
|
||||
}
|
||||
if g, ok := binaryFloat[f]; ok {
|
||||
return c.lanes2(t, args, func(a, b uint32) uint32 {
|
||||
return bits(float32(g(float64(f32(a)), float64(f32(b)))))
|
||||
})
|
||||
}
|
||||
panic(fmt.Sprintf("built-in function %s is not supported", f))
|
||||
}
|
||||
|
||||
func dot(s *state, a, b operand) float64 {
|
||||
var sum float64
|
||||
for i := range a.n() {
|
||||
sum += float64(f32(s.r[a.off+i])) * float64(f32(s.r[b.off+i]))
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func (c *compiler) constBits(t shaderir.Type, v uint32) operand {
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) { s.r[o.off] = v }}
|
||||
}
|
||||
|
||||
// construct compiles a constructor: the arguments' lanes in order, each
|
||||
// converted to the type's kind, a scalar alone filling a vector, and
|
||||
// making the diagonal of a matrix.
|
||||
func (c *compiler) construct(t shaderir.Type, args []operand) operand {
|
||||
o := c.alloc(t)
|
||||
n, kind := o.n, t.Scalar()
|
||||
if len(args) == 1 && args[0].n() == 1 {
|
||||
a := args[0]
|
||||
conv := convert(a.t.Scalar(), kind)
|
||||
if t.IsMatrix() {
|
||||
size := t.MatrixSize()
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a)
|
||||
clear(s.r[o.off : o.off+n])
|
||||
v := conv(s.r[a.off])
|
||||
for i := range size {
|
||||
s.r[o.off+i*size+i] = v
|
||||
}
|
||||
}}
|
||||
}
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a)
|
||||
v := conv(s.r[a.off])
|
||||
for i := range n {
|
||||
s.r[o.off+i] = v
|
||||
}
|
||||
}}
|
||||
}
|
||||
convs := make([]func(uint32) uint32, len(args))
|
||||
for i, a := range args {
|
||||
convs[i] = convert(a.t.Scalar(), kind)
|
||||
}
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
k := 0
|
||||
for i, a := range args {
|
||||
eval(s, a)
|
||||
for j := 0; j < a.n() && k < n; j++ {
|
||||
s.r[o.off+k] = convs[i](s.r[a.off+j])
|
||||
k++
|
||||
}
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
// texelAt compiles the pixel of an image at a position, transparent
|
||||
// outside it.
|
||||
func (c *compiler) texelAt(t shaderir.Type, tex, pos operand) operand {
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, tex, pos)
|
||||
clear(s.r[o.off : o.off+4])
|
||||
i := int(s.r[tex.off])
|
||||
if i >= len(s.in.Images) || s.in.Images[i] == nil {
|
||||
return
|
||||
}
|
||||
img := s.in.Images[i]
|
||||
w, h := img.Size()
|
||||
x, y := math.Floor(float64(f32(s.r[pos.off]))), math.Floor(float64(f32(s.r[pos.off+1])))
|
||||
if !(x >= 0 && y >= 0 && x < float64(w) && y < float64(h)) {
|
||||
return
|
||||
}
|
||||
px := img.At(int(x), int(y))
|
||||
for k := range px {
|
||||
s.r[o.off+k] = bits(px[k])
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
// fold compiles min or max of any number of arguments, a scalar going
|
||||
// with every lane of a vector.
|
||||
func (c *compiler) fold(t shaderir.Type, args []operand, g func(a, b uint32) uint32) operand {
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, args...)
|
||||
for i := range n {
|
||||
v := s.r[args[0].off+i*stride(args[0])]
|
||||
for _, a := range args[1:] {
|
||||
v = g(v, s.r[a.off+i*stride(a)])
|
||||
}
|
||||
s.r[o.off+i] = v
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
func stride(o operand) int {
|
||||
if o.n() == 1 {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// lanes2 and lanes3 compile functions of two and three lanes, lane by
|
||||
// lane, a scalar going with every lane.
|
||||
func (c *compiler) lanes2(t shaderir.Type, args []operand, g func(a, b uint32) uint32) operand {
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
a, b := args[0], args[1]
|
||||
sa, sb := stride(a), stride(b)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a, b)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = g(s.r[a.off+i*sa], s.r[b.off+i*sb])
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
func (c *compiler) lanes3(t shaderir.Type, args []operand, g func(a, b, x uint32) uint32) operand {
|
||||
o := c.alloc(t)
|
||||
n := o.n
|
||||
a, b, x := args[0], args[1], args[2]
|
||||
sa, sb, sx := stride(a), stride(b), stride(x)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a, b, x)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = g(s.r[a.off+i*sa], s.r[b.off+i*sb], s.r[x.off+i*sx])
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
// reduce compiles a function of vectors that gives a float.
|
||||
func (c *compiler) reduce(t shaderir.Type, args []operand, g func(s *state, v []operand) float64) operand {
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, args...)
|
||||
s.r[o.off] = bits(float32(g(s, args)))
|
||||
}}
|
||||
}
|
||||
|
||||
func (c *compiler) absSign(f shaderir.BuiltinFunc, t shaderir.Type, a operand) operand {
|
||||
o := c.alloc(t)
|
||||
n, kind := o.n, t.Scalar()
|
||||
var g func(uint32) uint32
|
||||
switch {
|
||||
case kind == shaderir.Float && f == shaderir.Abs:
|
||||
g = func(x uint32) uint32 { return x &^ 0x80000000 }
|
||||
case kind == shaderir.Float:
|
||||
g = func(x uint32) uint32 {
|
||||
v := f32(x)
|
||||
switch {
|
||||
case v > 0:
|
||||
return bits(1)
|
||||
case v < 0:
|
||||
return bits(-1)
|
||||
}
|
||||
return bits(0)
|
||||
}
|
||||
case f == shaderir.Abs:
|
||||
g = func(x uint32) uint32 {
|
||||
if int32(x) < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
default:
|
||||
g = func(x uint32) uint32 {
|
||||
v := int32(x)
|
||||
return uint32(boolBits(v > 0)) - uint32(boolBits(v < 0))
|
||||
}
|
||||
}
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, a)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = g(s.r[a.off+i])
|
||||
}
|
||||
}}
|
||||
}
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
package interp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/constant"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
)
|
||||
|
||||
// maxIterations bounds a loop, as a GPU's watchdog would: a shader whose
|
||||
// loop does not end draws what it has.
|
||||
const maxIterations = 1 << 20
|
||||
|
||||
// operand is an expression compiled: once run has run (nil for a value
|
||||
// already in place, as a local's), its value lies in the registers from
|
||||
// off, of type t.
|
||||
type operand struct {
|
||||
run func(s *state)
|
||||
off int
|
||||
t shaderir.Type
|
||||
}
|
||||
|
||||
func (o operand) n() int { return lanes(&o.t) }
|
||||
|
||||
// eval runs the operands' computations.
|
||||
func eval(s *state, os ...operand) {
|
||||
for _, o := range os {
|
||||
if o.run != nil {
|
||||
o.run(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *compiler) block(fn *function, b *shaderir.Block) []stmt {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
// The block's locals, a loop's counter among them, which has the type
|
||||
// of its loop, start at zero, as the backends declare them.
|
||||
scope := map[int]slot{}
|
||||
var zero []slot
|
||||
for i, t := range b.LocalVars {
|
||||
index := b.LocalVarIndexOffset + i
|
||||
if t.Main == shaderir.None {
|
||||
for _, st := range b.Stmts {
|
||||
if st.Type == shaderir.For && st.ForVarIndex == index {
|
||||
t = st.ForVarType
|
||||
}
|
||||
}
|
||||
scope[index] = c.alloc(t)
|
||||
continue
|
||||
}
|
||||
scope[index] = c.alloc(t)
|
||||
zero = append(zero, scope[index])
|
||||
}
|
||||
c.scopes = append(c.scopes, scope)
|
||||
defer func() { c.scopes = c.scopes[:len(c.scopes)-1] }()
|
||||
|
||||
var out []stmt
|
||||
if len(zero) > 0 {
|
||||
out = append(out, func(s *state) control {
|
||||
for _, z := range zero {
|
||||
clear(s.r[z.off : z.off+z.n])
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
for i := range b.Stmts {
|
||||
if st := c.stmt(fn, &b.Stmts[i]); st != nil {
|
||||
out = append(out, st)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func runBlock(s *state, body []stmt) control {
|
||||
for _, st := range body {
|
||||
if ctl := st(s); ctl != next {
|
||||
return ctl
|
||||
}
|
||||
if s.discard {
|
||||
return returned
|
||||
}
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (c *compiler) stmt(fn *function, st *shaderir.Stmt) stmt {
|
||||
switch st.Type {
|
||||
case shaderir.ExprStmt:
|
||||
o := c.expr(fn, &st.Exprs[0])
|
||||
if o.run == nil {
|
||||
return nil
|
||||
}
|
||||
return func(s *state) control { o.run(s); return next }
|
||||
case shaderir.BlockStmt:
|
||||
body := c.block(fn, st.Blocks[0])
|
||||
return func(s *state) control { return runBlock(s, body) }
|
||||
case shaderir.Assign:
|
||||
return c.assign(fn, &st.Exprs[0], &st.Exprs[1])
|
||||
case shaderir.Init:
|
||||
l := c.local(fn, st.InitIndex)
|
||||
return func(s *state) control { clear(s.r[l.off : l.off+l.n]); return next }
|
||||
case shaderir.If:
|
||||
cond := c.expr(fn, &st.Exprs[0])
|
||||
then := c.block(fn, st.Blocks[0])
|
||||
var els []stmt
|
||||
if len(st.Blocks) > 1 {
|
||||
els = c.block(fn, st.Blocks[1])
|
||||
}
|
||||
return func(s *state) control {
|
||||
eval(s, cond)
|
||||
if s.r[cond.off] != 0 {
|
||||
return runBlock(s, then)
|
||||
}
|
||||
return runBlock(s, els)
|
||||
}
|
||||
case shaderir.For:
|
||||
return c.loop(fn, st)
|
||||
case shaderir.Continue:
|
||||
return func(*state) control { return continueLoop }
|
||||
case shaderir.Break:
|
||||
return func(*state) control { return breakLoop }
|
||||
case shaderir.Return:
|
||||
if len(st.Exprs) == 0 {
|
||||
return func(*state) control { return returned }
|
||||
}
|
||||
o := c.expr(fn, &st.Exprs[0])
|
||||
ret := fn.ret
|
||||
return func(s *state) control {
|
||||
eval(s, o)
|
||||
copy(s.r[ret.off:ret.off+ret.n], s.r[o.off:o.off+ret.n])
|
||||
return returned
|
||||
}
|
||||
case shaderir.Discard:
|
||||
return func(s *state) control { s.discard = true; return returned }
|
||||
}
|
||||
panic(fmt.Sprintf("unexpected statement %d", st.Type))
|
||||
}
|
||||
|
||||
// loop compiles a for loop: its counter goes from the start by the step
|
||||
// while it compares with the end, evaluated before each iteration.
|
||||
func (c *compiler) loop(fn *function, st *shaderir.Stmt) stmt {
|
||||
counter := c.local(fn, st.ForVarIndex)
|
||||
var start, end operand
|
||||
if len(st.Exprs) == 2 {
|
||||
start, end = c.expr(fn, &st.Exprs[0]), c.expr(fn, &st.Exprs[1])
|
||||
} else {
|
||||
start = c.constant(st.ForInit, st.ForVarType)
|
||||
end = c.constant(st.ForEnd, st.ForVarType)
|
||||
}
|
||||
delta := c.constant(st.ForDelta, st.ForVarType)
|
||||
kind := st.ForVarType.Scalar()
|
||||
add := arith(shaderir.Add, kind)
|
||||
cmp := compare(st.ForOp, kind)
|
||||
body := c.block(fn, st.Blocks[0])
|
||||
return func(s *state) control {
|
||||
eval(s, start, delta)
|
||||
s.r[counter.off] = s.r[start.off]
|
||||
for i := 0; i < maxIterations; i++ {
|
||||
eval(s, end)
|
||||
if cmp(s.r[counter.off], s.r[end.off]) == 0 {
|
||||
break
|
||||
}
|
||||
switch runBlock(s, body) {
|
||||
case breakLoop:
|
||||
return next
|
||||
case returned:
|
||||
return returned
|
||||
}
|
||||
s.r[counter.off] = add(s.r[counter.off], s.r[delta.off])
|
||||
}
|
||||
return next
|
||||
}
|
||||
}
|
||||
|
||||
// assign compiles lhs = rhs: lhs a local, an element of one or a swizzle
|
||||
// of one, at any depth.
|
||||
func (c *compiler) assign(fn *function, lhs, rhs *shaderir.Expr) stmt {
|
||||
src := c.expr(fn, rhs)
|
||||
n := src.n()
|
||||
if lhs.Type == shaderir.LocalVariable {
|
||||
dst := c.local(fn, lhs.Index)
|
||||
return func(s *state) control {
|
||||
eval(s, src)
|
||||
copy(s.r[dst.off:dst.off+n], s.r[src.off:src.off+n])
|
||||
return next
|
||||
}
|
||||
}
|
||||
// The value is copied first, as the target may overlap it.
|
||||
tmp := c.alloc(src.t)
|
||||
write := c.lvalue(fn, lhs)
|
||||
return func(s *state) control {
|
||||
eval(s, src)
|
||||
copy(s.r[tmp.off:tmp.off+n], s.r[src.off:src.off+n])
|
||||
write(s, tmp.off)
|
||||
return next
|
||||
}
|
||||
}
|
||||
|
||||
// lvalue returns what writes the value at src to e's lanes.
|
||||
func (c *compiler) lvalue(fn *function, e *shaderir.Expr) func(s *state, src int) {
|
||||
switch e.Type {
|
||||
case shaderir.LocalVariable:
|
||||
l := c.local(fn, e.Index)
|
||||
return func(s *state, src int) { copy(s.r[l.off:l.off+l.n], s.r[src:src+l.n]) }
|
||||
case shaderir.Index:
|
||||
base := &e.Exprs[0]
|
||||
bt := shaderir.TypeOf(base, env{c, fn})
|
||||
et := shaderir.TypeOf(e, env{c, fn})
|
||||
size, count := lanes(&et), elements(&bt)
|
||||
idx := c.expr(fn, &e.Exprs[1])
|
||||
unsigned := shaderir.TypeOf(&e.Exprs[1], env{c, fn}).Scalar() == shaderir.Uint
|
||||
// Write the element into a copy of the base, then the base back.
|
||||
tmp := c.alloc(bt)
|
||||
read := c.expr(fn, base)
|
||||
write := c.lvalue(fn, base)
|
||||
bn := lanes(&bt)
|
||||
return func(s *state, src int) {
|
||||
eval(s, read, idx)
|
||||
copy(s.r[tmp.off:tmp.off+bn], s.r[read.off:read.off+bn])
|
||||
i := clampIndex(indexAt(s.r[idx.off], unsigned), count)
|
||||
copy(s.r[tmp.off+i*size:tmp.off+(i+1)*size], s.r[src:src+size])
|
||||
write(s, tmp.off)
|
||||
}
|
||||
case shaderir.FieldSelector:
|
||||
base := &e.Exprs[0]
|
||||
bt := shaderir.TypeOf(base, env{c, fn})
|
||||
m := e.Exprs[1]
|
||||
tmp := c.alloc(bt)
|
||||
read := c.expr(fn, base)
|
||||
write := c.lvalue(fn, base)
|
||||
bn := lanes(&bt)
|
||||
var targets []int
|
||||
if m.Type == shaderir.SwizzlingExpr {
|
||||
targets = swizzle(m.Swizzling)
|
||||
} else {
|
||||
off := memberOffset(&bt, m.Index)
|
||||
for i := range lanes(&bt.Sub[m.Index]) {
|
||||
targets = append(targets, off+i)
|
||||
}
|
||||
}
|
||||
return func(s *state, src int) {
|
||||
eval(s, read)
|
||||
copy(s.r[tmp.off:tmp.off+bn], s.r[read.off:read.off+bn])
|
||||
for i, t := range targets {
|
||||
s.r[tmp.off+t] = s.r[src+i]
|
||||
}
|
||||
write(s, tmp.off)
|
||||
}
|
||||
}
|
||||
panic(fmt.Sprintf("cannot assign to expression %d", e.Type))
|
||||
}
|
||||
|
||||
// elements returns how many elements indexing t reaches.
|
||||
func elements(t *shaderir.Type) int {
|
||||
switch {
|
||||
case t.Main == shaderir.Array:
|
||||
return t.Length
|
||||
case t.IsMatrix():
|
||||
return t.MatrixSize()
|
||||
}
|
||||
return t.VectorElementCount()
|
||||
}
|
||||
|
||||
// clampIndex keeps an index within count, where a GPU's would be
|
||||
// undefined.
|
||||
func clampIndex(i int64, count int) int {
|
||||
return int(min(max(i, 0), int64(count-1)))
|
||||
}
|
||||
|
||||
// indexAt returns the index in r, a uint's bits when unsigned, else an
|
||||
// int's.
|
||||
func indexAt(r uint32, unsigned bool) int64 {
|
||||
if unsigned {
|
||||
return int64(r)
|
||||
}
|
||||
return int64(int32(r))
|
||||
}
|
||||
|
||||
func swizzle(s string) []int {
|
||||
out := make([]int, len(s))
|
||||
for i, r := range s {
|
||||
switch r {
|
||||
case 'x':
|
||||
out[i] = 0
|
||||
case 'y':
|
||||
out[i] = 1
|
||||
case 'z':
|
||||
out[i] = 2
|
||||
case 'w':
|
||||
out[i] = 3
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func memberOffset(t *shaderir.Type, index int) int {
|
||||
off := 0
|
||||
for i := 0; i < index; i++ {
|
||||
off += lanes(&t.Sub[i])
|
||||
}
|
||||
return off
|
||||
}
|
||||
|
||||
// constant returns an operand of the constant v as type t's kind.
|
||||
func (c *compiler) constant(v constant.Value, t shaderir.Type) operand {
|
||||
st := shaderir.Type{Main: t.Scalar()}
|
||||
o := c.alloc(st)
|
||||
bits := constBits(v, st.Main)
|
||||
return operand{off: o.off, t: st, run: func(s *state) { s.r[o.off] = bits }}
|
||||
}
|
||||
|
||||
func constBits(v constant.Value, kind shaderir.BasicType) uint32 {
|
||||
switch kind {
|
||||
case shaderir.Float:
|
||||
f, _ := constant.Float64Val(constant.ToFloat(v))
|
||||
return math.Float32bits(float32(f))
|
||||
case shaderir.Bool:
|
||||
if constant.BoolVal(v) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
if x, ok := constant.Int64Val(constant.ToInt(v)); ok {
|
||||
return uint32(x)
|
||||
}
|
||||
x, _ := constant.Uint64Val(constant.ToInt(v))
|
||||
return uint32(x)
|
||||
}
|
||||
|
||||
func (c *compiler) expr(fn *function, e *shaderir.Expr) operand {
|
||||
en := env{c, fn}
|
||||
switch e.Type {
|
||||
case shaderir.NumberExpr:
|
||||
return c.constant(e.Const, shaderir.TypeOf(e, en))
|
||||
case shaderir.LocalVariable:
|
||||
l := c.local(fn, e.Index)
|
||||
return operand{off: l.off, t: l.t}
|
||||
case shaderir.UniformVariable:
|
||||
t := c.p.Uniforms[e.Index]
|
||||
o := c.alloc(t)
|
||||
w, n := c.uniforms[e.Index], o.n
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
copy(s.r[o.off:o.off+n], s.in.Uniforms[w:w+n])
|
||||
}}
|
||||
case shaderir.TextureVariable:
|
||||
o := c.alloc(shaderir.Type{Main: shaderir.Texture})
|
||||
i := uint32(e.Index)
|
||||
return operand{off: o.off, t: o.t, run: func(s *state) { s.r[o.off] = i }}
|
||||
case shaderir.Unary:
|
||||
return c.unary(fn, e)
|
||||
case shaderir.Binary:
|
||||
return c.binary(fn, e)
|
||||
case shaderir.Selection:
|
||||
cond, a, b := c.expr(fn, &e.Exprs[0]), c.expr(fn, &e.Exprs[1]), c.expr(fn, &e.Exprs[2])
|
||||
o := c.alloc(a.t)
|
||||
n := o.n
|
||||
return operand{off: o.off, t: a.t, run: func(s *state) {
|
||||
eval(s, cond, a, b)
|
||||
src := b.off
|
||||
if s.r[cond.off] != 0 {
|
||||
src = a.off
|
||||
}
|
||||
copy(s.r[o.off:o.off+n], s.r[src:src+n])
|
||||
}}
|
||||
case shaderir.Call:
|
||||
if e.Exprs[0].Type == shaderir.FunctionExpr {
|
||||
return c.call(fn, e)
|
||||
}
|
||||
return c.builtin(fn, e)
|
||||
case shaderir.FieldSelector:
|
||||
base := c.expr(fn, &e.Exprs[0])
|
||||
t := shaderir.TypeOf(e, en)
|
||||
m := e.Exprs[1]
|
||||
var from []int
|
||||
if m.Type == shaderir.SwizzlingExpr {
|
||||
from = swizzle(m.Swizzling)
|
||||
} else {
|
||||
off := memberOffset(&base.t, m.Index)
|
||||
for i := range lanes(&t) {
|
||||
from = append(from, off+i)
|
||||
}
|
||||
}
|
||||
// Lanes in order are read in place.
|
||||
inOrder := true
|
||||
for i := range from {
|
||||
inOrder = inOrder && from[i] == from[0]+i
|
||||
}
|
||||
if inOrder {
|
||||
return operand{run: base.run, off: base.off + from[0], t: t}
|
||||
}
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, base)
|
||||
for i, f := range from {
|
||||
s.r[o.off+i] = s.r[base.off+f]
|
||||
}
|
||||
}}
|
||||
case shaderir.Index:
|
||||
return c.index(fn, e)
|
||||
}
|
||||
panic(fmt.Sprintf("unexpected expression %d", e.Type))
|
||||
}
|
||||
|
||||
// index compiles an element of an array, a vector or a matrix: in place
|
||||
// for a constant index, copied for another.
|
||||
func (c *compiler) index(fn *function, e *shaderir.Expr) operand {
|
||||
en := env{c, fn}
|
||||
t := shaderir.TypeOf(e, en)
|
||||
bt := shaderir.TypeOf(&e.Exprs[0], en)
|
||||
size, count := lanes(&t), elements(&bt)
|
||||
ie := &e.Exprs[1]
|
||||
unsigned := shaderir.TypeOf(ie, en).Scalar() == shaderir.Uint
|
||||
// An element of a uniform is read from the uniforms, not the whole.
|
||||
if e.Exprs[0].Type == shaderir.UniformVariable {
|
||||
w := c.uniforms[e.Exprs[0].Index]
|
||||
idx := c.expr(fn, ie)
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, idx)
|
||||
i := clampIndex(indexAt(s.r[idx.off], unsigned), count)
|
||||
copy(s.r[o.off:o.off+size], s.in.Uniforms[w+i*size:w+(i+1)*size])
|
||||
}}
|
||||
}
|
||||
base := c.expr(fn, &e.Exprs[0])
|
||||
if ie.Type == shaderir.NumberExpr {
|
||||
i64, _ := constant.Int64Val(constant.ToInt(ie.Const))
|
||||
i := clampIndex(i64, count)
|
||||
return operand{run: base.run, off: base.off + i*size, t: t}
|
||||
}
|
||||
idx := c.expr(fn, ie)
|
||||
o := c.alloc(t)
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, base, idx)
|
||||
i := clampIndex(indexAt(s.r[idx.off], unsigned), count)
|
||||
copy(s.r[o.off:o.off+size], s.r[base.off+i*size:base.off+(i+1)*size])
|
||||
}}
|
||||
}
|
||||
|
||||
// call compiles a call of a function of the program: the arguments go to
|
||||
// its parameters, and its output parameters to the caller's locals after.
|
||||
func (c *compiler) call(fn *function, e *shaderir.Expr) operand {
|
||||
callee := c.funcs[e.Exprs[0].Index]
|
||||
if callee == nil {
|
||||
panic("call of a function not compiled")
|
||||
}
|
||||
in := len(callee.f.InParams)
|
||||
var args []operand
|
||||
for i := 1; i <= in; i++ {
|
||||
args = append(args, c.expr(fn, &e.Exprs[i]))
|
||||
}
|
||||
// The arguments are computed before any goes to the parameters, as one
|
||||
// may call the same function.
|
||||
tmps := make([]slot, len(args))
|
||||
for i, a := range args {
|
||||
tmps[i] = c.alloc(a.t)
|
||||
}
|
||||
var outs []slot
|
||||
for i := in + 1; i < len(e.Exprs); i++ {
|
||||
outs = append(outs, c.local(fn, e.Exprs[i].Index))
|
||||
}
|
||||
var o slot
|
||||
if callee.f.Return.Main != shaderir.None {
|
||||
o = c.alloc(callee.f.Return)
|
||||
}
|
||||
return operand{off: o.off, t: callee.f.Return, run: func(s *state) {
|
||||
for i, a := range args {
|
||||
eval(s, a)
|
||||
copy(s.r[tmps[i].off:tmps[i].off+tmps[i].n], s.r[a.off:a.off+tmps[i].n])
|
||||
}
|
||||
for i, t := range tmps {
|
||||
p := callee.params[i]
|
||||
copy(s.r[p.off:p.off+p.n], s.r[t.off:t.off+t.n])
|
||||
}
|
||||
callee.run(s)
|
||||
for i, out := range outs {
|
||||
p := callee.params[in+i]
|
||||
copy(s.r[out.off:out.off+out.n], s.r[p.off:p.off+p.n])
|
||||
}
|
||||
if o.n > 0 {
|
||||
copy(s.r[o.off:o.off+o.n], s.r[callee.ret.off:callee.ret.off+o.n])
|
||||
}
|
||||
}}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//go:build !ios
|
||||
|
||||
package interp_test
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/gpu/metal"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/interp"
|
||||
"github.com/egoist/mygo/internal/shaderir/msl"
|
||||
)
|
||||
|
||||
// TestMetal draws a shader with the Metal renderer, its Metal function
|
||||
// wrapped in an effect, and checks that the interpreter computes the same
|
||||
// pixels.
|
||||
func TestMetal(t *testing.T) {
|
||||
p, prog := compile(t, noiseSource)
|
||||
words := noiseUniforms(p)
|
||||
fx := &scene.Effect{
|
||||
Name: "shader",
|
||||
Metal: scene.EffectCode{Source: metalEffect(p, words)},
|
||||
Pixels: func() scene.EffectPixels { return &shaderPixels{prog: prog, in: &interp.Inputs{Uniforms: words}} },
|
||||
}
|
||||
s := effectScene(fx)
|
||||
pix, err := metal.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Metal:", err)
|
||||
}
|
||||
gputest.Compare(t, "shader-metal", pix, s.Width*4, s)
|
||||
}
|
||||
|
||||
// metalEffect returns an effect's Metal source calling p's fragment
|
||||
// function, with the uniform values words laid out as Metal lays out its
|
||||
// struct of uniforms, in the source.
|
||||
func metalEffect(p *shaderir.Program, words []uint32) string {
|
||||
at, size := msl.UniformLanes(p)
|
||||
buf := make([]byte, (size+15)/16*16)
|
||||
for k, w := range words {
|
||||
binary.LittleEndian.PutUint32(buf[at[k]:], w)
|
||||
}
|
||||
var lanes []string
|
||||
for i := 0; i < len(buf); i += 4 {
|
||||
lanes = append(lanes, fmt.Sprintf("%du", binary.LittleEndian.Uint32(buf[i:])))
|
||||
}
|
||||
return msl.Fragment(p, "shaderFragment", "") + fmt.Sprintf(`
|
||||
constant uint shaderUniforms[%d] = {%s};
|
||||
|
||||
float4 effect(float2 p, Effect e, texture2d<float> backdrop) {
|
||||
constant Uniforms& u = *(constant Uniforms*)shaderUniforms;
|
||||
return shaderFragment(u, backdrop, backdrop, backdrop, backdrop, float4(p, 0.0f, 1.0f), p - e.rect.xy);
|
||||
}
|
||||
`, len(lanes), strings.Join(lanes, ", "))
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//go:build (amd64 || arm64) && !android
|
||||
|
||||
package interp_test
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gl"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shaderir/glsl"
|
||||
"github.com/egoist/mygo/internal/shaderir/interp"
|
||||
)
|
||||
|
||||
// TestOpenGL draws a shader with OpenGL 3.3 and OpenGL ES 3.0, its GLSL
|
||||
// function wrapped in an effect, and checks that the interpreter computes
|
||||
// the same pixels.
|
||||
func TestOpenGL(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
p, prog := compile(t, noiseSource)
|
||||
words := noiseUniforms(p)
|
||||
code := constUniforms(glsl.Fragment(p, "shaderFragment", glsl.Options{FlipY: "true"}),
|
||||
regexp.MustCompile(`(?m)^uniform ((?:\w+) (U\d+)(?:\[\d+\])?);$`), p, words, false)
|
||||
fx := &scene.Effect{
|
||||
Name: "shader",
|
||||
GLSL: code + `
|
||||
vec4 effect(vec2 p, Effect e) {
|
||||
return shaderFragment(vec4(p, 0.0, 1.0), p - e.rect.xy);
|
||||
}`,
|
||||
Pixels: func() scene.EffectPixels { return &shaderPixels{prog: prog, in: &interp.Inputs{Uniforms: words}} },
|
||||
}
|
||||
for _, es := range []bool{false, true} {
|
||||
s := effectScene(fx)
|
||||
o, err := gl.NewOffscreen(es, s.Width, s.Height)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Log(o.Info())
|
||||
pix, err := o.Render(s)
|
||||
o.Release()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := "shader-gl"
|
||||
if es {
|
||||
name += "-es"
|
||||
}
|
||||
gputest.Compare(t, name, pix, s.Width*4, s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package interp_test
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shaderir/hlsl"
|
||||
"github.com/egoist/mygo/internal/shaderir/interp"
|
||||
)
|
||||
|
||||
// TestDirect3D draws a shader with Direct3D 11, its HLSL function wrapped
|
||||
// in an effect, and checks that the interpreter computes the same pixels.
|
||||
func TestDirect3D(t *testing.T) {
|
||||
p, prog := compile(t, noiseSource)
|
||||
words := noiseUniforms(p)
|
||||
// The uniforms' constants in place of the cbuffer's members.
|
||||
code := hlsl.Fragment(p, "shaderFragment", 2, 6, "")
|
||||
code = regexp.MustCompile(`(?s)cbuffer Uniforms : register\(b\d+\) \{\n(.*?)\n\}`).ReplaceAllString(code, "$1")
|
||||
code = constUniforms(code, regexp.MustCompile(`(?m)^\t((?:\w+) (U\d+)(?:\[\d+\])?) : packoffset\(\w+(?:\.\w)?\);$`), p, words, true)
|
||||
src := code + `
|
||||
float4 effect(float2 p, Effect e) {
|
||||
return shaderFragment(float4(p, 0, 1), p - e.rect.xy);
|
||||
}`
|
||||
if _, err := d3d11.CompileEffect(src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fx := &scene.Effect{
|
||||
Name: "shader",
|
||||
HLSL: scene.EffectCode{Source: src},
|
||||
Pixels: func() scene.EffectPixels { return &shaderPixels{prog: prog, in: &interp.Inputs{Uniforms: words}} },
|
||||
}
|
||||
s := effectScene(fx)
|
||||
pix, stride, err := d3d11.RenderOffscreen(s)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D:", err)
|
||||
}
|
||||
gputest.Compare(t, "shader-d3d11", pix, stride, s)
|
||||
}
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
// Package interp runs shaders on the CPU, for MyGo's CPU renderer: it
|
||||
// compiles a program of package shaderir into Go closures, which compute
|
||||
// what the GPU renderers' code computes, within the rounding of their
|
||||
// floats.
|
||||
//
|
||||
// Values are lanes of 32 bits in a register file, floats as their bits,
|
||||
// ints as their two's complement and bools as 0 and 1; vectors, matrices
|
||||
// (by columns) and arrays are runs of lanes. Shaders call no function
|
||||
// recursively, so each function has registers of its own, and running
|
||||
// one allocates nothing.
|
||||
package interp
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
)
|
||||
|
||||
// Image is an image a shader reads: its size in pixels, and its pixels,
|
||||
// premultiplied, from 0 to 1.
|
||||
type Image interface {
|
||||
Size() (w, h int)
|
||||
At(x, y int) [4]float32
|
||||
}
|
||||
|
||||
// Inputs are what a program reads: its uniform variables, as the words of
|
||||
// their lanes, in the order of the program's, and its images.
|
||||
type Inputs struct {
|
||||
Uniforms []uint32
|
||||
Images []Image
|
||||
}
|
||||
|
||||
// Program is a shader compiled for the CPU. It is safe for concurrent
|
||||
// use.
|
||||
type Program struct {
|
||||
entry *function
|
||||
position int // the registers of the entry point's position
|
||||
varyings []int // and of its varyings
|
||||
words int // the uniforms' words
|
||||
regs int
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
// state is a run's: its registers, inputs, and whether it discarded the
|
||||
// pixel.
|
||||
type state struct {
|
||||
r []uint32
|
||||
in *Inputs
|
||||
discard bool
|
||||
}
|
||||
|
||||
// UniformWords returns how many words each of p's uniform variables
|
||||
// takes in Inputs.Uniforms.
|
||||
func UniformWords(p *shaderir.Program) []int {
|
||||
words := make([]int, len(p.Uniforms))
|
||||
for i := range p.Uniforms {
|
||||
words[i] = lanes(&p.Uniforms[i])
|
||||
}
|
||||
return words
|
||||
}
|
||||
|
||||
// New compiles p, a program with a fragment entry point.
|
||||
func New(p *shaderir.Program) (prog *Program, err error) {
|
||||
lib, entry, funcs := p.FragmentLibrary()
|
||||
if entry == nil {
|
||||
return nil, errors.New("interp: the program has no fragment entry point")
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
prog, err = nil, fmt.Errorf("interp: %v", r)
|
||||
}
|
||||
}()
|
||||
c := &compiler{p: lib, funcs: map[int]*function{}}
|
||||
for _, w := range UniformWords(lib) {
|
||||
c.uniforms = append(c.uniforms, c.words)
|
||||
c.words += w
|
||||
}
|
||||
// Registers for every function first, so that bodies can call any.
|
||||
for _, f := range funcs {
|
||||
c.funcs[f.Index] = c.declare(f)
|
||||
}
|
||||
for _, f := range funcs {
|
||||
c.define(c.funcs[f.Index])
|
||||
}
|
||||
e := c.funcs[entry.Index]
|
||||
prog = &Program{entry: e, position: e.params[0].off, words: c.words, regs: c.size}
|
||||
for i := 1; i < len(entry.InParams); i++ {
|
||||
prog.varyings = append(prog.varyings, e.params[i].off)
|
||||
}
|
||||
prog.pool.New = func() any { return &state{r: make([]uint32, prog.regs)} }
|
||||
return prog, nil
|
||||
}
|
||||
|
||||
// Color returns the color the entry point returns for the pixel at
|
||||
// position, with the varyings' lanes in order, and false where it
|
||||
// discards the pixel.
|
||||
func (p *Program) Color(in *Inputs, position [4]float32, varyings ...float32) ([4]float32, bool) {
|
||||
s := p.pool.Get().(*state)
|
||||
defer p.pool.Put(s)
|
||||
if len(in.Uniforms) < p.words {
|
||||
return [4]float32{}, false
|
||||
}
|
||||
s.in, s.discard = in, false
|
||||
for i, v := range position {
|
||||
s.r[p.position+i] = math.Float32bits(v)
|
||||
}
|
||||
// The varyings' lanes follow one another in the arguments.
|
||||
lane := 0
|
||||
for vi, off := range p.varyings {
|
||||
n := p.entry.params[vi+1].n
|
||||
for i := range n {
|
||||
if lane < len(varyings) {
|
||||
s.r[off+i] = math.Float32bits(varyings[lane])
|
||||
}
|
||||
lane++
|
||||
}
|
||||
}
|
||||
p.entry.run(s)
|
||||
if s.discard {
|
||||
return [4]float32{}, false
|
||||
}
|
||||
var out [4]float32
|
||||
for i := range out {
|
||||
out[i] = math.Float32frombits(s.r[p.entry.ret.off+i])
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// lanes returns how many lanes a value of type t takes.
|
||||
func lanes(t *shaderir.Type) int {
|
||||
switch t.Main {
|
||||
case shaderir.Bool, shaderir.Int, shaderir.Uint, shaderir.Float, shaderir.Texture:
|
||||
return 1
|
||||
case shaderir.Vec2, shaderir.IVec2, shaderir.UVec2:
|
||||
return 2
|
||||
case shaderir.Vec3, shaderir.IVec3, shaderir.UVec3:
|
||||
return 3
|
||||
case shaderir.Vec4, shaderir.IVec4, shaderir.UVec4, shaderir.Mat2:
|
||||
return 4
|
||||
case shaderir.Mat3:
|
||||
return 9
|
||||
case shaderir.Mat4:
|
||||
return 16
|
||||
case shaderir.Array:
|
||||
return t.Length * lanes(&t.Sub[0])
|
||||
case shaderir.Struct:
|
||||
n := 0
|
||||
for i := range t.Sub {
|
||||
n += lanes(&t.Sub[i])
|
||||
}
|
||||
return n
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// slot is where a value lies in the registers.
|
||||
type slot struct {
|
||||
off, n int
|
||||
t shaderir.Type
|
||||
}
|
||||
|
||||
// function is a function compiled: the registers of its parameters,
|
||||
// inputs then outputs, and of its result, and its body. Its other locals
|
||||
// have registers in the blocks declaring them (compiler.scopes): an index
|
||||
// names a local of the innermost block around that declares it, as the
|
||||
// backends declare them, in blocks of C.
|
||||
type function struct {
|
||||
f *shaderir.Func
|
||||
params []slot
|
||||
ret slot
|
||||
body []stmt
|
||||
}
|
||||
|
||||
// control tells what a statement did: went on, or broke out of a loop,
|
||||
// went on to its next iteration, returned or discarded the pixel.
|
||||
type control uint8
|
||||
|
||||
const (
|
||||
next control = iota
|
||||
breakLoop
|
||||
continueLoop
|
||||
returned
|
||||
)
|
||||
|
||||
type stmt func(s *state) control
|
||||
|
||||
func (f *function) run(s *state) {
|
||||
for _, st := range f.body {
|
||||
if st(s) != next || s.discard {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type compiler struct {
|
||||
p *shaderir.Program
|
||||
funcs map[int]*function
|
||||
uniforms []int // each uniform's first word
|
||||
words int
|
||||
size int
|
||||
// scopes are the locals of the blocks around what is being compiled,
|
||||
// the innermost last.
|
||||
scopes []map[int]slot
|
||||
}
|
||||
|
||||
// local returns the registers of local index of fn where it is being
|
||||
// compiled.
|
||||
func (c *compiler) local(fn *function, index int) slot {
|
||||
for i := len(c.scopes) - 1; i >= 0; i-- {
|
||||
if l, ok := c.scopes[i][index]; ok {
|
||||
return l
|
||||
}
|
||||
}
|
||||
if index < len(fn.params) {
|
||||
return fn.params[index]
|
||||
}
|
||||
panic(fmt.Sprintf("no local %d", index))
|
||||
}
|
||||
|
||||
func (c *compiler) alloc(t shaderir.Type) slot {
|
||||
n := lanes(&t)
|
||||
s := slot{off: c.size, n: n, t: t}
|
||||
c.size += n
|
||||
return s
|
||||
}
|
||||
|
||||
// declare gives f's parameters and result registers of their own.
|
||||
func (c *compiler) declare(f *shaderir.Func) *function {
|
||||
fn := &function{f: f}
|
||||
for _, t := range append(append([]shaderir.Type(nil), f.InParams...), f.OutParams...) {
|
||||
fn.params = append(fn.params, c.alloc(t))
|
||||
}
|
||||
if f.Return.Main != shaderir.None {
|
||||
fn.ret = c.alloc(f.Return)
|
||||
}
|
||||
return fn
|
||||
}
|
||||
|
||||
func (c *compiler) define(fn *function) {
|
||||
fn.body = c.block(fn, fn.f.Block)
|
||||
}
|
||||
|
||||
// env is a function's types.
|
||||
type env struct {
|
||||
c *compiler
|
||||
fn *function
|
||||
}
|
||||
|
||||
func (e env) LocalType(index int) shaderir.Type { return e.c.local(e.fn, index).t }
|
||||
func (e env) UniformType(index int) shaderir.Type { return e.c.p.Uniforms[index] }
|
||||
func (e env) FuncReturn(index int) shaderir.Type { return e.c.funcs[index].f.Return }
|
||||
@@ -0,0 +1,356 @@
|
||||
package interp_test
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/shader"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/interp"
|
||||
)
|
||||
|
||||
func compile(t *testing.T, src string) (*shaderir.Program, *interp.Program) {
|
||||
t.Helper()
|
||||
p, err := shader.CompileFragment([]byte(src))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prog, err := interp.New(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p, prog
|
||||
}
|
||||
|
||||
// uniforms packs values by name as the program's uniform words.
|
||||
func uniforms(p *shaderir.Program, values map[string][]uint32) []uint32 {
|
||||
var out []uint32
|
||||
for i, w := range interp.UniformWords(p) {
|
||||
v := values[p.UniformNames[i]]
|
||||
for j := range w {
|
||||
if j < len(v) {
|
||||
out = append(out, v[j])
|
||||
} else {
|
||||
out = append(out, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func f(v ...float32) []uint32 {
|
||||
out := make([]uint32, len(v))
|
||||
for i := range v {
|
||||
out[i] = math.Float32bits(v[i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func pcg(v uint32) uint32 {
|
||||
s := v*747796405 + 2891336453
|
||||
w := ((s >> ((s >> 28) + 4)) ^ s) * 277803737
|
||||
return (w >> 22) ^ w
|
||||
}
|
||||
|
||||
const hashSource = `package main
|
||||
|
||||
var Seed uint
|
||||
|
||||
func pcg(v uint) uint {
|
||||
s := v*747796405 + 2891336453
|
||||
w := ((s >> ((s >> 28) + 4)) ^ s) * 277803737
|
||||
return (w >> 22) ^ w
|
||||
}
|
||||
|
||||
func unit(h uint) float {
|
||||
return float(h>>8) * (1.0 / 16777216.0)
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
c := uvec2(dst.xy)
|
||||
h := pcg(c.x*0x9E3779B9 ^ pcg(c.y^Seed))
|
||||
return vec4(unit(h), unit(pcg(h)), float(h%7)/7, 1)
|
||||
}
|
||||
`
|
||||
|
||||
// Unsigned arithmetic wraps around and shifts in zeros, as Go's uint32.
|
||||
func TestHash(t *testing.T) {
|
||||
p, prog := compile(t, hashSource)
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, map[string][]uint32{"Seed": {0x3fa1c2d9}})}
|
||||
unit := func(h uint32) float32 { return float32(h>>8) * (1.0 / 16777216.0) }
|
||||
for y := range 16 {
|
||||
for x := range 16 {
|
||||
got, ok := prog.Color(in, [4]float32{float32(x) + 0.5, float32(y) + 0.5, 0, 1}, float32(x)+0.5, float32(y)+0.5)
|
||||
h := pcg(uint32(x)*0x9E3779B9 ^ pcg(uint32(y)^0x3fa1c2d9))
|
||||
want := [4]float32{unit(h), unit(pcg(h)), float32(h%7) / 7, 1}
|
||||
if !ok || got != want {
|
||||
t.Fatalf("(%d, %d): %v, want %v", x, y, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Loops run to bounds that are not constants, functions return several
|
||||
// results through output parameters, and assignments reach elements and
|
||||
// swizzles.
|
||||
func TestStatements(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
var Count int
|
||||
var Weights [4]float
|
||||
|
||||
func split(x float) (float, float) {
|
||||
return floor(x), fract(x)
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
sum := 0.0
|
||||
for i := 0; i < Count; i++ {
|
||||
if i == 2 {
|
||||
continue
|
||||
}
|
||||
sum += Weights[i]
|
||||
}
|
||||
var a [3]float
|
||||
for i := range 3 {
|
||||
a[i] = float(i) * 2
|
||||
}
|
||||
a[Count-3] = 10
|
||||
whole, part := split(pos.x)
|
||||
v := vec4(0)
|
||||
v.zx = vec2(whole, part)
|
||||
v.y = a[0] + a[1] + a[2]
|
||||
v.w = sum
|
||||
return v
|
||||
}
|
||||
`)
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, map[string][]uint32{
|
||||
"Count": {4},
|
||||
"Weights": f(1, 2, 4, 8),
|
||||
})}
|
||||
got, _ := prog.Color(in, [4]float32{}, 2.25, 0)
|
||||
// a = {0, 10, 4}; Weights without the third: 1 + 2 + 8.
|
||||
if want := [4]float32{0.25, 14, 2, 11}; got != want {
|
||||
t.Errorf("%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Matrices are products of columns, and the built-in functions compute
|
||||
// what GLSL's do.
|
||||
func TestBuiltins(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
var M mat2
|
||||
var X float
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
v := M * vec2(1, 2)
|
||||
w := vec2(1, 2) * M
|
||||
s := smoothstep(0, 4, X) + mix(1.0, 3.0, 0.25) + clamp(X, 0, 1) + step(2, X)
|
||||
return vec4(v.x+v.y*10, w.x+w.y*10, s, mod(-X, 1.5) + max(1, 2, X) + min(vec2(X), 0).x + abs(-2.0))
|
||||
}
|
||||
`)
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, map[string][]uint32{
|
||||
"M": f(1, 2, 3, 4), // columns (1, 2) and (3, 4)
|
||||
"X": f(3),
|
||||
})}
|
||||
got, _ := prog.Color(in, [4]float32{}, 0, 0)
|
||||
// M*(1,2) = (7, 10); (1,2)*M = (5, 11).
|
||||
sm := float32(0.75 * 0.75 * (3 - 1.5))
|
||||
want := [4]float32{7 + 100, 5 + 110, sm + 1.5 + 1 + 1, 0 + 3 + 0 + 2}
|
||||
for i := range got {
|
||||
if math.Abs(float64(got[i]-want[i])) > 1e-5 {
|
||||
t.Errorf("component %d: %v, want %v", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type testImage struct {
|
||||
w, h int
|
||||
pix [][4]float32
|
||||
}
|
||||
|
||||
func (m *testImage) Size() (int, int) { return m.w, m.h }
|
||||
func (m *testImage) At(x, y int) [4]float32 { return m.pix[y*m.w+x] }
|
||||
|
||||
// Images are read pixel by pixel, transparent outside, and sampled
|
||||
// between pixels' centers, clamped to their edges.
|
||||
func TestImages(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
var At vec2
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
return vec4(image0At(At).r, image0Sample(At).r, image1At(vec2(0)).g, image0Size().x)
|
||||
}
|
||||
`)
|
||||
img := &testImage{w: 2, h: 2, pix: [][4]float32{{0, 0, 0, 1}, {1, 0, 0, 1}, {0.5, 0, 0, 1}, {0.25, 0, 0, 1}}}
|
||||
for _, c := range []struct {
|
||||
at [2]float32
|
||||
pixel, sampled float32
|
||||
}{
|
||||
{[2]float32{0.5, 0.5}, 0, 0},
|
||||
{[2]float32{1, 0.5}, 1, 0.5},
|
||||
{[2]float32{1, 1}, 0.25, 0.4375},
|
||||
{[2]float32{-1, 0.5}, 0, 0},
|
||||
{[2]float32{5, 5}, 0, 0.25},
|
||||
} {
|
||||
in := &interp.Inputs{
|
||||
Uniforms: uniforms(p, map[string][]uint32{"At": f(c.at[0], c.at[1]), "__imageSizes": f(2, 2)}),
|
||||
Images: []interp.Image{img},
|
||||
}
|
||||
got, _ := prog.Color(in, [4]float32{}, 0, 0)
|
||||
if got[0] != c.pixel || math.Abs(float64(got[1]-c.sampled)) > 1e-6 || got[2] != 0 || got[3] != 2 {
|
||||
t.Errorf("at %v: %v, want pixel %v, sampled %v, no image 1, width 2", c.at, got, c.pixel, c.sampled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A discarded pixel has no color.
|
||||
func TestDiscard(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
if pos.x < 1 {
|
||||
discard()
|
||||
}
|
||||
return vec4(1)
|
||||
}
|
||||
`)
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, nil)}
|
||||
if _, ok := prog.Color(in, [4]float32{}, 0.5, 0); ok {
|
||||
t.Error("a pixel the shader discards has a color")
|
||||
}
|
||||
if c, ok := prog.Color(in, [4]float32{}, 1.5, 0); !ok || c != [4]float32{1, 1, 1, 1} {
|
||||
t.Errorf("%v, %v, want white", c, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// A local's index names the variable of the innermost block declaring
|
||||
// it: a block after a loop reuses the indices of the loop's locals, with
|
||||
// types of its own.
|
||||
func TestScopes(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
var Count int
|
||||
var Taps [4]vec4
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
glow := 0.0
|
||||
for i := 0; i < Count; i++ {
|
||||
d := distance(pos, Taps[i].xy)
|
||||
glow += Taps[i].z * exp(-d*d/(Taps[i].w*Taps[i].w))
|
||||
}
|
||||
c := vec3(1, 2, glow)
|
||||
c.rb = c.br
|
||||
return vec4(c, glow)
|
||||
}
|
||||
`)
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, map[string][]uint32{
|
||||
"Count": {2},
|
||||
"Taps": f(0, 0, 1, 10, 30, 0, 0.5, 20, 0, 0, 0, 0, 0, 0, 0, 0),
|
||||
})}
|
||||
got, _ := prog.Color(in, [4]float32{}, 30, 0)
|
||||
glow := float32(math.Exp(-9)) + 0.5
|
||||
if want := [4]float32{glow, 2, 1, glow}; math.Abs(float64(got[0]-want[0])) > 1e-6 || got[1] != 2 || got[2] != 1 {
|
||||
t.Errorf("%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkNoise(b *testing.B) {
|
||||
p, err := shader.CompileFragment([]byte(noiseSource))
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
prog, err := interp.New(p)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
in := &interp.Inputs{Uniforms: noiseUniforms(p)}
|
||||
b.ReportAllocs()
|
||||
for i := range b.N {
|
||||
x := float32(i % 256)
|
||||
prog.Color(in, [4]float32{x, 10, 0, 1}, x, 10)
|
||||
}
|
||||
}
|
||||
|
||||
// A range reads its count once, as Go does, though the body changes it;
|
||||
// smoothstep between equal edges is 0, as GPUs clamp its NaN.
|
||||
func TestRangeAndSmoothstep(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
var N int
|
||||
var X float
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
n := N
|
||||
sum := 0.0
|
||||
for i := range n {
|
||||
n--
|
||||
sum += 1
|
||||
_ = i
|
||||
}
|
||||
return vec4(sum, float(n), smoothstep(X, X, X), 0)
|
||||
}
|
||||
`)
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, map[string][]uint32{"N": {5}, "X": f(0.5)})}
|
||||
got, _ := prog.Color(in, [4]float32{}, 0, 0)
|
||||
if want := [4]float32{5, 0, 0, 0}; got != want {
|
||||
t.Errorf("%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A uint's complement is in its 32 bits, ints shift by uints, ranges run
|
||||
// over uints and index arrays with them, uint loops run past int's
|
||||
// range, and a shift of an untyped constant takes the type of its
|
||||
// context, as in Go.
|
||||
func TestUintForms(t *testing.T) {
|
||||
p, prog := compile(t, `package main
|
||||
|
||||
var Seed uint
|
||||
var Shift int
|
||||
|
||||
const N uint = 7
|
||||
|
||||
func top(m int) uint {
|
||||
return 1 << m
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
var bits [4]uint
|
||||
for i := range Seed%3 + 1 {
|
||||
bits[i] = ^uint(0) >> (i * 8)
|
||||
}
|
||||
s := int(pos.x)
|
||||
s >>= Seed % 3
|
||||
sel := bits[uint(int(pos.y))%4] & (1 << (s % 31))
|
||||
sum := uint(0)
|
||||
for j := uint(4294967290); j < 4294967295; j++ {
|
||||
sum += j & N
|
||||
}
|
||||
var shifted uint = 1 << Shift
|
||||
return vec4(float(sel>>8), float(shifted|^(1<<Shift)&N), float(sum), float(top(Shift)|N&(1<<Shift)))
|
||||
}
|
||||
`)
|
||||
const seed, shift = 0x3fa1c2d9, 2
|
||||
in := &interp.Inputs{Uniforms: uniforms(p, map[string][]uint32{"Seed": {seed}, "Shift": {shift}})}
|
||||
for _, pos := range [][2]float32{{60, 0}, {80, 1}, {40, 2}, {60, 3}, {100, 1}} {
|
||||
var bits [4]uint32
|
||||
for i := range uint32(seed%3 + 1) {
|
||||
bits[i] = ^uint32(0) >> (i * 8)
|
||||
}
|
||||
s := int32(pos[0])
|
||||
s >>= uint32(seed % 3)
|
||||
sel := bits[uint32(int32(pos[1]))%4] & (1 << (s % 31))
|
||||
sum := uint32(0)
|
||||
for j := uint32(4294967290); j < 4294967295; j++ {
|
||||
sum += j & 7
|
||||
}
|
||||
var shifted uint32 = 1 << shift
|
||||
want := [4]float32{float32(sel >> 8), float32(shifted | ^uint32(1<<shift)&7), float32(sum), float32(uint32(1<<shift) | 7&(1<<shift))}
|
||||
got, _ := prog.Color(in, [4]float32{}, pos[0], pos[1])
|
||||
if got != want {
|
||||
t.Errorf("%v: %v, want %v", pos, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package interp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
)
|
||||
|
||||
func f32(b uint32) float32 { return math.Float32frombits(b) }
|
||||
func bits(f float32) uint32 { return math.Float32bits(f) }
|
||||
|
||||
func boolBits(b bool) uint32 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// arith returns op on two lanes of kind.
|
||||
func arith(op shaderir.Op, kind shaderir.BasicType) func(a, b uint32) uint32 {
|
||||
switch kind {
|
||||
case shaderir.Float:
|
||||
switch op {
|
||||
case shaderir.Add:
|
||||
return func(a, b uint32) uint32 { return bits(f32(a) + f32(b)) }
|
||||
case shaderir.Sub:
|
||||
return func(a, b uint32) uint32 { return bits(f32(a) - f32(b)) }
|
||||
case shaderir.ComponentWiseMul, shaderir.MatrixMul:
|
||||
return func(a, b uint32) uint32 { return bits(f32(a) * f32(b)) }
|
||||
case shaderir.Div:
|
||||
return func(a, b uint32) uint32 { return bits(f32(a) / f32(b)) }
|
||||
}
|
||||
case shaderir.Int:
|
||||
switch op {
|
||||
case shaderir.Add:
|
||||
return func(a, b uint32) uint32 { return uint32(int32(a) + int32(b)) }
|
||||
case shaderir.Sub:
|
||||
return func(a, b uint32) uint32 { return uint32(int32(a) - int32(b)) }
|
||||
case shaderir.ComponentWiseMul, shaderir.MatrixMul:
|
||||
return func(a, b uint32) uint32 { return uint32(int32(a) * int32(b)) }
|
||||
case shaderir.Div:
|
||||
// Dividing by zero is undefined on GPUs; here it gives zero.
|
||||
return func(a, b uint32) uint32 {
|
||||
if b == 0 || int32(a) == math.MinInt32 && int32(b) == -1 {
|
||||
return 0
|
||||
}
|
||||
return uint32(int32(a) / int32(b))
|
||||
}
|
||||
case shaderir.ModOp:
|
||||
return func(a, b uint32) uint32 {
|
||||
if b == 0 || int32(b) == -1 {
|
||||
return 0
|
||||
}
|
||||
return uint32(int32(a) % int32(b))
|
||||
}
|
||||
}
|
||||
case shaderir.Uint:
|
||||
switch op {
|
||||
case shaderir.Add:
|
||||
return func(a, b uint32) uint32 { return a + b }
|
||||
case shaderir.Sub:
|
||||
return func(a, b uint32) uint32 { return a - b }
|
||||
case shaderir.ComponentWiseMul, shaderir.MatrixMul:
|
||||
return func(a, b uint32) uint32 { return a * b }
|
||||
case shaderir.Div:
|
||||
return func(a, b uint32) uint32 {
|
||||
if b == 0 {
|
||||
return 0
|
||||
}
|
||||
return a / b
|
||||
}
|
||||
case shaderir.ModOp:
|
||||
return func(a, b uint32) uint32 {
|
||||
if b == 0 {
|
||||
return 0
|
||||
}
|
||||
return a % b
|
||||
}
|
||||
}
|
||||
}
|
||||
switch op {
|
||||
case shaderir.And:
|
||||
return func(a, b uint32) uint32 { return a & b }
|
||||
case shaderir.AndNot:
|
||||
return func(a, b uint32) uint32 { return a &^ b }
|
||||
case shaderir.Or:
|
||||
return func(a, b uint32) uint32 { return a | b }
|
||||
case shaderir.Xor:
|
||||
return func(a, b uint32) uint32 { return a ^ b }
|
||||
case shaderir.LeftShift:
|
||||
return func(a, b uint32) uint32 { return a << (b & 31) }
|
||||
case shaderir.RightShift:
|
||||
if kind == shaderir.Int {
|
||||
return func(a, b uint32) uint32 { return uint32(int32(a) >> (b & 31)) }
|
||||
}
|
||||
return func(a, b uint32) uint32 { return a >> (b & 31) }
|
||||
case shaderir.AndAnd:
|
||||
return func(a, b uint32) uint32 { return a & b }
|
||||
case shaderir.OrOr:
|
||||
return func(a, b uint32) uint32 { return a | b }
|
||||
}
|
||||
panic(fmt.Sprintf("unexpected operator %d on %d", op, kind))
|
||||
}
|
||||
|
||||
// compare returns a comparison of two lanes of kind, 1 for true.
|
||||
func compare(op shaderir.Op, kind shaderir.BasicType) func(a, b uint32) uint32 {
|
||||
var less func(a, b uint32) bool
|
||||
eq := func(a, b uint32) bool { return a == b }
|
||||
switch kind {
|
||||
case shaderir.Float:
|
||||
less = func(a, b uint32) bool { return f32(a) < f32(b) }
|
||||
eq = func(a, b uint32) bool { return f32(a) == f32(b) }
|
||||
case shaderir.Int:
|
||||
less = func(a, b uint32) bool { return int32(a) < int32(b) }
|
||||
default:
|
||||
less = func(a, b uint32) bool { return a < b }
|
||||
}
|
||||
switch op {
|
||||
case shaderir.LessThanOp:
|
||||
return func(a, b uint32) uint32 { return boolBits(less(a, b)) }
|
||||
case shaderir.LessThanEqualOp:
|
||||
return func(a, b uint32) uint32 { return boolBits(less(a, b) || eq(a, b)) }
|
||||
case shaderir.GreaterThanOp:
|
||||
return func(a, b uint32) uint32 { return boolBits(less(b, a)) }
|
||||
case shaderir.GreaterThanEqualOp:
|
||||
return func(a, b uint32) uint32 { return boolBits(less(b, a) || eq(a, b)) }
|
||||
case shaderir.EqualOp, shaderir.VectorEqualOp:
|
||||
return func(a, b uint32) uint32 { return boolBits(eq(a, b)) }
|
||||
case shaderir.NotEqualOp, shaderir.VectorNotEqualOp:
|
||||
return func(a, b uint32) uint32 { return boolBits(!eq(a, b)) }
|
||||
}
|
||||
panic(fmt.Sprintf("unexpected comparison %d", op))
|
||||
}
|
||||
|
||||
func (c *compiler) unary(fn *function, e *shaderir.Expr) operand {
|
||||
x := c.expr(fn, &e.Exprs[0])
|
||||
if e.Op == shaderir.Add {
|
||||
return x
|
||||
}
|
||||
o := c.alloc(x.t)
|
||||
n, kind := o.n, x.t.Scalar()
|
||||
var f func(uint32) uint32
|
||||
switch e.Op {
|
||||
case shaderir.Sub:
|
||||
switch kind {
|
||||
case shaderir.Float:
|
||||
f = func(a uint32) uint32 { return a ^ 0x80000000 }
|
||||
default:
|
||||
f = func(a uint32) uint32 { return -a }
|
||||
}
|
||||
case shaderir.NotOp:
|
||||
f = func(a uint32) uint32 { return a ^ 1 }
|
||||
case shaderir.ComplementOp:
|
||||
f = func(a uint32) uint32 { return ^a }
|
||||
default:
|
||||
panic(fmt.Sprintf("unexpected unary operator %d", e.Op))
|
||||
}
|
||||
return operand{off: o.off, t: x.t, run: func(s *state) {
|
||||
eval(s, x)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = f(s.r[x.off+i])
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
func (c *compiler) binary(fn *function, e *shaderir.Expr) operand {
|
||||
l, r := c.expr(fn, &e.Exprs[0]), c.expr(fn, &e.Exprs[1])
|
||||
t := shaderir.TypeOf(e, env{c, fn})
|
||||
o := c.alloc(t)
|
||||
ln, rn := l.n(), r.n()
|
||||
|
||||
// A matrix times a vector or a matrix; times a scalar, it goes lane by
|
||||
// lane.
|
||||
if e.Op == shaderir.MatrixMul && (l.t.IsMatrix() || r.t.IsMatrix()) && ln > 1 && rn > 1 {
|
||||
return c.matrixMul(l, r, o)
|
||||
}
|
||||
|
||||
switch e.Op {
|
||||
case shaderir.LessThanOp, shaderir.LessThanEqualOp, shaderir.GreaterThanOp, shaderir.GreaterThanEqualOp:
|
||||
cmp := compare(e.Op, l.t.Scalar())
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, l, r)
|
||||
s.r[o.off] = cmp(s.r[l.off], s.r[r.off])
|
||||
}}
|
||||
case shaderir.EqualOp, shaderir.VectorEqualOp, shaderir.NotEqualOp, shaderir.VectorNotEqualOp:
|
||||
eq := compare(shaderir.EqualOp, l.t.Scalar())
|
||||
want := uint32(1)
|
||||
if e.Op == shaderir.NotEqualOp || e.Op == shaderir.VectorNotEqualOp {
|
||||
want = 0
|
||||
}
|
||||
n := ln
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, l, r)
|
||||
all := uint32(1)
|
||||
for i := range n {
|
||||
all &= eq(s.r[l.off+i], s.r[r.off+i])
|
||||
}
|
||||
s.r[o.off] = boolBits(all == want)
|
||||
}}
|
||||
}
|
||||
|
||||
// Lane by lane, a scalar going with every lane of the other operand.
|
||||
op := arith(e.Op, l.t.Scalar())
|
||||
n := o.n
|
||||
ls, rs := 1, 1
|
||||
if ln == 1 {
|
||||
ls = 0
|
||||
}
|
||||
if rn == 1 {
|
||||
rs = 0
|
||||
}
|
||||
return operand{off: o.off, t: t, run: func(s *state) {
|
||||
eval(s, l, r)
|
||||
for i := range n {
|
||||
s.r[o.off+i] = op(s.r[l.off+i*ls], s.r[r.off+i*rs])
|
||||
}
|
||||
}}
|
||||
}
|
||||
|
||||
// matrixMul compiles the product of a matrix and a vector, a vector and a
|
||||
// matrix, or two matrices, whose columns follow one another.
|
||||
func (c *compiler) matrixMul(l, r operand, o slot) operand {
|
||||
switch {
|
||||
case l.t.IsMatrix() && r.t.IsMatrix():
|
||||
n := l.t.MatrixSize()
|
||||
return operand{off: o.off, t: o.t, run: func(s *state) {
|
||||
eval(s, l, r)
|
||||
for col := range n {
|
||||
for row := range n {
|
||||
var sum float32
|
||||
for k := range n {
|
||||
sum += f32(s.r[l.off+k*n+row]) * f32(s.r[r.off+col*n+k])
|
||||
}
|
||||
s.r[o.off+col*n+row] = bits(sum)
|
||||
}
|
||||
}
|
||||
}}
|
||||
case l.t.IsMatrix():
|
||||
n := l.t.MatrixSize()
|
||||
return operand{off: o.off, t: o.t, run: func(s *state) {
|
||||
eval(s, l, r)
|
||||
for row := range n {
|
||||
var sum float32
|
||||
for k := range n {
|
||||
sum += f32(s.r[l.off+k*n+row]) * f32(s.r[r.off+k])
|
||||
}
|
||||
s.r[o.off+row] = bits(sum)
|
||||
}
|
||||
}}
|
||||
default:
|
||||
n := r.t.MatrixSize()
|
||||
return operand{off: o.off, t: o.t, run: func(s *state) {
|
||||
eval(s, l, r)
|
||||
for col := range n {
|
||||
var sum float32
|
||||
for k := range n {
|
||||
sum += f32(s.r[l.off+k]) * f32(s.r[r.off+col*n+k])
|
||||
}
|
||||
s.r[o.off+col] = bits(sum)
|
||||
}
|
||||
}}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package interp_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/shaderir"
|
||||
"github.com/egoist/mygo/internal/shaderir/interp"
|
||||
)
|
||||
|
||||
// noiseSource is a shader of what textures computed in shaders are made
|
||||
// of, for the GPU renderers to draw as the interpreter does: hashes of
|
||||
// unsigned integers, value noise from them, loops over uniform arrays to
|
||||
// a count that is not a constant, swizzles, a matrix, and the usual
|
||||
// functions.
|
||||
const noiseSource = `package main
|
||||
|
||||
var Seed uint
|
||||
var Time float
|
||||
var Count int
|
||||
var Taps [4]vec4
|
||||
var Turn mat2
|
||||
|
||||
func pcg(v uint) uint {
|
||||
s := v*747796405 + 2891336453
|
||||
w := ((s >> ((s >> 28) + 4)) ^ s) * 277803737
|
||||
return (w >> 22) ^ w
|
||||
}
|
||||
|
||||
func unit(h uint) float {
|
||||
return float(h>>8) * (1.0 / 16777216.0)
|
||||
}
|
||||
|
||||
func value(p vec2) float {
|
||||
i := floor(p)
|
||||
f := p - i
|
||||
w := f * f * (3 - 2*f)
|
||||
x0, y0 := uint(int(i.x)), uint(int(i.y))
|
||||
a := unit(pcg(x0 ^ pcg(y0^Seed)))
|
||||
b := unit(pcg((x0 + 1) ^ pcg(y0^Seed)))
|
||||
c := unit(pcg(x0 ^ pcg((y0+1)^Seed)))
|
||||
d := unit(pcg((x0 + 1) ^ pcg((y0+1)^Seed)))
|
||||
return mix(mix(a, b, w.x), mix(c, d, w.x), w.y)
|
||||
}
|
||||
|
||||
func Fragment(dst vec4, pos vec2) vec4 {
|
||||
q := Turn * pos
|
||||
n := value(q/9 + Time) * 0.6 + value(q/4) * 0.4
|
||||
glow := 0.0
|
||||
for i := 0; i < Count; i++ {
|
||||
d := distance(pos, Taps[i].xy)
|
||||
glow += Taps[i].z * exp(-d*d/(Taps[i].w*Taps[i].w))
|
||||
}
|
||||
// A uint loop by twos, a uvec of one scalar, a range over a count the
|
||||
// body changes (read once, as Go reads it), and smoothstep between
|
||||
// equal edges (0, not NaN).
|
||||
k := 0.0
|
||||
for j := uint(0); j < Seed%7+uint(int(pos.x/40)); j += 2 {
|
||||
k += 0.02
|
||||
}
|
||||
m := Count + int(pos.y/30)
|
||||
for i := range m {
|
||||
m--
|
||||
k += 0.01 * float(i+1)
|
||||
}
|
||||
u := uvec3(Seed + uint(int(pos.x)))
|
||||
k += float(u.y%5)*0.01 + smoothstep(Time, Time, Time)
|
||||
// A uint's complement, an int shifted by a uint, a range over a uint
|
||||
// indexing an array, a shift of an untyped constant in a uint, and a
|
||||
// uint loop past int's range.
|
||||
var bits [4]uint
|
||||
for i := range Seed%3 + 1 {
|
||||
bits[i] = ^uint(0) >> (i * 8)
|
||||
}
|
||||
s := int(pos.x)
|
||||
s >>= Seed % 3
|
||||
sel := bits[uint(int(pos.y))%4] & (1 << (s % 31))
|
||||
k += float(sel>>(s%31)) * 0.03
|
||||
for j := uint(4294967290); j < 4294967293; j++ {
|
||||
k += float(j%3) * 0.01
|
||||
}
|
||||
c := vec3(n, smoothstep(0.2, 0.8, n), clamp(glow, 0, 1))
|
||||
c.rb = c.br * vec2(1, 0.5+0.5*sin(pos.x/7))
|
||||
c.g = fract(c.g + k)
|
||||
return vec4(c*0.9, 0.9)
|
||||
}
|
||||
`
|
||||
|
||||
// noiseUniforms returns the values of noiseSource's uniforms.
|
||||
func noiseUniforms(p *shaderir.Program) []uint32 {
|
||||
return uniforms(p, map[string][]uint32{
|
||||
"Seed": {0x3fa1c2d9},
|
||||
"Time": f(1.75),
|
||||
"Count": {3},
|
||||
"Taps": f(40, 30, 1, 20, 150, 60, 0.7, 35, 220, 100, 0.4, 50, 0, 0, 9, 1),
|
||||
"Turn": f(0.8, 0.6, -0.6, 0.8),
|
||||
})
|
||||
}
|
||||
|
||||
// effectScene returns a scene of fx over a white frame.
|
||||
func effectScene(fx *scene.Effect) *scene.Scene {
|
||||
s := &scene.Scene{Width: 240, Height: 120, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{X: 10, Y: 6, W: 220, H: 108}})
|
||||
s.Effects = append(s.Effects, scene.EffectOp{Effect: fx})
|
||||
return s
|
||||
}
|
||||
|
||||
// shaderPixels draws the effect with the interpreter.
|
||||
type shaderPixels struct {
|
||||
prog *interp.Program
|
||||
in *interp.Inputs
|
||||
rect scene.Rect
|
||||
}
|
||||
|
||||
func (s *shaderPixels) Begin(op *scene.EffectOp, rect scene.Rect, radii [4]float32) { s.rect = rect }
|
||||
|
||||
func (s *shaderPixels) Color(x, y float32, _ *scene.BackdropImage) [4]float32 {
|
||||
c, _ := s.prog.Color(s.in, [4]float32{x, y, 0, 1}, x-s.rect.X, y-s.rect.Y)
|
||||
return c
|
||||
}
|
||||
|
||||
// constUniforms replaces the uniform variables U0, U1, ... that the
|
||||
// declarations of code (a line each, matched by decl, with the variable
|
||||
// as its group) declare, with constants of their values: GLSL and HLSL
|
||||
// read them as globals.
|
||||
func constUniforms(code string, decl *regexp.Regexp, p *shaderir.Program, words []uint32, hlsl bool) string {
|
||||
vals := map[string]string{}
|
||||
k := 0
|
||||
for i := range p.Uniforms {
|
||||
t := &p.Uniforms[i]
|
||||
n := interp.UniformWords(p)[i]
|
||||
vals[fmt.Sprintf("U%d", i)] = literal(t, words[k:k+n], hlsl)
|
||||
k += n
|
||||
}
|
||||
return decl.ReplaceAllStringFunc(code, func(line string) string {
|
||||
m := decl.FindStringSubmatch(line)
|
||||
v, ok := vals[m[2]]
|
||||
if !ok {
|
||||
return line
|
||||
}
|
||||
if hlsl {
|
||||
return fmt.Sprintf("static const %s = %s;", m[1], v)
|
||||
}
|
||||
return fmt.Sprintf("const %s = %s;", m[1], v)
|
||||
})
|
||||
}
|
||||
|
||||
// literal returns the value of type t in words in GLSL or HLSL.
|
||||
func literal(t *shaderir.Type, words []uint32, hlsl bool) string {
|
||||
num := func(kind shaderir.BasicType, w uint32) string {
|
||||
switch kind {
|
||||
case shaderir.Float:
|
||||
s := fmt.Sprintf("%.9g", math.Float32frombits(w))
|
||||
if !strings.ContainsAny(s, ".e") {
|
||||
s += ".0"
|
||||
}
|
||||
return s
|
||||
case shaderir.Uint:
|
||||
return fmt.Sprintf("%du", w)
|
||||
case shaderir.Bool:
|
||||
return fmt.Sprint(w != 0)
|
||||
}
|
||||
return fmt.Sprint(int32(w))
|
||||
}
|
||||
if t.Main == shaderir.Array {
|
||||
n := len(words) / t.Length
|
||||
var es []string
|
||||
for i := range t.Length {
|
||||
es = append(es, literal(&t.Sub[0], words[i*n:(i+1)*n], hlsl))
|
||||
}
|
||||
if hlsl {
|
||||
return "{" + strings.Join(es, ", ") + "}"
|
||||
}
|
||||
return fmt.Sprintf("%s[%d](%s)", typeName(&t.Sub[0], hlsl), t.Length, strings.Join(es, ", "))
|
||||
}
|
||||
var es []string
|
||||
for _, w := range words {
|
||||
es = append(es, num(t.Scalar(), w))
|
||||
}
|
||||
if len(es) == 1 {
|
||||
return es[0]
|
||||
}
|
||||
// A matrix's lanes are its columns, which HLSL's constructor takes as
|
||||
// rows of the transposed matrix the HLSL backend keeps.
|
||||
return typeName(t, hlsl) + "(" + strings.Join(es, ", ") + ")"
|
||||
}
|
||||
|
||||
func typeName(t *shaderir.Type, hlsl bool) string {
|
||||
if !hlsl {
|
||||
return t.String()
|
||||
}
|
||||
switch t.Main {
|
||||
case shaderir.Vec2, shaderir.Vec3, shaderir.Vec4:
|
||||
return fmt.Sprintf("float%d", t.VectorElementCount())
|
||||
case shaderir.IVec2, shaderir.IVec3, shaderir.IVec4:
|
||||
return fmt.Sprintf("int%d", t.VectorElementCount())
|
||||
case shaderir.UVec2, shaderir.UVec3, shaderir.UVec4:
|
||||
return fmt.Sprintf("uint%d", t.VectorElementCount())
|
||||
case shaderir.Mat2, shaderir.Mat3, shaderir.Mat4:
|
||||
n := t.MatrixSize()
|
||||
return fmt.Sprintf("float%dx%d", n, n)
|
||||
}
|
||||
return t.String()
|
||||
}
|
||||
Reference in new issue
Block a user