【Blender Python】随手一记

一个猴头复制另一个猴头的形状

import bpy

def update_mesh(scene):
    o1 = bpy.data.objects['猴头']
    o2 = bpy.data.objects['猴头.001']
    for vert in o1.data.vertices[:]:
        o2.data.vertices[vert.index].co = vert.co
    print("update Finished!!!")
    

update_mesh( bpy.context.scene)
bpy.app.handlers.frame_change_pre.append(update_mesh)

设置一个集合的是否可见

 import bpy

def set_visible(col_name, is_hide, obj_type = 'MESH'):
    if col_name in bpy.data.collections:
        col = bpy.data.collections[col_name]
    else:
        return
    for o in col.objects:
        if obj_type == o.type:
            o.hide_set(is_hide)

再起一个blender

import subprocess
subprocess.Popen(bpy.app.binary_path)

模型成堆起伏

import bpy 
import math

C = bpy.context

objs = C.scene.objects
#for obj in objs:
#    if obj.name.startswith("N"):
#        obj.select_set(True)
#        obj.location[2] += -1


size = 10
for obj in objs:
    x_sin = size * math.sin(obj.location[0] / 10)
    y_sin = size * math.sin(obj.location[1] / 10)
    obj.location[2] = x_sin + y_sin

修改器目标选中

import bpy 
C = bpy.context
D = bpy.data

objs = D.objects


tail = "_W"
tail2 = "_L"
for obj in C.scene.objects:
    for mod in obj.modifiers[:]:
        if mod.type == 'SHRINKWRAP':
            try:
                mod.target = objs[obj.name + tail]
            except:
                print("NONE")
                continue
        if mod.type == 'LATTICE':
            try:
                l_obj = objs[obj,name + tail2]
                if isinstance(l_obj.data, bpy,types.Lattice):
                    mod.object = l_obj
            except:
                print("NONE")
                continue

蜡笔的标注 转换为 网格

import bpy
import bmesh

gp = bpy.data.grease_pencils['Annotations']
l = gp.layers[0]
frame = l.frames[0]
sts = [st for st in frame.strokes]

me = bpy.data.meshes.new(name = "Mesh")
o = bpy.data.objects.new(name = "MyObjectCollection", object_data = me)
bpy.context.scene.collection.objects.link(o)

bm = bmesh.new()

for st in sts:
    for p in st.points[:]:
        bm.verts.new(p.co)
    
    bm.verts.ensure_lookup_table()
    for i in range(1, len(bm.verts)):
        try:
            bm.edges.new(bm.verts[i - 1], bm.verts[i])
        except:
            pass
    
    bm.edges.ensure_lookup_table()

bm.to_mesh(me)
    

蜡笔的标注 转换为 曲线

import bpy

gp = bpy.data.grease_pencils['Annotations']
l = gp.layers[0]
frame = l.frames[0]
sts = [st for st in frame.strokes]

bezier_name_head = "bezier_"
counter = 0

for st in sts:
    curve = bpy.data.curves.new(name = bezier_name_head + str(counter), type = 'CURVE')
    curve.splines.new(type = 'BEZIER')
    lines = curve.splines[0]
    
    lines.bezier_points.add(len(st.points) - 1)
    for i, p in enumerate(st.points):
        lines.bezier_points[i].co = p.co
        lines.bezier_points[i].handle_left = p.co
        lines.bezier_points[i].handle_right = p.co
    
    counter += 1
    o = bpy.data.objects.new(name = "MyObjectCollection", object_data = curve)
    bpy.context.scene.collection.objects.link(o)
    

蜡笔绘制成圆(TODO:象限划分)

import bpy

D = bpy.data
C = bpy.context

Gp = D.grease_pencils.new("mygp")
O = D.objects.new("myobj", Gp)
layer = Gp.layers.new("layer")
f = layer.frames.new(0)
st = f.strokes.new()
st.points.add(100)

r = 5

def y(r, x):
    return (r ** 2 - x ** 2) ** 0.5

# 1
xs1 = [5 * i/24 for i in range(25)]
ys1 = [y(r, x) for x in xs1]

#2
xs2 = [-x for x in xs1]
ys2 = ys1.copy()

#3
xs3 = xs2.copy()
ys3 = [-y for y in ys1]

#4
xs4 = xs1.copy()
ys4 = ys3.copy()

xs = xs1 + xs2 + xs3 + xs4
ys  = ys1 + ys2 + ys3 + ys4

for ids, p in enumerate(st.points):
    p.co = (xs[ids], ys[ids], 0)
    
C.scene.collection.objects.link(O)

蜡笔绘制成圆(角度划分)

import bpy
import math

D = bpy.data
C = bpy.context

Gp = D.grease_pencils.new("mygp")
O = D.objects.new("myobj", Gp)
layer = Gp.layers.new("layer")
f = layer.frames.new(0)
st = f.strokes.new()
st.points.add(101)

C.scene.collection.objects.link(O)

r = 5
dgree = 360 / 100

for ids, p in enumerate(st.points):
    angle = ids * dgree
    p.co = (r * math.cos(math.radians(angle)), r * math.sin(math.radians(angle)), 0)
    

图片转换成起伏图

import random
import bpy
import math

from mathutils import Vector



rr = random.random


curimg = bpy.data.images[1]

x = curimg.size[0]
y = curimg.size[1]

p = curimg.pixels

vp = Vector(p)


for i in range(x):
    for j in range(y):
        k = 4 * (i * y + j)
        vp[k: k + 4] = (abs(math.sin(j/10))/2 + abs(math.cos(i/10))/2, 1, 0, 1)
        
p[:] = vp


curimg.update()

类似Qt 的QComBox的弹窗制作:

from cgi import test
import enum
import bpy


def get_enum(self, context):
    it = []
    # test = bpy.context.scene.test.test_int
    test = self.test_int
    for i in range(test):
        it.append((f"T{i}", f"t{i}", "", i))
    return it

class My_Props(bpy.types.PropertyGroup):
    test_int: bpy.props.IntProperty(default=1)
    enum: bpy.props.EnumProperty(items=get_enum)



class My_Panel(bpy.types.Panel):
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_label = ""
    bl_idname = "testpanel"
    
    def draw(self, context: 'Context'):
        self.layout.prop(bpy.context.scene.test, "test_int")
        self.layout.prop(bpy.context.scene.test, "enum")

bpy.utils.register_class(My_Props)
bpy.utils.register_class(My_Panel)
    

bpy.types.Scene.test = bpy.props.PointerProperty(type = My_Props)

顶点存储在文件中 蜡笔汇聚成像

import bpy

with open("C:\\Users\\LMX\\AppData\\Roaming\\Blender Foundation\\Blender\\3.2\\scripts\\addons\\vertices.txt","r") as f:
   str_data = f.read()
   
   
D = bpy.data
C = bpy.context

Gp = D.grease_pencils.new("mygp")
O = D.objects.new("myobj", Gp)
layer = Gp.layers.new("layer")
f = layer.frames.new(0)
st = f.strokes.new()

C.scene.collection.objects.link(O)

data_lsit = str_data.split("\n")
st.points.add(len(data_lsit))

for idx, str_v in enumerate( data_lsit ):
   if str_v == "":
      break
   str_list = str_v.split(" ")
   tuple_v = (float(str_list[0]),float(str_list[1]), float(str_list[2]))
   print(tuple_v)
   st.points[idx].co = tuple_v 

新增81个立方体并且位于相机的视角内渲染出图像

import bpy
from bpy import data as D
from bpy import context as C
from mathutils import *
from math import *

#~ PYTHON INTERACTIVE CONSOLE 3.10.2 (main, Jan 27 2022, 08:34:43) [MSC v.1928 64 bit (AMD64)]
#~ 
#~ Builtin Modules:       bpy, bpy.data, bpy.ops, bpy.props, bpy.types, bpy.context, bpy.utils, bgl, blf, mathutils
#~ Convenience Imports:   from mathutils import *; from math import *
#~ Convenience Variables: C = bpy.context, D = bpy.data
#~ 

bpy.ops.object.select_by_type(type = 'MESH')
bpy.ops.object.delete()

for i in range(9):
    for j in range(9):
        bpy.ops.mesh.primitive_cube_add(location = (i*3, j*3, 0))

bpy.ops.object.select_all(action = 'DESELECT')

for obj in D.objects:
    if obj.name.startswith("立方体"):
        obj.select_set(True)



bpy.ops.view3d.camera_to_view_selected()
bpy.ops.render.render()
bpy.ops.render.opengl()
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐