def make_current(self): """ Makes _context current for the surface of this window Returns ------- bool True if successful False if an error occurs """ success = False if self._context is None: self._context = QOpenGLContext() self._context.create() success = self._context.makeCurrent(self) if success: # self.initializeOpenGLFunctions() self._context.doneCurrent() else: return success if self._context is not None: success = self._context.makeCurrent(self) # err = glGetError() return success
def renderNow(self): if not self.isExposed(): return self.m_update_pending = False needsInitialise = False if self.m_context is None: self.m_context = QOpenGLContext(self) self.m_context.setFormat(self.requestedFormat()) self.m_context.create() needsInitialise = True self.m_context.makeCurrent(self) if needsInitialise: self.initialise() self.render() self.m_context.swapBuffers(self) if self.m_animating: self.renderLater()
def renderNow(self): if not self.isExposed(): return self.m_update_pending = False needsInitialize = False if self.m_context is None: self.m_context = QOpenGLContext(self) self.m_context.setFormat(self.requestedFormat()) self.m_context.create() needsInitialize = True self.m_context.makeCurrent(self) if needsInitialize: version_profile = QOpenGLVersionProfile() version_profile.setVersion(2, 0) self.m_gl = self.m_context.versionFunctions(version_profile) self.m_gl.initializeOpenGLFunctions() self.initialize() self.render(self.m_gl) self.m_context.swapBuffers(self) if self.m_animating: self.renderLater()
def setContext(cls, major_version: int, minor_version: int, core=False, profile=None): """Set OpenGL context, given major, minor version + core using QOpenGLContext Unfortunately, what you get back does not have to be the requested version. """ 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_) new_context = QOpenGLContext() new_context.setFormat(new_format) success = new_context.create() if success: return new_context else: Logger.log( "e", "Failed creating OpenGL context (%d, %d, core=%s)" % (major_version, minor_version, core)) return None
def renderNow(self): if not self.isExposed(): return self.m_update_pending = False needsInitialize = False if self.m_context is None: self.m_context = QOpenGLContext(self) self.surface_format = QSurfaceFormat() self.surface_format.setVersion(4, 1) self.surface_format.setProfile(QSurfaceFormat.CoreProfile) self.m_context.setFormat(self.surface_format) self.m_context.create() needsInitialize = True self.m_context.makeCurrent(self) if needsInitialize: self.initialize() self.render() self.m_context.swapBuffers(self) if self.m_animating: self.renderLater()
def setContext(cls, major_version: int, minor_version: int, 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_) new_context = QOpenGLContext() new_context.setFormat(new_format) success = new_context.create() if success: return new_context else: Logger.log( "e", "Failed creating OpenGL context (%d, %d, core=%s)" % (major_version, minor_version, core)) return None
def opengl_info() -> Optional[OpenGLInfo]: # pragma: no cover """Get the OpenGL vendor used. This returns a string such as 'nouveau' or 'Intel Open Source Technology Center'; or None if the vendor can't be determined. """ assert QApplication.instance() override = os.environ.get('QUTE_FAKE_OPENGL') if override is not None: log.init.debug("Using override {}".format(override)) vendor, version = override.split(', ', maxsplit=1) return OpenGLInfo.parse(vendor=vendor, version=version) old_context = cast(Optional[QOpenGLContext], QOpenGLContext.currentContext()) old_surface = None if old_context is None else old_context.surface() surface = QOffscreenSurface() surface.create() ctx = QOpenGLContext() ok = ctx.create() if not ok: log.init.debug("Creating context failed!") return None ok = ctx.makeCurrent(surface) if not ok: log.init.debug("Making context current failed!") return None try: if ctx.isOpenGLES(): # Can't use versionFunctions there return OpenGLInfo(gles=True) vp = QOpenGLVersionProfile() vp.setVersion(2, 0) try: vf = ctx.versionFunctions(vp) except ImportError as e: log.init.debug("Importing version functions failed: {}".format(e)) return None if vf is None: log.init.debug("Getting version functions failed!") return None vendor = vf.glGetString(vf.GL_VENDOR) version = vf.glGetString(vf.GL_VERSION) return OpenGLInfo.parse(vendor=vendor, version=version) finally: ctx.doneCurrent() if old_context and old_surface: old_context.makeCurrent(old_surface)
def started_(self): self.ctx = QOpenGLContext(self.offscreen_surface) self.ctx.setFormat(self.offscreen_surface.requestedFormat()) self.ctx.create() self.fbo = -1 self.tex = -1 self.rbuf = -1 self.setup_fbo() self.renderer = ModelRenderer(self.workspace, self.offscreen_surface)
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 offscreen_context(format): """Provide a temporary QOpenGLContext with the given QSurfaceFormat on an QOffscreenSurface.""" surface = QOffscreenSurface() surface.create() context = QOpenGLContext() context.setFormat(format) context.create() context.makeCurrent(surface) try: yield context finally: context.doneCurrent()
def opengl_vendor(): # pragma: no cover """Get the OpenGL vendor used. This returns a string such as 'nouveau' or 'Intel Open Source Technology Center'; or None if the vendor can't be determined. """ assert QApplication.instance() old_context = QOpenGLContext.currentContext() old_surface = None if old_context is None else old_context.surface() surface = QOffscreenSurface() surface.create() ctx = QOpenGLContext() ok = ctx.create() if not ok: log.init.debug("opengl_vendor: Creating context failed!") return None ok = ctx.makeCurrent(surface) if not ok: log.init.debug("opengl_vendor: Making context current failed!") return None try: if ctx.isOpenGLES(): # Can't use versionFunctions there return None vp = QOpenGLVersionProfile() vp.setVersion(2, 0) try: vf = ctx.versionFunctions(vp) except ImportError as e: log.init.debug("opengl_vendor: Importing version functions " "failed: {}".format(e)) return None if vf is None: log.init.debug("opengl_vendor: Getting version functions failed!") return None return vf.glGetString(vf.GL_VENDOR) finally: ctx.doneCurrent() if old_context and old_surface: old_context.makeCurrent(old_surface)
def opengl_vendor(): # pragma: no cover """Get the OpenGL vendor used. This returns a string such as 'nouveau' or 'Intel Open Source Technology Center'; or None if the vendor can't be determined. """ # We're doing those imports here because this is only available with Qt 5.4 # or newer. from PyQt5.QtGui import (QOpenGLContext, QOpenGLVersionProfile, QOffscreenSurface) assert QApplication.instance() old_context = QOpenGLContext.currentContext() old_surface = None if old_context is None else old_context.surface() surface = QOffscreenSurface() surface.create() ctx = QOpenGLContext() ok = ctx.create() if not ok: log.init.debug("opengl_vendor: Creating context failed!") return None ok = ctx.makeCurrent(surface) if not ok: log.init.debug("opengl_vendor: Making context current failed!") return None try: if ctx.isOpenGLES(): # Can't use versionFunctions there return None vp = QOpenGLVersionProfile() vp.setVersion(2, 0) vf = ctx.versionFunctions(vp) if vf is None: log.init.debug("opengl_vendor: Getting version functions failed!") return None return vf.glGetString(vf.GL_VENDOR) finally: ctx.doneCurrent() if old_context and old_surface: old_context.makeCurrent(old_surface)
def __init__(self): super().__init__() fmt = QSurfaceFormat() fmt.setVersion(2, 0) fmt.setProfile(QSurfaceFormat.CompatibilityProfile) fmt.setStereo(False) fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer) self.setSurfaceType(QWindow.OpenGLSurface) self.context = QOpenGLContext() self.context.setFormat(fmt) if not self.context.create(): raise Exception("Unable to create context") self.create() self.setTitle("OpenGL")
def opengl_vendor(): # pragma: no cover """Get the OpenGL vendor used. This returns a string such as 'nouveau' or 'Intel Open Source Technology Center'; or None if the vendor can't be determined. """ # We're doing those imports here because this is only available with Qt 5.4 # or newer. from PyQt5.QtGui import (QOpenGLContext, QOpenGLVersionProfile, QOffscreenSurface) assert QApplication.instance() assert QOpenGLContext.currentContext() is None surface = QOffscreenSurface() surface.create() ctx = QOpenGLContext() ok = ctx.create() assert ok ok = ctx.makeCurrent(surface) assert ok if ctx.isOpenGLES(): # Can't use versionFunctions there return None vp = QOpenGLVersionProfile() vp.setVersion(2, 0) vf = ctx.versionFunctions(vp) vendor = vf.glGetString(vf.GL_VENDOR) ctx.doneCurrent() return vendor
def detectBestOpenGLVersion(cls): Logger.log("d", "Trying OpenGL context 4.1...") ctx = cls.setContext(4, 1, core=True) if ctx is not None: fmt = ctx.format() profile = fmt.profile() # First test: we hope for this if ((fmt.majorVersion() == 4 and fmt.minorVersion() >= 1) or (fmt.majorVersion() > 4)) and profile == QSurfaceFormat.CoreProfile: Logger.log( "d", "Yay, we got at least OpenGL 4.1 core: %s", cls.versionAsText(fmt.majorVersion(), fmt.minorVersion(), profile)) # https://riverbankcomputing.com/pipermail/pyqt/2017-January/038640.html # PyQt currently only implements 2.0, 2.1 and 4.1Core # If eg 4.5Core would be detected and used here, PyQt would not be able to handle it. major_version = 4 minor_version = 1 # CURA-6092: Check if we're not using software backed 4.1 context; A software 4.1 context # is much slower than a hardware backed 2.0 context gl_window = QWindow() gl_window.setSurfaceType(QWindow.OpenGLSurface) gl_window.showMinimized() gl_format = QSurfaceFormat() gl_format.setMajorVersion(major_version) gl_format.setMinorVersion(minor_version) gl_format.setProfile(profile) gl_context = QOpenGLContext() gl_context.setFormat(gl_format) gl_context.create() gl_context.makeCurrent(gl_window) gl_profile = QOpenGLVersionProfile() gl_profile.setVersion(major_version, minor_version) gl_profile.setProfile(profile) gl = gl_context.versionFunctions( gl_profile ) # type: Any #It's actually a protected class in PyQt that depends on the requested profile and the implementation of your graphics card. gpu_type = "Unknown" # type: str result = None if gl: result = gl.initializeOpenGLFunctions() if not result: Logger.log("e", "Could not initialize OpenGL to get gpu type") else: # WORKAROUND: Cura/#1117 Cura-packaging/12 # Some Intel GPU chipsets return a string, which is not undecodable via PyQt5. # This workaround makes the code fall back to a "Unknown" renderer in these cases. try: gpu_type = gl.glGetString(gl.GL_RENDERER) #type: str except UnicodeDecodeError: Logger.log( "e", "DecodeError while getting GL_RENDERER via glGetString!" ) Logger.log("d", "OpenGL renderer type for this OpenGL version: %s", gpu_type) if "software" in gpu_type.lower(): Logger.log( "w", "Unfortunately OpenGL 4.1 uses software rendering") else: return major_version, minor_version, QSurfaceFormat.CoreProfile else: Logger.log("d", "Failed to create OpenGL context 4.1.") # Fallback: check min spec Logger.log("d", "Trying OpenGL context 2.0...") ctx = cls.setContext(2, 0, profile=QSurfaceFormat.NoProfile) if ctx is not None: fmt = ctx.format() profile = fmt.profile() if fmt.majorVersion() >= 2 and fmt.minorVersion() >= 0: Logger.log( "d", "We got at least OpenGL context 2.0: %s", cls.versionAsText(fmt.majorVersion(), fmt.minorVersion(), profile)) return 2, 0, QSurfaceFormat.NoProfile else: Logger.log( "d", "Current OpenGL context is too low: %s" % cls.versionAsText(fmt.majorVersion(), fmt.minorVersion(), profile)) return None, None, None else: Logger.log("d", "Failed to create OpenGL context 2.0.") return None, None, None
format = QSurfaceFormat() format.setSwapBehavior(QSurfaceFormat.DoubleBuffer) format.setSamples(16) format.setStencilBufferSize(8) if core: format.setProfile(QSurfaceFormat.CoreProfile) window.setSurfaceType(QWindow.OpenGLSurface) window.setFormat(format) window.setTitle(name) pixel_ratio = window.devicePixelRatio() window.resize(*(u/pixel_ratio for u in window_size)) gl_context = QOpenGLContext(window) gl_context.setFormat(window.requestedFormat()) gl_context.create() # asynchronous redisplay def redisplay(): gl_display(scene, feedback) gl_context.swapBuffers(window) waiting_redisplay = False def post_redisplay(): global waiting_redisplay if not waiting_redisplay: waiting_redisplay = True
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <https://www.gnu.org/licenses/>. """Show information about the OpenGL setup.""" from PyQt5.QtGui import (QOpenGLContext, QOpenGLVersionProfile, QOffscreenSurface, QGuiApplication) app = QGuiApplication([]) surface = QOffscreenSurface() surface.create() ctx = QOpenGLContext() ok = ctx.create() assert ok ok = ctx.makeCurrent(surface) assert ok print(f"GLES: {ctx.isOpenGLES()}") vp = QOpenGLVersionProfile() vp.setVersion(2, 0) vf = ctx.versionFunctions(vp) print(f"Vendor: {vf.glGetString(vf.GL_VENDOR)}") print(f"Renderer: {vf.glGetString(vf.GL_RENDERER)}") print(f"Version: {vf.glGetString(vf.GL_VERSION)}")
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