blender_icons_geom.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # Apache License, Version 2.0
  2. """
  3. Example Usage
  4. =============
  5. Command line::
  6. ./blender.bin \
  7. icon_file.blend --background --python ./release/datafiles/blender_icons_geom.py -- \
  8. --output-dir=./release/datafiles/blender_icons_geom
  9. Icon Format
  10. ===========
  11. This is a simple binary format (all bytes, so no endian).
  12. The header is 8 bytes:
  13. :0..3: ``VCO``: identifier.
  14. :4: ``0``: icon file version.
  15. :5: icon size-x.
  16. :6: icon size-y.
  17. :7: icon start-x.
  18. :8: icon start-y.
  19. Icon width and height are for icons that don't use the full byte range
  20. (so we don't get bad alignment for 48 pixel grid for eg).
  21. Start values are currently unused.
  22. After the header, the remaining length of the data defines the geometry size.
  23. :6 bytes each: triangle (XY) locations.
  24. :12 bytes each: triangle (RGBA) locations.
  25. All coordinates are written, then all colors.
  26. Since this is a binary format which isn't intended for general use
  27. the ``.dat`` file extension should be used.
  28. """
  29. # This script writes out geometry-icons.
  30. import bpy
  31. # Generic functions
  32. def area_tri_signed_2x_v2(v1, v2, v3):
  33. return (v1[0] - v2[0]) * (v2[1] - v3[1]) + (v1[1] - v2[1]) * (v3[0] - v2[0])
  34. class TriMesh:
  35. """
  36. Triangulate, may apply other changes here too.
  37. """
  38. __slots__ = ("object", "mesh")
  39. def __init__(self, ob):
  40. self.object = ob
  41. self.mesh = None
  42. def __enter__(self):
  43. self.mesh = self._tri_copy_from_object(self.object)
  44. return self.mesh
  45. def __exit__(self, *args):
  46. bpy.data.meshes.remove(self.mesh)
  47. @staticmethod
  48. def _tri_copy_from_object(ob):
  49. import bmesh
  50. assert(ob.type == 'MESH')
  51. bm = bmesh.new()
  52. bm.from_mesh(ob.data)
  53. bmesh.ops.triangulate(bm, faces=bm.faces)
  54. me = bpy.data.meshes.new(ob.name + ".copy")
  55. bm.to_mesh(me)
  56. bm.free()
  57. return me
  58. def object_material_colors(ob):
  59. material_colors = []
  60. color_default = (1.0, 1.0, 1.0, 1.0)
  61. for slot in ob.material_slots:
  62. material = slot.material
  63. color = color_default
  64. if material is not None and material.use_nodes:
  65. node_tree = material.node_tree
  66. if node_tree is not None:
  67. color = next((
  68. node.outputs[0].default_value[:]
  69. for node in node_tree.nodes
  70. if node.type == 'RGB'
  71. ), color_default)
  72. if min(color) < 0.0 or max(color) > 1.0:
  73. print(f"Material: {material.name!r} has color out of 0..1 range {color!r}")
  74. color = tuple(max(min(c, 1.0), 0.0) for c in color)
  75. material_colors.append(color)
  76. return material_colors
  77. def object_child_map(objects):
  78. objects_children = {}
  79. for ob in objects:
  80. ob_parent = ob.parent
  81. # Get the root.
  82. if ob_parent is not None:
  83. while ob_parent and ob_parent.parent:
  84. ob_parent = ob_parent.parent
  85. if ob_parent is not None:
  86. objects_children.setdefault(ob_parent, []).append(ob)
  87. for ob_all in objects_children.values():
  88. ob_all.sort(key=lambda ob: ob.name)
  89. return objects_children
  90. def mesh_data_lists_from_mesh(me, material_colors):
  91. me_loops = me.loops[:]
  92. me_loops_color = me.vertex_colors.active.data[:]
  93. me_verts = me.vertices[:]
  94. me_polys = me.polygons[:]
  95. tris_data = []
  96. for p in me_polys:
  97. # Note, all faces are handled, backfacing/zero area is checked just before writing.
  98. material_index = p.material_index
  99. if material_index < len(material_colors):
  100. base_color = material_colors[p.material_index]
  101. else:
  102. base_color = (1.0, 1.0, 1.0, 1.0)
  103. l_sta = p.loop_start
  104. l_len = p.loop_total
  105. loops_poly = me_loops[l_sta:l_sta + l_len]
  106. color_poly = me_loops_color[l_sta:l_sta + l_len]
  107. i0 = 0
  108. i1 = 1
  109. # we only write tris now
  110. assert(len(loops_poly) == 3)
  111. for i2 in range(2, l_len):
  112. l0 = loops_poly[i0]
  113. l1 = loops_poly[i1]
  114. l2 = loops_poly[i2]
  115. c0 = color_poly[i0]
  116. c1 = color_poly[i1]
  117. c2 = color_poly[i2]
  118. v0 = me_verts[l0.vertex_index]
  119. v1 = me_verts[l1.vertex_index]
  120. v2 = me_verts[l2.vertex_index]
  121. tris_data.append((
  122. # float depth
  123. p.center.z,
  124. # XY coords.
  125. (
  126. v0.co.xy[:],
  127. v1.co.xy[:],
  128. v2.co.xy[:],
  129. ),
  130. # RGBA color.
  131. tuple((
  132. [int(c * b * 255) for c, b in zip(cn.color, base_color)]
  133. for cn in (c0, c1, c2)
  134. )),
  135. ))
  136. i1 = i2
  137. return tris_data
  138. def mesh_data_lists_from_objects(ob_parent, ob_children):
  139. tris_data = []
  140. has_parent = False
  141. if ob_children:
  142. parent_matrix = ob_parent.matrix_world.copy()
  143. parent_matrix_inverted = parent_matrix.inverted()
  144. for ob in (ob_parent, *ob_children):
  145. with TriMesh(ob) as me:
  146. if has_parent:
  147. me.transform(parent_matrix_inverted @ ob.matrix_world)
  148. tris_data.extend(
  149. mesh_data_lists_from_mesh(
  150. me,
  151. object_material_colors(ob),
  152. )
  153. )
  154. has_parent = True
  155. return tris_data
  156. def write_mesh_to_py(fh, ob, ob_children):
  157. def float_as_byte(f, axis_range):
  158. assert(axis_range <= 255)
  159. # -1..1 -> 0..255
  160. f = (f + 1.0) * 0.5
  161. f = int(round(f * axis_range))
  162. return min(max(f, 0), axis_range)
  163. def vert_as_byte_pair(v):
  164. return (
  165. float_as_byte(v[0], coords_range_align[0]),
  166. float_as_byte(v[1], coords_range_align[1]),
  167. )
  168. tris_data = mesh_data_lists_from_objects(ob, ob_children)
  169. # 100 levels of Z depth, round to avoid differences from precision error
  170. # causing different computers to write triangles in more or less random order.
  171. tris_data.sort(key=lambda data: int(data[0] * 100))
  172. if 0:
  173. # make as large as we can, keeping alignment
  174. def size_scale_up(size):
  175. assert(size != 0)
  176. while size * 2 <= 255:
  177. size *= 2
  178. return size
  179. coords_range = (
  180. size_scale_up(ob.get("size_x")) or 255,
  181. size_scale_up(ob.get("size_y")) or 255,
  182. )
  183. else:
  184. # disable for now
  185. coords_range = 255, 255
  186. # Pixel size needs to be increased since a pixel needs one extra geom coordinate,
  187. # if we're writing 32 pixel, align verts to 33.
  188. coords_range_align = tuple(min(c + 1, 255) for c in coords_range)
  189. print("Writing:", fh.name, coords_range)
  190. fw = fh.write
  191. # Header (version 0).
  192. fw(b'VCO\x00')
  193. # Width, Height
  194. fw(bytes(coords_range))
  195. # X, Y
  196. fw(bytes((0, 0)))
  197. # Once converted into bytes, the triangle might become zero area
  198. tri_skip = [False] * len(tris_data)
  199. for i, (_, tri_coords, _) in enumerate(tris_data):
  200. tri_coords_as_byte = [vert_as_byte_pair(vert) for vert in tri_coords]
  201. if area_tri_signed_2x_v2(*tri_coords_as_byte) <= 0:
  202. tri_skip[i] = True
  203. continue
  204. for vert_byte in tri_coords_as_byte:
  205. fw(bytes(vert_byte))
  206. for i, (_, _, tri_color) in enumerate(tris_data):
  207. if tri_skip[i]:
  208. continue
  209. for color in tri_color:
  210. fw(bytes(color))
  211. def create_argparse():
  212. import argparse
  213. parser = argparse.ArgumentParser()
  214. parser.add_argument(
  215. "--output-dir",
  216. dest="output_dir",
  217. default=".",
  218. type=str,
  219. metavar="DIR",
  220. required=False,
  221. help="Directory to write icons to.",
  222. )
  223. parser.add_argument(
  224. "--group",
  225. dest="group",
  226. default="",
  227. type=str,
  228. metavar="GROUP",
  229. required=False,
  230. help="Group name to export from (otherwise export all objects).",
  231. )
  232. return parser
  233. def main():
  234. import os
  235. import sys
  236. parser = create_argparse()
  237. if "--" in sys.argv:
  238. argv = sys.argv[sys.argv.index("--") + 1:]
  239. else:
  240. argv = []
  241. args = parser.parse_args(argv)
  242. objects = []
  243. if args.group:
  244. group = bpy.data.collections.get(args.group)
  245. if group is None:
  246. print(f"Group {args.group!r} not found!")
  247. return
  248. objects_source = group.objects
  249. del group
  250. else:
  251. objects_source = bpy.data.objects
  252. for ob in objects_source:
  253. # Skip non-mesh objects
  254. if ob.type != 'MESH':
  255. continue
  256. name = ob.name
  257. # Skip copies of objects
  258. if name.rpartition(".")[2].isdigit():
  259. continue
  260. if not ob.data.vertex_colors:
  261. print("Skipping:", name, "(no vertex colors)")
  262. continue
  263. objects.append((name, ob))
  264. objects.sort(key=lambda a: a[0])
  265. objects_children = object_child_map(bpy.data.objects)
  266. for name, ob in objects:
  267. if ob.parent:
  268. continue
  269. filename = os.path.join(args.output_dir, name + ".dat")
  270. with open(filename, 'wb') as fh:
  271. write_mesh_to_py(fh, ob, objects_children.get(ob, []))
  272. if __name__ == "__main__":
  273. main()