def __init__(self, parent=None): super().__init__(parent) # multisampling fmt = QSurfaceFormat(self.format()) fmt.setSamples(4) fmt.setSwapBehavior(QSurfaceFormat.DoubleBuffer) self.setFormat(fmt) self.lists = None self.clearLists = False self.waveform_data = None # if not none, it will be rendered and deleted (to None) self.beatgrid_data = None # if not none, it will be rendered and deleted (to None) self.data_lock = Lock() self.time_offset = 0 self.zoom_seconds = 4 self.pitch = 1 # affects animation speed self.viewport = (50, 40) # viewport +- x, y self.waveform_lines_per_x = 150 self.baseline_height = 0.2 self.position_marker_width = 0.3 self.waveform_zoom_changed_signal.connect(self.setZoom) self.update_interval = 0.04 self.startTimer(self.update_interval*1000)
def __init__(self, parent=None): super().__init__(parent) if USE_OPENGL and not isRemoteSession(): fmt = QSurfaceFormat() fmt.setSamples(4) self.setViewport(QOpenGLWidget()) self.viewport().setFormat(fmt) self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate) else: self.setViewportUpdateMode(QGraphicsView.SmartViewportUpdate) layout = QFormLayout(self) layout.setContentsMargins(0, 0, 6, 0) layout.setFormAlignment(Qt.AlignRight | Qt.AlignBottom) self.minimap = MiniMapGraphicsView(self) layout.addWidget(self.minimap) self.setLayout(layout) self.setCacheMode(QGraphicsView.CacheBackground) self.setRenderHint(QPainter.Antialiasing) self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QGraphicsView.AnchorViewCenter) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setOptimizationFlags(QGraphicsView.DontSavePainterState | QGraphicsView.DontAdjustForAntialiasing) self.setStyleSheet( """NetworkView:focus { border: 3px solid palette(highlight); }""")
def __init__(self, scene, projection=None, navigation=None, parent=None): # super init super().__init__(parent) fmt = QSurfaceFormat() fmt.setVersion(*opengl_version) fmt.setProfile(QSurfaceFormat.CoreProfile) fmt.setSamples(4) self.setFormat(fmt) self.setFocusPolicy(Qt.StrongFocus) self.setAttribute(Qt.WA_AcceptTouchEvents, True) # interaction methods self.projection = projection or globals()[settings.scene['projection']]() self.navigation = navigation or globals()[settings.controls['navigation']]() self.tool = [Tool(self.navigation.tool, self)] # tool stack, the last tool is used for input events, until it is removed # render parameters self.scene = scene if isinstance(scene, Scene) else Scene(scene) self.uniforms = {'proj':fmat4(1), 'view':fmat4(1), 'projview':fmat4(1)} # last frame rendering constants self.targets = [] self.steps = [] self.step = 0 self.stepi = 0 # dump targets self.map_depth = None self.map_idents = None self.fresh = set() # set of refreshed internal variables since the last render
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 __init__(self, *args): super().__init__(*args) self.setMinimumSize(300, 300) fmt = QSurfaceFormat() fmt.setSamples(4) self.setFormat(fmt)
def __init__(self, *args, samples=4, **kwargs): super().__init__(*args, **kwargs) self.is_dragging = False self.mouse_location = None self.renderer = None self.camera = PerspectiveCamera() format_ = QSurfaceFormat() format_.setSamples(samples) self.setFormat(format_)
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 toggleOpenGL(self): vp = QWidget() if self.openGlButton.isChecked(): fmt = QSurfaceFormat() fmt.setSamples(8) vp = QOpenGLWidget() vp.setFormat(fmt) self.graphicsView.setViewport(vp)
def __init__(self, obj_path, parent=None): super().__init__(parent) surface_format = QSurfaceFormat() surface_format.setSamples(16) QOpenGLWidget.setFormat(self, surface_format) self.projection = QMatrix4x4() self.vertex_buf_offsets = [3, 3, 2] #position, normal, tex_coord self.vertex_buf_stride = sum(self.vertex_buf_offsets) self.obj_path = obj_path self.initialized = False
def __init__(self, parent=None, title="A Marc Paint Widget", view_bounds=(0, 1, 0, 1), window_size=(500, 500), bg_color=(0.0, 0.0, 0.0, 1.0), textures=None): super().__init__(parent) this_format = QSurfaceFormat() this_format.setSamples(16) self.setFormat(this_format) # note: textures takes the form {name: path to image} if textures is None: textures = {} self.textures = {} self.textures_to_load = textures self.setWindowTitle(title) self.view_bounds = view_bounds self.setGeometry((get_screen_width() - window_size[0])/2, (get_screen_height() - window_size[1])/2, window_size[0], window_size[1]) self.bg_color = bg_color self.setAutoFillBackground(False) self.last_resize = None self.resize_mode = ResizeModes.ANCHOR_MIDDLE self.squash_factor = float(self.get_view_width()) * self.height() / self.width() / self.get_view_height() # track mouse movements self.setMouseTracking(True) # this stores the current mouse view location self._mouse_view_location = (0, 0) self.click_started = False self.click_buttons = None self.click_count = 1 self.last_click = -1 # be sensitive to the pinch gesture self.grabGesture(4) # key event stuff self._keys_down = [] self.use_shift_sensitive_key_codes = False # animation timer self.timer = QTimer(self) self.timer.timeout.connect(self._do_animate_frame) QTimer().singleShot(0, self.on_load) self.last_animate = None self.animation_layers = [] # shapes to be drawn self._shapes = []
def __init__(self, obj_path, parent=None): super().__init__(parent) surface_format = QSurfaceFormat() surface_format.setSamples(16) QOpenGLWidget.setFormat(self, surface_format) self.projection = QMatrix4x4() self.vertex_buf_offsets = [3, 3, 2] # position, normal, tex_coord self.vertex_buf_stride = sum(self.vertex_buf_offsets) self.obj_path = obj_path self.initialized = False if not has_libGL: get_main_window().show_status( 'OpenGL library not found. Disabling 3D view.')
def __init__(self, scene, projection=None, navigation=None, parent=None): # super init super(QOpenGLWidget, self).__init__(parent) fmt = QSurfaceFormat() fmt.setVersion(*opengl_version) fmt.setProfile(QSurfaceFormat.CoreProfile) fmt.setSamples(4) self.setFormat(fmt) # ugly trick to receive interaction events in a different function than QOpenGLWidget.event (that one is locking the GIL during the whole rendering, killing any possibility of having a computing thread aside) # that event reception should be in the current widget ... self.handler = GhostWidget(self) self.handler.setFocusPolicy(Qt.StrongFocus) self.handler.setAttribute(Qt.WA_AcceptTouchEvents, True) ViewCommon.__init__(self, scene, projection=None, navigation=None) self.tool = [ Tool(self.navigation.tool, self) ] # tool stack, the last tool is used for input events, until it is removed
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_dragging = False self.mouse_location = None self.renderer = None self.camera = PerspectiveCamera() format_ = QSurfaceFormat() format_.setSamples(4) self.setFormat(format_) self.setAcceptDrops(True) # cursor_file_name = pkg_resources.resource_filename( 'wiggle.images', 'cross-hair.png') cursor_pixmap = QPixmap(cursor_file_name) cross_hair_cursor = QCursor(cursor_pixmap, 15, 15) self.setCursor(cross_hair_cursor) self.setMouseTracking(True) # Hover event self.main_window = None self.hover_actor = None self.has_hover_effect = False
def __init__(self, parent): QOpenGLWidget.__init__(self, parent=parent) # Adding samples format = QSurfaceFormat() format.setSamples(8) self.setFormat(format) self.programLocations: Dict[str, GLuint] self.view: View = View() self.functionModel = FunctionModel(2) self.axesModel = AxisModel() self.evalPointsModel = EvalPointsModel() self.evalLinesModel = EvalLinesModel() self.userModels = [] self.locations = {} self.screenView = None self.mouse: List[int] = None self.setMouseTracking(True)
def __init__(self, parent): super(ViewerWidget, self).__init__(parent) self.main_window = parent # Add antialiasing format = QSurfaceFormat() format.setSamples(8) self.setFormat(format) # Global viewer attributes self.camera = Camera(self.size()) self.global_uniforms = {} self.global_uniforms["lightDirection"] = np.array([0.0, 0.0, 1.0]) self.global_uniforms["lightDirection"] /= np.linalg.norm( self.global_uniforms["lightDirection"] ) self.global_uniforms["lightIntensity"] = np.array([0.95, 0.95, 0.95]) self.global_uniforms["ambientLighting"] = np.array([0.05, 0.05, 0.05]) self.global_uniforms["cameraPosition"] = self.camera.get_position() self.global_uniforms["linkLight"] = False self.line_width = 1 self.point_size = 3 # Available shaders self.shaders = {} # Mesh attributes self.mesh_groups = {} self.draw_wireframe = True # Mouse input handling self.mouse_handler = MouseHandler() self.setMouseTracking(True) # Event queues self.mesh_events = Queue() self.post_draw_events = Queue()
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): pass
native = Widget(helper, self) openGL = GLWidget(helper, self) nativeLabel = QLabel("Native") nativeLabel.setAlignment(Qt.AlignHCenter) openGLLabel = QLabel("OpenGL") openGLLabel.setAlignment(Qt.AlignHCenter) layout = QGridLayout() layout.addWidget(native, 0, 0) layout.addWidget(openGL, 0, 1) layout.addWidget(nativeLabel, 1, 0) layout.addWidget(openGLLabel, 1, 1) self.setLayout(layout) timer = QTimer(self) timer.timeout.connect(native.animate) timer.timeout.connect(openGL.animate) timer.start(50) if __name__ == '__main__': app = QApplication(sys.argv) fmt = QSurfaceFormat() fmt.setSamples(9) QSurfaceFormat.setDefaultFormat(fmt) window = Window() window.show() sys.exit(app.exec_())
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_())
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]) gl.glVertexAttribPointer(self.m_colAttr, 3, gl.GL_FLOAT, False, 0, colors) gl.glEnableVertexAttribArray(self.m_colAttr) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) self.m_program.release() self.m_frame += 1 if __name__ == '__main__': import sys app = QGuiApplication(sys.argv) format = QSurfaceFormat() format.setSamples(4) window = TriangleWindow() window.setFormat(format) window.resize(640, 480) window.show() window.setAnimating(True) sys.exit(app.exec_())
self.m_program.setAttributeArray(self.m_vertex_index, self.m_vertices) self.m_program.setAttributeArray(self.m_norm_index, self.m_norms) self.m_program.setAttributeValue(self.m_color_index, QVector4D(1.0, 0.0, 0.0, 0.0)) self.m_program.bind() self.m_program.setUniformValue(self.m_mvp_index, self.m_mvp_matrix) GL.glDrawArrays(GL.GL_TRIANGLES, 0, len(self.m_vertices)) self.m_program.release() if __name__ == '__main__': import sys app = QGuiApplication(sys.argv) surface_format = QSurfaceFormat() surface_format.setSamples(4) window = TeaPot() window.setFormat(surface_format) window.resize(600, 600) window.show() window.setAnimating(True) sys.exit(app.exec_())
glutKeyboardFunc(keyboard_func) glutMainLoop() elif toolkit == "qt5": from PyQt5.QtCore import Qt, QEvent from PyQt5.QtGui import (QGuiApplication, QWindow, QSurfaceFormat, QOpenGLContext, QOpenGLPaintDevice) app = QGuiApplication(sys.argv) window = QWindow() 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()
def antialias(px): fmt = QSurfaceFormat() fmt.setSamples(px) QSurfaceFormat.setDefaultFormat(fmt)
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 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()
0.0, 0.0, 1.0]) gl.glVertexAttribPointer(self.m_colAttr, 3, gl.GL_FLOAT, False, 0, colors) gl.glEnableVertexAttribArray(self.m_colAttr) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) self.m_program.release() self.m_frame += 1 if __name__ == '__main__': import sys app = QGuiApplication(sys.argv) format = QSurfaceFormat() format.setSamples(4) window = TriangleWindow() window.setFormat(format) window.resize(640, 480) window.show() window.setAnimating(True) sys.exit(app.exec_())
if self.run and not self.auto: self.statistic.save_snapshot(self.snapshot) self.prev_key = self.key cells = [(cell.x, cell.y, Qt.green) for cell in self.snake] cells.append((self.fruit.x, self.fruit.y, Qt.red)) self.openGL.animate(cells) if __name__ == '__main__': # ai = NeuralNetworkPlus(file_name="dump.txt", my_lambda=0.001, layers=[10, 10]) # ai = NeuralNetwork(file_name="dump_ot.txt", my_lambda=3) # ai = LogisticRegression(file_name="dump.txt") # ai.optimize() # ai = None app = QApplication(sys.argv) fmt = QSurfaceFormat() fmt.setSamples(1) QSurfaceFormat.setDefaultFormat(fmt) x = 10 y = 10 window = SnakeGame(x, y, ai=None, auto=False) # window = ShowSavedDate() window.show() sys.exit(app.exec_())
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 key_down(self, key):
QBrush(Qt.green)) def make_path(scene, n): path2 = QPainterPath() path2.moveTo(50, -10) path2.lineTo(50 + n, 220 + n) scene.addPath(path2, QPen(Qt.black)) if __name__ == '__main__': app = QApplication([]) fmt = QSurfaceFormat() fmt.setSamples(10) QSurfaceFormat.setDefaultFormat(fmt) scene = MyScene(0., 0., 600., 400.) path = QPainterPath() path.moveTo(0, 0) path.lineTo(50, 110) path2 = QPainterPath() path2.moveTo(50, -10) path2.lineTo(50, 220) scene.addPath(path2, QPen(Qt.black)) scene.addRect(QRectF(0, 0, 100, 200), QPen(Qt.transparent), QBrush(Qt.green))
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_())
__author__ = 'akirayu101' from PyQt5.QtGui import (QGuiApplication, QSurfaceFormat) from akira_shader import AkiraRenderWindow if __name__ == '__main__': import sys app = QGuiApplication(sys.argv) surface_format = QSurfaceFormat() surface_format.setSamples(4) window = AkiraRenderWindow() window.setFormat(surface_format) window.resize(800, 600) window.show() window.setAnimating(True) sys.exit(app.exec_())