示例#1
0
 def __init__(self, sys_argv):
     # sys_argv += ['-style', 'material']  #! MUST HAVE
     self._m_vtkFboItem = None
     QApplication.setAttribute(Qt.AA_UseDesktopOpenGL)
     QSurfaceFormat.setDefaultFormat(
         defaultVtkFormat(False))  # from vtk 8.2.0
     super(App, self).__init__(sys_argv)
示例#2
0
def set_format() -> QSurfaceFormat:
    surface_format = QSurfaceFormat()
    surface_format.setVersion(4, 1)
    surface_format.setProfile(QSurfaceFormat.CoreProfile)
    surface_format.setSamples(4)
    QSurfaceFormat.setDefaultFormat(surface_format)

    return surface_format
示例#3
0
 def __init__(self, parent=None):
     QOpenGLWidget.__init__(self, parent)
     self.gl_format = QSurfaceFormat()
     self.gl_format.setRenderableType(QSurfaceFormat.OpenGL)
     self.gl_format.setProfile(QSurfaceFormat.CoreProfile)
     self.gl_format.setVersion(4, 1)
     self.setFormat(self.gl_format)
     self.mouse_x = 0
     self.mouse_y = 0
     self.mouse_init = False
     self.mouse_pressed = False
示例#4
0
    def __init__(self, sys_argv):
        super().__init__()
        self.__m_previousWorldX:float = 0.0
        self.__m_previousWorldY:float = 0.0
        self.__m_draggingMouse:bool = False
        self.__m_showFileDialog:bool = False
        self.__m_vtkFboItem = None
        #* Set style: https://stackoverflow.com/questions/43093797/PySide2-quickcontrols-material-style
        sys_argv += ['--style', 'material'] #! MUST HAVE

        QSurfaceFormat.setDefaultFormat(FboItem.defaultSurfaceFormat(False))
        app = QApplication(sys_argv)

        engine = QQmlApplicationEngine()
        # engine.setImportPathList(['C:\\Users\\tungdao\\.conda\\envs\\qtvtkpy\\Lib\\site-packages\\PySide2\\qml'])
        # print(engine.importPathList())
        app.setApplicationName('QtVTK-Py')

        #* Register QML Types
        qmlRegisterType(FboItem, 'QtVTK', 1, 0, 'VtkFboItem')

        # #* Create classes instances
        self.__m_processingEngine = ProcessingEngine()

        # #* Expose/Bind Python classes (QObject) to QML
        ctxt = engine.rootContext() # returns QQmlContext
        ctxt.setContextProperty('canvasHandler', self)

        # #* Load main QML file
        engine.load(QUrl.fromLocalFile('resources/main.qml'))

        # #* Get reference to the QVTKFramebufferObjectItem in QML
        rootObject = engine.rootObjects()[0] # returns QObject
        self.__m_vtkFboItem = rootObject.findChild(FboItem, 'vtkFboItem')

        # # #* Give the vtkFboItem reference to the CanvasHandler
        if (self.__m_vtkFboItem):
            qDebug('CanvasHandler::CanvasHandler: setting vtkFboItem to CanvasHandler')
            self.__m_vtkFboItem.setProcessingEngine(self.__m_processingEngine)

            self.__m_vtkFboItem.rendererInitialized.connect(self.startApplication)
            self.__m_vtkFboItem.isModelSelectedChanged.connect(self.isModelSelectedChanged)
            self.__m_vtkFboItem.selectedModelPositionXChanged.connect(self.selectedModelPositionXChanged)
            self.__m_vtkFboItem.selectedModelPositionYChanged.connect(self.selectedModelPositionYChanged)
        else:
            qCritical('CanvasHandler::CanvasHandler: Unable to get vtkFboItem instance')
            return

        rc = app.exec_()
        qDebug(f'CanvasHandler::CanvasHandler: Execution finished with return code: {rc}')
示例#5
0
文件: view.py 项目: nitrotm/3dtagger
 def __init__(self, project, filename, parent):
   self.mutex = QMutex()
   self.project = project
   self.filename = filename
   self.parent = parent
   self.surface = QOffscreenSurface()
   self.surface.setFormat(QSurfaceFormat.defaultFormat())
   self.surface.create()
示例#6
0
 def __init__(self, parent=None):
     QWindow.__init__(self, parent)
     self.setSurfaceType(QSurface.OpenGLSurface)
     self.gl_format = QSurfaceFormat()
     self.gl_format.setRenderableType(QSurfaceFormat.OpenGL)
     self.gl_format.setProfile(QSurfaceFormat.CoreProfile)
     self.gl_format.setVersion(4, 1)
     self.setFormat(self.gl_format)
     if self.supportsOpenGL():
         print("OpenGL supported !")
     self.mouse_x = 0
     self.mouse_y = 0
     self.mouse_init = False
     self.animating = False
     self.requestRender.connect(self.requestUpdate)
     # self.setMouseGrabEnabled(True)
     self.mouse_pressed = False
示例#7
0
 def __init__(self):
     super(MainWindow, self).__init__()
     hBoxLayout = QHBoxLayout(self)
     self.plainTextEdit = QPlainTextEdit()
     self.plainTextEdit.setMinimumWidth(400)
     self.plainTextEdit.setReadOnly(True)
     hBoxLayout.addWidget(self.plainTextEdit)
     self.renderWindow = RenderWindow(QSurfaceFormat())
     container = QWidget.createWindowContainer(self.renderWindow)
     container.setMinimumSize(QSize(400, 400))
     hBoxLayout.addWidget(container)
示例#8
0
    def __init__(self, id: str, app: QGuiApplication):
        assert self._initialized
        self.id = id
        self.app = app
        self.qml_view = QUrl(os.fspath(get_data_path("webview.qml")))

        gl_context = QOpenGLContext()
        gl_context.setFormat(QSurfaceFormat.defaultFormat())
        gl_context.create()

        self.client = Client(id, self.qml_view, gl_context)
        self.client.disconnected.connect(self.on_disconnected)
        self.client.start()
示例#9
0
 def create_gl_widget():
     # QGLWidget Not currently available in pyside2.
     # It has actually been deprecated and we should use
     # QtGui.QGLFormat and other related classes instead.
     from PyQt5.QtWidgets import QOpenGLWidget
     from PyQt5.QtGui import QSurfaceFormat
     from PyQt5 import QtOpenGL
     QGLFormat = QtOpenGL.QGLFormat
     QGL = QtOpenGL.QGL
     open_gl_widget = QOpenGLWidget()
     fmt = QSurfaceFormat.defaultFormat()
     fmt.setSamples(8)
     open_gl_widget.setFormat(fmt)
     return open_gl_widget
示例#10
0
class GLWidget(QOpenGLWidget):
    def __init__(self, parent=None):
        QOpenGLWidget.__init__(self, parent)
        self.gl_format = QSurfaceFormat()
        self.gl_format.setRenderableType(QSurfaceFormat.OpenGL)
        self.gl_format.setProfile(QSurfaceFormat.CoreProfile)
        self.gl_format.setVersion(4, 1)
        self.setFormat(self.gl_format)
        self.mouse_x = 0
        self.mouse_y = 0
        self.mouse_init = False
        self.mouse_pressed = False

    def paintGL(self):
        display_loop(c_double(0.0), c_uint(self.defaultFramebufferObject()))

    def resizeGL(self, width, height):
        width = c_double(self.size().width())
        height = c_double(self.size().height())
        dpi_ratio = c_double(self.devicePixelRatio())
        resize_window(width, height, dpi_ratio)

    def initializeGL(self):
        width = c_double(self.size().width())
        height = c_double(self.size().height())
        dpi_ratio = c_double(self.devicePixelRatio())
        load_gl_symbol()
        init_gl(width, height, dpi_ratio)
        print_gl_info()
        init_scene(width, height, dpi_ratio)

    def mousePressEvent(self, ev):
        if ev.button() == Qt.LeftButton:
            self.mouse_pressed = True

    def mouseReleaseEvent(self, ev):
        if ev.button() == Qt.LeftButton:
            self.mouse_pressed = False
            self.mouse_init = False

    def mouseMoveEvent(self, ev):
        pos = ev.localPos()
        if self.mouse_pressed:
            if not self.mouse_init:
                self.mouse_x = pos.x()
                self.mouse_y = pos.y()
                self.mouse_init = True
            else:
                dx = self.mouse_x - pos.x()
                dy = self.mouse_y - pos.y()
                self.mouse_x = pos.x()
                self.mouse_y = pos.y()
                handle_mouse(c_float(dx), c_float(dy), c_float(0.001))
                self.update()
示例#11
0
    def __init__(self, argv: List[str]):
        super().__init__(argv)
        self.setApplicationName('Qt Offscreen Rendering')

        format = QSurfaceFormat()
        format.setDepthBufferSize(16)
        format.setStencilBufferSize(8)

        self.window = MainWindow(format)
        self.window.addQmlView('View', os.path.join(os.path.dirname(__file__), 'view.qml'))
        self.window.addQmlView('Web', os.path.join(os.path.dirname(__file__), 'web.qml'))
示例#12
0
        self.__slot_channels()

    def __slot_checkerboard(self):
        self._viewport.set_colors(True, None, None)

    def __slot_solid_color(self):
        color = QColorDialog.getColor(Qt.black, self,
                                      "Choose background color")
        if color.isValid():
            self._viewport.set_colors(False, color, color)


if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)
    # must be called before the OpenGLWidget or its parent window gets shown
    # set default OpenGL surface format
    glformat = QSurfaceFormat()
    glformat.setDepthBufferSize(24)
    glformat.setStencilBufferSize(8)
    glformat.setVersion(3, 1)
    glformat.setProfile(QSurfaceFormat.CoreProfile)
    QSurfaceFormat.setDefaultFormat(glformat)
    # Create and show the form
    form = TViewerWindow()
    form.show()
    sample = join(dirname(realpath(__file__)), "rgba.tga")
    form.view(sample)
    # Run the main Qt loop
    sys.exit(app.exec_())
示例#13
0
def get_default_format(*, gles: bool):
    fmt = QSurfaceFormat()
    fmt.setVersion(2, 0)
    fmt.setProfile(QSurfaceFormat.CoreProfile)
    fmt.setRenderableType(
        QSurfaceFormat.OpenGLES if gles else QSurfaceFormat.OpenGL)
    fmt.setDepthBufferSize(24)
    fmt.setStencilBufferSize(8)
    fmt.setOption(QSurfaceFormat.DebugContext)
    return fmt
示例#14
0
def initialize_gl():
    QSurfaceFormat.setDefaultFormat(get_default_format(gles=True))
    QGuiApplication.setAttribute(Qt.AA_UseOpenGLES, True)
    QGuiApplication.setAttribute(Qt.AA_ShareOpenGLContexts, True)
示例#15
0
    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Escape:
            exit()
        elif key == Qt.Key_W:
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        elif key == Qt.Key_S:
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        self.update()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    format = QSurfaceFormat()
    format.setSamples(4)
    format.setMajorVersion(4)
    format.setMinorVersion(1)
    format.setProfile(QSurfaceFormat.CoreProfile)
    # now set the depth buffer to 24 bits
    format.setDepthBufferSize(24)
    # set that as the default format for all windows
    QSurfaceFormat.setDefaultFormat(format)

    window = MainWindow()
    window.setFormat(format)
    window.resize(1024, 720)
    window.show()
    sys.exit(app.exec_())
示例#16
0
class GLWin(QWindow):
    requestRender = Signal()

    def __init__(self, parent=None):
        QWindow.__init__(self, parent)
        self.setSurfaceType(QSurface.OpenGLSurface)
        self.gl_format = QSurfaceFormat()
        self.gl_format.setRenderableType(QSurfaceFormat.OpenGL)
        self.gl_format.setProfile(QSurfaceFormat.CoreProfile)
        self.gl_format.setVersion(4, 1)
        self.setFormat(self.gl_format)
        if self.supportsOpenGL():
            print("OpenGL supported !")
        self.mouse_x = 0
        self.mouse_y = 0
        self.mouse_init = False
        self.animating = False
        self.requestRender.connect(self.requestUpdate)
        # self.setMouseGrabEnabled(True)
        self.mouse_pressed = False

    def mousePressEvent(self, ev):
        if ev.button() == Qt.LeftButton:
            self.mouse_pressed = True

    def mouseReleaseEvent(self, ev):
        if ev.button() == Qt.LeftButton:
            self.mouse_pressed = False
            self.mouse_init = False

    def mouseMoveEvent(self, ev):
        pos = ev.localPos()
        if self.mouse_pressed:
            if not self.mouse_init:
                self.mouse_x = pos.x()
                self.mouse_y = pos.y()
                self.mouse_init = True
            else:
                dx = self.mouse_x - pos.x()
                dy = self.mouse_y - pos.y()
                self.mouse_x = pos.x()
                self.mouse_y = pos.y()
                handle_mouse(c_float(dx), c_float(dy), c_float(0.001))

    def start(self):
        self.animating = True
        self.renderLater()

    def render(self):
        display_loop(c_double(0.0))

    def renderLater(self):
        self.requestRender.emit()

    def renderNow(self):
        if not self.isExposed():
            return
        self.render()
        self.gl_context.swapBuffers(self)
        if self.animating:
            self.renderLater()

    def init_context(self):
        self.gl_context = QOpenGLContext(self)
        self.gl_context.setFormat(self.gl_format)
        if self.gl_context.create():
            print("Context created !")
        if self.gl_context.makeCurrent(self):
            print("Context made current !")

    def init_scene(self):
        width = c_double(self.size().width())
        height = c_double(self.size().height())
        dpi_ratio = c_double(self.devicePixelRatio())

        load_gl_symbol()
        init_gl(width, height, dpi_ratio)
        print_gl_info()
        init_scene(width, height, dpi_ratio)

    def resize(self):
        if self.isExposed():
            width = c_double(self.size().width())
            height = c_double(self.size().height())
            dpi_ratio = c_double(self.devicePixelRatio())
            resize_window(width, height, dpi_ratio)

    def event(self, ev):
        if ev.type() == QEvent.UpdateRequest:
            self.renderNow()
            return True
        else:
            return super().event(ev)

    def exposeEvent(self, ev):
        self.renderLater()

    def resizeEvent(self, ev):
        self.resize()
        self.renderLater()
示例#17
0
from PySide2.QtCore import QObject, QUrl, qDebug, qCritical, QFileInfo, QEvent, Qt, QSize, Signal
from PySide2.QtGui import QSurfaceFormat, QColor, QMouseEvent, QWheelEvent, QOpenGLFramebufferObject, QOpenGLFramebufferObjectFormat, QOpenGLFunctions
from PySide2.QtQuick import QQuickFramebufferObject

from Model import Model, setSelectedModelColor
from ProcessingEngine import ProcessingEngine

import numpy as np
import vtk
import logging
from OpenGL import GL

#* https://github.com/Kitware/VTK/blob/master/GUISupport/Qt/QVTKOpenGLNativeWidget.cxx
fmt = QSurfaceFormat()
fmt.setRenderableType(QSurfaceFormat.OpenGL)
fmt.setVersion(3, 2)
fmt.setProfile(QSurfaceFormat.CoreProfile)
fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
fmt.setRedBufferSize(8)
fmt.setGreenBufferSize(8)
fmt.setBlueBufferSize(8)
fmt.setDepthBufferSize(8)
fmt.setAlphaBufferSize(8)
fmt.setStencilBufferSize(0)
fmt.setStereo(True)
fmt.setSamples(
    0
)  # we never need multisampling in the context since the FBO can support multisamples independently


class SquircleInFboRenderer(QQuickFramebufferObject.Renderer):
示例#18
0
        dx = event.x() - self.lastPos.x()
        dy = event.y() - self.lastPos.y()

        if event.buttons() & Qt.LeftButton:
            self.setXRotation(self.xRot + 8 * dy)
            self.setYRotation(self.yRot + 8 * dx)
        elif event.buttons() & Qt.RightButton:
            self.setXRotation(self.xRot + 8 * dy)
            self.setZRotation(self.zRot + 8 * dx)

        self.lastPos = QPoint(event.pos())

if __name__ == '__main__':
    app = QApplication(sys.argv)

    fmt = QSurfaceFormat()
    fmt.setDepthBufferSize(24)
    if "--multisample" in QCoreApplication.arguments():
        fmt.setSamples(4)
    if "--coreprofile" in QCoreApplication.arguments():
        fmt.setVersion(3, 2)
        fmt.setProfile(QSurfaceFormat.CoreProfile)
    QSurfaceFormat.setDefaultFormat(fmt)

    mainWindow = Window()
    if "--transparent" in QCoreApplication.arguments():
        mainWindow.setAttribute(Qt.WA_TranslucentBackground)
        mainWindow.setAttribute(Qt.WA_NoSystemBackground, False)

    mainWindow.resize(mainWindow.sizeHint())
    mainWindow.show()
示例#19
0
def defaultVtkFormat(stereo_capable):
    """ Po prostu skopiowałem to z https://github.com/Kitware/VTK/blob/master/GUISupport/Qt/QVTKRenderWindowAdapter.cxx
     i działa poprawnie bufor głębokości
    """
    fmt = QSurfaceFormat()
    fmt.setRenderableType(QSurfaceFormat.OpenGL)
    fmt.setVersion(3, 2)
    fmt.setProfile(QSurfaceFormat.CoreProfile)
    fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
    fmt.setRedBufferSize(8)
    fmt.setGreenBufferSize(8)
    fmt.setBlueBufferSize(8)
    fmt.setDepthBufferSize(8)
    fmt.setAlphaBufferSize(8)
    fmt.setStencilBufferSize(0)
    fmt.setStereo(stereo_capable)
    fmt.setSamples(0)
    return fmt
示例#20
0
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtGui import QSurfaceFormat
from PySide2.QtCore import Qt

from PolyEdit3D.Widgets import PlyMainWindow
from PolyEdit3D.GL.Setup import GLSurfaceFormat

if __name__ == '__main__':
    QApplication.setAttribute(Qt.AA_UseDesktopOpenGL)
    QSurfaceFormat.setDefaultFormat(GLSurfaceFormat())

    app = QApplication()

    window = PlyMainWindow()
    window.show()

    sys.exit(app.exec_())
    def defaultSurfaceFormat(stereo_capable):
        """ Ported from: https://github.com/Kitware/VTK/blob/master/GUISupport/Qt/QVTKRenderWindowAdapter.cxx
        """
        fmt = QSurfaceFormat()
        fmt.setRenderableType(QSurfaceFormat.OpenGL)
        fmt.setVersion(3, 2)
        fmt.setProfile(QSurfaceFormat.CoreProfile)
        fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
        fmt.setRedBufferSize(8)
        fmt.setGreenBufferSize(8)
        fmt.setBlueBufferSize(8)
        fmt.setDepthBufferSize(8)
        fmt.setAlphaBufferSize(8)
        fmt.setStencilBufferSize(0)
        fmt.setStereo(stereo_capable)
        fmt.setSamples(0)

        return fmt
示例#22
0
 def is_good_opengl_version():
     from PyQt5.QtGui import QSurfaceFormat
     default_format = QSurfaceFormat.defaultFormat()
     return default_format.majorVersion() >= 2
示例#23
0
def print_surface_format(surface_format: QSurfaceFormat) -> str:
    return "{} version {}.{}".format(
        'core' if surface_format.profile() == QSurfaceFormat.CoreProfile else 'compatibility',
        surface_format.majorVersion(),
        surface_format.minorVersion(),
    )
示例#24
0
    def initialize(self, size: QSize, shareContext: QOpenGLContext) -> None:
        """
        Initialize offscreen renderer.

        Args:
            size: The size of the area available for rendering.
            shareContext: OpenGL context used as a share context.

        Raises:
            RuntimeError: If the renderer has already been initialized.
        """
        print(f'QmlOffscreenRenderer.initialize: {size}')
        if self.initialized:
            raise RuntimeError('Already initialized')

        format = QSurfaceFormat()
        format.setDepthBufferSize(16)
        format.setStencilBufferSize(8)
        context = QOpenGLContext()
        context.setFormat(format)
        context.setShareContext(shareContext)
        context.create()

        self.size = size
        self.context = context

        # Create offscreen surface with initialized format
        self._surface = surface = QOffscreenSurface()
        surface.setFormat(context.format())
        surface.create()

        # Set up quick rendering
        self._control = control = QQuickRenderControl()
        self._window = window = QQuickWindow(control)
        self._engine = engine = QQmlEngine()
        if not engine.incubationController():
            engine.setIncubationController(window.incubationController())

        # Don't polish/sync/render immediately for better performance, use a timer
        self._renderTimer = renderTimer = QTimer()
        renderTimer.setSingleShot(True)
        renderTimer.setInterval(5)
        renderTimer.timeout.connect(self._onRenderTimer)
        self._syncTimer = syncTimer = QTimer()
        syncTimer.setSingleShot(True)
        syncTimer.setInterval(5)
        syncTimer.timeout.connect(self._onSyncTimer)
        syncTimer.destroyed.connect(self._onSyncTimerDestroyed)

        # Request to create frame buffer
        window.sceneGraphInitialized.connect(self._onSceneGraphInitialized)
        # Request to release frame buffer
        window.sceneGraphInvalidated.connect(self._onSceneGraphInvalidated)
        # Only render is needed
        control.renderRequested.connect(self._onRenderRequested)
        # Polish, sync & render
        control.sceneChanged.connect(self._onSceneChanged)

        self.initialized = True

        # Load QML component
        self._component = component = QQmlComponent(self._engine, self.qmlUrl)
        if component.isLoading():
            component.statusChanged.connect(self._onComponentStatusChanged)
        else:
            self._attachRootItem()
示例#25
0
        transform = QMatrix4x4()
        transform.setToIdentity()
        transform.rotate(self.timer.elapsed() / 10, QVector3D(0, 0, 1))
        transform.translate(QVector3D(0.25, 0.25, -2.))

        projection = QMatrix4x4()
        projection.setToIdentity()
        projection.perspective(45.,
                               float(self.width()) / self.height(), 0.1, 100.)

        self.square.render(projection * transform)


if __name__ == '__main__':
    app = QGuiApplication(sys.argv)
    format = QSurfaceFormat()
    format.setProfile(QSurfaceFormat.CoreProfile)
    format.setVersion(3, 3)

    win = Window()
    win.setFormat(format)
    win.resize(800, 600)
    win.show()

    timer = QTimer()
    timer.start(20)
    timer.timeout.connect(win.update)

    def cleanup():
        global win
        win.makeCurrent()
示例#26
0
文件: app.py 项目: nitrotm/2dtagger
# app.py: application entry point
#
# author: Antony Ducommun dit Boudry ([email protected])
# license: GPL
#

import sys

from PySide2.QtCore import QCoreApplication, QPoint, QSize, Qt
from PySide2.QtGui import QSurfaceFormat
from PySide2.QtWidgets import QApplication

from window import Window

if __name__ == '__main__':
    fmt = QSurfaceFormat()
    fmt.setRenderableType(QSurfaceFormat.OpenGL)
    fmt.setVersion(2, 1)
    fmt.setProfile(QSurfaceFormat.CoreProfile)
    fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
    fmt.setSwapInterval(1)
    fmt.setStereo(False)
    fmt.setSamples(0)
    fmt.setRedBufferSize(8)
    fmt.setGreenBufferSize(8)
    fmt.setBlueBufferSize(8)
    fmt.setAlphaBufferSize(8)
    fmt.setDepthBufferSize(24)
    fmt.setStencilBufferSize(1)
    QSurfaceFormat.setDefaultFormat(fmt)
        qimage = QFileDialog.getOpenFileName(None, 'OpenFile', 'C:\\',
                                             "Image file(*.jpeg *.jpg)")
        self.imageView.setVisible(1)
        self.imageView.setPixmap(QPixmap(qimage[0]).scaledToWidth(400))
        self.glWidget.updateImage(qimage[0])

    def showSaveDialog(self):
        filename = QFileDialog.getSaveFileName(self, "Save file", "", ".STL")
        print(filename[0])
        self.glWidget.generateSTL(filename[0] + filename[1])


if __name__ == '__main__':
    app = QApplication(sys.argv)

    fmt = QSurfaceFormat()
    if "--multisample" in QCoreApplication.arguments():
        fmt.setSamples(4)
    if "--coreprofile" in QCoreApplication.arguments():
        fmt.setVersion(3, 2)
        fmt.setProfile(QSurfaceFormat.CoreProfile)
    QSurfaceFormat.setDefaultFormat(fmt)

    mainWindow = Window()
    if "--transparent" in QCoreApplication.arguments():
        mainWindow.setAttribute(Qt.WA_TranslucentBackground)
        mainWindow.setAttribute(Qt.WA_NoSystemBackground, False)

    mainWindow.resize(mainWindow.sizeHint())
    mainWindow.show()
 def defaultFormat(stereo_capable):
     fmt = QSurfaceFormat()
     fmt.setRenderableType(QSurfaceFormat.OpenGL)
     fmt.setVersion(3, 2)
     fmt.setProfile(QSurfaceFormat.CoreProfile)
     fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
     fmt.setRedBufferSize(8)
     fmt.setGreenBufferSize(8)
     fmt.setBlueBufferSize(8)
     fmt.setDepthBufferSize(8)
     fmt.setAlphaBufferSize(8)
     fmt.setStencilBufferSize(0)
     fmt.setStereo(stereo_capable)
     fmt.setSamples(0)
     return fmt
示例#29
0
文件: main.py 项目: csdl-jbnu/ATHENA
    if NSWindow is None:
        return
    setAllowsAutomaticWindowTabbing = sel_registerName(
        b'setAllowsAutomaticWindowTabbing:')
    # class_respondsToSelector does not work (for class methods)
    if class_getClassMethod(NSWindow, setAllowsAutomaticWindowTabbing):
        # [NSWindow setAllowsAutomaticWindowTabbing: NO]
        objc_msgSend(
            NSWindow,
            setAllowsAutomaticWindowTabbing,
            ctypes.c_bool(False),
        )


fix_macos_nswindow_tabbing()
f = QSurfaceFormat()
f.setDepthBufferSize(24)
f.setSamples(4)
QSurfaceFormat.setDefaultFormat(f)


class DebugApp(QApplication):
    def notify(self, x, y):
        if (x.__class__ == QWindow and y.__class__ == QMouseEvent):
            x.event(y)
            return True
        if (y.__class__ == QMouseEvent):
            print('App:', x, y)
            print(y.isAccepted(), int(y.buttons()), int(y.source()))
        return super().notify(x, y)
示例#30
0
    def __init__(self, window):

        self.window = window

        self.offscreenSurface = QOffscreenSurface()
        sformat = QSurfaceFormat.defaultFormat()
        sformat.setDepthBufferSize(32)
        self.offscreenSurface.setFormat( sformat )
        self.offscreenSurface.create()

        self.overlayCamera = Qt3DRender.QCamera()
        self.overlayCamera.setViewCenter( vec3d() )
        self.overlayCamera.setPosition( vec3d( 0, 0, -1 ) )
        self.overlayCamera.setUpVector( vec3d( 0, 1, 0 ) )
        self.overlayCamera.lens().setOrthographicProjection( -1, 1, -1, 1, -1, 1 )

        # Framegraph root #1 -- onscreen rendering
        self.surfaceSelector = Qt3DRender.QRenderSurfaceSelector()
        self.surfaceSelector.setSurface(window)
        self.root = self.surfaceSelector


        # Framgraph root #2 -- Used for offscreen renders, not in the graph by default
        # During screenshots, offscreenSurfaceSelector becomes the root
        # and the branch roots will become a child of renderTargetSelector
        self.offscreenSurfaceSelector = Qt3DRender.QRenderSurfaceSelector()
        self.offscreenSurfaceSelector.setSurface(self.offscreenSurface)
        self.renderTargetSelector = Qt3DRender.QRenderTargetSelector(self.offscreenSurfaceSelector)
        self.targetTexture = OffscreenRenderTarget(self.renderTargetSelector)
        self.renderTargetSelector.setTarget(self.targetTexture)
        self.noDraw2 = Qt3DRender.QNoDraw(self.renderTargetSelector)

        # Branch 1: clear buffers
        self.clearBuffers = Qt3DRender.QClearBuffers(self.surfaceSelector)
        self.clearBuffers.setBuffers(Qt3DRender.QClearBuffers.ColorDepthBuffer)
        self.clearBuffers.setClearColor(Qt.white)
        self.noDraw = Qt3DRender.QNoDraw(self.clearBuffers)

        # Branch 2: main drawing branches using the Athena camera
        self.cameraSelector = Qt3DRender.QCameraSelector(self.surfaceSelector)
        self.cameraSelector.setCamera(window.camera())

        # Branch 2A: solid objects
        self.viewport = Qt3DRender.QViewport(self.cameraSelector)
        self.viewport.setNormalizedRect(QRectF(0, 0, 1.0, 1.0))
        self.qfilt = Qt3DRender.QTechniqueFilter(self.viewport)
        self.solidPassFilter = Qt3DRender.QFilterKey(self.qfilt)
        self.solidPassFilter.setName('pass')
        self.solidPassFilter.setValue('solid')
        self.qfilt.addMatch(self.solidPassFilter)

        # Branch 2B: transparent objects
        self.viewport2 = Qt3DRender.QViewport(self.cameraSelector)
        self.viewport2.setNormalizedRect(QRectF(0, 0, 1.0, 1.0))
        self.qfilt2 = Qt3DRender.QTechniqueFilter(self.viewport2)
        self.transPassFilter = Qt3DRender.QFilterKey(self.qfilt2)
        self.transPassFilter.setName('pass')
        self.transPassFilter.setValue('transp')
        self.qfilt2.addMatch(self.transPassFilter)

        # Branch 3: 2D screen overlays
        self.cameraSelector2 = Qt3DRender.QCameraSelector(self.surfaceSelector)
        self.cameraSelector2.setCamera(self.overlayCamera)
        self.viewport3 = Qt3DRender.QViewport(self.cameraSelector2)
        self.viewport3.setNormalizedRect(QRectF(0, 0, 1.0, 1.0))
        self.qfilt3 = Qt3DRender.QTechniqueFilter(self.viewport3)
        self.overlayPassFilter = Qt3DRender.QFilterKey(self.viewport3)
        self.overlayPassFilter.setName('pass')
        self.overlayPassFilter.setValue('overlay')
        self.qfilt3.addMatch(self.overlayPassFilter)

        # Branch 4: render capture branch for taking screenshots
        self.renderCapture = Qt3DRender.QRenderCapture(self.surfaceSelector)
        self.noDraw3 = Qt3DRender.QNoDraw(self.renderCapture)

        # Branch roots are the bits that need reparenting when switching between
        # offscreen and onscreen rendering
        self.branchRoots = [ self.clearBuffers, self.cameraSelector, self.cameraSelector2, self.renderCapture ]