Thomas Larsson - Введение в написание скриптов на Питоне для Блендера 2.5x. Примеры кода
#----------------------------------------------------------
# File cloth.py
#----------------------------------------------------------
import bpy, mathutils, math from mathutils import Vector
def run(origin):
side = 4
diagonal = side/math.sqrt(2)
hoopRad = 0.1
eps = 0.75
nDivs = 40
scn = bpy.context.scene
# Добавление сферы, выступающей в качестве объекта столкновения
bpy.ops.mesh.primitive_ico_sphere_add(location=origin)
sphere = bpy.context.object
bpy.ops.object.shade_smooth()
# Добавление модификатора collision к сфере
bpy.ops.object.modifier_add(type='COLLISION')
cset = sphere.modifiers[0].settings
cset.thickness_outer = 0.2
cset.thickness_inner = 0.5
cset.permeability = 0.2
cset.stickness = 0.2
bpy.ops.object.modifier_add(type='SUBSURF')
# Добавление кольца
center = origin+Vector((0,0,2))
bpy.ops.mesh.primitive_torus_add(
major_radius= diagonal + hoopRad,
minor_radius= hoopRad,
location=center,
rotation=(0, 0, 0))
bpy.ops.object.shade_smooth()
ring = bpy.context.object
# Добавление плоскости над сферой и привязка её к кольцу
bpy.ops.mesh.primitive_plane_add(location=(0,0,0))
bpy.ops.transform.resize(value=(side/2,side/2,1))
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.subdivide(number_cuts=nDivs)
bpy.ops.object.mode_set(mode='OBJECT')
plane = bpy.context.object
plane.parent = ring
me = plane.data
# Создание группы вершин. Объект не должен быть активным?
scn.objects.active = None
grp = plane.vertex_groups.new('Group')
for v in plane.data.vertices:
r = v.co - center
x = r.length/diagonal
w = 3*(x-eps)/(1-eps)
if w > 1:
w = 1
if w > 0:
grp.add([v.index], w, 'REPLACE')
# Активация плоскости снова
scn.objects.active = plane
# Добавление модификатора cloth (ткань)
cloth = plane.modifiers.new(name='Cloth', type='CLOTH')
cset = cloth.settings
cset.use_pin_cloth = True
cset.vertex_group_mass = 'Group'
# Настройки шёлка, скопировано из "scripts/presets/cloth/silk.py"
cset.quality = 5
cset.mass = 0.150
cset.structural_stiffness = 5
cset.bending_stiffness = 0.05
cset.spring_damping = 0
cset.air_damping = 1
# Сглаженное затенение
plane.select = True
bpy.ops.object.shade_smooth()
bpy.ops.object.modifier_add(type='SUBSURF')
# Текстура Blend
tex = bpy.data.textures.new('Blend', type = 'BLEND')
tex.progression = 'SPHERICAL'
tex.intensity = 1.0
tex.contrast = 1.0
tex.use_color_ramp = True
elts = tex.color_ramp.elements
elts[0].color = (0, 0, 0, 1)
elts[0].position = 0.56
elts[1].color = (1, 1, 1, 0)
elts[1].position = 0.63
# материал Rubber (Резиновый)
mat = bpy.data.materials.new('Rubber')
mat.diffuse_color = (1,0,0)
mat.use_transparency = True
mat.alpha = 0.25
mtex = mat.texture_slots.add()
mtex.texture = tex
mtex.texture_coords = 'STRESS'
mtex.use_map_color_diffuse = True
mtex.diffuse_color_factor = 0.25
mtex.use_map_alpha = True
mtex.alpha_factor = 1.0
mtex.blend_type = 'ADD'
# Добавление материала к плоскости
plane.data.materials.append(mat)
# Анимация кольца
ring.location = center
ring.keyframe_insert('location', index=2, frame=1)
ring.location = origin - Vector((0,0,0.5))
ring.keyframe_insert('location', index=2, frame=20)
ring.location = center
return
if __name__ == "__main__":
bpy.ops.object.select_by_type(type='MESH')
bpy.ops.object.delete()
run(Vector((0,0,0)))
scn = bpy.context.scene
scn.frame_current = 1
bpy.ops.screen.animation_play()
Мягкие телаЭта программа добавляет конус с модификатором softbody (мягкое тело) и плоскость-препятствие.
#----------------------------------------------------------
# File softbody.py
#----------------------------------------------------------
import bpy
import mathutils
from mathutils import Vector
def run(origin):
# Добавление материала
red = bpy.data.materials.new('Red')
red.diffuse_color = (1,0,0)
blue = bpy.data.materials.new('Blue')
blue.diffuse_color = (0,0,1)
# Добавление конуса
bpy.ops.mesh.primitive_cone_add(
vertices=4,
radius=1.5,
cap_end=True)
ob1 = bpy.context.object
me1 = ob1.data
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.subdivide(number_cuts=5, smoothness=1, fractal=1)
bpy.ops.object.mode_set(mode='OBJECT')
# Странно, нужен новый меш, который является копией
verts = []
faces = []
for v in me1.vertices:
verts.append(v.co)
for f in me1.faces:
faces.append(f.vertices)
me2 = bpy.data.meshes.new('Drop')
me2.from_pydata(verts, [], faces)
me2.update(calc_edges=True)
# Установка гладкости граням (smooth)
for f in me2.faces: f.use_smooth = True
# Добавление нового объекта и его активация
ob2 = bpy.data.objects.new('Drop', me2)
scn = bpy.context.scene
scn.objects.link(ob2)
scn.objects.unlink(ob1)
scn.objects.active = ob2
# Добавление групп вершин
top = ob2.vertex_groups.new('Top')
bottom = ob2.vertex_groups.new('Bottom')
for v in me2.vertices:
w = v.co[2] - 0.2
if w < 0:
if w < -1:
w = -1
bottom.add([v.index], -w, 'REPLACE')
elif w > 0:
if w > 1:
w = 1
top.add([v.index], w, 'REPLACE')
bpy.ops.object.mode_set(mode='OBJECT')
ob2.location = origin
me2.materials.append(blue)
# Добавление модификатора softbody
mod = ob2.modifiers.new(name='SoftBody', type='SOFT_BODY')
sbset = mod.settings
# Мягкое тело
sbset.friction = 0.6
sbset.speed = 0.4
sbset.mass = 8.1
# Цель
sbset.goal_default = 0.7
sbset.goal_spring = 0.3
sbset.goal_friction = 0.0
sbset.vertex_group_goal = 'Top'
# Края мягкого тела
sbset.pull = 0.6
sbset.push = 0.1
sbset.bend = 0.1
sbset.aerodynamics_type = 'LIFT_FORCE'
sbset.aero = 0.5
# Добавление вихря
bpy.ops.object.effector_add(
type='VORTEX',
location=origin+Vector((0,0,-4)))
vortex = bpy.context.object
fset = vortex.field
fset.strength = 4.5
fset.shape = 'PLANE'
fset.apply_to_location = False
fset.apply_to_rotation = True
fset.falloff_type = 'TUBE'
# Добавление плоскости столкновения
# Предупреждение. Столкновение объектов делает симуляцию очень медленной!
bpy.ops.mesh.primitive_plane_add(
location=origin-Vector((0,0,1.7)))
bpy.ops.transform.resize(value=(4, 4, 4))
plane = bpy.context.object
plane.data.materials.append(red)
mod = plane.modifiers.new(name='Collision', type='COLLISION')
return
if __name__ == "__main__":
bpy.context.scene.frame_end = 600
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
run(Vector((0,0,6)))
bpy.ops.screen.animation_play()
#bpy.ops.render.opengl(animation=True)
Ткань, мягкие тела и текстуры displaceЭта программа показывает три различных метода размахивания флагом: модификатором ткани, модификатором мягких тел, и с помощью анимированных текстур смещения.
#----------------------------------------------------------
# File flags.py
# Создает флаг из мягкого тела и флаг из ткани на ветру.
# Update to API rev. 36816
#----------------------------------------------------------
import bpy, mathutils, math
from mathutils import Vector
from math import pi
# Размер флага, глобальные переменные
xmax = 40
zmax = 24
ds = 2.0/xmax
def makeFlag(name, origin, invert):
# Добавление нового меша, который будет флагом
Откройте для себя мир чтения на siteknig.com - месте, где каждая книга оживает прямо в браузере. Здесь вас уже ждёт произведение Thomas Larsson - Введение в написание скриптов на Питоне для Блендера 2.5x. Примеры кода, относящееся к жанру Программирование. Никаких регистраций, никаких преград - только вы и история, доступная в полном формате. Наш литературный портал создан для тех, кто любит комфорт: хотите читать с телефона - пожалуйста; предпочитаете ноутбук - идеально! Все книги открываются моментально и представлены полностью, без сокращений и скрытых страниц. Каталог жанров поможет вам быстро найти что-то по настроению: увлекательный роман, динамичное фэнтези, глубокую классику или лёгкое чтение перед сном. Мы ежедневно расширяем библиотеку, добавляя новые произведения, чтобы вам всегда было что открыть "на потом". Сегодня на siteknig.com доступно более 200000 книг - и каждая готова стать вашей новой любимой. Просто выбирайте, открывайте и наслаждайтесь чтением там, где вам удобно.


