forked from hlorus/CAD_Sketcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icon_manager.py
97 lines (69 loc) · 2.5 KB
/
icon_manager.py
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
from pathlib import Path
import gpu
from gpu_extras.batch import batch_for_shader
from bpy.app import background
from .shaders import Shaders
icons = {}
def coords_from_icon(data, range_x=255, range_y=255):
length = len(data)
# Take the 1st third of the data
geometry_data = data[: length // 3]
# Cut geometry_data into chunks of 6 bytes
tris = [geometry_data[i * 6 : (i + 1) * 6] for i in range(len(geometry_data) // 6)]
coords = []
indices = []
for i, tri in enumerate(tris):
v1 = tri[0:2]
# split the 6 Byte chunk into 2 Byte chunks
# Each 2 Byte chunk represent the xy coordinates
# of triangles to render for the icon
verts = [tri[i * 2 : (i + 1) * 2] for i in range(3)]
indices.append([])
for v in verts:
x = (int.from_bytes(v[0], "little") / range_x) - 0.5
y = (int.from_bytes(v[1], "little") / range_y) - 0.5
co = (x, y)
if co not in coords:
coords.append(co)
index = len(coords) - 1
else:
index = coords.index(co)
indices[i].append(index)
return coords, indices
def read_icon(fp):
data = []
name = fp.stem
with open(fp, "rb") as icon:
identifier = icon.read(3)
_version, size_x, size_y, _start_x, _start_y = icon.read(5)
while True:
val = icon.read(1)
if not val:
break
data.append(val)
coords, indices = coords_from_icon(data, range_x=size_x, range_y=size_y)
batch = batch_from_coords(coords, indices)
icons[name] = batch
def batch_from_coords(coords, indices):
shader = Shaders.uniform_color_2d()
return batch_for_shader(shader, "TRIS", {"pos": coords}, indices=indices)
def load():
if background:
return
# Read icons from filepath and store as python data(batch?) for easy access
filepath = Path(Path(__file__).parent, "ressources/icons")
for icon in filepath.iterdir():
read_icon(icon)
def draw(id, color):
batch = icons.get(id)
if not batch:
batch = icons.get("none")
if not batch:
print('Icon with name: "{}" not found!'.format(id))
return
gpu.state.blend_set("ALPHA")
shader = Shaders.uniform_color_2d()
shader.bind()
shader.uniform_float("color", color)
batch.draw(shader)
gpu.state.blend_set("NONE")