text: Remove uniqFace for performance

Fixes #554. Add comments for #498.
This commit is contained in:
Hajime Hoshi 2018-03-15 23:00:23 +09:00
parent 1b35bbec9a
commit 9092ec083d

View File

@ -21,7 +21,6 @@ import (
"image" "image"
"image/color" "image/color"
"math" "math"
"reflect"
"golang.org/x/image/font" "golang.org/x/image/font"
"golang.org/x/image/math/fixed" "golang.org/x/image/math/fixed"
@ -112,25 +111,6 @@ func drawGlyph(dst *ebiten.Image, face font.Face, r rune, x, y fixed.Int26_6, cl
_ = dst.DrawImage(img, op) _ = dst.DrawImage(img, op)
} }
var (
fontFaces = map[font.Face]struct{}{}
)
func uniqFace(f font.Face) font.Face {
if _, ok := fontFaces[f]; ok {
return f
}
// If the (DeepEqual-ly) same font exists,
// reuse this to avoid to consume a lot of cache (#498).
for key := range fontFaces {
if reflect.DeepEqual(key, f) {
return key
}
}
fontFaces[f] = struct{}{}
return f
}
var ( var (
// Use pointers to avoid copying on browsers. // Use pointers to avoid copying on browsers.
glyphBoundsCache = map[font.Face]map[rune]*fixed.Rectangle26_6{} glyphBoundsCache = map[font.Face]map[rune]*fixed.Rectangle26_6{}
@ -223,6 +203,9 @@ var textM sync.Mutex
// Glyphs used for rendering are cached in least-recently-used way. // Glyphs used for rendering are cached in least-recently-used way.
// It is OK to call this function with a same text and a same face at every frame in terms of performance. // It is OK to call this function with a same text and a same face at every frame in terms of performance.
// //
// Be careful that the passed font face is held by this package and is never released.
// This is a known issue (#498).
//
// This function is concurrent-safe. // This function is concurrent-safe.
func Draw(dst *ebiten.Image, text string, face font.Face, x, y int, clr color.Color) { func Draw(dst *ebiten.Image, text string, face font.Face, x, y int, clr color.Color) {
textM.Lock() textM.Lock()
@ -235,9 +218,8 @@ func Draw(dst *ebiten.Image, text string, face font.Face, x, y int, clr color.Co
if prevR >= 0 { if prevR >= 0 {
fx += face.Kern(prevR, r) fx += face.Kern(prevR, r)
} }
fa := uniqFace(face) drawGlyph(dst, face, r, fx, fixed.I(y), clr)
drawGlyph(dst, fa, r, fx, fixed.I(y), clr) fx += glyphAdvance(face, r)
fx += glyphAdvance(fa, r)
prevR = r prevR = r
} }