text.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // Copyright 2023 The Ebitengine Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package text offers functions to draw texts on an Ebitengine's image.
  15. //
  16. // For the example using a TrueType font, see examples in the examples directory.
  17. package text
  18. import (
  19. "strings"
  20. "golang.org/x/image/math/fixed"
  21. "github.com/hajimehoshi/ebiten/v2"
  22. "github.com/hajimehoshi/ebiten/v2/vector"
  23. )
  24. // Face is an interface representing a font face.
  25. // The implementations are only faces defined in this package, like GoTextFace and GoXFace.
  26. type Face interface {
  27. // Metrics returns the metrics for this Face.
  28. Metrics() Metrics
  29. advance(text string) float64
  30. hasGlyph(r rune) bool
  31. appendGlyphsForLine(glyphs []Glyph, line string, indexOffset int, originX, originY float64) []Glyph
  32. appendVectorPathForLine(path *vector.Path, line string, originX, originY float64)
  33. direction() Direction
  34. // private is an unexported function preventing being implemented by other packages.
  35. private()
  36. }
  37. // Metrics holds the metrics for a Face.
  38. // A visual depiction is at https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyph_metrics_2x.png
  39. type Metrics struct {
  40. // HLineGap is the recommended amount of vertical space between two lines of text in pixels.
  41. HLineGap float64
  42. // HAscent is the distance in pixels from the top of a line to its baseline for horizontal lines.
  43. HAscent float64
  44. // HDescent is the distance in pixels from the bottom of a line to its baseline for horizontal lines.
  45. // The value is typically positive, even though a descender goes below the baseline.
  46. HDescent float64
  47. // VLineGap is the recommended amount of horizontal space between two lines of text in pixels.
  48. // If the face is GoXFace or the font doesn't support a vertical direction, VLineGap is 0.
  49. VLineGap float64
  50. // VAscent is the distance in pixels from the top of a line to its baseline for vertical lines.
  51. // If the face is GoXFace or the font doesn't support a vertical direction, VAscent is 0.
  52. VAscent float64
  53. // VDescent is the distance in pixels from the top of a line to its baseline for vertical lines.
  54. // If the face is GoXFace or the font doesn't support a vertical direction, VDescent is 0.
  55. VDescent float64
  56. // XHeight is the distance in pixels from the baseline to the top of the lower case letters.
  57. XHeight float64
  58. // CapHeight is the distance in pixels from the baseline to the top of the capital letters.
  59. CapHeight float64
  60. }
  61. func fixed26_6ToFloat32(x fixed.Int26_6) float32 {
  62. return float32(x) / (1 << 6)
  63. }
  64. func fixed26_6ToFloat64(x fixed.Int26_6) float64 {
  65. return float64(x) / (1 << 6)
  66. }
  67. func float32ToFixed26_6(x float32) fixed.Int26_6 {
  68. return fixed.Int26_6(x * (1 << 6))
  69. }
  70. func float64ToFixed26_6(x float64) fixed.Int26_6 {
  71. return fixed.Int26_6(x * (1 << 6))
  72. }
  73. func glyphVariationCount(face Face) int {
  74. var s float64
  75. if m := face.Metrics(); face.direction().isHorizontal() {
  76. s = m.HAscent + m.HDescent
  77. } else {
  78. s = m.VAscent + m.VDescent
  79. }
  80. // The threshold is decided based on the rendering result of the examples (e.g. examples/text, examples/ui).
  81. if s < 20 {
  82. return 8
  83. }
  84. if s < 40 {
  85. return 4
  86. }
  87. if s < 80 {
  88. return 2
  89. }
  90. return 1
  91. }
  92. func adjustGranularity(x fixed.Int26_6, face Face) fixed.Int26_6 {
  93. c := glyphVariationCount(face)
  94. factor := (1 << 6) / fixed.Int26_6(c)
  95. return x / factor * factor
  96. }
  97. // Glyph represents one glyph to render.
  98. type Glyph struct {
  99. // StartIndexInBytes is the start index in bytes for the given string at AppendGlyphs.
  100. StartIndexInBytes int
  101. // EndIndexInBytes is the end index in bytes for the given string at AppendGlyphs.
  102. EndIndexInBytes int
  103. // GID is an ID for a glyph of TrueType or OpenType font. GID is valid when the face is GoTextFace.
  104. GID uint32
  105. // Image is a rasterized glyph image.
  106. // Image is a grayscale image i.e. RGBA values are the same.
  107. //
  108. // Image should be used as a render source and must not be modified.
  109. //
  110. // Image can be nil.
  111. Image *ebiten.Image
  112. // X is the X position to render this glyph.
  113. // The position is determined in a sequence of characters given at AppendGlyphs.
  114. // The position's origin is the first character's origin position.
  115. X float64
  116. // Y is the Y position to render this glyph.
  117. // The position is determined in a sequence of characters given at AppendGlyphs.
  118. // The position's origin is the first character's origin position.
  119. Y float64
  120. // OriginX is the X position of the origin of this glyph.
  121. OriginX float64
  122. // OriginY is the Y position of the origin of this glyph.
  123. OriginY float64
  124. // OriginOffsetX is the adjustment value to the X position of the origin of this glyph.
  125. // OriginOffsetX is usually 0, but can be non-zero for some special glyphs or glyphs in the vertical text layout.
  126. OriginOffsetX float64
  127. // OriginOffsetY is the adjustment value to the Y position of the origin of this glyph.
  128. // OriginOffsetY is usually 0, but can be non-zero for some special glyphs or glyphs in the vertical text layout.
  129. OriginOffsetY float64
  130. }
  131. // Advance returns the advanced distance from the origin position when rendering the given text with the given face.
  132. //
  133. // Advance doesn't treat multiple lines.
  134. //
  135. // Advance is concurrent-safe.
  136. func Advance(text string, face Face) float64 {
  137. return face.advance(text)
  138. }
  139. // Direction represents a direction of text rendering.
  140. // Direction indicates both the primary direction, in which a text in one line is rendered,
  141. // and the secondary direction, in which multiple lines are rendered.
  142. type Direction int
  143. const (
  144. // DirectionLeftToRight indicates that the primary direction is from left to right,
  145. // and the secondary direction is from top to bottom.
  146. DirectionLeftToRight Direction = iota
  147. // DirectionRightToLeft indicates that the primary direction is from right to left,
  148. // and the secondary direction is from top to bottom.
  149. DirectionRightToLeft
  150. // DirectionTopToBottomAndLeftToRight indicates that the primary direction is from top to bottom,
  151. // and the secondary direction is from left to right.
  152. // This is used e.g. for Mongolian.
  153. DirectionTopToBottomAndLeftToRight
  154. // DirectionTopToBottomAndRightToLeft indicates that the primary direction is from top to bottom,
  155. // and the secondary direction is from right to left.
  156. // This is used e.g. for Japanese.
  157. DirectionTopToBottomAndRightToLeft
  158. )
  159. func (d Direction) isHorizontal() bool {
  160. switch d {
  161. case DirectionLeftToRight, DirectionRightToLeft:
  162. return true
  163. }
  164. return false
  165. }
  166. // Measure measures the boundary size of the text.
  167. // With a horizontal direction face, the width is the longest line's advance, and the height is the total of line heights.
  168. // With a vertical direction face, the width and the height are calculated in an opposite manner.
  169. //
  170. // Measure is concurrent-safe.
  171. func Measure(text string, face Face, lineSpacingInPixels float64) (width, height float64) {
  172. if text == "" {
  173. return 0, 0
  174. }
  175. var primary float64
  176. var lineCount int
  177. for t := text; ; {
  178. lineCount++
  179. line, rest, found := strings.Cut(t, "\n")
  180. a := face.advance(line)
  181. if primary < a {
  182. primary = a
  183. }
  184. if !found {
  185. break
  186. }
  187. t = rest
  188. }
  189. m := face.Metrics()
  190. if face.direction().isHorizontal() {
  191. secondary := float64(lineCount-1)*lineSpacingInPixels + m.HAscent + m.HDescent
  192. return primary, secondary
  193. }
  194. secondary := float64(lineCount-1)*lineSpacingInPixels + m.VAscent + m.VDescent
  195. return secondary, primary
  196. }
  197. // CacheGlyphs pre-caches the glyphs for the given text and the given font face into the cache.
  198. //
  199. // CacheGlyphs doesn't treat multiple lines.
  200. //
  201. // Glyphs used for rendering are cached in the least-recently-used way.
  202. // Then old glyphs might be evicted from the cache.
  203. // As the cache capacity has limitations, it is not guaranteed that all the glyphs for runes given at CacheGlyphs are cached.
  204. // The cache is shared with Draw and AppendGlyphs.
  205. //
  206. // One rune can have multiple variations of glyphs due to sub-pixels in X or Y direction.
  207. // CacheGlyphs creates all such variations for one rune, while Draw and AppendGlyphs create only necessary glyphs.
  208. //
  209. // Draw and AppendGlyphs automatically create and cache necessary glyphs, so usually you don't have to call CacheGlyphs explicitly.
  210. // If you really care about the performance, CacheGlyphs might be useful.
  211. //
  212. // CacheGlyphs is pretty heavy since it creates all the possible variations of glyphs.
  213. // Call CacheGlyphs only when you really need it.
  214. //
  215. // CacheGlyphs is concurrent-safe.
  216. func CacheGlyphs(text string, face Face) {
  217. var x, y float64
  218. c := glyphVariationCount(face)
  219. var buf []Glyph
  220. // Create all the possible variations (#2528).
  221. for i := 0; i < c; i++ {
  222. buf = appendGlyphs(buf, text, face, x, y, nil)
  223. buf = buf[:0]
  224. if face.direction().isHorizontal() {
  225. x += 1.0 / float64(c)
  226. } else {
  227. y += 1.0 / float64(c)
  228. }
  229. }
  230. }