-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfont.rb
88 lines (63 loc) · 2.02 KB
/
font.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require 'yaml'
class Font
def initialize(fontfile)
definition = YAML.load_file(fontfile) # based on fonts/ascii.yml.example
@name = definition['name']
@version = definition['version']
@width = definition['width'].to_i
@height = definition['height'].to_i
@dots = @width * @height
@grids = build(definition['characters'])
@cache = { # to cache core output formats
text: {},
dcled: {}
}
end
def text(char)
@cache[:text][char] ||= if grid == @grids[char.to_sym]
o = grid_def(grid).map { |e| e == 0 ? ' ' : '*' } # 0 -> space, 1 -> *
o.each_slice(@width).to_a.flat_map { |e| e.join + $/ }.join
end
end
def text_word(word)
chars = []
word.split('').each { |char| chars << text(char).split($/) }
chars.transpose.map { |e| e.join(' ') } # join letters with space
end
def text_grids(word_width = 80)
grids_per_line = (word_width + 1) / (@width + 1)
@grids.keys.each_slice(grids_per_line).map { |w| text_word(w.join) << $/ }
end
def dcled(char)
@cache[:dcled][char] ||= if grid = @grids[char.to_sym]
o = grid_def(grid).map { |e| (e + 1) % 2 } # flip bits
[[1] * 8] + o.each_slice(@width).to_a.transpose.map { |e| e << 1 }
end
end
def dcled_hash(char)
h = {}
if dcled_o = dcled(char)
dcled_o.each_with_index { |k, i| h[i + 1] = k }
end
h
end
private
def build(chars)
assembled = {}
aliases = {}
chars.each do |k, v|
if v.length == 1
aliases[k] = v # skip aliases until rest assembled
else
assembled[k.to_sym] = v.join.tr('.', '0').tr('*', '1').to_i(2)
end
end
aliases.each do |k, v| # assemble aliases, following redirects
assembled[k.to_sym] = assembled[v[0].to_sym]
end
assembled
end
def grid_def(grid)
("%0#{@dots}b" % grid).split('').map(&:to_i) # to binary array of chars
end
end