Line data Source code
1 : package resources
2 :
3 : import (
4 : "errors"
5 : "fmt"
6 :
7 : "github.com/hajimehoshi/ebiten/v2/text/v2"
8 : )
9 :
10 : // errNoFontSource は利用可能なフォントソースが無い場合に返す
11 : var errNoFontSource = errors.New("no available font source")
12 :
13 : type fonts struct {
14 : smallFace text.Face
15 : bodyFace text.Face
16 : keycapFace text.Face
17 : titleFontFace text.Face
18 : splashFontFace text.Face
19 : }
20 :
21 : // loadFonts は指定されたサイズでフォントフェイスを作成する
22 : // 複数のFaceSourceを指定した場合、順番にフォールバックする
23 : func loadFonts(sources []*text.GoTextFaceSource) (*fonts, error) {
24 1 : smallFace, err := loadFont(sources, 13)
25 1 : if err != nil {
26 1 : return nil, fmt.Errorf("failed to load small font: %w", err)
27 1 : }
28 1 : bodyFace, err := loadFont(sources, 16)
29 1 : if err != nil {
30 0 : return nil, fmt.Errorf("failed to load body font: %w", err)
31 0 : }
32 : // キーキャップの箱に入れるグリフ用。アイコンフォントの字形は em 内の余白が広く
33 : // 本文サイズでは小さく見えるため、ひと回り大きい em で描いて字面を出す。
34 : // 合成フェイスの行メトリクスは最大フェイスで決まるので、本文フェイスを拡大せず
35 : // 専用フェイスに分けることで、通常のリスト行の高さへ影響させない
36 1 : keycapFace, err := loadFont(sources, 24)
37 1 : if err != nil {
38 0 : return nil, fmt.Errorf("failed to load keycap font: %w", err)
39 0 : }
40 1 : titleFontFace, err := loadFont(sources, 32)
41 1 : if err != nil {
42 0 : return nil, fmt.Errorf("failed to load title font: %w", err)
43 0 : }
44 1 : splashFontFace, err := loadFont(sources, 48)
45 1 : if err != nil {
46 0 : return nil, fmt.Errorf("failed to load splash font: %w", err)
47 0 : }
48 :
49 1 : return &fonts{
50 1 : smallFace: smallFace,
51 1 : bodyFace: bodyFace,
52 1 : keycapFace: keycapFace,
53 1 : titleFontFace: titleFontFace,
54 1 : splashFontFace: splashFontFace,
55 1 : }, nil
56 : }
57 :
58 : func loadFont(sources []*text.GoTextFaceSource, size float64) (text.Face, error) {
59 1 : if len(sources) == 0 {
60 1 : return nil, errNoFontSource
61 1 : }
62 :
63 1 : faces := make([]text.Face, 0, len(sources))
64 1 : for _, src := range sources {
65 1 : if src != nil {
66 1 : faces = append(faces, &text.GoTextFace{
67 1 : Source: src,
68 1 : Size: size,
69 1 : })
70 1 : }
71 : }
72 :
73 1 : if len(faces) == 0 {
74 1 : return nil, errNoFontSource
75 1 : }
76 1 : if len(faces) == 1 {
77 1 : return faces[0], nil
78 1 : }
79 :
80 1 : multiFace, err := text.NewMultiFace(faces...)
81 1 : if err != nil {
82 0 : return nil, fmt.Errorf("failed to create multi face: %w", err)
83 0 : }
84 1 : return multiFace, nil
85 : }
|