Skip to content

Commit

Permalink
internal/atlas: add TestGCShader
Browse files Browse the repository at this point in the history
  • Loading branch information
hajimehoshi committed Jan 29, 2024
1 parent f74d66e commit 872ffc1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
16 changes: 9 additions & 7 deletions internal/atlas/shader.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,20 @@ func NewShader(ir *shaderir.Program) *Shader {
}
}

func (s *Shader) finalize() {
// A function from finalizer must not be blocked, but disposing operation can be blocked.
// Defer this operation until it becomes safe. (#913)
appendDeferred(func() {
s.deallocate()
})
}

func (s *Shader) ensureShader() *graphicscommand.Shader {
if s.shader != nil {
return s.shader
}
s.shader = graphicscommand.NewShader(s.ir)
runtime.SetFinalizer(s, func(shader *Shader) {
// A function from finalizer must not be blocked, but disposing operation can be blocked.
// Defer this operation until it becomes safe. (#913)
appendDeferred(func() {
shader.deallocate()
})
})
runtime.SetFinalizer(s, (*Shader).finalize)
return s.shader
}

Expand Down
26 changes: 26 additions & 0 deletions internal/atlas/shader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package atlas_test
import (
"image"
"image/color"
"runtime"
"testing"

"github.com/hajimehoshi/ebiten/v2/internal/atlas"
Expand Down Expand Up @@ -78,3 +79,28 @@ func TestImageDrawTwice(t *testing.T) {
t.Errorf("got: %v, want: %v", got, want)
}
}

func TestGCShader(t *testing.T) {
s := atlas.NewShader(etesting.ShaderProgramFill(0xff, 0xff, 0xff, 0xff))

// Use the shader to initialize it.
const w, h = 1, 1
dst := atlas.NewImage(w, h, atlas.ImageTypeRegular)
vs := quadVertices(w, h, 0, 0, 1)
is := graphics.QuadIndices()
dr := image.Rect(0, 0, w, h)
dst.DrawTriangles([graphics.ShaderImageCount]*atlas.Image{}, vs, is, graphicsdriver.BlendCopy, dr, [graphics.ShaderImageCount]image.Rectangle{}, s, nil, graphicsdriver.FillAll)

// Ensure other objects are GCed, as GC appends deferred functions for collected objects.
runtime.GC()

// Get the difference of the number of deferred functions before and after s is GCed.
c := atlas.DeferredFuncCountForTesting()
runtime.KeepAlive(s)
runtime.GC()
diff := atlas.DeferredFuncCountForTesting() - c

if got, want := diff, 1; got != want {
t.Errorf("got: %d, want: %d", got, want)
}
}

0 comments on commit 872ffc1

Please sign in to comment.