internal/ui: move the implementation for AntiAlias to stencilbuffer.go

Updates #3361
This commit is contained in:
Hajime Hoshi
2026-01-18 19:31:07 +09:00
parent eba3818e0e
commit 369f2ab8f7
4 changed files with 101 additions and 225 deletions
+6 -6
View File
@@ -333,7 +333,7 @@ func (i *Image) DrawImage(img *Image, options *DrawImageOptions) {
if !skipMipmap {
skipMipmap = canSkipMipmap(det, filter)
}
i.image.DrawTriangles(srcs, vs, is, blend, dr, [graphics.ShaderSrcImageCount]image.Rectangle{img.adjustedBounds()}, shader.shader, i.tmpUniforms, skipMipmap, false)
i.image.DrawTriangles(srcs, vs, is, blend, dr, [graphics.ShaderSrcImageCount]image.Rectangle{img.adjustedBounds()}, shader.shader, i.tmpUniforms, skipMipmap)
}
// Vertex represents a vertex passed to DrawTriangles.
@@ -586,7 +586,7 @@ func (i *Image) DrawTriangles(vertices []Vertex, indices []uint16, img *Image, o
//
// When the image i is disposed, DrawTriangles32 does nothing.
func (i *Image) DrawTriangles32(vertices []Vertex, indices []uint32, img *Image, options *DrawTrianglesOptions) {
if options != nil && options.FillRule != FillRuleFillAll {
if options != nil && (options.FillRule != FillRuleFillAll || options.AntiAlias) {
drawTrianglesWithStencilBuffer(i, vertices, indices, img, options)
return
}
@@ -694,7 +694,7 @@ func (i *Image) DrawTriangles32(vertices []Vertex, indices []uint32, img *Image,
if !skipMipmap {
skipMipmap = filter != builtinshader.FilterLinear
}
i.image.DrawTriangles(srcs, vs, indices, blend, i.adjustedBounds(), [graphics.ShaderSrcImageCount]image.Rectangle{img.adjustedBounds()}, shader.shader, i.tmpUniforms, skipMipmap, options.AntiAlias)
i.image.DrawTriangles(srcs, vs, indices, blend, i.adjustedBounds(), [graphics.ShaderSrcImageCount]image.Rectangle{img.adjustedBounds()}, shader.shader, i.tmpUniforms, skipMipmap)
}
// DrawTrianglesShaderOptions represents options for DrawTrianglesShader.
@@ -809,7 +809,7 @@ func (i *Image) DrawTrianglesShader(vertices []Vertex, indices []uint16, shader
//
// When the image i is disposed, DrawTrianglesShader32 does nothing.
func (i *Image) DrawTrianglesShader32(vertices []Vertex, indices []uint32, shader *Shader, options *DrawTrianglesShaderOptions) {
if options != nil && options.FillRule != FillRuleFillAll {
if options != nil && (options.FillRule != FillRuleFillAll || options.AntiAlias) {
drawTrianglesShaderWithStencilBuffer(i, vertices, indices, shader, options)
return
}
@@ -931,7 +931,7 @@ func (i *Image) DrawTrianglesShader32(vertices []Vertex, indices []uint32, shade
i.tmpUniforms = i.tmpUniforms[:0]
i.tmpUniforms = shader.appendUniforms(i.tmpUniforms, options.Uniforms)
i.image.DrawTriangles(imgs, vs, indices, blend, i.adjustedBounds(), srcRegions, shader.shader, i.tmpUniforms, true, options.AntiAlias)
i.image.DrawTriangles(imgs, vs, indices, blend, i.adjustedBounds(), srcRegions, shader.shader, i.tmpUniforms, true)
}
// DrawRectShaderOptions represents options for DrawRectShader.
@@ -1089,7 +1089,7 @@ func (i *Image) DrawRectShader(width, height int, shader *Shader, options *DrawR
dr := i.adjustedBounds()
i.image.DrawTriangles(imgs, vs, is, blend, dr, srcRegions, shader.shader, i.tmpUniforms, true, false)
i.image.DrawTriangles(imgs, vs, is, blend, dr, srcRegions, shader.shader, i.tmpUniforms, true)
}
// SubImage returns an image representing the portion of the image p visible through r.
-3
View File
@@ -259,9 +259,6 @@ func (c *context) drawGame(graphicsDriver graphicsdriver.Graphics, ui *UserInter
c.game.DrawFinalScreen(c.screenScaleAndOffsets())
// The final screen is never used as the rendering source.
// Flush its buffer here just in case.
c.screen.flushBufferIfNeeded()
return true, nil
}
+2 -213
View File
@@ -16,7 +16,6 @@ package ui
import (
"image"
"math"
"github.com/hajimehoshi/ebiten/v2/internal/atlas"
"github.com/hajimehoshi/ebiten/v2/internal/graphics"
@@ -32,8 +31,6 @@ func SetPanicOnErrorOnReadingPixelsForTesting(value bool) {
panicOnErrorOnReadingPixels = value
}
const bigOffscreenScale = 2
type Image struct {
ui *UserInterface
@@ -45,9 +42,6 @@ type Image struct {
// lastBlend is the lastly-used blend for mipmap.Image.
lastBlend graphicsdriver.Blend
// bigOffscreenBuffer is a double-sized offscreen for anti-alias rendering.
bigOffscreenBuffer *bigOffscreenImage
// modifyCallback is a callback called when DrawTriangles or WritePixels is called.
// modifyCallback is useful to detect whether the image is manipulated or not after a certain time.
modifyCallback func()
@@ -70,36 +64,21 @@ func (i *Image) Deallocate() {
if i.mipmap == nil {
return
}
if i.bigOffscreenBuffer != nil {
i.bigOffscreenBuffer.deallocate()
}
i.mipmap.Deallocate()
}
func (i *Image) DrawTriangles(srcs [graphics.ShaderSrcImageCount]*Image, vertices []float32, indices []uint32, blend graphicsdriver.Blend, dstRegion image.Rectangle, srcRegions [graphics.ShaderSrcImageCount]image.Rectangle, shader *Shader, uniforms []uint32, canSkipMipmap bool, antialias bool) {
func (i *Image) DrawTriangles(srcs [graphics.ShaderSrcImageCount]*Image, vertices []float32, indices []uint32, blend graphicsdriver.Blend, dstRegion image.Rectangle, srcRegions [graphics.ShaderSrcImageCount]image.Rectangle, shader *Shader, uniforms []uint32, canSkipMipmap bool) {
if i.modifyCallback != nil {
i.modifyCallback()
}
i.lastBlend = blend
if antialias {
if i.bigOffscreenBuffer == nil {
i.bigOffscreenBuffer = i.ui.newBigOffscreenImage(i, atlas.ImageTypeUnmanaged)
}
i.bigOffscreenBuffer.drawTriangles(srcs, vertices, indices, blend, dstRegion, srcRegions, shader, uniforms, canSkipMipmap)
return
}
i.flushBufferIfNeeded()
var srcMipmaps [graphics.ShaderSrcImageCount]*mipmap.Mipmap
for i, src := range srcs {
if src == nil {
continue
}
src.flushBufferIfNeeded()
srcMipmaps[i] = src.mipmap
}
@@ -110,7 +89,6 @@ func (i *Image) WritePixels(pix []byte, region image.Rectangle) {
if i.modifyCallback != nil {
i.modifyCallback()
}
i.flushBufferIfNeeded()
i.mipmap.WritePixels(pix, region)
}
@@ -120,8 +98,6 @@ func (i *Image) ReadPixels(pixels []byte, region image.Rectangle) {
return
}
i.flushBigOffscreenBufferIfNeeded()
if err := i.ui.readPixels(i.mipmap, pixels, region); err != nil {
if panicOnErrorOnReadingPixels {
panic(err)
@@ -131,20 +107,9 @@ func (i *Image) ReadPixels(pixels []byte, region image.Rectangle) {
}
func (i *Image) DumpScreenshot(name string, blackbg bool) (string, error) {
i.flushBufferIfNeeded()
return i.ui.dumpScreenshot(i.mipmap, name, blackbg)
}
func (i *Image) flushBufferIfNeeded() {
i.flushBigOffscreenBufferIfNeeded()
}
func (i *Image) flushBigOffscreenBufferIfNeeded() {
if i.bigOffscreenBuffer != nil {
i.bigOffscreenBuffer.flush()
}
}
func (u *UserInterface) DumpImages(dir string) (string, error) {
return u.dumpImages(dir)
}
@@ -174,181 +139,5 @@ func (i *Image) Fill(r, g, b, a float32, region image.Rectangle) {
}
sr := image.Rect(0, 0, i.ui.whiteImage.width, i.ui.whiteImage.height)
// i.lastBlend is updated in DrawTriangles.
i.DrawTriangles(srcs, i.tmpVerticesForFill, is, blend, region, [graphics.ShaderSrcImageCount]image.Rectangle{sr}, NearestFilterShader, nil, true, false)
}
type bigOffscreenImage struct {
ui *UserInterface
orig *Image
imageType atlas.ImageType
image *Image
region image.Rectangle
blend graphicsdriver.Blend
dirty bool
tmpVerticesForFlushing []float32
tmpVerticesForCopying []float32
}
func (u *UserInterface) newBigOffscreenImage(orig *Image, imageType atlas.ImageType) *bigOffscreenImage {
return &bigOffscreenImage{
ui: u,
orig: orig,
imageType: imageType,
}
}
func (i *bigOffscreenImage) deallocate() {
if i.image != nil {
i.image.Deallocate()
}
i.dirty = false
}
func (i *bigOffscreenImage) drawTriangles(srcs [graphics.ShaderSrcImageCount]*Image, vertices []float32, indices []uint32, blend graphicsdriver.Blend, dstRegion image.Rectangle, srcRegions [graphics.ShaderSrcImageCount]image.Rectangle, shader *Shader, uniforms []uint32, canSkipMipmap bool) {
if i.blend != blend {
i.flush()
}
i.blend = blend
// If the new region doesn't match with the current region, remove the buffer image and recreate it later.
if r := i.requiredRegion(vertices); i.region != r {
i.flush()
i.image = nil
i.region = r
}
if i.region.Empty() {
return
}
if i.image == nil {
i.image = i.ui.NewImage(i.region.Dx()*bigOffscreenScale, i.region.Dy()*bigOffscreenScale, i.imageType)
}
// Copy the current rendering result to get the correct blending result.
if blend != graphicsdriver.BlendSourceOver && !i.dirty {
srcs := [graphics.ShaderSrcImageCount]*Image{i.orig}
if len(i.tmpVerticesForCopying) < 4*graphics.VertexFloatCount {
i.tmpVerticesForCopying = make([]float32, 4*graphics.VertexFloatCount)
}
// i.tmpVerticesForCopying can be reused as this is sent to DrawTriangles immediately.
graphics.QuadVerticesFromSrcAndMatrix(
i.tmpVerticesForCopying,
float32(i.region.Min.X), float32(i.region.Min.Y), float32(i.region.Max.X), float32(i.region.Max.Y),
bigOffscreenScale, 0, 0, bigOffscreenScale, 0, 0,
1, 1, 1, 1)
is := graphics.QuadIndices()
dstRegion := image.Rect(0, 0, i.region.Dx()*bigOffscreenScale, i.region.Dy()*bigOffscreenScale)
srcRegion := i.region
i.image.DrawTriangles(srcs, i.tmpVerticesForCopying, is, graphicsdriver.BlendCopy, dstRegion, [graphics.ShaderSrcImageCount]image.Rectangle{srcRegion}, NearestFilterShader, nil, true, false)
}
for idx := 0; idx < len(vertices); idx += graphics.VertexFloatCount {
vertices[idx] = (vertices[idx] - float32(i.region.Min.X)) * bigOffscreenScale
vertices[idx+1] = (vertices[idx+1] - float32(i.region.Min.Y)) * bigOffscreenScale
}
// Translate to i.region coordinate space, and clamp against region size.
dstRegion = dstRegion.Sub(i.region.Min)
dstRegion = dstRegion.Intersect(image.Rect(0, 0, i.region.Dx(), i.region.Dy()))
dstRegion.Min.X *= bigOffscreenScale
dstRegion.Min.Y *= bigOffscreenScale
dstRegion.Max.X *= bigOffscreenScale
dstRegion.Max.Y *= bigOffscreenScale
i.image.DrawTriangles(srcs, vertices, indices, blend, dstRegion, srcRegions, shader, uniforms, canSkipMipmap, false)
i.dirty = true
}
func (i *bigOffscreenImage) flush() {
if i.image == nil {
return
}
if !i.dirty {
return
}
// Mark the offscreen clean earlier to avoid recursive calls.
i.dirty = false
srcs := [graphics.ShaderSrcImageCount]*Image{i.image}
if len(i.tmpVerticesForFlushing) < 4*graphics.VertexFloatCount {
i.tmpVerticesForFlushing = make([]float32, 4*graphics.VertexFloatCount)
}
// i.tmpVerticesForFlushing can be reused as this is sent to DrawTriangles in this function.
graphics.QuadVerticesFromSrcAndMatrix(
i.tmpVerticesForFlushing,
0, 0, float32(i.region.Dx()*bigOffscreenScale), float32(i.region.Dy()*bigOffscreenScale),
1.0/bigOffscreenScale, 0, 0, 1.0/bigOffscreenScale, float32(i.region.Min.X), float32(i.region.Min.Y),
1, 1, 1, 1)
is := graphics.QuadIndices()
dstRegion := i.region
srcRegion := image.Rect(0, 0, i.region.Dx()*bigOffscreenScale, i.region.Dy()*bigOffscreenScale)
blend := graphicsdriver.BlendSourceOver
if i.blend != graphicsdriver.BlendSourceOver {
blend = graphicsdriver.BlendCopy
}
i.orig.DrawTriangles(srcs, i.tmpVerticesForFlushing, is, blend, dstRegion, [graphics.ShaderSrcImageCount]image.Rectangle{srcRegion}, LinearFilterShader, nil, true, false)
i.image.clear()
i.dirty = false
}
func (i *bigOffscreenImage) requiredRegion(vertices []float32) image.Rectangle {
minX := float32(i.orig.width)
minY := float32(i.orig.height)
maxX := float32(0)
maxY := float32(0)
for i := 0; i < len(vertices); i += graphics.VertexFloatCount {
dstX := vertices[i]
dstY := vertices[i+1]
if minX > floor(dstX)-1 {
minX = floor(dstX) - 1
}
if minY > floor(dstY)-1 {
minY = floor(dstY) - 1
}
if maxX < ceil(dstX)+1 {
maxX = ceil(dstX) + 1
}
if maxY < ceil(dstY)+1 {
maxY = ceil(dstY) + 1
}
}
// Adjust the granularity of the rectangle.
r := image.Rect(
roundDown16(int(minX)),
roundDown16(int(minY)),
roundUp16(int(maxX)),
roundUp16(int(maxY)))
r = r.Intersect(image.Rect(0, 0, i.orig.width, i.orig.height))
// TODO: Is this check required?
if r.Dx() < 0 || r.Dy() < 0 {
return i.region
}
return r.Union(i.region)
}
func floor(x float32) float32 {
return float32(math.Floor(float64(x)))
}
func ceil(x float32) float32 {
return float32(math.Ceil(float64(x)))
}
func roundDown16(x int) int {
return x & ^(0xf)
}
func roundUp16(x int) int {
return ((x - 1) & ^(0xf)) + 0x10
i.DrawTriangles(srcs, i.tmpVerticesForFill, is, blend, region, [graphics.ShaderSrcImageCount]image.Rectangle{sr}, NearestFilterShader, nil, true)
}
+93 -3
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// This file emulates the deprecated APIs (FillRule) with the non-deprecated APIs.
// This file emulates the deprecated APIs (FillRule and AntiAlias) with the non-deprecated APIs.
//
// The pseudo stencil buffer implementation is based on the following article:
// https://medium.com/@evanwallace/easy-scalable-text-rendering-on-the-gpu-c3f4d782c5ac
@@ -189,14 +189,22 @@ func shaderFromFillRule(fillRule FillRule) *Shader {
func drawTrianglesWithStencilBuffer(dst *Image, vertices []Vertex, indices []uint32, img *Image, options *DrawTrianglesOptions) {
if options.FillRule == FillRuleFillAll {
panic("ebiten: FillRule must be FillRuleNonZero or FillRuleEvenOdd at drawTrianglesWithStencilBuffer")
if !options.AntiAlias {
panic("not reached")
}
doDrawTrianglesWithAntialias(dst, vertices, indices, img, options, nil, nil)
return
}
doDrawTrianglesShaderWithStencilBuffer(dst, vertices, indices, img, options, nil, nil)
}
func drawTrianglesShaderWithStencilBuffer(dst *Image, vertices []Vertex, indices []uint32, shader *Shader, options *DrawTrianglesShaderOptions) {
if options.FillRule == FillRuleFillAll {
panic("ebiten: FillRule must be FillRuleNonZero or FillRuleEvenOdd at drawTrianglesShaderWithStencilBuffer")
if !options.AntiAlias {
panic("not reached")
}
doDrawTrianglesWithAntialias(dst, vertices, indices, nil, nil, shader, options)
return
}
doDrawTrianglesShaderWithStencilBuffer(dst, vertices, indices, nil, nil, shader, options)
}
@@ -205,6 +213,86 @@ var (
tmpVerticesForStencilBuffer []Vertex
)
// doDrawTrianglesWithAntialias draw triangles with antialiasing.
//
// doDrawTrianglesWithAntialias doesn't batch draw calls, so this might not be efficient.
// This is different from Ebitengine v2.9's behavior.
// However, this function is for the legacy API and its usage is expected to be minimal.
func doDrawTrianglesWithAntialias(dst *Image, vertices []Vertex, indices []uint32, img *Image, dtOptions *DrawTrianglesOptions, shader *Shader, dtsOptions *DrawTrianglesShaderOptions) {
stencilBufferM.Lock()
defer stencilBufferM.Unlock()
bounds := dst.Bounds()
bounds.Min.X *= 2
bounds.Max.X *= 2
bounds.Min.Y *= 2
bounds.Max.Y *= 2
tmpVerticesForStencilBuffer = slices.Grow(tmpVerticesForStencilBuffer, len(vertices))
vs := tmpVerticesForStencilBuffer[:len(vertices)]
copy(vs, vertices)
for i := range vs {
vs[i].DstX *= 2
vs[i].DstY *= 2
}
var uncommonBlend bool
if dtOptions != nil {
if dtOptions.CompositeMode != CompositeModeCustom {
uncommonBlend = dtOptions.CompositeMode != CompositeModeSourceOver
} else {
uncommonBlend = dtOptions.Blend != BlendSourceOver
}
} else if dtsOptions != nil {
if dtsOptions.CompositeMode != CompositeModeCustom {
uncommonBlend = dtsOptions.CompositeMode != CompositeModeSourceOver
} else {
uncommonBlend = dtsOptions.Blend != BlendSourceOver
}
}
// Copy the current destination image for the blending, if the blend mode is not the regular alpha blending.
os1 := ensureOffscreenImage1(bounds).SubImage(bounds).(*Image)
if uncommonBlend {
op := &DrawImageOptions{}
op.GeoM.Scale(2, 2)
op.Blend = BlendCopy
os1.DrawImage(dst, op)
}
if dtOptions != nil {
op := &DrawTrianglesOptions{}
op.ColorM = dtOptions.ColorM
op.ColorScaleMode = dtOptions.ColorScaleMode
op.CompositeMode = dtOptions.CompositeMode
op.Blend = dtOptions.Blend
op.Filter = dtOptions.Filter
op.Address = dtOptions.Address
op.DisableMipmaps = dtOptions.DisableMipmaps
os1.DrawTriangles32(vs, indices, img, op)
} else if dtsOptions != nil {
op := &DrawTrianglesShaderOptions{}
op.Uniforms = dtsOptions.Uniforms
op.Images = dtsOptions.Images
op.CompositeMode = dtsOptions.CompositeMode
op.Blend = dtsOptions.Blend
os1.DrawTrianglesShader32(vs, indices, shader, op)
}
op := &DrawImageOptions{}
op.GeoM.Scale(0.5, 0.5)
op.Filter = FilterLinear
if uncommonBlend {
op.Blend = BlendCopy
}
dst.DrawImage(os1, op)
}
// doDrawTrianglesShaderWithStencilBuffer draw triangles with stencil buffer.
//
// doDrawTrianglesShaderWithStencilBuffer doesn't batch draw calls, so this might not be efficient.
// This is different from Ebitengine v2.9's behavior.
// However, this function is for the legacy API and its usage is expected to be minimal.
func doDrawTrianglesShaderWithStencilBuffer(dst *Image, vertices []Vertex, indices []uint32, img *Image, dtOptions *DrawTrianglesOptions, shader *Shader, dtsOptions *DrawTrianglesShaderOptions) {
stencilBufferM.Lock()
defer stencilBufferM.Unlock()
@@ -271,6 +359,8 @@ func doDrawTrianglesShaderWithStencilBuffer(dst *Image, vertices []Vertex, indic
}
// Render the offscreen image onto dst.
// Note that some blends like BlendXor might not work correctly, but this is expected,
// as this logic is for the legacy API.
op := &DrawImageOptions{}
if dtOptions != nil {
op.CompositeMode = dtOptions.CompositeMode