chair_exporter.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # Blender addon to export an object as a lib.rs/chair mesh file
  2. # Based on the Raw mesh exporter distributed with blender
  3. bl_info = {
  4. "name": "Chair Mesh Exporter",
  5. "author": "deltanedas",
  6. "blender": (3, 0, 0),
  7. "location": "File > Import-Export > Chair Mesh (.chr)",
  8. # Same as the crate version
  9. "version": (0, 1, 1),
  10. "category": "Import-Export"
  11. }
  12. # For normal lookup
  13. import math
  14. # For writing floats
  15. import struct
  16. def face_to_tris(face, mesh, matrix, vertices, vertex_ids, indices):
  17. uvs = mesh.uv_layers.active.data
  18. for n in range(3):
  19. verti = face.vertices[n]
  20. loopi = face.loops[n]
  21. vert = mesh.vertices[verti]
  22. loop = mesh.loops[loopi]
  23. v = [(matrix @ vert.co)[:], (loop.normal)[:], (uvs[loopi].uv)[:]]
  24. # really inefficient but this is pyton so
  25. key = str(v)
  26. if key in vertex_ids:
  27. i = vertex_ids[key]
  28. else:
  29. # new vertex, push to list
  30. i = len(vertices)
  31. vertices.append(v)
  32. vertex_ids[key] = i
  33. indices.append(i)
  34. def process_scene(context, apply_modifiers):
  35. objects = []
  36. indices = []
  37. scene = context.scene
  38. for obj in context.selected_objects:
  39. me = None
  40. if apply_modifiers or obj.type != "MESH":
  41. try:
  42. me = obj.to_mesh()
  43. except:
  44. me = None
  45. is_tmp_mesh = True
  46. else:
  47. me = obj.data
  48. is_tmp_mesh = False
  49. if me is None:
  50. continue
  51. if not me.loop_triangles and me.polygons:
  52. me.calc_loop_triangles()
  53. # TODO: texture used by this object
  54. vertices = []
  55. vertex_ids = {}
  56. matrix = obj.matrix_world.copy()
  57. for face in me.loop_triangles:
  58. face_to_tris(face, me, matrix, vertices, vertex_ids, indices)
  59. min_pos = [
  60. min(vertices, key=lambda v: v[0][0])[0][0],
  61. min(vertices, key=lambda v: v[0][1])[0][1],
  62. min(vertices, key=lambda v: v[0][2])[0][2]
  63. ]
  64. max_pos = [
  65. max(vertices, key=lambda v: v[0][0])[0][0],
  66. max(vertices, key=lambda v: v[0][1])[0][1],
  67. max(vertices, key=lambda v: v[0][2])[0][2]
  68. ]
  69. scale = [
  70. max_pos[0] - min_pos[0],
  71. max_pos[1] - min_pos[1],
  72. max_pos[2] - min_pos[2]
  73. ]
  74. objects.append((vertices, scale, min_pos))
  75. # Remove meshes that are created solely for exporting
  76. if is_tmp_mesh:
  77. obj.to_mesh_clear()
  78. return objects, indices
  79. def index_size(vertices):
  80. if vertices < 256:
  81. return 1
  82. if vertices < 65536:
  83. return 2
  84. return 4
  85. def write_vec2_float(f, v):
  86. f.write(bytes(struct.pack("<f", v[0])))
  87. f.write(bytes(struct.pack("<f", 1.0 - v[1])))
  88. def write_vec2_byte(f, v):
  89. x = v[0]
  90. y = v[1]
  91. while x < 0.0:
  92. x += 1.0
  93. while y < 0.0:
  94. y += 1.0
  95. while x > 1.0:
  96. x -= 1.0
  97. while y > 1.0:
  98. y -= 1.0
  99. x = int(x * 128)
  100. # flip y axis
  101. y = 128 - int(y * 128)
  102. f.write(bytes([x, y]))
  103. def write_vec3_float(f, v):
  104. # <f = little-endian float
  105. f.write(bytes(struct.pack("<f", v[0])))
  106. # Y = up in chair/wgpu, Z = up in blender so swap them
  107. f.write(bytes(struct.pack("<f", v[2])))
  108. f.write(bytes(struct.pack("<f", v[1])))
  109. def write_vec3_byte(f, v, scale, offset):
  110. # use range 0-128 to allow for even divisions
  111. x = 128 * (v[0] - offset[0]) / scale[0]
  112. # Y = up in chair/wgpu, Z = up in blender so swap them
  113. y = 128 * (v[2] - offset[2]) / scale[2]
  114. z = 128 * (v[1] - offset[1]) / scale[1]
  115. f.write(bytes([int(x), int(y), int(z)]))
  116. def index_normal(n):
  117. # asin fairly slow but this is pyton so doesnt matter
  118. return 128 + int(math.asin(n) * 255 / math.pi)
  119. def write_vec3_sin(f, v):
  120. x = index_normal(v[0])
  121. # Y = up in chair/wgpu, Z = up in blender so swap them
  122. y = index_normal(v[2])
  123. z = index_normal(v[1])
  124. f.write(bytes([x, y, z]))
  125. def write_model(path, objects, indices, export_colours, export_normals, export_uvs, export_skeleton, short_pos, short_normals, short_uvs, short_weights):
  126. f = open(path, "wb")
  127. # Chair file header
  128. f.write(bytes("CHAIR", "ascii"))
  129. # Format version
  130. f.write(bytes([0]))
  131. # MeshFeatures
  132. features = 0
  133. if export_colours:
  134. features |= 0b0001
  135. if export_normals:
  136. features |= 0b0010
  137. if export_uvs:
  138. features |= 0b0100
  139. if export_skeleton:
  140. features |= 0b1000
  141. if short_pos:
  142. features |= 0b00010000
  143. if short_normals:
  144. features |= 0b00100000
  145. if short_uvs:
  146. features |= 0b01000000
  147. if short_weights:
  148. features |= 0b10000000
  149. f.write(bytes([features]))
  150. # TODO: export unique vertex colours from objects
  151. if export_colours:
  152. f.write((1).to_bytes(2, "little"))
  153. f.write(bytes([255, 255, 255, 255]))
  154. # TODO: export texture names
  155. if export_uvs:
  156. f.write(bytes([1, 5]))
  157. f.write(bytes("chair", "ascii"))
  158. # TODO: export skeleton
  159. f.write(bytes([len(objects)]))
  160. for obj in objects:
  161. # Vertices count for this object
  162. f.write(len(obj[0]).to_bytes(4, "little"))
  163. scale = obj[1]
  164. offset = obj[2]
  165. if short_pos:
  166. write_vec3_float(f, scale)
  167. write_vec3_float(f, offset)
  168. write_pos = lambda f, v: write_vec3_byte(f, v, scale, offset)
  169. else:
  170. write_pos = write_vec3_float
  171. if short_normals:
  172. write_normals = write_vec3_sin
  173. else:
  174. write_normals = write_vec3_float
  175. if export_uvs:
  176. # TODO: actual texture index
  177. f.write(bytes([0]))
  178. if short_uvs:
  179. write_uvs = write_vec2_byte
  180. else:
  181. write_uvs = write_vec2_float
  182. # TODO: texture name index
  183. # Write data
  184. for v in obj[0]:
  185. write_pos(f, v[0])
  186. if export_colours:
  187. # TODO: colour index
  188. f.write(bytes([0]))
  189. if export_normals:
  190. write_normals(f, v[1])
  191. if export_uvs:
  192. write_uvs(f, v[2])
  193. # TODO: bone weights
  194. # Indices
  195. f.write(len(indices).to_bytes(4, "little"))
  196. indsize = index_size(sum([len(obj[0]) for obj in objects]))
  197. for i in indices:
  198. f.write(i.to_bytes(indsize, "little"))
  199. f.close()
  200. return
  201. import bpy
  202. from bpy_extras.io_utils import ExportHelper
  203. from bpy.props import StringProperty, BoolProperty
  204. from bpy.types import Operator
  205. class ModelExporter(Operator, ExportHelper):
  206. """Export geometry to chair mesh format (lib.rs/chair)"""
  207. bl_idname = "export.chair"
  208. bl_label = "Export Chair Mesh"
  209. filename_ext = ".chr"
  210. filter_glob: StringProperty(
  211. default = "*.chr",
  212. options = {"HIDDEN"}
  213. )
  214. apply_modifiers: BoolProperty(
  215. name = "Apply Modifiers",
  216. description = "Use transformed mesh data from each object",
  217. default = True
  218. )
  219. export_colours: BoolProperty(
  220. name = "Export Colours",
  221. description = "Save vertex colours in the exported mesh",
  222. default = False
  223. )
  224. export_normals: BoolProperty(
  225. name = "Export Normals",
  226. description = "Save vertex normals in the exported mesh",
  227. default = True
  228. )
  229. export_uvs: BoolProperty(
  230. name = "Export UVs",
  231. description = "Save vertex texture coordinates (and texture names) in the exported mesh",
  232. default = True
  233. )
  234. export_skeleton: BoolProperty(
  235. name = "Export Skeleton",
  236. description = "Save skeleton and vertex bones/weights in the exported mesh",
  237. default = False
  238. )
  239. short_pos: BoolProperty(
  240. name = "Short Positions",
  241. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex positions.\nAlso stores scale + offset of objects",
  242. default = False
  243. )
  244. short_normals: BoolProperty(
  245. name = "Short Normals",
  246. description = "Use a byte sin lookup table instead of floats to lossily encode vertex normals",
  247. default = False
  248. )
  249. short_uvs: BoolProperty(
  250. name = "Short UVs",
  251. description = "Use bytes 0 to 128 instead of floats to lossily encode vertex texture coordinates",
  252. default = False
  253. )
  254. short_weights: BoolProperty(
  255. name = "Short Weights",
  256. description = "Use bytes -64 to +64 instead of floats to lossily encode vertex weights",
  257. default = False
  258. )
  259. def execute(self, context):
  260. objects, indices = process_scene(context, self.apply_modifiers)
  261. write_model(self.filepath, objects, indices, self.export_colours, self.export_normals, self.export_uvs, self.export_skeleton,
  262. self.short_pos, self.short_normals, self.short_uvs, self.short_weights)
  263. return {"FINISHED"}
  264. def menu_export(self, context):
  265. self.layout.operator(ModelExporter.bl_idname, text = "Chair Mesh (.chr)")
  266. def register():
  267. bpy.utils.register_class(ModelExporter)
  268. bpy.types.TOPBAR_MT_file_export.append(menu_export)
  269. def unregister():
  270. bpy.utils.unregister_class(ModelExporter)
  271. bpy.types.TOPBAR_MT_file_export.remove(menu_export)
  272. if __name__ == "__main__":
  273. register()