Esempio n. 1
0
 def createImpactHelper(self):
     '''
     Creates IS Sphere Helper
     '''
     mImpact = cmds.sphere(r = 0.00001, n = 'IS_Impact')
     mImpactShape = cmds.listRelatives(mImpact[0])[0]
     
     self._mVoroImpactTrs = mImpact[0]
     self._mVoroImpactShape = mImpact[1]
     
     cmds.setAttr(mImpact[0] + '.visibility', False)
     cmds.setAttr(mImpact[0] + '.overrideEnabled', True)
     cmds.setAttr(mImpact[0] + '.overrideColor', 14)
     cmds.setAttr(mImpact[1] + '.sections', 2)
     cmds.setAttr(mImpact[1] + '.spans', 2)
     cmds.setAttr(mImpactShape + '.curvePrecisionShaded', 20)
     
     self._mVoroImpactShader = cmds.shadingNode('lambert', name = 'IS_ImpactMat', asShader = True)
     cmds.setAttr(self._mVoroImpactShader + '.diffuse', 0.0)
     cmds.setAttr(self._mVoroImpactShader + '.translucence', 0.3)
     cmds.setAttr(self._mVoroImpactShader + '.translucenceDepth', 0.75)
     cmds.setAttr(self._mVoroImpactShader + '.color', 0.0, 1.0, 0.0, type = 'double3')
     cmds.setAttr(self._mVoroImpactShader + '.incandescence', 0.0, 0.15, 0.0, type = 'double3')
     cmds.setAttr(self._mVoroImpactShader + '.transparency', 0.55, 0.55, 0.55, type = 'double3')
     
     cmds.select(mImpact, replace = True)
     cmds.hyperShade(assign = self._mVoroImpactShader)
     mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
     
     if (cmds.attributeQuery('hiddenInOutliner', node = self._mVoroImpactTrs, exists = True)):
         cmds.setAttr(self._mVoroImpactTrs + '.hiddenInOutliner', True)
     
     cmds.select(clear = True)
     cmds.scriptEditorInfo (clearHistory = True)
Esempio n. 2
0
    def switch(self, side, rigmodule, mode):
        """Switches the given module to the given mode.
        @param side: the side
        @param rigmodule: the name of the rigmodule
        @param mode: the mode to switch to

        """
        warnings = cmds.scriptEditorInfo(q=True, suppressWarnings=True)
        cmds.scriptEditorInfo(e=True, suppressWarnings=True)

        default_length_a, default_length_b = self._get_default_length(side, rigmodule)
        current_length_a, current_length_b = self._get_current_length(side, rigmodule)

        length_a_factor = current_length_a / default_length_a
        length_b_factor = current_length_b / default_length_b

        rot_a, rot_b, rot_c = self._get_snap_rotation(side, rigmodule)

        if mode == 0:
            ctl_a, ctl_b, ctl_c, settings, gimbal = self._get_ctls(side, rigmodule, mode)
            cmds.setAttr('%s.length' % ctl_a, length_a_factor)
            cmds.setAttr('%s.length' % ctl_b, length_b_factor)
            cmds.setAttr('%s.rotate' % gimbal, 0, 0, 0)
            cmds.xform(ctl_a, ws=True, ro=rot_a)
            cmds.xform(ctl_b, ws=True, ro=rot_b)
            cmds.xform(ctl_c, ws=True, ro=rot_c)
        elif mode == 1:
            snap_a, ctl_a, snap_b, ctl_b, settings = self._get_ctls(side, rigmodule, mode)
            self.c.snap_a_to_b(ctl_a, snap_a)
            self.c.snap_a_to_b(ctl_b, snap_b)
        # END if
        cmds.setAttr('%s.FK_IK_Blend' % settings, mode)

        cmds.scriptEditorInfo(e=True, suppressWarnings=warnings)
 def restore_output(cls):
     """Restores the script editor output settings to their original values."""
     if None not in {cls.suppress_results, cls.suppress_errors, cls.suppress_warnings, cls.suppress_info}:
         cmds.scriptEditorInfo(e=True,
                               suppressResults=cls.suppress_results,
                               suppressInfo=cls.suppress_info,
                               suppressWarnings=cls.suppress_warnings,
                               suppressErrors=cls.suppress_errors)
Esempio n. 4
0
 def deleteIShatterCtx(self):
     '''
     Delete IShatter Context Tool
     '''
     cmds.deleteUI(self._mContext)
     cmds.modelEditor('modelPanel4', edit = True, grid = True)       
     
     cmds.scriptEditorInfo (clearHistory = True)
     cmds.flushUndo()   
Esempio n. 5
0
def modify_lite_scene(filepath):
    #Use the maya.cmds module to manipulate Maya
    cmds.scriptEditorInfo(
        suppressInfo=True,
        suppressResults=True,
        suppressErrors=True,
        suppressWarnings=True)
    cmds.file(filepath, open=True, force=True)
    cmds.polyCube(name="my_cuber2")
    cmds.file(save=True, force=True)
Esempio n. 6
0
def create_lite_scene(filepath):
    #Create a new scene file
    cmds.scriptEditorInfo(
        suppressInfo=True,
        suppressResults=True,
        suppressErrors=True,
        suppressWarnings=True)
    cmds.file(new=True, force=True)

    #Perform some actions in the new scene
    pcube = cmds.polyCube(name='my_cuber1')
    cmds.xform(pcube, ws=True, t=(0.5, 0, 0))

    #Name the scene file and save
    cmds.file(rename=filepath)
    cmds.file(save=True, force=True)
Esempio n. 7
0
 def show(self):
     '''
     
     '''        
     # First close the IShatter Window if it exists
 	self.close()
 	
 	# clear selection
 	cmds.select(clear = True)
 	
 	# make the window
 	global LJ_IShatterWin
 	LJ_IShatterWin = cmds.window(title = self._windowTitle, sizeable = False, mnb = False, mxb = False)   	
 	
 	# create main layout    	
 	self.addShatterOptions()    												
 	
 	# display the Window	
 	cmds.showWindow(LJ_IShatterWin)
 	cmds.scriptEditorInfo(clearHistory = True)
Esempio n. 8
0
def setupHotkeys():
	cmds.scriptEditorInfo(suppressWarnings=True) # supress annoying warnings
	#from JR_hk_map import *		# import user_hotkeys script
	import JR_hk_map # import user_hotkeys script
	JR_hk_map.Map.globalHotkeys() 				# init global hotkeys
	JR_hk_map.Map.setCategory('frostbite') 		# init category hotkeys
	# hide icon menu
	hideIconMenu()
	# SET SCENE DEFAULTS
	cmds.setAttr ("defaultResolution.height", 720) # Frame Height
	cmds.setAttr ("defaultResolution.width", 1280) # Frame Width
	cmds.setAttr ("defaultResolution.deviceAspectRatio", 1.777) # Aspect Ratio
	cmds.setAttr ("defaultResolution.pixelAspect", 1) # Pixel Aspect
	cmds.currentUnit( time='ntsc') # Time - NTSC
	# SET CAMERA PLANES TO FAR AWAY::
	# FAR PLANE
	cmds.setAttr("perspShape.farClipPlane",  1000000 )
	cmds.setAttr("sideShape.farClipPlane",   1000000 )
	cmds.setAttr("topShape.farClipPlane",    1000000 )
	cmds.setAttr("frontShape.farClipPlane",  1000000 )
	# NEAR PLANE
	#cmds.setAttr("perspShape.nearClipPlane", 0.01 )
	#cmds.setAttr("sideShape.nearClipPlane",  0.01 )
	#cmds.setAttr("topShape.nearClipPlane",   0.01 )
	#cmds.setAttr("frontShape.nearClipPlane", 0.01 )
	# turn current frame off to start with
	mel.eval( "setCurrentFrameVisibility  (0) ;" )
	mel.eval( "setSceneTimecodeVisibility (0) ;" )
	mel.eval( "setFocalLengthVisibility   (0) ;" )
	# Set all of the defaults to what they should be.
	mel.eval( "setFrameRateVisibility (0) ; " )
	mel.eval( "setSelectDetailsVisibility (0) ; " )
	mel.eval( "setObjectDetailsVisibility (0) ; " )
	mel.eval( "setParticleCountVisibility (0) ; " )
	mel.eval( "setPolyCountVisibility (0) ; " )           #- maybe set this one to 1 if we go to modeling but 0 for the rest?
	mel.eval( "setSubdDetailsVisibility (0) ; " )         #- maybe set this one to 1 if we go to modeling but 0 for the rest?
	mel.eval( "setAnimationDetailsVisibility (0) ; " )    #- maybe set this to 1 for animation?
	mel.eval( "setHikDetailsVisibility (0) ; " )          #- maybe set this to 1 for animation?
	mel.eval( "setCurrentContainerVisibility (0) ; " )
	mel.eval( "setCameraNamesVisibility (0) ; " )
Esempio n. 9
0
    def finalizeCtx(self):
        '''
        called when we exit the context
        '''
        if cmds.objExists(self._mVoroImpactTrs):
            cmds.delete(self._mVoroImpactTrs) ; self._mVoroImpactTrs = None
        
        if cmds.objExists(self._mVoroDisplay[0]):
            cmds.delete(self._mVoroDisplay) ; self._mVoroDisplay = None
        
        if cmds.objExists(self._mVoroObject):
            cmds.setAttr(self._mVoroObject + '.visibility', True)
            mBreakNode = cmds.listConnections(self._mVoroObject, sh = True, type = 'fxBreakGeometry')
            if len(mBreakNode) > 0:
                if self._mVoroPoints.length() > 0:
                    cmds.setAttr(mBreakNode[0] + '.numPoints', self._mVoroPoints.length())       
        
        if len(self._mObjectsToHide):
            cmds.showHidden(self._mObjectsToHide)
        
        self._mVoroPoints.clear() ; self._mVoroPoints = None
        self._mObjectsToHide = None            
            
        cmds.select(clear = True)
        mel.eval('hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes")')
        cmds.scriptEditorInfo (clearHistory = True)
            
        if self._mInViewMessage:
            cmds.inViewMessage(amg = '<hl> IShatter Completed </hl>', dragKill = True, fade = True, pos = 'topCenter')
        else:                     
            cmds.headsUpMessage('IShatter Completed', verticalOffset = (cmds.control('modelPanel4', q = True, h = True) / 2.5))        
        
        cmds.scriptJob(event = ("idle", self.deleteIShatterCtx), runOnce = True)                        

#****************************************************************************************************************************************************************************************#
#****************************************************************************************************************************************************************************************#
# 													    	                     CLASS END DEFINITION                                                                                    #
#****************************************************************************************************************************************************************************************#
#****************************************************************************************************************************************************************************************#
Esempio n. 10
0
def finishSetup(arg):
  global doProfiling, frameRange, voxelSize, cubeSize, siState, srState, swState
  frameRange = cmds.floatFieldGrp('frameRangeText', query=True,
    value=True)
  if not useVoxCtrl:
    voxelSize = cmds.floatFieldGrp('voxSizeText', q=True, value=1)[0]
  if not useCubeCtrl:
    cubeSize = cmds.floatFieldGrp('cubeSizeText', q=True, value=1)[0]
  # store script editor message settings
  siState = cmds.scriptEditorInfo(q=True, si=True)
  srState = cmds.scriptEditorInfo(q=True, sr=True)
  swState = cmds.scriptEditorInfo(q=True, sw=True)
  
  killVoxWindow(0)

  if doProfiling:
    import cProfile
    cProfile.run('doit()', 'results')
    import pstats
    p = pstats.Stats('results')
    p.sort_stats('cumulative').print_stats(10)
  else:
    doit()
 def suppress_output(cls):
     """Hides all script editor output."""
     if Settings.buffer_output:
         cls.suppress_results = cmds.scriptEditorInfo(q=True, suppressResults=True)
         cls.suppress_errors = cmds.scriptEditorInfo(q=True, suppressErrors=True)
         cls.suppress_warnings = cmds.scriptEditorInfo(q=True, suppressWarnings=True)
         cls.suppress_info = cmds.scriptEditorInfo(q=True, suppressInfo=True)
         cmds.scriptEditorInfo(e=True,
                               suppressResults=True,
                               suppressInfo=True,
                               suppressWarnings=True,
                               suppressErrors=True)
Esempio n. 12
0
    cmds.delete(chr_grp)
    # Add reset clusters position


def set_random(*args):

    for o in random_objects:
        cmds.xform(o, t=get_random_tr(), a=True)


def process(*args):
    set_template()
    save_generated(get_commands())


# gui
if cmds.window('Generate', exists=True):
    print 'got to existing'
    cmds.deleteUI('Generate')
# Supress warnings
cmds.scriptEditorInfo(sw=True)
cmds.window('Generate', width=250)
cmds.columnLayout(adjustableColumn=True)
cmds.button(label='Set Random',
            command=set_random,
            ann='Mix controls position')
cmds.button(label='Process',
            command=process,
            ann='Export mesh with blendshapes and construction file')
cmds.showWindow()
Esempio n. 13
0
def bakeTextureTool(obj, xRes, yRes, imFormat, alpha=True):
    '''{'del_path':'Rendering/Render/bakeTextureTool()ONLYSE',
'usage':'$fun(cmds.ls(sl=True)[0], 512, 512, "iff", alpha=True)',
}    
'''
    #if str(type(objects)) == "<type 'str'>" or str(type(objects)) == "<type 'unicode'>":
    #objects = [objects]
    #obj = cmds.ls(sl=True)[0]
    #xRes=1024
    #yRes=1024
    #imFormat = "tif"
    #alpha=True
    imFormatV = ["tif", "iff", "jpg", "rgb", "rla", "tga", "bmp", "hdr"
                 ].index(imFormat) + 1

    cmds.scriptEditorInfo(sr=True, suppressWarnings=True)
    #set path
    prj = cmds.workspace(q=True, rd=True)

    if not os.path.exists(prj + "sourceimages"):
        os.mkdir(prj + "sourceimages")

    os.chdir(prj + "sourceimages")

    if os.path.exists("lightMap"):
        os.rename("lightMap", "lightMapOrig")
    os.mkdir("lightMap")

    #create and set textureBakeSet
    if cmds.objExists("tempBakeSet*"):
        cmds.delete("tempBakeSet*")
    tempBakeSet = mel.eval(r'createBakeSet( "tempBakeSet", "textureBakeSet")')

    cmds.setAttr("%s.colorMode" % tempBakeSet, 0)
    cmds.setAttr("%s.xResolution" % tempBakeSet, xRes)
    cmds.setAttr("%s.yResolution" % tempBakeSet, yRes)
    cmds.setAttr("%s.fileFormat" % tempBakeSet, imFormatV)
    if alpha:
        cmds.setAttr("%s.bakeAlpha" % tempBakeSet, 1)

    #copy new renderLayer for bake
    bakeSetRL = cmds.createRenderLayer(g=True, n="tempBakeSetL")

    #get shape and shadingEngine
    if not cmds.objectType(obj, i="mesh"):
        obj = cmds.listRelatives(obj, f=True, type="mesh")
        if obj != None:
            obj = obj[0]
            sE = cmds.listConnections(obj, type="shadingEngine")
            if sE != None: sE = sE[0]
            #print obj,sE

    if obj != None and sE != None:
        mel.eval('assignBakeSet( "%s", "%s")' % (tempBakeSet, obj))
        startF = cmds.playbackOptions(q=True, min=True)
        endF = cmds.playbackOptions(q=True, max=True)
        for curF in range(startF, endF + 1):
            cmds.currentTime(curF, e=True)
            mapName = cmds.convertLightmap(sE,
                                           obj,
                                           camera="persp",
                                           prj=prj + "sourceimages")[0]
            if os.path.exists("lightMap/%s.%04d.%s" %
                              (mapName, curF, imFormat)):
                os.remove("lightMap/%s.%04d.%s" % (mapName, curF, imFormat))
            os.rename("lightMap/%s.%s" % (mapName, imFormat),
                      "lightMap/%s.%04d.%s" % (mapName, curF, imFormat))
            print "saved image %s.%04d.%s" % (mapName, curF, imFormat)
        if os.path.exists(mapName):
            shutil.rmtree(mapName)
        print "saved images squeuence to %s\%s" % (os.getcwd(), mapName)
        os.rename("lightMap", mapName)
        os.rename("lightMapOrig", "lightMap")
    cmds.delete(tempBakeSet)
    cmds.scriptEditorInfo(sr=False, suppressWarnings=False)
Esempio n. 14
0
def doit():
  global voxelSize, cubeSize, cubeDict, allLights, amb, useAmbient, useShadows, disableUndos, showCommands, useVoxCtrl, useCubeCtrl, frameRange, verboseOutput, xmin, xmax, ymin, ymax, zmin, zmax, xLocs, yLocs, zLocs

  cubeDict = {}
  shaderDict = {}
  SGDict = {}

  if useAmbient:
      # disable and store all existing lights
      allLights = cmds.sets("defaultLightSet", q=1)
      cmds.sets(clear="defaultLightSet")
      # make an ambient light
      amb = cmds.ambientLight(i=True, ambientShade=0)
  else: allLights = None

  # identify control objects
  sel = cmds.ls(sl=True)
  if len(sel) > 0:
    # filter for polymeshes
    ctrl = cmds.filterExpand(sel, fullPath=0, selectionMask=12)
    cmds.select(cl=1)
    sel = []
    if ctrl == None:
      print "No meshes found in selection, checking scene..."
      # check for object or group named "voxelGeo"
      if cmds.objExists("voxelGeo"):
        cmds.select("voxelGeo")
        sel = cmds.ls(sl=1)
  if len(sel) == 0: # select all dag objects
    cmds.select(ado=True)
    sel = cmds.ls(sl=True)
  if sel == None or sel == []:
    cmds.confirmDialog( title='Mesh selection', message= 'No meshes found in scene.', button=['OK'])
    return 0
  else: # filter for polymeshes
    ctrl = cmds.filterExpand(sel, fullPath=0, selectionMask=12)
    if ctrl == None:
      cmds.confirmDialog( title='Mesh selection', message= 'No meshes found in scene.', button=['OK'])
      return 0

  if disableUndos: cmds.undoInfo(state=False)
  if not showCommands: cmds.scriptEditorInfo(sr=True, sw=True, si=True)
  firstFrame = frameRange[0]
  lastFrame = frameRange[1]
  duration = abs(int(lastFrame-firstFrame))+1

  # deal with backwards frame ranges
  if lastFrame < firstFrame:
    lastFrame -= 1
    frameStep = -1
  else:
    lastFrame += 1
    frameStep = 1

  startTime= cmds.timerX()
  makeProgBar(duration*len(ctrl))
  cmds.progressBar(gMainProgressBar, edit=True, beginProgress=True)
  s = "s" if duration > 1 else ""
  print "Voxelizer animating over", duration, "frame%s..."%s
  print "Press ESC to cancel"

  resetList = []
  directions = [(-1.0, 0.0, 0,0), (0.0, -1.0, 0,0), (0.0, 0.0, -1.0)]
  cubegroup = cmds.group(em=True, n='cubes')
  cmds.select(cl=1)

  #for f in range(firstFrame,lastFrame,frameStep): # for each frame
  for f in range(int(firstFrame),int(lastFrame),int(frameStep)): # for each frame
    stepTime= cmds.timerX()
    if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ):
      return docancel()
    cmds.currentTime(f, edit=True, update=True)

    # get sizes from control objects, if available
    if useVoxCtrl:
      voxelSize = round(cmds.getAttr('voxelScaleCtrl.scaleX'), 3)
    if useCubeCtrl:
      cubeSize = round(cmds.getAttr('cubeScaleCtrl.scaleX'), 3)

    # hide visible cubes
    for x in resetList:
      cmds.setKeyframe(x, at="scale", v=0, t=f)
    resetList = []

    # for every target control object:
    for c in ctrl:
      if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ):
        return docancel()
      cmds.progressBar(gMainProgressBar, edit=True, step=True)
      # if ctrl object is invisible, skip to the next one
      if objIsVisible(c) == 0:
        continue

      # bake textures into verts
      cmds.select(c)
      cmds.polyGeoSampler(sampleByFace=True, computeShadows=useShadows, rs=useShadows)
      
      # set ray starting points
      setLocs(c)
      locArrays = [xLocs, yLocs, zLocs]

      # for each axis:
      for i in range(3):
        # for every gridpoint:
        for loc in locArrays[i]:
          hits = []
          # zap a ray through the object
          rayInt = rayIntersect(c, loc, directions[i])
          hits = rayInt[0]
          hfaces =  rayInt[1]
          for j, x in enumerate(hits):
            # snap hit locations to cubegrid
            x = (roundToFraction(x[0], voxelSize), roundToFraction(x[1], voxelSize), roundToFraction(x[2], voxelSize) )

            # if location isn't in cubeDict: make a new cube
            if x not in cubeDict:
              # add location and new cube to cubeDict
              cubeDict[x] = cmds.polyCube(sz=1, sy=1, sx=1, cuv=4, d=1, h=1, w=1, ch=1)[0]
              cube = cubeDict[x]
              if useShadows:
                # prevent cubes from casting shadows onto the ctrl objs
                cmds.setAttr(cube+".castsShadows", 0)
              cmds.parent(cube, cubegroup)
              # move cube to location
              cmds.xform(cube, t=x)

              # shader coloring method: uses one shader per cube
              shader = cmds.shadingNode("lambert", asShader=1)
              # create a shading group
              shaderSG = cmds.sets(renderable=True, noSurfaceShader=True, empty=True, name=shader+"SG")
              # connect the shader to the shading group
              cmds.connectAttr('%s.outColor'%shader, '%s.surfaceShader'%shaderSG, f=True)
              # add cube to the shaderSG
              shape = cmds.listRelatives(cube, shapes=1)[0]
              cmds.sets('%s'%shape, e=True, fe='%s'%shaderSG)

              shaderDict[cube] = shader
              SGDict[cube] = shaderSG

              # set scale key of 0 on the previous frame
              cmds.setKeyframe(cube, at="scale", v=0, t=(f-1))

            cube = cubeDict[x]
            cubeshape = cmds.listRelatives(cube, shapes=1)[0]

            # add cube to resetList
            resetList.append(cube)

            if len(hfaces) > 0:
              # check the alpha of the face
              alpha = cmds.polyColorPerVertex(c+'.f['+str(hfaces[j])+']', q=True, a=True, cdo=True)
              
              if alpha[0] > 0.5: # if more than half opaque
                # get the color of the face
                fcolor = cmds.polyColorPerVertex(c+'.f['+str(hfaces[j])+']', q=True, rgb=True, cdo=True, nun=True)
                cmds.setKeyframe(shaderDict[cube]+'.colorR', v=fcolor[0])
                cmds.setKeyframe(shaderDict[cube]+'.colorG', v=fcolor[1])
                cmds.setKeyframe(shaderDict[cube]+'.colorB', v=fcolor[2])

                # set a scale key
                cmds.setKeyframe(cube, at="scale", v=cubeSize, t=f, breakdown=0, hierarchy="none", controlPoints=0, shape=0)

                # if previous frame didn't have a scale key, set it to 0
                tempCurTime = cmds.currentTime(q=True)-1
                lastKey = cmds.keyframe(cube, at="scale", q=True, t=(tempCurTime,tempCurTime), valueChange=True)
                if lastKey == None:
                  cmds.setKeyframe(cube, at="scale", v=0, t=(f-1))

    if verboseOutput:
      stepTime = cmds.timerX(st=stepTime)
      totalTime = cmds.timerX(st=startTime)
      print "frame:", cmds.currentTime(q=True), "\tkeyed cubes:", len(resetList), "\ttotal cubes:", len(cubeDict)
      cps = "inf" if stepTime == 0 else round(len(resetList)/stepTime, 2)
      if useVoxCtrl or useCubeCtrl:
        print "\t\tvoxelSize:", voxelSize, "\tcubeSize: ", cubeSize
      print "\t\tstepTime:", round(stepTime, 2), "\ttotal time:", round(totalTime, 2), "\tcubes per second:", cps

  # restore scene state
  if useAmbient:
    if cmds.objExists(amb): cmds.delete(cmds.listRelatives(amb, parent=True)[0])
    cmds.sets(allLights, add="defaultLightSet")
  elif useShadows:
    # turn the cubes' shadows back on
    for x in cubeDict:
      cmds.setAttr(cubeDict[x]+".castsShadows", 1)
  if not showCommands: cmds.scriptEditorInfo(sr=srState, sw=swState, si=siState)
  if disableUndos: cmds.undoInfo(state=True)

  cmds.progressBar(gMainProgressBar, edit=True, endProgress=True)
  totalTime = cmds.timerX(st=startTime)
  print("Voxelizer finished: "+str(round(totalTime, 2))+ " seconds ("+str(round(totalTime/60, 2)) + " minutes)")

#promptSetup()

### End Voxelizer 1.0 ###
Esempio n. 15
0
def bendy_proc():
	cmds.scriptEditorInfo(suppressWarnings=True)
	global globalScale
	globalScale = cmds.textField( "textField", q = True, tx = True )
	
	#get the selected objects and add them
	tsl = []
	tsl = cmds.textScrollList( "tsList", q = True, ai = True )
	cmds.textScrollList( "tsList", e = True, di = ("(only works on joints)")  )

	#select the textScrollList
	if ( len(tsl) > 0 ):
		list = ('' )
		
		for item in tsl:
			list += ('"' + item )
			list += '", '
			
		list = list[:-2]
		list = list.replace("(only works on joints)", "")
		list = list[4:]
		list = ('cmds.select(' + list + ', r = True )' )
	eval(list)
	
	#list and count only the joints in tsList
	joints = []
	joints = cmds.ls( sl = True, type = 'joint' )
	num = len(joints)
	
	
	#isolates the bottom most child joints in tsList
	i = 0
	#a = 0
	children = []
	while (i < num):
		pod = cmds.select( joints[i], hi = True )
		pods = cmds.ls( sl = True, type = 'joint' )
		hi = len(pods)
		f = 0
		b = 1
		while( f == 0 ):
			cmds.select(pods[hi-b], r = True)
			bottom = cmds.ls( sl = True )
			if any( ch in bottom for ch in joints):
				f = 1
			b += 1
		cmds.select( bottom, r = True )
		cmds.pickWalk( d = 'down' )
		bottom = cmds.ls( sl = True )
		children.append(str(bottom)[3:][:-2])
		i += 1
		
	#Babies!? Babies are childless.
	global babies
	babies = []
	for b in children:
		if b not in babies:
			babies.append(b)
	
	num = len(babies)
	i = 0
	while (i < num):
		babies[i] = str(babies[i])
		i += 1

	cmds.select( joints, r = True )
	cmds.select( babies, d = True )
	parents = cmds.ls( sl = True )

	n = len(parents)
	i = 0
	while( i < n ):
		child = cmds.pickWalk( parents[i], d = 'down' )
		cmds.select( parents[i], child, r = True )
		split()
		getBent()
		i += 1
	
	#organizes end controls that are not at root
	i = 0
	while( i < n ):
		cmds.select( '%s_segment_*_joint' % parents[i] )
		seg = []
		seg = cmds.ls( sl = True )
		segNum = len(seg)
		cmds.select( parents[i], r = True )
		pick = cmds.ls( sl = True )
		cmds.pickWalk( d = 'up' )
		check = cmds.ls( sl = True )
		endSeg = str(check[0])
		jointName = seg[0][:-16]
		if( pick != check ):
			if any( pa in check for pa in parents):
				cmds.parent( '%s_segment_%d_curve_tipClusterHandle_grp' % ( endSeg, segNum - 1 ), '%s_segment_%d_ikh' % ( endSeg, segNum - 1 ), '%s_ctrl' % jointName )
		i += 1
	
	#create ik/cluster groups
	i = 0
	while( i < n ):
		q = 0
		cmds.select( '%s_segment_*_joint' % parents[i] )
		segLen = ( len(cmds.ls( sl = True ) ) - 1 )			
		while( q < segLen - 1):
			global s
			s = cmds.intSliderGrp( "seg", q = True, v = True )
			tac = 1
			cmds.select( '%s_segment_*_joint' % parents[i] )
			segs = []
			segs = cmds.ls( sl = True )
			tac = 0
			if(q >= 9):
				tac = 1
			jointName = segs[q][:-16 - tac]
			cmds.select( '%s_segment_%d_curve_tipClusterHandle_grp' % ( jointName, (q + 1) ), '%s_segment_%d_curve_baseClusterHandle_grp' % ( jointName, (q + 2) ), '%s_segment_%d_ikh' % ( jointName, (q + 1) ), r = True )
			groupSpecial()
			q += 1
			
		x = ( s/2 ) - 1
		d = 0		
		#create constraints that control bend:
		#upper segment
		while ( d < ( s/2 ) - 1):
			y = (s / x) - 1
			W0 =  ( 1 / y )
			W1 = 1 - W0
			cmds.select( '%s_segment_*_joint' % parents[i] )
			tac = 0
			
			j = []
			j = cmds.ls( sl = True )
			j = str(j[1])
			tx = abs(cmds.getAttr( '%s.tx' % j ))
			ty = abs(cmds.getAttr( '%s.ty' % j ))
			tz = abs(cmds.getAttr( '%s.tz' % j ))

			if( tx > .001 ):
				prim = 'X'
			if( ty > .001):
				prim = 'Y'
			if( tz > .001 ):
				prim = 'Z'	
			
			if(s > 9):
				tac = 1
			segs = []
			segs = cmds.ls( sl = True )
			jointName = segs[q][:-16 - tac]
			
			#translate	
			cmds.parentConstraint( '%s_upper_ctrl_const_grp' % jointName, '%s_bendy_ctrl_const_grp' % jointName, '%s_segment_%d_ikh_grp' % (jointName, d + 1 ), mo = True, sr = ('x','y','z') ) ###Make sr = xyz - primary axis
			cmds.setAttr( '%s_segment_%d_ikh_grp_parentConstraint1.%s_upper_ctrl_const_grpW0' % (jointName, d + 1, jointName ), W0 )
			cmds.setAttr( '%s_segment_%d_ikh_grp_parentConstraint1.%s_bendy_ctrl_const_grpW1' % (jointName, d + 1, jointName ), W1 )
			
			#twist
			cmds.select( '%s_segment_%d_ikh' % (jointName, (d + 1)), r = True )
			cmds.rename( groupSpecial(), '%s_segment_%d_ikh_rot_grp' % ( jointName, (d + 1)) )
			cmds.select( '%s_segment_%d_ikh_rot_grp' % (jointName, (d + 1)), '%s_segment_%d_ikh' % (jointName, (d + 1)), r = True )
			nm_alignLRAs()
			
			cmds.createNode ('multiplyDivide', n = '%s_segment_%d_md' % (jointName, (d + 1)) )
			cmds.createNode ('addDoubleLinear', n = '%s_segment_%d_adl' % (jointName, (d + 1)) )
			cmds.createNode ('multDoubleLinear', n = '%s_segment_%d_twist_mdl' % (jointName, (d + 1)) )
			
			cmds.setAttr('%s_segment_%d_md.input2X' % (jointName, (d + 1)), W1 )
			cmds.setAttr('%s_segment_%d_md.input2Y' % (jointName, (d + 1)), W0 )
			
			cmds.connectAttr('%s_bendy_ctrl.rotate%s' % (jointName, prim), '%s_segment_%d_md.input1X' % (jointName, (d + 1)) )
			cmds.connectAttr('%s_ctrl.rotate%s' % (jointName, prim), '%s_segment_%d_md.input1Y' % (jointName, (d + 1)) )
			cmds.connectAttr('%s_segment_%d_md.outputX' % (jointName, (d + 1)), '%s_segment_%d_adl.input1' % (jointName, (d + 1)) )
			cmds.connectAttr('%s_segment_%d_md.outputY' % (jointName, (d + 1)), '%s_segment_%d_adl.input2' % (jointName, (d + 1)) )
			cmds.connectAttr('%s_twist_mdl.output' % jointName, '%s_segment_%d_twist_mdl.input1' % (jointName, (d + 1)) )
			cmds.connectAttr('%s_segment_%d_adl.output' % (jointName, (d + 1)), '%s_segment_%d_twist_mdl.input2' % (jointName, (d + 1)) )
			cmds.connectAttr('%s_segment_%d_twist_mdl.output' % (jointName, (d + 1)), '%s_segment_%d_ikh_rot_grp.rotate%s' % (jointName, (d + 1), prim) )
			
			x -= 1
			d += 1
		
		#lower segment
		x = ( s/2 ) - 1
		m = d + x
		while( d >= 1):
			y = (s / x) - 1
			W0 =  ( 1 / y )
			W1 = 1 - W0
			cmds.select( '%s_segment_*_joint' % parents[i] )

			if(s > 8):
				tac = 1
			segs = []
			segs = cmds.ls( sl = True )
			jointName = segs[q+1][:-16 - tac]

			cmds.select( jointName, r = True )
			cmds.pickWalk( d = 'down' )
			joint2Name = cmds.ls( sl = True )
			joint2Name = str(joint2Name)[3:][:-2]
			
			#translate
			cmds.parentConstraint( '%s_lower_ctrl_const_grp' % joint2Name, '%s_bendy_ctrl_const_grp' % jointName, '%s_segment_%d_ikh_grp' % (jointName, m + 1 ), mo = True, sr = ('x','y','z') )
			cmds.setAttr( '%s_segment_%d_ikh_grp_parentConstraint1.%s_lower_ctrl_const_grpW0' % (jointName, m + 1, joint2Name ), W0 )
			cmds.setAttr( '%s_segment_%d_ikh_grp_parentConstraint1.%s_bendy_ctrl_const_grpW1' % (jointName, m + 1, jointName ), W1 )
			
			#twist
			cmds.select( '%s_segment_%d_ikh' % (jointName, (m + 1)), r = True )
			cmds.rename( groupSpecial(), '%s_segment_%d_ikh_rot_grp' % ( jointName, (m + 1)) )
			cmds.select( '%s_segment_%d_ikh_rot_grp' % (jointName, (m + 1)), '%s_segment_%d_ikh' % (jointName, (m + 1)), r = True )
			nm_alignLRAs()
			
			cmds.createNode ('multiplyDivide', n = '%s_segment_%d_md' % (jointName, (m + 1)) )
			cmds.createNode ('addDoubleLinear', n = '%s_segment_%d_adl' % (jointName, (m + 1)) )
			cmds.createNode ('multDoubleLinear', n = '%s_segment_%d_twist_mdl' % (jointName, (m + 1)) )
			
			cmds.setAttr('%s_segment_%d_md.input2X' % (jointName, (m + 1)), W1 )
			cmds.setAttr('%s_segment_%d_md.input2Y' % (jointName, (m + 1)), W0 )
			
			cmds.connectAttr('%s_bendy_ctrl.rotate%s' % (jointName, prim), '%s_segment_%d_md.input1X' % (jointName, (m + 1)) )
			cmds.connectAttr('%s_ctrl.rotate%s' % (joint2Name, prim), '%s_segment_%d_md.input1Y' % (jointName, (m + 1)) )
			cmds.connectAttr('%s_segment_%d_md.outputX' % (jointName, (m + 1)), '%s_segment_%d_adl.input1' % (jointName, (m + 1)) )
			cmds.connectAttr('%s_segment_%d_md.outputY' % (jointName, (m + 1)), '%s_segment_%d_adl.input2' % (jointName, (m + 1)) )
			cmds.connectAttr('%s_twist_mdl.output' % jointName, '%s_segment_%d_twist_mdl.input1' % (jointName, (m + 1)) )
			cmds.connectAttr('%s_segment_%d_adl.output' % (jointName, (m + 1)), '%s_segment_%d_twist_mdl.input2' % (jointName, (m + 1)) )
			cmds.connectAttr('%s_segment_%d_twist_mdl.output' % (jointName, (m + 1)), '%s_segment_%d_ikh_rot_grp.rotate%s' % (jointName, (m + 1), prim) )
			
			d -= 1
			m -= 1
			x -= 1
		i += 1
	#group cluster and ikh for the last ctrl
	i = 0

	while( i < num ):
		cmds.select( babies[i], r = True )
		cmds.pickWalk( d = 'up' )
		babyMama = str(cmds.ls( sl = True ))[3:][:-2]
		cmds.select( '%s_segment_%d_curve_tipClusterHandle_grp' % (babyMama, s), '%s_segment_%d_ikh' % (babyMama, s), r = True )
		groupSpecial()
		cmds.parentConstraint( '%s_ctrl' % (babies[i]), '%s_segment_%d_ikh_grp' % (babyMama, s), mo = True, sr = ('x','y','z') )
		i += 1
		
	#middle segment
	i = 0
	if( s%2 == 0 ):
		cmds.select( joints, r = True )
		cmds.select( babies, d = True )
		parents = cmds.ls( sl = True )
		while ( i < n ):
			parent = parents[i]
			cmds.select( '%s_segment_*_joint' % parent )
			j = []
			j = cmds.ls( sl = True )
			j = str(j[1])
			tx = abs(cmds.getAttr( '%s.tx' % j ))
			ty = abs(cmds.getAttr( '%s.ty' % j ))
			tz = abs(cmds.getAttr( '%s.tz' % j ))

			if( tx > .001 ):
				prim = 'X'
			if( ty > .001):
				prim = 'Y'
			if( tz > .001 ):
				prim = 'Z'	

			#translate
			cmds.parentConstraint( '%s_bendy_ctrl_const_grp' % parent, '%s_segment_%d_ikh_grp' % ( parent, (s/2)), mo = True, sr = ('x','y','z') )
			
			#twist
			cmds.select( '%s_segment_%d_ikh' % ( parent, (s/2)), r = True )
			cmds.rename( groupSpecial(), '%s_segment_%d_ikh_rot_grp' % ( parent, (s/2)) )
			cmds.select( '%s_segment_%d_ikh_rot_grp' % ( parent, (s/2)), '%s_segment_%d_ikh' % ( parent, (s/2)), r = True )
			nm_alignLRAs()
			
			cmds.createNode ('multDoubleLinear', n = '%s_segment_%d_twist_mdl' % ( parent, (s/2)) )
			
			cmds.connectAttr('%s_twist_mdl.output' % parent, '%s_segment_%d_twist_mdl.input1' % ( parent, (s/2)) )
			cmds.connectAttr('%s_bendy_ctrl.rotate%s' % (parent, prim), '%s_segment_%d_twist_mdl.input2' % ( parent, (s/2)))
			cmds.connectAttr('%s_segment_%d_twist_mdl.output' % ( parent, (s/2)), '%s_segment_%d_ikh_rot_grp.rotate%s' % ( parent, (s/2), prim) )

			i += 1

	cmds.select( "*_segment_*_curve", r = True )
	curves = []
	curves = cmds.ls( sl = True )
	curveNum = len(curves)
	i = 0
	while( i < curveNum ):
		cmds.setAttr( '%s.inheritsTransform' % curves[i], 0 )
		i += 1

	if cmds.objExists( 'curve_segment_dnt_grp' ):
		cmds.parent( cmds.ls( sl = True ), 'curve_segment_dnt_grp' )
	else:
		cmds.group( n = 'curve_segment_dnt_grp' )

	
	#make joint_segment_grps
	i = 0
	while( i < n ):
		cmds.select( '%s_segment_*_ikh_grp' % parents[i], '%s_bendy_ctrl_orientPad' % parents[i], '%s_ctrl_orientPad' % parents[i], r = True )
		cmds.select( '%s_segment_1_ikh_grp' % parents[i], add = True )
		cmds.rename( groupSpecial(), '%s_segment_grp' % parents[i] )
		cmds.parentConstraint( parents[i], '%s_segment_grp' % parents[i], mo = True )
		i += 1
	i = 0
	while( i < num ):
		cmds.select( babies[i], r = True )
		cmds.pickWalk( d = 'up' )
		babyMama = str(cmds.ls( sl = True ))[3:][:-2]
		cmds.parent( '%s_ctrl_orientPad' % babies[i], '%s_segment_grp' % babyMama )
		i += 1
	
	if cmds.objExists( 'main_ctrl_const_grp' ):
		cmds.parent( '**_ctrl_const_grp_orientPad', 'main_ctrl_const_grp' )
	else:
		cmds.select( '**_ctrl_const_grp_orientPad', r = True )
		cmds.group ( n = 'main_ctrl_const_grp' )

	if cmds.objExists( 'main_segment_grp' ):
		cmds.select('**_segment_grp', r = True )
		cmds.select( 'main_segment_grp', d = True )
		grps = cmds.ls(sl = True)
		cmds.parent( grps, 'main_segment_grp' )
	else:
		cmds.select( '**_segment_grp', r = True )
		cmds.group( n = 'main_segment_grp' )

	i = 0
	elders = []
	while( i < n ):
		cmds.select( parents[i], r = True )
		b = 0
		while( b == 0 ):
			gp = cmds.ls( sl = True )
			cmds.pickWalk( d = 'up' )
			root = cmds.ls( sl = True )
			if( gp == root ):
				b = 1
		elders.append(root)
		i += 1
	roots = []
	for eld in elders:
		if eld not in roots:
			roots.append(eld)
			
	num = len(roots)
	i = 0
	while (i < num):
		roots[i] = str(roots[i])[3:][:-2]
		i += 1

	if( globalScale != '' ):	
		gs, sep, tail = globalScale.partition('.')	
		gsPos = cmds.xform( gs, q = True, piv = True, ws = True )
		if cmds.objExists( 'joint_scale_grp' ):
			cmds.parent( roots, 'joint_scale_grp' )
			cmds.select( 'joint_scale_grp', r = True )
			cmds.xform( os = True, piv = gsPos[0:3] )
		else:
			cmds.group( em = True, n = 'joint_scale_grp' )
			cmds.parent( roots, 'joint_scale_grp' )
			cmds.select( 'joint_scale_grp', r = True )
			cmds.xform( os = True, piv = gsPos[0:3] )
			cmds.parent( 'main_ctrl_const_grp', 'main_segment_grp', gs )
			cmds.scaleConstraint( gs, 'joint_scale_grp', mo = True )
		
	seg = cmds.intSliderGrp( "seg", q = True, v = True ) + 1
	cmds.select( '*_segment_*_joint', r = True )
	cmds.select( '*_segment_%d_joint' % seg, d = True )	
	if cmds.objExists( 'segmentBindSet' ):
		cmds.delete( 'segmentBindSet' )
		cmds.sets( n = 'segmentBindSet')
	else:
		cmds.sets( n = 'segmentBindSet' )
	
	print 'huzzah!'
 def pStopCallback(*pArgs):
     print 'Stopped Recording.'
     mc.scriptEditorInfo(writeHistory=False)
     outputField(enable=False)
 def pRecordCallback(*pArgs):
     print 'Recording...'
     fileHistDir = mc.fileDialog2(fileMode=0)
     savingDir = fileHistDir[0]
     userHist = mc.scriptEditorInfo(historyFilename=savingDir,
                                    writeHistory=True)
Esempio n. 18
0
def dynamicTab(*arg):
    cmds.frameLayout(label='FX', cll=1, cl=0, w=290)
    cmds.columnLayout()
    cmds.button()
    cmds.setParent('..')
    cmds.setParent('..')


#UI
try:
    if cmds.window(mainwindow, ex=True):
        cmds.deleteUI(mainwindow, wnd=True)
        cmds.deleteUI(checkTools, wnd=True)
except:
    #print 'Nothing mainWindow'
    cmds.scriptEditorInfo(clearHistory=True)

mainwindow = cmds.window(title="WoHeYun", mnb=True, mxb=False, sizeable=0)
mainLayout = cmds.columnLayout(w=250, h=340)
cmds.columnLayout(h=90, bgc=(0, 0, 0))
cmds.symbolButton(enable=1,
                  command=visitHomePage,
                  image="icons/woheyunlogo.png",
                  ann='www.woheyun.com')
cmds.setParent('..')
cmds.text(l='www.woheyun.com',
          h=15,
          w=289,
          fn='boldLabelFont',
          bgc=(0.15, 0.15, 0.15))  #
Esempio n. 19
0
    def loadUsingCmdsAndReturnInfoDict(self, uiFile):
        
        ## Remember where stuff was printing before
        seFile = 'c:/users/joe/mmmmScriptEditorHistory.txt'
        
        oldStatusOfHistoryFilename = cmds.scriptEditorInfo( query=True, historyFilename=True )
        oldStatusOfWriteHistory = cmds.scriptEditorInfo( query=True, writeHistory=True )

        ## Redirect printing        
        cmds.scriptEditorInfo( historyFilename=seFile )
        cmds.scriptEditorInfo( writeHistory=1 )
        
        cmds.scriptEditorInfo(clearHistoryFile=True)
        design = cmds.loadUI( uiFile=uiFile, v=True )
        
        ## Restore remembered old print location
        cmds.scriptEditorInfo( historyFilename=oldStatusOfHistoryFilename )
        cmds.scriptEditorInfo( writeHistory=oldStatusOfWriteHistory )
        
        fh = open(seFile,'r')
        printed = fh.read()
        fh.close()
        uiElements = self.splitUiPrintout( printed )

        result = { 'design':design, 'elements':uiElements }
            
        return result
Esempio n. 20
0
def IMPORTFILE(outputReference, listImportWidget, batchMode, home):
    py.scriptEditorInfo(suppressWarnings=1, e=1)
    validSelection = 0
    animationSelection = True
    if (str(listImportWidget) != "none" and
        ("." not in str(listImportWidget) or "<" in str(listImportWidget))):
        #IF FILE NAME ISN'T PROVIDED BY OUTSIDE SOURCES, GET IT FROM LIBRARY
        try:
            selectedAnimation = listImportWidget.currentItem().text()
        except:
            animationSelection = False
    customFile = home + "CUSTOM.json" if (".json"
                                          not in home.split("/")[-1]) else home
    customFileCheck = py.file(customFile, q=1, ex=1)
    if (customFileCheck == 1):
        with open(customFile, 'r') as f:
            line = json.load(f)
    if (outputReference == "none" and animationSelection == True):
        outputReference = line['IMPORT FILE (PATH)'] + selectedAnimation
    #GET RIG PATH FROM CUSTOM (USE "LITE" PATH IF IN BATCH MODE)
    rigPath = line['RIG (FULL NAME)']
    rigLitePath = rigPath.replace("CHAR_", "LITE_")
    if (py.file(rigLitePath, q=1, ex=1) == 1 and line['EXPORT AS .MA'] == 0
            and batchMode == 1 and animationSelection == True):
        rigPath = rigLitePath
    inputNameSpace = "inputFile"
    outputNameSpace = "outputFile"
    i = 1
    while (py.namespace(exists=outputNameSpace) == 1):
        outputNameSpace = outputNameSpace + str(i)
        i += 1
    i = 1
    while (py.namespace(exists=inputNameSpace) == 1):
        inputNameSpace = inputNameSpace + str(i)
        i += 1
    #IF SELECTED, CHECK NAMESPACE IF CONTROLLER IS VALID
    selections = py.ls(sl=1)
    if (selections != [] and animationSelection == True):
        i = 0
        while (i < len(selections)):
            RiGGiE = py.listAttr(selections[i], st=["RiGGiE"], r=1)
            if (isinstance(RiGGiE, list) == 1):
                selections = selections[i]
                try:
                    filePath = py.referenceQuery(selections, filename=1)
                    if (":" in selections):
                        name = selections.split(":")[-1]
                    else:
                        name = selections
                    if (len(selections) > len(name)):
                        nameSpace = selections[0:(len(selections) - len(name))]
                    else:
                        nameSpace = ""
                    if ("_" in nameSpace):
                        correctedName = nameSpace.replace("_", "")
                        py.file(filePath,
                                referenceNode="nameSpace",
                                namespace=correctedName,
                                e=1)
                        inputNameSpace = correctedName
                    else:
                        inputNameSpace = nameSpace
                except:
                    inputNameSpace = "none"
                validSelection = 1
                break
            if (i == len(selections) - 1):
                selections = []
                py.headsUpMessage(
                    '"No valid controllers selected..." - HiGGiE', t=2)
                print '"No valid controllers selected..." - HiGGiE'
            i += 1
    #REFERENCE IN THE INPUT RIG (TARGET) AND output RIG (ANIMATED)
    if ((py.file(rigPath, q=1, ex=1) == 1 or inputNameSpace == "none")
            and py.file(outputReference, q=1, ex=1) == 1
            and animationSelection == True):
        #try:#IF FAILS, THEN USER IS IMPORTING THE SAME FILE INTO ITSELF
        py.file(outputReference,
                namespace=outputNameSpace,
                prompt=0,
                mnp=1,
                iv=1,
                gr=1,
                r=1)
        referenceGroup = py.ls(sl=1)[0]
        py.setAttr(referenceGroup + ".v", 0)
        try:
            firstItem = py.listRelatives(referenceGroup,
                                         type="joint",
                                         c=1,
                                         s=0)[-1]
        except:
            firstItem = py.listRelatives(referenceGroup,
                                         type="joint",
                                         ad=1,
                                         s=0)[-1]
        nameSpaceBreakdown = firstItem.split(":")[:-1]
        officialOutputNameSpace = ""
        i = 0
        while (i < len(nameSpaceBreakdown)):
            officialOutputNameSpace = officialOutputNameSpace + nameSpaceBreakdown[
                i] + ":"
            i += 1
        outputNameSpace = officialOutputNameSpace[:-1]
        #IMPORT INPUT RIG IF NO RIG IS SELECTED
        if (inputNameSpace != "none" and validSelection == 0):
            initialObjects = py.ls(type="transform", o=1)
            py.file(rigPath,
                    namespace=inputNameSpace,
                    prompt=0,
                    mnp=1,
                    iv=1,
                    r=1)
        #FIND OFFICIAL NAMESPACE OF INPUT RIG
        if (selections == []):
            allObjects = py.ls(type="transform", o=1)
            allTransforms = list(set(allObjects) - set(initialObjects))
            i = 0
            while (i < len(allTransforms)):
                if ("_" in allTransforms[i]):
                    if (allTransforms[i].split("_")[-1] == "CTRL"):
                        rigController = allTransforms[i]
                        break
                i += 1
            if (":" in rigController):
                name = rigController.split(":")[-1]
                inputNameSpace = rigController[0:(len(rigController) -
                                                  len(name))]
            else:
                inputNameSpace = "none"
            selections = rigController
        joints = py.ls(outputNameSpace + ":*", type="joint")
        if (joints != []):
            py.select(selections, r=1)
            animationTransfer.ANIMATIONTRANSFER(inputNameSpace,
                                                outputNameSpace,
                                                outputReference, home)
        else:
            py.headsUpMessage('"No joints found in animated file..." - HiGGiE',
                              t=2)
            print '"No joints found in animated file..." - HiGGiE'
        #except:
        #    py.headsUpMessage('"Can not reference the same file into itself." - HiGGiE', t=2);
        #    print '"Can not reference the same file into itself." - HiGGiE';
    elif (animationSelection == False):
        py.headsUpMessage(
            '"You must select a valid animation in the library." - HiGGiE',
            t=2)
        print '"You must select a valid animation in the library." - HiGGiE'
    else:
        py.headsUpMessage('"Import file(s) do not exist..." - HiGGiE', t=2)
        print '"Import file(s) do not exist..." - HiGGiE'
Esempio n. 21
0
    def loadUsingCmdsAndReturnInfoDict(self, uiFile):

        ## Remember where stuff was printing before
        seFile = 'c:/users/joe/mmmmScriptEditorHistory.txt'

        oldStatusOfHistoryFilename = cmds.scriptEditorInfo(
            query=True, historyFilename=True)
        oldStatusOfWriteHistory = cmds.scriptEditorInfo(query=True,
                                                        writeHistory=True)

        ## Redirect printing
        cmds.scriptEditorInfo(historyFilename=seFile)
        cmds.scriptEditorInfo(writeHistory=1)

        cmds.scriptEditorInfo(clearHistoryFile=True)
        design = cmds.loadUI(uiFile=uiFile, v=True)

        ## Restore remembered old print location
        cmds.scriptEditorInfo(historyFilename=oldStatusOfHistoryFilename)
        cmds.scriptEditorInfo(writeHistory=oldStatusOfWriteHistory)

        fh = open(seFile, 'r')
        printed = fh.read()
        fh.close()
        uiElements = self.splitUiPrintout(printed)

        result = {'design': design, 'elements': uiElements}

        return result
Esempio n. 22
0
def createUI(pWindowTitle):

    windowID = 'myWindowID'

    if mc.window(windowID, exists=True):
        mc.deleteUI(windowID)

    mc.window(windowID,
              title=pWindowTitle,
              sizeable=True,
              resizeToFitChildren=True,
              width=200)

    # OPENING ANS SAVING WINDOWS
    def pOpenFileCallback(*pArgs):
        fileOutput = pm.fileDialog2(fileMode=1)  #fileOutput[0]
        myFile = "X:/Documents/SchoolWork/LMU/Fall2016/PipelineCS/FinalTools/history.txt"
        #string $filePath = myFile;
        #$fileId = "`mm.fopen $filePath "r"`";

    def pSaveFileCallback(*pArgs):
        pm.fileDialog2(fileMode=0)

    def pPastaCallback(*pArgs):
        mm.eval("sphere -radius 3;")

    mc.menuBarLayout('Meun')
    mc.menu('File')
    mc.menuItem('Open', command=pOpenFileCallback)
    mc.menuItem('Save As...', command=pSaveFileCallback)
    mc.menuItem('CloseMM')
    mc.menu('Edit')
    mc.menuItem('Copy')
    mc.menuItem('Pasta', command=pPastaCallback)

    mc.rowColumnLayout(numberOfColumns=1,
                       columnWidth=(1, 400),
                       columnOffset=(1, 'left', 3))

    # MENUBAR LAYOUT
    def pRecordCallback(*pArgs):
        print 'Record button pressed.'
        fileHistDir = "X:/Documents/SchoolWork/LMU/Fall2016/PipelineCS/FinalTools/history.txt"
        userHist = mc.scriptEditorInfo(historyFilename=fileHistDir,
                                       writeHistory=True)

    def pExecuteCallback(*pArgs):
        mc.scriptEditorInfo(writeHistory=False)
        print 'Execute button pressed.'

    def pClearCallback(*pArgs):
        print 'Clear button pressed.'
        outputField(clear=True)

    mc.separator(h=10, style="none")

    mc.rowLayout(numberOfColumns=3)
    mc.button(label='Record',
              width=195,
              backgroundColor=(50, 0, 0),
              command=pRecordCallback)
    mc.button(label='Execute',
              width=195,
              backgroundColor=(0, 50, 0),
              command=pExecuteCallback)
    mc.setParent("..")

    mc.separator(h=10, style="none")

    mc.text(label='SELECTED STEPS')

    output = 'test test test'

    def pUpdateOutputField(*pArgs):
        #outputField = mc.cmdScrollFieldExecuter(width= 395, height=400, showLineNumbers=True, sw=True, text= output)
        outputField = mc.cmdScrollFieldReporter(width=395,
                                                height=400,
                                                echoAllCommands=True)

    pUpdateOutputField()

    mc.separator(h=10, style="none")

    #mc.button(label= 'Execute', width=395, backgroundColor=(0, 50, 0), command=pExecuteCallback)
    mc.button(label='Clear', width=395, command=pClearCallback)

    #mc.textScrollList(append=[''])
    mc.scriptEditorInfo(input="")

    mc.separator(h=10, style='none')

    mc.showWindow()
Esempio n. 23
0
 def pExecuteCallback(*pArgs):
     mc.scriptEditorInfo(writeHistory=False)
     print 'Execute button pressed.'
Esempio n. 24
0
 def pRecordCallback(*pArgs):
     print 'Record button pressed.'
     fileHistDir = "X:/Documents/SchoolWork/LMU/Fall2016/PipelineCS/FinalTools/history.txt"
     userHist = mc.scriptEditorInfo(historyFilename=fileHistDir,
                                    writeHistory=True)
Esempio n. 25
0
def fileWithLog(*args):
	""" open file, create log and report number of errors and warnings
		returns   (False, None) if no problems were encountered  
	"""
	result = False
	batch = cmds.about(batch=True)
	err = None	
	Lrequires = []
	Lwarnings = []
	Lerrors = []
	try:
		cmds.file(new=True, force=True) 
	except RuntimeError:
		scenefilename = cmds.file(sn=True)
		print '%s is not a new scene, has unsaved changes' % scenefilename
		pass
	# save the log file to a temp directory	
	scriptEditorLog = os.path.join(tempfile.gettempdir(), 'scriptEditor.log')
	# scriptEditorLog = ''.join([cmds.internalVar(userTmpDir=True), 'scriptEditor.log'])
	# delete the log file if it exists 
	try:
		os.remove(scriptEditorLog) 
	# ignore errors if the file does not exist
	except OSError:
		pass
	# if we're in GUI mode write the outut of the script editor to a log file
	if batch:
		print 'we\'re soooo... in batch mode'
		# sys.stderr = open(scriptEditorLog, w)
		
	cmds.scriptEditorInfo(historyFilename=scriptEditorLog, writeHistory=True)
	# open a scene file,  if a file name is provided, use it	
	try:
		scenefilename = args[0] 
	except IndexError:	  
		multipleFilters = "Maya Files (*.ma *.mb);;Maya ASCII (*.ma);;Maya Binary (*.mb);;All Files (*.*)"
		scenefilename = cmds.fileDialog2(fileFilter=multipleFilters, fileMode=1, okCaption='Open',caption='Open a Maya scene file for certification')
	# open the scene file	
	cmds.file(scenefilename[0],open=True, force=True)
	# turn off the file logging
	cmds.scriptEditorInfo(historyFilename=scriptEditorLog, writeHistory=False)
	
	
	openfile = open(scriptEditorLog, 'r')
	lines = openfile.readlines()
	# check for requires statements in the log
	requires = map((lambda x: 'requires' in x), lines)  
	if True in requires:
		# find all True in requires append the lines with corresponding index to list 
		i = -1
		try:
			while True:
				i = requires.index(True, i+1)
				Lrequires.append(lines[i])
				#print '\t', lines[i]
		# stop when we reach the end of the list
		except ValueError:
				pass				  
	warnings = map((lambda x: 'Warning:' in x), lines)
	if True in warnings:
		result = True
		i = -1
		try:
			while True:
				i = warnings.index(True, i+1)
				Lwarnings.append(lines[i])
				#print '\t', lines[i]
		# stop when we reach the end of the list
		except ValueError:
				pass
				
	errors = map((lambda x: '# Error:' in x), lines)
	if True in errors:	
		result = True
		i = -1
		try:
			while True:
				i = errors.index(True, i+1)
				Lerrors.append(lines[i])
		except ValueError:
				pass
	# close the log file
	openfile.close() 
	return result, Lrequires, Lwarnings, Lerrors
Esempio n. 26
0
def _suppressWarn(sw):
    """
	"""
    if exc == 'mayapy.exe':
        cmds.scriptEditorInfo(sw=sw)
Esempio n. 27
0
def clear_nodes(*args):
    cmds.scriptEditorInfo(sw=True, si=True, sr=True, ssw=True, se=True)
    mel.eval(
        'hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes");')
    cmds.scriptEditorInfo(sw=False, si=False, sr=False, ssw=False, se=False)
Esempio n. 28
0
 def pStopCallback(*pArgs):
     mc.scriptEditorInfo(writeHistory=False)
     print 'Stopped Recording.'
Esempio n. 29
0
def bendy_proc():
    cmds.scriptEditorInfo(suppressWarnings=True)
    global globalScale
    globalScale = cmds.textField("textField", q=True, tx=True)

    #get the selected objects and add them
    tsl = []
    tsl = cmds.textScrollList("tsList", q=True, ai=True)
    cmds.textScrollList("tsList", e=True, di=("(only works on joints)"))

    #select the textScrollList
    if (len(tsl) > 0):
        list = ('')

        for item in tsl:
            list += ('"' + item)
            list += '", '

        list = list[:-2]
        list = list.replace("(only works on joints)", "")
        list = list[4:]
        list = ('cmds.select(' + list + ', r = True )')
    eval(list)

    #list and count only the joints in tsList
    joints = []
    joints = cmds.ls(sl=True, type='joint')
    num = len(joints)

    #isolates the bottom most child joints in tsList
    i = 0
    #a = 0
    children = []
    while (i < num):
        pod = cmds.select(joints[i], hi=True)
        pods = cmds.ls(sl=True, type='joint')
        hi = len(pods)
        f = 0
        b = 1
        while (f == 0):
            cmds.select(pods[hi - b], r=True)
            bottom = cmds.ls(sl=True)
            if any(ch in bottom for ch in joints):
                f = 1
            b += 1
        cmds.select(bottom, r=True)
        cmds.pickWalk(d='down')
        bottom = cmds.ls(sl=True)
        children.append(str(bottom)[3:][:-2])
        i += 1

    #Babies!? Babies are childless.
    global babies
    babies = []
    for b in children:
        if b not in babies:
            babies.append(b)

    num = len(babies)
    i = 0
    while (i < num):
        babies[i] = str(babies[i])
        i += 1

    cmds.select(joints, r=True)
    cmds.select(babies, d=True)
    parents = cmds.ls(sl=True)

    n = len(parents)
    i = 0
    while (i < n):
        child = cmds.pickWalk(parents[i], d='down')
        cmds.select(parents[i], child, r=True)
        split()
        getBent()
        i += 1

    #organizes end controls that are not at root
    i = 0
    while (i < n):
        cmds.select('%s_segment_*_joint' % parents[i])
        seg = []
        seg = cmds.ls(sl=True)
        segNum = len(seg)
        cmds.select(parents[i], r=True)
        pick = cmds.ls(sl=True)
        cmds.pickWalk(d='up')
        check = cmds.ls(sl=True)
        endSeg = str(check[0])
        jointName = seg[0][:-16]
        if (pick != check):
            if any(pa in check for pa in parents):
                cmds.parent(
                    '%s_segment_%d_curve_tipClusterHandle_grp' %
                    (endSeg, segNum - 1),
                    '%s_segment_%d_ikh' % (endSeg, segNum - 1),
                    '%s_ctrl' % jointName)
        i += 1

    #create ik/cluster groups
    i = 0
    while (i < n):
        q = 0
        cmds.select('%s_segment_*_joint' % parents[i])
        segLen = (len(cmds.ls(sl=True)) - 1)
        while (q < segLen - 1):
            global s
            s = cmds.intSliderGrp("seg", q=True, v=True)
            tac = 1
            cmds.select('%s_segment_*_joint' % parents[i])
            segs = []
            segs = cmds.ls(sl=True)
            tac = 0
            if (q >= 9):
                tac = 1
            jointName = segs[q][:-16 - tac]
            cmds.select(
                '%s_segment_%d_curve_tipClusterHandle_grp' % (jointName,
                                                              (q + 1)),
                '%s_segment_%d_curve_baseClusterHandle_grp' % (jointName,
                                                               (q + 2)),
                '%s_segment_%d_ikh' % (jointName, (q + 1)),
                r=True)
            groupSpecial()
            q += 1

        x = (s / 2) - 1
        d = 0
        #create constraints that control bend:
        #upper segment
        while (d < (s / 2) - 1):
            y = (s / x) - 1
            W0 = (1 / y)
            W1 = 1 - W0
            cmds.select('%s_segment_*_joint' % parents[i])
            tac = 0

            j = []
            j = cmds.ls(sl=True)
            j = str(j[1])
            tx = abs(cmds.getAttr('%s.tx' % j))
            ty = abs(cmds.getAttr('%s.ty' % j))
            tz = abs(cmds.getAttr('%s.tz' % j))

            if (tx > .001):
                prim = 'X'
            if (ty > .001):
                prim = 'Y'
            if (tz > .001):
                prim = 'Z'

            if (s > 9):
                tac = 1
            segs = []
            segs = cmds.ls(sl=True)
            jointName = segs[q][:-16 - tac]

            #translate
            cmds.parentConstraint('%s_upper_ctrl_const_grp' % jointName,
                                  '%s_bendy_ctrl_const_grp' % jointName,
                                  '%s_segment_%d_ikh_grp' % (jointName, d + 1),
                                  mo=True,
                                  sr=('x', 'y',
                                      'z'))  ###Make sr = xyz - primary axis
            cmds.setAttr(
                '%s_segment_%d_ikh_grp_parentConstraint1.%s_upper_ctrl_const_grpW0'
                % (jointName, d + 1, jointName), W0)
            cmds.setAttr(
                '%s_segment_%d_ikh_grp_parentConstraint1.%s_bendy_ctrl_const_grpW1'
                % (jointName, d + 1, jointName), W1)

            #twist
            cmds.select('%s_segment_%d_ikh' % (jointName, (d + 1)), r=True)
            cmds.rename(groupSpecial(),
                        '%s_segment_%d_ikh_rot_grp' % (jointName, (d + 1)))
            cmds.select('%s_segment_%d_ikh_rot_grp' % (jointName, (d + 1)),
                        '%s_segment_%d_ikh' % (jointName, (d + 1)),
                        r=True)
            nm_alignLRAs()

            cmds.createNode('multiplyDivide',
                            n='%s_segment_%d_md' % (jointName, (d + 1)))
            cmds.createNode('addDoubleLinear',
                            n='%s_segment_%d_adl' % (jointName, (d + 1)))
            cmds.createNode('multDoubleLinear',
                            n='%s_segment_%d_twist_mdl' % (jointName, (d + 1)))

            cmds.setAttr('%s_segment_%d_md.input2X' % (jointName, (d + 1)), W1)
            cmds.setAttr('%s_segment_%d_md.input2Y' % (jointName, (d + 1)), W0)

            cmds.connectAttr('%s_bendy_ctrl.rotate%s' % (jointName, prim),
                             '%s_segment_%d_md.input1X' % (jointName, (d + 1)))
            cmds.connectAttr('%s_ctrl.rotate%s' % (jointName, prim),
                             '%s_segment_%d_md.input1Y' % (jointName, (d + 1)))
            cmds.connectAttr('%s_segment_%d_md.outputX' % (jointName, (d + 1)),
                             '%s_segment_%d_adl.input1' % (jointName, (d + 1)))
            cmds.connectAttr('%s_segment_%d_md.outputY' % (jointName, (d + 1)),
                             '%s_segment_%d_adl.input2' % (jointName, (d + 1)))
            cmds.connectAttr(
                '%s_twist_mdl.output' % jointName,
                '%s_segment_%d_twist_mdl.input1' % (jointName, (d + 1)))
            cmds.connectAttr(
                '%s_segment_%d_adl.output' % (jointName, (d + 1)),
                '%s_segment_%d_twist_mdl.input2' % (jointName, (d + 1)))
            cmds.connectAttr(
                '%s_segment_%d_twist_mdl.output' % (jointName, (d + 1)),
                '%s_segment_%d_ikh_rot_grp.rotate%s' % (jointName,
                                                        (d + 1), prim))

            x -= 1
            d += 1

        #lower segment
        x = (s / 2) - 1
        m = d + x
        while (d >= 1):
            y = (s / x) - 1
            W0 = (1 / y)
            W1 = 1 - W0
            cmds.select('%s_segment_*_joint' % parents[i])

            if (s > 8):
                tac = 1
            segs = []
            segs = cmds.ls(sl=True)
            jointName = segs[q + 1][:-16 - tac]

            cmds.select(jointName, r=True)
            cmds.pickWalk(d='down')
            joint2Name = cmds.ls(sl=True)
            joint2Name = str(joint2Name)[3:][:-2]

            #translate
            cmds.parentConstraint('%s_lower_ctrl_const_grp' % joint2Name,
                                  '%s_bendy_ctrl_const_grp' % jointName,
                                  '%s_segment_%d_ikh_grp' % (jointName, m + 1),
                                  mo=True,
                                  sr=('x', 'y', 'z'))
            cmds.setAttr(
                '%s_segment_%d_ikh_grp_parentConstraint1.%s_lower_ctrl_const_grpW0'
                % (jointName, m + 1, joint2Name), W0)
            cmds.setAttr(
                '%s_segment_%d_ikh_grp_parentConstraint1.%s_bendy_ctrl_const_grpW1'
                % (jointName, m + 1, jointName), W1)

            #twist
            cmds.select('%s_segment_%d_ikh' % (jointName, (m + 1)), r=True)
            cmds.rename(groupSpecial(),
                        '%s_segment_%d_ikh_rot_grp' % (jointName, (m + 1)))
            cmds.select('%s_segment_%d_ikh_rot_grp' % (jointName, (m + 1)),
                        '%s_segment_%d_ikh' % (jointName, (m + 1)),
                        r=True)
            nm_alignLRAs()

            cmds.createNode('multiplyDivide',
                            n='%s_segment_%d_md' % (jointName, (m + 1)))
            cmds.createNode('addDoubleLinear',
                            n='%s_segment_%d_adl' % (jointName, (m + 1)))
            cmds.createNode('multDoubleLinear',
                            n='%s_segment_%d_twist_mdl' % (jointName, (m + 1)))

            cmds.setAttr('%s_segment_%d_md.input2X' % (jointName, (m + 1)), W1)
            cmds.setAttr('%s_segment_%d_md.input2Y' % (jointName, (m + 1)), W0)

            cmds.connectAttr('%s_bendy_ctrl.rotate%s' % (jointName, prim),
                             '%s_segment_%d_md.input1X' % (jointName, (m + 1)))
            cmds.connectAttr('%s_ctrl.rotate%s' % (joint2Name, prim),
                             '%s_segment_%d_md.input1Y' % (jointName, (m + 1)))
            cmds.connectAttr('%s_segment_%d_md.outputX' % (jointName, (m + 1)),
                             '%s_segment_%d_adl.input1' % (jointName, (m + 1)))
            cmds.connectAttr('%s_segment_%d_md.outputY' % (jointName, (m + 1)),
                             '%s_segment_%d_adl.input2' % (jointName, (m + 1)))
            cmds.connectAttr(
                '%s_twist_mdl.output' % jointName,
                '%s_segment_%d_twist_mdl.input1' % (jointName, (m + 1)))
            cmds.connectAttr(
                '%s_segment_%d_adl.output' % (jointName, (m + 1)),
                '%s_segment_%d_twist_mdl.input2' % (jointName, (m + 1)))
            cmds.connectAttr(
                '%s_segment_%d_twist_mdl.output' % (jointName, (m + 1)),
                '%s_segment_%d_ikh_rot_grp.rotate%s' % (jointName,
                                                        (m + 1), prim))

            d -= 1
            m -= 1
            x -= 1
        i += 1
    #group cluster and ikh for the last ctrl
    i = 0

    while (i < num):
        cmds.select(babies[i], r=True)
        cmds.pickWalk(d='up')
        babyMama = str(cmds.ls(sl=True))[3:][:-2]
        cmds.select('%s_segment_%d_curve_tipClusterHandle_grp' % (babyMama, s),
                    '%s_segment_%d_ikh' % (babyMama, s),
                    r=True)
        groupSpecial()
        cmds.parentConstraint('%s_ctrl' % (babies[i]),
                              '%s_segment_%d_ikh_grp' % (babyMama, s),
                              mo=True,
                              sr=('x', 'y', 'z'))
        i += 1

    #middle segment
    i = 0
    if (s % 2 == 0):
        cmds.select(joints, r=True)
        cmds.select(babies, d=True)
        parents = cmds.ls(sl=True)
        while (i < n):
            parent = parents[i]
            cmds.select('%s_segment_*_joint' % parent)
            j = []
            j = cmds.ls(sl=True)
            j = str(j[1])
            tx = abs(cmds.getAttr('%s.tx' % j))
            ty = abs(cmds.getAttr('%s.ty' % j))
            tz = abs(cmds.getAttr('%s.tz' % j))

            if (tx > .001):
                prim = 'X'
            if (ty > .001):
                prim = 'Y'
            if (tz > .001):
                prim = 'Z'

            #translate
            cmds.parentConstraint('%s_bendy_ctrl_const_grp' % parent,
                                  '%s_segment_%d_ikh_grp' % (parent, (s / 2)),
                                  mo=True,
                                  sr=('x', 'y', 'z'))

            #twist
            cmds.select('%s_segment_%d_ikh' % (parent, (s / 2)), r=True)
            cmds.rename(groupSpecial(),
                        '%s_segment_%d_ikh_rot_grp' % (parent, (s / 2)))
            cmds.select('%s_segment_%d_ikh_rot_grp' % (parent, (s / 2)),
                        '%s_segment_%d_ikh' % (parent, (s / 2)),
                        r=True)
            nm_alignLRAs()

            cmds.createNode('multDoubleLinear',
                            n='%s_segment_%d_twist_mdl' % (parent, (s / 2)))

            cmds.connectAttr(
                '%s_twist_mdl.output' % parent,
                '%s_segment_%d_twist_mdl.input1' % (parent, (s / 2)))
            cmds.connectAttr(
                '%s_bendy_ctrl.rotate%s' % (parent, prim),
                '%s_segment_%d_twist_mdl.input2' % (parent, (s / 2)))
            cmds.connectAttr(
                '%s_segment_%d_twist_mdl.output' % (parent, (s / 2)),
                '%s_segment_%d_ikh_rot_grp.rotate%s' % (parent, (s / 2), prim))

            i += 1

    cmds.select("*_segment_*_curve", r=True)
    curves = []
    curves = cmds.ls(sl=True)
    curveNum = len(curves)
    i = 0
    while (i < curveNum):
        cmds.setAttr('%s.inheritsTransform' % curves[i], 0)
        i += 1

    if cmds.objExists('curve_segment_dnt_grp'):
        cmds.parent(cmds.ls(sl=True), 'curve_segment_dnt_grp')
    else:
        cmds.group(n='curve_segment_dnt_grp')

    #make joint_segment_grps
    i = 0
    while (i < n):
        cmds.select('%s_segment_*_ikh_grp' % parents[i],
                    '%s_bendy_ctrl_orientPad' % parents[i],
                    '%s_ctrl_orientPad' % parents[i],
                    r=True)
        cmds.select('%s_segment_1_ikh_grp' % parents[i], add=True)
        cmds.rename(groupSpecial(), '%s_segment_grp' % parents[i])
        cmds.parentConstraint(parents[i],
                              '%s_segment_grp' % parents[i],
                              mo=True)
        i += 1
    i = 0
    while (i < num):
        cmds.select(babies[i], r=True)
        cmds.pickWalk(d='up')
        babyMama = str(cmds.ls(sl=True))[3:][:-2]
        cmds.parent('%s_ctrl_orientPad' % babies[i],
                    '%s_segment_grp' % babyMama)
        i += 1

    if cmds.objExists('main_ctrl_const_grp'):
        cmds.parent('**_ctrl_const_grp_orientPad', 'main_ctrl_const_grp')
    else:
        cmds.select('**_ctrl_const_grp_orientPad', r=True)
        cmds.group(n='main_ctrl_const_grp')

    if cmds.objExists('main_segment_grp'):
        cmds.select('**_segment_grp', r=True)
        cmds.select('main_segment_grp', d=True)
        grps = cmds.ls(sl=True)
        cmds.parent(grps, 'main_segment_grp')
    else:
        cmds.select('**_segment_grp', r=True)
        cmds.group(n='main_segment_grp')

    i = 0
    elders = []
    while (i < n):
        cmds.select(parents[i], r=True)
        b = 0
        while (b == 0):
            gp = cmds.ls(sl=True)
            cmds.pickWalk(d='up')
            root = cmds.ls(sl=True)
            if (gp == root):
                b = 1
        elders.append(root)
        i += 1
    roots = []
    for eld in elders:
        if eld not in roots:
            roots.append(eld)

    num = len(roots)
    i = 0
    while (i < num):
        roots[i] = str(roots[i])[3:][:-2]
        i += 1

    if (globalScale != ''):
        gs, sep, tail = globalScale.partition('.')
        gsPos = cmds.xform(gs, q=True, piv=True, ws=True)
        if cmds.objExists('joint_scale_grp'):
            cmds.parent(roots, 'joint_scale_grp')
            cmds.select('joint_scale_grp', r=True)
            cmds.xform(os=True, piv=gsPos[0:3])
        else:
            cmds.group(em=True, n='joint_scale_grp')
            cmds.parent(roots, 'joint_scale_grp')
            cmds.select('joint_scale_grp', r=True)
            cmds.xform(os=True, piv=gsPos[0:3])
            cmds.parent('main_ctrl_const_grp', 'main_segment_grp', gs)
            cmds.scaleConstraint(gs, 'joint_scale_grp', mo=True)

    seg = cmds.intSliderGrp("seg", q=True, v=True) + 1
    cmds.select('*_segment_*_joint', r=True)
    cmds.select('*_segment_%d_joint' % seg, d=True)
    if cmds.objExists('segmentBindSet'):
        cmds.delete('segmentBindSet')
        cmds.sets(n='segmentBindSet')
    else:
        cmds.sets(n='segmentBindSet')

    print 'huzzah!'
Esempio n. 30
0
def playblastOnFarm(mayaScene, fileout='/tmp/playblast.tif', format='tif', width=640, height=480, start=None, end=None, panel=None):
    '''
    The method that gets called from a farm machine to perform a playblast.
    '''
    # Set up logging
    logLevel = logging.DEBUG
    logFormat = "[playblastOnFarm] %(asctime)-15s %(levelname)s -- %(message)s"
    logging.basicConfig(level=logLevel, format=logFormat)

    try:
        # Pipe script editor output to log
        cmds.scriptEditorInfo(wh=True, hfn='/dev/stderr')
        
        # Read Scene
        logging.info('Maya is opening file: ' + mayaScene)
        cmds.file(mayaScene, open=True, force=True)
        logging.info('File opened succesfully.')
        
        # Might be unecessary, but ensure the desired UI panel for playblasting
        if panel:
            cmds.setFocus(panel)
#         else:
#             # Create a new window in case for whatever reason there isn't one
#             window = cmds.window(title='playblastWindow')
#             layout = cmds.paneLayout()
#             panel = cmds.modelPanel()
#             editor = cmds.modelPanel(panel, q=True, modelEditor=True)
#             cmds.showWindow(window)
#             cmds.setFocus(window)

        # Check/set framerange
        if not start:
            start = cmds.playbackOptions(q=True, minTime=True)
        else:
            cmds.playbackOptions(e=True, minTime=float(start)) 
        if not end:
            end = cmds.playbackOptions(q=True, maxTime=True)
        else:
            cmds.playbackOptions(e=True, maxTime=float(end))

        logging.info('Frame range is %s-%s.' % (start, end))
        assert start < end, "End frame is not greater than start frame."

        # Set renderglobal imageformat
        cmds.setAttr('defaultRenderGlobals.imageFormat', IMAGE_FORMAT_DICT[format])
        logging.info('Image format: %s' % format)

        playblastArgs = {
                        'filename': fileout,
                        'startTime': start,
                        'endTime': end,
                        'format': 'image',
                        'widthHeight': [int(width), int(height)],
                        'percent': 100,
                        'viewer': False,
                        'offScreen': True,
                        'forceOverwrite': True
                        }
                        #'sequenceTime' = True
                        #'framePadding' = 4 (default)
                        #'rawFrameNumbers' = True (maybe)
        logging.info('Playblasting with arguments: %s' % playblastArgs)
        logging.debug('Playblasting with arguments: %s' % playblastArgs)
        cmds.playblast(**playblastArgs)
        logging.info('Playblast completed succesfully.')
        
    except Exception, e:
        logging.error(e)
Esempio n. 31
0
    def dpMoveAttr(self,
                   mode,
                   objList=None,
                   attrList=None,
                   verbose=False,
                   *args):
        """ Change order of attributes in order to move it to up or down in the list position.
        """
        # do ScriptEditor do not print Undo messages:
        cmds.scriptEditorInfo(suppressInfo=False)
        if not objList:
            # get current selected objects:
            objList = cmds.channelBox('mainChannelBox',
                                      query=True,
                                      mainObjectList=True)
        if objList:
            if not attrList:
                # get selected attributes from channelBox
                attrList = cmds.channelBox('mainChannelBox',
                                           query=True,
                                           selectedMainAttributes=True)
            if attrList:
                for obj in objList:
                    userDefAttrList = cmds.listAttr(obj, userDefined=True)
                    if userDefAttrList:
                        if not attrList[0] in userDefAttrList:
                            if verbose:
                                mel.eval(
                                    "warning \"Selected attribute " +
                                    str(attrList) +
                                    " is static and can not be moved, sorry.\";"
                                )
                        else:
                            cmds.scriptEditorInfo(suppressInfo=True)
                            # unlock all user defined attibutes before start the changing position:
                            lockAttrList = cmds.listAttr(obj,
                                                         userDefined=True,
                                                         locked=True)
                            if lockAttrList:
                                for lockAttr in lockAttrList:
                                    cmds.setAttr(obj + "." + lockAttr,
                                                 lock=False)
                            # start moving attributes
                            if mode == 0:  #down
                                if len(attrList) > 1:
                                    attrList.reverse()
                                    sortedList = attrList
                                if len(attrList) == 1:
                                    sortedList = attrList
                                for i in sortedList:
                                    attrLs = cmds.listAttr(obj,
                                                           userDefined=True)
                                    attrSize = len(attrLs)
                                    attrPos = attrLs.index(i)
                                    cmds.deleteAttr(obj, at=attrLs[attrPos])
                                    cmds.undo()
                                    for x in range(attrPos + 2, attrSize, 1):
                                        cmds.deleteAttr(obj, at=attrLs[x])
                                        cmds.undo()

                            elif mode == 1:  #up
                                for i in attrList:
                                    attrLs = cmds.listAttr(obj,
                                                           userDefined=True)
                                    attrSize = len(attrLs)
                                    attrPos = attrLs.index(i)
                                    if attrLs[attrPos - 1]:
                                        cmds.deleteAttr(obj,
                                                        at=attrLs[attrPos - 1])
                                        cmds.undo()
                                    for x in range(attrPos + 1, attrSize, 1):
                                        cmds.deleteAttr(obj, at=attrLs[x])
                                        cmds.undo()

                            # lock all user defined attibutes after the changing position:
                            if lockAttrList:
                                for lockAttr in lockAttrList:
                                    cmds.setAttr(obj + "." + lockAttr,
                                                 lock=True)
                    else:
                        if verbose:
                            mel.eval(
                                "warning \"We can only reorder added attributes by user.\";"
                            )
            else:
                if verbose:
                    mel.eval(
                        "warning \"Select one or more attributes in the Channel Box, please.\";"
                    )
        else:
            if verbose:
                mel.eval(
                    "warning \"Select one or more transform nodes to reorder attributes, please.\";"
                )
        # back ScritpEditor to show info:
        cmds.scriptEditorInfo(suppressInfo=True)
Esempio n. 32
0
def importMatrix():

    # autoKeyFrameが有効だと処理が重くなるため、autoKeyFrameをオフにする
    # あとで状態を復元するためにautoKeyFrameが有効かどうかを保存しておく
    isAutoKeyFrame =  cmds.autoKeyframe(query=True, state=True)
    cmds.autoKeyframe(state=False)
     
    # ジョイントを選択
    cmds.select(clear=True)
    cmds.select("|Hips1", add=True)
    cmds.select("|Spine", add=True)
    cmds.select("|Spine1", add=True)
    cmds.select("|Spine2", add=True)
    cmds.select("|Spine3", add=True)
    cmds.select("|Neck", add=True)
    cmds.select("|Neck1", add=True)
    cmds.select("|Head", add=True)
    cmds.select("|RightShoulder", add=True)
    cmds.select("|RightArm", add=True)
    cmds.select("|RightForeArm", add=True)
    cmds.select("|RightHand", add=True)
    cmds.select("|LeftShoulder", add=True)
    cmds.select("|LeftArm", add=True)
    cmds.select("|LeftForeArm", add=True)
    cmds.select("|LeftHand", add=True)
    cmds.select("|RightUpLeg", add=True)
    cmds.select("|RightLeg", add=True)
    cmds.select("|RightForeFoot", add=True)
    cmds.select("|RightToeBase", add=True)
    cmds.select("|LeftUpLeg", add=True)
    cmds.select("|LeftLeg", add=True)
    cmds.select("|LeftForeFoot", add=True)
    cmds.select("|LeftToeBase", add=True)

    selectedItem = cmds.ls(sl=1, long=1)
    sList = om.MGlobal.getActiveSelectionList()

    # 先に全ジョイントのMFnTransformをリスト化しとく
    lsFnTrs = list()
    iter = om.MItSelectionList(sList)
    while not iter.isDone():
        dagPath = iter.getDagPath()
        fnTrs = om.MFnTransform(dagPath)
        lsFnTrs.append(fnTrs)
        iter.next()

    # csvを読み込む
    o_file = open("C:/Users/0300091280/Desktop/predict.csv", 'r')
    reader = csv.reader(o_file)
    setFrame = int(cmds.playbackOptions(q=True, min=True))

    # scriptEditorへの出力を抑制
    cmds.scriptEditorInfo(suppressInfo=True, suppressResults=True) 

    for row in reader:
        offset = 0
        for i, c_fnTrs in enumerate(lsFnTrs):
            mat = om.MMatrix([float(row[offset+0]), float(row[offset+1]), float(row[offset+2]), 0.0,
                              float(row[offset+3]), float(row[offset+4]), float(row[offset+5]), 0.0,
                              float(row[offset+6]), float(row[offset+7]), float(row[offset+8]), 0.0,
                              float(row[offset+9]), float(row[offset+10]), float(row[offset+11]), 1.0])
            mat = om.MTransformationMatrix(mat)
            c_fnTrs.setTransformation(mat)
            cmds.setKeyframe(selectedItem[i], time=(setFrame, setFrame))
            offset += 12
        setFrame += 1
    o_file.close()

    if isAutoKeyFrame:
        cmds.autoKeyframe(state=True)