## +
## ===================================================================
## Copyright(C) 2010 - 2012 Basefount Technology (Hong Kong) Limited.
## and/or its licensors.  All rights reserved.
##
## The coded instructions, statements, computer programs, and/or
## related material (collectively the "Data") in these files contain
## unpublished information proprietary to Basefount Technology
## (Hong Kong) Limitd. ("Basefount") and/or its licensors, which is
## protected by Hong Kong copyright law and by international treaties.
##
## The Data is provided for use exclusively by You. You have the right
## to use, modify, and incorporate this Data into other products for
## purposes authorized by the Basefount software license agreement,
## without fee.
##
## The copyright notices in the Software and this entire statement,
## including the above license grant, this restriction and the
## following disclaimer, must be included in all copies of the
## Software, in whole or in part, and all derivative works of
## the Software, unless such copies or derivative works are solely
## in the form of machine-executable object code generated by a
## source language processor.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
## BASEFOUNT DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR
## IMPLIED WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES
## OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
## PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE, OR
## TRADE PRACTICE. IN NO EVENT WILL BASEFOUNT AND/OR ITS LICENSORS
## BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL,
## DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF BASEFOUNT
## AND/OR ITS LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY
## OR PROBABILITY OF SUCH DAMAGES.
##
## ===================================================================
## -

## +
## ===================================================================
##  Module Name: McdOriginalAgentFunctions
##
##  Description:
##    Functions related to Original Agent (OAgent)
##
##  Special Thanks:
##    Thanapoom Siripopungul (Luma Picture)
##    www.imdb.com/name/nm1451324/
##    for make CopyGeoFromSetupAndSkinToOA()
##
## ===================================================================
## -

import maya.cmds as cmds
import maya.mel as mel
from McdGeneral import *
from McdSimpleCmd import *

def McdParseRootBoneCreateOAgent(usePreset):
    # parse origianl agent group
    # and the root bone:(select the root bone)

    globalNode = McdGetMcdGlobalNode()
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        miarmyGrp = cmds.ls("Miarmy_Contents")
        if miarmyGrp == [] or miarmyGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Miarmy_Contents\" group, please create it with Miarmy->Agent Manager")
            raise Exception("No found you Miarmy Contents group")

        agentGrp = cmds.ls("Agent_" + activeAgentName)
        if agentGrp == [] or agentGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please create it with Miarmy->Agent Manager")
            raise Exception("No found you Agent group")
        else:
            if cmds.nodeType(agentGrp[0]) != "McdAgentGroup":
                cmds.confirmDialog(t = "Error", m = "Invaild \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please delete it and create it with Miarmy->Agent Manager")
                raise Exception("No found you Agent group")

        setupGrp = cmds.ls("Setup_" + activeAgentName)
        if setupGrp == [] or setupGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your setup group, please make sure Setup_" + activeAgentName +\
                                                " is exist under \"Miarmy_Contents->Agent_" + activeAgentName + "\"", \
                                                b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "Setup_" + activeAgentName, em = True)
                cmds.parent("Setup_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you setup group")

        oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
        alreadyDone = False;
        if oAgentGrp == [] or oAgentGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your OriginalAgent group, please make sure OriginalAgent_" +\
                                                activeAgentName + " is exist under \"Miarmy_Contents->Agent_" +\
                                                activeAgentName + "\"", b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "OriginalAgent_" + activeAgentName, em = True)
                cmds.parent("OriginalAgent_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you original agent group")
        else:
            allChildren = cmds.listRelatives(oAgentGrp[0], c = True, p = False)
            if allChildren != [] and allChildren != None:
                cmds.confirmDialog(t = "Abort", m = "Please make sure OriginalAgent_" + activeAgentName + \
                                 " group is empty, original agent might be created already.")
                alreadyDone = True
                cmds.select("OriginalAgent_" + activeAgentName)

        if alreadyDone == False:
            cmds.select("Setup_" + activeAgentName, "OriginalAgent_" + activeAgentName)
            mel.eval("McdCreateOAgentCmd;")
            allChildren = cmds.listRelatives("OriginalAgent_" + activeAgentName)
            if allChildren != [] and allChildren != None:
                MakeBoundingBoxForOriginalAgent()

    # add some attribute and link:
    McdAddAttrBoneShapeLinkToBone()


    if usePreset == 1:
        McdTryToSetupDynJoint(activeAgentName)


def McdSelectSkinBoneTemp():
    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid != True:
        return;

    print "root_ogb_" + activeAgentName

    cmds.select("root_ogb_" + activeAgentName)

    # Result: [u'root_ogb_loco', u'torso1_ogb_loco', u'torso2_ogb_loco', u'torso3_ogb_loco', u'neck1_ogb_loco', u'head_ogb_loco', u'shoulderL_ogb_loco', u'upArmL_ogb_loco', u'lowArmL_ogb_loco', u'handL_ogb_loco', u'shoulderR_ogb_loco', u'upArmR_ogb_loco', u'lowArmR_ogb_loco', u'handR_ogb_loco', u'upLegL_ogb_loco', u'lowLegL_ogb_loco', u'footL_ogb_loco', u'toeL_ogb_loco', u'upLegR_ogb_loco', u'lowLegR_ogb_loco', u'footR_ogb_loco', u'toeR_ogb_loco'] #


def McdParseRootBoneReCreateOAgent():
    # parse origianl agent group
    # and the root bone:(select the root bone)

    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        miarmyGrp = cmds.ls("Miarmy_Contents")
        if miarmyGrp == [] or miarmyGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Miarmy_Contents\" group, please create it with Miarmy->Agent Manager")
            raise Exception("No found you Miarmy Contents group")

        agentGrp = cmds.ls("Agent_" + activeAgentName)
        if agentGrp == [] or agentGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please create it with Miarmy->Agent Manager")
            raise Exception("No found you Agent group")
        else:
            if cmds.nodeType(agentGrp[0]) != "McdAgentGroup":
                cmds.confirmDialog(t = "Error", m = "Invaild \"Agent_" + activeAgentName + \
                "\" group, it should under \"Miarmy_Contents\", please delete it and create it with Miarmy->Agent Manager")
                raise Exception("No found you Agent group")

        setupGrp = cmds.ls("Setup_" + activeAgentName)
        if setupGrp == [] or setupGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your setup group, please make sure Setup_" + activeAgentName +\
                                                " is exist under \"Miarmy_Contents->Agent_" + activeAgentName + "\"", \
                                                b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "Setup_" + activeAgentName, em = True)
                cmds.parent("Setup_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you setup group")

        oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
        alreadyDone = False;
        if oAgentGrp == [] or oAgentGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your OriginalAgent group, please make sure OriginalAgent_" +\
                                                activeAgentName + " is exist under \"Miarmy_Contents->Agent_" +\
                                                activeAgentName + "\"", b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "OriginalAgent_" + activeAgentName, em = True)
                cmds.parent("OriginalAgent_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you original agent group")
        else:
            allChildren = cmds.listRelatives(oAgentGrp[0], c = True, p = False)
            if allChildren != [] and allChildren != None:
                stat = cmds.confirmDialog(t = "Warning", m="Original Agent of "+activeAgentName+" to be deleted, are you Sure?", \
                                        b = ["Proceed", "Cancel"])
                if stat == "Proceed":
                    for i in range(len(allChildren)):
                        try:
                            cmds.delete(allChildren[i])
                        except:
                            cmds.confirmDialog(t = "Error", m = allChildren[i] + "cannot be deleted.")
                else:
                    alreadyDone = True;

        if alreadyDone == False:
            cmds.select("Setup_" + activeAgentName, "OriginalAgent_" + activeAgentName)
            mel.eval("McdCreateOAgentCmd;")
            oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
            allChildren = cmds.listRelatives(oAgentGrp[0])
            if allChildren != [] and allChildren != None:
                MakeBoundingBoxForOriginalAgent()


def McdParseRootBoneDeleteOAgent():
    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        stat = cmds.confirmDialog(t = "Warning", m="Original Agent of "+activeAgentName+" to be deleted, are you Sure?", \
                                b = ["Proceed", "Cancel"])
        if stat == "Proceed":
            try:
                oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
                allChildren = cmds.listRelatives(oAgentGrp[0], p = False, c = True);
                for i in range(len(allChildren)):
                    cmds.delete(allChildren[i])
            except:
                pass


def MakeBoundingBoxForOriginalAgent():
    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        miarmyGrp = cmds.ls("Miarmy_Contents")
        if miarmyGrp == [] or miarmyGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Miarmy_Contents\" group, please create it with Miarmy->Agent Manager")
            raise Exception("No found you Miarmy Contents group")

        agentGrp = cmds.ls("Agent_" + activeAgentName)
        if agentGrp == [] or agentGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please create it with Miarmy->Agent Manager")
            raise Exception("No found you Agent group")
        else:
            if cmds.nodeType(agentGrp[0]) != "McdAgentGroup":
                cmds.confirmDialog(t = "Error", m = "Invaild \"Agent_" + activeAgentName + \
                "\" group, it should under \"Miarmy_Contents\", please delete it and create it with Miarmy->Agent Manager")
                raise Exception("No found you Agent group")

        setupGrp = cmds.ls("Setup_" + activeAgentName)
        if setupGrp == [] or setupGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your setup group, please make sure Setup_" + activeAgentName +\
                                                " is exist under \"Miarmy_Contents->Agent_" + activeAgentName + "\"", \
                                                b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "Setup_" + activeAgentName, em = True)
                cmds.parent("Setup_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you setup group")

        oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
        alreadyDone = False;
        if oAgentGrp == [] or oAgentGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your OriginalAgent group, please make sure OriginalAgent_" +\
                                                activeAgentName + " is exist under \"Miarmy_Contents->Agent_" +\
                                                activeAgentName + "\"", b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "OriginalAgent_" + activeAgentName, em = True)
                cmds.parent("OriginalAgent_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you original agent group")

        if alreadyDone == False:
            bbName = "BoundingBox_" + activeAgentName;
            bbShape = "BoundingBoxShape_" + activeAgentName;
            bbObj = cmds.ls(bbName)
            if bbObj == [] or bbObj == None:
                cmds.group(n = bbName, em = True)
                cmds.createNode("McdBoundBox", n = bbShape, p = bbName)
                cmds.color(bbName, ud = 4)
                cmds.parent(bbName, "OriginalAgent_" + activeAgentName)
                cmds.setAttr(bbName+".tx", 0)
                cmds.setAttr(bbName+".ty", 0)
                cmds.setAttr(bbName+".tz", 0)
                cmds.setAttr(bbName+".rx", e = True, k = False, l = True)
                cmds.setAttr(bbName+".ry", e = True, k = False, l = True)
                cmds.setAttr(bbName+".rz", e = True, k = False, l = True)
            else:
                try:
                    cmds.parent(bbName, "OriginalAgent_" + activeAgentName)
                except:
                    cmds.confirmDialog(t = "Abort", m = "Bounding box exist for active agent.")



def McdTryToSetupDynJoint(activeAgentName):

    try:
        # joint
        # bone shape
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".ty", 1.536)
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".sx", 4.736)
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".sy", 5.641)
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".sz", 2.516)
    except:
        pass

    try:
        # joint:
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".ry", 180)
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".swingDw", 60)
        
        # bone shape
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".tx", -3.325)
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".sx", 6.65)
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".sy", 1.857)
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".sz", 2.403)
    except:
        pass

    try:
        # joint:
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".swingUp", 15)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".swingDw", 120)

        # bone shape:
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".tx", -4.386)
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".sx", 8.773)
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".sy", 1.615)
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".sz", 1.92)
    except:
        pass

    try:
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".swingUp", 45)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".swingDw", 45)

        cmds.setAttr("footL_dummyShape_" + activeAgentName + ".tx", -1.122)
        cmds.setAttr("footL_dummyShape_" + activeAgentName + ".sx", 2.244)
        cmds.setAttr("footL_dummyShape_" + activeAgentName + ".sz", 1.647)
        
    except:
        pass

    try:
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".swingUp", 20)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".swingDw", 20)

        cmds.setAttr("toeL_dummyShape_" + activeAgentName + ".tx", -0.695)
        cmds.setAttr("toeL_dummyShape_" + activeAgentName + ".sx", 1.39)
        cmds.setAttr("toeL_dummyShape_" + activeAgentName + ".sz", 1.419)
    except:
        pass

    try:
        # joint:
        cmds.setAttr("upLegR_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("upLegR_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("upLegR_phyJoint_" + activeAgentName + ".swingDw", 60)
        
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".tx", 3.325)
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".sx", 6.65)
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".sy", 1.857)
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".sz", 2.403)
    except:
        pass

    try:
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".swingUp", 15)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".swingDw", 120)

        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".tx", 4.386)
        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".sx", 8.773)
        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".sy", 1.615)
        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".sz", 1.92)
    except:
        pass

    try:
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".swingUp", 45)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".swingDw", 45)

        cmds.setAttr("footR_dummyShape_" + activeAgentName + ".tx", 1.122)
        cmds.setAttr("footR_dummyShape_" + activeAgentName + ".sx", 2.244)
        cmds.setAttr("footR_dummyShape_" + activeAgentName + ".sz", 1.647)
    except:
        pass

    try:
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".swingUp", 20)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".swingDw", 25)

        cmds.setAttr("toeR_dummyShape_" + activeAgentName + ".tx", 0.695)
        cmds.setAttr("toeR_dummyShape_" + activeAgentName + ".sx", 1.39)
        cmds.setAttr("toeR_dummyShape_" + activeAgentName + ".sz", 1.419)
    except:
        pass

    # upper body:
    try:
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".ty", 0.615)
        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".sx", 5.05)
        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".sy", 2.84)
        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".sz", 2.782)
    except:
        pass

    try:
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".twistDw", -30)
        

        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".ty", 0.742)
        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".sx", 5.99)
        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".sy", 2.558)
        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".sz", 3.069)
    except:
        pass

    try:
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".ty", 1.419)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".tz", -0.491)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".sx", 5.013)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".sy", 2.619)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".sz", 3.452)
    except:
        pass

    try:
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".ty", 0.541)
        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".sx", 2.152)
        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".sy", 1.417)
        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".sz", 1.477)
        
    except:
        pass

    try:
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("head_dummyShape_" + activeAgentName + ".ty", 1.802)
        cmds.setAttr("head_dummyShape_" + activeAgentName + ".sx", 3.036)
        cmds.setAttr("head_dummyShape_" + activeAgentName + ".sy", 3.207)
        cmds.setAttr("head_dummyShape_" + activeAgentName + ".sz", 2.663)
    except:
        pass

    try:
        cmds.setAttr("shoulderL_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("shoulderL_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("shoulderL_phyJoint_" + activeAgentName + ".swingDw", 60)

        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".tx", 1.393)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".ty", 0.774)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".sx", 2.786)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".sy", 2.018)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".sz", 2.42)
    except:
        pass

    try:
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".ry", 180)
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".swingDw", 60)

        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".tx", -1.393)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".ty", -0.774)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".sx", 2.786)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".sy", 2.018)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".sz", 2.42)
    except:
        pass

    try:
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".swingUp", 80)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".swingDw", 10)

        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".tx", 2.237)
        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".sx", 4.474)
        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".sy", 1.911)
        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".sz", 2.096)
    except:
        pass

    try:
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".swingUp", 80)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".swingDw", 10)

        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".tx", -2.209)
        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".sx", 4.474)
        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".sy", 1.911)
        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".sz", 2.096)
    except:
        pass

    try:
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".rz", -90)
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".swingUp", 130)
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".swingDw", 10)

        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".tx", 2.638)
        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".sx", 5.275)
        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".sy", 1.49)
        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".sz", 1.869)
    except:
        pass

    try:
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".swingUp", 10)
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".swingDw", 130)

        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".tx", -2.638)
        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".sx", 5.275)
        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".sy", 1.49)
        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".sz", 1.869)
    except:
        pass

    try:
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".swingUp", 75)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".swingDw", 75)

        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".tx", 0.638)
        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".sx", 1.621)
        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".sy", 0.977)
        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".sz", 1.815)
    except:
        pass

    try:
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".swingUp", 75)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".swingDw", 75)

        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".tx", -0.638)
        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".sx", 1.621)
        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".sy", 0.977)
        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".sz", 1.815)
    except:
        pass

    try:
        cmds.setAttr("BoundingBox_" + activeAgentName + ".ty", 18.263)
        cmds.setAttr("BoundingBox_" + activeAgentName + ".sx", 33.651)
        cmds.setAttr("BoundingBox_" + activeAgentName + ".sy", 36.692)
        cmds.setAttr("BoundingBox_" + activeAgentName + ".sz", 32.75)
    except:
        pass



def McdSelectSkinBone():
    globalNode = McdListMcdGlobal()
    actName = cmds.getAttr(globalNode + ".activeAgentName")

    allOrgBones = cmds.ls("*_" + actName, type = "joint", l = True)
    if allOrgBones == [] or allOrgBones == None:
        cmds.confirmDialog(t = "Error", m = "No joints found for current original agent.")
        return
    geoGroup = cmds.ls("Geometry_" + actName, l = True)
    if geoGroup == [] or geoGroup == None:
        cmds.confirmDialog(t = "Error", m = "No Geometry group found for current original agent.")
        return

    skinBone = []
    for i in range(len(allOrgBones)):
        allChild = cmds.listRelatives(allOrgBones[i], c = True, p = False, pa = True)
        if allChild == [] or allChild == None:
            continue
        for j in range(len(allChild)):
            if cmds.nodeType(allChild[j]) == "joint":
                skinBone.append(allOrgBones[i])
                continue

    skinGeo = []
    cmds.select(geoGroup[0], hi = True)
    allGeo = cmds.ls(sl = True, l = True)
    for i in range(len(allGeo)):
        if cmds.nodeType(allGeo[i]) == "mesh":
            skinGeo.append(allGeo[i])


    if skinBone == [] or skinGeo == []:
        cmds.confirmDialog(t = "Error", m = "No geometries or joints found for current original agent.")
        return

    # select session:
    cmds.select(clear = True)
    for i in range(len(skinBone)):
        try:
            cmds.select(skinBone[i], add = True)
        except:
            pass

    for i in range(len(skinGeo)):
        try:
            cmds.select(skinGeo[i], add = True)
        except:
            pass

    cmds.confirmDialog(t = "Done", m = "We selected the following things for you:\n * Joints without \"End Joint\"\n * Geometries in group"+ \
                     "\n\nYou can now skin geometry directly by Maya skin tools")


def CopyGeoFromSetupAndSkinToOA1():
    # parse selection:
    selObjs = cmds.ls(sl = True, long = True)
    if selObjs == [] or selObjs == None:
        cmds.confirmDialog(t = "Error", m = "Please select activated character geometry(ies) firstly")
        return;

    activeAgentName = McdGetActiveAgentName()

    errorReport = []
    # ---------------------------
    # 1: no skin
    # 2: not found match bone or not active
    # 3: cannot copy
    # 4: cannot parent
    # ---------------------------

    # for each geo:
    for i in range(len(selObjs)):
        selTrans = selObjs[i]
        if cmds.nodeType(selTrans) == "mesh":
            selGeo = selObjs
        else:
            selGeo = cmds.listRelatives(selTrans, c = True, f = True)
        if selGeo == [] or selGeo == None:
            continue

        if cmds.nodeType(selGeo[0]) != "mesh":
            continue

        points = cmds.ls(selGeo[0] + ".vtx[*]")
        if points == [] or points == None:
            continue

        temp = points[0].split(":")[-1]
        temp = temp.split("]")[0]
        maxPoints = int(temp) + 1


        #---------------------------
        # find skinCluster history
        # find skin bones
        # match bones in OA
        # copy mesh
        # skin
        # copy weight
        # put it to Geometry_<Agt>
        # feedback errors
        #---------------------------

        # find skinCluster history
        sourceSkin = ""
        sourceHistory = cmds.listHistory(selGeo)
        for i in range(len(sourceHistory)):
            if cmds.nodeType(sourceHistory[i]) == "skinCluster":
                sourceSkin = sourceHistory[i]
                break
        if sourceSkin == "":
            if 1 not in errorReport:
                errorReport.append(1)
            continue

        # find skin bones
        influenceList = cmds.listConnections(sourceSkin + ".lockWeights")
        if influenceList == [] or influenceList == None:
            continue

        # match bones in OA
        targetInfluenceList = []
        isActiveBone = False
        cannotMatchCorrectly = False
        for j in range(len(influenceList)):
            if McdCheckNodeActiveCmd(influenceList[j]):
                # find counterpart and append:
                try:
                    counterpartBone = findCounterpartBone(influenceList[j])
                except:
                    counterpartBone = ""
                if counterpartBone == "":
                    cannotMatchCorrectly = True
                    break
                targetInfluenceList.append(counterpartBone)
            else:
                cannotMatchCorrectly = True
                break

        if cannotMatchCorrectly:
            if 2 not in errorReport:
                errorReport.append(2)
            continue

        #if not isActiveBone:
        #    continue

        # copy mesh
        newMeshList = cmds.duplicate(selGeo, rr = True, po = True)
        if newMeshList == None or newMeshList == []:
            if 3 not in errorReport:
                errorReport.append(3)
            continue
        newMesh = newMeshList[0]
        selMesh = selGeo[0]

        # skin newMesh by targetInfluenceList
        # resource by new:

        cmds.select(newMesh)
        cmds.select(targetInfluenceList, add = True)

        targetSkin = cmds.skinCluster(toSelectedBones = True)[0]

        # copy weight
        for i in range(maxPoints):
            sourcePoint = selMesh + ".vtx["+ str(i) +"]"
            targetPoint = newMesh + ".vtx["+ str(i) +"]"
            info = cmds.skinPercent(sourceSkin, sourcePoint, q = True, v = True)
            for j in range(len(influenceList)):
                cmds.skinPercent(targetSkin, targetPoint, tv = [(targetInfluenceList[j], info[j])])

        # put it to Geometry_<Agt>
        try:
            cmds.parent(newMesh, "Geometry_" + activeAgentName)
        except:
            if 4 not in errorReport:
                errorReport.append(4)

    # ---------------------------
    # Feedback Errors
    # 1: no skin
    # 2: not found match bone or not active
    # 3: cannot copy
    # 4: cannot parent
    # ---------------------------

    errorMessage = ""

    if errorReport != []:
        errorMessage += "Not all of your selected geometry correctly copied:\n"

        if 1 in errorReport:
            errorMessage += "* did not find skinCluster node for selected Geo\n"
        if 2 in errorReport:
            errorMessage += "* did not find matched bone for your rig, \nplease active your agent or check the naming of original agent\n"
        if 3 in errorReport:
            errorMessage += "* cannot perform duplicate maya command for your selected\n"
        if 4 in errorReport:
            errorMessage += "* cannot parent new geometry to the Geometry_<AgtName>\n"

    if errorMessage != "":
        cmds.confirmDialog(t = "Error", m = errorMessage)


def findCounterpartBone(rigBone):
    activeAgentName = McdGetActiveAgentName()

    oaBone = ""
    # find real name:
    temp1 = rigBone.split("|")[-1]
    temp2 = temp1.split(":")[-1]
    rigBoneNodeName = temp2

    oaBoneNodeName = rigBoneNodeName + "_ogb_" + activeAgentName

    foundBoneSet = cmds.ls('*' + oaBoneNodeName)
    if foundBoneSet == [] or foundBoneSet == None:
        return "" # blank

    if len(foundBoneSet) == 1:
        oaBone = foundBoneSet[0]
        return oaBone

    # not only one, test activate!






    # not only one, test root bone!
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    if cmds.nodeType(rigBoneParent) != "joint":
        for i in range(len(foundBoneSet)):
            temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
            if cmds.nodeType(temp) != "joint":
                oaBone = foundBoneSet[i];
                return oaBone

    # not only one, compare parent!!
    equalIndexSet = []
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParentNodeName = rigBoneParent.split('|')[-1]
    rigBoneParentNodeName = rigBoneParentNodeName.split(':')[-1]
    for i in range(len(foundBoneSet)):
        temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
        temp = temp.split('|')[-1]
        temp = temp.split(':')[-1]
        thisFoundBoneNode = temp.split("_ogb_")[0]

        if thisFoundBoneNode == rigBoneParentNodeName:
            equalIndexSet.append(i)


    if len(equalIndexSet) == 0:
        return ""
    elif len(equalIndexSet) == 1:
        oaBone = foundBoneSet[equalIndexSet[0]]
        return oaBone


    ############################################################################
    # not only one, test root bone!
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    if cmds.nodeType(rigBoneParent) != "joint":
        for i in range(len(foundBoneSet)):
            temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
            temp = cmds.listRelatives(temp, p = True, f = True)[0]
            if cmds.nodeType(temp) != "joint":
                oaBone = foundBoneSet[i];
                return oaBone

    # if not found, compare parent of parent!!
    equalIndexSet = []
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParentNodeName = rigBoneParent.split('|')[-1]
    rigBoneParentNodeName = rigBoneParentNodeName.split(':')[-1]
    for i in range(len(foundBoneSet)):
        temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
        temp = cmds.listRelatives(temp, p = True, f = True)[0]
        temp = temp.split('|')[-1]
        temp = temp.split(':')[-1]
        thisFoundBoneNode = temp.split("_ogb_")[0]

        if thisFoundBoneNode == rigBoneParentNodeName:
            equalIndexSet.append(i)

    if len(equalIndexSet) == 0:
        return ""
    elif len(equalIndexSet) == 1:
        oaBone = foundBoneSet[equalIndexSet[0]]
        return oaBone


    ############################################################################
    # not only one, test root bone!
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    if cmds.nodeType(rigBoneParent) != "joint":
        for i in range(len(foundBoneSet)):
            temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
            temp = cmds.listRelatives(temp, p = True, f = True)[0]
            temp = cmds.listRelatives(temp, p = True, f = True)[0]
            if cmds.nodeType(temp) != "joint":
                oaBone = foundBoneSet[i];
                return oaBone

    # if not found, compare parent of parent!!
    equalIndexSet = []
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParentNodeName = rigBoneParent.split('|')[-1]
    rigBoneParentNodeName = rigBoneParentNodeName.split(':')[-1]
    for i in range(len(foundBoneSet)):
        temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
        temp = cmds.listRelatives(temp, p = True, f = True)[0]
        temp = cmds.listRelatives(temp, p = True, f = True)[0]
        temp = temp.split('|')[-1]
        temp = temp.split(':')[-1]
        thisFoundBoneNode = temp.split("_ogb_")[0]

        if thisFoundBoneNode == rigBoneParentNodeName:
            equalIndexSet.append(i)

    if len(equalIndexSet) == 0:
        return ""
    elif len(equalIndexSet) == 1:
        oaBone = foundBoneSet[equalIndexSet[0]]
        return oaBone


    return ""


def CopyGeoFromSetupAndSkinToOA():

    selObjs = cmds.ls(sl = 1)
    if selObjs == [] or selObjs == None:
        cmds.confirmDialog(t = "Error", m = "Please select activated character geometry(ies) firstly")

    #getAgentName
    activeAgentName = McdGetActiveAgentName()
    for selGeo in selObjs:
        # get Jnt that use for skinCluster for each Obj
        links = cmds.listHistory(selGeo, pdo=0, il=1)
        skin = cmds.ls(links, typ="skinCluster")
        if MIsBlank(skin):
            cmds.confirmDialog(t = "Error", m = "Only support smooth skin cluster, skip: \n" + selGeo)
            continue
        
        jnts = cmds.skinCluster(skin[0], q=1, inf=1)
        if MIsBlank(jnts):
            cmds.confirmDialog(t = "Error", m = "Skin Cluster no inf joint found, skip: \n" + selGeo)
            continue
        
        for i in range(len(jnts)):
            if jnts[i].find("|") >= 0:
                cmds.confirmDialog(t = "Error", m = "Repeated name detected in your initial rig.\n" + jnts[i])
                return
        
        newJnt= []
        # add suffix for eachJnt 'ogb_'+activeAgentName)
        for jnt in jnts:
            jntRaw = jnt.split(":")[-1]
            newJnt.append(jntRaw + '_ogb_' + activeAgentName)
            
        
            
        # dulplicate Mesh
        newMesh = cmds.duplicate(selGeo,n= selGeo+'_'+activeAgentName+'Geo')[0]
        try:
            cmds.setAttr(newMesh + ".tx", l = False)
            cmds.setAttr(newMesh + ".ty", l = False)
            cmds.setAttr(newMesh + ".tz", l = False)
            cmds.setAttr(newMesh + ".rx", l = False)
            cmds.setAttr(newMesh + ".ry", l = False)
            cmds.setAttr(newMesh + ".rz", l = False)
            cmds.setAttr(newMesh + ".sx", l = False)
            cmds.setAttr(newMesh + ".sy", l = False)
            cmds.setAttr(newMesh + ".sz", l = False)
            cmds.makeIdentity(newMesh, apply = True, t = True, r = True, s = True, n = False, pn = True)
        except:
            pass
        #delete OrigShape
        nodes = cmds.ls(newMesh,dag=1)
        for obj in nodes:
            if obj[-4:]=='Orig':
                cmds.delete(obj)
        cmds.skinCluster(newJnt, newMesh, ibp=1, ih=1, dr=4, tsb=1, mi=1, nw=1)
        # select originalMesh and duplicateMesh then do copySkin
        cmds.select(selGeo, newMesh)
        cmds.copySkinWeights(surfaceAssociation='closestPoint', influenceAssociation=['oneToOne','closestJoint', 'label'], noMirror=1)
        # parent to
        if cmds.objExists("Geometry_" + activeAgentName) :
            cmds.parent(newMesh, "Geometry_" + activeAgentName)
            
def McdAddAttrBoneShapeLinkToBone( addFull = False ):

    activeAgentName = McdGetActiveAgentName()
    
    # link custom data number!!
    orgSel = cmds.ls(sl = True)
    McdStatAndLinkCustomDataNum(activeAgentName)
    try:
        cmds.select(orgSel)
    except:
        pass

    orgSelObj = cmds.ls(sl = True, l = True)

    # find the root bone
    try:
        oaGrp = cmds.ls("OriginalAgent_" + activeAgentName)[0]
    except:
        return

    # walk bone tree
    allChildren = cmds.listRelatives(oaGrp, c = True, p =False, fullPath =True)
    if allChildren == [] or allChildren == None:
        return

    #select whole tree:
    rootJoint = ""
    for i in range(len(allChildren)):
        if cmds.nodeType(allChildren[i]) == "joint":
            rootJoint = allChildren[i]

    if rootJoint == "":
        return

    # create and link!
    cmds.select(rootJoint)
    allJoints = mel.eval("McdSimpleCommand -exe 31")

    for i in range(len(allJoints)):
        allChild = cmds.listRelatives(allJoints[i], c = True, p = False, fullPath = True)
        if allChild == [] or allChild == None:
            continue;
        for j in range(len(allChild)):
            if allChild[j].find("_dummyShape_") >0:
                McdAddAttrAndLink(allChild[j], allJoints[i], addFull)

    try:
        if orgSelObj == [] or orgSelObj == None:
            cmds.select(clear = True)
        else:
            cmds.select(orgSelObj)
    except:
        pass

def AddAimRotationLimitAttr():
    selObj = cmds.ls(sl = True)
    if MIsBlank(selObj):
        cmds.confirmDialog(t = "Error", m  = "Please select at least one dummy shape.", b = ["", ""])
        
    addThese = []
    for i in range(len(selObj)):
        if selObj[i].find("_dummyShape_") > 0:
            try:
                inNode = selObj[i]
                cmds.addAttr(inNode, ln = "horizontalL", at = "bool")
                cmds.setAttr(inNode + ".horizontalL", k = False, cb = True)
                cmds.addAttr(inNode, ln = "hlValue", at = "long", min = -180, max = 0, dv = -45)
                cmds.setAttr(inNode + ".hlValue", k = False, cb = True)
                
                cmds.addAttr(inNode, ln = "horizontalR", at = "bool")
                cmds.setAttr(inNode + ".horizontalR", k = False, cb = True)
                cmds.addAttr(inNode, ln = "hrValue", at = "long", min = 0, max = 180, dv = 45)
                cmds.setAttr(inNode + ".hrValue", k = False, cb = True)
                
                cmds.addAttr(inNode, ln = "verticalU", at = "bool")
                cmds.setAttr(inNode + ".verticalU", k = False, cb = True)
                cmds.addAttr(inNode, ln = "vuValue", at = "long", min = -180, max = 0, dv = -45)
                cmds.setAttr(inNode + ".vuValue", k = False, cb = True)
                
                cmds.addAttr(inNode, ln = "verticalD", at = "bool")
                cmds.setAttr(inNode + ".verticalD", k = False, cb = True)
                cmds.addAttr(inNode, ln = "vdValue", at = "long", min = 0, max = 180, dv = 45)
                cmds.setAttr(inNode + ".vdValue", k = False, cb = True)
                
                attachJoint = cmds.listRelatives(inNode, c = False, p = True)[0] #-------------------------
                
                cmds.addAttr(attachJoint, ln = "horizontalL", at = "bool")
                cmds.addAttr(attachJoint, ln = "hlValue", at = "long")
                
                cmds.addAttr(attachJoint, ln = "horizontalR", at = "bool")
                cmds.addAttr(attachJoint, ln = "hrValue", at = "long")
                
                cmds.addAttr(attachJoint, ln = "verticalU", at = "bool")
                cmds.addAttr(attachJoint, ln = "vuValue", at = "long")
                
                cmds.addAttr(attachJoint, ln = "verticalD", at = "bool")
                cmds.addAttr(attachJoint, ln = "vdValue", at = "long")
                
                # -------------------------------
                cmds.connectAttr(inNode + ".horizontalL", attachJoint + ".horizontalL")
                cmds.connectAttr(inNode + ".horizontalR", attachJoint + ".horizontalR")
                cmds.connectAttr(inNode + ".verticalU", attachJoint + ".verticalU")
                cmds.connectAttr(inNode + ".verticalD", attachJoint + ".verticalD")
                cmds.connectAttr(inNode + ".hlValue", attachJoint + ".hlValue")
                cmds.connectAttr(inNode + ".hrValue", attachJoint + ".hrValue")
                cmds.connectAttr(inNode + ".vuValue", attachJoint + ".vuValue")
                cmds.connectAttr(inNode + ".vdValue", attachJoint + ".vdValue")
                
                addThese.append(selObj[i])
                
            except:
                pass
            
            
            
            
def McdAddAttrAndLink(inNode, linkToBone, addFull = False):

    globalNode = McdGetMcdGlobalNode()
    if cmds.getAttr(globalNode + ".hookCustomData") == 1:
        ### customDataNum ###########################################################################
        try:
            cmds.addAttr(inNode, ln = "customDataNum", at = "long")
            cmds.setAttr(inNode + ".customDataNum", k = False, cb = True)
        except:
            pass
        
        try:
            cmds.connectAttr(linkToBone + ".customDataNum", inNode + ".customDataNum", f = True)
        except:
            pass

    if addFull:
        
        ### collideCloth ###########################################################################
        try:
            cmds.addAttr(inNode, ln = "collideCloth", at = "bool")
            cmds.setAttr(inNode + ".collideCloth", k = False, cb = True)
        except:
            pass

        try:
            cmds.addAttr(linkToBone, ln = "collideCloth", at = "bool")
            cmds.setAttr(linkToBone + ".collideCloth", k = False, cb = False)
        except:
            pass
        try:
            cmds.connectAttr(inNode + ".collideCloth", linkToBone + ".collideCloth", f = True)
        except:
            pass

        ### collideFeel ###########################################################################
        try:
            cmds.addAttr(inNode, ln = "collideFeel", at = "bool")
            cmds.setAttr(inNode + ".collideFeel", k = False, cb = True)
        except:
            pass

        try:
            cmds.addAttr(linkToBone, ln = "collideFeel", at = "bool")
            cmds.setAttr(linkToBone + ".collideFeel", k = False, cb = False)
        except:
            pass
        try:
            cmds.connectAttr(inNode + ".collideFeel", linkToBone + ".collideFeel", f = True)
        except:
            pass

        #### fieldFeel #############################################################################
        try:
            cmds.addAttr(inNode, ln = "fieldFeel", at = "bool")
            cmds.setAttr(inNode + ".fieldFeel", k = False, cb = True)
        except:
            pass

        try:
            cmds.addAttr(linkToBone, ln = "fieldFeel", at = "bool")
            cmds.setAttr(linkToBone + ".fieldFeel", k = False, cb = False)
        except:
            pass
        try:
            cmds.connectAttr(inNode + ".fieldFeel", linkToBone + ".fieldFeel", f = True)
        except:
            pass

    ### density ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "density", at = "float")
        cmds.setAttr(inNode + ".density", k = False, cb = True)
        cmds.setAttr(inNode + ".density", 1)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "density", at = "float")
        cmds.setAttr(linkToBone + ".density", k = False, cb = False)
        cmds.setAttr(linkToBone + ".density", 1)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".density", linkToBone + ".density", f = True)
    except:
        pass

    ### genFootMap ############################################################################
    try:
        cmds.addAttr(inNode, ln = "genFootMap", at = "bool")
        cmds.setAttr(inNode + ".genFootMap", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "genFootMap", at = "bool")
        cmds.setAttr(linkToBone + ".genFootMap", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".genFootMap", linkToBone + ".genFootMap", f = True)
    except:
        pass

    ### disableDynSubTree ########################################################################
    try:
        cmds.addAttr(inNode, ln = "disableDynSubTree", at = "bool")
        cmds.setAttr(inNode + ".disableDynSubTree", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "disableDynSubTree", at = "bool")
        cmds.setAttr(linkToBone + ".disableDynSubTree", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".disableDynSubTree", linkToBone + ".disableDynSubTree", f = True)
    except:
        pass
    
    ### compoundRBD ########################################################################
    try:
        cmds.addAttr(inNode, ln = "compoundRBD", at = "bool")
        cmds.setAttr(inNode + ".compoundRBD", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "compoundRBD", at = "bool")
        cmds.setAttr(linkToBone + ".compoundRBD", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".compoundRBD", linkToBone + ".compoundRBD", f = True)
    except:
        pass
    
    #### block simulation #####################################################################
    try:
        cmds.addAttr(inNode, ln = "skipAnim", at = "bool")
        cmds.setAttr(inNode + ".skipAnim", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "skipAnim", at = "bool")
        cmds.setAttr(linkToBone + ".skipAnim", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".skipAnim", linkToBone + ".skipAnim", f = True)
    except:
        pass
    
    ### auto IK ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "autoIKLv", at = "long")
        cmds.setAttr(inNode + ".autoIKLv", k = False, cb = True)
        cmds.setAttr(inNode + ".autoIKLv")
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "autoIKLv", at = "long")
        cmds.setAttr(linkToBone + ".autoIKLv", k = False, cb = False)
        cmds.setAttr(linkToBone + ".autoIKLv")
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".autoIKLv", linkToBone + ".autoIKLv", f = True)
    except:
        pass

    ### IK axis ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "ikAxis", at = "enum", en = "auto:+X:+Y:+Z:-X:-Y:-Z:")
        cmds.setAttr(inNode + ".ikAxis", k = False, cb = True)
        cmds.setAttr(inNode + ".ikAxis")
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "ikAxis", at = "long")
        cmds.setAttr(linkToBone + ".ikAxis", k = False, cb = False)
        cmds.setAttr(linkToBone + ".ikAxis")
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".ikAxis", linkToBone + ".ikAxis", f = True)
    except:
        pass
    
    ### Up axis ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "autoIkUp", at = "enum", en = "+Z:+Y:")
        cmds.setAttr(inNode + ".autoIkUp", k = False, cb = True)
        cmds.setAttr(inNode + ".autoIkUp")
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "autoIkUp", at = "long")
        cmds.setAttr(linkToBone + ".autoIkUp", k = False, cb = False)
        cmds.setAttr(linkToBone + ".autoIkUp")
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".autoIkUp", linkToBone + ".autoIkUp", f = True)
    except:
        pass
    

    ### Up axis ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "blockTranslate", at = "bool")
        cmds.setAttr(inNode + ".blockTranslate", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "blockTranslate", at = "bool")
        cmds.setAttr(linkToBone + ".blockTranslate", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".blockTranslate", linkToBone + ".blockTranslate", f = True)
    except:
        pass


    ### rbd Target ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "rbdTarget", at = "bool")
        cmds.setAttr(inNode + ".rbdTarget", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "rbdTarget", at = "bool")
        cmds.setAttr(linkToBone + ".rbdTarget", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".rbdTarget", linkToBone + ".rbdTarget", f = True)
    except:
        pass


def McdUpgradeOAgent():

    McdAddAttrBoneShapeLinkToBone(True);

def McdStatAndLinkCustomDataNum(activeAgentName):
    
    globalNode = McdGetMcdGlobalNode()
    if cmds.getAttr(globalNode + ".hookCustomData") != 1:
        print "bypass custom data hooking"
        return;
    
    rigGrp = cmds.ls("Setup_" + activeAgentName)
    oaGrp = cmds.ls("OriginalAgent_" + activeAgentName)
    
    if McdIsBlank(rigGrp) or McdIsBlank(oaGrp):
        return
    
    agtGrpRaw = cmds.listRelatives(rigGrp[0], p = True, c = False)
    if MIsBlank(agtGrpRaw):
        return

    agtGrp = agtGrpRaw[0]
    if cmds.nodeType(agtGrp) != "McdAgentGroup":
        return
    
    cmds.select(rigGrp)
    rigRootJnt = mel.eval("McdSimpleCommand -exe 30")
    if McdIsBlank(rigRootJnt):
        return
    
    cmds.select(oaGrp)
    oaRootJnt = mel.eval("McdSimpleCommand -exe 30")
    if McdIsBlank(oaRootJnt):
        return

    try:
        cmds.select(rigRootJnt)
    except:
        pass
    rigAllBones = mel.eval("McdSimpleCommand -exe 31")
    
    try:
        cmds.select(oaRootJnt)
    except:
        pass
    oaAllBones = mel.eval("McdSimpleCommand -exe 31")
    
    if len(rigAllBones) != len(oaAllBones):
        return;
    
    # enable it!
    cmds.setAttr(agtGrp + ".cdHooked", 1)
    cdCount = 0
    
    for i in range(len(rigAllBones)):
        allUDAttr = cmds.listAttr(rigAllBones[i], ud = True)
        try:
            cmds.addAttr(oaAllBones[i], ln = "customDataNum", at = "long")
            if (len(allUDAttr) > 0):
                cmds.setAttr(oaAllBones[i] + ".customDataNum", len(allUDAttr))
        except:
            pass
        
        if MIsBlank(allUDAttr):
            continue
        else:
            for j in range(len(allUDAttr)):
                cmds.setAttr(agtGrp + ".cdNames[" + str(cdCount) + "]", allUDAttr[j], type = "string")
                cdCount += 1
        
    cmds.setAttr(agtGrp + ".cdNum", cdCount)































e5fffd27f8c9262775652674797a68be5dbfddcc
## +
## ===================================================================
## Copyright(C) 2010 - 2012 Basefount Technology (Hong Kong) Limited.
## and/or its licensors.  All rights reserved.
##
## The coded instructions, statements, computer programs, and/or
## related material (collectively the "Data") in these files contain
## unpublished information proprietary to Basefount Technology
## (Hong Kong) Limitd. ("Basefount") and/or its licensors, which is
## protected by Hong Kong copyright law and by international treaties.
##
## The Data is provided for use exclusively by You. You have the right
## to use, modify, and incorporate this Data into other products for
## purposes authorized by the Basefount software license agreement,
## without fee.
##
## The copyright notices in the Software and this entire statement,
## including the above license grant, this restriction and the
## following disclaimer, must be included in all copies of the
## Software, in whole or in part, and all derivative works of
## the Software, unless such copies or derivative works are solely
## in the form of machine-executable object code generated by a
## source language processor.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
## BASEFOUNT DOES NOT MAKE AND HEREBY DISCLAIMS ANY EXPRESS OR
## IMPLIED WARRANTIES INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES
## OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
## PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE, OR
## TRADE PRACTICE. IN NO EVENT WILL BASEFOUNT AND/OR ITS LICENSORS
## BE LIABLE FOR ANY LOST REVENUES, DATA, OR PROFITS, OR SPECIAL,
## DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES, EVEN IF BASEFOUNT
## AND/OR ITS LICENSORS HAS BEEN ADVISED OF THE POSSIBILITY
## OR PROBABILITY OF SUCH DAMAGES.
##
## ===================================================================
## -

## +
## ===================================================================
##  Module Name: McdOriginalAgentFunctions
##
##  Description:
##    Functions related to Original Agent (OAgent)
##
##  Special Thanks:
##    Thanapoom Siripopungul (Luma Picture)
##    www.imdb.com/name/nm1451324/
##    for make CopyGeoFromSetupAndSkinToOA()
##
## ===================================================================
## -

import maya.cmds as cmds
import maya.mel as mel
from McdGeneral import *
from McdSimpleCmd import *

def McdParseRootBoneCreateOAgent(usePreset):
    # parse origianl agent group
    # and the root bone:(select the root bone)

    globalNode = McdGetMcdGlobalNode()
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        miarmyGrp = cmds.ls("Miarmy_Contents")
        if miarmyGrp == [] or miarmyGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Miarmy_Contents\" group, please create it with Miarmy->Agent Manager")
            raise Exception("No found you Miarmy Contents group")

        agentGrp = cmds.ls("Agent_" + activeAgentName)
        if agentGrp == [] or agentGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please create it with Miarmy->Agent Manager")
            raise Exception("No found you Agent group")
        else:
            if cmds.nodeType(agentGrp[0]) != "McdAgentGroup":
                cmds.confirmDialog(t = "Error", m = "Invaild \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please delete it and create it with Miarmy->Agent Manager")
                raise Exception("No found you Agent group")

        setupGrp = cmds.ls("Setup_" + activeAgentName)
        if setupGrp == [] or setupGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your setup group, please make sure Setup_" + activeAgentName +\
                                                " is exist under \"Miarmy_Contents->Agent_" + activeAgentName + "\"", \
                                                b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "Setup_" + activeAgentName, em = True)
                cmds.parent("Setup_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you setup group")

        oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
        alreadyDone = False;
        if oAgentGrp == [] or oAgentGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your OriginalAgent group, please make sure OriginalAgent_" +\
                                                activeAgentName + " is exist under \"Miarmy_Contents->Agent_" +\
                                                activeAgentName + "\"", b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "OriginalAgent_" + activeAgentName, em = True)
                cmds.parent("OriginalAgent_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you original agent group")
        else:
            allChildren = cmds.listRelatives(oAgentGrp[0], c = True, p = False)
            if allChildren != [] and allChildren != None:
                cmds.confirmDialog(t = "Abort", m = "Please make sure OriginalAgent_" + activeAgentName + \
                                 " group is empty, original agent might be created already.")
                alreadyDone = True
                cmds.select("OriginalAgent_" + activeAgentName)

        if alreadyDone == False:
            cmds.select("Setup_" + activeAgentName, "OriginalAgent_" + activeAgentName)
            mel.eval("McdCreateOAgentCmd;")
            allChildren = cmds.listRelatives("OriginalAgent_" + activeAgentName)
            if allChildren != [] and allChildren != None:
                MakeBoundingBoxForOriginalAgent()

    # add some attribute and link:
    McdAddAttrBoneShapeLinkToBone()


    if usePreset == 1:
        McdTryToSetupDynJoint(activeAgentName)


def McdSelectSkinBoneTemp():
    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid != True:
        return;

    print "root_ogb_" + activeAgentName

    cmds.select("root_ogb_" + activeAgentName)

    # Result: [u'root_ogb_loco', u'torso1_ogb_loco', u'torso2_ogb_loco', u'torso3_ogb_loco', u'neck1_ogb_loco', u'head_ogb_loco', u'shoulderL_ogb_loco', u'upArmL_ogb_loco', u'lowArmL_ogb_loco', u'handL_ogb_loco', u'shoulderR_ogb_loco', u'upArmR_ogb_loco', u'lowArmR_ogb_loco', u'handR_ogb_loco', u'upLegL_ogb_loco', u'lowLegL_ogb_loco', u'footL_ogb_loco', u'toeL_ogb_loco', u'upLegR_ogb_loco', u'lowLegR_ogb_loco', u'footR_ogb_loco', u'toeR_ogb_loco'] #


def McdParseRootBoneReCreateOAgent():
    # parse origianl agent group
    # and the root bone:(select the root bone)

    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        miarmyGrp = cmds.ls("Miarmy_Contents")
        if miarmyGrp == [] or miarmyGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Miarmy_Contents\" group, please create it with Miarmy->Agent Manager")
            raise Exception("No found you Miarmy Contents group")

        agentGrp = cmds.ls("Agent_" + activeAgentName)
        if agentGrp == [] or agentGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please create it with Miarmy->Agent Manager")
            raise Exception("No found you Agent group")
        else:
            if cmds.nodeType(agentGrp[0]) != "McdAgentGroup":
                cmds.confirmDialog(t = "Error", m = "Invaild \"Agent_" + activeAgentName + \
                "\" group, it should under \"Miarmy_Contents\", please delete it and create it with Miarmy->Agent Manager")
                raise Exception("No found you Agent group")

        setupGrp = cmds.ls("Setup_" + activeAgentName)
        if setupGrp == [] or setupGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your setup group, please make sure Setup_" + activeAgentName +\
                                                " is exist under \"Miarmy_Contents->Agent_" + activeAgentName + "\"", \
                                                b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "Setup_" + activeAgentName, em = True)
                cmds.parent("Setup_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you setup group")

        oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
        alreadyDone = False;
        if oAgentGrp == [] or oAgentGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your OriginalAgent group, please make sure OriginalAgent_" +\
                                                activeAgentName + " is exist under \"Miarmy_Contents->Agent_" +\
                                                activeAgentName + "\"", b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "OriginalAgent_" + activeAgentName, em = True)
                cmds.parent("OriginalAgent_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you original agent group")
        else:
            allChildren = cmds.listRelatives(oAgentGrp[0], c = True, p = False)
            if allChildren != [] and allChildren != None:
                stat = cmds.confirmDialog(t = "Warning", m="Original Agent of "+activeAgentName+" to be deleted, are you Sure?", \
                                        b = ["Proceed", "Cancel"])
                if stat == "Proceed":
                    for i in range(len(allChildren)):
                        try:
                            cmds.delete(allChildren[i])
                        except:
                            cmds.confirmDialog(t = "Error", m = allChildren[i] + "cannot be deleted.")
                else:
                    alreadyDone = True;

        if alreadyDone == False:
            cmds.select("Setup_" + activeAgentName, "OriginalAgent_" + activeAgentName)
            mel.eval("McdCreateOAgentCmd;")
            oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
            allChildren = cmds.listRelatives(oAgentGrp[0])
            if allChildren != [] and allChildren != None:
                MakeBoundingBoxForOriginalAgent()


def McdParseRootBoneDeleteOAgent():
    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        stat = cmds.confirmDialog(t = "Warning", m="Original Agent of "+activeAgentName+" to be deleted, are you Sure?", \
                                b = ["Proceed", "Cancel"])
        if stat == "Proceed":
            try:
                oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
                allChildren = cmds.listRelatives(oAgentGrp[0], p = False, c = True);
                for i in range(len(allChildren)):
                    cmds.delete(allChildren[i])
            except:
                pass


def MakeBoundingBoxForOriginalAgent():
    allMcdGlobal = cmds.ls(type = "McdGlobal");
    if allMcdGlobal == [] or allMcdGlobal == None:
        cmds.confirmDialog(t = "Error", m = "No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")
        raise Exception("No found Miarmy Global, please create it in \"Miarmy > Miarmy Global\"")

    globalNode = allMcdGlobal[0]
    activeAgentName = cmds.getAttr(globalNode + ".activeAgentName")
    isValid = CheckStringIsValid(activeAgentName)
    if isValid == True:
        miarmyGrp = cmds.ls("Miarmy_Contents")
        if miarmyGrp == [] or miarmyGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Miarmy_Contents\" group, please create it with Miarmy->Agent Manager")
            raise Exception("No found you Miarmy Contents group")

        agentGrp = cmds.ls("Agent_" + activeAgentName)
        if agentGrp == [] or agentGrp == None:
            cmds.confirmDialog(t = "Error", m = "No found \"Agent_" + activeAgentName + "\" group, it should under \"Miarmy_Contents\", please create it with Miarmy->Agent Manager")
            raise Exception("No found you Agent group")
        else:
            if cmds.nodeType(agentGrp[0]) != "McdAgentGroup":
                cmds.confirmDialog(t = "Error", m = "Invaild \"Agent_" + activeAgentName + \
                "\" group, it should under \"Miarmy_Contents\", please delete it and create it with Miarmy->Agent Manager")
                raise Exception("No found you Agent group")

        setupGrp = cmds.ls("Setup_" + activeAgentName)
        if setupGrp == [] or setupGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your setup group, please make sure Setup_" + activeAgentName +\
                                                " is exist under \"Miarmy_Contents->Agent_" + activeAgentName + "\"", \
                                                b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "Setup_" + activeAgentName, em = True)
                cmds.parent("Setup_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you setup group")

        oAgentGrp = cmds.ls("OriginalAgent_" + activeAgentName)
        alreadyDone = False;
        if oAgentGrp == [] or oAgentGrp == None:
            stat = cmds.confirmDialog(t = "Error", m = "No found your OriginalAgent group, please make sure OriginalAgent_" +\
                                                activeAgentName + " is exist under \"Miarmy_Contents->Agent_" +\
                                                activeAgentName + "\"", b = ["Create for me", "Cancel"])
            if stat == "Create for me":
                cmds.group(n = "OriginalAgent_" + activeAgentName, em = True)
                cmds.parent("OriginalAgent_" + activeAgentName, "Agent_" + activeAgentName)
            else:
                raise Exception("No found you original agent group")

        if alreadyDone == False:
            bbName = "BoundingBox_" + activeAgentName;
            bbShape = "BoundingBoxShape_" + activeAgentName;
            bbObj = cmds.ls(bbName)
            if bbObj == [] or bbObj == None:
                cmds.group(n = bbName, em = True)
                cmds.createNode("McdBoundBox", n = bbShape, p = bbName)
                cmds.color(bbName, ud = 4)
                cmds.parent(bbName, "OriginalAgent_" + activeAgentName)
                cmds.setAttr(bbName+".tx", 0)
                cmds.setAttr(bbName+".ty", 0)
                cmds.setAttr(bbName+".tz", 0)
                cmds.setAttr(bbName+".rx", e = True, k = False, l = True)
                cmds.setAttr(bbName+".ry", e = True, k = False, l = True)
                cmds.setAttr(bbName+".rz", e = True, k = False, l = True)
            else:
                try:
                    cmds.parent(bbName, "OriginalAgent_" + activeAgentName)
                except:
                    cmds.confirmDialog(t = "Abort", m = "Bounding box exist for active agent.")



def McdTryToSetupDynJoint(activeAgentName):

    try:
        # joint
        # bone shape
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".ty", 1.536)
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".sx", 4.736)
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".sy", 5.641)
        cmds.setAttr("root_dummyShape_" + activeAgentName + ".sz", 2.516)
    except:
        pass

    try:
        # joint:
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".ry", 180)
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("upLegL_phyJoint_" + activeAgentName + ".swingDw", 60)
        
        # bone shape
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".tx", -3.325)
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".sx", 6.65)
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".sy", 1.857)
        cmds.setAttr("upLegL_dummyShape_" + activeAgentName + ".sz", 2.403)
    except:
        pass

    try:
        # joint:
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".swingUp", 15)
        cmds.setAttr("lowLegL_phyJoint_" + activeAgentName + ".swingDw", 120)

        # bone shape:
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".tx", -4.386)
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".sx", 8.773)
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".sy", 1.615)
        cmds.setAttr("lowLegL_dummyShape_" + activeAgentName + ".sz", 1.92)
    except:
        pass

    try:
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".swingUp", 45)
        cmds.setAttr("footL_phyJoint_" + activeAgentName + ".swingDw", 45)

        cmds.setAttr("footL_dummyShape_" + activeAgentName + ".tx", -1.122)
        cmds.setAttr("footL_dummyShape_" + activeAgentName + ".sx", 2.244)
        cmds.setAttr("footL_dummyShape_" + activeAgentName + ".sz", 1.647)
        
    except:
        pass

    try:
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".swingUp", 20)
        cmds.setAttr("toeL_phyJoint_" + activeAgentName + ".swingDw", 20)

        cmds.setAttr("toeL_dummyShape_" + activeAgentName + ".tx", -0.695)
        cmds.setAttr("toeL_dummyShape_" + activeAgentName + ".sx", 1.39)
        cmds.setAttr("toeL_dummyShape_" + activeAgentName + ".sz", 1.419)
    except:
        pass

    try:
        # joint:
        cmds.setAttr("upLegR_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("upLegR_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("upLegR_phyJoint_" + activeAgentName + ".swingDw", 60)
        
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".tx", 3.325)
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".sx", 6.65)
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".sy", 1.857)
        cmds.setAttr("upLegR_dummyShape_" + activeAgentName + ".sz", 2.403)
    except:
        pass

    try:
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".swingUp", 15)
        cmds.setAttr("lowLegR_phyJoint_" + activeAgentName + ".swingDw", 120)

        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".tx", 4.386)
        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".sx", 8.773)
        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".sy", 1.615)
        cmds.setAttr("lowLegR_dummyShape_" + activeAgentName + ".sz", 1.92)
    except:
        pass

    try:
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".swingUp", 45)
        cmds.setAttr("footR_phyJoint_" + activeAgentName + ".swingDw", 45)

        cmds.setAttr("footR_dummyShape_" + activeAgentName + ".tx", 1.122)
        cmds.setAttr("footR_dummyShape_" + activeAgentName + ".sx", 2.244)
        cmds.setAttr("footR_dummyShape_" + activeAgentName + ".sz", 1.647)
    except:
        pass

    try:
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".swingUp", 20)
        cmds.setAttr("toeR_phyJoint_" + activeAgentName + ".swingDw", 25)

        cmds.setAttr("toeR_dummyShape_" + activeAgentName + ".tx", 0.695)
        cmds.setAttr("toeR_dummyShape_" + activeAgentName + ".sx", 1.39)
        cmds.setAttr("toeR_dummyShape_" + activeAgentName + ".sz", 1.419)
    except:
        pass

    # upper body:
    try:
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("torso1_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".ty", 0.615)
        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".sx", 5.05)
        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".sy", 2.84)
        cmds.setAttr("torso1_dummyShape_" + activeAgentName + ".sz", 2.782)
    except:
        pass

    try:
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("torso2_phyJoint_" + activeAgentName + ".twistDw", -30)
        

        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".ty", 0.742)
        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".sx", 5.99)
        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".sy", 2.558)
        cmds.setAttr("torso2_dummyShape_" + activeAgentName + ".sz", 3.069)
    except:
        pass

    try:
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("torse3_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".ty", 1.419)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".tz", -0.491)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".sx", 5.013)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".sy", 2.619)
        cmds.setAttr("torse3_dummyShape_" + activeAgentName + ".sz", 3.452)
    except:
        pass

    try:
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("neck1_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".ty", 0.541)
        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".sx", 2.152)
        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".sy", 1.417)
        cmds.setAttr("neck1_dummyShape_" + activeAgentName + ".sz", 1.477)
        
    except:
        pass

    try:
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".swingUp", 30)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".swingDw", 30)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".twistUp", 30)
        cmds.setAttr("head_phyJoint_" + activeAgentName + ".twistDw", -30)

        cmds.setAttr("head_dummyShape_" + activeAgentName + ".ty", 1.802)
        cmds.setAttr("head_dummyShape_" + activeAgentName + ".sx", 3.036)
        cmds.setAttr("head_dummyShape_" + activeAgentName + ".sy", 3.207)
        cmds.setAttr("head_dummyShape_" + activeAgentName + ".sz", 2.663)
    except:
        pass

    try:
        cmds.setAttr("shoulderL_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("shoulderL_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("shoulderL_phyJoint_" + activeAgentName + ".swingDw", 60)

        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".tx", 1.393)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".ty", 0.774)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".sx", 2.786)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".sy", 2.018)
        cmds.setAttr("shoulderL_dummyShape_" + activeAgentName + ".sz", 2.42)
    except:
        pass

    try:
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".jointType", 1)
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".ry", 180)
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".swingUp", 60)
        cmds.setAttr("shoulderR_phyJoint_" + activeAgentName + ".swingDw", 60)

        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".tx", -1.393)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".ty", -0.774)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".sx", 2.786)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".sy", 2.018)
        cmds.setAttr("shoulderR_dummyShape_" + activeAgentName + ".sz", 2.42)
    except:
        pass

    try:
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".swingUp", 80)
        cmds.setAttr("upArmL_phyJoint_" + activeAgentName + ".swingDw", 10)

        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".tx", 2.237)
        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".sx", 4.474)
        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".sy", 1.911)
        cmds.setAttr("upArmL_dummyShape_" + activeAgentName + ".sz", 2.096)
    except:
        pass

    try:
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".swingUp", 80)
        cmds.setAttr("upArmR_phyJoint_" + activeAgentName + ".swingDw", 10)

        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".tx", -2.209)
        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".sx", 4.474)
        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".sy", 1.911)
        cmds.setAttr("upArmR_dummyShape_" + activeAgentName + ".sz", 2.096)
    except:
        pass

    try:
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".rz", -90)
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".swingUp", 130)
        cmds.setAttr("lowArmL_phyJoint_" + activeAgentName + ".swingDw", 10)

        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".tx", 2.638)
        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".sx", 5.275)
        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".sy", 1.49)
        cmds.setAttr("lowArmL_dummyShape_" + activeAgentName + ".sz", 1.869)
    except:
        pass

    try:
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".rz", 90)
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".swingUp", 10)
        cmds.setAttr("lowArmR_phyJoint_" + activeAgentName + ".swingDw", 130)

        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".tx", -2.638)
        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".sx", 5.275)
        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".sy", 1.49)
        cmds.setAttr("lowArmR_dummyShape_" + activeAgentName + ".sz", 1.869)
    except:
        pass

    try:
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".rx", 90)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".swingUp", 75)
        cmds.setAttr("handL_phyJoint_" + activeAgentName + ".swingDw", 75)

        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".tx", 0.638)
        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".sx", 1.621)
        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".sy", 0.977)
        cmds.setAttr("handL_dummyShape_" + activeAgentName + ".sz", 1.815)
    except:
        pass

    try:
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".jointType", 2)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".rx", -90)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".ry", 90)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".swingUp", 75)
        cmds.setAttr("handR_phyJoint_" + activeAgentName + ".swingDw", 75)

        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".tx", -0.638)
        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".sx", 1.621)
        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".sy", 0.977)
        cmds.setAttr("handR_dummyShape_" + activeAgentName + ".sz", 1.815)
    except:
        pass

    try:
        cmds.setAttr("BoundingBox_" + activeAgentName + ".ty", 18.263)
        cmds.setAttr("BoundingBox_" + activeAgentName + ".sx", 33.651)
        cmds.setAttr("BoundingBox_" + activeAgentName + ".sy", 36.692)
        cmds.setAttr("BoundingBox_" + activeAgentName + ".sz", 32.75)
    except:
        pass



def McdSelectSkinBone():
    globalNode = McdListMcdGlobal()
    actName = cmds.getAttr(globalNode + ".activeAgentName")

    allOrgBones = cmds.ls("*_" + actName, type = "joint", l = True)
    if allOrgBones == [] or allOrgBones == None:
        cmds.confirmDialog(t = "Error", m = "No joints found for current original agent.")
        return
    geoGroup = cmds.ls("Geometry_" + actName, l = True)
    if geoGroup == [] or geoGroup == None:
        cmds.confirmDialog(t = "Error", m = "No Geometry group found for current original agent.")
        return

    skinBone = []
    for i in range(len(allOrgBones)):
        allChild = cmds.listRelatives(allOrgBones[i], c = True, p = False, pa = True)
        if allChild == [] or allChild == None:
            continue
        for j in range(len(allChild)):
            if cmds.nodeType(allChild[j]) == "joint":
                skinBone.append(allOrgBones[i])
                continue

    skinGeo = []
    cmds.select(geoGroup[0], hi = True)
    allGeo = cmds.ls(sl = True, l = True)
    for i in range(len(allGeo)):
        if cmds.nodeType(allGeo[i]) == "mesh":
            skinGeo.append(allGeo[i])


    if skinBone == [] or skinGeo == []:
        cmds.confirmDialog(t = "Error", m = "No geometries or joints found for current original agent.")
        return

    # select session:
    cmds.select(clear = True)
    for i in range(len(skinBone)):
        try:
            cmds.select(skinBone[i], add = True)
        except:
            pass

    for i in range(len(skinGeo)):
        try:
            cmds.select(skinGeo[i], add = True)
        except:
            pass

    cmds.confirmDialog(t = "Done", m = "We selected the following things for you:\n * Joints without \"End Joint\"\n * Geometries in group"+ \
                     "\n\nYou can now skin geometry directly by Maya skin tools")


def CopyGeoFromSetupAndSkinToOA1():
    # parse selection:
    selObjs = cmds.ls(sl = True, long = True)
    if selObjs == [] or selObjs == None:
        cmds.confirmDialog(t = "Error", m = "Please select activated character geometry(ies) firstly")
        return;

    activeAgentName = McdGetActiveAgentName()

    errorReport = []
    # ---------------------------
    # 1: no skin
    # 2: not found match bone or not active
    # 3: cannot copy
    # 4: cannot parent
    # ---------------------------

    # for each geo:
    for i in range(len(selObjs)):
        selTrans = selObjs[i]
        if cmds.nodeType(selTrans) == "mesh":
            selGeo = selObjs
        else:
            selGeo = cmds.listRelatives(selTrans, c = True, f = True)
        if selGeo == [] or selGeo == None:
            continue

        if cmds.nodeType(selGeo[0]) != "mesh":
            continue

        points = cmds.ls(selGeo[0] + ".vtx[*]")
        if points == [] or points == None:
            continue

        temp = points[0].split(":")[-1]
        temp = temp.split("]")[0]
        maxPoints = int(temp) + 1


        #---------------------------
        # find skinCluster history
        # find skin bones
        # match bones in OA
        # copy mesh
        # skin
        # copy weight
        # put it to Geometry_<Agt>
        # feedback errors
        #---------------------------

        # find skinCluster history
        sourceSkin = ""
        sourceHistory = cmds.listHistory(selGeo)
        for i in range(len(sourceHistory)):
            if cmds.nodeType(sourceHistory[i]) == "skinCluster":
                sourceSkin = sourceHistory[i]
                break
        if sourceSkin == "":
            if 1 not in errorReport:
                errorReport.append(1)
            continue

        # find skin bones
        influenceList = cmds.listConnections(sourceSkin + ".lockWeights")
        if influenceList == [] or influenceList == None:
            continue

        # match bones in OA
        targetInfluenceList = []
        isActiveBone = False
        cannotMatchCorrectly = False
        for j in range(len(influenceList)):
            if McdCheckNodeActiveCmd(influenceList[j]):
                # find counterpart and append:
                try:
                    counterpartBone = findCounterpartBone(influenceList[j])
                except:
                    counterpartBone = ""
                if counterpartBone == "":
                    cannotMatchCorrectly = True
                    break
                targetInfluenceList.append(counterpartBone)
            else:
                cannotMatchCorrectly = True
                break

        if cannotMatchCorrectly:
            if 2 not in errorReport:
                errorReport.append(2)
            continue

        #if not isActiveBone:
        #    continue

        # copy mesh
        newMeshList = cmds.duplicate(selGeo, rr = True, po = True)
        if newMeshList == None or newMeshList == []:
            if 3 not in errorReport:
                errorReport.append(3)
            continue
        newMesh = newMeshList[0]
        selMesh = selGeo[0]

        # skin newMesh by targetInfluenceList
        # resource by new:

        cmds.select(newMesh)
        cmds.select(targetInfluenceList, add = True)

        targetSkin = cmds.skinCluster(toSelectedBones = True)[0]

        # copy weight
        for i in range(maxPoints):
            sourcePoint = selMesh + ".vtx["+ str(i) +"]"
            targetPoint = newMesh + ".vtx["+ str(i) +"]"
            info = cmds.skinPercent(sourceSkin, sourcePoint, q = True, v = True)
            for j in range(len(influenceList)):
                cmds.skinPercent(targetSkin, targetPoint, tv = [(targetInfluenceList[j], info[j])])

        # put it to Geometry_<Agt>
        try:
            cmds.parent(newMesh, "Geometry_" + activeAgentName)
        except:
            if 4 not in errorReport:
                errorReport.append(4)

    # ---------------------------
    # Feedback Errors
    # 1: no skin
    # 2: not found match bone or not active
    # 3: cannot copy
    # 4: cannot parent
    # ---------------------------

    errorMessage = ""

    if errorReport != []:
        errorMessage += "Not all of your selected geometry correctly copied:\n"

        if 1 in errorReport:
            errorMessage += "* did not find skinCluster node for selected Geo\n"
        if 2 in errorReport:
            errorMessage += "* did not find matched bone for your rig, \nplease active your agent or check the naming of original agent\n"
        if 3 in errorReport:
            errorMessage += "* cannot perform duplicate maya command for your selected\n"
        if 4 in errorReport:
            errorMessage += "* cannot parent new geometry to the Geometry_<AgtName>\n"

    if errorMessage != "":
        cmds.confirmDialog(t = "Error", m = errorMessage)


def findCounterpartBone(rigBone):
    activeAgentName = McdGetActiveAgentName()

    oaBone = ""
    # find real name:
    temp1 = rigBone.split("|")[-1]
    temp2 = temp1.split(":")[-1]
    rigBoneNodeName = temp2

    oaBoneNodeName = rigBoneNodeName + "_ogb_" + activeAgentName

    foundBoneSet = cmds.ls('*' + oaBoneNodeName)
    if foundBoneSet == [] or foundBoneSet == None:
        return "" # blank

    if len(foundBoneSet) == 1:
        oaBone = foundBoneSet[0]
        return oaBone

    # not only one, test activate!






    # not only one, test root bone!
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    if cmds.nodeType(rigBoneParent) != "joint":
        for i in range(len(foundBoneSet)):
            temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
            if cmds.nodeType(temp) != "joint":
                oaBone = foundBoneSet[i];
                return oaBone

    # not only one, compare parent!!
    equalIndexSet = []
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParentNodeName = rigBoneParent.split('|')[-1]
    rigBoneParentNodeName = rigBoneParentNodeName.split(':')[-1]
    for i in range(len(foundBoneSet)):
        temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
        temp = temp.split('|')[-1]
        temp = temp.split(':')[-1]
        thisFoundBoneNode = temp.split("_ogb_")[0]

        if thisFoundBoneNode == rigBoneParentNodeName:
            equalIndexSet.append(i)


    if len(equalIndexSet) == 0:
        return ""
    elif len(equalIndexSet) == 1:
        oaBone = foundBoneSet[equalIndexSet[0]]
        return oaBone


    ############################################################################
    # not only one, test root bone!
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    if cmds.nodeType(rigBoneParent) != "joint":
        for i in range(len(foundBoneSet)):
            temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
            temp = cmds.listRelatives(temp, p = True, f = True)[0]
            if cmds.nodeType(temp) != "joint":
                oaBone = foundBoneSet[i];
                return oaBone

    # if not found, compare parent of parent!!
    equalIndexSet = []
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParentNodeName = rigBoneParent.split('|')[-1]
    rigBoneParentNodeName = rigBoneParentNodeName.split(':')[-1]
    for i in range(len(foundBoneSet)):
        temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
        temp = cmds.listRelatives(temp, p = True, f = True)[0]
        temp = temp.split('|')[-1]
        temp = temp.split(':')[-1]
        thisFoundBoneNode = temp.split("_ogb_")[0]

        if thisFoundBoneNode == rigBoneParentNodeName:
            equalIndexSet.append(i)

    if len(equalIndexSet) == 0:
        return ""
    elif len(equalIndexSet) == 1:
        oaBone = foundBoneSet[equalIndexSet[0]]
        return oaBone


    ############################################################################
    # not only one, test root bone!
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    if cmds.nodeType(rigBoneParent) != "joint":
        for i in range(len(foundBoneSet)):
            temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
            temp = cmds.listRelatives(temp, p = True, f = True)[0]
            temp = cmds.listRelatives(temp, p = True, f = True)[0]
            if cmds.nodeType(temp) != "joint":
                oaBone = foundBoneSet[i];
                return oaBone

    # if not found, compare parent of parent!!
    equalIndexSet = []
    rigBoneParent = cmds.listRelatives(rigBone, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParent = cmds.listRelatives(rigBoneParent, p = True, f = True)[0]
    rigBoneParentNodeName = rigBoneParent.split('|')[-1]
    rigBoneParentNodeName = rigBoneParentNodeName.split(':')[-1]
    for i in range(len(foundBoneSet)):
        temp = cmds.listRelatives(foundBoneSet[i], p = True, f = True)[0]
        temp = cmds.listRelatives(temp, p = True, f = True)[0]
        temp = cmds.listRelatives(temp, p = True, f = True)[0]
        temp = temp.split('|')[-1]
        temp = temp.split(':')[-1]
        thisFoundBoneNode = temp.split("_ogb_")[0]

        if thisFoundBoneNode == rigBoneParentNodeName:
            equalIndexSet.append(i)

    if len(equalIndexSet) == 0:
        return ""
    elif len(equalIndexSet) == 1:
        oaBone = foundBoneSet[equalIndexSet[0]]
        return oaBone


    return ""


def CopyGeoFromSetupAndSkinToOA():

    selObjs = cmds.ls(sl = 1)
    if selObjs == [] or selObjs == None:
        cmds.confirmDialog(t = "Error", m = "Please select activated character geometry(ies) firstly")

    #getAgentName
    activeAgentName = McdGetActiveAgentName()
    for selGeo in selObjs:
        # get Jnt that use for skinCluster for each Obj
        links = cmds.listHistory(selGeo, pdo=0, il=1)
        skin = cmds.ls(links, typ="skinCluster")
        if MIsBlank(skin):
            cmds.confirmDialog(t = "Error", m = "Only support smooth skin cluster, skip: \n" + selGeo)
            continue
        
        jnts = cmds.skinCluster(skin[0], q=1, inf=1)
        if MIsBlank(jnts):
            cmds.confirmDialog(t = "Error", m = "Skin Cluster no inf joint found, skip: \n" + selGeo)
            continue
        
        for i in range(len(jnts)):
            if jnts[i].find("|") >= 0:
                cmds.confirmDialog(t = "Error", m = "Repeated name detected in your initial rig.\n" + jnts[i])
                return
        
        newJnt= []
        # add suffix for eachJnt 'ogb_'+activeAgentName)
        for jnt in jnts:
            jntRaw = jnt.split(":")[-1]
            newJnt.append(jntRaw + '_ogb_' + activeAgentName)
            
        
            
        # dulplicate Mesh
        newMesh = cmds.duplicate(selGeo,n= selGeo+'_'+activeAgentName+'Geo')[0]
        try:
            cmds.setAttr(newMesh + ".tx", l = False)
            cmds.setAttr(newMesh + ".ty", l = False)
            cmds.setAttr(newMesh + ".tz", l = False)
            cmds.setAttr(newMesh + ".rx", l = False)
            cmds.setAttr(newMesh + ".ry", l = False)
            cmds.setAttr(newMesh + ".rz", l = False)
            cmds.setAttr(newMesh + ".sx", l = False)
            cmds.setAttr(newMesh + ".sy", l = False)
            cmds.setAttr(newMesh + ".sz", l = False)
            cmds.makeIdentity(newMesh, apply = True, t = True, r = True, s = True, n = False, pn = True)
        except:
            pass
        #delete OrigShape
        nodes = cmds.ls(newMesh,dag=1)
        for obj in nodes:
            if obj[-4:]=='Orig':
                cmds.delete(obj)
        cmds.skinCluster(newJnt, newMesh, ibp=1, ih=1, dr=4, tsb=1, mi=1, nw=1)
        # select originalMesh and duplicateMesh then do copySkin
        cmds.select(selGeo, newMesh)
        cmds.copySkinWeights(surfaceAssociation='closestPoint', influenceAssociation=['oneToOne','closestJoint', 'label'], noMirror=1)
        # parent to
        if cmds.objExists("Geometry_" + activeAgentName) :
            cmds.parent(newMesh, "Geometry_" + activeAgentName)
            
def McdAddAttrBoneShapeLinkToBone( addFull = False ):

    activeAgentName = McdGetActiveAgentName()
    
    # link custom data number!!
    orgSel = cmds.ls(sl = True)
    McdStatAndLinkCustomDataNum(activeAgentName)
    try:
        cmds.select(orgSel)
    except:
        pass

    orgSelObj = cmds.ls(sl = True, l = True)

    # find the root bone
    try:
        oaGrp = cmds.ls("OriginalAgent_" + activeAgentName)[0]
    except:
        return

    # walk bone tree
    allChildren = cmds.listRelatives(oaGrp, c = True, p =False, fullPath =True)
    if allChildren == [] or allChildren == None:
        return

    #select whole tree:
    rootJoint = ""
    for i in range(len(allChildren)):
        if cmds.nodeType(allChildren[i]) == "joint":
            rootJoint = allChildren[i]

    if rootJoint == "":
        return

    # create and link!
    cmds.select(rootJoint)
    allJoints = mel.eval("McdSimpleCommand -exe 31")

    for i in range(len(allJoints)):
        allChild = cmds.listRelatives(allJoints[i], c = True, p = False, fullPath = True)
        if allChild == [] or allChild == None:
            continue;
        for j in range(len(allChild)):
            if allChild[j].find("_dummyShape_") >0:
                McdAddAttrAndLink(allChild[j], allJoints[i], addFull)

    try:
        if orgSelObj == [] or orgSelObj == None:
            cmds.select(clear = True)
        else:
            cmds.select(orgSelObj)
    except:
        pass

def AddAimRotationLimitAttr():
    selObj = cmds.ls(sl = True)
    if MIsBlank(selObj):
        cmds.confirmDialog(t = "Error", m  = "Please select at least one dummy shape.", b = ["", ""])
        
    addThese = []
    for i in range(len(selObj)):
        if selObj[i].find("_dummyShape_") > 0:
            try:
                inNode = selObj[i]
                cmds.addAttr(inNode, ln = "horizontalL", at = "bool")
                cmds.setAttr(inNode + ".horizontalL", k = False, cb = True)
                cmds.addAttr(inNode, ln = "hlValue", at = "long", min = -180, max = 0, dv = -45)
                cmds.setAttr(inNode + ".hlValue", k = False, cb = True)
                
                cmds.addAttr(inNode, ln = "horizontalR", at = "bool")
                cmds.setAttr(inNode + ".horizontalR", k = False, cb = True)
                cmds.addAttr(inNode, ln = "hrValue", at = "long", min = 0, max = 180, dv = 45)
                cmds.setAttr(inNode + ".hrValue", k = False, cb = True)
                
                cmds.addAttr(inNode, ln = "verticalU", at = "bool")
                cmds.setAttr(inNode + ".verticalU", k = False, cb = True)
                cmds.addAttr(inNode, ln = "vuValue", at = "long", min = -180, max = 0, dv = -45)
                cmds.setAttr(inNode + ".vuValue", k = False, cb = True)
                
                cmds.addAttr(inNode, ln = "verticalD", at = "bool")
                cmds.setAttr(inNode + ".verticalD", k = False, cb = True)
                cmds.addAttr(inNode, ln = "vdValue", at = "long", min = 0, max = 180, dv = 45)
                cmds.setAttr(inNode + ".vdValue", k = False, cb = True)
                
                attachJoint = cmds.listRelatives(inNode, c = False, p = True)[0] #-------------------------
                
                cmds.addAttr(attachJoint, ln = "horizontalL", at = "bool")
                cmds.addAttr(attachJoint, ln = "hlValue", at = "long")
                
                cmds.addAttr(attachJoint, ln = "horizontalR", at = "bool")
                cmds.addAttr(attachJoint, ln = "hrValue", at = "long")
                
                cmds.addAttr(attachJoint, ln = "verticalU", at = "bool")
                cmds.addAttr(attachJoint, ln = "vuValue", at = "long")
                
                cmds.addAttr(attachJoint, ln = "verticalD", at = "bool")
                cmds.addAttr(attachJoint, ln = "vdValue", at = "long")
                
                # -------------------------------
                cmds.connectAttr(inNode + ".horizontalL", attachJoint + ".horizontalL")
                cmds.connectAttr(inNode + ".horizontalR", attachJoint + ".horizontalR")
                cmds.connectAttr(inNode + ".verticalU", attachJoint + ".verticalU")
                cmds.connectAttr(inNode + ".verticalD", attachJoint + ".verticalD")
                cmds.connectAttr(inNode + ".hlValue", attachJoint + ".hlValue")
                cmds.connectAttr(inNode + ".hrValue", attachJoint + ".hrValue")
                cmds.connectAttr(inNode + ".vuValue", attachJoint + ".vuValue")
                cmds.connectAttr(inNode + ".vdValue", attachJoint + ".vdValue")
                
                addThese.append(selObj[i])
                
            except:
                pass
            
            
            
            
def McdAddAttrAndLink(inNode, linkToBone, addFull = False):

    globalNode = McdGetMcdGlobalNode()
    if cmds.getAttr(globalNode + ".hookCustomData") == 1:
        ### customDataNum ###########################################################################
        try:
            cmds.addAttr(inNode, ln = "customDataNum", at = "long")
            cmds.setAttr(inNode + ".customDataNum", k = False, cb = True)
        except:
            pass
        
        try:
            cmds.connectAttr(linkToBone + ".customDataNum", inNode + ".customDataNum", f = True)
        except:
            pass

    if addFull:
        
        ### collideCloth ###########################################################################
        try:
            cmds.addAttr(inNode, ln = "collideCloth", at = "bool")
            cmds.setAttr(inNode + ".collideCloth", k = False, cb = True)
        except:
            pass

        try:
            cmds.addAttr(linkToBone, ln = "collideCloth", at = "bool")
            cmds.setAttr(linkToBone + ".collideCloth", k = False, cb = False)
        except:
            pass
        try:
            cmds.connectAttr(inNode + ".collideCloth", linkToBone + ".collideCloth", f = True)
        except:
            pass

        ### collideFeel ###########################################################################
        try:
            cmds.addAttr(inNode, ln = "collideFeel", at = "bool")
            cmds.setAttr(inNode + ".collideFeel", k = False, cb = True)
        except:
            pass

        try:
            cmds.addAttr(linkToBone, ln = "collideFeel", at = "bool")
            cmds.setAttr(linkToBone + ".collideFeel", k = False, cb = False)
        except:
            pass
        try:
            cmds.connectAttr(inNode + ".collideFeel", linkToBone + ".collideFeel", f = True)
        except:
            pass

        #### fieldFeel #############################################################################
        try:
            cmds.addAttr(inNode, ln = "fieldFeel", at = "bool")
            cmds.setAttr(inNode + ".fieldFeel", k = False, cb = True)
        except:
            pass

        try:
            cmds.addAttr(linkToBone, ln = "fieldFeel", at = "bool")
            cmds.setAttr(linkToBone + ".fieldFeel", k = False, cb = False)
        except:
            pass
        try:
            cmds.connectAttr(inNode + ".fieldFeel", linkToBone + ".fieldFeel", f = True)
        except:
            pass

    ### density ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "density", at = "float")
        cmds.setAttr(inNode + ".density", k = False, cb = True)
        cmds.setAttr(inNode + ".density", 1)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "density", at = "float")
        cmds.setAttr(linkToBone + ".density", k = False, cb = False)
        cmds.setAttr(linkToBone + ".density", 1)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".density", linkToBone + ".density", f = True)
    except:
        pass

    ### genFootMap ############################################################################
    try:
        cmds.addAttr(inNode, ln = "genFootMap", at = "bool")
        cmds.setAttr(inNode + ".genFootMap", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "genFootMap", at = "bool")
        cmds.setAttr(linkToBone + ".genFootMap", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".genFootMap", linkToBone + ".genFootMap", f = True)
    except:
        pass

    ### disableDynSubTree ########################################################################
    try:
        cmds.addAttr(inNode, ln = "disableDynSubTree", at = "bool")
        cmds.setAttr(inNode + ".disableDynSubTree", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "disableDynSubTree", at = "bool")
        cmds.setAttr(linkToBone + ".disableDynSubTree", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".disableDynSubTree", linkToBone + ".disableDynSubTree", f = True)
    except:
        pass
    
    ### compoundRBD ########################################################################
    try:
        cmds.addAttr(inNode, ln = "compoundRBD", at = "bool")
        cmds.setAttr(inNode + ".compoundRBD", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "compoundRBD", at = "bool")
        cmds.setAttr(linkToBone + ".compoundRBD", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".compoundRBD", linkToBone + ".compoundRBD", f = True)
    except:
        pass
    
    #### block simulation #####################################################################
    try:
        cmds.addAttr(inNode, ln = "skipAnim", at = "bool")
        cmds.setAttr(inNode + ".skipAnim", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "skipAnim", at = "bool")
        cmds.setAttr(linkToBone + ".skipAnim", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".skipAnim", linkToBone + ".skipAnim", f = True)
    except:
        pass
    
    ### auto IK ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "autoIKLv", at = "long")
        cmds.setAttr(inNode + ".autoIKLv", k = False, cb = True)
        cmds.setAttr(inNode + ".autoIKLv")
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "autoIKLv", at = "long")
        cmds.setAttr(linkToBone + ".autoIKLv", k = False, cb = False)
        cmds.setAttr(linkToBone + ".autoIKLv")
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".autoIKLv", linkToBone + ".autoIKLv", f = True)
    except:
        pass

    ### IK axis ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "ikAxis", at = "enum", en = "auto:+X:+Y:+Z:-X:-Y:-Z:")
        cmds.setAttr(inNode + ".ikAxis", k = False, cb = True)
        cmds.setAttr(inNode + ".ikAxis")
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "ikAxis", at = "long")
        cmds.setAttr(linkToBone + ".ikAxis", k = False, cb = False)
        cmds.setAttr(linkToBone + ".ikAxis")
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".ikAxis", linkToBone + ".ikAxis", f = True)
    except:
        pass
    
    ### Up axis ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "autoIkUp", at = "enum", en = "+Z:+Y:")
        cmds.setAttr(inNode + ".autoIkUp", k = False, cb = True)
        cmds.setAttr(inNode + ".autoIkUp")
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "autoIkUp", at = "long")
        cmds.setAttr(linkToBone + ".autoIkUp", k = False, cb = False)
        cmds.setAttr(linkToBone + ".autoIkUp")
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".autoIkUp", linkToBone + ".autoIkUp", f = True)
    except:
        pass
    

    ### Up axis ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "blockTranslate", at = "bool")
        cmds.setAttr(inNode + ".blockTranslate", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "blockTranslate", at = "bool")
        cmds.setAttr(linkToBone + ".blockTranslate", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".blockTranslate", linkToBone + ".blockTranslate", f = True)
    except:
        pass


    ### rbd Target ###########################################################################
    try:
        cmds.addAttr(inNode, ln = "rbdTarget", at = "bool")
        cmds.setAttr(inNode + ".rbdTarget", k = False, cb = True)
    except:
        pass

    try:
        cmds.addAttr(linkToBone, ln = "rbdTarget", at = "bool")
        cmds.setAttr(linkToBone + ".rbdTarget", k = False, cb = False)
    except:
        pass
    try:
        cmds.connectAttr(inNode + ".rbdTarget", linkToBone + ".rbdTarget", f = True)
    except:
        pass


def McdUpgradeOAgent():

    McdAddAttrBoneShapeLinkToBone(True);

def McdStatAndLinkCustomDataNum(activeAgentName):
    
    globalNode = McdGetMcdGlobalNode()
    if cmds.getAttr(globalNode + ".hookCustomData") != 1:
        print "bypass custom data hooking"
        return;
    
    rigGrp = cmds.ls("Setup_" + activeAgentName)
    oaGrp = cmds.ls("OriginalAgent_" + activeAgentName)
    
    if McdIsBlank(rigGrp) or McdIsBlank(oaGrp):
        return
    
    agtGrpRaw = cmds.listRelatives(rigGrp[0], p = True, c = False)
    if MIsBlank(agtGrpRaw):
        return

    agtGrp = agtGrpRaw[0]
    if cmds.nodeType(agtGrp) != "McdAgentGroup":
        return
    
    cmds.select(rigGrp)
    rigRootJnt = mel.eval("McdSimpleCommand -exe 30")
    if McdIsBlank(rigRootJnt):
        return
    
    cmds.select(oaGrp)
    oaRootJnt = mel.eval("McdSimpleCommand -exe 30")
    if McdIsBlank(oaRootJnt):
        return

    try:
        cmds.select(rigRootJnt)
    except:
        pass
    rigAllBones = mel.eval("McdSimpleCommand -exe 31")
    
    try:
        cmds.select(oaRootJnt)
    except:
        pass
    oaAllBones = mel.eval("McdSimpleCommand -exe 31")
    
    if len(rigAllBones) != len(oaAllBones):
        return;
    
    # enable it!
    cmds.setAttr(agtGrp + ".cdHooked", 1)
    cdCount = 0
    
    for i in range(len(rigAllBones)):
        allUDAttr = cmds.listAttr(rigAllBones[i], ud = True)
        try:
            cmds.addAttr(oaAllBones[i], ln = "customDataNum", at = "long")
            if (len(allUDAttr) > 0):
                cmds.setAttr(oaAllBones[i] + ".customDataNum", len(allUDAttr))
        except:
            pass
        
        if MIsBlank(allUDAttr):
            continue
        else:
            for j in range(len(allUDAttr)):
                cmds.setAttr(agtGrp + ".cdNames[" + str(cdCount) + "]", allUDAttr[j], type = "string")
                cdCount += 1
        
    cmds.setAttr(agtGrp + ".cdNum", cdCount)






























