def transferUV(self): for key ,vlaue in self.dit.items(): pm.polyTransfer(key, uv=1 ,ao = vlaue ) pm.select(key , r =1) pm.cycleCheck(e=0) mel.eval('doBakeNonDefHistory( 1, {"prePost" });') OpenMaya.MGlobal_clearSelectionList()
def export(self): # where to save file? if not self.set_export_path(): return # verify if anything is selected selection = pm.ls(sl=True) if not selection: pm.confirmDialog(title='No objects selected', message='Please select one or more object(s) to export.', button=['OK'], defaultButton='OK') self.original_selection = None return self.original_selection = pm.ls(sl=True) time_range = self.get_time_range() if time_range is None: pm.error('Could not determine time range.') return try: cycle_check = pm.cycleCheck(q=True, evaluation=True) pm.cycleCheck(evaluation=False) # if "bake animation" is checked if self.bake_animation_checkbox.isChecked(): self.bake(time_range) else: self.export_fbx(time_range) pm.cycleCheck(evaluation=cycle_check) except Exception as e: sys.stdout.write(str(e) + '\n')
def recalculatePosition(currentPositions, newNumberPositions, degree=2): """ For a given set of position create a curve and return fewer/more a set of position that follow on that arc. @param currentPositions: Current list of cv position @param newNumberPositions: How many CV points do me require @param degree: What degree should be on the created curve @return: list of new cv positions """ if len(currentPositions) < 4: crv = createCurve(currentPositions, 1) else: crv = createCurve(currentPositions, degree) newPositions = [] pm.cycleCheck(e=False) for posOnCurve in libMath.spread(0, 1, newNumberPositions - 1): pm.select(clear=True) tempDag = pm.joint() mp = pm.PyNode(pm.pathAnimation(tempDag, fractionMode=True, follow=False, curve=crv )) pm.delete(mp.listConnections(type="animCurve")) mp.uValue.set(posOnCurve) newPositions.append(libUtilities.get_world_space_pos(tempDag)) pm.delete([mp, tempDag]) pm.delete(crv) return newPositions
def space_switcher(self, index, start_frame, end_frame, key_switch): # Temporary disable cycle checks during swapping cycle_check = pm.cycleCheck(q=True, e=True) pm.cycleCheck(e=False) autokey_state = pm.autoKeyframe(q=True, state=True) pm.autoKeyframe(state=False) try: # Disable viewport refresh to speed up execution pm.refresh(su=True) pm.currentTime(start_frame) current_space = self.get_current_space() if current_space != None: control = self.network['controls'].get_first_connection() matrix_list = maya_utils.baking.get_bake_values([control], start_frame, end_frame) self.swap_space(index, current_space, start_frame, key_switch) self.swap_space(current_space, index, end_frame, key_switch, end_cap = True) maya_utils.baking.space_switch_bake([control], start_frame, end_frame, matrix_list) pm.currentTime(start_frame) except Exception, e: exception_info = sys.exc_info() v1_core.exceptions.except_hook(exception_info[0], exception_info[1], exception_info[2])
def recalculatePosition(currentPositions, newNumberPositions, degree=2): """ For a given set of position create a curve and return fewer/more a set of position that follow on that arc. @param currentPositions: Current list of cv position @param newNumberPositions: How many CV points do me require @param degree: What degree should be on the created curve @return: list of new cv positions """ if len(currentPositions) < 4: crv = createCurve(currentPositions, 1) else: crv = createCurve(currentPositions, degree) newPositions = [] pm.cycleCheck(e=False) for posOnCurve in libMath.spread(0, 1, newNumberPositions - 1): pm.select(clear=True) tempDag = pm.joint() mp = pm.PyNode( pm.pathAnimation(tempDag, fractionMode=True, follow=False, curve=crv)) pm.delete(mp.listConnections(type="animCurve")) mp.uValue.set(posOnCurve) newPositions.append(libUtilities.get_world_space_pos(tempDag)) pm.delete([mp, tempDag]) pm.delete(crv) return newPositions
def set_current_frame(): ''' Set the current frame to itself to force a scene update ''' # Weird issue, turning off cycle check here prevents warnings of a meaningless cycle cycle_check = pm.cycleCheck(q=True, e=True) pm.cycleCheck(e=False) pm.currentTime(pm.currentTime()) pm.cycleCheck(e=cycle_check)
def bakeAnimation(self, switch_attr_name, val_src_nodes, key_src_nodes, key_dst_nodes, startFrame, endFrame, onlyKeyframes=True): # type: (str, List[pm.nodetypes.Transform], # List[pm.nodetypes.Transform], # List[pm.nodetypes.Transform], int, int, bool) -> None # Temporaly turn off cycle check to avoid misleading cycle message # on Maya 2016. With Maya 2016.5 and 2017 the cycle warning doesn't # show up if versions.current() < 201650: pm.cycleCheck(e=False) pm.displayWarning("Maya version older than: 2016.5: " "CycleCheck temporal turn OFF") channels = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"] worldMatrixList = self.getWorldMatrices(startFrame, endFrame, val_src_nodes) keyframeList = sorted( set(pm.keyframe(key_src_nodes, at=["t", "r", "s"], q=True))) # delete animation in the space switch channel and destination ctrls pm.cutKey(key_dst_nodes, at=channels, time=(startFrame, endFrame)) pm.cutKey(switch_attr_name, time=(startFrame, endFrame)) for i, x in enumerate(range(startFrame, endFrame + 1)): if onlyKeyframes and x not in keyframeList: continue pm.currentTime(x) # set the new space in the channel self.changeAttrToBoundValue() # bake the stored transforms to the cotrols for j, n in enumerate(key_dst_nodes): n.setMatrix(worldMatrixList[i][j], worldSpace=True) pm.setKeyframe(key_dst_nodes, at=channels) if versions.current() < 201650: pm.cycleCheck(e=True) pm.displayWarning("CycleCheck turned back ON")
def bake_objects(obj_list, translate, rotate, scale, use_settings=True, custom_attrs=None, bake_range=None, **kwargs): ''' Wrapper around pm.bakeResults and sets up the scene to ensure the objects are bake-able and using the user's custom bake settings. Note: At the end we set a key at -10000 and value 0 for rotation as a reference point for a eurler filter operation. Args: obj_list (list<PyNode>): List of objects to perform the bake operation on translate (boolean): Whether or not to bake translate channels rotate (boolean): Whether or not to bake rotate channels scale (boolean): Whether or not to bake scale channels use_settings (boolean): Whether or not to use user defined settings for bake settings custom_attrs (list<str>): A list of strings defining all custom attributes that should also be baked kwargs (kwargs): keyword arguments for pm.bakeResults ''' # Temporary disable cycle checks during baking cycle_check = pm.cycleCheck(q=True, e=True) pm.cycleCheck(e=False) try: # Disable viewport refresh to speed up execution pm.refresh(su=True) # Anim Layers with a single keyframe don't bake reliably, add a second key 1 frame after the first on any single keyframe layers fix_solo_keyframe_layers() # Objects on hidden layers don't reliably bake correctly, toggle them all true, then reset values after baking. layer_dict = {} default_display_layer = pm.PyNode('defaultLayer') if pm.objExists( 'defaultLayer') else None for layer in pm.ls(type='displayLayer'): if layer != default_display_layer: layer_dict[layer] = layer.visibility.get() layer.visibility.set(True) attr_list = [] if translate: attr_list += ['.tx', '.ty', '.tz'] if rotate: attr_list += ['.rx', '.ry', '.rz'] if scale: attr_list += ['.sx', '.sy', '.sz'] if custom_attrs: attr_list += custom_attrs process = System.Diagnostics.Process.GetCurrentProcess() # In maya standalone don't use user settings file if "mayapy" in process.ToString(): use_settings = False bake_settings = v1_core.global_settings.GlobalSettings().get_category( v1_core.global_settings.BakeSettings, default=not use_settings) sample = bake_settings.sample_by # Set/get time range time_range = (pm.playbackOptions(q=True, ast=True), pm.playbackOptions(q=True, aet=True)) if use_settings: time_range = get_bake_time_range(obj_list, bake_settings) elif bake_range: time_range = bake_range time_range = [int(time_range[0]), int(time_range[1])] if type(time_range[0]) != int or type(time_range[1]) != int: raise BakeRangeError v1_core.v1_logging.get_logger().info( "Baking {0} \n Use Settings: {1}, over range {2}\nBake Attrs: {3}\nBakeSettings: {4}" .format(obj_list, use_settings, time_range, attr_list, kwargs)) bake_start = time.clock() # Baking is stupidly slower if you pass in a value to smart bake(sr), even if it's False, so we split out the command if bake_settings.smart_bake: pm.bakeResults(obj_list, at=attr_list, t=time_range, sb=sample, sr=True, preserveOutsideKeys=True, **kwargs) else: pm.bakeResults(obj_list, at=attr_list, t=time_range, sb=sample, preserveOutsideKeys=True, **kwargs) v1_core.v1_logging.get_logger().info( "Bake Command Completed in {0} Seconds".format(time.clock() - bake_start)) pm.setKeyframe(obj_list, t=-1010, at='rotate', v=0) pm.filterCurve(obj_list) pm.cutKey(obj_list, t=-1010) for layer, value in layer_dict.iteritems(): layer.visibility.set(value) except Exception, e: exception_info = sys.exc_info() v1_core.exceptions.except_hook(exception_info[0], exception_info[1], exception_info[2])
"Bake Command Completed in {0} Seconds".format(time.clock() - bake_start)) pm.setKeyframe(obj_list, t=-1010, at='rotate', v=0) pm.filterCurve(obj_list) pm.cutKey(obj_list, t=-1010) for layer, value in layer_dict.iteritems(): layer.visibility.set(value) except Exception, e: exception_info = sys.exc_info() v1_core.exceptions.except_hook(exception_info[0], exception_info[1], exception_info[2]) finally: pm.refresh(su=False) pm.cycleCheck(e=cycle_check) @undoable def space_switch_bake(obj_list, start_time, end_time, matrix_dict): ''' space_switch_bake(obj_list, start_time, end_time, matrix_dict) Key translate and rotate values of an object across a time range across states. Store all world space matrix values in a list, run the method that will change the object state, then re-apply all world space values back across the time range. Args: obj (PyNode): Maya scene object to bake start_time (int): Start of the frame range for baking end_time (int): End of the frame range for baking matrix_dict (dict<list<matrix>>): List of world space matrix values for the provided object from start time to end time
def match_to_skeleton(self, time_range, set_key): ''' Handle single frame matching of rig component to it's skeleton ''' cycle_check = pm.cycleCheck(q=True, e=True) pm.cycleCheck(e=False) if not time_range: time_range = [pm.currentTime, pm.currentTime + 1] skeleton_jnt_list = self.network.get('skeleton').get_connections() skeleton_jnt_list = rigging.skeleton.sort_chain_by_hierarchy( skeleton_jnt_list) ik_control = self.get_control('ik_handle') # if the control is driven by an overdriver, apply the match to the overdriver control addon_control = self.get_addon_control(ik_control) ik_control = addon_control if addon_control else ik_control pv_control = self.get_control('pv') # if the control is driven by an overdriver, apply the match to the overdriver control addon_control = self.get_addon_control(pv_control) pv_control = addon_control if addon_control else pv_control hand_jnt = skeleton_jnt_list[0] loc = pm.spaceLocator() loc.rotateOrder.set(ik_control.rotateOrder.get()) loc.setParent(ik_control.getParent()) loc.translate.set([0, 0, 0]) loc.rotate.set([0, 0, 0]) rigging.rig_base.Component_Base.zero_all_overdrivers( self.network['character']) rigging.rig_base.Component_Base.zero_all_rigging( self.network['character']) rigging.skeleton.zero_character(self.skel_root, ignore_rigged=False) temp_constraint = pm.parentConstraint(hand_jnt, loc, mo=True) maya_utils.baking.bake_objects([loc], True, True, False, False, None, time_range) pm.delete(temp_constraint) if (time_range[1] - time_range[0] == 1) and set_key == False: pm.currentTime(time_range[0]) ik_control.translate.set(loc.translate.get()) ik_control.rotate.set(loc.rotate.get()) else: temp_constraint = pm.parentConstraint(loc, ik_control, mo=False) maya_utils.baking.bake_objects([ik_control], True, True, False, False, None, time_range, preserveOutsideKeys=True) pm.delete(temp_constraint) pm.delete(loc) pv_position = rigging.skeleton.calculate_pole_vector_position( skeleton_jnt_list, pm.currentTime()) pm.xform(pv_control, ws=True, translation=pv_position) pm.cycleCheck(e=cycle_check)
def bakeScene(): sel = pm.ls(sl=True) if sel == [] or sel == None: pm.warning("Please select a camera or camera group!") return False new_nulls = pm.confirmDialog( title='Rebake nulls?', message='Do you want to rebake your scene nulls?', button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='Cancel') # Break operation on user cancel if new_nulls == 'Cancel': return None # Cleanup lists constraints = [] exports = [] # Generate export objects export_camera, src_cam = __createExportCamera() if new_nulls == 'Yes': nulls = __createNulls() elif new_nulls == 'No': nulls = __createNullList() # List of objects to be baked exports = nulls exports.append(export_camera) # Frame range range = (pm.playbackOptions(q=True, min=True), pm.playbackOptions(q=True, max=True)) # Bake it pm.cycleCheck(e=False) pm.bakeResults(exports, t=range) # Clear the constraints from the exported objects __clearConstraints(exports) export_list = "" for obj in exports: export_list += (str(obj) + "\n") # Confirm the export before proceeding do_export = pm.confirmDialog( title='Confirm Export', message='The following objects will be exported:\n' + str(export_list), button=['Looks Good', 'Oops'], defaultButton='Looks Good', cancelButton='Oops', dismissString='Oops') if do_export == 'Looks Good': try: out_file = __createOutputFile(src_cam) pm.select(exports) pm.exportSelected(out_file) pm.warning('File exported to: ' + str(out_file)) except: return False elif do_export == 'Oops': pm.delete(exports) return False pm.delete(exports) pm.select(sel) return True
def motionPath_setup(self): pos = [] self._MODEL.getJoints = [ pm.joint(rad=self._MODEL.radius) for x in range(self._MODEL.interval) ] for _joint in self._MODEL.getJoints: pm.parent(_joint, w=True) adb.makeroot_func(_joint) double_linears_nodes = [] _motionPathNode = pm.pathAnimation(self._MODEL.curve, _joint.getParent(), upAxis='y', fractionMode=True, worldUpType="vector", inverseUp=False, inverseFront=False, follow=True, bank=False, followAxis='x', worldUpVector=(0, 1, 0)) ## Delete double Linear nodes for axis in 'xyz': double_linear = pm.listConnections( _motionPathNode + '.{}Coordinate'.format(axis))[0] double_linears_nodes.append(double_linear) pm.delete(double_linears_nodes) for axis in 'xyz': pm.cycleCheck(e=1) pm.connectAttr('{}.{}Coordinate'.format(_motionPathNode, axis), '{}.t{}'.format(_joint.getParent(), axis), f=1) self._MODEL.motionPaths.append(_motionPathNode) # New interval value for the Function Nintervalls = self._MODEL.interval - 1 for i in range(0, Nintervalls): factor = 1 / float((Nintervalls)) oPos = factor * i pos.append(oPos) pos.append(1) for oPosition, oMotionPath in zip(pos, self._MODEL.motionPaths): pm.PyNode(oMotionPath).uValue.set(oPosition) _dup = pm.duplicate(self._MODEL.getJoints[-1]) # delete animation for path in self._MODEL.motionPaths: pm.cutKey(path) for joint in self._MODEL.getJoints: joint.jointOrient.set(0, 0, 0) joint.translate.set(0, 0, 0) pm.select(None) # Cleaning the scene pm.delete(_dup)
def bakeAnimation(self, switch_attr_name, val_src_nodes, key_src_nodes, key_dst_nodes, startFrame, endFrame, onlyKeyframes=True): # Temporaly turn off cycle check to avoid misleading cycle message # on Maya 2016. With Maya 2016.5 and 2017 the cycle warning doesn't # show up # if versions.current() <= 20180200: pm.cycleCheck(e=False) pm.displayWarning("Maya version older than: 2016.5: " "CycleCheck temporal turn OFF") channels = ["tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz"] if onlyKeyframes: keyframeList = sorted( set(pm.keyframe(key_src_nodes, at=["t", "r", "s"], q=True))) else: keyframeList = [x for x in range(startFrame, endFrame + 1)] worldMatrixList = self.getWorldMatrices(startFrame, endFrame, val_src_nodes, keyframeList) # delete animation in the space switch channel and destination ctrls pm.cutKey(key_dst_nodes, at=channels, time=(startFrame, endFrame)) pm.cutKey(switch_attr_name, time=(startFrame, endFrame)) def keyframe(x, i): pm.currentTime(x) # set the new space in the channel self.changeAttrToBoundValue() # bake the stored transforms to the cotrols for j, n in enumerate(key_dst_nodes): # n.setMatrix(worldMatrixList[i][j], worldSpace=True) _m = [] for row in worldMatrixList[i][j]: for elem in row: _m.append(elem) for _ in range(2): cmds.xform(n.name(), ws=True, matrix=_m) # bake the stored transforms to the cotrols for j, n in enumerate(key_dst_nodes): # n.setMatrix(worldMatrixList[i][j], worldSpace=True) _m = [] for row in worldMatrixList[i][j]: for elem in row: _m.append(elem) for _ in range(2): cmds.xform(n.name(), ws=True, matrix=_m) pm.setKeyframe(key_dst_nodes, at=channels) pm.setKeyframe(switch_attr_name) if onlyKeyframes: for i, x in enumerate(keyframeList): keyframe(x, i) else: for i, x in enumerate(range(startFrame, endFrame + 1)): keyframe(x, i) # if versions.current() <= 20180200: pm.cycleCheck(e=True) pm.displayWarning("CycleCheck turned back ON")