Jump to content

Useful Python Scripts for Blender


LHammonds

Recommended Posts

I have written a few small Python scripts to import/export animation data to/from a text file. Useful if you generate animation data instead of using Blender's cumbersome Transform Properties.

 

Anyone interested?

Link to comment
Share on other sites

The loop tool one looks so handy! Thanks.

 

Yea fore, Im gonna be trying to animate my guy the old fashioned way but u might as well post the script :D

 

Here is a site with some useful blender scripts. I use geom tool and uv tool a lot and theres 2 other ones also.

Geom tool and other scripts

 

I think it is cumbersome to position the constraint pivots. I wonder if there is a script for that or some other way to get the desired position from 3d cursor.

Link to comment
Share on other sites

Yea fore, Im gonna be trying to animate my guy the old fashioned way but u might as well post the script :D

 

Ehhhm..... but how should I post that? These are 3 scripts with a total o 150 lines. Post as code snippet's here? I don't think it should be a mod file ....

Link to comment
Share on other sites

use the [ code ] tags in conjunction with the [ spoiler ] tags.

 

Example:

 

 

#!BPY
"""
Name: 'Empty mesh'
Blender: 243
Group: 'AddMesh'
"""
import BPyAddMesh
import Blender

def main():
BPyAddMesh.add_mesh_simple('EmptyMesh', [], [], [])

main()

 

Link to comment
Share on other sites

Thanks, baduk and LHammonds :thumbsup:

 

Here are my Python scripts (partially based on the Nif Scripts). I use them to import/export and analyze animation key data, mainly for the OP (breast bones). This way I can design and manage the animation data outside of Blender (in a spread sheet).

 

Import animation key data from a text file. Key data is sorted by frames and has the following format:

<frame>,<bone name>,<x-loc>,<y-loc>,<z-loc>,<x-rot>,<y-rot>,<z-rot>

 

 

#!BPY
"""
Name: '0_My_Import_KeyData'
Blender: 249
Group: 'Import'
Tooltip: 'Import Anim Key Data'
"""
import Blender
from Blender import Armature, Mathutils

# Imports animation key data from a text file. Key data is sorted and has the following format:
# <frame>,<bone name>,<x-loc>,<y-loc>,<z-loc>,<x-rot>,<y-rot>,<z-rot>
# e.g.
# 3,Bip01 Op1.R,0.01,0.12,0.12, 4, 3, 0
# All bones get the Bip01 priority
# Note: Remove imported bones in action list before running this script

def set_keys():
arm = Blender.Object.Get('Scene Root')
mypose = arm.getPose()
f = open('A:\key_data.txt', 'r')					###### file with import data ######

# define string with priority constraint (Bip01 priority)	
prio = "priority:50"
for bonename, bone in ( mypose.bones.items() ):
	if bonename == "Bip01":
		for constr in bone.constraints:
			if constr.type == Blender.Constraint.Type.NULL and constr.name[:9] == "priority:":
				prio = constr.name
print "OP %s" % prio

# read import lines
for line in f:
	kdata = line.split(',')
	pbone = mypose.bones[kdata[1]]
	# frame 1: define bone and set priority
	if int(kdata[0]) == 1:
		pbone.localMatrix = Blender.Mathutils.Matrix().identity().resize4x4()
		priorityconstr = None
		for constr in pbone.constraints:
			if constr.type == Blender.Constraint.Type.NULL and constr.name[:9] == "priority:":
				priorityconstr = constr
				break
		if not priorityconstr:
			priorityconstr = pbone.constraints.append(Blender.Constraint.Type.NULL)
		priorityconstr.name = prio
	# set loc and rot, and insert key
	pbone.loc = Blender.Mathutils.Vector(float(kdata[2]),float(kdata[3]),float(kdata[4]))
	pbone.quat = Blender.Mathutils.Euler(float(kdata[5]), float(kdata[6]), float(kdata[7])).toQuat()
	pbone.insertKey(arm, int(kdata[0]), [blender.Object.Pose.ROT, Blender.Object.Pose.LOC])
mypose.update

set_keys()

 

 

Export animation key data into a text file.

 

 

#!BPY
"""
Name: '01_My_Export__KeyData'
Blender: 249
Group: 'Export'
Tooltip: 'Export Anim Key Data'
"""
import Blender
import bpy
from Blender import Armature, Mathutils, Ipo

# Exports animation key data into a text file. Key data has the following format
# <frame>,<bone name>,<x-loc>,<y-loc>,<z-loc>,<x-rot>,<y-rot>,<z-rot>

def get_keys():
f = open('A:\_EXPORT_keys.txt', 'w')					###### file for export data ######
arm = Blender.Object.Get('Scene Root')
mypose = arm.getPose()
bones_ipo = arm.getAction().getAllChannelIpos()
keydata = []

# iterate through all interesting bones
for bone in ( 'Bip01 Op1.R', 'Bip01 Op1.L', 'Bip01 Op2.R', 'Bip01 Op2.L' ):
#	for bone, bonename in ( mypose.bones.items() ):
#	for bone in ( 'Bip01 Head', 'Bip01 Hand.L', 'Bip01 Hand.R', 'Bip01 UpperArm.L', 'Bip01 UpperArm.R', 'Bip01 ForearmTwist.L', 'Bip01 ForearmTwist.R', \
#		'Bip01 UpperArmTwist.L', 'Bip01 UpperArmTwist.R', 'Bip01 Forearm.L', 'Bip01 Forearm.R', 'Bip01 Spine', 'Bip01 Spine1', 'Bip01 Spine2', 'Bip01 Clavicle.L', 'Bip01 Clavicle.R' ):
	ipo = bones_ipo[bone]
	ipo_curves = ipo.curveConsts.values()
	maxframe = 0
	# read translation data from ipo(s) and add to key data
	for curve in ipo_curves:
		if ipo[curve] is None:
#				print >> f, "NOT a curve"
			continue
		for btriple in ipo[curve].bezierPoints:
			frame = int(btriple.pt[0])
			maxframe = frame
			Blender.Set('curframe', frame)
			ploc = mypose.bones[bone].loc
			x1 = ploc[0]
			y1 = ploc[1]
			z1 = ploc[2]
			myRot = mypose.bones[bone].quat.toEuler()
			rx = myRot[0]
			ry = myRot[1]
			rz = myRot[2]
			s = "%3d,%s,%.2f,%.2f,%.2f,%.0f,%.0f,%.0f" % (frame,bone,x1,y1,z1,rx,ry,rz)
			keydata.append(s)

# sort selected keydata and export
dic={}
for i in keydata: 
	dic[i]=''
keydata=dic.keys()

keydata.sort()
for line in keydata:
	print >> f, line

get_keys()

 

 

Export "worldspace" location data, i.e. location relative to the scene, into a text file. This allows to read the body movement at the place of the bone

 

 

#!BPY
"""
Name: '03_My_Export_WorldLocation'
Blender: 249
Group: 'Export'
Tooltip: 'Bone World Location'
"""
import Blender
import bpy
from Blender import Armature, Mathutils, Ipo

# Exports "worldspace" location data (i.e. location relative to the scene) into a text file
# Key data has the following format
# <frame>;<bone name>;<x-loc>;<y-loc>;<z-loc>

def get_keys():
f = open('A:\_EXPORT_keys3.txt', 'w')					###### file for export data ######
arm = Blender.Object.Get('Scene Root')

exp_scn = Blender.Scene.GetCurrent()
exp_con = exp_scn.getRenderingContext()
last_frame = Blender.Draw.Create(exp_con.endFrame())

frame = 1
# iterate through all frames
while frame <= last_frame.val:
	Blender.Set('curframe', frame)
	mypose = arm.getPose()	
	wo_matrix = arm.getMatrix("worldspace")
	# iterate through interesting bones
	for bone in ( 'Bip01 Op1.R', 'Bip01 Op1.L'):
#		for bone in ( 'Bip02 Pelvis', 'Bip02 Spine'):

#The total transformation of this PoseBone including constraints.
#This matrix is in armature space, for the current worldspace location of this pose bone, multiply it with its objects worldspace matrix.
#eg. pose_bone.poseMatrix * object.matrixWorld

		pmat=mypose.bones[bone].poseMatrix * wo_matrix
		wloc = pmat.translationPart()
		x2 = wloc[0]
		y2 = wloc[1]
		z2 = wloc[2]
		ploc = mypose.bones[bone].loc
		x1 = ploc[0]
		y1 = ploc[1]
		z1 = ploc[2]
		print >> f, "%d; %s; %.4f; %.4f; %.4f" % (frame,bone,x2,y2,z2)
	frame += 1

get_keys()

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...