[Maya][Python3] オブジェクトのメソッド一覧を取得する

from pxr import Usd, UsdGeom

obj = Usd
for x in dir(obj):
    print (str(x)+ ':'+ str(type(eval("obj."+x))))

出力結果

APISchemaBase:<class 'Boost.Python.class'>
AssetInfoKeys:<class 'Boost.Python.class'>
Attribute:<class 'Boost.Python.class'>
AttributeQuery:<class 'Boost.Python.class'>
BlockStageCachePopulation:<class 'pxr.Usd.StageCacheContextBlockType'>
BlockStageCaches:<class 'pxr.Usd.StageCacheContextBlockType'>
ClipsAPI:<class 'Boost.Python.class'>
CollectionAPI:<class 'Boost.Python.class'>
CompositionArc:<class 'Boost.Python.class'>
ComputeIncludedObjectsFromCollection:<class 'Boost.Python.function'>
ComputeIncludedPathsFromCollection:<class 'Boost.Python.function'>
CrateInfo:<class 'Boost.Python.class'>
Describe:<class 'Boost.Python.function'>
EditContext:<class 'Boost.Python.class'>
EditTarget:<class 'Boost.Python.class'>
FlattenLayerStack:<class 'Boost.Python.function'>
FlattenLayerStackResolveAssetPath:<class 'Boost.Python.function'>
GetMajorVersion:<class 'Boost.Python.function'>
GetMinorVersion:<class 'Boost.Python.function'>
GetPatchVersion:<class 'Boost.Python.function'>
GetVersion:<class 'Boost.Python.function'>
Inherits:<class 'Boost.Python.class'>
InterpolationType:<class 'Boost.Python.class'>
InterpolationTypeHeld:<class 'pxr.Usd.InterpolationType'>
InterpolationTypeLinear:<class 'pxr.Usd.InterpolationType'>
ListPosition:<class 'Boost.Python.class'>
ListPositionBackOfAppendList:<class 'pxr.Usd.ListPosition'>
ListPositionBackOfPrependList:<class 'pxr.Usd.ListPosition'>
ListPositionFrontOfAppendList:<class 'pxr.Usd.ListPosition'>
ListPositionFrontOfPrependList:<class 'pxr.Usd.ListPosition'>
LoadPolicy:<class 'Boost.Python.class'>
LoadWithDescendants:<class 'pxr.Usd.LoadPolicy'>
LoadWithoutDescendants:<class 'pxr.Usd.LoadPolicy'>
ModelAPI:<class 'Boost.Python.class'>
Notice:<class 'Boost.Python.class'>
Object:<class 'Boost.Python.class'>
Payloads:<class 'Boost.Python.class'>
Prim:<class 'Boost.Python.class'>
PrimAllPrimsPredicate:<class 'pxr.Usd._PrimFlagsPredicate'>
PrimCompositionQuery:<class 'Boost.Python.class'>
PrimDefaultPredicate:<class 'pxr.Usd._PrimFlagsConjunction'>
PrimDefinition:<class 'Boost.Python.class'>
PrimHasDefiningSpecifier:<class 'pxr.Usd._Term'>
PrimIsAbstract:<class 'pxr.Usd._Term'>
PrimIsActive:<class 'pxr.Usd._Term'>
PrimIsDefined:<class 'pxr.Usd._Term'>
PrimIsGroup:<class 'pxr.Usd._Term'>
PrimIsInstance:<class 'pxr.Usd._Term'>
PrimIsLoaded:<class 'pxr.Usd._Term'>
PrimIsModel:<class 'pxr.Usd._Term'>
PrimRange:<class 'Boost.Python.class'>
PrimTypeInfo:<class 'Boost.Python.class'>
Property:<class 'Boost.Python.class'>
References:<class 'Boost.Python.class'>
Relationship:<class 'Boost.Python.class'>
ResolveInfo:<class 'Boost.Python.class'>
ResolveInfoSource:<class 'Boost.Python.class'>
ResolveInfoSourceDefault:<class 'pxr.Usd.ResolveInfoSource'>
ResolveInfoSourceFallback:<class 'pxr.Usd.ResolveInfoSource'>
ResolveInfoSourceNone:<class 'pxr.Usd.ResolveInfoSource'>
ResolveInfoSourceTimeSamples:<class 'pxr.Usd.ResolveInfoSource'>
ResolveInfoSourceValueClips:<class 'pxr.Usd.ResolveInfoSource'>
SchemaBase:<class 'Boost.Python.class'>
SchemaKind:<class 'type'>
SchemaRegistry:<class 'Boost.Python.class'>
Specializes:<class 'Boost.Python.class'>
Stage:<class 'Boost.Python.class'>
StageCache:<class 'Boost.Python.class'>
StageCacheContext:<class 'Boost.Python.class'>
StageCacheContextBlockType:<class 'Boost.Python.class'>
StageLoadRules:<class 'Boost.Python.class'>
StagePopulationMask:<class 'Boost.Python.class'>
TimeCode:<class 'Boost.Python.class'>
Tokens:<class 'Boost.Python.class'>
TraverseInstanceProxies:<class 'Boost.Python.function'>
Typed:<class 'Boost.Python.class'>
UsdCollectionMembershipQuery:<class 'Boost.Python.class'>
UseButDoNotPopulateCache:<class 'Boost.Python.function'>
VariantSet:<class 'Boost.Python.class'>
VariantSets:<class 'Boost.Python.class'>
ZipFile:<class 'Boost.Python.class'>
ZipFileWriter:<class 'Boost.Python.class'>
_CanApplyAPIResult:<class 'Boost.Python.class'>
_CanApplyResult:<class 'Boost.Python.class'>
_NoBlock:<class 'pxr.Usd.StageCacheContextBlockType'>
_NonPopulatingStageCacheWrapper:<class 'Boost.Python.class'>
_PrimFlagsConjunction:<class 'Boost.Python.class'>
_PrimFlagsDisjunction:<class 'Boost.Python.class'>
_PrimFlagsPredicate:<class 'Boost.Python.class'>
_Term:<class 'Boost.Python.class'>
_TestPrimRangeRoundTrip:<class 'Boost.Python.function'>
_UnsafeGetStageForTesting:<class 'Boost.Python.function'>
__MFB_FULL_PACKAGE_NAME:<class 'str'>
__builtins__:<class 'dict'>
__cached__:<class 'str'>
__doc__:<class 'NoneType'>
__file__:<class 'str'>
__loader__:<class '_frozen_importlib_external.ExtensionFileLoader'>
__name__:<class 'str'>
__package__:<class 'str'>
__path__:<class 'list'>
__spec__:<class '_frozen_importlib.ModuleSpec'>

参考

https://developer.nvidia.com/usd/apinotes

[maya] よくあるtextFieldの入力をchangeCommandで受ける場合に必要なwindow object path のpythonの話

なんか引っかかってしまいがちな

どこにも書いてないウィンドウパスの話
MY_Export_window|MY_layout|pathTxtFld

    
def createWindow():
    MY_window = cmds.window("MY_Export_window", widthHeight=(400, 200))
    MY_layout = cmds.columnLayout("MY_layout",adjustableColumn=True, parent=MY_window)

    cmds.text (label="テキストを変更したら呼ばれるよ", align='left', parent=MY_layout)

    text_Field_id = cmds.textField("pathTxtFld",text=get_lastExportDirPath(),changeCommand=changeTextFld)
    print("text_Field_id= "+text_Field_id)

    cmds.showWindow(MY_window)
    
    return None

def changeTextFld(*arg):
    text_Field_id="MY_Export_window|MY_layout|pathTxtFld"
    print("text_Field_id= "+text_Field_id)
    pathTxtFld_value = cmds.textField(text_Field_id, q=True, text=True)
    print("pathTxtFld_value= "+pathTxtFld_value)
    set_lastExportDirPath(pathTxtFld_value)


createWindow()   

この時出力が

#columnLayoutに名前つけないとパスがこんな不安な感じになる。
text_Field_id= MY_Export_window|columnLayout118|pathTxtFld

#columnLayoutに名前つければとパスがこんな確実な感じになる。
text_Field_id= MY_Export_window|MY_layout|pathTxtFld

text_Field_id= MY_Export_window|MY_layout|pathTxtFld

[maya] カスタム アトリビュート を python で作る場合。

cmds.addAttr(longName=’lastDirPath’,dataType=’string’ )

import maya.cmds as cmds

cmds.select("any")
#custom-attribute-add-python
cmds.addAttr(longName='lastDirPath',dataType='string' )

これをこう使うわけだ

def select_exportDir(self):
    
    filePath = cmds.fileDialog2( cap = '書き出しディレクトリの選択', okc = '書き出しディレクトリを設定',ds = 2, fm = 3,startingDirectory=get_lastExportDirPath())
    if filePath == None:
        return False
    else:
        set_lastExportDirPath(filePath[0]+"/")



def get_lastExportDirPath_ExistBool():
    lastExportDirPath_ExistBool=False
    Attlist=cmds.listAttr( r=True )
    print("Attlist= "+str(Attlist))
    for AttName in Attlist:
        #print("AttName= "+AttName)
        if(AttName=="lastExportDirPath"):
            lastExportDirPath_ExistBool=True
            print("HIT!!!!!!!lastExportDirPath")
    return lastExportDirPath_ExistBool

def addAttr_lastExportDirPath():
    lastExportDirPath_ExistBool= get_lastExportDirPath_ExistBool()
    if(lastExportDirPath_ExistBool==False):
        cmds.addAttr(longName='lastExportDirPath',dataType='string')
        

def set_lastExportDirPath(lastExportDirPath):
    
    selectList=cmds.ls(sl=True)
    if(str(selectList)== "[]"):
        print("なにも選択されていません。0 set_lastExportDirPath")
    else:

        for i in selectList:
            cmds.select(i)
            #---------------------------
            addAttr_lastExportDirPath()
            #---------------------------
            print("i= "+str(i))
            attName=i+"."+'lastExportDirPath'
            print("attName= "+attName)
            cmds.setAttr( attName, lastExportDirPath,type="string")
    cmds.textField("pathTxtFld", edit=True, text=lastExportDirPath)
    cmds.select(selectList)



def get_lastExportDirPath():

    selectList=cmds.ls(sl=True)
    
    lastExportDirPath=""
    if(str(selectList)== "[]"):
        print("なにも選択されていません。3 get_lastExportDirPath")
        lastExportDirPath = get_scenePath()
    else:
        for i in selectList:
            cmds.select(i)
            #---------------------------
            addAttr_lastExportDirPath()
            #---------------------------
            print("i= "+str(i))
            attName=i+"."+'lastExportDirPath'
            print("attName= "+attName)
            lastExportDirPath = cmds.getAttr(attName)
            print("lastExportDirPath="+str(lastExportDirPath))
            if(str(lastExportDirPath)=="None"):
                lastExportDirPath = get_scenePath()
        cmds.select(selectList)
    return lastExportDirPath
       

[maya] MEL To Python2 From pymel For Maya 2016

MEL To Python2

これがシンプルな状態
import pymel.tools.mel2py as mel2py

pyCmd = mel2py.mel2pyStr(melCmd,pymelNamespace=’pm‘)

pyCmd = mel2py.mel2pyStr(melCmd,pymelNamespace=’cmds‘)でいいのかも

# -*- coding: cp932 -*-
import pymel.core as pm
import pymel.tools.mel2py as mel2py
import re
import math
import random
melCmd = """
$value1 = `floatFieldGrp -q -label "Frame range" -v1`;
	"""
pyCmd =  mel2py.mel2pyStr(melCmd,pymelNamespace='pm')

melで改行をしてる「+”¥n”」と「¥n」を けしてから

あと、出力結果がPyMelにならないようにしてみたり。

# -*- coding: cp932 -*-
import pymel.core as pm
import pymel.tools.mel2py as mel2py
import re
import math
import random
melCmd = """
global proc Generic_modelFileOpen()
{
  string $workspaceRoot = `workspace -q -rootDirectory`;
    string $motionFileDir= $workspaceRoot+"scenes/Generic_model_wep.mb";
    file -f -options "v=0;"  -ignoreVersion  -typ "mayaBinary" -o $motionFileDir;
        if(`file -q -writable`==1){
            select `ls -type joint`;
    
    string $joints[] =`ls -type joint`;
   int $jointsLength=size($joints);
    if($jointsLength==0)
    {
      print ("-------------------------joint nothing-----------------------------");
    }else{
        for	($joint in $joints)
        {
            //setKeyframe 0 ,1
            currentTime 0 ;
            setKeyframe -breakdown 0 -hierarchy none -controlPoints 0 -shape 0 -time 0 $joint;
           currentTime 1 ;
            setKeyframe -breakdown 0 -hierarchy none -controlPoints 0 -shape 0 -time 0 $joint;
        }
    }
    print("-------------------------joint-----------------------------");
    print($joint);
    print ("\n-------------------------joint-----------------------------");
    if($joint=="")
    {
    print ("-------------------------joint nothing-----------------------------");
    }
    ////////////////////////////////////////////////////////joint select
            print("TstanceFBXExport()");
           TstanceFBXExport();
    }
}
$value1 = `floatFieldGrp -q -label "Frame range" -v1`;
	"""
		
print "----------------mel code replace----------------------------"
#melCmd = melCmd.replace('$writable_bool','`file -q -writable`')
melCmd = melCmd.replace('"\n--', '"--')
melCmd = melCmd.replace('+"\n"', '')
melCmd = melCmd.replace('\n"', '"')
print("melCmd="+melCmd)
print "------------------------------------------------"
# mel2py.mel2pyStr  
pyCmd =  mel2py.mel2pyStr(melCmd,pymelNamespace='pm')
pyFixed_Dest = ""
#pyFixed_Dest = pyFixed_Dest + "# -*- coding: cp932 -*- \n"
pyFixed_Dest = pyFixed_Dest + "# -*- coding: utf-8 -*- \n"
#pyFixed_Dest = pyFixed_Dest + "# -*- coding: shift-jis -*- \n"
pyFixed_Dest = pyFixed_Dest + "from maya import cmds \n"
pyFixed_Dest = pyFixed_Dest + "from python import Debug \n"
pyFixed = pyCmd.replace("pymel.all","pymel.core")
pyFixed = pyFixed.replace("pm.pm.cmds","cmds")
pyFixed_Dest = pyFixed_Dest + pyFixed+"\n"
print "----------------------python sorce replace----------------------"

pyFixed_Dest = pyFixed_Dest.replace('import pymel.core as pm', 'import pymel.core as pm \nDebug=Debug.Debug')
pyFixed_Dest = pyFixed_Dest.replace('pm.file', 'cmds.file')
pyFixed_Dest = pyFixed_Dest.replace('pm.ls', 'cmds.ls')
pyFixed_Dest = pyFixed_Dest.replace('pm.select', 'cmds.select')
pyFixed_Dest = pyFixed_Dest.replace('pm.internalVar', 'cmds.internalVar')
pyFixed_Dest = pyFixed_Dest.replace('pm.keyframe', 'cmds.keyframe')
pyFixed_Dest = pyFixed_Dest.replace('pm.workspace', 'cmds.workspace')
pyFixed_Dest = pyFixed_Dest.replace('pm.getFileList', 'cmds.getFileList')
pyFixed_Dest = pyFixed_Dest.replace('=="1"', '==1')
pyFixed_Dest = pyFixed_Dest.replace('== "1"', '== 1')
pyFixed_Dest = pyFixed_Dest.replace('print("', 'print(u"')
pyFixed_Dest = pyFixed_Dest.replace('print "', 'print u"')
pyFixed_Dest = pyFixed_Dest.replace('pm.flushUndo()', 'cmds.flushUndo()')
pyFixed_Dest = pyFixed_Dest.replace('pm.parent', 'cmds.parent')
pyFixed_Dest = pyFixed_Dest.replace('pm.objExists', 'cmds.objExists')
pyFixed_Dest = pyFixed_Dest.replace('pm.rename', 'cmds.rename')
pyFixed_Dest = pyFixed_Dest.replace('pm.playbackOptions', 'cmds.playbackOptions')
pyFixed_Dest = pyFixed_Dest.replace('pm.mel.DebugLog', 'self.DebugLog')
pyFixed_Dest = pyFixed_Dest.replace('pm.currentTime', 'cmds.currentTime')
pyFixed_Dest = pyFixed_Dest.replace('pm.setKeyframe', 'cmds.setKeyframe')
#pyFixed_Dest = pyFixed_Dest.replace('maya.mel.eval("listRelatives -pa -ad `ls -sl -l`"', 'cmds.listRelatives(path=True, allDescendents =True,cmds.ls(selection=True, long=True))'))
#for Class
pyFixed_Dest = pyFixed_Dest.replace('():', '(self):')
pyFixed_Dest = pyFixed_Dest.replace('():', '(self):')
regex = r'print+'
#pattern = re.compile(regex)
#matchObj = pattern.match(pyFixed_Dest)
#matchObj = re.search(r'[a-z]+', pyFixed_Dest)

def repl(m):
    inner_word1 = list(m.group(1))  #prin(\w\W)    "prin" "t" " "    real ['t', ' ']
    #print("inner_word1= "+str(inner_word1))   
    inner_word2 = list(m.group(2))    #(.*)     something strings "----1-----" real ['u', '"', '-', '-', '-', '-', '1', '-', '-', '-', '-']
    #print("inner_word2= "+str(inner_word2))
    inner_word3 = list(m.group(3))
    #inner_word4 = list(m.group(4))    #(\")  double cout   real  ['"']
    print("inner_word123= "+str(inner_word1)+str(inner_word2)+str(inner_word3)+""+str(list(m.group(4)))+str(list(m.group(5)))+"")
    #print("inner_word2= "+str(inner_word1)+str(inner_word2)+str(inner_word3))
    #random.shuffle(inner_word)
    #back= m.group(1) + "".join(inner_word) + m.group(3)
    back="00000"+ str(m.end())
    back=m.group(1) +m.group(2)+"("+m.group(3)+m.group(4)+m.group(5)+")" #for print
    back=m.group(1) +"Debug.Log"+"("+m.group(3)+m.group(4)+m.group(5)+")"  #for Debug.Log  Debug Class is https://gist.github.com/whaison/fc625381dce126ca5d88d1f914ce89f0
    
    return back
#text = "Professor Abdolmalek, please report your absences promptly."
text = """
print "----1----"
print "----2----"
print "----3----"
print "----4----"
print "----5----"
print "----6----"
print "----7----"
	"""
#resub=re.sub(r"(\w)(\w+)(\w)", repl, text)
#resub=re.sub(r'(prin\w)', repl, text)
resub=re.sub(r'(.*)(prin\w\W)(.*)(\")(.*)', repl, text)

print("resub    --------------------output  start")
print resub 
#print resub[:m.start()]
#print resub[m.end():]
print("resub    --------------------output  end")
pyFixed_Dest=re.sub(r'(.*)(prin\w\W)(.*)(\")(.*)', repl, pyFixed_Dest)
print("resub  pyFixed_Dest  --------------------output  start")
print pyFixed_Dest 
#print resub[:m.start()]
#print resub[m.end():]
print("resub pyFixed_Dest   --------------------output  end")
print("search    --------------------output  start")
email = "tony@tiremove_thisger.net"
m = re.search(r'print*', text)
print text[:m.start()] +"print("+ text[m.end():]
print("search    --------------------output  end")
print "------------------------------------------------"
print pyFixed_Dest

出力結果

------------------------------------------------
# -*- coding: utf-8 -*- 
from maya import cmds 
from python import Debug 
import pymel.core as pm 
Debug=Debug.Debug

def Generic_modelFileOpen(self):
	
	workspaceRoot=str(cmds.workspace(q=1, rootDirectory=1))
	motionFileDir=workspaceRoot + "scenes/Generic_model_wep.mb"
	cmds.file(motionFileDir, ignoreVersion=1, typ="mayaBinary", options="v=0;", o=1, f=1)
	if cmds.file(q=1, writable=1) == 1:
		cmds.select(cmds.ls(type='joint'))
		joints=cmds.ls(type='joint')
		jointsLength=len(joints)
		if jointsLength == 0:
			Debug.Log(u"-------------------------joint nothing-----------------------------")
			
		
		else:
			for joint in joints:
				cmds.currentTime(0)
				#setKeyframe 0 ,1
				cmds.setKeyframe(joint, breakdown=0, hierarchy='none', shape=0, time=0, controlPoints=0)
				cmds.currentTime(1)
				cmds.setKeyframe(joint, breakdown=0, hierarchy='none', shape=0, time=0, controlPoints=0)
				
			
		Debug.Log(u"-------------------------joint-----------------------------")
		print joint
		Debug.Log(u"-------------------------joint-----------------------------")
		if joint == "":
			Debug.Log(u"-------------------------joint nothing-----------------------------")
			
		Debug.Log(u"TstanceFBXExport()")
		#//////////////////////////////////////////////////////joint select
		pm.mel.TstanceFBXExport()
		
	

value1=pm.floatFieldGrp("Frame range", q=1, v1=1, label=1)

maya ls python のまとめ

このごろサイトが丸ごとなくなったので置いておく

Top Node をとってくる

topNodeList=cmds.ls(assemblies=True)

dagObjects 階層をとってくる

topNodeList=cmds.ls( "root", dagObjects=True, type="transform" )

Python でUTF-8, shift_jis, euc_jp,など日本語を使う方法

ここ最近、サイトが無くなって困ったことがあったので記事にしておく

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import codecs

fout = codecs.open('sjis.txt', 'w', 'shift_jis')
fout.write("abcdefg")
fout.close()

#または
fin  = codecs.open('utf_8.txt', 'r', 'utf_8')
file_txt = fin.read()
file_Arr = setting_file_txt.split("\n")

参考

https://osksn2.hep.sci.osaka-u.ac.jp/~taku/osx/python/encoding.html

[mel] 全リファレンスからオブジェクトを読み込み

[mel] 全リファレンスからオブジェクトを読み込み

[mel] import object from all references


global proc reference_to_object(){
    print("reference_to_object \n");
    
    string $refArr[] = `file -q -list`;
    //-list(-l)		query
    //すべてのファイルをリスト表示します。 すべてのセグメント/リファレンス ファイルの名前を文字配列で返し、複製は削除します。つまり、ファイルが複数回参照され、-withoutCopyNumber フラグを設定している場合は、シーン内で 1 度リスト表示されます。
    
    string $mayaAsciiArr[] = {};
    for ($ref in $refArr) {
        print($ref+" \n");
        string $fileNameExt[];
        $numTokens = `tokenize $ref "." $fileNameExt`;

        //_Motion.ma{1} の対応
        string $ExtArr[];
        $numTokens2 = `tokenize $fileNameExt[1] "{" $ExtArr`;
        //print("$fileNameExt[1]="+$fileNameExt[1]+" \n");
        /*
        if($fileNameExt[1]=="ma"){
            print("HIT!! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ $ref+" \n");
            //Array Append Add
            $mayaAsciiArr[size($mayaAsciiArr)] = $ref;
        }else
        //_Motion.ma{1}  の対応
        */ 
        if($ExtArr[0]=="ma"){
            print("HIT!! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ $ref+" \n");
            //Array Append Add
            $refFileName=$fileNameExt[0]+"."+$ExtArr[0];
            $mayaAsciiArr[size($mayaAsciiArr)] = $refFileName;
        }
    }
    string $Ref_MayaAsciiArr[] = {};
    for ($ref_mayaAscii in $mayaAsciiArr) {
        print("$ref_mayaAscii= "+ $ref_mayaAscii+" \n");
        string $sceneName=`file -q -sceneName`;
        print("$sceneName= "+$sceneName+" \n");
        
        if($ref_mayaAscii==$sceneName){
            print("-----------------------HIT $sceneName ------------------------------ \n");
        }else{
            $Ref_MayaAsciiArr[size($Ref_MayaAsciiArr)] = $ref_mayaAscii;
        }
    }
    //string $refArrStr = stringArrayToString($refArr,", \n");
    //print("$refArrStr= "+$refArrStr+ " \n");
    print("----------------------------------- $Ref_MayaAsciiArr ------------------------------------------ \n");
    for ($ref_mayaAscii_path in $Ref_MayaAsciiArr) {
        print("$ref_mayaAscii_path= "+$ref_mayaAscii_path+" \n");
        //=====================================================================
        file -importReference $ref_mayaAscii_path;
        //-importReference(-ir)		create
        //指定したファイル内でデータの周りのリファレンスのカプセル化を削除します。これにより指定したファイルの内容がカレント シーンの一部となり、オリジナル ファイルのすべてのリファレンスが失われます。 インポートされたリファレンスの名前が返されます。
        //====================================================================
    }
    print("----------------------------------- $Ref_MayaAsciiArr ------------------------------------------ \n");

    
}

//reference_to_object();

[Maya] .offsetParentMatrixをmel/Pythonスクリプトで取り扱う場合の研究

解決策から、、画像のような状態でよかった。関数はこんな感じ

global proc _Input_Lines(){
    print("_Input_Lines \n");
    
    _offsetParentMatrix_Value_Input("Dummy_calf_l",-15.216,0);
    _offsetParentMatrix_Value_Input("Dummy_calf_r",15.216,0);
    _offsetParentMatrix_Value_Input("Dummy_foot_l",-7.821,-0.047);
    _offsetParentMatrix_Value_Input("Dummy_foot_r",7.821,0.047);
}

global proc _offsetParentMatrix_Value_Input(string $NodeName,float $X,float $Y){
    print("_offsetParentMatrix_Value_Input \n");
    string $LocatorName="OffsetParentMatrix_locator_"+$NodeName;
    print("$LocatorName= "+$LocatorName+" \n");
    spaceLocator -position 0.0 0.0 0.0 -name $LocatorName;
    $LocatorNameTransX = $LocatorName+".translateX";
    print("$LocatorNameTransX= "+$LocatorNameTransX+" \n");
    setAttr $LocatorNameTransX $X;
    $LocatorNameTransY = $LocatorName+".translateY";
    print("$LocatorNameTransY= "+$LocatorNameTransY+" \n");
    setAttr $LocatorNameTransY $Y;
    $LocatorName_worldMatrix0 = $LocatorName+".worldMatrix[0]";
    print("$LocatorName_worldMatrix0= "+$LocatorName_worldMatrix0+" \n");
    $NodeName_offsetParentMatrix = $NodeName+".offsetParentMatrix";
    print("$NodeName_offsetParentMatrix= "+$NodeName_offsetParentMatrix+" \n");
    connectAttr -f $LocatorName_worldMatrix0 $NodeName_offsetParentMatrix;
}

で大丈夫そう

————————————————–下は参考サイトの例————————————————-

この関数を

import os
import stat
import maya.cmds as cmds
#import maya.OpenMaya as OpenMaya
import maya.api.OpenMaya as OpenMaya
def func_offsetParentMatrix(node,driver):
    mult = cmds.createNode("multMatrix")

    offset = matrix_to_list(
        OpenMaya.MMatrix(cmds.getAttr("{}.worldMatrix[0]".format(node)))
        * OpenMaya.MMatrix(cmds.getAttr("{}.matrix".format(node))).inverse()
        * OpenMaya.MMatrix(cmds.getAttr("{}.worldInverseMatrix[0]".format(driver)))
    )
    cmds.setAttr("{}.matrixIn[0]".format(mult), offset, type="matrix")

    cmds.connectAttr("{}.worldMatrix[0]".format(driver), "{}.matrixIn[1]".format(mult))

    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        cmds.connectAttr("{}.worldInverseMatrix[0]".format(parent[0]), "{}.matrixIn[2]".format(mult))

    cmds.connectAttr(
        "{}.matrixSum".format(mult), "{}.offsetParentMatrix".format(node)
    )
    
def matrix_to_list(mtx):
    lst=[]
    for row in range(0,4):
        for col in range(0,4):
            lst.append(mtx.getElement(row,col))
    return lst
    
def list_to_matrix(lst):
    mtx=OpenMaya.MMatrix(lst)
    # OpenMaya.MScriptUtil.createMatrixFromList(lst, mtx)
    return mtx

こう使った。

global proc Func_TEST_offsetParentMatrix_Proc(){    
    print("Func_TEST_offsetParentMatrix_Proc");
    spaceLocator -position -15.216 0.0 0.0 -name "calf_l_OffsetMatrix_locator_l" -absolute;
    func_offsetParentMatrix_Python_Proc("Dummy_calf_telescopic_l","calf_l_OffsetMatrix_locator_l");
}
    
global proc func_offsetParentMatrix_Python_Proc(string $node,string $driver){
    print("func_offsetParentMatrix");
    python("import func_offsetParentMatrix");
	python("import importlib");
	python("importlib.reload(func_offsetParentMatrix)");
    python("func_offsetParentMatrix.func_offsetParentMatrix('"+$node+"','"+$driver+"')");
}

参考

offsetParentMatrixの記事
https://www.chadvernon.com/blog/space-switching-offset-parent-matrix/

matrix_to_list
https://gist.github.com/rjmoggach/4ea80af3104a3517d3a2a46293acf043