-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScreenTri.py
More file actions
executable file
·371 lines (322 loc) · 12.4 KB
/
Copy pathScreenTri.py
File metadata and controls
executable file
·371 lines (322 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env -S uv run --script
"""
A template for creating a PySide6 application with an OpenGL viewport using py-ngl.
"""
import argparse
import sys
import traceback
from enum import Enum
import numpy as np
import OpenGL.GL as gl
from ncca.ngl import logger
from ncca.ngl.opengl import ShaderLib
from PySide6.QtCore import QEvent, QObject, Qt, QTimer, QTimerEvent
from PySide6.QtGui import QMouseEvent, QSurfaceFormat, QWheelEvent
from PySide6.QtOpenGL import QOpenGLWindow
from PySide6.QtWidgets import QApplication
TEXTURE_WIDTH = 1024
TEXTURE_HEIGHT = 720
class DrawMode(Enum):
Pixels = 0
Lines = 1
class MainWindow(QOpenGLWindow):
"""
The main window for the OpenGL application.
Inherits from QOpenGLWindow to provide a canvas for OpenGL rendering within a PySide6 GUI.
It handles user input (mouse, keyboard) for camera control and manages the OpenGL context.
"""
def __init__(self, parent: object = None) -> None:
super().__init__()
self.ratio = self.devicePixelRatio()
# A constant vector to simulate wind, pushing all particles.
# --- Window and UI Attributes ---
self.window_width: int = 1024 # Window width
self.window_height: int = 720 # Window height
self.setTitle("ScreenTri")
self.vao = None
self.texture_id = None
# use an RGBA uint8 buffer for easy uploading
self.buffer = np.zeros((TEXTURE_HEIGHT, TEXTURE_WIDTH, 4), dtype=np.uint8)
self.draw_mode = DrawMode.Pixels
self.animate = True
self.rng = np.random.default_rng()
self.width_dist = (0, TEXTURE_WIDTH - 1)
self.height_dist = (0, TEXTURE_HEIGHT - 1)
self.colour_dist = (0, 255)
def initializeGL(self) -> None:
"""
Called once when the OpenGL context is first created.
This is the place to set up global OpenGL state, load shaders, and create geometry.
"""
self.makeCurrent() # Make the OpenGL context current in this thread
# Set the background color to a dark grey
gl.glClearColor(0.4, 0.4, 0.4, 1.0)
# Enable depth testing, which ensures that objects closer to the camera obscure those further away
gl.glEnable(gl.GL_DEPTH_TEST)
# Enable multisampling for anti-aliasing, which smooths jagged edges
gl.glEnable(gl.GL_MULTISAMPLE)
ShaderLib.load_shader(
"ScreenTri",
"shaders/ScreenTriVertex.glsl",
"shaders/ScreenTriFragment.glsl",
)
ShaderLib.use("ScreenTri")
self.texture_id = gl.glGenTextures(1)
self.vao = gl.glGenVertexArrays(1)
self.clear_buffer()
self.update_texture_buffer()
self.startTimer(16)
def update_texture_buffer(self):
gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_id)
# Set some sensible defaults
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR
)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
# Upload RGBA8 data. PyOpenGL accepts numpy arrays directly.
# Note: OpenGL expects width,height ordering; numpy is (height,width,...)
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
gl.glTexImage2D(
gl.GL_TEXTURE_2D,
0,
gl.GL_RGBA,
TEXTURE_WIDTH,
TEXTURE_HEIGHT,
0,
gl.GL_RGBA,
gl.GL_UNSIGNED_BYTE,
self.buffer,
)
gl.glGenerateMipmap(gl.GL_TEXTURE_2D)
def clear_buffer(self):
"""Fill buffer with white (RGBA = 255,255,255,255)."""
self.buffer[..., 0:3] = 255
self.buffer[..., 3] = 255
def set_pixel(self, x, y, r, g, b):
if x < 0 or x >= TEXTURE_WIDTH or y < 0 or y >= TEXTURE_HEIGHT:
return
# Note: numpy uses row-major (y,x)
self.buffer[y, x, 0] = r
self.buffer[y, x, 1] = g
self.buffer[y, x, 2] = b
self.buffer[y, x, 3] = 255
def draw_line(self, x0, y0, x1, y1, r, g, b):
# Bresenham's line algorithm
dx = abs(x1 - x0)
dy = abs(y1 - y0)
sx = 1 if x0 < x1 else -1
sy = 1 if y0 < y1 else -1
err = dx - dy
while True:
self.set_pixel(x0, y0, r, g, b)
if x0 == x1 and y0 == y1:
break
e2 = 2 * err
if e2 > -dy:
err -= dy
x0 += sx
if e2 < dx:
err += dx
y0 += sy
def random_int(self, low_high):
lo, hi = low_high
return int(self.rng.integers(lo, hi + 1))
def random_pixels(self):
r = self.random_int(self.colour_dist)
g = self.random_int(self.colour_dist)
b = self.random_int(self.colour_dist)
for _ in range(1000):
x = self.random_int(self.width_dist)
y = self.random_int(self.height_dist)
self.set_pixel(x, y, r, g, b)
self.update_texture_buffer()
def random_lines(self):
self.clear_buffer()
for _ in range(1000):
r = self.random_int(self.colour_dist)
g = self.random_int(self.colour_dist)
b = self.random_int(self.colour_dist)
x0 = self.random_int(self.width_dist)
y0 = self.random_int(self.height_dist)
x1 = self.random_int(self.width_dist)
y1 = self.random_int(self.height_dist)
self.draw_line(x0, y0, x1, y1, r, g, b)
self.update_texture_buffer()
def paintGL(self) -> None:
"""
Called every time the window needs to be redrawn.
This is the main rendering loop where all drawing commands are issued.
"""
self.makeCurrent()
# Set the viewport to cover the entire window
gl.glViewport(0, 0, self.window_width, self.window_height)
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glBindVertexArray(self.vao)
# bind texture
gl.glActiveTexture(gl.GL_TEXTURE0)
gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_id)
# it's assumed the fragment shader samples from texture unit 0
gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
gl.glBindVertexArray(0)
def timerEvent(self, event: QTimerEvent) -> None:
"""
This event is called at a regular interval (set by startTimer).
It's used to update the animation of the scene.
Here, it updates the positions of the points and makes them bounce
off the edges of the simulation area.
Parameters
----------
event : QTimerEvent
The QTimerEvent object, not used in this method but required by the API.
"""
# Add the wind factor to the particle's own direction to get the final velocity
if not self.animate:
return
if self.draw_mode == DrawMode.Pixels:
self.random_pixels()
else:
self.random_lines()
self.update()
def resizeGL(self, w: int, h: int) -> None:
"""
Called whenever the window is resized.
It's crucial to update the viewport and projection matrix here.
Parameters
----------
w : int
The new width of the window.
h : int
The new height of the window.
"""
# Update the stored width and height, considering high-DPI displays
self.window_width = int(w * self.ratio)
self.window_height = int(h * self.ratio)
def keyPressEvent(self, event):
key = event.key()
if key == Qt.Key_Escape:
QApplication.exit(0)
elif key == Qt.Key_P:
self.draw_mode = DrawMode.Pixels
elif key == Qt.Key_L:
self.draw_mode = DrawMode.Lines
elif key == Qt.Key_Space:
self.clear_buffer()
self.update_texture_buffer()
self.update()
elif key == Qt.Key_F:
self.showFullScreen()
elif key == Qt.Key_N:
self.showNormal()
elif key == Qt.Key_A:
self.animate = not self.animate
else:
super().keyPressEvent(event)
self.update()
def mouseMoveEvent(self, event: QMouseEvent) -> None:
"""
Handles mouse movement events for camera control.
Parameters
----------
event : QMouseEvent
The QMouseEvent object containing the new mouse position.
"""
# Rotate the scene if the left mouse button is pressed
if event.buttons() == Qt.LeftButton or event.buttons() == Qt.RightButton:
self.update()
def mousePressEvent(self, event: QMouseEvent) -> None:
"""
Handles mouse button press events to initiate rotation or translation.
Parameters
----------
event : QMouseEvent
The QMouseEvent object.
"""
event.position()
# Left button initiates rotation
def wheelEvent(self, event: QWheelEvent) -> None:
"""
Handles mouse wheel events for zooming.
Parameters
----------
event : QWheelEvent
The QWheelEvent object.
"""
num_pixels = event.angleDelta()
# Zoom in or out by adjusting the Z position of the model
if num_pixels.x() > 0:
self.zoom += 0.01
elif num_pixels.x() < 0:
self.zoom -= 0.01
self.zoom = max(0.05, min(10.0, self.zoom))
self.update()
class DebugApplication(QApplication):
"""
A custom QApplication subclass for improved debugging.
By default, Qt's event loop can suppress exceptions that occur within event handlers
(like paintGL or mouseMoveEvent), making it very difficult to debug as the application
may simply crash or freeze without any error message. This class overrides the `notify`
method to catch these exceptions, print a full traceback to the console, and then
re-raise the exception to halt the program, making the error immediately visible.
"""
def __init__(self, argv: list[str]) -> None:
super().__init__(argv)
logger.info("Running in full debug mode")
def notify(self, receiver: QObject, event: QEvent) -> bool:
"""
Overrides the central event handler to catch and report exceptions.
"""
try:
# Attempt to process the event as usual
return super().notify(receiver, event)
except Exception:
# If an exception occurs, print the full traceback
traceback.print_exc()
# Re-raise the exception to stop the application
raise
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--smoketest",
nargs="?",
const=200,
default=None,
type=int,
metavar="MS",
help="run for MS milliseconds (default 200), print SMOKETEST OK and exit",
)
parser.add_argument(
"--debug",
action="store_true",
help="run with DebugApplication (tracebacks from Qt event handlers)",
)
args = parser.parse_args()
# --- Application Entry Point ---
format: QSurfaceFormat = QSurfaceFormat()
# Request 4x multisampling for anti-aliasing
format.setSamples(4)
# Request OpenGL version 4.1 as this is the highest supported on macOS
format.setMajorVersion(4)
format.setMinorVersion(1)
# Request a Core Profile context, which removes deprecated, fixed-function pipeline features
format.setProfile(QSurfaceFormat.CoreProfile)
# Request a 24-bit depth buffer for proper 3D sorting
format.setDepthBufferSize(24)
# Set default format for all new OpenGL contexts
QSurfaceFormat.setDefaultFormat(format)
# Apply this format to all new OpenGL contexts
QSurfaceFormat.setDefaultFormat(format)
if args.debug:
app = DebugApplication(sys.argv)
else:
app = QApplication(sys.argv)
window = MainWindow()
# Set the initial window size
window.resize(1024, 720)
# Show the window
window.show()
if args.smoketest is not None:
QTimer.singleShot(args.smoketest, lambda: (print("SMOKETEST OK"), app.quit()))
# Start the application's event loop
sys.exit(app.exec())