Example #1
0
def msg(msg="Heads Up!"):
    global PM_startTime
    global PM_timeAdder
    PM_offset = 0
    PM_time = cmds.timerX(startTime=PM_startTime)
    PM_startTime = cmds.timerX()
    if PM_time < 1.5:
        PM_offset = 10 + 20 * (PM_timeAdder)
        PM_timeAdder = PM_timeAdder + 1
    else:
        PM_offset = 10
        PM_timeAdder = 0
    if MAYA_version_float >= 2014:
        cmds.inViewMessage(amg="<span style=\"color:#ffffff\">" + msg +
                           "</span>",
                           fade=1,
                           fit=150,
                           fst=800,
                           fot=150,
                           fof=PM_offset,
                           bkc=0x2288ff,
                           pos="topCenter",
                           fontSize=10,
                           a=0,
                           ta=0.68)
    print(msg)
Example #2
0
    def rebuild(self, skinClusterList=[]):
        '''
		Rebuild a list of skinClusters using the data stored in the class member dictionaries.
		@param skinClusterList: List of scene skinClusters to rebuild. If empty, use all saved skinClusters.
		@type skinClusterList: list
		'''
        # Check skinClusterList
        if not skinClusterList: skinClusterList = self.data.keys()

        # Start timer
        print('Rebuilding skinClusters...')
        timer = mc.timerX()

        # Rebuild each skinCluster
        for skinCluster in skinClusterList:

            # Check skinCluster
            if not self.data.has_key(skinCluster):
                raise Exception('No data stored for skinCluster "' +
                                skinCluster + '"!')

            # Rebuild skinCluster
            self.rebuildSkinCluster(skinCluster)

        # Print timed result
        totalTime = mc.timerX(st=timer)
        print('Total rebuild time: ' + str(totalTime))
Example #3
0
	def buildData(self,curve,worldSpace=False):
		'''
		Build NurbsCurveData class.
		@param curve: Curve to build data from
		@type curve: str
		'''
		# ==========
		# - Checks -
		# ==========
		
		# Check Curve
		if not glTools.utils.curve.isCurve(curve):
			raise Exception('Object "'+curve+'" is not a vaild NURBS curve node!')
		
		# World Space
		space = OpenMaya.MSpace.kObject
		if worldSpace: space = OpenMaya.MSpace.kWorld
		
		# ==============
		# - Build Data -
		# ==============
		
		# Start timer
		timer = mc.timerX()
		
		# Get basic curve info
		self._data['name'] = curve

		# Get Curve Function Class
		curveFn = glTools.utils.curve.getCurveFn(curve)
		
		# Get Curve Degree and Form
		self._data['degree'] = curveFn.degreeU()
		self._data['form'] = int(curveFn.formInU())
		
		# Get Curve Knots
		knotArray = OpenMaya.MDoubleArray()
		curveFn.getKnotsInU(knotArray)
		self._data['knots'] = list(knotArray)
		
		# Get Control Vertices
		cvArray = OpenMaya.MPointArray()
		curveFn.getCVs(cvArray,space)
		self._data['cv'] = [(cvArray[i].x,cvArray[i].y,cvArray[i].z) for i in range(cvArray.length())]
		
		# Get Edit Points
		editPt = OPenMaya.MPoint()
		for u in self._data['knots']:
			curveFn.getPointAtParam(u,editPt,space)
			self._data['editPt'].append((editPt.x,editPt.y,editPt.z))
		
		# =================
		# - Return Result -
		# =================
		
		# Print timer result
		buildTime = mc.timerX(st=timer)
		print('NurbsCurveData: Data build time for curve "'+curve+'": '+str(buildTime))
		
		return self._data['name']
Example #4
0
	def rebuildMesh(self):
		'''
		'''
		# Start timer
		timer = mc.timerX()

		# Rebuild Mesh Data
		meshData = OpenMaya.MObject()
		meshUtil = OpenMaya.MScriptUtil()
		numVertices = len(self._data['vertexList'])/3
		numPolygons = len(self._data['polyCounts'])
		polygonCounts = OpenMaya.MIntArray()
		polygonConnects = OpenMaya.MIntArray()
		meshUtil.createIntArrayFromList(self._data['polyCounts'],polygonCounts)
		meshUtil.createIntArrayFromList(self._data['polyConnects'],polygonConnects)
		
		# Rebuild UV Data
		uArray = OpenMaya.MFloatArray()
		vArray = OpenMaya.MFloatArray()
		meshUtil.createFloatArrayFromList(self._data['uArray'],uArray)
		meshUtil.createFloatArrayFromList(self._data['vArray'],vArray)
		uvCounts = OpenMaya.MIntArray()
		uvIds = OpenMaya.MIntArray()
		meshUtil.createIntArrayFromList(self._data['uvCounts'],uvCounts)
		meshUtil.createIntArrayFromList(self._data['uvIds'],uvIds)

		# Rebuild Vertex Array
		vertexArray = OpenMaya.MFloatPointArray(numVertices,OpenMaya.MFloatPoint.origin)
		vertexList = [vertexArray.set(i,self._data['vertexList'][i*3],self._data['vertexList'][i*3+1],self._data['vertexList'][i*3+2],1.0) for i in xrange(numVertices)]

		# Rebuild Mesh
		meshFn = OpenMaya.MFnMesh()
		meshObj = meshFn.create(	numVertices,
									numPolygons,
									vertexArray,
									polygonCounts,
									polygonConnects,
									uArray,
									vArray,
									meshData	)
		
		# Assign UVs
		meshFn.assignUVs(uvCounts,uvIds)

		# Rename Mesh
		mesh = OpenMaya.MFnDependencyNode(meshObj).setName(self._data['name'])
		meshShape = mc.listRelatives(mesh,s=True,ni=True,pa=True)[0]

		# Assign Initial Shading Group
		mc.sets(meshShape,fe='initialShadingGroup')

		# Print timer result
		buildTime = mc.timerX(st=timer)
		print('MeshIntersectData: Geometry rebuild time for mesh "'+mesh+'": '+str(buildTime))

		# =================
		# - Return Result -
		# =================
		
		return mesh
Example #5
0
def pythonScripts():

    if (cmds.menu ('pythonScripts_menu', exists=True)):
	
        print ("Removing old pythonScripts menu...")
	cmds.deleteUI ('pythonScripts_menu')
	
    gMainWindow = maya.mel.eval('$temp1=$gMainWindow')
    gMainProgressBar = maya.mel.eval('$temp=$gMainProgressBar')

    mainDir = findFile('pythonScripts.py')

    timer = cmds.timerX()
    cmds.waitCursor (state=True)
    print ""
    
    cmds.progressBar (gMainProgressBar, edit=True,
    		beginProgress=True,
    		isInterruptable=True,
    		status="Creating pythonScripts...",
    		maxValue=100)

    pMenu = (cmds.menu ('pythonScripts_menu', parent=gMainWindow, tearOff=True, aob=True, label="pythonScripts"))

    gen_pythonScripts(mainDir, pMenu)
    		
    cmds.waitCursor (state=False)

    endTime = cmds.timerX(startTime=timer)

    cmds.progressBar (gMainProgressBar, edit=True,
    		endProgress=True,)
             
    print ("pythonTools has now been updated in: " + str(endTime) + " seconds...!")
Example #6
0
	def getClosestPointList(self,ptList):
		'''
		'''
		# Start timer
		timer = mc.timerX()

		# Display Progress
		glTools.utils.progressBar.init(status=('Building Closest Point Coord Array...'),maxValue=int(len(ptList)*0.1))

		# Rebuild Mesh Data
		meshUtil = OpenMaya.MScriptUtil()
		numVertices = len(self._data['vertexList'])/3
		numPolygons = len(self._data['polyCounts'])
		polygonCounts = OpenMaya.MIntArray()
		polygonConnects = OpenMaya.MIntArray()
		meshUtil.createIntArrayFromList(self._data['polyCounts'],polygonCounts)
		meshUtil.createIntArrayFromList(self._data['polyConnects'],polygonConnects)

		# Rebuild Vertex Array
		vertexArray = OpenMaya.MFloatPointArray(numVertices,OpenMaya.MFloatPoint.origin)
		vertexList = [vertexArray.set(i,self._data['vertexList'][i*3],self._data['vertexList'][i*3+1],self._data['vertexList'][i*3+2],1.0) for i in xrange(numVertices)]

		# Rebuild Mesh
		meshFn = OpenMaya.MFnMesh()
		meshData = OpenMaya.MFnMeshData().create()
		meshObj = meshFn.create(numVertices,numPolygons,vertexArray,polygonCounts,polygonConnects,meshData)

		# Build Mesh Intersector
		meshPt = OpenMaya.MPointOnMesh()
		meshIntersector = OpenMaya.MMeshIntersector()
		meshIntersector.create(meshObj,OpenMaya.MMatrix.identity)

		# Get Closest Point Data
		ptCount = len(ptList)
		pntList = [ (0,0,0) for i in range(ptCount) ]
		for i in range(ptCount):

			# Get Closest Point
			mpt = glTools.utils.base.getMPoint(ptList[i])
			meshIntersector.getClosestPoint(mpt,meshPt,self.maxDist)

			# Get Mesh Point Data
			pt = meshPt.getPoint()
			pntList[i] = (pt[0],pt[1],pt[2])

			# Update Progress Bar (Every 10th Iteration)
			if not i % 10: glTools.utils.progressBar.update(step=1)

		# =================
		# - Return Result -
		# =================
		
		# End Progress
		if showProgress: glTools.utils.progressBar.end()	

		# Print timer result
		buildTime = mc.timerX(st=timer)
		print('MeshIntersectData: Closest Point search time for mesh "'+self._data['name']+'": '+str(buildTime))
		
		return pntList
Example #7
0
    def build_data(self):
        """
        Builds deformer data
        """

        from tpDcc.dccs.maya.data import mesh
        from tpDcc.dccs.maya.core import deformer

        if not self._deformer:
            return

        if not deformer.is_deformer(deformer=self._deformer):
            raise Exception(
                'Object {} is not a valid deformer! Unable to instantiate MayaDeformerData() class object!'
                .format(self._deformer))

        timer = cmds.timerX()

        attr_value_list = copy.deepcopy(self._data['attrValueList'])
        attr_connection_list = copy.deepcopy(self._data['attrConnectionList'])
        self.reset()
        self._data['attrValueList'] = copy.deepcopy(attr_value_list)
        self._data['attrConnectionList'] = copy.deepcopy(attr_connection_list)

        self._data['name'] = self._deformer
        self._data['type'] = cmds.objectType(self._deformer)

        affected_geo = deformer.get_affected_geometry(self._deformer,
                                                      return_shapes=False)
        self._data['affectedGeometry'] = [
            str(i)
            for i in python.get_dict_ordered_keys_from_values(affected_geo)
        ]

        # Build data for each affected geometry
        for geo in self._data['affectedGeometry']:
            geo_shape = cmds.listRelatives(geo, s=True, ni=True, pa=True)[0]
            self._data[geo] = dict()
            self._data[geo]['index'] = affected_geo[geo]
            self._data[geo]['geometryTypej'] = str(cmds.objectType(geo_shape))
            self._data[geo][
                'membership'] = deformer.get_deformer_set_member_indices(
                    deformer=self._deformer, geometry=geo)
            self._data[geo]['weights'] = deformer.get_weights(
                deformer=self._deformer, geometry=geo)

            if self._data[geo]['geometryType'] == 'mesh':
                self._data[geo]['mesh'] = mesh.MeshData(geo)

        # Add custom data
        self.custom_deformer_atributes(self._data['type'])
        self.get_deformer_attr_values()
        self.get_deformer_attr_connections()

        build_time = cmds.timerX(st=timer)
        LOGGER.debug(
            'MayaDeformerData: Data build time for "{}" : "{}"'.format(
                self._deformer, str(build_time)))

        return self._deformer
Example #8
0
    def rebuildMesh(self):
        '''
        '''
        # Start timer
        timer = cmds.timerX()

        # Rebuild Mesh Data
        meshData = om.MObject()
        meshUtil = om.MScriptUtil()
        numVertices = len(self._data['vertexList']) / 3
        numPolygons = len(self._data['polyCounts'])
        polygonCounts = om.MIntArray()
        polygonConnects = om.MIntArray()
        meshUtil.createIntArrayFromList(self._data['polyCounts'],
                                        polygonCounts)
        meshUtil.createIntArrayFromList(self._data['polyConnects'],
                                        polygonConnects)

        # Rebuild UV Data
        uArray = om.MFloatArray()
        vArray = om.MFloatArray()
        meshUtil.createFloatArrayFromList(self._data['uArray'], uArray)
        meshUtil.createFloatArrayFromList(self._data['vArray'], vArray)
        uvCounts = om.MIntArray()
        uvIds = om.MIntArray()
        meshUtil.createIntArrayFromList(self._data['uvCounts'], uvCounts)
        meshUtil.createIntArrayFromList(self._data['uvIds'], uvIds)

        # Rebuild Vertex Array
        vertexArray = om.MFloatPointArray(numVertices, om.MFloatPoint.origin)
        vertexList = [
            vertexArray.set(i, self._data['vertexList'][i * 3],
                            self._data['vertexList'][i * 3 + 1],
                            self._data['vertexList'][i * 3 + 2], 1.0)
            for i in xrange(numVertices)
        ]

        # Rebuild Mesh
        meshFn = om.MFnMesh()
        meshObj = meshFn.create(numVertices, numPolygons, vertexArray,
                                polygonCounts, polygonConnects, uArray, vArray,
                                meshData)

        # Assign UVs
        meshFn.assignUVs(uvCounts, uvIds)

        # Rename Mesh
        mesh = om.MFnDependencyNode(meshObj).setName(self._data['name'] +
                                                     "WSMesh")
        meshShape = cmds.listRelatives(mesh, s=True, ni=True, pa=True)[0]

        # Assign Initial Shading Group
        cmds.sets(meshShape, fe='initialShadingGroup')

        # Print timer result
        buildTime = cmds.timerX(st=timer)
        print("MeshIntersectData: Geometry rebuild time for mesh {0}: {1}".
              format(mesh, str(buildTime)))

        return mesh
    def testViewport(self, json_data, play_mgr, selected):
        # consolidate
        for i in range(5): #one refresh is triggered outside of testViewport after a change.  Wait 5 frames here.  The next frame is the consolidation frame.
            cmds.refresh(force=True)
        start_time = cmds.timerX()
        cmds.refresh(force=True)
        json_data[selected][KEY_CONSOLIDATE][KEY_TIME] = cmds.timerX( startTime=start_time )
        json_data[selected][KEY_CONSOLIDATE][KEY_MEMORY] = self.get_memory()

        # tumble
        num_frames = int(play_mgr.maxTime) - int(play_mgr.minTime)
        json_data[selected][KEY_TUMBLE][KEY_FRAME_COUNT] = num_frames
        start_time = cmds.timerX()
        for i in range(num_frames-1): # subtract one becuase range is going to give num_frames + 1 value because it starts from 0.
            cmds.refresh(force=True);
        json_data[selected][KEY_TUMBLE][KEY_TIME] = cmds.timerX( startTime=start_time )
        json_data[selected][KEY_TUMBLE][KEY_MEMORY] = self.get_memory()

        # playback
        (elapsed, min_time, max_time) = play_mgr.play_all()
        assert max_time >= min_time
        json_data[selected][KEY_PLAYBACK][KEY_START_FRAME] = min_time
        json_data[selected][KEY_PLAYBACK][KEY_END_FRAME] = max_time
        json_data[selected][KEY_PLAYBACK][KEY_TIME] = elapsed
        json_data[selected][KEY_PLAYBACK][KEY_MEMORY] = self.get_memory()
	def rebuild(self,skinClusterList=[]):
		'''
		Rebuild a list of skinClusters using the data stored in the class member dictionaries.
		@param skinClusterList: List of scene skinClusters to rebuild. If empty, use all saved skinClusters.
		@type skinClusterList: list
		'''
		# Check skinClusterList
		if not skinClusterList: skinClusterList = self.data.keys()
		
		# Start timer
		print('Rebuilding skinClusters...')
		timer = mc.timerX()
		
		# Rebuild each skinCluster
		for skinCluster in skinClusterList:
			
			# Check skinCluster
			if not self.data.has_key(skinCluster):
				raise Exception('No data stored for skinCluster "'+skinCluster+'"!')
			
			# Rebuild skinCluster
			self.rebuildSkinCluster(skinCluster)
		
		# Print timed result
		totalTime = mc.timerX(st=timer)
		print('Total rebuild time: '+str(totalTime))
Example #11
0
def uv_borders(lssl=None, dosel=None):
    tim = cm.timerX(st=1)

    lssl = cm.ls(lssl)
    if not lssl:
        lssl = [x for x
                  in cm.ls(tr=1)
                  if cm.listRelatives(x, s=1, type="mesh")]
    
    for sel in lssl:
        # split first
        uvs = cm.ls(sel+".map[*]")
        cm.select(uvs)
        # bord_uvs = cm.polySelectConstraint(
        #     t=0x0010, uv=0, bo=1, m=2, returnSelection=1)
        bord_uvs = cm.polySelectConstraint(
            t=0x0010, uv=0, bo=1, m=2, returnSelection=1)
        # cm.select(bord_uvs)
        # ed = cm.ls(sl=1)[0]
        edgs = cm.filterExpand(cm.polyListComponentConversion(bord_uvs, te=1, internal=1), sm=32)
        uv2edg = []
        for ed in edgs:
            # cm.select(ed)
            uvs = cm.filterExpand(cm.polyListComponentConversion(ed, tuv=1), sm=35)
            if len(uvs) > 2:
                uv2edg.append(ed)
    print ("Finidshed in: ", cm.timerX(st=1) - tim)
    cm.polySelectConstraint(bo=0)
    if dosel:
        cm.select(uv2edg)
    else:
        cm.select(lssl)
    return uv2edg
Example #12
0
def cleanSkinClusters(showProgress=False):
    """
    @param showProgress:
    """
    # Start Timer
    timer = cmds.timerX()

    # Clean SkinClusters
    skinClusterList = cmds.ls(type='skinCluster')

    if showProgress and interactive:
        cmds.progressBar(gMainProgressBar, e=True, bp=True, ii=True, status=('Cleaning SkinClusters...'),
                       maxValue=len(skinClusterList))

    for skinCluster in skinClusterList:
        try:
            glTools.utils.skinCluster.clean(skinCluster, tolerance=0.001)
        except:
            print(
            '# Clean Rig: XXXXXXXXX ======== Unable to clean skinCluster "' + skinCluster + '"! ======== XXXXXXXXX')

        # Update Progress Bar
        if showProgress and interactive:
            if cmds.progressBar(gMainProgressBar, q=True, isCancelled=True):
                cmds.progressBar(gMainProgressBar, e=True, endProgress=True)
                raise UserInterupted('Operation cancelled by user!')
            cmds.progressBar(gMainProgressBar, e=True, step=1)

    if showProgress and interactive:
        cmds.progressBar(gMainProgressBar, e=True, endProgress=True)

    # Print Timed Result
    print('# Clean Rig: Clean SkinClusters - ' + str(cmds.timerX(st=timer)))
Example #13
0
def deleteUnusedNodes():
    """
    Delete unused nodes
    """
    # Start Timer
    timer = cmds.timerX()

    # BindPose
    print('Deleting bind pose ("dagPose") nodes')
    dagPoseNodes = cmds.ls(type='dagPose')
    if dagPoseNodes: cmds.delete(dagPoseNodes)

    # Unknown
    print('Deleting unknown nodes')
    glTools.utils.cleanup.deleteUnknownNodes()

    # Sets
    # print('Deleting empty sets')
    # glTools.utils.cleanup.deleteEmptySets()

    # Display Layers
    print('Deleting display layers')
    glTools.utils.cleanup.deleteDisplayLayers()

    # Render Layers
    print('Deleting render layers')
    glTools.utils.cleanup.deleteRenderLayers()

    # Turtle
    print('Removing Turtle plugin')
    glTools.utils.cleanup.removeTurtle()

    # Print Timed Result
    print('# Clean Rig: Delete Unused Nodes - ' + str(cmds.timerX(st=timer)))
Example #14
0
def cleanDeformers(eightThreshold=0.001,showProgress=False):
	'''
	Cleaning all deformers
	Prune small weights and membership
	'''
	print('# Clean Rig: Cleaning Deformers (prune weights and membership)')
	
	# Start Timer
	timer = mc.timerX()
	
	deformerList = glTools.utils.deformer.getDeformerList(nodeType='weightGeometryFilter')
	
	if showProgress and interactive:
		mc.progressBar( gMainProgressBar,e=True,bp=True,ii=True,status=('Cleaning Deformers...'),maxValue=len(deformerList) )
	
	# For Each Deformer
	for deformer in deformerList:
		
		# Clean Deformers
		try: glTools.utils.deformer.clean(deformer,threshold=weightThreshold)
		except: print('# Clean Rig: XXXXXXXXX ======== Unable to clean deformer "'+deformer+'"! ======== XXXXXXXXX')
		
		# Update Progress Bar
		if showProgress and interactive:
			if mc.progressBar(gMainProgressBar,q=True,isCancelled=True):
				mc.progressBar(gMainProgressBar,e=True,endProgress=True)
				raise UserInterupted('Operation cancelled by user!')
			mc.progressBar(gMainProgressBar,e=True,step=1)
	
	if showProgress and interactive:	
		mc.progressBar(gMainProgressBar,e=True,endProgress=True)
	
	# Print Timed Result
	print('# Clean Rig: Clean Deformers - '+str(mc.timerX(st=timer)))
Example #15
0
def cleanSkinClusters(showProgress=False):
	'''
	'''
	# Start Timer
	timer = mc.timerX()
	
	# Clean SkinClusters
	skinClusterList = mc.ls(type='skinCluster')
	
	if showProgress and interactive:
		mc.progressBar( gMainProgressBar,e=True,bp=True,ii=True,status=('Cleaning SkinClusters...'),maxValue=len(skinClusterList) )
	
	for skinCluster in skinClusterList:
		try: glTools.utils.skinCluster.clean(skinCluster,tolerance=0.001)
		except: print('# Clean Rig: XXXXXXXXX ======== Unable to clean skinCluster "'+skinCluster+'"! ======== XXXXXXXXX')
		
		# Update Progress Bar
		if showProgress and interactive:
			if mc.progressBar(gMainProgressBar,q=True,isCancelled=True):
				mc.progressBar(gMainProgressBar,e=True,endProgress=True)
				raise UserInterupted('Operation cancelled by user!')
			mc.progressBar(gMainProgressBar,e=True,step=1)
	
	if showProgress and interactive:	
		mc.progressBar(gMainProgressBar,e=True,endProgress=True)
	
	# Print Timed Result
	print('# Clean Rig: Clean SkinClusters - '+str(mc.timerX(st=timer)))
Example #16
0
def deleteUnusedNodes():
    """
    Delete unused nodes
    """
    # Start Timer
    timer = cmds.timerX()

    # BindPose
    print('Deleting bind pose ("dagPose") nodes')
    dagPoseNodes = cmds.ls(type='dagPose')
    if dagPoseNodes: cmds.delete(dagPoseNodes)

    # Unknown
    print('Deleting unknown nodes')
    glTools.utils.cleanup.deleteUnknownNodes()

    # Sets
    # print('Deleting empty sets')
    # glTools.utils.cleanup.deleteEmptySets()

    # Display Layers
    print('Deleting display layers')
    glTools.utils.cleanup.deleteDisplayLayers()

    # Render Layers
    print('Deleting render layers')
    glTools.utils.cleanup.deleteRenderLayers()

    # Turtle
    print('Removing Turtle plugin')
    glTools.utils.cleanup.removeTurtle()

    # Print Timed Result
    print('# Clean Rig: Delete Unused Nodes - ' + str(cmds.timerX(st=timer)))
def Cas_MCW_convertRidgidToSoftButton_cmd():
	sel = cmds.ls(sl=True , tr= 1)
	if (sel == None) or (sel==[]):
		Cas_IO.Cas_printWarning ("Please select at lease one objects or group to convert...")
		return
	
	org = []
	rel = cmds.listRelatives(sel[:],ad = 1,pa =1 , typ="transform")
	if rel != None:
		org = rel
	org.extend(sel[:])
	source = org[:] # make a copy
	
	for node in org :
		shape = cmds.listRelatives(node , s=1 , type = "mesh")
		if shape == None:
			source.remove(node);
	
	#print source
	
	result = Cas_convertRigidToSmooth.Cas_convertRigidToSmooth_cmd(source)
	if result[1] == 0:
		Cas_IO.Cas_printInfo("%s rigid skin converted to smooth skin" %result[0])
	else:
		Cas_IO.Cas_printWarning("%s rigid skin converted to smooth skin with %s warnings. please check your script editor" %(result[0],result[1]))
	
	autoDelete = cmds.checkBox(Cas_MCW_autoDeleteJointClusterCheckCT,q=True,v=True)
	if autoDelete == True:
		time2 = cmds.timerX()
		confirm = cmds.confirmDialog( title="Delete rigid joint clusters" , message="It will disconnect the other objects bind to the deleted clusters as well"+"\n"\
																				+"                                             Are you sure?", button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
		timeTook2 = cmds.timerX(st=time2)
		if confirm == "Yes":
			Cas_convertRigidToSmooth.Cas_CRTS_deleteJointCluster(source)
Example #18
0
	def getClosestPointList(self,ptList):
		'''
		'''
		# Start timer
		timer = mc.timerX()

		# Display Progress
		glTools.utils.progressBar.init(status=('Building Closest Point Coord Array...'),maxValue=int(len(ptList)*0.1))

		# Rebuild Mesh Data
		meshUtil = OpenMaya.MScriptUtil()
		numVertices = len(self._data['vertexList'])/3
		numPolygons = len(self._data['polyCounts'])
		polygonCounts = OpenMaya.MIntArray()
		polygonConnects = OpenMaya.MIntArray()
		meshUtil.createIntArrayFromList(self._data['polyCounts'],polygonCounts)
		meshUtil.createIntArrayFromList(self._data['polyConnects'],polygonConnects)

		# Rebuild Vertex Array
		vertexArray = OpenMaya.MFloatPointArray(numVertices,OpenMaya.MFloatPoint.origin)
		vertexList = [vertexArray.set(i,self._data['vertexList'][i*3],self._data['vertexList'][i*3+1],self._data['vertexList'][i*3+2],1.0) for i in xrange(numVertices)]

		# Rebuild Mesh
		meshFn = OpenMaya.MFnMesh()
		meshData = OpenMaya.MFnMeshData().create()
		meshObj = meshFn.create(numVertices,numPolygons,vertexArray,polygonCounts,polygonConnects,meshData)

		# Build Mesh Intersector
		meshPt = OpenMaya.MPointOnMesh()
		meshIntersector = OpenMaya.MMeshIntersector()
		meshIntersector.create(meshObj,OpenMaya.MMatrix.identity)

		# Get Closest Point Data
		ptCount = len(ptList)
		pntList = [ (0,0,0) for i in range(ptCount) ]
		for i in range(ptCount):

			# Get Closest Point
			mpt = glTools.utils.base.getMPoint(ptList[i])
			meshIntersector.getClosestPoint(mpt,meshPt,self.maxDist)

			# Get Mesh Point Data
			pt = meshPt.getPoint()
			pntList[i] = (pt[0],pt[1],pt[2])

			# Update Progress Bar (Every 10th Iteration)
			if not i % 10: glTools.utils.progressBar.update(step=1)

		# =================
		# - Return Result -
		# =================

		# End Progress
		if showProgress: glTools.utils.progressBar.end()

		# Print timer result
		buildTime = mc.timerX(st=timer)
		print('MeshIntersectData: Closest Point search time for mesh "'+self._data['name']+'": '+str(buildTime))

		return pntList
Example #19
0
	def buildData(self,surface,worldSpace=False):
		'''
		Build NurbsSurfaceData class.
		@param surface: Surface to build data from
		@type surface: str
		'''
		# ==========
		# - Checks -
		# ==========
		
		# Check Surface
		if not glTools.utils.surface.isSurface(surface):
			raise Exception('Object "'+surface+'" is not a vaild NURBS surface node!')
		
		# World Space
		space = OpenMaya.MSpace.kObject
		if worldSpace: space = OpenMaya.MSpace.kWorld
		
		# ==============
		# - Build Data -
		# ==============
		
		# Start timer
		timer = mc.timerX()
		
		# Get basic surface info
		self._data['name'] = surface

		# Get Surface Function Class
		surfaceFn = glTools.utils.surface.getSurfaceFn(surface)
		
		# Get Surface Degree and Form
		self._data['degreeU'] = surfaceFn.degreeU()
		self._data['degreeV'] = surfaceFn.degreeV()
		self._data['formU'] = int(surfaceFn.formInU())
		self._data['formV'] = int(surfaceFn.formInV())
		
		# Get Surface Knots
		knotsUarray = OpenMaya.MDoubleArray()
		knotsVarray = OpenMaya.MDoubleArray()
		surfaceFn.getKnotsInU(knotsUarray)
		surfaceFn.getKnotsInV(knotsVarray)
		self._data['knotsU'] = list(knotsUarray)
		self._data['knotsV'] = list(knotsVarray)

		# Get Control Vertices
		cvArray = OpenMaya.MPointArray()
		surfaceFn.getCVs(cvArray,space)
		self._data['cv'] = [(cvArray[i].x,cvArray[i].y,cvArray[i].z) for i in range(cvArray.length())]
		
		# =================
		# - Return Result -
		# =================
		
		# Print timer result
		buildTime = mc.timerX(st=timer)
		print('NurbsSurfaceData: Data build time for surface "'+surface+'": '+str(buildTime))
		
		return self._data['name']
Example #20
0
    def rebuild(self):
        '''
		'''
        # Start timer
        timer = mc.timerX()

        # Rebuild Mesh Data
        meshUtil = OpenMaya.MScriptUtil()
        numVertices = len(self._data['vertexList']) / 3
        numPolygons = len(self._data['polyCounts'])
        polygonCounts = OpenMaya.MIntArray()
        polygonConnects = OpenMaya.MIntArray()
        meshUtil.createIntArrayFromList(self._data['polyCounts'],
                                        polygonCounts)
        meshUtil.createIntArrayFromList(self._data['polyConnects'],
                                        polygonConnects)

        # Rebuild UV Data
        uvCounts = OpenMaya.MIntArray()
        uvIds = OpenMaya.MIntArray()
        meshUtil.createIntArrayFromList(self._data['uvCounts'], uvCounts)
        meshUtil.createIntArrayFromList(self._data['uvIds'], uvIds)
        uArray = OpenMaya.MFloatArray()
        vArray = OpenMaya.MFloatArray()
        meshUtil.createFloatArrayFromList(self._data['uArray'], uArray)
        meshUtil.createFloatArrayFromList(self._data['vArray'], vArray)

        # Rebuild Vertex Array
        vertexArray = OpenMaya.MFloatPointArray(numVertices,
                                                OpenMaya.MFloatPoint.origin)
        vertexList = [
            vertexArray.set(i, self._data['vertexList'][i * 3],
                            self._data['vertexList'][i * 3 + 1],
                            self._data['vertexList'][i * 3 + 2], 1.0)
            for i in xrange(numVertices)
        ]

        # Rebuild Mesh
        meshFn = OpenMaya.MFnMesh()
        meshData = OpenMaya.MFnMeshData().create()
        meshObj = meshFn.create(numVertices, numPolygons, vertexArray,
                                polygonCounts, polygonConnects, uArray, vArray,
                                meshData)

        # Assign UVs
        meshFn.assignUVs(uvCounts, uvIds)

        meshObjHandle = OpenMaya.MObjectHandle(meshObj)

        # Print Timed Result
        buildTime = mc.timerX(st=timer)
        print('MeshIntersectData: Data rebuild time for mesh "' +
              self._data['name'] + '": ' + str(buildTime))

        # =================
        # - Return Result -
        # =================

        return meshObjHandle
    def _LoadAssemblies(self):
        loadStartTime = cmds.timerX()

        UsdMaya.LoadReferenceAssemblies()

        loadElapsedTime = cmds.timerX(startTime=loadStartTime)

        Tf.Status("Load Elapsed Time: %f" % loadElapsedTime)
Example #22
0
    def rebuild(self, overrides={}, setMembership=True):
        '''
        Rebuild the deformer from the stored deformerData
        @param overrides: Dictionary of data overrides to apply 
        @type overrides: dict
        '''
        # Apply Overrides
        self._data.update(overrides)

        # ==========
        # - Checks -
        # ==========

        # Check target geometry
        for geo in self._data['affectedGeometry']:
            if not cmds.objExists(geo):
                raise Exception('Deformer (' + self._data['name'] +
                                ') affected geometry "' + geo +
                                '" does not exist!')

        # ====================
        # - Rebuild Deformer -
        # ====================

        # Start timer
        timer = cmds.timerX()

        setMembershipGo = False
        deformer = self._data['name']
        if not cmds.objExists(self._data['name']):
            deformer = cmds.deformer(self.getMemberList(),
                                     typ=self._data['type'],
                                     n=deformer)[0]
        else:
            setMembershipGo = setMembership
        if setMembershipGo:
            self.setDeformerMembership()

        # Set deformer weights
        self.loadWeights()

        # ================================
        # - Set Deformer Attribute Values -
        # ================================

        self.setDeformerAttrValues()
        self.setDeformerAttrConnections()

        # =================
        # - Return Result -
        # =================

        # Print Timed Result
        totalTime = cmds.timerX(st=timer)
        print(self.__class__.__name__ + ': Rebuild time for deformer "' +
              deformer + '": ' + str(totalTime))

        return deformer
Example #23
0
    def doIt(self, args):

        modeArg = 0
        fileName = ''
        orderArg = 0
        exclusiveArg = 0

        # parse the arguments.
        argData = OpenMaya.MArgDatabase(self.syntax(), args)

        if argData.isFlagSet(helpFlag):
            self.setResult(helpText)
            return ()

        # read flag arguments
        if argData.isFlagSet(modeFlag):
            modeArg = argData.flagArgumentDouble(modeFlag, 0)
        if argData.isFlagSet(orderFlag):
            orderArg = argData.flagArgumentDouble(orderFlag, 0)
        if argData.isFlagSet(exclusiveFlag):
            exclusiveArg = argData.flagArgumentDouble(exclusiveFlag, 0)
        if argData.isFlagSet(fileFlag):
            fileName = argData.flagArgumentString(fileFlag, 0)
        else:
            OpenMaya.MGlobal.displayError(kPluginCmdName +
                                          ' needs file name flag.')
            return ()

        if fileName == '':
            OpenMaya.MGlobal.displayError(kPluginCmdName +
                                          ' file name is not specified.')
            return ()

        if modeArg < 0 or modeArg > 1:
            OpenMaya.MGlobal.displayError(
                kPluginCmdName +
                ' mode needs to be set to either 0 for \'write\' or 1 for \'read\'.'
            )
            return ()

        start = cmds.timerX()
        msgString = ''

        result = 0
        if modeArg == 0:
            result = self.writeWeights(fileName, exclusiveArg)
            msgString = 'exported to '
        else:
            result = self.readWeights(fileName, orderArg)
            msgString = 'imported from '

        doneTime = cmds.timerX(startTime=start)
        if result == 1:
            OpenMaya.MGlobal.displayInfo(
                'transferSkinCluster command took %.02f seconds' % doneTime)
            OpenMaya.MGlobal.displayInfo('Weights ' + msgString + '\'' +
                                         fileName + '\'')
Example #24
0
    def rebuildSurface(self):
        """
        """
        # Start timer
        timer = cmds.timerX()

        # ========================
        # - Rebuild Surface Data -
        # ========================

        # Rebuild Control Vertices
        nucmdsVs = len(self._data["cv"])
        cvArray = OpenMaya.MPointArray(nucmdsVs, OpenMaya.MPoint.origin)
        for i in range(nucmdsVs):
            cvArray.set(OpenMaya.MPoint(self._data["cv"][i][0], self._data["cv"][i][1], self._data["cv"][i][2], 1.0), i)

        # Rebuild Surface Knot Arrays
        numKnotsU = len(self._data["knotsU"])
        numKnotsV = len(self._data["knotsV"])
        knotsU = OpenMaya.MDoubleArray(numKnotsU, 0)
        knotsV = OpenMaya.MDoubleArray(numKnotsV, 0)
        for i in range(numKnotsU):
            knotsU.set(self._data["knotsU"][i], i)
        for i in range(numKnotsV):
            knotsV.set(self._data["knotsV"][i], i)

        # Rebuild Surface
        surfaceFn = OpenMaya.MFnMesh()
        surfaceData = OpenMaya.MObject()
        surfaceObj = surfaceFn.create(
            cvArray,
            knotsU,
            knotsV,
            self._data["degreeU"],
            self._data["degreeV"],
            self._data["formU"],
            self._data["formV"],
            self._data["rational"],
            surfaceData,
        )

        # Rename Surface
        surface = OpenMaya.MFnDependencyNode(surfaceObj).setName(self._data["name"])
        surfaceShape = cmds.listRelatives(surface, s=True, ni=True, pa=True)[0]

        # Assign Initial Shading Group
        cmds.sets(surfaceShape, fe="initialShadingGroup")

        # =================
        # - Return Result -
        # =================

        # Print timer result
        buildTime = cmds.timerX(st=timer)
        print('NurbsSurfaceData: Geometry rebuild time for surface "' + surface + '": ' + str(buildTime))

        return surface
Example #25
0
    def rebuild(self, nodeList=None):
        """
        Rebuild constraint(s) from data
        @param nodeList: List of constraint nodes to rebuild. If None, rebuild all stored data.
        @type nodeList: list
        """
        # ==========
        # - Checks -
        # ==========

        self.verify()

        # ===========================
        # - Rebuild Constraint Data -
        # ===========================

        # Start timer
        timer = cmds.timerX()

        # Get Node List
        if not nodeList:
            nodeList = self._data.keys()

        # =================================
        # - Rebuild Constraints from Data -
        # =================================

        print(self.name() + ': Rebuilding Constraints...')

        constraintList = []
        for constraint in nodeList:

            # Check Constraint Key
            if not self._data.has_key(constraint):
                print('No constraint data for "' + constraint +
                      '"!! Skipping...')
                continue
            if not self._data[constraint]['type'] == 'aicmdsonstraint':
                raise Exception('Invalid constraint data type! (' +
                                self._data[constraint]['type'] + ')')

            # Rebuild Constraint
            print('REBUILDING - "' + constraint + '"...')
            constraintNode = self.rebuildConstraint(constraint)
            constraintList.append(constraintNode)

        # Print Timer Result
        buildTime = cmds.timerX(st=timer)
        print(self.name() + ': Rebuild time "' + str(nodeList) + '": ' +
              str(buildTime))

        # =================
        # - Return Result -
        # =================

        return constraintList
Example #26
0
    def rebuild(self):
        """
        """
        # Start timer
        timer = cmds.timerX()

        # Rebuild Mesh Data
        meshUtil = OpenMaya.MScriptUtil()
        numVertices = len(self._data['vertexList']) / 3
        numPolygons = len(self._data['polyCounts'])
        polygonCounts = OpenMaya.MIntArray()
        polygonConnects = OpenMaya.MIntArray()
        meshUtil.createIntArrayFromList(self._data['polyCounts'], polygonCounts)
        meshUtil.createIntArrayFromList(self._data['polyConnects'], polygonConnects)

        # Rebuild UV Data
        uvCounts = OpenMaya.MIntArray()
        uvIds = OpenMaya.MIntArray()
        meshUtil.createIntArrayFromList(self._data['uvCounts'], uvCounts)
        meshUtil.createIntArrayFromList(self._data['uvIds'], uvIds)
        uArray = OpenMaya.MFloatArray()
        vArray = OpenMaya.MFloatArray()
        meshUtil.createFloatArrayFromList(self._data['uArray'], uArray)
        meshUtil.createFloatArrayFromList(self._data['vArray'], vArray)

        # Rebuild Vertex Array
        vertexArray = OpenMaya.MFloatPointArray(numVertices, OpenMaya.MFloatPoint.origin)
        vertexList = [vertexArray.set(i, self._data['vertexList'][i * 3], self._data['vertexList'][i * 3 + 1],
                                      self._data['vertexList'][i * 3 + 2], 1.0) for i in xrange(numVertices)]

        # Rebuild Mesh
        meshFn = OpenMaya.MFnMesh()
        meshData = OpenMaya.MFnMeshData().create()
        meshObj = meshFn.create(numVertices,
                                numPolygons,
                                vertexArray,
                                polygonCounts,
                                polygonConnects,
                                uArray,
                                vArray,
                                meshData)

        # Assign UVs
        meshFn.assignUVs(uvCounts, uvIds)

        meshObjHandle = OpenMaya.MObjectHandle(meshObj)

        # Print Timed Result
        buildTime = cmds.timerX(st=timer)
        print('MeshIntersectData: Data rebuild time for mesh "' + self._data['name'] + '": ' + str(buildTime))

        # =================
        # - Return Result -
        # =================

        return meshObjHandle
Example #27
0
    def rebuildSurface(self):
        """
        """
        # Start timer
        timer = cmds.timerX()

        # ========================
        # - Rebuild Surface Data -
        # ========================

        # Rebuild Control Vertices
        nucmdsVs = len(self._data['cv'])
        cvArray = OpenMaya.MPointArray(nucmdsVs, OpenMaya.MPoint.origin)
        for i in range(nucmdsVs):
            cvArray.set(
                OpenMaya.MPoint(self._data['cv'][i][0], self._data['cv'][i][1],
                                self._data['cv'][i][2], 1.0), i)

        # Rebuild Surface Knot Arrays
        numKnotsU = len(self._data['knotsU'])
        numKnotsV = len(self._data['knotsV'])
        knotsU = OpenMaya.MDoubleArray(numKnotsU, 0)
        knotsV = OpenMaya.MDoubleArray(numKnotsV, 0)
        for i in range(numKnotsU):
            knotsU.set(self._data['knotsU'][i], i)
        for i in range(numKnotsV):
            knotsV.set(self._data['knotsV'][i], i)

        # Rebuild Surface
        surfaceFn = OpenMaya.MFnMesh()
        surfaceData = OpenMaya.MObject()
        surfaceObj = surfaceFn.create(cvArray, knotsU, knotsV,
                                      self._data['degreeU'],
                                      self._data['degreeV'],
                                      self._data['formU'], self._data['formV'],
                                      self._data['rational'], surfaceData)

        # Rename Surface
        surface = OpenMaya.MFnDependencyNode(surfaceObj).setName(
            self._data['name'])
        surfaceShape = cmds.listRelatives(surface, s=True, ni=True, pa=True)[0]

        # Assign Initial Shading Group
        cmds.sets(surfaceShape, fe='initialShadingGroup')

        # =================
        # - Return Result -
        # =================

        # Print timer result
        buildTime = cmds.timerX(st=timer)
        print('NurbsSurfaceData: Geometry rebuild time for surface "' +
              surface + '": ' + str(buildTime))

        return surface
Example #28
0
    def rebuild(self, nodeList=None):
        ''' Rebuild constraint(s) from data
        @param nodeList: List of constraint nodes to rebuild. If None, rebuild all stored data.
        @type nodeList: list
        '''
        # ==========
        # - Checks -
        # ==========

        self.verify()

        # ===========================
        # - Rebuild Constraint Data -
        # ===========================

        # Start timer
        timer = cmds.timerX()

        # Get Node List
        if not nodeList: nodeList = self._data.keys()

        # =================================
        # - Rebuild Constraints from Data -
        # =================================

        print(self.name() + ': Rebuilding Constraints...')

        constraintList = []
        for constraint in nodeList:

            # Check Constraint Key
            if not self._data.has_key(constraint):
                print('No constraint data for "{0}"!! Skipping...'.format(
                    constraint))
                continue

            # Rebuild Constraint
            print('REBUILDING - "' + constraint + '"...')
            constraintNode = self.rebuildConstraint(constraint)
            constraintList.append(constraintNode)

        # Reconnect
        self.restoreAttrConnections()
        self.restoreAttrValues()

        # Print Timer Result
        buildTime = cmds.timerX(st=timer)
        print(self.name() + ': Rebuild time "' + str(nodeList) + '": ' +
              str(buildTime))

        # =================
        # - Return Result -
        # =================

        return constraintList
Example #29
0
def copyInputShapeAttrs():
    """
    """
    # Start Timer
    timer = cmds.timerX()

    print('# Clean Rig: Copy Input Shape User Attributes')
    glTools.utils.cleanup.copyInputShapeAttrs(0)

    # Print Timed Result
    print('# Clean Rig: Copy Input Shape User Attributes - ' + str(cmds.timerX(st=timer)))
Example #30
0
def copyInputShapeAttrs():
	'''
	'''
	# Start Timer
	timer = mc.timerX()
	
	print('# Clean Rig: Copy Input Shape User Attributes')
	glTools.utils.cleanup.copyInputShapeAttrs(0)
	
	# Print Timed Result
	print('# Clean Rig: Copy Input Shape User Attributes - '+str(mc.timerX(st=timer)))
Example #31
0
    def buildData(self, mesh):
        ''' Build meshData class.
        :param mesh str: Mesh to initialize data for
        '''
        # Check Mesh
        if not easy.isMesh(mesh):
            raise Exception(
                'Object {0} is not a vaild Mesh node!'.format(mesh))

        # Start timer
        timer = cmds.timerX()

        # Get basic mesh info
        self._data['name'] = mesh

        # Get Mesh Function Class
        meshFn = easy.getMeshFn(mesh)

        # Get Polygon Data
        polygonCounts = om.MIntArray()
        polygonConnects = om.MIntArray()
        meshFn.getVertices(polygonCounts, polygonConnects)
        self._data['polyCounts'] = list(polygonCounts)
        self._data['polyConnects'] = list(polygonConnects)

        # Get Vertex Data
        meshPts = meshFn.getRawPoints()
        numVerts = meshFn.numVertices()
        meshPtUtil = om.MScriptUtil()
        self._data['vertexList'] = [
            meshPtUtil.getFloatArrayItem(meshPts, i)
            for i in xrange(numVerts * 3)
        ]

        # UV Connect Data
        uvCounts = om.MIntArray()
        uvIds = om.MIntArray()
        meshFn.getAssignedUVs(uvCounts, uvIds)
        self._data['uvCounts'] = list(uvCounts)
        self._data['uvIds'] = list(uvIds)

        # Get UVs
        uArray = om.MFloatArray()
        vArray = om.MFloatArray()
        meshFn.getUVs(uArray, vArray)
        self._data['uArray'] = list(uArray)
        self._data['vArray'] = list(vArray)

        # Print timer result
        buildTime = cmds.timerX(st=timer)
        print("MeshData: Data build time for mesh {0}: {1}".format(
            mesh, str(buildTime)))

        return self._data['name']
Example #32
0
    def rebuild(self, nodeList=None):
        """
        Rebuild constraint(s) from data
        @param nodeList: List of constraint nodes to rebuild. If None, rebuild all stored data.
        @type nodeList: list
        """
        # ==========
        # - Checks -
        # ==========

        self.verify()

        # ===========================
        # - Rebuild Constraint Data -
        # ===========================

        # Start timer
        timer = cmds.timerX()

        # Get Node List
        if not nodeList:
            nodeList = self._data.keys()

        # =================================
        # - Rebuild Constraints from Data -
        # =================================

        print(self.name() + ': Rebuilding Constraints...')

        constraintList = []
        for constraint in nodeList:

            # Check Constraint Key
            if not self._data.has_key(constraint):
                print('No constraint data for "' + constraint + '"!! Skipping...')
                continue
            if not self._data[constraint]['type'] == 'aicmdsonstraint':
                raise Exception('Invalid constraint data type! (' + self._data[constraint]['type'] + ')')

            # Rebuild Constraint
            print('REBUILDING - "' + constraint + '"...')
            constraintNode = self.rebuildConstraint(constraint)
            constraintList.append(constraintNode)

        # Print Timer Result
        buildTime = cmds.timerX(st=timer)
        print(self.name() + ': Rebuild time "' + str(nodeList) + '": ' + str(buildTime))

        # =================
        # - Return Result -
        # =================

        return constraintList
Example #33
0
def pub_cleanLocators():
	_sel = mc.ls(sl=True)
#START - get the number of pieces
	_pieceNumber = len(_sel) - 1
	if ( _pieceNumber <= 0):
		#print "Not enough cutting points!"
		mm.eval('error -showLineNumber False "Not enough cutting points!";')
#END - get the number of pieces
#
#START - get the object to cut and check if it`s valid
	_baseObj = _sel[ len(_sel) - 1]
	_shps = mc.listRelatives( _baseObj, shapes=True )
	for _shp in _shps:
		#print mc.objectType( _shp )
		if mc.objectType(_shp) != "mesh":
			mm.eval('error -showLineNumber False "Make sure the last object selected is a polygon object!";')
			#print "Make sure the last object selected is a polygon object!"
# END - get the object to cut and check if it`s valid
#
#
# START - clean the object for anouther round :)
	if mc.attributeQuery( 'factureCrack', node=_baseObj, ex=True) == 1:
		mc.deleteAttr( _baseObj, at='factureCrack' )
# END - clean the object for anouther round :)
#
# START - Preparing progressBar
	ui_addPB( "add", 0, "Preparing cut points...", _pieceNumber)
# END - Preparing progressBar

	_startTime = mc.timerX()

	for _i in range (0, _pieceNumber):
		_loc = _sel[_i];

		gMainProgressBar = mm.eval('$tmp = $gMainProgressBar');
		if mc.progressBar(gMainProgressBar, query=True, isCancelled=True ):
			break

		ui_addPB( "edit", 1, "Testing cut point %d/%d   " % (_i, _pieceNumber), 0)

		print "Locator " + _loc + ":"
		#priv_rayIntersect(_loc, _baseObj )
		if priv_rayIntersect(_loc, _baseObj ) == 0:
			#mc.select( _loc, replace=True )
			mc.delete( _loc )

#START - close the progressBar
	ui_addPB( "del", 0, "", 0)
#END - close the progressBar
#
#START - show some statistics
	_totalTime = mc.timerX( startTime= _startTime)
	print ("Sorting %d cutting points took %g s to complete." % (_pieceNumber, _totalTime))
Example #34
0
    def doIt(self, args):
        modeArg = 0
        fileName = ""
        orderArg = 0
        exclusiveArg = 0

        # parse the arguments.
        argData = OpenMaya.MArgDatabase(self.syntax(), args)

        if argData.isFlagSet(helpFlag):
            self.setResult(helpText)
            return ()

        if argData.isFlagSet(modeFlag):
            modeArg = argData.flagArgumentDouble(modeFlag, 0)
        if argData.isFlagSet(orderFlag):
            orderArg = argData.flagArgumentDouble(orderFlag, 0)
        if argData.isFlagSet(exclusiveFlag):
            exclusiveArg = argData.flagArgumentDouble(exclusiveFlag, 0)
        if argData.isFlagSet(fileFlag):
            fileName = argData.flagArgumentString(fileFlag, 0)
        else:
            OpenMaya.MGlobal.displayError(
                "{} needs file name flag.".format(kPluginCmdName))
            return ()

        if fileName == "":
            OpenMaya.MGlobal.displayError(
                "{} file name is not specified.".format(kPluginCmdName))
            return ()

        if modeArg < 0 or modeArg > 1:
            OpenMaya.MGlobal.displayError(
                "{} mode needs to be set to either 0 for 'write' "
                "or 1 for 'read'.".format(kPluginCmdName))
            return ()

        start = cmds.timerX()

        if modeArg == 0:
            result = self.writeWeights(fileName, exclusiveArg)
            msgString = "exported to "
        else:
            result = self.readWeights(fileName, orderArg)
            msgString = "imported from "

        doneTime = cmds.timerX(startTime=start)
        if result == 1:
            OpenMaya.MGlobal.displayInfo(
                "transferSkinCluster command took {:.2f} seconds".format(
                    doneTime))
            OpenMaya.MGlobal.displayInfo("Weights {}: {}".format(
                msgString, fileName))
Example #35
0
def toggleJointVis():
	'''
	Toggle "End" and "Con" joint visibility and display overrides.
	'''
	# Start Timer
	timer = mc.timerX()
	
	print('# Clean Rig: Lock Unused Joints (toggle display overrides for all "End" and "Con" joints)')
	glTools.utils.cleanup.toggleEnds(0)
	glTools.utils.cleanup.toggleCons(0)
	
	# Print Timed Result
	print('# Clean Rig: End/Con Joints Locked - '+str(mc.timerX(st=timer)))
Example #36
0
def toggleJointVis():
    """
    Toggle "End" and "Con" joint visibility and display overrides.
    """
    # Start Timer
    timer = cmds.timerX()

    print('# Clean Rig: Lock Unused Joints (toggle display overrides for all "End" and "Con" joints)')
    glTools.utils.cleanup.toggleEnds(0)
    glTools.utils.cleanup.toggleCons(0)

    # Print Timed Result
    print('# Clean Rig: End/Con Joints Locked - ' + str(cmds.timerX(st=timer)))
Example #37
0
    def rebuild(self):
        """
        """
        # Start timer
        timer = cmds.timerX()

        # ========================
        # - Rebuild Surface Data -
        # ========================

        # Rebuild Control Vertices
        nucmdsVs = len(self._data["cv"])
        cvArray = OpenMaya.MPointArray(nucmdsVs, OpenMaya.MPoint.origin)
        for i in range(nucmdsVs):
            cvArray.set(OpenMaya.MPoint(self._data["cv"][i][0], self._data["cv"][i][1], self._data["cv"][i][2], 1.0), i)

        # Rebuild Surface Knot Arrays
        numKnotsU = len(self._data["knotsU"])
        numKnotsV = len(self._data["knotsV"])
        knotsU = OpenMaya.MDoubleArray(numKnotsU, 0)
        knotsV = OpenMaya.MDoubleArray(numKnotsV, 0)
        for i in range(numKnotsU):
            knotsU.set(self._data["knotsU"][i], i)
        for i in range(numKnotsV):
            knotsV.set(self._data["knotsV"][i], i)

        # Rebuild Surface
        surfaceFn = OpenMaya.MFnMesh()
        surfaceData = OpenMaya.MFnNurbsSurfaceData().create()
        surfaceObj = surfaceFn.create(
            cvArray,
            knotsU,
            knotsV,
            self._data["degreeU"],
            self._data["degreeV"],
            self._data["formU"],
            self._data["formV"],
            self._data["rational"],
            surfaceData,
        )
        surfaceObjHandle = OpenMaya.MObjectHandle(surfaceObj)

        # =================
        # - Return Result -
        # =================

        # Print Timed Result
        buildTime = cmds.timerX(st=timer)
        print('NurbsSurfaceData: Data rebuild time for surface "' + self._data["name"] + '": ' + str(buildTime))

        return surfaceObjHandle
Example #38
0
def lockJointAttrs():
    """
    Locked Unused Joint Attributes
        - jointOrient
        - preferredAngle
    """
    # Start Timer
    timer = cmds.timerX()

    print('Locked Unused Joint Attributes (jointOrient, preferredAngle)')
    glTools.rig.utils.lockJointAttrs([])

    # Print Timed Result
    print('# Clean Rig: Clean Deformers - ' + str(cmds.timerX(st=timer)))
Example #39
0
def lockInfluenceWeights():
	'''
	Lock skinCluster influence weights
	'''
	# Start Timer
	timer = mc.timerX()
	
	print('Lock SkinCluster Influence Weights')
	influenceList = mc.ls('*.liw',o=True,r=True)
	for influence in influenceList:
		glTools.utils.skinCluster.lockInfluenceWeights(influence,lock=True,lockAttr=True)
	
	# Print Timed Result
	print('# Clean Rig: Lock SkinCluster Influences - '+str(mc.timerX(st=timer)))
Example #40
0
	def rebuild(self,overrides={}):
		'''
		Rebuild the deformer from the stored deformerData
		@param overrides: Dictionary of data overrides to apply 
		@type overrides: dict
		'''
		# Apply Overrides
		self._data.update(overrides)
		
		# ==========
		# - Checks -
		# ==========
		
		# Check target geometry
		for geo in self._data['affectedGeometry']:
			if not mc.objExists(geo):
				raise Exception('Deformer ('+self._data['name']+') affected geometry "'+geo+'" does not exist!')
		
		# ====================
		# - Rebuild Deformer -
		# ====================
		
		# Start timer
		timer = mc.timerX()
		
		deformer = self._data['name']
		if not mc.objExists(self._data['name']):
			deformer = mc.deformer(self.getMemberList(),typ=self._data['type'],n=deformer)[0]
		else:
			self.setDeformerMembership()
		
		# Set deformer weights
		self.loadWeights()
		
		# ================================
		# - Set Deformer Attribute Values -
		# ================================
		
		self.setDeformerAttrValues()
		self.setDeformerAttrConnections()
		
		# =================
		# - Return Result -
		# =================
		
		# Print Timed Result
		totalTime = mc.timerX(st=timer)
		print(self.__class__.__name__+': Rebuild time for deformer "'+deformer+'": '+str(totalTime))
		
		return deformer
Example #41
0
def lockJointAttrs():
    """
    Locked Unused Joint Attributes
        - jointOrient
        - preferredAngle
    """
    # Start Timer
    timer = cmds.timerX()

    print('Locked Unused Joint Attributes (jointOrient, preferredAngle)')
    glTools.rig.utils.lockJointAttrs([])

    # Print Timed Result
    print('# Clean Rig: Clean Deformers - ' + str(cmds.timerX(st=timer)))
Example #42
0
def lockInfluenceWeights():
    """
    Lock skinCluster influence weights
    """
    # Start Timer
    timer = cmds.timerX()

    print('Lock SkinCluster Influence Weights')
    influenceList = cmds.ls('*.liw', o=True, r=True)
    for influence in influenceList:
        glTools.utils.skinCluster.lockInfluenceWeights(influence, lock=True, lockAttr=True)

    # Print Timed Result
    print('# Clean Rig: Lock SkinCluster Influences - ' + str(cmds.timerX(st=timer)))
Example #43
0
    def playAll():
        '''Playback the entire animation sequence, returning the elapsed time when it is done'''
        _dbg('*** playbackModeManager::playAll')
        cmds.currentTime(cmds.playbackOptions(query=True, minTime=True))
        start_time = cmds.timerX()
        cmds.play(wait=True)
        elapsed_time = cmds.timerX(startTime=start_time)

        if cmds.currentTime(query=True) != cmds.playbackOptions(query=True,
                                                                maxTime=True):
            _dbg('### ERR: Play All to {} ended on frame {}'.format(
                cmds.playbackOptions(query=True, maxTime=True),
                cmds.currentTime(query=True)))

        return elapsed_time
Example #44
0
    def rebuild(self):
        """
        """
        # Start timer
        timer = cmds.timerX()

        # ========================
        # - Rebuild Surface Data -
        # ========================

        # Rebuild Control Vertices
        nucmdsVs = len(self._data['cv'])
        cvArray = OpenMaya.MPointArray(nucmdsVs, OpenMaya.MPoint.origin)
        for i in range(nucmdsVs):
            cvArray.set(
                OpenMaya.MPoint(self._data['cv'][i][0], self._data['cv'][i][1],
                                self._data['cv'][i][2], 1.0), i)

        # Rebuild Surface Knot Arrays
        numKnotsU = len(self._data['knotsU'])
        numKnotsV = len(self._data['knotsV'])
        knotsU = OpenMaya.MDoubleArray(numKnotsU, 0)
        knotsV = OpenMaya.MDoubleArray(numKnotsV, 0)
        for i in range(numKnotsU):
            knotsU.set(self._data['knotsU'][i], i)
        for i in range(numKnotsV):
            knotsV.set(self._data['knotsV'][i], i)

        # Rebuild Surface
        surfaceFn = OpenMaya.MFnMesh()
        surfaceData = OpenMaya.MFnNurbsSurfaceData().create()
        surfaceObj = surfaceFn.create(cvArray, knotsU, knotsV,
                                      self._data['degreeU'],
                                      self._data['degreeV'],
                                      self._data['formU'], self._data['formV'],
                                      self._data['rational'], surfaceData)
        surfaceObjHandle = OpenMaya.MObjectHandle(surfaceObj)

        # =================
        # - Return Result -
        # =================

        # Print Timed Result
        buildTime = cmds.timerX(st=timer)
        print('NurbsSurfaceData: Data rebuild time for surface "' +
              self._data['name'] + '": ' + str(buildTime))

        return surfaceObjHandle
Example #45
0
	def rebuild(self):
		'''
		Rebuild the set from the stored setData.
		@param mode: Membership mode if the specified set already exists. Accepted values are "add" and "replace".
		@type mode: str
		@param forceMembership: Forces addition of items to the set. If items are in another set which is in the same partition as the given set, the items will be removed from the other set in order to keep the sets in the partition mutually exclusive with respect to membership.
		@type forceMembership: bool
		'''
		# ==========
		# - Checks -
		# ==========

		# Set Name
		if not self._data['name']:
			raise Exception('SetData has not been initialized!')

		# Member Items
		memberList = self._data['membership'] or []
		for obj in memberList:
			if not mc.objExists(obj):
				print('Set member item "'+obj+'" does not exist! Unable to add to set...')
				memberList.remove(obj)

		# Flatten Membership List
		memberList = mc.ls(memberList,fl=True) or []

		# Mode
		if not mode in self.mode:
			raise Exception('Invalid set membership mode "'+mode+'"! Use "add" or "replace"!')

		# ===============
		# - Rebuild Set -
		# ===============

		# Start timer
		timer = mc.timerX()

		# Create Set
		setName = self._data['name']

		# Delete Set (REPLACE only)
		if mc.objExists(setName) and mode == 'replace': mc.delete(setName)

		# Create Set
		if not mc.objExists(setName): setName = mc.sets(n=setName)

		# Add Members
		if memberList:
			if forceMembership:
				for obj in memberList:
					try: mc.sets(obj,e=True,fe=setName)
					except Exception, e:
						print('Error adding item "'+obj+'" to set "'+setName+'"! Skipping')
						print(str(e))
			else:
				for obj in memberList:
					try: mc.sets(obj,e=True,add=setName)
					except Exception, e:
						print('Error adding item "'+obj+'" to set "'+setName+'"! Skipping')
						print(str(e))
Example #46
0
def chronoEnd(startChrono, firstStep, thisStep, totalSteps):
            
    if thisStep >= firstStep +2:
        endChrono       = cmds.timerX(startTime=startChrono)
        estimatedTime   = formatTime((((endChrono+1)/(thisStep+1))*totalSteps)-endChrono)
    
        return estimatedTime
Example #47
0
def cutSkin(mesh, weightThreshold=0.25, reducePercent=None, parentShape=False):
    '''
	Extract a per influence proxy mesh from a skinned mesh based on influence weights.
	@param mesh: Mesh to extract faces from
	@type mesh: str
	@param weightThreshold: Influence to use to extract faces
	@type weightThreshold: float
	@param reducePercent: Influence to use to extract faces
	@type reducePercent: int or None
	'''
    # Initialize
    startTime = mc.timerX()
    mc.undoInfo(state=False)

    # Get Skin Info
    skin = glTools.utils.skinCluster.findRelatedSkinCluster(mesh)
    if not skin:
        print('Cut Skin: Mesh "" has no skinCluster! Skipping...')
        return None

    # Prune Weights
    glTools.utils.skinCluster.lockSkinClusterWeights(skin,
                                                     lock=False,
                                                     lockAttr=False)
    pruneWts = glTools.utils.mathUtils.distributeValue(
        10, rangeStart=0.001, rangeEnd=weightThreshold)
    mc.select(mesh)
    for wt in pruneWts:
        try:
            mm.eval('doPruneSkinClusterWeightsArgList 1 {"' + str(wt) + '"}')
        except Exception, e:
            print('Prune weight FAILED (' + mesh + ')! ' + str(e))
            break
Example #48
0
 def setTimeout(self, function, sec, offset=0, xTimes=1, id=None, interval=None):
     
     timeNow     = cmds.timerX()
     timeToExec  = timeNow + sec + offset
     
     self.queue.append([function, timeToExec, sec, xTimes, id, interval])    
     self.runQueue()
Example #49
0
 def runQueue(self):        
     
     if len(self.queue) > 0:
         timeNow = cmds.timerX()
         for loopQueue in self.queue:
             timeToExec = loopQueue[1] 
             if timeToExec <= timeNow:
                 function    = loopQueue[0]
                 sec         = loopQueue[2]
                 xTimes      = loopQueue[3]
                 id          = loopQueue[4]
                 interval    = loopQueue[5]
                 timeToExec  = timeNow + sec
                 xTimes      -= 1
                 
                 function() 
                 if loopQueue in self.queue: self.queue.remove(loopQueue)
                 if xTimes > 0 or interval: self.queue.append([function, timeToExec, sec, xTimes, id, interval])
                         
     if len(self.queue) > 0:
         priority = 1
         for loopQueue in self.queue:
             interval    = loopQueue[5]
             id          = loopQueue[4]
             if interval: 
                 priority = 50
                 break
   
         
         G.deferredManager.sendToQueue(self.runQueue, priority, "timeoutInterval")
Example #50
0
def cutSkin(mesh, weightThreshold=0.25, reducePercent=None, parentShape=False):
    """
    Extract a per influence proxy mesh from a skinned mesh based on influence weights.
    @param mesh: Mesh to extract faces from
    @type mesh: str
    @param weightThreshold: Influence to use to extract faces
    @type weightThreshold: float
    @param reducePercent: Influence to use to extract faces
    @type reducePercent: int or None
    """
    # Initialize
    startTime = cmds.timerX()
    cmds.undoInfo(state=False)

    # Get Skin Info
    skin = glTools.utils.skinCluster.findRelatedSkinCluster(mesh)
    if not skin:
        print('Cut Skin: Mesh "" has no skinCluster! Skipping...')
        return None

    # Prune Weights
    glTools.utils.skinCluster.lockSkinClusterWeights(skin, lock=False, lockAttr=False)
    pruneWts = glTools.utils.mathUtils.distributeValue(10, rangeStart=0.001, rangeEnd=weightThreshold)
    cmds.select(mesh)
    for wt in pruneWts:
        try:
            mel.eval('doPruneSkinClusterWeightsArgList 1 {"' + str(wt) + '"}')
        except Exception, e:
            print('Prune weight FAILED (' + mesh + ')! ' + str(e))
            break
Example #51
0
	def rebuild(self):
		'''
		'''
		# Start timer
		timer = mc.timerX()

		# ========================
		# - Rebuild Surface Data -
		# ========================
		
		# Rebuild Control Vertices
		numCVs = len(self._data['cv'])
		cvArray = OpenMaya.MPointArray(numCVs,OpenMaya.MPoint.origin)
		for i in range(numCVs):
			cvArray.set(OpenMaya.MPoint(self._data['cv'][i][0],self._data['cv'][i][1],self._data['cv'][i][2],1.0),i)
		
		# Rebuild Surface Knot Arrays
		numKnotsU = len(self._data['knotsU'])
		numKnotsV = len(self._data['knotsV'])
		knotsU = OpenMaya.MDoubleArray(numKnotsU,0)
		knotsV = OpenMaya.MDoubleArray(numKnotsV,0)
		for i in range(numKnotsU): knotsU.set(self._data['knotsU'][i],i)
		for i in range(numKnotsV): knotsV.set(self._data['knotsV'][i],i)

		# Rebuild Surface
		surfaceFn = OpenMaya.MFnMesh()
		surfaceData = OpenMaya.MFnNurbsSurfaceData().create()
		surfaceObj = surfaceFn.create(	cvArray,
										knotsU,
										knotsV,
										self._data['degreeU'],
										self._data['degreeV'],
										self._data['formU'],
										self._data['formV'],
										self._data['rational'],
										surfaceData	)
		surfaceObjHandle = OpenMaya.MObjectHandle(surfaceObj)

		# =================
		# - Return Result -
		# =================
		
		# Print Timed Result
		buildTime = mc.timerX(st=timer)
		print('NurbsSurfaceData: Data rebuild time for surface "'+self._data['name']+'": '+str(buildTime))
		
		return surfaceObjHandle
Example #52
0
 def get(self):
     # timer start
     start = cmds.timerX()
     #
     self.sel = cmds.ls(sl=True, fl=True)
     if self.sel:
         self.user = getpass.getuser()
         self.date = time.strftime("%c")
         self.getLayers()
         self.getClipAttrs()
         self.getClipStartEndLength()
         # timer end
         # code that is being timed
         totalTime = cmds.timerX(startTime=start)
         print "------------  Total time: ", totalTime
     else:
         message('Select some objects. Export aborted.', maya=True, warning=True)
Example #53
0
	def doIt( self, args ):
		
		modeArg = 0
		fileName = ''
		orderArg = 0
		
		# parse the arguments.
		argData = OpenMaya.MArgDatabase(self.syntax(), args)
		
		if argData.isFlagSet(helpFlag):
			self.setResult(helpText)
			return()
		
		if argData.isFlagSet(modeFlag):
			modeArg = argData.flagArgumentDouble(modeFlag, 0)
		if argData.isFlagSet(orderFlag):
			orderArg = argData.flagArgumentDouble(orderFlag, 0)
		if argData.isFlagSet(fileFlag):
			fileName = argData.flagArgumentString(fileFlag, 0)
		else:
			OpenMaya.MGlobal.displayError(kPluginCmdName + ' needs file name flag.')
			return();
		
		if fileName == '':
			OpenMaya.MGlobal.displayError(kPluginCmdName + ' file name is not specified.')
			return()
		
		if modeArg < 0 or modeArg > 1:
			OpenMaya.MGlobal.displayError(kPluginCmdName + ' mode needs to be set to either 0 for \'write\' or 1 for \'read\'.')
			return()
		
		start = cmd.timerX()
		msgString = ''
		
		result = 0
		if modeArg == 0:
			result = self.writeWeights(fileName)
			msgString = 'exported to '
		else:
			result = self.readWeights(fileName, orderArg)
			msgString = 'imported from '
		
		doneTime = cmd.timerX(startTime=start)
		if result == 1:
			OpenMaya.MGlobal.displayInfo('transferSkinCluster command took %.02f seconds' % doneTime)
			OpenMaya.MGlobal.displayInfo('Weights ' + msgString + '\'' + fileName + '\'')
Example #54
0
    def rebuild(self):
        """
        Rebuild the set from the stored setData.
        """
        # ==========
        # - Checks -
        # ==========

        # Set Name
        if not self._data['name']:
            raise Exception('SetData has not been initialized!')

        # Member Items
        memberList = self._data['membership'] or []
        for obj in memberList:
            if not cmds.objExists(obj):
                print('Set member item "' + obj + '" does not exist! Unable to add to set...')
                memberList.remove(obj)

        # Flatten Membership List
        memberList = cmds.ls(memberList, fl=True) or []

        # Mode
        if not mode in self.mode:
            raise Exception('Invalid set membership mode "' + mode + '"! Use "add" or "replace"!')

        # ===============
        # - Rebuild Set -
        # ===============

        # Start timer
        timer = cmds.timerX()

        # Create Set
        setName = self._data['name']

        # Delete Set (REPLACE only)
        if cmds.objExists(setName) and mode == 'replace': cmds.delete(setName)

        # Create Set
        if not cmds.objExists(setName): setName = cmds.sets(n=setName)

        # Add Members
        if memberList:
            if forceMembership:
                for obj in memberList:
                    try:
                        cmds.sets(obj, e=True, fe=setName)
                    except Exception, e:
                        print('Error adding item "' + obj + '" to set "' + setName + '"! Skipping')
                        print(str(e))
            else:
                for obj in memberList:
                    try:
                        cmds.sets(obj, e=True, add=setName)
                    except Exception, e:
                        print('Error adding item "' + obj + '" to set "' + setName + '"! Skipping')
                        print(str(e))
Example #55
0
	def rebuildCurve(self):
		'''
		'''
		# Start timer
		timer = mc.timerX()
		
		# ========================
		# - Rebuild Curve Data -
		# ========================
		
		# Rebuild Control Vertices
		numCVs = len(self._data['cv'])
		cvArray = OpenMaya.MPointArray(numCVs,OpenMaya.MPoint.origin)
		for i in range(numCVs):
			cvArray.set(OpenMaya.MPoint(self._data['cv'][i][0],self._data['cv'][i][1],self._data['cv'][i][2],1.0),i)
		
		# Rebuild Curve Knot Arrays
		numKnots = len(self._data['knots'])
		knots = OpenMaya.MDoubleArray(numKnots,0)
		for i in range(numKnots): knots.set(self._data['knots'][i],i)
		
		# Rebuild Curve
		curveFn = OpenMaya.MFnMesh()
		curveData = OpenMaya.MObject()
		curveObj = curveFn.create(	cvArray,
									knots,
									self._data['degree'],
									self._data['form'],
									self._data['rational'],
									self._data['2d'],
									curveData	)

		# Rename Curve
		curve = OpenMaya.MFnDependencyNode(curveObj).setName(self._data['name'])
		
		# =================
		# - Return Result -
		# =================
		
		# Print timer result
		buildTime = mc.timerX(st=timer)
		print('NurbsCurveData: Geometry rebuild time for mesh "'+curve+'": '+str(buildTime))
		
		return curve
Example #56
0
def channelStateSet():
    """
    Enable channel states.
    Store Default Attr States.
    """
    # Start Timer
    timer = cmds.timerX()

    # Channel State - All ON
    print('Channel States Enabled')
    glTools.utils.channelState.ChannelState().set(1)

    # Default Attr State - All ON
    print('Default Attribute States Enabled')
    glTools.utils.defaultAttrState.setDisplayOverridesState(displayOverrideState=1)
    glTools.utils.defaultAttrState.setVisibilityState(visibilityState=1)

    # Print Timed Result
    print('# Clean Rig: Channel States - ' + str(cmds.timerX(st=timer)))