| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package glwidget |
| 9 |
|
| 10 |
import ( |
| 11 |
"fmt" |
| 12 |
"image" |
| 13 |
"image/draw" |
| 14 |
|
| 15 |
"golang.org/x/exp/shiny/driver/gldriver" |
| 16 |
"golang.org/x/exp/shiny/widget/node" |
| 17 |
"golang.org/x/mobile/gl" |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
type GL struct { |
| 40 |
node.LeafEmbed |
| 41 |
|
| 42 |
Ctx gl.Context |
| 43 |
|
| 44 |
draw func(*GL) |
| 45 |
framebuffer gl.Framebuffer |
| 46 |
tex gl.Texture |
| 47 |
dst *image.RGBA |
| 48 |
origin image.Point |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
func NewGL(drawFunc func(*GL)) *GL { |
| 53 |
|
| 54 |
const maxWidth, maxHeight = 4096, 3072 |
| 55 |
|
| 56 |
glctx, err := gldriver.NewContext() |
| 57 |
if err != nil { |
| 58 |
panic(fmt.Sprintf("glwidget: %v", err)) |
| 59 |
} |
| 60 |
w := &GL{ |
| 61 |
Ctx: glctx, |
| 62 |
draw: drawFunc, |
| 63 |
} |
| 64 |
w.tex = w.Ctx.CreateTexture() |
| 65 |
w.Ctx.BindTexture(gl.TEXTURE_2D, w.tex) |
| 66 |
|
| 67 |
w.Ctx.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, maxWidth, maxHeight, gl.RGBA, gl.UNSIGNED_BYTE, nil) |
| 68 |
w.Ctx.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) |
| 69 |
w.Ctx.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) |
| 70 |
w.Ctx.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) |
| 71 |
w.Ctx.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) |
| 72 |
|
| 73 |
w.framebuffer = w.Ctx.CreateFramebuffer() |
| 74 |
w.Ctx.BindFramebuffer(gl.FRAMEBUFFER, w.framebuffer) |
| 75 |
w.Ctx.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, w.tex, 0) |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
w.Wrapper = w |
| 81 |
|
| 82 |
return w |
| 83 |
} |
| 84 |
|
| 85 |
func (w *GL) PaintBase(ctx *node.PaintBaseContext, origin image.Point) error { |
| 86 |
w.Marks.UnmarkNeedsPaintBase() |
| 87 |
if w.Rect.Empty() { |
| 88 |
return nil |
| 89 |
} |
| 90 |
w.dst = ctx.Dst |
| 91 |
w.origin = origin |
| 92 |
w.draw(w) |
| 93 |
w.dst = nil |
| 94 |
return nil |
| 95 |
} |
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
func (w *GL) Publish() { |
| 100 |
if w.dst == nil { |
| 101 |
panic("glwidget: no destination, Publish called outside of Draw") |
| 102 |
} |
| 103 |
|
| 104 |
m := image.NewRGBA(image.Rect(0, 0, w.Rect.Dx(), w.Rect.Dy())) |
| 105 |
w.Ctx.PixelStorei(gl.PACK_ALIGNMENT, 1) |
| 106 |
w.Ctx.ReadPixels(m.Pix, 0, 0, w.Rect.Dx(), w.Rect.Dy(), gl.RGBA, gl.UNSIGNED_BYTE) |
| 107 |
draw.Draw(w.dst, w.Rect.Add(w.origin), m, image.Point{}, draw.Over) |
| 108 |
} |