def setDefaultFormat(cls, major_version: int, minor_version: int, core=False, profile=None) -> None: """Set the default format for each new OpenGL context :param major_version: :param minor_version: :param core: (optional) True for QSurfaceFormat.CoreProfile, False for CompatibilityProfile :param profile: (optional) QSurfaceFormat.CoreProfile, CompatibilityProfile or NoProfile, overrules option core """ new_format = QSurfaceFormat() new_format.setMajorVersion(major_version) new_format.setMinorVersion(minor_version) if core: profile_ = QSurfaceFormat.CoreProfile else: profile_ = QSurfaceFormat.CompatibilityProfile if profile is not None: profile_ = profile new_format.setProfile(profile_) QSurfaceFormat.setDefaultFormat(new_format) cls.major_version = major_version cls.minor_version = minor_version cls.profile = profile_
def main(): queue = Queue(maxsize=1000) world = World(queue, DEFAULT_UNIV_X, DEFAULT_UNIV_Y, BOTS_AT_BEGINNING, MINERALS_AT_BEGINNING) world.start() # app = QApplication(sys.argv) # widget = Qwidget(queue, DEFAULT_UNIV_X, DEFAULT_UNIV_Y, SCALE) # app.exec_() # # print(queue.qsize()) app = QApplication(sys.argv) fmt = QSurfaceFormat() fmt.setSamples(4) QSurfaceFormat.setDefaultFormat(fmt) window = WorldWindow(queue, DEFAULT_UNIV_X, DEFAULT_UNIV_Y, SCALE) window.show() app.exec_() world.finish_him() world.join()
def qt_qml_opengl(multi_windows_script='', qml_dirs=[], img_providers=[]): # Create the application instance. # app = QGuiApplication(sys.argv) --> CRASH app = QApplication(sys.argv) #https://machinekoder.com/how-to-not-shoot-yourself-in-the-foot-using-python-qt/ timer = QTimer() timer.timeout.connect(lambda: None) timer.start(100) # app = QApplication(sys.argv) QSurfaceFormat.setDefaultFormat(create_format()) if multi_windows_script: engine = create_multi_windows( try_to_complete_path(multi_windows_script, qml_dirs), qml_dirs, img_providers, app) view = engine.rootObjects()[0] else: view = create_qquick_view(os.path.join(QMLDIR, "root.qml"), qml_dirs, img_providers) view.show() exit(app.exec_())
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 setDefaultFormat(cls, major_version, minor_version, core = False, profile = None): new_format = QSurfaceFormat() new_format.setMajorVersion(major_version) new_format.setMinorVersion(minor_version) if core: profile_ = QSurfaceFormat.CoreProfile else: profile_ = QSurfaceFormat.CompatibilityProfile if profile is not None: profile_ = profile new_format.setProfile(profile_) QSurfaceFormat.setDefaultFormat(new_format) cls.major_version = major_version cls.minor_version = minor_version cls.profile = profile_
def __init__(self, script, qml_dirs = [], img_providers = []): ''' script is assumed to contain a 'key' property which is updated on Keys.onPressed events. script's API is assumed to be its root level properties ''' self.app = QApplication(sys.argv) ## This remove the following warning at the started of the viewer : QML Settings: The following application identifiers have not been set: QVector("organizationName", "organizationDomain") self.app.setOrganizationName("Leddartech") self.app.setOrganizationDomain("Advanced_Engineering") # https://machinekoder.com/how-to-not-shoot-yourself-in-the-foot-using-python-qt/ self.timer = QTimer() self.timer.timeout.connect(lambda: None) self.timer.start(100) QSurfaceFormat.setDefaultFormat(utils.create_format()) self.engine = None self.root = None self.view = None if script: self.create_view(script, qml_dirs, img_providers)
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)
def enable_multisampling(num: int = 10): fmt = QSurfaceFormat() fmt.setSamples(num) QSurfaceFormat.setDefaultFormat(fmt)
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_())
def init(): ''' Startup initialisation of OpenGL. ''' if gl is None: version, profile = get_profile_settings() # Initialise application-wide GL version fmt = QSurfaceFormat() fmt.setVersion(*version) # profile = QSurfaceFormat.CoreProfile if sys.platform == 'darwin' else QSurfaceFormat.CompatibilityProfile fmt.setProfile(profile or QSurfaceFormat.CompatibilityProfile) QSurfaceFormat.setDefaultFormat(fmt) if profile is not None: # Use a dummy context to get GL functions glprofile = QOpenGLVersionProfile(fmt) ctx = QOpenGLContext() globals()['gl'] = ctx.versionFunctions(glprofile) # Check and set OpenGL capabilities if not glprofile.hasProfiles(): raise RuntimeError( 'No OpenGL version >= 3.3 support detected for this system!' ) else: # If profile was none, PyQt5 is not shipped with any OpenGL function modules. Use PyOpenGL instead print( "Couldn't find OpenGL functions in Qt. Falling back to PyOpenGL" ) globals()['gl'] = importlib.import_module('OpenGL.GL') globals()['_glvar_sizes'] = { gl.GL_FLOAT: 1, gl.GL_FLOAT_VEC2: 2, gl.GL_FLOAT_VEC3: 3, gl.GL_FLOAT_VEC4: 4, gl.GL_FLOAT_MAT2: 4, gl.GL_FLOAT_MAT3: 9, gl.GL_FLOAT_MAT4: 16, gl.GL_FLOAT_MAT2x3: 6, gl.GL_FLOAT_MAT2x4: 8, gl.GL_FLOAT_MAT3x2: 6, gl.GL_FLOAT_MAT3x4: 12, gl.GL_FLOAT_MAT4x2: 8, gl.GL_FLOAT_MAT4x3: 12, gl.GL_INT: 1, gl.GL_INT_VEC2: 2, gl.GL_INT_VEC3: 3, gl.GL_INT_VEC4: 4, gl.GL_UNSIGNED_INT: 1, gl.GL_UNSIGNED_INT_VEC2: 2, gl.GL_UNSIGNED_INT_VEC3: 3, gl.GL_UNSIGNED_INT_VEC4: 4, gl.GL_DOUBLE: 1, gl.GL_DOUBLE_VEC2: 2, gl.GL_DOUBLE_VEC3: 3, gl.GL_DOUBLE_VEC4: 4, gl.GL_DOUBLE_MAT2: 4, gl.GL_DOUBLE_MAT3: 9, gl.GL_DOUBLE_MAT4: 16, gl.GL_DOUBLE_MAT2x3: 6, gl.GL_DOUBLE_MAT2x4: 8, gl.GL_DOUBLE_MAT3x2: 6, gl.GL_DOUBLE_MAT3x4: 12, gl.GL_DOUBLE_MAT4x2: 8, gl.GL_DOUBLE_MAT4x3: 12 } return gl
#!/usr/bin/env python3 import sys # Check if we're in a virtual environment. if sys.prefix == sys.base_prefix: raise Exception('Not using a virtual environment! (See README.md)') from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QSurfaceFormat from widgets import * if __name__ == '__main__': qsf = QSurfaceFormat() qsf.setRenderableType(QSurfaceFormat.OpenGL) qsf.setProfile(QSurfaceFormat.CoreProfile) qsf.setVersion(4, 1) QSurfaceFormat.setDefaultFormat(qsf) app = QApplication(sys.argv) imp = IMPWindow() sys.exit(app.exec_())
def initialize_opengl(): surface_format = QSurfaceFormat() surface_format.setProfile(QSurfaceFormat.CoreProfile) surface_format.setVersion(4, 5) surface_format.setSamples(4) QSurfaceFormat.setDefaultFormat(surface_format)
def __init__(self, initMode: DriveMode) -> None: # Init values self.mode = initMode self.tachometerEngineRpm = 0 # 0 - 9000 self.tachometerEngineLevel = DashboardLevel.inactive self.tachometerGearboxRpm = 0 # 0 - 9000 self.tachometerGearboxLevel = DashboardLevel.inactive self.tachometerGear1Rpm = 0 # 0 - 9000 self.tachometerGear2Rpm = 0 # 0 - 9000 self.tachometerGear3Rpm = 0 # 0 - 9000 self.tachometerGear4Rpm = 0 # 0 - 9000 self.tachometerGear5Rpm = 0 # 0 - 9000 self.accelerometerAngel = 0 # -180 - +180 self.accelerometerValue = 0.0 # 0.0 - 1.0 self.accelerometerLevel = DashboardLevel.inactive self.steeringWheelEncoderAngel = 0 # -7 - +7 self.steeringWheelEncoderLevel = DashboardLevel.inactive self.turnLeftIndicatorLevel = DashboardLevel.inactive self.turnRightIndicatorLevel = DashboardLevel.inactive self.oilWarningIndicatorLevel = DashboardLevel.inactive self.watterWarningIndicatorLevel = DashboardLevel.inactive self.gearNumberValue = 0 # 0 - 5 self.speedometerValue = 0 # 0 - 999 self.speedometerLevel = DashboardLevel.inactive self.stopwatchMills = 0 # 0 - 99 self.stopwatchSeconds = 0 # 0 - 59 self.stopwatchMinutes = 0 # 0 - 59 self.stopwatchHours = 0 # 0 - 9 self.stopwatchLevel = DashboardLevel.inactive self.oilManometerValue = 0.0 # 0.0 - 9.99 self.oilManometerLevel = DashboardLevel.inactive self.oilThermometerValue = 0 # 0 - 999 self.oilThermometerLevel = DashboardLevel.inactive self.watterThermometerValue = 0 # 0 - 999 self.watterThermometerLevel = DashboardLevel.inactive self.odometerValue = 0 # 0 - 9999 self.odometerLevel = DashboardLevel.inactive # Init UI super(Dashboard, self).__init__() viewport = QOpenGLWidget() viewportFormat = QSurfaceFormat() viewportFormat.setSwapInterval(0) # disable VSync viewportFormat.setSamples(2**8) viewportFormat.setDefaultFormat(viewportFormat) viewport.setFormat(viewportFormat) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setGeometry(0, 0, self.WINDOW_WIDTH, self.WINDOW_HEIGHT) self.setStyleSheet("border: 0px") self.setWindowTitle("Dashboard") self.setWindowFlags(Qt.FramelessWindowHint) self.scene = QGraphicsScene(0, 0, self.WINDOW_WIDTH, self.WINDOW_HEIGHT) self.setScene(self.scene) self.setViewport(viewport) self.setInteractive(False) self.levelPens = { DashboardLevel.inactive: QPen(self.INACTIVE_COLOR, 1, Qt.SolidLine), DashboardLevel.ok: QPen(self.OK_COLOR, 1, Qt.SolidLine), DashboardLevel.warning: QPen(self.WARNING_COLOR, 1, Qt.SolidLine), DashboardLevel.dangerous: QPen(self.DANGEROUS_COLOR, 1, Qt.SolidLine) } self.levelBrushes = { DashboardLevel.inactive: QBrush(self.INACTIVE_COLOR, Qt.SolidPattern), DashboardLevel.ok: QBrush(self.OK_COLOR, Qt.SolidPattern), DashboardLevel.warning: QBrush(self.WARNING_COLOR, Qt.SolidPattern), DashboardLevel.dangerous: QBrush(self.DANGEROUS_COLOR, Qt.SolidPattern) } # Helpers dirPath = os.path.dirname(os.path.abspath(__file__)) inactivePen = self.levelPens[DashboardLevel.inactive] inactiveBrush = self.levelBrushes[DashboardLevel.inactive] def buildPolygonItem(origin: QPointF, polygon: List[QPointF]): return self.scene.addPolygon( QPolygonF([ QPointF(p.x() + origin.x(), p.y() + origin.y()) for p in polygon ]), inactivePen, inactiveBrush) def makeNumberItems(origin: QPointF, polygon: Dict[str, List[QPointF]]): return {k: buildPolygonItem(origin, p) for k, p in polygon.items()} # Add background self.backgroundPixmaps = { DriveMode.race: QPixmap(os.path.join(dirPath, "background_race.png")).scaled( self.WINDOW_WIDTH, self.WINDOW_HEIGHT), DriveMode.street: QPixmap(os.path.join(dirPath, "background_street.png")).scaled( self.WINDOW_WIDTH, self.WINDOW_HEIGHT) } logging.debug( f"[Dashboard.__init__] Loaded: backgroundPixmaps = {self.backgroundPixmaps}, initMode = {initMode}" ) self.backgroundItem = QGraphicsPixmapItem() self.backgroundItem.setZValue(-1) self.scene.addItem(self.backgroundItem) # Add tachometer graphics self.tachometerEngineItems = \ {k: self.scene.addPolygon(p, inactivePen, inactiveBrush) for k, p in PolygonsMapping.TACHOMETER_ENGINE.items()} self.tachometerGearboxItems = \ {k: self.scene.addPolygon(p, inactivePen, inactiveBrush) for k, p in PolygonsMapping.TACHOMETER_GEARBOX.items()} self.tachometerGearsPens = { "A": QPen(self.TACHOMETER_GEARS_ARROW_COLOR, 1, Qt.SolidLine), "N": QPen(self.TACHOMETER_GEARS_NUMBER_COLOR, 1, Qt.SolidLine) } self.tachometerGearsBrushes = { "A": QBrush(self.TACHOMETER_GEARS_ARROW_COLOR, Qt.SolidPattern), "N": QBrush(self.TACHOMETER_GEARS_NUMBER_COLOR, Qt.SolidPattern) } def makeGearsTransforms(translate: QPointF, rotate: int): arrowTrans = QTransform() arrowTrans.translate(translate.x(), translate.y()) arrowTrans.rotate(rotate) numberTrans = QTransform() numberTrans.translate(translate.x(), translate.y()) return arrowTrans, numberTrans self.tachometerGearsTransforms = \ {k: makeGearsTransforms(p[0], p[1]) for k, p in PolygonsMapping.TACHOMETER_GEARS["T"].items()} def tachometerGearsItem(gearNumber: int): (arrowTrans, numberTrans) = self.tachometerGearsTransforms[0] arrowItem = self.scene.addPolygon( PolygonsMapping.TACHOMETER_GEARS["A"], inactivePen, inactiveBrush) arrowItem.setTransform(arrowTrans) numberItem = buildPolygonItem( PolygonsMapping.TACHOMETER_GEARS["N"]["O"], PolygonsMapping.TACHOMETER_GEARS["N"]["P"][gearNumber]) numberItem.setTransform(numberTrans) return arrowItem, numberItem self.tachometerGearsItems = { 1: tachometerGearsItem(1), 2: tachometerGearsItem(2), 3: tachometerGearsItem(3), 4: tachometerGearsItem(4), 5: tachometerGearsItem(5) } # Add accelerometer graphics def makeEllipse(points: Tuple[QPointF, QPointF]): return self.scene.addEllipse(points[0].x(), points[0].y(), points[1].x() - points[0].x(), points[1].y() - points[0].y(), inactivePen, inactiveBrush) self.accelerometerCenterItem = makeEllipse( PolygonsMapping.ACCELEROMETER["C"]) self.accelerometerSectorItem = makeEllipse( PolygonsMapping.ACCELEROMETER["S"]) self.accelerometerSectorItem.setStartAngle( int((270 - (self.ACCELEROMETER_MIN_ANGEL / 2))) * 16) self.accelerometerSectorItem.setSpanAngle( self.ACCELEROMETER_MIN_ANGEL * 16) # Add steering wheel encoder graphics self.steeringWheelEncoderItems = \ {k: self.scene.addPolygon(p, inactivePen, inactiveBrush) for k, p in PolygonsMapping.STEERING_WHEEL_ENCODER.items()} # Add turn indicator graphics def makeTurnIndicatorItem(initCoordinates: Dict[str, Any]): return buildPolygonItem(initCoordinates["C"], initCoordinates["P"]) self.turnIndicatorLeftItem = makeTurnIndicatorItem( PolygonsMapping.TURN_INDICATOR["L"]) self.turnIndicatorRightItem = makeTurnIndicatorItem( PolygonsMapping.TURN_INDICATOR["R"]) # Add warning indicators graphics def makeWarningIndicatorItems(initCoordinates: Dict[str, Any]): return [ buildPolygonItem(initCoordinates["C"], p) for p in initCoordinates["P"] ] self.oilWarningIndicatorItems = makeWarningIndicatorItems( PolygonsMapping.WARNING_INDICATORS["OIL"]) self.watterWarningIndicatorItems = makeWarningIndicatorItems( PolygonsMapping.WARNING_INDICATORS["WATTER"]) # Add gear number graphics self.gearNumberPen = QPen(self.GEAR_NUMBER_COLOR, 1, Qt.SolidLine) self.gearNumberBrush = QBrush(self.GEAR_NUMBER_COLOR, Qt.SolidPattern) self.gearNumberItems = makeNumberItems( PolygonsMapping.GEAR_NUMBER["C"], PolygonsMapping.GEAR_NUMBER["P"]) # Add speedometer graphics self.speedometer001Items = makeNumberItems( PolygonsMapping.SPEEDOMETER[1], PolygonsMapping.SPEED_NUMBERS) self.speedometer010Items = makeNumberItems( PolygonsMapping.SPEEDOMETER[10], PolygonsMapping.SPEED_NUMBERS) self.speedometer100Items = makeNumberItems( PolygonsMapping.SPEEDOMETER[100], PolygonsMapping.SPEED_NUMBERS) # Add stopwatch graphics self.stopwatchMS01Items = makeNumberItems( PolygonsMapping.STOPWATCH["MS01"], PolygonsMapping.STANDARD_NUMBERS) self.stopwatchMS10Items = makeNumberItems( PolygonsMapping.STOPWATCH["MS10"], PolygonsMapping.STANDARD_NUMBERS) self.stopwatchS01Items = makeNumberItems( PolygonsMapping.STOPWATCH["S01"], PolygonsMapping.STANDARD_NUMBERS) self.stopwatchS10Items = makeNumberItems( PolygonsMapping.STOPWATCH["S10"], PolygonsMapping.STANDARD_NUMBERS) self.stopwatchM01Items = makeNumberItems( PolygonsMapping.STOPWATCH["M01"], PolygonsMapping.STANDARD_NUMBERS) self.stopwatchM10Items = makeNumberItems( PolygonsMapping.STOPWATCH["M10"], PolygonsMapping.STANDARD_NUMBERS) self.stopwatchH01Items = makeNumberItems( PolygonsMapping.STOPWATCH["H01"], PolygonsMapping.STANDARD_NUMBERS) # Add oil manometer graphics self.oilManometer0d01Items = makeNumberItems( PolygonsMapping.OIL_MANOMETER[0.01], PolygonsMapping.STANDARD_NUMBERS) self.oilManometer0d10Items = makeNumberItems( PolygonsMapping.OIL_MANOMETER[0.1], PolygonsMapping.STANDARD_NUMBERS) self.oilManometer1d00Items = makeNumberItems( PolygonsMapping.OIL_MANOMETER[1], PolygonsMapping.STANDARD_NUMBERS) # Add oil thermometer graphics self.oilThermometer001Items = makeNumberItems( PolygonsMapping.OIL_THERMOMETER[1], PolygonsMapping.STANDARD_NUMBERS) self.oilThermometer010Items = makeNumberItems( PolygonsMapping.OIL_THERMOMETER[10], PolygonsMapping.STANDARD_NUMBERS) self.oilThermometer100Items = makeNumberItems( PolygonsMapping.OIL_THERMOMETER[100], PolygonsMapping.STANDARD_NUMBERS) # Add watter thermometer graphics self.watterThermometer001Items = makeNumberItems( PolygonsMapping.WATTER_THERMOMETER[1], PolygonsMapping.STANDARD_NUMBERS) self.watterThermometer010Items = makeNumberItems( PolygonsMapping.WATTER_THERMOMETER[10], PolygonsMapping.STANDARD_NUMBERS) self.watterThermometer100Items = makeNumberItems( PolygonsMapping.WATTER_THERMOMETER[100], PolygonsMapping.STANDARD_NUMBERS) # Add odometer graphics self.watterOdometer0001Items = makeNumberItems( PolygonsMapping.ODOMETER[1], PolygonsMapping.STANDARD_NUMBERS) self.watterOdometer0010Items = makeNumberItems( PolygonsMapping.ODOMETER[10], PolygonsMapping.STANDARD_NUMBERS) self.watterOdometer0100Items = makeNumberItems( PolygonsMapping.ODOMETER[100], PolygonsMapping.STANDARD_NUMBERS) self.watterOdometer1000Items = makeNumberItems( PolygonsMapping.ODOMETER[1000], PolygonsMapping.STANDARD_NUMBERS) # Initial rendering self.renderBackground() self.renderTachometerScale(self.tachometerEngineItems, self.tachometerEngineRpm, self.tachometerEngineLevel) self.renderTachometerScale(self.tachometerGearboxItems, self.tachometerGearboxRpm, self.tachometerGearboxLevel) self.renderAccelerometer() self.renderSteeringWheelEncoder() self.renderTurnLeftIndicator() self.renderTurnRightIndicator() self.renderOilWarningIndicator() self.renderWatterWarningIndicator() self.renderGearNumber() self.renderSpeedometer() self.renderStopwatch() self.renderOilManometer() self.renderOilThermometer() self.renderWatterThermometer() self.renderOdometer()
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)
class OpenGLWidget(QOpenGLWidget): format = QSurfaceFormat() #format.setDepthBufferSize(24) #format.setStencilBufferSize(8) format.setSamples(6) format.setSwapBehavior(QSurfaceFormat.DoubleBuffer) QSurfaceFormat.setDefaultFormat(format) def __init__(self, parent, debug=False): QOpenGLWidget.__init__(self, parent) global debugger debugger = Debug(debug, 'OpenGLWidget') self.debug = debug self.viewerTab = parent self.notebook = parent.notebook self.setMinimumSize(640, 672) self.lightingOn = True self.diffuseMaterialFactor = 0.9 self.ambientMaterialFactor = 0.4 self.specularMaterialFactor = 0.7 self.glintMaterialFactor = 100.0 self.diffuseLightFactor = 0.8 self.ambientLightFactor = 0.6 self.specularLightFactor = 1.0 self.linearAttenuation = True self.image_size = 15.0 self.white = np.array([1.0, 1.0, 1.0, 1.0]) self.spheres = deque() self.cylinders = deque() self.arrows = deque() self.current_phase = 0 self.phase_direction = 1 self.number_of_phases = 1 self.sphere_slices = 20 self.sphere_stacks = 20 self.cylinder_slices = 8 self.cylinder_stacks = 2 self.timer = None self.show_arrows = True self.timer_interval = 60 self.my_width = None self.my_height = None self.background_colour = None self.show_full_screen = False self.writer = None self.rotation_centre = np.array([0.0, 0.0, 0.0]) self.matrix = np.eye(4, dtype=np.float32) self.light_switches = None d = 200.0 self.light_positions = [[-d, d, d], [d, -d, d], [-d, -d, d], [d, d, d], [-d, d, -d], [d, -d, -d], [-d, -d, -d], [d, d, -d]] self.lights = [ GL_LIGHT0, GL_LIGHT1, GL_LIGHT2, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7 ] def enterEvent(self, event): debugger.print('enter event') self.setFocus() self.viewerTab.enterEvent(event) def showArrows(self, show): debugger.print('show arrows', show) self.show_arrows = show def timeoutHandler(self): self.current_phase += self.phase_direction if self.current_phase >= self.number_of_phases: self.phase_direction = -1 self.current_phase = self.number_of_phases - 2 elif self.current_phase < 0: self.current_phase = 1 self.phase_direction = +1 debugger.print('Timeout - phase', self.current_phase) self.update() def myMakeCurrent(self): self.makeCurrent() err = glGetError() while err != GL_NO_ERROR: err = glGetError() def moleculeRotate(self, scale, x, y, z): # Rotate molecular frame using glortho # Create a 4x4 matrix for the model view debugger.print('molecule rotation', x, y, z) self.myMakeCurrent() glMatrixMode(GL_MODELVIEW) glGetFloatv(GL_MODELVIEW_MATRIX, self.matrix) glLoadIdentity() glRotatef(scale * x, 1.0, 0.0, 0.0) glRotatef(scale * y, 0.0, 1.0, 0.0) glMultMatrixf(self.matrix) self.update() def keyPressEvent(self, event): self.myMakeCurrent() key = event.key() modifiers = event.modifiers() debugger.print('kepressevent', key, modifiers) control = False shift = False if modifiers & Qt.ShiftModifier: shift = True if modifiers & Qt.ControlModifier: control = True if modifiers & Qt.ShiftModifier or modifiers & Qt.ControlModifier: amount = 45.0 else: amount = 5.0 if key == Qt.Key_Left: self.moleculeRotate(-amount, 0.0, 1.0, 0.0) elif key == Qt.Key_Right: self.moleculeRotate(+amount, 0.0, 1.0, 0.0) elif key == Qt.Key_Up: self.moleculeRotate(-amount, 1.0, 0.0, 0.0) elif key == Qt.Key_Down: self.moleculeRotate(+amount, 1.0, 0.0, 0.0) elif key == Qt.Key_Plus: self.zoom(+1.0) elif key == Qt.Key_Minus: self.zoom(-1.0) elif key == Qt.Key_P: self.save_movie() elif key == Qt.Key_F: self.show_full_screen = not self.show_full_screen if self.show_full_screen: self.showFullScreen() else: self.showNormal() elif key == Qt.Key_Home: glMatrixMode(GL_MODELVIEW) glLoadIdentity() self.matrix = np.eye(4, dtype=np.float32) self.current_phase = int(self.number_of_phases / 2) debugger.print('Home key', self.current_phase) self.update() def save_movie(self, filename): import imageio imageio.plugins.ffmpeg.download() debugger.print('save_movie', filename) if self.timer is not None: self.timer.stop() writer = imageio.get_writer(filename, mode='I', fps=24) tmpdir = os.path.dirname(filename) tmpfile = os.path.join(tmpdir, '.snapshot.png') debugger.print('save_movie', filename) for i in range(0, 2 * self.number_of_phases): self.timeoutHandler() image = self.grabFramebuffer() x = image.width() y = image.height() modx = x % 16 mody = y % 16 startx = int(modx / 2) starty = int(mody / 2) x = x - modx + startx y = y - mody + starty # The image is cropped so that the height and widths are multiples of 16 image = image.copy(startx, starty, x, y) image.save(tmpfile) image = imageio.imread(tmpfile) writer.append_data(image) writer.close() os.remove(tmpfile) if self.timer is not None: self.timer.start() def snapshot(self, filename): debugger.print('snapshot', filename) image = self.grabFramebuffer() image.save(filename) def translate(self, x, y): debugger.print('translate ', x, y) self.myMakeCurrent() glTranslatef(x, y, 0.0) def wheelEvent(self, event): debugger.print('Wheel event ') self.myMakeCurrent() zoom = event.angleDelta().y() self.zoom(zoom) self.update() def mousePressEvent(self, event): self.xAtPress = event.x() self.yAtPress = event.y() #print('mouse press',self.xAtPress, self.yAtPress) def mouseReleaseEvent(self, event): self.xAtRelease = event.x() self.yAtRelease = event.y() #print('mouse release',self.xAtRelease, self.yAtRelease) def zoom(self, zoom): debugger.print('zoom ', zoom) self.myMakeCurrent() if zoom > 0: zoom_factor = 1.06 else: zoom_factor = 0.94 debugger.print('zoom factor', zoom_factor) glScalef(zoom_factor, zoom_factor, zoom_factor) self.update() def mouseMoveEvent(self, event): self.xAtMove = event.x() self.yAtMove = event.y() buttons = event.buttons() modifiers = event.modifiers() if buttons & Qt.LeftButton: debugger.print('Mouse event - left button') if modifiers & Qt.ShiftModifier or modifiers & Qt.ControlModifier: # handle zoom xzoom = +1.0 * (self.xAtMove - self.xAtPress) yzoom = -1.0 * (self.yAtMove - self.yAtPress) self.zoom(xzoom + yzoom) else: # handle ordinary rotation xrotate = (self.xAtMove - self.xAtPress) * 1 yrotate = (self.yAtMove - self.yAtPress) * 1 self.moleculeRotate(0.3, yrotate, xrotate, 0.0) elif buttons & Qt.MidButton: debugger.print('Mouse event - mid button') xshift = 0.02 * (self.xAtMove - self.xAtPress) yshift = -0.02 * (self.yAtMove - self.yAtPress) self.translate(xshift, yshift) self.update() debugger.print('Mouse event - xy', self.xAtPress, self.yAtPress) self.xAtPress = self.xAtMove self.yAtPress = self.yAtMove def stopAnimation(self): debugger.print('stopAnimation') if self.timer is not None: self.timer.stop() def startAnimation(self): debugger.print('startAnimation') if self.timer is not None: self.timer.stop() else: self.timer = QTimer(self) self.timer.timeout.connect(self.timeoutHandler) self.timer.setInterval(self.timer_interval) self.timer.start() def paintGL(self): debugger.print('paintGL') glMatrixMode(GL_MODELVIEW) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.background_colour = np.array( self.viewerTab.settings['Background colour']) / 255.0 glClearColor(*self.background_colour) glPushMatrix() glTranslatef(-self.rotation_centre[0], -self.rotation_centre[1], -self.rotation_centre[2]) self.drawSpheres() self.drawCylinders() if self.show_arrows: self.drawArrows() glPopMatrix() def drawSpheres(self): debugger.print('drawSpheres') if self.spheres is None: return for sphere in self.spheres[self.current_phase]: col = sphere.colour rad = sphere.radius (x, y, z) = sphere.position diffMatColour = col * self.diffuseMaterialFactor ambMatColour = col * self.ambientMaterialFactor specMatColour = self.white * self.specularLightFactor glMaterialfv(GL_FRONT, GL_DIFFUSE, diffMatColour) glMaterialfv(GL_FRONT, GL_AMBIENT, ambMatColour) glMaterialfv(GL_FRONT, GL_SPECULAR, specMatColour) glMaterialf(GL_FRONT, GL_SHININESS, self.glintMaterialFactor) glPushMatrix() glTranslatef(x, y, z) gluSphere(self.quadric, rad, self.sphere_slices, self.sphere_stacks) glPopMatrix() def drawCylinders(self): debugger.print('drawCylinders') if self.cylinders is None: return for cylinder in self.cylinders[self.current_phase]: col = cylinder.colour rad = cylinder.radius pos1 = cylinder.position1 pos2 = cylinder.position2 length = cylinder.height angle = cylinder.angle rot = cylinder.rotation diffMatColour = col * self.diffuseMaterialFactor ambMatColour = col * self.ambientMaterialFactor specMatColour = self.white * self.specularLightFactor glMaterialfv(GL_FRONT, GL_DIFFUSE, diffMatColour) glMaterialfv(GL_FRONT, GL_AMBIENT, ambMatColour) glMaterialfv(GL_FRONT, GL_SPECULAR, specMatColour) glMaterialf(GL_FRONT, GL_SHININESS, self.glintMaterialFactor) glPushMatrix() glTranslated(pos2[0], pos2[1], pos2[2]) glRotated(angle, rot[0], rot[1], rot[2]) gluCylinder(self.quadric, rad, rad, length, self.cylinder_slices, self.cylinder_stacks) glPopMatrix() def drawArrows(self): debugger.print('drawArrows') if self.arrows is None: return self.arrow_colour = np.array( self.viewerTab.settings['Arrow colour']) / 255.0 for arrow, sphere in zip(self.arrows, self.spheres[self.current_phase]): pos = sphere.position direction = arrow.direction length = arrow.height angle = arrow.angle rot = arrow.rotation colour = arrow.colour radius = arrow.radius diffMatColour = colour * self.diffuseMaterialFactor ambMatColour = colour * self.ambientMaterialFactor specMatColour = self.white * self.specularLightFactor glMaterialfv(GL_FRONT, GL_DIFFUSE, diffMatColour) glMaterialfv(GL_FRONT, GL_AMBIENT, ambMatColour) glMaterialfv(GL_FRONT, GL_SPECULAR, specMatColour) glMaterialf(GL_FRONT, GL_SHININESS, self.glintMaterialFactor) glPushMatrix() glTranslated(pos[0], pos[1], pos[2]) glRotated(angle, rot[0], rot[1], rot[2]) gluCylinder(self.quadric, radius, radius, length, self.cylinder_slices, self.cylinder_stacks) glTranslated(0.0, 0.0, length) length = 0.1 gluCylinder(self.quadric, 2.0 * radius, 0.1 * radius, length, self.cylinder_slices, self.cylinder_stacks) glPopMatrix() def resizeGL(self, w, h): debugger.print('resizeGL', w, h) self.my_width = w self.my_height = h # set projection matrix self.setProjectionMatrix() def initializeGL(self): debugger.print('initializeGL') self.quadric = gluNewQuadric() gluQuadricDrawStyle(self.quadric, GLU_FILL) gluQuadricNormals(self.quadric, GLU_SMOOTH) glClearDepth(1.0) glDepthFunc(GL_LESS) glEnable(GL_DEPTH_TEST) glEnable(GL_NORMALIZE) #glDisable(GL_DITHER) glShadeModel(GL_SMOOTH) glEnable(GL_POLYGON_SMOOTH) glEnable(GL_POINT_SMOOTH) glEnable(GL_LINE_SMOOTH) glEnable(GL_MULTISAMPLE) glCullFace(GL_BACK) glEnable(GL_CULL_FACE) #glBlendFunc(GL_SRC_ALPHA_SATURATE, GL_ONE) glEnable(GL_BLEND) self.defineLights() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.background_colour = np.array( self.viewerTab.settings['Background colour']) / 255.0 glClearColor(*self.background_colour) def setImageSize(self): maxsize = 0.0 for sphere in self.spheres[self.current_phase]: pos = sphere.position vec = pos - self.rotation_centre dist = math.sqrt(np.dot(vec, vec)) if dist > maxsize: maxsize = dist for cylinder in self.cylinders[self.current_phase]: pos1 = cylinder.position1 pos2 = cylinder.position2 vec1 = pos1 - self.rotation_centre dist1 = math.sqrt(np.dot(vec, vec)) vec2 = pos2 - self.rotation_centre dist2 = math.sqrt(np.dot(vec, vec)) dist = max(dist1, dist2) if dist > maxsize: maxsize = dist self.image_size = maxsize self.setProjectionMatrix() debugger.print('setImageSize', self.image_size) def setProjectionMatrix(self): if self.image_size is None or self.my_width is None or self.my_height is None: return self.myMakeCurrent() glMatrixMode(GL_PROJECTION) glLoadIdentity() orthox = 1.1 * self.image_size * self.my_width / min( self.my_width, self.my_height) orthoy = 1.1 * self.image_size * self.my_height / min( self.my_width, self.my_height) orthoz = 1.1 * self.image_size * max(self.my_width, self.my_height) debugger.print('projection', orthox, orthoy, orthoz) glOrtho(-orthox, orthox, -orthoy, orthoy, -orthoz, orthoz) glMatrixMode(GL_MODELVIEW) glLoadIdentity() self.matrix = np.eye(4, dtype=np.float32) # reset the current phase to the centre of the phases self.current_phase = int(self.number_of_phases / 2) debugger.print('set projection matrix ortho', orthox, orthoy, orthoz) debugger.print('set projection matrix image_size', self.image_size) debugger.print('set projection matrix current_phase', self.current_phase) def defineLights(self): debugger.print('Define Lights') self.myMakeCurrent() if self.light_switches is None: self.light_switches = self.viewerTab.light_switches glEnable(GL_LIGHTING) for position, lightOn, light in zip(self.light_positions, self.light_switches, self.lights): glLightfv(light, GL_AMBIENT, [ self.ambientLightFactor, self.ambientLightFactor, self.ambientLightFactor, 1.0 ]) glLightfv(light, GL_DIFFUSE, [ self.diffuseLightFactor, self.diffuseLightFactor, self.diffuseLightFactor, 1.0 ]) glLightfv(light, GL_SPECULAR, [ self.specularLightFactor, self.specularLightFactor, self.specularLightFactor, 1.0 ]) glLightfv(light, GL_POSITION, position) if self.linearAttenuation: glLight(light, GL_LINEAR_ATTENUATION, 1.0) for lightOn, light in zip(self.light_switches, self.lights): if lightOn: glEnable(light) else: glDisable(light) def setRotationCentre(self, pos): debugger.print('set rotation centre', pos) self.rotation_centre = np.array(pos) def createArrays(self, nphases): debugger.print('createArrays') # Create an empty list for each phase # self.spheres = [ [] for i in range(nphases) ] # self.cylinders = [ [] for i in range(nphases) ] #self.spheres = deque( deque() for i in range(nphases) ) #self.cylinders = deque( deque() for i in range(nphases) ) self.spheres.clear() self.cylinders.clear() for i in range(nphases): self.spheres.append(deque()) self.cylinders.append(deque()) self.number_of_phases = nphases self.current_phase = int(self.number_of_phases / 2) def deleteSpheres(self): debugger.print('deleteSpheres') if self.spheres is not None: for spheres in self.spheres: spheres = [] def deleteCylinders(self): debugger.print('deleteCylinders') if self.cylinders is not None: for cylinders in self.cylinders: cylinders = [] def deleteArrows(self): debugger.print('deleteArrows') #self.arrows = [] self.arrows.clear() def addArrows(self, colour, radius, direction, length, phase=0): # There is no phase requirement for arrows - they are just displacements self.arrows.append(Arrow(colour, radius, direction, length)) def addCylinder(self, colour, radius, pos1, pos2, phase=0): self.cylinders[phase].append(Cylinder(colour, radius, pos1, pos2)) def addSphere(self, colour, radius, pos, phase=0): self.spheres[phase].append(Sphere(colour, radius, pos))
rect = metrics.boundingRect(0, 0, self.width() - 2*border, int(self.height()*0.125), Qt.AlignCenter | Qt.TextWordWrap, 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) def setClearColor(self, c): self.gl.glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF()) def setColor(self, c): self.gl.glColor4f(c.redF(), c.greenF(), c.blueF(), c.alphaF()) if __name__ == '__main__': app = QApplication(sys.argv) fmt = QSurfaceFormat() fmt.setSamples(4) QSurfaceFormat.setDefaultFormat(fmt) window = GLWidget() window.show() sys.exit(app.exec_())
def antialias(px): fmt = QSurfaceFormat() fmt.setSamples(px) QSurfaceFormat.setDefaultFormat(fmt)
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) def setClearColor(self, c): self.gl.glClearColor(c.redF(), c.greenF(), c.blueF(), c.alphaF()) def setColor(self, c): self.gl.glColor4f(c.redF(), c.greenF(), c.blueF(), c.alphaF()) if __name__ == '__main__': app = QApplication(sys.argv) fmt = QSurfaceFormat() fmt.setSamples(4) QSurfaceFormat.setDefaultFormat(fmt) window = GLWidget() 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_())