| 1 |
"""An example sprite previewer using Qt and pyglet together. |
| 2 |
|
| 3 |
It allows you to edit the fragment and vertex shaders, then compile them |
| 4 |
to get a live view. Errors and success will be printed to the console. Users |
| 5 |
running GNOME on Linux may need the --use-qt-file-dialog flag to prevent invisible |
| 6 |
window issues. A brief feature overview is located after the license notes below. |
| 7 |
|
| 8 |
Important license notes: |
| 9 |
|
| 10 |
1. Libraries can use licenses which impose requirements beyond those of |
| 11 |
pyglet's BSD-style style license. |
| 12 |
2. This example defaults to using PySide6 by default, but can also use |
| 13 |
PyQt6 due to their nearly-identical APIs. |
| 14 |
3. PySide6 uses the LGPL license while PyQt6 uses a GPL / commercial |
| 15 |
dual-license approach. |
| 16 |
|
| 17 |
To the best knowledge of the contributors, this example and derivatives |
| 18 |
are only obligated to meet the restrictions of the LGPL because it does |
| 19 |
not use any PyQt6-specific features. Please see the following for more |
| 20 |
information: |
| 21 |
|
| 22 |
* The licenses and documentation for the libraries you plan to use |
| 23 |
* This guide for prior versions of PySide and PyQt: |
| 24 |
thttps://www.pythonguis.com/faq/pyqt5-vs-pyside2/ |
| 25 |
|
| 26 |
For additional certainty, please consult a legal professional. |
| 27 |
|
| 28 |
|
| 29 |
Example features: |
| 30 |
|
| 31 |
You can choose the current Qt binding in two ways: |
| 32 |
|
| 33 |
1. Add PySide6 or PyQt6 as the first argument after the launch command |
| 34 |
when running the script in the terminal |
| 35 |
2. Set the PYGLET_QT_BACKEND environment variable to either PySide6 or |
| 36 |
PyQt6. |
| 37 |
|
| 38 |
The priority order is: |
| 39 |
|
| 40 |
1. positional argument |
| 41 |
2. environment variable |
| 42 |
3. default to PySide6 |
| 43 |
|
| 44 |
To load images, choose File -> Open Image. |
| 45 |
|
| 46 |
Images loaded will be listed in the Images menu. By selecting an image in |
| 47 |
the menu list, it will be unloaded. Names in parentheses will be used for |
| 48 |
the sampler2D name. |
| 49 |
|
| 50 |
You can open a shader (both vert and frag) at the same time. Text is |
| 51 |
allowed, but will load into the fragment shader. Saving a shader saves |
| 52 |
both frag and vertex (IE: test becomes test.vert and test.frag) |
| 53 |
|
| 54 |
Scrolling the mousewheel also zooms in. |
| 55 |
""" |
| 56 |
from __future__ import annotations |
| 57 |
|
| 58 |
import argparse |
| 59 |
import os |
| 60 |
import sys |
| 61 |
import traceback |
| 62 |
from pathlib import Path |
| 63 |
from textwrap import dedent |
| 64 |
from typing import TYPE_CHECKING, Final, Mapping |
| 65 |
|
| 66 |
|
| 67 |
ENV_VARIABLE: Final[str] = 'PYGLET_QT_BACKEND' |
| 68 |
|
| 69 |
PYSIDE6: Final[str] = 'PySide6' |
| 70 |
PYQT6: Final[str] = 'PyQt6' |
| 71 |
|
| 72 |
valid_backends: Final[dict[str, str]] = { |
| 73 |
PYSIDE6: "LGPL; may allow releasing under non-GPL licenses", |
| 74 |
PYQT6: "Dual GPL / Commercial license; requires GPL or a fee", |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
DEFAULT: Final[str] = PYSIDE6 |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
parser = argparse.ArgumentParser( |
| 84 |
description=dedent("""\ |
| 85 |
A sprite & shader previewer using Qt and pyglet together. |
| 86 |
|
| 87 |
It defaults to PySide6, but can run on PyQt6. The details of how may |
| 88 |
be helpful to users who want to avoid spreading PyQt6's GPL license |
| 89 |
while using it as a fallback. See the docstrings and comments in the |
| 90 |
source to learn more. |
| 91 |
"""), |
| 92 |
formatter_class=argparse.RawTextHelpFormatter) |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
parser.add_argument( |
| 97 |
'--use-qt-file-dialog', dest='native_file_dialog', action='store_false', |
| 98 |
help="Use Qt's file chooser instead of the system's. Helpful on Gnome DE.", |
| 99 |
) |
| 100 |
parser.set_defaults(native_file_dialog=True) |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
backend_column_width: Final[int] = max(map(len, valid_backends)) |
| 105 |
help_lines: list[str] = ["Which Qt binding to use.\n"] |
| 106 |
|
| 107 |
for backend, description in valid_backends.items(): |
| 108 |
line_parts = [ |
| 109 |
f"{backend: <{backend_column_width}} - ", |
| 110 |
'(Default) ' if backend == DEFAULT else '', |
| 111 |
description, |
| 112 |
] |
| 113 |
help_lines.append(''.join(line_parts)) |
| 114 |
|
| 115 |
|
| 116 |
parser.add_argument('backend', nargs='?', |
| 117 |
choices=valid_backends.keys(), |
| 118 |
help='\n'.join(help_lines)) |
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
arguments = None |
| 123 |
if __name__ == "__main__": |
| 124 |
arguments = parser.parse_args() |
| 125 |
|
| 126 |
reasons_with_backend_values: Final[dict[str, str | None]] = { |
| 127 |
'first positional argument' : None if not arguments else arguments.backend, |
| 128 |
|
| 129 |
|
| 130 |
f'{ENV_VARIABLE!r} env variable' : os.environ.get(ENV_VARIABLE, None), |
| 131 |
'default' : DEFAULT, |
| 132 |
} |
| 133 |
reason, backend = next(filter( |
| 134 |
lambda t: t[1] is not None, reasons_with_backend_values.items())) |
| 135 |
|
| 136 |
print(f"Selected {backend} as the Qt binding from the {reason}'s value.") |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
import pyglet |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
if TYPE_CHECKING or backend == PYSIDE6: |
| 147 |
from PySide6 import QtCore, QtWidgets, QtGui |
| 148 |
from PySide6.QtGui import QWheelEvent |
| 149 |
from PySide6.QtWidgets import QFileDialog |
| 150 |
from PySide6.QtOpenGLWidgets import QOpenGLWidget |
| 151 |
|
| 152 |
elif backend == PYQT6: |
| 153 |
from PyQt6 import QtCore, QtWidgets, QtGui |
| 154 |
from PyQt6.QtGui import QWheelEvent |
| 155 |
from PyQt6.QtWidgets import QFileDialog |
| 156 |
from PyQt6.QtOpenGLWidgets import QOpenGLWidget |
| 157 |
|
| 158 |
else: |
| 159 |
raise ValueError( |
| 160 |
f"Expected a value in {valid_backends}," |
| 161 |
f" but got {backend!r} via {reason}") |
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
from pyglet.gl import ( |
| 166 |
GL_BLEND, |
| 167 |
GL_COLOR_BUFFER_BIT, |
| 168 |
GL_DEPTH_BUFFER_BIT, |
| 169 |
GL_TEXTURE0, |
| 170 |
glActiveTexture, |
| 171 |
glBindTexture, |
| 172 |
glBlendFunc, |
| 173 |
glClear, |
| 174 |
glDisable, |
| 175 |
glEnable, |
| 176 |
) |
| 177 |
|
| 178 |
default_vertex_src = """#version 150 core |
| 179 |
in vec3 translate; |
| 180 |
in vec4 colors; |
| 181 |
in vec3 tex_coords; |
| 182 |
in vec2 scale; |
| 183 |
in vec3 position; |
| 184 |
in float rotation; |
| 185 |
|
| 186 |
out vec4 vertex_colors; |
| 187 |
out vec3 texture_coords; |
| 188 |
|
| 189 |
uniform WindowBlock |
| 190 |
{ |
| 191 |
mat4 projection; |
| 192 |
mat4 view; |
| 193 |
} window; |
| 194 |
|
| 195 |
mat4 m_scale = mat4(1.0); |
| 196 |
mat4 m_rotation = mat4(1.0); |
| 197 |
mat4 m_translate = mat4(1.0); |
| 198 |
|
| 199 |
void main() |
| 200 |
{ |
| 201 |
m_scale[0][0] = scale.x; |
| 202 |
m_scale[1][1] = scale.y; |
| 203 |
m_translate[3][0] = translate.x; |
| 204 |
m_translate[3][1] = translate.y; |
| 205 |
m_translate[3][2] = translate.z; |
| 206 |
m_rotation[0][0] = cos(-radians(rotation)); |
| 207 |
m_rotation[0][1] = sin(-radians(rotation)); |
| 208 |
m_rotation[1][0] = -sin(-radians(rotation)); |
| 209 |
m_rotation[1][1] = cos(-radians(rotation)); |
| 210 |
|
| 211 |
gl_Position = window.projection * window.view * m_translate * m_rotation * m_scale * vec4(position, 1.0); |
| 212 |
|
| 213 |
vertex_colors = colors; |
| 214 |
texture_coords = tex_coords; |
| 215 |
} |
| 216 |
""" |
| 217 |
|
| 218 |
default_frag_src = """#version 150 core |
| 219 |
in vec4 vertex_colors; |
| 220 |
in vec3 texture_coords; |
| 221 |
out vec4 final_colors; |
| 222 |
|
| 223 |
uniform sampler2D sprite_texture0; |
| 224 |
uniform sampler2D sprite_texture1; |
| 225 |
uniform float time; |
| 226 |
|
| 227 |
void main() |
| 228 |
{ |
| 229 |
vec2 uv = texture_coords.xy; |
| 230 |
vec3 col = 0.5 + 0.5 * cos(time + uv.xyx + vec3(0, 2, 4)); |
| 231 |
|
| 232 |
final_colors = texture(sprite_texture1, uv) * texture(sprite_texture0, uv) * vertex_colors * vec4(col, 1.0); |
| 233 |
}""" |
| 234 |
|
| 235 |
|
| 236 |
class MultiTextureSpriteGroup(pyglet.sprite.SpriteGroup): |
| 237 |
"""A sprite group which uses multiple textures and samplers.""" |
| 238 |
|
| 239 |
def __init__( |
| 240 |
self, |
| 241 |
textures: Mapping[str, pyglet.image.Texture], |
| 242 |
blend_src: int, |
| 243 |
blend_dest: int, |
| 244 |
program: pyglet.graphics.shader.ShaderProgram | None = None, |
| 245 |
parent: pyglet.graphics.Group | None = None, |
| 246 |
) -> None: |
| 247 |
"""Create a sprite group for multiple textures and samplers. |
| 248 |
|
| 249 |
All textures must share the same target type. |
| 250 |
|
| 251 |
:Parameters: |
| 252 |
`textures` : |
| 253 |
A mapping of sampler names to texture data. |
| 254 |
`blend_src` : |
| 255 |
OpenGL blend source mode; for example, |
| 256 |
``GL_SRC_ALPHA``. |
| 257 |
`blend_dest` : |
| 258 |
OpenGL blend destination mode; for example, |
| 259 |
``GL_ONE_MINUS_SRC_ALPHA``. |
| 260 |
`parent` : |
| 261 |
Optional parent group. |
| 262 |
""" |
| 263 |
self.images = textures |
| 264 |
texture = list(self.images.values())[0] |
| 265 |
self.target = texture.target |
| 266 |
super().__init__(texture, blend_src, blend_dest, program, parent) |
| 267 |
|
| 268 |
self.program.use() |
| 269 |
for idx, name in enumerate(self.images): |
| 270 |
try: |
| 271 |
self.program[name] = idx |
| 272 |
except pyglet.graphics.shader.ShaderException as e: |
| 273 |
print(e) |
| 274 |
|
| 275 |
self.program.stop() |
| 276 |
|
| 277 |
def set_state(self) -> None: |
| 278 |
self.program.use() |
| 279 |
|
| 280 |
for i, texture in enumerate(self.images.values()): |
| 281 |
glActiveTexture(GL_TEXTURE0 + i) |
| 282 |
glBindTexture(self.target, texture.id) |
| 283 |
|
| 284 |
glEnable(GL_BLEND) |
| 285 |
glBlendFunc(self.blend_src, self.blend_dest) |
| 286 |
|
| 287 |
def unset_state(self) -> None: |
| 288 |
glDisable(GL_BLEND) |
| 289 |
self.program.stop() |
| 290 |
glActiveTexture(GL_TEXTURE0) |
| 291 |
|
| 292 |
def __repr__(self) -> str: |
| 293 |
return f'{self.__class__.__name__}({self.texture!r}-{int(self.texture.id)})' |
| 294 |
|
| 295 |
def __eq__(self, other) -> bool: |
| 296 |
return (other.__class__ is self.__class__ and |
| 297 |
self.program is other.program and |
| 298 |
self.images == other.textures and |
| 299 |
self.blend_src == other.blend_src and |
| 300 |
self.blend_dest == other.blend_dest) |
| 301 |
|
| 302 |
def __hash__(self) -> int: |
| 303 |
return hash((id(self.parent), |
| 304 |
id(self.images), |
| 305 |
self.blend_src, self.blend_dest)) |
| 306 |
|
| 307 |
|
| 308 |
class MultiTextureSprite(pyglet.sprite.Sprite): |
| 309 |
|
| 310 |
def __init__( |
| 311 |
self, |
| 312 |
imgs: Mapping[str, pyglet.image.Texture], |
| 313 |
x: float = 0, y: float = 0, z: float = 0, |
| 314 |
blend_src: int = pyglet.gl.GL_SRC_ALPHA, |
| 315 |
blend_dest: int = pyglet.gl.GL_ONE_MINUS_SRC_ALPHA, |
| 316 |
batch: pyglet.graphics.Batch | None = None, |
| 317 |
group: MultiTextureSpriteGroup | None = None, |
| 318 |
subpixel: bool = False, |
| 319 |
program: pyglet.graphics.shader.ShaderProgram = None, |
| 320 |
) -> None: |
| 321 |
|
| 322 |
self._x = x |
| 323 |
self._y = y |
| 324 |
self._z = z |
| 325 |
|
| 326 |
self._texture = list(imgs.values())[0] |
| 327 |
|
| 328 |
if isinstance(self._texture, pyglet.image.TextureArrayRegion): |
| 329 |
self._program = program or pyglet.sprite.get_default_array_shader() |
| 330 |
else: |
| 331 |
self._program = program or pyglet.sprite.get_default_shader() |
| 332 |
|
| 333 |
self._batch = batch or pyglet.graphics.get_default_batch() |
| 334 |
|
| 335 |
self._group = MultiTextureSpriteGroup(imgs, blend_src, blend_dest, self.program, group) |
| 336 |
|
| 337 |
self._subpixel = subpixel |
| 338 |
self._create_vertex_list() |
| 339 |
|
| 340 |
|
| 341 |
class Ui_MainWindow: |
| 342 |
SPRITE_POSITION = (0, 0) |
| 343 |
|
| 344 |
def __init__(self, use_native_file_dialog: bool = True): |
| 345 |
self.use_native_file_dialog: bool = use_native_file_dialog |
| 346 |
|
| 347 |
self.images = [] |
| 348 |
|
| 349 |
self.group = pyglet.graphics.Group() |
| 350 |
|
| 351 |
self.sprite = None |
| 352 |
self.program = None |
| 353 |
|
| 354 |
def get_file_dialog_options(self) -> QFileDialog.Option: |
| 355 |
"""Convert instance attributes to a file dialog options object. |
| 356 |
|
| 357 |
At the moment, it supports choosing which dialog to use. This is |
| 358 |
helpful on certain Gnome and tiling Linux desktop configurations |
| 359 |
which can have issues with the system file picker. |
| 360 |
|
| 361 |
You may want to expand on this in your own application with |
| 362 |
additional options. |
| 363 |
""" |
| 364 |
options = QFileDialog.Option() |
| 365 |
if not self.use_native_file_dialog: |
| 366 |
options |= QFileDialog.Option.DontUseNativeDialog |
| 367 |
|
| 368 |
return options |
| 369 |
|
| 370 |
def setupUi(self, MainWindow: QtWidgets.QMainWindow) -> None: |
| 371 |
self._window = MainWindow |
| 372 |
|
| 373 |
|
| 374 |
MainWindow.setObjectName("MainWindow") |
| 375 |
MainWindow.resize(820, 855) |
| 376 |
self.centralwidget = QtWidgets.QWidget(MainWindow) |
| 377 |
self.centralwidget.setObjectName("centralwidget") |
| 378 |
|
| 379 |
|
| 380 |
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) |
| 381 |
self.gridLayout.setObjectName("gridLayout") |
| 382 |
self.verticalLayout_3 = QtWidgets.QVBoxLayout() |
| 383 |
self.verticalLayout_3.setObjectName("verticalLayout_3") |
| 384 |
self.horizontalLayout = QtWidgets.QHBoxLayout() |
| 385 |
self.horizontalLayout.setObjectName("horizontalLayout") |
| 386 |
self.verticalLayout = QtWidgets.QVBoxLayout() |
| 387 |
self.verticalLayout.setObjectName("verticalLayout") |
| 388 |
self.label = QtWidgets.QLabel(self.centralwidget) |
| 389 |
self.label.setAlignment( |
| 390 |
QtCore.Qt.AlignmentFlag.AlignLeading |
| 391 |
| QtCore.Qt.AlignmentFlag.AlignLeft |
| 392 |
| QtCore.Qt.AlignmentFlag.AlignVCenter) |
| 393 |
self.label.setObjectName("label") |
| 394 |
self.verticalLayout.addWidget(self.label) |
| 395 |
self.vertex_source_edit = QtWidgets.QTextEdit(self.centralwidget) |
| 396 |
self.vertex_source_edit.setAcceptRichText(False) |
| 397 |
self.vertex_source_edit.setObjectName("vertex_source_edit") |
| 398 |
self.verticalLayout.addWidget(self.vertex_source_edit) |
| 399 |
self.horizontalLayout.addLayout(self.verticalLayout) |
| 400 |
self.verticalLayout_2 = QtWidgets.QVBoxLayout() |
| 401 |
self.verticalLayout_2.setObjectName("verticalLayout_2") |
| 402 |
self.label_2 = QtWidgets.QLabel(self.centralwidget) |
| 403 |
self.label_2.setObjectName("label_2") |
| 404 |
self.verticalLayout_2.addWidget(self.label_2) |
| 405 |
self.fragSourceEdit = QtWidgets.QTextEdit(self.centralwidget) |
| 406 |
self.fragSourceEdit.setAcceptRichText(False) |
| 407 |
self.fragSourceEdit.setObjectName("frag_source_edit") |
| 408 |
self.verticalLayout_2.addWidget(self.fragSourceEdit) |
| 409 |
self.horizontalLayout.addLayout(self.verticalLayout_2) |
| 410 |
self.verticalLayout_3.addLayout(self.horizontalLayout) |
| 411 |
self.compileShaderBtn = QtWidgets.QPushButton(self.centralwidget) |
| 412 |
self.compileShaderBtn.clicked.connect(self.compileClick) |
| 413 |
self.compileShaderBtn.setObjectName("compile_shader_btn") |
| 414 |
self.verticalLayout_3.addWidget(self.compileShaderBtn) |
| 415 |
|
| 416 |
|
| 417 |
self.openGLWidget = PygletWidget(800, 400, self.centralwidget, self) |
| 418 |
self.openGLWidget.setMinimumSize(QtCore.QSize(800, 400)) |
| 419 |
self.openGLWidget.setObjectName("openGLWidget") |
| 420 |
self.verticalLayout_3.addWidget(self.openGLWidget) |
| 421 |
self.gridLayout.addLayout(self.verticalLayout_3, 0, 0, 1, 1) |
| 422 |
|
| 423 |
MainWindow.setCentralWidget(self.centralwidget) |
| 424 |
|
| 425 |
|
| 426 |
self.menubar = QtWidgets.QMenuBar(MainWindow) |
| 427 |
self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21)) |
| 428 |
self.menubar.setObjectName("menubar") |
| 429 |
self.menuFile = QtWidgets.QMenu(self.menubar) |
| 430 |
self.menuFile.setObjectName("menuFile") |
| 431 |
MainWindow.setMenuBar(self.menubar) |
| 432 |
self.statusbar = QtWidgets.QStatusBar(MainWindow) |
| 433 |
self.statusbar.setObjectName("statusbar") |
| 434 |
MainWindow.setStatusBar(self.statusbar) |
| 435 |
|
| 436 |
|
| 437 |
self.actionOpen_Image = QtGui.QAction(MainWindow) |
| 438 |
self.actionOpen_Image.setObjectName("actionOpen_Image") |
| 439 |
self.actionOpen_Image.triggered.connect(self.loadImages) |
| 440 |
self.actionOpen_Image.setShortcut("Ctrl+I") |
| 441 |
|
| 442 |
self.actionOpen_Shader = QtGui.QAction(MainWindow) |
| 443 |
self.actionOpen_Shader.setObjectName("actionOpen_Shader") |
| 444 |
self.actionOpen_Shader.triggered.connect(self.loadShaders) |
| 445 |
self.actionOpen_Shader.setShortcut("Ctrl+O") |
| 446 |
|
| 447 |
self.actionSave_Shader = QtGui.QAction(MainWindow) |
| 448 |
self.actionSave_Shader.setObjectName("actionSave_Shader") |
| 449 |
self.actionSave_Shader.triggered.connect(self.saveShaders) |
| 450 |
self.actionSave_Shader.setStatusTip('Saves both Shader Files') |
| 451 |
self.actionSave_Shader.setShortcut("Ctrl+S") |
| 452 |
|
| 453 |
self.actionExit = QtGui.QAction(MainWindow) |
| 454 |
self.actionExit.triggered.connect(self.closeProgram) |
| 455 |
self.actionExit.setObjectName("actionExit") |
| 456 |
self.menuFile.addAction(self.actionOpen_Image) |
| 457 |
self.menuFile.addSeparator() |
| 458 |
self.menuFile.addAction(self.actionOpen_Shader) |
| 459 |
self.menuFile.addAction(self.actionSave_Shader) |
| 460 |
self.menuFile.addSeparator() |
| 461 |
self.menuFile.addAction(self.actionExit) |
| 462 |
self.menubar.addAction(self.menuFile.menuAction()) |
| 463 |
|
| 464 |
self.imageMenu = QtWidgets.QMenu(self.menubar) |
| 465 |
self.imageMenu.setObjectName("imageMenu") |
| 466 |
self.noImageAction = QtGui.QAction(MainWindow) |
| 467 |
self.noImageAction.setDisabled(True) |
| 468 |
self.imageMenu.addAction(self.noImageAction) |
| 469 |
|
| 470 |
self.menubar.addAction(self.imageMenu.menuAction()) |
| 471 |
|
| 472 |
|
| 473 |
self.retranslateUi(MainWindow) |
| 474 |
QtCore.QMetaObject.connectSlotsByName(MainWindow) |
| 475 |
|
| 476 |
def compileClick(self) -> None: |
| 477 |
if not self.images: |
| 478 |
print("No images have been loaded.") |
| 479 |
return |
| 480 |
|
| 481 |
self.openGLWidget.makeCurrent() |
| 482 |
|
| 483 |
if self.sprite: |
| 484 |
self.sprite.delete() |
| 485 |
self.sprite = None |
| 486 |
|
| 487 |
if self.program: |
| 488 |
del self.program |
| 489 |
self.program = None |
| 490 |
|
| 491 |
try: |
| 492 |
vertex_ = pyglet.graphics.shader.Shader(self.vertex_source_edit.toPlainText(), 'vertex') |
| 493 |
fragment_ = pyglet.graphics.shader.Shader(self.fragSourceEdit.toPlainText(), 'fragment') |
| 494 |
|
| 495 |
self.program = pyglet.graphics.shader.ShaderProgram(vertex_, fragment_) |
| 496 |
|
| 497 |
if len(self.images) == 1: |
| 498 |
self.sprite = pyglet.sprite.Sprite( |
| 499 |
self.images[0], |
| 500 |
x=self.SPRITE_POSITION[0], y=self.SPRITE_POSITION[1], |
| 501 |
group=self.group, batch=self.openGLWidget.batch, |
| 502 |
program=self.program) |
| 503 |
else: |
| 504 |
textures = {image.shader_name: image.get_texture() for image in self.images} |
| 505 |
self.sprite = MultiTextureSprite( |
| 506 |
textures, |
| 507 |
x=self.SPRITE_POSITION[0], y=self.SPRITE_POSITION[1], |
| 508 |
group=self.group, batch=self.openGLWidget.batch, |
| 509 |
program=self.program) |
| 510 |
|
| 511 |
if self.program: |
| 512 |
print("Successfully compiled shader.") |
| 513 |
except pyglet.gl.lib.GLException as err: |
| 514 |
print(f"Failed to compile shader: {err}") |
| 515 |
except Exception as err: |
| 516 |
print("Unexpected error", err) |
| 517 |
def loadImages(self) -> None: |
| 518 |
options = self.get_file_dialog_options() |
| 519 |
fileNames, _ = QFileDialog.getOpenFileNames( |
| 520 |
self._window, "Select Image Files", "", "Image Files (*.png *.jpg *.jpeg *.bmp)", |
| 521 |
options=options) |
| 522 |
|
| 523 |
for fileName in fileNames: |
| 524 |
if not self.images: |
| 525 |
self.imageMenu.removeAction(self.noImageAction) |
| 526 |
|
| 527 |
action = QtGui.QAction(self._window) |
| 528 |
shader_name = f"sprite_texture{len(self.images)}" |
| 529 |
action.setText(f"{os.path.basename(fileName)} ({shader_name})") |
| 530 |
action.fileName = fileName |
| 531 |
action.setCheckable(True) |
| 532 |
action.setChecked(True) |
| 533 |
action.triggered.connect(lambda: self.removeImage(action)) |
| 534 |
image = pyglet.image.load(fileName) |
| 535 |
image.shader_name = shader_name |
| 536 |
action.image = image |
| 537 |
self.images.append(image) |
| 538 |
self.imageMenu.addAction(action) |
| 539 |
|
| 540 |
def loadShaders(self) -> None: |
| 541 |
options = self.get_file_dialog_options() |
| 542 |
file_names, _ = QFileDialog.getOpenFileNames( |
| 543 |
self._window, "Load Shader Files", "", "Shader Files (*.vert *.frag *.txt)", |
| 544 |
options=options) |
| 545 |
|
| 546 |
for file_name in file_names: |
| 547 |
file_path = Path(file_name) |
| 548 |
ext = file_path.suffixes[-1] |
| 549 |
|
| 550 |
if ext == '.vert': |
| 551 |
dest = self.vertex_source_edit |
| 552 |
elif ext in ('.txt', '.frag'): |
| 553 |
dest = self.fragSourceEdit |
| 554 |
else: |
| 555 |
dest = self.fragSourceEdit |
| 556 |
|
| 557 |
text = file_path.read_text() |
| 558 |
dest.setText(text) |
| 559 |
|
| 560 |
def saveShaders(self) -> None: |
| 561 |
options = self.get_file_dialog_options() |
| 562 |
file_name, _ = QFileDialog.getSaveFileName( |
| 563 |
self._window, "Saving Both Shader Files (vert and frag)", "", |
| 564 |
options=options) |
| 565 |
|
| 566 |
if file_name: |
| 567 |
base_path = Path(file_name) |
| 568 |
vert_filename = base_path.with_suffix(".vert") |
| 569 |
frag_filename = base_path.with_suffix(".frag") |
| 570 |
|
| 571 |
vert_filename.write_text(self.vertex_source_edit.toPlainText()) |
| 572 |
frag_filename.write_text(self.fragSourceEdit.toPlainText()) |
| 573 |
|
| 574 |
def removeImage(self, actionWidget: QtGui.QAction) -> None: |
| 575 |
if self.imageMenu: |
| 576 |
self.imageMenu.removeAction(actionWidget) |
| 577 |
|
| 578 |
self.images.remove(actionWidget.image) |
| 579 |
|
| 580 |
|
| 581 |
for idx, image in enumerate(self.images): |
| 582 |
image.shader_name = f"sprite_texture{idx}" |
| 583 |
|
| 584 |
for action in self.imageMenu.actions(): |
| 585 |
shader_name = action.image.shader_name |
| 586 |
action.setText(f"{os.path.basename(action.fileName)} ({shader_name})") |
| 587 |
|
| 588 |
if len(self.images) == 0: |
| 589 |
self.imageMenu.addAction(self.noImageAction) |
| 590 |
|
| 591 |
def closeProgram(self) -> None: |
| 592 |
app.exit() |
| 593 |
|
| 594 |
def retranslateUi(self, MainWindow: QtWidgets.QMainWindow) -> None: |
| 595 |
_translate = QtCore.QCoreApplication.translate |
| 596 |
MainWindow.setWindowTitle(_translate("MainWindow", "Sprite Shader Previewer")) |
| 597 |
self.label.setText(_translate("MainWindow", "Vertex Source:")) |
| 598 |
self.label_2.setText(_translate("MainWindow", "Fragment Source:")) |
| 599 |
self.compileShaderBtn.setText(_translate("MainWindow", "Compile Shaders")) |
| 600 |
self.menuFile.setTitle(_translate("MainWindow", "File")) |
| 601 |
self.actionOpen_Image.setText(_translate("MainWindow", "Open Images")) |
| 602 |
self.actionOpen_Shader.setText(_translate("MainWindow", "Open Shader")) |
| 603 |
self.actionSave_Shader.setText(_translate("MainWindow", "Save Shader")) |
| 604 |
self.actionExit.setText(_translate("MainWindow", "Exit")) |
| 605 |
self.imageMenu.setTitle(_translate("MainWindow", "Images")) |
| 606 |
self.noImageAction.setText(_translate("MainWindow", "No Images Loaded")) |
| 607 |
|
| 608 |
self.vertex_source_edit.setText(default_vertex_src) |
| 609 |
self.fragSourceEdit.setText(default_frag_src) |
| 610 |
|
| 611 |
|
| 612 |
class PygletWidget(QOpenGLWidget): |
| 613 |
_default_vertex_source = """#version 150 core |
| 614 |
in vec4 position; |
| 615 |
|
| 616 |
uniform WindowBlock |
| 617 |
{ |
| 618 |
mat4 projection; |
| 619 |
mat4 view; |
| 620 |
} window; |
| 621 |
|
| 622 |
void main() |
| 623 |
{ |
| 624 |
gl_Position = window.projection * window.view * position; |
| 625 |
} |
| 626 |
""" |
| 627 |
_default_fragment_source = """#version 150 core |
| 628 |
out vec4 color; |
| 629 |
|
| 630 |
void main() |
| 631 |
{ |
| 632 |
color = vec4(1.0, 0.0, 0.0, 1.0); |
| 633 |
} |
| 634 |
""" |
| 635 |
|
| 636 |
def __init__(self, width, height, parent, mainWindow) -> None: |
| 637 |
super().__init__(parent) |
| 638 |
self.mainWindow = mainWindow |
| 639 |
self.setMinimumSize(width, height) |
| 640 |
|
| 641 |
self.timer = QtCore.QTimer() |
| 642 |
self.timer.timeout.connect(self._pyglet_update) |
| 643 |
self.timer.setInterval(0) |
| 644 |
self.timer.start() |
| 645 |
|
| 646 |
self.zoom = 1.0 |
| 647 |
|
| 648 |
self.elapsed = 0 |
| 649 |
|
| 650 |
pyglet.clock.schedule_interval(self.update_time_uniform, 1 / 60.0) |
| 651 |
|
| 652 |
def wheelEvent(self, event: QWheelEvent) -> None: |
| 653 |
super().wheelEvent(event) |
| 654 |
if event.angleDelta().y() > 0: |
| 655 |
self.zoom *= 2 |
| 656 |
else: |
| 657 |
self.zoom /= 2 |
| 658 |
|
| 659 |
self.zoom = pyglet.math.clamp(self.zoom, 0.125, 40.0) |
| 660 |
self.view = pyglet.math.Mat4().scale(pyglet.math.Vec3( |
| 661 |
self.zoom, self.zoom, 1.0)) |
| 662 |
|
| 663 |
event.accept() |
| 664 |
|
| 665 |
def update_time_uniform(self, dt: float) -> None: |
| 666 |
self.elapsed += dt |
| 667 |
|
| 668 |
if self.mainWindow.program: |
| 669 |
self.mainWindow.program.use() |
| 670 |
|
| 671 |
|
| 672 |
try: |
| 673 |
self.mainWindow.program['time'] = self.elapsed |
| 674 |
except Exception: |
| 675 |
pass |
| 676 |
|
| 677 |
self.mainWindow.program.stop() |
| 678 |
|
| 679 |
def _pyglet_update(self) -> None: |
| 680 |
|
| 681 |
pyglet.clock.tick() |
| 682 |
|
| 683 |
|
| 684 |
self.update() |
| 685 |
|
| 686 |
def paintGL(self) -> None: |
| 687 |
"""Pyglet equivalent of on_draw event for window""" |
| 688 |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) |
| 689 |
|
| 690 |
self.batch.draw() |
| 691 |
|
| 692 |
def resizeGL(self, width: int, height: int) -> None: |
| 693 |
self.projection = pyglet.math.Mat4.orthogonal_projection(0, width, 0, height, -255, 255) |
| 694 |
|
| 695 |
self.viewport = 0, 0, width, height |
| 696 |
|
| 697 |
def initializeGL(self) -> None: |
| 698 |
"""Call anything that needs a context to be created.""" |
| 699 |
self._projection_matrix = pyglet.math.Mat4() |
| 700 |
self._view_matrix = pyglet.math.Mat4() |
| 701 |
|
| 702 |
self.batch = pyglet.graphics.Batch() |
| 703 |
|
| 704 |
self._default_program = pyglet.graphics.shader.ShaderProgram( |
| 705 |
pyglet.graphics.shader.Shader(self._default_vertex_source, 'vertex'), |
| 706 |
pyglet.graphics.shader.Shader(self._default_fragment_source, 'fragment')) |
| 707 |
|
| 708 |
self.ubo = self._default_program.uniform_blocks['WindowBlock'].create_ubo() |
| 709 |
|
| 710 |
self.view = pyglet.math.Mat4() |
| 711 |
self.projection = pyglet.math.Mat4.orthogonal_projection(0, self.width(), 0, self.height(), -255, 255) |
| 712 |
self.viewport = 0, 0, self.width(), self.height() |
| 713 |
|
| 714 |
@property |
| 715 |
def viewport(self) -> tuple[int, int, int, int]: |
| 716 |
"""The Window viewport |
| 717 |
|
| 718 |
The Window viewport, expressed as (x, y, width, height). |
| 719 |
|
| 720 |
:return: The viewport size as a tuple of four ints. |
| 721 |
""" |
| 722 |
return self._viewport |
| 723 |
|
| 724 |
@viewport.setter |
| 725 |
def viewport(self, values: tuple[int, int, int, int]) -> None: |
| 726 |
self._viewport = values |
| 727 |
pr = 1.0 |
| 728 |
x, y, w, h = values |
| 729 |
pyglet.gl.glViewport(int(x * pr), int(y * pr), int(w * pr), int(h * pr)) |
| 730 |
|
| 731 |
@property |
| 732 |
def projection(self) -> pyglet.math.Mat4: |
| 733 |
return self._projection_matrix |
| 734 |
|
| 735 |
@projection.setter |
| 736 |
def projection(self, matrix: pyglet.math.Mat4) -> None: |
| 737 |
with self.ubo as window_block: |
| 738 |
window_block.projection[:] = matrix |
| 739 |
|
| 740 |
self._projection_matrix = matrix |
| 741 |
|
| 742 |
@property |
| 743 |
def view(self) -> pyglet.math.Mat4: |
| 744 |
"""The OpenGL window view matrix. Read-write. |
| 745 |
|
| 746 |
The default view is an identity matrix, but a custom |
| 747 |
:py:class:`pyglet.math.Mat4` instance can be set. |
| 748 |
Alternatively, you can supply a flat tuple of 16 values. |
| 749 |
""" |
| 750 |
return self._view_matrix |
| 751 |
|
| 752 |
@view.setter |
| 753 |
def view(self, matrix: pyglet.math.Mat4) -> None: |
| 754 |
|
| 755 |
with self.ubo as window_block: |
| 756 |
window_block.view[:] = matrix |
| 757 |
|
| 758 |
self._view_matrix = matrix |
| 759 |
|
| 760 |
|
| 761 |
def excepthook(exc_type, exc_value, exc_tb) -> None: |
| 762 |
"""Replacement for Python's default exception handler function. |
| 763 |
|
| 764 |
See the following for more information: |
| 765 |
https://docs.python.org/3/library/sys.html#sys.excepthook |
| 766 |
""" |
| 767 |
tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb)) |
| 768 |
print(tb) |
| 769 |
|
| 770 |
|
| 771 |
if __name__ == "__main__": |
| 772 |
|
| 773 |
app = QtWidgets.QApplication(sys.argv) |
| 774 |
ui = Ui_MainWindow(use_native_file_dialog=arguments.native_file_dialog) |
| 775 |
qt_window = QtWidgets.QMainWindow() |
| 776 |
ui.setupUi(qt_window) |
| 777 |
qt_window.show() |
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
sys.excepthook = excepthook |
| 782 |
|
| 783 |
|
| 784 |
sys.exit(app.exec()) |