def set_bounding_box(self): m3d_view = OpenMayaUI.M3dView() for index in range(m3d_view.numberOf3dViews()): view = OpenMayaUI.M3dView() m3d_view.get3dView(index, view) view.setDisplayStyle(0) view.refresh()
def connectToDependNode(self, node): nodeFn = OpenMaya.MFnDependencyNode(node) try: syPlug = nodeFn.findPlug("scaleY") tPlug = nodeFn.findPlug("translate") distanceManipFn = OpenMayaUI.MFnDistanceManip(self.fDistanceManip) distanceManipFn.connectToDistancePlug(syPlug) freePointManipFn = OpenMayaUI.MFnFreePointTriadManip(self.fFreePointManip) freePointManipFn.connectToPointPlug(tPlug) OpenMayaMPx.MPxManipContainer.finishAddingManips(self) OpenMayaMPx.MPxManipContainer.connectToDependNode(self,node) except: sys.stderr.write( "Error finding and connecting plugs\n" ) raise
def __run(self, *args, **kwargs): img = OpenMaya.MImage() view = OpenMayaUI.M3dView_active3dView() view.readColorBuffer(img, True) img.writeToFile(args[0], os.path.splitext(args[0])[-1][1:]) return True
def getMayaWindow(*args, **kw): ptr = apiUI.MQtUtil_mainWindow() if ptr is not None: try: return shiboken.wrapInstance(long(ptr), QtWidgets.QWidget) except: return shiboken2.wrapInstance(long(ptr), QtWidgets.QWidget)
def setUp(self): mayaSceneFile = '%s.ma' % self._testName mayaSceneFullPath = os.path.join(self._inputDir, mayaSceneFile) cmds.file(mayaSceneFullPath, open=True, force=True) # Create a new custom viewport. self._window = cmds.window(widthHeight=(500, 400)) cmds.paneLayout() self._panel = cmds.modelPanel() cmds.modelPanel(self._panel, edit=True, camera='persp') cmds.modelEditor(cmds.modelPanel(self._panel, q=True, modelEditor=True), edit=True, displayAppearance='smoothShaded', rnm='vp2Renderer') cmds.showWindow(self._window) # Force all views to re-draw. This causes us to block until the # geometry we're making live has actually been evaluated and is present # in the viewport. Otherwise execution of the test may continue and the # create tool may be invoked before there's any geometry there, in # which case the tool won't create anything. cmds.refresh() # Get the viewport widget. self._view = OMUI.M3dView() OMUI.M3dView.getM3dViewFromModelPanel(self._panel, self._view) self._viewWidget = wrapInstance(long(self._view.widget()), QWidget)
def getMayaWindow(): ptr = apiUI.MQtUtil_mainWindow() if ptr is not None: if iv < 2017: return shiboken.wrapInstance(long(ptr), QtWidgets.QWidget) else: return shiboken2.wrapInstance(long(ptr), QtWidgets.QWidget)
def get_maya_main_window(): # Get the memory address of the main window win = omui.MQtUtil_mainWindow() # Convert it into a wrap instance mainWindowPointer = wrapInstance(long(win), QtWidgets.QMainWindow) return mainWindowPointer
def initProgressWindow(self): self.MayaGUIMode = OpenMaya.MGlobal.mayaState() == OpenMaya.MGlobal.kInteractive if self.MayaGUIMode: self.mProgress = OpenMayaUI.MProgressWindow() else: self.mProgress = consoleProgress()
def getMayaWindow(): ''' return maya window by Qt object.. ''' ptr = apiUI.MQtUtil_mainWindow() if ptr is not None: return sip.wrapinstance(long(ptr),QtCore.QObject)
def getMainWindow(): '''This function should be overriden''' if BoilerDict['Environment'] == 'Maya': win = omui.MQtUtil_mainWindow() ptr = wrapInstance(long(win), QtWidgets.QMainWindow) return ptr if BoilerDict['Environment'] == '3dsMax': try: mainWindow = MaxPlus.GetQMaxWindow() except AttributeError: None None None mainWindow = MaxPlus.GetQMaxMainWindow() return mainWindow if BoilerDict['Environment'] == 'Houdini': return hou.qt.mainWindow() if BoilerDict['Environment'] == 'Nuke': for obj in QtWidgets.QApplication.instance().topLevelWidgets(): if ( obj.inherits("QMainWindow") and obj.metaObject().className() == "Foundry::UI::DockMainWindow" ): return obj else: raise RuntimeError("Could not find DockMainWindow instance") return None if BoilerDict['Environment'] == 'Hiero': return hiero.ui.mainWindow()
def getIntersectPoint(meshDagPath, mouseX, mouseY): meshMatrix = meshDagPath.inclusiveMatrix() invMtx = meshDagPath.inclusiveMatrixInverse() activeView = OpenMayaUI.M3dView().active3dView() nearPoint = OpenMaya.MPoint() farPoint = OpenMaya.MPoint() activeView.viewToWorld(mouseX, mouseY, nearPoint, farPoint) nearPoint *= invMtx farPoint *= invMtx fnMesh = OpenMaya.MFnMesh(meshDagPath) intersectPoints = OpenMaya.MPointArray() fnMesh.intersect(nearPoint, farPoint - nearPoint, intersectPoints) if not intersectPoints.length(): return None if intersectPoints.length() == 1: return intersectPoints[0] * meshMatrix elif intersectPoints.length() > 1: pointCenter = OpenMaya.MPoint( (intersectPoints[0].x + intersectPoints[1].x) / 2.0, (intersectPoints[0].y + intersectPoints[1].y) / 2.0, (intersectPoints[0].z + intersectPoints[1].z) / 2.0) return pointCenter * meshMatrix
def connectToDependNode(self, node): try: #- Find the "windDirection" plug on the selected node, which is the custom #- locator node. fnDepNode = OpenMaya.MFnDependencyNode(node) rotationPlug = fnDepNode.findPlug("windDirection") #- Connect the "windDirection" plug with the base disc manip fnDisc = OpenMayaUI.MFnDiscManip(self.fDiscManip) fnDisc.connectToAnglePlug(rotationPlug) #- Set up affecting relationship using conversion callback function #- We are using addPlugToManipConversionCallback so that whenever #- the custom locator moves, the dis manip moves with it. fnDagNode = OpenMaya.MFnDagNode(node) fnDagNode.getPath(self.fNodePath) centerPointIndex = fnDisc.centerIndex() #NOT Available in Python. self.addPlugToManipConversion(centerPointIndex) #- The following two functions are mandatory inside your #- connectToDependNode() function self.finishAddingManips() OpenMayaMPx.MPxManipContainer.connectToDependNode(self, node) except: sys.stderr.write("ERROR: arrowLocatorManip.connectToDependNode\n") raise
def remove_exists_window(object_name): from maya import OpenMaya from maya import OpenMayaUI wind = OpenMayaUI.MQtUtil() if wind.findWindow(object_name): mel_command = 'deleteUI \"%s\"' % object_name OpenMaya.MGlobal.executeCommand(mel_command, False, True)
def plugToManipConversion(self, manipIndex): try: #Get parent transform node of the locator node parentTransform = self.fNodePath.transform() #Get the transform node DAG path transformPath = OpenMaya.MDagPath() OpenMaya.MDagPath.getAPathTo(parentTransform, transformPath) #Retrieve world space translation fnTrans = OpenMaya.MFnTransform(transformPath) translation = OpenMaya.MVector() translation = fnTrans.getTranslation(OpenMaya.MSpace.kWorld) numData = OpenMaya.MFnNumericData() numDataValue = numData.create(OpenMaya.MFnNumericData.k3Double) status = numData.setData3Double(translation.x, translation.y, translation.z) manipData = OpenMayaUI.MManipData(numDataValue) except: sys.stderr.write("ERROR: arrowManip.plugToManipConversion\n") raise return manipData
def getIntersection(self): # Create mpoint variables pos = om.MPoint() # 3D point with double-precision coordinates dir = om.MVector() # 3D vector with double-precision coordinates vpX, vpY, _ = cmds.draggerContext(self.ctx, query=True, dragPoint=True) # This takes vpX and vpY as input and outputs position and direction # values for the active view. # - M3dView: provides methods for working with 3D model views # - active3dView(): Returns the active view in the form of a class # - viewToWorld: Takes a point in port coordinates and # returns a corresponding ray in world coordinates omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, dir) #pos2 = om.MFloatPoint(pos.x, pos.y, pos.z) # Creating a 3 vector float point to use #raySource = om.MFloatPoint(pos2) raySource = om.MFloatPoint(pos) rayDirection = om.MFloatVector(dir) faceIds = None triIds = None idsSorted = False maxParamPtr = 99999999 testBothDirections = False accelParams = None hitpoint = om.MFloatPoint() hitRayParam = None hitFacePtr = om.MScriptUtil().asIntPtr() hitTriangle = None hitBary1 = None hitBary2 = None intersection = self.fnMesh.closestIntersection( raySource, rayDirection, faceIds, triIds, idsSorted, om.MSpace.kWorld, maxParamPtr, testBothDirections, accelParams, hitpoint, hitRayParam, hitFacePtr, hitTriangle, hitBary1, hitBary2) return intersection, hitFacePtr
def fetch_maya_statusline_toolbox(): status_line = mel.eval('$tmp = $gStatusLineForm') pointer = omui.MQtUtil_findControl(status_line) status_line = wrapInstance(long(pointer), QtWidgets.QWidget) toolbox = status_line.children()[1].children()[2] return toolbox
def thumbnailApiFromView(filename, width, height, compression='bmp', modelPanel='modelPanel4'): ''' grab the thumbnail direct from the buffer? TODO: not yet figured out how you crop the data here? ''' import maya.OpenMaya as OpenMaya import maya.OpenMayaUI as OpenMayaUI #Grab the last active 3d viewport view = None if modelPanel is None: view = OpenMayaUI.M3dView.active3dView() else: try: view = OpenMayaUI.M3dView() OpenMayaUI.M3dView.getM3dViewFromModelEditor(modelPanel, view) except: #in case the given modelPanel doesn't exist!! view = OpenMayaUI.M3dView.active3dView() #read the color buffer from the view, and save the MImage to disk image = OpenMaya.MImage() view.readColorBuffer(image, True) image.resize(width, height, True) image.writeToFile(filename, compression) log.info('API Thumbname call path : %s' % filename)
def getDock(name='LightingManagerDock'): """ This function creates a dock with the given name. It's an example of how we can mix Maya's UI elements with Qt elements Args: name: The name of the dock to create Returns: QtWidget.QWidget: The dock's widget """ # First lets delete any conflicting docks deleteDock(name) # Then we create a workspaceControl dock using Maya's UI tools # This gives us back the name of the dock created ctrl = pm.workspaceControl(name, dockToMainWindow=('right', 1), label="Lighting Manager") # We can use the OpenMayaUI API to get the actual Qt widget associated with the name qtCtrl = omui.MQtUtil_findControl(ctrl) # Finally we use wrapInstance to convert it to something Python can understand, in this case a QWidget ptr = wrapInstance(long(qtCtrl), QtWidgets.QWidget) # And we return that QWidget back to whoever wants it. return ptr
def __init__(self): self.namespace = None # if the ui exists then delete it old_window = omui.MQtUtil_findWindow('ribbonTools') if old_window: cmds.deleteUI('ribbonTools') # create a new dialog and give it the main maya window as its parent # store it as the parent for our current UI to be put inside parent = QtWidgets.QDialog(parent=getMayaMainWindow()) # set its name so that we can find and delete it later parent.setObjectName('ribbonTools') parent.setWindowTitle('Ribbon Tools') super(RibbonTools, self).__init__(parent=parent) dlgLayout = QtWidgets.QVBoxLayout(parent) self.buildUI() self.parent().layout().addWidget(self) parent.show()
def getDrawRequests(self, info, objectAndActiveOnly, queue): """ The draw data is used to pass geometry through the draw queue. The data should hold all the information needed to draw the shape. """ data = OpenMayaUI.MDrawData() # printMsg("**before getProtoype\n"); request = info.getPrototype(self) # printMsg("**after getProtoype\n"); shapeNode = self.surfaceShape() geom = shapeNode.geometry() self.getDrawData(geom, data) request.setDrawData(data) # Are we displaying meshes? if (not info.objectDisplayStatus(OpenMayaUI.M3dView.kDisplayMeshes)): return # Use display status to determine what color to draw the object if (info.displayStyle() == OpenMayaUI.M3dView.kWireFrame): self.getDrawRequestsWireframe(request, info) queue.add(request) elif (info.displayStyle() == OpenMayaUI.M3dView.kGouraudShaded): request.setToken(basicShapeUI.__kDrawSmoothShaded) self.getDrawRequestsShaded(request, info, queue, data) queue.add(request) elif (info.displayStyle() == OpenMayaUI.M3dView.kFlatShaded): request.setToken(basicShapeUI.__kDrawFlatShaded) self.getDrawRequestsShaded(request, info, queue, data) queue.add(request) return
def connectToDependNode(self, node): self.nodeFn.setObject(node) # input curve plug curvePositionPlug = self.nodeFn.findPlug(positionOnCurve.curvePositionAttribute) curvePlug = self.nodeFn.findPlug(positionOnCurve.inputCurveAttribute) connections = OpenMaya.MPlugArray() curvePlug.connectedTo(connections, True, False) curveNodeFn = OpenMaya.MFnDagNode(connections[0].node()) curveNode = OpenMaya.MDagPath() curveNodeFn.getPath(curveNode) curveFn = OpenMaya.MFnNurbsCurve(curveNode) manipPos = OpenMaya.MPoint() curveFn.getPointAtParam(0.001, manipPos, OpenMaya.MSpace.kWorld) # get curve position plug # and set manip translation distanceManipFn = OpenMayaUI.MFnDistanceManip(self.distManip) distanceManipFn.setDirection(OpenMaya.MVector(0, 1, 0)) distanceManipFn.connectToDistancePlug(curvePositionPlug) distanceManipFn.setTranslation(OpenMaya.MVector(manipPos), OpenMaya.MSpace.kWorld) mscriptutil = OpenMaya.MScriptUtil() # scale Manip mscriptutil.createFromList([10, 10, 10], 3) scaleDoubleArrayPtr = mscriptutil.asDoublePtr() distanceManipFn.setScale(scaleDoubleArrayPtr) self.finishAddingManips() OpenMayaMPx.MPxManipContainer.connectToDependNode(self, node)
def __init__(self, editor): """Makes your interaction in viewport fast, by installing this event viewport changes to bounding box Args: editor(str): modelEditor Usage:: >> tracker = BBBlastTracker('modelPanel1') >> tracker.install() >> tracker.uninstall() # OR >> BBBlastTracker.install_from_active_panel() """ super(BBBlastTracker, self).__init__() self.editor = editor self.last_appearance = cmds.modelEditor(self.editor, q=True, displayAppearance=True) self.restore_on_release = True self.timer = None self.timeout = 0.05 # get QWidget from the view view = apiUI.M3dView() apiUI.M3dView.getM3dViewFromModelPanel(self.editor, view) self.view = shiboken2.wrapInstance(long(view.widget()), QtWidgets.QWidget) self.__class__._all.append(self)
view.drawText("Swiss Army Manipulator", textPos, OpenMayaUI.M3dView.kLeft) view.endGL() def plugToManipConversion(self, theIndex): numData = OpenMaya.MFnNumericData() numDataObj = numData.create(OpenMaya.MFnNumericData.k3Float)
def getMayaMainWindow(): """ :return: maya main window as a python object """ win = omui.MQtUtil_mainWindow() ptr = wrapInstance(int(win), QtWidgets.QMainWindow) return ptr
def getDock(name='CoutureDock'): """ Get the ptr to a dockable location for Couture @param name: str, name of the Couture dockable window @return ptr: ptr the dock windows newly created """ deleteDock(name) if maya_api_version() < MAYA2017: ctrl = pm.dockControl(name, area='right', content='Couture', allowedArea='all', label="Couture tool", vis=True, r=True) print "do ctrl" # And then we return the control name return ctrl else: # ctrl = pm.workspaceControl(name, dockToMainWindow=('right', 1), label="Couture tool") ctrl = pm.workspaceControl(name, dockToMainWindow=('right', 1), label="Couture tool", loadImmediately=True, vis=True, r=True) qtCtrl = omui.MQtUtil_findControl(ctrl) ptr = wrapInstance(long(qtCtrl), QtWidgets.QWidget) return ptr
def testObjectNormal(self): """ Tests that an object created interactively by dragging in the viewport has the correct orientation based on the live surface normal. """ from pxr import Gf # Load our reference assembly. UsdMaya.LoadReferenceAssemblies() # Create a new custom viewport. window = cmds.window(widthHeight=(500, 400)) cmds.paneLayout() panel = cmds.modelPanel() cmds.modelPanel(panel, edit=True, camera='persp') cmds.modelEditor(cmds.modelPanel(panel, q=True, modelEditor=True), edit=True, displayAppearance='smoothShaded', rnm='vp2Renderer') cmds.showWindow(window) # Get the viewport widget. view = OMUI.M3dView() OMUI.M3dView.getM3dViewFromModelPanel(panel, view) viewWidget = wrapInstance(long(view.widget()), QWidget) # Make our assembly live. cmds.makeLive('Block_2') # Enter interactive creation context. cmds.setToolTo('CreatePolyConeCtx') # Click in the center of the viewport widget. QTest.mouseClick(viewWidget, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, viewWidget.rect().center()) # Find the cone (it should be called pCone1). self.assertTrue(cmds.ls('pCone1')) # Check the cone's rotation. # Because our scene is Z-axis up, the cone's Z-axis should be aligned # with Block_2's surface normal (though it might not necessarily have # the same exact rotation). rotationAngles = cmds.xform('pCone1', q=True, ro=True) rotation = (Gf.Rotation(Gf.Vec3d.XAxis(), rotationAngles[0]) * Gf.Rotation(Gf.Vec3d.YAxis(), rotationAngles[1]) * Gf.Rotation(Gf.Vec3d.ZAxis(), rotationAngles[2])) actualZAxis = rotation.TransformDir(Gf.Vec3d.ZAxis()) expectedRotation = (Gf.Rotation(Gf.Vec3d.XAxis(), 75.0) * Gf.Rotation(Gf.Vec3d.YAxis(), 90.0)) expectedZAxis = expectedRotation.TransformDir(Gf.Vec3d.ZAxis()) # Verify that the error angle between the two axes is less than # 0.1 degrees (less than ~0.0003 of a revolution, so not bad). That's # about as close as we're going to get. errorRotation = Gf.Rotation(actualZAxis, expectedZAxis) self.assertLess(errorRotation.GetAngle(), 0.1)
def getDock(name='LightingManagerDock'): deleteDock(name) ctrl = pm.workspaceControl(name, dockToMainWindow=('right', 1), label="Lighting Manager") qtCtrl = omui.MQtUtil_findControl(ctrl) ptr = wrapInstance(long(qtCtrl), QtWidgets.QWidget) return ptr
def createChildren(self): self.fDistanceManip = self.addDistanceManip("distanceManip", "distance") distanceManipFn = OpenMayaUI.MFnDistanceManip(self.fDistanceManip) startPoint = OpenMaya.MPoint(0.0, 0.0, 0.0) direction = OpenMaya.MVector(0.0, 1.0, 0.0) distanceManipFn.setStartPoint(startPoint) distanceManipFn.setDirection(direction) self.fFreePointManip = self.addFreePointTriadManip("pointManip", "freePoint")
def getCam(self): # get current view currentView = omui.M3dView().active3dView() dag = om.MDagPath() cam = currentView.getCamera(dag) cam = om.MFnCamera(dag) return cam
def startPointCallback(self, index): numData = OpenMaya.MFnNumericData() numDataObj = numData.create(OpenMaya.MFnNumericData.k3Double) vec = self.nodeTranslation() numData.setData3Double(vec.x, vec.y, vec.z) return OpenMayaUI.MManipData(numDataObj)