Repository navigation
Expand file tree
/
Copy pathShowMipmap.py
More file actions
executable file
·454 lines (395 loc) · 16.9 KB
/
Copy pathShowMipmap.py
File metadata and controls
executable file
·454 lines (395 loc) · 16.9 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#!/usr/bin/env -S uv run --script
"""
A template for creating a PySide6 application with an OpenGL viewport using py-ngl.
This script sets up a basic window, initializes an OpenGL context, and provides
standard mouse and keyboard controls for interacting with a 3D scene (rotate, pan, zoom).
It is designed to be a starting point for more complex OpenGL applications.
"""
import argparse
import sys
import traceback
import numpy as np
import OpenGL.GL as gl
from ncca.ngl import Mat4, Transform, Vec3, logger, look_at, perspective
from ncca.ngl.opengl import ShaderLib
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QSurfaceFormat
from PySide6.QtOpenGL import QOpenGLWindow
from PySide6.QtWidgets import QApplication
TEXTURE_SHADER = "TextureShader"
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__()
# Camera and Transformation Attributes
self.mouse_global_tx: Mat4 = (
Mat4()
) # Global transformation matrix controlled by the mouse
self.view: Mat4 = Mat4()
self.project: Mat4 = Mat4()
self.model_position: Vec3 = Vec3() # Position of the model in world space
# Window and UI Attributes
self.window_width: int = 1024 # Window width
self.window_height: int = 720 # Window height
self.setTitle("MipMap Display")
# Mouse Control Attributes for Camera Manipulation
self.rotate: bool = False # Flag to check if the scene is being rotated
self.translate: bool = (
False # Flag to check if the scene is being translated (panned)
)
self.spin_x_face: int = 0 # Accumulated rotation around the X-axis
self.spin_y_face: int = 0 # Accumulated rotation around the Y-axis
self.original_x_rotation: int = (
0 # Initial X position of the mouse when a rotation starts
)
self.original_y_rotation: int = (
0 # Initial Y position of the mouse when a rotation starts
)
self.original_x_pos: int = (
0 # Initial X position of the mouse when a translation starts
)
self.original_y_pos: int = (
0 # Initial Y position of the mouse when a translation starts
)
self.INCREMENT: float = 0.01 # Sensitivity for translation
self.ZOOM: float = 0.1 # Sensitivity for zooming
self.transform = Transform()
def create_texture(self):
"""
Create a 2D texture with explicit mip levels. Each mip level is filled
with a distinct solid color so you can visually inspect which level is used.
"""
mip_level = 0
self.tex_id = gl.glGenTextures(1)
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tex_id)
# Using an image width of 128 gives us 6 mip levels: 128,64,32,16,8,4
colours = [
(1.0, 0.0, 0.0), # red
(0.0, 1.0, 0.0), # green
(0.0, 0.0, 1.0), # blue
(1.0, 1.0, 0.0), # yellow
(1.0, 1.0, 1.0), # white
(1.0, 0.0, 1.0), # magenta
]
ml = 128
while ml >= 4:
print("mip level", ml)
color = colours[mip_level]
# create an ml x ml texture filled with `color`, dtype float32 to match GL_FLOAT
data = np.full((ml, ml, 3), color, dtype=np.float32)
print("data size", data.size, "using colour", color)
# Set filters (set per-texture here; could also be set once after all levels uploaded)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST
)
gl.glTexParameteri(
gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST_MIPMAP_NEAREST
)
# Upload this mip level
# Note: internalFormat and format use GL_RGB and type GL_FLOAT to match the C++ code
gl.glTexImage2D(
gl.GL_TEXTURE_2D,
mip_level,
gl.GL_RGB,
ml,
ml,
0,
gl.GL_RGB,
gl.GL_FLOAT,
data,
)
mip_level += 1
ml //= 2
# Do not auto-generate mipmaps (we provided them manually)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_BASE_LEVEL, 0)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAX_LEVEL, mip_level - 1)
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAX_LOD, mip_level - 1)
gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
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)
# It looks from (0, 1, 4) towards (0, 0, 0) with the 'up' direction along the Y-axis.
self.view = look_at(Vec3(0, 2, 4), Vec3(0, 0, 0), Vec3(0, 1, 0))
# Load the Texture shader
ShaderLib.load_shader(
TEXTURE_SHADER, "shaders/TextureVert.glsl", "shaders/TextureFrag.glsl"
)
ShaderLib.use(TEXTURE_SHADER)
# We now create our view matrix for a static camera
eye = Vec3(0.0, 2.0, 4.0)
to = Vec3(0.0, 0.0, 0.0)
up = Vec3(0.0, 1.0, 0.0)
# now load to our new camera
self.view = look_at(eye, to, up)
ShaderLib.set_uniform("tex", 0)
self._create_cube(0.2)
self.create_texture()
def _create_cube(self, scale) -> None:
# Create a cube primitive
# fmt: off
vertices= np.array((
-1, 1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, # back
-1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, # front
-1, 1, -1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, # top
-1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, -1, # bottom
-1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, # left
1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, # right
), dtype=np.float32)
uvs = np.array((
0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, # back
0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, # front
0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, # top
0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, # bottom
1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, # left
1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, # right
), dtype=np.float32)
vertices=vertices*scale
# fmt: on
self.vao_id = gl.glGenVertexArrays(1)
gl.glBindVertexArray(self.vao_id)
vbo_id = gl.glGenBuffers(2)
# 4. Configure the first VBO for vertex positions.
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo_id[0])
gl.glBufferData(
gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices, gl.GL_STATIC_DRAW
)
# Set up vertex attribute pointer 0 (for "inPosition" in the vertex shader).
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glEnableVertexAttribArray(0)
# 5. Configure the second VBO for vertex colours.
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo_id[1])
gl.glBufferData(gl.GL_ARRAY_BUFFER, uvs.nbytes, uvs, gl.GL_STATIC_DRAW)
# Set up vertex attribute pointer 1 (for "inColour" in the vertex shader).
gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
gl.glEnableVertexAttribArray(1)
# 6. Unbind the VAO to prevent accidental modification.
gl.glBindVertexArray(0)
def load_matrices_to_shader(self) -> None:
ShaderLib.use(TEXTURE_SHADER)
# Create an actual structured array instance
MVP = self.project @ self.view @ self.mouse_global_tx @ self.transform.matrix()
ShaderLib.set_uniform("MVP", MVP)
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)
self.load_matrices_to_shader()
# Apply rotation based on user input
# Apply rotation based on user input
rot_x = Mat4().rotate_x(self.spin_x_face)
rot_y = Mat4().rotate_y(self.spin_y_face)
self.mouse_global_tx = rot_y @ rot_x
# Update model position
self.mouse_global_tx[3, 0] = self.model_position.x
self.mouse_global_tx[3, 1] = self.model_position.y
self.mouse_global_tx[3, 2] = self.model_position.z
gl.glBindTexture(gl.GL_TEXTURE_2D, self.tex_id)
gl.glBindVertexArray(self.vao_id)
for z in np.linspace(-14, 15, 50):
for x in np.linspace(-14, 15, 50):
self.transform.reset()
self.transform.set_position(x, 0, z)
self.transform.set_rotation(x * 20.0, (x * z) * 40.0, z * 2.0)
self.load_matrices_to_shader()
gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)
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.devicePixelRatio())
self.window_height = int(h * self.devicePixelRatio())
self.project = perspective(45.0, float(w) / h, 0.01, 350.0)
def keyPressEvent(self, event) -> None:
"""
Handles keyboard press events.
Parameters
----------
event
The QKeyEvent object containing information about the key press.
"""
key = event.key()
if key == Qt.Key_Escape:
self.close()
elif key == Qt.Key_W:
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)
elif key == Qt.Key_S:
gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL)
elif key == Qt.Key_Space:
# Reset camera rotation and position
self.spin_x_face = 0
self.spin_y_face = 0
self.model_position.set(0, 0, 0)
# Trigger a redraw to apply changes
self.update()
super().keyPressEvent(event)
def mouseMoveEvent(self, event) -> None:
"""
Handles mouse movement events for camera control.
Parameters
----------
event
The QMouseEvent object containing the new mouse position.
"""
# Rotate the scene if the left mouse button is pressed
if self.rotate and event.buttons() == Qt.LeftButton:
position = event.position()
diff_x = position.x() - self.original_x_rotation
diff_y = position.y() - self.original_y_rotation
self.spin_x_face += int(0.5 * diff_y)
self.spin_y_face += int(0.5 * diff_x)
self.original_x_rotation = position.x()
self.original_y_rotation = position.y()
self.update()
# Translate (pan) the scene if the right mouse button is pressed
elif self.translate and event.buttons() == Qt.RightButton:
position = event.position()
diff_x = int(position.x() - self.original_x_pos)
diff_y = int(position.y() - self.original_y_pos)
self.original_x_pos = position.x()
self.original_y_pos = position.y()
self.model_position.x += self.INCREMENT * diff_x
self.model_position.y -= self.INCREMENT * diff_y
self.update()
def mousePressEvent(self, event) -> None:
"""
Handles mouse button press events to initiate rotation or translation.
Parameters
----------
event
The QMouseEvent object.
"""
position = event.position()
# Left button initiates rotation
if event.button() == Qt.LeftButton:
self.original_x_rotation = position.x()
self.original_y_rotation = position.y()
self.rotate = True
# Right button initiates translation
elif event.button() == Qt.RightButton:
self.original_x_pos = position.x()
self.original_y_pos = position.y()
self.translate = True
def mouseReleaseEvent(self, event) -> None:
"""
Handles mouse button release events to stop rotation or translation.
Parameters
----------
event
The QMouseEvent object.
"""
# Stop rotating when the left button is released
if event.button() == Qt.LeftButton:
self.rotate = False
# Stop translating when the right button is released
elif event.button() == Qt.RightButton:
self.translate = False
def wheelEvent(self, event) -> None:
"""
Handles mouse wheel events for zooming.
Parameters
----------
event
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.model_position.z += self.ZOOM
elif num_pixels.x() < 0:
self.model_position.z -= 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):
super().__init__(argv)
logger.info("Running in full debug mode")
def notify(self, receiver, event):
"""
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())