diff --git a/internal/present/compositor.go b/internal/present/compositor.go index 0301411..b7ef05a 100644 --- a/internal/present/compositor.go +++ b/internal/present/compositor.go @@ -31,11 +31,29 @@ type compositor struct { lastSize image.Point order []any // this frame's, in the backing array lastOrder had - quads []C.pres_quad - damage []image.Rectangle - ops op.Ops + // history is the damage of the frames before, newest last: what a + // framebuffer drawn some frames ago is missing. + history [maxAge][]image.Rectangle + frames int + + quads []C.pres_quad + places []quad + damage []image.Rectangle + redrawn []image.Rectangle + pieces []piece + regions []C.int + cPieces []C.pres_piece + ops op.Ops } +// maxAge is the oldest framebuffer brought up to date by drawing only what +// changed since: an older one is drawn whole. +const maxAge = 4 + +// maxRegions is the most rectangles drawn again one by one: more are drawn +// as the one rectangle round them all. +const maxRegions = 16 + // layerTexture is a layer, as last drawn. type layerTexture struct { tex, fbo C.GLuint @@ -76,12 +94,15 @@ func (c *compositor) newGPU() (gpu.GPU, error) { // frame draws s into framebuffer fbo, which is the scene's size, and // returns the rectangles of it that differ from the last frame. srgb says -// whether fbo encodes to sRGB. -func (c *compositor) frame(s *scene.Scene, fbo C.GLuint, srgb bool) ([]image.Rectangle, error) { +// whether fbo encodes to sRGB. age is how many frames ago fbo was drawn, +// which is what it still holds, or 0 if that's unknown: only what changed +// since is drawn again. +func (c *compositor) frame(s *scene.Scene, fbo C.GLuint, srgb bool, age int) ([]image.Rectangle, error) { size := s.Size() win := image.Rectangle{Max: size} c.damage = c.damage[:0] c.quads = c.quads[:0] + c.places = c.places[:0] for _, t := range c.layers { t.seen = false } @@ -133,6 +154,7 @@ func (c *compositor) frame(s *scene.Scene, fbo C.GLuint, srgb bool) ([]image.Rec w: C.int(r.Dx()), h: C.int(r.Dy()), opaque: opaque, }) + c.places = append(c.places, quad{r: r, opaque: l.Opaque}) } for k, t := range c.layers { if !t.seen { @@ -147,18 +169,92 @@ func (c *compositor) frame(s *scene.Scene, fbo C.GLuint, srgb bool) ([]image.Rec } c.lastOrder, c.order, c.lastSize = order, c.lastOrder, size + redraw, whole := c.redraw(age, size) + c.remember() + if whole || !srgb { // without sRGB, see pres_composite + redraw = append(redraw[:0], win) + } + if len(redraw) == 0 { + return c.damage, nil // what fbo holds is this frame + } + redraw = merge(redraw) + c.pieces = plan(c.places, redraw, c.pieces[:0]) + + // In GL's coordinates, from the bottom left. + c.regions = c.regions[:0] + for _, r := range redraw { + c.regions = append(c.regions, C.int(r.Min.X), C.int(size.Y-r.Max.Y), C.int(r.Dx()), C.int(r.Dy())) + } + c.cPieces = c.cPieces[:0] + for _, p := range c.pieces { + c.cPieces = append(c.cPieces, C.pres_piece{ + quad: C.int(p.quad), + x: C.int(p.r.Min.X), y: C.int(size.Y - p.r.Max.Y), + w: C.int(p.r.Dx()), h: C.int(p.r.Dy()), + }) + } var q *C.pres_quad if len(c.quads) > 0 { q = &c.quads[0] } + var pieces *C.pres_piece + if len(c.cPieces) > 0 { + pieces = &c.cPieces[0] + } s3 := C.int(0) if srgb { s3 = 1 } - C.pres_composite(&c.gl, fbo, s3, C.int(size.X), C.int(size.Y), q, C.int(len(c.quads))) + C.pres_composite(&c.gl, fbo, s3, C.int(size.X), C.int(size.Y), q, &c.regions[0], C.int(len(redraw)), pieces, C.int(len(c.cPieces))) return c.damage, nil } +// redraw is what must be drawn again of a framebuffer drawn age frames +// ago: this frame's damage and that of the frames since, or whole if +// that's unknown. +func (c *compositor) redraw(age int, size image.Point) (rects []image.Rectangle, whole bool) { + rects = c.redrawn[:0] + defer func() { c.redrawn = rects }() + if age <= 0 || age > maxAge || age-1 > c.frames { + return rects, true + } + win := image.Rectangle{Max: size} + add := func(r image.Rectangle) { + if r = r.Intersect(win); !r.Empty() { + rects = append(rects, r) + } + } + for _, r := range c.damage { + add(r) + } + for i := 1; i < age; i++ { + for _, r := range c.history[maxAge-i] { + add(r) + } + } + if len(rects) > maxRegions { + u := rects[0] + for _, r := range rects[1:] { + u = u.Union(r) + } + rects = append(rects[:0], u) + } + for _, r := range rects { + if r == win { + return rects, true + } + } + return rects, false +} + +// remember adds this frame's damage to the history. +func (c *compositor) remember() { + oldest := c.history[0] + copy(c.history[:], c.history[1:]) + c.history[maxAge-1] = append(oldest[:0], c.damage...) + c.frames++ +} + // draw draws layer l into its texture t, with the layer's origin at off. func (c *compositor) draw(t *layerTexture, l *scene.Layer, off image.Point) error { c.ops.Reset() diff --git a/internal/present/gl.c b/internal/present/gl.c index 0f60ae2..2b37e62 100644 --- a/internal/present/gl.c +++ b/internal/present/gl.c @@ -146,11 +146,12 @@ static void draw(pres_compositor *c, GLuint tex, int x, int y, int w, int h) { glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } -void pres_composite(pres_compositor *c, GLuint fbo, int srgb, int w, int h, const pres_quad *q, int n) { +void pres_composite(pres_compositor *c, GLuint fbo, int srgb, int w, int h, const pres_quad *q, const int *regions, int nr, const pres_piece *p, int np) { GLuint into = fbo; if (!srgb) { // Blending must happen in linear light, as Gio's does, which - // only an sRGB framebuffer does. + // only an sRGB framebuffer does. The caller draws it all, as + // it's copied whole. if (c->mid && (c->midW != w || c->midH != h)) { pres_delete_texture(c->mid, c->midFBO); c->mid = c->midFBO = 0; @@ -164,28 +165,34 @@ void pres_composite(pres_compositor *c, GLuint fbo, int srgb, int w, int h, cons } } glBindFramebuffer(GL_FRAMEBUFFER, into); - glDisable(GL_SCISSOR_TEST); glDisable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glDisable(GL_CULL_FACE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glViewport(0, 0, w, h); glClearColor(1, 1, 1, 1); - glClear(GL_COLOR_BUFFER_BIT); + glEnable(GL_SCISSOR_TEST); + for (int j = 0; j < nr; j++) { + const int *r = ®ions[4 * j]; + glScissor(r[0], r[1], r[2], r[3]); + glClear(GL_COLOR_BUFFER_BIT); + } glUseProgram(c->prog); glBindVertexArray(c->vao); glActiveTexture(GL_TEXTURE0); glUniform1i(c->tex, 0); glUniform1i(c->encode, 0); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - for (int i = 0; i < n; i++) { - if (q[i].opaque) { + for (int i = 0; i < np; i++) { + const pres_quad *qu = &q[p[i].quad]; + if (qu->opaque) { glDisable(GL_BLEND); } else { glEnable(GL_BLEND); } - draw(c, q[i].tex, q[i].x, q[i].y, q[i].w, q[i].h); + glScissor(p[i].x, p[i].y, p[i].w, p[i].h); + draw(c, qu->tex, qu->x, qu->y, qu->w, qu->h); } + glDisable(GL_SCISSOR_TEST); if (into != fbo) { glBindFramebuffer(GL_FRAMEBUFFER, fbo); glDisable(GL_BLEND); @@ -237,3 +244,16 @@ EGLDisplay pres_headless_display(void) { } return eglGetDisplay(EGL_DEFAULT_DISPLAY); } + +EGLint pres_buffer_age(EGLDisplay disp, EGLSurface surf) { + static int has = -1; + if (has < 0) { + const char *exts = eglQueryString(disp, EGL_EXTENSIONS); + has = exts && (strstr(exts, "EGL_EXT_buffer_age") || strstr(exts, "EGL_KHR_partial_update")); + } + EGLint age = 0; + if (!has || !eglQuerySurface(disp, surf, EGL_BUFFER_AGE_EXT, &age)) { + return 0; + } + return age; +} diff --git a/internal/present/gl.h b/internal/present/gl.h index 6cfbd69..737dd79 100644 --- a/internal/present/gl.h +++ b/internal/present/gl.h @@ -39,9 +39,21 @@ void pres_delete_texture(GLuint tex, GLuint fbo); // what's written to it as sRGB. int pres_srgb(GLuint fbo); -// pres_composite draws quads, back to front, over all of framebuffer fbo, -// which is w by h, after clearing it to white. -void pres_composite(pres_compositor *c, GLuint fbo, int srgb, int w, int h, const pres_quad *q, int n); +// A part of a quad to draw: where, in GL's coordinates. +typedef struct { + int quad; + int x, y, w, h; +} pres_piece; + +// pres_composite draws framebuffer fbo, which is w by h, again within the +// nr regions, as x, y, w, h each in GL's coordinates, leaving the rest as +// it was: it clears them to white, then draws the np pieces of quads, in +// order. +void pres_composite(pres_compositor *c, GLuint fbo, int srgb, int w, int h, const pres_quad *q, const int *regions, int nr, const pres_piece *p, int np); + +// pres_buffer_age is how many frames ago the window's back buffer was +// drawn, which is what it holds; 0 if that's unknown. +EGLint pres_buffer_age(EGLDisplay disp, EGLSurface surf); // pres_read reads w by h pixels of framebuffer fbo, from x, y in GL's // coordinates, into pix as RGBA. diff --git a/internal/present/headless.go b/internal/present/headless.go index 419ca27..cf8b114 100644 --- a/internal/present/headless.go +++ b/internal/present/headless.go @@ -14,24 +14,37 @@ import ( "100gex/internal/scene" ) -// Headless draws frames as a Window does, but into a texture, with no +// Headless draws frames as a Window does, but into textures, with no // window: for tests and benchmarks. It may be used from any goroutine, one // at a time: as Gio's own headless windows do, it makes its context current // only for each call. +// +// Like a window's swapchain, it draws each frame into the next of its +// buffers in turn, which holds the frame it was last drawn with, so that +// frames are drawn as a window's are: only what changed since that frame. type Headless struct { - egl *eglContext + egl *eglContext + bufs []buffer + next int // the buffer the next frame is drawn into + last int // the buffer the last frame was drawn into + frames int + size image.Point + comp *compositor +} + +type buffer struct { tex, fbo C.GLuint - size image.Point - comp *compositor + drawn int // the frame last drawn into it; 0 if none since it was made } -// NewHeadless makes a context and a target of size pixels. +// NewHeadless makes a context and a target of size pixels, with one +// buffer. func NewHeadless(size image.Point) (*Headless, error) { c, err := newHeadlessContext() if err != nil { return nil, err } - h := &Headless{egl: c} + h := &Headless{egl: c, bufs: make([]buffer, 1)} err = h.do(func() error { var err error if h.comp, err = newCompositor(); err != nil { @@ -46,6 +59,18 @@ func NewHeadless(size image.Point) (*Headless, error) { return h, nil } +// SetBuffers makes the target n buffers, drawn into in turn, as a window +// with a swapchain of n is. +func (h *Headless) SetBuffers(n int) error { + return h.do(func() error { + h.free() + h.bufs, h.next, h.last = make([]buffer, n), 0, 0 + size := h.size + h.size = image.Point{} + return h.resize(size) + }) +} + // do calls f with the context current. func (h *Headless) do(f func() error) error { runtime.LockOSThread() @@ -61,15 +86,25 @@ func (h *Headless) resize(size image.Point) error { if size == h.size { return nil } - C.pres_delete_texture(h.tex, h.fbo) - h.tex, h.fbo, h.size = 0, 0, image.Point{} - if err := C.pres_texture(C.int(size.X), C.int(size.Y), &h.tex, &h.fbo); err != 0 { - return fmt.Errorf("present: a %v target: GL error %#x", size, err) + h.free() + for i := range h.bufs { + b := &h.bufs[i] + if err := C.pres_texture(C.int(size.X), C.int(size.Y), &b.tex, &b.fbo); err != 0 { + return fmt.Errorf("present: a %v target: GL error %#x", size, err) + } } h.size = size return nil } +func (h *Headless) free() { + for i := range h.bufs { + b := &h.bufs[i] + C.pres_delete_texture(b.tex, b.fbo) + *b = buffer{} + } +} + // Frame draws s, and returns what changed since the last frame, as a // Window tells the compositor. func (h *Headless) Frame(s *scene.Scene) (damage []image.Rectangle, err error) { @@ -77,7 +112,15 @@ func (h *Headless) Frame(s *scene.Scene) (damage []image.Rectangle, err error) { if err := h.resize(s.Size()); err != nil { return err } - damage, err = h.comp.frame(s, h.fbo, true) + h.frames++ + b := &h.bufs[h.next] + age := 0 + if b.drawn > 0 { + age = h.frames - b.drawn + } + damage, err = h.comp.frame(s, b.fbo, true, age) + b.drawn = h.frames + h.last, h.next = h.next, (h.next+1)%len(h.bufs) return err }) return damage, err @@ -93,7 +136,7 @@ func (h *Headless) Screenshot(img *image.RGBA) error { pix := make([]byte, r.Dx()*r.Dy()*4) err := h.do(func() error { // GL's rows go up from the bottom. - C.pres_read(h.fbo, C.int(r.Min.X), C.int(h.size.Y-r.Max.Y), C.int(r.Dx()), C.int(r.Dy()), unsafe.Pointer(&pix[0])) + C.pres_read(h.bufs[h.last].fbo, C.int(r.Min.X), C.int(h.size.Y-r.Max.Y), C.int(r.Dx()), C.int(r.Dy()), unsafe.Pointer(&pix[0])) return nil }) stride := r.Dx() * 4 @@ -112,7 +155,7 @@ func (h *Headless) Release() { if h.comp != nil { h.comp.release() } - C.pres_delete_texture(h.tex, h.fbo) + h.free() return nil }) h.egl.release() diff --git a/internal/present/plan.go b/internal/present/plan.go new file mode 100644 index 0000000..e31d2d5 --- /dev/null +++ b/internal/present/plan.go @@ -0,0 +1,104 @@ +package present + +import "image" + +// quad is a layer's place in the window, as composited. +type quad struct { + r image.Rectangle + opaque bool +} + +// piece is part of a quad to draw: r, in the window's coordinates. +type piece struct { + quad int + r image.Rectangle +} + +// maxFragments is the most pieces a quad is cut into within a region by +// the opaque quads over it: past that, it's drawn whole, which costs more +// pixels but is the same picture. +const maxFragments = 32 + +// merge returns rects, made not to overlap: any that do are replaced by the +// rectangle round them, until none do. Drawing overlapping regions one by +// one would draw their overlap more than once. +func merge(rects []image.Rectangle) []image.Rectangle { + out := rects[:0] + for _, r := range rects { + if !r.Empty() { + out = append(out, r) + } + } + for merged := true; merged; { + merged = false + for i := 0; i < len(out); i++ { + for j := i + 1; j < len(out); j++ { + if out[i].Overlaps(out[j]) { + out[i] = out[i].Union(out[j]) + out = append(out[:j], out[j+1:]...) + merged = true + j = i // out[i] grew: check the rest against it again + } + } + } + } + return out +} + +// plan appends to out the pieces of quads that draw regions again, which +// don't overlap: for each region, each quad's part of it, back to front, +// less what opaque quads in front of it cover, which would hide it. +func plan(quads []quad, regions []image.Rectangle, out []piece) []piece { + var frags, next []image.Rectangle + for _, region := range regions { + for i, q := range quads { + part := q.r.Intersect(region) + if part.Empty() { + continue + } + frags = append(frags[:0], part) + for _, above := range quads[i+1:] { + if !above.opaque || !above.r.Overlaps(part) { + continue + } + next = next[:0] + for _, f := range frags { + next = subtract(f, above.r, next) + } + frags, next = next, frags + if len(frags) == 0 || len(frags) > maxFragments { + break + } + } + if len(frags) > maxFragments { + frags = append(frags[:0], part) + } + for _, f := range frags { + out = append(out, piece{quad: i, r: f}) + } + } + } + return out +} + +// subtract appends to out the parts of a outside b: up to four rectangles, +// the bands above and below b, and either side of it. +func subtract(a, b image.Rectangle, out []image.Rectangle) []image.Rectangle { + if !a.Overlaps(b) { + return append(out, a) + } + if a.Min.Y < b.Min.Y { + out = append(out, image.Rect(a.Min.X, a.Min.Y, a.Max.X, b.Min.Y)) + } + if b.Max.Y < a.Max.Y { + out = append(out, image.Rect(a.Min.X, b.Max.Y, a.Max.X, a.Max.Y)) + } + top, bottom := max(a.Min.Y, b.Min.Y), min(a.Max.Y, b.Max.Y) + if a.Min.X < b.Min.X { + out = append(out, image.Rect(a.Min.X, top, b.Min.X, bottom)) + } + if b.Max.X < a.Max.X { + out = append(out, image.Rect(b.Max.X, top, a.Max.X, bottom)) + } + return out +} diff --git a/internal/present/plan_test.go b/internal/present/plan_test.go new file mode 100644 index 0000000..d9e295f --- /dev/null +++ b/internal/present/plan_test.go @@ -0,0 +1,93 @@ +package present + +import ( + "image" + "math/rand/v2" + "slices" + "testing" +) + +// TestPlan checks plan against drawing every pixel: within the regions, +// a pixel must be drawn by the quads over it, in order, from the frontmost +// opaque one, which hides those behind it; outside, by none. +func TestPlan(t *testing.T) { + rng := rand.New(rand.NewPCG(1, 2)) + const size = 40 + rect := func() image.Rectangle { + x, y := rng.IntN(size), rng.IntN(size) + return image.Rect(x, y, x+1+rng.IntN(size/2), y+1+rng.IntN(size/2)).Intersect(image.Rect(0, 0, size, size)) + } + for n := range 2000 { + var quads []quad + if rng.IntN(2) == 0 { + quads = append(quads, quad{r: image.Rect(0, 0, size, size), opaque: true}) // a base + } + for range 1 + rng.IntN(6) { + quads = append(quads, quad{r: rect(), opaque: rng.IntN(3) > 0}) + } + var regions []image.Rectangle + for range 1 + rng.IntN(4) { + regions = append(regions, rect()) + } + merged := merge(slices.Clone(regions)) + for i, a := range merged { + for _, b := range merged[i+1:] { + if a.Overlaps(b) { + t.Fatalf("scene %d: merged regions %v and %v overlap", n, a, b) + } + } + } + // Every pixel of the merged regions is cleared, so each must be + // drawn again whole; they must cover the regions asked for. + want := make([][]int, size*size) // the quads drawn at each pixel + in := make([]bool, size*size) + for y := range size { + for x := range size { + in[y*size+x] = covered(merged, x, y) + if covered(regions, x, y) && !in[y*size+x] { + t.Fatalf("scene %d: merging %v gave %v, without %d,%d", n, regions, merged, x, y) + } + } + } + for y := range size { + for x := range size { + if !in[y*size+x] { + continue + } + p := image.Pt(x, y) + for i, q := range quads { + if !p.In(q.r) { + continue + } + if q.opaque { + want[y*size+x] = want[y*size+x][:0] + } + want[y*size+x] = append(want[y*size+x], i) + } + } + } + + got := make([][]int, size*size) + for _, pc := range plan(quads, merged, nil) { + for y := pc.r.Min.Y; y < pc.r.Max.Y; y++ { + for x := pc.r.Min.X; x < pc.r.Max.X; x++ { + got[y*size+x] = append(got[y*size+x], pc.quad) + } + } + } + for i := range got { + if !slices.Equal(got[i], want[i]) { + t.Fatalf("scene %d: pixel %d,%d drawn by quads %v, want %v\nquads %v\nregions %v", n, i%size, i/size, got[i], want[i], quads, regions) + } + } + } +} + +func covered(rects []image.Rectangle, x, y int) bool { + for _, r := range rects { + if image.Pt(x, y).In(r) { + return true + } + } + return false +} diff --git a/internal/present/present_test.go b/internal/present/present_test.go index 6d27a0e..9478736 100644 --- a/internal/present/present_test.go +++ b/internal/present/present_test.go @@ -154,12 +154,21 @@ func TestMatchesGio(t *testing.T) { {"wash gone", func(l *look) { l.absent = true }}, {"wash back", func(l *look) { l.absent = false }}, } - s := new(scene.Scene) - l := start - for _, st := range steps { - t.Run(st.name, func(t *testing.T) { - st.change(&l) - compare(t, h, gio, s, drawFrame(s, size, l), translucentTolerance) + // A window's buffers hold older frames the more there are, so more + // must be drawn again to bring them up to date. + for _, bufs := range []int{1, 2, 3} { + t.Run(fmt.Sprintf("%d buffers", bufs), func(t *testing.T) { + if err := h.SetBuffers(bufs); err != nil { + t.Fatal(err) + } + s := new(scene.Scene) + l := start + for _, st := range steps { + t.Run(st.name, func(t *testing.T) { + st.change(&l) + compare(t, h, gio, s, drawFrame(s, size, l), translucentTolerance) + }) + } }) } } diff --git a/internal/present/wayland.go b/internal/present/wayland.go index 516323f..cce8279 100644 --- a/internal/present/wayland.go +++ b/internal/present/wayland.go @@ -98,7 +98,7 @@ func (w *Window) Frame(s *scene.Scene) error { C.wl_egl_window_resize(w.eglWin, C.int(size.X), C.int(size.Y), 0, 0) w.size = size } - damage, err := w.comp.frame(s, 0, w.srgb) + damage, err := w.comp.frame(s, 0, w.srgb, int(C.pres_buffer_age(w.egl.disp, w.surf))) if err != nil { return err } diff --git a/internal/ui/layers_test.go b/internal/ui/layers_test.go index e9a2b0a..7f44dd1 100644 --- a/internal/ui/layers_test.go +++ b/internal/ui/layers_test.go @@ -32,6 +32,11 @@ func TestLayersMatchGio(t *testing.T) { t.Skipf("no headless EGL context: %v", err) } defer comp.Release() + // As many buffers as a window usually has: each frame draws only what + // changed since its buffer's. + if err := comp.SetBuffers(3); err != nil { + t.Fatal(err) + } var gio *headless.Window defer func() { if gio != nil {