From a1f157c317cced93bb6a1e9b19451fe4109ab202 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Sat, 23 May 2020 08:56:52 +0200 Subject: [PATCH] A sub-bitmap now removes itself from the registration of its parent. With this change it is safe to Destroy the sub-bitmap (and afterwards destroy the parent bitmap). The implementation is not thread-safe. --- bitmap.go | 21 +++++++++++++++++---- display.go | 4 ++-- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/bitmap.go b/bitmap.go index 093539f..9dc30bf 100644 --- a/bitmap.go +++ b/bitmap.go @@ -16,6 +16,7 @@ type Bitmap struct { width int height int subs []*Bitmap + sup *Bitmap } type DrawOptions struct { @@ -58,7 +59,7 @@ func newBitmap(width, height int, mut func(m FlagMutation), flags []NewBitmapFla if b == nil { return nil, errors.New("error creating bitmap") } - return &Bitmap{b, width, height, nil}, nil + return &Bitmap{b, width, height, nil, nil}, nil } // NewBitmap creates a new bitmap of given width and height and optional flags @@ -123,7 +124,7 @@ func NewBitmapFromImage(src image.Image, video bool) (*Bitmap, error) { }) C.al_convert_bitmap(b) } - return &Bitmap{b, width, height, nil}, nil + return &Bitmap{b, width, height, nil, nil}, nil } // LoadBitmap tries to load the image at the specified path as a bitmap @@ -136,7 +137,7 @@ func LoadBitmap(path string) (*Bitmap, error) { } width := int(C.al_get_bitmap_width(b)) height := int(C.al_get_bitmap_height(b)) - return &Bitmap{b, width, height, nil}, nil + return &Bitmap{b, width, height, nil, nil}, nil } // Draw draws the bitmap at the given location @@ -202,7 +203,7 @@ func (b *Bitmap) Sub(x, y, w, h int) *Bitmap { if sub == nil { return nil } - var bmp = &Bitmap{sub, w, h, nil} + var bmp = &Bitmap{sub, w, h, nil, b} b.subs = append(b.subs, bmp) return bmp } @@ -267,5 +268,17 @@ func (b *Bitmap) Destroy() { for _, sub := range b.subs { sub.Destroy() } + if b.sup != nil { + b.sup.removeSub(b) + } C.al_destroy_bitmap(bmp) } + +func (b *Bitmap) removeSub(sub *Bitmap) { + for i := 0; i < len(b.subs); i++ { + if b.subs[i] == sub { + b.subs = append(b.subs[:i], b.subs[i+1:]...) + return + } + } +} diff --git a/display.go b/display.go index 927d9e7..ea85273 100644 --- a/display.go +++ b/display.go @@ -150,7 +150,7 @@ func (d *Display) SetWindowTitle(title string) { } func (d *Display) Target() *Bitmap { - return &Bitmap{C.al_get_backbuffer(d.display), d.Width(), d.Height(), nil} + return &Bitmap{C.al_get_backbuffer(d.display), d.Width(), d.Height(), nil, nil} } // Destroy destroys the display @@ -160,7 +160,7 @@ func (d *Display) Destroy() { func CurrentTarget() *Bitmap { var bmp = C.al_get_target_bitmap() - return &Bitmap{bmp, int(C.al_get_bitmap_width(bmp)), int(C.al_get_bitmap_height(bmp)), nil} + return &Bitmap{bmp, int(C.al_get_bitmap_width(bmp)), int(C.al_get_bitmap_height(bmp)), nil, nil} } func SetNewWindowTitle(title string) {