-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
919 lines (777 loc) · 40.5 KB
/
main.py
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
"""
Run this script to start the GUI.
"""
import os
import sys
import numpy as np
from PyQt5.QtCore import Qt, QStringListModel, QItemSelectionModel
from PyQt5.QtGui import QIcon, QPixmap, QKeyEvent, QKeySequence
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QFileDialog, QMenu, QWidget, QFrame, QPushButton, QCheckBox, QLabel, QSpinBox, QDoubleSpinBox, QGroupBox, QTabWidget, QListView, QAbstractItemView
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QFormLayout, QGridLayout
import vtk
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor # type: ignore (this comment hides the warning shown by PyLance in VS Code)
from continuity import Continuity
from geometry import *
from interaction import InteractorStyle
PROGRAM_NAME = "Curve and Surface Visualizer"
PROGRAM_VERSION = (1, 0, 0)
AUTHORS = ["Sujay Kestur", "Marshall Lee"]
# The temporary folder created when running an executable created by PyInstaller, or the current folder when running this script directly.
FOLDER_ROOT = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
class MainWindow(QMainWindow):
"""
The main window of the program, which defines the layout and contents of the window and what occurs in response to user input.
Methods prefixed with a single underscore are intended to be run only one time, during startup.
"""
def __init__(self):
super().__init__()
# All existing Geometry objects.
self.geometries = []
# The currently selected Geometry objects.
self.selected_geometry = []
# The currently selected point ID.
self.selected_point = None
# Create the menu bar and its menus.
menu_bar = self.menuBar()
menu_file = menu_bar.addMenu("File")
menu_file.addAction("Save As Image...", self.save_image, QKeySequence(Qt.CTRL + Qt.Key_S))
menu_file.addSeparator()
menu_file.addAction("Settings...", self.show_settings)
menu_presets = menu_bar.addMenu("Presets")
menu_presets.addAction(f"3 {Geometry.BEZIER} Curves", self.preset_1)
menu_presets.addAction(f"2 {Geometry.BEZIER} Surfaces", self.preset_2)
menu_presets.addAction(f"2 {Geometry.HERMITE} Curves", self.preset_3)
menu_presets.addAction(f"2 {Geometry.HERMITE} Surfaces", self.preset_4)
menu_help = menu_bar.addMenu("Help")
menu_help.addAction("About...", self.show_about)
# Create the overall layout and main widgets of the window.
layout = QGridLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.setColumnStretch(0, 0)
layout.setColumnStretch(1, 1)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
layout.addWidget(self._make_sidebar(), 0, 0, 2, 1)
layout.addWidget(self._make_visualizer(), 0, 1)
layout.addWidget(self._make_buttons_camera(), 1, 1)
# Create dialog windows that can be hidden and shown.
self.window_settings = self._make_window_settings()
self.window_about = self._make_window_about()
# Disable fields initially.
self.load_fields()
# Start the interactor after the layout is created.
self.iren.Initialize()
self.iren.Start()
def _make_sidebar(self) -> QWidget:
"""Return a sidebar widget."""
widget = QWidget()
main_layout = QVBoxLayout(widget)
main_layout.setAlignment(Qt.AlignTop)
# Buttons for adding curves and surfaces.
button_curve = QPushButton("Add Curve...")
menu = QMenu()
menu.addAction(Geometry.BEZIER, self.make_bezier_curve)
menu.addAction(Geometry.HERMITE, self.make_hermite_curve)
menu.addAction(Geometry.BSPLINE, self.make_bspline_curve)
button_curve.setMenu(menu)
button_surface = QPushButton("Add Surface...")
menu = QMenu()
menu.addAction(Geometry.BEZIER, self.make_bezier_surface)
menu.addAction(Geometry.HERMITE, self.make_hermite_surface)
menu.addAction(Geometry.BSPLINE, self.make_bspline_surface)
button_surface.setMenu(menu)
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(button_curve)
layout.addWidget(button_surface)
main_layout.addLayout(layout)
# Fields for modifying the currently selected geometries.
self.fields_cp = self._make_fields_cp()
main_layout.addWidget(self.fields_cp)
self.fields_number_cp = self._make_fields_number_cp()
self.fields_number_nodes = self._make_fields_number_nodes()
self.fields_order = self._make_fields_order()
main_layout.addWidget(self.fields_number_cp)
main_layout.addWidget(self.fields_number_nodes)
main_layout.addWidget(self.fields_order)
main_layout.addStretch(1)
# Label for displaying the continuity of the currently selected geometries.
self.label_continuity = QLabel()
self.label_continuity.setAlignment(Qt.AlignCenter)
main_layout.addWidget(self.label_continuity)
# List view showing all existing geometries.
self.listview_model = QStringListModel()
self.listview = QListView()
self.listview.setModel(self.listview_model)
self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.listview.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.listview.selectionModel().selectionChanged.connect(self.listview_changed)
main_layout.addWidget(self.listview)
# Button for deleting currently selected geometries.
self.button_delete = QPushButton("Delete")
self.button_delete.clicked.connect(self.remove_selected_geometries)
main_layout.addWidget(self.button_delete)
return widget
def _make_fields_cp(self) -> QWidget:
"""Return a widget containing fields for modifying the current control point."""
widget = QWidget()
main_layout = QVBoxLayout(widget)
main_layout.setContentsMargins(0, 0, 0, 0)
self.field_x = QDoubleSpinBox()
self.field_x.setRange(-1000, 1000)
self.field_x.setSingleStep(1)
self.field_x.setDecimals(1)
self.field_x.setAlignment(Qt.AlignRight)
self.field_x.setToolTip("X coordinate of the currently selected control point.")
self.field_x.valueChanged.connect(self.update_cp)
layout = QHBoxLayout()
layout.addWidget(QLabel("X"))
layout.addWidget(self.field_x)
main_layout.addLayout(layout)
self.field_y = QDoubleSpinBox()
self.field_y.setRange(-1000, 1000)
self.field_y.setSingleStep(1)
self.field_y.setDecimals(1)
self.field_y.setAlignment(Qt.AlignRight)
self.field_y.setToolTip("Y coordinate of the currently selected control point.")
self.field_y.valueChanged.connect(self.update_cp)
layout = QHBoxLayout()
layout.addWidget(QLabel("Y"))
layout.addWidget(self.field_y)
main_layout.addLayout(layout)
self.field_z = QDoubleSpinBox()
self.field_z.setRange(-1000, 1000)
self.field_z.setSingleStep(1)
self.field_z.setDecimals(1)
self.field_z.setAlignment(Qt.AlignRight)
self.field_z.setToolTip("Z coordinate of the currently selected control point.")
self.field_z.valueChanged.connect(self.update_cp)
layout = QHBoxLayout()
layout.addWidget(QLabel("Z"))
layout.addWidget(self.field_z)
main_layout.addLayout(layout)
return widget
def _make_fields_number_cp(self) -> QWidget:
"""Return a widget containing fields for modifying the number of control points."""
widget = QWidget()
widget.setToolTip("Number of control points in the currently selected geometry. Adjust this while multiple geometries are selected to modify all selected geometries simultaneously.")
main_layout = QVBoxLayout(widget)
main_layout.setContentsMargins(0, 0, 0, 0)
layout = QHBoxLayout()
self.field_cp_u = QSpinBox()
self.field_cp_u.setRange(2, 100)
self.field_cp_u.setAlignment(Qt.AlignRight)
self.field_cp_u.valueChanged.connect(self.update_number_cp)
self.field_cp_v = QSpinBox()
self.field_cp_v.setRange(2, 100)
self.field_cp_v.setAlignment(Qt.AlignRight)
self.field_cp_v.valueChanged.connect(self.update_number_cp)
layout.addWidget(QLabel("Control Points:"))
layout.addStretch(1)
layout.addWidget(QLabel("u"))
layout.addWidget(self.field_cp_u)
layout.addWidget(QLabel("v"))
layout.addWidget(self.field_cp_v)
main_layout.addLayout(layout)
return widget
def _make_fields_number_nodes(self) -> QWidget:
"""Return a widget containing fields for modifying the number of nodes."""
widget = QWidget()
widget.setToolTip("Number of nodes in the currently selected geometry. Adjust this while multiple geometries are selected to modify all selected geometries simultaneously.")
main_layout = QVBoxLayout(widget)
main_layout.setContentsMargins(0, 0, 0, 0)
layout = QHBoxLayout()
self.field_nodes_u = QSpinBox()
self.field_nodes_u.setRange(2, 100)
self.field_nodes_u.setAlignment(Qt.AlignRight)
self.field_nodes_u.valueChanged.connect(self.update_number_nodes)
self.field_nodes_v = QSpinBox()
self.field_nodes_v.setRange(2, 100)
self.field_nodes_v.setAlignment(Qt.AlignRight)
self.field_nodes_v.valueChanged.connect(self.update_number_nodes)
layout.addWidget(QLabel("Nodes:"))
layout.addStretch(1)
layout.addWidget(QLabel("u"))
layout.addWidget(self.field_nodes_u)
layout.addWidget(QLabel("v"))
layout.addWidget(self.field_nodes_v)
main_layout.addLayout(layout)
return widget
def _make_fields_order(self) -> QWidget:
"""Return a widget containing fields for modifying the order."""
widget = QWidget()
main_layout = QVBoxLayout(widget)
main_layout.setContentsMargins(0, 0, 0, 0)
layout = QHBoxLayout()
self.field_order = QSpinBox()
self.field_order.setRange(1, 10)
self.field_order.setAlignment(Qt.AlignRight)
self.field_order.setToolTip("Order of the currently selected geometry. Adjust this while multiple geometries are selected to modify all selected geometries simultaneously.")
self.field_order.valueChanged.connect(self.update_order)
self.field_order.setVisible(False)
self.label_order = QLabel()
layout.addWidget(QLabel("Order:"))
layout.addStretch(1)
layout.addWidget(self.label_order)
layout.addWidget(self.field_order)
main_layout.addLayout(layout)
return widget
def _make_visualizer(self) -> QWidget:
"""Return a VTK widget for visualizing and interacting with geometries."""
self.ren = vtk.vtkRenderer()
widget = QVTKRenderWindowInteractor(self)
self.renwin = widget.GetRenderWindow()
self.renwin.AddRenderer(self.ren)
self.iren = self.renwin.GetInteractor()
style = InteractorStyle(self)
style.SetDefaultRenderer(self.ren)
self.iren.SetInteractorStyle(style)
return widget
def _make_buttons_camera(self) -> QWidget:
"""Return a widget containing controls for the camera."""
widget = QWidget()
layout = QHBoxLayout(widget)
layout.addWidget(QLabel("Camera:"))
button = QPushButton("Top")
button.clicked.connect(self.set_camera_top)
layout.addWidget(button)
button = QPushButton("Front")
button.clicked.connect(self.set_camera_front)
layout.addWidget(button)
button = QPushButton("Fit")
button.setToolTip("Make all geometries visible, or only the currently selected geometries.")
button.clicked.connect(self.set_camera_fit)
layout.addWidget(button)
layout.addStretch(1)
return widget
def _make_window_settings(self) -> QDialog:
"""Return the Settings window."""
window = QDialog(self)
window.setModal(True)
window.setWindowTitle("Settings")
window.setWindowFlag(Qt.WindowMinimizeButtonHint, False)
window.setWindowFlag(Qt.WindowMaximizeButtonHint, False)
window.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
main_layout = QVBoxLayout(window)
main_layout.setAlignment(Qt.AlignTop)
# Settings related to geometries.
box = QGroupBox("Geometry")
layout = QFormLayout(box)
main_layout.addWidget(box)
self.settings_field_cp = QSpinBox()
self.settings_field_cp.setRange(2, 100)
self.settings_field_cp.setValue(3)
self.settings_field_cp.setToolTip("Default number of control points used when adding a new geometry.")
layout.addRow("Default Control Points:", self.settings_field_cp)
self.settings_field_nodes = QSpinBox()
self.settings_field_nodes.setRange(2, 100)
self.settings_field_nodes.setValue(10)
self.settings_field_nodes.setToolTip("Default number of nodes used when adding a new geometry.")
layout.addRow("Default Nodes:", self.settings_field_nodes)
self.settings_field_hermite_tangent_scaling = QDoubleSpinBox()
self.settings_field_hermite_tangent_scaling.setRange(1.0, 100.0)
self.settings_field_hermite_tangent_scaling.setValue(1.0)
self.settings_field_hermite_tangent_scaling.setToolTip(f"Increase this value to increase the effect that modifying {Geometry.HERMITE} tangent vectors has on the shape.")
self.settings_field_hermite_tangent_scaling.valueChanged.connect(self.update_hermite_tangent_scaling)
layout.addRow(f"{Geometry.HERMITE} Tangent Scaling:", self.settings_field_hermite_tangent_scaling)
# Settings related to the visualizer.
box = QGroupBox("Visualizer")
layout = QFormLayout(box)
main_layout.addWidget(box)
self.settings_field_mouse_modifier = QDoubleSpinBox()
self.settings_field_mouse_modifier.setMinimum(0.01)
self.settings_field_mouse_modifier.setValue(1.00)
self.settings_field_mouse_modifier.setSingleStep(0.5)
self.settings_field_mouse_modifier.setToolTip("Multiply mouse positions, in pixels, by this value to fix incorrect mouse positions on some devices.")
layout.addRow("Mouse Position Modifier:", self.settings_field_mouse_modifier)
self.settings_field_mouse_z_depth = QDoubleSpinBox()
self.settings_field_mouse_z_depth.setRange(0.0, 10.0)
self.settings_field_mouse_z_depth.setValue(0.5)
self.settings_field_mouse_z_depth.setSingleStep(0.1)
self.settings_field_mouse_z_depth.setToolTip("Increase this value to make mouse positions, in pixels, correspond to coordinates farther from the camera.")
layout.addRow("Mouse Z Depth:", self.settings_field_mouse_z_depth)
# Settings related to saving images.
box = QGroupBox("Export")
layout = QFormLayout(box)
main_layout.addWidget(box)
self.settings_field_save_scale = QSpinBox()
self.settings_field_save_scale.setRange(1, 5)
self.settings_field_save_scale.setToolTip("Increase this value to increase the resolution of the saved image.")
layout.addRow("Image Scale:", self.settings_field_save_scale)
self.settings_checkbox_save_transparency = QCheckBox("Include Transparency")
self.settings_checkbox_save_transparency.setChecked(True)
layout.addRow("", self.settings_checkbox_save_transparency)
return window
def _make_window_about(self) -> QDialog:
"""Return the About window."""
window = QDialog(self)
window.setModal(True)
window.setWindowTitle("About")
window.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
main_layout = QVBoxLayout()
main_layout.setAlignment(Qt.AlignCenter)
window.setLayout(main_layout)
logo = QLabel()
logo.setPixmap(QPixmap(os.path.join(FOLDER_ROOT, "Images/logo.png")).scaledToHeight(100))
main_layout.addWidget(logo, alignment=Qt.AlignCenter)
main_layout.addWidget(QLabel(PROGRAM_NAME), alignment=Qt.AlignCenter)
main_layout.addWidget(QLabel(f"Version: {'.'.join([str(_) for _ in PROGRAM_VERSION])}"), alignment=Qt.AlignCenter)
main_layout.addWidget(QLabel(f"Authors: {', '.join(AUTHORS)}"), alignment=Qt.AlignCenter)
label_url = QLabel(f"<a href='https://github.com/mlee-0/ME-6104-Project/'>Show on GitHub...</a>")
label_url.setOpenExternalLinks(True)
main_layout.addWidget(label_url, alignment=Qt.AlignCenter)
return window
def save_image(self) -> None:
"""Show a file dialog and save the visualizer as an image."""
dialog = QFileDialog(
self,
caption="",
directory=os.path.join(os.path.curdir, "screenshot.png"),
filter="Image files (*.png)",
)
# Set the suffix added to the file name, if the user does not specify one.
dialog.setDefaultSuffix("png")
# Set the dialog to save mode.
dialog.setAcceptMode(QFileDialog.AcceptSave)
# The user specified a file name.
if dialog.exec():
filename = dialog.selectedFiles()[0]
filter = vtk.vtkWindowToImageFilter()
filter.SetInput(self.renwin)
filter.SetScale(self.settings_field_save_scale.value())
if self.settings_checkbox_save_transparency.isChecked():
filter.SetInputBufferTypeToRGBA()
else:
filter.SetInputBufferTypeToRGB()
filter.Update()
writer = vtk.vtkPNGWriter()
writer.SetFileName(filename)
writer.SetInputConnection(filter.GetOutputPort())
writer.Write()
def show_settings(self) -> None:
"""Show the Settings window."""
self.window_settings.show()
self.window_settings.setFixedSize(self.window_settings.size())
def show_about(self) -> None:
"""Show the About window."""
self.window_about.show()
def add_geometry(self, geometry: Geometry) -> None:
"""Add a new geometry."""
self.geometries.append(geometry)
# Add the geometry's name to the list view.
row_index = self.listview_model.rowCount()
self.listview_model.insertRow(row_index)
self.listview_model.setData(self.listview_model.index(row_index, 0), str(geometry))
# Add the geometry's actors to the visualizer.
for actor in geometry.get_actors():
self.ren.AddActor(actor)
self.iren.GetInteractorStyle().add_to_pick_list(geometry)
self.reset_camera()
def remove_selected_geometries(self) -> None:
"""Remove all currently selected geometries."""
if self.selected_geometry:
for geometry in self.selected_geometry:
# Remove the geometry's name from the list view.
row_index = self.listview_model.stringList().index(str(geometry))
self.listview_model.removeRow(row_index)
# Remove the geometry's actors from the visualizer.
self.iren.GetInteractorStyle().remove_from_pick_list(geometry)
for actor in geometry.get_actors():
self.ren.RemoveActor(actor)
del self.geometries[self.geometries.index(geometry)]
self.selected_geometry.clear()
self.selected_point = None
self.load_fields()
self.update_label_order()
self.ren.Render()
self.iren.Render()
def make_bezier_curve(self) -> None:
"""Add a preset Bezier curve to the visualizer."""
number_cp_u = self.settings_field_cp.value()
number_u = self.settings_field_nodes.value()
cp = np.vstack((
np.linspace(0, 10, number_cp_u), # x-coordinates
np.linspace(0, 10, number_cp_u), # y-coordinates
np.zeros(number_cp_u), # z-coordinates
)).reshape((3, number_cp_u, 1))
self.add_geometry(BezierCurve(cp, number_u))
def make_hermite_curve(self) -> None:
"""Add a preset Hermite curve to the visualizer."""
number_u = self.settings_field_nodes.value()
cp = np.array([
[[0, 0, 0], [10, 10, 0], [5, 0, 0], [15, 10, 0]]
]).transpose()
self.add_geometry(HermiteCurve(cp, number_u))
def make_bspline_curve(self) -> None:
"""Add a preset B-spline curve to the visualizer."""
order = 2
number_cp_u = self.settings_field_cp.value()
number_u = self.settings_field_nodes.value()
cp = np.vstack((
np.linspace(0, 10, number_cp_u), # x-coordinates
np.linspace(0, 10, number_cp_u), # y-coordinates
np.zeros(number_cp_u), # z-coordinates
)).reshape((3, number_cp_u, 1))
self.add_geometry(BSplineCurve(cp, number_u, order=order))
def make_bezier_surface(self) -> None:
"""Add a preset Bezier surface to the visualizer."""
number_cp_u = self.settings_field_cp.value()
number_u = number_v = self.settings_field_nodes.value()
cp = np.dstack(
np.meshgrid(np.linspace(0, 10, number_cp_u), np.linspace(0, 10, number_cp_u)) + [np.zeros((number_cp_u,)*2)]
).transpose((2, 0, 1))
self.add_geometry(BezierSurface(cp, number_u, number_v))
def make_hermite_surface(self) -> None:
"""Add a preset Hermite surface to the visualizer."""
number_u = number_v = self.settings_field_nodes.value()
cp = np.array([
[[0,0,0], [0,10,0], [0,1,0], [0,11,0]],
[[10,0,0], [10,10,0], [10,1,0], [10,11,0]],
[[1,0,0], [1,10,0], [0,0,1], [0,10,-1]],
[[11,0,0], [11,10,0], [10,0,-1], [10,10,1]],
]).transpose((2, 0, 1))
self.add_geometry(HermiteSurface(cp, number_u, number_v))
def make_bspline_surface(self) -> None:
"""Add a preset B-spline surface to the visualizer."""
order = 2
number_cp_u = number_cp_v = self.settings_field_cp.value()
number_u = number_v = self.settings_field_nodes.value()
cp = np.dstack(
np.meshgrid(np.linspace(0, 10, number_cp_u), np.linspace(0, 10, number_cp_v)) + [np.zeros((number_cp_u, number_cp_v))]
).transpose((2, 0, 1))
self.add_geometry(BSplineSurface(cp, number_u, number_v, order))
def update_cp(self) -> None:
"""Update the coordinates of the currently selected control point. Called automatically when the fields are edited."""
# Get the values in the fields.
point = np.array([
self.field_x.value(),
self.field_y.value(),
self.field_z.value(),
])
if len(self.selected_geometry) == 1:
geometry = self.selected_geometry[0]
geometry.update_single_cp(point, self.selected_point)
self.ren.Render()
self.iren.Render()
def set_cp(self, point: np.ndarray, point_id: int) -> None:
"""Set the coordinates of the given control point."""
if len(self.selected_geometry) == 1:
geometry = self.selected_geometry[0]
geometry.update_single_cp(point, point_id)
self.ren.Render()
self.iren.Render()
def translate_geometries(self, translation: tuple) -> None:
"""Translate the currently selected geometries."""
for geometry in self.selected_geometry:
geometry.translate(translation)
self.ren.Render()
self.iren.Render()
def update_number_cp(self, value) -> None:
"""Update the number of control points in the currently selected geometries. Called automatically when the fields are edited."""
for geometry in self.selected_geometry:
# Lower the order for B-spline geometries if it is too high.
if isinstance(geometry, BSpline):
max_order = geometry.max_order(value)
if self.field_order.value() > max_order:
self.field_order.setValue(max_order)
cp = geometry.resize_cp(self.field_cp_u.value(), self.field_cp_v.value())
geometry.update(cp)
# Deselect the currently selected point ID to prevent errors when decreasing the number of control points, which may result in the currently selected point ID being out of bounds.
self.selected_point = None
self.load_fields()
self.iren.GetInteractorStyle().set_selected_point_id(None)
self.iren.GetInteractorStyle().set_selected_cp(None)
self.update_label_order()
self.ren.Render()
self.iren.Render()
def update_number_nodes(self) -> None:
"""Update the number of nodes in the currently selected geometries. Called automatically when the fields are edited."""
for geometry in self.selected_geometry:
geometry.update(
number_u=self.field_nodes_u.value(),
number_v=self.field_nodes_v.value(),
)
self.ren.Render()
self.iren.Render()
def update_order(self, value) -> None:
"""Update the order of the currently selected geometries. Called automatically when the fields are edited."""
for geometry in self.selected_geometry:
if isinstance(geometry, BSpline):
max_order = geometry.max_order()
# Lower the order entered by the user if it is too high.
if value > geometry.max_order():
self.field_order.blockSignals(True)
self.field_order.setValue(max_order)
self.field_order.blockSignals(False)
return
geometry.update(order=self.field_order.value())
self.update_label_order()
self.ren.Render()
self.iren.Render()
def update_label_order(self) -> None:
"""Update the label with the order of the currently selected geometry."""
# Show the order if only one geometry is selected.
if len(self.selected_geometry) == 1:
geometry = self.selected_geometry[0]
self.label_order.setText(Geometry.get_order_name(geometry.get_order()))
else:
self.label_order.clear()
def update_label_continuity(self) -> None:
"""Update the label with the continuity of the currently selected geometries."""
if len(self.selected_geometry) > 1:
continuity = self.calculate_continuity(*self.selected_geometry)
# Show the continuity if it was calculated.
if continuity is not None:
self.label_continuity.setText(f"{len(self.selected_geometry)} {self.selected_geometry[0].geometry_name} {self.selected_geometry[0].geometry_type}s have {continuity} continuity")
# If continuity cannot be calculated, show the number of selected geometries.
else:
geometry_types = tuple(set([_.geometry_type for _ in self.selected_geometry]))
geometry_type = f"{geometry_types[0]}s" if len(geometry_types) == 1 else "geometries"
self.label_continuity.setText(f"{len(self.selected_geometry)} {geometry_type} selected")
else:
self.label_continuity.clear()
def calculate_continuity(self, *geometries) -> Continuity:
"""Return the continuity of the given geometries, or return None if continuity cannot be calculated."""
if len(geometries) >= 2:
geometry_classes = set([type(_) for _ in geometries])
# Calculate continuity only if all selected geometries are of the same class.
if len(geometry_classes) == 1:
# Get the class's method for calculating continuity.
try:
continuity_function = tuple(geometry_classes)[0].continuity
# The class does not have a method for calculating continuity.
except AttributeError:
return None
else:
continuities = []
# Calculate continuities for all pairs of geometries.
for i in range(len(geometries) - 1):
for j in range(i+1, len(geometries)):
continuity = continuity_function(geometries[i].cp, geometries[j].cp)
# Append the continuity only if at least C0/G0, ignoring pairs that have no continuity.
if continuity:
continuities.append(continuity)
# Return the lowest continuity found.
if len(continuities) > 0:
return min(continuities)
# No continuity was found.
else:
return Continuity()
def listview_changed(self, new, old) -> None:
"""Highlight the selected geometries in the visualizer, and load the fields with their information. Called automatically when the list view's selection changes."""
self.iren.GetInteractorStyle().unhighlight_selection_point()
self.iren.GetInteractorStyle().unhighlight_selection_nodes()
names = [str(_) for _ in self.geometries]
indices = self.listview.selectionModel().selectedIndexes()
is_multiselection = len(indices) > 1
if len(indices):
for index in indices:
name = self.listview_model.data(index, Qt.DisplayRole)
geometry = self.geometries[names.index(name)]
self.set_selected_geometry(geometry, append=is_multiselection)
self.iren.GetInteractorStyle().set_selected_nodes(geometry.actor_nodes, append=is_multiselection)
self.iren.GetInteractorStyle().highlight_actor(geometry.actor_nodes)
else:
self.set_selected_geometry(None)
self.load_fields()
self.update_label_continuity()
self.update_label_order()
self.ren.Render()
self.iren.Render()
def select_in_listview(self, geometry: Geometry) -> None:
"""Highlight the given geometry in the list view."""
for i in range(self.listview_model.rowCount()):
index = self.listview_model.index(i, 0)
name = self.listview_model.data(index, Qt.DisplayRole)
if name == str(geometry):
# Changing the list view's selection here emits the selectionChanged signal, which calls its connected slot.
self.listview.selectionModel().select(index, QItemSelectionModel.Select)
def get_geometry_of_actor(self, actor: vtk.vtkActor) -> Geometry:
"""Return the Geometry object that contains the given actor, or return None if it does not exist."""
for geometry in self.geometries:
if actor in geometry.get_actors():
return geometry
def set_selected_point(self, point_id: int = None) -> None:
"""Set the point ID as the current selection."""
self.selected_point = point_id
def set_selected_geometry(self, geometry: Geometry = None, append: bool = False) -> None:
"""Set or append the given Geometry to the current selection."""
if append:
if geometry is not None and geometry not in self.selected_geometry:
self.selected_geometry.append(geometry)
else:
if geometry is None:
self.selected_geometry.clear()
else:
self.selected_geometry = [geometry]
def load_fields(self) -> None:
"""Populate the fields in the sidebar with the currently selected geometries, or disable them if no geometries are selected."""
self.update_label_continuity()
self.update_label_order()
if self.selected_geometry:
is_multiple_selected = len(self.selected_geometry) >= 2
# If multiple geometries are selected, load the most recently selected geometry.
geometry = self.selected_geometry[-1] if is_multiple_selected else self.selected_geometry[0]
# Disable fields corresponding to the v direction if not a surface.
is_surface = isinstance(geometry, Surface)
# Disable fields for the order if there is any selection that cannot change its order.
is_all_order_modifiable = all(isinstance(_, BSpline) for _ in self.selected_geometry)
# Disable fields for the number of control points if there is any selection that cannot change its number of control points.
is_all_cp_modifiable = not any(isinstance(_, Hermite) for _ in self.selected_geometry)
# Load the control point fields only if a control point is currently selected and only one geometry is selected.
if self.selected_point is not None:
self.fields_cp.setEnabled(not is_multiple_selected)
if not is_multiple_selected:
point = geometry.get_point(self.selected_point)
self.fields_cp.setEnabled(True)
# Prevent the valueChanged signal from being emitted while changing the fields here.
self.field_x.blockSignals(True)
self.field_y.blockSignals(True)
self.field_z.blockSignals(True)
self.field_x.setValue(point[0])
self.field_y.setValue(point[1])
self.field_z.setValue(point[2])
self.field_x.blockSignals(False)
self.field_y.blockSignals(False)
self.field_z.blockSignals(False)
else:
self.fields_cp.setEnabled(False)
self.fields_number_cp.setEnabled(is_all_cp_modifiable)
self.fields_number_nodes.setEnabled(True)
self.field_cp_v.setEnabled(is_surface)
self.field_nodes_v.setEnabled(is_surface)
self.fields_order.setEnabled(True)
self.field_order.setVisible(is_all_order_modifiable)
self.label_order.setVisible(not is_all_order_modifiable)
self.button_delete.setEnabled(True)
self.field_cp_u.blockSignals(True)
self.field_cp_v.blockSignals(True)
self.field_cp_u.setValue(geometry.get_number_cp_u())
if is_surface:
self.field_cp_v.setValue(geometry.get_number_cp_v())
self.field_cp_u.blockSignals(False)
self.field_cp_v.blockSignals(False)
self.field_nodes_u.blockSignals(True)
self.field_nodes_v.blockSignals(True)
self.field_nodes_u.setValue(geometry.number_u)
if is_surface:
self.field_nodes_v.setValue(geometry.number_v)
self.field_nodes_u.blockSignals(False)
self.field_nodes_v.blockSignals(False)
if isinstance(geometry, BSpline):
self.field_order.blockSignals(True)
self.field_order.setValue(geometry.get_order())
self.field_order.blockSignals(False)
else:
for fields in (self.fields_cp, self.fields_number_cp, self.fields_number_nodes, self.fields_order):
fields.setEnabled(False)
self.button_delete.setEnabled(False)
self.listview.clearSelection()
def set_camera_top(self) -> None:
"""Set the camera to look down along the Z direction."""
camera = self.ren.GetActiveCamera()
camera.SetViewUp(0, 1, 0)
x, y, z = camera.GetPosition()
camera.SetFocalPoint(x, y, z-1)
self.reset_camera()
def set_camera_front(self) -> None:
"""Set the camera to look forward along the Y direction."""
camera = self.ren.GetActiveCamera()
camera.SetViewUp(0, 0, 1)
x, y, z = camera.GetPosition()
camera.SetFocalPoint(x, y+1, z)
self.reset_camera()
def set_camera_fit(self) -> None:
"""Adjust the camera so that the selected geometries, or all geometries if none are selected, are visible."""
if self.selected_geometry:
data_combined = vtk.vtkAppendPoints()
for geometry in self.selected_geometry:
data_combined.AddInputData(geometry.actor_cp.GetMapper().GetInput())
data_combined.Update()
self.ren.ResetCamera(data_combined.GetOutput().GetBounds())
else:
self.ren.ResetCamera()
self.iren.Render()
def reset_camera(self) -> None:
self.ren.ResetCamera()
self.iren.Render()
def update_hermite_tangent_scaling(self, value: float) -> None:
"""Update the scaling factor in the Hermite class and update all Hermite geometries."""
Hermite.hermite_tangent_scaling = value
for geometry in self.geometries:
if isinstance(geometry, Hermite):
geometry.update()
self.ren.Render()
self.iren.Render()
def keyPressEvent(self, event: QKeyEvent) -> None:
"""Define actions for key presses. This overrides the parent class method."""
if event.key() == Qt.Key_Backspace:
self.remove_selected_geometries()
def preset_1(self):
"""Add three preset Bézier curves with G1 and C1 continuity."""
cp_1 = np.array([[[3,10,0], [4,7,0], [6,6,0], [7.5,7.5,0]]]).transpose()
cp_2 = np.array([[[7.5,7.5,0], [8.2,8.2,0], [11,7,0], [14,6,0]]]).transpose()
cp_3 = np.array([[[14,6,0], [17,5,0], [20,10,0], [23,15,0]]]).transpose()
number_u = self.settings_field_nodes.value()
self.add_geometry(BezierCurve(cp_1, number_u))
self.add_geometry(BezierCurve(cp_2, number_u))
self.add_geometry(BezierCurve(cp_3, number_u))
def preset_2(self):
"""Add two preset Bézier surfaces with C1 continuity."""
cp_1 = np.array([[[0,20,0], [8,21,5], [18,23,0]], [[0,17,0], [8,17,6], [18,17,3]], [[0,14,0], [8,14,6], [18,14,4]]]).transpose((2,0,1))
cp_2 = np.array([[[0,14,0], [8,14,6], [18,14,4]], [[0,11,0], [8,11,6], [18,11,5]], [[0,0,0], [8,0,0], [18,0,0]]]).transpose((2,0,1))
number_u = number_v = self.settings_field_nodes.value()
self.add_geometry(BezierSurface(cp_1, number_u, number_v))
self.add_geometry(BezierSurface(cp_2, number_u, number_v))
def preset_3(self):
"""Add two preset Hermite curves with C2 continuity."""
cp_1 = np.array([[[1,5,0], [3,8,0], [3,3,0], [1.9286,-1.2321,0]]]).transpose()
cp_2 = np.array([[[3,8,0], [6,4,0], [1.9286,-1.2321,0], [4.2857,-1.0714,0]]]).transpose()
number_u = self.settings_field_nodes.value()
self.add_geometry(HermiteCurve(cp_1, number_u))
self.add_geometry(HermiteCurve(cp_2, number_u))
def preset_4(self):
"""Add two preset Hermite surfaces with some continuity."""
cp_1 = np.array([
[[0,0,0], [0,10,0], [0,1,0], [0,11,0]],
[[10,0,0], [10,10,0], [10,1,0], [10,11,0]],
[[1,0,0], [1,10,0], [0,0,1], [0,10,1]],
[[11,0,0], [11,10,0], [10,0,1], [10,10,1]],
]).transpose((2,0,1))
cp_2 = np.array([
[[10,0,0], [10,10,0], [10,1,0], [10,11,0]],
[[20,0,0], [20,10,0], [20,1,0], [20,11,0]],
[[11,0,0], [11,10,0], [10,0,1], [10,10,1]],
[[21,0,0], [21,10,0], [20,0,1], [20,10,1]],
]).transpose((2,0,1))
number_u = number_v = self.settings_field_nodes.value()
self.add_geometry(HermiteSurface(cp_1, number_u, number_v))
self.add_geometry(HermiteSurface(cp_2, number_u, number_v))
def preset_4_1(self):
print("Homework 4, Bezier curve")
cp = np.array([
[3, 4, 6, 7.2, 11, 14],
[10, 7, 6, 7.5, 7, 6],
[1, 2, 3, 3.5, 2, 1]
])
geometry = BezierCurve(cp, 25, 25)
self.add_geometry(geometry)
def preset_4_2(self):
print("Homework 4, Bezier surface")
cp = np.array([
[[1, 3, 6, 8], [1, 3, 6, 8], [1, 3, 6, 8], [1, 3, 6, 8]],
[[20, 21, 22, 23], [17, 17, 17, 17], [14, 14, 14, 14], [11, 11, 11, 11]],
[[2, 5, 4, 3], [2, 6, 5, 5], [2, 6, 5, 4], [2, 3, 4, 3]],
])
geometry = BezierSurface(cp, 25, 25)
self.add_geometry(geometry)
if __name__ == "__main__":
application = QApplication(sys.argv)
window = MainWindow()
window.setWindowTitle(PROGRAM_NAME)
window.setWindowIcon(QIcon(os.path.join(FOLDER_ROOT, "Images/logo.png")))
window.show()
# Start the application.
sys.exit(application.exec_())