-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotter.py
More file actions
269 lines (227 loc) · 11.1 KB
/
Copy pathplotter.py
File metadata and controls
269 lines (227 loc) · 11.1 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
'''
Turn a config file to a 2-D array of pixels with colors, which can be visualized by rendering or plotting later.
'''
import json
from essentials import *
class elements:
def __init__(self, config: dict, default_color: str | tuple[int, int, int] | None = None):
'''
Translate a config to a text element
'''
if not isinstance(config, dict): raise TypeError("Config is not dictionary.")
# Read config
# Read and check text
self.text = config.get("value")
if not isinstance(self.text, str): raise TypeError("Text will be plotted is not in str format or not given.")
if self.text == "": raise ValueError("Text is empty.")
# Read and check font name
self.font_name = config.get("font") or None
if not isinstance(self.font_name, str): raise KeyError(f"Font name is not in str format or not given. (Occured when plotting {self.text})")
if self.font_name not in get_font_list(): raise ValueError(f"Font {self.font_name} not found. (Occured when plotting {self.text})")
# Read font
with open(f'{FONT_DIR}/{self.font_name}.json', 'r') as file:
font = json.load(file)
# Read type, colour, distance and caps setting
self.type = bool(font.get("is_symbol") or False) # True is symbol, False is text
if self.type: self.text=[(self.text)]
self.color = (normalize_color(default_color),
normalize_color(config.get("color") or None))
# char_dist and space_dist can be empty to use data provided from the font
self.char_dist = config.get("char_dist")
if not isinstance(self.char_dist, int): self.char_dist = font.get("char_dist")
self.space_dist = config.get("space_dist")
if not isinstance(self.space_dist, int): self.space_dist = font.get("space_dist")
self.force_caps = config.get("force_caps",True)
if not isinstance(self.char_dist , int) and len(self.text) > 1: raise KeyError(f"Distance between characters is invalid. (Occured when plotting {self.text})")
if not isinstance(self.space_dist, int) and " " in list(self.text): raise KeyError(f"Space span between characters is invalid. (Occured when plotting {self.text})")
self.offset_x = config.get("offset_x") or 0
self.offset_y = config.get("offset_y") or 0
for _ in (self.offset_x, self.offset_y):
if not isinstance(_, int): raise TypeError(f"Offset parameter must be integer. (Occured when plotting {self.text})")
def plot(self):
'''
Plot text
'''
with open(f'{FONT_DIR}/{self.font_name}.json', 'r') as file:
font = json.load(file)
mask_height = font.get("height")
char_lib = font.get("character")
if mask_height == None: raise KeyError(f"Character height of {self.font_name} not found.")
mask_width = 0
mask=[[] for _ in range(mask_height)]
is_first_digit=True
# Plot text
for char in self.text:
# Space
if char==" ":
for row in range(mask_height): mask[row] += [self.color[0]] * (self.space_dist - self.char_dist)
mask_width += self.space_dist - self.char_dist
continue
# Retrieve character list
if not self.type:
if self.force_caps: char = char.upper()
char_matrix = char_lib.get(char)
if char_matrix == None: raise KeyError(f"{self.font_name} does not have key {char}")
# Fill
shape = char_matrix.get("shape")
char_width = char_matrix.get("width") or len(shape[0])
ret = [[self.color[shape[row][col]]
for col in range(char_width)]
for row in range(mask_height)]
# Add to mask
if not is_first_digit:
mask_width += self.char_dist
mask_width += char_width
for row in range(mask_height):
if not is_first_digit:
mask[row]+=[self.color[0]]*self.char_dist
mask[row]+=ret[row]
if is_first_digit: is_first_digit=False
return mask, mask_height, mask_width
class components:
def __init__(self, config: dict, default_color):
self.align_type = config.get("align_type")
raw_elements = config.get("elements") or []
self.elements = []
self.default_color = default_color
for element in raw_elements:
try:
cur = elements(element,default_color)
except ValueError as e:
if str(e)=="Text is empty.":
pass
else:
raise
except Exception:
raise
else:
self.elements.append(cur)
def plot(self):
ret = [] # will be resized when first element being plotted
ret_w = 0
ret_h = 0
offset_x = 0
offset_y = 0
is_first = True
curpos_x = 0
curpos_y = 0
for element in self.elements:
mask, mask_height, mask_width = element.plot()
if is_first:
offset_x = element.offset_x
offset_y = element.offset_y
ret = [[] for _ in range(mask_height)]
ret_h = mask_height
else:
curpos_x += element.offset_x
curpos_y = element.offset_y
is_first = False
mask_hdiff = ret_h - mask_height
align_offset = 0
if self.align_type == "middle": curpos_y += mask_hdiff //2
if self.align_type == "bottom": curpos_y += mask_hdiff
# allocate space
if curpos_x<0:
adj = -curpos_x
offset_x -= adj
for i in range(ret_h): ret[i] = [self.default_color for _ in range(adj)] + ret[i]
curpos_x = 0
ret_w += adj
if curpos_y <0:
adj = -curpos_y
offset_y -= adj
ret = [[self.default_color for _ in range(ret_w)] for _ in range(adj)] + ret
curpos_y = 0
ret_h += adj
end_x = curpos_x + mask_width
end_y = curpos_y + mask_height
if end_x >= ret_w:
diff = end_x - ret_w
for i in range(ret_h): ret[i] += [self.default_color for _ in range(diff)]
ret_w = end_x
if end_y >= ret_h:
diff = end_y - ret_h
ret += [[self.default_color for _ in range(ret_w)] for _ in range(diff)]
ret_h = end_y
# Plot
for i in range(mask_height):
ret[i+curpos_y+align_offset] = ret[i+curpos_y+align_offset][:ret_w-mask_width] + mask[i]
curpos_x += mask_width
return ret, offset_x, offset_y
def merge_mask(original_mask: list, new_mask: list, pos_w: int, pos_h: int, default_color: tuple[int,int,int] | None):
''' Override a mask onto portion of another mask
'''
px_count_height=len(original_mask)
px_count_width=len(original_mask[0])
for i in range(len(new_mask)):
if not 0<=pos_h+i<px_count_height: continue
for j in range(len(new_mask[i])):
if not 0<=pos_w+j<px_count_width: continue
if original_mask[pos_h+i][pos_w+j] == default_color:
original_mask[pos_h+i][pos_w+j]=new_mask[i][j]
return original_mask
def plot(config: dict) -> list:
'''Plot the headsign as a matrix of colors accroding to the config'''
# Read config
file_name = config.get("file_name") or "LED.svg"
svg_style = config.get("svg_style")
if not isinstance(svg_style, dict): raise TypeError("Invalid SVG style type")
default_color = normalize_color(svg_style.get("px_default_color") )
dimensions = config.get("dimensions")
if not isinstance(dimensions, dict): raise TypeError("Invalid dimension type")
width_px = dimensions.get("width_px")
height_px = dimensions.get("height_px")
for _ in (width_px, height_px):
if not isinstance(_, int): raise TypeError("Dimension parameter must be integer.")
if _ <= 0: raise ValueError("Dimension parameter must be positive.")
components_left = components(config.get("components_left") or DEFAULT_COMPONENTS, default_color)
components_middle_all = config.get("components_middle") or None
components_middle = components_middle_all.get("middle") or None
if components_middle == None:
components_up = components(components_middle_all.get("up") or DEFAULT_COMPONENTS, default_color)
components_down = components(components_middle_all.get("down") or DEFAULT_COMPONENTS, default_color)
else:
components_middle = components(components_middle_all.get("middle"), default_color)
components_right = components(config.get("components_right") or DEFAULT_COMPONENTS, default_color)
# Initialize headsign
sign = [[default_color for _ in range(width_px)]
for _ in range(height_px)]
# Plot left part
mask, offset_x, offset_y = components_left.plot()
base_x = 0
base_y = 0
sign = merge_mask(sign, mask, base_x + offset_x, base_y + offset_y, default_color)
width_L = max(get_mask_width(mask) + offset_x, 0)
# Plot right part
mask, offset_x, offset_y = components_right.plot()
base_x = width_px - get_mask_width(mask)
base_y = 0
sign = merge_mask(sign, mask, base_x + offset_x, base_y + offset_y, default_color)
width_R = max(get_mask_width(mask) + (-offset_x), 0)
width_mid = width_px - width_L - width_R
mid_px = width_L + width_mid//2
# Plot middle part
if components_middle == None:
# up
mask, offset_x, offset_y = components_up.plot()
base_x = mid_px - get_mask_width(mask) //2
base_y = 0
sign = merge_mask(sign, mask, base_x + offset_x, base_y + offset_y, default_color)
# down
mask, offset_x, offset_y = components_down.plot()
base_x = mid_px - get_mask_width(mask) //2
base_y = height_px - len(mask)
sign = merge_mask(sign, mask, base_x + offset_x, base_y + offset_y, default_color)
else:
mask, offset_x, offset_y = components_middle.plot()
base_x = mid_px - get_mask_width(mask) //2
base_y = (height_px - len(mask)) //2
sign = merge_mask(sign, mask, base_x + offset_x, base_y + offset_y, default_color)
return sign
if __name__=="__main__":
import json
with open("config.json", "r") as f:
config = json.load(f)
from mask_to_svg import plot_svg
mask = plot(config)
plot_svg(mask, config.get("svg_style"))