r/blenderpython • • Aug 02 '19

attaching events to buttons via blender api

2 Upvotes

How do I attach callback functions to buttons? I created button using this code:

    class RigLayers(bpy.types.Panel):
        bl_idname = 'POSE_PT_RigLayers'
        bl_label = "Rig Layers"
        bl_space_type = "VIEW_3D"
        bl_region_type = "UI"
        bl_context = "posemode"
        bl_category = CUSTOM_CATEGORY
        
        bone_groups ={
                    
                    'Root bone': 0,
                    'FK bones': 1,
                    'IK bones': 2,
                    'Facial bones':3,
                    'Manual spine':14
        }
        
        control_layers = [0,1,2,3,14]
        total_layers = 20  
    def draw(self, context):
            column = self.layout.column() #items are placed under each other in a column
            
            column.prop(context.scene, "switch_mode")
            contexts = []
            if context.scene.switch_mode==False:
                for item in self.bone_groups.keys():
    
                    column.prop(context.active_object.data, 'layers',
                     index=self.bone_groups[item],
                     toggle=True, text=item, 
                     emboss=True)  

now there are basically 5 buttons created inside the for loop. But, I'd want to associate each button with a specific callback in addition to it's behaviour of toggling the bone layers. Any help would really be appreciated.


r/blenderpython • • Feb 25 '22

My new addon | Procedural Building Design and Construction

Thumbnail
youtu.be
12 Upvotes

r/blenderpython • • Nov 21 '22

Optic flow in Blender Python 2.79

6 Upvotes

Hey All! I am making some motion animation videos through blender python and was wondering if getting the optic flow for the objects moving in the animation video created could be retrieved somehow through blender python.

I am using blender python version 2.79.


r/blenderpython • • Jun 29 '24

Loader/progress

2 Upvotes

I have a bpy script that can take some time to execute. It basically freezes Blender. Is there any way to show a loader or something while my bpy script is executing?


r/blenderpython • • Mar 18 '21

How to bake physics via python for Blender 2.9x?

5 Upvotes

The method I used to use only works for 2.7x and not for 2.8x and 2.9x. Anyone have a good way to do this for 2.9x for fluid simulation?


r/blenderpython • • Feb 19 '21

Check if object is duplication of other object through python

3 Upvotes

Hello!

I'm writing an export script for my scenes in blender to use in a custom game engine. If I create a house and name it "House" and then duplicate it, it gets named "House.001" by default. When I loop through the objects in the scene in python, is there a way to check if an object is a duplication of another object and therefor has the same mesh? It would be helpful to not have to save (and later load) the geometry data more than once when it's the same.

I could of course just assume that all objects with names ending with ".00X" is a duplication, but that would lead to problems if I change the name of the object or if I modify the object without changing the name.

Thanks for help!


r/blenderpython • • Jan 02 '19

How to keyframe smoke flow particle size via python script

Thumbnail
blender.stackexchange.com
2 Upvotes

r/blenderpython • • Sep 29 '18

How do I name a selected group via python script

Thumbnail
blender.stackexchange.com
1 Upvotes

r/blenderpython • • Jan 02 '20

Ray casting and bounding boxes

3 Upvotes

Hello everybody!

I've already explained my problem in this post on SO. Basically I need to identify bounding boxes for the objects in the rendered image, but only accounting for the portion of the object which is in view, not the one behind other objects. I've tried using the scene.ray_cast function, but that gives highly incorrect results.

I need this in order to generate synthetic images as a training dataset for a neural network, but I'm really stuck on this point and I won't get my MSc degree in space engineering if I don't solve it LOL

Please, someone help me


r/blenderpython • • Jan 04 '19

How to change the font size of a text row inside a script via python

Thumbnail
blender.stackexchange.com
1 Upvotes

r/blenderpython • • Nov 22 '23

MatLayer 2

1 Upvotes

Hi everyone,

I’ve been working for the past 5 months, putting roughly 6 – 10 hours a day (in addition to some of my heart and soul) to create the next version of my Blender add-on.

I’m very proud to announce the release of MatLayer 2!

For those who are not familiar, MatLayer is a 100% free Blender add-on that wraps the material nodes with a layer based user interface. This allows instant mixing of full PBR materials, emulation of industry leading material creation workflow, and implementation of many essential features for a fast and efficient material editing workflow.

Some of the main features of this add-on currently includes:

- A one-click mesh map baker for baking ambient occlusion, curvature, thickness, world space normals, and high to low poly normal maps, all heavily optimized to bake mesh maps as fast as possible.

- Fast, full PBR material layering, with lots of control, and built-in filters like blurring.

- Fast, optimized masking and multi-masking for materials.

- A toggle for true tri-planar projection (with corrected normals)!

- Auto-corrections for normal map projections.

- Decal layers for non-destructive projection of text / stickers.

- Basic support for merging materials.

- Fast effects for edge wear and dirt.

- Fast importing of full PBR texture sets.

- One-click exporting for texture sets with automatic channel packing for commonly used software applications and formats.

- An exporting options for baking multiple material slots to a single texture set.

The main focus of this release was initially better performance, bug fixes and stability, but I’ve implemented some massive improvements to workflow, quality and many new features!

To get MatLayer 2, and to see a full list of features and new changes in this version you can check out the latest release on the Github - https://github.com/LoganFairbairn/matlayer/releases

I plan on creating a new tutorial series, within the near future to help explain workflow and features available in the software.

Although MatLayer is still not a perfect software, I really hope you enjoy this add-on, I’ve put many long days and nights into this. I’m hoping this gives users the freedom to create some new amazing materials for their 3D models within Blender.

This add-on is my personal thank you to the Blender developers for making such an amazing software, and to the community for keeping it charged.

Cheers, and happy blending!


r/blenderpython • • Nov 14 '23

Getting text data from geometry nodes

1 Upvotes

I've created a modifier that creates shapes using the bounding box data of an object. I now need to write the parameters (size, rotation, etc) of those shapes to a text file. I figured the best way to do that would be to grab the data from the node outputs but I'm having trouble with that. I can't seem to get anything to print using python.

For instance I have the X length of the bounding box using a "Separate XYZ" node which is a float. When I enter "bpy.data.node_groups["Modifier"].nodes["Separate XYZ.001"].outputs[0].default_value[1]" I get "'float' object is not subscriptable". When I try to convert it to a string in the text editor using "str()" I just get the same error. When I use the convert float to string node and try to print that the value is empty. I just get " ".

Any thoughts on how I can write the outputs of nodes to text?


r/blenderpython • • Dec 11 '23

Script Update 4.0 Component Space

1 Upvotes

Hello,
I have this script from blender 3.3 that I would like to use in 4.0. Select a face and the script will move the orientation to the face.

3.6

import bpy

class ComponentSpace(bpy.types.Operator):

bl_label = 'Component Space'

bl_idname = 'wm.setcomponentspace'

def execute(self, context):

for area in bpy.context.screen.areas:

if area.type == 'VIEW_3D':

ctx = bpy.context.copy()

ctx['area'] = area

ctx['region'] = area.regions[-1]

orientName = 'tempOrientation'

bpy.ops.transform.create_orientation(name=orientName)

bpy.context.scene.transform_orientation_slots[0].type = orientName

bpy.ops.object.editmode_toggle()

bpy.context.scene.tool_settings.use_transform_data_origin = True

matrix = bpy.context.scene.transform_orientation_slots[0].custom_orientation.matrix

bpy.ops.transform.transform(mode='ALIGN', orient_matrix=matrix)

bpy.ops.object.editmode_toggle()

bpy.ops.view3d.snap_cursor_to_selected(ctx)

bpy.ops.object.editmode_toggle()

bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')

bpy.context.scene.tool_settings.use_transform_data_origin = False

bpy.ops.transform.delete_orientation()

bpy.context.scene.transform_orientation_slots[0].type = 'LOCAL'

break

return {'FINISHED'}

addonKeymaps = []

def register():

bpy.utils.register_class(ComponentSpace)

windowManager = bpy.context.window_manager

keyConfig = windowManager.keyconfigs.addon

if keyConfig:

keymap = keyConfig.keymaps.new(name='3D View', space_type='VIEW_3D')

keymapitem = keymap.keymap_items.new('wm.setcomponentspace', type='F', shift=True, value='PRESS')

addonKeymaps.append((keymap, keymapitem))

def unregister():

for keymap, keymapitem in addonKeymaps:

keymap.keymap_items.remove(keymapitem)

addonKeymaps.clear()

bpy.utils.unregister_class(ComponentSpace)

if __name__ == '__main__':

register()


r/blenderpython • • Nov 26 '23

Use a scipt to control an object by acceleration or velocity in real time

2 Upvotes

Hi, I'm trying to use Blender to simulate a vehicle to test the autonomous navigation I'm working on. To be able to do this you would need to be able to give, preferably, an acceleration setpoint to the vehicle, or a speed setpoint, to be able to move the vehicle through the simulation in real time. Do you know if there is any way to do it? or any addon that makes it easier?


r/blenderpython • • Nov 27 '23

MatLayer 2.0.2 is out! (free, layer based PBR material editing add-on)

4 Upvotes

https://github.com/LoganFairbairn/matlayer/releases

Feel free to fiddle with the code!

This release fixes some major bugs with mesh map baking, toggling material channels on / off and implements better options for managing external textures.

Change Log:

- Removed the icon from the load export template menu because it wasn't required and was identical to the icon used in the save export template operator.

- Fixed many issues with toggling on / off material channels in the texture set settings.

- Fixed mesh maps saving in the wrong resolution when using upscaling.

- Changed baked mesh maps to save in uncompressed png format, instead of open exr. This also fixes the bug where images were saving as png files with an exr extension.

- Changed baked mesh maps to save in their own folder.

- Made all folder properties store in the blend file, instead of in add-on preferences. This means users can have unique folder paths per blend which is much more useful.

- Made it possible to define custom paths for custom folders for all images MatLayer saves externally.

- Added the ability to mark debug log messages as errors or warnings.

- Removed auto snapping adjustments when selecting layers. This auto snapping adjustment feature implemented to make it easier to move decal layer objects was more annoying and confusing for users than it was helpful.

- Updated the MatLayer BSDF to be more compatible with Blender 4.0. This improved performance slightly, but makes Blender 3.6 materials no longer compatible.


r/blenderpython • • Oct 25 '23

My simple add-on won't install - traceback error

1 Upvotes

Hello, so I have a very simple add-on. If I run it in the Scripting workspace, all is well.

If I try to install the .py file as an add-on through Preferences, I receive this error. Any ideas as to what's happening here?

Thanks in advance


r/blenderpython • • Oct 29 '23

Interjecting a python script within the "render" path.

1 Upvotes

When you click "render" or "render animation" (or use the command line -f or -a) is there a way you can hook into those using python? I have multiple cameras with different rendering resolution for X and Y. So I need to mess with bpy.data.scenes["Scene"].render.resolution_y and bpy.data.scenes["Scene"].render.resolution_x before the render.

I can write a script to mimic -a or -f via the command line, but it would be nicer to hook into the existing UI buttons and CLI options.


r/blenderpython • • Jan 25 '15

Learning Python

2 Upvotes

Hello everybody! I'm learning python so i was wondering what kind of things could i do in Blender as a beginner at this language? I feel like exercising the use of python inside Blender could help me learn the language.


r/blenderpython • • Apr 04 '14

Your favorite use of blender python.

4 Upvotes

And if it is different, what do you use it for the most often?


r/blenderpython • • Jan 31 '15

Collection of helpful scripts!

5 Upvotes

Iterate over objects belonging to a group:

import bpy

group = bpy.data.groups['GroupName']

for obj in bpy.data.objects: 
        if(group in obj.users_group):
            #Do stuff here


Apply location, rotation and scale of all objects in scene

import bpy

for obj in bpy.data.objects:
        obj.select = True
        bpy.ops.object.transform_apply(location=True,rotation=True,scale=True)
        obj.select = False


Set all objects origin to their geometry

import bpy

for obj in bpy.data.objects:
    if obj.type == 'MESH':
        obj.select = True
        bpy.context.scene.objects.active = obj
        bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')
        obj.select = False


Remove doubles for every object in the scene

import bpy

for obj in bpy.data.objects:
    if obj.type == 'MESH':
        obj.select = True
        bpy.context.scene.objects.active = obj
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.remove_doubles()
        bpy.ops.object.mode_set(mode='OBJECT')
        obj.select = False


Render animation (Blender Internal)


import bpy
nframes = 150
scene = bpy.data.scenes['Scene']
scene.frame_current =1
for n in range(0,nframes):
    scene.render.filepath = "C:/temp/"+str(scene.frame_current)
    bpy.ops.render.render(write_still =True)
    bpy.data.scenes['Scene'].frame_current +=1


Write keyframe to file


import bpy

obj = bpy.context.active_object
scn = bpy.context.scene
scn.frame_set(1)
fileID = "C:/temp/"+obj.name+".txt"
f = open(fileID,'a')
nframes=150
for n in range(0,nframes):
    f.write(str(n)+","+str(obj.location.x)+","+str(obj.location.y)+","+str(obj.location.z)+","+str(obj.rotation_euler[0])+","+str(obj.rotation_euler[1])+","+str(obj.rotation_euler[2])+","+str(obj.scale.x)+","+str(obj.scale.y)+","+str(obj.scale.z)+"\n")
    scn.frame_set(n)
f.close()


Insert keyframes from textfile

(Textformat: frame,loc_x,loc_y,loc_x,rot_x,rot_y,rot_z,scl_x,scl_y,scl_z)


import bpy

scn = bpy.context.scene

obj = scn.objects['Cube']

fileID = "C:/temp/"+obj.name+".txt"

f = open(fileID,'r')

for line in f:
    temp = line.split(',')
    obj.location = (float(temp[1]),float(temp[2]),float(temp[3]))
    obj.rotation_euler = (float(temp[4]),float(temp[5]),float(temp[6]))
    obj.scale = (float(temp[7]),float(temp[8]),float(temp[9]))
    obj.keyframe_insert(data_path="location", frame=float(temp[0]))
    obj.keyframe_insert(data_path="rotation_euler", frame=float(temp[0]))
    obj.keyframe_insert(data_path="scale", frame=float(temp[0]))
f.close()


Remove all materials in a scene


import bpy

for obj in bpy.data.objects:
    if obj.type == 'MESH':
        while len(obj.material_slots) > 0:
            obj.select = True
            bpy.context.scene.objects.active = obj
            bpy.ops.object.material_slot_remove()
            obj.select = False


More to be added. In the mean time feel free to contribute!


r/blenderpython • • Feb 02 '15

Looking to hire blender/python person for contract.

2 Upvotes

We need a way of automatically generating images of cropland using a combination of Blender, pre-generated plant models, and Blender/Python scripting. We are looking for someone experienced with Blender and scripting to create a realistic ground/environmental model (the ground texture may be procedurally generated, but must be realistic); and a script that places pre-generated plant models in rows to simulate cropland. the script must also contain parameters controlling camera position, lighting conditions and sun position, and parameters such as plant spacing; allowing us to alter (and randomise) the scene that is generated. The scene must render in Blender, and be photorealistic.

Plant models are available using tools such as the Plant Factory. The deliverables are the realistic ground/environmental model; and the parametrised script to generate scenes.


r/blenderpython • • Sep 11 '17

moving vertices over time in python

2 Upvotes

hi there,

im new to bpy and i just wanted to mess around and try things. right now i want to manipulate vertices of a cube over time. my goal is to make a wabbling cube with the sin function. the example below is a reduced example where i just want to manipulate the vertices.

the thing im struggeling with is, i don't know how to make those changes visible each time i changed the vertex coordinates. When i run the script blender kinda freezes for 5 second and then i see the end result. i want to see the transition.

import bpy
import time
from math import sin

cube = bpy.data.objects['Cube']
start_second = time.time()
end_second = start_second + 10

while start_second < end_second:
    t = time.time()
    for vertex in cube.data.vertices:
        vertex.co.x = sin(t/10.0)*2.0

    start = time.time()

so how is that done right :)


r/blenderpython • • Dec 08 '24

Is Numpy always pre-installed in Blender?

5 Upvotes

Hello everyone!
I'm working on an add-on that uses numpy and, until now, I wrote a "double" of any numpy-using function without numpy, that is slower but allows users without numpy to test the add-on without all installing story. But now I need some function that is difficult to implement by myself (matrix inverse, and matrix can be larger than 4x4).
I tested Blender on Ubuntu and Windows, and it seems that numpy is pre-installed. Is it true? Do people still use older versions without this feature?
The feature that needs matrix inverse is not a core feature, I can work-around it if numpy is a problem for someone.
Thanks for your thoughts!


r/blenderpython • • Oct 30 '24

[HELP] Cant get proper obj copies from alembic frames

1 Upvotes

I am currently working on a vertex animation texture generation inside blender and I got pretty far, I specifically was working on remeshing water simulations to always use constant amount of vertecies/polygons.

But now I wanted to debug it with a simple Icosphere rolling down from a slope,

The problem is Bender refuses to make correct copies and get the correct vertex position data even tho it fully works for imported alembic files of water drops but not a simple rigid body simulation?

They both are mesh cash animated objects inside blender and the script expects them to be

relevant function from my script:

https://pastebin.com/cc96nB5j