| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324 |
- # Blender addon to export an object as a lib.rs/chair mesh file
- # Based on the Raw mesh exporter distributed with blender
- bl_info = {
- "name": "Chair Mesh Exporter",
- "author": "deltanedas",
- "blender": (3, 0, 0),
- "location": "File > Import-Export > Chair Mesh (.chr)",
- # Same as the crate version
- "version": (0, 1, 3),
- "category": "Import-Export"
- }
- # For normal lookup
- import math
- # For writing floats
- import struct
- def face_to_tris(face, mesh, matrix, vertices, vertex_ids, indices):
- uvs = mesh.uv_layers.active.data
- for n in range(3):
- verti = face.vertices[n]
- loopi = face.loops[n]
- vert = mesh.vertices[verti]
- loop = mesh.loops[loopi]
- v = [(matrix @ vert.co)[:], (loop.normal)[:], (uvs[loopi].uv)[:]]
- # really inefficient but this is pyton so
- key = str(v)
- if key in vertex_ids:
- i = vertex_ids[key]
- else:
- # new vertex, push to list
- i = len(vertices)
- vertices.append(v)
- vertex_ids[key] = i
- indices.append(i)
- def process_scene(context, apply_modifiers):
- objects = []
- indices = []
- scene = context.scene
- for obj in context.selected_objects:
- me = None
- if apply_modifiers or obj.type != "MESH":
- try:
- me = obj.to_mesh()
- except:
- me = None
- is_tmp_mesh = True
- else:
- me = obj.data
- is_tmp_mesh = False
- if me is None:
- continue
- if not me.loop_triangles and me.polygons:
- me.calc_loop_triangles()
- # TODO: texture used by this object
- vertices = []
- vertex_ids = {}
- matrix = obj.matrix_world.copy()
- for face in me.loop_triangles:
- face_to_tris(face, me, matrix, vertices, vertex_ids, indices)
- min_pos = [
- min(vertices, key=lambda v: v[0][0])[0][0],
- min(vertices, key=lambda v: v[0][1])[0][1],
- min(vertices, key=lambda v: v[0][2])[0][2]
- ]
- max_pos = [
- max(vertices, key=lambda v: v[0][0])[0][0],
- max(vertices, key=lambda v: v[0][1])[0][1],
- max(vertices, key=lambda v: v[0][2])[0][2]
- ]
- scale = [
- max_pos[0] - min_pos[0],
- max_pos[1] - min_pos[1],
- max_pos[2] - min_pos[2]
- ]
- objects.append((vertices, scale, min_pos))
- # Remove meshes that are created solely for exporting
- if is_tmp_mesh:
- obj.to_mesh_clear()
- return objects, indices
- def index_size(vertices):
- if vertices < 256:
- return 1
- if vertices < 65536:
- return 2
- return 4
- def write_vec2_float(f, v):
- f.write(bytes(struct.pack("<f", v[0])))
- f.write(bytes(struct.pack("<f", 1.0 - v[1])))
- def write_vec2_byte(f, v):
- x = v[0]
- y = v[1]
- while x < 0.0:
- x += 1.0
- while y < 0.0:
- y += 1.0
- while x > 1.0:
- x -= 1.0
- while y > 1.0:
- y -= 1.0
- x = int(x * 128)
- # flip y axis
- y = 128 - int(y * 128)
- f.write(bytes([x, y]))
- def write_vec3_float(f, v):
- # <f = little-endian float
- f.write(bytes(struct.pack("<f", v[0])))
- # Y = up in chair/wgpu, Z = up in blender so swap them
- f.write(bytes(struct.pack("<f", v[2])))
- f.write(bytes(struct.pack("<f", v[1])))
- def write_vec3_byte(f, v, scale, offset):
- # use range 0-128 to allow for even divisions
- x = 128 * (v[0] - offset[0]) / scale[0]
- # Y = up in chair/wgpu, Z = up in blender so swap them
- y = 128 * (v[2] - offset[2]) / scale[2]
- z = 128 * (v[1] - offset[1]) / scale[1]
- f.write(bytes([int(x), int(y), int(z)]))
- def index_normal(n):
- # asin fairly slow but this is pyton so doesnt matter
- return 128 + int(math.asin(n) * 255 / math.pi)
- def write_vec3_sin(f, v):
- x = index_normal(v[0])
- # Y = up in chair/wgpu, Z = up in blender so swap them
- y = index_normal(v[2])
- z = index_normal(v[1])
- f.write(bytes([x, y, z]))
- def write_model(path, objects, indices, export_colours, export_normals, export_uvs, export_skeleton, short_pos, short_normals, short_uvs, short_weights):
- f = open(path, "wb")
- # Chair file header
- f.write(bytes("CHAIR", "ascii"))
- # Format version
- f.write(bytes([0]))
- # MeshFeatures
- features = 0
- if export_colours:
- features |= 0b0001
- if export_normals:
- features |= 0b0010
- if export_uvs:
- features |= 0b0100
- if export_skeleton:
- features |= 0b1000
- if short_pos:
- features |= 0b00010000
- if short_normals:
- features |= 0b00100000
- if short_uvs:
- features |= 0b01000000
- if short_weights:
- features |= 0b10000000
- f.write(bytes([features]))
- # TODO: export unique vertex colours from objects
- if export_colours:
- f.write((1).to_bytes(2, "little"))
- f.write(bytes([255, 255, 255, 255]))
- if 1 > 255:
- colour_size = 2
- else:
- colour_size = 1
- # TODO: export texture names
- if export_uvs:
- f.write(bytes([1, 5]))
- f.write(bytes("chair", "ascii"))
- # TODO: export skeleton
- f.write(bytes([len(objects)]))
- for obj in objects:
- # Vertices count for this object
- f.write(len(obj[0]).to_bytes(4, "little"))
- scale = obj[1]
- offset = obj[2]
- if short_pos:
- write_vec3_float(f, scale)
- write_vec3_float(f, offset)
- write_pos = lambda f, v: write_vec3_byte(f, v, scale, offset)
- else:
- write_pos = write_vec3_float
- if short_normals:
- write_normals = write_vec3_sin
- else:
- write_normals = write_vec3_float
- if export_uvs:
- # TODO: actual texture index
- f.write((0).to_bytes(colour_size, "little"))
- if short_uvs:
- write_uvs = write_vec2_byte
- else:
- write_uvs = write_vec2_float
- # Write data
- for v in obj[0]:
- write_pos(f, v[0])
- if export_colours:
- # TODO: colour index
- f.write(bytes([0]))
- if export_normals:
- write_normals(f, v[1])
- if export_uvs:
- write_uvs(f, v[2])
- # TODO: bone weights
- # Indices
- f.write(len(indices).to_bytes(4, "little"))
- indsize = index_size(sum([len(obj[0]) for obj in objects]))
- for i in indices:
- f.write(i.to_bytes(indsize, "little"))
- f.close()
- return
- import bpy
- from bpy_extras.io_utils import ExportHelper
- from bpy.props import StringProperty, BoolProperty
- from bpy.types import Operator
- class ModelExporter(Operator, ExportHelper):
- """Export geometry to chair mesh format (lib.rs/chair)"""
- bl_idname = "export.chair"
- bl_label = "Export Chair Mesh"
- filename_ext = ".chr"
- filter_glob: StringProperty(
- default = "*.chr",
- options = {"HIDDEN"}
- )
- apply_modifiers: BoolProperty(
- name = "Apply Modifiers",
- description = "Use transformed mesh data from each object",
- default = True
- )
- export_colours: BoolProperty(
- name = "Export Colours",
- description = "Save vertex colours in the exported mesh",
- default = False
- )
- export_normals: BoolProperty(
- name = "Export Normals",
- description = "Save vertex normals in the exported mesh",
- default = True
- )
- export_uvs: BoolProperty(
- name = "Export UVs",
- description = "Save vertex texture coordinates (and texture names) in the exported mesh",
- default = True
- )
- export_skeleton: BoolProperty(
- name = "Export Skeleton",
- description = "Save skeleton and vertex bones/weights in the exported mesh",
- default = False
- )
- short_pos: BoolProperty(
- name = "Short Positions",
- description = "Use bytes -64 to +64 instead of floats to lossily encode vertex positions.\nAlso stores scale + offset of objects",
- default = False
- )
- short_normals: BoolProperty(
- name = "Short Normals",
- description = "Use a byte sin lookup table instead of floats to lossily encode vertex normals",
- default = False
- )
- short_uvs: BoolProperty(
- name = "Short UVs",
- description = "Use bytes 0 to 128 instead of floats to lossily encode vertex texture coordinates",
- default = False
- )
- short_weights: BoolProperty(
- name = "Short Weights",
- description = "Use bytes -64 to +64 instead of floats to lossily encode vertex weights",
- default = False
- )
- def execute(self, context):
- objects, indices = process_scene(context, self.apply_modifiers)
- write_model(self.filepath, objects, indices, self.export_colours, self.export_normals, self.export_uvs, self.export_skeleton,
- self.short_pos, self.short_normals, self.short_uvs, self.short_weights)
- return {"FINISHED"}
- def menu_export(self, context):
- self.layout.operator(ModelExporter.bl_idname, text = "Chair Mesh (.chr)")
- def register():
- bpy.utils.register_class(ModelExporter)
- bpy.types.TOPBAR_MT_file_export.append(menu_export)
- def unregister():
- bpy.utils.unregister_class(ModelExporter)
- bpy.types.TOPBAR_MT_file_export.remove(menu_export)
- if __name__ == "__main__":
- register()
|