gamnit: extract general Font from TileSetFont
[nit.git] / lib / gamnit / font.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
15 # Abstract font drawing services, implemented by `bmfont` and `tileset`
16 module font
17
18 import flat
19
20 # Abstract font, drawn by a `TextSprites`
21 abstract class Font
22
23 # Line spacing modifier for `pld` and `plu`
24 #
25 # This value acts as multiplier to the standard line height.
26 # Defaults to 0.4, so a `pld` moves chars down by about half a line.
27 var partial_line_mod: Numeric = 0.4 is writable
28
29 # Backend writing service, clients should use `TextSprites.text=`
30 protected fun write_into(text_sprites: TextSprites, text: Text) is abstract
31 end
32
33 # Manage a set of sprites to display some text
34 class TextSprites
35
36 # Font used to draw text
37 var font: Font
38
39 # Top left of the first character in UI coordinates
40 var anchor: Point3d[Float]
41
42 # Last set of sprites generated to display `text=`
43 var sprites = new Array[Sprite]
44
45 # Sprite set where to put created sprites
46 #
47 # Defaults to `app::ui_sprites`, but it could also be set to a
48 # `app::sprites` or a custom collection.
49 var target_sprite_set: Set[Sprite] = app.ui_sprites is lazy, writable
50
51 private var cached_text: nullable Text = ""
52
53 # Last text drawn
54 fun text: nullable Text do return cached_text
55
56 # Update the text displayed by inserting new sprites into `app.ui_sprites`
57 #
58 # Does not redraw if `text` has not changed.
59 fun text=(text: nullable Text)
60 is autoinit do
61 # Don't redraw if text hasn't changed
62 if text == cached_text then return
63 cached_text = text
64
65 # Clean up last used sprites
66 for s in sprites do if target_sprite_set.has(s) then target_sprite_set.remove s
67 sprites.clear
68
69 if text == null then return
70
71 font.write_into(self, text)
72
73 # Register sprites to be drawn by `app.ui_camera`
74 target_sprite_set.add_all sprites
75 end
76 end
77
78 # Partial line forward (U+008B)
79 fun pld: Char do return '\8b'
80
81 # Partial line backward (U+008C)
82 fun plu: Char do return '\8c'