Python bpy.data() Examples

The following are 30 code examples of bpy.data(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bpy , or try the search function .
Example #1
Source File: bl_previews_render.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def do_clear_previews(do_objects, do_groups, do_scenes, do_data_intern):
    if do_data_intern:
        bpy.ops.wm.previews_clear(id_type=INTERN_PREVIEW_TYPES)

    if do_objects:
        for ob in ids_nolib(bpy.data.objects):
            ob.preview.image_size = (0, 0)

    if do_groups:
        for grp in ids_nolib(bpy.data.groups):
            grp.preview.image_size = (0, 0)

    if do_scenes:
        for scene in ids_nolib(bpy.data.scenes):
            scene.preview.image_size = (0, 0)

    print("Saving %s..." % bpy.data.filepath)
    bpy.ops.wm.save_mainfile() 
Example #2
Source File: wm.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def execute(self, context):
        value = self.value
        data_path = self.data_path

        # match the pointer type from the target property to bpy.data.*
        # so we lookup the correct list.
        data_path_base, data_path_prop = data_path.rsplit(".", 1)
        data_prop_rna = eval("context.%s" % data_path_base).rna_type.properties[data_path_prop]
        data_prop_rna_type = data_prop_rna.fixed_type

        id_iter = None

        for prop in bpy.data.rna_type.properties:
            if prop.rna_type.identifier == "CollectionProperty":
                if prop.fixed_type == data_prop_rna_type:
                    id_iter = prop.identifier
                    break

        if id_iter:
            value_id = getattr(bpy.data, id_iter).get(value)
            exec("context.%s = value_id" % data_path)

        return operator_path_undo_return(context, data_path) 
Example #3
Source File: import_sprites.py    From coa_tools with GNU General Public License v3.0 6 votes vote down vote up
def move_verts(self,obj,ratio_x,ratio_y):
        bpy.ops.object.mode_set(mode="EDIT")
        bpy.ops.mesh.reveal()
        bpy.ops.object.mode_set(mode="OBJECT")
        
        shapekeys = [obj.data.vertices]
        if obj.data.shape_keys != None:
            shapekeys = []
            for shapekey in obj.data.shape_keys.key_blocks:
                shapekeys.append(shapekey.data)
        
        for shapekey in shapekeys:
            for vert in shapekey:
                co_x = vert.co[0] * ratio_x
                co_y = vert.co[2] * ratio_y
                vert.co = Vector((co_x,0,co_y))
            
            
        obj.coa_sprite_dimension = Vector((get_local_dimension(obj)[0],0,get_local_dimension(obj)[1]))
        obj.coa_tiles_x = self.tiles_x
        obj.coa_tiles_y = self.tiles_y 
Example #4
Source File: wm.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _values_store(self, context):
        data_path_iter = self.data_path_iter
        data_path_item = self.data_path_item

        self._values = values = {}

        for item in getattr(context, data_path_iter):
            try:
                value_orig = eval("item." + data_path_item)
            except:
                continue

            # check this can be set, maybe this is library data.
            try:
                exec("item.%s = %s" % (data_path_item, value_orig))
            except:
                continue

            values[item] = value_orig 
Example #5
Source File: path.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def relpath(path, start=None):
    """
    Returns the path relative to the current blend file using the "//" prefix.

    :arg path: An absolute path.
    :type path: string or bytes
    :arg start: Relative to this path,
       when not set the current filename is used.
    :type start: string or bytes
    """
    if isinstance(path, bytes):
        if not path.startswith(b"//"):
            if start is None:
                start = _os.path.dirname(_getattr_bytes(_bpy.data, "filepath"))
            return b"//" + _os.path.relpath(path, start)
    else:
        if not path.startswith("//"):
            if start is None:
                start = _os.path.dirname(_bpy.data.filepath)
            return "//" + _os.path.relpath(path, start)

    return path 
Example #6
Source File: custom_ui.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def filter_items(self, context, data, property):

        coll_list = getattr(data, property)
        filter_name = self.filter_name.lower()

        flt_flags = [self.bitflag_filter_item
            if filter_name in item.name.lower()
            else 0 for i, item in enumerate(coll_list, 1)
        ]

        if self.use_filter_sort_alpha:
            flt_neworder = [x[1] for x in sorted(
                    zip(
                        [x[0] for x in sorted(enumerate(coll_list), key=lambda x: x[1].name)],
                        range(len(coll_list))
                    )
                )
            ]
        else:
            flt_neworder = []

        return flt_flags, flt_neworder 
Example #7
Source File: common.py    From Blender-CM3D2-Converter with Apache License 2.0 6 votes vote down vote up
def remove_data(target_data):
	try: target_data = target_data[:]
	except: target_data = [target_data]
	
	for data in target_data:
		if data.__class__.__name__ == 'Object':
			if data.name in bpy.context.scene.objects:
				bpy.context.scene.objects.unlink(data)
	
	for data in target_data:
		if 'users' in dir(data) and 'user_clear' in dir(data):
			if data.users: data.user_clear()
	
	for data in target_data:
		for data_str in dir(bpy.data):
			if data_str[-1] != "s": continue
			try:
				if data.__class__.__name__ == eval('bpy.data.%s[0].__class__.__name__' % data_str):
					exec('bpy.data.%s.remove(data, do_unlink=True)' % data_str)
					break
			except: pass

# オブジェクトのマテリアルを削除/復元するクラス 
Example #8
Source File: common.py    From Blender-CM3D2-Converter with Apache License 2.0 6 votes vote down vote up
def __init__(self, ob):
		override = bpy.context.copy()
		override['object'] = ob
		self.object = ob
		
		self.slots = []
		for slot in ob.material_slots:
			if slot: self.slots.append(slot.material)
			else: self.slots.append(None)
		
		self.mesh_data = []
		for index, slot in enumerate(ob.material_slots):
			self.mesh_data.append([])
			for face in ob.data.polygons:
				if face.material_index == index:
					self.mesh_data[-1].append(face.index)
		
		for slot in ob.material_slots[:]:
			bpy.ops.object.material_slot_remove(override) 
Example #9
Source File: common.py    From Blender-CM3D2-Converter with Apache License 2.0 6 votes vote down vote up
def restore(self):
		override = bpy.context.copy()
		override['object'] = self.object
		
		for slot in self.object.material_slots[:]:
			bpy.ops.object.material_slot_remove(override)
		
		for index, mate in enumerate(self.slots):
			bpy.ops.object.material_slot_add(override)
			slot = self.object.material_slots[index]
			if slot:
				slot.material = mate
			for face_index in self.mesh_data[index]:
				self.object.data.polygons[face_index].material_index = index

# 現在のレイヤー内のオブジェクトをレンダリングしなくする/戻す 
Example #10
Source File: common.py    From Blender-CM3D2-Converter with Apache License 2.0 6 votes vote down vote up
def __init__(self, render_objects=[]):
		try: render_objects = render_objects[:]
		except: render_objects = [render_objects]
		
		if not len(render_objects):
			render_objects = bpy.context.selected_objects[:]
		
		self.render_objects = render_objects[:]
		self.render_object_names = [ob.name for ob in render_objects]
		
		self.rendered_objects = []
		for ob in render_objects:
			if ob.hide_render:
				self.rendered_objects.append(ob)
				ob.hide_render = False
		
		self.hide_rendered_objects = []
		for ob in bpy.data.objects:
			for layer_index, is_used in enumerate(bpy.context.scene.layers):
				if not is_used: continue
				if ob.layers[layer_index] and is_used and ob.name not in self.render_object_names and not ob.hide_render:
					self.hide_rendered_objects.append(ob)
					ob.hide_render = True
					break 
Example #11
Source File: script.py    From GrowthNodes with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        scriptCode = bpy.data.texts[self.textBlockName].as_string()
        scriptLocals = {}
        if len(self.inputs) > 1:
            for socket in self.inputs[1:]:
                if socket.isLinked:
                    scriptLocals[socket.text] = socket.getFromSocket.value
            for socket in self.outputs:
                scriptLocals[socket.text] = None

            comiledScript = compile(scriptCode, '<string>', 'exec')

            exec(comiledScript, None, scriptLocals)

            for socket in self.outputs:
                socket.value = str(scriptLocals[socket.text]) 
Example #12
Source File: bpy_types.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def users_id(self):
        """ID data blocks which use this library"""
        import bpy

        # See: readblenentry.c, IDTYPE_FLAGS_ISLINKABLE,
        # we could make this an attribute in rna.
        attr_links = ("actions", "armatures", "brushes", "cameras",
                      "curves", "grease_pencil", "groups", "images",
                      "lamps", "lattices", "materials", "metaballs",
                      "meshes", "node_groups", "objects", "scenes",
                      "sounds", "speakers", "textures", "texts",
                      "fonts", "worlds")

        return tuple(id_block
                     for attr in attr_links
                     for id_block in getattr(bpy.data, attr)
                     if id_block.library == self) 
Example #13
Source File: texture2.py    From GrowthNodes with GNU General Public License v3.0 6 votes vote down vote up
def initOutputData(self, resolution):
        D = bpy.data
        textureName = self.nodeTree.name + " - " + self.node.name + " - " + str(
            self.index)
        if textureName not in D.textures:
            texture = D.textures.new(textureName, "IMAGE")
        else:
            texture = D.textures[textureName]

        if textureName in D.images:
            D.images.remove(D.images[textureName])

        image = D.images.new(textureName, resolution, resolution, alpha = False,
                             float_buffer = True)

        texture.image = image
        self.value = texture.name 
Example #14
Source File: parallel_render.py    From ktba with MIT License 6 votes vote down vote up
def _run(self, scn):
        props = scn.parallel_render_panel
        props.last_run_result = 'pending'

        if _need_temporary_file(bpy.data):
            work_project_file = TemporaryProjectCopy()
        else:
            work_project_file = CurrentProjectFile()

        try:
            with work_project_file:
                self._render_project_file(scn, work_project_file.path)
            props.last_run_result = 'done' if self.state == ParallelRenderState.RUNNING else 'failed'
        except Exception as exc:
            LOGGER.exception(exc)
            props.last_run_result = 'failed' 
Example #15
Source File: parallel_render.py    From ktba with MIT License 6 votes vote down vote up
def __enter__(self):
        project_file = tempfile.NamedTemporaryFile(
            delete=False,
            # Temporary project files has to be in the
            # same directory to ensure relative paths work.
            dir=bpy.path.abspath("//"),
            prefix='parallel_render_copy_{}_'.format(os.path.splitext(os.path.basename(bpy.data.filepath))[0]),
            suffix='.blend',
        )
        project_file.close()
        try:
            self.path = project_file.name

            bpy.ops.wm.save_as_mainfile(
                filepath=self.path,
                copy=True,
                check_existing=False,
                relative_remap=True,
            )

            assert os.path.exists(self.path)
            return self
        except:
            self._cleanup()
            raise 
Example #16
Source File: custom.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 6 votes vote down vote up
def invoke(self, context, event):
        if self.armatures:
            armature = context.scene.objects[self.armatures]
            bpy.ops.object.mode_set(mode="OBJECT")

            bpy.ops.object.select_all(action='DESELECT')
            armature.select_set(state=True)
            context.view_layer.objects.active = armature

            bpy.ops.object.mode_set(mode="EDIT")
            data = armature.data
            self.armature = data.name

            bones_builder.nuke_mixamo_prefix(data.edit_bones)

            bpy.ops.object.mode_set(mode="OBJECT")
            automatic_bind_bones(self, data.bones)

        return context.window_manager.invoke_props_dialog(self, width=600) 
Example #17
Source File: custom_ui.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def draw_item(self, context, layout, data, item, icon, active_data, active_property, index, flt_flag):
        col = layout.column()
        col.prop(item, 'name', text='', emboss=False)
        col = layout.column()
        col.prop(item.v3d, 'enable_export', text='') 
Example #18
Source File: parallel_render.py    From ktba with MIT License 5 votes vote down vote up
def __enter__(self):
        self.path = bpy.data.filepath
        return self 
Example #19
Source File: parallel_render.py    From ktba with MIT License 5 votes vote down vote up
def _need_temporary_file(data):
    return data.is_dirty 
Example #20
Source File: custom.py    From Blender-Metaverse-Addon with GNU General Public License v3.0 5 votes vote down vote up
def get_bones(self, context):

    armature = context.scene.objects.get(self.custom_armatures)

    print("--- get bones", armature)
    if armature is None:
        return
    return [(bone.name, bone.name, "") for bone in armature.data.bones] 
Example #21
Source File: mixamo_utilities_panel.py    From Godot_Game_Tools with GNU General Public License v2.0 5 votes vote down vote up
def draw(self, context):
        layout = self.layout
        scene = context.scene
        tool = scene.godot_game_tools
        ob = tool.target_object
        layout.template_list("ACTION_UL_list", "", bpy.data, "actions", scene, "action_list_index")
        box = layout.box()
        box.operator("wm_ggt.animation_player", icon="PLAY")
        box.operator("wm_ggt.animation_stop", icon="PAUSE")
        # box.prop(tool, "action_name")
        # box.operator("wm_ggt.rename_animation", icon="ARMATURE_DATA")
        box.operator("wm_ggt.add_animation_loop", icon="COPYDOWN")
        box.operator("wm_ggt.push_nlas", icon="ANIM_DATA")
        # box.operator("wm_ggt.character_export", icon="EXPORT")
        box.separator() 
Example #22
Source File: mixamo_utilities_panel.py    From Godot_Game_Tools with GNU General Public License v2.0 5 votes vote down vote up
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
        custom_icon = "ANIM_DATA"
        # Make sure your code supports all 3 layout types
        if self.layout_type in {'DEFAULT', 'COMPACT'}:
            layout.prop(item, "name", text="", emboss=False, icon=custom_icon)
        elif self.layout_type in {'GRID'}:
            pass 
Example #23
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
        
        layout.label(item.name,icon='RENDER_RESULT')
        layout.operator('2dviews.view_image',text="",icon='RESTRICT_VIEW_OFF',emboss=False).image_name = item.name
        layout.operator('2dviews.delete_image',text="",icon='X',emboss=False).image_name = item.name 
Example #24
Source File: parallel_render.py    From ktba with MIT License 5 votes vote down vote up
def draw(self, context):
        layout = self.layout
        if _need_temporary_file(bpy.data):
            _add_multiline_label(
                layout,
                [
                    'Unsaved changes to project.',
                    'Will attempt to create temporary file.',
                ],
                icon='ERROR',
            )

        layout.row().label(text='Will render frames from {} to {}'.format(context.scene.frame_start, context.scene.frame_end)) 
Example #25
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
        
        if item.mv.plan_view_scene or item.mv.elevation_scene:
            layout.label(item.mv.name_scene,icon='RENDER_REGION')
            layout.prop(item.mv, 'render_type_2d_view', text="")
            layout.prop(item.mv, 'elevation_selected', text="")
        else:
            layout.label(item.name,icon='SCENE_DATA') 
Example #26
Source File: bpy_restrict_state.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        self.data = _bpy.data
        self.context = _bpy.context
        _bpy.data = _data_restrict
        _bpy.context = _context_restrict 
Example #27
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def draw(self, context):
        layout = self.layout
        scene = context.scene
        panel_box = layout.box()
        
        row = panel_box.row(align=True)
        row.scale_y = 1.3
        
        elv_scenes = []
        for scene in bpy.data.scenes:
            if scene.mv.elevation_scene:
                elv_scenes.append(scene)
                
        if len(elv_scenes) < 1:
            row.operator("fd_2d_views.genereate_2d_views",text="Prepare 2D Views",icon='RENDERLAYERS')
        else:
            row.operator("fd_2d_views.genereate_2d_views",text="",icon='FILE_REFRESH')
            row.operator("fd_2d_views.create_new_view",text="",icon='ZOOMIN')
            row.operator("2dviews.render_2d_views",text="Render Selected Scenes",icon='RENDER_REGION')
            row.menu('MENU_elevation_scene_options',text="",icon='DOWNARROW_HLT')
            panel_box.template_list("LIST_scenes", 
                                    " ", 
                                    bpy.data, 
                                    "scenes", 
                                    bpy.context.window_manager.mv, 
                                    "elevation_scene_index")
            
        image_views = context.window_manager.mv.image_views
        
        if len(image_views) > 0:
            panel_box.label("Image Views",icon='RENDERLAYERS')
            row = panel_box.row()
            row.template_list("LIST_2d_images"," ",context.window_manager.mv,"image_views",context.window_manager.mv,"image_view_index")
            col = row.column(align=True)
            col.operator('fd_2d_views.move_2d_image_item', text="", icon='TRIA_UP').direction = 'UP'
            col.operator('fd_2d_views.move_2d_image_item', text="", icon='TRIA_DOWN').direction = 'DOWN'
            panel_box.menu('MENU_2dview_reports',icon='FILE_BLANK')
#             panel_box.operator('2dviews.create_pdf',text="Create PDF",icon='FILE_BLANK') 
Example #28
Source File: bpy_restrict_state.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def __exit__(self, type, value, traceback):
        _bpy.data = self.data
        _bpy.context = self.context 
Example #29
Source File: wm.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def execute(self, context):
        import os
        import shutil
        ver = bpy.app.version
        ver_old = ((ver[0] * 100) + ver[1]) - 1
        path_src = bpy.utils.resource_path('USER', ver_old // 100, ver_old % 100)
        path_dst = bpy.utils.resource_path('USER')

        if os.path.isdir(path_dst):
            self.report({'ERROR'}, "Target path %r exists" % path_dst)
        elif not os.path.isdir(path_src):
            self.report({'ERROR'}, "Source path %r does not exist" % path_src)
        else:
            shutil.copytree(path_src, path_dst, symlinks=True)

            # reload recent-files.txt
            bpy.ops.wm.read_history()

            # don't loose users work if they open the splash later.
            if bpy.data.is_saved is bpy.data.is_dirty is False:
                bpy.ops.wm.read_homefile()
            else:
                self.report({'INFO'}, "Reload Start-Up file to restore settings")

            return {'FINISHED'}

        return {'CANCELLED'} 
Example #30
Source File: console_python.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def copy_as_script(context):
    sc = context.space_data
    lines = [
        "import bpy",
        "from bpy import data as D",
        "from bpy import context as C",
        "from mathutils import *",
        "from math import *",
        "",
    ]

    for line in sc.scrollback:
        text = line.body
        type = line.type

        if type == 'INFO':  # ignore autocomp.
            continue
        if type == 'INPUT':
            if text.startswith(PROMPT):
                text = text[len(PROMPT):]
            elif text.startswith(PROMPT_MULTI):
                text = text[len(PROMPT_MULTI):]
        elif type == 'OUTPUT':
            text = "#~ " + text
        elif type == 'ERROR':
            text = "#! " + text

        lines.append(text)

    context.window_manager.clipboard = "\n".join(lines)

    return {'FINISHED'}