-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathvisualizer.py
More file actions
executable file
·2139 lines (1837 loc) · 81.2 KB
/
visualizer.py
File metadata and controls
executable file
·2139 lines (1837 loc) · 81.2 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import annotations
import collections
import math
import os
import time
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from excitation.trajectoryGenerator import Trajectory
import platform
import subprocess
import numpy as np
import pyglet
from OpenGL import GL as gl
from OpenGL.GL.shaders import compileShader
from pyglet.window import key
from excitation.trajectoryGenerator import PulsedTrajectory
from identification.model import Model
def _is_dark_mode() -> bool:
"""Detect if the OS is in dark mode (macOS, GNOME, KDE)."""
system = platform.system()
try:
if system == "Darwin":
result = subprocess.run(
["defaults", "read", "-g", "AppleInterfaceStyle"],
capture_output=True,
text=True,
)
return result.stdout.strip().lower() == "dark"
elif system == "Linux":
# GNOME
result = subprocess.run(
["gsettings", "get", "org.gnome.desktop.interface", "color-scheme"],
capture_output=True,
text=True,
)
if "dark" in result.stdout.lower():
return True
# KDE
result = subprocess.run(
["kreadconfig5", "--group", "General", "--key", "ColorScheme"],
capture_output=True,
text=True,
)
if "dark" in result.stdout.lower():
return True
except Exception:
pass
return False
# ── Matrix utility functions (replace legacy fixed-function pipeline) ──────────
def perspective_matrix(fov_deg: float, aspect: float, near: float, far: float) -> np.ndarray:
"""Build a perspective projection matrix (replaces gluPerspective)."""
f = 1.0 / math.tan(math.radians(fov_deg) / 2.0)
nf = near - far
return np.array(
[
[f / aspect, 0.0, 0.0, 0.0],
[0.0, f, 0.0, 0.0],
[0.0, 0.0, (far + near) / nf, (2.0 * far * near) / nf],
[0.0, 0.0, -1.0, 0.0],
],
dtype=np.float32,
)
def ortho_matrix(left: float, right: float, bottom: float, top: float, near: float, far: float) -> np.ndarray:
"""Build an orthographic projection matrix (replaces glOrtho)."""
rl = right - left
tb = top - bottom
fn = far - near
return np.array(
[
[2.0 / rl, 0.0, 0.0, -(right + left) / rl],
[0.0, 2.0 / tb, 0.0, -(top + bottom) / tb],
[0.0, 0.0, -2.0 / fn, -(far + near) / fn],
[0.0, 0.0, 0.0, 1.0],
],
dtype=np.float32,
)
def translation_matrix(x: float, y: float, z: float) -> np.ndarray:
"""Build a 4x4 translation matrix (replaces glTranslatef)."""
m = np.eye(4, dtype=np.float32)
m[0, 3] = x
m[1, 3] = y
m[2, 3] = z
return m
def rotation_matrix(angle_deg: float, ax: float, ay: float, az: float) -> np.ndarray:
"""Build a 4x4 rotation matrix around an arbitrary axis (replaces glRotatef)."""
a = math.radians(angle_deg)
c = math.cos(a)
s = math.sin(a)
length = math.sqrt(ax * ax + ay * ay + az * az)
if length < 1e-12:
return np.eye(4, dtype=np.float32)
ax, ay, az = ax / length, ay / length, az / length
t = 1.0 - c
return np.array(
[
[t * ax * ax + c, t * ax * ay - s * az, t * ax * az + s * ay, 0.0],
[t * ax * ay + s * az, t * ay * ay + c, t * ay * az - s * ax, 0.0],
[t * ax * az - s * ay, t * ay * az + s * ax, t * az * az + c, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
dtype=np.float32,
)
def scale_matrix(sx: float, sy: float, sz: float) -> np.ndarray:
"""Build a 4x4 scale matrix (replaces glScalef)."""
m = np.eye(4, dtype=np.float32)
m[0, 0] = sx
m[1, 1] = sy
m[2, 2] = sz
return m
def shadow_matrix(light: np.ndarray, plane: np.ndarray) -> np.ndarray:
"""Build a 4x4 planar shadow projection matrix.
Projects geometry onto the plane defined by the 4-component plane equation
(nx, ny, nz, d) as if cast from a point light at (lx, ly, lz, lw).
Formula: M = dot(plane, light) * I - outer(light, plane).
"""
d = float(np.dot(plane, light))
m = -np.outer(light, plane)
m[0, 0] += d
m[1, 1] += d
m[2, 2] += d
m[3, 3] += d
return m.astype(np.float32)
# ── VAO/VBO mesh wrapper (replaces pyglet.graphics.vertex_list_indexed) ───────
class VAOMesh:
"""Raw OpenGL VAO/VBO wrapper for core-profile rendering."""
def __init__(
self,
vertices: np.ndarray,
indices: np.ndarray,
normals: np.ndarray | None = None,
) -> None:
vertices = np.asarray(vertices, dtype=np.float32)
indices = np.asarray(indices, dtype=np.uint16)
self.index_count = len(indices)
self.vao = gl.glGenVertexArrays(1)
gl.glBindVertexArray(self.vao)
# position VBO — attribute 0
vbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices, gl.GL_STATIC_DRAW)
gl.glEnableVertexAttribArray(0)
gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
# normals VBO — attribute 1
if normals is not None:
normals = np.asarray(normals, dtype=np.float32)
nbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, nbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, normals.nbytes, normals, gl.GL_STATIC_DRAW)
gl.glEnableVertexAttribArray(1)
gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
# element buffer
ebo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo)
gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, gl.GL_STATIC_DRAW)
gl.glBindVertexArray(0)
def draw(self, mode: int) -> None:
"""Draw with the given GL primitive mode."""
gl.glBindVertexArray(self.vao)
gl.glDrawElements(mode, self.index_count, gl.GL_UNSIGNED_SHORT, None)
gl.glBindVertexArray(0)
# ── Geometry classes ──────────────────────────────────────────────────────────
class Cube:
"""vertices for a cube of size 1"""
def __init__(self):
self.vertices = np.array(
[
-0.5,
0.5,
0.5,
-0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
0.5,
0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
-0.5,
0.5,
0.5,
-0.5,
],
np.float32,
)
self.indices = np.array(
[
0,
1,
2,
0,
2,
3,
0,
3,
7,
0,
7,
4,
0,
4,
5,
0,
5,
1,
3,
2,
6,
3,
6,
7,
1,
2,
5,
2,
5,
6,
5,
4,
7,
7,
6,
5,
],
np.uint16,
)
# normals are unit vector from center to vertex
c = np.array([0.0, 0.0, 0.0])
self.normals = ((self.vertices.reshape((8, 3)) - c) / np.sqrt(3)).flatten().astype(np.float32)
def getVerticeList(self) -> VAOMesh:
return VAOMesh(self.vertices, self.indices, self.normals)
class CylinderGeom:
"""Unit open-ended cylinder along Z from -0.5 to 0.5, radius 1.
Used as the shaft of a capsule. Hemisphere caps are rendered separately as
SphereGeom instances at each endpoint to avoid non-uniform scale distortion.
"""
def __init__(self, n_segments: int = 16) -> None:
"""Generate cylinder side vertices, normals, and triangle indices."""
verts: list[list[float]] = []
norms: list[list[float]] = []
idxs: list[int] = []
for z in [-0.5, 0.5]:
for i in range(n_segments + 1):
theta = 2.0 * np.pi * i / n_segments
x, y = np.cos(theta), np.sin(theta)
verts.append([x, y, z])
norms.append([x, y, 0.0])
for i in range(n_segments):
b = 0
t = n_segments + 1
idxs.extend([b + i, b + i + 1, t + i])
idxs.extend([b + i + 1, t + i + 1, t + i])
self.vertices = np.array(verts, dtype=np.float32).flatten()
self.normals = np.array(norms, dtype=np.float32).flatten()
self.indices = np.array(idxs, dtype=np.uint16)
def getVerticeList(self) -> VAOMesh:
"""Create a VAOMesh for this cylinder geometry."""
return VAOMesh(self.vertices, self.indices, self.normals)
class SphereGeom:
"""Unit sphere of radius 1 centered at origin.
Used for hemisphere caps of capsule rendering.
"""
def __init__(self, n_segments: int = 16, n_rings: int = 12) -> None:
"""Generate sphere vertices, normals, and triangle indices."""
verts: list[list[float]] = []
norms: list[list[float]] = []
idxs: list[int] = []
# generate vertices ring by ring from bottom pole to top pole
for ring in range(n_rings + 1):
phi = np.pi * ring / n_rings # 0 (top) to pi (bottom)
y = float(np.cos(phi))
r = float(np.sin(phi))
for seg in range(n_segments + 1):
theta = 2.0 * np.pi * seg / n_segments
x = float(r * np.cos(theta))
z = float(r * np.sin(theta))
verts.append([x, y, z])
norms.append([x, y, z]) # unit sphere: normal = position
# triangulate adjacent rings
for ring in range(n_rings):
for seg in range(n_segments):
r0 = ring * (n_segments + 1) + seg
r1 = r0 + n_segments + 1
idxs.extend([r0, r1, r0 + 1])
idxs.extend([r0 + 1, r1, r1 + 1])
self.vertices = np.array(verts, dtype=np.float32).flatten()
self.normals = np.array(norms, dtype=np.float32).flatten()
self.indices = np.array(idxs, dtype=np.uint16)
def getVerticeList(self) -> VAOMesh:
"""Create a VAOMesh for this sphere geometry."""
return VAOMesh(self.vertices, self.indices, self.normals)
def capsule_render_matrices(
p0_world: np.ndarray, p1_world: np.ndarray, radius: float
) -> tuple[np.ndarray | None, np.ndarray, np.ndarray]:
"""Compute model matrices for rendering a capsule as cylinder + two sphere caps.
Returns:
(cylinder_model, sphere0_model, sphere1_model) — three 4x4 matrices.
The cylinder is scaled by (radius, radius, length) along the capsule axis.
Each sphere is placed at an endpoint with uniform radius scaling.
"""
mid = 0.5 * (p0_world + p1_world)
axis = p1_world - p0_world
length = float(np.linalg.norm(axis))
# sphere matrices: uniform scale at each endpoint
S_sphere = np.eye(4, dtype=np.float32)
S_sphere[0, 0] = S_sphere[1, 1] = S_sphere[2, 2] = radius
T0 = np.eye(4, dtype=np.float32)
T0[:3, 3] = p0_world
T1 = np.eye(4, dtype=np.float32)
T1[:3, 3] = p1_world
sphere0 = (T0 @ S_sphere).astype(np.float32)
sphere1 = (T1 @ S_sphere).astype(np.float32)
if length < 1e-10:
# degenerate: both spheres at same point, no cylinder needed
return None, sphere0, sphere1
# rotation that maps Z-hat to capsule axis direction
z_hat = axis / length
if abs(z_hat[2]) < 0.9:
up = np.array([0.0, 0.0, 1.0])
else:
up = np.array([1.0, 0.0, 0.0])
x_hat = np.cross(up, z_hat)
x_hat /= np.linalg.norm(x_hat)
y_hat = np.cross(z_hat, x_hat)
R = np.eye(4, dtype=np.float32)
R[:3, 0] = x_hat
R[:3, 1] = y_hat
R[:3, 2] = z_hat
T = np.eye(4, dtype=np.float32)
T[:3, 3] = mid
S = np.eye(4, dtype=np.float32)
S[0, 0] = radius
S[1, 1] = radius
S[2, 2] = length
cylinder = (T @ R @ S).astype(np.float32)
return cylinder, sphere0, sphere1
class Coord:
"""vertices for 3-axis coordinate system arrows"""
def __init__(self):
l = 0.2
self.vertices = np.array([0.0, 0.0, 0.0, l, 0.0, 0.0, 0.0, l, 0.0, 0.0, 0.0, l], np.float32)
self.indices = np.array([0, 1, 0, 2, 0, 3], np.uint16)
def getVerticeList(self) -> VAOMesh:
return VAOMesh(self.vertices, self.indices)
class Grid:
"""vertices for the coordinate grid"""
def __init__(self):
# dx, dy are the width of grid
xmin = -50.0
xmax = 50.0
dx = 5.0
self.vertices: list[tuple[float, float, float]] = []
self.indices: list[tuple[int, int]] = []
idx = 0
for x in np.arange(xmin, xmax + dx, dx):
for y in np.arange(xmin, xmax + dx, dx):
self.vertices.append((x, xmin, 0.0))
self.vertices.append((x, xmax, 0.0))
self.indices.append((idx + 0, idx + 1))
idx += 2
self.vertices.append((xmin, y, 0.0))
self.vertices.append((xmax, y, 0.0))
self.indices.append((idx + 0, idx + 1))
idx += 2
self.vertices_flat = np.array(self.vertices, np.float32).flatten()
self.indices_flat = np.array(self.indices, np.uint16).flatten()
def getVerticeList(self) -> VAOMesh:
return VAOMesh(self.vertices_flat, self.indices_flat)
class TorqueArc:
"""A filled arc (annular sector) in the XY plane for visualizing joint torques.
The arc spans from angle 0 to `sweep` radians, with inner radius `r_inner`
and outer radius `r_outer`. The geometry is a triangle strip."""
def __init__(self, sweep: float, r_inner: float = 0.06, r_outer: float = 0.09, segments: int = 32) -> None:
if abs(sweep) < 1e-6:
# degenerate arc — create empty geometry
self.vertices = np.zeros(6, dtype=np.float32)
self.indices = np.array([0, 1, 0], dtype=np.uint16)
return
n = max(2, int(abs(sweep) / (2 * np.pi) * segments) + 1)
verts: list[float] = []
idxs: list[int] = []
for i in range(n + 1):
angle = sweep * i / n
c, s = float(np.cos(angle)), float(np.sin(angle))
# inner vertex
verts.extend([r_inner * c, r_inner * s, 0.0])
# outer vertex
verts.extend([r_outer * c, r_outer * s, 0.0])
if i < n:
base = i * 2
# two triangles forming a quad
idxs.extend([base, base + 1, base + 2])
idxs.extend([base + 1, base + 3, base + 2])
self.vertices = np.array(verts, dtype=np.float32)
self.indices = np.array(idxs, dtype=np.uint16)
def getVerticeList(self) -> VAOMesh:
"""Return a VAOMesh for this arc."""
return VAOMesh(self.vertices, self.indices)
class GroundQuad:
"""A large quad used as a stencil mask for planar shadows."""
def __init__(self, half_extent: float = 50.0, z: float = 0.0) -> None:
e = half_extent
self.vertices = np.array(
[-e, -e, z, e, -e, z, e, e, z, -e, e, z],
dtype=np.float32,
)
self.indices = np.array([0, 1, 2, 0, 2, 3], dtype=np.uint16)
def getVerticeList(self) -> VAOMesh:
return VAOMesh(self.vertices, self.indices)
class Mesh:
def __init__(self, mesh_file: str, scaling: np.ndarray) -> None:
import trimesh
self.mesh = trimesh.load_mesh(mesh_file)
self.num_vertices = np.size(self.mesh.vertices)
self.vertices: np.ndarray = self.mesh.vertices.copy()
self.vertices[:, 0] *= scaling[0]
self.vertices[:, 1] *= scaling[1]
self.vertices[:, 2] *= scaling[2]
normals = np.array(self.mesh.vertex_normals)
faces = np.array(self.mesh.faces)
# fix face winding and normals when scale has negative components (mirroring)
if np.prod(scaling) < 0:
faces = np.asarray(faces[:, ::-1])
# flip normals for mirrored axes
for ax in range(3):
if scaling[ax] < 0:
normals[:, ax] *= -1
self.normals = np.asarray(normals.reshape(-1), dtype=np.float32)
self.faces = np.asarray(faces.reshape(-1), dtype=np.uint16)
self.vertices = np.asarray(self.vertices.reshape(-1), dtype=np.float32)
def getVerticeList(self) -> VAOMesh:
return VAOMesh(self.vertices, self.faces, self.normals)
# ── Camera ────────────────────────────────────────────────────────────────────
class FirstPersonCamera:
DEFAULT_MOVEMENT_SPEED = 2.0
DEFAULT_MOUSE_SENSITIVITY = 0.4
DEFAULT_KEY_MAP = {
"forward": key.W,
"backward": key.S,
"left": key.A,
"right": key.D,
"up": key.SPACE,
"down": key.LCTRL,
}
class InputHandler:
def __init__(self, window):
self.pressed = collections.defaultdict(bool)
self.dx = 0
self.dy = 0
self._window = window
# skip drag events after a press: pyglet may fire spurious drags
# with large deltas from the cursor warp on exclusive mouse lock
self._skip_drag_count = 0
def on_key_press(self, symbol, modifiers):
self.pressed[symbol] = True
def on_key_release(self, symbol, modifiers):
self.pressed[symbol] = False
def on_mouse_press(self, x, y, button, modifiers):
if button == pyglet.window.mouse.LEFT:
self._skip_drag_count = 2
self._window.set_exclusive_mouse(True)
def on_mouse_release(self, x, y, button, modifiers):
if button == pyglet.window.mouse.LEFT:
self._window.set_exclusive_mouse(False)
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if buttons & pyglet.window.mouse.LEFT:
if self._skip_drag_count > 0:
self._skip_drag_count -= 1
return
# clamp to reject spurious large deltas from cursor warps
max_delta = 40
if abs(dx) > max_delta or abs(dy) > max_delta:
return
self.dx = dx
self.dy = dy
def __init__(
self,
window,
position=(0, 0, 0),
pitch=-90.0,
yaw=0.0,
key_map=DEFAULT_KEY_MAP,
movement_speed=DEFAULT_MOVEMENT_SPEED,
mouse_sensitivity=DEFAULT_MOUSE_SENSITIVITY,
y_inv=True,
):
"""Create camera object
Arguments:
window -- pyglet window with camera attached
position -- position of camera
key_map -- dict like FirstPersonCamera.DEFAULT_KEY_MAP
movement_speed -- speed of camera move (scalar)
mouse_sensitivity -- sensitivity of mouse (scalar)
y_inv -- inversion turn above y-axis
"""
self.__position = list(position)
self.__yaw = yaw
self.__pitch = pitch
self.__input_handler = FirstPersonCamera.InputHandler(window)
window.push_handlers(self.__input_handler)
self.y_inv = y_inv
self.key_map = key_map
self.movement_speed = movement_speed
self.mouse_sensitivity = mouse_sensitivity
# orbit mode state (activated while shift is held)
self._orbit_mode = False
self._orbit_az = 0.0 # azimuth around Z in degrees
self._orbit_el = 30.0 # elevation above XY plane in degrees
self._orbit_r = 3.0 # distance from origin
self._shift_prev = False
@property
def position(self):
return self.__position
@position.setter
def position(self, value: list[float]) -> None:
self.__position = value
@property
def yaw(self) -> float:
return self.__yaw
@yaw.setter
def yaw(self, value: float) -> None:
"""Turn above x-axis"""
self.__yaw += value * self.mouse_sensitivity
@property
def pitch(self) -> float:
return self.__pitch
@pitch.setter
def pitch(self, value: float) -> None:
"""Turn above y-axis"""
self.__pitch += value * self.mouse_sensitivity * ((-1) if self.y_inv else 1)
@property
def keys_pressed(self) -> collections.defaultdict:
"""Expose held-key state for use outside the camera (e.g. frame stepping)."""
return self.__input_handler.pressed
def move_forward(self, distance):
"""Fly forward along the full 3D look direction (includes pitch)."""
p_rad = math.radians(self.__pitch)
y_rad = math.radians(self.__yaw)
# forward_world = (-sin(y)*sin(p), -cos(y)*sin(p), -cos(p))
# stored position = -world_eye, so position -= forward * distance
self.__position[0] += math.sin(y_rad) * math.sin(p_rad) * distance
self.__position[1] += math.cos(y_rad) * math.sin(p_rad) * distance
self.__position[2] += math.cos(p_rad) * distance
def move_backward(self, distance):
"""Fly backward along the full 3D look direction (includes pitch)."""
self.move_forward(-distance)
def move_left(self, distance):
"""Move left on distance"""
self.__position[0] -= distance * math.sin(math.radians(-self.__yaw - 90))
self.__position[1] += distance * math.cos(math.radians(-self.__yaw - 90))
def move_right(self, distance):
"""Move right on distance"""
self.__position[0] -= distance * math.sin(math.radians(-self.__yaw + 90))
self.__position[1] += distance * math.cos(math.radians(-self.__yaw + 90))
def move_up(self, distance):
"""Move up on distance"""
self.__position[2] -= distance
def move_down(self, distance):
"""Move down on distance"""
self.__position[2] += distance
def update(self, delta_time):
"""Update camera state"""
dx = self.__input_handler.dx
dy = self.__input_handler.dy
self.__input_handler.dx = 0
self.__input_handler.dy = 0
shift_held = self.__input_handler.pressed[key.LSHIFT]
# on shift press: initialise orbit parameters from the current camera position
if shift_held and not self._shift_prev:
# __position stores the negative of the world-space eye position
wx, wy, wz = -self.__position[0], -self.__position[1], -self.__position[2]
self._orbit_r = math.sqrt(wx * wx + wy * wy + wz * wz) or 3.0
self._orbit_el = math.degrees(math.asin(max(-1.0, min(1.0, wz / self._orbit_r))))
horiz = math.cos(math.radians(self._orbit_el))
self._orbit_az = math.degrees(math.atan2(wy, wx)) if abs(horiz) > 1e-6 else 0.0
# on shift release: sync yaw/pitch to the current look direction so the
# free-cam view is continuous with the orbit view (no visual jump)
if not shift_held and self._shift_prev:
r = math.sqrt(sum(p * p for p in self.__position))
if r > 1e-10:
lx, ly, lz = self.__position[0] / r, self.__position[1] / r, self.__position[2] / r
self.__yaw = math.degrees(math.atan2(lx, ly))
self.__pitch = -math.degrees(math.acos(max(-1.0, min(1.0, -lz))))
self._shift_prev = shift_held
self._orbit_mode = shift_held
if shift_held:
# orbit mode: drag rotates the camera around the world origin
if dx != 0 or dy != 0:
self._orbit_az -= dx * self.mouse_sensitivity
self._orbit_el += dy * self.mouse_sensitivity * ((-1) if self.y_inv else 1)
self._orbit_el = max(-89.0, min(89.0, self._orbit_el))
# w/s adjust the orbit radius (zoom in/out)
if self.__input_handler.pressed[self.key_map["forward"]]:
self._orbit_r = max(0.1, self._orbit_r - delta_time * self.movement_speed)
if self.__input_handler.pressed[self.key_map["backward"]]:
self._orbit_r += delta_time * self.movement_speed
el_r = math.radians(self._orbit_el)
az_r = math.radians(self._orbit_az)
r = self._orbit_r
# store negated world position (convention used by the free-cam view matrix)
self.__position = [
-(r * math.cos(el_r) * math.cos(az_r)),
-(r * math.cos(el_r) * math.sin(az_r)),
-(r * math.sin(el_r)),
]
else:
# normal first-person mode
self.__yaw += dx * self.mouse_sensitivity
self.__pitch += dy * self.mouse_sensitivity * ((-1) if self.y_inv else 1)
if self.__input_handler.pressed[self.key_map["forward"]]:
self.move_forward(delta_time * self.movement_speed)
if self.__input_handler.pressed[self.key_map["backward"]]:
self.move_backward(delta_time * self.movement_speed)
if self.__input_handler.pressed[self.key_map["left"]]:
self.move_left(delta_time * self.movement_speed)
if self.__input_handler.pressed[self.key_map["right"]]:
self.move_right(delta_time * self.movement_speed)
if self.__input_handler.pressed[self.key_map["up"]]:
self.move_up(delta_time * self.movement_speed)
if self.__input_handler.pressed[self.key_map["down"]]:
self.move_down(delta_time * self.movement_speed)
def _look_at_origin(self) -> np.ndarray:
"""Build a view matrix looking from the current position toward the world origin."""
# __position stores the negative of the world eye, so negate to get world eye
eye = np.array([-self.__position[0], -self.__position[1], -self.__position[2]], dtype=np.float32)
up = np.array([0.0, 0.0, 1.0], dtype=np.float32)
f = -eye # look toward origin
norm_f = float(np.linalg.norm(f))
if norm_f < 1e-10:
return np.eye(4, dtype=np.float32)
f = f / norm_f
r = np.cross(f, up)
if float(np.linalg.norm(r)) < 1e-6:
# camera pointing straight up/down, fall back to Y-up
up = np.array([0.0, 1.0, 0.0], dtype=np.float32)
r = np.cross(f, up)
r = r / float(np.linalg.norm(r))
u = np.cross(r, f)
m = np.eye(4, dtype=np.float32)
m[0, :3] = r
m[1, :3] = u
m[2, :3] = -f
m[0, 3] = -float(np.dot(r, eye))
m[1, 3] = -float(np.dot(u, eye))
m[2, 3] = float(np.dot(f, eye))
return m
def get_view_matrix(self) -> np.ndarray:
"""Compute and return the 4x4 view matrix (replaces legacy draw())."""
if self._orbit_mode:
return self._look_at_origin()
return (
rotation_matrix(self.__pitch, 1.0, 0.0, 0.0)
@ rotation_matrix(self.__yaw, 0.0, 0.0, 1.0)
@ translation_matrix(*self.__position)
)
# ── GLSL 410 core shaders ────────────────────────────────────────────────────
LIT_VERTEX_SHADER = """
#version 410 core
layout(location=0) in vec3 aPos;
layout(location=1) in vec3 aNormal;
uniform mat4 uMVP;
uniform mat4 uMV;
uniform mat3 uNormalMat;
out vec3 vN;
out vec3 vPos;
void main() {
vPos = vec3(uMV * vec4(aPos, 1.0));
vN = normalize(uNormalMat * aNormal);
gl_Position = uMVP * vec4(aPos, 1.0);
}
"""
LIT_FRAGMENT_SHADER = """
#version 410 core
in vec3 vN;
in vec3 vPos;
uniform vec4 uLightPos;
uniform vec4 uMatAmbient;
uniform vec4 uMatDiffuse;
uniform vec4 uMatSpecular;
uniform vec4 uMatEmission;
uniform float uMatShininess;
out vec4 fragColor;
void main() {
vec3 N = normalize(vN);
vec3 L = normalize(uLightPos.xyz - vPos);
vec3 E = normalize(-vPos);
vec3 R = normalize(-reflect(L, N));
vec4 Iamb = uMatAmbient * 0.3;
vec4 Idiff = uMatDiffuse * max(dot(N, L), 0.0);
Idiff = clamp(Idiff, 0.0, 1.0);
vec4 Ispec = uMatSpecular * pow(max(dot(R, E), 0.0), max(uMatShininess, 1.0));
Ispec = clamp(Ispec, 0.0, 1.0);
fragColor = uMatEmission + Iamb + Idiff + Ispec;
}
"""
UNLIT_VERTEX_SHADER = """
#version 410 core
layout(location=0) in vec3 aPos;
uniform mat4 uMVP;
void main() {
gl_Position = uMVP * vec4(aPos, 1.0);
}
"""
UNLIT_FRAGMENT_SHADER = """
#version 410 core
uniform vec4 uColor;
out vec4 fragColor;
void main() {
fragColor = uColor;
}
"""
# ── Material definitions ─────────────────────────────────────────────────────
def _f32(v: list[float]) -> np.ndarray:
return np.array(v, dtype=np.float32)
# Numpy arrays are pre-built so _upload_material makes zero allocations per frame.
MATERIALS: dict[str, dict[str, Any]] = {
"neutral": {
"ambient": _f32([0.6, 0.6, 0.6, 1.0]),
"diffuse": _f32([0.1, 0.1, 0.1, 1.0]),
"specular": _f32([0.2, 0.2, 0.2, 1.0]),
"shininess": 0.0,
"emission": _f32([0.0, 0.0, 0.0, 1.0]),
},
"metal": {
"ambient": _f32([0.25, 0.25, 0.25, 1.0]),
"diffuse": _f32([0.4, 0.4, 0.4, 1.0]),
"specular": _f32([0.774597, 0.774597, 0.774597, 1.0]),
"shininess": 0.6 * 128.0,
"emission": _f32([0.1, 0.1, 0.1, 1.0]),
},
"green rubber": {
"ambient": _f32([0.01, 0.1, 0.01, 1.0]),
"diffuse": _f32([0.5, 0.6, 0.5, 1.0]),
"specular": _f32([0.05, 0.1, 0.05, 1.0]),
"shininess": 0.03 * 128.0,
"emission": _f32([0.0, 0.0, 0.0, 1.0]),
},
"white rubber": {
"ambient": _f32([0.7, 0.7, 0.7, 1.0]),
"diffuse": _f32([0.5, 0.5, 0.5, 1.0]),
"specular": _f32([0.01, 0.01, 0.01, 1.0]),
"shininess": 0.03 * 128.0,
"emission": _f32([0.2, 0.2, 0.2, 1.0]),
},
"dark world": {
"ambient": _f32([0.12, 0.12, 0.12, 1.0]),
"diffuse": _f32([0.15, 0.15, 0.15, 1.0]),
"specular": _f32([0.02, 0.02, 0.02, 1.0]),
"shininess": 0.03 * 128.0,
"emission": _f32([0.02, 0.02, 0.02, 1.0]),
},
"collision red": {
"ambient": _f32([0.3, 0.02, 0.02, 1.0]),
"diffuse": _f32([0.8, 0.1, 0.1, 1.0]),
"specular": _f32([0.3, 0.1, 0.1, 1.0]),
"shininess": 0.1 * 128.0,
"emission": _f32([0.3, 0.0, 0.0, 1.0]),
},
}
# ── Visualizer ────────────────────────────────────────────────────────────────
class Visualizer:
def __init__(self, config: dict[str, Any]) -> None:
self.dark_mode = _is_dark_mode()
# theme colors
if self.dark_mode:
self.grid_color = (0.25, 0.25, 0.25, 1.0)
self.coord_color = (0.4, 0.4, 0.4, 1.0)
self.label_color = (200, 200, 200, 220)
else:
self.grid_color = (0.6, 0.6, 0.6, 1.0)
self.coord_color = (0.6, 0.6, 0.6, 1.0)
self.label_color = (0, 0, 0, 220)
# some vars
self.window_closed = False
self.mode = "b" # 'b' - blocking or 'c' - continous
self.display_index = 0 # current index for displaying e.g. postures from file
self.display_max = 1
self.config = config
# keep a list of bodies
self.bodies: list[dict[str, Any]] = []
# mesh display mode: "visual", "collision", or "boxes"
self.mesh_mode = "boxes"
self.show_meshes = False # legacy compat, updated by mesh_mode
self.angles: list[float] | None = None
self.trajectory: Trajectory | None = None
self.playing_traj = False # currently playing or not
self.playable = False # can the trajectory be "played"
self.freq = 1 # frequency in Hz of position / angle data
# torque visualization
self.torque_rings: list[dict[str, Any]] = [] # per-frame torque ring data
self.show_torque_rings = False
self.has_torque_data = False # set to True when torque data is available
# collision highlighting
self.colliding_links: set[str] = set()
self.check_collisions = True # toggled with C key
# additional callbacks to be used with key handling
self.event_callback: Callable | None = None
self.timer_callback = self.next_frame
self._playback_start_time: float = 0.0
self._playback_start_index: int = 0
self.info_label = None
# shader programs and uniform caches
self.lit_shader: int = 0
self.unlit_shader: int = 0
self.lit_uniforms: dict[str, int] = {}
self.unlit_uniforms: dict[str, int] = {}
# projection matrix (updated on resize)
self.proj_matrix: np.ndarray = np.eye(4, dtype=np.float32)
# light position and ground plane for shadow projection
self.light_pos = np.array([1.0, 0.0, 2.0, 1.0], dtype=np.float32)