-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
executable file
·1382 lines (1211 loc) · 55.4 KB
/
main.cpp
File metadata and controls
executable file
·1382 lines (1211 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <imgui.h>
#include <igl/colormap.h>
#include <igl/triangle_triangle_adjacency.h>
#include <string>
#include <iostream>
#include <vector>
#include <utility>
#include <optional>
#include <unordered_set>
#include <array>
#include <filesystem>
#include <igl/edge_exists_near.h>
#include <igl/serialize.h>
#include <igl/file_dialog_open.h>
#include <igl/opengl/glfw/Viewer.h>
#include <igl/opengl/glfw/imgui/ImGuiPlugin.h>
#include <igl/opengl/glfw/imgui/ImGuiMenu.h>
#include <igl/readOBJ.h>
#include <igl/readOFF.h>
#include "imgui_internal.h"
#include "src/mesh.h"
#include "src/selection.hpp"
#include "src/geometry.hpp"
#include "src/isoline_selection.h"
#include "src/app_state.h"
#include "src/user_interface.hpp"
#include "external/ImGuizmo/ImGuizmo.h"
#include "src/deformation.hpp"
// Expanding state serialization
namespace igl::serialization
{
// optional<int>
template<> inline void serialize(const std::optional<int>& obj, std::vector<char>& buffer)
{
::igl::serialize(obj.has_value(), std::string("has_value"), buffer);
if (obj.has_value())
{
::igl::serialize(obj.value(), std::string("value"), buffer);
}
}
template<> inline void deserialize(std::optional<int>& obj, const std::vector<char>& buffer)
{
bool has_value;
::igl::deserialize(has_value, std::string("has_value"), buffer);
if (has_value)
{
int value;
::igl::deserialize(value, std::string("value"),buffer);
obj = value;
} else {
obj = {};
}
}
// optional<VectorXd>
template<> inline void serialize(const std::optional<Eigen::VectorXd>& obj, std::vector<char>& buffer)
{
::igl::serialize(obj.has_value(), std::string("has_value"), buffer);
if (obj.has_value())
{
::igl::serialize(obj.value(), std::string("value"), buffer);
}
}
template<> inline void deserialize(std::optional<Eigen::VectorXd>& obj, const std::vector<char>& buffer)
{
bool has_value;
::igl::deserialize(has_value, std::string("has_value"), buffer);
if (has_value)
{
Eigen::VectorXd value;
::igl::deserialize(obj, std::string("value"),buffer);
obj = value;
} else {
obj = {};
}
}
// optional<ContiguousSelection>
template<> inline void serialize(const std::optional<SelectionRegion>& obj, std::vector<char>& buffer)
{
::igl::serialize(obj.has_value(), std::string("has_value"), buffer);
if (obj.has_value())
{
::igl::serialize(obj.value(), std::string("value"), buffer);
}
}
template<> inline void deserialize(std::optional<SelectionRegion>& obj, const std::vector<char>& buffer)
{
bool has_value;
::igl::deserialize(has_value, std::string("has_value"), buffer);
if (has_value)
{
SelectionRegion value;
::igl::deserialize(value, std::string("value"),buffer);
obj = value;
} else {
obj = {};
}
}
}
using Eigen::Vector2f;
using Eigen::Vector3d, Eigen::Vector3i, Eigen::Vector3f;
using Eigen::VectorXd, Eigen::VectorXi;
using Eigen::MatrixXd, Eigen::MatrixXi;
using igl::opengl::glfw::Viewer;
using igl::opengl::glfw::imgui::ImGuiMenu, igl::opengl::glfw::imgui::ImGuiPlugin;
using std::string;
using std::pair;
using std::optional;
const string TEST_MESH_ARMADILLO = "../data/armadillo0.off";
const string TEST_MESH_TEAPOT = "../data/teapot.obj";
const string TEST_MESH_COW = "../data/cow.off";
const Vector3d SELECTION_COLOR = Vector3d(0, 0, 0);
const Vector3d COLOR_RED(1, 0, 0);
const Vector3d COLOR_GREEN(0, 1, 0);
const Vector3d COLOR_BLUE(0, 0, 1);
const Vector3d COLOR_LIGHT_RED(.8, .3 , .3);
const Vector3d COLOR_LIGHT_GREEN(0.53, 0.85, 0.5);
Viewer viewer;
AppState appState;
enum ViewerData
{
DATA_IDX_MESH = 0,
DATA_IDX_SELECTION_ISOLINES = 1,
DATA_IDX_BBOX = 2,
DATA_IDX_EXPANSION_ISOLINES = 3,
};
void set_colors(MatrixXd& color_arr, const std::vector<int>& items, const Vector3d& color)
{
for (const int idx: items) { color_arr.row(idx) = color; }
}
void set_colors(MatrixXd& color_arr, const std::unordered_set<int>& items, const Vector3d& color)
{
for (const int idx: items) { color_arr.row(idx) = color; }
}
void set_colors(MatrixXd& color_arr, const Eigen::VectorXi& items, const Vector3d& color)
{
for (const int idx: items) { color_arr.row(idx) = color; }
}
MatrixXd
highlight_selection(const Mesh& mesh, const MeshSelection& selection)
{
MatrixXd colors = MatrixXd::Constant(mesh.faces.rows(), 3, 1);
set_colors(colors, selection.faces, COLOR_RED);
return colors;
}
void color_deform_handles(
const SelectionRegion& fixed,
const SelectionRegion& handle,
MatrixXd& colors)
{
set_colors(colors, fixed.interior.faces, COLOR_LIGHT_RED);
set_colors(colors, fixed.boundary.faces, COLOR_RED);
set_colors(colors, handle.interior.faces, COLOR_LIGHT_GREEN);
set_colors(colors, handle.boundary.faces, COLOR_GREEN);
}
void show_candidate_isolines()
{
if (!appState.initialCandidates.has_value()) return;
const auto& isolines = appState.initialCandidates->candidates;
viewer.data().clear_edges();
const Eigen::RowVector3d COLOR_DEBUG_LINE(1, 0, 1);
const Eigen::RowVector3d COLOR_SELECTED_LINE(0, 1, 0);
for (int i = 0; i < NB_ISOLINES; i++) {
const auto color = i == appState.initialCandidates->currCandidateIdx ? COLOR_SELECTED_LINE : COLOR_DEBUG_LINE;
debug_draw_line(viewer, isolines[i].points, color);
}
}
/* ====================================================================
* =============== State (De)Serialization ============================
* ====================================================================
*/
bool load_mesh(const string filename, Mesh& targetMesh) {
// @TODO: Load OBJ / OFF automatically without having to worry about it
if (filename.rfind(".off") == filename.size() - 4) {
std::cout << "Loading OFF file: " << filename << std::endl;
igl::readOFF(filename, targetMesh.vertices, targetMesh.faces);
} else if (filename.rfind(".obj") == filename.size() - 4) {
std::cout << "Loading OBJ file: " << filename << std::endl;
igl::readOBJ(filename, targetMesh.vertices, targetMesh.faces);
} else {
std::cerr << "load_mesh: Unknown file extension!" << std::endl;
return false;
}
std::cout << "Post loading - precomputing conformal map" << std::endl;
igl::triangle_triangle_adjacency(targetMesh.faces, targetMesh.faceNeighbors);
targetMesh.faceColors = MatrixXd::Constant(targetMesh.faces.rows(), 3, 1);
targetMesh.conformalMap = compute_conformal_map(appState.mesh);
targetMesh.boundingBox = BoundingBox::from_points(targetMesh.vertices);
std::vector<std::vector<int>> _VFI;
igl::vertex_triangle_adjacency(targetMesh.vertices, targetMesh.faces, targetMesh.vertexAdjacentFaces, _VFI);
std::cout << "Loaded mesh has approximate size of " << targetMesh.approx_size_in_bytes() / (1024.f * 1024.f) << "MB" << std::endl;
return true;
}
void serialize_state()
{
igl::serialize(appState,"appState","stored_state",true);
}
void deserialize_state()
{
igl::deserialize(appState, "appState", "stored_state");
viewer.data().clear();
}
/* ===================================================================
* =============== Rendering & UI Updating ============================
* ====================================================================
*/
void color_current_selection(MatrixXd& colors)
{
// Color reference selection & expansions
// const auto& initialFaces = appState.initialSelection->selectedFaces;
const auto& initialFaces = appState.initialCandidates->currSel.interior.faces;
set_colors(colors, initialFaces, COLOR_BLUE);
for (int i = 0; i < appState.selectionExpansionCounter; i++) {
set_colors(colors, appState.candidateExpansions[i].interior.faces, COLOR_BLUE);
}
}
void render_current_selection()
{
if (!appState.initialCandidates.has_value())
return;
const Vector3d COLOR_SELECTED(1, 0, 0);
const Vector3d COLOR_EXPANSION(1, 0, 0);
// Color selected faces & reference selection
MatrixXd colors = MatrixXd::Constant(appState.mesh.faces.rows(), 3, 1);
// const auto& initialFaces = appState.initialSelection->selectedFaces;
const auto& initialFaces = appState.initialCandidates->currSel.interior.faces;
set_colors(colors, initialFaces, COLOR_SELECTED);
for (int i = 0; i < appState.selectionExpansionCounter; i++) {
set_colors(colors, appState.candidateExpansions[i].interior.faces, COLOR_EXPANSION);
}
viewer.data().set_colors(colors);
}
void update_viewer()
{
// Render mesh
viewer.data().set_mesh(appState.mesh.vertices, appState.mesh.faces);
viewer.data().set_face_based(true);
viewer.data().clear_labels();
viewer.data().clear_points();
MatrixXd meshColors = appState.mesh.faceColors;
// Render selected points
bool points_set = false;
if (appState.showSelectionBoundaryConditions) {
MatrixXd colorMatrix = MatrixXd::Constant(2 * appState.boundaryStrokes.size(), 3, 0);
MatrixXd pointMatrix = MatrixXd::Constant(2 * appState.boundaryStrokes.size(), 3, 1);
int rowCount = 0;
for (auto const& stroke : appState.boundaryStrokes) {
const Vector3d& pStart = appState.mesh.vertices.row(stroke.first);
const Vector3d& pEnd = appState.mesh.vertices.row(stroke.second);
pointMatrix.row(rowCount) = pStart.transpose();
colorMatrix.row(rowCount) = COLOR_BLUE;
rowCount++;
pointMatrix.row(rowCount) = pEnd.transpose();
colorMatrix.row(rowCount) = COLOR_RED;
rowCount++;
}
if (points_set) {
viewer.data().add_points(pointMatrix, colorMatrix);
} else {
viewer.data().set_points(pointMatrix, colorMatrix);
points_set = true;
}
}
if (appState.showMeshBoundingBox) {
MatrixXd colors(8, 3);
colors.rowwise() = COLOR_RED.transpose();
colors.row(0) = COLOR_GREEN;
bool isLocalTransfom = appState.transformMode & (TRANSFORM_TRANSLATE_LOCAL | TRANSFORM_RESIZE_LOCAL);
const BoundingBox& bbox = (isLocalTransfom && appState.has_initial_selection())
? appState.initialCandidates->currSel.interior.box : appState.mesh.boundingBox;
if (points_set) {
viewer.data().add_points(bbox.vertices(), colors);
} else {
viewer.data().set_points(bbox.vertices(), colors);
points_set = true;
}
if (appState.showMeshBoundingBoxLabels) {
snprintf(appState.bboxMinString, STR_BUFFER_LEN, "(%.3f, %.3f, %.3f)", bbox.min.x(), bbox.min.y(), bbox.min.z());
snprintf(appState.bboxMaxString, STR_BUFFER_LEN, "(%.3f, %.3f, %.3f)", bbox.max.x(), bbox.max.y(), bbox.max.z());
viewer.data().add_label(bbox.min, appState.bboxMinString);
viewer.data().add_label(bbox.max, appState.bboxMaxString);
}
}
if (appState.has_initial_selection() && appState.showSelectionIsocontours) {
show_candidate_isolines();
} else {
// TODO: Would be cleaner to separate this into a separate data(DATA_IDX_ISOLINES) "slot"
viewer.data().clear_edges();
}
if (// appState.handleRegion.has_value() &&
appState.handleRegion.has_value()) {
set_colors(meshColors, appState.handleRegion->interior.faces, COLOR_LIGHT_GREEN);
set_colors(meshColors, appState.handleRegion->boundary.faces, COLOR_GREEN);
}
if (// appState.fixedRegion.has_value() &&
appState.fixedRegion.has_value()) {
set_colors(meshColors, appState.fixedRegion->interior.faces, COLOR_LIGHT_RED);
set_colors(meshColors, appState.fixedRegion->boundary.faces, COLOR_RED);
}
if (auto maybeDeformSel = appState.get_current_deform_selection();
maybeDeformSel.has_value()) {
color_deform_handles(maybeDeformSel->fixedRegion, maybeDeformSel->handleRegion, meshColors);
}
if (appState.has_initial_selection()) {
color_current_selection(meshColors);
}
viewer.data().set_colors(meshColors);
}
void clean_slate()
{
// Reset selection brush & constraints
appState.brushStroke = {};
appState.strokeStart = {};
appState.strokeEnd = {};
appState.boundaryStrokes.clear();
// Reset Generated harmonic field
appState.selectionHarmonicField = {};
// Reset selection candidates & expansion counter
appState.initialCandidates = {};
appState.candidateExpansions.clear();
appState.selectionExpansionCounter = 0;
appState.deformExpansions.clear();
appState.debugDeformExpansionIdx = 0;
// reset fixed & handle regions
appState.handleRegion = {};
appState.fixedRegion = {};
viewer.data().clear();
update_viewer();
}
void update_gizmo_bounds(const BoundingBox& box)
{
const Vector3f& bbmin = box.min.cast<float>();
const Vector3f& bbmax = box.max.cast<float>();
appState.resizeGizmoBounds = {
bbmin.x(), bbmin.y(), bbmin.z(),
bbmax.x(), bbmax.y(), bbmax.z()
};
// Reset the gizmo transform matrix
appState.resizeGizmoTransformMatrix = MAT_4X4_IDENTITY;
}
void apply_transform(const Eigen::Matrix4d& transform, Mesh& mesh) {
// Apply a transform to the whole mesh
const int numVertices = mesh.vertices.rows();
// Copy old vertices into temporary matrix
MatrixXd tempVertices = MatrixXd::Constant(numVertices, 4, 1);
tempVertices.block(0, 0, numVertices, 3) = mesh.vertices.block(0, 0, numVertices, 3);
// Transform temporary matrix & put back
MatrixXd deformedShape = transform * tempVertices.transpose();
mesh.vertices.block(0, 0, numVertices, 3) = deformedShape.transpose().block(0, 0, numVertices, 3);
// Update bounding box
mesh.boundingBox = BoundingBox::from_points(mesh.vertices);
}
void apply_transform(const Eigen::Matrix4d& transform, Mesh& mesh, const MeshSelection& selection) {
// Modify vertices in selection
for (int v : selection.vertices) {
const Eigen::Vector4d pos = mesh.vertices.row(v).homogeneous();
mesh.vertices.row(v) = (transform * pos).head<3>();
}
// Update the bounding box
mesh.boundingBox = BoundingBox::from_points(mesh.vertices);
}
bool selection_compute_candidates()
{
if (!appState.has_initial_selection()) {
std::cerr << "No initial selection" << std::endl;
return false;
}
if (appState.brushStroke.empty()) {
std::cerr << "BrushStroke contains no points" << std::endl;
return false;
}
// ContiguousSelection& initialSel = appState.initialSelection.value();
auto& initialSel = appState.initialCandidates->currSel;
std::vector<IsolineCandidate> candidateIsolines = compute_expansion_candidates(
appState.mesh, initialSel, appState.brushStroke, appState.candidateExpansions);
show_candidate_isolines();
return true;
}
bool expand_and_render_selection()
{
// Expand selection
if (!appState.selectionHarmonicField.has_value() || !appState.has_initial_selection()) {
std::cout << "Cannot expand: Reference selection does not exist" << std::endl;
return false;
}
if (appState.candidateExpansions.size() <= appState.selectionExpansionCounter) {
std::cout << "Cannot expand: Maximum number of expansions selected" << std::endl;
return false;
}
appState.selectionExpansionCounter++;
render_current_selection();
return true;
}
void gizmo_apply_transform(MeshSelection& handle)
{
using Eigen::Matrix4d;
BoundingBox& bbox = handle.box;
// Apply transform to mesh & handle bbox
// Transform to origin, then apply transform.
const Matrix4d gizmoTransform = ImGui_matrix_to_Eigen(appState.resizeGizmoTransformMatrix.data());
const Matrix4d mat_t = translation_matrix(bbox.min);
const Matrix4d mat_ti = translation_matrix(-bbox.min);
// This looks a little weird:
// - Since the gizmo transform is located at bbox.min, we need to undo this transformation.
// - We need to apply transformations center-origined. This does not matter for translations, but it does for rotations/scaling.
// For translation the outer terms cancel out. For rotations they do not.
const Matrix4d composedTransform = mat_t * gizmoTransform * mat_ti * mat_ti;
apply_transform(composedTransform, appState.mesh, handle);
compute_bounding_box_from_vertex_selection(appState.mesh, handle.vertices, handle.box);
}
/* ===================================================================
* =============== Algorithmics =======================================
* ====================================================================
*/
void test_triangle_adjacency(Viewer& viewer, Mesh& mesh) {
std::optional<std::tuple<int, Vector3f>> maybe_pick = pick_mouse(viewer, mesh);
if (!maybe_pick.has_value()) {
return;
}
auto [face_id, bary_coords] = maybe_pick.value();
VectorXi neighbours = mesh.faceNeighbors.row(face_id);
// Color current face red, and all neighbours blue
mesh.faceColors.row(face_id) << 1, 0, 0;
set_colors(mesh.faceColors, neighbours, COLOR_BLUE);
viewer.data().set_colors(mesh.faceColors);
}
/* ====================================================================
* =============== Event handlers =====================================
* ====================================================================
*/
bool key_down(Viewer& viewer, unsigned char key, int modifier)
{
std::cout << "Key press " << (int) key << std::endl;
if (key == KEY_F1) {
appState.showDefaultMenu = !appState.showDefaultMenu;
} if (key == KEY_F4) { // F4 {
std::cout << "Entering debugger" << std::endl;
} else if (key == KEY_B) { // F5 : Brush across (pick) trigger
std::cout << "Entering brush mode" << std::endl;
appState.mode = MODE_BRUSH_ALONG;
} else if (key == KEY_F6) { // F6 : Compute harmonic map (debug - Solve for laplacians)
bool result = selection_find_initial(appState, viewer, SELECTION_COMPUTE_HARMONIC);
if (result) {
return true;
}
// render_current_selection();
update_viewer();
} else if (key == KEY_F7) { // F7 : Find selection (Debug)
bool result = selection_find_initial(appState, viewer, SELECTION_COMPUTE_INITIAL_SELECTION);
if (result) {
return true;
}
// render_current_selection();
update_viewer();
} else if (key == KEY_F8) { // F8 : Clean selection
clean_slate();
} else if (key == KEY_F10) { // F10
bool result = selection_compute_candidates();
if (result) {
return true;
}
} else if (key == KEY_1) { // key 1 : Brush mode across trigger
appState.mode = MODE_BRUSH_ALONG;
clean_slate();
} else if (key == KEY_5) { // key 5
load_mesh(TEST_MESH_TEAPOT, appState.mesh);
clean_slate();
} else if (key == KEY_6) {
load_mesh(TEST_MESH_COW, appState.mesh);
} else if (key == KEY_NUMPAD_PLUS) { // numpad +
bool result = expand_and_render_selection();
if (result) {
return true;
}
} else if (key == 'N') {
test_triangle_adjacency(viewer, appState.mesh);
} else if (key == KEY_H) {
appState.assign_handle();
update_viewer();
} else if (key == KEY_F) {
appState.assign_fixed();
update_viewer();
}
// Exit brush mode on every other keystroke
if (key != KEY_F5 && appState.mode == MODE_BRUSH_ACROSS) {
std::cout << "Exiting brush mode" << std::endl;
appState.mode = MODE_NONE;
}
return appState.showDefaultMenu;
// return false;
}
bool mouse_down(Viewer& viewer, int button, int modifier)
{
if (appState.mode == MODE_BRUSH_ACROSS) {
const optional<int> vert_select = find_selected_vertex(appState.mesh, viewer);
if (!vert_select.has_value()) {
return false;
}
if (!appState.strokeStart.has_value()) {
appState.strokeStart = vert_select;
} else if (!appState.strokeEnd.has_value()) {
appState.strokeEnd = vert_select;
}
if (appState.strokeStart.has_value()
&& appState.strokeEnd.has_value()) {
appState.push_current_stroke();
}
update_viewer();
return true;
}
if (appState.mode == MODE_BRUSH_ALONG) {
appState.dragging = true;
}
if (appState.mode == MODE_TEST) {
// Mode case for small tests & experiments
test_triangle_adjacency(viewer, appState.mesh);
return true;
}
if (appState.mode == MODE_PICK) {
std::optional<std::tuple<int, Vector3f>> maybe_pick = pick_mouse(viewer, appState.mesh);
appState.selectedTriangle = maybe_pick.has_value() ? std::optional(std::get<0>(*maybe_pick)) : std::nullopt;
return appState.selectedTriangle.has_value();
}
return false;
}
bool mouse_up(Viewer& viewer, int button, int modifier)
{
appState.dragging = false;
if (appState.mode == MODE_BRUSH_ALONG
&& brush_select_mouse_release(appState)) {
update_viewer();
return true;
}
// if (ImGuizmo::IsUsing() && appState.transformMode == TRANSFORM_ROTATE_LOCAL) {
// gizmo_reset_to_point(appState, appState.handleRegion->interior.box.min);
// }
return false;
}
bool mouse_move(Viewer& viewer, int mouse_x, int mouse_y)
{
if (ImGuizmo::IsUsing()){
return true;
}
if (appState.dragging && appState.mode == MODE_BRUSH_ALONG) {
brush_select_mouse_move(viewer, appState);
return true;
}
return false;
}
void compute_deform_expansions()
{
if (!appState.has_boundary_selection(BOUNDARY_TYPE_BOTH)) {
return;
}
assert(appState.fixedRegion->contains(*appState.handleRegion));
// Compute the fixed region expansions
const Mesh& mesh = appState.mesh;
const auto& initialFixed = appState.fixedRegion.value();
const auto& initialHandle = appState.handleRegion.value();
std::vector<SelectionRegion> candidateFixedExpansions;
compute_expansion_candidates(mesh, initialFixed, {}, candidateFixedExpansions);
std::vector<DeformSelection> expansions;
for (const SelectionRegion& cFixedExp : candidateFixedExpansions) {
// Find within expansion region, the region that best matches the initHandle region
std::vector<SelectionRegion> candidateHandleExpansions;
compute_expansion_candidates(mesh, initialHandle, {}, candidateHandleExpansions, cFixedExp.interior.faces);
if (candidateHandleExpansions.empty()) {
std::cout << "No handle expansion candidates found for expansion region" << std::endl;
continue;
}
std::cout << "Found deformation expansion" << std::endl;
// Add this to the set of candidates
DeformSelection ds;
ds.fixedRegion = cFixedExp;
ds.handleRegion = candidateHandleExpansions[0];
expansions.push_back(ds);
}
appState.deformExpansions = expansions;
}
void gui_section_expansion_deform(Viewer& viewer) {
if (!appState.has_boundary_selection(BOUNDARY_TYPE_BOTH))
return;
if (!ImGui::CollapsingHeader("Handle Expansion", ImGuiTreeNodeFlags_DefaultOpen))
return;
float w = ImGui::GetContentRegionAvail().x;
float p = ImGui::GetStyle().FramePadding.x;
if (ImGui::Button("Compute expansion candidates")) {
compute_deform_expansions();
}
if (appState.deformExpansions.empty()) {
return;
}
constexpr auto TABLE_FLAGS = ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; // | ImGuiTableFlags_Resizable;
const float MIN_ROW_HEIGHT = ImGui::GetTextLineHeightWithSpacing() + 5;
const ImVec2 TABLE_SIZE = ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing()+ 5*MIN_ROW_HEIGHT);
if (ImGui::BeginTable("##DeformExpansionTable", 3, TABLE_FLAGS, TABLE_SIZE)) {
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("#F (fixed)", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("#F (handle)", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableHeadersRow(); // Render the headers
ImGuiListClipper clipper;
clipper.Begin(appState.deformExpansions.size());
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) {
// Render rows for each Deform expansion candidate
ImGui::PushID(i);
DeformSelection & c = appState.deformExpansions[i];
char label[32];
snprintf(label, 32, "%d##selIC", i);
ImGui::TableNextRow(ImGuiTableRowFlags_None, MIN_ROW_HEIGHT);
ImGui::TableNextColumn();
ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap;
if (ImGui::Selectable(label, i == appState.debugDeformExpansionIdx, selectable_flags, ImVec2(0, MIN_ROW_HEIGHT))) {
appState.debugDeformExpansionIdx = i;
MatrixXd colors = MatrixXd::Constant(appState.mesh.faces.rows(), 3, 1);
color_deform_handles(c.fixedRegion, c.handleRegion, colors);
viewer.data().set_colors(colors);
// update_viewer();
}
ImGui::TableNextColumn();
ImGui::Text("%zu", c.fixedRegion.interior.faces.size());
ImGui::TableNextColumn();
ImGui::Text("%zu", c.handleRegion.interior.faces.size());
ImGui::PopID();
}
}
ImGui::EndTable();
if (appState.is_selected_expansion_valid() && ImGui::Button("Select Expansion")) {
std::cout << "Moving expansion to selection " << std::endl;
appState.move_selected_expansion_to_selection();
update_viewer();
}
}
}
void gui_section_expansion(Viewer& viewer) {
if (!appState.has_initial_selection())
return;
if (!ImGui::CollapsingHeader("Selection Expansion", ImGuiTreeNodeFlags_DefaultOpen))
return;
float w = ImGui::GetContentRegionAvail().x;
float p = ImGui::GetStyle().FramePadding.x;
if (ImGui::Button("Compute expansion candidates")) {
selection_compute_candidates();
}
if (!appState.has_expansions())
return;
if (ImGui::Button("Expand Selection")) {
expand_and_render_selection();
}
auto& reference = appState.initialCandidates->currSel;
const ImVec2 GRAPH_SIZE(100, 40);
const auto fn_access = [](void* data, int idx) { return static_cast<float>(static_cast<double *>(data)[idx]); };
// Draw the expansion candidate table.
constexpr auto TABLE_FLAGS = ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg; // | ImGuiTableFlags_Resizable;
const float MIN_ROW_HEIGHT = GRAPH_SIZE.y + 5;
const ImVec2 TABLE_SIZE = ImVec2(-FLT_MIN, ImGui::GetTextLineHeightWithSpacing()+ 5*MIN_ROW_HEIGHT);
if (ImGui::BeginTable("##ExpansionTable", 4, TABLE_FLAGS, TABLE_SIZE)) {
// Headers
ImGui::TableSetupScrollFreeze(0, 2);
ImGui::TableSetupColumn("ID", ImGuiTableColumnFlags_WidthFixed);
char histLabel[32];
snprintf(histLabel, 32, "Hist (#bins=%zu)", reference.descriptor.size());
ImGui::TableSetupColumn(histLabel, ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("#F", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableSetupColumn("Area", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableHeadersRow(); // Render the headers
ImGuiListClipper clipper;
clipper.Begin(appState.candidateExpansions.size());
// Reference selection
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::Text("Ref");
ImGui::TableNextColumn();
ImGui::PlotLines("##refplot", fn_access, reference.descriptor.data(), reference.descriptor.size(),
0, nullptr, FLT_MAX, FLT_MAX, GRAPH_SIZE);
ImGui::TableNextColumn();
ImGui::Text("%zu", reference.interior.faces.size());
ImGui::TableNextColumn();
ImGui::Text("%.3f", reference.totalArea);
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) {
ImGui::PushID(i);
SelectionRegion& c = appState.candidateExpansions[i];
char label[32];
snprintf(label, 32, "%d##selIC", i);
ImGui::TableNextRow(ImGuiTableRowFlags_None, MIN_ROW_HEIGHT);
ImGui::TableNextColumn();
ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap;
if (ImGui::Selectable(label, i == appState.debugSelectionExpansionIdx, selectable_flags, ImVec2(0, MIN_ROW_HEIGHT))) {
appState.debugSelectionExpansionIdx = i;
MatrixXd colors = MatrixXd::Constant(appState.mesh.faces.rows(), 3, 1);
set_colors(colors, c.interior.faces, COLOR_GREEN);
viewer.data().set_colors(colors);
// update_viewer();
}
ImGui::TableNextColumn();
ImGui::PlotLines("##DescHist", fn_access, c.descriptor.data(), c.descriptor.size(),
0, nullptr, FLT_MAX, FLT_MAX, GRAPH_SIZE);
ImGui::TableNextColumn();
ImGui::Text("%zu", c.interior.faces.size());
ImGui::TableNextColumn();
ImGui::Text("%.3f", c.totalArea);
ImGui::PopID();
}
}
ImGui::EndTable();
}
}
void gui_section_selection(Viewer& viewer) {
if (!ImGui::CollapsingHeader("Selection", ImGuiTreeNodeFlags_DefaultOpen))
return;
float w = ImGui::GetContentRegionAvail().x;
float p = ImGui::GetStyle().FramePadding.x;
float window_hw = (w-p)/2.f; // half width
float window_w = w - p;
if (ImGui::Button("Brush Select (B)", ImVec2(window_hw, 0))) {
appState.mode = MODE_BRUSH_ALONG;
}
if (!appState.brushStroke.empty()) {
ImGui::SameLine(0, p);
if (ImGui::Button("Clear brush", ImVec2(window_hw, 0))) {
appState.clear_selection_brush();
update_viewer();
}
}
if (appState.has_selection_stroke()
&& ImGui::Button("Compute Selection", ImVec2(window_w, 0))) {
selection_find_initial(appState, viewer);
update_viewer();
}
if (ImGui::Button("Clear all", ImVec2(window_w, 0))) {
clean_slate();
}
if (appState.has_initial_selection()) {
ImGui::Text("ARAP");
if (ImGui::Button("-> fixed (a)", ImVec2(window_hw, 0))) {
std::cout << "Assigned selection to fixed region" << std::endl;
appState.assign_fixed();
update_viewer();
}
ImGui::SameLine(0, p);
if (ImGui::Button("-> handle (h)", ImVec2(window_hw, 0))) {
std::cout << "Assigned selection to handle region" << std::endl;
appState.assign_handle();
update_viewer();
}
}
ImGui::Separator();
if (appState.initialCandidates.has_value()
&& ImGui::TreeNode("Isoline candidates")) {
IsolineCandidates& c = appState.initialCandidates.value();
constexpr auto TABLE_FLAGS = ImGuiTableFlags_Borders; // | ImGuiTableFlags_Resizable;
const ImVec2 TABLE_SIZE = ImVec2(-FLT_MIN, 5*ImGui::GetTextLineHeightWithSpacing());
if (ImGui::BeginTable("##ChosenIsoline", 4, TABLE_FLAGS, TABLE_SIZE)) {
for (int i = 0; i < NB_ISOLINES; ++i) {
char label[32];
snprintf(label, 32, "%d##selIC", i);
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable(label, i == c.currCandidateIdx, ImGuiSelectableFlags_SpanAllColumns)) {
c.currCandidateIdx = i;
appState.switch_candidate(i);
update_viewer();
}
ImGui::TableNextColumn();
ImGui::Text("%.4f", c.candidates[i].isoValue);
ImGui::TableNextColumn();
ImGui::Text("%zu", c.candidates[i].faces.size());
ImGui::TableNextColumn();
const ImVec4 color = (i == c.bestCandidateIdx) ? ImVec4{0, 1, 0, 1} : ImVec4{1, 1, 1, 1};
ImGui::TextColored(color, "%.3f", c.scores[i]);
}
ImGui::EndTable();
}
ImGui::TreePop();
}
}
template<typename T>
void imgui_saveload_object(
const std::string label,
const std::optional<T>& data,
const std::filesystem::path fileDir,
std::function<void(const T&)> load_callback)
{
namespace fs = std::filesystem;
const bool isDirValid = fs::exists(fileDir) && fs::is_directory(fileDir);
if (isDirValid && ImGui::TreeNode(label.c_str())) {
if (data.has_value() && ImGui::Button("Save current")) {
igl::serialize(*data, (fileDir / "dumped_file.bin").c_str());
}
for (const auto& entry : fs::directory_iterator(fileDir)) {
bool isBinFile = entry.is_regular_file() && entry.path().extension() == ".bin";
if (!isBinFile) { continue; }
if (ImGui::Button(entry.path().filename().c_str())) {
std::cout << "Loading state from file" << std::endl;
T load_obj;
igl::deserialize(load_obj, entry.path().string().c_str());
load_callback(load_obj);
}
}
ImGui::TreePop();
}
}
void gui_section_settings(Viewer& viewer) {
if (!ImGui::CollapsingHeader("Settings"))
return;
const char* solverOptions[] = { "Direct", "Least Squares" };
ImGui::ListBox("Solver", reinterpret_cast<int*>(&appState.solver), solverOptions, 2);
if (ImGui::TreeNode("ARAP Settings")) {
if (ImGui::BeginListBox("ARAP Mode", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()*3))) {
if (ImGui::Selectable("Spokes", appState.arapEnergyType == igl::ARAP_ENERGY_TYPE_SPOKES)) {
appState.arapEnergyType = igl::ARAP_ENERGY_TYPE_SPOKES;
}
if (ImGui::Selectable("Spokes and Rims", appState.arapEnergyType == igl::ARAP_ENERGY_TYPE_SPOKES_AND_RIMS)) {
appState.arapEnergyType = igl::ARAP_ENERGY_TYPE_SPOKES_AND_RIMS;
}
if (ImGui::Selectable("Elements", appState.arapEnergyType == igl::ARAP_ENERGY_TYPE_ELEMENTS)) {
appState.arapEnergyType = igl::ARAP_ENERGY_TYPE_ELEMENTS;
}
ImGui::EndListBox();
}
ImGui::Checkbox("Use dynamics", &appState.arapUseDynamics);
ImGui::InputFloat("Youngs modulus", &appState.arapYoungsModulus);
ImGui::InputFloat("Dynamics timestep", &appState.arapDynamicsTimestep);
ImGui::InputInt("Max iters", &appState.arapMaxIters);
ImGui::TreePop();
}
ImGui::InputFloat("Isoline selection sigma", &appState.isoselectionSigma);
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip("Convolution kernel width, see section 3.1 of \"Mesh Decomposition with Cross-boundary brushes\"");
}
ImGui::InputFloat("Stroke offset distance", &appState.strokeOffsetDistance);
if (ImGui::IsItemHovered()) {
ImGui::SetTooltip("offset of placed boundary conditions for stroke points, see section 4.2 of \"SimSelect: Similarity-based selection for 3D surfaces\"");
}
}
void gui_section_debug_options(Viewer& viewer) {
if (!ImGui::CollapsingHeader("Debug"))
return;
float w = ImGui::GetContentRegionAvail().x;
float p = ImGui::GetStyle().FramePadding.x;
float window_hw = (w-p)/2.f; // half width
// Debugging utilities (put in separate section?)
if (ImGui::Checkbox("Show Selection bdry conditions", &appState.showSelectionBoundaryConditions)) {
update_viewer();
}
// Load / Save state functionality
ImGui::Text("State serialization");
if (ImGui::Button("Load##State", ImVec2(window_hw, 0))) {
std::cout << "Loading serialized state" << std::endl;
deserialize_state();
update_viewer();
}
ImGui::SameLine(0, p);
if (ImGui::Button("Save##State", ImVec2(window_hw, 0))) {
// std::cout << "Saving temporarily disabled for safety" << std::endl;
std::cout << "Saving serialized state" << std::endl;
serialize_state();
}
ImGui::Spacing();
if (ImGui::Button("Load Mesh", ImVec2(window_hw, 0))) {
std::string fname = igl::file_dialog_open();
if (fname.length() == 0) {
return;
}
load_mesh(fname, appState.mesh);
clean_slate();
}
if (ImGui::Button("Show conformal map")) {
std::cout << "Rendering Conformal map" << std::endl;
MatrixXd Colors;
igl::colormap(igl::COLOR_MAP_TYPE_JET, appState.mesh.conformalMap, true, Colors);
viewer.data().set_colors(Colors);
}
if (ImGui::Button("Dbg: Compute Harmonic Field")) {