r/blenderpython • • May 22 '21

Deleting script-generated objects each time I run my script

4 Upvotes

What is the best practice so that every time I run my script, the objects created in the previous execution are deleted?

I want to create a setup() function and a corresponding teardown() function so to speak.


r/blenderpython • • May 05 '21

Mesh Validation in Python?

4 Upvotes

Hey People,

Im working on a generator for 3D models to print afterwards.
Since its based on different parameters that influence the result, I would want to be able to do some simple quality check afterwards. Mainly about topics like:
* is the mesh closed?
* are there any intersections of faces?
* is it one coherent object or somehow split into multiple ones?

So far I found https://github.com/WoLpH/numpy-stl which is nice but only covers the first question easily.

I wondered if any of you ever tried to do some kind of automated quality check on a 3D model with python.

PS: I guess it would be an option to just code those checks by hand, but this would take me quite a while and I thought I cannot be the first one with this need, and that smth like this likely already exists.

Any Ideas?

Super highly appreciated!

Thhhaannkss! :)


r/blenderpython • • Sep 07 '20

How do you get the World material in Python?

4 Upvotes

So for an object material you can get it using:

bpy.data.materials.get("Dark Trees.001")

but this has not been working if i use:

bpy.data.materials.get("World")

is there a different way you have to get the World material?


r/blenderpython • • Sep 04 '20

Need help setting up a "Time" variable that controls multiple mix shaders across multiple materials

4 Upvotes

So as i havent had any experience with Python coding in Blender, i am wondering if this is possible and if so how to do it.

I essentially want to have a variable “Time” that can be key framed, and depending on that variable change multiple mix shaders from 1 to 0 or from 0 to 1 independent from one another across multiple materials. For example:

If “time” = 12, then set “mix shader 001” = 1 and “mix shader 002” = 0

But with many more mix shaders.

What i am trying to do is keyframe the switching of the background material to make a bunch of day/night cycles. I could keyframe the mix shaders manually but if i could just keyframe a time variable that controls the mix shaders it would make it much quicker and less cluttered. Pretty sure this is possible within the node editor with a ton of math nodes set to compare, but like i said if there is a less cluttered way to go about it i would want to do it that way.

Thanks!


r/blenderpython • • Jul 30 '20

Save selected objects in different blender files

4 Upvotes

Hello everyone,

What I'm trying to do is fairly simple but I've found no way to do it. I want to store each object in a scene into a separate blender file. Here's my code:

import bpy
import os

destination_folder = "destination_folder"

for idx, obj in enumerate(bpy.data.objects):

    ctx = bpy.context.copy()
    ctx['selected_objects'] = obj
    file_name = 'file_number' + str(idx) + '.blend'
    bpy.ops.wm.save_as_mainfile(ctx, filepath=os.path.join(destination_folder, file_name))

The problem is that the operator bpy.ops.wm.save_as_mainfile() doesn't have the flag "selected" as many others wm operators do. Any idea? I think context override is a good idea but I'm struggling to do it

I've posted the question on blender stackexchange too: https://blender.stackexchange.com/questions/188113/save-objects-into-separate-blender-files?noredirect=1#comment315486_188113

Edit: for the solution check the link to blender stackexchange. thanks u/dustractor for helping me out


r/blenderpython • • Jun 25 '20

How to set an NLA strip to active?

4 Upvotes

Hi, I wonder how to make an NLA strip to be activated by a script.
I try to achieve the goal through

bpy.context.object.animation_data.nla_tracks.active.strips[0].active

but it only returns a bool and it’s readonly.

How should I do it?


r/blenderpython • • May 02 '20

Creating animations / curves from simulations in python.

4 Upvotes

Most things for now I have seen regarding python with Blender is connected to Artists trying to automatize repetitive workflow. I'm interested in doing simulations with python and then python to create curves / animations from this simulation data.

As a first project I had a simple pendulum in mind.

If somebody could point me into the right direction it would be wonderful.


r/blenderpython • • Apr 19 '20

A step towards 3d L1 voronoi

4 Upvotes

Seems missing from the internets, 3d taxi/manhattan voronoi. So, here's a step in that direction, a function to create a mesh to be intersected with other HalfCubes until a cell is completed (all verts are equal-L1-distant to c1 as c2)

def HalfCube(c1,c2,S):
   d = c1-c2
   cc = (c2-c1)/2
   
   bm = bmesh.new()
   bmesh.ops.create_cube(bm, size=1)
   bmesh.ops.scale(bm, vec=[abs(n) for n in d], verts=bm.verts[:])
   bmesh.ops.translate(bm,vec=cc,verts=bm.verts[:])
   # corner of box at (0,0,0) is c1
   
   geom = bm.verts[:] + bm.edges[:] + bm.faces[:]
   bmesh.ops.bisect_plane(bm, geom=geom, 
      plane_co=cc, plane_no=[sgn(n) for n in d],
      use_snap_center=False,clear_inner=True)
   
   c12 = [(0,0,0),(c2-c1)]
   
   for vert in bm.verts:
      x,y,z = vert.co
      p = [x,y,z]
      for c in c12:
         for i in [0,1,2]:
            if abs( p[i]-c[i] ) < epsilon:
               p[i] = c[i]
      vert.co = p
   
   SSS = mathutils.Vector((S,S,S))
   pMin = cc-SSS
   pMax = cc+SSS
   
   b1 = [(pMin[i] if c1[i]<c2[i] else pMax[i]) for i in [0,1,2]]
   b2 = [(pMin[i] if c1[i]>c2[i] else pMax[i]) for i in [0,1,2]]
   b12 = b1,b2
   
   for j in [0,1]:
      c = c12[j]
      b = b12[j]
      for i in [0,1,2]:
         cn = c[i]
         bn = b[i]
         geom = set()
         pci = None
         for f in bm.faces:
            p = f.calc_center_median()
            pn = p[i]
            if abs(pn-cn) < epsilon:
               geom.add(f)
               for v in f.verts: geom.add(v)
               for e in f.edges: geom.add(e)
         
         d = [0,0,0]
         d[i] = b[i]-c[i]
         ret = bmesh.ops.extrude_face_region(bm, geom=list(geom))
         va = [v for v in ret['geom'] if type(v) is bmesh.types.BMVert]
         bmesh.ops.translate(bm,vec=d,verts=va)
   
   bound_edges = [e for e in bm.edges if e.is_boundary]
   bmesh.ops.edgeloop_fill(bm, edges=bound_edges)
   
   me = bpy.data.meshes.new('mesh');bm.to_mesh(me);bm.free()
   obj = bpy.data.objects.new('halfCube', me)
   bpy.context.collection.objects.link(obj)
   obj.location = c1
   return obj

I'm still working on the full voronoi generator, but crazy times we live in, who knows what tomorrow holds, so I'll just leave this here. The world needs 3d printed voronoi crap in non-euclidean metrics, too!


r/blenderpython • • Apr 14 '20

Live visualisation of Coronavirus cases - in Blender! Just uses a script to download data and the pandas library to manipulate it

Thumbnail thumbs.gfycat.com
4 Upvotes

r/blenderpython • • Feb 21 '20

Requesting blender script or add-on upgrade?

4 Upvotes

Hopefully this isn't asking to much, but I am at my wits end.

I have been trying to find a script or add-on that would allow me to select vertices by the number of vertex groups they belong to.

The reason I titled this post "or add-on upgrade" is because I did find an add-on that can do this.

The problem is that this add-on is for Blender 2.6, so it won't work for new version of Blender.

https://github.com/cessen/blender_vg_tools

If anyone is willing to help me out, I would be very thankful.


r/blenderpython • • Jan 14 '20

Python crashes blender from big array loop

4 Upvotes

Hey all so I wrote a blender script that duplicates an object, rotates it, and eventually creates a mosaic

data looks like this:

[x,x,x, o,o,o, x,x,x,]

where x is 90 degrees and o is 180, for example. Creating a "board" of the rotated objects

the problem is that my mosaic is 17,000 objects big and blender crashes when ever I run the script..it worked great when I was only doing 30/40 objects in testing but 17k is just too much

script does this:

  1. duplicates active object and moves to the right (or down and to the left if its the end of the row)

  2. rotates that object

  3. repeat!

I'm fairly new to blender, a few donut and modeling tutorials in. Should I be going about this another way?I tried to run the script on the starter cube and that crashed too so its not poly count

also, I tried `time.sleep(0.1)` to try and slow it down or something it but that also crashes

import bpy.ops
from math import radians
from mathutils import Matrix
import time

def move_obj(x, y, z):
   bpy.ops.object.duplicate_move(OBJECT_OT_duplicate={"linked":False, "mode":'TRANSLATION'}, TRANSFORM_OT_translate={"value":(x, y, z), "orient_type":'GLOBAL', "orient_matrix":((1, 0, 0), (0, 1, 0), (0, 0, 1)), "orient_matrix_type":'GLOBAL', "constraint_axis":(True, False, False), "mirror":True, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "gpencil_strokes":False, "cursor_transform":False, "texture_space":False, "remove_on_cancel":False, "release_confirm":False, "use_accurate":False})




def rotate_object(rot_mat):
    obj = bpy.context.active_object
    orig_loc, orig_rot, orig_scale = obj.matrix_world.decompose()

    orig_loc_mat = Matrix.Translation(orig_loc)
    orig_rot_mat = orig_rot.to_matrix().to_4x4()
    orig_scale_mat = (Matrix.Scale(orig_scale[0],4,(1,0,0)) @
                      Matrix.Scale(orig_scale[1],4,(0,1,0)) @
                      Matrix.Scale(orig_scale[2],4,(0,0,1)))

    obj.matrix_world = orig_loc_mat @ rot_mat @ orig_rot_mat @ orig_scale_mat



#rotate_object( Matrix.Rotation(radians(90), 4, 'X')) #2
#rotate_object( Matrix.Rotation(radians(270), 4, 'Z')) #3
#rotate_object( Matrix.Rotation(radians(270), 4, 'X')) #4
#rotate_object( Matrix.Rotation(radians(90), 4, 'Z')) #5
#rotate_object( Matrix.Rotation(radians(180), 4, 'X')) #6

def rotate_dice(num):
    if num == 2: rotate_object( Matrix.Rotation(radians(90), 4, 'X')) #2
    if num == 3: rotate_object( Matrix.Rotation(radians(270), 4, 'Z')) #3
    if num == 4: rotate_object( Matrix.Rotation(radians(270), 4, 'X')) #4
    if num == 5: rotate_object( Matrix.Rotation(radians(90), 4, 'Z')) #5
    if num == 6: rotate_object( Matrix.Rotation(radians(180), 4, 'X')) #6

def rotate_to_one(num): 
    if num == 2: rotate_object( Matrix.Rotation(radians(-90), 4, 'X')) #2
    if num == 3: rotate_object( Matrix.Rotation(radians(-270), 4, 'Z')) #3
    if num == 4: rotate_object( Matrix.Rotation(radians(-270), 4, 'X')) #4
    if num == 5: rotate_object( Matrix.Rotation(radians(-90), 4, 'Z')) #5
    if num == 6: rotate_object( Matrix.Rotation(radians(-180), 4, 'X')) #6

def dup(to, fro, x, z):
    move_obj(x, 0, z)
    rotate_to_one(fro)
    rotate_dice(to)



dice_arr = [1,2,3,4,5,1,2,3,4,5] // actually 17,000 entries long (removed for post)
break_on = 119 # go back to the left and start a new row of mosaic

def run_arr():
    counter = 0
    last_index = 1
    movement_amount = 2.075
    count = 0

    for i in dice_arr: 
        if count == break_on: 
            dup(i, last_index, -movement_amount * break_on, -movement_amount) 
            count = 0
        else: 
            count = count + 1
            dup(i, last_index, movement_amount, 0)

        last_index = i
        time.sleep(0.1)



run_arr()

r/blenderpython • • Nov 11 '19

Made with blender python.

Thumbnail
youtu.be
4 Upvotes

r/blenderpython • • Dec 04 '18

Python Tutorial: 3D Wrecking Animation With 14 Lines of Code

Thumbnail
youtube.com
4 Upvotes

r/blenderpython • • Oct 28 '18

Python Tutorial: 3D Wrecking Animation With 14 Lines of Code

Thumbnail
youtube.com
4 Upvotes

r/blenderpython • • Jul 10 '18

Is there any way to export the last frame of a physics simulation as a .stl file from the command line?

4 Upvotes

I have a basic rigid body physics sim, but I want to export the last frame of the simulation. So far I have tried setting the "current frame to the last frame of the simulation and exporting it that way, but that doesn't work.

import bpy
from random import randint
import os

bpy.types.Area.type = 'VIEW_3D'

#Duplicates bottles "b" times
bpy.ops.object.select_all(action='DESELECT')
b = int(input("Number of bottles: "))
if b == 0:
    bpy.data.objects['Bottle'].select = True
    bpy.ops.object.delete()
    bpy.ops.object.select_all(action='DESELECT')
elif b > 0:
    for x in range(0, b-1):
        bpy.data.objects['Bottle'].select = True
        bpy.ops.object.duplicate(linked=False)
        bpy.ops.object.select_all(action='DESELECT')

#Select all objects other than the suitcase
bpy.ops.object.select_all(action='SELECT')
bpy.data.objects['Suitcase'].select = False

# store the location of current 3d cursor
saved_location = bpy.context.scene.cursor_location.copy()  # returns a copy of the vector

# give 3dcursor new coordinates
bpy.context.scene.cursor_location = (0.0,0.0,0.0)

# set the origin on the current object to the 3dcursor location
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_VOLUME')

# Randomly place objects in the air    
bpy.ops.object.randomize_transform(random_seed= randint(1,9000), use_delta=False, use_loc=True, loc=(12.0, 8.0, 0.0), use_rot=True, rot=(360.0, 360.0, 360.0), use_scale=False, scale_even=False, scale=(1.0, 1.0, 1.0))
bpy.ops.object.select_all(action='SELECT')

#Runs physics simulation
try:
bpy.ops.rigidbody.bake_to_keyframes(frame_start=firstFrame, frame_end=lastFrame, step=1)
except:
pass
bpy.context.scene.frame_set(250)

# Define Directory
dir = bpy.path.abspath('//stlexport/')

# Create Directory (If Necessary)
if not os.path.exists(dir): os.makedirs(dir)

# Export STLs
bpy.ops.export_mesh.stl(filepath = dir, batch_mode = 'OBJECT')

This script only exports the first frame of the simulation, and I cannot, for the life of me, figure out how to get it to export after the simulation is run. This has to be run without UI because blender crashes if I ask the user to give input for the number of duplications for the objects.


r/blenderpython • • Jan 12 '18

Optical Flow with Phyton in Blender

4 Upvotes

Hi,

i need to get the "speed"-vectors from a scene(eg. animation) out of images.

I was told that it is only possible via Python in Blender. But despite searching in the web for quite some time i couldnt find any real article helping me understand what exactly i need to do.

My problem is this:

  • I have a simple scene of a cube moving from the left to the right. (It will become a more complex scene later on but for now i want to start with a simple one, once i know how to get the desired information i can just use it on other work)

  • My scene is done in stereo-function with a right and left side.

  • I want to get the optical flow of that animation. That can be later used for another work.

NOTE: i have no experience with Python at all, my sole goal is to have a code which i can use to make Blender give me the optical flow of a scene (and the scene can be different from the one im using right now eg. scenes which have either static camera while objects move or static objects while camera moves).

I hope this is possible. Thanks in advance for any possible help.


r/blenderpython • • May 25 '17

Blender Discord Hit 100 Users

4 Upvotes

Hey I'm the owner of the fastest growing Blender Discord; I would like to say, YAY we made it to 100 members. If you would like to join make a Discord account and start chatting.

We have Young and old, experienced and new users. So it doesn't matter who you are just pop in!

Blender Discord


r/blenderpython • • Jul 15 '16

Any word of progress cuda implementation of GPU rendering on NVidia pascal?

4 Upvotes

Like an idiot, I picked up the new 1080 only to realize that Cycles had some catching up to do before I could use GPU rendering. I found a 3rd party cuda kernel online that enables GPU rendering but the results (while lightning fast compared to CPU) look very non-antialiased. Branched path tracing is purported to fix this but trying this on my system only crashes. I was wondering if anyone here has any info, where online should I be seeking the latest info, or even the right sub to be asking this.


r/blenderpython • • Mar 22 '15

Python access to vertices, polygons, topology etc

4 Upvotes

I'm working on a school project about mesh decimation and thought that blender would be a good place to test things - and make illustrations of course. Can I access vertices, polygons and topology directly from python, or do I have to make something more low level to try these things out?


r/blenderpython • • Sep 06 '14

Switching to 3D view with Python?

4 Upvotes

I'm writing a script that will generate some camera animation. I need to have the user select the area for the camera to focus on, and I thought select_border() would do the trick. However, I can't seem to be able to switch to the active 3D view. Any ideas?

import bpy
from math import floor,ceil
from random import uniform, randint
from time import sleep

MIN_SIZE = 1024
MAX_SIZE = 1200
MIN_FOCUS = 0.4
MAX_FOCUS = 0.9

def get_frame_size():
    rnd = bpy.data.scenes[0].render
    return (rnd.resolution_x, rnd.resolution_y)

def get_2D_cursor_position():
    curs = bpy.context.scene.cursor_location
    return (curs.x, curs.y)

def get_px_unit_ratio(cam_obj=bpy.context.scene.camera): # this can constantly change
    fs = get_frame_size()
    dim = max(fs[0], fs[1])
    return cam_obj.data.ortho_scale/dim

def get_random_pos_factors():
    values = ((2, 2),(2, -2), (-2, 2), (-2, -2))
    return values[randint(0,3)]

def do_selection():
    screen = bpy.context.window.screen
    for area in screen.areas:
        if area.type == 'VIEW_3D':
            for region in area.regions:
                if region.type == 'WINDOW':
                    region3d = area.spaces[0].region_3d
                    region3d.view_perspective = "CAMERA"
                    
                    override = bpy.context.copy()
                    override["area"] = area
                    override["screen"] = screen
                    override["region"] = region
                    return bpy.ops.view3d.select_border(override, gesture_mode=3)
            
target = bpy.context.active_object
total_w = target.dimensions.x
total_h = target.dimensions.y
focal_d = target.location.x+(target.dimensions.z/2)

frame_x, frame_y = get_frame_size()
curs_x, curs_y = get_2D_cursor_position()

bpy.ops.object.camera_add()
cam = bpy.context.active_object
cam.data.type = "ORTHO"
cam.data.ortho_scale = min(total_w, total_h)
bpy.context.scene.camera = cam
cam.data.ortho_scale = cam.data.ortho_scale*uniform(MIN_FOCUS, MAX_FOCUS)
corner = get_random_pos_factors()
cam.location = ((total_w-(frame_x*get_px_unit_ratio(cam)))/corner[0], (total_h-(frame_y*get_px_unit_ratio(cam)))/corner[1], 2)
print(do_selection())

r/blenderpython • • Apr 10 '14

Post your favorite code along with a screenshot of the result.

4 Upvotes

Everyone has that snippet of code that they're really proud of. In Blender, it might produce a fractal or a psychedelic image. I don't feel like there's enough opportunity to actually see visual results of Python in Blender, so post away!

Thanks in advance :)


r/blenderpython • • Apr 06 '14

What's the best way to learn Blender?

4 Upvotes

The title basically says it all. I'm picking up Python as a new language doing some indie game programming. Any recommendations?


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 • • May 06 '26

A question about self in Blender scripts

3 Upvotes

Hi,

I am completely new to Blender API and scripting. When I was looking at addons made by others, there was a thing I couldn't really understand.

In scripts and addons, most regular functions have self as the first parameter like here in this example:

import bpy
#...

class MyPanel(bpy.types.Panel):
    def draw(self, context):
        pass

class MyOperator():
    def execute(self, context):
        pass

def function1(self, context):
    pass

def function2(self, context):
    pass

#...

I know self refers to an instance of a class in OOP, but I can't figure out what it represent in these functions above: function1(...) or function2(...)

I assume addons are executed in some closed environment and self would simply represent an object of that environment but I can't find what it is. Thanks


EDIT. I finally found out what these functions are for. In case you see self as the first parameter, these functions become objects to pass into other methods, which are going to need self to refer to their object.

Stupiditly easy thing and yet it took me so long to figure it out :/