#!BPY

"""
Name: 'Arm2Empty'
Blender: 239
Group: 'Wizards'
Tip: 'Create parented empties upon armature'
"""

__author__ = "Jean-Baptiste PERIN"
__url__ = ("blender", "elysiun", "http://perso.wanadoo.fr/jb.perin/")
__version__ = "0.2"
__bpydoc__ = """\
This script create parented empties upon a given armature

Supported:<br>

Missing:<br>

Known issues:<br>

Notes:<br>

"""
# -------------------------------------------------------------------------- 
# ARM2EMPTY.py 
# -------------------------------------------------------------------------- 
# ***** BEGIN GPL LICENSE BLOCK ***** 
# 
# This program is free software; you can redistribute it and/or 
# modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation; either version 2 
# of the License, or (at your option) any later version. 
# 
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
# GNU General Public License for more details. 
# 
# You should have received a copy of the GNU General Public License 
# along with this program; if not, write to the Free Software Foundation, 
# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
# 
# ***** END GPL LICENCE BLOCK ***** 
# -------------------------------------------------------------------------- 



import Blender

def getRootBone(armature):
	rootBone = None
	for bone in armature.bones.values():
		if bone.parent == None :
			if rootBone == None:
				rootBone = bone
			else:
				print "Multiple root armature not handled"
	return rootBone

def makeParenting(bone):
    lempty = Blender.Object.Get(bone.name)
    if bone.children != None:
        for b in bone.children:
            if bone.name == b.parent.name:
                chld_empt = Blender.Object.Get(b.name)
                lempty.makeParent([chld_empt],0,0)
                makeParenting(b)

print "**** START ****"

armaturename = ""
obj_sel = Blender.Object.GetSelected()
if (obj_sel != None) and (len (obj_sel) == 1) and (type(obj_sel[0].getData()) == Blender.Types.ArmatureType):
    armaturename = obj_sel[0].getName()
    armData = Blender.Object.Get(armaturename).getData()
    for b in armData.bones.values():
        lempty = Blender.Object.New('Empty',b.name)	
        Blender.Scene.getCurrent().link(lempty)
        lempty.setMatrix(b.matrix['ARMATURESPACE'])
        lempty.setLocation(b.head['ARMATURESPACE'])

    makeParenting(getRootBone(armData))
    rootemp = Blender.Object.Get(getRootBone(armData).name)
    rootemp.setLocation(Blender.Object.Get(armaturename).getLocation())
    Blender.Redraw()
else:
     error_txt = "Error%t|Select one and only one armature before running this script"
     Blender.Draw.PupMenu(error_txt)
     print error_txt
    
print "**** END ****"


