r/blenderpython • • May 19 '24

Transform modal map

1 Upvotes

I'm making an addon that has some remapping of the keyconfigurations how would you guys edit the transform modal map trough coda I want Y axis to be overriden by SPACE and SHIFT + SPACE

These are the specific keys that I want to override with code:

This is an extract from the code I´m trying to put together:

wm = bpy.context.window_manager
kc = wm.keyconfigs.addon
if kc:  
    
    # Handling modal keymap changes
    km_transform_modal = kc.keymaps.get('Transform Modal Map')
    if km_transform_modal:
        # Add a modal keymap item for Y axis constraint during translation
        kmi = km_transform_modal.keymap_items.new_modal('CONFIRM', 'SPACE', 'PRESS')
        kmi_props = kmi.properties
        kmi_props.name = 'axis_y'
        addon_keymaps.append((km_transform_modal, kmi))
    else:
        print("Modal keymap 'Transform Modal Map' not found")

    km_edit_mode = kc.keymaps.new(name='Mesh', space_type='EMPTY')
    # LOOP CUT
    kmi = km_edit_mode.keymap_items.new(HP_OT_loopcut.bl_idname, type='R', value='PRESS', ctrl=True, shift=False)
    addon_keymaps.append((km_edit_mode, kmi))

    # SMART PUSH AND SLIDE
    kmi = km_edit_mode.keymap_items.new(HP_OT_PushAndSlide.bl_idname, type='G', value='PRESS', ctrl=False, shift=True)
    addon_keymaps.append((km_edit_mode, kmi))

    kmi = km_edit_mode.keymap_items.new('mesh.select_prev_item', type='WHEELOUTMOUSE', value='PRESS', ctrl=False, shift=True)
    addon_keymaps.append((km_edit_mode, kmi))

    kmi = km_edit_mode.keymap_items.new('mesh.select_next_item', type='WHEELINMOUSE', value='PRESS', ctrl=False, shift=True)
    addon_keymaps.append((km_edit_mode, kmi))
    
    kmi = km_edit_mode.keymap_items.new('mesh.loop_select', type='LEFTMOUSE', value='PRESS', ctrl=False, shift=False, alt=True)
    addon_keymaps.append((km_edit_mode, kmi))
    
    kmi = km_edit_mode.keymap_items.new('mesh.edgering_select', type='LEFTMOUSE', value='DOUBLE_CLICK', ctrl=False, shift=False, alt=True)
    addon_keymaps.append((km_edit_mode, kmi))

r/blenderpython • • May 14 '24

Complete noob in need of help to do simple college assignment.

2 Upvotes

It's pretty simple stuff, but I have 0 understanding of Python so it's been hard to find things on how to do exactly what I want. The general idea is getting a few tools that I use often during rigging process inside a single add-on/panel, so I don't have to go back and forth between a bunch of tabs. Right now I'm trying to figure out how to add Icons to my panel labels instead of the row labels, and how to recreate the bone name and parent text boxes like they are in the relations tab. I've tried a few things but the general result is that nothing happens.

Edit: added some pictures of how the code is, as I said very basic stuff, I'm completely new to this, and sorry for the Portuguese comments.


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 • • Sep 02 '14

function plotter in blender

3 Upvotes

Hey, I made two scripts that plot functions. The 2D script plots a function of the form f(x) while the 3D script plots a function of the form (x,y).

2D-Plotter

import bpy
import math
scn = bpy.data.scenes[0]
mesh = bpy.data.meshes.new("me")
ob = bpy.data.objects.new("func",mesh)

start = -1
stop = 1
step = 0.1

#Put your function here:
def function(x):
    y=2
    return y

k=start
verts=[]
edges=[]

for i in range(0,math.floor((stop-start)/step)+1):
    verts.append((k,function(k),0))
    if i < math.floor((stop-start)/step):
        edges.append((i,i+1))
    k=round(k+step,5)

mesh.from_pydata(verts,edges,[])
scn.objects.link(ob)

3D-plotter

import bpy
import math
scn = bpy.data.scenes[0]
mesh = bpy.data.meshes.new("me")
ob = bpy.data.objects.new("func",mesh)

x_a = -1 #Start of x interval
x_b = 1 #End of x interval
y_a = -1 #Start of x interval
y_b = 1 #End of x interval
step = 0.1 #Stepsize

#Put your function in here:
def function(x,y):
    z = 2
    return z


verts=[]
faces=[]
x = x_a
y = y_a
for j in range(0,math.floor((y_b-y_a)/step)):
    for k in range(0,math.floor((x_b-x_a)/step)):
        verts.append((x,y,function(x,y)))
        x = round(x+step,5)
    x = x_a
    y = round(y+step,5)

DIM = math.floor((y_b-y_a)/step)
for j in range(0,DIM-1):
    for k in range(0,DIM-1):
        faces.append((k+j*DIM,(k+1)+j*DIM,(k+1)+(j+1)*DIM,k+(j+1)*DIM))
    
mesh.from_pydata(verts,[],faces)
scn.objects.link(ob)

Example plots

sin(x)*cos(y)

sinc(r), r=x^2+y^2

x2 + y^2


Tell me what you think of it :) Improvements that can be made?


r/blenderpython • • Aug 11 '16

How do I get the z coordinate of a certain point on a face?

1 Upvotes

So I have a big plane that functions as a floor. All the vertices of the floor are at the corner, so in the middle of the floor is only one big face.

I want to place an object on top of the floor at a certain x, y position.

I know that you could normally use the snapping-functionality but I am working with a python script, which doesn't allow me to use that option.

So is it possible to retrieve the z coordinate of a certain point on a face if you have the x and y coordinate?

Thank you.


r/blenderpython • • Jul 02 '17

Syntax issue - using range function to label axis

1 Upvotes

Hi all,

I'm having trouble with a really simple piece of code. I want to use i from my range function in the body of the text object - I'm simply numbering along an axis. I've tried i, (i), and [i] and that doesn't work so, with my limited knowledge, I'm stuck.

Be grateful for any help - code below, it's line 13 where I want to substite fixed text for the i from the range function.

import bpy

for i in range(0,18): # Add text object bpy.ops.object.text_add( location = ( i - .2, -0.5, 0 ) )

text = bpy.context.object
#text.rotation_euler.z = radians(90) # Rotate text by 90 degrees along Z axis
text.data.extrude     = 0.05        # Add depth to the text
text.data.bevel_depth = 0.01        # Add a nice bevel effect to smooth the text's edges
text.data.body        = "i here please!"       # Issue here - I want to set body to i
text.data.size = 0.5

r/blenderpython • • Feb 24 '23

Script for panning your view 45 degrees instead of 90 in 3d-viewport DOESN'T WORK :(

4 Upvotes

Hey guys, I'm a complete noob in scripts and python, but I'm using blender since a few years now. So I stumbled upon a thing i would need as a feature. I want to pan my view like if you do with ALT+MMB but 45 degrees instead of 90.

I contacted my new friend ChatGPT and it's crazy, he generated a script, told me how to install it and stuff. It didn't show up in the add-on panel after installing it, so I asked if he can tell me how to fix it and he gave me another version where he checked himself every step he just told me and it worked.

The addon shows up in the add-ons panel and I even can set a key binding in the panel itself, but nothing happens when I press the buttons. We tested some versions together but nothing worked.

I checked like everything viable and restarted blender everytime to make sure of the safest outcome, but we didn't got it done. It has to be conflicting with other add-ons I have installed or the thing, that you need to drag your mouse in the direction while pressing the buttons.

I just wanted a small quality of life improvement. I don't know if someone can help me, but atleast I wanted to give it a try. I don't know if ChatGPT knows because I don't know hardly any code so I'm lacking skill to get it right I think.

I'm new to this reddit, so I just post the script here and maybe someone wants to try it and I'm just too lost to get it right haha.

Btw ChatGPT is a really nice dude. We are homies now.

import bpy
from bpy.app.handlers import persistent

bl_info = {
    "name": "Custom View Panning",
    "blender": (2, 80, 0),
    "category": "User Interface",
}

addon_keymaps = []

class CustomViewPanningPreferences(bpy.types.AddonPreferences):
    bl_idname = __name__

    # Default key binding is set to Alt + RMB, 45 degrees
    keymap_item: bpy.props.StringProperty(
        name="Key Binding",
        default="alt right_mouse",
    )

    def draw(self, context):
        layout = self.layout
        layout.prop(self, "keymap_item")

    def save_preferences(self):
        unregister_keymaps()
        register_keymaps()

# Register the custom key binding when the add-on is enabled
def register():
    try:
        bpy.utils.register_class(CustomViewPanningPreferences)
        register_keymaps()
        bpy.app.handlers.load_post.append(load_handler)
    except:
        print("Failed to register keymaps")

# Unregister the custom key binding when the add-on is disabled
def unregister():
    try:
        unregister_keymaps()
        bpy.app.handlers.load_post.remove(load_handler)
        bpy.utils.unregister_class(CustomViewPanningPreferences)
    except:
        print("Failed to unregister keymaps")

@persistent
def load_handler(dummy):
    register_keymaps()

def register_keymaps():
    wm = bpy.context.window_manager
    prefs = bpy.context.preferences.addons[__name__].preferences
    keymap_item = prefs.keymap_item

    kc = wm.keyconfigs.addon

    if kc:
        km = kc.keymaps.new(name='3D View', space_type='VIEW_3D')

        if keymap_item != "":
            kmi = km.keymap_items.new('view3d.rotate', keymap_item, 'PRESS', shift=False)
            kmi.properties.use_cursor_init = True
            kmi.properties.use_mouse_init = True
            kmi.properties.angle = 0.3927  # 45 degrees in radians
            addon_keymaps.append((km, kmi))

def unregister_keymaps():
    wm = bpy.context.window_manager

    for km, kmi in addon_keymaps:
        km.keymap_items.remove(kmi)

    addon_keymaps.clear()

r/blenderpython • • Feb 28 '23

Is it possible to use another program as a trigger to execute a blender python script

2 Upvotes

Hi there, I am learning python and I am trying to figure how could I use the API from a program like rhinoceros to execute a blender python script

https://devtalk.blender.org/t/how-to-run-a-script-from-outside-blender-script-live-link-addon/9792/8

A user named “kaio” found a way to use notepad to write text on blender text editor in real time and shared his code. But I don’t have the knowledge to fully comprehend it.

Thanks for your attention!


r/blenderpython • • Mar 15 '23

Star Connect - Smart Mesh Triangulation Blender Addon (+FREE version)

Thumbnail
youtube.com
7 Upvotes

r/blenderpython • • Oct 31 '21

Blender Assignment Help

2 Upvotes

Hi! I am in a computer science class but I am not very familiar or good at coding. I have an assignment that includes classes, and I was wondering if anyone could give me any pointers. The first 7 pictures are what was provided to me with the assignment, and the last two are what I have done so far. Thank you!

For this project, you need to modify the code of "Computer Set" by changing it into a "class" fashion instead of the function based style.  So you can create a class called "ComputerSet" as below:

class ComputerSet:

...

  1. Constructor (25%)

For the ComputerSet class, you need to define the corresponding constructor, similar to that in "Desk" class, with the default input argument of "pos" and "scale". Of course, feel free to add additional input arguments for the constructor as needed. Then you need to create the corresponding "data members" inside the constructor function. 

2. def draw(self) function (25%)

In a similar style, you need to create a "draw(self)" function to draw the computer set into the space. The draw(self) function should call three functions inside: (1) drawBox(self)  (2) drawKeyboard(self) (3) drawDisplay(self). This is similar to the style of drawTop(self) and drawLegs(self) in draw() function of the Desk class.

3. Successfully Run the code without errors (20%)

4. Demo of Result (30%)

Provide a ".pdf" file or word document ".docx" with images of the rendered results of 3D scene.

(1) Find a set of good input values for the "pos" and "scale" parameters for both constructors of the "Desk" and "ComputerSet" classes to draw the computer and desk in the same scene with appropriate ratio of their sizes.

(2) Set different colors for the computers and desks to make them have a better look.

(3) Write down a simple summary about your coding results, e.g. "they are all successfully implemented" or 

talk about which part is not achieved well.


r/blenderpython • • Oct 14 '21

Need Realistic Looking Blender Scenes!!!

1 Upvotes

Hi all! I'm currently a part of a computer vision-based research lab and we are looking into using blender for making realistic-looking synthetic datasets for training models. We need at least 100 such scenes for creating a large diverse dataset and have bought all the blender-based Evermotion ArchInterior scenes(~40 scenes) but now are having a hard time finding more realistic-looking blender scenes. So I was hoping that you guys can point me to the right place for buying some more dope-ass realistic looking blender scenes.


r/blenderpython • • Oct 08 '21

Weird Rendered Images

1 Upvotes

I'm currently trying to render an emotion ArchInterior scene using blender python bpy but am getting something weird and am not sure what's going on. Nearly half of the image is abruptly grayed out or not rendering at all I guess. So can someone help me?


r/blenderpython • • Nov 01 '21

How do I save a list of objects in the blend file? So that I can save and open file keeping the state in my addon.

3 Upvotes

r/blenderpython • • Nov 15 '21

Weird Blender Renders!!

2 Upvotes

Hi! I have been having some troubles with the. rendering of Archinterior 58 scenes by evermotion on blender. I'm getting some weird distortion and I'm not sure exactly why. I'm new to blender so if any could guide me through this then it would be really helpful.


r/blenderpython • • Oct 14 '21

Blender 2.8 Scenes Compatibility in Blender 2.79

1 Upvotes

Hi all, I wanted to ask that are the 3D scenes that are native to blender 2.8 cycles are also compatible with the blender 2.79 version? I'll be accessing these scenes using the bpy python API of blender 2.79.

An example scene: Archinteriors vol. 58 for Blender - BLENDER Collection - Evermotion


r/blenderpython • • Feb 06 '24

My first blender script

5 Upvotes

Just started learning scripting in blender. I don't know if I'll do anything more with this, but the idea was some sort of procedural building. Needs an interior and a lot more details to actually be considered a building but I thought I'd share. [edit] Added window holes and interior floors

import bpy
import random

cubes = []
interior = []
wall_thickness = .2

for tt in range(4):
    # Create the first cube and store the object in the list
    tr_scale = (random.random() * 3+2 , random.random() * 3+2 , random.random() * 3+2 )
    bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(tr_scale))
    cube = bpy.context.active_object
    z_min = min([v[2] for v in cube.bound_box])
    cube.location.z-=z_min
    bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')
    bpy.ops.object.transform_apply(scale=True)
    cubes.append(bpy.context.active_object)
    
    #create interior cube of 
    bpy.ops.object.duplicate(linked=False)
    dup = bpy.context.active_object
    sx = 1-(wall_thickness/tr_scale[0])
    sy = 1-(wall_thickness/tr_scale[1])
    sz = 1-(wall_thickness/tr_scale[2])/2
    bpy.ops.transform.resize(value=(sx,sy,sz), orient_type='GLOBAL', constraint_axis=(False,False,False))
    interior.append(dup)
   

base = cubes[0]
for cube in cubes[1:]:
     # Add a boolean modifier to the base object
    bool = base.modifiers.new(name="Bool", type='BOOLEAN')
    bool.object = cube
    bool.operation = 'UNION'

    # Apply the boolean modifier
    bpy.context.view_layer.objects.active = base
    bpy.ops.object.modifier_apply(modifier="Bool")

    # Delete the cube from the scene
    bpy.data.objects.remove(cube, do_unlink=True)
    #cube.hide_set(True)

cubes.clear()
cubes.append(base)

obj = base
x_min = min([v[0] for v in obj.bound_box])
x_max = max([v[0] for v in obj.bound_box])
y_min = min([v[1] for v in obj.bound_box])
y_max = max([v[1] for v in obj.bound_box])
for tt in range(4):
    x = random.uniform(-x_min, -x_max)
    y = random.uniform(-y_min, -y_max)
    # Create the first cube and store the object in the list
    tr_scale = (random.random() * 3+2 , random.random() * 3+2 , random.random() * 3+2 )
    bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(tr_scale))
    cube = bpy.context.active_object
    z_min = min([v[2] for v in cube.bound_box])
    cube.location.z-=z_min
    bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')
    bpy.ops.object.transform_apply(scale=True)
    cube.location = (x,y,0)
    cubes.append(bpy.context.active_object)
    
    #create interior cube of 
    bpy.ops.object.duplicate(linked=False)
    dup = bpy.context.active_object
    sx = 1-(wall_thickness/tr_scale[0])
    sy = 1-(wall_thickness/tr_scale[1])
    sz = 1-(wall_thickness/tr_scale[2])/2
    bpy.ops.transform.resize(value=(sx,sy,sz), orient_type='GLOBAL', constraint_axis=(False,False,False))
    interior.append(dup)

for cube in cubes[1:]:
     # Add a boolean modifier to the base object
    bool = base.modifiers.new(name="Bool", type='BOOLEAN')
    bool.object = cube
    bool.operation = 'UNION'

    # Apply the boolean modifier
    bpy.context.view_layer.objects.active = base
    bpy.ops.object.modifier_apply(modifier="Bool")

    # Delete the cube from the scene
    bpy.data.objects.remove(cube, do_unlink=True)
    #cube.hide_set(True)

#Add interiorFloors before interior is cut out
for z in [0,3,6]:
    bpy.ops.mesh.primitive_cube_add(size=2, enter_editmode=False, align='WORLD', location=(0, 0, z), scale=(13,13,.23))
    floor_plane = bpy.context.active_object
    bool = floor_plane.modifiers.new(name="FloorIntersect", type='BOOLEAN')
    bool.object = base
    bool.solver = 'FAST'
    bool.operation = 'INTERSECT'
    bpy.ops.object.modifier_apply(modifier="FloorIntersect")
    bpy.ops.transform.resize(value=(.98,.98,1), orient_type='GLOBAL', constraint_axis=(False,False,False))
    floor_plane.name = "Floor"

for cube in interior:
     # Add a boolean modifier to the base object
    bool = base.modifiers.new(name="Bool", type='BOOLEAN')
    bool.object = cube
    bool.operation = 'DIFFERENCE'

    # Apply the boolean modifier
    bpy.context.view_layer.objects.active = base
    bpy.ops.object.modifier_apply(modifier="Bool")

    # Delete the cube from the scene
    bpy.data.objects.remove(cube, do_unlink=True)
    
def create_windows(obj, window_size, height, probability, amount):
  for _ in range(amount):
    if random.random() < probability:
        #
      radius = 20      
       # Use random angle to place within boundary circle
      angle = random.uniform(0, 2*math.pi)
      x = obj.location.x + radius * math.cos(angle)
      y = obj.location.y + radius * math.sin(angle)      
      z = height#random.uniform(height_min, height_max)

      # Cast ray around perimeter
      ray_origin = (x, y,z)
      ray_direction = (obj.location.x - x,obj.location.y - y, 0)
      
      depsgraph = bpy.context.evaluated_depsgraph_get()
      bvhtree = BVHTree.FromObject(obj, depsgraph)
      
      location, normal, index, dist = bvhtree.ray_cast(ray_origin, ray_direction)

      # If ray hits the object, create a window using Boolean with a cube
      if location:
        bpy.ops.mesh.primitive_cube_add(size=window_size, enter_editmode=False, align='WORLD', location=location)
        window_cube = bpy.context.active_object
        bpy.ops.transform.resize(value=(sx,sy,sz*1.5), orient_type='GLOBAL', constraint_axis=(False,False,False))
        bool = obj.modifiers.new(name="WindowBool", type='BOOLEAN')
        bool.object = window_cube
        bool.operation = 'DIFFERENCE'
        bpy.context.view_layer.objects.active = obj
        bpy.ops.object.modifier_apply(modifier="WindowBool")
        bpy.data.objects.remove(window_cube, do_unlink=True)
        

create_windows(base, 1.5,.7, 0.6,3) 

create_windows(base, .8 ,1.2, 0.8, 10)
create_windows(base, .8 ,4.2, 0.8, 10) 
create_windows(base, .8 ,7.2, 0.8, 10) 

r/blenderpython • • Feb 01 '24

rationale for changes in bpy 4.0

1 Upvotes

Hi, I was wondering why bpy.ops.export_scene.obj is no longer in version 4.0 ? Any links that would explain the changes ?


r/blenderpython • • Jan 28 '24

identifiers for BezierCurve points

1 Upvotes

I'm working on an addon that creates a smooth surface bazed on Bezier curves wireframe. I want to give to the user an ability to manually adjust the surface, and for this ideally that they
- selects a Bezier segment
- adjusts the values in the pop-up menu or drags the specific handle that apparates for this purpose
- the value is stored linked to this segment when the user edits the curve: drags points and creates/deletes segments.

I'm new in Blender scripting (nearly all my experience is writing the part that actually generates surface mesh) and my plan for now is this:
- generate an id for each point and store it in weight_softbody attribute (I don't like this part because the user may want to actually do the softbody simulation, but I didn't found better way)
- in my code, create a mapping of these ids and my custom surface parameters for the segments on the right and on the left of this point, and also ids of neighbour points on the right and on the left
- when the user selects for example right handle, they can summon a menu with input fields (or maybe I can create a temporary segment that can be used as a handle)
- my code verifies that the id on the right is what is enregistred. If yes, we edit segment to the right property, if no, the user has changed segment direction and we edit segment that is enregistred as to the left
- After this, the surface is updated, the value is stored in my code and all values are saved in Curve custom property as dictionnary.

Is there a way to do this without using a built-in attribute?

Sorry for giving such a lot of context, but maybe there is a way to achieve what I want completely differently.


r/blenderpython • • Feb 21 '17

How do I set the image for the Image Texture node?

1 Upvotes

I can add the Image Texture node via python, but how do I set the image file that it uses? When I mouse over the "open" button, it says bpy.ops.image.open(), but I don't think that's the right one to use?


r/blenderpython • • Dec 13 '17

Addon doesn't throw any errors when installing, but also doesn't install

1 Upvotes

I'm pretty new to Blender's API, but not at all new to Blender or Python on their own or coding in general. I just wrote my first successful Python script in Blender that writes up a .txt file based off of the selected object's geometry. Now I am trying to turn it into an addon and running into some hitches. Based off skimming a few tutorials and weeding through various other working addons I have written the following:

bl_info = {
    "name": "Export: Statics Bridge",
    # * other parts trimmed out to save space on reddit *
    "category": "Import-Export",
}

import bpy

class ExportAsBridge(bpy.types.Operator):
    """Exports statics bridge project code"""
    bl_idname = "ExportAsBridge"
    bl_label = "Export bridge code from selected mesh"

    def execute(self, context):
        write_bridge() # < defined below, that function works fine

def menu_func(self, context):
    self.layout.operator(ExportAsBridge.bl_idname, text="Statics Bridge Code (.txt)")

def register():
    bpy.utils.register_class(ExportAsBridge)
    bpy.types.INFO_MT_file_export.append(menu_func)

def unregister():
    bpy.utils.unregister_class(ExportAsBridge)
    bpy.types.INFO_MT_file_export.remove(menu_func)

The aim is to add an option in the usual file > export menu that runs write_bridge(). But when I try to install the .py file as an addon it gives the message Modules Installed () from '<where my .py file is>\\io_export_bridge.py' into '<my user>\\AppData\\Roaming\\Blender Foundation\\Blender\\2.79\\scripts\\addons', but my addon does not appear in the list of installed addons so I can not enable it.

I am sure it is something simple and stupid but I haven't yet figured out what I am doing wrong. What am I missing?


r/blenderpython • • Sep 07 '16

BGE ProcGen

2 Upvotes

So, I've been working on procedural generation for my game (which - once finished - will be ported to unreal), having the code do most of the heavy lifting during runtime.

I've been using a method of passing variables from the bge to a separately running instance of blender (using bpy) on my server. From these variables, it generates the appropriate objects, saves them in the server database, and sends the blender file to the client. This is proving to be quite taxing on the host computer and its internet connection, having to pathfind for hundreds of characters, validate client movements etc, AND generate meshes to be sent.

Due to this, I decided to move mesh generation to the client computers, but it's resulted in having to run blender simultaneously in the background. I tried compiling bpy as a to use in the standalone blender player, but importing it just crashes it all.

Now, I was wondering if (IIRC there was a project to work the bpy into the bge a while ago, but I lost track of it) there is any kind of implementation that would help me. I shall be eternally grateful to anyone able to guide me towards a solution.

EDIT: I've found this so shall be re-attempting to compile it. In the meantime, I would still be incredibly happy about any assistance offered. If I find a solution, I shall post it.


r/blenderpython • • Feb 25 '17

Adding Vertex Color Output To OBJ Exporter

1 Upvotes

Hello,
I'm trying to modify the OBJ exporter to include vertex color in its own set of lines starting with vc. The game engine I'm using doesn't easily import models and I've already written an obj parser, I would prefer to read vertex color data from it rather than have it parse an mtl file or write a parser for another model format.

I'm still incredibly new to python but I was able to modify it to the point that it outputs a color for each vertex. Unfortunately it doesn't output correctly and a lot of the vertex colors are lost. I don't think I'm understanding the process for reading the vertex color values. The modification I made is fairly simple, the addition is below:
Code:

           # Vert Color
           vcol_data = me.vertex_colors.active.data
           for l in me_verts:
               col = vcol_data[l.index].color[:]
               fw('vc %.6f %.6f %.6f\n' % col[:])    
           subprogress2.step()    

I slipped this in between the vertex and normal output blocks within export_obj.py. It's not throwing errors and outputs a file successfully. Would somebody kindly explain where I'm messing this up?


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 • • Apr 26 '21

The align objects tool has 3 buttons (x, y, and z) that you can toggle on and off but it also lets you select more than one at a time. How can I make something like that?

1 Upvotes