forked from f3d-app/f3d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinteractor_impl.cxx
1462 lines (1290 loc) · 50.6 KB
/
interactor_impl.cxx
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
#include "interactor_impl.h"
#include "animationManager.h"
#include "engine.h"
#include "log.h"
#include "scene_impl.h"
#include "utils.h"
#include "window_impl.h"
#include "vtkF3DConsoleOutputWindow.h"
#if F3D_MODULE_UI
#include "vtkF3DImguiConsole.h"
#endif
#include "vtkF3DInteractorEventRecorder.h"
#include "vtkF3DInteractorStyle.h"
#include "vtkF3DRenderer.h"
#include "vtkF3DUIActor.h"
#include "vtkF3DUIObserver.h"
#include <vtkCallbackCommand.h>
#include <vtkCellPicker.h>
#include <vtkGenericRenderWindowInteractor.h>
#include <vtkMath.h>
#include <vtkMatrix3x3.h>
#include <vtkNew.h>
#include <vtkPicker.h>
#include <vtkPointPicker.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRendererCollection.h>
#include <vtkStringArray.h>
#include <vtkVersion.h>
#include <vtksys/SystemTools.hxx>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <map>
#include <numeric>
#include <regex>
#include <vector>
#include "camera.h"
namespace fs = std::filesystem;
namespace f3d::detail
{
using mod_t = interaction_bind_t::ModifierKeys;
class interactor_impl::internals
{
public:
struct BindingCommands
{
std::vector<std::string> CommandVector;
documentation_callback_t DocumentationCallback;
};
internals(options& options, window_impl& window, scene_impl& scene, interactor_impl& inter)
: Options(options)
, Window(window)
, Scene(scene)
, Interactor(inter)
{
window::Type type = window.getType();
if (type == window::Type::GLX || type == window::Type::WGL || type == window::Type::COCOA ||
type == window::Type::WASM)
{
this->VTKInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
}
else
{
this->VTKInteractor = vtkSmartPointer<vtkGenericRenderWindowInteractor>::New();
}
#ifdef __EMSCRIPTEN__
vtkRenderWindowInteractor::InteractorManagesTheEventLoop = false;
#endif
this->VTKInteractor->SetRenderWindow(this->Window.GetRenderWindow());
this->VTKInteractor->SetInteractorStyle(this->Style);
this->VTKInteractor->Initialize();
// Some implementation (e.g. macOS) in VTK set the window name during initialization
// so we need to set the name right after initialization
this->Window.setWindowName("f3d");
this->UIObserver->InstallObservers(this->VTKInteractor);
// observe console event to trigger commands
vtkNew<vtkCallbackCommand> commandCallback;
commandCallback->SetClientData(this);
commandCallback->SetCallback(OnConsoleEvent);
vtkOutputWindow::GetInstance()->AddObserver(
vtkF3DConsoleOutputWindow::TriggerEvent, commandCallback);
vtkOutputWindow::GetInstance()->AddObserver(
vtkF3DConsoleOutputWindow::ShowEvent, commandCallback);
vtkOutputWindow::GetInstance()->AddObserver(
vtkF3DConsoleOutputWindow::HideEvent, commandCallback);
// Disable standard interactor behavior with timer event
// in order to be able to interact while animating
this->VTKInteractor->RemoveObservers(vtkCommand::TimerEvent);
vtkNew<vtkCallbackCommand> keyPressCallback;
keyPressCallback->SetClientData(this);
keyPressCallback->SetCallback(OnKeyPress);
this->Style->AddObserver(vtkF3DInteractorStyle::KeyPressEvent, keyPressCallback);
vtkNew<vtkCallbackCommand> dropFilesCallback;
dropFilesCallback->SetClientData(this);
dropFilesCallback->SetCallback(OnDropFiles);
this->Style->AddObserver(vtkF3DInteractorStyle::DropFilesEvent, dropFilesCallback);
vtkNew<vtkCallbackCommand> middleButtonPressCallback;
middleButtonPressCallback->SetClientData(this);
middleButtonPressCallback->SetCallback(OnMiddleButtonPress);
this->Style->AddObserver(vtkCommand::MiddleButtonPressEvent, middleButtonPressCallback);
vtkNew<vtkCallbackCommand> middleButtonReleaseCallback;
middleButtonReleaseCallback->SetClientData(this);
middleButtonReleaseCallback->SetCallback(OnMiddleButtonRelease);
this->Style->AddObserver(vtkCommand::MiddleButtonReleaseEvent, middleButtonReleaseCallback);
this->Recorder = vtkSmartPointer<vtkF3DInteractorEventRecorder>::New();
this->Recorder->SetInteractor(this->VTKInteractor);
}
//----------------------------------------------------------------------------
// Method defined to normalize the Z axis so all models are treated temporarily
// as Z-up axis models.
void ToEnvironmentSpace(vtkMatrix3x3* transform)
{
vtkRenderer* renderer =
this->VTKInteractor->GetRenderWindow()->GetRenderers()->GetFirstRenderer();
const double* up = renderer->GetEnvironmentUp();
const double* right = renderer->GetEnvironmentRight();
double fwd[3];
vtkMath::Cross(right, up, fwd);
const double m[9] = {
right[0], right[1], right[2], //
fwd[0], fwd[1], fwd[2], //
up[0], up[1], up[2], //
};
transform->DeepCopy(m);
}
//----------------------------------------------------------------------------
// Set the view orbit position on the viewport.
enum class ViewType
{
VT_FRONT,
VT_RIGHT,
VT_TOP,
VT_ISOMETRIC
};
void SetViewOrbit(ViewType view)
{
vtkNew<vtkMatrix3x3> transform;
this->ToEnvironmentSpace(transform);
camera& cam = this->Window.getCamera();
vector3_t up = { 0, 0, 1 };
point3_t foc = cam.getFocalPoint();
point3_t axis, newPos;
switch (view)
{
case ViewType::VT_FRONT:
axis = { 0, +1, 0 };
break;
case ViewType::VT_RIGHT:
axis = { +1, 0, 0 };
break;
case ViewType::VT_TOP:
axis = { 0, 0, +1 };
up = { 0, -1, 0 };
break;
case ViewType::VT_ISOMETRIC:
axis = { -1, +1, +1 };
break;
}
transform->MultiplyPoint(up.data(), up.data());
transform->MultiplyPoint(axis.data(), axis.data());
newPos[0] = foc[0] + axis[0];
newPos[1] = foc[1] + axis[1];
newPos[2] = foc[2] + axis[2];
/* set camera coordinates back */
cam.setPosition(newPos);
cam.setViewUp(up);
cam.resetToBounds(0.9);
}
//----------------------------------------------------------------------------
// Increase/Decrease light intensity
void IncreaseLightIntensity(bool negative)
{
const double intensity = this->Options.render.light.intensity;
/* `ref < x` is equivalent to:
* - `intensity <= x` when going down
* - `intensity < x` when going up */
const double ref = negative ? intensity - 1e-6 : intensity;
// clang-format off
/* offset in percentage points */
const int offsetPp = ref < .5 ? 1
: ref < 1 ? 2
: ref < 5 ? 5
: ref < 10 ? 10
: 25;
// clang-format on
/* new intensity in percents */
const int newIntensityPct = std::lround(intensity * 100) + (negative ? -offsetPp : +offsetPp);
this->Options.render.light.intensity = std::max(newIntensityPct, 0) / 100.0;
}
//----------------------------------------------------------------------------
// Increase/Decrease opacity
void IncreaseOpacity(bool negative)
{
// current opacity, interpreted as 1 if it does not exist
const double currentOpacity = this->Options.model.color.opacity.value_or(1.0);
// new opacity, clamped between 0 and 1 if not already set outside that range
const double increment = negative ? -0.05 : 0.05;
double newOpacity = currentOpacity + increment;
if (currentOpacity <= 1.0 && 0.0 <= currentOpacity)
{
newOpacity = std::min(1.0, std::max(0.0, newOpacity));
}
this->Options.model.color.opacity = newOpacity;
}
//----------------------------------------------------------------------------
// Synchronise options from the renderer properties
static void SynchronizeScivisOptions(f3d::options& opt, vtkF3DRenderer* ren)
{
// Synchronize renderer coloring status with scivis options
opt.model.scivis.enable = ren->GetEnableColoring();
opt.model.scivis.cells = ren->GetUseCellColoring();
opt.model.scivis.array_name = ren->GetArrayNameForColoring();
opt.model.scivis.component = ren->GetComponentForColoring();
}
//----------------------------------------------------------------------------
static void OnConsoleEvent(vtkObject*, unsigned long event, void* clientData, void* data)
{
internals* self = static_cast<internals*>(clientData);
if (event == vtkF3DConsoleOutputWindow::TriggerEvent)
{
const char* commandWithArgs = static_cast<const char*>(data);
self->Interactor.SetCommandBuffer(commandWithArgs);
}
else if (event == vtkF3DConsoleOutputWindow::ShowEvent)
{
// Invoked when console badge is clicked
self->Options.ui.console = true;
}
else if (event == vtkF3DConsoleOutputWindow::HideEvent)
{
// Invoked when esc key is pressed while in minimal console or console display, or when
// something is submitted to minimal console
self->Options.ui.console = false;
self->Options.ui.minimal_console = false;
}
self->RenderRequested = true;
}
//----------------------------------------------------------------------------
static void OnKeyPress(vtkObject*, unsigned long, void* clientData, void*)
{
internals* self = static_cast<internals*>(clientData);
vtkRenderWindowInteractor* rwi = self->Style->GetInteractor();
std::string interaction = rwi->GetKeySym();
if (!interaction.empty())
{
// Make sure key symbols starts with an upper char (e.g. "space" -> "Space")
interaction[0] = std::toupper(interaction[0]);
}
self->TriggerBinding(interaction, "");
}
//----------------------------------------------------------------------------
static void OnDropFiles(vtkObject*, unsigned long, void* clientData, void* callData)
{
internals* self = static_cast<internals*>(clientData);
vtkStringArray* filesArr = static_cast<vtkStringArray*>(callData);
const std::regex charsToEscape(R"((["\\]))");
std::string filesString;
for (int i = 0; i < filesArr->GetNumberOfTuples(); i++)
{
const vtkStdString& filename = filesArr->GetValue(i);
const std::string escapedFilename = std::regex_replace(filename, charsToEscape, "\\$1");
if (i > 0)
{
filesString.push_back(' ');
}
filesString.push_back('"');
filesString.append(escapedFilename);
filesString.push_back('"');
}
self->TriggerBinding("Drop", filesString);
}
//----------------------------------------------------------------------------
static void OnMiddleButtonPress(vtkObject*, unsigned long, void* clientData, void*)
{
internals* self = static_cast<internals*>(clientData);
self->VTKInteractor->GetEventPosition(self->MiddleButtonDownPosition);
self->Style->OnMiddleButtonDown();
}
//----------------------------------------------------------------------------
static void OnMiddleButtonRelease(vtkObject*, unsigned long, void* clientData, void*)
{
internals* self = static_cast<internals*>(clientData);
const int* middleButtonUpPosition = self->VTKInteractor->GetEventPosition();
const int xDelta = middleButtonUpPosition[0] - self->MiddleButtonDownPosition[0];
const int yDelta = middleButtonUpPosition[1] - self->MiddleButtonDownPosition[1];
const int sqPosDelta = xDelta * xDelta + yDelta * yDelta;
if (sqPosDelta < self->DragDistanceTol * self->DragDistanceTol)
{
const int x = self->MiddleButtonDownPosition[0];
const int y = self->MiddleButtonDownPosition[1];
vtkRenderer* renderer =
self->VTKInteractor->GetRenderWindow()->GetRenderers()->GetFirstRenderer();
bool pickSuccessful = false;
double picked[3];
if (self->CellPicker->Pick(x, y, 0, renderer))
{
self->CellPicker->GetPickPosition(picked);
pickSuccessful = true;
}
else if (self->PointPicker->Pick(x, y, 0, renderer))
{
self->PointPicker->GetPickPosition(picked);
pickSuccessful = true;
}
if (pickSuccessful)
{
/* pos.--------------------.foc
* /| /
* / | /
* .--.-----------------.picked
* pos1 pos2
*/
const camera_state_t state = self->Window.getCamera().getState();
double focV[3];
vtkMath::Subtract(picked, state.focalPoint.data(), focV); /* foc -> picked */
double posV[3];
vtkMath::Subtract(
picked, state.focalPoint.data(), posV); /* pos -> pos1, parallel to focV */
if (!self->Style->GetInteractor()->GetShiftKey())
{
double v[3];
vtkMath::Subtract(state.focalPoint.data(), state.position.data(), v); /* pos -> foc */
vtkMath::ProjectVector(focV, v, v); /* pos2 -> pos1 */
vtkMath::Subtract(posV, v, posV); /* pos -> pos2, keeps on camera plane */
}
const auto interpolateCameraState = [&state, &focV, &posV](double ratio) -> camera_state_t
{
return { {
state.position[0] + posV[0] * ratio,
state.position[1] + posV[1] * ratio,
state.position[2] + posV[2] * ratio,
},
{
state.focalPoint[0] + focV[0] * ratio,
state.focalPoint[1] + focV[1] * ratio,
state.focalPoint[2] + focV[2] * ratio,
},
state.viewUp, state.viewAngle };
};
self->AnimateCameraTransition(interpolateCameraState);
}
}
self->Style->OnMiddleButtonUp();
}
/**
* Run a camera transition animation based on a camera state interpolation function.
* The provided function will be called with an interpolation parameter
* varying from `0.` for the initial state to `1.` for the final state;
* it shall return an appropriate linearly interpolated `camera_state_t` for any value in between.
*/
template<class CameraStateInterpolator>
void AnimateCameraTransition(CameraStateInterpolator interpolateCameraState)
{
window& win = this->Window;
camera& cam = win.getCamera();
const int duration = this->TransitionDuration;
if (duration > 0)
{
// TODO implement a way to not queue key presses while the animation is running
const auto start = std::chrono::high_resolution_clock::now();
const auto end = start + std::chrono::milliseconds(duration);
auto now = start;
while (now < end)
{
const double timeDelta =
std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();
const double ratio = (1 - std::cos(vtkMath::Pi() * (timeDelta / duration))) / 2;
cam.setState(interpolateCameraState(ratio));
this->Window.render();
now = std::chrono::high_resolution_clock::now();
}
}
cam.setState(interpolateCameraState(1.)); // ensure final update
this->Window.render();
}
//----------------------------------------------------------------------------
void TriggerBinding(const std::string& interaction, const std::string& argsString)
{
mod_t mod = mod_t::NONE;
vtkRenderWindowInteractor* rwi = this->Style->GetInteractor();
const bool shift = rwi->GetShiftKey() == 1;
const bool ctrl = rwi->GetControlKey() == 1;
if (shift && ctrl)
{
mod = mod_t::CTRL_SHIFT;
}
else if (ctrl)
{
mod = mod_t::CTRL;
}
else if (shift)
{
mod = mod_t::SHIFT;
}
// Check for an interaction command with modifiers
const interaction_bind_t bind = { mod, interaction };
log::debug("Interaction: KeyPress ", bind.format());
auto commandsIt = this->Bindings.find(bind);
if (commandsIt == this->Bindings.end())
{
// Modifiers version not found, try ANY instead
commandsIt = this->Bindings.find({ mod_t::ANY, interaction });
}
if (commandsIt != this->Bindings.end())
{
for (const std::string& command : commandsIt->second.CommandVector)
{
std::string commandWithArgs = command;
if (!argsString.empty())
{
commandWithArgs.push_back(' ');
commandWithArgs.append(argsString);
};
try
{
// XXX: Ignore the boolean return of triggerCommand,
// error is already logged by triggerCommand
this->Interactor.triggerCommand(commandWithArgs);
}
catch (const f3d::interactor::command_runtime_exception& ex)
{
log::error(
"Interaction: error running command: \"" + commandWithArgs + "\": " + ex.what());
}
}
}
// Always render after interaction
this->Window.render();
}
//----------------------------------------------------------------------------
void StartEventLoop(double deltaTime, std::function<void()> userCallBack)
{
// Trigger a render to ensure Window is ready to be configured
this->Window.render();
// Copy user callback
this->EventLoopUserCallBack = std::move(userCallBack);
// Configure UI delta time
vtkRenderWindow* renWin = this->Window.GetRenderWindow();
vtkF3DRenderer* ren = vtkF3DRenderer::SafeDownCast(renWin->GetRenderers()->GetFirstRenderer());
ren->SetUIDeltaTime(deltaTime);
// Configure animation delta time
this->AnimationManager->SetDeltaTime(deltaTime);
// Create the timer
this->EventLoopTimerId = this->VTKInteractor->CreateRepeatingTimer(deltaTime * 1000);
// Create the callback and add an observer
vtkNew<vtkCallbackCommand> timerCallBack;
timerCallBack->SetCallback(
[](vtkObject*, unsigned long, void* clientData, void*)
{
internals* that = static_cast<internals*>(clientData);
that->EventLoop();
});
this->EventLoopObserverId =
this->VTKInteractor->AddObserver(vtkCommand::TimerEvent, timerCallBack);
timerCallBack->SetClientData(this);
}
//----------------------------------------------------------------------------
void StopEventLoop()
{
this->VTKInteractor->RemoveObserver(this->EventLoopObserverId);
this->VTKInteractor->DestroyTimer(this->EventLoopTimerId);
this->EventLoopObserverId = -1;
this->EventLoopTimerId = 0;
}
//----------------------------------------------------------------------------
void EventLoop()
{
if (this->EventLoopUserCallBack)
{
this->EventLoopUserCallBack();
}
if (this->CommandBuffer.has_value())
{
try
{
// XXX: Ignore the boolean return of triggerCommand,
// error is already logged by triggerCommand
this->Interactor.triggerCommand(this->CommandBuffer.value());
}
catch (const f3d::interactor::command_runtime_exception& ex)
{
log::error("Interaction: error running command: \"" + this->CommandBuffer.value() +
"\": " + ex.what());
}
this->CommandBuffer.reset();
}
this->AnimationManager->Tick();
if (this->RenderRequested)
{
this->Window.render();
this->RenderRequested = false;
}
else
{
this->Window.RenderUIOnly();
}
}
//----------------------------------------------------------------------------
options& Options;
window_impl& Window;
scene_impl& Scene;
interactor_impl& Interactor;
animationManager* AnimationManager;
vtkSmartPointer<vtkRenderWindowInteractor> VTKInteractor;
vtkNew<vtkF3DInteractorStyle> Style;
vtkSmartPointer<vtkF3DInteractorEventRecorder> Recorder;
vtkNew<vtkF3DUIObserver> UIObserver;
std::map<unsigned long, std::pair<int, std::function<void()>>> TimerCallBacks;
std::map<std::string, std::function<void(const std::vector<std::string>&)>> Commands;
std::optional<std::string> CommandBuffer;
std::map<interaction_bind_t, BindingCommands> Bindings;
std::multimap<std::string, interaction_bind_t> GroupedBinds;
std::vector<std::string> OrderedBindGroups;
std::map<std::string, std::string> AliasMap;
vtkNew<vtkCellPicker> CellPicker;
vtkNew<vtkPointPicker> PointPicker;
int MiddleButtonDownPosition[2] = { 0, 0 };
int DragDistanceTol = 3; /* px */
int TransitionDuration = 100; /* ms */
std::function<void()> EventLoopUserCallBack = nullptr;
unsigned long EventLoopTimerId = 0;
int EventLoopObserverId = -1;
std::atomic<bool> RenderRequested = false;
};
//----------------------------------------------------------------------------
interactor_impl::interactor_impl(options& options, window_impl& window, scene_impl& scene)
: Internals(std::make_unique<interactor_impl::internals>(options, window, scene, *this))
{
// scene need the interactor, scene will set the AnimationManager on the interactor
this->Internals->Scene.SetInteractor(this);
this->Internals->Window.SetInteractor(this);
assert(this->Internals->AnimationManager);
this->initCommands();
this->initBindings();
#if F3D_MODULE_UI
vtkF3DImguiConsole* console = vtkF3DImguiConsole::SafeDownCast(vtkOutputWindow::GetInstance());
assert(console != nullptr);
// Set the callback to get the list of commands
console->SetCommandsMatchCallback(
[this](const std::string& pattern)
{
// Build a list of candidates
std::vector<std::string> candidates;
// Copy all commands that start with the pattern
auto startWith = [&pattern](const std::string& s)
{
return s.rfind(pattern, 0) == 0; // To avoid dependency for C++20 starts_with
};
for (auto const& [action, callback] : this->Internals->Commands)
{
if (startWith(action))
{
candidates.push_back(action);
}
else
{
// List is sorted so we can break early
if (!candidates.empty())
{
break;
}
}
}
return candidates;
});
#endif
}
//----------------------------------------------------------------------------
interactor_impl::~interactor_impl()
{
vtkOutputWindow::GetInstance()->RemoveObservers(vtkF3DConsoleOutputWindow::TriggerEvent);
vtkOutputWindow::GetInstance()->RemoveObservers(vtkF3DConsoleOutputWindow::ShowEvent);
vtkOutputWindow::GetInstance()->RemoveObservers(vtkF3DConsoleOutputWindow::HideEvent);
}
//----------------------------------------------------------------------------
interactor& interactor_impl::initCommands()
{
this->Internals->Commands.clear();
const auto check_args =
[&](const std::vector<std::string>& args, size_t expectedSize, std::string_view actionName)
{
if (args.size() != expectedSize)
{
throw interactor::invalid_args_exception(std::string("Command: ") + std::string(actionName) +
" is expecting " + std::to_string(expectedSize) + " arguments");
}
};
// Add default callbacks
this->addCommand("set",
[&](const std::vector<std::string>& args)
{
check_args(args, 2, "set");
this->Internals->Options.setAsString(args[0], args[1]);
});
this->addCommand("toggle",
[&](const std::vector<std::string>& args)
{
check_args(args, 1, "toggle");
this->Internals->Options.toggle(args[0]);
});
this->addCommand("reset",
[&](const std::vector<std::string>& args)
{
check_args(args, 1, "reset");
this->Internals->Options.reset(args[0]);
});
this->addCommand("clear",
[&](const std::vector<std::string>& args)
{
check_args(args, 0, "clear");
#if F3D_MODULE_UI
vtkF3DImguiConsole* console =
vtkF3DImguiConsole::SafeDownCast(vtkOutputWindow::GetInstance());
assert(console != nullptr);
console->Clear();
#endif
});
this->addCommand("print",
[&](const std::vector<std::string>& args)
{
check_args(args, 1, "print");
log::info(this->Internals->Options.getAsString(args[0]));
});
this->addCommand("set_reader_option",
[&](const std::vector<std::string>& args)
{
check_args(args, 2, "set_reader_option");
f3d::engine::setReaderOption(args[0], args[1]);
});
this->addCommand("cycle_animation",
[&](const std::vector<std::string>&)
{
this->Internals->AnimationManager->CycleAnimation();
this->Internals->Options.scene.animation.index =
this->Internals->AnimationManager->GetAnimationIndex();
});
this->addCommand("cycle_anti_aliasing",
[&](const std::vector<std::string>&)
{
bool& enabled = this->Internals->Options.render.effect.antialiasing.enable;
std::string& mode = this->Internals->Options.render.effect.antialiasing.mode;
if (!enabled)
{
enabled = true;
mode = "fxaa";
}
else
{
if (mode == "fxaa")
{
mode = "ssaa";
}
else
{
enabled = false;
}
}
this->Internals->Window.render();
});
this->addCommand("cycle_coloring",
[&](const std::vector<std::string>& args)
{
check_args(args, 1, "cycle_coloring");
std::string_view type = args[0];
vtkRenderWindow* renWin = this->Internals->Window.GetRenderWindow();
vtkF3DRenderer* ren =
vtkF3DRenderer::SafeDownCast(renWin->GetRenderers()->GetFirstRenderer());
if (type == "field")
{
ren->CycleFieldForColoring();
}
else if (type == "array")
{
ren->CycleArrayForColoring();
}
else if (type == "component")
{
ren->CycleComponentForColoring();
}
else
{
throw interactor::invalid_args_exception(std::string("Command: cycle_coloring arg:\"") +
std::string(type) + "\" is not recognized.");
}
this->Internals->SynchronizeScivisOptions(this->Internals->Options, ren);
this->Internals->Window.PrintColoringDescription(log::VerboseLevel::DEBUG);
});
this->addCommand("roll_camera",
[&](const std::vector<std::string>& args)
{
check_args(args, 1, "roll_camera");
this->Internals->Window.getCamera().roll(options::parse<int>(args[0]));
this->Internals->Style->SetTemporaryUp(
this->Internals->Window.getCamera().getViewUp().data());
});
this->addCommand("increase_light_intensity",
[&](const std::vector<std::string>&) { this->Internals->IncreaseLightIntensity(false); });
this->addCommand("decrease_light_intensity",
[&](const std::vector<std::string>&) { this->Internals->IncreaseLightIntensity(true); });
this->addCommand("increase_opacity",
[&](const std::vector<std::string>&) { this->Internals->IncreaseOpacity(false); });
this->addCommand("decrease_opacity",
[&](const std::vector<std::string>&) { this->Internals->IncreaseOpacity(true); });
this->addCommand("print_scene_info", [&](const std::vector<std::string>&)
{ this->Internals->Window.PrintSceneDescription(log::VerboseLevel::INFO); });
this->addCommand("print_coloring_info", [&](const std::vector<std::string>&)
{ this->Internals->Window.PrintColoringDescription(log::VerboseLevel::INFO); });
this->addCommand("print_mesh_info", [&](const std::vector<std::string>&)
{ this->Internals->Scene.PrintImporterDescription(log::VerboseLevel::INFO); });
this->addCommand("print_options_info",
[&](const std::vector<std::string>&)
{
for (const std::string& option : this->Internals->Options.getNames())
{
const std::string val{ this->Internals->Options.getAsString(option) };
std::string descr{};
descr.append(option).append(": ").append(val);
log::print(log::VerboseLevel::INFO, descr);
}
});
this->addCommand("set_camera",
[&](const std::vector<std::string>& args)
{
check_args(args, 1, "set_camera");
std::string_view type = args[0];
if (type == "front")
{
this->Internals->SetViewOrbit(internals::ViewType::VT_FRONT);
this->Internals->Style->ResetTemporaryUp();
}
else if (type == "top")
{
this->Internals->SetViewOrbit(internals::ViewType::VT_TOP);
this->Internals->Style->ResetTemporaryUp();
}
else if (type == "right")
{
this->Internals->SetViewOrbit(internals::ViewType::VT_RIGHT);
this->Internals->Style->ResetTemporaryUp();
}
else if (type == "isometric")
{
this->Internals->SetViewOrbit(internals::ViewType::VT_ISOMETRIC);
this->Internals->Style->ResetTemporaryUp();
}
else
{
throw interactor::invalid_args_exception(
std::string("Command: set_camera arg:\"") + std::string(type) + "\" is not recognized.");
}
});
this->addCommand("toggle_volume_rendering",
[&](const std::vector<std::string>&)
{
this->Internals->Options.model.volume.enable = !this->Internals->Options.model.volume.enable;
this->Internals->Window.render();
this->Internals->Window.PrintColoringDescription(log::VerboseLevel::DEBUG);
});
this->addCommand("stop_interactor", [&](const std::vector<std::string>&) { this->stop(); });
this->addCommand("reset_camera",
[&](const std::vector<std::string>&)
{
this->Internals->Window.getCamera().resetToDefault();
this->Internals->Style->ResetTemporaryUp();
});
this->addCommand("toggle_animation",
[&](const std::vector<std::string>&) { this->Internals->AnimationManager->ToggleAnimation(); });
this->addCommand("add_files",
[&](const std::vector<std::string>& files)
{
this->Internals->AnimationManager->StopAnimation();
this->Internals->Scene.add(files);
});
this->addCommand("alias",
[&](const std::vector<std::string>& args)
{
if (args.size() < 2)
{
throw interactor::invalid_args_exception("alias command requires at least 2 arguments");
}
// Validate the alias arguments
const std::string& aliasName = args[0];
// Combine all remaining arguments into the alias command
// Add alias command to the map
this->Internals->AliasMap[aliasName] = std::accumulate(args.begin() + 2, args.end(),
args[1], // Start with first command argument
[](const std::string& a, const std::string& b) { return a + " " + b; });
log::info(
"Alias " + aliasName + " added with command " + this->Internals->AliasMap[aliasName]);
});
return *this;
}
//----------------------------------------------------------------------------
interactor& interactor_impl::addCommand(
std::string action, std::function<void(const std::vector<std::string>&)> callback)
{
const auto [it, success] =
this->Internals->Commands.insert({ std::move(action), std::move(callback) });
if (!success)
{
throw interactor::already_exists_exception(
"Could not add a command callback for action: " + it->first + " as it already exists.");
}
return *this;
}
//----------------------------------------------------------------------------
interactor& interactor_impl::removeCommand(const std::string& action)
{
this->Internals->Commands.erase(action);
return *this;
}
//----------------------------------------------------------------------------
std::vector<std::string> interactor_impl::getCommandActions() const
{
std::vector<std::string> actions;
for (auto const& [action, callback] : this->Internals->Commands)
{
actions.emplace_back(action);
}
return actions;
}
//----------------------------------------------------------------------------
bool interactor_impl::triggerCommand(std::string_view command)
{
log::debug("Command: ", command);
// Resolve Alias Before Tokenizing
auto aliasIt = this->Internals->AliasMap.find(std::string(command));
if (aliasIt != this->Internals->AliasMap.end())
{
command = aliasIt->second;
}
std::vector<std::string> tokens;
try
{
tokens = utils::tokenize(command);
}
catch (const utils::tokenize_exception&)
{
log::error("Command: unable to tokenize command:\"", command, "\", ignoring");
return false;
}
if (tokens.empty())
{
return true;
}
const std::string& action = tokens[0];
try
{
// Find the right command to call
auto callbackIt = this->Internals->Commands.find(action);
if (callbackIt != this->Internals->Commands.end())
{
callbackIt->second({ tokens.begin() + 1, tokens.end() });
return true;
}
else
{
log::error("Command: \"", action, "\" is not recognized, ignoring");
return false;
}
}
catch (const f3d::options::incompatible_exception&)
{
log::error("Command: provided args in command: \"", command,
"\" are not compatible with action:\"", action, "\", ignoring");
}
catch (const f3d::options::inexistent_exception&)
{
log::error("Command: provided args in command: \"", command,
"\" point to an inexistent option, ignoring");
}
catch (const f3d::options::no_value_exception&)
{
log::error("Command: provided args in command: \"", command,
"\" point to an option without a value, ignoring");