gl_js.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SPDX-License-Identifier: Unlicense OR MIT
  2. package app
  3. import (
  4. "errors"
  5. "syscall/js"
  6. "gioui.org/gpu"
  7. "gioui.org/internal/gl"
  8. )
  9. type glContext struct {
  10. ctx js.Value
  11. cnv js.Value
  12. w *window
  13. }
  14. func newContext(w *window) (*glContext, error) {
  15. args := map[string]interface{}{
  16. // Enable low latency rendering.
  17. // See https://developers.google.com/web/updates/2019/05/desynchronized.
  18. "desynchronized": true,
  19. "preserveDrawingBuffer": true,
  20. }
  21. ctx := w.cnv.Call("getContext", "webgl2", args)
  22. if ctx.IsNull() {
  23. ctx = w.cnv.Call("getContext", "webgl", args)
  24. }
  25. if ctx.IsNull() {
  26. return nil, errors.New("app: webgl is not supported")
  27. }
  28. c := &glContext{
  29. ctx: ctx,
  30. cnv: w.cnv,
  31. w: w,
  32. }
  33. return c, nil
  34. }
  35. func (c *glContext) RenderTarget() (gpu.RenderTarget, error) {
  36. if c.w.contextStatus != contextStatusOkay {
  37. return nil, gpu.ErrDeviceLost
  38. }
  39. return gpu.OpenGLRenderTarget{}, nil
  40. }
  41. func (c *glContext) API() gpu.API {
  42. return gpu.OpenGL{Context: gl.Context(c.ctx)}
  43. }
  44. func (c *glContext) Release() {
  45. }
  46. func (c *glContext) Present() error {
  47. return nil
  48. }
  49. func (c *glContext) Lock() error {
  50. return nil
  51. }
  52. func (c *glContext) Unlock() {}
  53. func (c *glContext) Refresh() error {
  54. switch c.w.contextStatus {
  55. case contextStatusLost:
  56. return errOutOfDate
  57. case contextStatusRestored:
  58. c.w.contextStatus = contextStatusOkay
  59. return gpu.ErrDeviceLost
  60. default:
  61. return nil
  62. }
  63. }
  64. func (w *window) NewContext() (context, error) {
  65. return newContext(w)
  66. }