def process_geojson_features(geojson_features, raster, header, csvfile): """Using a raster input, get values of a raster at features in geojson. Output the final points and depths to a csv file.""" # write to csv file as depth found csv_writer = csv.writer(csvfile) csv_writer.writerow(header) # provide progress whilst processing: number given is the total number of features in the cruise track number_features_to_process = len(geojson_features) progress_report = ProgressReport(number_features_to_process) # process each of the shapefiles for feature in geojson_features: # get point values from raster at points in shapefile result = rasterstats.gen_point_query(feature, raster, geojson_out=True) # for each value obtained from the raster, output a line into a csvfile for r in result: csv_writer.writerow([ r['properties']['date_time'], r.geometry.coordinates[1], r.geometry.coordinates[0], r['properties']['value'] ]) progress_report.increment_and_print_if_needed()
def load_materials(progress: ProgressReport, manager: ImportManager) -> List[bpy.types.Material]: progress.enter_substeps(len(manager.gltf.textures), "Loading materials...") materials = [ _create_material(progress, manager, material) for material in manager.gltf.materials ] progress.leave_substeps() return materials
def load_meshes( progress: ProgressReport, manager: ImportManager ) -> List[Tuple[bpy.types.Mesh, gltf_buffer.VertexBuffer]]: progress.enter_substeps(len(manager.gltf.meshes), "Loading meshes...") meshes = [ _create_mesh(progress, manager, mesh) for mesh in manager.gltf.meshes ] progress.leave_substeps() return meshes
def create_object(self, progress: ProgressReport, collection: bpy.types.Collection, manager: import_manager.ImportManager)->None: # create object if self.gltf_node.mesh != -1: self.blender_object = bpy.data.objects.new( self.name, manager.meshes[self.gltf_node.mesh][0]) else: # empty self.blender_object = bpy.data.objects.new(self.name, None) self.blender_object.empty_display_size = 0.1 # self.blender_object.empty_draw_type = 'PLAIN_AXES' collection.objects.link(self.blender_object) self.blender_object.select_set("SELECT") self.blender_object['js'] = json.dumps(self.gltf_node.js, indent=2) # parent if self.parent: self.blender_object.parent = self.parent.blender_object if self.gltf_node.translation: self.blender_object.location = manager.mod_v( self.gltf_node.translation) if self.gltf_node.rotation: r = self.gltf_node.rotation q = mathutils.Quaternion((r[3], r[0], r[1], r[2])) with tmp_mode(self.blender_object, 'QUATERNION'): self.blender_object.rotation_quaternion = manager.mod_q(q) if self.gltf_node.scale: s = self.gltf_node.scale self.blender_object.scale = (s[0], s[2], s[1]) if self.gltf_node.matrix: m = self.gltf_node.matrix matrix = mathutils.Matrix(( (m[0], m[4], m[8], m[12]), (m[1], m[5], m[9], m[13]), (m[2], m[6], m[10], m[14]), (m[3], m[7], m[11], m[15]) )) t, q, s = matrix.decompose() self.blender_object.location = manager.mod_v(t) with tmp_mode(self.blender_object, 'QUATERNION'): self.blender_object.rotation_quaternion = manager.mod_q(q) self.blender_object.scale = (s[0], s[2], s[1]) progress.step() for child in self.children: child.create_object(progress, collection, manager)
def load(self, context, filepath=""): ob = bpy.context.object if ob.type != 'ARMATURE': return "An armature must be selected!" path = os.path.dirname(filepath) path = os.path.normpath(path) try: ob.animation_data.action except: ob.animation_data_create() with ProgressReport(context.window_manager) as progress: # Begin the progress counter with 1 step for each file progress.enter_substeps(len(self.files)) # Force all bones to use quaternion rotation # (Must be included or bone.rotation_quaternion won't update # properly when setting the matrix directly) for bone in ob.pose.bones.data.bones: bone.rotation_mode = 'QUATERNION' for f in self.files: progress.enter_substeps(1, f.name) try: anim_path = os.path.normpath(os.path.join(path, f.name)) load_seanim(self, context, progress, anim_path) except Exception as e: progress.leave_substeps("ERROR: " + repr(e)) else: progress.leave_substeps() # Print when all files have been imported progress.leave_substeps("Finished!")
def _create_mesh( progress: ProgressReport, manager: ImportManager, mesh: gltftypes.Mesh ) -> Tuple[bpy.types.Mesh, gltf_buffer.VertexBuffer]: blender_mesh = bpy.data.meshes.new(mesh.name) materials = [manager.materials[prim.material] for prim in mesh.primitives] for m in materials: blender_mesh.materials.append(m) attributes = gltf_buffer.VertexBuffer(manager, mesh) blender_mesh.vertices.add(len(attributes.pos) / 3) blender_mesh.vertices.foreach_set("co", attributes.pos) blender_mesh.vertices.foreach_set("normal", attributes.nom) blender_mesh.loops.add(len(attributes.indices)) blender_mesh.loops.foreach_set("vertex_index", attributes.indices) triangle_count = int(len(attributes.indices) / 3) blender_mesh.polygons.add(triangle_count) starts = [i * 3 for i in range(triangle_count)] blender_mesh.polygons.foreach_set("loop_start", starts) total = [3 for _ in range(triangle_count)] blender_mesh.polygons.foreach_set("loop_total", total) blen_uvs = blender_mesh.uv_layers.new() for blen_poly in blender_mesh.polygons: blen_poly.use_smooth = True blen_poly.material_index = attributes.get_submesh_from_face( blen_poly.index) for lidx in blen_poly.loop_indices: index = attributes.indices[lidx] # vertex uv to face uv uv = attributes.uv[index] blen_uvs.data[lidx].uv = (uv.x, uv.y) # vertical flip uv # *Very* important to not remove lnors here! blender_mesh.validate(clean_customdata=False) blender_mesh.update() progress.step() return blender_mesh, attributes
def load(context, filepath: str, yup_to_zup: bool) -> Set[str]: path = pathlib.Path(filepath) if not path.exists(): return {'CANCELLED'} with ProgressReport(context.window_manager) as progress: progress.enter_substeps(5, "Importing GLTF %r..." % path.name) body = b'' try: with path.open('rb') as f: ext = path.suffix.lower() if ext == '.gltf': gltf = gltftypes.from_json(json.load(f)) elif ext == '.glb' or ext == '.vrm': gltf, body = glb.parse_glb(f.read()) else: logger.error("%s is not supported", ext) return {'CANCELLED'} except Exception as ex: # pylint: disable=w0703 logger.error("%s", ex) return {'CANCELLED'} manager = ImportManager(path, gltf, body, yup_to_zup) manager.textures.extend(load_textures(progress, manager)) manager.materials.extend(load_materials(progress, manager)) manager.meshes.extend(load_meshes(progress, manager)) nodes, root = load_objects(context, progress, manager) # skinning armature_object = next(node for node in root.traverse() if node.blender_armature) for node in nodes: if node.gltf_node.mesh != -1 and node.gltf_node.skin != -1: _, attributes = manager.meshes[node.gltf_node.mesh] skin = gltf.skins[node.gltf_node.skin] bone_names = [nodes[joint].bone_name for joint in skin.joints] #armature_object =nodes[skin.skeleton].blender_armature _setup_skinning(node.blender_object, attributes, bone_names, armature_object.blender_armature) # remove empties _remove_empty(root) # done context.scene.update() progress.leave_substeps("Finished") return {'FINISHED'}
def save(context, filepath, use_selection=True, provides_mtl=False): with ProgressReport(context.window_manager) as progress: scene = context.scene # Exit edit mode before exporting, so current object states are exported properly. if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') objects = context.selected_objects if use_selection else scene.objects progress.enter_substeps(1) write_file(context, filepath, objects, scene, provides_mtl, progress) progress.leave_substeps() return {'FINISHED'}
def _write( context, filepath, EXPORT_SEL_ONLY, # ok EXPORT_GLOBAL_MATRIX, EXPORT_PATH_MODE, # Not used ): with ProgressReport(context.window_manager) as progress: base_name, ext = os.path.splitext(filepath) context_name = [base_name, '', '', ext] # Base name, scene name, frame number, extension scene = context.scene # Exit edit mode before exporting, so current object states are exported properly. if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') orig_frame = scene.frame_current scene_frames = [orig_frame] # Dont export an animation. # Loop through all frames in the scene and export. progress.enter_substeps(len(scene_frames)) for frame in scene_frames: scene.frame_set(frame, 0.0) if EXPORT_SEL_ONLY: objects = context.selected_objects else: objects = scene.objects full_path = ''.join(context_name) progress.enter_substeps(1) write_file( full_path, objects, scene, EXPORT_GLOBAL_MATRIX, EXPORT_PATH_MODE, progress, ) progress.leave_substeps() scene.frame_set(orig_frame, 0.0) progress.leave_substeps()
def load(operator, context, filepath=""): with ProgressReport(context.window_manager) as progress: progress.enter_substeps(3, "Importing \'%s\' ..." % filepath) mainLoader = GR2Loader(filepath) progress.step("Parsing file ...", 1) mainLoader.parse(operator) progress.step("Done, building ...", 2) if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT', toggle=False) mainLoader.build(operator.import_collision) progress.leave_substeps("Done, finished importing: \'%s\'" % filepath) return {'FINISHED'}
def save(self, context): ob = bpy.context.object if ob.type != 'ARMATURE': return "An armature must be selected!" prefix = self.prefix # os.path.basename(self.filepath) suffix = self.suffix path = os.path.dirname(self.filepath) path = os.path.normpath(path) # Gets automatically updated per-action if self.use_actions is true, # otherwise it stays the same filepath = self.filepath with ProgressReport(context.window_manager) as progress: actions = [] if self.use_actions: actions = bpy.data.actions else: actions = [bpy.context.object.animation_data.action] progress.enter_substeps(len(actions)) for action in actions: if self.use_actions: filename = prefix + action.name + suffix + ".seanim" filepath = os.path.normpath(os.path.join(path, filename)) progress.enter_substeps(1, action.name) try: export_action(self, context, progress, action, filepath) except Exception as e: progress.leave_substeps("ERROR: " + repr(e)) else: progress.leave_substeps() progress.leave_substeps("Finished!")
def write_file( filepath, objects, scene, EXPORT_GLOBAL_MATRIX=None, EXPORT_PATH_MODE='AUTO', progress=ProgressReport(), ): from io_scene_forsaken import forsaken_utils if EXPORT_GLOBAL_MATRIX is None: EXPORT_GLOBAL_MATRIX = mathutils.Matrix() # ----------------------------------------------------------------------------- # create a new file file = open(filepath, "w", encoding="utf8", newline="\n") fw = file.write fw('// Generated Forsaken Level Data for Kex Engine\n') fw('// DO NOT MODIFY!\n\n') # ----------------------------------------------------------------------------- # iterate each scene object for i, ob_main in enumerate(objects): if ob_main.parent and ob_main.parent.dupli_type in {'VERTS', 'FACES'}: continue obs = [(ob_main, ob_main.matrix_world)] # ----------------------------------------------------------------------------- # iterate every mesh for ob, ob_mat in obs: if object_is_actor(ob): parse_actor(fw, ob, EXPORT_GLOBAL_MATRIX, scene) continue name1 = ob.name name2 = ob.data.name #if name1 == name2: # obnamestring = name_compat(name1) #else: # obnamestring = '%s_%s' % (name_compat(name1), name_compat(name2)) obnamestring = name_compat(name1) # ----------------------------------------------------------------------------- # set the name of this group fw('group \"%s\"' % obnamestring) fw(' // %i\n' % i) axis = get_group_axis(ob, EXPORT_GLOBAL_MATRIX) fw('orientation %.6f %.6f %.6f\n' % axis[:]) fw('waterType %i\n' % get_enum_type( bpy.types.Object.groupWaterType, ob.groupWaterType)) fw('soundDistanceScale %f\n' % ob.groupSoundDistScale) fw('caustics_red %f\n' % ob.groupCausticColor[0]) fw('caustics_green %f\n' % ob.groupCausticColor[1]) fw('caustics_blue %f\n' % ob.groupCausticColor[2]) try: mesh = ob.to_mesh(scene, True, 'PREVIEW') except RuntimeError: mesh = None if mesh is None: continue #print('processing group ', ob.name) mesh.transform(EXPORT_GLOBAL_MATRIX * ob_mat) #forsaken_utils.mesh_triangulate(mesh) if not mesh.tessfaces and mesh.polygons: mesh.calc_tessface() faceuv = len(mesh.uv_textures) > 0 has_materials = len(mesh.materials) > 0 if faceuv: uv_texture = mesh.uv_textures.active.data[:] uv_layer = mesh.uv_layers.active.data[:] mesh_verts = mesh.vertices has_uv = bool(mesh.tessface_uv_textures) has_vcol = bool(mesh.tessface_vertex_colors) use_uv_coords = True # ----------------------------------------------------------------------------- # get uv layer if has_uv: active_uv_layer = mesh.tessface_uv_textures.active if not active_uv_layer: has_uv = False else: active_uv_layer = active_uv_layer.data # ----------------------------------------------------------------------------- # get color layer if has_vcol: active_col_layer = mesh.tessface_vertex_colors.active if not active_col_layer: has_vcol = False else: active_col_layer = active_col_layer.data try: bpy.ops.object.mode_set(mode='OBJECT') scene.objects.active = ob me = ob.data ob.select = True bpy.ops.object.mode_set(mode='EDIT') bm = bmesh.from_edit_mesh(me) bm.faces.ensure_lookup_table() ignoreBspLayer = bm.faces.layers.int.get("ignore_bsp") transparentLayer = bm.faces.layers.int.get("transparent") animInstanceLayer = bm.faces.layers.string.get("animInstance") # ----------------------------------------------------------------------------- # iterate polygons for i, f in enumerate(mesh.polygons): f_verts = f.vertices bFixFace = False # for some bizzare reason, quads referencing vertex indexes of zero results in # the UV and color indexes being in the incorrect order. this will check for this # bug and correct it when writing out the face information for j, vidx in enumerate(f_verts): # check only if zero vertex index is the 3rd or 4th indice if vidx == 0 and j >= 2 and len(f_verts) >= 4: bFixFace = True break if uv_texture[f.index].image is None or has_uv == False: continue if has_uv: uv = active_uv_layer[i] uv = uv.uv1, uv.uv2, uv.uv3, uv.uv4 if has_vcol: col = active_col_layer[i] col = col.color1[:], col.color2[:], col.color3[:], col.color4[:] # ----------------------------------------------------------------------------- # write out a new face block fw('face %i ' % len(f_verts)) fw('\"%s\" ' % uv_texture[f.index].image.filepath) if ignoreBspLayer is not None or transparentLayer is not None or animInstanceLayer is not None: bmf = bm.faces[f.index] if ignoreBspLayer is None: fw('0 ') else: fw('%i ' % bmf[ignoreBspLayer]) if transparentLayer is None: fw('0 ') else: fw('%i ' % bmf[transparentLayer]) if animInstanceLayer is None: fw('\"\" ') else: fw('\"%s\" ' % bmf[animInstanceLayer].decode("utf-8")) else: fw('0 0 \"\"') fw(' // %i\n' % f.index) fw('{') for j, vidx in enumerate(f_verts): v = mesh_verts[vidx] idx = j if bFixFace: # offset the index to fix the bizzare bug idx = (j + 2) % len(f_verts) if has_uv: uvcoord = uv[idx][0], uv[idx][1] else: uvcoord = 0.0, 0.0 if has_vcol: color = col[idx] color = ( int(color[0] * 255.0), int(color[1] * 255.0), int(color[2] * 255.0), ) else: color = 255, 255, 255 fw('\n %.6f %.6f %.6f ' % v.co[:]) fw('%.6f ' % uvcoord[0]) fw('%.6f ' % uvcoord[1]) fw('%u ' % color[0]) fw('%u ' % color[1]) fw('%u ' % color[2]) fw('// %i' % f_verts[idx]) fw('\n}\n\n') bpy.ops.object.mode_set(mode='OBJECT') ob.select = False except RuntimeError: file.close() return file.close()
def load(context, filepath): with ProgressReport(context.window_manager) as progress: progress.enter_substeps(1, "Importing ADT OBJ %r..." % filepath) csvpath = filepath.replace('.obj', '_ModelPlacementInformation.csv') # Coordinate setup ## WoW coordinate sytem # Max Size: 51200 / 3 = 17066,66666666667 # Map Size: Max Size * 2 = 34133,33333333333 # ADT Size: Map Size / 64 = 533,3333333333333 max_size = 51200 / 3 map_size = max_size * 2 adt_size = map_size / 64 base_folder, adtname = os.path.split(filepath) adtsplit = adtname.split("_") mapname = adtsplit[0] map_x = int(adtsplit[1]) map_y = int(adtsplit[2].replace(".obj", "")) print(mapname) print(map_x) print(map_y) offset_x = adt_size * map_x offset_y = adt_size * map_y print(offset_x) print(offset_y) # Import ADT bpy.ops.import_scene.obj(filepath=filepath) adtObject = bpy.data.objects[mapname + '_' + str(map_x) + '_' + str(map_y)] # Make shader sane and fix UV clamping (Kruithne) for mat_slot in adtObject.material_slots: node_tree = mat_slot.material.node_tree nodes = node_tree.nodes for node in nodes: if node.name != 'Image Texture' and node.name != 'Material Output' and node.name != 'Diffuse BSDF': node_tree.nodes.remove(node) node_tree.links.new(nodes['Image Texture'].outputs[0], nodes['Diffuse BSDF'].inputs[0]) node_tree.links.new(nodes['Diffuse BSDF'].outputs[0], nodes['Material Output'].inputs[0]) imageNode = nodes['Image Texture'] imageNode.extension = 'EXTEND' imageNode.image.use_alpha = False bpy.ops.object.add(type='EMPTY') doodadparent = bpy.context.active_object doodadparent.parent = adtObject doodadparent.name = "Doodads" doodadparent.rotation_euler = [0, 0, 0] doodadparent.rotation_euler.x = radians(-90) bpy.ops.object.add(type='EMPTY') wmoparent = bpy.context.active_object wmoparent.parent = adtObject wmoparent.name = "WMOs" wmoparent.rotation_euler = [0, 0, 0] wmoparent.rotation_euler.x = radians(-90) # Make object active # bpy.context.scene.objects.active = obj # Read doodad definitions file with open(csvpath) as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for row in reader: doodad_path, doodad_filename = os.path.split(filepath) newpath = os.path.join(doodad_path, row['ModelFile']) if row['Type'] == 'wmo': bpy.ops.object.add(type='EMPTY') parent = bpy.context.active_object parent.name = row['ModelFile'] parent.parent = wmoparent parent.location = (17066 - float(row['PositionX']), (17066 - float(row['PositionZ'])) * -1, float(row['PositionY'])) parent.rotation_euler = [0, 0, 0] #obj.rotation_euler.x += (radians(90 + float(row['RotationX']))) # TODO #obj.rotation_euler.y -= radians(float(row['RotationY'])) # TODO parent.rotation_euler.z = radians( (-90 + float(row['RotationY']))) if row['ScaleFactor']: parent.scale = (float(row['ScaleFactor']), float(row['ScaleFactor']), float(row['ScaleFactor'])) bpy.ops.import_scene.obj(filepath=newpath) obj_objects = bpy.context.selected_objects[:] # Put ADT rotations in here for obj in obj_objects: obj.parent = parent wmocsvpath = newpath.replace( '.obj', '_ModelPlacementInformation.csv') # Read WMO doodads definitions file with open(wmocsvpath) as wmocsvfile: wmoreader = csv.DictReader(wmocsvfile, delimiter=';') for wmorow in wmoreader: wmodoodad_path, wmodoodad_filename = os.path.split( filepath) wmonewpath = os.path.join(wmodoodad_path, wmorow['ModelFile']) # Import the doodad if (os.path.exists(wmonewpath)): bpy.ops.import_scene.obj(filepath=wmonewpath) # Select the imported doodad wmoobj_objects = bpy.context.selected_objects[:] for wmoobj in wmoobj_objects: # Prepend name wmoobj.name = "(" + wmorow[ 'DoodadSet'] + ") " + wmoobj.name # Set parent wmoobj.parent = parent # Set position wmoobj.location = ( float(wmorow['PositionX']) * -1, float(wmorow['PositionY']) * -1, float(wmorow['PositionZ'])) # Set rotation rotQuat = Quaternion( (float(wmorow['RotationW']), float(wmorow['RotationX']), float(wmorow['RotationY']), float(wmorow['RotationZ']))) rotEul = rotQuat.to_euler() rotEul.x += radians(90) rotEul.z += radians(180) wmoobj.rotation_euler = rotEul # Set scale if wmorow['ScaleFactor']: wmoobj.scale = ( float(wmorow['ScaleFactor']), float(wmorow['ScaleFactor']), float(wmorow['ScaleFactor'])) # Duplicate material removal script by Kruithne # Merge all duplicate materials # for obj in bpy.context.scene.objects: # if obj.type == 'MESH': # i = 0 # for mat_slot in obj.material_slots: # mat = mat_slot.material # obj.material_slots[i].material = bpy.data.materials[mat.name.split('.')[0]] # i += 1 # # Cleanup unused materials # for img in bpy.data.images: # if not img.users: # bpy.data.images.remove(img) else: if (os.path.exists(newpath)): bpy.ops.import_scene.obj(filepath=newpath) obj_objects = bpy.context.selected_objects[:] for obj in obj_objects: # Set parent obj.parent = doodadparent # Set location obj.location.x = (17066 - float(row['PositionX'])) obj.location.y = (17066 - float(row['PositionZ'])) * -1 obj.location.z = float(row['PositionY']) obj.rotation_euler.x += radians( float(row['RotationZ'])) obj.rotation_euler.y += radians( float(row['RotationX'])) obj.rotation_euler.z = radians( 90 + float(row['RotationY'])) # okay # Set scale if row['ScaleFactor']: obj.scale = (float(row['ScaleFactor']), float(row['ScaleFactor']), float(row['ScaleFactor'])) # Set doodad and WMO parent to 0 wmoparent.location = (0, 0, 0) doodadparent.location = (0, 0, 0) print("Deduplicating and cleaning up materials!") # Duplicate material removal script by Kruithne # Merge all duplicate materials for obj in bpy.context.scene.objects: if obj.type == 'MESH': i = 0 for mat_slot in obj.material_slots: mat = mat_slot.material obj.material_slots[i].material = bpy.data.materials[ mat.name.split('.')[0]] i += 1 # Cleanup unused materials for img in bpy.data.images: if not img.users: bpy.data.images.remove(img) progress.leave_substeps("Finished importing: %r" % filepath) return {'FINISHED'}
def load(context, filepath ): with ProgressReport(context.window_manager) as progress: progress.enter_substeps(1, "Importing WMO OBJ %r..." % filepath) csvpath = filepath.replace('.obj', '_ModelPlacementInformation.csv') bpy.ops.import_scene.obj(filepath=filepath) # Duplicate material removal script by Kruithne # Merge all duplicate materials for obj in bpy.context.scene.objects: if obj.type == 'MESH': i = 0 for mat_slot in obj.material_slots: mat = mat_slot.material obj.material_slots[i].material = bpy.data.materials[mat.name.split('.')[0]] i += 1 # Cleanup unused materials for img in bpy.data.images: if not img.users: bpy.data.images.remove(img) # Select the imported WMO obj_objects = bpy.context.selected_objects[:] for obj in obj_objects: obj.rotation_euler = [0, 0, 0] obj.rotation_euler.x += radians(90) obj.rotation_euler.z -= radians(90) # Read doodad definitions file with open(csvpath) as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for row in reader: doodad_path, doodad_filename = os.path.split(filepath) newpath = os.path.join(doodad_path, row['ModelFile']) # Import the doodad bpy.ops.import_scene.obj(filepath=newpath) # Select the imported doodad obj_objects = bpy.context.selected_objects[:] for obj in obj_objects: # Print object name # print (obj.name) # Prepend name obj.name = "(" + row['DoodadSet'] + ") " + obj.name # Set position obj.location = (float(row['PositionY']) * -1, float(row['PositionX']), float(row['PositionZ'])) # Set rotation rotQuat = Quaternion((float(row['RotationW']), float(row['RotationX']), float(row['RotationY']), float(row['RotationZ']))) rotEul = rotQuat.to_euler() rotEul.x += radians(90); rotEul.z += radians(90); obj.rotation_euler = rotEul # Set scale if row['ScaleFactor']: obj.scale = (float(row['ScaleFactor']), float(row['ScaleFactor']), float(row['ScaleFactor'])) # Duplicate material removal script by Kruithne # Merge all duplicate materials for obj in bpy.context.scene.objects: if obj.type == 'MESH': i = 0 for mat_slot in obj.material_slots: mat = mat_slot.material obj.material_slots[i].material = bpy.data.materials[mat.name.split('.')[0]] i += 1 # Cleanup unused materials for img in bpy.data.images: if not img.users: bpy.data.images.remove(img) progress.leave_substeps("Finished importing: %r" % filepath) return {'FINISHED'}
def load(self, context, filepath, *, import_skeleton=True, skeleton_auto_connect=True, import_animations=False, scale_factor=1.0, use_cycles=True, relpath=None, global_matrix=None): """ Called by the use interface or another script. load_cgf(path) - should give acceptable result. This function passes the file and sends the data off to be split into objects and then converted into mesh objects """ self.filepath = filepath self.armature_auto_connect = skeleton_auto_connect self.scale_factor = scale_factor if self.filepath.endswith('.caf'): self.load_animation() return {'FINISHED'} with ProgressReport(context.window_manager) as progress: progress.enter_substeps( 1, "Importing CGF %r ... relpath: %r" % (filepath, relpath)) if global_matrix is None: global_matrix = Matrix() time_main = time.time() b_mats = [] progress.enter_substeps(1, "Parsing CGF file ...") with open(filepath, 'rb') as f: data = CgfFormat.Data() # check if cgf file is valid try: data.inspect_version_only(f) except ValueError: # not a cgf file raise else: progress.enter_substeps(2, "Reading CGF %r ..." % filepath) data.read(f) print('Project root: %s' % self.project_root) progress.leave_substeps("Done reading.") progress.enter_substeps(3, "Parsing CGF %r ..." % filepath) if data.game == 'Crysis': print( '[WARNING]: Crysis import is very experimental, and is likely to fail' ) print('game: %s' % data.game) print('file type: 0x%08X' % data.header.type) print('version: 0x%08X' % data.version) print('user version: 0x%08X' % data.user_version) for i, chunk in enumerate(data.chunks): print('id %i: %s' % (i, chunk.__class__.__name__)) # TODO: fixed the scale correction scale_factor = self.get_global_scale(data) for chunk in data.chunks: chunk.apply_scale(1.0 / scale_factor) # import data progress.step("Done, making data into blender") progress.step("Done, loading materials and images ...") # TODO: create materials # Far Cry: iterate over all standard material chunks for chunk in data.chunks: # check chunk type if not isinstance(chunk, CgfFormat.MtlChunk): continue # multi material: skip if chunk.children or to_str(chunk.name).startswith('s_nouvmap') \ or chunk.type != CgfFormat.MtlType.STANDARD \ or self.get_material_name(chunk.name) is None: continue # single material b_mats.append((self.create_std_material(chunk, use_cycles=use_cycles), self.is_material_nodraw(chunk.name))) # Deselect all if bpy.ops.object.select_all.poll(): bpy.ops.object.select_all(action="DESELECT") scene = context.scene new_objects = {} # put new objects here armature_chunk = None node_transforms = {} # SPLIT_OB_OR_GROUP = bool(use_split_objects or use_split_groups) # Create meshes from the data, warning 'vertex_groups' wont suppot splitting #~ print(dataname, user_vnor, use_vtex) # parse bone list first. for chunk in data.chunks: if isinstance(chunk, CgfFormat.BoneNameListChunk): self.parse_bone_name_list(chunk) # parse bone data for chunk in data.chunks: if isinstance(chunk, CgfFormat.BoneAnimChunk): self.build_bone_infos(chunk) elif isinstance(chunk, CgfFormat.BoneInitialPosChunk): self.process_bone_initial_position(chunk) for chunk in data.chunks: if isinstance(chunk, CgfFormat.NodeChunk) and isinstance( chunk.object, CgfFormat.MeshChunk): self.dataname = to_str(chunk.name) self.create_mesh( new_objects, chunk.object, b_mats, self.dataname, ) node_transforms[chunk.object] = Matrix( chunk.transform.as_tuple()).transposed() self.mapping_vertex_group_weights(new_objects) elif import_skeleton and isinstance(chunk, CgfFormat.BoneAnimChunk): self.create_armatures(chunk, new_objects, scale_factor=scale_factor) # create new obj for (chk, obj) in new_objects.items(): if obj not in scene.objects.values(): scene.objects.link(obj) # we could apply this anywhere before scaling node_transform = node_transforms[ chk] if chk in node_transforms else None print('Node transform: %s' % node_transform) obj.matrix_world = global_matrix if node_transform: obj.matrix_world = obj.matrix_world * node_transform print('Apply obj %s\' matrix world.' % obj) scene.update() for i in scene.objects: i.select = False # deselect all objects # Deselect all if bpy.ops.object.select_all.poll(): bpy.ops.object.select_all(action="DESELECT") if len(new_objects): for obj in new_objects.values(): if obj.type == 'ARMATURE': obj.select = True scene.objects.active = obj break progress.leave_substeps("Done ...") if import_animations: progress.enter_substeps( 4, "Import animations by searching Cry action list file (CAL) ..." ) self.load_animations() progress.leave_substeps("Done, imported animations ...") progress.leave_substeps("Finished importing CGF %r ..." % filepath) return {'FINISHED'}
def load(context, filepath): with ProgressReport(context.window_manager) as progress: progress.enter_substeps(1, "Importing ADT OBJ %r..." % filepath) csvpath = filepath.replace('.obj', '_ModelPlacementInformation.csv') # Coordinate setup ## WoW coordinate sytem # Max Size: 51200 / 3 = 17066,66666666667 # Map Size: Max Size * 2 = 34133,33333333333 # ADT Size: Map Size / 64 = 533,3333333333333 max_size = 51200 / 3 map_size = max_size * 2 adt_size = map_size / 64 base_folder, adtname = os.path.split(filepath) adtsplit = adtname.split("_") mapname = adtsplit[0] map_x = int(adtsplit[1]) map_y = int(adtsplit[2].replace(".obj", "")) print(mapname) print(map_x) print(map_y) offset_x = adt_size * map_x offset_y = adt_size * map_y print(offset_x) print(offset_y) # Import ADT bpy.ops.import_scene.obj(filepath=filepath) # Select the imported doodad obj = bpy.context.object # Make object active # bpy.context.scene.objects.active = obj # Read doodad definitions file with open(csvpath) as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for row in reader: doodad_path, doodad_filename = os.path.split(filepath) newpath = os.path.join(doodad_path, row['ModelFile']) # Import the doodad bpy.ops.import_scene.obj(filepath=newpath) # Select the imported doodad obj = bpy.context.object # Make object active # bpy.context.scene.objects.active = obj # Set position # WARNING: WoW world coordinates, are Y and Z swapped? obj.location = (float(row['PositionX']) - offset_x, float(row['PositionY']), float(row['PositionZ']) - offset_y) print(float(row['PositionX']) - offset_x) print(obj.location[0]) # Set scale if row['ScaleFactor']: obj.scale = (float(row['ScaleFactor']), float(row['ScaleFactor']), float(row['ScaleFactor'])) print(obj.scale[0]) #break #print(newpath) #print(row['ModelFile'], row['PositionX']) #file = open(newpath, "r") # #for line in file: # print(line) # splitted_line = line.split(";") # # modelname = splitted_line[0] # type(modelname) # position_x = float(splitted_line[1]) # type(position_x) # position_y = float(splitted_line[2]) # position_z = float(splitted_line[3]) # rotation_x = float(splitted_line[4]) # rotation_y = float(splitted_line[5]) # rotation_z = float(splitted_line[6]) # scale = float(splitted_line[7]) # modelid = int(splitted_line[8]) # type(modelid) # # print ("Model name: %r, POS: %f %f %f, ROT: %f %f %f, Scale: %f, ModelID: %d" % (modelname, position_x, position_y, position_z, rotation_x, rotation_y, rotation_z, scale, modelid)) #file.close() progress.leave_substeps("Finished importing: %r" % filepath) return {'FINISHED'}
def write(self, filepath): """ This function starts the exporting. It defines a few "globals" as class members, notably the total_* variables It loops through objects, writing each to .objex (with the write_object method), and collecting materials/armatures/animations as it goes. Once the .objex is finished being written, write_mtl is called to write the .mtl and same thing with write_anim which writes .anim and itself calls .skel which writes .skel """ log = self.log self.filepath = filepath with ProgressReport(self.context.window_manager) as progress: scene = self.context.scene # Exit edit mode before exporting, so current object states are exported properly. if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') # EXPORT THE FILE. progress.enter_substeps(1) with ProgressReportSubstep(progress, 3, "Objex Export path: %r" % filepath, "Objex Export Finished") as subprogress1: with open(filepath, "w", encoding="utf8", newline="\n") as f: self.fw_objex = f.write # write leading comments, mtllib/animlib/skellib directives, and defines filepath_* to write .mtl/... to self.write_header() # Initialize totals, these are updated each object self.total_vertex = self.total_uv = self.total_normal = self.total_vertex_color = 1 # A Dict of Materials # "materials" here refer to a material + face image pair, where either or both may be unset # (material, image): (name, name_q, material, face_image) # name_q = util.quote(name) self.mtl_dict = {} copy_set = set() self.armatures = [] # Get all meshes subprogress1.enter_substeps(len(self.objects)) for ob_main in self.objects: # 421todo I don't know what this dupli stuff is about # ("instancer" stuff in 2.80+) use_old_dupli = hasattr(ob_main, 'dupli_type') # True in < 2.80 # ignore dupli children if (ob_main.parent and (ob_main.parent.dupli_type if use_old_dupli else ob_main.parent.instance_type) in {'VERTS', 'FACES'} ): subprogress1.step("Ignoring %s, dupli child..." % ob_main.name) continue obs = [(ob_main, ob_main.matrix_world)] added_dupli_children = True if use_old_dupli and ob_main.dupli_type != 'NONE': # XXX log.info('creating dupli_list on {}', ob_main.name) ob_main.dupli_list_create(scene) obs += [(dob.object, dob.matrix) for dob in ob_main.dupli_list] elif not use_old_dupli and ob_main.is_instancer: # evaluated_depsgraph_get may be called in-between this line executing, # ie in write_object when evaluating mesh data, so call it again every time here depsgraph = self.context.evaluated_depsgraph_get() obs += [(dup.instance_object.original, dup.matrix_world.copy()) for dup in depsgraph.object_instances if dup.parent and dup.parent.original == ob_main] del depsgraph else: added_dupli_children = False if added_dupli_children: log.debug('{} has {:d} dupli children', ob_main.name, len(obs) - 1) subprogress1.enter_substeps(len(obs)) for ob, ob_mat in obs: self.write_object(subprogress1, ob, ob_mat) if use_old_dupli and ob_main.dupli_type != 'NONE': ob_main.dupli_list_clear() elif not use_old_dupli: pass # no clean-up needed subprogress1.leave_substeps("Finished writing geometry of '%s'." % ob_main.name) subprogress1.leave_substeps() del self.fw_objex subprogress1.step("Finished exporting geometry, now exporting materials") # Now we have all our materials, save them if self.options['EXPORT_MTL']: def append_header_mtl(fw_mtl): fw_mtl(self.export_id_line) export_objex_mtl.write_mtl(scene, self.filepath_mtl, append_header_mtl, self.options, copy_set, self.mtl_dict) subprogress1.step("Finished exporting materials, now exporting skeletons/animations") # save gathered skeletons and animations if self.options['EXPORT_SKEL']: log.info('now exporting skeletons') skelfile = None animfile = None try: skelfile = open(self.filepath_skel, "w", encoding="utf8", newline="\n") skelfile_write = skelfile.write skelfile_write(self.export_id_line) link_anim_basepath = None if self.options['EXPORT_ANIM']: log.info(' ... and animations') animfile = open(self.filepath_anim, "w", encoding="utf8", newline="\n") animfile_write = animfile.write animfile_write(self.export_id_line) if self.options['EXPORT_LINK_ANIM_BIN']: log.info(' ... and Link animation binaries') link_anim_basepath = self.filepath_linkbase else: animfile_write = None export_objex_anim.write_armatures(skelfile_write, animfile_write, scene, self.options['GLOBAL_MATRIX'], self.armatures, link_anim_basepath, self.options['LINK_BIN_SCALE']) finally: if skelfile: skelfile.close() if animfile: animfile.close() # copy all collected files. bpy_extras.io_utils.path_reference_copy(copy_set) progress.leave_substeps()
def _create_material(progress: ProgressReport, manager: ImportManager, material: gltftypes.Material) -> bpy.types.Material: blender_material = bpy.data.materials.new(material.name) blender_material['js'] = json.dumps(material.js, indent=2) blender_material.use_nodes = True tree = blender_material.node_tree tree.nodes.remove(tree.nodes['Principled BSDF']) getLogger('').disabled = True groups = blender_groupnode_io.import_groups(gltf_pbr_node.groups) getLogger('').disabled = False bsdf = tree.nodes.new('ShaderNodeGroup') bsdf.node_tree = groups['glTF Metallic Roughness'] tree.links.new(bsdf.outputs['Shader'], tree.nodes['Material Output'].inputs['Surface']) def create_image_node(texture_index: int): # uv => tex image_node = tree.nodes.new(type='ShaderNodeTexImage') image_node.image = manager.textures[texture_index] tree.links.new( tree.nodes.new('ShaderNodeTexCoord').outputs['UV'], image_node.inputs['Vector']) return image_node def bsdf_link_image(texture_index: int, input_name: str): texture = create_image_node(texture_index) tree.links.new(texture.outputs["Color"], bsdf.inputs[input_name]) if material.normalTexture: bsdf_link_image(material.normalTexture.index, 'Normal') if material.occlusionTexture: bsdf_link_image(material.occlusionTexture.index, 'Occlusion') if material.emissiveTexture: bsdf_link_image(material.emissiveTexture.index, 'Emissive') pbr = material.pbrMetallicRoughness if pbr: if pbr.baseColorTexture and pbr.baseColorFactor: # mix mix = tree.nodes.new(type='ShaderNodeMixRGB') mix.blend_type = 'MULTIPLY' mix.inputs[2].default_value = pbr.baseColorFactor elif pbr.baseColorTexture: bsdf_link_image(pbr.baseColorTexture.index, 'BaseColor') else: # factor pass if pbr.metallicRoughnessTexture: bsdf_link_image(pbr.metallicRoughnessTexture.index, 'MetallicRoughness') progress.step() return blender_material
def write_file(context, filepath, objects, scene, provides_mtl, progress=ProgressReport()): # bpy.ops.object.select_all(action='DESELECT') with ProgressReportSubstep(progress, 2, "JSON export path: %r" % filepath, "JSON export finished") as subprogress1: with open(filepath, "w", encoding="utf8", newline="\n") as f: limbs = {'anchor': {'opacity': 0}} pose = {} for obj in objects: if obj.type != "MESH": continue name1 = obj.name name2 = obj.data.name if name1 == name2: name = name_compat(name1) else: name = '%s_%s' % (name_compat(name1), name_compat(name2)) cursor = obj.matrix_world.translation x = cursor[0] y = cursor[2] z = cursor[1] limb = { 'origin': [x, y, -z], 'smooth': True, 'parent': 'anchor' } transform = {'translate': [x * 16, y * 16, z * 16]} # Some automatic setup of limbs based on name if name1 == 'head': limb['looking'] = True elif name1 == 'left_arm': limb['holding'] = 'left' limb['swinging'] = True limb['idle'] = True limb['invert'] = True elif name1 == 'right_arm': limb['holding'] = 'right' limb['swinging'] = True limb['idle'] = True limb['swiping'] = True elif name1 == 'right_leg': limb['swinging'] = True limb['invert'] = True elif name1 == 'left_leg': limb['swinging'] = True limbs[name] = limb pose[name] = transform # Write JSON to the file pose = {'size': [0.6, 1.8, 0.6], 'limbs': pose} data = { 'scheme': "1.3", 'providesObj': True, 'providesMtl': provides_mtl, 'name': path_leaf(filepath), 'limbs': limbs, 'poses': { 'standing': pose, 'sneaking': pose, 'sleeping': pose, 'flying': pose } } f.write(json.dumps(data, indent=4)) subprogress1.step("Finished exporting JSON")
def write_file( filepath, objects, scene, EXPORT_TRI=False, EXPORT_EDGES=False, EXPORT_SMOOTH_GROUPS=False, EXPORT_SMOOTH_GROUPS_BITFLAGS=False, EXPORT_NORMALS=False, EXPORT_UV=True, EXPORT_MTL=True, EXPORT_APPLY_MODIFIERS=True, EXPORT_BLEN_OBS=True, EXPORT_GROUP_BY_OB=False, EXPORT_GROUP_BY_MAT=False, EXPORT_KEEP_VERT_ORDER=False, EXPORT_POLYGROUPS=False, EXPORT_CURVE_AS_NURBS=True, EXPORT_GLOBAL_MATRIX=None, EXPORT_RELATIVE_PATH="", EXPORT_PATH_MODE='AUTO', progress=ProgressReport(), ): """ Basic write function. The context and options must be already set This can be accessed externaly eg. write( 'c:\\test\\foobar.obj', Blender.Object.GetSelected() ) # Using default options. """ if EXPORT_GLOBAL_MATRIX is None: EXPORT_GLOBAL_MATRIX = mathutils.Matrix() def veckey3d(v): return round(v.x, 4), round(v.y, 4), round(v.z, 4) def veckey2d(v): return round(v[0], 4), round(v[1], 4) def findVertexGroupName(face, vWeightMap): """ Searches the vertexDict to see what groups is assigned to a given face. We use a frequency system in order to sort out the name because a given vetex can belong to two or more groups at the same time. To find the right name for the face we list all the possible vertex group names with their frequency and then sort by frequency in descend order. The top element is the one shared by the highest number of vertices is the face's group """ weightDict = {} for vert_index in face.vertices: vWeights = vWeightMap[vert_index] for vGroupName, weight in vWeights: weightDict[vGroupName] = weightDict.get(vGroupName, 0.0) + weight if weightDict: return max((weight, vGroupName) for vGroupName, weight in weightDict.items())[1] else: return '(null)' with ProgressReportSubstep(progress, 2, "OBJ Export path: %r" % filepath, "OBJ Export Finished") as subprogress1: with open(filepath, "w", encoding="utf8", newline="\n") as f: fw = f.write # Write Header fw('# Blender v%s OBJ File: %r\n' % (bpy.app.version_string, os.path.basename(bpy.data.filepath))) fw('# www.blender.org\n') # Tell the obj file what material file to use. if EXPORT_MTL: mtlfilepath = os.path.splitext(filepath)[0] + ".mtl" # filepath can contain non utf8 chars, use repr fw('mtllib %s\n' % repr(os.path.basename(mtlfilepath))[1:-1]) # Initialize totals, these are updated each object totverts = totuvco = totno = 1 face_vert_index = 1 # A Dict of Materials # (material.name, image.name):matname_imagename # matname_imagename has gaps removed. mtl_dict = {} # Used to reduce the usage of matname_texname materials, which can become annoying in case of # repeated exports/imports, yet keeping unique mat names per keys! # mtl_name: (material.name, image.name) mtl_rev_dict = {} copy_set = set() # Get all meshes subprogress1.enter_substeps(len(objects)) for i, ob_main in enumerate(objects): # ignore dupli children if ob_main.parent and ob_main.parent.dupli_type in { 'VERTS', 'FACES' }: # XXX subprogress1.step("Ignoring %s, dupli child..." % ob_main.name) continue obs = [(ob_main, ob_main.matrix_world)] if ob_main.dupli_type != 'NONE': # XXX print('creating dupli_list on', ob_main.name) ob_main.dupli_list_create(scene) obs += [(dob.object, dob.matrix) for dob in ob_main.dupli_list] # XXX debug print print(ob_main.name, 'has', len(obs) - 1, 'dupli children') subprogress1.enter_substeps(len(obs)) for ob, ob_mat in obs: with ProgressReportSubstep(subprogress1, 6) as subprogress2: uv_unique_count = no_unique_count = 0 # Nurbs curve support if EXPORT_CURVE_AS_NURBS and test_nurbs_compat(ob): ob_mat = EXPORT_GLOBAL_MATRIX * ob_mat totverts += write_nurb(fw, ob, ob_mat) continue # END NURBS try: me = ob.to_mesh(scene, EXPORT_APPLY_MODIFIERS, 'PREVIEW', calc_tessface=False) except RuntimeError: me = None if me is None: continue me.transform(EXPORT_GLOBAL_MATRIX * ob_mat) if EXPORT_TRI: # _must_ do this first since it re-allocs arrays mesh_triangulate(me) if EXPORT_UV: faceuv = len(me.uv_textures) > 0 if faceuv: uv_texture = me.uv_textures.active.data[:] uv_layer = me.uv_layers.active.data[:] else: faceuv = False me_verts = me.vertices[:] # Make our own list so it can be sorted to reduce context switching face_index_pairs = [ (face, index) for index, face in enumerate(me.polygons) ] # faces = [ f for f in me.tessfaces ] if EXPORT_EDGES: edges = me.edges else: edges = [] if not (len(face_index_pairs) + len(edges) + len(me.vertices) ): # Make sure there is something to write # clean up bpy.data.meshes.remove(me) continue # dont bother with this mesh. if EXPORT_NORMALS and face_index_pairs: me.calc_normals_split() # No need to call me.free_normals_split later, as this mesh is deleted anyway! loops = me.loops if (EXPORT_SMOOTH_GROUPS or EXPORT_SMOOTH_GROUPS_BITFLAGS ) and face_index_pairs: smooth_groups, smooth_groups_tot = me.calc_smooth_groups( EXPORT_SMOOTH_GROUPS_BITFLAGS) if smooth_groups_tot <= 1: smooth_groups, smooth_groups_tot = (), 0 else: smooth_groups, smooth_groups_tot = (), 0 materials = me.materials[:] material_names = [ m.name if m else None for m in materials ] # avoid bad index errors if not materials: materials = [None] material_names = [name_compat(None)] # Sort by Material, then images # so we dont over context switch in the obj file. if EXPORT_KEEP_VERT_ORDER: pass else: if faceuv: if smooth_groups: sort_func = lambda a: ( a[0].material_index, hash(uv_texture[a[1]].image ), smooth_groups[a[1]] if a[0].use_smooth else False) else: sort_func = lambda a: (a[0].material_index, hash(uv_texture[a[ 1]].image), a[0] .use_smooth) elif len(materials) > 1: if smooth_groups: sort_func = lambda a: (a[ 0].material_index, smooth_groups[a[ 1]] if a[0].use_smooth else False) else: sort_func = lambda a: (a[0].material_index, a[0].use_smooth) else: # no materials if smooth_groups: sort_func = lambda a: smooth_groups[a[ 1] if a[0].use_smooth else False] else: sort_func = lambda a: a[0].use_smooth face_index_pairs.sort(key=sort_func) del sort_func # Set the default mat to no material and no image. contextMat = 0, 0 # Can never be this, so we will label a new material the first chance we get. contextSmooth = None # Will either be true or false, set bad to force initialization switch. if EXPORT_BLEN_OBS or EXPORT_GROUP_BY_OB: name1 = ob.name name2 = ob.data.name if name1 == name2: obnamestring = name_compat(name1) else: obnamestring = '%s_%s' % (name_compat(name1), name_compat(name2)) if EXPORT_BLEN_OBS: fw('o %s\n' % obnamestring) # Write Object name else: # if EXPORT_GROUP_BY_OB: fw('g %s\n' % obnamestring) subprogress2.step() # Vert for v in me_verts: fw('v %.6f %.6f %.6f\n' % v.co[:]) subprogress2.step() # UV if faceuv: # in case removing some of these dont get defined. uv = f_index = uv_index = uv_key = uv_val = uv_ls = None uv_face_mapping = [None] * len(face_index_pairs) uv_dict = {} uv_get = uv_dict.get for f, f_index in face_index_pairs: uv_ls = uv_face_mapping[f_index] = [] for uv_index, l_index in enumerate( f.loop_indices): uv = uv_layer[l_index].uv # include the vertex index in the key so we don't share UV's between vertices, # allowed by the OBJ spec but can cause issues for other importers, see: T47010. # this works too, shared UV's for all verts #~ uv_key = veckey2d(uv) uv_key = loops[ l_index].vertex_index, veckey2d(uv) uv_val = uv_get(uv_key) if uv_val is None: uv_val = uv_dict[ uv_key] = uv_unique_count fw('vt %.4f %.4f\n' % uv[:]) uv_unique_count += 1 uv_ls.append(uv_val) del uv_dict, uv, f_index, uv_index, uv_ls, uv_get, uv_key, uv_val # Only need uv_unique_count and uv_face_mapping subprogress2.step() # NORMAL, Smooth/Non smoothed. if EXPORT_NORMALS: no_key = no_val = None normals_to_idx = {} no_get = normals_to_idx.get loops_to_normals = [0] * len(loops) for f, f_index in face_index_pairs: for l_idx in f.loop_indices: no_key = veckey3d(loops[l_idx].normal) no_val = no_get(no_key) if no_val is None: no_val = normals_to_idx[ no_key] = no_unique_count fw('vn %.4f %.4f %.4f\n' % no_key) no_unique_count += 1 loops_to_normals[l_idx] = no_val del normals_to_idx, no_get, no_key, no_val else: loops_to_normals = [] if not faceuv: f_image = None subprogress2.step() # XXX if EXPORT_POLYGROUPS: # Retrieve the list of vertex groups vertGroupNames = ob.vertex_groups.keys() if vertGroupNames: currentVGroup = '' # Create a dictionary keyed by face id and listing, for each vertex, the vertex groups it belongs to vgroupsMap = [[] for _i in range(len(me_verts))] for v_idx, v_ls in enumerate(vgroupsMap): v_ls[:] = [(vertGroupNames[g.group], g.weight) for g in me_verts[v_idx].groups] for f, f_index in face_index_pairs: f_smooth = f.use_smooth if f_smooth and smooth_groups: f_smooth = smooth_groups[f_index] f_mat = min(f.material_index, len(materials) - 1) if faceuv: tface = uv_texture[f_index] f_image = tface.image # MAKE KEY if faceuv and f_image: # Object is always true. key = material_names[f_mat], f_image.name else: key = material_names[ f_mat], None # No image, use None instead. # Write the vertex group if EXPORT_POLYGROUPS: if vertGroupNames: # find what vertext group the face belongs to vgroup_of_face = findVertexGroupName( f, vgroupsMap) if vgroup_of_face != currentVGroup: currentVGroup = vgroup_of_face fw('g %s\n' % vgroup_of_face) # CHECK FOR CONTEXT SWITCH if key == contextMat: pass # Context already switched, dont do anything else: if key[0] is None and key[1] is None: # Write a null material, since we know the context has changed. if EXPORT_GROUP_BY_MAT: # can be mat_image or (null) fw("g %s_%s\n" % (name_compat(ob.name), name_compat(ob.data.name))) if EXPORT_MTL: fw("usemtl (null)\n") # mat, image else: mat_data = mtl_dict.get(key) if not mat_data: # First add to global dict so we can export to mtl # Then write mtl # Make a new names from the mat and image name, # converting any spaces to underscores with name_compat. # If none image dont bother adding it to the name # Try to avoid as much as possible adding texname (or other things) # to the mtl name (see [#32102])... mtl_name = "%s" % name_compat(key[0]) if mtl_rev_dict.get( mtl_name, None) not in {key, None}: if key[1] is None: tmp_ext = "_NONE" else: tmp_ext = "_%s" % name_compat( key[1]) i = 0 while mtl_rev_dict.get( mtl_name + tmp_ext, None) not in {key, None}: i += 1 tmp_ext = "_%3d" % i mtl_name += tmp_ext mat_data = mtl_dict[ key] = mtl_name, materials[ f_mat], f_image mtl_rev_dict[mtl_name] = key if EXPORT_GROUP_BY_MAT: # can be mat_image or (null) fw("g %s_%s_%s\n" % (name_compat( ob.name), name_compat( ob.data.name), mat_data[0])) if EXPORT_MTL: fw("usemtl %s\n" % mat_data[0] ) # can be mat_image or (null) contextMat = key if f_smooth != contextSmooth: if f_smooth: # on now off if smooth_groups: f_smooth = smooth_groups[f_index] fw('s %d\n' % f_smooth) else: fw('s 1\n') else: # was off now on fw('s off\n') contextSmooth = f_smooth f_v = [(vi, me_verts[v_idx], l_idx) for vi, (v_idx, l_idx) in enumerate( zip(f.vertices, f.loop_indices))] fw('f') if faceuv: if EXPORT_NORMALS: for vi, v, li in f_v: fw(" %d/%d/%d" % ( totverts + v.index, totuvco + uv_face_mapping[f_index][vi], totno + loops_to_normals[li], )) # vert, uv, normal else: # No Normals for vi, v, li in f_v: fw(" %d/%d" % ( totverts + v.index, totuvco + uv_face_mapping[f_index][vi], )) # vert, uv face_vert_index += len(f_v) else: # No UV's if EXPORT_NORMALS: for vi, v, li in f_v: fw(" %d//%d" % (totverts + v.index, totno + loops_to_normals[li])) else: # No Normals for vi, v, li in f_v: fw(" %d" % (totverts + v.index)) fw('\n') subprogress2.step() # Write edges. if EXPORT_EDGES: for ed in edges: if ed.is_loose: fw('l %d %d\n' % (totverts + ed.vertices[0], totverts + ed.vertices[1])) # Make the indices global rather then per mesh totverts += len(me_verts) totuvco += uv_unique_count totno += no_unique_count # clean up bpy.data.meshes.remove(me) if ob_main.dupli_type != 'NONE': ob_main.dupli_list_clear() subprogress1.leave_substeps( "Finished writing geometry of '%s'." % ob_main.name) subprogress1.leave_substeps() subprogress1.step( "Finished exporting geometry, now exporting materials") # Now we have all our materials, save them if EXPORT_MTL: write_mtl(scene, mtlfilepath, EXPORT_PATH_MODE, copy_set, mtl_dict, EXPORT_RELATIVE_PATH) # copy all collected files. bpy_extras.io_utils.path_reference_copy(copy_set)
def load(context, filepath): with ProgressReport(context.window_manager) as progress: progress.enter_substeps(1, "Importing ADT OBJ %r..." % filepath) csvpath = filepath.replace('.obj', '_ModelPlacementInformation.csv') # Coordinate setup ## WoW coordinate sytem # Max Size: 51200 / 3 = 17066,66666666667 # Map Size: Max Size * 2 = 34133,33333333333 # ADT Size: Map Size / 64 = 533,3333333333333 max_size = 51200 / 3 map_size = max_size * 2 adt_size = map_size / 64 base_folder, adtname = os.path.split(filepath) adtsplit = adtname.split("_") mapname = adtsplit[0] map_x = int(adtsplit[1]) map_y = int(adtsplit[2].replace(".obj", "")) print(mapname) print(map_x) print(map_y) offset_x = adt_size * map_x offset_y = adt_size * map_y print(offset_x) print(offset_y) # Import ADT bpy.ops.import_scene.obj(filepath=filepath) bpy.ops.object.add(type='EMPTY') doodadparent = bpy.context.active_object doodadparent.parent = bpy.data.objects[mapname + '_' + str(map_x) + '_' + str(map_y)] doodadparent.name = "Doodads" doodadparent.rotation_euler = [0, 0, 0] doodadparent.rotation_euler.x = radians(-90) bpy.ops.object.add(type='EMPTY') wmoparent = bpy.context.active_object wmoparent.parent = bpy.data.objects[mapname + '_' + str(map_x) + '_' + str(map_y)] wmoparent.name = "WMOs" wmoparent.rotation_euler = [0, 0, 0] wmoparent.rotation_euler.x = radians(-90) # Make object active # bpy.context.scene.objects.active = obj # Read doodad definitions file with open(csvpath) as csvfile: reader = csv.DictReader(csvfile, delimiter=';') for row in reader: doodad_path, doodad_filename = os.path.split(filepath) newpath = os.path.join(doodad_path, row['ModelFile']) if row['Type'] == 'wmo': bpy.ops.object.add(type='EMPTY') parent = bpy.context.active_object parent.name = row['ModelFile'] parent.parent = wmoparent parent.location = (17066 - float(row['PositionX']), (17066 - float(row['PositionZ'])) * -1, float(row['PositionY'])) parent.rotation_euler = [0, 0, 0] #obj.rotation_euler.x += (radians(90 + float(row['RotationX']))) # TODO #obj.rotation_euler.y -= radians(float(row['RotationY'])) # TODO parent.rotation_euler.z = radians( (-90 + float(row['RotationY']))) bpy.ops.import_scene.obj(filepath=newpath) obj_objects = bpy.context.selected_objects[:] # Put ADT rotations in here for obj in obj_objects: obj.parent = parent wmocsvpath = newpath.replace( '.obj', '_ModelPlacementInformation.csv') # Read WMO doodads definitions file with open(wmocsvpath) as wmocsvfile: wmoreader = csv.DictReader(wmocsvfile, delimiter=';') for wmorow in wmoreader: wmodoodad_path, wmodoodad_filename = os.path.split( filepath) wmonewpath = os.path.join(wmodoodad_path, wmorow['ModelFile']) # Import the doodad bpy.ops.import_scene.obj(filepath=wmonewpath) # Select the imported doodad wmoobj_objects = bpy.context.selected_objects[:] for wmoobj in wmoobj_objects: # Prepend name wmoobj.name = "(" + wmorow[ 'DoodadSet'] + ") " + wmoobj.name # Set parent wmoobj.parent = parent # Set position wmoobj.location = (float(wmorow['PositionX']) * -1, float(wmorow['PositionY']) * -1, float(wmorow['PositionZ'])) # Set rotation rotQuat = Quaternion( (float(wmorow['RotationW']), float(wmorow['RotationX']), float(wmorow['RotationY']), float(wmorow['RotationZ']))) rotEul = rotQuat.to_euler() rotEul.x += radians(90) #rotEul.z += radians(90); wmoobj.rotation_euler = rotEul # Set scale if wmorow['ScaleFactor']: wmoobj.scale = (float( wmorow['ScaleFactor']), float( wmorow['ScaleFactor']), float( wmorow['ScaleFactor'])) else: print("m2") bpy.ops.import_scene.obj(filepath=newpath) obj_objects = bpy.context.selected_objects[:] for obj in obj_objects: # Set parent obj.parent = doodadparent # Set location obj.location.x = (17066 - float(row['PositionX'])) obj.location.y = (17066 - float(row['PositionZ'])) * -1 obj.location.z = float(row['PositionY']) obj.rotation_euler.x += radians(float( row['RotationZ'])) obj.rotation_euler.y += radians(float( row['RotationX'])) obj.rotation_euler.z = radians( 90 + float(row['RotationY'])) # okay # Set scale if row['ScaleFactor']: obj.scale = (float(row['ScaleFactor']), float(row['ScaleFactor']), float(row['ScaleFactor'])) progress.leave_substeps("Finished importing: %r" % filepath) return {'FINISHED'}
def load_objects(context, progress: ProgressReport, manager: ImportManager) -> Tuple[List[Node], Node]: progress.enter_substeps(len(manager.gltf.nodes) + 1, "Loading objects...") # collection view_layer = context.view_layer if view_layer.collections.active: collection = view_layer.collections.active.collection else: collection = context.scene.master_collection.new() view_layer.collections.link(collection) # setup nodes = [ Node(i, gltf_node) for i, gltf_node in enumerate(manager.gltf.nodes) ] # set parents for gltf_node, node in zip(manager.gltf.nodes, nodes): for child_index in gltf_node.children: child = nodes[child_index] node.children.append(child) child.parent = node progress.step() # check root roots = [node for node in enumerate(nodes) if not node[1].parent] if len(roots) != 1: root = Node(len(nodes), gltftypes.Node({'name': '__root__'})) for _, node in roots: root.children.append(node) node.parent = root else: root = nodes[0] root.create_object(progress, collection, manager) def get_root(skin: gltftypes.Skin) -> Optional[Node]: root = None for joint in skin.joints: node = nodes[joint] if not root: root = node else: if node in root.get_ancestors(): root = node return root # create armatures root_skin = gltftypes.Skin({'name': 'skin'}) for skin in manager.gltf.skins: for joint in skin.joints: if joint not in root_skin.joints: root_skin.joints.append(joint) skeleton = get_root(root_skin) if skeleton: skeleton.create_armature(context, collection, view_layer, root_skin) bpy.ops.object.mode_set(mode='OBJECT', toggle=False) progress.leave_substeps() return (nodes, root)
def _write( context, filepath, EXPORT_TRI, # ok EXPORT_EDGES, EXPORT_SMOOTH_GROUPS, EXPORT_SMOOTH_GROUPS_BITFLAGS, EXPORT_NORMALS, # ok EXPORT_UV, # ok EXPORT_MTL, EXPORT_APPLY_MODIFIERS, # ok EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER, EXPORT_POLYGROUPS, EXPORT_CURVE_AS_NURBS, EXPORT_SEL_ONLY, # ok EXPORT_ANIMATION, EXPORT_GLOBAL_MATRIX, EXPORT_RELATIVE_PATH, EXPORT_PATH_MODE, # Not used ): with ProgressReport(context.window_manager) as progress: base_name, ext = os.path.splitext(filepath) context_name = [base_name, '', '', ext] # Base name, scene name, frame number, extension scene = context.scene # Exit edit mode before exporting, so current object states are exported properly. if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') orig_frame = scene.frame_current # Export an animation? if EXPORT_ANIMATION: scene_frames = range(scene.frame_start, scene.frame_end + 1) # Up to and including the end frame. else: scene_frames = [orig_frame] # Dont export an animation. # Loop through all frames in the scene and export. progress.enter_substeps(len(scene_frames)) for frame in scene_frames: if EXPORT_ANIMATION: # Add frame to the filepath. context_name[2] = '_%.6d' % frame scene.frame_set(frame, 0.0) if EXPORT_SEL_ONLY: objects = context.selected_objects else: objects = scene.objects full_path = ''.join(context_name) # erm... bit of a problem here, this can overwrite files when exporting frames. not too bad. # EXPORT THE FILE. progress.enter_substeps(1) write_file( full_path, objects, scene, EXPORT_TRI, EXPORT_EDGES, EXPORT_SMOOTH_GROUPS, EXPORT_SMOOTH_GROUPS_BITFLAGS, EXPORT_NORMALS, EXPORT_UV, EXPORT_MTL, EXPORT_APPLY_MODIFIERS, EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER, EXPORT_POLYGROUPS, EXPORT_CURVE_AS_NURBS, EXPORT_GLOBAL_MATRIX, EXPORT_RELATIVE_PATH, EXPORT_PATH_MODE, progress, ) progress.leave_substeps() scene.frame_set(orig_frame, 0.0) progress.leave_substeps()
def save(context, filepath): with ProgressReport(context.window_manager) as progress: scene = context.scene if bpy.ops.object.mode_set.poll(): bpy.ops.object.mode_set(mode='OBJECT') frame = scene.frame_current scene.frame_set(frame, 0.0) objects = scene.objects nscene = exporter.io_Scene () file = open(filepath + ".log", 'w') fw = file.write exp = exporter.io_Exporter () scn = exporter.io_Scene () animObjects = [] models = {} for oi, ob in enumerate(objects): model = None if ob.animation_data: animObjects.append (ob) if ob.type == 'MESH': model = exportMesh (scene, scn, ob, fw) if ob.type != 'ARMATURE' and ob.type != 'MESH': model = exportObject (scene, scn, ob) if model: parName = None if ob.parent: parName = ob.parent.name if ob.parent.type == 'ARMATURE' and ob.parent.parent: parName = ob.parent.parent.name models[model.name] = { "model" : model, "parent" : parName } fw ("\n") # Set parents for name in models: fw ("\n") fw (name) fw ("\n") data = models[name] parName = data["parent"] fw ("1") if parName: parent = models.get (parName, None) fw ("\n") fw (parName) fw ("\n") if parent: fw ("3") parModel = parent["model"] data["model"].parent = parModel fw ("\n") fw (parModel.name) fw ("\n") writeAnimation (scene, scn, animObjects, fw) exp.write (filepath, scn) file.close () return {'FINISHED'}