/
vtkBlenderLikeInteractionStyle.py
1440 lines (1055 loc) · 45 KB
/
vtkBlenderLikeInteractionStyle.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
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
import logging
import warnings
import vtk
import numpy as np
from dataclasses import dataclass
from vtkmodules.vtkRenderingCore import (
vtkActor2D,
vtkTextMapper,
)
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleUser
from vtkmodules.vtkCommonCore import vtkCommand, vtkUnsignedCharArray
"""
Create an interaction style using the Blender default key-bindings (with left-select that is).
Due to C++/Python implementation this requires re-implementing the interaction completely as the c++ methods
can not be overridden/overloaded in python.
Camera action code is largely a translation of https://github.com/Kitware/VTK/blob/master/Interaction/Style/vtkInteractorStyleTrackballCamera.cxx
Rubber band code : https://gitlab.kitware.com/updega2/vtk/-/blob/d324b2e898b0da080edee76159c2f92e6f71abe2/Rendering/vtkInteractorStyleRubberBandZoom.cxx
Interaction:
Left button: Sections
----------------------
Left button: select
Left button drag: rubber band select or line select, depends on the dragged distance
Middle button: Navigation
--------------------------
Middle button: rotate
Middle button + shift : pan
Middle button + ctrl : zoom
Middle button + alt : center view on picked point
OR
Middle button + alt : zoom rubber band --> TODO : see https://gitlab.kitware.com/updega2/vtk/-/blob/d324b2e898b0da080edee76159c2f92e6f71abe2/Rendering/vtkInteractorStyleRubberBandZoom.cxx
Mouse wheel : zoom
Right button : context
-----------------------
Right key click: reserved for context-menu
Keys
------
2 or 3 : toggle perspective view
a : zoom all
x,y,z : view direction (toggles positive and negative)
left/right arrows: rotate 45 deg clockwise/ccw about z-axis, snaps to nearest 45 deg
b : box zoom
m : mouse middle lock (toggles)
space : same as middle mouse button
g : grab (move actors)
enter : accept drag
esc : cancel drag
call callbackEscape
LAPTOP MODE:
Use space or 'm' as replacement for middle button (m is sticky, space is not)
callbacks / overriding keys:
if callbackAnyKey is assigned then this function is called on every key press. If this function returns True
then further processing of events is stopped.
Moving actors
--------------
Actors can be moved interactively by the user.
To support custom groups of actors to be moved as a whole the following system is implemented:
When 'g' is pressed (grab) then a DragInfo dataclass object is assigned to style to style.draginfo
DragInfo includes a list of all the actors that are being dragged. By default this is the selection, but
this may be altered.
Drag is accepted using enter, click, or g. Drag is cancelled by esc
events:
self.callbackStartDrag is called when initializing the drag. This is when to assign actors and other data to draginfo.
self.callbackEndDrag is called when the drag is accepted.
Responding to other events
---------------------------
callbackCameraDirectionChanged : executed when camera has rotated but before re-rendering
"""
@dataclass
class DragInfo:
"""Data structure containing the data required to execute dragging a node"""
# Scene related
dragged_node = None # Node
# VTK related
actors_dragging: list
dragged_actors_original_positions: list # original VTK positions
start_position_3d = np.array((0,0,0)) # start position of the cursor
delta = np.array((0,0,0))
def __init__(self):
self.actors_dragging = []
self.dragged_actors_original_positions = []
class BlenderStyle(vtkInteractorStyleUser):
def RightButtonPress(self, obj, event):
pass
def RightButtonRelease(self, obj, event):
pass
def MiddleButtonPress(self, obj, event):
self._middle_button_down = True
def MiddleButtonRelease(self, obj, event):
self._middle_button_down = False
# perform middle button focus event if ALT is down
if self.GetInteractor().GetAltKey():
logging.info("Middle button released while ALT is down")
# try to pick an object at the current mouse position
rwi = self.GetInteractor()
self.start_x, self.start_y = rwi.GetEventPosition()
props = self.PerformPickingOnSelection()
if props:
self.FocusOn(props[0])
def MouseWheelBackward(self, obj, event):
self.MoveMouseWheel(-1)
def MouseWheelForward(self, obj, event):
self.MoveMouseWheel(1)
def MouseMove(self, obj, event):
interactor = self.GetInteractor()
# Find the renderer that is active below the current mouse position
x, y = interactor.GetEventPosition()
self.FindPokedRenderer(
x, y
) # sets the current renderer [this->SetCurrentRenderer(this->Interactor->FindPokedRenderer(x, y));]
Shift = interactor.GetShiftKey()
Ctrl = interactor.GetControlKey()
Alt = interactor.GetAltKey()
MiddleButton = self._middle_button_down or self.middle_mouse_lock
# start with the special modes
if self._is_box_zooming:
self.DrawDraggedSelection()
elif MiddleButton and not Shift and not Ctrl and not Alt:
self.Rotate()
elif MiddleButton and Shift and not Ctrl and not Alt:
self.Pan()
elif MiddleButton and Ctrl and not Shift and not Alt:
self.Zoom() # Dolly
elif self.draginfo is not None:
self.ExecuteDrag()
elif self._left_button_down and Ctrl and Shift:
self.DrawMeasurement()
elif self._left_button_down:
self.DrawDraggedSelection()
self.InvokeEvent(vtkCommand.InteractionEvent, None)
def MoveMouseWheel(self, direction):
rwi = self.GetInteractor()
# Find the renderer that is active below the current mouse position
x, y = rwi.GetEventPosition()
self.FindPokedRenderer(
x, y
) # sets the current renderer [this->SetCurrentRenderer(this->Interactor->FindPokedRenderer(x, y));]
# The movement
CurrentRenderer = self.GetCurrentRenderer()
# // Calculate the focal depth since we'll be using it a lot
camera = CurrentRenderer.GetActiveCamera()
viewFocus = camera.GetFocalPoint()
temp_out = [0, 0, 0]
self.ComputeWorldToDisplay(
CurrentRenderer, viewFocus[0], viewFocus[1], viewFocus[2], temp_out
)
focalDepth = temp_out[2]
newPickPoint = [0, 0, 0, 0]
x, y = rwi.GetEventPosition()
self.ComputeDisplayToWorld(CurrentRenderer, x, y, focalDepth, newPickPoint)
# // Has to recalc old mouse point since the viewport has moved,
# // so can't move it outside the loop
oldPickPoint = [0, 0, 0, 0]
# xp, yp = rwi.GetLastEventPosition()
# find the center of the window
size = rwi.GetRenderWindow().GetSize()
xp = size[0] / 2
yp = size[1] / 2
self.ComputeDisplayToWorld(
CurrentRenderer, xp, yp, focalDepth, oldPickPoint
)
#
# // Camera motion is reversed
#
move_factor = -1 * self.ZOOM_MOTION_FACTOR * direction
motionVector = (
move_factor * (oldPickPoint[0] - newPickPoint[0]),
move_factor * (oldPickPoint[1] - newPickPoint[1]),
move_factor * (oldPickPoint[2] - newPickPoint[2]),
)
viewFocus = (
camera.GetFocalPoint()
) # do we need to do this again? Already did this
viewPoint = camera.GetPosition()
camera.SetFocalPoint(
motionVector[0] + viewFocus[0],
motionVector[1] + viewFocus[1],
motionVector[2] + viewFocus[2],
)
camera.SetPosition(
motionVector[0] + viewPoint[0],
motionVector[1] + viewPoint[1],
motionVector[2] + viewPoint[2],
)
# the Zooming
factor = self.MOUSE_MOTION_FACTOR * self.MOUSE_WHEEL_MOTION_FACTOR
self.ZoomByStep(direction*factor)
def ZoomByStep(self, step):
CurrentRenderer = self.GetCurrentRenderer()
if CurrentRenderer:
self.StartDolly()
self.Dolly(pow(1.1, step))
self.EndDolly()
def LeftButtonPress(self, obj, event):
if self._is_box_zooming:
return
if self.draginfo:
return
self._left_button_down = True
interactor = self.GetInteractor()
Shift = interactor.GetShiftKey()
Ctrl = interactor.GetControlKey()
if Shift and Ctrl:
if not self.GetCurrentRenderer().GetActiveCamera().GetParallelProjection():
self.ToggleParallelProjection()
rwi = self.GetInteractor()
self.start_x, self.start_y = rwi.GetEventPosition()
self.end_x = self.start_x
self.end_y = self.start_y
self.InitializeScreenDrawing()
def LeftButtonRelease(self, obj, event):
if self._is_box_zooming:
self._is_box_zooming = False
self.ZoomBox(self.start_x, self.start_y, self.end_x, self.end_y)
return
if self.draginfo:
self.FinishDrag()
return
self._left_button_down = False
interactor = self.GetInteractor()
Shift = interactor.GetShiftKey()
Ctrl = interactor.GetControlKey()
Alt = interactor.GetAltKey()
if Ctrl and Shift:
pass # we were drawing the measurement
else:
if self.callbackSelect:
props = self.PerformPickingOnSelection()
if props: # only call back if anything was selected
self.picked_props = tuple(props)
self.callbackSelect(props)
# remove the selection rubber band / line
self.DoRender()
def KeyPress(self, obj, event):
key = obj.GetKeySym()
KEY = key.upper()
# logging.info(f"Key Press: {key}")
if self.callbackAnyKey:
if self.callbackAnyKey(key):
return
if KEY == "M":
self.middle_mouse_lock = not self.middle_mouse_lock
self.UpdateMiddleMouseButtonLockActor()
elif KEY == "G":
if self.draginfo is not None:
self.FinishDrag()
else:
if self.callbackStartDrag:
self.callbackStartDrag()
else:
self.StartDrag() # internally calls end-drag if drag is already active
elif KEY=="ESCAPE":
if self.callbackEscapeKey:
self.callbackEscapeKey()
if self.draginfo is not None:
self.CancelDrag()
elif KEY=="DELETE":
if self.callbackDeleteKey:
self.callbackDeleteKey()
elif KEY=="RETURN":
if self.draginfo:
self.FinishDrag()
elif KEY == "SPACE":
self.middle_mouse_lock = True
# self.UpdateMiddleMouseButtonLockActor()
# self.GrabFocus(vtkCommand.MouseMoveEvent, self) # TODO: grab and release focus; possible from python?
elif KEY == "B":
self._is_box_zooming = True
rwi = self.GetInteractor()
self.start_x, self.start_y = rwi.GetEventPosition()
self.end_x = self.start_x
self.end_y = self.start_y
self.InitializeScreenDrawing()
elif KEY == "2" or KEY == "3":
self.ToggleParallelProjection()
elif KEY == "A":
self.ZoomFit()
elif KEY == "X":
self.SetViewX()
elif KEY == "Y":
self.SetViewY()
elif KEY == "Z":
self.SetViewZ()
elif KEY == "LEFT":
self.RotateDiscreteStep(1)
elif KEY == "RIGHT":
self.RotateDiscreteStep(-1)
elif KEY == "UP":
self.RotateTurtableBy(0,10)
elif KEY == "DOWN":
self.RotateTurtableBy(0,-10)
elif KEY == "PLUS":
self.ZoomByStep(2)
elif KEY == "MINUS":
self.ZoomByStep(-2)
elif KEY == "F":
if self.callbackFocusKey:
self.callbackFocusKey()
self.InvokeEvent(vtkCommand.InteractionEvent, None)
def KeyRelease(self, obj, event):
key = obj.GetKeySym()
KEY = key.upper()
logging.info(f"Key release: {key}")
if KEY == "SPACE":
if self.middle_mouse_lock:
self.middle_mouse_lock = False
self.UpdateMiddleMouseButtonLockActor()
def WindowResized(self):
logging.info("window resized")
self.InitializeScreenDrawing()
def RotateDiscreteStep(self, movement_direction, step=22.5):
"""Rotates CW or CCW to the nearest 45 deg angle - includes some fuzzyness to determine about which axis"""
CurrentRenderer = self.GetCurrentRenderer()
camera = CurrentRenderer.GetActiveCamera()
step = np.deg2rad(step)
direction = -np.array(camera.GetViewPlaneNormal()) # current camera direction
if (
abs(direction[2]) < 0.7
): # horizontal view, rotate camera position about Z-axis
angle = np.arctan2(direction[1], direction[0])
# find the nearest angle that is an integer number of steps
if movement_direction > 0:
angle = step * np.floor((angle + 0.1 * step) / step) + step
else:
angle = -step * np.floor(-(angle - 0.1 * step) / step) - step
dist = np.linalg.norm(direction[:2])
direction[0] = np.cos(angle) * dist
direction[1] = np.sin(angle) * dist
self.SetCameraDirection(direction)
else: # Top or bottom like view - rotate camera "up" direction
up = np.array(camera.GetViewUp())
angle = np.arctan2(up[1], up[0])
# find the nearest angle that is an integer number of steps
if movement_direction > 0:
angle = step * np.floor((angle + 0.1 * step) / step) + step
else:
angle = -step * np.floor(-(angle - 0.1 * step) / step) - step
dist = np.linalg.norm(up[:2])
up[0] = np.cos(angle) * dist
up[1] = np.sin(angle) * dist
camera.SetViewUp(up)
camera.OrthogonalizeViewUp()
self.DoRender()
def ToggleParallelProjection(self):
renderer = self.GetCurrentRenderer()
camera = renderer.GetActiveCamera()
camera.SetParallelProjection(not bool(camera.GetParallelProjection()))
# self.GetInteractor().Render()
self.DoRender()
def SetViewX(self):
self.SetCameraPlaneDirection((1, 0, 0))
def SetViewY(self):
self.SetCameraPlaneDirection((0, 1, 0))
def SetViewZ(self):
self.SetCameraPlaneDirection((0, 0, 1))
def ZoomFit(self):
self.GetCurrentRenderer().ResetCamera()
self.DoRender()
def SetCameraPlaneDirection(self, direction):
"""Sets the camera to display a plane of which direction is the normal - includes logic to reverse the direction if benificial"""
CurrentRenderer = self.GetCurrentRenderer()
if CurrentRenderer is None:
return
camera = CurrentRenderer.GetActiveCamera()
direction = np.array(direction)
normal = camera.GetViewPlaneNormal()
# can not set the normal, need to change the position to do that
current_alignment = np.dot(normal, -direction)
logging.info(f"Current alignment = {current_alignment}")
if abs(current_alignment) > 0.9999:
logging.info("toggling")
direction = -np.array(normal)
elif current_alignment > 0: # find the nearest plane
logging.info("reversing to find nearest")
direction = -direction
self.SetCameraDirection(-direction)
def SetCameraDirection(self, direction):
"""Sets the camera to this direction, sets view up if horizontal enough"""
direction = np.array(direction)
CurrentRenderer = self.GetCurrentRenderer()
camera = CurrentRenderer.GetActiveCamera()
rwi = self.GetInteractor()
pos = np.array(camera.GetPosition())
focal = np.array(camera.GetFocalPoint())
dist = np.linalg.norm(pos - focal)
pos = focal - dist * direction
camera.SetPosition(pos)
if abs(direction[2]) < 0.9:
camera.SetViewUp(0, 0, 1)
elif direction[2] > 0.9:
camera.SetViewUp(0,-1,0)
else:
camera.SetViewUp(0, 1, 0)
camera.OrthogonalizeViewUp()
self.UpdateClippingRange()
if rwi.GetLightFollowCamera():
CurrentRenderer.UpdateLightsGeometryToFollowCamera()
if self.callbackCameraDirectionChanged:
self.callbackCameraDirectionChanged()
self.DoRender()
def UpdateClippingRange(self):
if self.GetAutoAdjustCameraClippingRange():
self.GetCurrentRenderer().ResetCameraClippingRange()
camera = self.GetCurrentRenderer().GetActiveCamera()
near,far = camera.GetClippingRange()
camera.SetClippingRange(self.CLIPPING_PLANE_NEAR_FRACTION_OF_FAR * far, far)
def PerformPickingOnSelection(self):
"""Preforms prop3d picking on the current dragged selection
If the distance between the start and endpoints is less than the threshold
then a SINGLE prop3d is picked along the line
the selection area is drawn by the rubber band and is defined by
self.start_x, self.start_y, self.end_x, self.end_y
"""
renderer = self.GetCurrentRenderer()
assemblyPath = renderer.PickProp(
self.start_x, self.start_y, self.end_x, self.end_y
)
# re-pick in larger area if nothing is returned
if not assemblyPath:
logging.info(
"Did not find anything in this area, extending by 2px to all sides and picking again"
)
self.start_x -= 2
self.end_x += 2
self.start_y -= 2
self.end_y += 2
assemblyPath = renderer.PickProp(
self.start_x, self.start_y, self.end_x, self.end_y
)
# The nearest prop (by Z-value)
if assemblyPath:
logging.info(
f"Renderer Pick returned {assemblyPath.GetNumberOfItems()} items in assembly-path"
)
assert (
assemblyPath.GetNumberOfItems() == 1
), "Wrong assumption on number of returned nodes when picking"
nearest_prop = assemblyPath.GetItemAsObject(0).GetViewProp()
# all props
collection = renderer.GetPickResultProps()
props = [
collection.GetItemAsObject(i)
for i in range(collection.GetNumberOfItems())
]
props.remove(nearest_prop)
props.insert(0, nearest_prop)
return props
else:
return []
# ----------- actor dragging ------------
def StartDrag(self):
if self.callbackStartDrag:
logging.info("Calling callbackStartDrag")
self.callbackStartDrag()
return
else: # grab the current selection
if self.picked_props:
self.StartDragOnProps(self.picked_props)
else:
logging.info('Can not start drag, nothing selected and callbackStartDrag not assigned')
def FinishDrag(self):
logging.info('Finished drag')
if self.callbackEndDrag:
# reset actor positions as actors positions will be controlled by called functions
for pos0, actor in zip(self.draginfo.dragged_actors_original_positions, self.draginfo.actors_dragging):
actor.SetPosition(pos0)
self.callbackEndDrag(self.draginfo)
self.draginfo = None
def StartDragOnProps(self, props):
"""Starts drag on the provided props (actors) by filling self.draginfo"""
if self.draginfo is not None:
self.FinishDrag()
return
logging.info('Starting drag')
# create and fill drag-info
draginfo = DragInfo()
#
# draginfo.dragged_node = node
#
# # find all actors and outlines corresponding to this node
# actors = [*self.actor_from_node(node).actors.values()]
# outlines = [ol.outline_actor for ol in self.node_outlines if ol.parent_vp_actor in actors]
draginfo.actors_dragging = props # [*actors, *outlines]
for a in draginfo.actors_dragging:
draginfo.dragged_actors_original_positions.append(a.GetPosition()) # numpy ndarray
# Get the start position of the drag in 3d
rwi = self.GetInteractor()
CurrentRenderer = self.GetCurrentRenderer()
camera = CurrentRenderer.GetActiveCamera()
viewFocus = camera.GetFocalPoint()
temp_out = [0, 0, 0]
self.ComputeWorldToDisplay(
CurrentRenderer, viewFocus[0], viewFocus[1], viewFocus[2], temp_out
)
focalDepth = temp_out[2]
newPickPoint = [0, 0, 0, 0]
x, y = rwi.GetEventPosition()
self.ComputeDisplayToWorld(CurrentRenderer, x, y, focalDepth, newPickPoint)
mouse_pos_3d = np.array(newPickPoint[:3])
draginfo.start_position_3d = mouse_pos_3d
self.draginfo = draginfo
def ExecuteDrag(self):
rwi = self.GetInteractor()
CurrentRenderer = self.GetCurrentRenderer()
camera = CurrentRenderer.GetActiveCamera()
viewFocus = camera.GetFocalPoint()
# Get the picked point in 3d
temp_out = [0, 0, 0]
self.ComputeWorldToDisplay(
CurrentRenderer, viewFocus[0], viewFocus[1], viewFocus[2], temp_out
)
focalDepth = temp_out[2]
newPickPoint = [0, 0, 0, 0]
x, y = rwi.GetEventPosition()
self.ComputeDisplayToWorld(CurrentRenderer, x, y, focalDepth, newPickPoint)
mouse_pos_3d = np.array(newPickPoint[:3])
# compute the delta and execute
delta = np.array(mouse_pos_3d) - self.draginfo.start_position_3d
logging.info(f'Delta = {delta}')
view_normal = np.array(self.GetCurrentRenderer().GetActiveCamera().GetViewPlaneNormal())
delta_inplane = delta - view_normal * np.dot(delta, view_normal)
logging.info(f'delta_inplane = {delta_inplane}')
for pos0, actor in zip(self.draginfo.dragged_actors_original_positions, self.draginfo.actors_dragging):
m = actor.GetUserMatrix()
if m:
warnings.warn('UserMatrices/transforms not supported')
# m.Invert() #inplace
# rotated = m.MultiplyFloatPoint([*delta_inplane, 1])
# actor.SetPosition(pos0 + np.array(rotated[:3]))
actor.SetPosition(pos0 + delta_inplane)
logging.info(f'Set position to {pos0 + delta_inplane}')
self.draginfo.delta = delta_inplane # store the current delta
# self.GetInteractor().Render()
self.DoRender()
def CancelDrag(self):
"""Cancels the drag and restored the original positions of all dragged actors"""
for pos0, actor in zip(self.draginfo.dragged_actors_original_positions, self.draginfo.actors_dragging):
actor.SetPosition(pos0)
self.draginfo = None
self.DoRender()
# ----------- end dragging --------------
def Zoom(self):
rwi = self.GetInteractor()
x, y = rwi.GetEventPosition()
xp, yp = rwi.GetLastEventPosition()
direction = y - yp
self.MoveMouseWheel(direction / 10)
def Pan(self):
CurrentRenderer = self.GetCurrentRenderer()
if CurrentRenderer:
rwi = self.GetInteractor()
# // Calculate the focal depth since we'll be using it a lot
camera = CurrentRenderer.GetActiveCamera()
viewFocus = camera.GetFocalPoint()
temp_out = [0, 0, 0]
self.ComputeWorldToDisplay(
CurrentRenderer, viewFocus[0], viewFocus[1], viewFocus[2], temp_out
)
focalDepth = temp_out[2]
newPickPoint = [0, 0, 0, 0]
x, y = rwi.GetEventPosition()
self.ComputeDisplayToWorld(CurrentRenderer, x, y, focalDepth, newPickPoint)
# // Has to recalc old mouse point since the viewport has moved,
# // so can't move it outside the loop
oldPickPoint = [0, 0, 0, 0]
xp, yp = rwi.GetLastEventPosition()
self.ComputeDisplayToWorld(
CurrentRenderer, xp, yp, focalDepth, oldPickPoint
)
#
# // Camera motion is reversed
#
motionVector = (
oldPickPoint[0] - newPickPoint[0],
oldPickPoint[1] - newPickPoint[1],
oldPickPoint[2] - newPickPoint[2],
)
viewFocus = (
camera.GetFocalPoint()
) # do we need to do this again? Already did this
viewPoint = camera.GetPosition()
camera.SetFocalPoint(
motionVector[0] + viewFocus[0],
motionVector[1] + viewFocus[1],
motionVector[2] + viewFocus[2],
)
camera.SetPosition(
motionVector[0] + viewPoint[0],
motionVector[1] + viewPoint[1],
motionVector[2] + viewPoint[2],
)
if rwi.GetLightFollowCamera():
CurrentRenderer.UpdateLightsGeometryToFollowCamera()
# rwi.Render()
self.DoRender()
def Rotate(self):
CurrentRenderer = self.GetCurrentRenderer()
if CurrentRenderer:
rwi = self.GetInteractor()
dx = rwi.GetEventPosition()[0] - rwi.GetLastEventPosition()[0]
dy = rwi.GetEventPosition()[1] - rwi.GetLastEventPosition()[1]
size = CurrentRenderer.GetRenderWindow().GetSize()
delta_elevation = -20.0 / size[1]
delta_azimuth = -20.0 / size[0]
rxf = dx * delta_azimuth * self.MOUSE_MOTION_FACTOR
ryf = dy * delta_elevation * self.MOUSE_MOTION_FACTOR
self.RotateTurtableBy(rxf, ryf)
def RotateTurtableBy(self, rxf, ryf):
CurrentRenderer = self.GetCurrentRenderer()
rwi = self.GetInteractor()
# rfx is rotation about the global Z vector (turn-table mode)
# rfy is rotation about the side vector
camera = CurrentRenderer.GetActiveCamera()
campos = np.array(camera.GetPosition())
focal = np.array(camera.GetFocalPoint())
up = camera.GetViewUp()
upside_down_factor = -1 if up[2]<0 else 1
# rotate about focal point
P = campos - focal # camera position
# Rotate left/right about the global Z axis
H = np.linalg.norm(P[:2]) # horizontal distance of camera to focal point
elev = np.arctan2(P[2], H) # elevation
# if the camera is near the poles, then derive the azimuth from the up-vector
sin_elev = np.sin(elev)
if abs(sin_elev) < 0.8:
azi = np.arctan2(P[1], P[0]) # azimuth from camera position
else:
if sin_elev < -0.8:
azi = np.arctan2(upside_down_factor*up[1], upside_down_factor*up[0])
else:
azi = np.arctan2(-upside_down_factor*up[1], -upside_down_factor*up[0])
D = np.linalg.norm(P) # distance from focal point to camera
# apply the change in azimuth and elevation
azi_new = azi + rxf / 60
elev_new = elev + upside_down_factor * ryf / 60
# the changed elevation changes H (D stays the same)
Hnew = D*np.cos(elev_new)
# calculate new camera position relative to focal point
Pnew = np.array((Hnew*np.cos(azi_new),
Hnew*np.sin(azi_new),
D*np.sin(elev_new)))
# calculate the up-direction of the camera
up_z = upside_down_factor * np.cos(elev_new) # z follows directly from elevation
up_h = upside_down_factor * np.sin(elev_new) # horizontal component
#
# if upside_down:
# up_z = -up_z
# up_h = -up_h
up = (-up_h * np.cos(azi_new),
-up_h * np.sin(azi_new),
up_z)
new_pos = focal + Pnew
camera.SetViewUp(up)
camera.SetPosition(new_pos)
camera.OrthogonalizeViewUp()
# Update
self.UpdateClippingRange()
if rwi.GetLightFollowCamera():
CurrentRenderer.UpdateLightsGeometryToFollowCamera()
if self.callbackCameraDirectionChanged:
self.callbackCameraDirectionChanged()
self.DoRender()
def ZoomBox(self, x1, y1, x2, y2):
"""Zooms to a box"""
# int width, height;
# width = abs(this->EndPosition[0] - this->StartPosition[0]);
# height = abs(this->EndPosition[1] - this->StartPosition[1]);
if x1 > x2:
_ = x1
x1 = x2
x2 = _
if y1 > y2:
_ = y1
y1 = y2
y2 = _
width = x2 - x1
height = y2 - y1
# int *size = this->CurrentRenderer->GetSize();
CurrentRenderer = self.GetCurrentRenderer()
size = CurrentRenderer.GetSize()
origin = CurrentRenderer.GetOrigin()
camera = CurrentRenderer.GetActiveCamera()
# Assuming we're drawing the band on the view-plane
rbcenter = (x1 + width / 2, y1 + height / 2, 0)
CurrentRenderer.SetDisplayPoint(rbcenter)
CurrentRenderer.DisplayToView()
CurrentRenderer.ViewToWorld()
worldRBCenter = CurrentRenderer.GetWorldPoint()
invw = 1.0 / worldRBCenter[3]
worldRBCenter = [c * invw for c in worldRBCenter]
#
# double winCenter[3];
winCenter = [origin[0] + 0.5 * size[0], origin[1] + 0.5 * size[1], 0]
CurrentRenderer.SetDisplayPoint(winCenter)
CurrentRenderer.DisplayToView()
CurrentRenderer.ViewToWorld()
worldWinCenter = CurrentRenderer.GetWorldPoint()
invw = 1.0 / worldWinCenter[3]
worldWinCenter = [c * invw for c in worldWinCenter]
translation = [
worldRBCenter[0] - worldWinCenter[0],
worldRBCenter[1] - worldWinCenter[1],
worldRBCenter[2] - worldWinCenter[2],
]
pos = camera.GetPosition()
fp = camera.GetFocalPoint()
#
pos = [pos[i] + translation[i] for i in range(3)]
fp = [fp[i] + translation[i] for i in range(3)]
#
camera.SetPosition(pos)
camera.SetFocalPoint(fp)
if width > height:
camera.Zoom(size[0] / width)
else:
camera.Zoom(size[1] / height)
# self.GetInteractor().Render()
self.DoRender()
def FocusOn(self, prop3D):
"""Move the camera to focus on this particular prop3D"""
position = prop3D.GetPosition()
logging.info(f"Focus on {position}")
CurrentRenderer = self.GetCurrentRenderer()
camera = CurrentRenderer.GetActiveCamera()
fp = camera.GetFocalPoint()
pos = camera.GetPosition()
camera.SetFocalPoint(position)
camera.SetPosition(