Sun Position: Fix crash when Blender was started in background
[blender-addons.git] / io_scene_obj / export_obj.py
blobac01570740a91cf07f28f9b35044e6119aadfa8f
1 # SPDX-License-Identifier: GPL-2.0-or-later
3 import os
5 import bpy
6 from mathutils import Matrix, Vector, Color
7 from bpy_extras import io_utils, node_shader_utils
9 from bpy_extras.wm_utils.progress_report import (
10 ProgressReport,
11 ProgressReportSubstep,
15 def name_compat(name):
16 if name is None:
17 return 'None'
18 else:
19 return name.replace(' ', '_')
22 def mesh_triangulate(me):
23 import bmesh
24 bm = bmesh.new()
25 bm.from_mesh(me)
26 bmesh.ops.triangulate(bm, faces=bm.faces)
27 bm.to_mesh(me)
28 bm.free()
31 def write_mtl(scene, filepath, path_mode, copy_set, mtl_dict):
32 source_dir = os.path.dirname(bpy.data.filepath)
33 dest_dir = os.path.dirname(filepath)
35 with open(filepath, "w", encoding="utf8", newline="\n") as f:
36 fw = f.write
38 fw('# Blender MTL File: %r\n' % (os.path.basename(bpy.data.filepath) or "None"))
39 fw('# Material Count: %i\n' % len(mtl_dict))
41 mtl_dict_values = list(mtl_dict.values())
42 mtl_dict_values.sort(key=lambda m: m[0])
44 # Write material/image combinations we have used.
45 # Using mtl_dict.values() directly gives un-predictable order.
46 for mtl_mat_name, mat in mtl_dict_values:
47 # Get the Blender data for the material and the image.
48 # Having an image named None will make a bug, dont do it :)
50 fw('\nnewmtl %s\n' % mtl_mat_name) # Define a new material: matname_imgname
52 mat_wrap = node_shader_utils.PrincipledBSDFWrapper(mat) if mat else None
54 if mat_wrap:
55 use_mirror = mat_wrap.metallic != 0.0
56 use_transparency = mat_wrap.alpha != 1.0
58 # XXX Totally empirical conversion, trying to adapt it
59 # (from 1.0 - 0.0 Principled BSDF range to 0.0 - 1000.0 OBJ specular exponent range):
60 # (1.0 - bsdf_roughness)^2 * 1000
61 spec = (1.0 - mat_wrap.roughness)
62 spec *= spec * 1000
63 fw('Ns %.6f\n' % spec)
65 # Ambient
66 if use_mirror:
67 fw('Ka %.6f %.6f %.6f\n' % (mat_wrap.metallic, mat_wrap.metallic, mat_wrap.metallic))
68 else:
69 fw('Ka %.6f %.6f %.6f\n' % (1.0, 1.0, 1.0))
70 fw('Kd %.6f %.6f %.6f\n' % mat_wrap.base_color[:3]) # Diffuse
71 # XXX TODO Find a way to handle tint and diffuse color, in a consistent way with import...
72 fw('Ks %.6f %.6f %.6f\n' % (mat_wrap.specular, mat_wrap.specular, mat_wrap.specular)) # Specular
73 # Emission, not in original MTL standard but seems pretty common, see T45766.
74 emission_strength = mat_wrap.emission_strength
75 emission = [emission_strength * c for c in mat_wrap.emission_color[:3]]
76 fw('Ke %.6f %.6f %.6f\n' % tuple(emission))
77 fw('Ni %.6f\n' % mat_wrap.ior) # Refraction index
78 fw('d %.6f\n' % mat_wrap.alpha) # Alpha (obj uses 'd' for dissolve)
80 # See http://en.wikipedia.org/wiki/Wavefront_.obj_file for whole list of values...
81 # Note that mapping is rather fuzzy sometimes, trying to do our best here.
82 if mat_wrap.specular == 0:
83 fw('illum 1\n') # no specular.
84 elif use_mirror:
85 if use_transparency:
86 fw('illum 6\n') # Reflection, Transparency, Ray trace
87 else:
88 fw('illum 3\n') # Reflection and Ray trace
89 elif use_transparency:
90 fw('illum 9\n') # 'Glass' transparency and no Ray trace reflection... fuzzy matching, but...
91 else:
92 fw('illum 2\n') # light normally
94 #### And now, the image textures...
95 image_map = {
96 "map_Kd": "base_color_texture",
97 "map_Ka": None, # ambient...
98 "map_Ks": "specular_texture",
99 "map_Ns": "roughness_texture",
100 "map_d": "alpha_texture",
101 "map_Tr": None, # transmission roughness?
102 "map_Bump": "normalmap_texture",
103 "disp": None, # displacement...
104 "refl": "metallic_texture",
105 "map_Ke": "emission_color_texture" if emission_strength != 0.0 else None,
108 for key, mat_wrap_key in sorted(image_map.items()):
109 if mat_wrap_key is None:
110 continue
111 tex_wrap = getattr(mat_wrap, mat_wrap_key, None)
112 if tex_wrap is None:
113 continue
114 image = tex_wrap.image
115 if image is None:
116 continue
118 filepath = io_utils.path_reference(image.filepath, source_dir, dest_dir,
119 path_mode, "", copy_set, image.library)
120 options = []
121 if key == "map_Bump":
122 if mat_wrap.normalmap_strength != 1.0:
123 options.append('-bm %.6f' % mat_wrap.normalmap_strength)
124 if tex_wrap.translation != Vector((0.0, 0.0, 0.0)):
125 options.append('-o %.6f %.6f %.6f' % tex_wrap.translation[:])
126 if tex_wrap.scale != Vector((1.0, 1.0, 1.0)):
127 options.append('-s %.6f %.6f %.6f' % tex_wrap.scale[:])
128 if options:
129 fw('%s %s %s\n' % (key, " ".join(options), repr(filepath)[1:-1]))
130 else:
131 fw('%s %s\n' % (key, repr(filepath)[1:-1]))
133 else:
134 # Write a dummy material here?
135 fw('Ns 500\n')
136 fw('Ka 0.8 0.8 0.8\n')
137 fw('Kd 0.8 0.8 0.8\n')
138 fw('Ks 0.8 0.8 0.8\n')
139 fw('d 1\n') # No alpha
140 fw('illum 2\n') # light normally
143 def test_nurbs_compat(ob):
144 if ob.type != 'CURVE':
145 return False
147 for nu in ob.data.splines:
148 if nu.point_count_v == 1 and nu.type != 'BEZIER': # not a surface and not bezier
149 return True
151 return False
154 def write_nurb(fw, ob, ob_mat):
155 tot_verts = 0
156 cu = ob.data
158 # use negative indices
159 for nu in cu.splines:
160 if nu.type == 'POLY':
161 DEG_ORDER_U = 1
162 else:
163 DEG_ORDER_U = nu.order_u - 1 # odd but tested to be correct
165 if nu.type == 'BEZIER':
166 print("\tWarning, bezier curve:", ob.name, "only poly and nurbs curves supported")
167 continue
169 if nu.point_count_v > 1:
170 print("\tWarning, surface:", ob.name, "only poly and nurbs curves supported")
171 continue
173 if len(nu.points) <= DEG_ORDER_U:
174 print("\tWarning, order_u is lower then vert count, skipping:", ob.name)
175 continue
177 pt_num = 0
178 do_closed = nu.use_cyclic_u
179 do_endpoints = (do_closed == 0) and nu.use_endpoint_u
181 for pt in nu.points:
182 fw('v %.6f %.6f %.6f\n' % (ob_mat @ pt.co.to_3d())[:])
183 pt_num += 1
184 tot_verts += pt_num
186 fw('g %s\n' % (name_compat(ob.name))) # name_compat(ob.getData(1)) could use the data name too
187 fw('cstype bspline\n') # not ideal, hard coded
188 fw('deg %d\n' % DEG_ORDER_U) # not used for curves but most files have it still
190 curve_ls = [-(i + 1) for i in range(pt_num)]
192 # 'curv' keyword
193 if do_closed:
194 if DEG_ORDER_U == 1:
195 pt_num += 1
196 curve_ls.append(-1)
197 else:
198 pt_num += DEG_ORDER_U
199 curve_ls = curve_ls + curve_ls[0:DEG_ORDER_U]
201 fw('curv 0.0 1.0 %s\n' % (" ".join([str(i) for i in curve_ls]))) # Blender has no U and V values for the curve
203 # 'parm' keyword
204 tot_parm = (DEG_ORDER_U + 1) + pt_num
205 tot_parm_div = float(tot_parm - 1)
206 parm_ls = [(i / tot_parm_div) for i in range(tot_parm)]
208 if do_endpoints: # end points, force param
209 for i in range(DEG_ORDER_U + 1):
210 parm_ls[i] = 0.0
211 parm_ls[-(1 + i)] = 1.0
213 fw("parm u %s\n" % " ".join(["%.6f" % i for i in parm_ls]))
215 fw('end\n')
217 return tot_verts
220 def write_file(filepath, objects, depsgraph, scene,
221 EXPORT_TRI=False,
222 EXPORT_EDGES=False,
223 EXPORT_SMOOTH_GROUPS=False,
224 EXPORT_SMOOTH_GROUPS_BITFLAGS=False,
225 EXPORT_NORMALS=False,
226 EXPORT_UV=True,
227 EXPORT_MTL=True,
228 EXPORT_APPLY_MODIFIERS=True,
229 EXPORT_APPLY_MODIFIERS_RENDER=False,
230 EXPORT_BLEN_OBS=True,
231 EXPORT_GROUP_BY_OB=False,
232 EXPORT_GROUP_BY_MAT=False,
233 EXPORT_KEEP_VERT_ORDER=False,
234 EXPORT_POLYGROUPS=False,
235 EXPORT_CURVE_AS_NURBS=True,
236 EXPORT_GLOBAL_MATRIX=None,
237 EXPORT_PATH_MODE='AUTO',
238 progress=ProgressReport(),
241 Basic write function. The context and options must be already set
242 This can be accessed externally
244 write( 'c:\\test\\foobar.obj', Blender.Object.GetSelected() ) # Using default options.
246 if EXPORT_GLOBAL_MATRIX is None:
247 EXPORT_GLOBAL_MATRIX = Matrix()
249 def veckey3d(v):
250 return round(v.x, 4), round(v.y, 4), round(v.z, 4)
252 def veckey2d(v):
253 return round(v[0], 4), round(v[1], 4)
255 def findVertexGroupName(face, vWeightMap):
257 Searches the vertexDict to see what groups is assigned to a given face.
258 We use a frequency system in order to sort out the name because a given vertex can
259 belong to two or more groups at the same time. To find the right name for the face
260 we list all the possible vertex group names with their frequency and then sort by
261 frequency in descend order. The top element is the one shared by the highest number
262 of vertices is the face's group
264 weightDict = {}
265 for vert_index in face.vertices:
266 vWeights = vWeightMap[vert_index]
267 for vGroupName, weight in vWeights:
268 weightDict[vGroupName] = weightDict.get(vGroupName, 0.0) + weight
270 if weightDict:
271 return max((weight, vGroupName) for vGroupName, weight in weightDict.items())[1]
272 else:
273 return '(null)'
275 with ProgressReportSubstep(progress, 2, "OBJ Export path: %r" % filepath, "OBJ Export Finished") as subprogress1:
276 with open(filepath, "w", encoding="utf8", newline="\n") as f:
277 fw = f.write
279 # Write Header
280 fw('# Blender v%s OBJ File: %r\n' % (bpy.app.version_string, os.path.basename(bpy.data.filepath)))
281 fw('# www.blender.org\n')
283 # Tell the obj file what material file to use.
284 if EXPORT_MTL:
285 mtlfilepath = os.path.splitext(filepath)[0] + ".mtl"
286 # filepath can contain non utf8 chars, use repr
287 fw('mtllib %s\n' % repr(os.path.basename(mtlfilepath))[1:-1])
289 # Initialize totals, these are updated each object
290 totverts = totuvco = totno = 1
292 face_vert_index = 1
294 # A Dict of Materials
295 # (material.name, image.name):matname_imagename # matname_imagename has gaps removed.
296 mtl_dict = {}
297 # Used to reduce the usage of matname_texname materials, which can become annoying in case of
298 # repeated exports/imports, yet keeping unique mat names per keys!
299 # mtl_name: (material.name, image.name)
300 mtl_rev_dict = {}
302 copy_set = set()
304 # Get all meshes
305 subprogress1.enter_substeps(len(objects))
306 for i, ob_main in enumerate(objects):
307 # ignore dupli children
308 if ob_main.parent and ob_main.parent.instance_type in {'VERTS', 'FACES'}:
309 subprogress1.step("Ignoring %s, dupli child..." % ob_main.name)
310 continue
312 obs = [(ob_main, ob_main.matrix_world)]
313 if ob_main.is_instancer:
314 obs += [(dup.instance_object.original, dup.matrix_world.copy())
315 for dup in depsgraph.object_instances
316 if dup.parent and dup.parent.original == ob_main]
317 # ~ print(ob_main.name, 'has', len(obs) - 1, 'dupli children')
319 subprogress1.enter_substeps(len(obs))
320 for ob, ob_mat in obs:
321 with ProgressReportSubstep(subprogress1, 6) as subprogress2:
322 uv_unique_count = no_unique_count = 0
324 # Nurbs curve support
325 if EXPORT_CURVE_AS_NURBS and test_nurbs_compat(ob):
326 ob_mat = EXPORT_GLOBAL_MATRIX @ ob_mat
327 totverts += write_nurb(fw, ob, ob_mat)
328 continue
329 # END NURBS
331 ob_for_convert = ob.evaluated_get(depsgraph) if EXPORT_APPLY_MODIFIERS else ob.original
333 try:
334 me = ob_for_convert.to_mesh()
335 except RuntimeError:
336 me = None
338 if me is None:
339 continue
341 # _must_ do this before applying transformation, else tessellation may differ
342 if EXPORT_TRI:
343 # _must_ do this first since it re-allocs arrays
344 mesh_triangulate(me)
346 me.transform(EXPORT_GLOBAL_MATRIX @ ob_mat)
347 # If negative scaling, we have to invert the normals...
348 if ob_mat.determinant() < 0.0:
349 me.flip_normals()
351 if EXPORT_UV:
352 faceuv = len(me.uv_layers) > 0
353 if faceuv:
354 uv_layer = me.uv_layers.active.data[:]
355 else:
356 faceuv = False
358 me_verts = me.vertices[:]
360 # Make our own list so it can be sorted to reduce context switching
361 face_index_pairs = [(face, index) for index, face in enumerate(me.polygons)]
363 if EXPORT_EDGES:
364 edges = me.edges
365 else:
366 edges = []
368 if not (len(face_index_pairs) + len(edges) + len(me.vertices)): # Make sure there is something to write
369 # clean up
370 ob_for_convert.to_mesh_clear()
371 continue # dont bother with this mesh.
373 if EXPORT_NORMALS and face_index_pairs:
374 me.calc_normals_split()
375 # No need to call me.free_normals_split later, as this mesh is deleted anyway!
377 loops = me.loops
379 if (EXPORT_SMOOTH_GROUPS or EXPORT_SMOOTH_GROUPS_BITFLAGS) and face_index_pairs:
380 smooth_groups, smooth_groups_tot = me.calc_smooth_groups(use_bitflags=EXPORT_SMOOTH_GROUPS_BITFLAGS)
381 if smooth_groups_tot <= 1:
382 smooth_groups, smooth_groups_tot = (), 0
383 else:
384 smooth_groups, smooth_groups_tot = (), 0
386 materials = me.materials[:]
387 material_names = [m.name if m else None for m in materials]
389 # avoid bad index errors
390 if not materials:
391 materials = [None]
392 material_names = [name_compat(None)]
394 # Sort by Material, then images
395 # so we dont over context switch in the obj file.
396 if EXPORT_KEEP_VERT_ORDER:
397 pass
398 else:
399 if len(materials) > 1:
400 if smooth_groups:
401 sort_func = lambda a: (a[0].material_index,
402 smooth_groups[a[1]] if a[0].use_smooth else False)
403 else:
404 sort_func = lambda a: (a[0].material_index,
405 a[0].use_smooth)
406 else:
407 # no materials
408 if smooth_groups:
409 sort_func = lambda a: smooth_groups[a[1] if a[0].use_smooth else False]
410 else:
411 sort_func = lambda a: a[0].use_smooth
413 face_index_pairs.sort(key=sort_func)
415 del sort_func
417 # Set the default mat to no material and no image.
418 contextMat = 0, 0 # Can never be this, so we will label a new material the first chance we get.
419 contextSmooth = None # Will either be true or false, set bad to force initialization switch.
421 if EXPORT_BLEN_OBS or EXPORT_GROUP_BY_OB:
422 name1 = ob.name
423 name2 = ob.data.name
424 if name1 == name2:
425 obnamestring = name_compat(name1)
426 else:
427 obnamestring = '%s_%s' % (name_compat(name1), name_compat(name2))
429 if EXPORT_BLEN_OBS:
430 fw('o %s\n' % obnamestring) # Write Object name
431 else: # if EXPORT_GROUP_BY_OB:
432 fw('g %s\n' % obnamestring)
434 subprogress2.step()
436 # Vert
437 for v in me_verts:
438 fw('v %.6f %.6f %.6f\n' % v.co[:])
440 subprogress2.step()
442 # UV
443 if faceuv:
444 # in case removing some of these dont get defined.
445 uv = f_index = uv_index = uv_key = uv_val = uv_ls = None
447 uv_face_mapping = [None] * len(face_index_pairs)
449 uv_dict = {}
450 uv_get = uv_dict.get
451 for f, f_index in face_index_pairs:
452 uv_ls = uv_face_mapping[f_index] = []
453 for uv_index, l_index in enumerate(f.loop_indices):
454 uv = uv_layer[l_index].uv
455 # include the vertex index in the key so we don't share UVs between vertices,
456 # allowed by the OBJ spec but can cause issues for other importers, see: T47010.
458 # this works too, shared UVs for all verts
459 #~ uv_key = veckey2d(uv)
460 uv_key = loops[l_index].vertex_index, veckey2d(uv)
462 uv_val = uv_get(uv_key)
463 if uv_val is None:
464 uv_val = uv_dict[uv_key] = uv_unique_count
465 fw('vt %.6f %.6f\n' % uv[:])
466 uv_unique_count += 1
467 uv_ls.append(uv_val)
469 del uv_dict, uv, f_index, uv_index, uv_ls, uv_get, uv_key, uv_val
470 # Only need uv_unique_count and uv_face_mapping
472 subprogress2.step()
474 # NORMAL, Smooth/Non smoothed.
475 if EXPORT_NORMALS:
476 no_key = no_val = None
477 normals_to_idx = {}
478 no_get = normals_to_idx.get
479 loops_to_normals = [0] * len(loops)
480 for f, f_index in face_index_pairs:
481 for l_idx in f.loop_indices:
482 no_key = veckey3d(loops[l_idx].normal)
483 no_val = no_get(no_key)
484 if no_val is None:
485 no_val = normals_to_idx[no_key] = no_unique_count
486 fw('vn %.4f %.4f %.4f\n' % no_key)
487 no_unique_count += 1
488 loops_to_normals[l_idx] = no_val
489 del normals_to_idx, no_get, no_key, no_val
490 else:
491 loops_to_normals = []
493 subprogress2.step()
495 # XXX
496 if EXPORT_POLYGROUPS:
497 # Retrieve the list of vertex groups
498 vertGroupNames = ob.vertex_groups.keys()
499 if vertGroupNames:
500 currentVGroup = ''
501 # Create a dictionary keyed by face id and listing, for each vertex, the vertex groups it belongs to
502 vgroupsMap = [[] for _i in range(len(me_verts))]
503 for v_idx, v_ls in enumerate(vgroupsMap):
504 v_ls[:] = [(vertGroupNames[g.group], g.weight) for g in me_verts[v_idx].groups]
506 for f, f_index in face_index_pairs:
507 f_smooth = f.use_smooth
508 if f_smooth and smooth_groups:
509 f_smooth = smooth_groups[f_index]
510 f_mat = min(f.material_index, len(materials) - 1)
512 # MAKE KEY
513 key = material_names[f_mat], None # No image, use None instead.
515 # Write the vertex group
516 if EXPORT_POLYGROUPS:
517 if vertGroupNames:
518 # find what vertext group the face belongs to
519 vgroup_of_face = findVertexGroupName(f, vgroupsMap)
520 if vgroup_of_face != currentVGroup:
521 currentVGroup = vgroup_of_face
522 fw('g %s\n' % vgroup_of_face)
524 # CHECK FOR CONTEXT SWITCH
525 if key == contextMat:
526 pass # Context already switched, dont do anything
527 else:
528 if key[0] is None and key[1] is None:
529 # Write a null material, since we know the context has changed.
530 if EXPORT_GROUP_BY_MAT:
531 # can be mat_image or (null)
532 fw("g %s_%s\n" % (name_compat(ob.name), name_compat(ob.data.name)))
533 if EXPORT_MTL:
534 fw("usemtl (null)\n") # mat, image
536 else:
537 mat_data = mtl_dict.get(key)
538 if not mat_data:
539 # First add to global dict so we can export to mtl
540 # Then write mtl
542 # Make a new names from the mat and image name,
543 # converting any spaces to underscores with name_compat.
545 # If none image dont bother adding it to the name
546 # Try to avoid as much as possible adding texname (or other things)
547 # to the mtl name (see [#32102])...
548 mtl_name = "%s" % name_compat(key[0])
549 if mtl_rev_dict.get(mtl_name, None) not in {key, None}:
550 if key[1] is None:
551 tmp_ext = "_NONE"
552 else:
553 tmp_ext = "_%s" % name_compat(key[1])
554 i = 0
555 while mtl_rev_dict.get(mtl_name + tmp_ext, None) not in {key, None}:
556 i += 1
557 tmp_ext = "_%3d" % i
558 mtl_name += tmp_ext
559 mat_data = mtl_dict[key] = mtl_name, materials[f_mat]
560 mtl_rev_dict[mtl_name] = key
562 if EXPORT_GROUP_BY_MAT:
563 # can be mat_image or (null)
564 fw("g %s_%s_%s\n" % (name_compat(ob.name), name_compat(ob.data.name), mat_data[0]))
565 if EXPORT_MTL:
566 fw("usemtl %s\n" % mat_data[0]) # can be mat_image or (null)
568 contextMat = key
569 if f_smooth != contextSmooth:
570 if f_smooth: # on now off
571 if smooth_groups:
572 f_smooth = smooth_groups[f_index]
573 fw('s %d\n' % f_smooth)
574 else:
575 fw('s 1\n')
576 else: # was off now on
577 fw('s off\n')
578 contextSmooth = f_smooth
580 f_v = [(vi, me_verts[v_idx], l_idx)
581 for vi, (v_idx, l_idx) in enumerate(zip(f.vertices, f.loop_indices))]
583 fw('f')
584 if faceuv:
585 if EXPORT_NORMALS:
586 for vi, v, li in f_v:
587 fw(" %d/%d/%d" % (totverts + v.index,
588 totuvco + uv_face_mapping[f_index][vi],
589 totno + loops_to_normals[li],
590 )) # vert, uv, normal
591 else: # No Normals
592 for vi, v, li in f_v:
593 fw(" %d/%d" % (totverts + v.index,
594 totuvco + uv_face_mapping[f_index][vi],
595 )) # vert, uv
597 face_vert_index += len(f_v)
599 else: # No UVs
600 if EXPORT_NORMALS:
601 for vi, v, li in f_v:
602 fw(" %d//%d" % (totverts + v.index, totno + loops_to_normals[li]))
603 else: # No Normals
604 for vi, v, li in f_v:
605 fw(" %d" % (totverts + v.index))
607 fw('\n')
609 subprogress2.step()
611 # Write edges.
612 if EXPORT_EDGES:
613 for ed in edges:
614 if ed.is_loose:
615 fw('l %d %d\n' % (totverts + ed.vertices[0], totverts + ed.vertices[1]))
617 # Make the indices global rather then per mesh
618 totverts += len(me_verts)
619 totuvco += uv_unique_count
620 totno += no_unique_count
622 # clean up
623 ob_for_convert.to_mesh_clear()
625 subprogress1.leave_substeps("Finished writing geometry of '%s'." % ob_main.name)
626 subprogress1.leave_substeps()
628 subprogress1.step("Finished exporting geometry, now exporting materials")
630 # Now we have all our materials, save them
631 if EXPORT_MTL:
632 write_mtl(scene, mtlfilepath, EXPORT_PATH_MODE, copy_set, mtl_dict)
634 # copy all collected files.
635 io_utils.path_reference_copy(copy_set)
638 def _write(context, filepath,
639 EXPORT_TRI, # ok
640 EXPORT_EDGES,
641 EXPORT_SMOOTH_GROUPS,
642 EXPORT_SMOOTH_GROUPS_BITFLAGS,
643 EXPORT_NORMALS, # ok
644 EXPORT_UV, # ok
645 EXPORT_MTL,
646 EXPORT_APPLY_MODIFIERS, # ok
647 EXPORT_APPLY_MODIFIERS_RENDER, # ok
648 EXPORT_BLEN_OBS,
649 EXPORT_GROUP_BY_OB,
650 EXPORT_GROUP_BY_MAT,
651 EXPORT_KEEP_VERT_ORDER,
652 EXPORT_POLYGROUPS,
653 EXPORT_CURVE_AS_NURBS,
654 EXPORT_SEL_ONLY, # ok
655 EXPORT_ANIMATION,
656 EXPORT_GLOBAL_MATRIX,
657 EXPORT_PATH_MODE, # Not used
660 with ProgressReport(context.window_manager) as progress:
661 base_name, ext = os.path.splitext(filepath)
662 context_name = [base_name, '', '', ext] # Base name, scene name, frame number, extension
664 depsgraph = context.evaluated_depsgraph_get()
665 scene = context.scene
667 # Exit edit mode before exporting, so current object states are exported properly.
668 if bpy.ops.object.mode_set.poll():
669 bpy.ops.object.mode_set(mode='OBJECT')
671 orig_frame = scene.frame_current
673 # Export an animation?
674 if EXPORT_ANIMATION:
675 scene_frames = range(scene.frame_start, scene.frame_end + 1) # Up to and including the end frame.
676 else:
677 scene_frames = [orig_frame] # Dont export an animation.
679 # Loop through all frames in the scene and export.
680 progress.enter_substeps(len(scene_frames))
681 for frame in scene_frames:
682 if EXPORT_ANIMATION: # Add frame to the filepath.
683 context_name[2] = '_%.6d' % frame
685 scene.frame_set(frame, subframe=0.0)
686 if EXPORT_SEL_ONLY:
687 objects = context.selected_objects
688 else:
689 objects = scene.objects
691 full_path = ''.join(context_name)
693 # erm... bit of a problem here, this can overwrite files when exporting frames. not too bad.
694 # EXPORT THE FILE.
695 progress.enter_substeps(1)
696 write_file(full_path, objects, depsgraph, scene,
697 EXPORT_TRI,
698 EXPORT_EDGES,
699 EXPORT_SMOOTH_GROUPS,
700 EXPORT_SMOOTH_GROUPS_BITFLAGS,
701 EXPORT_NORMALS,
702 EXPORT_UV,
703 EXPORT_MTL,
704 EXPORT_APPLY_MODIFIERS,
705 EXPORT_APPLY_MODIFIERS_RENDER,
706 EXPORT_BLEN_OBS,
707 EXPORT_GROUP_BY_OB,
708 EXPORT_GROUP_BY_MAT,
709 EXPORT_KEEP_VERT_ORDER,
710 EXPORT_POLYGROUPS,
711 EXPORT_CURVE_AS_NURBS,
712 EXPORT_GLOBAL_MATRIX,
713 EXPORT_PATH_MODE,
714 progress,
716 progress.leave_substeps()
718 scene.frame_set(orig_frame, subframe=0.0)
719 progress.leave_substeps()
723 Currently the exporter lacks these features:
724 * multiple scene export (only active scene is written)
725 * particles
729 def save(context,
730 filepath,
732 use_triangles=False,
733 use_edges=True,
734 use_normals=False,
735 use_smooth_groups=False,
736 use_smooth_groups_bitflags=False,
737 use_uvs=True,
738 use_materials=True,
739 use_mesh_modifiers=True,
740 use_mesh_modifiers_render=False,
741 use_blen_objects=True,
742 group_by_object=False,
743 group_by_material=False,
744 keep_vertex_order=False,
745 use_vertex_groups=False,
746 use_nurbs=True,
747 use_selection=True,
748 use_animation=False,
749 global_matrix=None,
750 path_mode='AUTO'
753 _write(context, filepath,
754 EXPORT_TRI=use_triangles,
755 EXPORT_EDGES=use_edges,
756 EXPORT_SMOOTH_GROUPS=use_smooth_groups,
757 EXPORT_SMOOTH_GROUPS_BITFLAGS=use_smooth_groups_bitflags,
758 EXPORT_NORMALS=use_normals,
759 EXPORT_UV=use_uvs,
760 EXPORT_MTL=use_materials,
761 EXPORT_APPLY_MODIFIERS=use_mesh_modifiers,
762 EXPORT_APPLY_MODIFIERS_RENDER=use_mesh_modifiers_render,
763 EXPORT_BLEN_OBS=use_blen_objects,
764 EXPORT_GROUP_BY_OB=group_by_object,
765 EXPORT_GROUP_BY_MAT=group_by_material,
766 EXPORT_KEEP_VERT_ORDER=keep_vertex_order,
767 EXPORT_POLYGROUPS=use_vertex_groups,
768 EXPORT_CURVE_AS_NURBS=use_nurbs,
769 EXPORT_SEL_ONLY=use_selection,
770 EXPORT_ANIMATION=use_animation,
771 EXPORT_GLOBAL_MATRIX=global_matrix,
772 EXPORT_PATH_MODE=path_mode,
775 return {'FINISHED'}