def createCurve(ptList,start,end,group=''): ''' ''' # Initialize Curves crvList = [] for pt in ptList: pos = mc.pointPosition(pt) curve = mc.curve(p=[pos,pos],d=1) curve = mc.rename(curve,pt+'_curve') crvList.append(curve) # Track Curves for i in range(start,end+1): mc.currentTime(i) for n in range(len(ptList)): pos = mc.pointPosition(ptList[n]) mc.curve(crvList[n],a=True,p=pos) # Remove Initial CV and Rebuild for crv in crvList: mc.delete(crv+'.cv[0]') mc.rebuildCurve(crv,ch=False,rpo=True,rt=0,end=1,kr=2,kcp=True,kep=True) # Group Curves if group: # Check Group if not mc.objExists(group): group = mc.group(em=True,n=group) # Parent Curves to Group mc.parent(crvList,group) # Return Result if group: return [group] else: return crvList
def distanceBetween(*args): # distance between two points if len(args) == 0: args = mc.ls(sl=True) if len(args) == 0: return p = [] for a in args: if isIterable(a) and len(a) >= 3 and isinstance(a[0], (float, long, int)) and len(a) >= 3: p.append(a) elif isinstance(a, basestring) and mc.objExists(a): if len(a.split(".")) > 1: try: p.append(mc.pointPosition(a)) except: pass else: try: p.append(mc.pointPosition(a + ".rp")) except: err = True if len(p) < 1: return if len(p) > 2: p[:] = p[:2] dx = abs(p[0][0] - p[1][0]) dy = abs(p[0][1] - p[1][1]) dz = abs(p[0][2] - p[1][2]) return sqrt(dx * dx + dy * dy + dz * dz)
def doIt(self,argList): #print "Trying to build a house..." selected = cmds.ls(orderedSelection=True) if(len(selected) != 1): house = building([20,20],[0,0,0]) else: print "Selected %s" %(selected[0]) tmp = selected[0] a = cmds.pointPosition(tmp+'.vtx[0]') b = cmds.pointPosition(tmp+'.vtx[1]') c = cmds.pointPosition(tmp+'.vtx[2]') d = cmds.pointPosition(tmp+'.vtx[3]') width = int(b[0] - a[0]) print width depth = int(b[2] - c[2]) print depth offsetX = b[0] - width/2 offsetY = int(b[1]) offsetZ = b[2] - depth/2 # print "Calculated %d x %d lot at [ %d, %d ]." %(width, depth, offsetX, offsetY ) house = building([width-2,depth-2],[offsetX,offsetY,offsetZ]) house.build()
def curveCoord(surfaceSkin,influence,controlPoints,curve): ''' Set the target coordinates for the specified control points to lie along a given isoparm @param surfaceSkin: surfaceSkin node to apply the coordinates to @type surfaceSkin: str @param influence: surfaceSkin influence to get coordinate for @type influence: str @param controlPoints: List of control points to set the target coordinates for @type controlPoints: list @param curve: Curve to derive coordinates from @type curve: str ''' # Check surfaceSkin if not ssUtil.verifyNode(surfaceSkin): raise Exception('Object "'+surfaceSkin+'" is not a valid surfaceSkin node!') # Iterate through control point list for controlPoint in controlPoints: # Get component position pos = mc.pointPosition(controlPoint) # Get closest point on curve cCoord = glTools.utils.curve.closestPoint(curve,pos) pos = mc.pointPosition(curve+'.u['+str(cCoord)+']') # Get surface coordinate uvCoord = glTools.utils.surface.closestPoint(influence,pos) # Apply Coord applyCoord(surfaceSkin,influence,controlPoint,uvCoord)
def splitBlendShape( percentRange = .1 ): #USER CAN CHANGE THIS NUMBER ################### # percentRange = .1 #### .1 = 10% falloff #### .3 = 30% falloff #### 1 = 100% falloff (probably looks bad) ################### (sourceObj, targetObj) = cmds.ls(sl=1) sourceShape = getShapeNode(sourceObj) #look at number of verticies cmds.select(sourceObj) numVerts = cmds.polyEvaluate(v=1) #figure out width of face (assume X axis) rgtX = 0 lftX = 0 for i in range(0,numVerts): testX = cmds.pointPosition(targetObj + ".vtx[" + str(i) + "]", l=1)[0] if testX < rgtX: rgtX = testX if testX > lftX: lftX = testX #duplicate face twice (one left, one right) cmds.select(targetObj) targetObj_Lft = cmds.duplicate(n=targetObj+'_Lft')[0] cmds.move(rgtX * -2.1, 0, 0, r=1) cmds.select(targetObj) targetObj_Rgt = cmds.duplicate(n=targetObj+'_Rgt')[0] cmds.move(rgtX * 2.1, 0, 0, r=1) side = 1 #on each object for target in ([targetObj_Lft, targetObj_Rgt]): side *= -1 #for each vert for i in range(0,numVerts): #get vert positions #sourcePos = cmds.getAttr(sourceShape + '.pnts[' + str(i) + ']')[0] #targetPos = cmds.getAttr(target + '.pnts[' + str(i) + ']')[0] sourcePos = cmds.pointPosition(sourceObj + ".vtx[" + str(i) + "]", l=1) targetPos = cmds.pointPosition(target + ".vtx[" + str(i) + "]", l=1) #find difference differencePos = (sourcePos[0] - targetPos[0], sourcePos[1] - targetPos[1], sourcePos[2] - targetPos[2]) #get falloff amount from side of object testX = cmds.pointPosition(sourceObj + ".vtx[" + str(i) + "]", l=1)[0] falloff = getValue(testX, percentRange, rgtX * side) #move vert difference * falloff amount cmds.xform(target + '.vtx[' + str(i) + ']', rt=(differencePos[0] * falloff, differencePos[1] * falloff, differencePos[2] * falloff)) cmds.select(cl=True)
def averageCV(amount=1.0): for cv in mc.ls(sl=True,fl=True): num = int(cv.split('.cv[')[-1].split(']')[0]) baseObj = cv.split('.')[0] pos1 = mc.pointPosition('%s.cv[%i]' % (baseObj, num+1)) pos2 = mc.pointPosition('%s.cv[%i]' % (baseObj, num-1)) pos3 = mc.pointPosition('%s.cv[%i]' % (baseObj, num)) average = [(pos1[0]+pos2[0]+pos3[0])/3, (pos1[1]+pos2[1]+pos3[1])/3, (pos1[2]+pos2[2]+pos3[2])/3] relAvg = [average[0]-pos3[0], average[1]-pos3[1], average[2]-pos3[2]] mc.move(relAvg[0]*amount, relAvg[1]*amount, relAvg[2]*amount, cv, r=True)
def getDelta(targetVert, referenceGeo): ''' returns delta of vert based on referenceGeo ''' targetGeo = getMeshName(targetVert) referenceVert = targetVert.replace(targetGeo, referenceGeo) targetPos = mc.pointPosition(targetVert, l=True) referencePos = mc.pointPosition(referenceVert, l=True) return [tP - rP for (tP, rP) in zip(targetPos, referencePos)]
def createInterpolatedCurve(curve1, curve2, v): interpolatedCurve = mc.duplicate(curve1, rr=True, rc=True)[0] for shape in mc.listRelatives(curve2,shapes=True,fullPath=True): cvList = (mc.ls([shape+'.cv[*]'],flatten=True)) mc.rebuildCurve(interpolatedCurve, ch=0, rpo=1, rt= 0, end = 1, kr = 0, kcp = 0, kep = 1, kt = 0, s = len(cvList)-3, d = 3, tol = 0) for i in range(len(cvList)): pos1 = mc.pointPosition('%s.cv[%i]' % (interpolatedCurve,i)) pos2 = mc.pointPosition('%s.cv[%i]' % (curve2,i)) newPos = ((pos2[0]-pos1[0])*v+pos1[0], (pos2[1]-pos1[1])*v+pos1[1], (pos2[2]-pos1[2])*v+pos1[2]) mc.move(newPos[0], newPos[1], newPos[2], '%s.cv[%i]' % (interpolatedCurve,i), a=True) return interpolatedCurve
def createEyelidsPlane(): curSel = cmds.ls(sl=1,fl=1) eyeCtr = cmds.xform(curSel[2],ws=1,piv=1,q=1)[0:3] eyeCnra = cmds.pointPosition(curSel[0],w=1) eyeCnrb = cmds.pointPosition(curSel[1],w=1) eyeballPlane = cmds.polyCreateFacet(n='tmp_eyeball_plane',ch=0,p=[eyeCtr,eyeCnra,eyeCnrb]) eyelidsPlane = cmds.polyPlane(n='tmp_eyelids_plane') cmds.select((eyelidsPlane[0]+'.vtx[60]'),(eyelidsPlane[0]+'.vtx[70:71]'),(eyeballPlane[0]+'.vtx[0:2]'),r=1) mel.eval('snap3PointsTo3Points(0)') cmds.select(eyelidsPlane,r=1) cmds.xform(eyelidsPlane,os=1,r=1,ro=(0,0,90)) cmds.delete(eyeballPlane)
def snapComponentsOnClosestVertex(referenceObject, components, tolerance) : """ This function snaps vertices onto the reference object vertices. :param referenceObject: Reference mesh. :type referenceObject: str :param components: Components. :type components: list """ vertices = cmds.ls(cmds.polyListComponentConversion(components, toVertex=True), fl=True) progressBar = mel.eval("$container=$gMainProgressBar"); cmds.progressBar(progressBar, edit=True, beginProgress=True, isInterruptable=True, status="Snapping vertices ...", maxValue=len(vertices)) loadPlugin("nearestPointOnMesh") nearestPointOnMeshNode = mel.eval("nearestPointOnMesh " + referenceObject) for vertex in vertices : if cmds.progressBar(progressBar, query=True, isCancelled=True) : break closestDistance = MAXIMUM_SEARCH_DISTANCE vertexPosition = cmds.pointPosition(vertex, world=True) cmds.setAttr(nearestPointOnMeshNode + ".inPosition", vertexPosition[0], vertexPosition[1], vertexPosition[2]) associatedFaceId = cmds.getAttr(nearestPointOnMeshNode + ".nearestFaceIndex") vtxsFaces = cmds.filterExpand(cmds.polyListComponentConversion((referenceObject + ".f[" + str(associatedFaceId) + "]"), fromFace=True, toVertexFace=True), sm=70, expand=True) closestPosition = [] for vtxsFace in vtxsFaces : associatedVtx = cmds.polyListComponentConversion(vtxsFace, fromVertexFace=True, toVertex=True) associatedVtxPosition = cmds.pointPosition(associatedVtx, world=True) distance = norme(vertexPosition, associatedVtxPosition) if distance < closestDistance : closestDistance = distance closestPosition = associatedVtxPosition if closestDistance < tolerance : cmds.move(closestPosition[0], closestPosition[1], closestPosition[2], vertex, worldSpace=True) cmds.progressBar(progressBar, edit=True, step=1) cmds.progressBar(progressBar, edit=True, endProgress=True) cmds.delete(nearestPointOnMeshNode)
def locMeEdgeLoop(polyEdge): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Creates a locator from an edgeloop ARGUMENTS: polyEdge(string) RETURNS: locatorName(string) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ # Get the loop if ':' in polyEdge: edges = mc.ls(polyEdge,flatten=True) elif ',' in polyEdge: edges = polyEdge else: edges = search.returnEdgeLoopFromEdge(polyEdge) mc.select(cl=True) mc.select(edges) mel.eval("PolySelectConvert 3") edgeVerts = mc.ls(sl=True,fl=True) postList = [] for vert in edgeVerts: posList.append(mc.pointPosition(vert,w=True)) objTrans = distance.returnAveragePointPosition(posList) mc.select(cl=True) # Make the loc locatorName = createLocFromObject(polyEdge) mc.move (objTrans[0],objTrans[1],objTrans[2], locatorName) # aim it posList = [] for vtx in edgeVerts: posList.append( mc.pointPosition(vtx,w=True) ) polyBuffer = geo.createPolyFromPosList(posList) constBuffer = mc.normalConstraint(polyBuffer,locatorName) mc.delete(constBuffer[0]) mc.delete(polyBuffer) return locatorName
def avgElementPos(verts, *args): """uses a list of verts and gets the average position""" #get a selection of verts and avg their position xVal = [] yVal = [] zVal = [] xAll = 0.0 yAll = 0.0 zAll = 0.0 for vert in verts: pos = cmds.pointPosition(vert) xVal.append(pos[0]) yVal.append(pos[1]) zVal.append(pos[2]) for x in xVal: xAll += x for y in yVal: yAll += y for z in zVal: zAll += z avgX = xAll/len(xVal) avgY = yAll/len(yVal) avgZ = zAll/len(zVal) avgPos = (avgX, avgY, avgZ) return avgPos
def isoparmCoord(surfaceSkin,influence,controlPoints,coord,direction='u'): ''' Set the target coordinates for the specified control points to lie along a given isoparm @param surfaceSkin: surfaceSkin node to apply the coordinates to @type surfaceSkin: str @param influence: surfaceSkin influence to get coordinate for @type influence: str @param controlPoints: List of control points to set the target coordinates for @type controlPoints: list @param coord: Coordinate value of the target isoparm @type coord: float @param direction: Direction of the isoparm @type direction: str ''' # Get surface curve crv = mc.duplicateCurve(influence+'.'+direction+'['+str(coord)+']',ch=False,rn=0,local=0,n=influence+'TEMP_CRV')[0] # Iterate through control point list for controlPoint in controlPoints: # Get component position pos = mc.pointPosition(controlPoint) # Get closest point on curve cCoord = glTools.utils.curve.closestPoint(crv,pos) # Apply Coord uvCoord = (0,0) if direction == 'u': uvCoord = (coord,cCoord) else: uvCoord = (cCoord,coord) applyCoord(surfaceSkin,influence,controlPoint,uvCoord) # Delete surface curve mc.delete(crv)
def kmSelectVtxFromSide(searchVtx, pos): pX = [] mc.select(clear=True) for vtx in searchVtx: vtxPos = mc.pointPosition(vtx) if pos[0] > 0: if vtxPos[0] > 0: pX.append(vtx) elif pos[0] < 0: if vtxPos[0] < 0: pX.append(vtx) if pos[1] > 0: if vtxPos[1] > 0: pX.append(vtx) elif pos[1] < 0: if vtxPos[1] < 0: pX.append(vtx) if pos[2] > 0: if vtxPos[2] > 0: pX.append(vtx) elif pos[2] < 0: if vtxPos[2] < 0: pX.append(vtx) mc.select(pX)
def getCrvData(crvList): """ This method finds all the ctrl objects in a scene, and creates a data set describing the positions of the cvs in world space. This data is used to reposition the controls after the rig is built. This is the format of the data: data = [('ctrlA':['ctrlAShape':[[point1.X, point1.Y, point1.Z], [point2.X, point2.Y, point2.Z], etc...]]), ('ctrlB':['ctrlBShape':[[point1.X, point1.Y, point1.Z], [point2.X, point2.Y, point2.Z], etc...], 'ctrlBShape1':[point1.X, point1.Y, point1.Z]]), ] :Returns: A list of ctrlData tuples :Rtype: `list` """ data = [] for crv in crvList: shapes = cmds.listRelatives(crv, shapes=1, type="nurbsCurve") shapeData = {} for shape in shapes: pointData = [] for i in range(cmds.getAttr("%s.controlPoints" % shape, size=1)): pointData.append(cmds.pointPosition("%s.cv[%s]" % (shape, i), w=1)) shapeData[shape] = pointData data.append((crv, shapeData)) return data
def locMeCvFromCvIndex(shape,cvIndex): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Places locators on the cv's closest position on a curve ARGUMENTS: curve(string) RETURNS: locList(list) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ cv = ('%s%s%i%s'%(shape,'.cv[',cvIndex,']')) if mc.objExists(cv): cvPos = mc.pointPosition (cv,w=True) wantedName = (cv + 'loc') actualName = mc.spaceLocator (n= wantedName) mc.move (cvPos[0],cvPos[1],cvPos[2], [actualName[0]]) uPos = distance.returnClosestUPosition (actualName[0],shape) mc.move (uPos[0],uPos[1],uPos[2], [actualName[0]]) return actualName[0] else: guiFactory.warning ('Shape does not exist') return False
def snapPtsToSurface(surface,pointList): ''' @param surface: Nurbs surface to snap points to @type surface: str @param pointList: Point to snap to the specified surface @type pointList: list ''' # Check surface if not isSurface(surface): raise UserInputError('Object '+surface+' is not a valid surface!') # Check points pointList = mc.ls(pointList,fl=True) # Transform types transform = ['transform','joint','ikHandle','effector'] # Snap points for pt in pointList: # Check Transform if transform.count(mc.objectType(pt)): snapToSurface(surface,pt,0.0,0.0,True,snapPivot=False) continue # Move Point pos = mc.pointPosition(pt) (uParam,vParam) = closestPoint(surface,pos) sPt = mc.pointOnSurface(surface,u=uParam,v=vParam,position=True) mc.move(sPt[0],sPt[1],sPt[2],pt,ws=True,a=True)
def getFacesInFrustum(container,obj): obj = 'pHelix131' container = 'frust_camera_frustum_geo' # select faces in container(frustum) allVtx = cmds.ls('{0}.vtx[:]'.format(obj),fl=True) allIn = [] for vtx in allVtx: location = cmds.pointPosition(vtx,w=True) test = pyRayIntersect(container,location,(0,1,0)) if(test): allIn.append(vtx) inner_faces = cmds.polyListComponentConversion(allIn,fv=True,tf=True) # select faces that facing the camera cmds.select(obj,r=True) cmds.selectMode(co=True) cmds.selectType(pf=True) cmds.setAttr('{0}.backfaceCulling'.format(obj),2) view = OMU.M3dView.active3dView() OM.MGlobal.selectFromScreen(0, 0, view.portWidth(), view.portHeight(), OM.MGlobal.kReplaceList) facing_cam_faces = cmds.ls(sl=True,fl=True) # combine both selection all_faces = [x for x in cmds.ls(inner_faces,fl=True) if x in cmds.ls(facing_cam_faces,fl=True)] return all_faces
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 CreateObjects(objectlist,*args): selCVs = cmds.ls(sl=True) selCVs_pos = cmds.filterExpand(ex=True,sm=28) cmds.select(cl=True) ObjName = cmds.optionMenu(objectlist,query=True,value=True) for num in selCVs_pos: position = cmds.pointPosition(num,w=True) pos_x = position[0] pos_y = position[1] pos_z = position[2] if(ObjName == "Cube"): make_obj = cmds.nurbsCube(); cmds.setAttr(make_obj[0] + ".tx",pos_x) cmds.setAttr(make_obj[0] + ".ty",pos_y) cmds.setAttr(make_obj[0] + ".tz",pos_z) if(ObjName == "Circle"): make_obj = cmds.circle(); cmds.setAttr(make_obj[0] + ".tx",pos_x) cmds.setAttr(make_obj[0] + ".ty",pos_y) cmds.setAttr(make_obj[0] + ".tz",pos_z) if(ObjName == "Joint"): make_obj = cmds.joint() cmds.setAttr(make_obj + ".tx",pos_x) cmds.setAttr(make_obj + ".ty",pos_y) cmds.setAttr(make_obj + ".tz",pos_z)
def createFromTo(objs=[], divisions=4, degree=3): from maya.cmds import ls, attributeQuery, xform, pointPosition, curve from ezLib import transform # no objs put it: get from selection if not objs: objs = ls(sl=1) if len(objs) != 2: raise IOError, 'need 2 objs to get start & end from!' print ('objs: ' + str(objs)) pos = [] for i in range(2): # to get transforms/joints or anything that has translate attributes if attributeQuery('t', node=objs[i], exists=1): pos.append(xform(objs[i],q=1,t=1,ws=1)) else: try: pos.append(pointPosition(objs[i], world=1)) except IOError: print 'cannot get position from ' + objs[i] #vector from start to end posArray = transform.posRange(pos[0], pos[1], divisions + 1) crv = curve(p=posArray) # center pivot and reset pivot xform(crv, centerPivots=1) transform.resetPivot(crv)
def snapToVertex(mesh, transform, vtxId=-1, snapPivot=False): """ Snap a transform the the closest point on a specified mesh @param mesh: Mesh to snap to @type mesh: str @param transform: Transform to snap to mesh @type transform: str @param vtxId: Integer vertex id to snap to. If -1, snap to closest vertex. @type vtxId: int @param snapPivot: Move only the objects pivot to the vertex @type snapPivot: bool """ # Check mesh if not isMesh(mesh): raise Exception("Object " + mesh + " is not a valid mesh!") # Get transform position pos = mc.xform(transform, q=True, ws=True, rp=True) # Get mesh vertex to snap to if vtxId < 0: vtxId = closestVertex(mesh, pos) # Get vertex position vtxPt = mc.pointPosition(mesh + ".vtx[" + str(vtxId) + "]") # Snap to Vertex if snapPivot: mc.xform(obj, piv=vtxPt, ws=True) else: mc.move(vtxPt[0] - pos[0], vtxPt[1] - pos[1], vtxPt[2] - pos[2], transform, r=True, ws=True) # Retrun result return vtxPt
def snapPtsToMesh_old(mesh, pointList, amount=1.0): """ Snap a list of points to the closest point on a specified mesh @param mesh: Polygon to snap points to @type mesh: str @param pointList: Point to snap to the specified mesh @type pointList: list @param amount: Percentage of offset to apply to each point @type amount: float """ # Check mesh if not isMesh(mesh): raise Exception("Object " + mesh + " is not a valid mesh!") # Check points pointList = mc.ls(pointList, fl=True) if not pointList: pointList = mc.ls(sl=True, fl=True) # Transform types transform = ["transform", "joint", "ikHandle", "effector"] # Snap points for pt in pointList: # Check Transform if transform.count(mc.objectType(pt)): snapToMesh(mesh, pt, snapPivot=False) continue # Move Point pos = mc.pointPosition(pt) meshPt = closestPoint(mesh, pos) mc.move(meshPt[0], meshPt[1], meshPt[2], pt, ws=True, a=True)
def getCenter(componentList=[]): ''' Return the world center of the specified components @param componentList: List of components to find the center of @type componentList: list ''' # Check componentList if not componentList: componentList = mc.ls(sl=True) componentList = mc.ls(componentList,fl=True) # Initialize position pos = [0.0,0.0,0.0] # Append component position for component in componentList: pnt = mc.pointPosition(component) pos[0] += pnt[0] pos[1] += pnt[1] pos[2] += pnt[2] # Average position if componentList: componentLen = len(componentList) pos[0] /= componentLen pos[1] /= componentLen pos[2] /= componentLen # Return result return (pos[0],pos[1],pos[2])
def buildNurbsRibbon(self): if self.guideSpline: guideDeg = cmds.getAttr(self.guideSpline + '.degree' ) guideSpan = cmds.getAttr(self.guideSpline + '.spans' ) oneCurvePoints = [] otherCurvePoints = [] for i in xrange(guideDeg + guideSpan): cvPos = cmds.pointPosition(self.guideSpline + '.cv[' + str(i) + "]", w=True ) newPara = cmds.closestPointOnCurve(self.guideSpline, ip=cvPos, paramU=True) #Find the parameter Value newParaVal = cmds.getAttr(newPara + ".paramU") cmds.delete(newPara) infoNode = cmds.pointOnCurve(self.guideSpline, ch=True, pr=newParaVal) #Now find the Position and tangent! posy = (cmds.getAttr(infoNode + ".position"))[0] # returns the position posy = MVector(posy[0],posy[1],posy[2]) normy = (cmds.getAttr(infoNode + ".tangent"))[0] normy = MVector(normy[0],normy[1],normy[2]) #Use MVector from maya.openMaya normy = normy.normal() vertVect = MVector(0,1,0) sideMove = normy^vertVect #This is the notation for a cross product. Pretty cool. Should be a normal movement sideMove = sideMove.normal() * 0.5 sideMovePos = posy + sideMove otherSideMovePos = posy - sideMove oneCurvePoints.append([sideMovePos[0],sideMovePos[1],sideMovePos[2]]) otherCurvePoints.append([otherSideMovePos[0],otherSideMovePos[1],otherSideMovePos[2]]) oneSideCurve = cmds.curve(editPoint = oneCurvePoints, degree=3) OtherSideCurve = cmds.curve(editPoint = otherCurvePoints, degree=3) self.tempConstructionParts.append(oneSideCurve) self.tempConstructionParts.append(OtherSideCurve) #Now we loft the surface between the two Curves! nameStart = nameBase(self.totalMarkerList[0].getName(), self.searchString, "loc", "nbs") nameStart += "ribbonSurface" self.guideNurbsRibbon = cmds.loft(oneSideCurve, OtherSideCurve, name = nameStart, constructionHistory = True, uniform = True, close = False, autoReverse = True, degree = 3, sectionSpans = 1, range = False, polygon = 0, reverseSurfaceNormals = True) self.guideNurbsRibbon = self.guideNurbsRibbon[0] self.ribbonParts.append(self.guideNurbsRibbon)
def locMeCVOnCurve(curveCV): """ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION: Places locators on the cv's closest position on a curve ARGUMENTS: curve(string) RETURNS: locList(list) >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> """ if search.returnObjectType(curveCV) == 'curveCV': cvPos = mc.pointPosition (curveCV,w=True) wantedName = (curveCV + '_loc') actualName = mc.spaceLocator (n= wantedName) mc.move (cvPos[0],cvPos[1],cvPos[2], [actualName[0]]) splitBuffer = curveCV.split('.') uPos = distance.returnClosestUPosition (actualName[0],splitBuffer[0]) mc.move (uPos[0],uPos[1],uPos[2], [actualName[0]]) return actualName[0] else: guiFactory.warning ('Not a curveCV') return False
def nurbsCVSmoothWeights(cv): surface = '.'.join(cv.split('.')[0:-1]) skinCluster = querySkinCluster (surface) cvPos = mc.pointPosition (cv,world=True) wantedName = (cv + 'loc') actualName = mc.spaceLocator (n= wantedName) mc.move (cvPos[0],cvPos[1],cvPos[2], [actualName[0]]) influenceObjects = queryInfluences (skinCluster) culledList = influenceObjects """figure out our closest objects""" bestChoices = [] cnt = 5 while cnt >= 0: goodChoice = (distance.returnClosestObjToCV (cv, culledList)) culledList.remove(goodChoice) bestChoices.append (goodChoice) print bestChoices cnt-=1 distanceList = [] for obj in bestChoices: distanceList.append (distance.returnDistanceBetweenObjects(actualName[0],obj)) print distanceList """ return normalization value """ buffer=0 y = 1 + (x-A)*(10-1)/(B-A) for value in distanceList: buffer += value print buffer normalize = ((len(distanceList))*.1) print normalize mc.delete (actualName[0])
def _gather_skin(self): self._d_skin = {} _d = {} #for a in 'useComponents','skinningMethod','normalize','geometryType','bindMethod', #'normalizeWeights', #'maintainMaxInfluences','maxInfluences','dropoffRate','smoothness','lockweights': for a in self.mi_cluster.getAttrs():#...first gather general attributes try: _bfr = self.mi_cluster.getMayaAttr(a) if _bfr is not None:_d[a] = _bfr except: self.log_error("{0} failed to query".format(a)) self._d_skin = _d#...link back self._d_data['skin'] = _d #self.log_infoNestedDict('_d_skin') #...gather weighting data ------------------------------------------------------------------- _d = {} dagPath, components = self.__getGeometryComponents() #self.log_info('dagPath: {0}'.format(dagPath)) #self.log_info('components: {0}'.format(components)) self.gatherInfluenceData(dagPath, components) self.gatherBlendWeightData(dagPath, components) _vtx = self._d_data['mesh']['component']#...link to the component type l_sourceComponent = (mc.ls ("{0}.{1}[*]".format(self._mesh,_vtx),flatten=True)) l_influences = self._d_skin['matrix'] self.progressBar_start(stepMaxValue=len(l_sourceComponent), statusMessage='Calculating....', interruptableState=False) _d_componentWeights = {} for i,vertice in enumerate(l_sourceComponent): self.progressBar_iter(status = 'Getting {0}'.format(vertice)) skinValues = {} _key = str(i) self._d_data['mesh']['d_vertPositions'][_key] = mc.pointPosition("{0}.{1}[{2}]".format(self._mesh,_vtx,i),w=True) """for ii,influence in enumerate(l_influences): influenceValue = mc.skinPercent(self._skin, vertice, transform = influence, query = True) if influenceValue != 0: skinValues[str(ii)] = influenceValue""" for ii,influence in enumerate(l_influences): _bfr = self._d_data['weights'][str(ii)][i]#...pull from our weights data to be much much faster... if _bfr != 0: skinValues[str(ii)] = _bfr _d_componentWeights[_key] = skinValues self.progressBar_end() #self.log_infoDict( _d_componentWeights, "Component Weights...") self._d_data['influences']['componentWeights'] = _d_componentWeights return self._d_data
def updateMesh() : nVerts=cmds.polyEvaluate('pPlane1',v=True) for i in range(0,nVerts) : a=cmds.pointPosition('pPlane1.vtx[%d]'%i ) cmds.setAttr('noiseNode1.tx',a[0]) cmds.setAttr('noiseNode1.tz',a[2]) o=cmds.getAttr('noiseNode1.output') cmds.xform( 'pPlane1.vtx[%d]' %i ,a=True,ws=True,t=( a[0], o, a[2]) )
def makePlane(*args): points = [] cmds.polyCreateFacetCtx(pc=False) sel = cmds.ls(sl=True, type="transform") for obj in sel: loc = cmds.pointPosition((obj + ".rotatePivot"), world=True) points.append(loc) poly = cmds.polyCreateFacet(p=points)
def pushCurveOutFromScalp(curves, scalp, pushMult = 1.5): import cgm.lib.distance as bbDistanceLib sel = mc.ls(sl=True) for obj in curves: for shape in mc.listRelatives(obj,shapes=True,fullPath=True): cvList = (mc.ls([shape+'.cv[*]'],flatten=True)) for cv in cvList: currentPos = mc.pointPosition(cv) newPos = bbDistanceLib.returnClosestPointOnMeshInfoFromPos(currentPos, scalp)['position'] relPos = [newPos[0]-currentPos[0], newPos[1]-currentPos[1], newPos[2]-currentPos[2]] mc.move(relPos[0]*pushMult, relPos[1]*pushMult, relPos[2]*pushMult, cv, r=True) mc.select(sel)
def check_last_edge(self): try: if len(self.sub_edges) == 1: #print 'check last edge' self.last_edge = self.sub_edges[0] else: #print 'check last edge' dist = float('inf') pos_a = om.MPoint( cmds.pointPosition(self.mesh[0] + '.vtx[' + str(self.num_list[0]) + ']', w=True)) for e in self.sub_edges: e_vtx = common.conv_comp(e, mode='vtx') #print 'checking last :', e, e_vtx pos_b = om.MPoint(cmds.pointPosition(e_vtx[0], w=True)) pos_c = om.MPoint(cmds.pointPosition(e_vtx[1], w=True)) l = (pos_a - pos_b).length() + (pos_a - pos_c).length() if dist < l: continue self.last_edge = e dist = l self.uv_edge = self.edge + [self.last_edge] #print 'get last edge:', self.last_edge last_num = self.vtx2num( common.conv_comp(self.last_edge, mode='vtx')) for num in self.num_list[:]: if num in last_num: continue else: last_num.append(num) self.num_list = last_num #print 'new num_list :',self.num_list except Exception as e: print e.message, common.location() print(traceback.format_exc())
def getListOfCvPoints(self, selected_curve): """ getListOfCvPoints Return cvs positions (x, y, z) @param selected_curve: name of selected curve @return: list of points for selection """ curveCVs = cmds.ls('{0}.cv[:]'.format(selected_curve), fl=True) list = [] for cv in curveCVs: pos = cmds.pointPosition(cv) list.append(pos) return list
def instance_objects(self, object_to_instance, target_names): """instances an object to each target, scaling and rotating it appropriately""" for target in target_names: new_instance = cmds.instance(object_to_instance) new_instance = self.scale_instance(new_instance, self.scale_min, self.scale_max) new_instance = self.rotate_instance(new_instance, self.rotate_x_min, self.rotate_x_max, self.rotate_y_min, self.rotate_y_max, self.rotate_z_min, self.rotate_z_max) if self.faces: face_center = self.get_face_center(target) face_normal = self.get_face_normal(target) self.move_align(target, face_normal, face_center) if self.vertex: position = cmds.pointPosition(target, w=True) cmds.move(position[0], position[1], position[2], new_instance, a=True, ws=True)
def curveFromEdgeRing(): sel = cmds.ls(sl=True, fl=True) avgPositionList = [] for s in sel: cmds.select(s, r=True) edgeNum = int(s.split('[')[1].replace(']', '')) cmds.polySelect(elb=edgeNum) edgeLoopVtxList = cmds.ls(cmds.polyListComponentConversion(cmds.ls( sl=True, fl=True), tv=True), fl=True) posXlist = [] posYlist = [] posZlist = [] for v in edgeLoopVtxList: posXlist.append(cmds.pointPosition(v)[0]) posYlist.append(cmds.pointPosition(v)[1]) posZlist.append(cmds.pointPosition(v)[2]) avgPos = [ numpy.mean(posXlist), numpy.mean(posYlist), numpy.mean(posZlist) ] avgPositionList.append(avgPos) if len(avgPositionList) <= 1: pass else: cmds.curve(d=3, p=avgPositionList)
def makeIntermediateCurves(curve1, curve2, numIntermediates=1, close=True): cShape1 = mc.listRelatives(curve1, shapes=True)[0] cShape2 = mc.listRelatives(curve2, shapes=True)[0] numCV1 = mc.getAttr(cShape1+'.spans') + mc.getAttr(cShape1+'.degree') numCV2 = mc.getAttr(cShape2+'.spans') + mc.getAttr(cShape2+'.degree') if numCV1 != numCV2: mel.eval('warning "Number of CVs between curves are not equal. Can\'t create intermediate curves"') return [] step = 1.0/(numIntermediates+1) allCurves = [] for p in range(1, numIntermediates+1): points = [] for i in range(mc.getAttr(cShape1+'.spans')): p1 = mc.pointPosition('%s.cv[%i]' % (curve1,i)) p2 = mc.pointPosition('%s.cv[%i]' % (curve2,i)) v = (p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]) p3 = (p1[0]+(v[0]*step*p), p1[1]+(v[1]*step*p), p1[2]+(v[2]*step*p)) points.append(p3) allCurves += makeCurveFromPoints(points, close) allCurves[-1] = mc.rename(allCurves[-1], 'intCurve1') return allCurves
def perform_scatter(self): self.count = self.count +1 instances = [] pos_list = [] percentage_destination = [] for idx in range(0, len(self.destination_verts)): rand.seed(idx) rand_value = rand.random() if rand_value <= self.percentage: percentage_destination.append(self.destination_verts[idx]) for vert in percentage_destination: self.randomize() new_instance = cmds.instance(self.source_object, name=(str(self.source_object[0]) + "_instance" + str(self.count) + "_")) position = cmds.pointPosition(vert, world=True) cmds.xform(new_instance, translation=position) if self.align_to_normal: constraint = cmds.normalConstraint(vert, new_instance, aimVector=[0, 1, 0]) cmds.delete(constraint) cmds.xform(new_instance, objectSpace=True, relative=True, rotation=(self.rot_x, self.rot_y, self.rot_z), scale=(self.scale_x, self.scale_y, self.scale_z)) instances.append(new_instance) count = len(instances) sums = [0, 0, 0] for item in instances: pos = cmds.xform(item, q=True, t=True) pos_list.append(pos) sums[0] += pos[0] sums[1] += pos[1] sums[2] += pos[2] center = [sums[0] / count, sums[1] / count, sums[2] / count] idx = 0 for pos in pos_list: print(pos[0]) dist_x = (center[0] - pos[0]) * self.clump_amount dist_y = (center[1] - pos[1]) * self.clump_amount dist_z = (center[2] - pos[2]) * self.clump_amount cmds.xform(instances[idx], objectSpace=True, relative=True, translation=(dist_x, dist_y, dist_z)) idx = idx + 1
def disCal(p1, p2): disX = float(cmds.pointPosition(p1)[0]) - float(cmds.pointPosition(p2)[0]) disY = float(cmds.pointPosition(p1)[1]) - float(cmds.pointPosition(p2)[1]) disZ = float(cmds.pointPosition(p1)[2]) - float(cmds.pointPosition(p2)[2]) return [ math.sqrt(disX * disX + disY * disY + disZ * disZ), abs(disX), abs(disY), abs(disZ) ]
def getCurveSegmentLength(self): pointA = Vector3( cmds.pointPosition(self.curveName + '.cv[0]')[0], cmds.pointPosition(self.curveName + '.cv[0]')[1], cmds.pointPosition(self.curveName + '.cv[0]')[2]) pointB = Vector3( cmds.pointPosition(self.curveName + '.cv[1]')[0], cmds.pointPosition(self.curveName + '.cv[1]')[1], cmds.pointPosition(self.curveName + '.cv[1]')[2]) return Vector3.getDistanceBetweenTwoPoints(pointA, pointB)
def AveragePosFromVerts(vertList): # get the position average (center) # very slow on big old selections sumX, sumY, sumZ = 0.0, 0.0, 0.0 length = len(vertList) for vert in vertList: pos = cmds.pointPosition(vert, world=True) sumX += pos[0] sumY += pos[1] sumZ += pos[2] if (length == 0): return [0, 0, 0] return [sumX / length, sumY / length, sumZ / length]
def __init__(self, numberOfVertices=10): if not funnyPlane.plane: funnyPlane.plane = mc.polyPlane(sx=10, sy=10, w=10, h=10)[0] numVertices = mc.polyEvaluate(funnyPlane.plane, vertex=True) self.vertexList = [] self.positions = [] if numberOfVertices < numVertices: self.vertexList = random.sample(range(numVertices), numberOfVertices) for vertex in self.vertexList: position = mc.pointPosition(funnyPlane.plane + ".vtx[" + str(vertex) + "]") self.positions.append(position) mc.polyMoveVertex(funnyPlane.plane + ".vtx[" + str(vertex) + "]", translateY=2)
def changeNumber(self, newNumSpheres = 15): if newNumSpheres>self.numSpheres: vertices = random.sample(range(self.numVertices), newNumSpheres) for v in vertices: radius = random.uniform(1, self.maxRadius) position = mc.pointPosition(self.spherePlane[0]+".vtx["+str(v)+"]") self.sphereNames.append(mc.polySphere(r = radius)[0]) mc.move(position[0], radius, position[2]) if newNumSpheres<self.numSpheres: i = self.numSpheres - newNumSpheres while i>0: mc.delete(self.sphereNames[i]) i -=1 self.numSpheres = newNumSpheres
def getPosTable(mesh, **kwargs): ''' returns dictionary {vertId : dt.Point(x,y,z)} ''' vertCount = mc.polyEvaluate(mesh, v=True) retDict = {} for vertId in range(vertCount): retDict[vertId] = dt.Point( *mc.pointPosition('%s.vtx[%d]' % (mesh, vertId), **kwargs)) return retDict
def makeHairCurve(hullCurves, u, twist=0.0): ''' Create a curve through a series of hull curves by u parameter ''' p = [] i = 0 for hull in hullCurves: p.append(mc.pointPosition('%s.u[%f]' % (hull, (u+(twist*i))%1.0 ) )) i+=1 curve = mc.curve(p=p, d=3) curve = mc.rebuildCurve(curve, rpo=1, rt=0, end=1, kr=0, kcp=1, kep=1, kt=0, s=4, d=3, tol=0.000129167) mc.xform(curve, centerPivots=True) return curve
def create_instances(self): scattered_instances = [] for vtx in self.rand_selection(): pos = cmds.pointPosition(vtx) scatter_instance = cmds.instance(self.scatter_source_object, name=self.instance_name + "_1") scattered_instances.extend(scatter_instance) cmds.move(pos[0], pos[1], pos[2], scatter_instance, worldSpace=True) self.rand_rotation(scatter_instance[0]) self.rand_scale(scatter_instance[0]) # self.constrain_instance(scatter_instance[0]) cmds.group(scattered_instances, name="scattered")
def main(): """docstring for main""" vertices = cmds.ls(sl=True) if any('.vtx' in v for v in vertices): loc_size = 10 for vertex in vertices: point_pos = cmds.pointPosition(vertex) loc = cmds.spaceLocator(p=tuple(point_pos)) shapes = cmds.listRelatives(loc) for shape in shapes: cmds.setAttr("{}.localScaleX".format(shape), loc_size) cmds.setAttr("{}.localScaleY".format(shape), loc_size) cmds.setAttr("{}.localScaleZ".format(shape), loc_size) else: cmds.warning("No vertices selected!")
def calDist(curve, tempCrvPos, cpNode): ''' Calculate distance between temporary position on curve and closest point on surface. ''' # Get a temporary curve position and closest point on surface between curve and surface. crvPntWsPos = cmds.pointPosition('%s.un[%f]' % (curve, tempCrvPos), w=True) cmds.setAttr('%s.inPosition' % (cpNode), *crvPntWsPos) cp = cmds.getAttr('%s.position' % (cpNode))[0] # Get distance between curve point and closest point on surface. vCp = OpenMaya.MVector(*cp) vCrvPntWsPos = OpenMaya.MVector(*crvPntWsPos) dist = (vCp - vCrvPntWsPos).length() return dist
def snapToCurve(curve, obj, uValue=0.0, useClosestPoint=False, snapPivot=False): ''' Snap an object (or transform pivot) to a specified point on a curve. @param curve: Curve to snap to @type curve: str @param obj: Object to move to point on curve @type obj: str @param uValue: Paramater value of the curve to snap to @type uValue: float @param useClosestPoint: Use the closest point on the curve instead of the specified uv parameter @type useClosestPoint: bool @param snapPivot: Move only the objects pivot to the curve point @type snapPivot: bool ''' # Check curve if not isCurve(curve): raise Exception('Object ' + curve + ' is not a valid curve!!') # Check uValue minu = mc.getAttr(curve + '.minValue') maxu = mc.getAttr(curve + '.maxValue') # Closest Point if useClosestPoint: pos = mc.xform(obj, q=True, ws=True, rp=True) uValue = closestPoint(curve, pos) # Verify surface parameter if uValue < minu or uValue > maxu: raise Exception('U paramater ' + str(uValue) + ' is not within the parameter range for ' + curve + '!!') # Get curve point position pnt = mc.pointPosition(curve + '.u[' + str(uValue) + ']') # Snap to Curve piv = mc.xform(obj, q=True, ws=True, rp=True) if snapPivot: mc.xform(obj, piv=pnt, ws=True) else: mc.move(pnt[0] - piv[0], pnt[1] - piv[1], pnt[2] - piv[2], obj, r=True, ws=True)
def pushCVOutFromScalp(cvs, scalp, pushMult=1.5): import cgm.lib.distance as bbDistanceLib sel = mc.ls(sl=True) for obj in cvs: currentPos = mc.pointPosition(obj) newPos = bbDistanceLib.returnClosestPointOnMeshInfoFromPos( currentPos, scalp)['position'] relPos = [ newPos[0] - currentPos[0], newPos[1] - currentPos[1], newPos[2] - currentPos[2] ] mc.move(relPos[0] * pushMult, relPos[1] * pushMult, relPos[2] * pushMult, obj, r=True) mc.select(sel)
def CreateJoint(self, length, obj, jnts): ''' creates joints along cvs of curve or at pivot based on provided length ''' if length > 0: i = 0 while i < length: jnt = cmds.joint() pos = cmds.pointPosition((obj + '.cv[' + str(i) + ']'), w=True) cmds.move(pos[0], pos[1], pos[2], jnt, ws=True) jnts.append(jnt) i += 1 else: jnt = cmds.joint() cmds.matchTransform(jnt, obj) jnts.append(jnt) return jnts
def scale(componentList=[], scale=(1.0, 1.0, 1.0), pivot='center', userPivot=(0, 0, 0), worldSpace=False): ''' Scale the specified components based on the input argument values. @param componentList: List of components to scale @type componentList: list @param scale: Scale to apply to the component list @type scale: tuple @param pivot: Pivot option for scale. Valid pivot options are "object", "center" and "user". @type pivot: str @param userPivot: Pivot position to use if the pivot option is set to "user". @type userPivot: tuple @param worldSpace: Perform scaling about global world-space axis. @type worldSpace: bool ''' # Check componentList if not componentList: componentList = mc.ls(componentList, fl=True) # Determine rotation pivot piv = (0, 0, 0) if pivot == 'center': piv = getCenter(componentList) elif pivot == 'object': shape = mc.listRelatives(componentList[0], p=True, pa=True)[0] obj = mc.listRelatives(shape, p=True, type='transform', pa=True)[0] piv = mc.xform(obj, q=True, ws=True, rp=True) elif pivot == 'user': piv = userPivot else: raise Exception('Invalid pivot option - "' + pivot + '"! Specify "object", "center" or "user"!!') # Scale Components if worldSpace: for component in componentList: pnt = mc.pointPosition(component) offset = (pnt[0] - piv[0], pnt[1] - piv[1], pnt[2] - piv[2]) pnt = (piv[0] + offset[0] * scale[0], piv[1] + offset[1] * scale[1], piv[2] + offset[2] * scale[2]) mc.move(pnt[0], pnt[1], pnt[2], component, a=True, ws=True) else: mc.scale(scale[0], scale[1], scale[2], componentList, p=piv)
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 snapToClosestVertexFromUI(close=False): ''' ''' # Window window = 'snapToClosestVtxUI' if not mc.window(window, q=True, ex=1): raise UIError('SnapToClosestVertex UI does not exist!!') # Get UI data mesh = mc.textFieldGrp('snapToMeshVtxTFB', q=True, text=True) for i in mc.ls(sl=1, fl=1): #pt = mc.pointPosition(i) pt = glTools.utils.base.getPosition(i) vtx = glTools.utils.mesh.closestVertex(mesh, pt) pos = mc.pointPosition(mesh + '.vtx[' + str(vtx) + ']') mc.move(pos[0], pos[1], pos[2], i, ws=True, a=True)
def makeCurveDic(self): self.curveDic = {} selCurveShape = cmds.ls(sl=True, dag=True, ni=True, type='nurbsCurve') cvCountList = [] for i in range(len(selCurveShape)): if cmds.getAttr('%s.f' %selCurveShape[i])==2: cvCount = cmds.getAttr( '%s.spans' %selCurveShape[i]) else: cvCount = cmds.getAttr( '%s.spans' %selCurveShape[i]) + cmds.getAttr( '%s.degree' % selCurveShape[i] ) cvCountList.append( cvCount ) count = 0 while count < len( cvCountList ): self.curveDic[selCurveShape[count]] = {} for cvNum in range( cvCountList[count]): cvPosition = cmds.pointPosition( '%s.cv[%s]' %( selCurveShape[count], cvNum ) ,l=True) self.curveDic[selCurveShape[count]][cvNum] = cvPosition count = count + 1
def listEachMesh(self, vtx, meshes, negaPosi=1, plane=0): meshVtxList = [] preID = meshes.index(vtx[0].split('.')[0]) #メッシュ名を判別するためのID tempList = [] #メッシュごとのグループに分けるためのテンポラリ for v in vtx: if cmds.pointPosition(v, w=True)[plane] * negaPosi > 0: id = meshes.index(v.split('.')[0]) #メッシュ名を取得してIDに変換 if preID == id: #メッシュ名が同じ間はテンポラリに頂点を追加 tempList.append(v) else: #メッシュ名が変わったらリストをアペンドしてテンポラリをクリア meshVtxList.append(tempList) tempList = [] tempList.append(v) preID = id if tempList != []: #最後の一個も追加 meshVtxList.append(tempList) return meshVtxList
def barycentricPointWeightSetup(samplePt, targetList, calcList=[True, True, True], prefix=''): """ Create pointSampleWeight setup for driving up to 3 target region shapes @param samplePoint: The point to track between target points @type samplePoint: str @param targetList: List of meshes that define the target vertex positions @type targetList: list @param prefix: Naming prefix for created nodes @type prefix: str """ # Checks if not cmds.objExists(samplePt): raise Exception('Sample point "' + samplePt + '" does not exist!!') if not cmds.objExists(samplePt + '.vtx'): raise Exception('Sample point "' + samplePt + '" has not target vertex attribute (".vtx")!!') for target in targetList: if not cmds.objExists(target): raise Exception('Target mesh "' + target + '" does not exist!!') if not glTools.utils.mesh.isMesh(target): raise Exception('Target object "' + target + '" is not a valid mesh!!') # Generate target points vtxId = cmds.getAttr(samplePt + '.vtx') targetLoc = [] for target in targetList: targetSuffix = target.split('_')[-1] targetPos = cmds.pointPosition(target + '.vtx[' + str(vtxId) + ']') targetLoc.append( cmds.spaceLocator(n=prefix + '_' + targetSuffix + '_pnt')[0]) cmds.setAttr(targetLoc[-1] + '.t', targetPos[0], targetPos[1], targetPos[2]) # Create 3PointSampleWeight setup pointSetup = glTools.tools.barycentricPointWeight.create( samplePt, targetLoc, calcList, prefix) # Cleanup cmds.delete(targetLoc) # Return result return pointSetup # [locator list, triFace, locator_grp]
def orient_to_normals(self): self.selection = cmds.ls(os=True, fl=True) self.vert_list = cmds.ls(selection=True, fl=True) cmds.filterExpand(self.vert_list, selectionMask=31, expand=True) or [] self.obj_vert_list = cmds.ls(self.vert_list[1] + ".vtx[*]", flatten=True) if self.is_whole_object: self.den_list = random.sample( self.obj_vert_list, int(float(len(self.obj_vert_list) * self.def_density))) else: self.den_list = random.sample( self.vert_list, int(float(len(self.vert_list)) * self.def_density)) self.object_to_instance = self.selection[0] self.main_object = self.selection[1] # print(vertex_name) if cmds.objectType(self.object_to_instance, isType="transform"): for self.vertex in self.den_list: self.new_instance = cmds.instance(self.object_to_instance) self.position = cmds.pointPosition(self.vertex, w=True) cmds.move(self.position[0], self.position[1], self.position[2], self.new_instance, a=True, ws=True) self.nconst = cmds.normalConstraint(self.main_object, self.new_instance, aim=(0.0, 1.0, 0.0)) cmds.rename(self.new_instance, "instance") cmds.delete(self.nconst) else: print("Please ensure the first object you select is a transform.")
def createSpineIKHandle(self, spineJoints): self.pos = [] for spineIK in spineJoints: self.pointPP = cmds.xform(spineIK, q=True, ws=True, t=True) self.pos.append(self.pointPP) self.curve = cmds.curve(n="%s_Curve" % spineJoints[1], d=1, p=self.pos) self.spineIKSplineSolver = cmds.ikHandle(sol="ikSplineSolver", n="spine_ikSplineSolver", sj=spineJoints[0], ee=spineJoints[-1], c=self.curve, fj=True) cmds.rebuildCurve(self.curve, s=2) self.curveShape = cmds.listRelatives(self.curve, s=True) self.cv = cmds.getAttr(self.curveShape[0] + ".spans") + cmds.getAttr(self.curveShape[0] + ".degree") self.splineIkLoc = [] for cvs in range(self.cv): self.cvPos = cmds.pointPosition(self.curveShape[0] + ".cv[%d]" % cvs) self.loc = cmds.spaceLocator(p=self.cvPos, n="ikSplineLocator_0%d" % (cvs + 1))[0] self.locShape = cmds.listRelatives(self.loc, s=True) cmds.connectAttr(self.locShape[0] + ".worldPosition[0]", self.curveShape[0] + ".controlPoints[%d]" % cvs) self.piv = cmds.xform(self.loc, piv=self.cvPos) self.splineIkLoc.append(self.loc) cmds.parent(self.splineIkLoc[1], self.splineIkLoc[0]) cmds.parent(self.splineIkLoc[3], self.splineIkLoc[4]) self.spineIKLoc.append(self.splineIkLoc[0]) self.spineIKLoc.append(self.splineIkLoc[2]) self.spineIKLoc.append(self.splineIkLoc[-1]) self.IKSplineGP = self.System.createCenterPivotGP( [self.spineIKSplineSolver[0], self.curve], "%s_Grp" % self.spineIKSplineSolver[0]) return self.IKSplineGP
def hammerPoints(neighbors=3): """ moves selected cvs to the weighted average of the pts around it [neighbors] """ tgtPts = cmds.ls(sl=True, fl=True) #---------------- add in soft selection? if not tgtPts: cmds.warning("Select one or more cvs") return for tgtPt in tgtPts: #tgtPtPos = cmds.pointPosition(tgtPt) tgtNum = int(tgtPt.partition("[")[2].rpartition("]")[0]) #tgtBase = tgtPt.partition("[")[0] crv = tgtPts[0].partition(".")[0] ptPosListX = [] ptPosListY = [] ptPosListZ = [] count = 0 for x in range(-neighbors, neighbors + 1): count += abs(x) if x != 0: origPt = "{0}.cv[{1}]".format(crv, tgtNum + x) origPtPos = cmds.pointPosition(origPt) for a in range(abs(x)): ptPosListX.append(origPtPos[0]) ptPosListY.append(origPtPos[1]) ptPosListZ.append(origPtPos[2]) avgX = sum(ptPosListX) / (len(ptPosListX)) avgY = sum(ptPosListY) / (len(ptPosListY)) avgZ = sum(ptPosListZ) / (len(ptPosListZ)) newPos = [avgX, avgY, avgZ] cmds.xform(tgtPt, ws=True, t=newPos)
def mirrorCtrls(strA, strB): cmds.undoInfo(openChunk=True) try: masterCtrlSetName = 'CTRL_SET' if cmds.objExists(masterCtrlSetName): setMemberList = cmds.listConnections(masterCtrlSetName + '.dagSetMembers', s=True, d=False) for member in setMemberList: if strA in member and member.replace(strA, strB) in setMemberList: pointNumA = cmds.getAttr(member + '.controlPoints', size=True) pointNumB = cmds.getAttr(member.replace(strA, strB) + '.controlPoints', size=True) if pointNumA == pointNumB: for point in range(pointNumA): pos = cmds.pointPosition(member + '.cv[' + str(point) + ']', w=True) cmds.move(-pos[0], pos[1], pos[2], member.replace(strA, strB) + '.cv[' + str(point) + ']', a=True) else: message = QtGui.QMessageBox(self) message.setText(u'错误:\n' + masterCtrlSetName + u'不存在,请检查文件是否损坏!!!') message.setWindowTitle('Error!') message.setIcon(QtGui.QMessageBox.Warning) button = QtGui.QPushButton() button.setText('OK') message.addButton(button, QtGui.QMessageBox.DestructiveRole) message.setDefaultButton(button) message.exec_() return cmds.undoInfo(closeChunk=True) except: print 'something wrong…' cmds.undoInfo(closeChunk=True)