def initializeGL(self): f = QSurfaceFormat() #f.setVersion(2, 2) f.setDepthBufferSize(32) p = QOpenGLVersionProfile(f) self.gl = self.context().versionFunctions(p) self.gl.initializeOpenGLFunctions() self.setClearColor(self._bgColor) self.loadObject() if not BATCH_MODE: self.loadTargetImageMeta( self.systemModel.asteroid.sample_image_meta_file) self.gl.glEnable(self.gl.GL_CULL_FACE) # for transparent asteroid image on top of model self.gl.glBlendFunc(self.gl.GL_SRC_ALPHA, self.gl.GL_ONE_MINUS_SRC_ALPHA) if self._render: self._rendOpts() else: self._projOpts() if not BATCH_MODE: self.loadTargetImage(self.systemModel.asteroid.sample_image_file)
def create_format(): fmt = QSurfaceFormat() fmt.setProfile(QSurfaceFormat.CoreProfile) fmt.setVersion(3, 3) #vmware max opengl version is 3.3 fmt.setAlphaBufferSize(8) fmt.setStencilBufferSize(8) fmt.setDepthBufferSize(24) fmt.setOption(QSurfaceFormat.DebugContext) return fmt
def __init__(self, parent=None, **kwargs): super(ViewerWindow, self).__init__(parent) self.setSurfaceType(QWindow.OpenGLSurface) format = QSurfaceFormat() format.setVersion(3, 3) format.setProfile(QSurfaceFormat.CoreProfile) format.setStereo(False) format.setSwapBehavior(QSurfaceFormat.DoubleBuffer) format.setDepthBufferSize(24) format.setSamples(16) self.context = QOpenGLContext(self) self.context.setFormat(format) if not self.context.create(): raise Exception('self.context.create() failed') self.create() size = 720, 720 self.resize(*size) self.context.makeCurrent(self) self.hud_program = CrossHairProgram() self.default_view = np.eye(4, dtype=np.float32) self.view = self.default_view self.model = np.eye(4, dtype=np.float32) self.projection = np.eye(4, dtype=np.float32) self.layer_manager = LayerManager() self.visibility_toggle_listeners = [] self.multiview = True self.rotation = q.quaternion() self.scale = 0.6 self.translation = np.zeros(3) self.radius = 0.5 * min(*size) self.fov = 5. self.camera_position = -12. self.near_clip = .1 if 'near_clip' in kwargs: self.near_clip = kwargs['near_clip'] self.far_clip = 100. if 'far_clip' in kwargs: self.far_clip = kwargs['far_clip'] self.projection_mode = 'perspective' # 'orthographic' self.size = size self.bg_white = False self.viewpoint_dict = {} print((self.instructions))
def __init__(self, args, glWidget=QOpenGLWidget, requestedGLVersion=(2, 1)): super(_TestApplication, self).__init__(args) glType = QOpenGLContext.openGLModuleType() format = QSurfaceFormat() format.setDepthBufferSize(24) if glType == QOpenGLContext.LibGL: info("OPENGL MODULE TYPE", "LibGL") format.setVersion(requestedGLVersion[0], requestedGLVersion[1]) format.setProfile(QSurfaceFormat.CompatibilityProfile) format.setOption(QSurfaceFormat.DebugContext) QSurfaceFormat.setDefaultFormat(format) else: info( "OPENGL MODULE TYPE", "Unknown or LibGLES <--- this is likely to cause problems down the line" ) self.debugMembers = False self.mainWin = QWidget() if glWidget == QOpenGLWidget: # Only hard code size if we're not using a canvas self.mainWin.resize(600, 600) self.mainWin.setWindowTitle('TestApplication') self.mainWidget = glWidget() self.layout = QHBoxLayout(self.mainWin) self.layout.addWidget(self.mainWidget) self.mainWin.show() ctx = QOpenGLContext.currentContext() info("GL CURRENT CONTEXT", ctx) format = ctx.format() info("EFFECTIVE GL VERSION", ctx.format().version()) self.aboutToQuit.connect(self.applicationClosing)
def main(): qt_set_sequence_auto_mnemonic(False) if hasattr(Qt, 'AA_EnableHighDpiScaling'): QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) if hasattr(Qt, 'AA_Use96Dpi'): QGuiApplication.setAttribute(Qt.AA_Use96Dpi, True) if hasattr(Qt, 'AA_ShareOpenGLContexts'): fmt = QSurfaceFormat() fmt.setDepthBufferSize(24) QSurfaceFormat.setDefaultFormat(fmt) QGuiApplication.setAttribute(Qt.AA_ShareOpenGLContexts, True) # if sys.platform == 'darwin': # qApp.setStyle('Fusion') app = SingleApplication(vidcutter.__appid__, sys.argv) app.setApplicationName(vidcutter.__appname__) app.setApplicationVersion(vidcutter.__version__) app.setDesktopFileName(vidcutter.__desktopid__) app.setOrganizationDomain(vidcutter.__domain__) app.setQuitOnLastWindowClosed(True) win = MainWindow() win.stylename = app.style().objectName().lower() app.setActivationWindow(win) app.messageReceived.connect(win.file_opener) app.aboutToQuit.connect(MainWindow.cleanup) exit_code = app.exec_() if exit_code == MainWindow.EXIT_CODE_REBOOT: if sys.platform == 'win32': if hasattr(win.cutter, 'mpvWidget'): win.close() QProcess.startDetached('"{}"'.format(qApp.applicationFilePath())) else: QProcess.startDetached(' '.join(sys.argv)) sys.exit(exit_code)
from PyQt5.QtGui import QSurfaceFormat from PyQt5.QtWidgets import QFormLayout, QHBoxLayout, QInputDialog, QLabel, QLineEdit from PyQt5.QtWidgets import QMessageBox, QOpenGLWidget, QPushButton, QVBoxLayout from PyQt5.QtWidgets import QWidget from strike_with_a_pose.scene import Scene from strike_with_a_pose.settings import INITIAL_PARAMS, MODEL, TRUE_CLASS INSTRUCTIONS_F = pkg_resources.resource_filename("strike_with_a_pose", "instructions.html") ABOUT_F = pkg_resources.resource_filename("strike_with_a_pose", "about.html") fmt = QSurfaceFormat() fmt.setVersion(3, 3) fmt.setProfile(QSurfaceFormat.CoreProfile) fmt.setSwapInterval(1) fmt.setDepthBufferSize(24) fmt.setSamples(3) QSurfaceFormat.setDefaultFormat(fmt) class WindowInfo: def __init__(self): self.size = (0, 0) self.mouse = (0, 0) self.wheel = 0 self.time = 0 self.ratio = 1.0 self.viewport = (0, 0, 0, 0) self.keys = np.full(256, False) self.old_keys = np.copy(self.keys)
def main(): # make the Python warnings go to Friture logger logging.captureWarnings(True) logFormat = "%(asctime)s %(levelname)s %(name)s: %(message)s" formatter = logging.Formatter(logFormat) logFileName = "friture.log.txt" dirs = appdirs.AppDirs("Friture", "") logDir = dirs.user_data_dir try: os.makedirs(logDir) except OSError as e: if e.errno != errno.EEXIST: raise logFilePath = os.path.join(logDir, logFileName) # log to file fileHandler = logging.handlers.RotatingFileHandler(logFilePath, maxBytes=100000, backupCount=5) fileHandler.setLevel(logging.DEBUG) fileHandler.setFormatter(formatter) rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) rootLogger.addHandler(fileHandler) if hasattr(sys, "frozen"): # redirect stdout and stderr to the logger if this is a pyinstaller bundle sys.stdout = StreamToLogger(logging.getLogger('STDOUT'), logging.INFO) sys.stderr = StreamToLogger(logging.getLogger('STDERR'), logging.ERROR) else: # log to console if this is not a pyinstaller bundle console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) rootLogger.addHandler(console) # make Qt logs go to Friture logger QtCore.qInstallMessageHandler(qt_message_handler) logger = logging.getLogger(__name__) logger.info("Friture %s starting on %s (%s)", friture.__version__, platform.system(), sys.platform) # make sure Qt loads the desktop OpenGL stack, rather than OpenGL ES or a software OpenGL # only the former option is compatible with the use of PyOpenGL QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_UseDesktopOpenGL) if platform.system() == "Windows": logger.info("Applying Windows-specific setup") # enable automatic scaling for high-DPI screens os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" # set the App ID for Windows 7 to properly display the icon in the # taskbar. import ctypes myappid = 'Friture.Friture.Friture.current' # arbitrary string try: ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( myappid) except: logger.error( "Could not set the app model ID. If the plaftorm is older than Windows 7, this is normal." ) app = QApplication(sys.argv) if platform.system() == "Darwin": logger.info("Applying Mac OS-specific setup") # help the packaged application find the Qt plugins (imageformats and platforms) pluginsPath = os.path.normpath( os.path.join(QApplication.applicationDirPath(), os.path.pardir, 'PlugIns')) logger.info("Adding the following to the Library paths: %s", pluginsPath) QApplication.addLibraryPath(pluginsPath) # on macOS, OpenGL 2.1 does not work well # request a 3.2 Core context instead format = QSurfaceFormat() format.setDepthBufferSize(24) format.setStencilBufferSize(8) format.setVersion(3, 2) format.setProfile(QSurfaceFormat.CoreProfile) QSurfaceFormat.setDefaultFormat(format) # Splash screen #pixmap = QPixmap(":/images/splash.png") #splash = QSplashScreen(pixmap) #splash.show() #splash.showMessage("Initializing the audio subsystem") app.processEvents() window = Friture() window.show() #splash.finish(window) profile = "no" # "python" or "kcachegrind" or anything else to disable if len(sys.argv) > 1: if sys.argv[1] == "--python": profile = "python" elif sys.argv[1] == "--kcachegrind": profile = "kcachegrind" elif sys.argv[1] == "--no": profile = "no" else: logger.info("command-line arguments (%s) not recognized", sys.argv[1:]) return_code = 0 if profile == "python": import cProfile import pstats # friture.cprof can be visualized with SnakeViz # http://jiffyclub.github.io/snakeviz/ # snakeviz friture.cprof cProfile.runctx('app.exec_()', globals(), locals(), filename="friture.cprof") logger.info("Profile saved to '%s'", "friture.cprof") stats = pstats.Stats("friture.cprof") stats.strip_dirs().sort_stats('time').print_stats(20) stats.strip_dirs().sort_stats('cumulative').print_stats(20) elif profile == "kcachegrind": import cProfile import lsprofcalltree p = cProfile.Profile() p.run('app.exec_()') k = lsprofcalltree.KCacheGrind(p) with open('cachegrind.out.00000', 'wb') as data: k.output(data) else: return_code = app.exec_() # explicitly delete the main windows instead of waiting for the interpreter shutdown # tentative to prevent errors on exit on macos del window sys.exit(return_code)
from PyQt5.QtCore import QUrl from PyQt5.QtGui import QGuiApplication, QOpenGLVersionProfile, QSurfaceFormat from PyQt5.QtQuick import QQuickView from PyQt5.QtQml import qmlRegisterType from _004_3d_loading_model_and_rotating.object import ModelUnderlay import platform if __name__ == '__main__': # Not working in Ubuntu 16.04, result in 1282 error for simple calling like glViewport(...) # TODO if platform.uname().system == 'Darwin': f = QSurfaceFormat() f.setVersion(4, 1) f.setDepthBufferSize(1) # fix depth buffer error f.setStencilBufferSize(1) # fix stencil buffer error # If CoreProfile is used, all the other QML rendering will fail, because they only use 2.1 f.setProfile(QSurfaceFormat.CompatibilityProfile) QSurfaceFormat.setDefaultFormat(f) qmlRegisterType(ModelUnderlay, 'OpenGLUnderQml', 1, 0, 'ModelUnderlay') app = QGuiApplication(sys.argv) view = QQuickView() # view.setFormat(f) view.setPersistentSceneGraph(True) view.setPersistentOpenGLContext(True) view.setResizeMode(QQuickView.SizeRootObjectToView) # Set for the object to resize correctly
self.translate = False def wheelEvent(self,event) : numPixels = event.pixelDelta(); if numPixels.x() > 0 : self.modelPos.m_z += self.ZOOM elif numPixels.x() < 0 : self.modelPos.m_z -= self.ZOOM 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_())
import sys from PyQt5.QtGui import QSurfaceFormat from PyQt5.QtWidgets import QApplication from mcjsontool.ui.ui import JSONToolUI import mcjsontool.plugin if __name__ == "__main__": app = QApplication(sys.argv) format_ = QSurfaceFormat() format_.setVersion(4, 3) format_.setDepthBufferSize(24) format_.setProfile(QSurfaceFormat.CoreProfile) QSurfaceFormat.setDefaultFormat(format_) # temp: setup temp workspac w = JSONToolUI() w.show() sys.exit(app.exec_())
int(self.height()*0.125), Qt.AlignCenter, text) painter.setRenderHint(QPainter.TextAntialiasing) painter.fillRect(QRect(0, 0, self.width(), rect.height() + 2*border), QColor(0, 0, 0, 127)) painter.setPen(Qt.white) painter.fillRect(QRect(0, 0, self.width(), rect.height() + 2*border), QColor(0, 0, 0, 127)) painter.drawText((self.width() - rect.width())/2, border, rect.width(), rect.height(), Qt.AlignCenter | Qt.TextWordWrap, text) if __name__ == '__main__': import sys app = QApplication(sys.argv) format = QSurfaceFormat() format.setSamples(4) format.setDepthBufferSize(24) format.setOption(QSurfaceFormat.DebugContext) window = WaterWindow() window.setFormat(format) window.resize(640, 480) window.showMaximized() window.setAnimating(True) sys.exit(app.exec_())
import ctypes import numpy as np import math from .linalg import quaternion as q from .transforms import * from .gloo import * # import threading DEFAULT_FORMAT = QSurfaceFormat() DEFAULT_FORMAT.setVersion(3, 3) DEFAULT_FORMAT.setProfile(QSurfaceFormat.CoreProfile) DEFAULT_FORMAT.setStereo(False) DEFAULT_FORMAT.setSwapBehavior(QSurfaceFormat.DoubleBuffer) DEFAULT_FORMAT.setDepthBufferSize(24) DEFAULT_FORMAT.setSamples(4) class OpenGLWindow(QWindow): def __init__(self, parent=None): super(OpenGLWindow, self).__init__(parent) self.m_update_pending = False self.m_animating = False self.m_context = None self.m_gl = None self.setSurfaceType(QWindow.OpenGLSurface) def initialise(self):