def brk_image_load(context_imagepath_map, line, DIR, recursive, relpath): """ Mainly uses comprehensiveImageLoad But we try all space-separated items from current line when file is not found with last one (users keep generating/using image files with spaces in a format that does not support them, sigh...) Also tries to replace '_' with ' ' for Max's exporter replaces spaces with underscores. """ filepath_parts = line.split(b' ') image = None for i in range(-1, -len(filepath_parts), -1): imagepath = os.fsdecode(b" ".join(filepath_parts[i:])) image = context_imagepath_map.get(imagepath, ...) if image is ...: image = load_image(imagepath, DIR, recursive=recursive, relpath=relpath) if image is None and "_" in imagepath: image = load_image(imagepath.replace("_", " "), DIR, recursive=recursive, relpath=relpath) if image is not None: context_imagepath_map[imagepath] = image break; if image is None: imagepath = os.fsdecode(filepath_parts[-1]) image = load_image(imagepath, DIR, recursive=recursive, place_holder=True, relpath=relpath) context_imagepath_map[imagepath] = image return image
def load_texture(self, tex_name): if tex_name is None: return None found_img = False basename = os.path.splitext(tex_name)[0] for image in bpy.data.images: if basename.lower() == os.path.splitext(image.name)[0].lower(): img = image found_img = True if not found_img: tga_path = os.path.dirname(self.filepath) + "/" + basename + ".tga" dds_path = tga_path.replace(".tga", ".dds") img = load_image(tga_path) if img is None: img = load_image(dds_path) if img is None: msg = "texture not found: " + dds_path + "|.tga" print("WARNING: " + msg) self.report({'WARNING'}, msg) img = bpy.data.images.new(tex_name, width=2048, height=2048) img.generated_type = 'COLOR_GRID' img.source = 'GENERATED' img.alpha_mode = 'STRAIGHT' return img
def load_texture(self, tex_name): found_img = False basename = os.path.splitext(tex_name)[0] # Test if the image file already exists for image in bpy.data.images: if basename.lower() == os.path.splitext(image.name)[0].lower(): img = image found_img = True # Try to load the image file if not found_img: tgapath = os.path.dirname(self.filepath) + "/" + basename + ".tga" ddspath = os.path.dirname(self.filepath) + "/" + basename + ".dds" tgapath = insensitive_path(tgapath) ddspath = insensitive_path(ddspath) img = load_image(tgapath) if img is None: img = load_image(ddspath) if img is None: print("missing texture:" + ddspath) return img
def icons_to_blend_data(icondir, filext=".png", overwite=False): ''' TODO: Add suport fo all data that blender supports ''' icon_files = [fi for fi in os.listdir(icondir) if fi.endswith(filext)] for fname in icon_files: fpath = os.path.join(icondir, fname) if fname not in bpy.data.images: load_image(fpath, dirname='', place_holder=False, recursive=False, ncase_cmp=True, convert_callback=None, verbose=False) elif overwite: image = bpy.data.images[fname] bpy.data.images.remove(image) load_image(fpath, dirname='', place_holder=False, recursive=False, ncase_cmp=True, convert_callback=None, verbose=False)
def loadImage(imagePath, filePath): image = load_image(imagePath, os.path.dirname(imagePath), recursive=False) if image is not None: return image image = load_image(imagePath, os.path.dirname(filePath), recursive=False) if image is not None: return image return load_image(imagePath, os.path.dirname(filePath), recursive=False, place_holder=True)
def graphviz_image_single(image, basename): for filename in files_single(basename): output_filename = "%s.png" % filename imagename = bpy.path.basename(output_filename) convert_graphviz(filename, output_filename) if imagename in bpy.data.images: bpy.ops.image.reload() else: image_utils.load_image(output_filename) break
def icons_to_blend_data(icondir, filter=".png"): icon_files = [fi for fi in os.listdir(icondir) if fi.endswith(filter)] for fname in icon_files: fpath = os.path.join(icondir, fname) load_image(fpath, dirname='', place_holder=False, recursive=False, ncase_cmp=True, convert_callback=None, verbose=False)
def obj_image_load(imagepath, DIR, recursive, relpath): """ Mainly uses comprehensiveImageLoad but tries to replace '_' with ' ' for Max's exporter replaces spaces with underscores. """ if b'_' in imagepath: image = load_image(imagepath.replace(b'_', b' '), DIR, recursive=recursive, relpath=relpath) if image: return image return load_image(imagepath, DIR, recursive=recursive, place_holder=True, relpath=relpath)
def obj_image_load(imagepath, DIR, use_image_search): if b'_' in imagepath: image = load_image(imagepath.replace(b'_', b' '), DIR) if image: return image image = load_image(imagepath, DIR) if image: return image print("failed to load %r doesn't exist" % imagepath) return None
def make_blender_materials(self) -> List[bpy.types.Material]: from bpy_extras.node_shader_utils import PrincipledBSDFWrapper from bpy_extras.image_utils import load_image import os.path blender_material_list = [] for material in self.gmd_file.materials: blender_name = material_name(material) if blender_name in bpy.data.materials: bpy.data.materials.remove(bpy.data.materials[blender_name]) blender_mat: bpy.types.Material = bpy.data.materials.new( name=blender_name) blender_mat.use_nodes = True principled = PrincipledBSDFWrapper(blender_mat, is_readonly=False) diffuse_name = material.texture_names[ GMDMaterialTextureIndex.Diffuse] if diffuse_name == "dummy_black": principled.base_color = (0, 0, 0) elif diffuse_name == "dummy_white": principled.base_color = (1, 1, 1) else: principled.base_color_texture.image = load_image( f"{diffuse_name}.dds", os.path.dirname(self.filepath), place_holder=True, check_existing=True) normal_name = material.texture_names[ GMDMaterialTextureIndex.Normal] if normal_name != "dummy_nmap": principled.normalmap_texture.image = load_image( f"{normal_name}.dds", os.path.dirname(self.filepath), place_holder=True, check_existing=True) # TODO: If multi texture present: # Map red = shininess # Make green lerp between setting diffuse and emission color i.e. green=0 -> diffuse, 1->emission # Make blue darken base color (blue=0->base, 1->black or base = base * (1 - blue) # See blender screenshot # Note - if the actual file doesn't exist, changing this to be a placeholder will mess with stuff because the placeholder is purple. Disable placeholder? # TODO: If shader contains [skin], enable subsurf? would require connecting the base color texture to the subsurf texture and setting "subsurface" to 1 # Enable backface culling blender_mat.use_backface_culling = True blender_material_list.append(blender_mat) return blender_material_list
def icons_to_blend_data(icondir, filext = ".png", overwite = False): ''' TODO: Add suport fo all data that blender supports ''' icon_files = [fi for fi in os.listdir(icondir) if fi.endswith(filext) ] for fname in icon_files: fpath = os.path.join(icondir,fname) if fname not in bpy.data.images: load_image(fpath, dirname='', place_holder=False, recursive=False, ncase_cmp=True, convert_callback=None, verbose=False) elif overwite: image = bpy.data.images[fname] bpy.data.images.remove(image) load_image(fpath, dirname='', place_holder=False, recursive=False, ncase_cmp=True, convert_callback=None, verbose=False)
def modifyCarAttributes(texture_path, iterString, car_number, car_color, team_name): # update number car_num_path = "/generated/car_number-assets/car_number_" numberImage = load_image(texture_path + car_num_path + str(car_number) + ".png") bpy.data.materials[ 'car_material' + iterString].node_tree.nodes['car_number'].image = numberImage bpy.data.materials[ 'banner_number' + iterString].node_tree.nodes['banner_number_img'].image = numberImage # update color color, contrast = get_color_and_contrast(int(car_color, 16)) bpy.data.materials['car_material' + iterString].node_tree.nodes[ 'car_color'].outputs[0].default_value = color bpy.data.materials['banner_color' + iterString].node_tree.nodes[ 'banner_bg_color'].outputs[0].default_value = color bpy.data.materials['text_white' + iterString].node_tree.nodes[ 'text_color'].inputs[0].default_value = contrast # update banner text bpy.data.objects['team_name' + iterString].data.body = team_name # bpy.data.objects['city_name' + iterString].data.body = team_city bpy.data.objects['team_name_depth' + iterString].data.body = team_name # set camera constraints for starting grid intro shot bpy.data.objects['explode_sprite_color' + iterString].constraints[ "Locked Track"].target = bpy.data.objects["start_grid"] bpy.data.objects['banner_bg' + iterString].constraints[ "Locked Track"].target = bpy.data.objects["start_grid"] bpy.data.objects['banner_bg_white' + iterString].constraints[ "Locked Track"].target = bpy.data.objects["start_grid"] bpy.data.objects['banner_number' + iterString].constraints[ "Locked Track"].target = bpy.data.objects["start_grid"] bpy.data.objects['team_name' + iterString].constraints[ "Locked Track"].target = bpy.data.objects["start_grid"]
def loadTextureList(self): #Get base directory of model dirName = os.path.dirname(self.fp) dirName += "/" texBase = os.path.basename(self.fp) texBase = os.path.splitext(texBase)[0] self.bs.seek_set(self.texOfs) texd = self.bs.readUInt() texLen = self.bs.readUInt() nbTex = self.bs.readUInt() for i in range(nbTex): #Check for png extension of texture Name texName = "%s_%02d" % (texBase, i) texPath = dirName + texName + ".png" #If no texture exists, continue if not os.path.exists(texPath): self.imgList.append(None) continue print(texPath) #Create new blender texture blTex = bpy.data.textures.new(texName, type='IMAGE') blTex.image = load_image(texPath) self.imgList.append(blTex) return 1
def execute(self, context): location = context.space_data.cursor_location for file_elem in self.files: print("Importing image:", file_elem.name) filepath = os.path.join(self.directory, file_elem.name) image = load_image(filepath, check_existing=True) node_tree = context.space_data.node_tree node = node_tree.nodes.new('LuxCoreNodeTexImagemap') node.image = image node.location = location # Nodes are spawned in a vertical column location.y -= 400 if image: if self.detect_normalmaps_fast and "normal" in image.name: node.is_normal_map = True elif self.detect_normalmaps_slow and check_for_normalmap_slow( image): node.is_normal_map = True else: self.report({"ERROR"}, "Failed: " + file_elem.name) print("ERROR: Could not import", filepath) return {'FINISHED'}
def find_texture(context, file, name=None): if name is None: name = file file = file.split('.', -1)[0] if name in bpy.data.images: return bpy.data.images[name] path = insensitive_path(os.path.dirname(context.filepath)) filepath = path + os.path.sep + file extensions = ['.dds', '.tga', '.jpg', '.jpeg', '.png', '.bmp'] img = None for extension in extensions: img = load_image(filepath + extension) if img is not None: context.info('loaded texture: ' + filepath + extension) break if img is None: context.warning(f'texture not found: {filepath} {extensions}') img = bpy.data.images.new(name, width=2048, height=2048) img.generated_type = 'COLOR_GRID' img.source = 'GENERATED' img.name = name img.alpha_mode = 'STRAIGHT' return img
def load_images(filenames, directory, force_reload=False, frame_start=1, find_sequences=False, num_frames=1, frame_duration=1): if find_sequences: # if finding sequences, we need some pre-processing first file_iter = find_image_sequences(filenames, num_frames) else: file_iter = single_image_sequences(filenames, num_frames) for filename, offset, frames in file_iter: image = load_image(filename, directory, check_existing=True, force_reload=force_reload) # Size is unavailable for sequences, so we grab it early size = tuple(image.size) if image.source == 'MOVIE': # Blender BPY BUG! # This number is only valid when read a second time in 2.77 # This repeated line is not a mistake frames = image.frame_duration frames = image.frame_duration elif frames > 1 and find_sequences: # Not movie, but multiple frames -> image sequence image.source = 'FILE' elif frames > 1 and find_sequences == False: # Not movie, but multiple frames -> image sequence image.source = 'SEQUENCE' yield ImageSpec(image, size, frame_start, offset - 1, frames)
def blen_read_texture(fbx_tmpl, fbx_obj, basedir, image_cache, use_image_search): import os from bpy_extras import image_utils elem_name, elem_class = elem_split_name_class(fbx_obj) assert(elem_class == b'Texture') elem_name_utf8 = elem_name.decode('utf-8') filepath = elem_find_first_string(fbx_obj, b'FileName') if os.sep == '/': filepath = filepath.replace('\\', '/') else: filepath = filepath.replace('/', '\\') image = image_cache.get(filepath) if image is not None: return image image = image_utils.load_image( filepath, dirname=basedir, place_holder=True, recursive=use_image_search, ) image_cache[filepath] = image # name can be ../a/b/c image.name = os.path.basename(elem_name_utf8) return image
def import_images(self, context): engine = context.scene.render.engine import_list, directory = self.generate_paths(self.extension) #get blender image objects based on the import_list images = (load_image(path, directory) for path in import_list) if engine == 'BLENDER_RENDER': textures = [] for img in images: self.set_image_options(img) textures.append(self.create_image_texture(context, img)) materials = (self.create_material_for_texture(tex) for tex in textures) elif engine == 'CYCLES': materials = (self.create_cycles_material(img) for img in images) planes = tuple( self.create_image_plane_from_mat(context, mat) for mat in materials) context.scene.update() if self.align: self.align_planes(planes) for plane in planes: plane.select = True self.report({'INFO'}, "Added {} Image Plane(s)".format(len(planes)))
def convert_dds_to_png(self, dds_path): from bpy_extras.image_utils import load_image import platform import pathlib import subprocess png_path = dds_path[0:-4] + '.png' home = pathlib.Path.home() current_os = platform.system() if current_os == 'Linux': converter = home / 'Compressonator' / 'CompressonatorCLI' command = ['sh', str(converter), '-fs', 'BC7', dds_path, png_path] if current_os == 'Darwin': converter = home / 'Compressonator' / 'CompressonatorCLI.sh' command = ['sh', str(converter), '-fs', 'BC7', dds_path, png_path] if current_os == 'Windows': converter = home / 'texconv' / 'texconv.exe' dds_folder = pathlib.Path(dds_path).parent command = [ str(converter), '-ft', 'png', '-o', str(dds_folder), dds_path ] png_path = dds_path[0:-4] + '.PNG' subprocess.run(command) self.image = load_image(png_path) self.image.pack() os.remove(png_path)
def import_images(self, context): engine = context.scene.render.engine import_list, directory = self.generate_paths() images = tuple(load_image(path, directory, check_existing=True, force_reload=self.force_reload) for path in import_list) for img in images: self.set_image_options(img) if engine in {'BLENDER_RENDER', 'BLENDER_GAME'}: textures = (self.create_image_textures(context, img) for img in images) materials = (self.create_material_for_texture(tex) for tex in textures) elif engine == 'CYCLES': materials = (self.create_cycles_material(context, img) for img in images) else: self.report({'ERROR'}, "Cannot generate materials for unknown %s render engine" % engine) return planes = tuple(self.create_image_plane(context, mat) for mat in materials) context.scene.update() if self.align: self.align_planes(planes) for plane in planes: plane.select = True self.report({'INFO'}, "Added {} Image Plane(s)".format(len(planes)))
def get_render_image(outpath): saved = False # noinspection PyBroadException try: # noinspection PyBroadException try: result = bpy.data.images['Render Result'] if result.has_data is False: # this save produce to fill data image result.save_render(outpath) saved = True except: print("No render image found") return None # Save and reload if saved is False: result.save_render(outpath) img = img_utils.load_image(outpath) return img except: print("Unexpected render image error") return None
def import_images(self, context): engine = context.scene.render.engine import_list, directory = self.generate_paths() images = tuple(load_image(path, directory) for path in import_list) for img in images: self.set_image_options(img) if engine in {'BLENDER_RENDER', 'BLENDER_GAME'}: textures = (self.create_image_textures(context, img) for img in images) materials = (self.create_material_for_texture(tex) for tex in textures) elif engine == 'CYCLES': materials = (self.create_cycles_material(context, img) for img in images) else: return planes = tuple( self.create_image_plane(context, mat) for mat in materials) context.scene.update() if self.align: self.align_planes(planes) for plane in planes: plane.select = True self.report({'INFO'}, "Added {} Image Plane(s)".format(len(planes)))
def find_texture(context, file, name=None): file = file.rsplit('.', 1)[0] if name is None: name = file else: name = name.rsplit('.', 1)[0] for extension in extensions: combined = name + extension if combined in bpy.data.images: return bpy.data.images[combined] path = insensitive_path(os.path.dirname(context.filepath)) filepath = path + os.path.sep + file img = None for extension in extensions: img = load_image(filepath + extension) if img is not None: context.info('loaded texture: ' + filepath + extension) img.name = name + extension break if img is None: context.warning(f'texture not found: {filepath} {extensions}') img = bpy.data.images.new(name, width=2048, height=2048) img.generated_type = 'COLOR_GRID' img.source = 'GENERATED' img.name = name + extensions[0] img.alpha_mode = 'STRAIGHT' return img
def blen_read_texture(fbx_obj, basedir, texture_cache): from bpy_extras import image_utils elem_name, elem_class = elem_split_name_class(fbx_obj) assert(elem_class == b'Texture') elem_name_utf8 = elem_name.decode('utf-8') # im = bpy.data.images.new(name=elem_name_utf8, width=1, height=1) filepath = elem_find_first_string(fbx_obj, b'FileName') if os.sep == '/': filepath = filepath.replace('\\', '/') # unix else: filepath = filepath.replace('/', '\\') # ms-windows tex = texture_cache.get(filepath) if tex is not None: # print("Using cache", tex) return tex image = image_utils.load_image( filepath, dirname=basedir, place_holder=True, ) image.name = elem_name_utf8 tex = bpy.data.textures.new(name=elem_name_utf8, type='IMAGE') tex.image = image texture_cache[filepath] = tex return tex
def import_material(matname): texname = matname.split("+")[-1] imgname = texname + ".png" if imgname in bpy.data.images: img = bpy.data.images[imgname] else: img = load_image("textures/" + imgname, place_holder=True) if texname in bpy.data.textures: tex = bpy.data.textures[texname] else: tex = bpy.data.textures.new(texname, type='IMAGE') tex.image = img tex.use_alpha = True if matname in bpy.data.materials: mat = bpy.data.materials[matname] else: mat = bpy.data.materials.new(matname) mat.game_settings.alpha_blend = 'CLIP' mat.diffuse_intensity = 1.0 mat.specular_intensity = 0.0 mat.use_transparency = True mat.use_object_color = True slot = mat.texture_slots.create(0) slot.texture = tex slot.texture_coords = 'UV' slot.uv_layer = "UVMap" slot.use_map_color_diffuse = True slot.use_map_alpha = True slot.blend_type = 'MULTIPLY' return mat, img
def load_images(self, filename): dir = path.dirname(filename) for name, object in self.list.items(): imagename = object.values[1] if imagename not in self.images: imagepath = path.join(dir, imagename) self.images[imagename] = load_image(imagepath)
def load_images(filenames, directory, force_reload=False, frame_start=1, find_sequences=False): """Wrapper for bpy's load_image Loads a set of images, movies, or even image sequences Returns a generator of ImageSpec wrapper objects later used for texture setup """ if find_sequences: # if finding sequences, we need some pre-processing first file_iter = find_image_sequences(filenames) else: file_iter = zip(filenames, repeat(1), repeat(1)) for filename, offset, frames in file_iter: image = load_image(filename, directory, check_existing=True, force_reload=force_reload) # Size is unavailable for sequences, so we grab it early size = tuple(image.size) if image.source == 'MOVIE': # Blender BPY BUG! # This number is only valid when read a second time in 2.77 # This repeated line is not a mistake frames = image.frame_duration frames = image.frame_duration elif frames > 1: # Not movie, but multiple frames -> image sequence image.source = 'SEQUENCE' yield ImageSpec(image, size, frame_start, offset - 1, frames)
def get_image_datablock(image_relpath, image_directory, recursive=False, place_holder_image=True): """ Load the image to blender, check if image has been loaded before. Args: image_relpath ('str') - The relative path to the image. image_directory ('str') - The parent directory. Kwargs: recursive ('bool') - Use recursive image search. place_holder_image ('bool') - if True a new place holder image will be created. Returns: img ('bpy.types.Image') - The loaded image datablock. """ # FIXME: make use image search optional image_directory = os.path.normpath(image_directory) img = load_image(image_relpath.strip('/'), dirname=image_directory, place_holder=place_holder_image, recursive=recursive, check_existing=True) if img is None: log.warning('Warning: Image could not be loaded: %s in directory %s ', image_relpath, image_directory) return None img.use_fake_user = True return img
def import_images(self, context): engine = context.scene.render.engine import_list, directory = self.generate_paths() images = (load_image(path, directory) for path in import_list) if engine in {'BLENDER_RENDER', 'BLENDER_GAME'}: textures = [] for img in images: self.set_image_options(img) textures.append(self.create_image_textures(context, img)) materials = (self.create_material_for_texture(tex) for tex in textures) elif engine == 'CYCLES': materials = (self.create_cycles_material(img) for img in images) else: return planes = tuple(self.create_image_plane(context, mat) for mat in materials) context.scene.update() if self.align: self.align_planes(planes) for plane in planes: plane.select = True self.report({'INFO'}, "Added {} Image Plane(s)".format(len(planes)))
def import_images(self, context): import_list, directory = generate_paths(self) images = [] textures = [] materials = [] planes = [] for path in import_list: images.append(load_image(path, directory)) for image in images: set_image_options(self, image) textures.append(create_image_textures(self, image)) for texture in textures: materials.append(create_material_for_texture(self, texture)) for material in materials: plane = create_image_plane(self, context, material) planes.append(plane) context.scene.update() if self.align: align_planes(self, planes) for plane in planes: plane.select = True self.report(type={'INFO'}, message='Added %i Image Plane(s)' %len(planes))
def get_render_image(self, outpath): saved = False # noinspection PyBroadException try: # noinspection PyBroadException try: result = bpy.data.images['Render Result'] if result.has_data is False: # this save produce to fill data image result.save_render(outpath) saved = True except: print("No render image found") return None # Save and reload if saved is False: result.save_render(outpath) img = img_utils.load_image(outpath) return img except: print("Unexpected render image error") return None
def import_images(self, context): import_list, directory = generate_paths(self) images = [] textures = [] materials = [] planes = [] for path in import_list: images.append(load_image(path, directory)) for image in images: set_image_options(self, image) textures.append(create_image_textures(self, image)) for texture in textures: materials.append(create_material_for_texture(self, texture)) for material in materials: plane = create_image_plane(self, context, material) planes.append(plane) context.scene.update() if self.align: align_planes(self, planes) for plane in planes: plane.select = True self.report(type={'INFO'}, message='Added %i Image Plane(s)' % len(planes))
def load_img_stacks(self): axi_files = self.axi_files sag_files = self.sag_files cor_files = self.cor_files try: self.axi_imgs = [image_utils.load_image(f).name for f in axi_files] self.sag_imgs = [image_utils.load_image(f).name for f in sag_files] self.cor_imgs = [image_utils.load_image(f).name for f in cor_files] except AttributeError: print("Couldn't find certain images!") return print ("Loaded " + str(len(self.axi_imgs)) + " axial images!") print ("Loaded " + str(len(self.sag_imgs)) + " sagittal images!") print ("Loaded " + str(len(self.cor_imgs)) + " coronal images!")
def setup_material( mat_name , filepath ): newmaterial = bpy.data.materials.new(mat_name) # マテリアルを作成 newmaterial.use_nodes = True # ノードを使用 mat_nodes = newmaterial.node_tree.nodes # ノード参照 for n in mat_nodes: # ノード初期化 mat_nodes.remove(n) ## ノード追加: ## テクスチャ、透過BSDF、プリンシプルBSDF、シェーダーミックス、シェーダー出力 img_node = mat_nodes.new(type="ShaderNodeTexImage") # テクスチャノード if mat_name in material_dict: image = load_image(mat_name + ".dds", material_dict[mat_name], recursive=True, place_holder=True) else: image = load_image(mat_name + ".dds", os.path.dirname(filepath), recursive=True, place_holder=True) texture = bpy.data.textures.new(name=mat_name, type='IMAGE') texture.image = image img_node.image = image # テクスチャ設定 trans_node = mat_nodes.new(type="ShaderNodeBsdfTransparent") # 透過BSDFノード bsdf_node = mat_nodes.new(type="ShaderNodeBsdfPrincipled") # プリンシプルBSDFノード mix_node = mat_nodes.new(type="ShaderNodeMixShader") # ミックスノード output_node = mat_nodes.new(type="ShaderNodeOutputMaterial") # 出力ノード mat_link = newmaterial.node_tree.links # ノードリンク参照 for n in mat_link: # ノードリンク初期化 mat_link.remove(n) # ノードリンク設定 mat_link.new( img_node.outputs[0], bsdf_node.inputs[0]) # Color mat_link.new( img_node.outputs[1], bsdf_node.inputs[18]) # Alpha mat_link.new( trans_node.outputs[0], mix_node.inputs[1]) # Trans Mix mat_link.new( bsdf_node.outputs[0], mix_node.inputs[2]) # bsdf Mix mat_link.new( mix_node.outputs[0], output_node.inputs[0]) # Output # ブレンドモードをクリップ newmaterial.blend_method = 'CLIP' newmaterial.alpha_threshold = 0.0 # マテリアルスロットを追加する bpy.ops.object.material_slot_add() return newmaterial
def build_blender_data(self, blender_context): from bpy_extras.image_utils import load_image # Check if image was already loaded if self.texturename not in self.blender_images: print("Loading texture:", self.texturename, self.filename) # Load and create a new Blender image object self.blender_images[self.texturename] = load_image(self.filename)
def loadImage(imagePath, filePath): # Handle ufoai skin name format fileName = os.path.basename(imagePath) if imagePath[0] == '.': for ext in ['.png', '.jpg', '.jpeg']: fileName = imagePath[1:] + ext if os.path.isfile(os.path.join(os.path.dirname(imagePath), fileName)): break elif os.path.isfile(os.path.join(os.path.dirname(filePath), fileName)): break else: fileName = imagePath[1:] image = load_image(fileName, os.path.dirname(imagePath), recursive=False) if image is not None: return image image = load_image(fileName, os.path.dirname(filePath), recursive=False) if image is not None: return image return None
def execute(self, context): """ Load image, put on current light and force light object update in viewport """ context.light.rpr.ies_file = load_image(self.filepath) # force scene depsgraph to update light object energy = context.light.energy context.light.energy = 0.0 context.light.energy = energy return {'FINISHED'}
def import_textures(path, tex_names): for name in tex_names: print(f"importing {name}") image = image_utils.load_image( f"{name}.png", dirname=path, place_holder=True, recursive=True, ) image.name = name
def create_texture(filename, modelpath): name = filename texture = bpy.data.textures.new(name, type="IMAGE") image = load_image(filename, modelpath) has_data = False if image: texture.image = image has_data = image.has_data return texture
def try_texture(self, c_image, b_mat): mtex = None with self._tmpwrite(c_image.path, c_image.data) as tmp: image = load_image(tmp) if image is not None: image.pack(True) texture = bpy.data.textures.new(name='Kd', type='IMAGE') texture.image = image mtex = b_mat.texture_slots.add() mtex.texture_coords = 'UV' mtex.texture = texture self._images[b_mat.name] = image return mtex
def get_image_buffer(path): img = load_image(path) if not img: return None sx, sy = img.size buf = bgl.Buffer(bgl.GL_FLOAT, 4 * sx * sy) img.gl_load(filter=bgl.GL_LINEAR, mag=bgl.GL_LINEAR) bgl.glBindTexture(bgl.GL_TEXTURE_2D, img.bindcode[0]) bgl.glGetTexImage(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA, bgl.GL_FLOAT, buf) img.gl_free() img.user_clear() bpy.data.images.remove(img) return buf, sx, sy
def make_material(iqmaterial, dir): print("importing material", iqmaterial) matname = "+".join(iqmaterial) texname = iqmaterial[-1] # reuse materials if possible if matname in bpy.data.materials: return bpy.data.materials[matname], images.get(texname) twosided = 'twosided' in iqmaterial alphatest = 'alphatest' in iqmaterial unlit = 'unlit' in iqmaterial if not texname in images: print("load image", texname) images[texname] = load_image("textures/" + texname + ".png", dir, place_holder=True, recursive=True) images[texname].use_premultiply = True image = images[texname] if texname in bpy.data.textures: tex = bpy.data.textures[texname] else: tex = bpy.data.textures.new(texname, type = 'IMAGE') tex.image = image tex.use_alpha = True mat = bpy.data.materials.new(matname) mat.diffuse_intensity = 1 mat.specular_intensity = 0 mat.alpha = 0.0 texslot = mat.texture_slots.add() texslot.texture = tex texslot.texture_coords = 'UV' texslot.uv_layer = "UVMap" texslot.use_map_color_diffuse = True texslot.use_map_alpha = True if unlit: mat.use_shadeless = True mat.use_transparency = True # blender game engine mat.game_settings.use_backface_culling = not twosided mat.game_settings.alpha_blend = 'CLIP' if alphatest and unlit: mat.game_settings.alpha_blend = 'ADD' # return the material (and image so we can link the uvlayer faces) return mat, image
def import_images(self,context): import_list,directory=self.make_path(context) # Load Images images=(load_image( path, directory) for path in import_list) # Make Materials materials=(self.make_material(img) for img in images) # Make Objects objects= tuple(self.make_objects(context,mat) for mat in materials) # Update Scene context.scene.update() for ob in objects:ob.select=True # Build Material Nodes (Base_Mat) for ob in objects:self.build(context,ob) self.report({'INFO'},"Added {} objects".format(len(objects)))
def import_texture(path): print("importing texture", path) imgname = os.path.basename(path) if imgname in bpy.data.images: img = bpy.data.images[imgname] else: img = load_image(path, place_holder=True) texname = os.path.splitext(imgname)[0] if texname in bpy.data.textures: tex = bpy.data.textures[texname] else: tex = bpy.data.textures.new(texname, type='IMAGE') tex.image = img tex.use_alpha = True return tex
def load_tex(name): import os import sys from bpy_extras.image_utils import load_image if name == "": return None, None image = load_image(name, texture_dir, recursive=True, place_holder=True) texture = None if image: name = bpy.path.display_name_from_filepath(name) texture = bpy.data.textures.new(name=name, type="IMAGE") texture.image = image return image, texture
def GetImage(self, ms3dMaterial, alphamap, allow_create=True): if alphamap: nameImageRaw = ms3dMaterial.alphamap propName = ms3d_spec.PROP_NAME_ALPHAMAP else: nameImageRaw = ms3dMaterial.texture propName = ms3d_spec.PROP_NAME_TEXTURE nameImage = os.path.split(nameImageRaw)[1] nameDirectory = self.filepath_splitted[0] # already available blenderImage = self.dict_images.get(nameImage) if blenderImage is not None: return blenderImage, False # OPTIONAL: try to find an existing one, that fits if (self.prop_reuse == ms3d_utils.PROP_ITEM_REUSE_MATCH_VALUES): testBlenderImage = bpy.data.images.get(nameImage, None) if (testBlenderImage): # take a closer look to its content if ((not testBlenderImage.library) and (os.path.split( testBlenderImage.filepath)[1] == nameImage)): return testBlenderImage, False # elif (self.prop_reuse == ms3d_utils.PROP_ITEM_REUSE_MATCH_HASH): # # irrespecting its real content # # take materials, that have the same "ms3d_import_hash" # # custom property (of an previous import) # propKey = prop(PROP_NAME_HASH) # hexHash = hex(hash(nameImage)) # for testBlenderImage in bpy.data.images: # if ((testBlenderImage) and (not testBlenderImage.library) # and (propKey in testBlenderImage) # and (testBlenderImage[propKey] == hexHash)): # return testBlenderImage, False if not allow_create: return None, False # create new blenderImage = load_image(nameImage, nameDirectory) self.dict_images[nameImage] = blenderImage if blenderImage is not None: blenderImage[prop(ms3d_spec.PROP_NAME_NAME)] = ms3dMaterial.name blenderImage[prop(propName)] = nameImageRaw return blenderImage, True
def import_images(self, context): engine = context.scene.render.engine import_list, directory = self.generate_paths() import_list2, directory2 = self.generate_paths() # for x in import_list: # self.report({'INFO'}, x) images = (load_image(path, directory) for path in import_list) # Figure out the name of the BISE directory (the level above 'output') so we can give the image sequence a name. directory_list = directory.split("\\") found_output = 0 img_seq_name = "ImageSequence" for dir_element in reversed(directory_list): if (found_output == 1): img_seq_name = dir_element break if (dir_element == "output"): found_output = 1 myCount=len(self.files) i=0 imgWidth = 0 imgHeight = 0 for img in images: if i==0: imgWidth, imgHeight = img.size materials = self.create_cycles_material(img,myCount) # only make one material i += 1 # planes = tuple(self.create_image_plane(context, mat) for mat in materials) planes = self.create_image_plane(context, materials, imgWidth, imgHeight, img_seq_name) # planes only has one plane context.scene.update() # if self.align: # self.align_planes(planes) # for plane in planes: planes.select = True # self.report({'INFO'}, "Added {} Image Plane(s)".format(len(planes))) self.report({'INFO'}, "Added 1 Image Plane")
def execute(self, context): props = self.properties filepath = bpy.path.ensure_ext(self.filepath, self.filename_ext) image = load_image(filepath) if image == None: raise NameError('Failed to load image!') if len(bpy.context.selected_objects[:]) != 1: raise NameError('Please select one object!') object = bpy.context.selected_objects[0] if object.type != 'MESH': raise NameError('Selected object must be a mesh!') if len(object.data.faces) == 0: raise NameError('Selected object has no faces!') if len(object.data.uv_textures) == 0: raise NameError('Selected object has no texture coordinates!') for mf in object.data.uv_textures[0].data: mf.image = image return {'FINISHED'}
def read_texture(new_chunk, temp_chunk, name, mapto): new_texture = bpy.data.textures.new(name, type="IMAGE") u_scale, v_scale, u_offset, v_offset = 1.0, 1.0, 0.0, 0.0 mirror = False extension = "wrap" while new_chunk.bytes_read < new_chunk.length: # print 'MAT_TEXTURE_MAP..while', new_chunk.bytes_read, new_chunk.length read_chunk(file, temp_chunk) if temp_chunk.ID == MAT_MAP_FILEPATH: texture_name, read_str_len = read_string(file) img = TEXTURE_DICT[contextMaterial.name] = load_image(texture_name, dirname) temp_chunk.bytes_read += read_str_len # plus one for the null character that gets removed elif temp_chunk.ID == MAT_MAP_USCALE: u_scale = read_float(temp_chunk) elif temp_chunk.ID == MAT_MAP_VSCALE: v_scale = read_float(temp_chunk) elif temp_chunk.ID == MAT_MAP_UOFFSET: u_offset = read_float(temp_chunk) elif temp_chunk.ID == MAT_MAP_VOFFSET: v_offset = read_float(temp_chunk) elif temp_chunk.ID == MAT_MAP_TILING: tiling = read_short(temp_chunk) if tiling & 0x2: extension = "mirror" elif tiling & 0x10: extension = "decal" elif temp_chunk.ID == MAT_MAP_ANG: print("\nwarning: ignoring UV rotation") skip_to_end(file, temp_chunk) new_chunk.bytes_read += temp_chunk.bytes_read # add the map to the material in the right channel if img: add_texture_to_material( img, new_texture, (u_scale, v_scale), (u_offset, v_offset), extension, contextMaterial, mapto )
def img2plane( folder, filename ): if filename not in bpy.data.images: # no need to reload the image, it is already in the memory! f = load_image( bpy.path.abspath( folder + filename ) ) if filename not in bpy.data.images: print( "filename:", folder + filename, "NOT FOUND!" ) return img = bpy.data.images[ filename ] #print( img, img.generated_width, img.generated_height, img.size ) ratio = img.size[ 0 ] / img.size[ 1 ] #print( ratio ) scalew = ratio scaleh = 1 ''' if ratio > 1: scaleh = 1 / ratio else: scalew = 1 / ratio ''' texture = create_image_textures( bpy.context, img ) material = create_material_for_texture( texture ) bpy.ops.mesh.primitive_plane_add('INVOKE_REGION_WIN') plane = bpy.context.scene.objects.active if plane.mode is not 'OBJECT': bpy.ops.object.mode_set(mode='OBJECT') plane.location = (0,0,0) plane.dimensions = scalew, scaleh, 0.0 plane.name = material.name bpy.ops.object.transform_apply(scale=True) plane.data.uv_textures.new() plane.data.materials.append(material) plane.data.uv_textures[0].data[0].image = img material.game_settings.use_backface_culling = False material.game_settings.alpha_blend = 'ALPHA' return plane
def add_img_background(imfile, imtype='FILE', scn=None): """Add a background image to a blender scene (to be rendered) Currently re-sets entire scene node setup. Perhaps not desirable. """ if scn is None: # Get current scene if input not supplied scn = bpy.context.scene scn.use_nodes = True if scn.render.engine=='BLENDER_RENDER': scn.render.alpha_mode = 'TRANSPARENT' # If blender render else: raise Exception("Untested with cycles! hold your horses!") # Re-set all nodes and render layers for n in scn.node_tree.nodes: scn.node_tree.nodes.remove(n) old_render_layers = bpy.context.scene.render.layers.keys() bpy.ops.scene.render_layer_add() for ii in range(len(old_render_layers)): bpy.context.scene.render.layers.active_index = 0 bpy.ops.scene.render_layer_remove() bpy.context.scene.render.layers[0].name = 'RenderLayer' # Load image (if not present already) if imfile in [i.name for i in bpy.data.images]: img = bpy.data.images[imfile] else: from bpy_extras.image_utils import load_image img = load_image(imfile) img.source = imtype.upper() # Base node RL = scn.node_tree.nodes.new(type=RLayerNode) # Image node img_node = scn.node_tree.nodes.new(type=ImageNode) img_node.image = img # Mix node mix_node = scn.node_tree.nodes.new(type=MixNode) # Output compositor_output = scn.node_tree.nodes.new(type=CompositorNode) # Connections scn.node_tree.links.new(RL.outputs['Alpha'], mix_node.inputs['Fac']) scn.node_tree.links.new(RL.outputs['Image'], mix_node.inputs[2]) scn.node_tree.links.new(img_node.outputs['Image'], mix_node.inputs[1]) scn.node_tree.links.new(mix_node.outputs['Image'], compositor_output.inputs['Image'])