Cleanup: autopep8 for 3DS i/o
[blender-addons.git] / io_scene_obj / import_obj.py
blob63c4d0e13100b47828f3a7a5a07cd63ed51b142d
1 # SPDX-License-Identifier: GPL-2.0-or-later
3 # Script copyright (C) Campbell Barton
4 # Contributors: Campbell Barton, Jiri Hnidek, Paolo Ciccone
6 """
7 This script imports a Wavefront OBJ files to Blender.
9 Usage:
10 Run this script from "File->Import" menu and then load the desired OBJ file.
11 Note, This loads mesh objects and materials only, nurbs and curves are not supported.
13 http://wiki.blender.org/index.php/Scripts/Manual/Import/wavefront_obj
14 """
16 import array
17 import os
18 import time
19 import bpy
20 import mathutils
22 from bpy_extras.io_utils import unpack_list
23 from bpy_extras.image_utils import load_image
24 from bpy_extras.wm_utils.progress_report import ProgressReport
27 def line_value(line_split):
28 """
29 Returns 1 string representing the value for this line
30 None will be returned if there's only 1 word
31 """
32 length = len(line_split)
33 if length == 1:
34 return None
36 elif length == 2:
37 return line_split[1]
39 elif length > 2:
40 return b' '.join(line_split[1:])
43 def filenames_group_by_ext(line, ext):
44 """
45 Splits material libraries supporting spaces, so:
46 b'foo bar.mtl baz spam.MTL' -> (b'foo bar.mtl', b'baz spam.MTL')
47 Also handle " chars (some software use those to protect filenames with spaces, see T67266... sic).
48 """
49 # Note that we assume that if there are some " in that line,
50 # then all filenames are properly enclosed within those...
51 start = line.find(b'"') + 1
52 if start != 0:
53 while start != 0:
54 end = line.find(b'"', start)
55 if end != -1:
56 yield line[start:end]
57 start = line.find(b'"', end + 1) + 1
58 else:
59 break
60 return
62 line_lower = line.lower()
63 i_prev = 0
64 while i_prev != -1 and i_prev < len(line):
65 i = line_lower.find(ext, i_prev)
66 if i != -1:
67 i += len(ext)
68 yield line[i_prev:i].strip()
69 i_prev = i
72 def obj_image_load(img_data, context_imagepath_map, line, DIR, recursive, relpath):
73 """
74 Mainly uses comprehensiveImageLoad
75 But we try all space-separated items from current line when file is not found with last one
76 (users keep generating/using image files with spaces in a format that does not support them, sigh...)
77 Also tries to replace '_' with ' ' for Max's exporter replaces spaces with underscores.
78 Also handle " chars (some software use those to protect filenames with spaces, see T67266... sic).
79 Also corrects img_data (in case filenames with spaces have been split up in multiple entries, see T72148).
80 """
81 filepath_parts = line.split(b' ')
83 start = line.find(b'"') + 1
84 if start != 0:
85 end = line.find(b'"', start)
86 if end != 0:
87 filepath_parts = (line[start:end],)
89 image = None
90 for i in range(-1, -len(filepath_parts), -1):
91 imagepath = os.fsdecode(b" ".join(filepath_parts[i:]))
92 image = context_imagepath_map.get(imagepath, ...)
93 if image is ...:
94 image = load_image(imagepath, DIR, recursive=recursive, relpath=relpath)
95 if image is None and "_" in imagepath:
96 image = load_image(imagepath.replace("_", " "), DIR, recursive=recursive, relpath=relpath)
97 if image is not None:
98 context_imagepath_map[imagepath] = image
99 del img_data[i:]
100 img_data.append(imagepath)
101 break;
102 else:
103 del img_data[i:]
104 img_data.append(imagepath)
105 break;
107 if image is None:
108 imagepath = os.fsdecode(filepath_parts[-1])
109 image = load_image(imagepath, DIR, recursive=recursive, place_holder=True, relpath=relpath)
110 context_imagepath_map[imagepath] = image
112 return image
115 def create_materials(filepath, relpath,
116 material_libs, unique_materials,
117 use_image_search, float_func):
119 Create all the used materials in this obj,
120 assign colors and images to the materials from all referenced material libs
122 from math import sqrt
123 from bpy_extras import node_shader_utils
125 DIR = os.path.dirname(filepath)
126 context_material_vars = set()
128 # Don't load the same image multiple times
129 context_imagepath_map = {}
131 nodal_material_wrap_map = {}
133 def load_material_image(blender_material, mat_wrap, context_material_name, img_data, line, type):
135 Set textures defined in .mtl file.
137 map_options = {}
139 # Absolute path - c:\.. etc would work here
140 image = obj_image_load(img_data, context_imagepath_map, line, DIR, use_image_search, relpath)
142 curr_token = []
143 for token in img_data[:-1]:
144 if token.startswith(b'-') and token[1:].isalpha():
145 if curr_token:
146 map_options[curr_token[0]] = curr_token[1:]
147 curr_token[:] = []
148 curr_token.append(token)
149 if curr_token:
150 map_options[curr_token[0]] = curr_token[1:]
152 map_offset = map_options.get(b'-o')
153 map_scale = map_options.get(b'-s')
154 if map_offset is not None:
155 map_offset = tuple(map(float_func, map_offset))
156 if map_scale is not None:
157 map_scale = tuple(map(float_func, map_scale))
159 def _generic_tex_set(nodetex, image, texcoords, translation, scale):
160 nodetex.image = image
161 nodetex.texcoords = texcoords
162 if translation is not None:
163 nodetex.translation = translation
164 if scale is not None:
165 nodetex.scale = scale
167 # Adds textures for materials (rendering)
168 if type == 'Kd':
169 _generic_tex_set(mat_wrap.base_color_texture, image, 'UV', map_offset, map_scale)
171 elif type == 'Ka':
172 # XXX Not supported?
173 print("WARNING, currently unsupported ambient texture, skipped.")
175 elif type == 'Ks':
176 _generic_tex_set(mat_wrap.specular_texture, image, 'UV', map_offset, map_scale)
178 elif type == 'Ke':
179 _generic_tex_set(mat_wrap.emission_color_texture, image, 'UV', map_offset, map_scale)
180 mat_wrap.emission_strength = 1.0
182 elif type == 'Bump':
183 bump_mult = map_options.get(b'-bm')
184 bump_mult = float(bump_mult[0]) if (bump_mult and len(bump_mult[0]) > 1) else 1.0
185 mat_wrap.normalmap_strength_set(bump_mult)
187 _generic_tex_set(mat_wrap.normalmap_texture, image, 'UV', map_offset, map_scale)
189 elif type == 'D':
190 _generic_tex_set(mat_wrap.alpha_texture, image, 'UV', map_offset, map_scale)
192 elif type == 'disp':
193 # XXX Not supported?
194 print("WARNING, currently unsupported displacement texture, skipped.")
195 # ~ mat_wrap.bump_image_set(image)
196 # ~ mat_wrap.bump_mapping_set(coords='UV', translation=map_offset, scale=map_scale)
198 elif type == 'refl':
199 map_type = map_options.get(b'-type')
200 if map_type and map_type != [b'sphere']:
201 print("WARNING, unsupported reflection type '%s', defaulting to 'sphere'"
202 "" % ' '.join(i.decode() for i in map_type))
204 _generic_tex_set(mat_wrap.base_color_texture, image, 'Reflection', map_offset, map_scale)
205 mat_wrap.base_color_texture.projection = 'SPHERE'
207 else:
208 raise Exception("invalid type %r" % type)
210 def finalize_material(context_material, context_material_vars, spec_colors,
211 do_highlight, do_reflection, do_transparency, do_glass):
212 # Finalize previous mat, if any.
213 if context_material:
214 if "specular" in context_material_vars:
215 # XXX This is highly approximated, not sure whether we can do better...
216 # TODO: Find a way to guesstimate best value from diffuse color...
217 # IDEA: Use standard deviation of both spec and diff colors (i.e. how far away they are
218 # from some grey), and apply the the proportion between those two as tint factor?
219 spec = sum(spec_colors) / 3.0
220 # ~ spec_var = math.sqrt(sum((c - spec) ** 2 for c in spec_color) / 3.0)
221 # ~ diff = sum(context_mat_wrap.base_color) / 3.0
222 # ~ diff_var = math.sqrt(sum((c - diff) ** 2 for c in context_mat_wrap.base_color) / 3.0)
223 # ~ tint = min(1.0, spec_var / diff_var)
224 context_mat_wrap.specular = spec
225 context_mat_wrap.specular_tint = 0.0
226 if "roughness" not in context_material_vars:
227 context_mat_wrap.roughness = 0.0
229 # FIXME, how else to use this?
230 if do_highlight:
231 if "specular" not in context_material_vars:
232 context_mat_wrap.specular = 1.0
233 if "roughness" not in context_material_vars:
234 context_mat_wrap.roughness = 0.0
235 else:
236 if "specular" not in context_material_vars:
237 context_mat_wrap.specular = 0.0
238 if "roughness" not in context_material_vars:
239 context_mat_wrap.roughness = 1.0
241 if do_reflection:
242 if "metallic" not in context_material_vars:
243 context_mat_wrap.metallic = 1.0
244 else:
245 # since we are (ab)using ambient term for metallic (which can be non-zero)
246 context_mat_wrap.metallic = 0.0
248 if do_transparency:
249 if "ior" not in context_material_vars:
250 context_mat_wrap.ior = 1.0
251 if "alpha" not in context_material_vars:
252 context_mat_wrap.alpha = 1.0
253 # EEVEE only
254 context_material.blend_method = 'BLEND'
256 if do_glass:
257 if "ior" not in context_material_vars:
258 context_mat_wrap.ior = 1.5
260 # Try to find a MTL with the same name as the OBJ if no MTLs are specified.
261 temp_mtl = os.path.splitext((os.path.basename(filepath)))[0] + ".mtl"
262 if os.path.exists(os.path.join(DIR, temp_mtl)):
263 material_libs.add(temp_mtl)
264 del temp_mtl
266 # Create new materials
267 for name in unique_materials: # .keys()
268 ma_name = "Default OBJ" if name is None else name.decode('utf-8', "replace")
269 ma = unique_materials[name] = bpy.data.materials.new(ma_name)
270 ma_wrap = node_shader_utils.PrincipledBSDFWrapper(ma, is_readonly=False)
271 nodal_material_wrap_map[ma] = ma_wrap
272 ma_wrap.use_nodes = True
274 for libname in sorted(material_libs):
275 # print(libname)
276 mtlpath = os.path.join(DIR, libname)
277 if not os.path.exists(mtlpath):
278 print("\tMaterial not found MTL: %r" % mtlpath)
279 else:
280 # Note: with modern Principled BSDF shader, things like ambient, raytrace or fresnel are always 'ON'
281 # (i.e. automatically controlled by other parameters).
282 do_highlight = False
283 do_reflection = False
284 do_transparency = False
285 do_glass = False
286 spec_colors = [0.0, 0.0, 0.0]
288 # print('\t\tloading mtl: %e' % mtlpath)
289 context_material = None
290 context_mat_wrap = None
291 mtl = open(mtlpath, 'rb')
292 for line in mtl: # .readlines():
293 line = line.strip()
294 if not line or line.startswith(b'#'):
295 continue
297 line_split = line.split()
298 line_id = line_split[0].lower()
300 if line_id == b'newmtl':
301 # Finalize previous mat, if any.
302 finalize_material(context_material, context_material_vars, spec_colors,
303 do_highlight, do_reflection, do_transparency, do_glass)
305 context_material_name = line_value(line_split)
306 context_material = unique_materials.get(context_material_name)
307 if context_material is not None:
308 context_mat_wrap = nodal_material_wrap_map[context_material]
309 context_material_vars.clear()
311 spec_colors[:] = [0.0, 0.0, 0.0]
312 do_highlight = False
313 do_reflection = False
314 do_transparency = False
315 do_glass = False
318 elif context_material:
319 def _get_colors(line_split):
320 # OBJ 'allows' one or two components values, treat single component as greyscale, and two as blue = 0.0.
321 ln = len(line_split)
322 if ln == 2:
323 return [float_func(line_split[1])] * 3
324 elif ln == 3:
325 return [float_func(line_split[1]), float_func(line_split[2]), 0.0]
326 else:
327 return [float_func(line_split[1]), float_func(line_split[2]), float_func(line_split[3])]
329 # we need to make a material to assign properties to it.
330 if line_id == b'ka':
331 refl = sum(_get_colors(line_split)) / 3.0
332 context_mat_wrap.metallic = refl
333 context_material_vars.add("metallic")
334 elif line_id == b'kd':
335 context_mat_wrap.base_color = _get_colors(line_split)
336 elif line_id == b'ks':
337 spec_colors[:] = _get_colors(line_split)
338 context_material_vars.add("specular")
339 elif line_id == b'ke':
340 # We cannot set context_material.emit right now, we need final diffuse color as well for this.
341 # XXX Unsupported currently
342 context_mat_wrap.emission_color = _get_colors(line_split)
343 context_mat_wrap.emission_strength = 1.0
344 elif line_id == b'ns':
345 # XXX Totally empirical conversion, trying to adapt it
346 # (from 0.0 - 1000.0 OBJ specular exponent range to 1.0 - 0.0 Principled BSDF range)...
347 val = max(0.0, min(1000.0, float_func(line_split[1])))
348 context_mat_wrap.roughness = 1.0 - (sqrt(val / 1000))
349 context_material_vars.add("roughness")
350 elif line_id == b'ni': # Refraction index (between 0.001 and 10).
351 context_mat_wrap.ior = float_func(line_split[1])
352 context_material_vars.add("ior")
353 elif line_id == b'd': # dissolve (transparency)
354 context_mat_wrap.alpha = float_func(line_split[1])
355 context_material_vars.add("alpha")
356 elif line_id == b'tr': # translucency
357 print("WARNING, currently unsupported 'tr' translucency option, skipped.")
358 elif line_id == b'tf':
359 # rgb, filter color, blender has no support for this.
360 print("WARNING, currently unsupported 'tf' filter color option, skipped.")
361 elif line_id == b'illum':
362 # Some MTL files incorrectly use a float for this value, see T60135.
363 illum = any_number_as_int(line_split[1])
365 # inline comments are from the spec, v4.2
366 if illum == 0:
367 # Color on and Ambient off
368 print("WARNING, Principled BSDF shader does not support illumination 0 mode "
369 "(colors with no ambient), skipped.")
370 elif illum == 1:
371 # Color on and Ambient on
372 pass
373 elif illum == 2:
374 # Highlight on
375 do_highlight = True
376 elif illum == 3:
377 # Reflection on and Ray trace on
378 do_reflection = True
379 elif illum == 4:
380 # Transparency: Glass on
381 # Reflection: Ray trace on
382 do_transparency = True
383 do_reflection = True
384 do_glass = True
385 elif illum == 5:
386 # Reflection: Fresnel on and Ray trace on
387 do_reflection = True
388 elif illum == 6:
389 # Transparency: Refraction on
390 # Reflection: Fresnel off and Ray trace on
391 do_transparency = True
392 do_reflection = True
393 elif illum == 7:
394 # Transparency: Refraction on
395 # Reflection: Fresnel on and Ray trace on
396 do_transparency = True
397 do_reflection = True
398 elif illum == 8:
399 # Reflection on and Ray trace off
400 do_reflection = True
401 elif illum == 9:
402 # Transparency: Glass on
403 # Reflection: Ray trace off
404 do_transparency = True
405 do_reflection = False
406 do_glass = True
407 elif illum == 10:
408 # Casts shadows onto invisible surfaces
409 print("WARNING, Principled BSDF shader does not support illumination 10 mode "
410 "(cast shadows on invisible surfaces), skipped.")
411 pass
413 elif line_id == b'map_ka':
414 img_data = line.split()[1:]
415 if img_data:
416 load_material_image(context_material, context_mat_wrap,
417 context_material_name, img_data, line, 'Ka')
418 elif line_id == b'map_ks':
419 img_data = line.split()[1:]
420 if img_data:
421 load_material_image(context_material, context_mat_wrap,
422 context_material_name, img_data, line, 'Ks')
423 elif line_id == b'map_kd':
424 img_data = line.split()[1:]
425 if img_data:
426 load_material_image(context_material, context_mat_wrap,
427 context_material_name, img_data, line, 'Kd')
428 elif line_id == b'map_ke':
429 img_data = line.split()[1:]
430 if img_data:
431 load_material_image(context_material, context_mat_wrap,
432 context_material_name, img_data, line, 'Ke')
433 elif line_id in {b'map_bump', b'bump'}: # 'bump' is incorrect but some files use it.
434 img_data = line.split()[1:]
435 if img_data:
436 load_material_image(context_material, context_mat_wrap,
437 context_material_name, img_data, line, 'Bump')
438 elif line_id in {b'map_d', b'map_tr'}: # Alpha map - Dissolve
439 img_data = line.split()[1:]
440 if img_data:
441 load_material_image(context_material, context_mat_wrap,
442 context_material_name, img_data, line, 'D')
444 elif line_id in {b'map_disp', b'disp'}: # displacementmap
445 img_data = line.split()[1:]
446 if img_data:
447 load_material_image(context_material, context_mat_wrap,
448 context_material_name, img_data, line, 'disp')
450 elif line_id in {b'map_refl', b'refl'}: # reflectionmap
451 img_data = line.split()[1:]
452 if img_data:
453 load_material_image(context_material, context_mat_wrap,
454 context_material_name, img_data, line, 'refl')
455 else:
456 print("WARNING: %r:%r (ignored)" % (filepath, line))
458 # Finalize last mat, if any.
459 finalize_material(context_material, context_material_vars, spec_colors,
460 do_highlight, do_reflection, do_transparency, do_glass)
461 mtl.close()
464 def face_is_edge(face):
465 """Simple check to test whether given (temp, working) data is an edge, and not a real face."""
466 face_vert_loc_indices = face[0]
467 face_vert_nor_indices = face[1]
468 return len(face_vert_nor_indices) == 1 or len(face_vert_loc_indices) == 2
471 def split_mesh(verts_loc, faces, unique_materials, filepath, SPLIT_OB_OR_GROUP):
473 Takes vert_loc and faces, and separates into multiple sets of
474 (verts_loc, faces, unique_materials, dataname)
477 filename = os.path.splitext((os.path.basename(filepath)))[0]
479 if not SPLIT_OB_OR_GROUP or not faces:
480 use_verts_nor = any(f[1] for f in faces)
481 use_verts_tex = any(f[2] for f in faces)
482 # use the filename for the object name since we aren't chopping up the mesh.
483 return [(verts_loc, faces, unique_materials, filename, use_verts_nor, use_verts_tex)]
485 def key_to_name(key):
486 # if the key is a tuple, join it to make a string
487 if not key:
488 return filename # assume its a string. make sure this is true if the splitting code is changed
489 elif isinstance(key, bytes):
490 return key.decode('utf-8', 'replace')
491 else:
492 return "_".join(k.decode('utf-8', 'replace') for k in key)
494 # Return a key that makes the faces unique.
495 face_split_dict = {}
497 oldkey = -1 # initialize to a value that will never match the key
499 for face in faces:
500 (face_vert_loc_indices,
501 face_vert_nor_indices,
502 face_vert_tex_indices,
503 context_material,
504 _context_smooth_group,
505 context_object_key,
506 _face_invalid_blenpoly,
507 ) = face
508 key = context_object_key
510 if oldkey != key:
511 # Check the key has changed.
512 (verts_split, faces_split, unique_materials_split, vert_remap,
513 use_verts_nor, use_verts_tex) = face_split_dict.setdefault(key, ([], [], {}, {}, [], []))
514 oldkey = key
516 if not face_is_edge(face):
517 if not use_verts_nor and face_vert_nor_indices:
518 use_verts_nor.append(True)
520 if not use_verts_tex and face_vert_tex_indices:
521 use_verts_tex.append(True)
523 # Remap verts to new vert list and add where needed
524 for loop_idx, vert_idx in enumerate(face_vert_loc_indices):
525 map_index = vert_remap.get(vert_idx)
526 if map_index is None:
527 map_index = len(verts_split)
528 vert_remap[vert_idx] = map_index # set the new remapped index so we only add once and can reference next time.
529 verts_split.append(verts_loc[vert_idx]) # add the vert to the local verts
531 face_vert_loc_indices[loop_idx] = map_index # remap to the local index
533 if context_material not in unique_materials_split:
534 unique_materials_split[context_material] = unique_materials[context_material]
536 faces_split.append(face)
538 # remove one of the items and reorder
539 return [(verts_split, faces_split, unique_materials_split, key_to_name(key), bool(use_vnor), bool(use_vtex))
540 for key, (verts_split, faces_split, unique_materials_split, _, use_vnor, use_vtex)
541 in face_split_dict.items()]
544 def create_mesh(new_objects,
545 use_edges,
546 verts_loc,
547 verts_nor,
548 verts_tex,
549 faces,
550 unique_materials,
551 unique_smooth_groups,
552 vertex_groups,
553 dataname,
556 Takes all the data gathered and generates a mesh, adding the new object to new_objects
557 deals with ngons, sharp edges and assigning materials
560 if unique_smooth_groups:
561 sharp_edges = set()
562 smooth_group_users = {context_smooth_group: {} for context_smooth_group in unique_smooth_groups.keys()}
563 context_smooth_group_old = -1
565 fgon_edges = set() # Used for storing fgon keys when we need to tessellate/untessellate them (ngons with hole).
566 edges = []
567 tot_loops = 0
569 context_object_key = None
571 # reverse loop through face indices
572 for f_idx in range(len(faces) - 1, -1, -1):
573 face = faces[f_idx]
575 (face_vert_loc_indices,
576 face_vert_nor_indices,
577 face_vert_tex_indices,
578 context_material,
579 context_smooth_group,
580 context_object_key,
581 face_invalid_blenpoly,
582 ) = face
584 len_face_vert_loc_indices = len(face_vert_loc_indices)
586 if len_face_vert_loc_indices == 1:
587 faces.pop(f_idx) # can't add single vert faces
589 # Face with a single item in face_vert_nor_indices is actually a polyline!
590 elif face_is_edge(face):
591 if use_edges:
592 edges.extend((face_vert_loc_indices[i], face_vert_loc_indices[i + 1])
593 for i in range(len_face_vert_loc_indices - 1))
594 faces.pop(f_idx)
596 else:
597 # Smooth Group
598 if unique_smooth_groups and context_smooth_group:
599 # Is a part of of a smooth group and is a face
600 if context_smooth_group_old is not context_smooth_group:
601 edge_dict = smooth_group_users[context_smooth_group]
602 context_smooth_group_old = context_smooth_group
604 prev_vidx = face_vert_loc_indices[-1]
605 for vidx in face_vert_loc_indices:
606 edge_key = (prev_vidx, vidx) if (prev_vidx < vidx) else (vidx, prev_vidx)
607 prev_vidx = vidx
608 edge_dict[edge_key] = edge_dict.get(edge_key, 0) + 1
610 # NGons into triangles
611 if face_invalid_blenpoly:
612 # ignore triangles with invalid indices
613 if len(face_vert_loc_indices) > 3:
614 from bpy_extras.mesh_utils import ngon_tessellate
615 ngon_face_indices = ngon_tessellate(verts_loc, face_vert_loc_indices, debug_print=bpy.app.debug)
616 faces.extend([([face_vert_loc_indices[ngon[0]],
617 face_vert_loc_indices[ngon[1]],
618 face_vert_loc_indices[ngon[2]],
620 [face_vert_nor_indices[ngon[0]],
621 face_vert_nor_indices[ngon[1]],
622 face_vert_nor_indices[ngon[2]],
623 ] if face_vert_nor_indices else [],
624 [face_vert_tex_indices[ngon[0]],
625 face_vert_tex_indices[ngon[1]],
626 face_vert_tex_indices[ngon[2]],
627 ] if face_vert_tex_indices else [],
628 context_material,
629 context_smooth_group,
630 context_object_key,
633 for ngon in ngon_face_indices]
635 tot_loops += 3 * len(ngon_face_indices)
637 # edges to make ngons
638 if len(ngon_face_indices) > 1:
639 edge_users = set()
640 for ngon in ngon_face_indices:
641 prev_vidx = face_vert_loc_indices[ngon[-1]]
642 for ngidx in ngon:
643 vidx = face_vert_loc_indices[ngidx]
644 if vidx == prev_vidx:
645 continue # broken OBJ... Just skip.
646 edge_key = (prev_vidx, vidx) if (prev_vidx < vidx) else (vidx, prev_vidx)
647 prev_vidx = vidx
648 if edge_key in edge_users:
649 fgon_edges.add(edge_key)
650 else:
651 edge_users.add(edge_key)
653 faces.pop(f_idx)
654 else:
655 tot_loops += len_face_vert_loc_indices
657 # Build sharp edges
658 if unique_smooth_groups:
659 for edge_dict in smooth_group_users.values():
660 for key, users in edge_dict.items():
661 if users == 1: # This edge is on the boundary of a group
662 sharp_edges.add(key)
664 # map the material names to an index
665 material_mapping = {name: i for i, name in enumerate(unique_materials)} # enumerate over unique_materials keys()
667 materials = [None] * len(unique_materials)
669 for name, index in material_mapping.items():
670 materials[index] = unique_materials[name]
672 me = bpy.data.meshes.new(dataname)
674 # make sure the list isn't too big
675 for material in materials:
676 me.materials.append(material)
678 me.vertices.add(len(verts_loc))
679 me.loops.add(tot_loops)
680 me.polygons.add(len(faces))
682 # verts_loc is a list of (x, y, z) tuples
683 me.vertices.foreach_set("co", unpack_list(verts_loc))
685 loops_vert_idx = tuple(vidx for (face_vert_loc_indices, _, _, _, _, _, _) in faces for vidx in face_vert_loc_indices)
686 faces_loop_start = []
687 lidx = 0
688 for f in faces:
689 face_vert_loc_indices = f[0]
690 nbr_vidx = len(face_vert_loc_indices)
691 faces_loop_start.append(lidx)
692 lidx += nbr_vidx
693 faces_loop_total = tuple(len(face_vert_loc_indices) for (face_vert_loc_indices, _, _, _, _, _, _) in faces)
695 me.loops.foreach_set("vertex_index", loops_vert_idx)
696 me.polygons.foreach_set("loop_start", faces_loop_start)
697 me.polygons.foreach_set("loop_total", faces_loop_total)
699 faces_ma_index = tuple(material_mapping[context_material] for (_, _, _, context_material, _, _, _) in faces)
700 me.polygons.foreach_set("material_index", faces_ma_index)
702 faces_use_smooth = tuple(bool(context_smooth_group) for (_, _, _, _, context_smooth_group, _, _) in faces)
703 me.polygons.foreach_set("use_smooth", faces_use_smooth)
705 if verts_nor and me.loops:
706 # Note: we store 'temp' normals in loops, since validate() may alter final mesh,
707 # we can only set custom lnors *after* calling it.
708 me.create_normals_split()
709 loops_nor = tuple(no for (_, face_vert_nor_indices, _, _, _, _, _) in faces
710 for face_noidx in face_vert_nor_indices
711 for no in verts_nor[face_noidx])
712 me.loops.foreach_set("normal", loops_nor)
714 if verts_tex and me.polygons:
715 # Some files Do not explicitly write the 'v' value when it's 0.0, see T68249...
716 verts_tex = [uv if len(uv) == 2 else uv + [0.0] for uv in verts_tex]
717 me.uv_layers.new(do_init=False)
718 loops_uv = tuple(uv for (_, _, face_vert_tex_indices, _, _, _, _) in faces
719 for face_uvidx in face_vert_tex_indices
720 for uv in verts_tex[face_uvidx])
721 me.uv_layers[0].data.foreach_set("uv", loops_uv)
723 use_edges = use_edges and bool(edges)
724 if use_edges:
725 me.edges.add(len(edges))
726 # edges should be a list of (a, b) tuples
727 me.edges.foreach_set("vertices", unpack_list(edges))
729 me.validate(clean_customdata=False) # *Very* important to not remove lnors here!
730 me.update(calc_edges=use_edges, calc_edges_loose=use_edges)
732 # Un-tessellate as much as possible, in case we had to triangulate some ngons...
733 if fgon_edges:
734 import bmesh
735 bm = bmesh.new()
736 bm.from_mesh(me)
737 verts = bm.verts[:]
738 get = bm.edges.get
739 edges = [get((verts[vidx1], verts[vidx2])) for vidx1, vidx2 in fgon_edges]
740 try:
741 bmesh.ops.dissolve_edges(bm, edges=edges, use_verts=False)
742 except:
743 # Possible dissolve fails for some edges, but don't fail silently in case this is a real bug.
744 import traceback
745 traceback.print_exc()
747 bm.to_mesh(me)
748 bm.free()
750 # XXX If validate changes the geometry, this is likely to be broken...
751 if unique_smooth_groups and sharp_edges:
752 for e in me.edges:
753 if e.key in sharp_edges:
754 e.use_edge_sharp = True
756 if verts_nor:
757 clnors = array.array('f', [0.0] * (len(me.loops) * 3))
758 me.loops.foreach_get("normal", clnors)
760 if not unique_smooth_groups:
761 me.polygons.foreach_set("use_smooth", [True] * len(me.polygons))
763 me.normals_split_custom_set(tuple(zip(*(iter(clnors),) * 3)))
764 me.use_auto_smooth = True
766 ob = bpy.data.objects.new(me.name, me)
767 new_objects.append(ob)
769 # Create the vertex groups. No need to have the flag passed here since we test for the
770 # content of the vertex_groups. If the user selects to NOT have vertex groups saved then
771 # the following test will never run
772 for group_name, group_indices in vertex_groups.items():
773 group = ob.vertex_groups.new(name=group_name.decode('utf-8', "replace"))
774 group.add(group_indices, 1.0, 'REPLACE')
777 def create_nurbs(context_nurbs, vert_loc, new_objects):
779 Add nurbs object to blender, only support one type at the moment
781 deg = context_nurbs.get(b'deg', (3,))
782 curv_range = context_nurbs.get(b'curv_range')
783 curv_idx = context_nurbs.get(b'curv_idx', [])
784 parm_u = context_nurbs.get(b'parm_u', [])
785 parm_v = context_nurbs.get(b'parm_v', [])
786 name = context_nurbs.get(b'name', b'ObjNurb')
787 cstype = context_nurbs.get(b'cstype')
789 if cstype is None:
790 print('\tWarning, cstype not found')
791 return
792 if cstype != b'bspline':
793 print('\tWarning, cstype is not supported (only bspline)')
794 return
795 if not curv_idx:
796 print('\tWarning, curv argument empty or not set')
797 return
798 if len(deg) > 1 or parm_v:
799 print('\tWarning, surfaces not supported')
800 return
802 cu = bpy.data.curves.new(name.decode('utf-8', "replace"), 'CURVE')
803 cu.dimensions = '3D'
805 nu = cu.splines.new('NURBS')
806 nu.points.add(len(curv_idx) - 1) # a point is added to start with
807 nu.points.foreach_set("co", [co_axis for vt_idx in curv_idx for co_axis in (vert_loc[vt_idx] + [1.0])])
809 nu.order_u = deg[0] + 1
811 # get for endpoint flag from the weighting
812 if curv_range and len(parm_u) > deg[0] + 1:
813 do_endpoints = True
814 for i in range(deg[0] + 1):
816 if abs(parm_u[i] - curv_range[0]) > 0.0001:
817 do_endpoints = False
818 break
820 if abs(parm_u[-(i + 1)] - curv_range[1]) > 0.0001:
821 do_endpoints = False
822 break
824 else:
825 do_endpoints = False
827 if do_endpoints:
828 nu.use_endpoint_u = True
830 # close
832 do_closed = False
833 if len(parm_u) > deg[0]+1:
834 for i in xrange(deg[0]+1):
835 #print curv_idx[i], curv_idx[-(i+1)]
837 if curv_idx[i]==curv_idx[-(i+1)]:
838 do_closed = True
839 break
841 if do_closed:
842 nu.use_cyclic_u = True
845 ob = bpy.data.objects.new(name.decode('utf-8', "replace"), cu)
847 new_objects.append(ob)
850 def strip_slash(line_split):
851 if line_split[-1][-1] == 92: # '\' char
852 if len(line_split[-1]) == 1:
853 line_split.pop() # remove the \ item
854 else:
855 line_split[-1] = line_split[-1][:-1] # remove the \ from the end last number
856 return True
857 return False
860 def get_float_func(filepath):
862 find the float function for this obj file
863 - whether to replace commas or not
865 file = open(filepath, 'rb')
866 for line in file: # .readlines():
867 line = line.lstrip()
868 if line.startswith(b'v'): # vn vt v
869 if b',' in line:
870 file.close()
871 return lambda f: float(f.replace(b',', b'.'))
872 elif b'.' in line:
873 file.close()
874 return float
876 file.close()
877 # in case all vert values were ints
878 return float
881 def any_number_as_int(svalue):
882 if b',' in svalue:
883 svalue = svalue.replace(b',', b'.')
884 return int(float(svalue))
887 def load(context,
888 filepath,
890 global_clamp_size=0.0,
891 use_smooth_groups=True,
892 use_edges=True,
893 use_split_objects=True,
894 use_split_groups=False,
895 use_image_search=True,
896 use_groups_as_vgroups=False,
897 relpath=None,
898 global_matrix=None
901 Called by the user interface or another script.
902 load_obj(path) - should give acceptable results.
903 This function passes the file and sends the data off
904 to be split into objects and then converted into mesh objects
906 def unique_name(existing_names, name_orig):
907 i = 0
908 if name_orig is None:
909 name_orig = b"ObjObject"
910 name = name_orig
911 while name in existing_names:
912 name = b"%s.%03d" % (name_orig, i)
913 i += 1
914 existing_names.add(name)
915 return name
917 def handle_vec(line_start, context_multi_line, line_split, tag, data, vec, vec_len):
918 ret_context_multi_line = tag if strip_slash(line_split) else b''
919 if line_start == tag:
920 vec[:] = [float_func(v) for v in line_split[1:]]
921 elif context_multi_line == tag:
922 vec += [float_func(v) for v in line_split]
923 if not ret_context_multi_line:
924 data.append(tuple(vec[:vec_len]))
925 return ret_context_multi_line
927 def create_face(context_material, context_smooth_group, context_object_key):
928 face_vert_loc_indices = []
929 face_vert_nor_indices = []
930 face_vert_tex_indices = []
931 return (
932 face_vert_loc_indices,
933 face_vert_nor_indices,
934 face_vert_tex_indices,
935 context_material,
936 context_smooth_group,
937 context_object_key,
938 [], # If non-empty, that face is a Blender-invalid ngon (holes...), need a mutable object for that...
941 with ProgressReport(context.window_manager) as progress:
942 progress.enter_substeps(1, "Importing OBJ %r..." % filepath)
944 if global_matrix is None:
945 global_matrix = mathutils.Matrix()
947 if use_split_objects or use_split_groups:
948 use_groups_as_vgroups = False
950 verts_loc = []
951 verts_nor = []
952 verts_tex = []
953 faces = [] # tuples of the faces
954 material_libs = set() # filenames to material libs this OBJ uses
955 vertex_groups = {} # when use_groups_as_vgroups is true
957 # Get the string to float conversion func for this file- is 'float' for almost all files.
958 float_func = get_float_func(filepath)
960 # Context variables
961 context_material = None
962 context_smooth_group = None
963 context_object_key = None
964 context_object_obpart = None
965 context_vgroup = None
967 objects_names = set()
969 # Nurbs
970 context_nurbs = {}
971 nurbs = []
972 context_parm = b'' # used by nurbs too but could be used elsewhere
974 # Until we can use sets
975 use_default_material = False
976 unique_materials = {}
977 unique_smooth_groups = {}
978 # unique_obects= {} - no use for this variable since the objects are stored in the face.
980 # when there are faces that end with \
981 # it means they are multiline-
982 # since we use xreadline we can't skip to the next line
983 # so we need to know whether
984 context_multi_line = b''
986 # Per-face handling data.
987 face_vert_loc_indices = None
988 face_vert_nor_indices = None
989 face_vert_tex_indices = None
990 verts_loc_len = verts_nor_len = verts_tex_len = 0
991 face_items_usage = set()
992 face_invalid_blenpoly = None
993 prev_vidx = None
994 face = None
995 vec = []
997 quick_vert_failures = 0
998 skip_quick_vert = False
1000 progress.enter_substeps(3, "Parsing OBJ file...")
1001 with open(filepath, 'rb') as f:
1002 for line in f:
1003 line_split = line.split()
1005 if not line_split:
1006 continue
1008 line_start = line_split[0] # we compare with this a _lot_
1010 if len(line_split) == 1 and not context_multi_line and line_start != b'end':
1011 print("WARNING, skipping malformatted line: %s" % line.decode('UTF-8', 'replace').rstrip())
1012 continue
1014 # Handling vertex data are pretty similar, factorize that.
1015 # Also, most OBJ files store all those on a single line, so try fast parsing for that first,
1016 # and only fallback to full multi-line parsing when needed, this gives significant speed-up
1017 # (~40% on affected code).
1018 if line_start == b'v':
1019 vdata, vdata_len, do_quick_vert = verts_loc, 3, not skip_quick_vert
1020 elif line_start == b'vn':
1021 vdata, vdata_len, do_quick_vert = verts_nor, 3, not skip_quick_vert
1022 elif line_start == b'vt':
1023 vdata, vdata_len, do_quick_vert = verts_tex, 2, not skip_quick_vert
1024 elif context_multi_line == b'v':
1025 vdata, vdata_len, do_quick_vert = verts_loc, 3, False
1026 elif context_multi_line == b'vn':
1027 vdata, vdata_len, do_quick_vert = verts_nor, 3, False
1028 elif context_multi_line == b'vt':
1029 vdata, vdata_len, do_quick_vert = verts_tex, 2, False
1030 else:
1031 vdata_len = 0
1033 if vdata_len:
1034 if do_quick_vert:
1035 try:
1036 vdata.append(list(map(float_func, line_split[1:vdata_len + 1])))
1037 except:
1038 do_quick_vert = False
1039 # In case we get too many failures on quick parsing, force fallback to full multi-line one.
1040 # Exception handling can become costly...
1041 quick_vert_failures += 1
1042 if quick_vert_failures > 10000:
1043 skip_quick_vert = True
1044 if not do_quick_vert:
1045 context_multi_line = handle_vec(line_start, context_multi_line, line_split,
1046 context_multi_line or line_start,
1047 vdata, vec, vdata_len)
1049 elif line_start == b'f' or context_multi_line == b'f':
1050 if not context_multi_line:
1051 line_split = line_split[1:]
1052 # Instantiate a face
1053 face = create_face(context_material, context_smooth_group, context_object_key)
1054 (face_vert_loc_indices, face_vert_nor_indices, face_vert_tex_indices,
1055 _1, _2, _3, face_invalid_blenpoly) = face
1056 faces.append(face)
1057 face_items_usage.clear()
1058 verts_loc_len = len(verts_loc)
1059 verts_nor_len = len(verts_nor)
1060 verts_tex_len = len(verts_tex)
1061 if context_material is None:
1062 use_default_material = True
1063 # Else, use face_vert_loc_indices and face_vert_tex_indices previously defined and used the obj_face
1065 context_multi_line = b'f' if strip_slash(line_split) else b''
1067 for v in line_split:
1068 obj_vert = v.split(b'/')
1069 idx = int(obj_vert[0]) # Note that we assume here we cannot get OBJ invalid 0 index...
1070 vert_loc_index = (idx + verts_loc_len) if (idx < 1) else idx - 1
1071 # Add the vertex to the current group
1072 # *warning*, this wont work for files that have groups defined around verts
1073 if use_groups_as_vgroups and context_vgroup:
1074 vertex_groups[context_vgroup].append(vert_loc_index)
1075 # This a first round to quick-detect ngons that *may* use a same edge more than once.
1076 # Potential candidate will be re-checked once we have done parsing the whole face.
1077 if not face_invalid_blenpoly:
1078 # If we use more than once a same vertex, invalid ngon is suspected.
1079 if vert_loc_index in face_items_usage:
1080 face_invalid_blenpoly.append(True)
1081 else:
1082 face_items_usage.add(vert_loc_index)
1083 face_vert_loc_indices.append(vert_loc_index)
1085 # formatting for faces with normals and textures is
1086 # loc_index/tex_index/nor_index
1087 if len(obj_vert) > 1 and obj_vert[1] and obj_vert[1] != b'0':
1088 idx = int(obj_vert[1])
1089 face_vert_tex_indices.append((idx + verts_tex_len) if (idx < 1) else idx - 1)
1090 else:
1091 face_vert_tex_indices.append(0)
1093 if len(obj_vert) > 2 and obj_vert[2] and obj_vert[2] != b'0':
1094 idx = int(obj_vert[2])
1095 face_vert_nor_indices.append((idx + verts_nor_len) if (idx < 1) else idx - 1)
1096 else:
1097 face_vert_nor_indices.append(0)
1099 if not context_multi_line:
1100 # Means we have finished a face, we have to do final check if ngon is suspected to be blender-invalid...
1101 if face_invalid_blenpoly:
1102 face_invalid_blenpoly.clear()
1103 face_items_usage.clear()
1104 prev_vidx = face_vert_loc_indices[-1]
1105 for vidx in face_vert_loc_indices:
1106 edge_key = (prev_vidx, vidx) if (prev_vidx < vidx) else (vidx, prev_vidx)
1107 if edge_key in face_items_usage:
1108 face_invalid_blenpoly.append(True)
1109 break
1110 face_items_usage.add(edge_key)
1111 prev_vidx = vidx
1113 elif use_edges and (line_start == b'l' or context_multi_line == b'l'):
1114 # very similar to the face load function above with some parts removed
1115 if not context_multi_line:
1116 line_split = line_split[1:]
1117 # Instantiate a face
1118 face = create_face(context_material, context_smooth_group, context_object_key)
1119 face_vert_loc_indices = face[0]
1120 # XXX A bit hackish, we use special 'value' of face_vert_nor_indices (a single True item) to tag this
1121 # as a polyline, and not a regular face...
1122 face[1][:] = [True]
1123 faces.append(face)
1124 if context_material is None:
1125 use_default_material = True
1126 # Else, use face_vert_loc_indices previously defined and used the obj_face
1128 context_multi_line = b'l' if strip_slash(line_split) else b''
1130 for v in line_split:
1131 obj_vert = v.split(b'/')
1132 idx = int(obj_vert[0]) - 1
1133 face_vert_loc_indices.append((idx + len(verts_loc) + 1) if (idx < 0) else idx)
1135 elif line_start == b's':
1136 if use_smooth_groups:
1137 context_smooth_group = line_value(line_split)
1138 if context_smooth_group == b'off':
1139 context_smooth_group = None
1140 elif context_smooth_group: # is not None
1141 unique_smooth_groups[context_smooth_group] = None
1143 elif line_start == b'o':
1144 if use_split_objects:
1145 context_object_key = unique_name(objects_names, line_value(line_split))
1146 context_object_obpart = context_object_key
1147 # unique_objects[context_object_key]= None
1149 elif line_start == b'g':
1150 if use_split_groups:
1151 grppart = line_value(line_split)
1152 context_object_key = (context_object_obpart, grppart) if context_object_obpart else grppart
1153 # print 'context_object_key', context_object_key
1154 # unique_objects[context_object_key]= None
1155 elif use_groups_as_vgroups:
1156 context_vgroup = line_value(line.split())
1157 if context_vgroup and context_vgroup != b'(null)':
1158 vertex_groups.setdefault(context_vgroup, [])
1159 else:
1160 context_vgroup = None # dont assign a vgroup
1162 elif line_start == b'usemtl':
1163 context_material = line_value(line.split())
1164 unique_materials[context_material] = None
1165 elif line_start == b'mtllib': # usemap or usemat
1166 # can have multiple mtllib filenames per line, mtllib can appear more than once,
1167 # so make sure only occurrence of material exists
1168 material_libs |= {os.fsdecode(f) for f in filenames_group_by_ext(line.lstrip()[7:].strip(), b'.mtl')
1171 # Nurbs support
1172 elif line_start == b'cstype':
1173 context_nurbs[b'cstype'] = line_value(line.split()) # 'rat bspline' / 'bspline'
1174 elif line_start == b'curv' or context_multi_line == b'curv':
1175 curv_idx = context_nurbs[b'curv_idx'] = context_nurbs.get(b'curv_idx', []) # in case were multiline
1177 if not context_multi_line:
1178 context_nurbs[b'curv_range'] = float_func(line_split[1]), float_func(line_split[2])
1179 line_split[0:3] = [] # remove first 3 items
1181 if strip_slash(line_split):
1182 context_multi_line = b'curv'
1183 else:
1184 context_multi_line = b''
1186 for i in line_split:
1187 vert_loc_index = int(i) - 1
1189 if vert_loc_index < 0:
1190 vert_loc_index = len(verts_loc) + vert_loc_index + 1
1192 curv_idx.append(vert_loc_index)
1194 elif line_start == b'parm' or context_multi_line == b'parm':
1195 if context_multi_line:
1196 context_multi_line = b''
1197 else:
1198 context_parm = line_split[1]
1199 line_split[0:2] = [] # remove first 2
1201 if strip_slash(line_split):
1202 context_multi_line = b'parm'
1203 else:
1204 context_multi_line = b''
1206 if context_parm.lower() == b'u':
1207 context_nurbs.setdefault(b'parm_u', []).extend([float_func(f) for f in line_split])
1208 elif context_parm.lower() == b'v': # surfaces not supported yet
1209 context_nurbs.setdefault(b'parm_v', []).extend([float_func(f) for f in line_split])
1210 # else: # may want to support other parm's ?
1212 elif line_start == b'deg':
1213 context_nurbs[b'deg'] = [int(i) for i in line.split()[1:]]
1214 elif line_start == b'end':
1215 # Add the nurbs curve
1216 if context_object_key:
1217 context_nurbs[b'name'] = context_object_key
1218 nurbs.append(context_nurbs)
1219 context_nurbs = {}
1220 context_parm = b''
1222 ''' # How to use usemap? deprecated?
1223 elif line_start == b'usema': # usemap or usemat
1224 context_image= line_value(line_split)
1227 progress.step("Done, loading materials and images...")
1229 if use_default_material:
1230 unique_materials[None] = None
1231 create_materials(filepath, relpath, material_libs, unique_materials,
1232 use_image_search, float_func)
1234 progress.step("Done, building geometries (verts:%i faces:%i materials: %i smoothgroups:%i) ..." %
1235 (len(verts_loc), len(faces), len(unique_materials), len(unique_smooth_groups)))
1237 # deselect all
1238 if bpy.ops.object.select_all.poll():
1239 bpy.ops.object.select_all(action='DESELECT')
1241 new_objects = [] # put new objects here
1243 # Split the mesh by objects/materials, may
1244 SPLIT_OB_OR_GROUP = bool(use_split_objects or use_split_groups)
1246 for data in split_mesh(verts_loc, faces, unique_materials, filepath, SPLIT_OB_OR_GROUP):
1247 verts_loc_split, faces_split, unique_materials_split, dataname, use_vnor, use_vtex = data
1248 # Create meshes from the data, warning 'vertex_groups' wont support splitting
1249 #~ print(dataname, use_vnor, use_vtex)
1250 create_mesh(new_objects,
1251 use_edges,
1252 verts_loc_split,
1253 verts_nor if use_vnor else [],
1254 verts_tex if use_vtex else [],
1255 faces_split,
1256 unique_materials_split,
1257 unique_smooth_groups,
1258 vertex_groups,
1259 dataname,
1262 # nurbs support
1263 for context_nurbs in nurbs:
1264 create_nurbs(context_nurbs, verts_loc, new_objects)
1266 view_layer = context.view_layer
1267 collection = view_layer.active_layer_collection.collection
1269 # Create new obj
1270 for obj in new_objects:
1271 collection.objects.link(obj)
1272 obj.select_set(True)
1274 # we could apply this anywhere before scaling.
1275 obj.matrix_world = global_matrix
1277 view_layer.update()
1279 axis_min = [1000000000] * 3
1280 axis_max = [-1000000000] * 3
1282 if global_clamp_size:
1283 # Get all object bounds
1284 for ob in new_objects:
1285 for v in ob.bound_box:
1286 for axis, value in enumerate(v):
1287 if axis_min[axis] > value:
1288 axis_min[axis] = value
1289 if axis_max[axis] < value:
1290 axis_max[axis] = value
1292 # Scale objects
1293 max_axis = max(axis_max[0] - axis_min[0], axis_max[1] - axis_min[1], axis_max[2] - axis_min[2])
1294 scale = 1.0
1296 while global_clamp_size < max_axis * scale:
1297 scale = scale / 10.0
1299 for obj in new_objects:
1300 obj.scale = scale, scale, scale
1302 progress.leave_substeps("Done.")
1303 progress.leave_substeps("Finished importing: %r" % filepath)
1305 return {'FINISHED'}