Added flag to NewBitmapFromImage.

Bitmap is now created as a memory bitmap and converted to a video bitmap if the user requested that explicitly.
This commit is contained in:
Sander Schobers 2018-02-15 20:17:27 +01:00
parent 0652c02caf
commit 7d7bc43a80
2 changed files with 60 additions and 8 deletions

View File

@ -60,18 +60,44 @@ func NewBitmap(width, height int) (*Bitmap, error) {
return &Bitmap{b, width, height}, nil return &Bitmap{b, width, height}, nil
} }
type newBmpFlagsCapture struct {
cap C.int
}
func captureNewBmpFlags() *newBmpFlagsCapture {
var cap = C.al_get_new_bitmap_flags()
return &newBmpFlagsCapture{cap}
}
func (c *newBmpFlagsCapture) Mut(mut func(*flagMut)) {
var m = &flagMut{c.cap}
mut(m)
C.al_set_new_bitmap_flags(m.flg)
}
func (c *newBmpFlagsCapture) Revert() {
C.al_set_new_bitmap_flags(c.cap)
}
// NewBitmapFromImage creates a new bitmap starting from a Go native image (image.Image) // NewBitmapFromImage creates a new bitmap starting from a Go native image (image.Image)
func NewBitmapFromImage(im image.Image) (*Bitmap, error) { func NewBitmapFromImage(im image.Image, video bool) (*Bitmap, error) {
var newBmpFlags = captureNewBmpFlags()
defer newBmpFlags.Revert()
newBmpFlags.Mut(func(m *flagMut) {
m.Unset(C.ALLEGRO_VIDEO_BITMAP)
m.Set(C.ALLEGRO_MEMORY_BITMAP)
m.Set(C.ALLEGRO_MIN_LINEAR)
})
var bnd = im.Bounds() var bnd = im.Bounds()
width, height := bnd.Dx(), bnd.Dy() width, height := bnd.Dx(), bnd.Dy()
bmp, err := NewBitmap(width, height) var b = C.al_create_bitmap(C.int(width), C.int(height))
if nil != err { if nil == b {
return nil, err return nil, errors.New("error creating memory bitmap")
} }
row := make([]uint8, width*4) row := make([]uint8, width*4)
rgn := C.al_lock_bitmap(bmp.bitmap, C.ALLEGRO_PIXEL_FORMAT_ABGR_8888, C.ALLEGRO_LOCK_WRITEONLY) rgn := C.al_lock_bitmap(b, C.ALLEGRO_PIXEL_FORMAT_ABGR_8888, C.ALLEGRO_LOCK_WRITEONLY)
if nil == rgn { if nil == rgn {
bmp.Destroy() C.al_destroy_bitmap(b)
return nil, errors.New("unable to lock bitmap") return nil, errors.New("unable to lock bitmap")
} }
data := (*[1 << 30]uint8)(rgn.data) data := (*[1 << 30]uint8)(rgn.data)
@ -87,8 +113,16 @@ func NewBitmapFromImage(im image.Image) (*Bitmap, error) {
copy(data[offset:], row) copy(data[offset:], row)
offset += int(rgn.pitch) offset += int(rgn.pitch)
} }
C.al_unlock_bitmap(bmp.bitmap) C.al_unlock_bitmap(b)
return bmp, nil if video {
newBmpFlags.Mut(func(m *flagMut) {
m.Unset(C.ALLEGRO_MEMORY_BITMAP)
m.Set(C.ALLEGRO_VIDEO_BITMAP)
m.Set(C.ALLEGRO_MIN_LINEAR)
})
C.al_convert_bitmap(b)
}
return &Bitmap{b, width, height}, nil
} }
// LoadBitmap tries to load the image at the specified path as a bitmap // LoadBitmap tries to load the image at the specified path as a bitmap

18
allegro5/flagmut.go Normal file
View File

@ -0,0 +1,18 @@
package allegro5
// #include <stdlib.h>
import "C"
type flagMut struct {
flg C.int
}
func (m *flagMut) Set(f C.int) {
m.flg |= f
}
func (m *flagMut) Unset(f C.int) {
if m.flg&f == f {
m.flg ^= f
}
}