chair_exporter.py 9.6 KB

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