def get_surfaceSplitCurves(surface=None, l_values=[], count=None, mode='u', offset=None, cullStartEnd=True): _str_func = 'get_surfaceSplitCurves' log.debug("|{0}| >> ".format(_str_func) + '-' * 80) _shape = SHAPES.get_nonintermediate(surface) if mode == 'u': l_base = get_dat(_shape, uKnots=True)['uKnots'] minKnot = ATTR.get(_shape, 'minValueU') maxKnot = ATTR.get(_shape, 'maxValueU') else: l_base = get_dat(_shape, vKnots=True)['vKnots'] minKnot = ATTR.get(_shape, 'minValueV') maxKnot = ATTR.get(_shape, 'maxValueV') if count is not None: l_values = MATH.get_splitValueList(minKnot, maxKnot, count, cullStartEnd=cullStartEnd) res = [] for v in l_values: crv = get_shapeCurve(_shape, v, mode, offset=offset) res.append(crv) return res
def get_targetWeightsDict(node=None): """ Get the constraints a given node drives :parameters: node(str): node to query :returns list of targets(list) """ _str_func = 'get_targetWeightsDict' node = VALID.mNodeString(node) _type = VALID.get_mayaType(node) _d = {} _l = [] _call = _d_type_to_call.get(_type, False) if not _call: raise ValueError, "|{0}| >> {1} not a known type of constraint. node: {2}".format( _str_func, _type, node) aliasList = _call(node, q=True, weightAliasList=True) if aliasList: for o in aliasList: _d[o] = ATTR.get(node, o) return _d
def get_dat(target = None, differential=False, module = dynFKPresets): _str_func = 'get_dat' mTar = cgmMeta.asMeta(target, noneValid = True) if not mTar: return log.error(cgmGEN.logString_msg(_str_func, "No valid target")) _type = mTar.getMayaType() _key = d_shortHand.get(_type,_type) log.info(cgmGEN.logString_msg(_str_func,"mTar: {0} | {1}".format(_type, mTar))) #_d = ATTR.get_attrsByTypeDict(mTar.mNode) #pprint.pprint(_d) _res = {} _tar = mTar.mNode for section,l in d_attrMap.get(_key).iteritems(): log.debug(cgmGEN.logString_msg(_str_func,section)) for a in l: if a in l_ignore: continue try: _v = ATTR.get(_tar,a) log.debug(cgmGEN.logString_msg(_str_func,"{0} | {1}".format(a,_v))) except Exception,err: log.error("Failed to query: {0} | {1} | {2}".format(_tar, a, err)) if _v is not None: _res[str(a)] = _v
def uiFunc_valuesTweak(self, mode='+'): _str_func = 'uiFunc_valuesTweak' if mode == 'zero': log.info("|{0}| >> Zeroing ".format(_str_func)) for a in 'XYZ': self.__dict__['uiff_transformTweak{0}'.format(a)].setValue(0) for k, cb in self._d_transformCBs.iteritems(): cb.setValue(0) return _ml_targets = uiFunc_getTargets(self) if not _ml_targets: raise ValueError, "Must have targets" _l_toTweak = [] for k, cb in self._d_transformCBs.iteritems(): if cb.getValue(): _l_toTweak.append(k) _tweak = [] for a in 'XYZ': _tweak.append( self.__dict__['uiff_transformTweak{0}'.format(a)].getValue()) pprint.pprint([mode, _l_toTweak, _tweak]) if mode == '+': _tweak_call = MATH.list_add else: _tweak_call = MATH.list_subtract for mObj in _ml_targets: for attr in _l_toTweak: if attr in [ 'translate', 'rotate', 'scale', 'jointOrient', 'rotateAxis' ]: _v = ATTR.get(mObj.mNode, attr) log.info("|{0}| >> pre tweak: [{1}] ".format(_str_func, _v)) _v = _tweak_call(_v, _tweak) log.info("|{0}| >> post tweak: [{1}] ".format(_str_func, _v)) ATTR.set(mObj.mNode, attr, _v) elif attr == 'position': _v = TRANS.position_get(mObj.mNode) log.info("|{0}| >> pre tweak: [{1}] ".format(_str_func, _v)) _v = _tweak_call(_v, _tweak) log.info("|{0}| >> post tweak: [{1}] ".format(_str_func, _v)) TRANS.position_set(mObj.mNode, _v) elif attr == 'orient': _v = TRANS.orient_get(mObj.mNode) log.info("|{0}| >> pre tweak: [{1}] ".format(_str_func, _v)) _v = _tweak_call(_v, _tweak) log.info("|{0}| >> post tweak: [{1}] ".format(_str_func, _v)) TRANS.orient_set(mObj.mNode, _v) else: log.warning("|{0}| >> Haven't setup for {1}...".format( _str_func, _s)) pass
def get_uv_normal(mesh, uvValue, asEuclid=False): """ Get a normal at a uv :parameters: mesh(string) | Surface uv resides on uValue(float) | uValue vValue(float) | vValue asEuclid(bool) - whether to return as Vector or not :returns pos(double3) """ _str_func = 'get_uv_position' _follicle = NODE.add_follicle(mesh) ATTR.set(_follicle[0], 'parameterU', uvValue[0]) ATTR.set(_follicle[0], 'parameterV', uvValue[1]) _normal = ATTR.get(_follicle[0], 'outNormal') mc.delete(_follicle) if asEuclid: log.debug("|{0}| >> asEuclid...".format(_str_func)) return EUCLID.Vector3(_normal[0], _normal[1], _normal[2]) return _normal
def test_b_masterNull(self): mPuppet = self.mi_puppet mMasterNull = mPuppet.masterNull self.assertEqual(mPuppet.masterNull.puppet.mNode, mPuppet.mNode, 'mNode walk...') self.assertEqual(mPuppet.masterNull.puppet, mPuppet, 'meta walk...') masterDefaultValues = { 'cgmType': ['string', 'ignore'], 'cgmModuleType': ['string', 'master'] } for attr in masterDefaultValues.keys(): try: self.assertEqual(ATTR.has_attr(mMasterNull.mNode, attr), True, attr) self.assertEqual(ATTR.get_type(mMasterNull.mNode, attr), masterDefaultValues.get(attr)[0]) self.assertEqual(ATTR.get(mMasterNull.mNode, attr), masterDefaultValues.get(attr) [1]) #"{0} value test fail".format(attr) except Exception, err: print "{0} attr failed...".format(attr) for arg in err: log.error(arg) raise Exception, err
def uiFunc_updateFields(self): _str_func = 'uiFunc_updateFields' #_type = VALID.get_mayaType(_short) if not self._mTransformTarget: return False _short = self._mTransformTarget.mNode #_space = self.var_sourceTransSpaceMode.value #log.info("|{0}| >> Getting data. Space: {1} ".format(_str_func, _space)) #_pos = POS.get(_short,'rp',_space) _info = POS.get_info(_short) pprint.pprint(_info) #pprint.pprint(self._d_transformAttrFields) _d_sectionToDatKey = {'rotate': 'rotateLocal', 'orient': 'rotation'} for section in self._d_transformAttrFields.keys(): log.info("|{0}| >> On {1}".format(_str_func, section)) _s = section if _s in [ 'translate', 'rotate', 'position', 'rotateAxis', 'scalePivot', 'orient' ]: _k = _d_sectionToDatKey.get(_s, _s) for i, v in enumerate(_info[_k]): self._d_transformAttrFields[_s]['XYZ'[i]].setValue(v) elif _s == 'jointOrient': if ATTR.has_attr(_short, 'jointOrient'): self._d_transformRows[_s](edit=True, vis=True) _v = ATTR.get(_short, 'jointOrient') log.info("|{0}| >> jointOrient: {1}".format(_str_func, _v)) for i, v in enumerate(_v): self._d_transformAttrFields[_s]['XYZ'[i]].setValue(v) else: self._d_transformRows[_s](edit=True, vis=False) elif _s == 'scale': for i, v in enumerate(ATTR.get(_short, 'scale')): self._d_transformAttrFields[_s]['XYZ'[i]].setValue(v) elif _s == 'scaleLossy': for i, v in enumerate(TRANS.scaleLossy_get(_short)): self._d_transformAttrFields[_s]['XYZ'[i]].setValue(v) else: log.info("|{0}| >> Missing query for {1}".format( _str_func, section))
def get_curveMidPointFromDagList(sourceList): _str_func = 'get_curveMidPointFromDagList' l_pos = [get(o) for o in sourceList] knot_len = len(l_pos) + 3 - 1 _created = mc.curve(d=3, ep=l_pos, k=[i for i in range(0, knot_len)], os=True) shp = mc.listRelatives(_created, s=True, fullPath=True)[0] _min = ATTR.get(shp, 'minValue') _max = ATTR.get(shp, 'maxValue') _mid = (_max - _min) / 2.0 pos = mc.pointPosition("{0}.u[{1}]".format(shp, _mid), w=True) mc.delete(_created) return pos
def get_nonintermediate(shape): """ Get the nonintermediate shape on a transform :parameters: shape(str): Shape to check :returns non intermediate shape(string) """ _str_func = "get_nonintermediate" try: if not VALID.is_shape(shape): _shapes = mc.listRelatives(shape, fullPath=True) _l_matches = [] for s in _shapes: if not ATTR.get(s, 'intermediateObject'): _l_matches.append(s) if len(_l_matches) == 1: return _l_matches[0] else: raise ValueError, "Not sure what to do with this many intermediate shapes: {0}".format( _l_matches) elif ATTR.get(shape, 'intermediateObject'): _type = VALID.get_mayaType(shape) _trans = SEARCH.get_transform(shape) _shapes = mc.listRelatives(_trans, s=True, type=_type, fullPath=True) _l_matches = [] for s in _shapes: if not ATTR.get(s, 'intermediateObject'): _l_matches.append(s) if len(_l_matches) == 1: return _l_matches[0] else: raise ValueError, "Not sure what to do with this many intermediate shapes: {0}".format( _l_matches) else: return shape except Exception, err: cgmGEN.cgmExceptCB(Exception, err)
def get_RGB_fromHSV(rValue=0, gValue=0, bValue=0, getNode=False): _node = mc.createNode('hsvToRgb') ATTR.set(_node, 'inHsvB', COREMATH.Clamp(float(bValue), 0.0001, 1.0)) ATTR.set(_node, 'inHsvG', COREMATH.Clamp(float(gValue), 0.0001, 1.0)) ATTR.set(_node, 'inHsvR', COREMATH.Clamp(float(rValue), 0.000001, 360.0)) res = ATTR.get(_node, 'outRgb')[0] if getNode: return _node, res mc.delete(_node) return res
def get_HSV_fromRGB(rValue=0, gValue=0, bValue=0, getNode=False): _node = mc.createNode('rgbToHsv') ATTR.set(_node, 'inRgbR', COREMATH.Clamp(float(rValue), 0, 1.0)) ATTR.set(_node, 'inRgbG', COREMATH.Clamp(float(gValue), 0, 1.0)) ATTR.set(_node, 'inRgbB', COREMATH.Clamp(float(bValue), 0, 1.0)) res = ATTR.get(_node, 'outHsv')[0] if getNode: return _node, res mc.delete(_node) return res
class Test_cgmPuppet(unittest.TestCase): def setUp(self): try: self.mi_puppet = PUPPETMETA.cgmPuppet( 'cgmPuppetTesting_puppetNetwork') except: self.mi_puppet = cgmMeta.createMetaNode('cgmPuppet', name='cgmPuppetTesting') def test_a_network(self): mPuppet = self.mi_puppet self.assertEqual(issubclass(type(mPuppet), PUPPETMETA.cgmPuppet), True) try: mPuppet._UTILS except Exception, error: raise Exception, "No _Utils found | error: {0}".format(error) self.assertEqual(mc.nodeType(mPuppet.mNode), 'network') #Attrs ----------------------------------------------------------------------------------------- puppetDefaultValues = { 'cgmName': ['string', 'cgmPuppetTesting'], 'cgmType': ['string', 'puppetNetwork'], 'mClass': ['string', 'cgmPuppet'], 'version': ['double', 1.0], 'masterNull': ['message', [u'cgmPuppetTesting']], 'font': ['string', 'Arial'], 'axisAim': ['enum', 2], 'axisUp': ['enum', 1], 'axisOut': ['enum', 0] } for attr in puppetDefaultValues.keys(): try: self.assertEqual(ATTR.has_attr(mPuppet.mNode, attr), True, attr) self.assertEqual(ATTR.get_type(mPuppet.mNode, attr), puppetDefaultValues.get(attr)[0]) self.assertEqual(ATTR.get(mPuppet.mNode, attr), puppetDefaultValues.get(attr) [1]) #"{0} value test fail".format(attr) except Exception, err: print "{0} attr failed...".format(attr) for arg in err: log.error(arg) raise Exception, err
def scale_to_axisSize(arg=None, size=None): _str_func = 'scale_to_axisSize' log.debug(cgmGEN.logString_start(_str_func)) _currentSize = get_axisSize(arg) _currentScale = ATTR.get(arg, 'scale') _targetScale = [] for i, s in enumerate(size): if s is not None: v = (_currentScale[i] * s) / _currentSize[i] _targetScale.append(v) else: _targetScale.append(_currentScale[i]) #log.info(_targetScale) for i, a in enumerate('xyz'): if size[i]: ATTR.set(arg, 's{0}'.format(a), _targetScale[i])
def limbRoot(self): try: _str_func = 'limbRoot' log_start(_str_func) ml_fkJoints = self.ml_fkJoints _short_module = self.mModule.mNode mHandleFactory = self.mHandleFactory #limbRoot ------------------------------------------------------------------------------ log.debug("|{0}| >> LimbRoot".format(_str_func)) idx = 0 #if self.b_lever: # idx = 1 mLimbRootHandle = self.ml_prerigHandles[idx] mLimbRoot = ml_fkJoints[0].rigJoint.doCreateAt() _size_root = MATH.average(POS.get_bb_size(self.mRootFormHandle.mNode)) #MATH.average(POS.get_bb_size(self.mRootFormHandle.mNode)) mRootCrv = cgmMeta.validateObjArg(CURVES.create_fromName( 'locatorForm', _size_root), 'cgmObject', setClass=True) mRootCrv.doSnapTo(ml_fkJoints[0]) #mLimbRootHandle #SNAP.go(mRootCrv.mNode, ml_joints[0].mNode,position=False) CORERIG.shapeParent_in_place(mLimbRoot.mNode, mRootCrv.mNode, False) for a in 'cgmName', 'cgmDirection', 'cgmModifier': if ATTR.get(_short_module, a): ATTR.copy_to(_short_module, a, mLimbRoot.mNode, driven='target') mLimbRoot.doStore('cgmTypeModifier', 'limbRoot') mLimbRoot.doName() mHandleFactory.color(mLimbRoot.mNode, controlType='sub') self.mRigNull.connectChildNode(mLimbRoot, 'limbRoot', 'rigNull') except Exception, err: cgmGEN.cgmExceptCB(Exception, err, localDat=vars())
def radius_modify(self, mode='+', factor=10): _str_func = 'radius_modify' _sel = MMCONTEXT.get_list(self.var_contextTD.value, 'joint') if not _sel: return log.error("|{0}| >> Nothing selected".format(_str_func)) for j in _sel: _r = ATTR.get(j, 'radius') if mode == '+': _r = _r + factor elif mode == '-': _r = _r - factor elif mode == '*': _r = _r * factor elif mode == '/': _r = _r / factor ATTR.set(j, 'radius', _r)
def scaleLocal_get(node=None, asEuclid=False): """ Query the local scale of a given obj :parameters: node(str): node to query asEuclid(bool): whether to return a EUCLID.Vector3 :returns rotation(vector/asEuclid.Vector3) """ _str_func = 'scaleLocal_get' node = VALID.mNodeString(node) _res = ATTR.get(node, 'scale') log.debug("|{0}| >> [{2}] = {1}".format(_str_func, _res, node)) if asEuclid: return EUCLID.Vector3(_res[0], _res[1], _res[2]) return _res
def patch_templateToForm(): try: _str_func = 'patch_templateToForm' log.debug(cgmGEN.logString_start(_str_func)) _l = mc.ls() _progressBar = CGMUI.doStartMayaProgressBar(stepMaxValue=len(_l)) for i, o in enumerate(_l): _str = "{0} | {1} ".format(i, o) log.debug(cgmGEN.logString_sub(_str_func, _str)) CGMUI.progressBar_set(_progressBar, step=1, status=_str) mObj = cgmMeta.asMeta(o) for a in mc.listAttr(o, ud=True) or []: log.debug(cgmGEN.logString_msg(_str_func, str(a))) if 'template' in a: log.info( cgmGEN.logString_msg( _str_func, "{0} | {1} | template in".format(_str, a))) ATTR.rename(o, a, a.replace('template', 'form')) elif 'Template' in a: log.info( cgmGEN.logString_msg( _str_func, "{0} | {1} | Template in".format(_str, a))) ATTR.rename(o, a, a.replace('Template', 'Form')) v = ATTR.get(o, a) if 'template' == str(v): log.info( cgmGEN.logString_msg( _str_func, "{0} | {1} | template value".format(_str, str(a)))) ATTR.set(o, a, 'form') except Exception, err: cgmGEN.cgmExceptCB(Exception, err)
def returnNormalizedUV(mesh, uValue, vValue): """ uv Values from many functions need to be normalized to be correct when using those values for other functions The calculcaion for doing so is size = maxV - minV sum = rawV + minV normalValue = sum / size :parameters: mesh(string) | Surface to normalize to uValue(float) | uValue to normalize vValue(float) | vValue to normalize :returns: Dict ------------------------------------------------------------------ 'uv'(double2) | point from which we cast 'uValue'(float) | normalized uValue 'vValue'(float) | normalized vValue :raises: Exception | if reached """ try: _str_funcName = 'returnNormalizedUV' try: #Validation ---------------------------------------------------------------- mesh = cgmValid.objString(mesh, 'nurbsSurface', calledFrom=_str_funcName) if len(mc.ls(mesh)) > 1: raise StandardError, "{0}>>> More than one mesh named: {1}".format( _str_funcName, mesh) _str_objType = search.returnObjectType(mesh) l_shapes = mc.listRelatives(mesh, shapes=True) if len(l_shapes) > 1: log.debug( "More than one shape found. Using 0. targetSurface : %s | shapes: %s" % (mesh, l_shapes)) #mi_shape = cgmMeta.validateObjArg(l_shapes[0],cgmMeta.cgmNode,noneValid=False) uMin = ATTR.get(l_shapes[0], 'mnu') uMax = ATTR.get(l_shapes[0], 'mxu') vMin = ATTR.get(l_shapes[0], 'mnv') vMax = ATTR.get(l_shapes[0], 'mxv') """uMin = mi_shape.mnu uMax = mi_shape.mxu vMin = mi_shape.mnv vMax = mi_shape.mxv""" except Exception, error: raise Exception, "Validation failure | {0}".format(error) try: #Calculation ---------------------------------------------------------------- uSize = uMax - uMin vSize = vMax - vMin uSum = uMin + uValue vSum = vMin + vValue uNormal = uSum / uSize vNormal = vSum / vSize except Exception, error: raise Exception, "Calculation |{0}".format(error)
def get_normalized_uv(mesh, uValue, vValue): """ uv Values from many functions need to be normalized to be correct when using those values for other functions The calculcaion for doing so is size = maxV - minV sum = rawV + minV normalValue = sum / size :parameters: mesh(string) | Surface to normalize to uValue(float) | uValue to normalize vValue(float) | vValue to normalize :returns Dict ------------------------------------------------------------------ 'uv'(double2) | point from which we cast 'uValue'(float) | normalized uValue 'vValue'(float) | normalized vValue :raises: Exception | if reached """ _str_func = 'get_normalized_uv' try: try: #Validation ---------------------------------------------------------------- reload(VALID) _mesh = VALID.objString(mesh, 'nurbsSurface', calledFrom=_str_func) #log.debug("|{0}| >> mesh arg: {1} | validated: {2}".format(_str_func,mesh,_mesh)) if not SEARCH.is_shape(_mesh): shape = mc.listRelatives(_mesh, shapes=True)[0] log.debug( "|{0}| >> Transform provided. using first shape: {1}". format(_str_func, shape)) else: shape = _mesh uMin = ATTR.get(shape, 'mnu') uMax = ATTR.get(shape, 'mxu') vMin = ATTR.get(shape, 'mnv') vMax = ATTR.get(shape, 'mxv') """uMin = mi_shape.mnu uMax = mi_shape.mxu vMin = mi_shape.mnv vMax = mi_shape.mxv""" except Exception, error: raise Exception, "Validation failure | {0}".format(error) try: #Calculation ---------------------------------------------------------------- uSize = uMax - uMin vSize = vMax - vMin uSum = uMin + uValue vSum = vMin + vValue uNormal = uSum / uSize vNormal = vSum / vSize except Exception, error: raise Exception, "Calculation |{0}".format(error)
def get_closest_point_data(targetSurface=None, targetObj=None, targetPoint=None): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Returns pertinent info of the closest point of a mesh to a target object - position, normal, parameterU,parameterV,closestFaceIndex,closestVertexIndex ARGUMENTS: targetObj(string) mesh(string) RETURNS: closestPointInfo(dict) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ try: _str_func = 'get_closest_point_data' _point = False if targetObj is not None: _point = POS.get(targetObj) elif targetPoint: _point = targetPoint if not _point: raise ValueError, "Must have point of reference" _loc = mc.spaceLocator()[0] POS.set(_loc, _point) _created = create_closest_point_node(_loc, targetSurface, singleReturn=True) _node = _created[1] _shape = _created[2] _type = _created[3] #_norm = get_normalized_uv(_shape, _u,_v) _res = {} _res['shape'] = _shape _res['type'] = _type _res['position'] = ATTR.get(_node, 'position') _res['normal'] = ATTR.get(_node, 'normal') if _type == 'nurbsCurve': _res['parameter'] = ATTR.get(_node, 'parameter') else: _u = mc.getAttr(_node + '.parameterU') _v = mc.getAttr(_node + '.parameterV') _res['parameterU'] = _u _res['parameterV'] = _v if _type == 'nurbsSurface': _norm = get_normalized_uv(_shape, _u, _v) _res['normUV'] = _norm['uv'] _res['normalizedU'] = _norm['uValue'] _res['normalizedV'] = _norm['vValue'] else: _res['closestFaceIndex'] = mc.getAttr(_node + '.closestFaceIndex') _res['closestVertexIndex'] = mc.getAttr(_node + '.closestVertexIndex') mc.delete([_loc], _created[0], _node) return _res except Exception, err: cgmGen.cgmExceptCB(Exception, err)
def get_closest_point_data_from_mesh(mesh=None, targetObj=None, targetPoint=None): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Returns pertinent info of the closest point of a mesh to a target object - position, normal, parameterU,parameterV,closestFaceIndex,closestVertexIndex ARGUMENTS: targetObj(string) mesh(string) RETURNS: closestPointInfo(dict) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ _str_func = 'get_closest_point_data_from_mesh' _point = False if targetObj is not None: _point = POS.get(targetObj) elif targetPoint: _point = targetPoint if not _point: raise ValueError, "Must have point of reference" _loc = mc.spaceLocator()[0] POS.set(_loc, _point) _shape = False if SEARCH.is_shape(mesh): if VALID.get_mayaType(mesh) == 'mesh': _shape = mesh else: raise ValueError, "Must be a mesh shape" else: _shape = SEARCH.get_nonintermediateShape(mesh) _shapes = mc.listRelatives(mesh, s=True, fullPath=True) """_meshes = [] for s in _shapes: if VALID.get_mayaType(s) == 'mesh': _meshes.append(s) if len(_meshes) > 1: _shape = _meshes[0]""" if not _shape: log.error("|{0}| >> Shapes...".format(_str_func)) for s in _shapes: print "{0} : {1}".format(s, VALID.get_mayaType(s)) raise ValueError, "Must have a mesh shape by now" """ make the closest point node """ _node = mc.createNode('closestPointOnMesh') """ to account for target objects in heirarchies """ ATTR.connect((targetObj + '.translate'), (_node + '.inPosition')) ATTR.connect((_shape + '.worldMesh'), (_node + '.inMesh')) ATTR.connect((_shape + '.matrix'), (_node + '.inputMatrix')) _u = mc.getAttr(_node + '.parameterU') _v = mc.getAttr(_node + '.parameterV') #_norm = get_normalized_uv(_shape, _u,_v) _res = {} _res['shape'] = _shape _res['position'] = ATTR.get(_node, 'position') _res['normal'] = ATTR.get(_node, 'normal') _res['parameterU'] = _u _res['parameterV'] = _v #_res['normalizedU'] = _norm[0] #_res['normalizedV'] = _norm[1] _res['closestFaceIndex'] = mc.getAttr(_node + '.closestFaceIndex') _res['closestVertexIndex'] = mc.getAttr(_node + '.closestVertexIndex') mc.delete([_node, _loc]) return _res
def attach_toShape(obj=None, targetShape=None, connectBy='parent', driver=None): """ :parameters: obj - transform to attach targetShape(str) - Curve, Nurbs, Mesh connectBy(str) parent - parent to track transform parentGroup - parent to group and have group follow conPoint - just point contraint conPointGroup - pointConstrain group conPointOrientGroup - point/orient constrain group conParentGroup - parent Constrain group None - just the tracker nodes :returns: resulting dat """ try: _str_func = 'attach_toShape' mObj = cgmMeta.validateObjArg(obj, 'cgmObject') mDriver = cgmMeta.validateObjArg(driver, 'cgmObject', noneValid=True) targetShape = VALID.mNodeString(targetShape) log.debug("targetShape: {0}".format(targetShape)) #Get our data... d_closest = DIST.get_closest_point_data(targetShape, mObj.mNode) log.debug("|{0}| >> jnt: {1} | {2}".format(_str_func, mObj.mNode, d_closest)) #pprint.pprint(d_closest) md_res = {} if d_closest['type'] in ['mesh', 'nurbsSurface']: log.debug("|{0}| >> Follicle mode...".format(_str_func)) _shape = SHAPES.get_nonintermediate(d_closest['shape']) log.debug("_shape: {0}".format(_shape)) l_follicleInfo = NODES.createFollicleOnMesh(_shape) i_follicleTrans = cgmMeta.asMeta(l_follicleInfo[1], 'cgmObject', setClass=True) i_follicleShape = cgmMeta.asMeta(l_follicleInfo[0], 'cgmNode') #> Name... i_follicleTrans.doStore('cgmName', mObj) i_follicleTrans.doStore('cgmTypeModifier', 'surfaceTrack') i_follicleTrans.doName() _trackTransform = i_follicleTrans.mNode #>Set follicle value... if d_closest['type'] == 'mesh': i_follicleShape.parameterU = d_closest['parameterU'] i_follicleShape.parameterV = d_closest['parameterV'] else: i_follicleShape.parameterU = d_closest['normalizedU'] i_follicleShape.parameterV = d_closest['normalizedV'] _res = [i_follicleTrans.mNode, i_follicleShape.mNode] md_res['mFollicle'] = i_follicleTrans md_res['mFollicleShape'] = i_follicleShape else: log.debug("|{0}| >> Curve mode...".format(_str_func)) #d_returnBuff = distance.returnNearestPointOnCurveInfo(obj,crv) _shape = SHAPES.get_nonintermediate(d_closest['shape']) mPOCI = cgmMeta.cgmNode(nodeType='pointOnCurveInfo') mc.connectAttr("%s.worldSpace" % _shape, "%s.inputCurve" % mPOCI.mNode) mPOCI.parameter = d_closest['parameter'] mTrack = mObj.doCreateAt() mTrack.doStore('cgmName', mObj) mTrack.doStore('cgmType', 'surfaceTrack') mTrack.doName() _trackTransform = mTrack.mNode mc.connectAttr("%s.position" % mPOCI.mNode, "%s.t" % _trackTransform) mPOCI.doStore('cgmName', mObj) mPOCI.doName() _res = [mTrack.mNode, mPOCI.mNode] if mDriver: if d_closest['type'] in ['nurbsSurface']: mFollicle = i_follicleTrans mFollShape = i_follicleShape minU = ATTR.get(_shape, 'minValueU') maxU = ATTR.get(_shape, 'maxValueU') minV = ATTR.get(_shape, 'minValueV') maxV = ATTR.get(_shape, 'maxValueV') mDriverLoc = mDriver.doLoc() mc.pointConstraint(mDriver.mNode, mDriverLoc.mNode) #mLoc = mObj.doLoc() str_baseName = "{0}_to_{1}".format(mDriver.p_nameBase, mObj.p_nameBase) mPlug_normalizedU = cgmMeta.cgmAttr( mDriverLoc.mNode, "{0}_normalizedU".format(str_baseName), attrType='float', hidden=False, lock=False) mPlug_sumU = cgmMeta.cgmAttr(mDriverLoc.mNode, "{0}_sumU".format(str_baseName), attrType='float', hidden=False, lock=False) mPlug_normalizedV = cgmMeta.cgmAttr( mDriverLoc.mNode, "{0}_normalizedV".format(str_baseName), attrType='float', hidden=False, lock=False) mPlug_sumV = cgmMeta.cgmAttr(mDriverLoc.mNode, "{0}_sumV".format(str_baseName), attrType='float', hidden=False, lock=False) #res_closest = DIST.create_closest_point_node(mLoc.mNode, mCrv_reparam.mNode,True) log.debug("|{0}| >> Closest info {1}".format(_str_func, _res)) srfNode = mc.createNode('closestPointOnSurface') mc.connectAttr("%s.worldSpace[0]" % _shape, "%s.inputSurface" % srfNode) mc.connectAttr("%s.translate" % mDriverLoc.mNode, "%s.inPosition" % srfNode) #mc.connectAttr("%s.position" % srfNode, "%s.translate" % mLoc.mNode, f=True) #mClosestPoint = cgmMeta.validateObjArg(srfNode,setClass=True) #mClosestPoint.doStore('cgmName',mObj) #mClosestPoint.doName() log.debug("|{0}| >> paramU {1}.parameterU | {2}".format( _str_func, srfNode, ATTR.get(srfNode, 'parameterU'))) log.debug("|{0}| >> paramV {1}.parameterV | {2}".format( _str_func, srfNode, ATTR.get(srfNode, 'parameterV'))) l_argBuild = [] mPlug_uSize = cgmMeta.cgmAttr(mDriverLoc.mNode, "{0}_uSize".format(str_baseName), attrType='float', hidden=False, lock=False) mPlug_vSize = cgmMeta.cgmAttr(mDriverLoc.mNode, "{0}_vSize".format(str_baseName), attrType='float', hidden=False, lock=False) l_argBuild.append("{0} = {1} - {2}".format( mPlug_vSize.p_combinedName, maxV, minV)) l_argBuild.append("{0} = {1} - {2}".format( mPlug_uSize.p_combinedName, maxU, minU)) l_argBuild.append("{0} = {1} + {2}.parameterU".format( mPlug_sumU.p_combinedName, minU, srfNode)) l_argBuild.append("{0} = {1} / {2}".format( mPlug_normalizedU.p_combinedName, mPlug_sumU.p_combinedName, mPlug_uSize.p_combinedName)) l_argBuild.append("{0} = {1} + {2}.parameterV".format( mPlug_sumV.p_combinedName, minV, srfNode)) l_argBuild.append("{0} = {1} / {2}".format( mPlug_normalizedV.p_combinedName, mPlug_sumV.p_combinedName, mPlug_vSize.p_combinedName)) for arg in l_argBuild: log.debug("|{0}| >> Building arg: {1}".format( _str_func, arg)) NODEFACTORY.argsToNodes(arg).doBuild() ATTR.connect(mPlug_normalizedU.p_combinedShortName, '{0}.parameterU'.format(mFollShape.mNode)) ATTR.connect(mPlug_normalizedV.p_combinedShortName, '{0}.parameterV'.format(mFollShape.mNode)) md_res['mDriverLoc'] = mDriverLoc elif d_closest['type'] in ['curve', 'nurbsCurve']: mDriverLoc = mDriver.doLoc() mc.pointConstraint(mDriver.mNode, mDriverLoc.mNode) _resClosest = DIST.create_closest_point_node( mDriverLoc.mNode, _shape, True) _loc = _resClosest[0] md_res['mDriverLoc'] = mDriverLoc md_res['mDrivenLoc'] = cgmMeta.asMeta(_loc) md_res['mTrack'] = mTrack else: log.warning( cgmGEN.logString_msg( _str_func, "Shape type not currently supported for driver setup. Type: {0}" .format(d_closest['type']))) #if connectBy is None: #return _res if connectBy == 'parent': mObj.p_parent = _trackTransform elif connectBy == 'conPoint': mc.pointConstraint(_trackTransform, mObj.mNode, maintainOffset=True) elif connectBy == 'conParent': mc.parentConstraint(_trackTransform, mObj.mNode, maintainOffset=True) elif connectBy == 'parentGroup': mGroup = mObj.doGroup(asMeta=True) #_grp = TRANS.group_me(obj,True) #TRANS.parent_set(_grp,_trackTransform) mGroup.p_parent = _trackTransform _res = _res + [mGroup.mNode] elif connectBy == 'conPointGroup': mLoc = mObj.doLoc() mLoc.p_parent = _trackTransform mGroup = mObj.doGroup(asMeta=True) mc.pointConstraint(mLoc.mNode, mGroup.mNode) _res = _res + [mGroup.mNode] elif connectBy == 'conPointOrientGroup': mLoc = mObj.doLoc() mLoc.p_parent = _trackTransform mGroup = mObj.doGroup(asMeta=True) mc.pointConstraint(mLoc.mNode, mGroup.mNode) mc.orientConstraint(mLoc.mNode, mGroup.mNode) _res = _res + [mGroup.mNode] elif connectBy == 'conParentGroup': mLoc = mObj.doLoc() mLoc.p_parent = _trackTransform mGroup = mObj.doGroup(asMeta=True) mc.parentConstraint(mLoc.mNode, mGroup.mNode) _res = _res + [mGroup.mNode] elif connectBy is None: pass else: raise NotImplementedError, "|{0}| >>invalid connectBy: {1}".format( _str_func, connectBy) if md_res: return _res, md_res return _res #pprint.pprint(vars()) except Exception, err: cgmGEN.cgmExceptCB(Exception, err)
m1 = cgmMeta.asMeta('l_arm_part') mShapeCast.go(m1,['segmentFK_Loli']) mShapeCast.go(m1,['settings']) mShapeCast.go(m1,['midIK']) mShapeCast.go(m1,['hand']) #Issues======================================================== import cgm.core.cgmPy.validateArgs as VALID reload(VALID) VALID.is_transform('cgmObject_poly2_parentConstraint1') mc.listAttr('cgmObject_poly2_parentConstraint1') ATTR.set('cgmObject_poly2_parentConstraint1','ty',100) ATTR.get('cgmObject_poly2_parentConstraint1','ty') import cgm.core.lib.curve_Utils as CURVES reload(CURVES) import maya.cmds as mc CURVES.mirror_worldSpace('l_eye_block|uprLid_rigHelper','r_eye_block|uprLid_rigHelper') CURVES.mirror_worldSpace(mc.ls(sl=1)[0],mc.ls(sl=1)[1]) CURVES.Copy eyeBlock = cgmMeta.asMeta('r_eyelids_part') eyeBlock.doSkeletonize() #Joints ==========================================================================
def get_objNameDict(obj, ignore=[False]): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Returns a generated dictionary of name info ARGUMENTS: obj(string) - object ignore(string) - default is 'none', only culls out cgmtags that are generated via returnCGMOrder() function RETURNS: namesDict(string) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ try: _str_funcName = "get_objNameDict" log.debug(">>> %s >>> " % (_str_funcName) + "=" * 75) if type(ignore) is not list: ignore = [ignore] namesDict = {} divider = returnCGMDivider() order = returnCGMOrder() nameBuilder = [] #>>> Get our cgmVar_iables #userAttrs = attributes.returnUserAttributes(obj) #cgmAttrs = lists.returnMatchList(userAttrs,order) #>>> Tag ignoring if ignore: for i in ignore: if i in order: order.remove(i) #>>> Geting our data for tag in order: tagInfo = SEARCH.get_tagInfo(obj, tag) if tagInfo is not False: namesDict[tag] = (tagInfo) if 'cgmIterator' in order: _iterator = ATTR.get(obj, 'cgmIterator') if _iterator is not False: log.debug("Iterator found") namesDict['cgmIterator'] = (_iterator) # remove tags up stream that we don't want if they don't exist on the actual object""" if not mc.objExists(obj + '.cgmTypeModifier'): if namesDict.get('cgmTypeModifier') != None: namesDict.pop('cgmTypeModifier') log.debug("%s >>> initial nameDict: %s " % (_str_funcName, namesDict)) #>>> checks if the names exist as objects or it's a shape node ChildNameObj = False nameObj = False cgmNameAttrType = ATTR.get_type(obj, 'cgmName') log.debug("cgmNameAttrType: {0}".format(cgmNameAttrType)) if cgmNameAttrType == 'message': #nameObj = SEARCH.get_nodeTagInfo(obj,'cgmName') nameObj = ATTR.get_message( obj, 'cgmName', simple=True) #SEARCH.get_nodeTagInfo(obj,'cgmName') if nameObj: nameObj = nameObj[0] nameObjDict = get_objNameDict(nameObj) #pprint.pprint(nameObjDict) for k in 'cgmDirection', 'cgmPosition': #if nameObjDict.get(k) and namesDict.get(k): try: namesDict.pop(k) except: pass log.debug("nameObj: {0}".format(nameObj)) namesDict['cgmName'] = names.getBaseName(nameObj) return namesDict typeTag = SEARCH.get_nodeTagInfo(obj, 'cgmType') isType = SEARCH.VALID.get_mayaType(obj) isShape = SEARCH.VALID.is_shape(obj) """first see if it's a group """ if isType == 'group' and typeTag == False: childrenObjects = TRANS.children_get(obj, False) log.debug("%s >>> group and no typeTag..." % (_str_funcName)) """ if it's a transform group """ groupNamesDict = {} if not nameObj: groupNamesDict['cgmName'] = childrenObjects[0] else: groupNamesDict['cgmName'] = nameObj groupNamesDict['cgmType'] = CORESHARE.d_cgmTypes.get('transform') if namesDict.get('cgmTypeModifier') != None: groupNamesDict['cgmTypeModifier'] = namesDict.get( 'cgmTypeModifier') return groupNamesDict """ see if there's a name tag""" elif isType in ['joint']: return namesDict elif isShape: #If we have a name object or shape log.debug("%s >>> nameObj not None or isType is 'shape'..." % (_str_funcName)) if isShape: #log.debug("%s >>> nameObj exists: '%s'..."%(_str_funcName,nameObj)) #Basic child object with cgmName tag childNamesDict = {} childNamesDict['cgmName'] = namesDict.get('cgmName') childNamesDict['cgmType'] = namesDict.get('cgmType') if namesDict.get('cgmTypeModifier') != None: childNamesDict['cgmTypeModifier'] = namesDict.get( 'cgmTypeModifier') if namesDict.get('cgmIterator') != None: childNamesDict['cgmIterator'] = namesDict.get( 'cgmIterator') return childNamesDict elif isShape or 'Constraint' in isType: """if so, it's a child name object""" log.debug("%s >>> child name object..." % (_str_funcName)) childNamesDict = {} childNamesDict['cgmName'] = TRANS.parent_get(obj, False) childNamesDict['cgmType'] = namesDict.get('cgmType') return childNamesDict else: log.debug("%s >>> No special case found. %s" % (_str_funcName, namesDict)) return namesDict else: return namesDict except Exception, err: raise cgmGEN.cgmExceptCB(Exception, err, msg=vars())
def get_uiScollList_dat(arg=None, tag=None, counter=0, blockList=None, stringList=None, showSide=True, presOnly=False): ''' Log a dictionary. :parameters: arg | dict tag | string label for the dict to log. :raises: TypeError | if not passed a dict ''' try: _str_func = 'walk_blockDict' if arg == None: arg = get_scene_block_heirarchy(True) if not isinstance(arg, dict): raise ValueError, "need dict: {0}".format(arg) if blockList is None: blockList = [] if stringList is None: stringList = [] l_keys = arg.keys() if not l_keys: return [], [] d_keys_to_idx = {} d_idx_to_keys = {} l_mNodeKeys = [] for i, k in enumerate(l_keys): l_mNodeKeys.append(k.mNode) d_keys_to_idx[k.mNode] = i d_idx_to_keys[i] = k l_mNodeKeys.sort() l_keys = [] #.reset and fill... for KmNode in l_mNodeKeys: l_keys.append(d_idx_to_keys[d_keys_to_idx[KmNode]]) counter += 1 for k in l_keys: try: mBlock = k #>>>Build strings _short = mBlock.p_nameShort #log.debug("|{0}| >> scroll list update: {1}".format(_str_func, _short)) _l_report = [] _l_parents = mBlock.getBlockParents(False) log.debug("{0} : {1}".format(mBlock.mNode, _l_parents)) _len = len(_l_parents) if _len: s_start = ' ' * _len + ' ' else: s_start = '' if counter == 1: s_start = s_start + " " else: #s_start = s_start + '-[{0}] '.format(counter-1) #s_start = s_start + ' ^-' + '--'*(counter-1) + ' ' s_start = s_start + ' ' + ' ' * (counter - 1) + ' ' if presOnly: _str = copy.copy(s_start) else: if showSide: if mBlock.getMayaAttr('side'): _v = mBlock.getEnumValueString('side') _l_report.append(_d_scrollList_shorts.get(_v, _v)) if mBlock.getMayaAttr('position'): _v = mBlock.getMayaAttr('position') if _v.lower() not in ['', 'none']: _l_report.append(_d_scrollList_shorts.get(_v, _v)) l_name = [] #l_name.append( ATTR.get(_short,'blockType').capitalize() ) _cgmName = mBlock.getMayaAttr('cgmName') l_name.append('"{0}"'.format(_cgmName)) #_l_report.append(STR.camelCase(' '.join(l_name))) _l_report.append(' - '.join(l_name)) #_l_report.append(ATTR.get(_short,'blockState')) if mBlock.getMayaAttr('isBlockFrame'): _l_report.append("[FRAME]") else: _state = mBlock.getEnumValueString('blockState') _blockState = _d_scrollList_shorts.get(_state, _state) _l_report.append("[{0}]".format(_blockState.upper())) """ if mObj.hasAttr('baseName'): _l_report.append(mObj.baseName) else: _l_report.append(mObj.p_nameBase)""" if mBlock.isReferenced(): _l_report.append("Referenced") _str = s_start + " | ".join(_l_report) #Block dat l_block = [] _blockProfile = mBlock.getMayaAttr('blockProfile') l_block.append(ATTR.get(_short, 'blockType').capitalize()) if _blockProfile: if _cgmName in _blockProfile: _blockProfile = _blockProfile.replace(_cgmName, '') _blockProfile = STR.camelCase(_blockProfile) l_block.append(_blockProfile) _str = _str + (' - [{0}]'.format("-".join(l_block))) log.debug(_str + " >> " + mBlock.mNode) #log.debug("|{0}| >> str: {1}".format(_str_func, _str)) stringList.append(_str) blockList.append(mBlock) buffer = arg[k] if buffer: get_uiScollList_dat(buffer, k, counter, blockList, stringList, showSide, presOnly) """if counter == 0: print('> {0} '.format(mBlock.mNode)) else: print('-'* counter + '> {0} '.format(mBlock.mNode) )""" except Exception, err: log.error("Failed: {0} | {1}".format(k, err)) log.error("List: {0}".format(_l_report)) return blockList, stringList
def get_closest_point(source=None, targetSurface=None, loc=False): """ Get the closest point on a target surface/curve/mesh to a given point or object. Evaluates to all sub shapes to get closest point for multi shape targets. :parameters: source(str/vector) -- source point or object targetSurface -- surface to check transform, nurbsSurface, curve, mesh supported loc -- whether to loc point found :returns position, distance, shape (list) """ _str_func = 'get_closest_point' _point = False if VALID.vectorArg(source) is not False: _point = source elif mc.objExists(source): _point = POS.get(source) if not _point: raise ValueError, "Must have point of reference" _loc = mc.spaceLocator(n='get_closest_point_loc')[0] POS.set(_loc, _point) if SEARCH.is_shape(targetSurface): _shapes = [targetSurface] elif VALID.is_component(targetSurface): _shapes = mc.listRelatives(VALID.get_component(targetSurface)[1], s=True, fullPath=True) else: _shapes = mc.listRelatives(targetSurface, s=True, fullPath=True) if not _shapes: log.error("|{0}| >> No shapes found. Skipping: {1}".format( _str_func, targetSurface)) mc.delete(_loc) return False _l_res_positions = [] _l_res_shapes = [] _l_res_distances = [] for s in _shapes: _type = VALID.get_mayaType(s) if _type not in ['mesh', 'nurbsSurface', 'nurbsCurve']: log.error( "|{0}| >> Unsupported target surface type. Skipping: {1} |{2} | {3}" .format(_str_func, s, _type)) _l_res_positions.append(False) continue if _type == 'mesh': _node = mc.createNode('closestPointOnMesh') ATTR.connect((_loc + '.translate'), (_node + '.inPosition')) ATTR.connect((s + '.worldMesh'), (_node + '.inMesh')) ATTR.connect((s + '.worldMatrix'), (_node + '.inputMatrix')) _pos = ATTR.get(_node, 'position') _tmpLoc = mc.spaceLocator(n='tmp')[0] ATTR.connect((_node + '.position'), (_tmpLoc + '.translate')) _l_res_positions.append(POS.get(_tmpLoc)) mc.delete(_node) mc.delete(_tmpLoc) elif _type == 'nurbsSurface': closestPointNode = mc.createNode('closestPointOnSurface') ATTR.set(closestPointNode, 'inPositionX', _point[0]) ATTR.set(closestPointNode, 'inPositionY', _point[1]) ATTR.set(closestPointNode, 'inPositionZ', _point[2]) ATTR.connect((s + '.worldSpace'), (closestPointNode + '.inputSurface')) _l_res_positions.append(ATTR.get(closestPointNode, 'position')) mc.delete(closestPointNode) elif _type == 'nurbsCurve': _node = mc.createNode('nearestPointOnCurve') p = [] distances = [] mc.connectAttr((_loc + '.translate'), (_node + '.inPosition')) mc.connectAttr((s + '.worldSpace'), (_node + '.inputCurve')) p = [ mc.getAttr(_node + '.positionX'), mc.getAttr(_node + '.positionY'), mc.getAttr(_node + '.positionZ') ] _l_res_positions.append(p) mc.delete(_node) mc.delete(_loc) if not _l_res_positions: raise ValueError, "No positions found" for p in _l_res_positions: if p: _l_res_distances.append(get_distance_between_points(_point, p)) else: _l_res_distances.append('no') closest = min(_l_res_distances) _idx = _l_res_distances.index(closest) _pos = _l_res_positions[_idx] if not _pos: return False #raise ValueError,"Failed to find point" if loc: _loc = mc.spaceLocator(n='get_closest_point_loc')[0] POS.set(_loc, _pos) return _pos, _l_res_distances[_idx], _shapes[_idx]
def create_closest_point_node(source=None, targetSurface=None, singleReturn=False): """ Create a closest point on surface node and wire it :parameters: source(str/vector) -- source point or object targetSurface -- surface to check transform, nurbsSurface, curve, mesh supported singleReturn - only return single return if we have :returns node(list) """ try: _str_func = 'create_closest_point_node' _transform = False if VALID.vectorArg(source) is not False: _transform = mc.spaceLocator(n='closest_point_source_loc')[0] POS.set(_transform, source) elif mc.objExists(source): if SEARCH.is_transform(source): _transform = source elif VALID.is_component(source): _transform = mc.spaceLocator( n='{0}_loc'.format(NAMES.get_base(source)))[0] POS.set(_transform, POS.get(source)) else: _transform = SEARCH.get_transform(source) if not _transform: raise ValueError, "Must have a transform" if SEARCH.is_shape(targetSurface): l_shapes = [targetSurface] else: l_shapes = mc.listRelatives(targetSurface, s=True, fullPath=True) if not l_shapes: raise ValueError, "Must have shapes to check." _nodes = [] _locs = [] _types = [] _shapes = [] for s in l_shapes: _type = VALID.get_mayaType(s) if _type not in ['mesh', 'nurbsSurface', 'nurbsCurve']: log.error( "|{0}| >> Unsupported target surface type. Skipping: {1} |{2} " .format(_str_func, s, _type)) continue _loc = mc.spaceLocator()[0] _res_loc = mc.rename( _loc, '{0}_to_{1}_result_loc'.format(NAMES.get_base(source), NAMES.get_base(s))) _locs.append(_res_loc) _types.append(_type) _shapes.append(s) if _type == 'mesh': _node = mc.createNode('closestPointOnMesh') _node = mc.rename( _node, "{0}_to_{1}_closePntMeshNode".format( NAMES.get_base(source), NAMES.get_base(s))) ATTR.connect((_transform + '.translate'), (_node + '.inPosition')) ATTR.connect((s + '.worldMesh'), (_node + '.inMesh')) ATTR.connect((s + '.worldMatrix'), (_node + '.inputMatrix')) _pos = ATTR.get(_node, 'position') ATTR.connect((_node + '.position'), (_res_loc + '.translate')) _nodes.append(_node) elif _type == 'nurbsSurface': closestPointNode = mc.createNode('closestPointOnSurface') closestPointNode = mc.rename( closestPointNode, "{0}_to_{1}_closePntSurfNode".format( NAMES.get_base(source), NAMES.get_base(s))) mc.connectAttr((_transform + '.translate'), (closestPointNode + '.inPosition')) #attributes.doSetAttr(closestPointNode,'inPositionX',_point[0]) #attributes.doSetAttr(closestPointNode,'inPositionY',_point[1]) #attributes.doSetAttr(closestPointNode,'inPositionZ',_point[2]) ATTR.connect((s + '.worldSpace'), (closestPointNode + '.inputSurface')) ATTR.connect((closestPointNode + '.position'), (_res_loc + '.translate')) _nodes.append(closestPointNode) elif _type == 'nurbsCurve': _node = mc.createNode('nearestPointOnCurve') _node = mc.rename( _node, "{0}_to_{1}_nearPntCurveNode".format( NAMES.get_base(source), NAMES.get_base(s))) p = [] distances = [] mc.connectAttr((_transform + '.translate'), (_node + '.inPosition')) mc.connectAttr((s + '.worldSpace'), (_node + '.inputCurve')) ATTR.connect((_node + '.position'), (_res_loc + '.translate')) _nodes.append(_node) if not singleReturn: return _locs, _nodes, _shapes, _types _l_distances = [] pos_base = POS.get(_transform) for i, n in enumerate(_nodes): p2 = POS.get(_locs[i]) _l_distances.append(get_distance_between_points(pos_base, p2)) if not _l_distances: raise ValueError, "No distance value found" closest = min(_l_distances) _idx = _l_distances.index(closest) for i, n in enumerate(_nodes): if i != _idx: mc.delete(n, _locs[i]) return _locs[_idx], _nodes[_idx], _shapes[_idx], _types[_idx] except Exception, err: cgmGen.cgmExceptCB(Exception, err)
def lever(self, ball=False): try: _str_func = 'lever_digit' log_start(_str_func) mBlock = self.mBlock mRigNull = self.mRigNull _offset = self.v_offset _jointOrientation = self.d_orientation['str'] ml_formHandles = self.ml_formHandles ml_prerigHandles = self.ml_prerigHandles mHandleFactory = self.mHandleFactory #Mesh shapes ---------------------------------------------------------- mMesh_tmp = self.mBlock.atUtils('get_castMesh') str_meshShape = mMesh_tmp.getShapes()[0] #Figure out our knots ---------------------------------------------------- mMain = self.ml_formHandlesUse[0] mMainLoft = mMain.loftCurve idxMain = self.ml_shapers.index(mMainLoft) minU = ATTR.get(str_meshShape, 'minValueU') maxU = ATTR.get(str_meshShape, 'maxValueU') f_factor = (maxU - minU) / (20) pprint.pprint(vars()) #reload(SURF) #Meat ============================================================== mLeverDirect = mRigNull.getMessageAsMeta('leverDirect') mLeverFK = mRigNull.getMessageAsMeta('leverFK') mLeverControlCast = mLeverDirect if not mLeverControlCast: mLeverControlCast = mLeverFK log.debug("|{0}| >> mLeverControlCast: {1}".format( _str_func, mLeverControlCast)) dist_lever = DIST.get_distance_between_points( ml_prerigHandles[0].p_position, ml_prerigHandles[1].p_position) log.debug("|{0}| >> Lever dist: {1}".format(_str_func, dist_lever)) #Dup our rig joint and move it mDup = mLeverControlCast.doDuplicate(po=True) mDup.p_parent = mLeverControlCast mDup.resetAttrs() ATTR.set(mDup.mNode, 't{0}'.format(_jointOrientation[0]), dist_lever * .5) l_lolis = [] l_starts = [] _mTar = mDup if ball: #Loli =============================================================== mDefineLeverObj = mBlock.defineLeverHelper _mVectorLeverUp = MATH.get_obj_vector(mDefineLeverObj.mNode, 'y+', asEuclid=True) #mOrientHelper = mBlock.orientHelper #_mVectorLeverUp = MATH.get_obj_vector(mOrientHelper.mNode,'y+',asEuclid=True) mBall_tmp = mBlock.atUtils('get_castMesh') str_ballShape = mBall_tmp.getShapes()[0] pos = RAYS.cast(str_ballShape, startPoint=_mTar.p_position, vector=_mVectorLeverUp).get('near') #pos = RAYS.get_cast_pos(_mTar.mNode,_mVectorLeverUp,shapes = str_ballShape) #SNAPCALLS.get_special_pos([_mTar,str_ballShape],'castNear',str_settingsDirections,False) vec = MATH.get_vector_of_two_points(_mTar.p_position, pos) newPos = DIST.get_pos_by_vec_dist(pos, vec, _offset * 4) ball = CURVES.create_fromName('sphere', _offset * 2) mBall = cgmMeta.cgmObject(ball) mBall.p_position = newPos SNAP.aim_atPoint( mBall.mNode, _mTar.p_position, aimAxis=_jointOrientation[0] + '+', mode='vector', vectorUp=_mTar.getAxisVector(_jointOrientation[0] + '-')) line = mc.curve(d=1, ep=[pos, newPos], os=True) l_lolis.extend([ball, line]) ATTR.set(mDup.mNode, 't{0}'.format(_jointOrientation[0]), dist_lever * .8) CORERIG.shapeParent_in_place(mLeverFK.mNode, l_lolis, False) mBall_tmp.delete() #Main clav section ======================================== """ ml_clavShapes = BUILDUTILS.shapes_fromCast(self, targets= [mLeverControlCast.mNode, mDup.mNode], aimVector= self.d_orientation['vectorOut'], connectionPoints = 5, f_factor=0, offset=_offset, mode = 'frameHandle')""" l_curves = SURF.get_splitValues(str_meshShape, knotIndices=[0, idxMain], mode='u', insertMax=False, preInset=f_factor * .5, postInset=-f_factor * .5, curvesCreate=True, curvesConnect=True, connectionPoints=6, offset=self.v_offset) ml_shapes = cgmMeta.validateObjListArg(l_curves) mHandleFactory.color(mLeverFK.mNode, controlType='sub') CORERIG.shapeParent_in_place(mLeverFK.mNode, ml_shapes[0].mNode, False, replaceShapes=False) mDup.delete() for mShape in ml_shapes: try: mShape.delete() except: pass mMesh_tmp.delete() except Exception, err: cgmGEN.cgmExceptCB(Exception, err, localDat=vars())
def optimize(nodeTypes='multiplyDivide'): _str_func = 'optimize' log.debug("|{0}| >> ".format(_str_func) + '-' * 80) _nodeTypes = VALID.listArg(nodeTypes) d_modeToNodes = {} d_modeToPlugs = {} l_oldNodes = [] for t in _nodeTypes: if t in ['plusMinusAverage']: raise ValueError, "Don't handle type: {0}".format(t) nodes = mc.ls(type=t) l_oldNodes.extend(nodes) for n in nodes: _mode = ATTR.get(n, 'operation') _operator = ATTR.get_enumValueString(n, 'operation') #d_operator_to_NodeType[t][_mode] if not d_modeToNodes.get(_mode): d_modeToNodes[_mode] = [] d_modeToNodes[_mode].append(n) d_plugs = {} d_plugValues = {} for i, inPlug in enumerate(d_node_to_input[t]['in']): d_plugs[i] = ATTR.get_children(n, inPlug) or [] for p in d_plugs[i]: c = ATTR.get_driver(n, p, False, skipConversionNodes=True) if c: d_plugValues[p] = c else: d_plugValues[p] = ATTR.get(n, p) l_outs = ATTR.get_children(n, d_node_to_input[t]['out']) or [] for p in l_outs: d_plugValues[p] = ATTR.get_driven(n, p, False, skipConversionNodes=True) #pprint.pprint(d_modeToNodes) #pprint.pprint(d_plugs) #print l_outs #print cgmGeneral._str_subLine #pprint.pprint(d_plugValues) for i in range(len(l_outs)): _out = d_plugValues[l_outs[i]] if _out: d_set = {'out': _out, 'in': []} log.debug("|{0}| >> Output found on: {1} ".format( _str_func, _out)) _keys = d_plugs.keys() _keys.sort() for k in _keys: d_set['in'].append(d_plugValues[d_plugs[k][i]]) #d_set['in'].append(d_plugs[k][i]) #pprint.pprint(d_set) if not d_modeToPlugs.get(_mode): d_modeToPlugs[_mode] = [] d_modeToPlugs[_mode].append(d_set) # if VALID.stringArg() l_inPlugs = ['input1', 'input2'] l_outplugs = [u'output'] l_new = [] _cnt = 0 for operator, d_sets in d_modeToPlugs.iteritems(): if operator == 1: for nodeSet in d_sets: newNode = mc.createNode('multDoubleLinear') newNode = mc.rename(newNode, 'optimize_{0}_mdNode'.format(_cnt)) _cnt += 1 l_new.append(newNode) _ins = d_set['in'] _outs = d_set['out'] for iii, inPlug in enumerate(_ins): if mc.objExists(inPlug): ATTR.connect(inPlug, "{0}.{1}".format(newNode, l_inPlugs[iii])) else: ATTR.set(newNode, l_inPlugs[iii], inPlug) for out in _outs: ATTR.connect("{0}.output".format(newNode), out) #pprint.pprint(d_setsSorted) print len(d_sets) #print len(d_setsSorted) """ l_inPlugs = {0: [u'input1X', u'input1Y', u'input1Z'], 1: [u'input2X', u'input2Y', u'input2Z']} l_outplugs = [u'outputX', u'outputY', u'outputZ'] for operator,d_sets in d_modeToPlugs.iteritems(): d_setsSorted = LISTS. get_chunks(d_sets,3) for nodeSet in d_setsSorted: newNode = mc.createNode('multiplyDivide') newNode = mc.rename(newNode,'optimize_{0}_mdNode'.format(_cnt)) _cnt+=1 l_new.append(newNode) ATTR.set(newNode,'operation',operator) for i,d_set in enumerate(nodeSet): _ins = d_set['in'] _outs = d_set['out'] for iii,inPlug in enumerate(_ins): if mc.objExists(inPlug): ATTR.connect(inPlug, "{0}.{1}".format(newNode, l_inPlugs[iii][i])) else: ATTR.set(newNode,l_inPlugs[iii][i], inPlug) for out in _outs: ATTR.connect("{0}.{1}".format(newNode, l_outplugs[i]), out) #pprint.pprint(d_setsSorted) print len(d_sets) print len(d_setsSorted) """ mc.delete(l_oldNodes) return len(l_new)
def get_splitValues(surface=None, values=[], mode='u', knotIndices=[], insertMin=False, insertMax=False, preInset=None, postInset=None, offset=None, curvesCreate=False, curvesConnect=False, connectionPoints=9): """ Function to split a curve up u positionally :parameters: 'curve'(None) -- Curve to split curvesCreate(bool) - create new curves from the new values curvesConnect(bool) - whether to connect the first and last curves connectionPoints(int) - how many points of connection to use :returns list of values(list) hat tip: http://ewertb.soundlinker.com/mel/mel.074.php """ _str_func = 'get_splitValues' log.debug("|{0}| >> ".format(_str_func) + '-' * 80) _shape = SHAPES.get_nonintermediate(surface) if mode == 'u': l_base = get_dat(_shape, uKnots=True)['uKnots'] minKnot = ATTR.get(_shape, 'minValueU') maxKnot = ATTR.get(_shape, 'maxValueU') else: l_base = get_dat(_shape, vKnots=True)['vKnots'] minKnot = ATTR.get(_shape, 'minValueV') maxKnot = ATTR.get(_shape, 'maxValueV') l_sets = [] log.debug("|{0}| >> l_base: {1}".format(_str_func, l_base)) if knotIndices: values = [l_base[v] for v in knotIndices] for i, v in enumerate(values): log.debug("|{0}| >> Processing: {1} | {2}".format(_str_func, i, v) + "-" * 40) _last = False if v == values[-1]: log.debug("|{0}| >> last...".format(_str_func)) _last = True if preInset: v += preInset log.debug("|{0}| >> preinset: {1}".format(_str_func, v)) _l = [v] _stop = False for knot in l_base: if _stop or MATH.is_float_equivalent(knot, v) == v: continue log.debug("|{0}| >> checking knot: {1}".format(_str_func, knot)) if _last: if knot > v: _stop = True _l.append(knot) if knot > v or knot < v: if _last != True and knot < values[i + 1] and knot > v: _l.append(knot) log.debug("|{0}| >> knot add: {1}".format(_str_func, _l)) """ if v == values[-1]: if knot < maxKnot: _l.append(knot) elif _last != True and knot < values[i+1]: _l.append(knot)""" if _last and insertMax: l_add = [] for v2 in l_base: if v2 > _l[-1]: l_add.append(v2) for v2 in l_add: _l.append(v2) _l.append(maxKnot) if _last != True: _l.append(values[i + 1]) if insertMin and i == 0: _l.insert(0, minKnot) if postInset: vPost = _l[-1] + postInset if vPost < _l[-2]: log.debug("|{0}| >> alternate postInset".format(_str_func)) vPost = _l[-2] + postInset log.debug("|{0}| >> postInset: {1} | new: {2}".format( _str_func, _l[-1], vPost)) if len(_l) > 1: if vPost > max(_l[:-1]): log.debug( "|{0}| >> v post creater the max".format(_str_func)) _l[-1] = vPost else: _l = _l[:-1] else: _l.append(vPost) """ if _last != True: for v2 in _l: if v2 > v: _l.remove(v2)""" _l = LISTS.get_noDuplicates(_l) _l.sort() l_sets.append(_l) log.debug("|{0}| >> result: {1} | {2} | {3}".format( _str_func, i, v, _l)) l_pre = copy.copy(l_sets) #pprint.pprint(vars()) if not curvesCreate: return l_sets log.debug("|{0}| >> creating curves...".format(_str_func)) l_newCurves = [] d_curves = {} l_finalCurves = [] def getCurve(uValue, l_newCurves): _crv = d_curves.get(uValue) if _crv: return _crv _crv = mc.duplicateCurve("{0}.u[{1}]".format(_shape, uValue), ch=0, rn=0, local=0)[0] if offset: DIST.offsetShape_byVector(_crv, offset, component='cv') d_curves[uValue] = _crv log.debug("|{0}| >> created: {1} ...".format(_str_func, _crv)) l_newCurves.append(_crv) return _crv for i, uSet in enumerate(l_sets): _loftCurves = [getCurve(uValue, l_newCurves) for uValue in uSet] """ if len(uSet)<2: l_finalCurves.append(mc.duplicate(_loftCurves[0])[0]) continue""" log.debug("|{0}| >> {1} | u's: {2}".format(_str_func, i, uSet)) """ if i == 0 and str_start: _pair = [str_start,c,l_newCurves[i+1]] else: _pair = [c,l_newCurves[i+1]]""" if len(_loftCurves) == 1: l_mainCurves = [mc.duplicate(_loftCurves[0])[0]] else: crvBase = mc.duplicate(_loftCurves[0])[0] crvEnd = mc.duplicate(_loftCurves[-1])[0] l_mainCurves = [crvBase, crvEnd] if curvesConnect: log.debug("|{0}| >> {1} | Making connectors".format( _str_func, i)) d_epPos = {} for i, crv in enumerate(_loftCurves): _l = CURVES.getUSplitList(crv, connectionPoints, rebuild=True, rebuildSpans=30)[:-1] for ii, p in enumerate(_l): if not d_epPos.get(ii): d_epPos[ii] = [] _l = d_epPos[ii] _l.append(p) for k, points in d_epPos.iteritems(): log.debug("|{0}| >> {1} | k: {1} | points: {2}".format( _str_func, k, points)) try: crv_connect = mc.curve(d=1, ep=points, os=True) #CURVES.create_fromList(posList=points) l_mainCurves.append(crv_connect) except Exception, err: print err for crv in l_mainCurves[1:]: CORERIG.shapeParent_in_place(l_mainCurves[0], crv, False) #ml_shapes.append(cgmMeta.validateObjArg(l_mainCurves[0])) l_finalCurves.append(l_mainCurves[0])