ebiten/internal/restorable/image.go

567 lines
16 KiB
Go
Raw Normal View History

2016-07-16 21:41:28 +02:00
// Copyright 2016 The Ebiten Authors
2016-07-13 19:35:20 +02:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2016-09-03 15:05:05 +02:00
package restorable
2016-07-13 19:35:20 +02:00
import (
"fmt"
2016-07-13 19:35:20 +02:00
"github.com/hajimehoshi/ebiten/internal/affine"
"github.com/hajimehoshi/ebiten/internal/driver"
"github.com/hajimehoshi/ebiten/internal/graphics"
2018-10-28 12:10:05 +01:00
"github.com/hajimehoshi/ebiten/internal/graphicscommand"
2016-07-13 19:35:20 +02:00
)
2019-02-12 15:31:52 +01:00
type Pixels struct {
rectToPixels *rectToPixels
2019-02-12 15:31:52 +01:00
}
// Apply applies the Pixels state to the given image especially for restoring.
func (p *Pixels) Apply(img *graphicscommand.Image) {
if p.rectToPixels == nil {
clearImage(img)
return
}
p.rectToPixels.apply(img)
2019-02-12 15:31:52 +01:00
}
func (p *Pixels) AddOrReplace(pix []byte, x, y, width, height int) {
if p.rectToPixels == nil {
p.rectToPixels = &rectToPixels{}
2019-02-12 15:31:52 +01:00
}
p.rectToPixels.addOrReplace(pix, x, y, width, height)
}
func (p *Pixels) Remove(x, y, width, height int) {
// Note that we don't care whether the region is actually removed or not here. There is an actual case that
// the region is allocated but nothing is rendered. See TestDisposeImmediately at shareable package.
if p.rectToPixels == nil {
return
}
p.rectToPixels.remove(x, y, width, height)
}
func (p *Pixels) At(i, j int) (byte, byte, byte, byte) {
if p.rectToPixels != nil {
if r, g, b, a, ok := p.rectToPixels.at(i, j); ok {
return r, g, b, a
}
2019-02-12 15:31:52 +01:00
}
2019-07-19 21:53:18 +02:00
return 0, 0, 0, 0
2019-02-12 15:31:52 +01:00
}
// drawTrianglesHistoryItem is an item for history of draw-image commands.
type drawTrianglesHistoryItem struct {
image *Image
vertices []float32
indices []uint16
colorm *affine.ColorM
mode driver.CompositeMode
filter driver.Filter
address driver.Address
2016-07-13 19:35:20 +02:00
}
2016-09-09 18:36:56 +02:00
// Image represents an image that can be restored when GL context is lost.
2016-09-03 15:05:05 +02:00
type Image struct {
2018-10-28 12:10:05 +01:00
image *graphicscommand.Image
basePixels Pixels
2017-09-19 18:35:56 +02:00
// drawTrianglesHistory is a set of draw-image commands.
2017-09-21 16:33:27 +02:00
// TODO: This should be merged with the similar command queue in package graphics (#433).
drawTrianglesHistory []*drawTrianglesHistoryItem
2017-05-29 20:31:29 +02:00
// stale indicates whether the image needs to be synced with GPU as soon as possible.
stale bool
// volatile indicates whether the image is cleared whenever a frame starts.
volatile bool
2017-05-29 19:06:45 +02:00
// screen indicates whether the image is used as an actual screen.
screen bool
// priority indicates whether the image is restored in high priority when context-lost happens.
priority bool
2016-07-13 19:35:20 +02:00
}
var emptyImage *Image
func init() {
const w, h = 16, 16
emptyImage = &Image{
image: graphicscommand.NewImage(w, h),
priority: true,
}
pix := make([]byte, 4*w*h)
for i := range pix {
pix[i] = 0xff
}
2019-07-15 19:16:00 +02:00
2019-07-19 21:53:18 +02:00
// As emptyImage is the source at clearImage, initialize this with ReplacePixels, not clearImage.
2019-07-15 19:16:00 +02:00
// This operation is also important when restoring emptyImage.
emptyImage.ReplacePixels(pix, 0, 0, w, h)
theImages.add(emptyImage)
}
// NewImage creates an empty image with the given size.
//
// The returned image is cleared.
//
// Note that Dispose is not called automatically.
2019-02-12 07:05:05 +01:00
func NewImage(width, height int) *Image {
theImages.m.Lock()
defer theImages.m.Unlock()
2017-05-03 16:15:18 +02:00
i := &Image{
2019-02-12 07:05:05 +01:00
image: graphicscommand.NewImage(width, height),
}
i.clear()
2017-05-03 16:15:18 +02:00
theImages.add(i)
return i
}
// Extend extends the image by the given size.
// Extend creates a new image with the given size and copies the pixels of the given source image.
// Extend disposes itself after its call.
//
// If the given size (width and height) is smaller than the source image, ExtendImage panics.
//
// The image must be ReplacePixels-only image. Extend panics when Fill or DrawTriangles are applied on the image.
//
// Extend panics when the image is stale.
func (i *Image) Extend(width, height int) *Image {
w, h := i.Size()
if w > width || h > height {
panic(fmt.Sprintf("restorable: the original size (%d, %d) cannot be extended to (%d, %d)", w, h, width, height))
}
if i.stale {
panic("restorable: Extend at a stale image is forbidden")
}
if len(i.drawTrianglesHistory) > 0 {
panic("restorable: Extend after DrawTriangles is forbidden")
}
newImg := NewImage(width, height)
i.basePixels.Apply(newImg.image)
newImg.basePixels = i.basePixels
i.Dispose()
return newImg
}
2019-02-12 07:05:05 +01:00
func (i *Image) MakeVolatile() {
i.volatile = true
}
2017-09-14 17:24:18 +02:00
// NewScreenFramebufferImage creates a special image that framebuffer is one for the screen.
//
// The returned image is cleared.
//
// Note that Dispose is not called automatically.
func NewScreenFramebufferImage(width, height int) *Image {
theImages.m.Lock()
defer theImages.m.Unlock()
2017-05-03 16:15:18 +02:00
i := &Image{
2018-12-26 19:11:56 +01:00
image: graphicscommand.NewScreenFramebufferImage(width, height),
screen: true,
}
i.clear()
2017-05-03 16:15:18 +02:00
theImages.add(i)
return i
2016-09-03 15:24:37 +02:00
}
2019-07-19 21:53:18 +02:00
func (i *Image) Clear() {
theImages.m.Lock()
defer theImages.m.Unlock()
theImages.makeStaleIfDependingOn(i)
2019-07-19 21:53:18 +02:00
i.clear()
}
2019-07-19 21:53:18 +02:00
// clearImage clears a graphicscommand.Image.
// This does nothing to do with a restorable.Image's rendering state.
2019-07-19 21:53:18 +02:00
func clearImage(img *graphicscommand.Image) {
2019-07-15 19:16:00 +02:00
if img == emptyImage.image {
2019-07-19 21:53:18 +02:00
panic("restorable: clearImage cannot be called on emptyImage")
}
// There are not 'drawTrianglesHistoryItem's for this image and emptyImage.
// As emptyImage is a priority image, this is restored before other regular images are restored.
2019-06-25 16:41:36 +02:00
// The rendering target size needs to be its 'internal' size instead of the exposed size to avoid glitches on
// mobile platforms (See the change 1e1f309a).
dw, dh := img.InternalSize()
sw, sh := emptyImage.Size()
vs := make([]float32, 4*graphics.VertexFloatNum)
graphics.PutQuadVertices(vs, emptyImage, 0, 0, sw, sh,
float32(dw)/float32(sw), 0, 0, float32(dh)/float32(sh), 0, 0,
2019-07-19 21:53:18 +02:00
0, 0, 0, 0)
is := graphics.QuadIndices()
2019-07-19 21:53:18 +02:00
// The first DrawTriangles must be clear mode for initialization.
// TODO: Can the graphicscommand package hide this knowledge?
img.DrawTriangles(emptyImage.image, vs, is, nil, driver.CompositeModeClear, driver.FilterNearest, driver.AddressClampToZero)
}
2019-07-19 21:53:18 +02:00
func (i *Image) clear() {
if i.priority {
panic("restorable: clear cannot be called on a priority image")
}
2019-07-19 21:53:18 +02:00
clearImage(i.image)
i.ResetRestoringState()
}
// ResetRestoringState resets all the information for restoring.
// ResetRestoringState doen't affect the underlying image.
//
// After ResetRestoringState, the image is assumed to be cleared.
func (i *Image) ResetRestoringState() {
i.basePixels = Pixels{}
i.drawTrianglesHistory = nil
i.stale = false
}
func (i *Image) IsVolatile() bool {
return i.volatile
}
2017-09-14 17:24:18 +02:00
// BasePixelsForTesting returns the image's basePixels for testing.
2019-02-12 15:31:52 +01:00
func (i *Image) BasePixelsForTesting() *Pixels {
return &i.basePixels
2017-05-31 18:27:56 +02:00
}
2017-09-14 17:24:18 +02:00
// Size returns the image's size.
2017-09-14 17:57:52 +02:00
func (i *Image) Size() (int, int) {
return i.image.Size()
}
2016-09-03 15:24:37 +02:00
// internalSize returns the size of the internal texture.
func (i *Image) internalSize() (int, int) {
2019-06-25 16:18:00 +02:00
return i.image.InternalSize()
}
func (i *Image) PutVertex(vs []float32, dx, dy, sx, sy float32, bx0, by0, bx1, by1 float32, cr, cg, cb, ca float32) {
// Specifying a range explicitly here is redundant but this helps optimization
// to eliminate boundary checks.
//
// VertexFloatNum is better than 12 in terms of code maintenanceability, but in GopherJS, optimization
// might not work.
vs = vs[0:12]
w, h := i.internalSize()
vs[0] = dx
vs[1] = dy
vs[2] = sx / float32(w)
vs[3] = sy / float32(h)
vs[4] = bx0 / float32(w)
vs[5] = by0 / float32(h)
vs[6] = bx1 / float32(w)
vs[7] = by1 / float32(h)
vs[8] = cr
vs[9] = cg
vs[10] = cb
vs[11] = ca
}
2017-09-14 17:24:18 +02:00
// makeStale makes the image stale.
2017-09-14 17:57:52 +02:00
func (i *Image) makeStale() {
i.basePixels = Pixels{}
i.drawTrianglesHistory = nil
2017-09-14 17:57:52 +02:00
i.stale = true
2018-03-25 12:42:44 +02:00
// Don't have to call makeStale recursively here.
// Restoring is done after topological sorting is done.
// If an image depends on another stale image, this means that
// the former image can be restored from the latest state of the latter image.
2016-07-26 19:16:31 +02:00
}
// ClearPixels clears the specified region by ReplacePixels.
func (i *Image) ClearPixels(x, y, width, height int) {
i.ReplacePixels(nil, x, y, width, height)
}
2017-09-14 17:24:18 +02:00
// ReplacePixels replaces the image pixels with the given pixels slice.
//
// ReplacePixels for a part is forbidden if the image is rendered with DrawTriangles or Fill.
func (i *Image) ReplacePixels(pixels []byte, x, y, width, height int) {
theImages.m.Lock()
defer theImages.m.Unlock()
w, h := i.image.Size()
if width <= 0 || height <= 0 {
panic("restorable: width/height must be positive")
}
if x < 0 || y < 0 || w <= x || h <= y || x+width <= 0 || y+height <= 0 || w < x+width || h < y+height {
panic(fmt.Sprintf("restorable: out of range x: %d, y: %d, width: %d, height: %d", x, y, width, height))
}
2018-02-28 18:49:45 +01:00
// TODO: Avoid making other images stale if possible. (#514)
// For this purpuse, images should remember which part of that is used for DrawTriangles.
2017-09-14 17:57:52 +02:00
theImages.makeStaleIfDependingOn(i)
2018-02-28 18:49:45 +01:00
if pixels != nil {
i.image.ReplacePixels(pixels, x, y, width, height)
} else {
// TODO: When pixels == nil, we don't have to care the pixel state there. In such cases, the image
// accepts only ReplacePixels and not Fill or DrawTriangles.
// TODO: Separate Image struct into two: images for only-ReplacePixels, and the others.
i.image.ReplacePixels(make([]byte, 4*width*height), x, y, width, height)
}
if x == 0 && y == 0 && width == w && height == h {
if pixels != nil {
i.basePixels.AddOrReplace(pixels, 0, 0, w, h)
} else {
i.basePixels.Remove(0, 0, w, h)
}
i.drawTrianglesHistory = nil
i.stale = false
return
}
2018-12-26 19:06:44 +01:00
// It looked like ReplacePixels on a part of image deletes other region that are rendered by DrawTriangles
// (#593, #758).
if len(i.drawTrianglesHistory) > 0 {
panic("restorable: ReplacePixels for a part after DrawTriangles is forbidden")
}
2018-12-26 19:06:44 +01:00
if i.stale {
// TODO: panic here?
return
}
2018-12-26 19:06:44 +01:00
if pixels != nil {
i.basePixels.AddOrReplace(pixels, x, y, width, height)
} else {
i.basePixels.Remove(x, y, width, height)
2019-07-15 20:08:26 +02:00
}
2016-07-26 03:51:48 +02:00
}
// DrawTriangles draws a given image img to the image.
func (i *Image) DrawTriangles(img *Image, vertices []float32, indices []uint16, colorm *affine.ColorM, mode driver.CompositeMode, filter driver.Filter, address driver.Address) {
theImages.m.Lock()
defer theImages.m.Unlock()
2019-01-20 18:17:09 +01:00
if i.priority {
panic("restorable: DrawTriangles cannot be called on a priority image")
2019-01-20 18:17:09 +01:00
}
if len(vertices) == 0 {
return
}
theImages.makeStaleIfDependingOn(i)
2019-05-26 14:10:25 +02:00
if img.stale || img.volatile || i.screen || !needsRestoring() || i.volatile {
2017-09-14 17:57:52 +02:00
i.makeStale()
2016-09-03 16:42:44 +02:00
} else {
i.appendDrawTrianglesHistory(img, vertices, indices, colorm, mode, filter, address)
2016-09-03 16:42:44 +02:00
}
i.image.DrawTriangles(img.image, vertices, indices, colorm, mode, filter, address)
2016-09-03 16:42:44 +02:00
}
// appendDrawTrianglesHistory appends a draw-image history item to the image.
func (i *Image) appendDrawTrianglesHistory(image *Image, vertices []float32, indices []uint16, colorm *affine.ColorM, mode driver.CompositeMode, filter driver.Filter, address driver.Address) {
if i.stale || i.volatile || i.screen {
2016-07-26 19:16:31 +02:00
return
}
// TODO: Would it be possible to merge draw image history items?
const maxDrawTrianglesHistoryNum = 1024
if len(i.drawTrianglesHistory)+1 > maxDrawTrianglesHistoryNum {
2017-09-14 17:57:52 +02:00
i.makeStale()
return
}
2016-08-22 17:05:23 +02:00
// All images must be resolved and not stale each after frame.
// So we don't have to care if image is stale or not here.
item := &drawTrianglesHistoryItem{
2016-07-24 19:28:59 +02:00
image: image,
vertices: vertices,
indices: indices,
colorm: colorm,
2016-07-24 19:28:59 +02:00
mode: mode,
filter: filter,
address: address,
2016-07-24 19:28:59 +02:00
}
i.drawTrianglesHistory = append(i.drawTrianglesHistory, item)
2016-07-13 19:35:20 +02:00
}
2018-11-12 16:00:10 +01:00
func (i *Image) readPixelsFromGPUIfNeeded() {
if len(i.drawTrianglesHistory) > 0 || i.stale {
2018-11-12 16:00:10 +01:00
graphicscommand.FlushCommands()
i.readPixelsFromGPU()
i.drawTrianglesHistory = nil
2018-11-12 16:00:10 +01:00
i.stale = false
}
}
2016-12-26 19:18:56 +01:00
// At returns a color value at (x, y).
2016-07-25 03:32:16 +02:00
//
// Note that this must not be called until context is available.
func (i *Image) At(x, y int) (byte, byte, byte, byte) {
theImages.m.Lock()
defer theImages.m.Unlock()
2017-09-14 17:57:52 +02:00
w, h := i.image.Size()
if x < 0 || y < 0 || w <= x || h <= y {
return 0, 0, 0, 0
}
2018-11-12 16:00:10 +01:00
i.readPixelsFromGPUIfNeeded()
return i.basePixels.At(x, y)
2016-07-13 19:35:20 +02:00
}
2017-09-14 17:24:18 +02:00
// makeStaleIfDependingOn makes the image stale if the image depends on target.
2017-09-14 17:57:52 +02:00
func (i *Image) makeStaleIfDependingOn(target *Image) {
if i.stale {
return
2016-07-26 19:16:31 +02:00
}
2017-09-14 17:57:52 +02:00
if i.dependsOn(target) {
i.makeStale()
2016-07-13 19:35:20 +02:00
}
}
2017-09-14 17:24:18 +02:00
// readPixelsFromGPU reads the pixels from GPU and resolves the image's 'stale' state.
func (i *Image) readPixelsFromGPU() {
w, h := i.Size()
i.basePixels = Pixels{}
i.basePixels.AddOrReplace(i.image.Pixels(), 0, 0, w, h)
i.drawTrianglesHistory = nil
2017-09-14 17:57:52 +02:00
i.stale = false
}
2017-09-14 17:24:18 +02:00
// resolveStale resolves the image's 'stale' state.
func (i *Image) resolveStale() {
2019-05-26 14:10:25 +02:00
if !needsRestoring() {
return
}
2017-09-14 17:57:52 +02:00
if i.volatile {
return
}
if i.screen {
return
}
2017-09-14 17:57:52 +02:00
if !i.stale {
return
2016-07-26 19:20:42 +02:00
}
i.readPixelsFromGPU()
2016-07-26 19:20:42 +02:00
}
2017-09-14 17:24:18 +02:00
// dependsOn returns a boolean value indicating whether the image depends on target.
2017-09-14 17:57:52 +02:00
func (i *Image) dependsOn(target *Image) bool {
for _, c := range i.drawTrianglesHistory {
if c.image == target {
return true
}
}
return false
}
2017-09-14 17:24:18 +02:00
// dependingImages returns all images that is depended by the image.
2017-09-14 17:57:52 +02:00
func (i *Image) dependingImages() map[*Image]struct{} {
r := map[*Image]struct{}{}
for _, c := range i.drawTrianglesHistory {
r[c.image] = struct{}{}
}
return r
}
2017-09-14 17:24:18 +02:00
// hasDependency returns a boolean value indicating whether the image depends on another image.
2017-09-14 17:57:52 +02:00
func (i *Image) hasDependency() bool {
if i.stale {
2016-07-26 19:16:31 +02:00
return false
}
return len(i.drawTrianglesHistory) > 0
2016-07-13 19:35:20 +02:00
}
2018-10-28 12:10:05 +01:00
// Restore restores *graphicscommand.Image from the pixels using its state.
func (i *Image) restore() {
w, h := i.Size()
// Dispose the internal image after getting its size for safety.
i.image.Dispose()
2017-09-14 17:57:52 +02:00
if i.screen {
// The screen image should also be recreated because framebuffer might
// be changed.
2018-10-28 12:10:05 +01:00
i.image = graphicscommand.NewScreenFramebufferImage(w, h)
i.basePixels = Pixels{}
i.drawTrianglesHistory = nil
2017-09-14 17:57:52 +02:00
i.stale = false
return
}
2017-09-14 17:57:52 +02:00
if i.volatile {
2018-10-28 12:10:05 +01:00
i.image = graphicscommand.NewImage(w, h)
i.clear()
return
}
2017-09-14 17:57:52 +02:00
if i.stale {
panic("restorable: pixels must not be stale when restoring")
}
2018-10-28 12:10:05 +01:00
gimg := graphicscommand.NewImage(w, h)
// Clear the image explicitly.
clearImage(gimg)
i.basePixels.Apply(gimg)
for _, c := range i.drawTrianglesHistory {
if c.image.hasDependency() {
2019-02-07 09:19:24 +01:00
panic("restorable: all dependencies must be already resolved but not")
}
gimg.DrawTriangles(c.image.image, c.vertices, c.indices, c.colorm, c.mode, c.filter, c.address)
2016-07-13 19:35:20 +02:00
}
if len(i.drawTrianglesHistory) > 0 {
i.basePixels = Pixels{}
i.basePixels.AddOrReplace(gimg.Pixels(), 0, 0, w, h)
2019-02-12 15:31:52 +01:00
}
i.image = gimg
i.drawTrianglesHistory = nil
2017-09-14 17:57:52 +02:00
i.stale = false
}
2017-09-14 17:24:18 +02:00
// Dispose disposes the image.
//
2017-09-14 20:13:36 +02:00
// After disposing, calling the function of the image causes unexpected results.
2017-09-14 17:57:52 +02:00
func (i *Image) Dispose() {
theImages.m.Lock()
defer theImages.m.Unlock()
theImages.remove(i)
2017-09-14 17:57:52 +02:00
i.image.Dispose()
i.image = nil
i.basePixels = Pixels{}
i.drawTrianglesHistory = nil
2017-09-14 17:57:52 +02:00
i.stale = false
2016-07-13 19:35:20 +02:00
}
2016-09-03 17:07:06 +02:00
2019-05-26 14:10:25 +02:00
// isInvalidated returns a boolean value indicating whether the image is invalidated.
2017-09-14 17:24:18 +02:00
//
// If an image is invalidated, GL context is lost and all the images should be restored asap.
2019-05-26 14:10:25 +02:00
func (i *Image) isInvalidated() bool {
2017-08-06 16:00:24 +02:00
// FlushCommands is required because c.offscreen.impl might not have an actual texture.
2018-10-28 12:10:05 +01:00
graphicscommand.FlushCommands()
2019-05-26 14:10:25 +02:00
return i.image.IsInvalidated()
2016-09-03 17:07:06 +02:00
}
2019-07-19 18:42:19 +02:00
func (i *Image) Dump(path string) error {
return i.image.Dump(path)
}