def assignShader2(): shaderInfoNode = pm.PyNode('shaderInfoNode') numAttr = shaderInfoNode.shaderInfos.numChildren() message = '' for i in range(numAttr): shaderInfos = json.loads( shaderInfoNode.attr('shaderInfos{}'.format(i)).get()) try: pm.select(shaderInfos.get('geometry')) surfaceShader = pm.PyNode(shaderInfos.get('surfaceShader')) pm.hyperShade(assign=surfaceShader) pm.select(cl=True) try: if shaderInfos.get('displacement'): displacement = pm.PyNode(shaderInfos.get('displacement')) sg = surfaceShader.outColor.outputs()[0] displacement.displacement.connect(sg.displacementShader) except: message += (str(shaderInfos.get('displacement')) + '-->' + sg.name() + '\n') except: message += (str(shaderInfos.get('surfaceShader')) + '-->' + str(shaderInfos.get('geometry')) + '\n') shaderInfoNode.unlock() pm.delete(shaderInfoNode) return message
def delete_vertex(mesh): # print mesh pm.select(None) for v in mesh.getShape().vtx: d = True if (vert_on_rect_edge(v, mesh.getBoundingBox())): d = False try: if (len(v.connectedEdges()) > 2): d = False except: d = False if (d): # print v pm.delete(v) pm.polyMergeVertex(mesh, d=0.001, am=1) # faces = [f for f in mesh.f] # for i in range(len(faces)) : # try : f = faces[i] # except : break # if( f.isZeroArea() ) : # # print f # pm.delete(f) # delete_vertex(mesh) # break pm.delete(mesh, ch=True) return mesh
def bind_card(source_mesh, target_mesh, combine=True): hasskin = True try: source_skin_cluster = pm.PyNode( pm.mel.eval('findRelatedSkinCluster %s' % (source_mesh))) joints = source_skin_cluster.getWeightedInfluence() except: hasskin = False if (combine): p = target_mesh.getParent() dup_source_mesh = source_mesh.duplicate()[0] dup_target_mesh = target_mesh.duplicate()[0] bind_mesh = pm.polyUnite(dup_source_mesh, dup_target_mesh)[0] bind_mesh.rename(target_mesh.name()) pm.delete(bind_mesh, ch=True) try: pm.delete(dup_source_mesh) except: pass else: bind_mesh = target_mesh if hasskin: target_skin_cluster = pm.skinCluster(bind_mesh, joints) pm.copySkinWeights(source_mesh, bind_mesh, ia='oneToOne', sa='closestPoint') pm.select(bind_mesh) th_skinClusterMerge.reduce_influences() pm.select(None)
def create_curves_from_mesh(mesh): global THU_MFT_ANGLE_TOLERANCE try: edges = mesh.edges except: pm.error('Could not get edges from %s' % (mesh)) edge_curve_group_name = mesh.name().split(':')[-1] + '_edgeCurve_GRP' try: edge_curve_group = pm.PyNode(edge_curve_group_name) except: edge_curve_group = pm.group(name=edge_curve_group_name, world=True, empty=True) converted_edges = [] for c, edge in enumerate(edges): if (edge not in converted_edges): print 'Processing edge %s of %s' % (c, len(edges)) merged_curve, edgeloop = __create_curve_from_edge(edge) pm.select(None) converted_edges.extend(edgeloop) # print merged_curve if (merged_curve): merged_curve.setParent(edge_curve_group) return edge_curve_group
def __create_curve_from_edge(edge): edgeloop = __get_edge_loop(edge, [], None) edgeloop.insert(0, edge) edge_curves = [] for edgeloop_edge in edgeloop: edge_curves.append( pm.curve( # name=n, degree=1, ws=True, point=[ v.getPosition() for v in edgeloop_edge.connectedVertices() ])) pm.select(None) if (len(edge_curves) > 1): merged_curve = pm.attachCurve(edge_curves[:-1], method=1, keepMultipleKnots=False, ch=False)[0] edge_curves.pop(edge_curves.index(merged_curve)) # closed_curve = pm.closeCurve( merged_curve )[0] closed_curve = merged_curve # pm.delete( merged_curve ) else: closed_curve = None pm.delete(edge_curves) return closed_curve, edgeloop
def create_locator(name): pm.select(None) global THU_MFT_LOCATOR_MATERIAL_NAME, THU_MFT_LOCATOR_ATTR try: material = pm.PyNode(THU_MFT_LOCATOR_MATERIAL_NAME) except: material = pm.createSurfaceShader( 'lambert', name=THU_MFT_LOCATOR_MATERIAL_NAME)[0] material.color.set((1, 0, 0)) material.transparency.set((0.8, 0.8, 0.8)) loc_name = '%s_%s' % (name, THU_MFT_LOCATOR_ATTR) try: locator_trans = pm.PyNode(loc_name) except: locator_trans = pm.polyPlane(name=loc_name, sw=1, sh=1)[0] pm.sets(material.shadingGroups()[0], edit=True, forceElement=locator_trans) if (not locator_trans.hasAttr(THU_MFT_LOCATOR_ATTR)): locator_trans.addAttr(THU_MFT_LOCATOR_ATTR, dt='string') locator_trans.setAttr(THU_MFT_LOCATOR_ATTR, name) return locator_trans
def skin(self, **kwargs): skip = kwargs.get("skip", 0) jnt_lst = kwargs.get("joints", []) vert_lst = kwargs.get("vert_lst", []) skin_cluster = self.get_skin_cluster(node=self.shape_node) pm.select(clear=True) if not skin_cluster: skin_cluster = pm.skinCluster(jnt_lst[0], self.shape_node, toSelectedBones=True) self.add_influence(skin_cls=skin_cluster, inf_lst=jnt_lst[1:]) else: self.add_influence(skin_cls=skin_cluster, inf_lst=jnt_lst) """ influence_objects = skin_cluster.getInfluence() for inf_obj in influence_objects: pm.skinCluster(skin_cluster, edit=True, influence=str(inf_obj), lockWeights=True) skin_cluster.addInfluence(jnt_lst) for inf_obj in influence_objects: pm.skinCluster(skin_cluster, edit=True, influence=str(inf_obj), lockWeights=False) """ if skin_cluster.getMaximumInfluences() < 2: skin_cluster.setMaximumInfluences(2) jnt_index = 0 jnt = str(jnt_lst[jnt_index]) for verts in vert_lst: if (vert_lst.index(verts) > 0) and (vert_lst.index(verts) % (skip + 1) == 0): if skip < (len(jnt_lst)): jnt_index += 1 jnt = str(jnt_lst[jnt_index]) for vert in verts: pm.skinPercent(skin_cluster, vert, transformValue=(jnt, 1.0)) return None
def addAttributeGroup( self, user_given_vray_attr_group ): ## Get selection sel = pm.ls(selection=True) ## Copy selection in case we modify the list objs = sel[:] for obj in objs: try: shp = obj try: shp = obj.getShape() except: shp = obj ##if hasattr( obj, "getShape" ): ## shp = obj.getShape() pm.mel.eval( 'vray addAttributesFromGroup "' + shp.name() + '" "' + user_given_vray_attr_group + '" 1;' ) except: print "not working" ##restore original selection pm.select(sel)
def main(): sel = pm.ls(os=True, fl=True) if len(sel) != 3: pm.warning("Select 3 vertices in order of origin, x, and y") return shape = pm.listRelatives(sel[0], parent=True)[0] transformNode = pm.listRelatives(shape, parent=True)[0] piv = pm.xform(transformNode, q=True, ws=True, rp=True) p0 = sel[0].getPosition() p1 = sel[1].getPosition() p2 = sel[2].getPosition() X = p1 - p0 # X-axis Y = p2 - p0 # Y-axis Z = X ^ Y # Z-axis P = pm.datatypes.Point(piv[0], piv[1], piv[2]) X.normalize() Y.normalize() Z.normalize() M = pm.datatypes.Matrix( X.x, X.y, X.z, 0, Y.x, Y.y, Y.z, 0, Z.x, Z.y, Z.z, 0, P.x, P.y, P.z, 1) pm.xform(transformNode, matrix=M.inverse()) pm.select(transformNode, r=True) pm.makeIdentity(apply=True, t=True, r=True, s=False, n=False) pm.xform(transformNode, ws=True, piv=(0, 0, 0)) pm.xform(transformNode, matrix=M)
def toPolygons(self): ## could have feature added to select joints if they have poly shape nodes objs = pm.ls( selection=True ) converted = [] #print pm.ls( selection=True, showType=True ) for obj in objs: print obj.type() is_confirmed_as_mesh = False if obj.type()=='transform': s = obj.getShape() if obj.type()=='mesh': s = obj obj = s.getParent() is_confirmed_as_mesh = True if is_confirmed_as_mesh==False: if s.type()=='mesh': is_confirmed_as_mesh = True if is_confirmed_as_mesh==True: converted.append( obj ) pm.select( converted )
def jnt_at_mid_vertex_orient(**kwargs): sel = pm.ls(orderedSelection=True, flatten=True) if not sel: pm.displayInfo("Please select vertex") return None obj_pos_map = {} for comp in sel: if not isinstance(comp, pm.MeshVertex): pm.displayInfo("Please select only vertex") return None mid_pos = 0 for comp in sel: comp.node() transform_node = pm.listTransforms(comp.node())[0] if transform_node not in obj_pos_map.keys(): vrts = CustomScripts.get_vrts(sel_obj=[transform_node])[0] pos = CustomScripts.midPos(selected_items=vrts) obj_pos_map[transform_node] = pos mid_pos = pos else: mid_pos = obj_pos_map[transform_node] comp_pos = pm.pointPosition(comp, world=True) pm.select(clear=True) jnt1 = pm.joint(position=mid_pos) jnt2 = pm.joint(position=comp_pos) pm.joint(jnt1, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', zeroScaleOrient=True) pm.select([jnt1, jnt2]) CustomScripts.CopyJntOri() return None
def __rename_from_ui() : # rename_replace( pm.ls( sl=True ), searchfield.getText(), replacefield.getText() ) sel = pm.ls( sl=True ) new = __rename_list_from_textfields( *[i.name() for i in sel] ) for name, obj in zip( new, sel ) : obj.rename( name ) pm.select(sel)
def joints_along_curve(**kwargs): number_of_joints = kwargs.get("number_of_joints", 2) bind_curve = kwargs.get("bind_curve_to_joint", False) curve = kwargs.get("curve", None) if not isinstance(curve, pm.PyNode): curve = pm.PyNode(bind_curve) crv_len = curve.length() parts = number_of_joints - 1 div = float(crv_len) / float(parts) len_lst = [0] inc = 0 for i in range(1, parts + 1): inc += div len_lst.append(inc) joint_lst = [] for val in len_lst: pm.select(clear=True) param = curve.findParamFromLength(val) point = curve.getPointAtParam(param) jnt = pm.joint(position=point, radius=3) joint_lst.append(jnt) if bind_curve: pm.skinCluster(joint_lst, curve) return joint_lst
def createJoint(positionList): for pos in position_list: pm.select(clear=True) new_joint = pm.joint(position=pos) new_joint.radius.set(0.2) pm.select(clear=True) return None
def makeCamPlaneForDrawing(self): drawPlaneGroup = pm.createNode( "transform" ); size = 1024 planeList = pm.polyPlane( w=size,h=size, sx=1,sy=1, n="drawPlane", axis=[0,0,1] ) #print( planeList ) planeXform = planeList[0] planeShape = planeXform.getShape() planeShape.overrideEnabled.set(1) planeShape.overrideShading.set(0) locatorXform = pm.spaceLocator(n="drawPlaneLocator") locatorShape = locatorXform.getShape() locatorShape.localScale.set( [128,128,128] ) camList = pm.camera( name="drawPlaneCam" ) #print( camList ) camXform = camList[0] camXform.tz.set(256) pm.parent( planeXform, locatorXform ) pm.parent( locatorXform, drawPlaneGroup ) pm.parent( camXform, drawPlaneGroup ) pm.orientConstraint( camXform, planeXform, ) ##aimVector=[0,1,0], upVector=[0,0,1] ) ## Look through cam pm.select( camXform ) panel = pm.getPanel( withFocus=True ) pm.mel.eval( "lookThroughSelected 0 " + panel +";") pm.makeLive( planeXform )
def snapVertsToGrid(cls, log=False): originalSelection = pm.ls( selection=True, flatten=True ) pm.mel.eval('ConvertSelectionToVertices;') selVerts = pm.ls( selection=True, flatten=True ) #objectSelection = pm.ls(selection=True, shapes=True ) #selObjs = originalSelection[:] ## copy the list #selVerts = pm.polyListComponentConversion( # fromFace=True, fromVertex=True, fromEdge=True, # fromVertexFace=True, # toVertex=True ) # #selVerts = spacing = cls.getSpacing() for v in selVerts: if isinstance( v, pm.MeshVertex ): pW = v.getPosition(space='world') p = pW.homogenize() ## Turn it into simply coords #print( type(p.x) ) def onGrid(n, s): return ( spacing * float( round( n/float(s) ) ) ) p.x = onGrid( p.x, spacing ) p.y = onGrid( p.y, spacing ) p.z = onGrid( p.z, spacing ) #print( p.x, p.y, p.z ) v.setPosition( p.homogenize(), space='world' ) #print p.x,p.y,p.z #print( help(p) ) #break pm.select( originalSelection )
def applyUvToWorldRatioToSelection(self, targetRatio=None): oSel = pm.ls(sl=True) pm.mel.eval("ConvertSelectionToFaces;") sel = pm.ls(sl=True) if targetRatio == None: targetRatio = input() currentRatio = self.calcUvToWorldAreaRatio() amountToScaleBeforeSqrt = targetRatio / currentRatio amountToScale = math.sqrt(amountToScaleBeforeSqrt) ## Calc a bounding box in uv space, and it's center, for a scale pivot bb = pm.polyEvaluate(sel, boundingBoxComponent2d=True) bbUMin = bb[0][0] bbUMax = bb[0][1] bbVMin = bb[1][0] bbVMax = bb[1][1] bbUCenter = (bbUMax + bbUMin) * 0.5 bbVCenter = (bbVMax + bbVMin) * 0.5 pm.polyEditUV(sel, pu=bbUCenter, pv=bbVCenter, su=amountToScale, sv=amountToScale) pm.select(oSel)
def create_material( xml_path, suppress_warnings=True ) : pm.select( None ) if( suppress_warnings ) : pm.scriptEditorInfo( edit=True, suppressWarings=True ) tree = et.parse( xml_path ) root_keys = tree.getroot().keys() if( not 'imagePath' in root_keys ) : pm.error( 'The XML file does not appear to be a Texture Packer XML' ) texture_file = tree.getroot().get( 'imagePath' ) texture_path = os.path.join( os.path.dirname( xml_path ), texture_file ); material_name = __get_filename_noext( texture_file ) + '_MAT' try : material = pm.PyNode( material_name ) except : material = pm.createSurfaceShader( 'lambert', name=material_name )[0] try : material_file = material.connections( type='file' )[0] except : material_file = pm.File( name=__get_filename_noext( texture_file ) + '_FILE' ) try : material_file.outColor >> material.color except : pass try : material_file.outTransparency >> material.transparency except : pass material_file.fileTextureName.set( texture_path ) if( suppress_warnings ) : pm.scriptEditorInfo( edit=True, suppressWarings=False ) return material
def projectSelection(self): hiliteOrig = pm.ls(hilite=True) selOrig = pm.ls(selection=True) selPre = pm.polyListComponentConversion(selOrig, tv=True) try: pm.select(self.referenceXformNode, replace=True) pm.select(selPre, add=True) selForTransfer = pm.ls(selection=True) pm.transferAttributes( transferPositions=1, transferNormals=0, transferUVs=0, transferColors=0, sampleSpace=0, searchMethod=0 ) objsToAddToSelection = [] for o in selForTransfer: # s = str( type(o) ) # print "y" + s + "y" if str(type(o)) == "<class 'pymel.core.general.MeshVertex'>": n = o.name().split(".")[0] objsToAddToSelection.append(n) for obj in objsToAddToSelection: pm.select(obj, add=True) pm.delete(ch=True) ##was #pm.mel.eval( "DeleteHistory;" ) print(selForTransfer) pm.select(selOrig, replace=True) pm.hilite(hiliteOrig) except: pm.select(selOrig) pm.hilite(hiliteOrig) print( "Please ensure that you have a valid reference mesh selected, and that you have verticies or objects select to project." )
def __rename_from_ui(): # rename_replace( pm.ls( sl=True ), searchfield.getText(), replacefield.getText() ) sel = pm.ls(sl=True) new = __rename_list_from_textfields(*[i.name() for i in sel]) for name, obj in zip(new, sel): obj.rename(name) pm.select(sel)
def curve_through_points(**kwargs): selection_points = kwargs.get("selection_points", None) curve_degree = kwargs.get("curve_degree", 3) curve_name = kwargs.get("curve_name", "Curve") if not selection_points: selection_points = pm.ls(selection=True) if not selection_points: pm.displayInfo("Please select reference points") return None if len(selection_points) < curve_degree + 1: pm.displayInfo("please select more than " + str(curve_degree + 1) + " points") return None points_locations = [] for point in selection_points: points_locations.append( pm.xform(point, query=True, translation=True, worldSpace=True)) pm.select(clear=True) current_curve = pm.curve(degree=curve_degree, worldSpace=True, point=points_locations) pm.rename(current_curve, curve_name) return current_curve
def volumeSelect(cls, faces=False ): sel = pm.ls(sl=1) if len(sel) < 2: print( "You must have at least two objects selected" ) return [] checkInsideObj = sel.pop() #checkInsideObj = sel[1] allIn = [] for container in sel: allVtx = pm.ls(str(checkInsideObj)+'.vtx[*]',fl=1) start = pm.timerX() for eachVtx in allVtx: location = pm.pointPosition(eachVtx,w=1) test = cls.pyRayIntersect(container,location,(0,1,0)) if(test): allIn.append(eachVtx) elapsedTime = pm.timerX(startTime = start) print "time :",elapsedTime pm.select(allIn,replace=1) if faces==True: pm.mel.eval( 'ConvertSelectionToContainedFaces;' ) return pm.ls(selection=True)
def __recursive_export_ffm( obj, res_path, model_rel_path, errors = [ '**Mesh export errors**' ] ) : global FFU_E_FFEXPORT_DEFAULT_OPTIONS, FFU_E_FFEXPORT_SETTINGS for obj_child in obj.getChildren( type='transform' ) : if( type( obj_child.getShape() ) is pm.Mesh ) : filename = os.path.join( res_path, model_rel_path, __clean_name( obj_child.name() ) ) filename = filename.replace( '\\', '/' ) options = FFU_E_FFEXPORT_DEFAULT_OPTIONS options += FFU_E_FFEXPORT_SETTINGS.to_string() cmd = 'file -force -options "%s" -type "FF Exporter" -es "%s";' % ( options, filename ) pm.select( obj_child ) try : pm.mel.eval( cmd ) except : errors.append( 'Could not export model %s to %s' % ( obj_child.name(), filename ) ) __recursive_export_ffm( obj_child, res_path, model_rel_path, errors ) if( len( errors ) > 1 ) : return errors else : return []
def export_models( res_path, model_rel_path, selected_only ) : print 'Exporting models' res_path = os.path.abspath( res_path ) model_rel_path = os.path.normpath( model_rel_path ) sel = pm.ls( sl=True ) try : os.makedirs( os.path.join( res_path, model_rel_path ) ) except : pass objects = __get_object_list( selected_only ) errors=[] for obj in objects : clean_obj = __create_clean_object( obj ) errors.extend( __recursive_export_ffm( clean_obj, res_path, model_rel_path ) ) # pm.delete( clean_obj ) pm.select( sel ) if( len(errors) ) : for error in errors : print error print 'Exporting models finished' return True
def sd_transfer_attributes(self, selection): new_sel = selection.pop(0) for obj in selection: transfer_from = [new_sel, obj] pm.select(transfer_from) pm.transferAttributes( transferPositions=0, transferNormals=0, transferUVs=1, sourceUvSet="tiling", targetUvSet="map1", transferColors=0, sampleSpace=5, sourceUvSpace="tiling", targetUvSpace="map1", searchMethod=3, flipUVs=0, colorBorders=1 ) pm.delete(ch=True)
def sd_random_y_offset(selection, y_value, both_directions=True): """ Randomly offsets objects in the range of -n to n where n is the y_value if both_directions is True :param selection: The current selection. :param y_value: -n to n where n is y_value :param both_directions: clamps the range to 0 to n where n is y_value :return: None """ # for obj in _is_group(selection): for obj in selection: pm.select(obj) if y_value == 0: y_random = 0 else: y_random = random.uniform(-y_value, y_value) if not both_directions: y_random = abs(y_random) if type(obj) == pm.MeshVertex: pm.setAttr('{}.pnty'.format(obj), y_random) else: obj.setAttr('translateY', y_random) pm.select(selection) return None
def unfold3dMultipleObjects(self): origSel = pm.ls(selection=True) for obj in origSel: pm.select(obj) pm.mel.eval("ConvertSelectionToUVs;") pm.mel.eval("Unfold3D -unfold -iterations 1 -p 1 -borderintersection 1 -triangleflip 1;") pm.select(origSel)
def snapVertsToGrid(cls, log=False): originalSelection = pm.ls(selection=True, flatten=True) pm.mel.eval('ConvertSelectionToVertices;') selVerts = pm.ls(selection=True, flatten=True) #objectSelection = pm.ls(selection=True, shapes=True ) #selObjs = originalSelection[:] ## copy the list #selVerts = pm.polyListComponentConversion( # fromFace=True, fromVertex=True, fromEdge=True, # fromVertexFace=True, # toVertex=True ) # #selVerts = spacing = cls.getSpacing() for v in selVerts: if isinstance(v, pm.MeshVertex): pW = v.getPosition(space='world') p = pW.homogenize() ## Turn it into simply coords #print( type(p.x) ) def onGrid(n, s): return (spacing * float(round(n / float(s)))) p.x = onGrid(p.x, spacing) p.y = onGrid(p.y, spacing) p.z = onGrid(p.z, spacing) #print( p.x, p.y, p.z ) v.setPosition(p.homogenize(), space='world') #print p.x,p.y,p.z #print( help(p) ) #break pm.select(originalSelection)
def __init__(self, factories, typename='', **kwargs): self.node = self.createNode() self.factories = factories self.type = typename self.attrs = {} self.children = {} self.parents = {} self.gui = CRObject_GUI(self) self.bScript = True clstypename = self.__class__.crtype.getTypeName() if not typename: typename = clstypename if Object.getInstanceQualifier() in kwargs: typename = kwargs[Object.getInstanceQualifier()] fact = self.factories.getFactory(clstypename) sim = fact.build(typename, **kwargs) self.initMembers(self.__class__.crtype, sim, prefix='default') if Scriptable.getTypeName() in kwargs: self.addScript(prefix='script', **kwargs[Scriptable.getTypeName()]) self.rename(typename) CRObject.addObjToGlobalContext(self) pm.select(self.node)
def delete_vertex( mesh ) : # print mesh pm.select(None) for v in mesh.getShape().vtx : d = True if( vert_on_rect_edge( v, mesh.getBoundingBox() ) ) : d = False try : if( len( v.connectedEdges() ) > 2 ) : d = False except : d = False if(d) : # print v pm.delete(v) pm.polyMergeVertex( mesh, d=0.001, am=1 ) # faces = [f for f in mesh.f] # for i in range(len(faces)) : # try : f = faces[i] # except : break # if( f.isZeroArea() ) : # # print f # pm.delete(f) # delete_vertex(mesh) # break pm.delete( mesh, ch=True ) return mesh
def exportYeti(path): yeitInfo = getYetiInfo() if pm.objExists('yetiInfoNode'): yetiInfoNode = pm.PyNode('yetiInfoNode') yetiInfoNode.unlock() pm.delete(yetiInfoNode) attrName = 'yetiInfo' yetiInfoNode = pm.createNode('network', n='yetiInfoNode') yetiInfoNode.addAttr(attrName, dt='string') jsonHandl = json.dumps(yeitInfo) yetiInfoNode.attr(attrName).set(jsonHandl) yetiInfoNode.attr(attrName).lock() yetiInfoNode.lock() exportList = [yetiInfoNode] for _, shader in yeitInfo.items(): exportList.append(shader) pm.select(exportList) try: pm.exportSelected(path, pr=1, typ='mayaBinary', force=1, es=1) print 'Success Export Shader' except: print exportList print path finally: yetiInfoNode.unlock() pm.delete(yetiInfoNode)
def place_objects(self, **kwargs): interval = kwargs.get("skip", 0) if not self.loop: pm.displayError("no Loops received") return None if interval > len(self.loop): pm.displayError( "Skipping value larger than number of edges present") return self.FAIL jnt_lst = [] index = 0 max_len = len(self.loop) while index < max_len: pos = CustomScripts.midPos(selected_items=self.loop[index]) jnt_lst.append(pm.joint(position=pos)) if len(jnt_lst) > 1: pm.parent(jnt_lst[-1], jnt_lst[-2]) pm.joint(jnt_lst[-2], edit=True, orientJoint='xyz', secondaryAxisOrient='yup', zeroScaleOrient=True) index += interval + 1 pm.select(jnt_lst[-2], jnt_lst[-1]) CustomScripts.CopyJntOri() return jnt_lst
def bind_card( source_mesh, target_mesh, combine=True ) : hasskin = True try : source_skin_cluster = pm.PyNode( pm.mel.eval( 'findRelatedSkinCluster %s' % ( source_mesh ) ) ) joints = source_skin_cluster.getWeightedInfluence() except : hasskin = False if( combine ) : p = target_mesh.getParent() dup_source_mesh = source_mesh.duplicate()[0] dup_target_mesh = target_mesh.duplicate()[0] bind_mesh = pm.polyUnite( dup_source_mesh, dup_target_mesh )[0] bind_mesh.rename( target_mesh.name() ) pm.delete( bind_mesh, ch=True ) try : pm.delete( dup_source_mesh ) except : pass else : bind_mesh = target_mesh if hasskin : target_skin_cluster = pm.skinCluster( bind_mesh, joints ) pm.copySkinWeights( source_mesh, bind_mesh, ia='oneToOne', sa='closestPoint' ) pm.select( bind_mesh ) th_skinClusterMerge.reduce_influences() pm.select(None)
def get_loop_from_edge(self, **kwargs): edg = kwargs.get("edg", None) obj = kwargs.get("obj", None) edg_num = int((edg.split("[")[1]).replace("]", "")) pm.polySelect(obj, edgeLoopOrBorder=edg_num) edg_loop = pm.ls(selection=True, flatten=True) pm.select(clear=True) return edg_loop
def assign_shader(self, sh, Utile, Vtile): self.sel = pm.ls(selection=True) if not pm.objExists(sh): self.create_shader(sh) pm.select(self.sel) pm.hyperShade(assign=pm.PyNode(sh)) self.disp_uv_tile_val(sh, Utile, Vtile) return None
def convertSelectionToHardEdges(): pm.mel.eval( "ConvertSelectionToEdges;" ) cmps = pm.ls(selection=True, flatten=True ) to_select = [] for cmp in cmps: if cmp.isSmooth()==False: to_select.append( cmp ) pm.select( to_select )
def convertSelectionToHardEdges(): pm.mel.eval("ConvertSelectionToEdges;") cmps = pm.ls(selection=True, flatten=True) to_select = [] for cmp in cmps: if cmp.isSmooth() == False: to_select.append(cmp) pm.select(to_select)
def jnt_at_mid_vertex_orient(**kwargs): sel = pm.ls(orderedSelection=True, flatten=True) if not sel: pm.displayInfo("Please select vertex") return None obj_pos_map = {} for comp in sel: if not isinstance(comp, pm.MeshVertex): pm.displayInfo("Please select only vertex") return None mid_pos = 0 for comp in sel: #vertex_position = pm.pointPosition(comp, world=True) #component_pos.append(vertex_position) shape_node = comp.node() transform_node = pm.listTransforms(comp.node())[0] if transform_node not in obj_pos_map.keys(): vrts = CustomScripts.get_vrts(sel_obj=[transform_node])[0] print vrts pos = CustomScripts.midPos(selected_items=vrts) obj_pos_map[transform_node] = pos mid_pos = pos else: mid_pos = obj_pos_map[transform_node] print obj_pos_map comp_pos = pm.pointPosition(comp, world=True) pm.select(clear=True) jnt1 = pm.joint(position=mid_pos) jnt2 = pm.joint(position=comp_pos) pm.joint(jnt1, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', zeroScaleOrient=True) pm.select([jnt1, jnt2]) CustomScripts.CopyJntOri() #obj_list[comp] = transform_node #if transform_node not in obj_list: # obj_list.append(transform_node) #vrts = CustomScripts.get_vrts(sel_obj = obj_list) #pos = [] #for vrt in vrts: # pos.append(CustomScripts.midPos(selected_items = vrt)) #for p in component_pos: # pm.select(clear=True) # jnt1 = pm.joint(position=p) # jnt2 = pm.joint(position = component_pos[pos.index(p)]) # pm.joint(jnt1, edit=True, orientJoint='xyz', # secondaryAxisOrient='yup', zeroScaleOrient=True) # pm.select(clear=True) # pm.select([jnt1, jnt2]) # CustomScripts.CopyJntOri() # pm.select(clear=True) return None
def fixJointComplexXformsForSelected(self): oSel = pm.ls(sl=True) objs=oSel[:] for obj in objs: try: self.fixJointComplexXforms( obj ) except: print( traceback.format_exc() ) pm.select(oSel)
def autoOrientXKeepZForSelected(self ): oSel = pm.ls(sl=True) objs=oSel[:] for obj in objs: try: self.autoOrientXKeepZ( obj ) except: print( traceback.format_exc() ) pm.select(oSel)
def unfold3dMultipleObjects(self): origSel = pm.ls(selection=True) for obj in origSel: pm.select(obj) pm.mel.eval("ConvertSelectionToUVs;") pm.mel.eval( "Unfold3D -unfold -iterations 1 -p 1 -borderintersection 1 -triangleflip 1;" ) pm.select(origSel)
def selectObjects(self, node = None, attribute = None): if node is None: OpenMaya.MGlobal.displayError('[Arsenal] You must to select a pass') return pm.select(cl=True) for myConnected in pm.listConnections(node + '.' + attribute, destination=False, source=True): pm.select(myConnected, add=True) print '[Arsenal] Object(s) selection done.'
def orient( self, _orientchildless=True, _rotateOrder=None ) : # get the rotation order we're after if( not _rotateOrder ) : _rotateOrder = settings.rotationorder # check we have a child to aim to and decide of aim vectors aimvector = utils.aim_axis_to_vectors( _rotateOrder )[0] upvector = utils.aim_axis_to_vectors( _rotateOrder )[1] aim = aimvector children = self.getChildren() parent = self.getParent() if( not parent ) : parent = self if( len( children ) < 1 ) : if( not _orientchildless ) : utils.wrn( '%s has no children. Skipping orient...' % ( self.name() ) ) return False else : aim = [ a * b for a, b in zip( aimvector, [-1] * 3 ) ] pm.select( None ) # create children average aim locator childrenlocator = pm.spaceLocator() if( len( children ) ) : pm.delete( pm.pointConstraint( children + [ childrenlocator ], mo=False ) ) else : childrenlocator.setTranslation( parent.getTranslation( space='world' ), space='world' ) # create up aim locator and aim self to it uplocator = pm.spaceLocator() pm.delete( pm.pointConstraint( [ parent, self, childrenlocator, uplocator ], mo=False ) ) pm.delete( pm.aimConstraint( [ self, uplocator ], mo=False, wut='object', wuo=parent ) ) uplocator.translateBy( ( 0, 0, 0.5 ) ) # unparent children, aim the joint to the average of it's children, then reparent children for joint in children : joint.setParent( None ) pm.delete( pm.aimConstraint( [ childrenlocator, self ], mo=False, wut='object', wuo=uplocator, upVector=upvector, aim=aim ) ) pm.makeIdentity( self, a=True, r=True ) for joint in children : joint.setParent( self ) # tidy up pm.delete( childrenlocator ) pm.delete( uplocator ) pm.select( self ) return True
def applyMultiplier(self, selection=False, multiplier = 1.0 ): originalSelection = pm.ls(selection=True) pm.select( hierarchy=True ) lights = pm.ls(selection=selection, lights=True) for light in lights: try: v = light.intensity.get() * multiplier light.intensity.set( v ) except: print( "Coundn't set intensity on light: " + light.name() ) pm.select(originalSelection)
def redoIt(self): """ redo it """ cmds.undoInfo(openChunk=True) try: cmds.ConvertSelectionToEdgePerimeter() cmds.ConvertSelectionToVertices() # List of pm vertex object vtxInOrder = self.getVerticesInOrder() pm.select(vtxInOrder, r=True) m_sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(m_sel) dagPath = OpenMaya.MDagPath() components = OpenMaya.MObject() m_sel.getDagPath(0, dagPath, components) v_iter = OpenMaya.MItMeshVertex(dagPath, components) self.CENTER = self.getCenter(v_iter) fnMesh = OpenMaya.MFnMesh(dagPath) normalVector = self.getClosestNormal(self.CENTER, fnMesh) firstPoint = OpenMaya.MPoint( vtxInOrder[0].getPosition(space='world').x, vtxInOrder[0].getPosition(space='world').y, vtxInOrder[0].getPosition(space='world').z) firstVector = firstPoint - self.CENTER # Scale circle firstVector = firstVector * self.MULTIPLY numOfVertices = len(vtxInOrder) baseDegree = 360.0 / numOfVertices degree = 0.0 + self.ROTATION for i in vtxInOrder: nextVector = self.rotateVector( degree, firstVector, normalVector) if self.INVERTED is True: degree += -baseDegree else: degree += baseDegree self.setPoint(i, nextVector, normalVector, fnMesh) except: pass finally: cmds.undoInfo(closeChunk=True)
print( 'attr info:' ) print( attr ) print( type(attr) ) attr.set( objsmsgs ) def selectConnectedToAttributeArray( self, attrName=None ): if attrName is None: attrName = raw_input() objs = pm.ls(selection=True) pm.select(clear=True)
def deleteFacesInSamePlace( self, faces_list, precision, tolerance ): faces = faces_list[:] face_center_dict = {} faces_to_delete = [] for face in faces: pm.select( face ) face_center = self.getFaceCenter( precision ) if face_center in face_center_dict.keys(): faces_to_delete.append( face ) print( "marking face for deletion: " + str( face) ) else: face_center_dict[ face_center ] = face pm.delete( faces_to_delete )
def makeScripterNode( self ): node = pm.createNode('mmmmScripterNodeV001v') originalName = node.name() node.rename( originalName + 'Shape' ) t = node.getParent() t.rename( originalName ) node.rename( t.name()+'Shape' ) c = pm.createNode('transform') c.rename( 'computationEnforcer' ) d = pm.createNode('plusMinusAverage') d.rename( 'dependency__plug_all_dependencies_into_1D_inputs_00' ) d.output1D >> node.dependency pm.parent( c, t ) node.output >> c.translateX pm.select(t) return [t,node,c]
def makeAndParentUcx(self): originalSelection = pm.ls(selection=True) ## Only attempt to export directly from transform nodes! objs = pm.ls( selection=True, transforms=True ) parentObj = objs.pop( ) for i, obj in enumerate(objs): newName = 'UCX_' + parentObj.name() + '_' + str(i).zfill(2) pm.parent( obj, parentObj ) obj.rename( newName ) s = obj.getShape() s.overrideEnabled.set(True) s.overrideShading.set(False)
pass def exportAsObj(self): pm.exportSelected( 'd:/deletemeLiamExport.obj', shader = 1, force=True, typ = "OBJexport", #pr = 1, ## #es = 1, ) def buildOutputFileNameWithPath( self, newEnding ): fname = cmds.file( location=True, query=True ) fnameParts = fname.split('.') ## any string then .join will combine a list by the string before .join fname = ".".join( fnameParts[0:-1] ) ename = "__FORUDK.fbx"
def duplicate_jointchain( self, *_tags, **kwargs ) : # make a deep copy of self # loop through bones and replace rigjoint with a new one # loop through minorbones and replace minorbone with bone.duplicate # we could duplicate the top joint and then compare with original to find the minorjoints # creating each joint individually seems to be more direct though try : _simple = kwargs[ '_simple' ] except : _simple = False dupjointchain = copy.deepcopy( self ) dupjointchain.copymother = self lastrigjoint = None pm.select( None ) for i, rigjoint in enumerate( dupjointchain.rigjoints ) : duprigjointname = utils.name_from_tags( rigjoint, *_tags ) duprigjoint = rigjoint.duplicate( n=duprigjointname )[0] dupjointchain.rigjoints[i] = duprigjoint duprigjoint.setParent( lastrigjoint ) lastrigjoint = duprigjoint # _simple copies only major rigjoints if( not _simple ) : dupjointchain.minorrigjoints[ duprigjoint ] = [] # duplicate each minorrigjoint, add it to it's duplicated major rigjoint array of minor rigjoints for minorrigjoint in dupjointchain.minorrigjoints[ rigjoint ] : dupminorrigjointname = utils.name_from_tags( minorrigjoint, *_tags ) dupminorrigjoint = minorrigjoint.duplicate( n=dupminorrigjointname )[0] dupjointchain.minorrigjoints[ duprigjoint ].append( dupminorrigjoint) dupminorrigjoint.setParent( lastrigjoint ) lastrigjoint = dupminorrigjoint # delete the original rigjoint entry in the dict del dupjointchain.minorrigjoints[ rigjoint ] self.duplicates.append( dupjointchain ) # we'll reset the partname here in case the mother jointchain hs had its changed dupjointchain.PARTNAME = dupjointchain.__class__.PARTNAME return dupjointchain
def mostlySafeCleanup(self, precision, tolerance): objs = pm.ls(selection=True) for obj in objs: pm.select( obj ) ## Now the individual object is selected we Convert to faces pm.mel.eval("""ConvertSelectionToFaces;""") ## Now the faces are all selected ## Get the face selection faces = pm.ls( selection=True, flatten=True ) self.deleteFacesInSamePlace( faces, precision, tolerance ) pm.select( obj ) pm.mel.eval("""ConvertSelectionToVertices;""") pm.polyMergeVertex( alwaysMergeTwoVertices=False, distance = tolerance, worldSpace=True ) pm.select( obj ) pm.mel.eval("""ConvertSelectionToEdges;""") pm.polySewEdge( worldSpace = True, texture = True, tolerance = tolerance ) pm.select( obj ) pm.mel.eval("""ConformPolygonNormals;""") #pm.polyNormal( normalMode = 2 ) ## Restore the original selection pm.select( objs )
def convertSelectionToCreasedEdges(): pm.mel.eval( "ConvertSelectionToEdges;" ) objs = pm.ls(selection=True, flatten=True) objsToSelect = [] for obj in objs: try: creaseValue = pm.polyCrease( obj, query=True, value=True ) creaseValue = creaseValue[0] except: creaseValue = 0 if creaseValue > 0.01: #print( "found a creased edge" ) objsToSelect.append(obj) if len(objsToSelect) > 0: #print(objsToSelect) #print("selecting") pm.select( objsToSelect, replace=True ) else: pm.select( clear=True )
def putObjOnSnappableSpacing(obj, snappableSpacing): oSel = pm.ls(selection=True) destinationObj = obj usedObj = obj pm.select(destinationObj) t = pm.xform(query=True, rotatePivot=True, worldSpace=True) vt = pm.core.datatypes.Vector(t[0], t[1], t[2]) vt = onSnappableSpacingVec(vt, snappableSpacing) pm.select(usedObj) pm.move(vt, worldSpace=True, absolute=True, worldSpaceDistance=True) ## We compensate by getting the *object being moved*'s ## pivot t2 = pm.xform(query=True, rotatePivot=True, worldSpace=True) vt2 = pm.core.datatypes.Vector(t2[0], t2[1], t2[2]) ## vExtra is the additional amount compensated vExtra = vt - vt2 vDest = vt + vExtra vFinal = vDest pm.move(vFinal, worldSpace=True, absolute=True, worldSpaceDistance=True) pm.select(oSel)
def createTwistJointToSelectedChild(): objs = pm.ls(selection=True) ## Make an empty list to store joints in newJoints = [] for obj in objs: pm.select( clear=True ) child = obj parentJnt = obj.getParent() jnt = pm.joint(position=[0,0,0]) pc = pm.pointConstraint( [parentJnt, child] , jnt ) oc = pm.orientConstraint( parentJnt, jnt ) pm.delete( pc ) pm.delete( oc ) pm.parent( jnt, parentJnt ) ## Put out new joint in the list! newJoints.append( jnt )
def ckFidgetInit(): """ ckFidgetInit() description: this function should initialize ckFidget it should check for existing persistent data and create a new node if none exists then it creates the interface inputs: None outputs: initializes ckFidget """ try: print "checking for persistent fidget data" pm.select("ckFidget_GRP") isFidget = pm.getAttr("ckFidget_GRP.ckIsFidget") if isFidget == True: print "Data Found!" pm.setAttr("ckFidget_GRP.bumpBy", False) except: print "data not found initializing new ckFidget instance" pm.group(empty=True, name="ckFidget_GRP") pm.addAttr( longName="ckIsFidget", attributeType='bool', keyable=False ) pm.setAttr("ckFidget_GRP.ckIsFidget", True) pm.addAttr( longName="bumpBy", attributeType='bool', keyable=False ) pm.setAttr("ckFidget_GRP.bumpBy", False) pm.addAttr( longName="ckFidgetBump", attributeType='float', keyable=False, defaultValue=0.1 ) pm.addAttr( longName="numSaves", attributeType="short", keyable=False, defaultValue=0 ) print "here is where I should ask about starting a new fidget" # should pop up a dialog and ask the name of the new fidget pm.addAttr( longName="ckFidgetList", dataType='string', keyable=False ) pm.addAttr( longName="ckFidgetSav", dataType='string', keyable=False ) pm.setAttr( "ckFidget_GRP.ckFidgetList","" ) pm.setAttr( "ckFidget_GRP.ckFidgetSav","" ) pm.select( clear = True ) ckFidgetWin()