def create_card_locators() : locators = {} rank_locators = [ 'rank_top', 'rank_bottom' ] suit_locators = [ 'suit_top', 'suit_bottom' ] face_locators = [ 'face' ] number_locators = range( 2, 11 ) locators[ 'rank_locators' ] = [] for rank_locator in rank_locators : locators[ 'rank_locators' ].append( create_locator( rank_locator ) ) locators[ 'suit_locators' ] = [] for suit_locator in suit_locators : locators[ 'suit_locators' ].append( create_locator( suit_locator ) ) locators[ 'face_locators' ] = [] for face_locator in face_locators : locators[ 'face_locators' ].append( create_locator( face_locator ) ) locators[ 'number_locators' ] = [] for number in number_locators : g_name = 'number_%s_GRP' % ( number ) try : g = pm.PyNode( g_name ) except : g = pm.group( name=g_name, empty=True, world=True ) locators[ 'number_locators' ].append( g ) for n in range( number ) : l = create_locator( 'number_%s_%s' % ( number, n ) ) l.setParent( g ) for key, item in locators.items() : g_name = '%s_GRP' % ( key ) try : g = pm.PyNode( g_name ) except : g = pm.group( name=g_name, empty=True, world=True ) for i in item : i.setParent(g) return locators
def make_groups(car_name): """Helper - Make common groups """ group = pm.group(name=car_name + '_group', empty=True) nodes_group = pm.group(name='nodes_group', empty=True, parent=group) beams_group = pm.group(name='beams_group', empty=True, parent=group) return group, nodes_group, beams_group
def create_zero_sdk_groups( _obj, _replacelast=True ) : zerogroup = pm.group( n=name_from_tags( _obj, 'zero', _replacelast=_replacelast ), em=True, world=True ) sdkgroup = pm.group( n=name_from_tags( _obj, 'sdk', _replacelast=_replacelast ), em=True, world=True ) zerogroup.setTransformation( _obj.getTransformation() ) sdkgroup.setTransformation( _obj.getTransformation() ) _obj.setParent( sdkgroup ) sdkgroup.setParent( zerogroup ) return sdkgroup, zerogroup
def build_box(car_name): """Method 1 - This buider make box strucutre (not strong) """ sel = pm.ls(sl=True) group = pm.group(name=car_name + '_group', empty=True) nodes_group = pm.group(name='nodes_group', empty=True, parent=group) beams_group = pm.group(name='beams_group', empty=True, parent=group) if not sel: return trans = sel[0] mesh = trans.getShape() pm.hide(trans) d = {} verts = mesh.verts for index, vtx in enumerate(verts): loc = pm.spaceLocator() loc.rename('b' + str(index)) loc.t.set(vtx.getPosition(space='world')) loc.overrideEnabled.set(True) loc.overrideColor.set(17) loc.setParent(nodes_group) index = vtx.index() d[index] = {'loc': loc, 'connected': []} for c in vtx.connectedVertices(): c_index = c.index() if c_index < index: continue d[index]['connected'].append(c_index) index = 0 for each in d: loc = d[each]['loc'] for other in d[each]['connected']: other_loc = d[other]['loc'] curve = pm.curve(p=[(0, 0, 0), (1, 0, 0)], degree=1) curve.rename('beam_' + str(index)) shape = curve.getShape() curve.overrideEnabled.set(True) curve.overrideColor.set(15) lock_hide(curve) loc.t >> shape.controlPoints[0] other_loc.t >> shape.controlPoints[1] curve.setParent(beams_group) index += 1 pm.select(clear=True)
def import_vehicle(): """Import a vehicle """ pm.newFile(force=True) print('importing: {}'.format(vehicle_path)) print('\nImporting the dae files\n') # Import the mesh files import_mesh(vehicle_path=vehicle_path) print('\nImporting the pc files\n') # Import the pc files for pc_path in glob.glob(os.path.join(vehicle_path, '*.pc')): import_pc(pc_path=pc_path) print('\nImporting the jbeam files\n') # Import the jbeam files grp = pm.group(empty=True, world=True, name='jbeam') # Import nodes first for jbeam_path in glob.glob(os.path.join(vehicle_path, '*.jbeam')): import_jbeam_nodes(root=grp, jbeam_path=jbeam_path) # Import beams for jbeam_path in glob.glob(os.path.join(vehicle_path, '*.jbeam')): import_jbeam_beams(root=grp, jbeam_path=jbeam_path)
def merge_cards(start, end, suit): cards = [] # suits = [ 'Hearts', 'Diamonds', 'Clubs', 'Spades' ] ranks = range(start, end) total_cards = len(ranks) i = 0 # for suit in suits : try: suit_group = pm.PyNode('%s_cards_GRP' % (suit)) except: suit_group = pm.group(name='%s_cards_GRP' % (suit), empty=True, world=True) for rank in ranks: print 'Processing card %s of %s' % (i, total_cards) # print rank, suit # print get_card_sprites( rank, suit ) # return card_sprites = pm.duplicate(get_card_sprites(rank, suit)) for card_sprite in card_sprites: card_sprite.setParent(None) card = pm.polyUnite(card_sprites, mergeUVSets=1, ch=True)[0] pm.delete(card, ch=True) for cs in card_sprites: try: pm.delete(cs) except: pass card.rename('%s_%s_G' % (suit, rank)) card.setParent(suit_group) cards.append(card) # pm.flushUndo() i += 1 return cards
def ConnectThroughRig(src, attr, root, rigObject): name = src.name() grp = pm.group(name='%s_squash_GRP' % (name), empty=True, parent=src.getParent()) grp.setTranslation(src.getTranslation(space='world'), space='world') for child in src.getChildren(type=pm.Transform): child.setParent(grp) md = pm.MultiplyDivide(name='%s_squashInvert_MD' % (name)) md.input1.set(-1, -1, -1) for i, axis in enumerate(['X', 'Y', 'Z']): src.attr('%s%s' % (attr, axis)) >> md.attr('input2%s' % axis) md.attr('output%s' % axis) >> rigObject['inattrs'][i] md = pm.MultiplyDivide(name='%s_squashScaleOffset_MD' % (name)) rigObject['outattrs'] >> md.input1 md.input2.set(3, 3, 3) md.output >> grp.scale pm.pointConstraint(src, grp, mo=False) pm.orientConstraint(src, grp, mo=False) return {'control': src, 'root': root, 'rig': rigObject['group']}
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 merge_cards( start, end, suit ) : cards = [] # suits = [ 'Hearts', 'Diamonds', 'Clubs', 'Spades' ] ranks = range( start, end ) total_cards = len( ranks ) i = 0 # for suit in suits : try : suit_group = pm.PyNode( '%s_cards_GRP' % ( suit ) ) except : suit_group = pm.group( name='%s_cards_GRP' % ( suit ), empty=True, world=True ) for rank in ranks : print 'Processing card %s of %s' % ( i, total_cards ) # print rank, suit # print get_card_sprites( rank, suit ) # return card_sprites = pm.duplicate( get_card_sprites( rank, suit ) ) for card_sprite in card_sprites : card_sprite.setParent(None) card = pm.polyUnite( card_sprites, mergeUVSets=1, ch=True )[0] pm.delete( card, ch=True ) for cs in card_sprites : try : pm.delete( cs ) except : pass card.rename( '%s_%s_G' % ( suit, rank ) ) card.setParent( suit_group ) cards.append( card ) # pm.flushUndo() i += 1 return cards
def mirrorSelection(self): #try: nobjs = pm.instance() gr = pm.group(em=True, n = "Mirrored") for nobj in nobjs: pm.parent( nobj, gr ) ### **** Fix this later to use pymel pm.scale( gr, -1,1,1 )
def import_jbeam_nodes(root, jbeam_path): print('importing jbeam nodes: {}'.format(jbeam_path)) data = jbeam_to_json.read(jbeam_file=jbeam_path) print('data: {}'.format(data)) if not data: return jbean_grp_name = os.path.basename(jbeam_path).split('.')[0] + '_group' jbeam_grp = pm.group(empty=True, parent=root, name=jbean_grp_name) for root in data.keys(): # print('\t{}'.format(root)) root_grp = pm.group(empty=True, parent=jbeam_grp, name=root + '_group') nodes_grp = pm.group(empty=True, parent=root_grp, name='nodes') nodes = [] beams = [] # Build nodes for key in data[root].keys(): # print('\t\t{}'.format(key)) if key == 'nodes': for node_val in data[root]['nodes']: if not type(node_val) == list: # read settings here continue if node_val[1] == 'posX': continue # simple nodes if len(node_val) == 4: # print('\t\t\t{}'.format(node_val)) point = [node_val[1], node_val[2], node_val[3]] # print('point: {}'.format(point)) maya_builders.make_node(name=node_val[0], parent=nodes_grp, point=point) # complex nodes else: pass
def set_poleLocator(**kwargs): """ Select 3 joints parent to child in order to which pole vector has to be placed Select 3 joints and ik handle in order, to create the pole vector object and constraint """ distance_scale = kwargs.get("distance_scale", 1) pole_vector_locator = kwargs.get("pole_vector", "poleLocator") selected_joint = pm.ls(selection=True) if len(selected_joint) < 3: print("please select 3 joints") return None joint1_position = pm.xform(selected_joint[0], query=True, worldSpace=True, translation=True) joint2_position = pm.xform(selected_joint[1], query=True, worldSpace=True, translation=True) joint3_position = pm.xform(selected_joint[2], query=True, worldSpace=True, translation=True) joint1_vector = openmaya.MVector(joint1_position[0], joint1_position[1], joint1_position[2]) joint2_vector = openmaya.MVector(joint2_position[0], joint2_position[1], joint2_position[2]) joint3_vector = openmaya.MVector(joint3_position[0], joint3_position[1], joint3_position[2]) joint1_joint2_vector = joint2_vector - joint1_vector joint1_joint2_vector.normalize() joint2_joint3_vector = joint3_vector - joint2_vector joint2_joint3_vector.normalize() plane_normal = joint1_joint2_vector ^ joint2_joint3_vector plane_normal.normalize() joint1_joint3_vector = joint3_vector - joint1_vector joint1_joint3_vector.normalize pole_vector = joint1_joint3_vector ^ plane_normal mag_vec = pole_vector * distance_scale pole_position = joint2_vector + mag_vec loc_pos = [pole_position.x, pole_position.y, pole_position.z] pole_locator = pm.spaceLocator(name=pole_vector_locator) locator_group = pm.group(pole_locator, name=pole_vector_locator + "_group") pm.xform(locator_group, translation=loc_pos) print("Pole object placed at ", str(loc_pos)) if len(selected_joint) == 4: ik_handle = selected_joint[3] pm.poleVectorConstraint(pole_locator, ik_handle) print("Pole Vector Constraint applied") return None
def __group(name, parent): try: grp = pm.PyNode('%s|%s' % (parent, name)) # if( len(grp.getChildren(type=pm.Shape)) > 0 ) : # return None # else : # return grp except: grp = pm.group(name=name, parent=parent, empty=True) return grp
def ckAddFidget(): """ ckAddFidget( ) description: this function collects the selected attribute and adds it to the list of data that fidget will work with inputs: None outputs: None CK - this would be a great place to add data to a persistent node in the maya file(working) """ # fist we are collecting the selected attribute atribSel = pm.mel.eval('selectedChannelBoxAttributes();') # then we get the object said attribute belongs to slectItm = pm.ls( selection = True ) # the two are added together so we can work with the information # inside the maya context newAttr = slectItm.pop() + '.' + atribSel.pop() # this is a test to ensure that we are in fact getting some kind of data from # the attribute newVal = pm.getAttr( newAttr ) print newVal pm.select( clear = True ) # given that has worked we will add the data to the lists ckAddToList( "ckFidget_GRP.ckFidgetList", newAttr) ckAddToList( "ckFidget_GRP.ckFidgetSav", newVal) pm.group(name = str(newAttr+"_SAV0" )) pm.addAttr( longName="fdgSave", dataType="string", keyable=False) newAttr = newAttr.split(".") pm.setAttr( str(newAttr[0]+"_"+newAttr[1]+"_SAV0.fdgSave"), str(newVal)) pm.select( "ckFidget_GRP") pm.parent( str(newAttr[0]+"_"+newAttr[1]+"_SAV0") ) pm.select( clear = True ) pm.select(newAttr[0]) # now issue the call to rebuild the interface ckFidgetWin()
def CreateScaleRig(name): outgrp = pm.group(name='%s_squashRig_GRP' % (name), empty=True) outloc = pm.spaceLocator(name='%s_squashOut_LOC' % (name)) outloc.setParent(outgrp) aims = [] inattrs = [] pm.cycleCheck(e=False) for axis in ['X', 'Y', 'Z']: loc = pm.spaceLocator(name='%s_squashIn%s_LOC' % (name, axis)) grp = pm.group(name='%s_squashLoc%s_GRP' % (name, axis), empty=True) loc.setParent(grp) grp.setAttr('translate%s' % (axis), 1) pm.pointConstraint(loc, outloc, mo=False) aims.append(pm.aimConstraint(outloc, grp)) grp.setParent(outgrp) inattrs.append(loc.translateX) for aim in aims: pm.delete(aim) pm.cycleCheck(e=True) return {'group': outgrp, 'inattrs': inattrs, 'outattrs': outloc.translate}
def immediateParent(**kwargs): """ Insert an immediate parent node to the selected object with the selected object position as reference to parent """ group_name = kwargs.get("name", "null") sel_obj = pm.ls(selection=True) if not sel_obj: pm.group(name=group_name) return None for obj in sel_obj: parent_node = pm.listRelatives(obj, parent=True) pm.select(clear=True) group_name = str(obj) + "_Znode" null = pm.group(name=group_name) pm.parentConstraint(obj, null, maintainOffset=False, name="temp_const") pm.delete("temp_const") if parent_node: pm.parent(null, parent_node) pm.parent(obj, null) return None
def create_card_locators(): locators = {} rank_locators = ['rank_top', 'rank_bottom'] suit_locators = ['suit_top', 'suit_bottom'] face_locators = ['face'] number_locators = range(2, 11) locators['rank_locators'] = [] for rank_locator in rank_locators: locators['rank_locators'].append(create_locator(rank_locator)) locators['suit_locators'] = [] for suit_locator in suit_locators: locators['suit_locators'].append(create_locator(suit_locator)) locators['face_locators'] = [] for face_locator in face_locators: locators['face_locators'].append(create_locator(face_locator)) locators['number_locators'] = [] for number in number_locators: g_name = 'number_%s_GRP' % (number) try: g = pm.PyNode(g_name) except: g = pm.group(name=g_name, empty=True, world=True) locators['number_locators'].append(g) for n in range(number): l = create_locator('number_%s_%s' % (number, n)) l.setParent(g) for key, item in locators.items(): g_name = '%s_GRP' % (key) try: g = pm.PyNode(g_name) except: g = pm.group(name=g_name, empty=True, world=True) for i in item: i.setParent(g) return locators
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()
def create_zero_group(self, **kwargs): ctr = kwargs.get("ctr", None) from_name = kwargs.get("from_nm", "") z_name = kwargs.get("zero_nm", "") if not z_name: z_name = "_ZeroNode" node_nm = str(ctr) + z_name grp_nd = pm.group(name="null", empty=True) if from_name: if str(ctr).find(from_name) > -1: node_nm = str(ctr).replace(from_name, z_name) self.set_control_position(cur_obj=ctr, ctr=grp_nd) pm.parent(ctr, grp_nd) pm.rename(grp_nd, node_nm) return None
def splitSelection() : __st(0) workingList, sel = getMeshesRecursivelyFromSelection() gMainProgressBar = pm.PyUI(pm.mel.eval( '$tmp = $gMainProgressBar' )) gMainProgressBar.setMaxValue( len(workingList) ) if( len(workingList) > 0 ) : try : outputGrp = pm.PyNode(OUTPUT_GRP_NAME) except (pm.MayaNodeError) : outputGrp = pm.group(name=OUTPUT_GRP_NAME, world=True, empty=True) outputContents = outputGrp.getChildren() for child in outputContents : pm.delete(child) pm.uitypes.ProgressBar.beginProgress( gMainProgressBar, status="Splitting meshes..." ) gMainProgressBar.step(0) pm.refresh() for mesh in workingList : splitByMaterials(mesh, outputGrp) gMainProgressBar.step(1) pm.refresh() materialGroups = outputGrp.getChildren() for group in materialGroups : mergeGroup(group) else : pm.warning( 'No meshes found in selection' ) gMainProgressBar.endProgress() # pm.select(sel) pm.select(outputGrp) print 'Splitting mesh by material COMPLETE' __et(0, 'Total')
def dae_to_mb(dae_path, mb_path): """Convert a dae file to Maya binary Args: dae_path (str): Path to dae file """ pm.newFile(force=True) pm.importFile(dae_path) name = os.path.basename(dae_path).split('.')[0] pm.select(pm.ls(type='mesh')) group = pm.group(world=True, name=name + '_meshGroup') for loc in pm.ls(type='locator'): pm.delete(loc.getParent()) pm.saveAs(mb_path)
def import_jbeam_beams(root, jbeam_path): # Build Beams data = jbeam_to_json.read(jbeam_file=jbeam_path) if not data: return jbean_grp_name = os.path.basename(jbeam_path).split('.')[0] b_index = 0 for root in data.keys(): root_grp_name = 'jbeam|{}_group|{}_group'.format(jbean_grp_name, root) root_grp = pm.DependNode(root_grp_name) # print('root_grp: {}'.format(root_grp)) beams_grp = pm.group(empty=True, parent=root_grp, name='beams') for key in data[root].keys(): if key == 'beams': for beam_val in data[root]['beams']: if not type(beam_val) == list: # read settings here continue if len(beam_val) == 2 and beam_val[0] == 'id1:': continue # print('\t\t\t{}'.format(beam_val)) # Create the beam if pm.objExists(beam_val[0]) and pm.objExists(beam_val[1]): # print('making beam with: {} and {}'.format( # beam_val[0], beam_val[1])) maya_builders.make_beam(index=b_index, c=beam_val, group=beams_grp) b_index += 1
def match_ctrl(jnt, ctrl): control_name = ctrl.name(long=None) control_shape = ctrl.getShape() transform = pm.group(parent=jnt, empty=True) transform.zeroTransformPivots() pm.parent(transform, world=True) pm.parent(control_shape, transform, absolute=True, shape=True) new_trans = pm.listRelatives(control_shape, parent=True) pm.makeIdentity(new_trans, s=True, r=True, t=True, apply=True) pm.parent(control_shape, transform, relative=True, shape=True) pm.delete(new_trans, ctrl) transform.rename(control_name) pm.delete(transform, constructionHistory=True)
def create_group(*args): """This method creates empty group at user selected positions function call format : create_locator("String", Integer) User Inputs: args[0] : Object name args[1] : object Id to start with Returns : None """ # If number of parameters mismatch, return with message if len(args) != 2: print "arguments mismatch" return None # Call to method to obtain list of selected position position_list = obtain_selection_position() # If user selected nothing, return with message display if not position_list: print 'please make selection' return None # Obtain object name from args object_name = args[0] # Obtain the object ID from args as integer object_id = int(args[1]) # Create empty roup and move the empty group to # selected position, and increment the ID value to name # the next group in loop for objectPosition in position_list: group_name = object_name + str(object_id) + '_Group' created_group = pm.group(name=group_name, empty=True) pm.xform(created_group, translation=objectPosition, worldSpace=True) object_id = object_id + 1 return None
def import_mesh(vehicle_path): """Import mesh. cache it to a mb file if one doesn't exists. Args: dae_path (str): Path to dae file """ pm.newFile(force=True) mb_paths = [] for dae_path in glob.glob(os.path.join(vehicle_path, '*.dae')): # import_mesh(dae_path=dae_path) ext = dae_path.split('.')[-1] mb_path = dae_path.replace('.' + ext, '.mb') if not os.path.exists(mb_path): dae_to_mb(dae_path=dae_path, mb_path=mb_path) mb_paths.append(mb_path) # name = os.path.basename(dae_path).split('.')[0] pm.newFile(force=True) for f in mb_paths: pm.importFile(f) # Cleanup # Remove lights for light in pm.ls(type='pointLight'): pm.delete(light.getParent()) # Group mesh root_grp = pm.group(empty=True, world=True, name='mesh') for grp in pm.ls(assemblies=True): if grp != root_grp and not grp.getShape(): grp.setParent(root_grp)
def make_groups_from_path_list( _pathlist, _topgroup=None, _stopbefore=0 ) : _ret = [] lastgroup = pm.PyNode( _topgroup ) for i, level in enumerate( _pathlist ) : if( i > len( _pathlist ) - abs( _stopbefore ) ) : break try : name = _pathlist[0].name except : name = level try : partname = level.PARTNAME except : partname = 'NULL' pm.select( None ) groupname = '%s%s%s' % ( name, settings.name_string_delimeter, partname ) groupname = name_from_tags( groupname, 'group', _replacelast=False ) # check if the group exists and return the previosuly created group ifit does # otherwise create a new group group = None lastgroupchildren = lastgroup.getChildren() for child in lastgroupchildren : if( child.name().split( '|' )[-1] == groupname ) : group = child break if( not group ) : group = pm.group( n=groupname ) group.setParent( lastgroup ) _ret.append( group ) lastgroup = group pm.select( lastgroup ) return _ret
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_offset(self): grp = pymel.group(empty=True) self.setParent(grp) return grp
def setup_ik_spline(**kwargs): curve = kwargs.get("curve", None) joint_chain = kwargs.get("joint_chain", None) auto_curve = kwargs.get("auto_curve", True) use_curve = kwargs.get("use_curve", None) spans = kwargs.get("number_of_spans", 4) ctrl_jnts = kwargs.get("num_control_joints", 3) ik_name = kwargs.get("ik_name", "ikHandle") scale_stretch = kwargs.get("scale_stretch", False) create_dense_chain = kwargs.get("dense_chain", False) dense_division = kwargs.get("dense_chain_divisions", 3) auto_simplify = kwargs.get("auto_simplify_curve", False) stretch_exp = kwargs.get("stretch_exp", False) global_scale_check = kwargs.get("global_scale_check", False) global_scale_attr = kwargs.get("global_scale_attr", None) pm.select(joint_chain, hierarchy=True) joint_chain = pm.ls(selection=True) if not isinstance(joint_chain[0], pm.Joint): pm.displayInfo("selection should be of type joint") return None if len(joint_chain) < 2: pm.displayInfo("Chain should consist of more than one joint") return None if (global_scale_check): if (global_scale_attr is None): pm.displayInfo("Please input global scale attribute") return None else: obj = global_scale_attr.split(".")[0] global_attr = global_scale_attr.split(".")[1] check_global_attr = pm.attributeQuery(global_attr, node=obj, exists=True) if not check_global_attr: pm.displayInfo("Invalid global scale attribute") return None start_jnt = joint_chain[0] end_joint = joint_chain[-1] if create_dense_chain: rep_chain = pm.duplicate(joint_chain) start_jnt = rep_chain[0] end_joint = rep_chain[-1] dense_chain(joints=rep_chain, joints_inbetween=dense_division) rep_chain.append(end_joint) for index in range(len(joint_chain)): pm.parentConstraint(rep_chain[index], joint_chain[index], maintainOffset=False) #pm.scaleConstraint(rep_chain[index], joint_chain[index], maintainOffset=False) pm.connectAttr( str(rep_chain[index]) + ".scale", str(joint_chain[index]) + ".scale") pm.select(start_jnt, hierarchy=True) new_chain = pm.ls(selection=True) crv = "" #print "START", start_jnt #print "END",end_joint if auto_curve: ik_handle, eff, crv = pm.ikHandle(startJoint=start_jnt, createCurve=auto_curve, solver="ikSplineSolver", numSpans=spans, endEffector=end_joint, simplifyCurve=auto_simplify) else: crv = pm.PyNode(use_curve) ik_handle, eff = pm.ikHandle(startJoint=start_jnt, curve=use_curve, solver="ikSplineSolver", endEffector=end_joint, createCurve=False) crv.inheritsTransform.set(0) pm.rename(ik_handle, ik_name + "IK_Handle") pm.rename(crv, ik_name + "IK_Curve") ik_curve_shp = crv.getShape() crv_info_node = pm.createNode("curveInfo") pm.connectAttr(ik_curve_shp + ".worldSpace", crv_info_node + ".inputCurve") ''' if stretch_exp: if create_dense_chain: stretch_expression(joints = new_chain, curve_info_node = crv_info_node, connect_scale = scale_stretch, expression_name = ik_name+"_stretch_expression") else: stretch_expression(joints = joint_chain, curve_info_node = crv_info_node, connect_scale = scale_stretch, expression_name = ik_name+"_stretch_expression") ''' if ctrl_jnts: if ctrl_jnts == 1: print "Minimum 2 joints needed as controllers" print "skipping control joint creation process" pm.displayInfo("Minimum 2 joints needed as controllers") else: ctrl_jnts = joints_along_curve(number_of_joints=ctrl_jnts, curve=crv, bind_curve_to_joint=True) pm.select(clear=True) ctr_jnt_gp = pm.group(ctrl_jnts, name="control_joints") #print "JNT NAME", ctr_jnt_gp if stretch_exp: pm.addAttr(ctrl_jnts[-1], longName="Stretch", attributeType="enum", enumName="off:on", keyable=True) print "ATTRIBUTE TO", str(ctrl_jnts[-1]) if create_dense_chain: stretch_expression(joints=new_chain, curve_info_node=crv_info_node, connect_scale=scale_stretch, expression_name=ik_name + "_stretch_expression", ctrl_attr=str(ctrl_jnts[-1]) + ".Stretch", glbl_scl_stat=global_scale_check, glbl_scl_attr=global_scale_attr) else: stretch_expression(joints=joint_chain, curve_info_node=crv_info_node, connect_scale=scale_stretch, expression_name=ik_name + "_stretch_expression", ctrl_attr=str(ctrl_jnts[-1]) + ".Stretch", glbl_scl_stat=global_scale_check, glbl_scl_attr=global_scale_attr) final_group = pm.group(name=ik_name + "_ik_group", empty=True) pm.parent(joint_chain[0], final_group) pm.parent(crv, final_group) pm.parent(ik_handle, final_group) if ctrl_jnts > 1: pm.parent(ctr_jnt_gp, final_group) if create_dense_chain: pm.select(clear=True) dense_grp = pm.group(start_jnt, name="dense_chain_group") pm.parent(dense_grp, final_group) return None
def treadAtPoints(**kwargs): #get inputs tread_name = kwargs.get("tr_name", "Tread") crv = kwargs.get("path_crv", None) crv = str(pm.duplicate(crv, name=str(tread_name) + "PathCrv")[0]) pm.xform(crv, centerPivots=True) #obtain curve length full_length = pm.arclen(crv) paramVal = [] uVal = [] # get param value on the curve at each position selected (locators) sel_obj = pm.ls(selection=True) for obj in sel_obj: pos = pm.xform(obj, query=True, translation=True, worldSpace=True) param = getuParamVal(pos, crv) paramVal.append(param) crv_shp = pm.listRelatives(crv, shapes=True)[0] # create arc length dimension tool arcLen = pm.arcLengthDimension(crv_shp + ".u[0]") # for each param value obtained set the arc length tool attribute and # store the length of curve at that param value # normalize the curve to obtain the motion path U value at each position for val in paramVal: pm.setAttr(str(arcLen) + ".uParamValue", val) len_at_pos = pm.getAttr(str(arcLen) + ".arcLength") uVal.append(len_at_pos / full_length) pm.delete(arcLen) mthPthLst = [] jntLst = [] # create joints, assign motion path and set U value obtained for u in uVal: pm.select(clear=True) jnt = pm.joint() jntLst.append(jnt) pathanim = pm.pathAnimation(jnt, curve=crv, fractionMode=True, follow=True, followAxis="x", worldUpType="vector", worldUpVector=(0, 1, 0)) mthPthLst.append(pathanim) pm.setAttr(str(pathanim) + ".uValue", u) pm.disconnectAttr(str(pathanim) + ".u") # create up locator at mid point of all joints #loc_pos = midPos(selected_items = jntLst) #loc_pos = pm.xform(crv, query=True, translation=True, worldSpace=True) loc_pos = midPosVec(objects=jntLst) loc = pm.spaceLocator() pm.xform(loc, translation=loc_pos, worldSpace=True) for mtPth in mthPthLst: pm.pathAnimation(mtPth, edit=True, worldUpType="object", worldUpObject=loc) # create control curve, add run and speed attributes control_crv = pm.circle(name=tread_name + "CTRL", normalX=1, normalY=0, normalZ=0) pm.xform(control_crv, translation=loc_pos) pm.select(clear=True) pm.addAttr(control_crv, longName="run", attributeType="float", keyable=True) pm.addAttr(control_crv, longName="speed", attributeType="float", keyable=True, minValue=0.0, defaultValue=0.5) # group the tread setup pm.parent(crv, control_crv) pm.parent(loc, control_crv) pm.select(clear=True) gp = pm.group(name=tread_name + "GP") pm.select(clear=True) jnt_gp = pm.group(jntLst, name=tread_name + "JNTGP") pm.xform(gp, translation=loc_pos) pm.parent(control_crv, gp) pm.parent(jnt_gp, gp) createTreadExpression(mtnPth=mthPthLst, runAttr=str(control_crv[0]) + ".run", speedAttr=str(control_crv[0]) + ".speed", exp_nm=tread_name) return None #treadAtPoints(pathCrv = "nurbsCircle1", tr_name = "testTread")
def setup_motion_path(self): setup_name = self.get_setup_name() path_name = self.get_path_name() sample_obj = self.get_sample_objects() duplicate_flag = self.get_duplicate_flag() placement_type = self.get_placement_type() division_count = self.get_division_count() if setup_name == self.INVALID_INPUT_FAIL: pm.displayError("Invalid Input Entered for setup name") return None if path_name == self.INVALID_INPUT_FAIL: pm.displayError("Invalid Input Entered for path name") return None if path_name == self.NO_OBJECT_FAIL: pm.displayError("path Curve does not exist") return None if path_name == self.DATA_TYPE_FAIL: pm.displayError("Path can be only Nurb Curves") return None if division_count == self.INVALID_INPUT_FAIL: pm.displayError("Invalid Input Entered for divisions") return None if division_count == self.DATA_TYPE_FAIL: pm.displayError("Divisions can take only integer values") return None if sample_obj == self.NO_OBJECT_FAIL: pm.displayError("Sample Object not found") return None obj_list = [] path_anim_list = [] sel_objs = pm.ls(selection=True) if duplicate_flag: path_name = self.get_duplicate_path(path_crv=path_name) path_name = pm.rename(path_name, setup_name + "_path_CRV") if placement_type == "uniform": obj_list, path_anim_list = self.uniform_distribution( name=setup_name, path=path_name, sample=sample_obj, divisions=division_count) else: if not sel_objs: pm.displayError("No Objects selected") for obj in sel_objs: if not pm.objExists(obj): pm.displayWarning(str(obj), "does not exist") return None obj_list, path_anim_list = self.at_selection( name=setup_name, path=path_name, sample=sample_obj, selection_list=sel_objs) loc_pos = CustomScripts.midPos(selected_items=path_name) loc = pm.spaceLocator(name=setup_name + "_up_loc") pm.xform(loc, translation=loc_pos) control_crv = pm.circle(name=setup_name + "CTRL", normalX=1, normalY=0, normalZ=0) pm.xform(control_crv[0], translation=loc_pos, worldSpace=True) pm.select(clear=True) # add run and speed attributes on parent nurb curve pm.addAttr(control_crv[0], longName="run", attributeType="float", keyable=True) pm.addAttr(control_crv[0], longName="speed", attributeType="float", keyable=True, minValue=0.0, defaultValue=0.5) # edit the existing motion path to assign up locator for mtPth in path_anim_list: pm.pathAnimation(mtPth, edit=True, worldUpType="object", worldUpObject=loc) # parent the setup under the parent nurb curve pm.parent(path_name, control_crv[0]) pm.parent(loc, control_crv[0]) pm.select(clear=True) gp = pm.group(name=setup_name + "GP") pm.xform(gp, translation=loc_pos) pm.select(clear=True) obj_gp = pm.group(obj_list, name=setup_name + "object_GP") pm.parent(control_crv[0], gp) pm.parent(obj_gp, gp) # call to create expression function self.createTreadExpression(mtnPth=path_anim_list, runAttr=str(control_crv[0]) + ".run", speedAttr=str(control_crv[0]) + ".speed", exp_nm=setup_name) return None
def main() : pp = pprint.PrettyPrinter( indent=4 ) # vclass.testJoint() # return l = 'file -f -options "v=0;" -esn false -ignoreVersion -typ "mayaAscii" -o "/Users/Tom/Development/th_autorig2/assets/autorig_test.ma";addRecentFile("/Users/Tom/Development/th_autorig2/assets/autorig_test.ma", "mayaAscii");' pm.mel.eval( l ) # print pm.api.MFnDependencyNode # RigJoint( name='test' ) # print type(pm.PyNode( 'pelvis_j' )) # print MyVirtualNode(n='wow') for group in settings.staticgroupsdict.values() : pm.group( n=group, empty=True, world=True ) staticcontrolgroup = utils.make_groups_from_path_list( [ 'static' ], pm.PyNode( settings.staticgroupsdict[ 'controls' ] ) )[0] for control in settings.staticcontrols.values() : c = RigControl( n=control ) c.zero_group().setParent( staticcontrolgroup ) # l_arm.orient_jointchain() # l_arm.split_rigjoint( 0, 2 ) # l_arm.duplicate_jointchain( ) # l_arm_rig = BasicRig( l_arm ) # print l_arm.tree_parent() chain, torun, twist, stretch, shouldtidy = [None] * 5 chain = 'arm' # chain = 'spine' torun = 'ik' # torun = 'fk' # torun = 'spline' # torun = 'blend' twist = False stretch = True shouldtidy = False # shouldtidy = True if( chain == 'arm' ) : l_arm = Jointchain.from_startend( pm.PyNode( 'leftUpperArm_1_j' ), pm.PyNode( 'leftWrist_j' ) ) l_arm_rig = BindRig( 'leftArm' ) l_arm_rig.create( l_arm, ( 1, 2 ) ) elif( chain == 'spine' ) : spine = Jointchain.from_startend( pm.PyNode( 'spine_1_j' ), pm.PyNode( 'neck_1_j' ) # pm.PyNode( 'leftUpperArm_1_j' ), # pm.PyNode( 'leftWrist_j' ) ) spine_rig = BindRig( 'spine' ) spine_rig.create( spine, # ( 1, 1 ) ) if( torun == 'fk' ) : fk_rig = FkRig() l_arm_rig.add_child( fk_rig ) fk_rig.create() if twist : fk_rig_twist = DistributedTwistAddin() fk_rig.add_child( fk_rig_twist ) fk_rig_twist.create() if stretch : fk_rig.addinSquashStretch() fkw = pm.PyNode('leftWrist_FKJ') palm = pm.PyNode('leftPalm_j') palm.setParent(fkw) if shouldtidy : fk_rig.tidy() elif( torun == 'ik' ) : ik_rig = IkRig() l_arm_rig.add_child( ik_rig ) ik_rig.create() if twist : ik_rig_twist = DistributedTwistAddin() ik_rig.add_child( ik_rig_twist ) ik_rig_twist.create() if stretch : ik_rig.addinSquashStretch() ikw = pm.PyNode('leftWrist_IKJ') palm = pm.PyNode('leftPalm_j') # palm.setParent(ikw) if shouldtidy : ik_rig.tidy() elif( torun == 'blend' ) : blendrig = BlendRig() l_arm_rig.add_child( blendrig ) blendrig.create() blendrig.add_child( fk_rig ) blendrig.add_child( ik_rig ) blendrig.connect_rigs() if shouldtidy : l_arm_rig.tidy() elif( torun == 'spline' ) : splineikfkrig = SplineIkFkRig() spine_rig.add_child( splineikfkrig ) splineikfkrig.create() if shouldtidy : spine_rig.tidy()
def createRivet(self): """ Create one rivet for each selected vertex """ selObjs = pm.ls(selection=True) if not selObjs: ## Nothing is selected, so print out warning and raise error print( self.emsgPleaseSelect ) return #raise Exception, self.emsgPleaseSelect self.originalSel = selObjs #### Store this step of of the selection in case we want it again later uvs = [] uvs.extend( pm.polyListComponentConversion( selObjs, tuv=True ) ) #### Change this to the full version #uvs.extend( [uv for uv in selObjs if '.uv' in uv] ) #### This is a very good list comprehension, perhaps expand it though ## the extend method of a list adds all items from another given list to the list uvsFromNurbs = [] for i in selObjs: if pm.objectType( i ) == 'nurbsSurface' : uvs.append( i ) ## select our new, smaller/filtered uvs pm.select( uvs ) uvs = pm.ls( flatten = True, selection = True ) ## The flatten command returns each component individually in the list, rather than using strings that specify ranges of selections. It takes more RAM but is often much more suitable to work with. ## Create a group so that we can organize the rivets - **** Note that this should be improved with the MmmmTools upcoming unique naming system if not pm.objExists('_follicle_grp'): #### This line and the next should eventually be improved to not use a hardcoded name group = pm.group( em = True, w=True, n='_follicle_grp' ) #### **** Totally recreate this line, use a variable name or at least a unique one else: group = pm.PyNode('_follicle_grp') rivets = [] pm.select( selObjs ) failCount = 0 ## Give an error msg if the user didn't use the script on a compatible selection if not uvs: failCount += 1 print( self.emsgPleaseSelect ) ## Everything is good, proceed to investigate and create rivets for uv in uvs: ## The commented out print line are simple useful for debugging print pm.objectType( uv ) objShapeName, index = tuple( uv.split( '.', 1 ) ) obj = pm.PyNode( objShapeName ) loc = pm.createNode( 'locator' ) tr = getT( loc ) #print( "Transform was: " + tr ) hair = pm.createNode( 'follicle', parent = tr ) pm.parent( tr, group ) #### This line sucks because it's using a f*****g stupid name again rivets.append( tr ) ## Poly mesh handler if pm.objectType( obj ) == 'mesh': obj.outMesh >> hair.inputMesh uvPos = pm.polyEditUV( uv, query=True ) ## Nurbs surface handler elif pm.objectType( obj ) == 'nurbsSurface': obj.local >> hair.inputSurface ## The index is a messy string, so we need to pull uv data out of it uvTuple = ( index.strip('.uv[]').split('][') ) ## We need to create the tuple as floats, because we got it as strings uvPos = ( float(uvTuple[0]), float(uvTuple[1]) ) #uvPos = ( uvTuple[0], uv[1] )#index.strip('.uv[]').split('][') ## Handle conditions where the uvs aren't normalized, this may not be required often maxU = float( obj.maxValueU.get() ) maxV = float( obj.maxValueV.get() ) uvPos = ( uvPos[0]/maxU, uvPos[1]/maxV ) ## Handle other cases, where this script can't do anything useful else: print( obj + ' with uv: ' + uv + \ ' was incompatible, it much be either polygons or Nurbs' ) failCount += 1 continue u, v = uvPos ## Make the hair follow the model, both by parenting, and by keeping its translate and rotate matched obj.worldMatrix >> hair.inputWorldMatrix hair.outTranslate >> tr.translate hair.outRotate >> tr.rotate ## Note: The hair has no outScale ## Set the u and v parameters of the hair so that it sticks to the correct place on the model hair.parameterU.set( u ) hair.parameterV.set( v ) ## Put the rivet into a group so we can select it afterwards self.lastRivetsCreated.append( loc ) ## Select all the new rivets we created pm.select( self.lastRivetsCreated, replace=True ) if failCount: print( str(failCount) + """ rivets failed to be created. Most likely because the selection was not correct. Try selecting vertices on a nurbs surface or a polygon mesh and running the script again. """) else: print( self.msgSucess ) return
def createCtrl(self, name): #cameraName = camera[0].name() cameraShape = self.camera.getShape() # 그룹 리깅 constraint = pm.group(n=name + "_constraint", em=True) offset = pm.group(n=name + "_offset") shakeTransform = pm.group(n=name + "_Shake") offsetTz = pm.group(n=name + "_offsetTz") offsetTy = pm.group(n=name + "_offsetTy") offsetTx = pm.group(n=name + "_offsetTx") tz = pm.group(n=name + "_tz") rz = pm.group(n=name + "_rz") rx = pm.group(n=name + "_rx") ry = pm.group(n=name + "_ry") ctrl = pm.group(n=name + "_Ctrl") pm.setAttr(ctrl + ".displayHandle", 1) pm.setAttr(ctrl + ".overrideEnabled", 1) pm.setAttr(ctrl + ".overrideColor", 7) #dark_green # Display dispGrp = pm.group(n=name + "_Template_Grp", em=1) pm.parent(dispGrp, ctrl) pm.setAttr(dispGrp + ".overrideEnabled", 1) pm.setAttr(dispGrp + ".overrideDisplayType", 1) pm.setAttr(dispGrp + ".overrideColor", 7) #dark_green dispNodeList = [] dispNodeList.extend(self.displayConnect([ctrl, tz])) dispNodeList.extend(self.displayConnect([tz, offsetTx])) dispNodeList.extend(self.displayConnect([offsetTx, offsetTy])) dispNodeList.extend(self.displayConnect([offsetTy, offsetTz])) # Outline for dispNode in dispNodeList: dispNode.rename(name + '_' + dispNode.name()) pm.parent(dispNodeList, dispGrp) # Add attribute # Camera attribute pm.addAttr(ctrl, ln="Camera", en="Option:", at="enum") pm.setAttr(ctrl + ".Camera", e=1, channelBox=True) pm.addAttr(ctrl, ln="focalLength", dv=35, at='double', nn="FocalLength (mm)", keyable=True) pm.addAttr(ctrl, ln="overscan", dv=1, at='double', nn="Overscan", keyable=True) pm.addAttr(ctrl, ln="frameRange", at='double2', nn="Frame Range (frame)") pm.addAttr(ctrl, ln="startFrame", p='frameRange', at='double', nn="Start Frame", keyable=True) pm.addAttr(ctrl, ln="endFrame", p='frameRange', at='double', nn="End Frame", keyable=True) # Tumble attribute pm.addAttr(ctrl, ln="Tumble", en="Option:", at="enum") pm.setAttr(ctrl + ".Tumble", e=1, channelBox=True) pm.addAttr(ctrl, ln="tumbleTranslateZ", at='double', nn="Tumble Translate Z", keyable=True) pm.addAttr(ctrl, ln="tumbleRotate", at='double3', nn="Tumble Rotate") pm.addAttr(ctrl, ln="tumbleRotateX", p='tumbleRotate', at='double', nn="Tumble Rotate X", keyable=True) pm.addAttr(ctrl, ln="tumbleRotateY", p='tumbleRotate', at='double', nn="Tumble Rotate Y", keyable=True) pm.addAttr(ctrl, ln="tumbleRotateZ", p='tumbleRotate', at='double', nn="Tumble Rotate Z", keyable=True) # Shake attribute pm.addAttr(ctrl, ln="Shake", en="Option:", at="enum") pm.setAttr(ctrl + ".Shake", e=1, channelBox=True) pm.addAttr(ctrl, ln="time", keyable=False, at='double', nn="Shake Time (second)") pm.addAttr(ctrl, ln="timeOffset", keyable=False, at='double', nn="Shake Time Offset (second)") pm.addAttr(ctrl, ln="shake1", at='double2', nn=u"Shake 1st (진폭, 주기)") pm.addAttr(ctrl, ln="shakeAmplitude1", p='shake1', at='double', nn=u"Shake 1st (진폭)", keyable=True) pm.addAttr(ctrl, ln="shakeFrequency1", p='shake1', at='double', nn=u"Frequency 1st (주기)", keyable=True) pm.addAttr(ctrl, ln="noise1", at='double3', nn="Shake Noise 1st") pm.addAttr(ctrl, ln="noise1X", p='noise1', at='double', nn="Shake Noise 1 X") pm.addAttr(ctrl, ln="noise1Y", p='noise1', at='double', nn="Shake Noise 1 Y") pm.addAttr(ctrl, ln="noise1Z", p='noise1', at='double', nn="Shake Noise 1 Z") pm.addAttr(ctrl, ln="shake2", at='double2', nn=u"Shake 2nd (진폭, 주기)") pm.addAttr(ctrl, ln="shakeAmplitude2", p='shake2', at='double', nn=u"Shake 2nd (진폭)", keyable=True) pm.addAttr(ctrl, ln="shakeFrequency2", p='shake2', at='double', nn=u"Frequency 2nd (주기)", keyable=True) pm.addAttr(ctrl, ln="noise2", at='double3', nn="Shake Noise 2nd") pm.addAttr(ctrl, ln="noise2X", p='noise2', at='double', nn="Shake Noise 2 X") pm.addAttr(ctrl, ln="noise2Y", p='noise2', at='double', nn="Shake Noise 2 Y") pm.addAttr(ctrl, ln="noise2Z", p='noise2', at='double', nn="Shake Noise 2 Z") pm.addAttr(ctrl, ln="shakeTranslate", at='double3', nn="Shake Translate") pm.addAttr(ctrl, ln="shakeTranslateX", p='shakeTranslate', at='double', nn="Shake Translate X", keyable=True) pm.addAttr(ctrl, ln="shakeTranslateY", p='shakeTranslate', at='double', nn="Shake Translate Y", keyable=True) pm.addAttr(ctrl, ln="shakeTranslateZ", p='shakeTranslate', at='double', nn="Shake Translate Z", keyable=True) pm.addAttr(ctrl, ln="shakeRotate", at='double3', nn="Shake Rotate") pm.addAttr(ctrl, ln="shakeRotateX", p='shakeRotate', at='double', nn="Shake Rotate X", keyable=True) pm.addAttr(ctrl, ln="shakeRotateY", p='shakeRotate', at='double', nn="Shake Rotate Y", keyable=True) pm.addAttr(ctrl, ln="shakeRotateZ", p='shakeRotate', at='double', nn="Shake Rotate Z", keyable=True) pm.addAttr(ctrl, ln="shakeScale", at='double', dv=1.0, keyable=True) pm.addAttr(ctrl, ln="timeScale", at='double', dv=1.0, keyable=True) # Offset attribute pm.addAttr(ctrl, ln="Offset", en="Option:", at="enum") pm.setAttr(ctrl + ".Offset", e=1, channelBox=True) pm.addAttr(ctrl, ln="offsetTranslate", at='double3', nn="Offset Translate") pm.addAttr(ctrl, ln="offsetTranslateX", p='offsetTranslate', at='double', nn="Offset Translate X", keyable=True) pm.addAttr(ctrl, ln="offsetTranslateY", p='offsetTranslate', at='double', nn="Offset Translate Y", keyable=True) pm.addAttr(ctrl, ln="offsetTranslateZ", p='offsetTranslate', at='double', nn="Offset Translate Z", keyable=True) pm.addAttr(ctrl, ln="offsetRotate", at='double3', nn="Offset Rotate") pm.addAttr(ctrl, ln="offsetRotateX", p='offsetRotate', at='double', nn="Offset Rotate X", keyable=True) pm.addAttr(ctrl, ln="offsetRotateY", p='offsetRotate', at='double', nn="Offset Rotate Y", keyable=True) pm.addAttr(ctrl, ln="offsetRotateZ", p='offsetRotate', at='double', nn="Offset Rotate Z", keyable=True) # Display attribute pm.addAttr(ctrl, ln="Display", en="Option:", at="enum") pm.setAttr(ctrl + ".Display", e=1, channelBox=True) pm.addAttr(ctrl, ln="cameraScale", dv=1, at='double', nn="Camera Scale", keyable=True) pm.addAttr(ctrl, en="off:on:", nn="Display Ctrler", ln="displayCtrler", keyable=1, at="enum", dv=1) # Connect Attr pm.connectAttr(ctrl + ".cameraScale", name + ".sx") pm.connectAttr(ctrl + ".cameraScale", name + ".sy") pm.connectAttr(ctrl + ".cameraScale", name + ".sz") pm.connectAttr(ctrl + ".focalLength", cameraShape + ".focalLength") pm.connectAttr(ctrl + ".overscan", cameraShape + ".overscan") pm.connectAttr(ctrl + ".tumbleRotateX", rx + ".rx") pm.connectAttr(ctrl + ".tumbleRotateY", ry + ".ry") pm.connectAttr(ctrl + ".tumbleRotateZ", rz + ".rz") pm.connectAttr(ctrl + ".tumbleTranslateZ", tz + ".tz") pm.connectAttr(ctrl + ".offsetTranslateX", offsetTx + ".tx") pm.connectAttr(ctrl + ".offsetTranslateY", offsetTy + ".ty") pm.connectAttr(ctrl + ".offsetTranslateZ", offsetTz + ".tz") pm.connectAttr(ctrl + ".offsetRotate", offset + ".r") pm.connectAttr(ctrl + ".displayCtrler", dispGrp + ".v") # Lock and Hide unused attr attrList = [ "_ry.tx", "_ry.ty", "_ry.tz", "_ry.rx", "_ry.rz", "_ry.sx", "_ry.sy", "_ry.sz", "_ry.v", "_rx.tx", "_rx.ty", "_rx.tz", "_rx.ry", "_rx.rz", "_rx.sx", "_rx.sy", "_rx.sz", "_rx.v", "_rz.tx", "_rz.ty", "_rz.tz", "_rz.rx", "_rz.ry", "_rz.sx", "_rz.sy", "_rz.sz", "_rz.v", "_tz.tx", "_tz.ty", "_tz.rx", "_tz.ry", "_tz.rz", "_tz.sx", "_tz.sy", "_tz.sz", "_tz.v", "_offsetTx.ty", "_offsetTx.tz", "_offsetTx.rx", "_offsetTx.ry", "_offsetTx.rz", "_offsetTx.sx", "_offsetTx.sy", "_offsetTx.sz", "_offsetTx.v", "_offsetTy.tx", "_offsetTy.tz", "_offsetTy.rx", "_offsetTy.ry", "_offsetTy.rz", "_offsetTy.sx", "_offsetTy.sy", "_offsetTy.sz", "_offsetTy.v", "_offsetTz.tx", "_offsetTz.ty", "_offsetTz.rx", "_offsetTz.ry", "_offsetTz.rz", "_offsetTz.sx", "_offsetTz.sy", "_offsetTz.sz", "_offsetTz.v", "_offset.sx", "_offset.sy", "_offset.sz", "_offset.v", "_Ctrl.sx", "_Ctrl.sy", "_Ctrl.sz" ] for attr in attrList: pm.setAttr(name + attr, lock=True, channelBox=False, keyable=False) pm.setAttr(cameraShape + ".orthographic", lock=False, channelBox=False, keyable=True) pm.setAttr(cameraShape + ".orthographicWidth", lock=False, channelBox=False, keyable=True) # Constraint camera const = pm.parentConstraint(constraint, self.camera, n=name + '_parentConstraint') pm.setAttr(const + ".nds", lock=True, channelBox=False, keyable=False) pm.setAttr(const + ".int", lock=True, channelBox=False, keyable=False) pm.setAttr(const + ".w0", lock=True, channelBox=False, keyable=False) pm.parent(const, ctrl) # Add and Connect message attr = "camera" nodes = [self.camera, ctrl] for node in nodes: if node.hasAttr(attr): node.deleteAttr(attr) pm.addAttr(node, ln=attr, multi=1, attributeType="message", indexMatters=False) for node in nodes: for i in range(0, 2): pm.connectAttr('{}.message'.format(nodes[i].name()), '{}.{}[{}]'.format(node.name(), attr, str(i)), f=1) # Return self.ctrl = ctrl uitConvertsion = self.ctrl.outputs(type="unitConversion") for uit in uitConvertsion: pm.rename(uit.name(), name + '_' + uit.name()) del self.extNode[:] self.extNode.extend([ constraint, offset, shakeTransform, offsetTz, offsetTy, offsetTx, tz, rz, rx, ry, ctrl ]) self.extNode.extend(dispNodeList) self.extNode.extend(uitConvertsion) pm.select(self.ctrl, r=1) return ctrl
def createTread(**kwargs): # get inputs divisions = kwargs.get("no_of_joints", 0) tread_name = kwargs.get("tr_name", "Tread") path_crv = kwargs.get("path_crv", None) # duplicate the existing curve to use for tread creation path_crv = str(pm.duplicate(path_crv, name=str(tread_name) + "PathCrv")[0]) pm.xform(path_crv, centerPivots=True) count = 0 part = float(1) / float(divisions) init = 0 path_anim_list = [] jnt_lst = [] # create joints and place them on curve using motion path at equal distance while count < divisions: pm.select(clear=True) jnt = pm.joint() jnt_lst.append(jnt) pathanim = pm.pathAnimation(jnt, curve=path_crv, fractionMode=True, follow=True, followAxis="x", worldUpType="vector", worldUpVector=(0, 1, 0)) path_anim_list.append(pathanim) pm.setAttr(str(pathanim) + ".uValue", init) pm.disconnectAttr(str(pathanim) + ".u") init += part count += 1 # obtain the midpoint of all joints to create an up locator and position it at midpoint #loc_pos = midPos(selected_items = jnt_lst) #loc_pos = pm.xform(path_crv, query=True, translation=True, worldSpace=True) loc_pos = midPosVec(objects=jnt_lst) loc = pm.spaceLocator(name=tread_name + "_up_loc") pm.xform(loc, translation=loc_pos) # create a nurb circle to act as parent controller control_crv = pm.circle(name=tread_name + "CTRL", normalX=1, normalY=0, normalZ=0) pm.xform(control_crv, translation=loc_pos) pm.select(clear=True) # add unr and speed attributes on parent nurb curve pm.addAttr(control_crv, longName="run", attributeType="float", keyable=True) pm.addAttr(control_crv, longName="speed", attributeType="float", keyable=True, minValue=0.0, defaultValue=0.5) #edit the existing motion path to assign up locator for mtPth in path_anim_list: pm.pathAnimation(mtPth, edit=True, worldUpType="object", worldUpObject=loc) #parent the setup under the parent nurb curve pm.parent(path_crv, control_crv) pm.parent(loc, control_crv) pm.select(clear=True) gp = pm.group(name=tread_name + "GP") pm.select(clear=True) jnt_gp = pm.group(jnt_lst, name=tread_name + "JNTGP") pm.xform(gp, translation=loc_pos) pm.parent(control_crv, gp) pm.parent(jnt_gp, gp) # call to create expression function createTreadExpression(mtnPth=path_anim_list, runAttr=str(control_crv[0]) + ".run", speedAttr=str(control_crv[0]) + ".speed", exp_nm=tread_name) return None
def splitByMaterials( mesh, outputGrp ) : materials = mesh.listConnections(type=pm.nodetypes.ShadingEngine) print mesh.name() materials = list(set(materials)) for material in materials : # print '----- ' + material.name() __st(1) faces = material.members( flatten=True ) outmesh = None for facelist in faces : if( type( facelist ) is pm.Mesh ) : facelist = facelist.f[:] shape = facelist.node() if( shape == mesh ) : __st(6) duplicate = facelist.node().getTransform().duplicate()[0] if( duplicate is None ) : pm.warning( "%s could not be duplicated" % mesh.name() ) continue duplicate.setParent(outputGrp) dupfacelist = facelist.indices() dupallfaces = duplicate.f[:].indices() deletefacelist = duplicate.f[facelist.indices()] __et(6, 'initTime') __st(2) # deletefacelist = [ duplicate.f[face] for face in dupallfaces if face not in dupfacelist ] pm.select(deletefacelist) pm.runtime.InvertSelection() # deletefacelist = pm.ls(sl=True, fl=True) __et(2, 'obtainFaceListTime') __st(3) pm.delete() __et(3, 'deleteFaceTime') # pm.filterExpand(dupfacelist, sm=34) __st(4) # pm.mel.select( duplicate.f[:] ) # pm.hyperShade(assign=material) pm.sets( material, fe=duplicate.f[:] ) __et(4, 'assignMaterialTime') outmesh = duplicate __st(5) try: outmeshGrp = pm.PyNode( '%s|%s' % ( OUTPUT_GRP_NAME, material.name() + '_split' ) ) except (pm.MayaNodeError) : outmeshGrp = pm.group(name=material.name() + '_split', parent=pm.PyNode(OUTPUT_GRP_NAME), empty=True) outmesh.setParent(outmeshGrp) __et(5, 'tidyUpTime') __et( 1, material.name() + ' done' )