From 875a529708a749c03356778b93896dda01320f87 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sun, 16 Feb 2020 22:16:27 +0900 Subject: [PATCH] graphics: Allow ReplacePixels on a sub-image Fixes #980 --- image.go | 8 ++---- image_test.go | 50 ++++++++++++++++++++++++++++++++++++++ internal/buffered/image.go | 1 + 3 files changed, 53 insertions(+), 6 deletions(-) diff --git a/image.go b/image.go index 011b04234..7713c62a8 100644 --- a/image.go +++ b/image.go @@ -472,12 +472,8 @@ func (i *Image) ReplacePixels(p []byte) error { if i.isDisposed() { return nil } - // TODO: Implement this. - if i.isSubImage() { - panic("ebiten: render to a subimage is not implemented (ReplacePixels)") - } - s := i.Bounds().Size() - if err := i.buffered.ReplacePixels(p, 0, 0, s.X, s.Y); err != nil { + r := i.Bounds() + if err := i.buffered.ReplacePixels(p, r.Min.X, r.Min.Y, r.Dx(), r.Dy()); err != nil { theUIContext.setError(err) } return nil diff --git a/image_test.go b/image_test.go index c57cb3c42..102766ede 100644 --- a/image_test.go +++ b/image_test.go @@ -1852,3 +1852,53 @@ func TestImageDrawTrianglesAndMutateArgs(t *testing.T) { } } } + +func TestImageReplacePixelsOnSubImage(t *testing.T) { + dst, _ := NewImage(17, 31, FilterDefault) + dst.Fill(color.RGBA{0xff, 0, 0, 0xff}) + + pix0 := make([]byte, 4*5*3) + idx := 0 + for j := 0; j < 3; j++ { + for i := 0; i < 5; i++ { + pix0[4*idx] = 0 + pix0[4*idx+1] = 0xff + pix0[4*idx+2] = 0 + pix0[4*idx+3] = 0xff + idx++ + } + } + r0 := image.Rect(4, 5, 9, 8) + dst.SubImage(r0).(*Image).ReplacePixels(pix0) + + pix1 := make([]byte, 4*5*3) + idx = 0 + for j := 0; j < 3; j++ { + for i := 0; i < 5; i++ { + pix1[4*idx] = 0 + pix1[4*idx+1] = 0 + pix1[4*idx+2] = 0xff + pix1[4*idx+3] = 0xff + idx++ + } + } + r1 := image.Rect(11, 10, 16, 13) + dst.SubImage(r1).(*Image).ReplacePixels(pix1) + + for j := 0; j < 31; j++ { + for i := 0; i < 17; i++ { + got := dst.At(i, j).(color.RGBA) + want := color.RGBA{0xff, 0, 0, 0xff} + p := image.Pt(i, j) + switch { + case p.In(r0): + want = color.RGBA{0, 0xff, 0, 0xff} + case p.In(r1): + want = color.RGBA{0, 0, 0xff, 0xff} + } + if got != want { + t.Errorf("dst.At(%d, %d): got: %v, want: %v", i, j, got, want) + } + } + } +} diff --git a/internal/buffered/image.go b/internal/buffered/image.go index 07d3be207..d1c965c4d 100644 --- a/internal/buffered/image.go +++ b/internal/buffered/image.go @@ -181,6 +181,7 @@ func (i *Image) ReplacePixels(pix []byte, x, y, width, height int) error { return nil } + // TODO: Can we use (*restorable.Image).ReplacePixels? if i.pixels == nil { pix := make([]byte, 4*i.width*i.height) idx := 0