r/blenderpython • • Sep 27 '24

Trying to use vscode with blender. Anyone know to fix this?

Post image
1 Upvotes

I already installed python extension by Microsoft, blender development plug-in by Jacques Lucke, Fake byp module. Python version on my system is 3.11.7 which is same what is used by blender 4.2.2

I have not clue where to go from here.


r/blenderpython • • Oct 02 '24

Custom ui panel : advanced IK FK switch

1 Upvotes

r/blenderpython • • May 19 '14

I've got another tutorial for you guys! This one explains how to use python in order to align a sky texture in cycles with a sun lamp.

Thumbnail
youtube.com
3 Upvotes

r/blenderpython • • May 16 '14

Just thought I'd share a tutorial I made on how to realistically simulate gravity in the blender game engine using python!

Thumbnail
youtube.com
5 Upvotes

r/blenderpython • • May 28 '14

The API Navigator

1 Upvotes

Just found an addon that seems interesting. If you open user preference panel and under the addon tab. There is an addon called API Navigator. Now activate it and open the text editor. Press ctrl+T to bring up that properties tab and scroll down to the API navigator. Now you can mess around with that.


r/blenderpython • • May 20 '14

Script that finds non-planar polygons, selects them and outputs total amount found.

3 Upvotes

This script checks if you object has any non-planar faces. If it does then it will select those faces so you can see which ones in edit mode. It will also output how many faces that were non-planar in the system console.


import bpy

def Vnorm(Vec):
    return (Vec[0]**2+Vec[1]**2+Vec[2]**2)**0.5

def Vdot(Vec1,Vec2):
    return Vec1[0]*Vec2[0]+Vec1[1]*Vec2[1]+Vec1[2]*Vec2[2]

scene = bpy.context.scene
ob = bpy.context.active_object
eps = 1e-3
pface = 0
planar = False

bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')

if ob.type != 'MESH':
    print("Please Select a mesh object")
else:
    for face in ob.data.polygons:
        fnorm = face.normal
        for edgekey in face.edge_keys:
            tempvec = ob.data.vertices[edgekey[0]].co-ob.data.vertices[edgekey[1]].co
            if abs(Vdot(tempvec,fnorm)) < eps:
                planar = True
            else:
                planar = False
                break
        if planar==False:
            pface +=1
            face.select = True
   
    print(pface)

Any critiques or suggestion on how to write it better are more than welcome! It would be great if you guys could test out the script and report if there are any bugs or if it gives incorrect values. I've tested it here and it seems to work for me, but more tests are always a good thing.


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 • • Aug 09 '14

Blend files with python scripts at BlendSwap. Going through some of them could be a good learning experience.

Thumbnail
blendswap.com
1 Upvotes

r/blenderpython • • Jun 12 '17

Bezier Curve TILT Value?

1 Upvotes

Hey,

I am currently working on a project invloving rollercoasters in Blender. I have found a way to get my bezier curve positions / locations using the .obj export function. However I also need my Pitch / TILT Export, which I can't be able to find.

I have been browsing the web for around 2 months now, looking for a python script / scripter which might be able to help me. I havent found any available python scripters or scripts.

Reddit will help me pls?


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 • • Oct 31 '17

Adding keyframes to custom (Python) node type

1 Upvotes

I'm working on a custom NodeTree class, with custom Node types (and also a custom NodeSocket class).

I'm running into problems when trying to add keyframes to either properties on the actual Node class itself (just stored as FloatProperty), or to the properties on the input sockets.

The call to (for example) "node.keyframe_insert('myFloatProperty', frame=10)" returns True when I run it from the Python console (and the property itself turns green in the node view), but nothing gets stored in the scene.animation_data object (it's None), and nothing shows up in the F-curve view (if I add a keyframe to a custom property on the default cube object, then this will show up there).

Is there something special that needs to be done to be able to add keyframes to custom NodeTrees?

Thanks


r/blenderpython • • Jan 03 '16

Exporting UV Islands in console (v2.72)

1 Upvotes

I understand how to display loop indices, polygons, edges with seams, uvs and various under information regarding meshes from the console, but I want to be able to identify list of polygon indices for all given islands.

Here is an example script I am talking about that I can run from the console:

me = D.objects['Plane'].to_mesh( C.scene, True, 'PREVIEW' )

t0 = me.uv_layers[0].data

for p in me.polygons:

      str = "%5d %5d %5d " % ( p.vertices[0], p.vertices[1], p.vertices[2] )

      str += " %+4.4f,%+4.4f " % ( t0[p.loop_indices[0]].uv.x, t0[p.loop_indices[0]].uv.y )

      str += " %+4.4f,%+4.4f " % ( t0[p.loop_indices[1]].uv.x, t0[p.loop_indices[1]].uv.y )

      str += " %+4.4f,%+4.4f " % ( t0[p.loop_indices[2]].uv.x, t0[p.loop_indices[2]].uv.y )

      print( str )

How can I in a similar fashion gather information for uv islands? I've been digging around the code looking at import/export scripts but I just can't find anything. I'm considering writing my own way of calculating this, but beyond saving a bunch of edges marked as seems, I'm struggling with the algorithm to utilize them to sort triangles by uv islands.


r/blenderpython • • Jan 06 '16

How do I make Python Control an Changing Animation?

2 Upvotes

Hey Guys,

Alright, so I am working on a student project in blender. My company wants me to take files that look like this and turn them into animations of a person walking.

Now, please bear with me as I explain this. Alright, so what these lines of code do is tell an operator,which is a human in an assembly line, what to do. aka, when to turn, how much to turn, what to pick up, when to walk and how far etc. And, the only ones that I am going to use for my animation are the turns, and the walks. So I have highlighted those here.

Alright, so what this code actually means is... TIP = Turn and the number after that is how may degrees of a turn it should be OBS and UOBS are walks. OBS is a obstructed walk, and UOBS is a Unobstructed walk. (The reason that this matters is that the Obstructed walk takes more time because you have something you need to walk around).

So, what I am tasked with doing is taking these files, and directly inputting them into blenders python module, and according to what the file says the human operator should do, the model that I have will follow. The reason that i'm doing this is so that mistakes in the files can be easily found and eliminated.

Okay, so down to the actual question...

First off, thanks for reading this far! I appreciate it! My main problem is that I have is I don't know how to make blender ask for input or even how to put one in. Once I got that figured out what I was thinking of doing is setting a bunch of variables to mean something. Like, there could be a 'walk' variable and within that variable it could contain all the python code for one step of the animation, and that code could just be repeated for however many steps the file had. However, the problem with that Is that the animation wouldn't move across the room, he would just take a step in the air. So, I was thinking that I could multiply the amount of steps the animation is supposed to take by a certain number of blender units to make him move forward. I cannot see any problems with this... yet.

Thanks for any help! It is VERY much appreciated. Trixworld


r/blenderpython • • Dec 14 '24

How do I interact with elements in Blender using Python

1 Upvotes

I'm trying to create an abacus in Blender and I want to select individual beads and interact with them using Python. I thought it'd be easier to model the abacus on Blender, instead of using stuff like three.js to code each shape individually. But I know next to nothing about Blender. Is there a way I'm able to select each bead, or the frame of the abacus, and make it a Python object? So I can use a Python script to interact with them, like move them across the rod.

Is this a foolish thing to do? I mean, is there a way better way to go about it?


r/blenderpython • • Jan 31 '25

Have any tips for a beginner?

5 Upvotes

(posted this about 2min ago on the wrong account. ups)

Hello. im currently trying to learn how to make my own addons/scripts in blender, but the course my work provided didn't help much.. i was wondering if you guys have any tips on where to begin and/or can recommend some courses? never coded before, so im guessing its obvious to learn the basics. but i really wanna know if there's some nice courses out there.

currently taking this course: https://www.udemy.com/course/learn-blender-python

although it has a lot of good information about everything, i cant seem to learn anything from it. the course consists of a bunch of videos where a guy explains a lot of stuff and then at the end of each video says "now you do it". i have to watch the videos 3 times before the information sticks and that doesn't always work either.. and sometimes he shows me stuff "he normally don't ever do" or goes a lot back and forth on what he's doing because he changes his mind.. and it makes me even more confused. i understand how others might like this course, but it just wasn't for me..

any tips?


r/blenderpython • • Dec 24 '24

Python and C++ programming in Blender

5 Upvotes

I don't know if this is the right place but I have a question for more experienced Blender-python and C++ developers that have years and years of professional add-on development and general scripting knowledge. But people of other skill levels are also welcome to give their opinion.

Aside from the mandatory and well known resources for learning python scripting and add-on development such as https://docs.blender.org/api, everything that's listed on this blenderartists page, as well as careful usage of ChatGPT as a tutor, are there any books or high-quality advanced tutorials that in the end made you say "Wow, I wish I knew this sooner, this changes everything. I'm so glad I stumbled upon this!"?

Heck, even resources that delve deeper into C++ side for Blender are welcome, because if I'm not wrong, writing modifiers is only possible in C++ even though they are planned to be completely replaced by geometry-node based ones, which are also written in C++.

Would the book by Paolo Acampora be a good candidate, I'm not posting a link since I don't want to promote anyone directly and potentially break the rules.

Sorry for the long-winded question. I know that when I write things they're kinda unintelligible so feel free to ask for further clarification if needed and thank you in advance.


r/blenderpython • • Dec 12 '24

Blender UI status !!

1 Upvotes

Hello, i want to know is blender API can send Interface statues
which mean if user switch between modes like from modeling to sculpting
i want to read the interaction with UI window in blender


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 • • Apr 20 '24

Split mesh but connect split vertices?

1 Upvotes

I’m working on a project where I’ve got a mesh that I want to split into chunks. The splitting part is easy. I’m using bmesh so I can just use split_edges to break it up and that works great.

So now it’s split into chunks and all the vertices on the boundary of each chunk has a matching vertex on the other chunk it was split from. I want to join those matching vertices on the different chunks with an edge, but there doesn’t seem to be an easy way to do that. I could loop through all the boundary points until I find all matching pairs and then call a function to connect them with edges one at a time but that seems ridiculous. Any suggestions?


r/blenderpython • • Apr 13 '24

Alternative to draw function in gpu Module?

1 Upvotes

I want to use the blender gpu Module. In the examples they say that the draw function is only there to make the code short. The problem is that I want to remove (or update) the lines without restarting blender. How would that be possible?

Example: https://docs.blender.org/api/current/gpu.html#d-lines-with-single-color

Thank you


r/blenderpython • • Apr 28 '24

I made a universal(?) Multi-File Add-On self-bootstrapping __init.py__

2 Upvotes

I spent way too much time on making this __init,py__ file for use in add-on development... instead of actually working on the add-on I want to make

It scans it's directory for all sub-modules (.py files) and imports and/or reloads them. It is a very, very greedy approach and it's likely to load / reload the same file multiple times (because it got imported in an already loaded file)

Also the script that you run inside of Blender to load in the add-on is different than what I've seen around (included in the code as a text block).

Do whatever you want with this code, I donate it to the public domain as much as I can and whatnot.

bl_info = {
    # your add-on info here
}

"""
### Dev Loader Script ###
# Run from Blender's Text Editor

import sys
import importlib
import importlib.util

# https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly

module_name = "module_name"
file_path = "C:/blah/module_name/__init__.py"

if module_name in sys.modules:
    try:
        sys.modules[module_name].unregister()
    except Exception as err:
        print(err)

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)

module.register()
"""

# bootstrapping code based on: https://b3d.interplanety.org/en/creating-multifile-add-on-for-blender/
import importlib
import sys
from glob import glob

child_modules = {mod_name: f'{__name__}.{mod_name}' for mod_name in (
    p.replace('\\', '.').replace('/', '.').removesuffix('.py')
    for p in glob("**/[!_]*.py", root_dir=__path__[0], recursive=True)
)}

for mod_name, full_name in child_modules.items():
    if full_name in sys.modules:
        print('Reload', full_name)
        importlib.reload(sys.modules[full_name])
    else:
        print('Initial load', full_name)
        parent, name = mod_name.rsplit('.', 1)
        exec(f'from .{parent} import {name}')

del mod_name, full_name

def register():
    for full_name in child_modules.values():
        if full_name in sys.modules and hasattr(sys.modules[full_name], 'register'):
            sys.modules[full_name].register()


def unregister():
    for full_name in child_modules.values():
        if full_name in sys.modules and hasattr(sys.modules[full_name], 'unregister'):
            sys.modules[full_name].unregister()

r/blenderpython • • May 03 '24

Python Help! Alembic to FBX

2 Upvotes

Hi all. I'm looking into all methods (if at all possible) to convert alembic cache data into fbx format. I realize that the changing vertex count doesn't allow for conversion and imported alembics are baked animation data, but my thought process here is to convert between multiple formats.

I first made a simple geom node particle system and exported that out as a alembic, then brought that back into blender to convert to a lightwave point cache format. I did this because I thought perhaps then taking this data to fbx could provide a solution but i haven't found a working method yet. I get an export that is just the first frame of the animation.

My methodology to this point has been to somehow convert the data into shape keys to then export out. I found this script online, but it seems to crash my scene. Honestly, if someone were able to break this down into simpler terms, I may be able to edit this to my needs.

If anyone has insight or creative solutions to get this result of an alembic to an fbx format, it would be greatly appreciated. my target goal is to take a growing fluid sim and get that to an fbx.

PYTHON SCRIPT:

import bpy

ob = bpy.context
obAc = ob.active_object
mesh_data = obAc.data

start_frame = bpy.context.scene.frame_start
end_frame = bpy.context.scene.frame_end

if not obAc.data.shape_keys:
obAc.shape_key_add(name="Basis")

Create shape keys for each frame

for frame in range(start_frame, end_frame + 1):
bpy.context.scene.frame_set(frame)

Evaluate the mesh with modifiers

depsgraph = bpy.context.evaluated_depsgraph_get()
object_eval = obAc.evaluated_get(depsgraph)
mesh_eval = object_eval.data

Create a new shape key and set its points based on the current frame

shape_key = obAc.shape_key_add(name=str(frame))

Collect vertex positions for the current frame

vertices = [vertex.co for vertex in mesh_eval.vertices]

Set shape key data

shape_key.data.foreach_set('co', [c for v in vertices for c in v])

if obAc.data.shape_keys:
shape_keys = obAc.data.shape_keys.key_blocks

Iterate through shape keys and set keyframes

for frame in range(start_frame, end_frame + 1):
ob.scene.frame_set(frame)

for shape_key in shape_keys:
if shape_key.name.isdigit():
value = 1.0 if int(shape_key.name) == frame else 0.0
shape_key.value = value
shape_key.keyframe_insert(data_path='value', index=-1)


r/blenderpython • • May 18 '24

I've got a (free) plugin user getting "AttributeError: 'Converter' object has no attribute 'scene'"

1 Upvotes

I'm doing my best, but so far no breakthroughs.

It's a classic case of "It works on my PC", and it doesn't work on theirs.

When they try and use the new "Import lego" menu item, they tell me of the AttributeError: 'Converter' object has no attribute 'scene' error.

total = len(self.scene.Bricks)

This is where I get stuck.

I googled it, and there's clear instructions that the BPY Scene object isn't available during registration of a plugin, and only when it's triggered, and is passed through to the execute function via a "context" attribute.

That's just what the code is doing! (and it works on my PC)

I wonder if it's because the users scene is empty, Null? Whereas mine default Blender scene has a Plane, light, etc... I'm waiting for them to get back to me.

If not that, that's where I lose it completely, is Pythons "self" / "context" things not passing "scene" through?

https://github.com/Sarah-C/BlenderImportLDD/issues/1

Traceback (most recent call last):
  File "C:\Users\Jack\AppData\Roaming\Blender Foundation\Blender\4.0\scripts\addons\BlenderImportLDD.py", line 1481, in execute
    return convertldd_data(context, self.filepath, self.lddLIFPath, self.useLogoStuds, self.useLDDCamera)
  File "C:\Users\Jack\AppData\Roaming\Blender Foundation\Blender\4.0\scripts\addons\BlenderImportLDD.py", line 1416, in convertldd_data
    converter.Export(filename=filepath, useLogoStuds=useLogoStuds, useLDDCamera=useLDDCamera)
  File "C:\Users\Jack\AppData\Roaming\Blender Foundation\Blender\4.0\scripts\addons\BlenderImportLDD.py", line 955, in Export
    total = len(self.scene.Bricks)
AttributeError: 'Converter' object has no attribute 'scene'

Many thanks for your help!


r/blenderpython • • May 18 '24

Scaling a new imported collection for LEGO!

2 Upvotes

I've managed to fix up and fine tune the old Lego LXF to Blender importer that's based on pyldd2obj version 0.4.8 - Copyright (c) 2019 by jonnysp.

The only Python and BPY API I know is that which I've learned doing this plugin tweaks, so not much at all.

During import I realised the object's where huge! The whole scale is some other unit, possibly mm to meters!

I had great difficulty resizing individual blocks as they were put in the scene - all the time I got "brick.scale isn't a method" or similar! I don't know what the constructors are making, so I was experimenting blind.

In the end, the solution I got working was some code I found on S.O.... which works great but with one problem I can't solve - the bit of code below scales the WHOLE scene!

So prior imports are shrunk repeatedly, like Russian Dolls!

Line 1421:

    # Scale the world
    scale = 0.025
    # change scale and location
    [setattr(obj, 'scale', obj.scale*scale) for obj in bpy.data.objects if ((obj.type != 'EMPTY') and (obj.type != 'CAMERA'))]
    [setattr(obj, 'location', obj.location*scale) for obj in bpy.data.objects if obj.type != 'CAMERA']

The layout of the new blocks is like below, a new collection contains empty elements that each have some brick bits and the lego mesh as children.

So what I figured was a correct course of action was to iterate through the -collection- that was just imported, not the whole scene like I am.

How can I do that?

https://github.com/Sarah-C/BlenderImportLDD/blob/main/BlenderImportLDD.py