def atPoint(settings=None): '''Creates a context in which the user can click on an object in the scene and a point will be traced on that mesh, using either a follicle or the nearest point on the mesh. This function takes the same settings dictionary that getShortcut creates.''' # Test for plugin. if not pluginLoaded(): return if not settings: settings = {} if pointOnMesh: if cmd.draggerContext(CONTEXTNAME, q=1, ex=1): cmd.deleteUI(CONTEXTNAME) # I have found no way to test if an icon exists, other than to # just attempt to create something with that icon. kwargs = {'releaseCommand': partial(getPoint, settings=settings), 'cursor': 'crossHair', 'image1': 'arcTracerOnMesh.png'} try: cmd.draggerContext(CONTEXTNAME, **kwargs) except RuntimeError: kwargs['image1'] = None cmd.draggerContext(CONTEXTNAME, **kwargs) cmd.setToolTo(CONTEXTNAME) else: om.MGlobal.displayWarning("Could not find module pointOnMesh. You must install pointOnMesh to use this functionality.")
def getProjectedPoint(self, dragged): ''' gets the mouse position (in screen coordinates) and finds the projected point on the plane that is parallel to the camera (in world coordinates). ''' # if we first clicked inside the viewport if not dragged: mousePosition = cmds.draggerContext(self._mContext, query = True, anchorPoint = True) self._mView.viewToWorld(int(mousePosition[0]), int(mousePosition[1]), self._mRayPos, self._mRayDir) self.setOriginPoint() # if we are dragging the mouse else: if self._mOriginPt: mousePosition = cmds.draggerContext(self._mContext, query = True, dragPoint = True) modifier = cmds.draggerContext(self._mContext, query = True, modifier = True) self._mView.viewToWorld(int(mousePosition[0]), int(mousePosition[1]), self._mNear, self._mFar) self.planeLineIntersection(self._mNear, self._mFar, self._mOriginPt, self._mEye) mRadius = self._mOriginPt.distanceTo(self._mDragPt) cmds.setAttr(self._mVoroImpactShape + '.radius', mRadius) cmds.setAttr(self._mVoroImpactTrs + '.visibility', True) if modifier == 'shift': cmds.setAttr(self._mVoroImpactShader + '.color', 1.0, 0.0, 0.0, type = 'double3') cmds.setAttr(self._mVoroImpactShader + '.incandescence', 0.15, 0.0, 0.0, type = 'double3') cmds.setAttr(self._mVoroImpactTrs + '.overrideColor', 13) else: 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._mVoroImpactTrs + '.overrideColor', 14)
def onDrag(self): mods = cmds.getModifiers() if (mods & 4) > 0: pressPosition = cmds.draggerContext(self.ctxName, query=True, anchorPoint=True) dragPosition = cmds.draggerContext(self.ctxName, query=True, dragPoint=True) self.magCoeff += (float(dragPosition[0]) - float(pressPosition[0])) * 0.001 if (len(self.clickedPoints) > 1 and self.curve): self.modifyCurve() """ elif( len( self.clickedPoints ) > 1 and self.curve ): p = self.getClickedParams() if( mods & 1 ) > 0: self.clickedPoints[0] = p else: self.clickedPoints[1] = p self.modifyCurve() """ cmds.refresh(cv=True)
def TraceGestureRelease( self ): """ when the mouse is released, find the matching joint trajectory """ if debug>0: print("begin RELEASE") releasePosition = Vector( mc.draggerContext( 'TraceGesture', query=True, dragPoint=True) ).projectToPlane( self.trace[self.nearestRoot].normal, planePt=self.trace[self.nearestRoot].planePt ) if debug>0: print "release! ", releasePosition theTrace = self.trace[self.nearestRoot] selectedMotion = None if theTrace.closestJoint and theTrace.timespan and (theTrace.timespan[1]-theTrace.timespan[0]) > 1 and \ not mc.draggerContext( 'TraceGesture', query=True, modifier=True) == "ctrl": theDTW = theTrace.dtws[theTrace.closest] if debug > 0: print "closest = ", theTrace.closestJoint, theTrace.timespan if not mc.objExists("DTW_Y"): mc.group(n="DTW_Y",empty=True) for pt in theDTW.Y: loc = mc.spaceLocator(p=pt) mc.parent(loc,"DTW_Y") ## ghostJoint(trace[nearestRoot].closestJoint,trace[nearestRoot].timespan) # Build the motion curve and store it's name in the selectedMotions dictionary duration = [ int(theTrace.timespan[0]), int(theTrace.timespan[1]+1) ] keyframes = [ theTrace.searchList[theTrace.closestJoint].points[frame] for frame in range(duration[0],duration[1]) ] selectedMotion = bmt.CurveMotionTrace( theTrace.closestJoint, keys=keyframes ) #duration=theTrace.timespan ) else: self.ScrubToNearestTimeOnPath( releasePosition, self.nearestRoot, self.nearestPath ) cam2pop = self.CameraToPopDist() path = theTrace.searchList[self.nearestPath] pointKey = path.ClosestTimeTo(releasePosition) closestPoint = path.points[pointKey] closestPtOnPath = closestPoint.projectToPlane( theTrace.normal, planePt=theTrace.planePt ) mouse2path = (releasePosition - closestPtOnPath).mag() # if motion paths are visible and no drag happened # and releasePosition is very close to the path, # then select the whole motion path if self.motionPathsVisible[self.nearestRoot] and mouse2path < 0.3: # Build the motion curve and store it's name in the selectedMotions dictionary duration = [ mc.playbackOptions(q=True,min=True),mc.playbackOptions(q=True,max=True)+1 ] keyframes = [ theTrace.searchList[self.nearestPath].points[frame] for frame in range(duration[0],duration[1]) ] selectedMotion = bmt.CurveMotionTrace( self.nearestPath, keys=keyframes ) #duration=[mc.playbackOptions(q=True,min=True),mc.playbackOptions(q=True,max=True)] ) # if not scrubbing if not mc.draggerContext( 'TraceGesture', query=True, modifier=True) == "ctrl" and \ cam2pop >= self.viewFitDistance: # if trucked out, and mouse is clicked (w/ no drag) mc.select(self.nearestRoot) # zoom in on the nearest root for a better view mc.viewFit(fitFactor=2.5) # the invisible parts of the roots can artificially enlarge the BB, so truck in a little extra mc.select(clear=True) if selectedMotion: selectedMotionCurve = selectedMotion.construct(self.nearestPath) if not self.nearestRoot in self.selectedMotions.keys(): self.selectedMotions[self.nearestRoot] = [] mc.setAttr("%s_MotionTraces.visibility"%self.nearestRoot, 0) selectedMotionCurve = mc.rename(selectedMotionCurve, "%s_selection%d"%(self.nearestPath,len(self.selectedMotions[self.nearestRoot]))) self.selectedMotions[self.nearestRoot].append( selectedMotionCurve ) self.AddCustomAttr( selectedMotionCurve, "isTraceSelection", True ) self.AddCustomAttr( selectedMotionCurve, "interactTime", time.time()-self.startTime ) self.AddCustomAttr( selectedMotionCurve, "startFrame", duration[0] ) self.AddCustomAttr( selectedMotionCurve, "endFrame", duration[1] ) mc.select(cl=True)
def drag(self, *args): self.dragPoint = mc.draggerContext(self.draggerContext, query=True, dragPoint=True) #if this doesn't work, try getmodifier self.modifier = mc.draggerContext(self.draggerContext, query=True, modifier=True) self.x = ((self.dragPoint[0] - self.anchorPoint[0]) * self.multiplier) + self.defaultValue self.y = ((self.dragPoint[1] - self.anchorPoint[1]) * self.multiplier) + self.defaultValue if self.minValue is not None and self.x < self.minValue: self.x = self.minValue if self.maxValue is not None and self.x > self.maxValue: self.x = self.maxValue #dragString if self.modifier == 'control': if self.button == 1: self.dragControlLeft(*args) elif self.button == 2: self.dragControlMiddle(*args) elif self.modifier == 'shift': if self.button == 1: self.dragShiftLeft(*args) elif self.button == 2: self.dragShiftMiddle(*args) else: if self.button == 1: self.dragLeft() elif self.button == 2: self.dragMiddle() mc.refresh()
def duplicate_guide_ctx(ui): global SCALP global DESCRIPTION if cmds.draggerContext(_DUPLICATE_GUIDE_CTX, exists=True): cmds.deleteUI(_DUPLICATE_GUIDE_CTX) name = ui.xgen_description_lineEdit.text() if not name: pm.displayWarning("No Xgen IGS description selected") return if not pm.selected(): pm.displayWarning("Nothing selected to duplicate") return DESCRIPTION = xgen_handler.get_description(name) SCALP = xgen_handler.get_scalp(DESCRIPTION) cmds.draggerContext( _DUPLICATE_GUIDE_CTX, pressCommand=partial(duplicate_guide_rig, ui), dragCommand=partial(drag_guide_rig, ui, _DUPLICATE_GUIDE_CTX), releaseCommand=release_guide_rig, name=_DUPLICATE_GUIDE_CTX, cursor='crossHair', undoMode='step') cmds.setToolTo(_DUPLICATE_GUIDE_CTX)
def start_translate(): global CAMERA global MOVE_DATA global MOUSE_START if cmds.draggerContext(ZOOM_TRANSLATE, q=True, bu=True) == 1: cmds.setToolTo('selectSuperContext') cmds.warning( 'Use the middle mouse button to slide objects toward/away from camera' ) return sel = cmds.ls(sl=1, fl=1) # Probably should eventually put some logic here to validate the selection if len(sel) == 0: cmds.setToolTo('selectSuperContext') print 'Nothing selected' return active_panel = cmds.getPanel(wf=True) CAMERA = cmds.modelPanel(active_panel, q=True, cam=True) CAMERA = CAMERA.replace('Shape', '') target_loc = cmds.xform(CAMERA, q=True, ws=True, a=True, rp=True) destination_vec = om.MVector(target_loc) MOUSE_START = cmds.draggerContext(ZOOM_TRANSLATE, q=True, ap=True) for each in sel: loc = cmds.xform(each, q=True, ws=True, a=True, rp=True) vec = om.MVector(loc) diff_vec = vec - destination_vec MOVE_DATA[each] = [vec, diff_vec]
def __init__(self, uioptions, transformoptions, sourcelist, targetlist): ''' initial setup ''' #create the tool context if (mc.draggerContext(spPaint3dContextID, exists=True)): mc.deleteUI(spPaint3dContextID); mc.draggerContext(spPaint3dContextID, pressCommand=self.onPress, dragCommand=self.onDrag, releaseCommand=self.onRelease, name=spPaint3dContextID, cursor='crossHair', undoMode='step') #create context local options self.runtimeUpdate(uioptions, transformoptions, sourcelist, targetlist) #debug purpose self.reentrance = 0 #initialise world up vector if ( (mc.upAxis(q=True, axis=True)) == "y" ): self.worldUp = om.MVector (0,1,0); elif ( (mc.upAxis(q=True, axis=True)) == "z" ): self.worldUp = om.MVector (0,0,1); else: #can't figure out up vector mc.confirmDialog(title='Weird stuff happening', message='Not getting any proper info on what the current up vector is. Quitting...') sys.exit() #fetch current scene unit self.unit = mc.currentUnit(query=True, linear=True)
def __init__(self): """ Initializes the instance variables and sets up the dragger context. """ self.press_position = [0, 0, 0] self.drag_position = [0, 0, 0] self.interpolation_mode = options.load_interpolation_mode() self.overshoot = options.load_overshoot() self.live_preview = options.load_live_preview() if not g.plugin_path: g.refresh_plug_in_path() icon_path = g.plugin_path + '/icons/tweener-icon.png' cmds.draggerContext('tweenerToolContext', name='tweenerTool', pressCommand=self.press, dragCommand=self.drag, releaseCommand=self.release, finalize=self.finalize, space='screen', image1=icon_path, undoMode='step')
def __init__(self, uioptions, transformoptions, sourcelist, targetlist): ''' initial setup ''' #create the tool context if (mc.draggerContext(spPaint3dContextID, exists=True)): mc.deleteUI(spPaint3dContextID); mc.draggerContext(spPaint3dContextID, pressCommand=self.onPress, dragCommand=self.onDrag, releaseCommand=self.onRelease, name=spPaint3dContextID, cursor='crossHair', undoMode='step') #create context local options self.runtimeUpdate(uioptions, transformoptions, sourcelist, targetlist) #debug purpose self.reentrance = 0 #initialise world up vector if ( (mc.upAxis(q=True, axis=True)) == "y" ): self.worldUp = om.MVector (0,1,0); elif ( (mc.upAxis(q=True, axis=True)) == "z" ): self.worldUp = om.MVector (0,0,1); else: #can't figure out up vector mc.confirmDialog(title='Weird stuff happening', message='Not getting any proper info on what the current up vector is. Quitting...') sys.exit() #fetch current scene unit self.unit = mc.currentUnit(query=True, linear=True)
def atPoint(settings=None): '''Creates a context in which the user can click on an object in the scene and a point will be traced on that mesh, using either a follicle or the nearest point on the mesh. This function takes the same settings dictionary that getShortcut creates.''' # Test for plugin. if not pluginLoaded(): return if not settings: settings = {} if pointOnMesh: if cmd.draggerContext(CONTEXTNAME, q=1, ex=1): cmd.deleteUI(CONTEXTNAME) # I have found no way to test if an icon exists, other than to # just attempt to create something with that icon. kwargs = {'releaseCommand': partial(getPoint, settings=settings), 'cursor': 'crossHair', 'image1': 'arcTracerOnMesh.png'} try: cmd.draggerContext(CONTEXTNAME, **kwargs) except RuntimeError: kwargs['image1'] = None cmd.draggerContext(CONTEXTNAME, **kwargs) cmd.setToolTo(CONTEXTNAME) else: om.MGlobal.displayWarning("Could not find module pointOnMesh. You must install pointOnMesh to use this functionality.")
def __init__(self, name = 'mlDraggerContext', title = 'Dragger', defaultValue=0, minValue=None, maxValue=None, multiplier=0.01, cursor='hand' ): self.multiplier = multiplier self.defaultValue = defaultValue self.minValue = minValue self.maxValue = maxValue self.cycleCheck = mc.cycleCheck(query=True, evaluation=True) self.draggerContext = name if not mc.draggerContext(self.draggerContext, exists=True): self.draggerContext = mc.draggerContext(self.draggerContext) mc.draggerContext(self.draggerContext, edit=True, pressCommand=self.press, dragCommand=self.drag, releaseCommand=self.release, cursor=cursor, drawString=title, undoMode='all' )
def buildUI(self) : self.resetExternalContext() self.window = cmds.window("autorigging_ui", title="Auto-rigging (BB, EL, TP)", w=self.width, h=self.height) # Title cmds.columnLayout(w=self.width, h=self.height) cmds.separator(h=10) cmds.text(label="Autorigging", w=self.width,h=20, backgroundColor=[0.15,0.15,0.15]) cmds.separator(h=10) # Mesh selector self.meshSelector = cmds.optionMenu(w=self.width,h=30,label="Choisissez un Mesh :") for m in cmds.ls(type="transform"): cmds.menuItem(label=str(m)) cmds.separator(h=40) # Point buttons cmds.scrollLayout(w=self.width) self.definePointButtons() # Action buttons (enter mode) cmds.setParent("..") cmds.setParent("..") # Here to exit scrollLayout cmds.separator(h=10) cmds.rowLayout(numberOfColumns=3) self.activateButton = cmds.button("activetaBtn", label="Activer", w=self.width/3 - 10, h=self.pointButtonHeight, command=self.onActivateButtonClick ) self.generateButton = cmds.button("generateBtn", label="Generer", w=self.width/3 - 10, h=self.pointButtonHeight, command=self.onGenerateButtonClick ) self.autoGenerateButton = cmds.button("generateAutoRigBtn", label="AutoGenerer", w=self.width/3 - 10, h=self.pointButtonHeight, command=self.onAutoRigButtonClick ) # Console cmds.setParent("..") cmds.columnLayout() cmds.separator(h=10) self.consoleText = cmds.text(label="Auto-rigging non-actif", width=self.width, height=50, backgroundColor=[0.3,0.3,0.3]) cmds.showWindow(self.window) cmds.draggerContext("riggingContext", space="world", pressCommand=self.on3DSceneClick) # Registring context ? cmds.setToolTo("riggingContext")
def drag(self): self.dragPoint = mc.draggerContext(self.name, query=True, dragPoint=True) self.button = mc.draggerContext( self.name, query=True, button=True) self.modifier = mc.draggerContext( self.name, query=True, modifier=True) self.x = self.dragPoint[0] self.y = self.dragPoint[1] self.z = self.dragPoint[2]
def drag(self): self.dragPoint = mc.draggerContext(self.name, query=True, dragPoint=True) self.button = mc.draggerContext( self.name, query=True, button=True) self.modifier = mc.draggerContext( self.name, query=True, modifier=True) self.x = self.dragPoint[0] self.y = self.dragPoint[1] self.z = self.dragPoint[2]
def contextPress(self): button = cmds.draggerContext(_dragOnMeshContext, query=True, button=True) # left : 1, middle: 2 if button == 1: self.mainGrp = pm.group(em=True) pm.parent(self.mainGrp, self.growSel) # create trans self.currentTrans = list() self.consGrp = list() for i in range(0, self.copyNum): currentTrans = pm.duplicate(self.initTrans, rr=1)[0] # type: str self.currentTrans.append(currentTrans) consGrp = pm.group(em=1, name='dragOnMesh#') pm.parent(consGrp, self.mainGrp) pm.parent(currentTrans, consGrp) consGrp.scale.set(self.scaList[i] * self.secondSca, self.scaList[i] * self.secondSca, self.scaList[i] * self.secondSca) currentTrans.rotate.set(0, self.rotateList[i] + self.secondRotate, 0) self.consGrp.append(consGrp) pm.geometryConstraint(self.growSel, consGrp, weight=1) pm.normalConstraint(self.growSel, consGrp, weight=1, aimVector=(0, 1, 0), upVector=(0, 0, 1), worldUpType="scene") vpX, vpY, _ = cmds.draggerContext(self.context, q=True, anchorPoint=True) sourcePoint, direction = getIntersect(vpX, vpY) hitPoint = getPoints(self.growSel, sourcePoint, direction) for consGrp in self.consGrp: if hitPoint: consGrp.translate.set(hitPoint) else: consGrp.translate.set(sourcePoint) if hitPoint: self.dragInitPos = vpX, vpY, _ updateView() elif button == 2: pressPosition = cmds.draggerContext(self.context, query=True, anchorPoint=True) self.mouseX = pressPosition[0] self.currentTransRotXYZ = list() for each in self.currentTrans: self.currentTransRotXYZ.append(each.rotate.get())
def activate(self): _str_func = 'LiveRecord.activate' self.clickAction = cgmDrag.ClickAction(onPress=self.onPress, onRelease=self.onRelease, onFinalize=self.onFinalize, dropOnPress=False, dropOnRelease=False) mc.draggerContext(self.clickAction.name, edit=True, cursor='hand')
def start(self): self.deleteUIIfExists() cmds.draggerContext(self.name, releaseCommand='jp.onRelease()', dragCommand='jp.onDrag()', pressCommand='jp.onPress()', cursor='crossHair') cmds.setToolTo(self.name) self.assignSelection()
def start_plant(self): if mc.draggerContext('plantTree', exists=True): mc.setToolTo('plantTree') else: mc.draggerContext('plantTree', pressCommand=partial(self.sample_context_press), dragCommand=partial(self.sample_context_drag), cursor='hand') mc.setToolTo('plantTree')
def TraceGesturePress( self ): """ Procedure called on press """ if debug>0: print("begin PRESS") # Clean up: if there are any locators or groups in the scene, delete them if( len(mc.ls("locator*")) > 0 ): mc.delete(mc.ls("locator*")) if( len(mc.ls("*Grp")) > 0 ): mc.delete(mc.ls("*Grp")) # find the position of the mouse click pressPosition = Vector( mc.draggerContext( 'TraceGesture', query=True, anchorPoint=True) ) camPos = self.CameraPosition() viewAxis = self.CameraViewAxis() closestObj2Cam = self.FindNearestObjectToCamera() self.interactionPlane = Plane(viewAxis,closestObj2Cam) pressPosition = self.FindRayPlaneIntersect( camPos, pressPosition, self.interactionPlane ) if debug > 0: mc.group(n="traceGrp",empty=True) loc = mc.spaceLocator(p=pressPosition) mc.parent(loc,"traceGrp") for root in self.xformRoots: # remember whether (or not) the motion paths for a root were visible when the interaction started self.motionPathsVisible[root] = mc.getAttr("%s_MotionTraces.visibility"%root) # set up all the traces self.trace[root].Clear() # set the trace normal to the viewing normal of the camera self.trace[root].normal = self.interactionPlane.normal #Vector( mc.xform(mc.lookThru(q=True), q=True, m=True)[8:11] ) self.trace[root].planePt = self.interactionPlane.point #closestObj2Cam self.nearestRoot, rootDist = self.FindNearestRoot( pressPosition, self.interactionPlane ) mc.setAttr("%s_MotionTraces.visibility"%self.nearestRoot, 1) # vis the new display layer # make a group to hold the trace locators if debug > 0: mc.group(name="trace%sGrp"%self.nearestRoot,empty=True) loc = mc.spaceLocator(p=pressPosition) mc.parent(loc,"trace%sGrp"%self.nearestRoot) # reset the trace self.trace[self.nearestRoot].Clear() # start the timer self.startTime = time.time() # set the trace normal to the viewing normal of the camera self.trace[self.nearestRoot].normal = Vector( mc.xform(mc.lookThru(q=True), q=True, m=True)[8:11] ) self.trace[self.nearestRoot].planePt = closestObj2Cam # add the initial click position to the trace self.trace[self.nearestRoot].AddPoint( pressPosition ) self.nearestPath, pathDist = self.FindNearestMotionPath( pressPosition, self.nearestRoot ) if not mc.draggerContext( 'TraceGesture', query=True, modifier=True) == "ctrl": self.trace[self.nearestRoot].SetUpDTWs() mc.refresh(currentView=True,force=True) if debug>0: print("end PRESS")
def _press(self): if cmds.draggerContext(self.name,query=True,exists=True): self._clear_info() self._clear_message() self.anchor_point = cmds.draggerContext(self.name, query=True, anchorPoint=True) self.modifier = cmds.draggerContext(self.name, query=True, modifier=True) self.button = cmds.draggerContext(self.name, query=True, button=True) self.points_list.append(self.anchor_point)
def addGuide(self): if mc.draggerContext(self.context, exists=True): print "setting context" mc.deleteUI(self.context) mc.draggerContext(self.context, name = self.context, releaseCommand= self.onPress, cursor="crossHair") print "set dragger context" mc.setToolTo(self.context) print "set tool to follicle context"
def selectGeoContextTool(self): self.waitWindow() ctx = partial(self.selectGeoContextPress) if (cmds.draggerContext('selGeoContext', exists=True)): cmds.deleteUI('selGeoContext') cmds.draggerContext('selGeoContext', pressCommand=ctx, cursor='hand', projection="s") cmds.setToolTo('selGeoContext')
def dragEvent(self): """ Event while dragging a 3d view """ if self.TARGET_FNMESH is None: return dragPosition = cmds.draggerContext(DRAGGER, query=True, dragPoint=True) x = dragPosition[0] y = dragPosition[1] modifier = cmds.draggerContext(DRAGGER, query=True, modifier=True) if modifier == "none": self.MOD_FIRST = True qtModifier = QApplication.keyboardModifiers() if qtModifier == self.CTRL or qtModifier == self.SHIFT: # If this is the first click of dragging if self.MOD_FIRST is True: self.MOD_POINT = [x, y] # global MOD_FIRST self.MOD_FIRST = False length, degree = self.getDragInfo(x, y) if qtModifier == self.CTRL: length = 1.0 if qtModifier == self.SHIFT: degree = 0.0 # Convert point_in_3d, vector_in_3d = convertTo3D(self.MOD_POINT[0], self.MOD_POINT[1]) else: point_in_3d, vector_in_3d = convertTo3D(x, y) length = 1.0 degree = 0.0 # Get new transform matrix for new object transformMatrix = self.getMatrix(point_in_3d, vector_in_3d, self.TARGET_FNMESH, self.SCALE_ORIG, self.MATRIX_ORIG, length, degree) if transformMatrix is None: return # Apply new transform cmds.xform(self.DUPLICATED, matrix=transformMatrix) cmds.setAttr(self.DUPLICATED + ".shear", *[0, 0, 0]) cmds.refresh(currentView=True, force=True)
def setupContext(self): """ Sets up our dragger context for the user to drag around with :return: """ self.deleteContext() cmds.draggerContext(self.ctx, dragCommand=self.onDrag, name=self.ctx, cursor='crossHair') cmds.setToolTo(self.ctx)
def pressEvent(self): button = cmds.draggerContext(DRAGGER, query=True, button=True) # Leave the tool by middle click if button == 2: cmds.setToolTo('selectSuperContext') return # Get clicked point in viewport screen space pressPosition = cmds.draggerContext(DRAGGER, query=True, ap=True) x = pressPosition[0] y = pressPosition[1] self.ANCHOR_POINT = [x, y] # Convert point_in_3d, vector_in_3d = convertTo3D(x, y) # Get MFnMesh of snap target targetDagPath = getDagPathFromScreen(x, y) # If draggin outside of objects if targetDagPath is None: return # Get origianl scale information self.SCALE_ORIG = cmds.getAttr(self.SOURCE + ".scale")[0] self.MATRIX_ORIG = cmds.xform(self.SOURCE, q=True, matrix=True) self.TARGET_FNMESH = OpenMaya.MFnMesh(targetDagPath) transformMatrix = self.getMatrix(point_in_3d, vector_in_3d, self.TARGET_FNMESH, self.SCALE_ORIG, self.MATRIX_ORIG) if transformMatrix is None: return # Create new object to snap self.DUPLICATED = self.getNewObject() # Reset transform of current object cmds.setAttr(self.DUPLICATED + ".translate", *[0, 0, 0]) location = [ -i for i in cmds.xform(self.DUPLICATED, q=True, ws=True, rp=True) ] cmds.setAttr(self.DUPLICATED + ".translate", *location) # Can't apply freeze to instances if self.InstanceFlag is not True: cmds.makeIdentity(self.DUPLICATED, apply=True, t=True) # Apply transformMatrix to the new object cmds.xform(self.DUPLICATED, matrix=transformMatrix)
def press(self): if not mc.draggerContext(self.name,query=True,exists=True): # if it exists, delete it self.build self.setTool() self.anchorPoint = mc.draggerContext(self.name, query=True, anchorPoint=True) self.modifier = mc.draggerContext(self.name, query=True, modifier=True) self.button = mc.draggerContext(self.name, query=True, button=True) self.x = self.anchorPoint[0] self.y = self.anchorPoint[1] self.z = self.anchorPoint[2]
def initiate(): #tool context definition if cmds.draggerContext('createObject', exists=True): cmds.deleteUI('createObject') cmds.draggerContext('createObject', pc='generate()', dc='generate()', cur='hand', i1='duplicateReference.png', space='world') cmds.setToolTo('createObject')
def press(self): if not mc.draggerContext(self.name,query=True,exists=True): # if it exists, delete it self.build self.setTool() self.anchorPoint = mc.draggerContext(self.name, query=True, anchorPoint=True) self.modifier = mc.draggerContext(self.name, query=True, modifier=True) self.button = mc.draggerContext(self.name, query=True, button=True) self.x = self.anchorPoint[0] self.y = self.anchorPoint[1] self.z = self.anchorPoint[2]
def create_context(self): self.delete_existing_contexts() mc.draggerContext(self.context_name, name=self.context_name, releaseCommand=self.release_command, cursor="crossHair", pressCommand=self.press_command, prePressCommand=self.pre_press_command, holdCommand=self.hold_command, initialize=self.intialize_command, dragCommand=self.drag_command, finalize=self.finalize_command)
def Dragger(self, selection = 'NA' , historyName = '', speed = [0.01, .1, .0001] ): if selection == 'NA': self.selection = self.getSelection() else: self.selection = selection self.history = self.getHistory(self.selection, -1, historyName) self.attribute = self.history[-1] + Cache.currentAttribute try: cmds.draggerContext( 'dragTool', edit=True, pressCommand= partial(self.pressFunction), dragCommand= partial(self.dragFunction), finalize = partial(self.exitFunction), undoMode = "step") except: cmds.draggerContext( 'dragTool', pressCommand= partial(self.pressFunction), dragCommand= partial(self.dragFunction), finalize = partial(self.exitFunction), undoMode = "step" ) cmds.setToolTo( 'dragTool' )
def overshoot(baseFrame='previous'): '''Input kan either be 'previous','next' or an integer''' global attrDict global deltaX global lastVal deltaX = 0 lastVal = 0 print "# Initializing drag" selList = mc.ls(sl=True) try: ### Checking userInput if baseFrame != 'previous' and baseFrame != 'next' and type(baseFrame) != type(123): raise QuitException, "# init >> Input is incorrect. Only supported inputs are 'previous', 'next' or an integer" ### Checking selection if selList != None: attrDict = calcAttrDiff(selList, baseFrame) else: raise QuitException, "# Init >> Nothing is selected" ### Initializing context if mc.draggerContext( 'overshootCtx', exists=True ) == 0: mc.draggerContext( "overshootCtx" ) ### Checking script file name (execution namespace) if __name__ != '__main__': prefix = __name__ + '.' else: prefix = '' mc.draggerContext( 'overshootCtx', edit=True, pressCommand= prefix + 'overshoot_OnPress()', dragCommand= prefix + 'overshoot_OnDrag()', releaseCommand= prefix + 'overshoot_EndDrag()', cursor='crossHair' ); mm.eval('storeLastAction( "restoreLastContext " + `currentCtx` )') mc.setToolTo( 'overshootCtx' ) except QuitException, arg: print "### Tool terminated ###" if arg != None: print arg,
def pressEvent(self): button = cmds.draggerContext(DRAGGER, query=True, button=True) # Leave the tool by middle click if button == 2: cmds.setToolTo('selectSuperContext') return # Get clicked point in viewport screen space pressPosition = cmds.draggerContext(DRAGGER, query=True, ap=True) x = pressPosition[0] y = pressPosition[1] self.ANCHOR_POINT = [x, y] # Convert point_in_3d, vector_in_3d = convertTo3D(x, y) # Get MFnMesh of snap target targetDagPath = getDagPathFromScreen(x, y) # If draggin outside of objects if targetDagPath is None: return # Create new object to snap self.DUPLICATED = self.getNewObject() # Get origianl scale information self.SCALE_ORIG = cmds.getAttr(self.DUPLICATED + ".scale")[0] self.MATRIX_ORIG = cmds.xform(self.SOURCE, q=True, matrix=True) self.TARGET_FNMESH = OpenMaya.MFnMesh(targetDagPath) transformMatrix = self.getMatrix( point_in_3d, vector_in_3d, self.TARGET_FNMESH, self.SCALE_ORIG, self.MATRIX_ORIG) # Reset transform of current object cmds.setAttr(self.DUPLICATED + ".translate", *[0, 0, 0]) location = [-i for i in cmds.xform(self.DUPLICATED, q=True, ws=True, rp=True)] cmds.setAttr(self.DUPLICATED + ".translate", *location) cmds.makeIdentity(self.DUPLICATED, apply=True, t=True) # Apply transformMatrix to the new object cmds.xform(self.DUPLICATED, matrix=transformMatrix)
def load(s): sel = cmds.ls(sl=True) if sel and sel[0] in s.valid: s.sel = sel[0] s.tool = cmds.currentCtx() s.myTool = "TempTool" if cmds.draggerContext(s.myTool, exists=True): cmds.deleteUI(s.myTool) cmds.draggerContext(s.myTool, name=s.myTool, pressCommand=s.click, cursor='hand') cmds.setToolTo(s.myTool) print "Make a selection" else: print "Nothing selected"
def pressFunction(self): self.attribute = self.history[-1] + Cache.currentAttribute # re-init the attribute in case cached has been switched self.modifier = cmds.draggerContext( 'dragTool', query=True, modifier=True) self.button = cmds.draggerContext('dragTool', query = True, button=True) self.attributeValue = cmds.getAttr( self.attribute ) if cmds.currentUnit( query=True, linear=True ) == 'cm': self.speed = .01 # modifier for speed traveled through values while dragging elif cmds.currentUnit( query=True, linear=True ) == 'm': self.speed = .001 # modifier for speed traveled through values while dragging else: self.speed = .0001 self.space = 'screen' # initialize the variable if isinstance(self.attributeValue, list): # only edit the space based on button if the attribute is a list value # If left click is used, then the space is set to (X,Y,Z) world based # If middle click is used, space is set to (X, Y) screen based if self.button == 1: # left button self.space = 'world' # tracking space used cmds.draggerContext( 'dragTool', edit=True, space = 'world') elif self.button == 2: # middle button self.space = 'screen' # tracking space used cmds.draggerContext( 'dragTool', edit=True, space = 'screen') else: # set to 'screen' as default if the attr isn't a list value cmds.draggerContext( 'dragTool', edit=True, space = 'screen') if self.modifier == 'ctrl': self.speed = self.speed * .01 if self.modifier == 'shift': self.speed = self.speed * 10 if len(self.dragDirection) > 0: self.dragDirection = []
def __init__(self, **kwargs): self.name = self.NAME if not cmds.draggerContext(self.NAME, exists=True): self.name = cmds.draggerContext(self.NAME) cmds.draggerContext(self.name, edit=True, pressCommand=self.press, dragCommand=self.drag, releaseCommand=self.release, inz=self.execute, fnz=self.tear_down, **kwargs) self.context = functools.partial(cmds.draggerContext, self.name)
def press(self, *args): ''' Be careful overwriting the press method in child classes, because of the undoInfo openChunk ''' self.anchorPoint = mc.draggerContext(self.draggerContext, query=True, anchorPoint=True) self.button = mc.draggerContext(self.draggerContext, query=True, button=True) #dragString # This makes it so the script editor doesn't get spammed by a cycle in the puppet mc.cycleCheck(evaluation=False) # This turns off the undo queue until we're done dragging, so we can undo it. mc.undoInfo(openChunk=True)
def __init__(self,name): self.userSelection = [] self.cursor = 'crossHair' self.dragStart = [0,0] self.dragEnd = [0,0] self.dragComponentSelection = [] self.dragObjectSelection = [] self.modifier = 'none' self.context = name+'_CTX' if mc.draggerContext(self.context,q=1,ex=1): mc.deleteUI(self.context) self.context = mc.draggerContext(self.context, pressCommand=name+'.onPress()', dragCommand=name+'.onDrag()', releaseCommand=name+'.onRelease()', cursor=self.cursor )
def pressFunction(self): self.attribute = self.history[ -1] + Cache.currentAttribute # re-init the attribute in case cached has been switched self.modifier = cmds.draggerContext('dragTool', query=True, modifier=True) self.button = cmds.draggerContext('dragTool', query=True, button=True) self.attributeValue = cmds.getAttr(self.attribute) if cmds.currentUnit(query=True, linear=True) == 'cm': self.speed = .01 # modifier for speed traveled through values while dragging elif cmds.currentUnit(query=True, linear=True) == 'm': self.speed = .001 # modifier for speed traveled through values while dragging else: self.speed = .0001 self.space = 'screen' # initialize the variable if isinstance( self.attributeValue, list ): # only edit the space based on button if the attribute is a list value # If left click is used, then the space is set to (X,Y,Z) world based # If middle click is used, space is set to (X, Y) screen based if self.button == 1: # left button self.space = 'world' # tracking space used cmds.draggerContext('dragTool', edit=True, space='world') elif self.button == 2: # middle button self.space = 'screen' # tracking space used cmds.draggerContext('dragTool', edit=True, space='screen') else: # set to 'screen' as default if the attr isn't a list value cmds.draggerContext('dragTool', edit=True, space='screen') if self.modifier == 'ctrl': self.speed = self.speed * .01 if self.modifier == 'shift': self.speed = self.speed * 10 if len(self.dragDirection) > 0: self.dragDirection = []
def run(self): if self.selected: if cmds.draggerContext(self.ctx, exists=True): cmds.deleteUI(self.ctx) # Create dragger context and set it to the active tool # cmds.draggerContext(self.ctx, pressCommand=self.create_job, dragCommand=self.move_job, name=self.ctx, cursor='crossHair', image1='curve_create.png') cmds.draggerContext(self.ctx, pressCommand=self.create_job, name=self.ctx, cursor='crossHair', image1='curve_create.png') cmds.setToolTo(self.ctx) else: print("No Mesh Selected!")
def overshoot(baseFrame='previous'): '''Input kan either be 'previous','next' or an integer''' global attrDict global deltaX global lastVal deltaX = 0 lastVal = 0 print "# Initializing drag" selList = mc.ls(sl=True) try: ### Checking userInput if baseFrame != 'previous' and baseFrame != 'next' and type( baseFrame) != type(123): raise QuitException, "# init >> Input is incorrect. Only supported inputs are 'previous', 'next' or an integer" ### Checking selection if selList != None: attrDict = calcAttrDiff(selList, baseFrame) else: raise QuitException, "# Init >> Nothing is selected" ### Initializing context if mc.draggerContext('overshootCtx', exists=True) == 0: mc.draggerContext("overshootCtx") ### Checking script file name (execution namespace) if __name__ != '__main__': prefix = __name__ + '.' else: prefix = '' mc.draggerContext('overshootCtx', edit=True, pressCommand=prefix + 'overshoot_OnPress()', dragCommand=prefix + 'overshoot_OnDrag()', releaseCommand=prefix + 'overshoot_EndDrag()', cursor='crossHair') mm.eval('storeLastAction( "restoreLastContext " + `currentCtx` )') mc.setToolTo('overshootCtx') except QuitException, arg: print "### Tool terminated ###" if arg != None: print arg,
def run(): if cmds.contextInfo(ZOOM_TRANSLATE, exists=True): cmds.setToolTo(ZOOM_TRANSLATE) return cmds.draggerContext(ZOOM_TRANSLATE, pressCommand='zoom_translate.start_translate()', dragCommand='zoom_translate.do_translate()', releaseCommand='zoom_translate.end_translate()', cursor='hand', undoMode='step') # Put it as the y-key slot mel.eval('$gNonSacredTool = "{}";'.format(ZOOM_TRANSLATE)) cmds.setToolTo(ZOOM_TRANSLATE)
def onHold(self): ''' on mouse hold event ''' if self.reentrance==1: return self.reentrance=1 dragPosition = mc.draggerContext(spPaint3dContextID, query=True, dragPoint=True); ctrl, shift, alt = self.mState.getState() if(ctrl): self.ctrlEvent() if(shift): self.shiftEvent() forceRefresh() if sp3d_log: message = 'key press detected: ' if (ctrl): message += 'ctrl pressed... ' if (shift): message += 'shift pressed... ' if (alt): message += 'alt pressed... ' print message self.reentrance=0
def onHold(self): ''' on mouse hold event ''' if self.reentrance==1: return self.reentrance=1 dragPosition = mc.draggerContext(spPaint3dContextID, query=True, dragPoint=True); ctrl, shift, alt = self.mState.getState() if(ctrl): self.ctrlEvent() if(shift): self.shiftEvent() forceRefresh() if sp3d_log: message = 'key press detected: ' if (ctrl): message += 'ctrl pressed... ' if (shift): message += 'shift pressed... ' if (alt): message += 'alt pressed... ' print message self.reentrance=0
def __init__(self, name, **kwargs): self.name = name if not cmds.draggerContext(self.name, exists=True): self.name = cmds.draggerContext(name) cmds.draggerContext( self.name, edit=True, pressCommand=self.press, dragCommand=self.drag, releaseCommand=self.release, inz=self.setup, fnz=self.tear_down, **kwargs ) self.context = partial(cmds.draggerContext, self.name)
def drag(self, *args): '''Called continuously when holding the mouse button down, updates self.x and self.y with the mouse position, and runs the corresponding method for whichever button is being pressed.''' self.dragPoint = mc.draggerContext(self.draggerContext, query=True, dragPoint=True) self.x = ((self.dragPoint[0] - self.anchorPoint[0]) * self.multiplier) + self.defaultValue self.y = ((self.dragPoint[1] - self.anchorPoint[1]) * self.multiplier) + self.defaultValue if self.minValue is not None and self.x < self.minValue: self.x = self.minValue if self.maxValue is not None and self.x > self.maxValue: self.x = self.maxValue #dragString if self.modifier == 'control': if self.button == 1: self.dragControlLeft() elif self.button == 2: self.dragControlMiddle() elif self.modifier == 'shift': if self.button == 1: self.dragShiftLeft() elif self.button == 2: self.dragShiftMiddle() else: if self.button == 1: self.dragLeft() elif self.button == 2: self.dragMiddle() mc.refresh()
def getPointer(s): """ Get intersection point on the mesh from the mouse click. """ if s.meshes: try: # Grab screen co-ords viewX, viewY, viewZ = cmds.draggerContext(s.tool, q=True, dp=True) # Set up empty vectors position = om.MPoint() direction = om.MVector() # Convert 2D positions into 3D positions omui.M3dView().active3dView().viewToWorld(int(viewX), int(viewY), position, direction) # Check our meshes for mesh in s.meshes: selection = om.MSelectionList() selection.add(mesh) dagPath = selection.getDagPath(0) fnMesh = om.MFnMesh(dagPath) # Shoot a ray and check for intersection intersection = fnMesh.closestIntersection(om.MFloatPoint(position), om.MFloatVector(direction), om.MSpace.kWorld, 99999, False) # hitPoint, hitRayParam, hitFace, hitTriangle, hitBary1, hitBary2 = intersection if intersection and intersection[3] != -1: return (mesh, intersection[2]) # hit mesh and face ID except RuntimeError: pass
def on3DSceneClick(self): if not cmds.window("autorigging_ui", exists=True) : self.resetExternalContext() return if not self.isActive : self.setConsoleText("Vous devez activer l'autorigging.",color=[255,0,0]) return if not self.currentPointKey : self.setConsoleText("Choisissez un type de point a placer.") return pos = cmds.draggerContext("riggingContext", query=1, anchorPoint=1) strPos = "x:"+str(round(pos[0],2)) +"\ny:" + str(round(pos[1],2)) if self.pointsMap[self.currentPointKey]["isSet"] is True : cmds.delete(self.currentPointKey+"sphere") nextObj = cmds.polySphere(name=self.currentPointKey+"sphere", radius=0.3) cmds.move(pos[0], pos[1], 10, nextObj) cmds.scale(1.0,1.0,0.0, nextObj) self.pointsMap[self.currentPointKey]["isSet"] = True self.pointsMap[self.currentPointKey]["clickedPoint"] = pos cmds.button(self.pointsMap[self.currentPointKey]["stateButton"], e=1, backgroundColor=[0,255,0],label=strPos)
def getPoint(settings): '''The real content of atPoint, this should only be called from the context created in atPoint.''' # Test for plugin. if not pluginLoaded(): return # Get screen position of pointer clickPosition = cmd.draggerContext(CONTEXTNAME, q=1, dragPoint=1) surfaceData = pointOnMesh.getPoint(clickPosition, createFollicle=0) # Limit maxSubframes on creation if they're not already set, because # follicles are SLOW if not 'maxSubframes' in settings: if 'minSubframes' in settings: settings['maxSubframes'] = settings['minSubframes'] else: settings['maxSubframes'] = 0 if surfaceData: if surfaceData.u is None or surfaceData.v is None: if surfaceData.type == 'mesh': om.MGlobal.displayWarning('Falling back to nearest point mode.') settings['traceVertex'] = surfaceData.closestVertex create(surfaceData.name, settings) else: om.MGlobal.displayError('Could not create arc on specified mesh. Could not find UV data') elif surfaceData.type == 'nurbsSurface' or surfaceData.type == 'mesh': follicle = pointOnMesh.createFollicle(surfaceData, 'arcTracerFollicle') if follicle: create(follicle, settings, follicle=True) else: om.MGlobal.displayError('Could not create arc on a %s' % surfaceData.type)
def setObjectToShatterCmd(self, *args): ''' ''' if not (cmds.draggerContext(self._IScontextTool._mContext, exists = True)): iMinTime = cmds.playbackOptions(query = True, minTime = True) cmds.currentTime(iMinTime, edit = True) polySelection = cmds.filterExpand(selectionMask = 12) if polySelection: if len(polySelection) > 0: mBreakNode = cmds.listConnections(polySelection[0], sh = True, type = 'fxBreakGeometry') if not mBreakNode: cmds.button(self._ISaddBtn, edit = True, label = 'Please wait... checking mesh toplogy') self._IScontextTool.checkForNonManifoldMeshes(polySelection[0]) cmds.delete(polySelection[0], ch = True) self.resetIShatterGUI() self._IScontextTool._mVoroObject = polySelection[0] cmds.button(self._ISaddBtn, edit = True, label = polySelection[0]) cmds.button(self._ISdelBtn, edit = True, enable = True) cmds.button(self._ISprocessBtn, edit = True, enable = True) cmds.checkBox(self._ISborderEdgesCbx, edit = True, enable = True) cmds.checkBox(self._IShideObjectsCbx, edit = True, enable = True) else: cmds.confirmDialog(title = 'Oups... IShatter Error', message = 'You must select one mesh object first !', button = 'OK', defaultButton = 'Yes', cancelButton = 'No', dismissString = 'No')
def __init__(self, **kwargs): self.name = self.NAME if not cmds.draggerContext(self.NAME, exists=True): self.name = cmds.draggerContext(self.NAME) cmds.draggerContext( self.name, edit=True, pressCommand=self.press, dragCommand=self.drag, releaseCommand=self.release, inz=self.execute, fnz=self.tear_down, **kwargs ) self.context = functools.partial(cmds.draggerContext, self.name)
def __init__(self, targetObj = [], step = 0.25, mesh = False, bRad = 1, bMult = 1, taper = 1, tMult = .1,autoAdd=True): """ initialize tool """ # create dragger context self.dragCtx = "gf_meshPlace_draggerCtx" if (cmds.draggerContext(self.dragCtx, exists=True)): cmds.deleteUI(self.dragCtx) cmds.draggerContext(self.dragCtx, pressCommand=self.onPress, dragCommand=self.onDrag, releaseCommand=self.onRelease, name=self.dragCtx, cursor='crossHair', undoMode='step') self.targetObj = targetObj # objects list self.worldUp = om.MVector(0,-1,0) self.step = step self.mesh = mesh self.bRad = bRad self.bMult = bMult self.taper = taper self.tMult = tMult self.autoAdd = autoAdd
def switchTool(s, mesh=None): """ Switch to our selection tool """ s.lastTool = cmds.currentCtx() ### For testing, refresh the tool each time this is run! if cmds.draggerContext(s.tool, ex=True): cmds.deleteUI(s.tool) ### if mesh and mesh in s.meshes: s.setColour("%s.vtx[0:]" % mesh, (0.4,0.4,0.4)) # Highlight mesh if provided. cmds.draggerContext( s.tool, name=s.tool, releaseCommand=s.makeSelection, dragCommand=s.updateSelectionPreview, # Preview selection while dragging cursor="hand", image1="hands.png") cmds.setToolTo(s.tool) s.active = True
def startCtx(self): ''' start draggerContext tool. ''' self.initSetup() if (cmds.draggerContext(self._mContext, exists = True)): cmds.deleteUI(self._mContext) cmds.draggerContext( self._mContext, pressCommand = self.pressCtx, dragCommand = self.dragCtx, releaseCommand = self.releaseCtx, finalize = self.finalizeCtx, name = self._mContext, cursor = 'hand' ) cmds.setToolTo(self._mContext)
def onDrag(self): ''' on mouse drag event ''' if self.reentrance==1: return self.reentrance=1 dragPosition = mc.draggerContext(spPaint3dContextID, query=True, dragPoint=True); worldPos, worldDir = getViewportClick(dragPosition[0],dragPosition[1]) ctrl, shift, alt = self.mState.getState() # #TODO scale and rotate depending on mouse drag direction # intersected = targetSurfaceLoopIntersect(self.targetList, worldPos, worldDir) if(intersected): #there was a usable intersection found #first checking and converting units if necessary intersected.convertUnit(self.unit) #now moving the cursor if(self.uiValues.align): rx, ry, rz = getEulerRotationQuaternion(self.worldUp, intersected.getHitNormal(self.uiValues.smoothNormal)) self.cursor.align(rx,ry,rz) self.cursor.move(intersected.hitPoint, self.cursor.rotationIncrement) if self.uiValues.transformRotate or self.uiValues.transformScale: #retransforming the cursor rotation if necessary self.cursor.transform(self.uiValues.transformRotate) if self.uiValues.continuousTransform: cursorRotate, cursorScale = self.fetchCursorTransform() self.cursor.setCursorTransform(cursorRotate, cursorScale) self.cursor.transform(self.uiValues.transformRotate, self.uiValues.transformScale) if (self.uiValues.upOffset != 0): offsetArray = [self.uiValues.upOffset*self.worldUp.x,self.uiValues.upOffset*self.worldUp.y,self.uiValues.upOffset*self.worldUp.z] mc.move(offsetArray[0],offsetArray[1],offsetArray[2],self.cursor.cursorDAG,relative=True) else: pass #no intersection found #TODO #moving cursor to worldPos and aligning to worldDir if(ctrl): self.ctrlEvent() if(shift): self.shiftEvent() forceRefresh() self.reentrance=0
def main( traceables=None ): global traceSelect if(traceables): traceableObjs = traceables jointRoots, xformRoots = findRootsFromTraceables(traceables) else: jointRoots, xformRoots, traceableObjs = autoFindTraceables() # if nothing traceable is in the scene, give up if len(xformRoots) == 0: mc.warning("no trace-able objects (e.g. joints or IK handles) are in your scene.") return None # otherwise, keep going... traceSelect = TraceSelection( xformRoots, traceableObjs ) # Define draggerContext with press and drag procedures if not traceSelect.forceReload and mc.draggerContext( 'TraceGesture', exists=True ) : mc.draggerContext( 'TraceGesture', edit=True, space='world', pressCommand='traceSelect.TraceGesturePress()', dragCommand='traceSelect.TraceGestureDrag()', releaseCommand='traceSelect.TraceGestureRelease()', cursor='default') else: mc.draggerContext( 'TraceGesture', space='world', pressCommand='traceSelect.TraceGesturePress()', dragCommand='traceSelect.TraceGestureDrag()', releaseCommand='traceSelect.TraceGestureRelease()', cursor='default') if len(mc.ls('*_MotionPaths')) == 0: # if first time script has been called on this scene traceSelect.DrawJointMotionPaths(xformRoots) traceSelect.LoadJointMotionPaths(xformRoots) mc.setToolTo('TraceGesture') return traceSelect