def test_g_sum(self): try: mObj = cgmMeta.cgmObject('argsToNodes_catch') except: mObj = cgmMeta.cgmObject(name='argsToNodes_catch') str_obj = mObj.p_nameShort mObj.tx = 1 mObj.ty = 2 mObj.tz = 3 arg = "%s.sumResult1 = %s.tx - %s.ty - %s.tz" % (str_obj, str_obj, str_obj, str_obj) d_return = NODEFACTORY.argsToNodes(arg).doBuild() log.debug(d_return['ml_outPlugs']) assert d_return['l_nodes'], "Should have made something" assert len(d_return['l_nodes'] ) == 1, "Only one node should be made. Found: %s" % len( d_return['l_nodes']) assert d_return['ml_outPlugs'][0].obj.getMayaType( ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][ 0].obj.getMayaType() plugCall = mc.listConnections("%s.sumResult1" % (mObj.mNode), plugs=True, scn=True) assert d_return['ml_nodes'][0].operation == 2, "Operation not 2" combinedName = d_return['ml_outPlugs'][0].p_combinedName assert str(plugCall[0]) == d_return['ml_outPlugs'][ 0].p_combinedName, "Connections don't match: %s | %s" % ( plugCall[0], combinedName) assert mObj.sumResult1 == mObj.tx - mObj.ty - mObj.tz, "Sum doesn't match"
def test_a_condition(self): try: mObj = cgmMeta.cgmObject('argsToNodes_catch') except: mObj = cgmMeta.cgmObject(name='argsToNodes_catch') str_obj = mObj.p_nameShort arg = "%s.condResult = if %s.ty == 3:5 else 1" % (str_obj, str_obj) d_return = NODEFACTORY.argsToNodes(arg).doBuild() _ml_nodes = d_return.get('ml_nodes') _ml_outPlugs = d_return.get('ml_outPlugs') _plugCall = mc.listConnections("%s.condResult" % (mObj.mNode), plugs=True, scn=True) _combinedName = _ml_outPlugs[0].p_combinedName self.assertIsNotNone(_ml_outPlugs) self.assertEqual(len(_ml_outPlugs), 1) self.assertIsNotNone(_ml_nodes) self.assertEqual(len(_ml_nodes), 1) self.assertEqual(_ml_nodes[0].getMayaType(), 'condition') self.assertEqual(_ml_nodes[0].operation, 0) self.assertEqual(str(_plugCall[0]), _combinedName) mObj.ty = 3 self.assertEqual(mObj.condResult, 5) mObj.ty = 1 self.assertEqual(mObj.condResult, 1) return
def test_c_simpleInvsersion(self): try: mObj = cgmMeta.cgmObject('argsToNodes_catch') except: mObj = cgmMeta.cgmObject(name='argsToNodes_catch') str_obj = mObj.p_nameShort arg = "%s.simpleInversion = -%s.tx" % (str_obj, str_obj) d_return = NODEFACTORY.argsToNodes(arg).doBuild() log.debug(d_return['ml_outPlugs']) assert d_return['l_nodes'], "Should have made something" assert len(d_return['l_nodes'] ) == 1, "Only one node should be made. Found: %s" % len( d_return['l_nodes']) assert d_return['ml_outPlugs'][0].obj.getMayaType( ) == 'multiplyDivide', "%s != pma" % d_return['ml_outPlugs'][ 0].obj.getMayaType() plugCall = mc.listConnections("%s.simpleInversion" % (mObj.mNode), plugs=True, scn=True) assert d_return['ml_nodes'][0].operation == 1, "Operation not 1" combinedName = d_return['ml_outPlugs'][0].p_combinedName assert str(plugCall[0]) == d_return['ml_outPlugs'][ 0].p_combinedName, "Connections don't match: %s | %s" % ( plugCall[0], combinedName) assert mObj.simpleInversion == -mObj.tx, "Inversion doesn't match"
def test_i_range(self): try: mObj = cgmMeta.cgmObject('argsToNodes_catch') except: mObj = cgmMeta.cgmObject(name='argsToNodes_catch') str_obj = mObj.p_nameShort mObj.tz = 5 arg = "%s.setRangeResult = setRange(0,1,0,10,%s.tz" % (str_obj, str_obj) d_return = NODEFACTORY.argsToNodes(arg).doBuild() log.debug(d_return['ml_outPlugs']) assert d_return['l_nodes'], "Should have made something" assert len(d_return['l_nodes'] ) == 1, "Only one node should be made. Found: %s" % len( d_return['l_nodes']) assert d_return['ml_outPlugs'][0].obj.getMayaType( ) == 'setRange', "%s != setRange" % d_return['ml_outPlugs'][ 0].obj.getMayaType() plugCall = mc.listConnections("%s.setRangeResult" % (mObj.mNode), plugs=True, scn=True) combinedName = d_return['ml_outPlugs'][0].p_combinedName assert str(plugCall[0]) == d_return['ml_outPlugs'][ 0].p_combinedName, "Connections don't match: %s | %s" % ( plugCall[0], combinedName) assert mObj.setRangeResult == .5, "Value 1 fail" mObj.tz = 10 assert mObj.setRangeResult == 1, "Value 2 fail"
def _nameFactory_(self, **kws): try: #Transform nodes try: i_trans1a = cgmMeta.cgmObject(name='trans') i_parent = cgmMeta.cgmObject(name='parent') i_parent.addAttr('cgmName', 'nameParent', attrType='string') except Exception, error: raise Exception, "Setup | {0}".format(error) try: i_trans1b = cgmMeta.cgmObject(mc.duplicate(i_trans1a.mNode)[0]) except Exception, error: raise Exception, "duplicate | {0}".format(error)
def _buildStuff_(self): mi_rootJoint = cgmMeta.cgmObject(mc.joint(name = 'root')) mi_rootJoint.parent = False self.md_rootToChildren[mi_rootJoint] = [] _last = mi_rootJoint for i in range(self.int_children): self.progressBar_set(status = ("Creating obj %i"%i), progress = i, maxValue = self.int_children) mi_child = cgmMeta.cgmObject(mc.joint(name = ' "child"%i'%i)) self.md_rootToChildren[mi_rootJoint].append(mi_child) mi_child.parent = _last mi_child.ty = (i) _last = mi_child#...change for the next self.mi_rootJoint = mi_rootJoint
def build_fkJoints(self): ml_fkJoints = [] for i,i_ctrl in enumerate(self._go._i_templateNull.msgList_get('controlObjects')): if not i_ctrl.getMessage('handleJoint'): raise Exception,"%s.build_rigSkeleton>>> failed to find a handle joint from: '%s'"%(self._go._mi_module.getShortName(),i_ctrl.getShortName()) i_new = cgmMeta.cgmObject((i_ctrl.getMessage('handleJoint')[0])).doDuplicate() i_new.addAttr('cgmTypeModifier','fk',attrType='string',lock=True) i_new.doName() if ml_fkJoints:#if we have data, parent to last i_new.parent = ml_fkJoints[-1] else:i_new.parent = False i_new.rotateOrder = self._go._jointOrientation#<<<<<<<<<<<<<<<<This would have to change for other orientations ml_fkJoints.append(i_new) ml_fkJoints[-1].addAttr('cgmName','clavicleEnd') ml_fkJoints[-1].doName() try: if self._go._str_mirrorDirection == 'Right':#mirror control setup #ml_fkDriverJoints = self._go.duplicate_jointChain(ml_fkJoints,'fkAttach','fkAttachJoints') self._go.mirrorChainOrientation(ml_fkJoints)#Mirror """ for i,mJoint in enumerate(ml_fkJoints): log.info("Mirror connect: %s | %s"%(i,mJoint.p_nameShort)) mJoint.connectChildNode(ml_fkDriverJoints[i],"attachJoint","rootJoint") cgmMeta.cgmAttr(mJoint.mNode,"rotateOrder").doConnectOut("%s.rotateOrder"%ml_fkDriverJoints[i].mNode) """ except Exception,error: raise Exception,"Failed to create mirror chain | %s"%error self._go._i_rigNull.msgList_connect(ml_fkJoints,'fkJoints',"rigNull") self.ml_fkJoints = ml_fkJoints#pass to wrapper
def _validate(self): #>> validate ============================================================================ self._d_data = {"mesh": {}, "skin": {}, "weights":{}, "blendWeights":[], "influences":{}} #_validate our source _source = self.d_kws['source'] _d = data().validateSourceMesh(_source) self._mesh = _d['mesh'] self._skin = _d['skin'] self.mi_mesh = cgmMeta.cgmObject(self._mesh) self.mi_cluster = cgmMeta.cgmNode(self._skin) # Get the skinCluster MObject self.selectionList = OM.MSelectionList() self.selectionList.add(self._skin, True) self.mobject = OM.MObject() self.selectionList.getDependNode(0, self.mobject) self.fn = OMA.MFnSkinCluster(self.mobject) """self.data = {'weights' : {}, 'blendWeights' : [], }""" _d['name'] = self.mi_mesh.mNode _d['d_vertPositions'] = {} self._d_data['mesh'] = _d
def _create(self): #Get our l_eps = self.d_info['l_eps'] l_cvs = self.d_info['l_cvs'] int_cvCount = len(l_cvs) #l_locs = locators.locMeCVsOnCurve(self.mi_crv.mNode) self.progressBar_setMaxStepValue(int_cvCount) for i,cv in enumerate(l_cvs): try:#Loc loop self.progressBar_iter(status = cv, step = i) #create it v_pos = p = mc.pointPosition(cv) str_loc = mc.spaceLocator()[0] mi_loc = cgmMeta.cgmObject(str_loc) mi_loc.translate = v_pos #self.d_info['ml_locators'].append(mi_loc) #aim it self.d_info['l_constraints'].append( mc.aimConstraint(self.mi_target.mNode,str_loc,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpVector = [0,1,0], worldUpType = 'scene')[0]) #move mc.move(0,0,self.f_offset, str_loc, r = True, os = True) #Get pos self.d_info['l_locPos'].append(mi_loc.getPosition()) mi_loc.delete() except Exception,error: raise StandardError,"Loc creation %s | %s"%(cv,error)
def doParentControlObjects(self): """ Needs instanced module """ log.info(">>> doParentControlObjects") i_templateNull = self.templateNull#link for speed i_root = i_templateNull.root i_controlObjects = i_templateNull.controlObjects #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>> Parent objects #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> for i_obj in i_controlObjects: i_obj.parent = i_root.mNode i_controlObjects[0].doGroup(maintain=True)#Group to zero out i_controlObjects[-1].doGroup(maintain=True) log.debug(i_templateNull.getMessage('controlObjects',False)) if self.moduleType not in ['foot']: constraintGroups = constraints.doLimbSegmentListParentConstraint(i_templateNull.getMessage('controlObjects',False)) for i_obj in i_controlObjects: i_parent = cgmMeta.cgmObject(i_obj.parent) i_parent.addAttr('mClass','cgmObject',lock=True)#tag it so it can initialize later i_obj.addAttr('owner',i_parent.mNode,attrType = 'messageSimple',lock=True) return
def holder(self): mObj = cgmMeta.cgmObject(name='awesomeArgObj_loc') str_obj = mObj.getShortName() try: #Mult inversion arg = "%s.inverseMultThree = 3 * -%s.tx" % (str_obj, str_obj) d_return = NODEFACTORY.argsToNodes(arg).doBuild() log.debug(d_return['ml_outPlugs']) assert d_return['l_nodes'], "Should have made something" assert len( d_return['l_nodes'] ) == 2, "Only two nodes should be made. Found: %s" % len( d_return['l_nodes']) assert d_return['ml_nodes'][0].getMayaType( ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][ 0].getMayaType() assert d_return['ml_nodes'][1].getMayaType( ) == 'multiplyDivide', "%s != md" % d_return['ml_nodes'][ 1].getMayaType() plugCall = mc.listConnections("%s.inverseMultThree" % (mObj.mNode), plugs=True, scn=True) assert d_return['ml_nodes'][-1].operation == 1, "Operation not 1" combinedName = d_return['ml_outPlugs'][-1].p_combinedName assert str(plugCall[0]) == d_return['ml_outPlugs'][ -1].p_combinedName, "Connections don't match: %s | %s" % ( plugCall[0], combinedName) assert mObj.inverseMultThree == 3 * -mObj.tx, "Inversion doesn't match" except StandardError, error: log.error("test_argsToNodes>>Inversion mult 3 Failure! '%s'" % (error)) raise StandardError, error
def __init__(self, profile='default', constrainMode='orient', constrainTo='selected', clean=True, forceNew=True, autoBuild=True, *a, **kws): """ Simple light studio setup idea """ _str_func = 'factory._init_' self.mLightGroup = None self.b_clean = clean self.profile = profile self.constrainTo = None if a: log.debug("|{0}| >> a: {1}".format(_str_func, a)) if kws: #...intial population self.call_kws = kws log.debug("|{0}| >> kws: {1}".format(_str_func, kws)) if constrainTo == 'selected': _sel = mc.ls(sl=1) or False if _sel: self.constrainTo = _sel[0] else: self.constrainTo = constrainTo if autoBuild: clean_lights() self.get_lights() mLightGroup = cgmMeta.cgmObject(name='cgmLightGroup') for mLight in self.ml_lightDags: mLight.p_parent = mLightGroup if self.constrainTo and constrainMode: mConstrainTo = cgmMeta.cgmObject(self.constrainTo) mLoc = mConstrainTo.doLoc() mConstrainTo.resetAttrs(['translate', 'rotate']) mc.orientConstraint(mConstrainTo.mNode, mLightGroup.mNode) mConstrainTo.doSnapTo(mLoc) mLoc.delete()
def verify_customizationData(i_network, skinDepth=2.5): """ Gather info from customization asset from morpheusRig_v2.core import MorpheusFactory as morphyF reload(morphyF) morphyF.verify_customizationData('Morphy_customizationNetwork') """ #These are the controls we'll drive positional data from to plug to our modules d_initialData = {} #>>> Verify our arg try: i_network.mNode except: if mc.objExists(i_network): i_network = r9Meta.MetaClass(i_network) else: log.error("'%s' doesn't exist" % i_network) return False assert i_network.mClass == 'cgmMorpheusMakerNetwork', "Not a cgmMorpheusMakerNetwork. Aborted!" #>> Collect our positional info #==================================================================== i_objSet = i_network.objSetAll #Should I use this or the message info log.debug(i_objSet.value) controlBuffer = i_network.objSetAll.value for moduleKey in l_modulesToDoOrder: if moduleKey not in d_moduleControls.keys(): log.warning("Missing controls info for: '%s'" % moduleKey) return False log.debug("On moduleKey: '%s'" % moduleKey) controls = d_moduleControls.get(moduleKey) posBuffer = [] for c in controls: if not mc.objExists(c): log.warning("Necessary positioning control not found: '%s'" % c) return False else: log.debug("Found: '%s'" % c) i_c = cgmMeta.cgmNode(c) if i_c.isComponent(): #If it's a component i_loc = cgmMeta.cgmObject( mc.spaceLocator()[0]) #make a loc Snap.go(i_loc.mNode, targets=c, move=True, orient=True) #Snap to the surface i_loc.tz -= skinDepth #Offset on z by skin depth pos = i_loc.getPosition() #get position i_loc.delete() else: pos = i_c.getPosition() if not pos: return False posBuffer.append(pos) d_initialData[moduleKey] = posBuffer return d_initialData
def test_e_directConnect(self): try: mObj = cgmMeta.cgmObject('argsToNodes_catch') except: mObj = cgmMeta.cgmObject(name='argsToNodes_catch') str_obj = mObj.p_nameShort arg = "%s.directConnect = %s.ty" % (str_obj, str_obj) NODEFACTORY.argsToNodes(arg).doBuild() log.debug( mc.listConnections("%s.directConnect" % str_obj, source=True, scn=True)) plugCall = mc.listConnections("%s.directConnect" % (mObj.mNode), plugs=True, scn=True) assert plugCall[0] == '%s.translateY' % mObj.getShortName(), log.error( "Direct connect failed. Plug call:{0}".format(plugCall))
def _copyTransform(self): copyTransform = self.d_kws['copyTransform'] if copyTransform is not None: if issubclass(type(copyTransform),cgmMeta.cgmNode): i_target = copyTransform elif mc.objExists(copyTransform): i_target = cgmMeta.cgmObject(copyTransform) else: raise StandardError,"Failed to find suitable copyTransform object: '%s"%copyTransform #Need to move this to default cgmNode stuff mBuffer = self.mi_control i_newTransform = cgmMeta.cgmObject( rigging.groupMeObject(i_target.mNode,False) ) for a in mc.listAttr(self.mi_control.mNode, userDefined = True): attributes.doCopyAttr(self.mi_control.mNode,a,i_newTransform.mNode) curves.parentShapeInPlace(i_newTransform.mNode,self.mi_control.mNode)#Parent shape i_newTransform.parent = self.mi_control.parent#Copy parent self.mi_control = cgmMeta.asMeta(i_newTransform,'cgmControl', setClass=True) mc.delete(mBuffer.mNode)
def test_d_average(self): try: mObj = cgmMeta.cgmObject('argsToNodes_catch') except: mObj = cgmMeta.cgmObject(name='argsToNodes_catch') str_obj = mObj.p_nameShort arg = "%s.sumAverage1 = 4 >< 4 >< 4" % (str_obj) d_return = NODEFACTORY.argsToNodes(arg).doBuild() assert d_return['l_nodes'], "Should have made something" assert len(d_return['l_nodes'] ) == 1, "Only one node should be made. Found: %s" % len( d_return['l_nodes']) assert d_return['ml_outPlugs'][0].obj.getMayaType( ) == 'plusMinusAverage', "%s != pma" % d_return['ml_outPlugs'][ 0].obj.getMayaType() assert d_return['ml_nodes'][0].operation == 3, "Operation not 3" assert mObj.sumAverage1 == 4, "Average is wrong: 4 != %s" % mObj.sumAverage1
def verify_customizationData(i_network, skinDepth = 2.5): """ Gather info from customization asset from morpheusRig_v2.core import MorpheusFactory as morphyF reload(morphyF) morphyF.verify_customizationData('Morphy_customizationNetwork') """ #These are the controls we'll drive positional data from to plug to our modules d_initialData = {} #>>> Verify our arg try:i_network.mNode except: if mc.objExists(i_network): i_network = r9Meta.MetaClass(i_network) else: log.error("'%s' doesn't exist"%i_network) return False assert i_network.mClass == 'cgmMorpheusMakerNetwork',"Not a cgmMorpheusMakerNetwork. Aborted!" #>> Collect our positional info #==================================================================== i_objSet = i_network.objSetAll#Should I use this or the message info log.debug(i_objSet.value) controlBuffer = i_network.objSetAll.value for moduleKey in l_modulesToDoOrder: if moduleKey not in d_moduleControls.keys(): log.warning("Missing controls info for: '%s'"%moduleKey) return False log.debug("On moduleKey: '%s'"%moduleKey) controls = d_moduleControls.get(moduleKey) posBuffer = [] for c in controls: if not mc.objExists(c): log.warning("Necessary positioning control not found: '%s'"%c) return False else: log.debug("Found: '%s'"%c) i_c = cgmMeta.cgmNode(c) if i_c.isComponent():#If it's a component i_loc = cgmMeta.cgmObject(mc.spaceLocator()[0])#make a loc Snap.go(i_loc.mNode,targets = c,move = True, orient = True)#Snap to the surface i_loc.tz -= skinDepth#Offset on z by skin depth pos = i_loc.getPosition()#get position i_loc.delete() else: pos = i_c.getPosition() if not pos:return False posBuffer.append(pos) d_initialData[moduleKey] = posBuffer return d_initialData
def AddShot(self, name, minVal, maxVal): # create if not found if not self.animListNode: self.animListNode = cgmMeta.cgmObject( name="AnimListNode") #node.Transform(name="AnimListNode") self.animListNode.addAttr("subAnimList", attrType='string') self.animDict[name] = [minVal, maxVal, maxVal - minVal] self.animListNode.subAnimList = self.animDict #json.dumps(self.animDict) self.Sort(self.sortType)
def _buildStuff_(self): for i in range(self.int_value): self.progressBar_set(status = ("Creating obj %s"%i), progress = i, maxValue = self.int_value) mi_obj = cgmMeta.cgmObject(name = "TestObj_%s"%i) #now we store... self.md_idxToObj[i] = mi_obj self.md_shortNameToIdx[mi_obj.p_nameShort] = i self.log_debug("Just built '%s'"%mi_obj.p_nameShort) if self.b_testException: self.log_warning("Test exception warning") self.log_error("Test exception error") raise Exception,"Just throwing this out there..."
def __init__(self, node='', makeAimable=True, controlRO=False): """ Asserts objects existance and that it has a transform. Then initializes. Keyword arguments: obj(string) makeAimable(bool) -- whether to set up aim controls """ self.i_object = cgmMeta.cgmObject(node) self.mirrorObject = False """
def __init__(self,node = '',makeAimable = True, controlRO = False): """ Asserts objects existance and that it has a transform. Then initializes. Keyword arguments: obj(string) makeAimable(bool) -- whether to set up aim controls """ self.i_object = cgmMeta.cgmObject(node) self.mirrorObject = False """
def constrainToParentModule(self): """ Pass a module class. Constrains template root to parent's closest template object """ log.debug(">>> constrainToParentModule") if not self.isTemplated(): log.error("Must be template state to contrainToParentModule: '%s' "%self.getShortName()) return False if not self.getMessage('moduleParent'): return False else: log.debug("looking for moduleParent info") i_templateNull = self.templateNull #Link i_parent = self.moduleParent #Link parentState = i_parent.getState() if i_parent.isTemplated():#If the parent has been templated, it makes things easy log.debug("Parent has been templated...") parentTemplateObjects = i_parent.templateNull.getMessage('controlObjects') log.debug("parentTemplateObjects: %s"%parentTemplateObjects) closestObj = distance.returnClosestObject(i_templateNull.getMessage('root')[0],parentTemplateObjects) log.debug("closestObj: %s"%closestObj) if parentTemplateObjects.index(closestObj) == 0:#if it's the first object, connect to the root log.info('Use root for parent object') closestObj = i_parent.templateNull.root.mNode #Find the closest object from the parent's template object log.debug("closestObj: %s"%closestObj) l_constraints = cgmMeta.cgmObject(i_templateNull.root.parent).getConstraintsTo() if cgmMeta.cgmObject(i_templateNull.root.parent).isConstrainedBy(closestObj): log.debug("Already constrained!") return True elif l_constraints:mc.delete(l_constraints) return constraints.doConstraintObjectGroup(closestObj,group = i_templateNull.root.parent,constraintTypes=['point']) else: log.debug("Parent has not been templated...") return False
def _copyPivot(self): copyPivot = self.d_kws['copyPivot'] if copyPivot is not None: try: if issubclass(type(copyPivot),cgmMeta.cgmNode): i_target = copyPivot elif mc.objExists(copyPivot): i_target = cgmMeta.cgmObject(copyPivot) else: raise StandardError,"Failed to find suitable copyTransform object: '%s"%copyPivot #Need to move this to default cgmNode stuff self.mi_control.doCopyPivot(i_target.mNode) except Exception,error:raise StandardError,"copyPivot | %s"%error
def duplicateJointChain(joint): mJoint = cgmMeta.cgmObject(joint) ml_joints = [mJoint] ml_children = mJoint.getAllChildren(fullPath=True, asMeta=True) ml_children.reverse() if ml_children: ml_joints.extend(ml_children) ml_dups = [] for i,mObj in enumerate(ml_joints): mDup = cgmMeta.cgmObject(mc.joint()) mc.delete(mc.parentConstraint(mObj.mNode,mDup.mNode)) mDup.rotateOrder = mObj.rotateOrder mDup.jointOrient = mObj.jointOrient mc.rename(mDup.mNode, mObj.getBaseName()) if i is 0: mDup.parent = mObj.parent else: mDup.parent = ml_dups[-1] ml_dups.append(mDup) return [ml_dups[0].mNode]
def __init__(self, group, chooseAttr='switcher', controlObject=None, connectTo='visibility', *args, **kws): """Constructor""" self.d_iAttrs = {} #attr instances stores as {index:instance} self.l_iAttrs = [] #Indices for iAttrs self.d_resultNetworksToBuild = { } #Index desctiptions of networks to build {target:[[1,2],3]} self.i_group = False self.i_control = False self.connectToAttr = connectTo self.i_attr = False #>>>Keyword args log.debug(">>> build_conditionNetworkFromGroup.__init__") if kws: log.debug("kws: %s" % str(kws)) if args: log.debug("args: %s" % str(args)) #Check our group if not mc.objExists(group): log.error("Group doesn't exist: '%s'" % group) return elif not search.returnObjectType(group) == 'group': log.error("Object is not a group: '%s'" % search.returnObjectType(group)) return self.i_group = cgmMeta.cgmObject(group) if not self.i_group.getChildren(): log.error("No children detected: '%s'" % group) return #Check our control if controlObject is None or not mc.objExists(controlObject): log.error("No suitable control object found: '%s'" % controlObject) return else: i_controlObject = cgmMeta.cgmNode(controlObject) self.i_attr = cgmMeta.cgmAttr(i_controlObject, chooseAttr, attrType='enum', initialValue=1) if self.buildNetwork(*args, **kws): log.debug("Chooser Network good to go")
def test_validateObjArg(self): null = mc.group(em=True) i_node = cgmMeta.cgmNode(nodeType='transform') i_obj = cgmMeta.cgmObject(nodeType='transform') self.assertRaises(ValueError, cgmMeta.validateObjArg, arg=None) self.assertEqual(i_obj, cgmMeta.validateObjArg(i_obj.mNode)) #...string arg self.assertEqual(i_obj, cgmMeta.validateObjArg(i_obj)) #...intance arg i_obj = cgmMeta.validateObjArg(i_obj.mNode, 'cgmObject', setClass=True) self.assertEqual(issubclass(type(i_obj), cgmMeta.cgmObject), True) #...String + mType self.assertEqual(i_obj, cgmMeta.validateObjArg( i_obj, 'cgmObject')) #...Instance + mType self.assertEqual( issubclass(type(cgmMeta.validateObjArg(null)), cgmMeta.cgmNode), True) #...null string failed i_null = cgmMeta.validateObjArg(null, 'cgmObject') self.assertEqual(issubclass(type(i_null), cgmMeta.cgmObject), True) #..."Null as cgmObject _objs = [ mc.joint(), mc.group(em=True), mc.createNode('multiplyDivide', name='multiplyDivideValideObjArg') ] for i, obj in enumerate(_objs): if i == 2: self.assertRaises(ValueError, cgmMeta.validateObjArg, obj, 'cgmObject') mc.delete(obj) #issubclass(type(n1),cgmMeta.cgmNode),True, type(n1)) else: n1 = cgmMeta.validateObjArg(obj, 'cgmObject') self.assertEqual(issubclass(type(n1), cgmMeta.cgmObject), True, type(n1)) n1.delete()
def build(self):#================================================================================ #>>>Create joint chains #============================================================= try: #>>Rig chain #===================================================================== l_rigJoints = mc.duplicate(self._go._l_skinJoints,po=True,ic=True,rc=True) ml_rigJoints = [] for i,j in enumerate(l_rigJoints): i_j = cgmMeta.cgmObject(j) i_j.addAttr('cgmTypeModifier','rig',attrType='string',lock=True) i_j.doName() l_rigJoints[i] = i_j.mNode ml_rigJoints.append(i_j) ml_rigJoints[0].parent = False#Parent to deformGroup self._go._i_rigNull.msgList_connect(ml_rigJoints,'rigJoints',"rigNull") except Exception,error: log.error("build_rigSkeleton>>Build rig joints fail!") raise Exception,error
def build_fkJoints(self): ml_fkJoints = [] for i, i_ctrl in enumerate( self._go._i_templateNull.msgList_get('controlObjects')): if not i_ctrl.getMessage('handleJoint'): raise Exception, "%s.build_rigSkeleton>>> failed to find a handle joint from: '%s'" % ( self._go._mi_module.getShortName(), i_ctrl.getShortName()) i_new = cgmMeta.cgmObject( (i_ctrl.getMessage('handleJoint')[0])).doDuplicate() i_new.addAttr('cgmTypeModifier', 'fk', attrType='string', lock=True) i_new.doName() if ml_fkJoints: #if we have data, parent to last i_new.parent = ml_fkJoints[-1] else: i_new.parent = False i_new.rotateOrder = self._go._jointOrientation #<<<<<<<<<<<<<<<<This would have to change for other orientations ml_fkJoints.append(i_new) ml_fkJoints[-1].addAttr('cgmName', 'clavicleEnd') ml_fkJoints[-1].doName() try: if self._go._str_mirrorDirection == 'Right': #mirror control setup #ml_fkDriverJoints = self._go.duplicate_jointChain(ml_fkJoints,'fkAttach','fkAttachJoints') self._go.mirrorChainOrientation(ml_fkJoints) #Mirror """ for i,mJoint in enumerate(ml_fkJoints): log.info("Mirror connect: %s | %s"%(i,mJoint.p_nameShort)) mJoint.connectChildNode(ml_fkDriverJoints[i],"attachJoint","rootJoint") cgmMeta.cgmAttr(mJoint.mNode,"rotateOrder").doConnectOut("%s.rotateOrder"%ml_fkDriverJoints[i].mNode) """ except Exception, error: raise Exception, "Failed to create mirror chain | %s" % error
def _create(self): #Get our l_eps = self.d_info['l_eps'] l_cvs = self.d_info['l_cvs'] int_cvCount = len(l_cvs) #l_locs = locators.locMeCVsOnCurve(self.mi_crv.mNode) self.progressBar_setMaxStepValue(int_cvCount) for i, cv in enumerate(l_cvs): try: #Loc loop self.progressBar_iter(status=cv, step=i) #create it v_pos = p = mc.pointPosition(cv) str_loc = mc.spaceLocator()[0] mi_loc = cgmMeta.cgmObject(str_loc) mi_loc.translate = v_pos #self.d_info['ml_locators'].append(mi_loc) #aim it self.d_info['l_constraints'].append( mc.aimConstraint(self.mi_target.mNode, str_loc, maintainOffset=False, weight=1, aimVector=[0, 0, -1], upVector=[0, 1, 0], worldUpVector=[0, 1, 0], worldUpType='scene')[0]) #move mc.move(0, 0, self.f_offset, str_loc, r=True, os=True) #Get pos self.d_info['l_locPos'].append(mi_loc.getPosition()) mi_loc.delete() except Exception, error: raise StandardError, "Loc creation %s | %s" % (cv, error)
from cgm.core import cgm_Meta as cgmMeta #============================================================================================== #>> cgmMeta.cgmObject #============================================================================================== from cgm.core import cgm_Meta as cgmMeta import maya.cmds as mc import copy #Let's start by making a series of objects #>>Parenting ==================================================================================== #First we're gonna make some objects to deal with, say 5 ml_cgmObjects = [] for i in range(5): mObj= cgmMeta.cgmObject(mc.joint(p = [0,0,2*i],name = 'generatedCGMObject_%i'%i)) ml_cgmObjects.append(mObj) #Neat,now we have a few joints to play with...let's play ml_cgmObjects[1].p_parent = False #We're gonna parent the idx 1 joint to the world by passing it false for mObj in ml_cgmObjects:mObj.p_parent = False #Let's parent them all to the world for i,mObj in enumerate(ml_cgmObjects[1:]):mObj.p_parent = ml_cgmObjects[i] #Parent em back #What if we wanted to parent idx 2 and 3 both to 1? ml_cgmObjects[2].p_parent = ml_cgmObjects[0]#We can pass the mClass ml_cgmObjects[2].tx = 2#just to be a little clearer ml_cgmObjects[4].p_parent = ml_cgmObjects[1].mNode#We can pass the string mNode ml_cgmObjects[1].tx = -2 #and a little more clear ml_cgmObjects[4].tx = 0 #and a little more clear
for mObj in cgmMeta.validateObjListArg(_l): if mObj.hasAttr('scaleJoint'): continue _good.append(mObj.mNode) mc.select(_good) #>>.Fixes ======================================================================= for m in 'l_eyelids_part','r_eyelids_part': mMod = cgmMeta.asMeta(m) mMod.helper.uprLidJoints = 12 mMod.helper.lwrLidJoints = 12 #mMod.doDeleteSkeleton() mMod.doSkeletonize() mHead = cgmMeta.cgmObject('head_jnt') for mChild in mHead.getChildren(asMeta=True): mChild.parent = mHead.scaleJoint for m in 'l_eye_part','l_eyelids_part','r_eye_part','r_eyelids_part': mMod = cgmMeta.asMeta(m) Rig.go(mMod,forceNew=False,autoBuild = True)#call to do general rig mMod.rigConnect() for m in 'l_leg_part','r_leg_part': mMod = cgmMeta.asMeta(m) Rig.go(mMod,forceNew=False,autoBuild = True)#call to do general rig mMod.rigConnect() for m in 'l_clav_part','l_arm_part','r_clav_part','r_arm_part': mMod = cgmMeta.asMeta(m)
import maya.cmds as mc from cgm.core import cgm_Meta as cgmMeta from cgm.core import cgm_PuppetMeta as cgmPM import Red9.core.Red9_Meta as r9Meta from cgm.core import cgm_General as cgmGeneral import cgm.core cgm.core._reload() from cgm.core import cgm_Meta as cgmMeta obj = mc.ls(sl=True)[0] or False obj = '' objList = [] orientation = ['xyz'] orientation[1] cgmMeta.cgmObject(mc.ls(sl=True)[0]).doName() mi_obj = cgmMeta.cgmObject(obj) cgmMeta.validateObjArg(mi_obj,cgmMeta.cgmObject) cgmMeta.validateObjArg(mi_obj) cgmMeta.validateAttrArg([mi_obj,'tx']) cgmMeta.validateAttrArg([obj,'tx']) cgmMeta.validateAttrArg("%s.tx"%obj) from cgm.core import cgm_Meta as cgmMeta n1 = cgmMeta.cgmNode(nodeType='transform')#This will create a cgmNode instance of a new transform node
mi_endLoc.__setattr__('t%s'%latheAxis,-(distanceToMove*insetMult)) log.debug("segment lathe: %s"%latheAxis) log.debug("segment aim: %s"%aimAxis) log.debug("segment rotateBank: %s"%rotateBank) d_endCastInfo = createMeshSliceCurve(targetGeo,mi_endLoc,midMeshCast=midMeshCast,curveDegree=curveDegree,latheAxis=latheAxis,aimAxis=aimAxis,posOffset = posOffset,points = points,returnDict=True,closedCurve = closedCurve, maxDistance = maxDistance, closestInRange=closestInRange, rotateBank=rotateBank, l_specifiedRotates = l_specifiedRotates,axisToCheck = axisToCheck) l_sliceReturns.append(d_endCastInfo) mi_end = cgmMeta.cgmObject(d_endCastInfo['curve']) il_curvesToCombine.append(mi_end) mc.delete(mi_endLoc.parent)#delete the loc except StandardError,error: raise StandardError,"createWrapControlShape>> segment wrap fail! | %s"%error elif extendMode == 'radial': d_handleInner = createMeshSliceCurve(targetGeo,mi_rootLoc,midMeshCast=midMeshCast,curveDegree=curveDegree,latheAxis=latheAxis,aimAxis=aimAxis,posOffset = 0,points = points,returnDict=True,closedCurve = closedCurve, maxDistance = maxDistance, closestInRange=closestInRange, rotateBank=rotateBank, l_specifiedRotates = l_specifiedRotates,axisToCheck = axisToCheck) mi_buffer = cgmMeta.cgmObject(d_handleInner['curve'])#instance curve l_sliceReturns.append(d_handleInner) il_curvesToCombine.append(mi_buffer) elif extendMode == 'disc': log.debug("disc mode") d_size = returnBaseControlSize(mi_rootLoc,targetGeo,axis=[aimAxis])#Get size #discOffset = d_size[ d_size.keys()[0]]*insetMult size = False l_absSize = [abs(i) for i in posOffset] if l_absSize:size = max(l_absSize) if not size: d_size = returnBaseControlSize(mi_rootLoc,targetGeo,axis=[aimAxis])#Get size log.debug("d_size: %s"%d_size) size = d_size[ d_size.keys()[0]]*insetMult
from cgm.lib import locators from cgm.lib import distance from cgm.lib import joints reload(distance) from cgm.core.rigger.lib import rig_Utils as rUtils from cgm.core.cgmPy import str_Utils as strUtils reload(strUtils) from cgm.core.rigger.lib import joint_Utils as jUtils for i_jnt in cgmMeta.validateObjListArg(mc.ls(sl=True), cgmMeta.cgmObject, mayaType='joint'): jUtils.metaFreezeJointOrientation(i_jnt) reload(rUtils) from cgm.core.classes import NodeFactory as NodeF reload(NodeF) obj = mc.ls(sl=True)[0] or False obj = '' objList = [] objList = mc.ls(sl=True) cgmMeta.cgmObject(obj).createTransformFromObj() _str = "5_asdfasdf<><" _str = "dog -1 * 3" strUtils.stripInvalidChars(_str) _str.startswith('0') #>>> Stretch IK #======================================================= reload(crvUtils) crv = 'uprLid_rigHelper' crvUtils.returnSplitCurveList(crv, 5, markPoints=True, rebuildForSplit=True)
#============================================================================================== from cgm.core import cgm_Meta as cgmMeta import maya.cmds as mc import copy #>>Setup ==================================================================================== ''' We need to create some objects to do our initial tests with ''' if not mc.objExists('nurbsSphere1'):mc.sphere(r=10) if not mc.objExists('pSphere1'):mc.polySphere(r=10) str_mesh = 'pSphere1' str_surface = 'nurbsSphere1' #Make a curve from our library so we can more sensibly see our cast direction.We'll be casting from z+ mi_aimObj = cgmMeta.cgmObject(curves.createControlCurve('arrowSingleFat3d',5,'y-')) #Aim #mc.delete(mc.aimConstraint('pSphere1', mi_loc.mNode)) #This is gonna be our dict reporter def report_dict(d): for k in d.keys(): print ("# {0} | {1}".format(k,d[k])) #=============================================================================================== #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #>>RayCast Functions ============================================================================================= #Gonna start with some functions found in cgm.core.lib.rayCaster #findMeshIntersectionFromObjectAxis ==============================================================
from cgm.core import cgm_PuppetMeta as cgmPM import Red9.core.Red9_Meta as r9Meta from cgm.lib import locators from cgm.lib import distance reload(distance) from cgm.core.lib import rayCaster as RayCast reload(RayCast) obj = mc.ls(sl=True)[0] or False obj = '' objList = [] #>>> Distance #======================================================= i_obj = cgmMeta.cgmObject(mc.ls(sl=True)[0]) i_obj.getPosition() mesh = 'Morphy_Body_GEO' RayCast.findMeshIntersectionFromObjectAxis(mesh,i_obj.mNode) info = RayCast.findMeshIntersectionFromObjectAxis(mesh,i_obj.mNode,vector = [0,-1,0]) log.info(info) info = distance.findMeshIntersection(mesh,i_obj.getPosition(), vector) vector = [matrix[9],matrix[10],matrix[11]] vector = [matrix[8],matrix[9],matrix[10]]#Z vector = [-matrix[8],-matrix[9],-matrix[10]]#Z RayCast.findMeshIntersectionFromObjectAxis(mesh,i_obj.mNode,axis = 'z-') locators.doLocPos(info['hit']) for axis in ['x+','x-','z+','z-']: locators.doLocPos(RayCast.findMeshIntersectionFromObjectAxis(mesh,i_obj.mNode,axis = axis)['hit']) matrix = mc.xform(i_obj.mNode, q=True, matrix=True, worldSpace=True)
def register( controlObject=None, #(mObject - None) -- The object to use as a control typeModifier=None, #(string - None) -- Tag for cgmTypeModifier for naming copyTransform=None, #(mObject - None) -- Object to copy the transform of for our control object copyPivot=None, #(mObject - None) -- Object to copy the pivot of for our control object shapeParentTo=None, #'(mObject - None) -- Object to shape parent our control curve to to use that transform useShape=None, #'(mObject - None) -- Object to use the curve shape of for our control setRotateOrder=None, #'(rotateOrder - None) -- Argument for a rotate order to set autoLockNHide=None, #'(bool - None) -- Try to set lock and hide mirrorAxis=None, #'(string - None) -- Mirror axis to set - using red9's setup terms mirrorSide=None, #'(string/int - None) -- Mirror side - using red9's setup terms makeMirrorable=True, #'(bool - True) -- Setup for mirrorability (using red9) -- implied by other mirror args addDynParentGroup=False, #'(False) -- Add a dynParent group setup addExtraGroups=False, #'(int - False) -- Number of nested extra groups desired addConstraintGroup=False, #'(bool - False) -- If a group just above the control is desired for consraining freezeAll=False, #'(bool - False) -- Freeze all transforms on the control object noFreeze=False, addSpacePivots=False, #'(int - False) -- Number of space pivots to generate and connect controlType=None, #'(string - None) -- Tag for cgmType aim=None, #'(string/int - None) -- aim axis to use up=None, #'(string/int - None) -- up axis to use out=None, #'(string/int - None) -- out axis to use makeAimable=None, #'(mObject - False) -- Make object aimable -- implied by aim/up/out): **kws): _str_func = 'register' """ [{'step':'validate','call':self._validate}, {'step':'Copy Transform','call':self._copyTransform}, {'step':'Shape Parent','call':self._shapeParent}, {'step':'Copy Pivot','call':self._copyPivot}, {'step':'Naming','call':self._naming}, {'step':'Aim Setup','call':self._aimSetup}, {'step':'Rotate Order','call':self._rotateOrder}, {'step':'Initial Freeze','call':self._initialFreeze}, {'step':'Groups Setup','call':self._groupsSetup}, {'step':'Space Pivot','call':self._spacePivots}, {'step':'Mirror Setup','call':self._mirrorSetup}, {'step':'Freeze','call':self._freeze}, {'step':'Mirror Attribute Bridges','call':self._mirrorAttributeBridges_}, {'step':'lock N Hide','call':self._lockNHide}, {'step':'Return build','call':self._returnBuild}] """ try: #Validate ================================================================================================ mi_control = cgmMeta.validateObjArg(controlObject, 'cgmControl', setClass=True) str_mirrorAxis = VALID.stringArg(mirrorAxis, calledFrom=_str_func) str_mirrorSide = cgmGeneral.verify_mirrorSideArg( mirrorSide) #VALID.stringArg(mirrorSide,calledFrom = _str_func) b_makeMirrorable = VALID.boolArg(makeMirrorable, calledFrom=_str_func) _addMirrorAttributeBridges = kws.get('addMirrorAttributeBridges', False) addForwardBack = kws.get('addForwardBack', False) if _addMirrorAttributeBridges: if type(_addMirrorAttributeBridges) not in [list, tuple]: raise ValueError, "[Bad addMirrorAttributeBridge arg]{arg: %s}" % _addMirrorAttributeBridge for i, l in enumerate(_addMirrorAttributeBridges): if type(l) not in [list, tuple]: raise ValueError, "[Bad addMirrorAttributeBridge arg: %s]{arg: %s}" % ( i, l) # Running lists ------------------------------------------------------------------------------------------ ml_groups = [] #Holder for groups ml_constraintGroups = [] ml_spacePivots = [] #Copy Transform ================================================================================================ if copyTransform is not None: mTarget = cgmMeta.validateObjArg(copyTransform, 'cgmObject', noneValid=True) if not mTarget: raise StandardError, "Failed to find suitable copyTransform object: '%s" % copyTransform #Need to move this to default cgmNode stuff mBuffer = mi_control i_newTransform = cgmMeta.cgmObject( rigging.groupMeObject(mTarget.mNode, False)) for a in mc.listAttr(mi_control.mNode, userDefined=True): ATTR.copy_to(mi_control.mNode, a, i_newTransform.mNode) curves.parentShapeInPlace(i_newTransform.mNode, mi_control.mNode) #Parent shape i_newTransform.parent = mi_control.parent #Copy parent mi_control = cgmMeta.asMeta(i_newTransform, 'cgmControl', setClass=True) mc.delete(mBuffer.mNode) #ShapeParent ================================================================================================ if shapeParentTo: i_target = cgmMeta.validateObjArg(shapeParentTo, 'cgmObject') CORERIG.shapeParent_in_place(i_target.mNode, mi_control.mNode) i_target = cgmMeta.asMeta(i_target, 'cgmControl', setClass=True) #mi_control.delete() mi_control = i_target #replace the control with the joint if useShape is not None: i_shape = cgmMeta.validateObjArg(useShape, cgmMeta.cgmObject, mayaType='nurbsCurve') curves.parentShapeInPlace(mi_control.mNode, i_shape.mNode) #Copy Pivot ============================================================================================ if copyPivot is not None: if issubclass(type(copyPivot), cgmMeta.cgmNode): i_target = copyPivot elif mc.objExists(copyPivot): i_target = cgmMeta.cgmObject(copyPivot) else: raise StandardError, "Failed to find suitable copyTransform object: '%s" % copyPivot #Need to move this to default cgmNode stuff mi_control.doCopyPivot(i_target.mNode) #Naming ============================================================================================ mi_control.addAttr('cgmType', 'controlAnim', lock=True) if typeModifier is not None: mi_control.addAttr('cgmTypeModifier', str(typeModifier), lock=True) mi_control.doName() #mi_control.doName(nameShapes=True) #Rotate Order ============================================================================================ _rotateOrder = False if setRotateOrder is not None: _rotateOrder = setRotateOrder elif controlType in __d_rotateOrderDefaults__.keys(): _rotateOrder = __d_rotateOrderDefaults__[controlType] elif mi_control.getAttr('cgmName') in __d_rotateOrderDefaults__.keys(): _rotateOrder = __d_rotateOrderDefaults__[mi_control.getAttr( 'cgmName')] else: log.debug("|{0}| >> Rotate order not set on: {1}".format( _str_func, mi_control.p_nameShort)) #Set it --------------------------------------------------------------- if _rotateOrder: mRotateOrder = VALID.simpleOrientation(_rotateOrder) #dictionary.validateRotateOrderString(_rotateOrder) mc.xform(mi_control.mNode, rotateOrder=mRotateOrder.p_string) #Initial Freeze ============================================================================================ if freezeAll: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0) #Groups ============================================================================================ if addDynParentGroup or addSpacePivots or mi_control.getAttr( 'cgmName') == 'cog' or _addMirrorAttributeBridges: mi_control.addAttr('________________', attrType='int', keyable=False, hidden=False, lock=True) ATTR.reorder(mi_control.mNode, '________________', top=True) #Aim Setup ============================================================================================ if aim is not None or up is not None or makeAimable: mi_control._verifyAimable() #First our master group: i_masterGroup = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) i_masterGroup.doStore('cgmName', mi_control) i_masterGroup.addAttr('cgmTypeModifier', 'master', lock=True) i_masterGroup.doName() mi_control.connectChildNode(i_masterGroup, 'masterGroup', 'groupChild') if addDynParentGroup: i_dynGroup = (cgmMeta.cgmObject(mi_control.doGroup(True))) i_dynGroup = cgmRigMeta.cgmDynParentGroup(dynChild=mi_control, dynGroup=i_dynGroup) i_dynGroup.doName() """ i_zeroGroup = (cgmMeta.cgmObject(mi_control.doGroup(True))) i_zeroGroup.addAttr('cgmTypeModifier','zero',lock=True) i_zeroGroup.doName() mi_control.connectChildNode(i_zeroGroup,'zeroGroup','groupChild')""" if addExtraGroups: for i in range(addExtraGroups): i_group = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) if type( addExtraGroups ) == int and addExtraGroups > 1: #Add iterator if necessary i_group.addAttr('cgmIterator', str(i + 1), lock=True) i_group.doName() ml_groups.append(i_group) mi_control.msgList_connect("extraGroups", ml_groups, 'groupChild') if addConstraintGroup: #ConstraintGroups i_constraintGroup = (cgmMeta.asMeta(mi_control.doGroup(True), 'cgmObject', setClass=True)) i_constraintGroup.addAttr('cgmTypeModifier', 'constraint', lock=True) i_constraintGroup.doName() ml_constraintGroups.append(i_constraintGroup) mi_control.connectChildNode(i_constraintGroup, 'constraintGroup', 'groupChild') #Space Pivot ============================================================================================ if addSpacePivots: parent = mi_control.getMessage('masterGroup')[0] for i in range(int(addSpacePivots)): #i_pivot = rUtils.create_spaceLocatorForObject(mi_control.mNode,parent) i_pivot = SPACEPIVOTS.create(mi_control.mNode, parent) ml_spacePivots.append(i_pivot) #log.info("spacePivot created: {0}".format(i_pivot.p_nameShort)) #Mirror Setup ============================================================================================ if str_mirrorSide is not None or b_makeMirrorable: for mObj in [mi_control] + ml_spacePivots: mi_control._verifyMirrorable() l_enum = cgmMeta.cgmAttr(mi_control, 'mirrorSide').p_enum if str_mirrorSide in l_enum: #log.debug("|{0}| >> Rotate order not set on: {1}".format(_str_func,mi_control.p_nameShort)) #log.debug("%s >> %s >> found in : %s"%(_str_funcCombined, "mirrorSetup", l_enum)) mi_control.mirrorSide = l_enum.index(str_mirrorSide) if str_mirrorAxis: mi_control.mirrorAxis = str_mirrorAxis for mObj in mi_control.msgList_get('spacePivots'): mObj._verifyMirrorable() mi_control.doConnectOut('mirrorAxis', mObj.mNode + '.mirrorAxis') mi_control.doConnectOut('mirrorSide', mObj.mNode + '.mirrorSide') #cgmMeta.cgmAttr(mObj,'mirrorSide').doConnectIn(mi_control,'mirrorSide') #cgmMeta.cgmAttr(mi_control,'mirrorAxis').doCopyTo(mObj,connectTargetToSource = 1) #ATTR.connect(mObj.mNode + '.mirrorAxis',"{0}.mirrorAxis".format(mi_control.mNode)) #ATTR.connect(mObj.mNode + 'mirrorSide',"{0}.mirrorSide".format(mi_control.mNode)) #Freeze ============================================================================================ if not shapeParentTo and noFreeze is not True: if not freezeAll: if mi_control.getAttr( 'cgmName' ) == 'cog' or controlType in __l_fullFreezeTypes__: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0) else: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=0, s=1, n=0) else: mc.makeIdentity(mi_control.mNode, apply=True, t=1, r=1, s=1, n=0) #Mirror attriubte Bridges ========================================================================== if addForwardBack: mPlug_forwardBackDriver = cgmMeta.cgmAttr(mi_control, "forwardBack", attrType='float', keyable=True) try: mPlug_forwardBackDriven = cgmMeta.validateAttrArg( [mi_control, addForwardBack])['mi_plug'] except Exception, error: raise StandardError, "push pull driver | %s" % (error) if str_mirrorSide.lower() == 'right': arg_forwardBack = "%s = -%s" % ( mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) else: arg_forwardBack = "%s = %s" % ( mPlug_forwardBackDriven.p_combinedShortName, mPlug_forwardBackDriver.p_combinedShortName) mPlug_forwardBackDriven.p_locked = True mPlug_forwardBackDriven.p_hidden = True mPlug_forwardBackDriven.p_keyable = False NodeF.argsToNodes(arg_forwardBack).doBuild() if _addMirrorAttributeBridges: for l_bridge in _addMirrorAttributeBridges: _attrName = VALID.stringArg(l_bridge[0]) _attrToBridge = VALID.stringArg(l_bridge[1]) if not mi_control.hasAttr(_attrToBridge): raise StandardError, "['%s' lacks the bridge attr '%s']" % ( mi_control.p_nameShort, _attrToBridge) mPlug_attrBridgeDriver = cgmMeta.cgmAttr(mi_control, _attrName, attrType='float', keyable=True) try: mPlug_attrBridgeDriven = cgmMeta.validateAttrArg( [mi_control, _attrToBridge])['mi_plug'] except Exception, error: raise StandardError, "[validate control attribute bridge attr]{%s}" % ( error) if str_mirrorSide.lower() == 'right': arg_attributeBridge = "%s = -%s" % ( mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) else: arg_attributeBridge = "%s = %s" % ( mPlug_attrBridgeDriven.p_combinedShortName, mPlug_attrBridgeDriver.p_combinedShortName) mPlug_attrBridgeDriven.p_locked = True mPlug_attrBridgeDriven.p_hidden = True mPlug_attrBridgeDriven.p_keyable = False NodeF.argsToNodes(arg_attributeBridge).doBuild()
def __init__(self,obj,targets = [],move = True, orient = False, aim = False, pos = [], snapToSurface = False, midSurfacePos = False, posOffset = False, aimVector = [0,0,1],upVector = [0,1,0], worldUpType = 'scene', snapComponents = False,softSelection = False, softSelectDistance = 20, mode = None,**kws): """ Asserts objects existance and that it has a transform. Then initializes. Keyword arguments: obj(string/instance) targets(list) -- target objects snapToSurface -- if target is a snappable surface will try to do that posOffset snapComponents(bool) -- will try to use components if True aimVector(vector) -- aim vector for object upVector(vector) -- up vector for object (used as lathe axis for midpoint surface snap too) midSurfacePos(bool) -- mid point snap with a surface worldUpType(string) -- arg for various modes (aim, orient, etc) softSelection(bool) -- soft select mode for component objects only softSelectDistance(float) -- arg for mc.softSelect ToDo: 1) midSurfacePos """ #>>> Check our obj log.debug("obj: %s"%obj) log.debug("targets: %s"%targets) if issubclass(type(obj),cgmMeta.cgmNode): self.i_obj = obj else: i_node = cgmMeta.cgmNode(obj) if i_node.isComponent(): self.i_obj = i_node else : self.i_obj = cgmMeta.cgmObject(obj) assert self.i_obj.isTransform() or self.i_obj.isComponent(),"Not a snappable object. Not a transform: '%s"%self.i_obj.getShortName() #>>> Pass through args self.b_snaptoSurface = snapToSurface self.b_midSurfacePos = midSurfacePos self.b_snapComponents = snapComponents self.b_softSelection = softSelection self.b_midSurfacePos = midSurfacePos self.b_aim = aim self._softSelectionDistance = softSelectDistance, self._posOffset = posOffset self._aimVector = aimVector self._upVector = upVector self._worldUpType = worldUpType #>>> Check our targets if targets and not type(targets)==list:targets=[targets] self.l_targets = [] self.d_targetTypes = {} self.d_targetPositions = {} for t in targets: self.registerTarget(t) if not self.l_targets: log.error("No existing targets found") return if self.b_softSelection: #Should we save soft select info before changing? mc.softSelect(softSelectDistance = softSelectDistance) mc.softSelect(softSelectFalloff = 0) log.debug("targetTypes: %s"%self.d_targetTypes) if move: log.debug("Moving") self.doMove(**kws) if orient: log.debug("orienting") self.doOrient(**kws) if aim: log.debug("orienting") self.doAim(**kws)
mc.select(cl=True) else: nameBuffer = mc.spaceLocator()[0] mc.move (pos[0],pos[1],pos[2], nameBuffer) for m in self.d_meshPos.keys():#check each mesh dictionary to see where it came from if pos in self.d_meshPos[m]:#if the mesh has a match attributes.storeInfo(nameBuffer,'cgmHitTarget',m) #attributes.doSetAttr(nameBuffer,'localScaleX',(self.f_meshArea*.025)) #attributes.doSetAttr(nameBuffer,'localScaleY',(self.f_meshArea*.025)) #attributes.doSetAttr(nameBuffer,'localScaleZ',(self.f_meshArea*.025)) if self.v_posOffset is not None and self.v_posOffset and nameBuffer and self.str_offsetMode and self._createMode not in ['follicle']: mi_obj = cgmMeta.cgmObject(nameBuffer) mc.move (pos[0],pos[1],pos[2], mi_obj.mNode,ws=True) if self.str_offsetMode =='vector': mi_hitLoc = cgmMeta.cgmObject(mc.spaceLocator(n='hitLoc')[0]) mc.move (self.startPoint[0],self.startPoint[1],self.startPoint[2], mi_hitLoc.mNode,ws=True) constBuffer = mc.aimConstraint(mi_hitLoc.mNode,mi_obj.mNode, aimVector=[0,0,1], upVector=[0,1,0], worldUpType = 'scene') mi_hitLoc.delete() else: constBuffer = mc.normalConstraint(m,mi_obj.mNode, aimVector=[0,0,1], upVector=[0,1,0], worldUpType = 'scene') try:mc.delete(constBuffer)
""" from cgm.core import cgm_Meta as cgmMeta #============================================================================================== #>> cgmMeta.cgmObject #============================================================================================== from cgm.core import cgm_Meta as cgmMeta import maya.cmds as mc #Let's start by making a series of objects #>>message Treatment ========================================================================= #We have made several changes to r9's stuff in how we do messages, it is however compatible with r9's stuff #One of our calls to store info is doStore #First we're gonna make a catcher node mi_catchMeObj = cgmMeta.cgmObject(name = 'catchMe') mi_catcherObj = cgmMeta.cgmObject(name = 'msgCather') #One of our calls to store info is doStore mi_catcherObj.doStore('objNoMessage',mi_catchMeObj.mNode,overideMessageCheck = True)#It's gonna just store a string, no message.... mi_catcherObj.doStore('objNoMessage',mi_catchMeObj.mNode,overideMessageCheck = False)#Now it's a message...woot! #So maya can do that, what if you wanted to do something neater like say, store an attribute mi_catcherObj.doStore('objTX',"%s.tx"%mi_catchMeObj.mNode)#It's gonna just store a string, no message.... mi_catchMeObj.tx = 4#our attribute changed. That's because, this storage method stores on a compatible attribute format #That's great and all, but we were talking about messages... mi_catcherObj.getMessage('objTX')# we get the attribute, neato... mi_catcherObj.getMessageAsMeta('objTX')# we get the attribute, neato...cgmAttr for the win #implementing attr setup to msgLists is on the ToDO list #============================================================================================== #>>Component use ==============================================================================
import maya.cmds as mc import Red9.core.Red9_Meta as r9Meta reload(r9Meta) from cgm.lib import curves from cgm.core.classes import SnapFactory as Snap reload(Snap) from cgm.core import cgm_Meta as cgmMeta reload(cgmMeta) obj = mc.ls(sl=True)[0] or False obj = '' objList = [] #>>> Modules #======================================================= i_obj = cgmMeta.cgmObject(mc.spaceLocator()[0]) i_obj = cgmMeta.cgmNode(obj) i_obj = cgmMeta.cgmNode(mc.ls(sl=True)[0]) i_obj.getComponents() i_obj.getComponent() a = i_obj i_obj.mNode i_obj.isTransform() Snap.go(i_obj) mc.xform(q_object, q=True, os=True, t = True) mc.xform(a.getComponent(), q=True, ws=True, rp=True) mc.pointPosition(a.getComponent()) cgmMeta.cgmNode(q_object).getPosition(True) cgmMeta.cgmNode(q_object).getPosition(False) i_obj = cgmMeta.cgmObject(mc.spaceLocator()[0]) Snap.go('hips_anim_shape1.ep[3]',targets = q_object,orient = False,posOffset=[0,0,2],
def doCreateOrientationHelpers(self): """ """ log.debug(">>> addOrientationHelpers") assert self.cls == 'TemplateFactory.go',"Not a TemlateFactory.go instance!" assert mc.objExists(self.m.mNode),"module no longer exists" #Gather limb specific data and check #=================================== #'orientHelpers':'messageSimple',#Orientation helper controls #'orientRootHelper':'messageSimple',#Root orienation helper helperObjects = [] helperObjectGroups = [] returnBuffer = [] root = self.i_templateNull.getMessage('root')[0] objects = self.i_templateNull.getMessage('controlObjects') log.debug(root) log.debug(objects) log.debug(self.foundDirections) #>> Create orient root control #============================= orientRootSize = (distance.returnBoundingBoxSizeToAverage(root,True)*2.5) i_orientRootControl = cgmMeta.cgmObject( curves.createControlCurve('circleArrow1',orientRootSize) ) i_orientRootControl.addAttr('mClass','cgmObject',lock=True) curves.setCurveColorByName(i_orientRootControl.mNode,self.moduleColors[0]) i_orientRootControl.addAttr('cgmName',value = str(self.m.getShortName()), attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug i_orientRootControl.addAttr('cgmType',value = 'templateOrientRoot', attrType = 'string', lock=True) i_orientRootControl.doName() #>>> Store it i_orientRootControl.connectParent(self.templateNull,'orientRootHelper','owner')#Connect it to it's object #>>> Position and set up follow groups position.moveParentSnap(i_orientRootControl.mNode,root) i_orientRootControl.parent = root #parent it to the root i_orientRootControl.doGroup(maintain = True)#group while maintainting position mc.pointConstraint(objects[0],i_orientRootControl.parent,maintainOffset = False)#Point contraint orient control to the first helper object mc.aimConstraint(objects[-1],i_orientRootControl.parent,maintainOffset = True, weight = 1, aimVector = [1,0,0], upVector = [0,1,0], worldUpObject = root, worldUpType = 'objectRotation' ) attributes.doSetLockHideKeyableAttr(i_orientRootControl.mNode,True,False,False,['tx','ty','tz','rx','ry','sx','sy','sz','v']) self.i_orientHelpers = []#we're gonna store the instances so we can get them all after parenting and what not #>> Sub controls #============================= if len(objects) == 1:#If a single handle module i_obj = cgmMeta.cgmObject(objects[0]) position.moveOrientSnap(objects[0],root) else: for i,obj in enumerate(objects): log.debug("on %s"%(mc.ls(obj,shortNames=True)[0])) #>>> Create and color size = (distance.returnBoundingBoxSizeToAverage(obj,True)*2) # Get size i_obj = cgmMeta.cgmObject(curves.createControlCurve('circleArrow2Axis',size))#make the curve i_obj.addAttr('mClass','cgmObject',lock=True) curves.setCurveColorByName(i_obj.mNode,self.moduleColors[1]) #>>> Tag and name i_obj.doCopyNameTagsFromObject(obj) i_obj.doStore('cgmType','templateOrientHelper',True) i_obj.doName() #>>> Link it to it's object and append list for full store i_obj.connectParent(obj,'helper','owner')#Connect it to it's object self.i_orientHelpers.append(i_obj) log.debug(i_obj.owner) #>>> initial snapping """ position.movePointSnap(i_obj.mNode,obj) if i < len(objects)-1:#If we have a pair for it, aim at that pairs aim, otherwise, aim at the second to last object constBuffer = mc.aimConstraint(objects[i+1],i_obj.mNode,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpVector = self.foundDirections[1], worldUpType = 'vector' ) else: constBuffer = mc.aimConstraint(objects[-2],i_obj.mNode,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpVector = self.foundDirections[1], worldUpType = 'vector' ) if constBuffer:mc.delete(constBuffer) #>>> follow groups i_obj.parent = obj i_obj.doGroup(maintain = True) if i < len(objects)-1:#If we have a pair for it, aim at that pairs aim, otherwise, aim at the second to last object mc.aimConstraint(objects[i+1],i_obj.parent,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpVector = [0,1,0], worldUpObject = i_orientRootControl.mNode, worldUpType = 'objectrotation' ) else: constBuffer = mc.aimConstraint(objects[-2],i_obj.parent,maintainOffset = False, weight = 1, aimVector = [0,0,-1], upVector = [0,1,0], worldUpObject = i_orientRootControl.mNode, worldUpType = 'objectrotation' ) #>>> ConnectVis, lock and hide #mc.connectAttr((visAttr),(helperObj+'.v')) if obj == objects[-1]: attributes.doSetLockHideKeyableAttr(i_obj.mNode,True,False,False,['tx','ty','tz','ry','sx','sy','sz','v']) else: attributes.doSetLockHideKeyableAttr(i_obj.mNode,True,False,False,['tx','ty','tz','rx','ry','sx','sy','sz','v']) #>>> Get data ready to go forward bufferList = [] for o in self.i_orientHelpers: bufferList.append(o.mNode) self.i_templateNull.orientHelpers = bufferList self.i_orientRootHelper = i_orientRootControl log.debug("orientRootHelper: [%s]"%self.i_templateNull.orientRootHelper.getShortName()) log.debug("orientHelpers: %s"%self.i_templateNull.getMessage('orientHelpers')) return True
def doMakeLimbTemplate(self): """ Self should be a TemplateFactory.go """ """ returnList = [] templObjNameList = [] templHandleList = [] """ log.debug(">>> doMakeLimbTemplate") assert self.cls == 'TemplateFactory.go',"Not a TemlateFactory.go instance!" #Gather limb specific data and check #============== doCurveDegree = getGoodCurveDegree(self) if not doCurveDegree:raise ValueError,"Curve degree didn't query" #>>>Scale stuff size = returnModuleBaseSize(self.m) lastCountSizeMatch = len(self.corePosList) -1 #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # Making the template objects #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> templHandleList = [] self.i_controlObjects = [] self.i_locs = [] for i,pos in enumerate(self.corePosList):# Don't like this sizing method but it is what it is for now #>> Make each of our base handles #============================= if i == 0: sizeMultiplier = 1 elif i == lastCountSizeMatch: sizeMultiplier = .8 else: sizeMultiplier = .75 #>>> Create and set attributes on the object i_obj = cgmMeta.cgmObject( curves.createControlCurve('sphere',(size * sizeMultiplier)) ) i_obj.addAttr('mClass','cgmObject',lock=True)#tag it so it can initialize later curves.setCurveColorByName(i_obj.mNode,self.moduleColors[0]) i_obj.addAttr('cgmName',value = str(self.l_coreNames[i]), attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug if self.direction != None: i_obj.addAttr('cgmDirection',value = self.direction,attrType = 'string',lock=True) i_obj.addAttr('cgmType',value = 'templateObject', attrType = 'string',lock=True) i_obj.doName()#Name it mc.move (pos[0], pos[1], pos[2], [i_obj.mNode], a=True) i_obj.parent = self.templateNull #>>> Loc it and store the loc #i_loc = cgmMeta.cgmObject( i_obj.doLoc() ) i_loc = i_obj.doLoc() i_loc.addAttr('mClass','cgmObject',lock=True)#tag it so it can initialize later i_loc.addAttr('cgmName',value = self.m.getShortName(), attrType = 'string', lock=True) #Add name tag i_loc.addAttr('cgmType',value = 'templateCurveLoc', attrType = 'string', lock=True) #Add Type i_loc.v = False # Turn off visibility i_loc.doName() self.i_locs.append(i_loc) i_obj.connectChildNode(i_loc.mNode,'curveLoc','owner') i_loc.parent = self.templateNull#parent to the templateNull mc.pointConstraint(i_obj.mNode,i_loc.mNode,maintainOffset = False)#Point contraint loc to the object templHandleList.append (i_obj.mNode) self.i_controlObjects.append(i_obj) #>> Make the curve #============================= i_crv = cgmMeta.cgmObject( mc.curve (d=doCurveDegree, p = self.corePosList , os=True) ) i_crv.addAttr('mClass','cgmObject',lock=True)#tag it so it can initialize later i_crv.addAttr('cgmName',value = str(self.m.getShortName()), attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug if self.direction != None: i_crv.addAttr('cgmDirection',value = self.direction, attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug i_crv.addAttr('cgmType',value = 'templateCurve', attrType = 'string', lock=True) curves.setCurveColorByName(i_crv.mNode,self.moduleColors[0]) i_crv.parent = self.templateNull i_crv.doName() i_crv.setDrawingOverrideSettings({'overrideEnabled':1,'overrideDisplayType':2},True) for i,i_obj in enumerate(self.i_controlObjects):#Connect each of our handles ot the cv's of the curve we just made mc.connectAttr ( (i_obj.curveLoc.mNode+'.translate') , ('%s%s%i%s' % (i_crv.mNode, '.controlPoints[', i, ']')), f=True ) self.foundDirections = returnGeneralDirections(self,templHandleList) log.debug("directions: %s"%self.foundDirections ) #>> Create root control #============================= rootSize = (distance.returnBoundingBoxSizeToAverage(templHandleList[0],True)*1.25) i_rootControl = cgmMeta.cgmObject( curves.createControlCurve('cube',rootSize) ) i_rootControl.addAttr('mClass','cgmObject',lock=True) curves.setCurveColorByName(i_rootControl.mNode,self.moduleColors[0]) i_rootControl.addAttr('cgmName',value = str(self.m.getShortName()), attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug i_rootControl.addAttr('cgmType',value = 'templateRoot', attrType = 'string', lock=True) if self.direction != None: i_rootControl.addAttr('cgmDirection',value = self.direction, attrType = 'string', lock=True)#<<<<<<<<<<<FIX THIS str(call) when Mark fixes bug i_rootControl.doName() #>>> Position it if self.m.moduleType in ['clavicle']: position.movePointSnap(i_rootControl.mNode,templHandleList[0]) else: position.movePointSnap(i_rootControl.mNode,templHandleList[0]) #See if there's a better way to do this log.debug("templHandleList: %s"%templHandleList) if self.m.moduleType not in ['foot']: if len(templHandleList)>1: log.info("setting up constraints...") constBuffer = mc.aimConstraint(templHandleList[-1],i_rootControl.mNode,maintainOffset = False, weight = 1, aimVector = [0,0,1], upVector = [0,1,0], worldUpVector = self.worldUpVector, worldUpType = 'vector' ) mc.delete (constBuffer[0]) elif self.m.getMessage('moduleParent'): #parentTemplateObjects = self.m.moduleParent.templateNull.getMessage('controlObjects') helper = self.m.moduleParent.templateNull.controlObjects[-1].helper.mNode if helper: log.info("helper: %s"%helper) constBuffer = mc.orientConstraint( helper,i_rootControl.mNode,maintainOffset = False) mc.delete (constBuffer[0]) i_rootControl.parent = self.templateNull i_rootControl.doGroup(maintain=True) #>> Store objects #============================= self.i_templateNull.curve = i_crv.mNode self.i_templateNull.root = i_rootControl.mNode self.i_templateNull.controlObjects = templHandleList self.i_rootControl = i_rootControl#link to carry #>> Orientation helpers #============================= """ Make our Orientation Helpers """ doCreateOrientationHelpers(self) doParentControlObjects(self.m) #if self.m.getMessage('moduleParent'):#If we have a moduleParent, constrain it #constrainToParentModule(self.m) return True
def __func__(self): """ """ _str_funcName = self._str_funcCombined curve = self.d_kws['curve'] points = self.d_kws['points'] mi_crv = cgmMeta.validateObjArg(self.d_kws['curve'],cgmMeta.cgmObject,mayaType='nurbsCurve',noneValid=False) int_points = cgmValid.valueArg(self.d_kws['points'],minValue=1,calledFrom = _str_funcName) f_insetSplitFactor = cgmValid.valueArg(self.d_kws['insetSplitFactor'],calledFrom = _str_funcName) f_startSplitFactor = cgmValid.valueArg(self.d_kws['startSplitFactor'],calledFrom = _str_funcName) f_kwMinU = cgmValid.valueArg(self.d_kws['minU'], noneValid=True, calledFrom = _str_funcName) f_kwMaxU = cgmValid.valueArg(self.d_kws['maxU'], noneValid=True, calledFrom = _str_funcName) f_points = float(int_points) int_spans = int(cgmValid.valueArg(self.d_kws['points'],minValue=5,autoClamp=True,calledFrom = _str_funcName)) b_rebuild = cgmValid.boolArg(self.d_kws['rebuildForSplit'],calledFrom = _str_funcName) b_markPoints = cgmValid.boolArg(self.d_kws['markPoints'],calledFrom = _str_funcName) b_reverseCurve = cgmValid.boolArg(self.d_kws['reverseCurve'],calledFrom = _str_funcName) try:#>>> Rebuild curve if b_rebuild: useCurve = mc.rebuildCurve (curve, ch=0, rpo=0, rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=int_spans, d=3, tol=0.001)[0] else: useCurve = mc.duplicate(curve)[0] if b_reverseCurve: useCurve = mc.reverseCurve(useCurve,rpo = True)[0] except Exception,error:raise StandardError,"Rebuild fail | %s"%error try:#>>> Divide stuff #========================== l_spanUPositions = [] str_bufferU = mc.ls("%s.u[*]"%useCurve)[0] log.debug("%s >> u list : %s"%(_str_funcName,str_bufferU)) f_maxU = float(str_bufferU.split(':')[-1].split(']')[0]) l_uValues = [0] if points == 1: l_uValues = [f_maxU/2] elif f_startSplitFactor is not False: if points < 5: raise StandardError,"Need at least 5 points for startSplitFactor. Points : %s"%(points) log.debug("%s >> f_startSplitFactor : %s"%(_str_funcName,f_startSplitFactor)) #Figure out our u's f_base = f_startSplitFactor * f_maxU l_uValues.append( f_base ) f_len = f_maxU - (f_base *2) int_toMake = f_points-4 f_factor = f_len/(int_toMake+1) log.debug("%s >> f_maxU : %s"%(_str_funcName,f_maxU)) log.debug("%s >> f_len : %s"%(_str_funcName,f_len)) log.debug("%s >> int_toMake : %s"%(_str_funcName,int_toMake)) log.debug("%s >> f_base : %s"%(_str_funcName,f_base)) log.debug("%s >> f_factor : %s"%(_str_funcName,f_factor)) for i in range(1,int_points-3): l_uValues.append(((i*f_factor + f_base))) l_uValues.append(f_maxU - f_base) l_uValues.append(f_maxU) log.debug("%s >> l_uValues : %s"%(_str_funcName,l_uValues)) elif f_insetSplitFactor is not False: log.debug("%s >> f_insetSplitFactor : %s"%(_str_funcName,f_insetSplitFactor)) #Figure out our u's f_base = f_insetSplitFactor * f_maxU f_len = f_maxU - (f_base *2) f_factor = f_len/(f_points-1) log.debug("%s >> f_maxU : %s"%(_str_funcName,f_maxU)) log.debug("%s >> f_len : %s"%(_str_funcName,f_len)) log.debug("%s >> f_base : %s"%(_str_funcName,f_base)) log.debug("%s >> f_factor : %s"%(_str_funcName,f_factor)) for i in range(1,int_points-1): l_uValues.append((i*f_factor)) l_uValues.append(f_maxU) log.debug("%s >> l_uValues : %s"%(_str_funcName,l_uValues)) elif f_kwMinU is not False or f_kwMaxU is not False: log.debug("%s >> Sub mode. "%(_str_funcName)) if f_kwMinU is not False: if f_kwMinU > f_maxU: raise StandardError, "kw minU value(%s) cannot be greater than maxU(%s)"%(f_kwMinU,f_maxU) f_useMinU = f_kwMinU else:f_useMinU = 0.0 if f_kwMaxU is not False: if f_kwMaxU > f_maxU: raise StandardError, "kw maxU value(%s) cannot be greater than maxU(%s)"%(f_kwMaxU,f_maxU) f_useMaxU = f_kwMaxU else:f_useMaxU = f_maxU if int_points == 1: l_uValues = [(f_useMaxU - f_useMinU)/2] elif int_points == 2: l_uValues = [f_useMaxU,f_useMinU] else: l_uValues = [f_useMinU] f_factor = (f_useMaxU - f_useMinU)/(f_points-1) log.debug("%s >> f_maxU : %s"%(_str_funcName,f_useMaxU)) log.debug("%s >> f_factor : %s"%(_str_funcName,f_factor)) for i in range(1,int_points-1): l_uValues.append((i*f_factor) + f_useMinU) l_uValues.append(f_useMaxU) else: #Figure out our u's log.debug("%s >> Regular mode. Points = %s "%(_str_funcName,int_points)) if int_points == 3: l_uValues.append(f_maxU/2) l_uValues.append(f_maxU) else: f_factor = f_maxU/(f_points-1) log.debug("%s >> f_maxU : %s"%(_str_funcName,f_maxU)) log.debug("%s >> f_factor : %s"%(_str_funcName,f_factor)) for i in range(1,int_points-1): l_uValues.append(i*f_factor) l_uValues.append(f_maxU) log.debug("%s >> l_uValues : %s"%(_str_funcName,l_uValues)) except Exception,error:raise StandardError,"Divide fail | %s"%error for u in l_uValues: try:l_spanUPositions.append(mc.pointPosition("%s.u[%f]"%(useCurve,u))) except StandardError,error:raise StandardError,"Failed on pointPositioning: %s"%u log.debug("%s >> l_spanUPositions | len: %s | list: %s"%(_str_funcName,len(l_spanUPositions),l_spanUPositions)) try: if b_markPoints: ml_built = [] for i,pos in enumerate(l_spanUPositions): buffer = mc.spaceLocator(n = "%s_u_%f"%(useCurve,(l_uValues[i])))[0] ml_built.append( cgmMeta.cgmObject(buffer)) log.debug("%s >> created : %s | at: %s"%(_str_funcName,ml_built[-1].p_nameShort,pos)) mc.xform(ml_built[-1].mNode, t = (pos[0],pos[1],pos[2]), ws=True) if len(ml_built)>1: try:f_distance = distance.returnAverageDistanceBetweenObjects([o.mNode for o in ml_built]) * .5 except StandardError,error:raise StandardError,"Average distance fail. Objects: %s| error: %s"%([o.mNode for o in ml_built],error) try: for o in ml_built: o.scale = [f_distance,f_distance,f_distance] except StandardError,error:raise StandardError,"Scale fail : %s"%error except StandardError,error:log.error("Mark points fail. error : %s"%(error)) mc.delete(useCurve)#Delete our use curve return l_spanUPositions
n1.msgMultiTest=['pCube2','pCube3'] n1.msgMultiTest #>>['pCube2','pCube3'] #... Let's look at a potential problem with multi message attributes and how they're natively connected. from cgm.lib import attributes attributes.storeObjectsToMessage(l_cubes,n1.mNode,'msgMultiTest')#...this uses maya's connection format n1.msgMultiTest #>> looks good... mc.duplicate(l_cubes[2]) n1.msgMultiTest #>> um...our list grew. There is a bug in some versions of maya that this connection is duplicated. #I'm not sure what versions are fixed. This is part of the reason why we created the data storage method we'll see in a moment #>>message Treatment ========================================================================= #We have made several changes to r9's stuff in how we do messages, it is however compatible with r9's stuff #One of our calls to store info is doStore #First we're gonna make a catcher node mi_catchMeObj = cgmMeta.cgmObject(name = 'catchMe') mi_catcherObj = cgmMeta.cgmObject(name = 'msgCather') #One of our calls to store info is doStore mi_catcherObj.doStore('objNoMessage',mi_catchMeObj.mNode,overideMessageCheck = True)#It's gonna just store a string, no message.... mi_catcherObj.doStore('objNoMessage',mi_catchMeObj.mNode,overideMessageCheck = False)#Now it's a message...woot! #So maya can do that, what if you wanted to do something neater like say, store an attribute mi_catcherObj.doStore('objTX',"%s.tx"%mi_catchMeObj.mNode)#It's gonna just store a string, no message.... mi_catchMeObj.tx = 4#our attribute changed. That's because, this storage method stores on a compatible attribute format #That's great and all, but we were talking about messages... mi_catcherObj.getMessage('objTX')# we get the attribute, neato... mi_catcherObj.getMessageAsMeta('objTX')# we get the attribute, neato...cgmAttr for the win #implementing attr setup to msgLists is on the ToDO list #==============================================================================================
def build_chain(posList = [], targetList = [], curve = None, axisAim = 'z+', axisUp = 'y+', worldUpAxis = [0,1,0], count = None, splitMode = 'curve', parent = False, orient = True, progressBar = None, relativeOrient=True, asMeta = True): """ General build oriented skeleton from a position list, targets or curve :parameters: posList(list) | List of positions to build from targetList(list) | List of targets to build from curve(str) | Curve to split worldUpAxis(vector) | World up direction for orientation count(int) | number of joints for splitting (None) is default which doesn't resplit splitMode(str) linear - Resplit along a vector from the first to last posList point curve - Resplit along a curve going through all of our points sub - Resplit adding the number of joints between our points :returns created(list) """ _str_func = 'build_chain' _axisAim = axisAim _axisUp = axisUp _axisWorldUp = worldUpAxis _radius = 1 mc.select(cl=True) #pprint.pprint(vars()) #>>Get positions ================================================================================ if not posList and targetList: log.debug("|{0}| >> No posList provided, using targets...".format(_str_func)) posList = [] for t in targetList: posList.append(POS.get(t)) if curve and not posList: log.debug("|{0}| >> Generating posList from curve arg...".format(_str_func)) splitMode == 'curve' posList = CURVES.returnSplitCurveList(curve,count) if count is not None: log.debug("|{0}| >> Resplit...".format(_str_func)) if splitMode == 'sub': l_new = [] for i,p in enumerate(posList[:-1]): #l_new.append(p) l_new.extend(DIST.get_posList_fromStartEnd(p,posList[i+1], count +2) [:-1]) l_new.append(posList[-1]) posList = l_new elif count != len(posList): if splitMode == 'linear': #_p_start = POS.get(_l_targets[0]) #_p_top = POS.get(_l_targets[1]) #posList = get_posList_fromStartEnd(posList[0],posList[-1],count) _crv = CURVES.create_fromList(posList= posList, linear=True) posList = CURVES.returnSplitCurveList(_crv,count) mc.delete(_crv) elif splitMode == 'curve': if not curve: log.debug("|{0}| >> Making curve...".format(_str_func)) _crv = CURVES.create_fromList(posList= posList) posList = CURVES.returnSplitCurveList(_crv,count) mc.delete(_crv) else: posList = CURVES.returnSplitCurveList(curve,count) else: raise ValueError, "Unknown splitMode: {0}".format(splitMode) #>>Radius ======================================================================================= _len = len(posList) if _len > 1: _baseDist = DIST.get_distance_between_points(posList[0],posList[1]) _radius = _baseDist/4 #>>Create joints ================================================================================= ml_joints = [] log.debug("|{0}| >> pos list...".format(_str_func)) #progressBar = cgmUI.progressBar_start(progressBar, stepMaxValue=_len) for i,p in enumerate(posList): log.debug("|{0}| >> {1}:{2}".format(_str_func,i,p)) #cgmUI.progressBar_iter(progressBar,status='Creating: {0}'.format(p)) mJnt = cgmMeta.cgmObject(mc.joint (p=(p[0],p[1],p[2]))) mJnt.displayLocalAxis = 1 mJnt.radius = _radius ml_joints.append ( mJnt ) if not parent: mJnt.parent=False """if i > 0: _mJnt.parent = _ml_joints[i-1] else: _mJnt.parent = False""" #cgmUI.progressBar_end(progressBar) #>>Orient chain... if orient: if _len == 1: log.debug("|{0}| >> Only one joint. Can't orient chain".format(_str_func,_axisWorldUp)) else: orientChain(ml_joints,axisAim,axisUp,worldUpAxis,relativeOrient) if asMeta: return ml_joints return [mJnt.mNode for mJnt in ml_joints]
reload(Snap) from cgm.core.rigger import ModuleControlFactory as mControlFactory reload(mControlFactory) from cgm.lib import search obj = mc.ls(sl=True)[0] or False obj = '' objList = [] #>>> Modules #======================================================= m1 = cgmPM.cgmModule(name = 'test') m1 = r9Meta.MetaClass('spine_part') m1.setState('skeleton') m1.getPartNameBase() m1.modulePuppet.getGeo() mObj = cgmMeta.cgmObject(control) i_loc = mObj.doLoc() i_loc.rx = i_loc.rx + 90 mObj.doCopyTransform(i_loc.mNode) mObj.mNode mObj.getAttr('asdfasdf') #>>> Testing control registering control = 'shoulders_ikCurve' mControlFactory.registerControl(mc.ls(sl=True)[0]) mControlFactory.registerControl(control,copyPivot='spine_2_segIKCurve') for i in range(2):log.info(i) class dataHolder(object): pass l_targetObjects = mc.ls(sl=True) log.info(cgmMeta.cgmObject(mc.ls(sl=True)[0]).getNameDict()) log.info(cgmMeta.cgmObject(mc.ls(sl=True)[0]).doName())
reload(Snap) from cgm.core.rigger import ModuleControlFactory as mControlFactory reload(mControlFactory) from cgm.lib import search obj = mc.ls(sl=True)[0] or False obj = '' objList = [] #>>> Modules #======================================================= m1 = cgmPM.cgmModule(name='test') m1 = r9Meta.MetaClass('spine_part') m1.setState('skeleton') m1.getPartNameBase() m1.modulePuppet.getGeo() mObj = cgmMeta.cgmObject(control) i_loc = mObj.doLoc() i_loc.rx = i_loc.rx + 90 mObj.doCopyTransform(i_loc.mNode) mObj.mNode mObj.getAttr('asdfasdf') #>>> Testing control registering control = 'cog_controlCurve' mControlFactory.registerControl(mc.ls(sl=True)[0]) mControlFactory.registerControl(control) for i in range(2): log.info(i) class dataHolder(object):
Website : http://www.cgmonks.com ------------------------------------------ Help for learning the basis of cgmMeta.cgmAttr ================================================================ """ #============================================================================================== #>> cgmMeta.cgmAttr #============================================================================================== from cgm.core import cgm_Meta as cgmMeta import maya.cmds as mc #>>Intro ========================================================================= #First we're gonna make some objects try:mi_baseObj = cgmMeta.cgmObject('baseObj')#...if it exists, initialize, except, make... except:mi_baseObj = cgmMeta.cgmObject(mc.spaceLocator(p = [5,0,0],name = 'baseObj')[0]) try:mi_catchObj = cgmMeta.cgmObject('catchObj')#...if it exists, initialize, except, make... except:mi_catchObj = cgmMeta.cgmObject(mc.spaceLocator(p = [-5,0,0],name = 'catchObj')[0]) #>> Let's start with existing attributes mi_baseObj.select() mPlug_t = cgmMeta.cgmAttr(mi_baseObj,'translate') mPlug_tx = cgmMeta.cgmAttr(mi_baseObj,'tx') #Getting attribte names as we like mPlug_tx.p_combinedName mPlug_tx.p_combinedShortName mPlug_tx.p_nameNice mPlug_t.p_hidden = True #...Hide something mPlug_tx.p_hidden = False #...Unhide 1
def doMove(self,**kws): if kws:log.debug("Snap.doMove>>> kws: %s"%kws) if len(self.l_targets) == 1: #>>> Check our target i_target = cgmMeta.cgmNode( self.l_targets[0] ) log.debug("i_target: %s"%i_target) targetType = i_target.getMayaType() if self.b_snapComponents: components = self.i_obj.getComponents() if not components:raise StandardError,"This objects has no components to snap: '%s'"%self.i_obj.getShortName() #>>>Progress bar mayaMainProgressBar = gui.doStartMayaProgressBar(len(components)) for c in components: if mc.progressBar(mayaMainProgressBar, query=True, isCancelled=True ) : break mc.progressBar(mayaMainProgressBar, edit=True, status = ("Wrapping '%s'"%c), step=1) if targetType in ['mesh','nurbsSurface','nurbsCurve']: pos = distance.returnWorldSpacePosition(c) targetLoc = mc.spaceLocator() mc.move (pos[0],pos[1],pos[2], targetLoc[0]) closestLoc = locators.locClosest([targetLoc[0]],i_target.mNode) if self._posOffset: self.doOrientObjToSurface(i_target.mNode,closestLoc) mc.move (self._posOffset[0],self._posOffset[1],self._posOffset[2], [closestLoc], r=True, rpr = True, os = True, wd = True) position.movePointSnap(c,closestLoc) mc.delete([targetLoc[0],closestLoc]) gui.doEndMayaProgressBar(mayaMainProgressBar)#Close out this progress bar else: pos = False if self.b_snaptoSurface:#>>> If our target is surface we can use if targetType in ['mesh','nurbsCurve','nurbsSurface']: i_locObj = self.i_obj.doLoc()#Get our position loc i_locTarget = cgmMeta.cgmObject( locators.locClosest([i_locObj.mNode],i_target.mNode) )#Loc closest #i_locObj.rename('objLoc') #i_locTarget.rename('targetLoc') if self._posOffset: try: self.doOrientObjToSurface(i_target.mNode,i_locTarget.mNode) mc.move (self._posOffset[0],self._posOffset[1],self._posOffset[2], [i_locTarget.mNode], r=True, rpr = True, os = True, wd = True) except StandardError,error: log.warn("self._posOffset failure!") log.error(error) pos = i_locTarget.getPosition(True) i_locObj.delete() i_locTarget.delete() elif self.b_midSurfacePos: log.debug("Snap.move>>> midSurfacePos mode!") if targetType not in ['mesh','nurbsCurve','nurbsSurface']: log.warning("Can't do midSurfacPos on targetType: '%s'"%targetType) return False #Get the axis info axisToCheck = kws.pop('axisToCheck',False) if not axisToCheck: axisToCheck = [] up = dictionary.returnVectorToString(self._upVector) or False if not up: raise StandardError,"SnapFactory>>> must have up vector for midSurfaceSnap: %s"%self._upVector for a in ['x','y','z']: if a != up[0]: axisToCheck.append(a) if not axisToCheck: raise StandardError,"SnapFactory>>> couldn't find any axis to do" #i_locObj = self.i_obj.doLoc()#Get our position loc #log.debug(axisToCheck) pos = RayCast.findMeshMidPointFromObject(i_target.mNode, self.i_obj.mNode, axisToCheck=axisToCheck,**kws) #i_locObj.delete() else: pos = i_target.getPosition(True) if pos: if self.i_obj.isComponent(): if self.b_softSelection:#Only need to do this if soft select is on mc.softSelect(softSelectEnabled = True) mc.select(self.i_obj.getComponent()) mc.move (pos[0],pos[1],pos[2],rpr=True) mc.select(cl=True) else: mc.move (pos[0],pos[1],pos[2], self.i_obj.getComponent()) else: mc.move (pos[0],pos[1],pos[2], self.i_obj.mNode, rpr=True)
def createWrapControlShape(targetObjects, targetGeo = None, latheAxis = 'z',aimAxis = 'y+',objectUp = 'y+', points = 8, curveDegree = 1, insetMult = None,#Inset multiplier posOffset = [], rootOffset = [],#offset root before cast rootRotate = None, joinMode = False, extendMode = None, closedCurve = True, l_specifiedRotates = None, maxDistance = 1000, closestInRange = True, midMeshCast = False, rotateBank = None, joinHits = None,#keys to processed hits to see what to join axisToCheck = ['x','y'], ):#'segment,radial,disc' """ Function for creating control curves from other objects. Currently assumes z aim, y up 1) Cather info 2) Get initial curves 3) Store info 4) return TODO: Change offsets to use lathe axis rather than """ _str_funcName = "createWrapControlShape" log.debug(">> %s >> "%(_str_funcName) + "="*75) if type(targetObjects) not in [list,tuple]:targetObjects = [targetObjects] if not targetGeo: raise NotImplementedError, "Must have geo for now" if len(mc.ls(targetGeo))>1: raise StandardError,"createWrapControlShape>> More than one mesh named: %s"%targetGeo assert type(points) is int,"Points must be int: %s"%points assert type(curveDegree) is int,"Points must be int: %s"%points assert curveDegree > 0,"Curve degree must be greater than 1: %s"%curveDegree if posOffset is not None and len(posOffset) and len(posOffset)!=3:raise StandardError, "posOffset must be len(3): %s | len: %s"%(posOffset,len(posOffset)) if rootOffset is not None and len(rootOffset) and len(rootOffset)!=3:raise StandardError, "rootOffset must be len(3): %s | len: %s"%(rootOffset,len(rootOffset)) if rootRotate is not None and len(rootRotate) and len(rootRotate)!=3:raise StandardError, "rootRotate must be len(3): %s | len: %s"%(rootRotate,len(rootRotate)) if extendMode in ['loliwrap'] and insetMult is None:insetMult = 1 for axis in ['x','y','z']: if axis in latheAxis.lower():latheAxis = axis log.debug("targetObjects: %s"%targetObjects) if len(aimAxis) == 2:single_aimAxis = aimAxis[0] else:single_aimAxis = aimAxis log.debug("Single aim: %s"%single_aimAxis) log.debug("createWrapControlShape>> midMeshCast: %s"%midMeshCast) #>> Info l_groupsBuffer = [] il_curvesToCombine = [] l_sliceReturns = [] #Need to do more to get a better size #>> Build curves #================================================================= #> Root curve # log.debug("RootRotate: %s"%rootRotate) mi_rootLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc() if rootOffset: log.debug("rootOffset: %s"%rootOffset) mc.move(rootOffset[0],rootOffset[1],rootOffset[2], [mi_rootLoc.mNode], r=True, rpr = True, os = True, wd = True) if rootRotate is not None and len(rootRotate): log.debug("rootRotate: %s"%rootRotate) mc.rotate(rootRotate[0],rootRotate[1],rootRotate[2], [mi_rootLoc.mNode], os = True,r=True) #>> Root mi_rootLoc.doGroup()#Group to zero if extendMode == 'segment': log.debug("segment mode. Target len: %s"%len(targetObjects[1:])) try: if len(targetObjects) < 2: log.warning("Segment build mode only works with two objects or more") else: if insetMult is not None: rootDistanceToMove = distance.returnDistanceBetweenObjects(targetObjects[0],targetObjects[1]) log.debug("rootDistanceToMove: %s"%rootDistanceToMove) mi_rootLoc.__setattr__('t%s'%latheAxis,rootDistanceToMove*insetMult) #mi_rootLoc.tz = (rootDistanceToMove*insetMult)#Offset it #Notes -- may need to play with up object for aim snapping #mi_upLoc = cgmMeta.cgmNode(targetObjects[0]).doLoc() #mi_upLoc.doGroup()#To zero objectUpVector = dictionary.returnStringToVectors(objectUp) log.debug("objectUpVector: %s"%objectUpVector) #mi_uploc for i,obj in enumerate(targetObjects[1:]): log.debug("i: %s"%i) #> End Curve mi_endLoc = cgmMeta.cgmNode(obj).doLoc() aimVector = dictionary.returnStringToVectors(latheAxis+'-') log.debug("segment aimback: %s"%aimVector) #Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,aim=True,aimVector=aimVector,upVector=objectUpVector) Snap.go(mi_endLoc.mNode,mi_rootLoc.mNode,move=False,orient=True) mi_endLoc.doGroup() if i == len(targetObjects[1:])-1: if insetMult is not None: log.debug("segment insetMult: %s"%insetMult) distanceToMove = distance.returnDistanceBetweenObjects(targetObjects[-1],targetObjects[0]) log.debug("distanceToMove: %s"%distanceToMove) #mi_endLoc.tz = -(distanceToMove*insetMult)#Offset it mi_endLoc.__setattr__('t%s'%latheAxis,-(distanceToMove*insetMult)) log.debug("segment lathe: %s"%latheAxis) log.debug("segment aim: %s"%aimAxis) log.debug("segment rotateBank: %s"%rotateBank) d_endCastInfo = createMeshSliceCurve(targetGeo,mi_endLoc,midMeshCast=midMeshCast,curveDegree=curveDegree,latheAxis=latheAxis,aimAxis=aimAxis,posOffset = posOffset,points = points,returnDict=True,closedCurve = closedCurve, maxDistance = maxDistance, closestInRange=closestInRange, rotateBank=rotateBank, l_specifiedRotates = l_specifiedRotates,axisToCheck = axisToCheck) l_sliceReturns.append(d_endCastInfo) mi_end = cgmMeta.cgmObject(d_endCastInfo['curve']) il_curvesToCombine.append(mi_end) mc.delete(mi_endLoc.parent)#delete the loc except StandardError,error: raise StandardError,"createWrapControlShape>> segment wrap fail! | %s"%error
i_rig = Rig.go(m1, forceNew=False, autoBuild=False) #call to do general rig m1.setState('skeleton', forceNew=True) m1.getState() m1.modulePuppet.getModuleFromDict({'moduleType': 'thumb'}) m1.modulePuppet.getModuleFromDict(moduleType=['torso', 'spine']) m1.modulePuppet.getModuleFromDict(checkDict={'moduleType': 'head'}) i_rig = Rig.go(m1, forceNew=False) #call to do general rig reload(Rig) i_rig._get_simpleRigJointDriverDict() i_rig._i_masterControl i_rig.build(i_rig, buildTo='') i_rig.build(i_rig, buildTo='skeleton') i_rig.build(i_rig, buildTo='shapes') i_rig.build(i_rig, buildTo='controls') Rig.get_report(m2) m1.rigNull.getMessage('skinJoints', False) m1.rigNull.msgList_getMessage('handleJoints') i_rig.buildModule.build_rigSkeleton(i_rig) i_rig.buildModule.build_shapes(i_rig) i_rig.buildModule.build_controls(i_rig) i_rig.buildModule.build_FKIK(i_rig) i_rig.buildModule.build_deformation(i_rig) i_rig.buildModule.build_rig(i_rig) i_rig.buildModule.build_matchSystem(i_rig) i_rig.buildModule.build_twistDriver_shoulder(i_rig) i_rig.buildModule.build_twistDriver_wrist(i_rig) reload(Rig) i_rig._get_handleJoints() cgmMeta.cgmObject('l_ankle_ik_anim').scalePivotY = 0 i_rig.build(i_rig) i_rig._i_deformNull.controlsIK
m1 = cgmMeta.cgmNode('spine_part') m1.setState('skeleton',forceNew = True) m1.rigNull.skinJoints m1.getModuleColors() m1.getPartNameBase() m1.modulePuppet.getGeo() targetObj = mc.ls(sl=True)[0] distance.returnClosestPointOnSurfaceInfo(targetObj,'test_controlSurface') distance.returnClosestUV(targetObj,'test_controlSurface') log.info(a) nodes.createFollicleOnMesh('spine_controlSurface','test') locators.locMeClosestUVOnSurface(mc.ls(sl=True)[0], 'test_controlSurface', pivotOnSurfaceOnly = False) mesh = 'Morphy_Body_GEO' i_obj = cgmMeta.cgmObject('hips_anim') mControlFactory.returnBaseControlSize(i_obj, mesh,axis = ['x','y','z-']) mControlFactory.returnBaseControlSize(i_obj, mesh,axis = ['z-']) mc.softSelect(softSelectEnabled = True) mc.softSelect(q = True, softSelectDistance = True) mc.softSelect(q = True, softSelectUVDistance = True) mc.softSelect(q = True, softSelectFalloff = 2) mc.softSelect(softSelectFalloff = 0) mc.softSelect(softSelectDistance = 20) mc.softSelect(softSelectUVDistance = 30) #252ms m1.isSkeletonized()