forked from Nelarius/imnodes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imnodes.cpp
3267 lines (2766 loc) · 112 KB
/
imnodes.cpp
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
// the structure of this file:
//
// [SECTION] bezier curve helpers
// [SECTION] draw list helper
// [SECTION] ui state logic
// [SECTION] render helpers
// [SECTION] API implementation
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imnodes.h"
#include "imnodes_internal.h"
#include "imgui.h"
#include "imgui_internal.h"
// Check minimum ImGui version
#define MINIMUM_COMPATIBLE_IMGUI_VERSION 17400
#if IMGUI_VERSION_NUM < MINIMUM_COMPATIBLE_IMGUI_VERSION
#error "Minimum ImGui version requirement not met -- please use a newer version!"
#endif
#include <limits.h>
#include <math.h>
#include <new>
#include <stdint.h>
#include <stdio.h> // for fwrite, ssprintf, sscanf
#include <stdlib.h>
#include <string.h> // strlen, strncmp
// Use secure CRT function variants to avoid MSVC compiler errors
#ifdef _MSC_VER
#define sscanf sscanf_s
#endif
ImNodesContext* GImNodes = NULL;
namespace IMNODES_NAMESPACE
{
namespace
{
// [SECTION] bezier curve helpers
struct CubicBezier
{
ImVec2 P0, P1, P2, P3;
int NumSegments;
};
inline ImVec2 EvalCubicBezier(
const float t,
const ImVec2& P0,
const ImVec2& P1,
const ImVec2& P2,
const ImVec2& P3)
{
// B(t) = (1-t)**3 p0 + 3(1 - t)**2 t P1 + 3(1-t)t**2 P2 + t**3 P3
const float u = 1.0f - t;
const float b0 = u * u * u;
const float b1 = 3 * u * u * t;
const float b2 = 3 * u * t * t;
const float b3 = t * t * t;
return ImVec2(
b0 * P0.x + b1 * P1.x + b2 * P2.x + b3 * P3.x,
b0 * P0.y + b1 * P1.y + b2 * P2.y + b3 * P3.y);
}
// Calculates the closest point along each bezier curve segment.
ImVec2 GetClosestPointOnCubicBezier(const int num_segments, const ImVec2& p, const CubicBezier& cb)
{
IM_ASSERT(num_segments > 0);
ImVec2 p_last = cb.P0;
ImVec2 p_closest;
float p_closest_dist = FLT_MAX;
float t_step = 1.0f / (float)num_segments;
for (int i = 1; i <= num_segments; ++i)
{
ImVec2 p_current = EvalCubicBezier(t_step * i, cb.P0, cb.P1, cb.P2, cb.P3);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist = ImLengthSqr(p - p_line);
if (dist < p_closest_dist)
{
p_closest = p_line;
p_closest_dist = dist;
}
p_last = p_current;
}
return p_closest;
}
inline float GetDistanceToCubicBezier(
const ImVec2& pos,
const CubicBezier& cubic_bezier,
const int num_segments)
{
const ImVec2 point_on_curve = GetClosestPointOnCubicBezier(num_segments, pos, cubic_bezier);
const ImVec2 to_curve = point_on_curve - pos;
return ImSqrt(ImLengthSqr(to_curve));
}
inline ImRect GetContainingRectForCubicBezier(const CubicBezier& cb)
{
const ImVec2 min = ImVec2(ImMin(cb.P0.x, cb.P3.x), ImMin(cb.P0.y, cb.P3.y));
const ImVec2 max = ImVec2(ImMax(cb.P0.x, cb.P3.x), ImMax(cb.P0.y, cb.P3.y));
const float hover_distance = GImNodes->Style.LinkHoverDistance;
ImRect rect(min, max);
rect.Add(cb.P1);
rect.Add(cb.P2);
rect.Expand(ImVec2(hover_distance, hover_distance));
return rect;
}
inline CubicBezier GetCubicBezier(
ImVec2 start,
ImVec2 end,
const ImNodesAttributeType start_type,
const float line_segments_per_length)
{
IM_ASSERT(
(start_type == ImNodesAttributeType_Input) || (start_type == ImNodesAttributeType_Output));
if (start_type == ImNodesAttributeType_Input)
{
ImSwap(start, end);
}
const float link_length = ImSqrt(ImLengthSqr(end - start));
const ImVec2 offset = ImVec2(0.25f * link_length, 0.f);
CubicBezier cubic_bezier;
cubic_bezier.P0 = start;
cubic_bezier.P1 = start + offset;
cubic_bezier.P2 = end - offset;
cubic_bezier.P3 = end;
cubic_bezier.NumSegments = ImMax(static_cast<int>(link_length * line_segments_per_length), 1);
return cubic_bezier;
}
inline float EvalImplicitLineEq(const ImVec2& p1, const ImVec2& p2, const ImVec2& p)
{
return (p2.y - p1.y) * p.x + (p1.x - p2.x) * p.y + (p2.x * p1.y - p1.x * p2.y);
}
inline int Sign(float val) { return int(val > 0.0f) - int(val < 0.0f); }
inline bool RectangleOverlapsLineSegment(const ImRect& rect, const ImVec2& p1, const ImVec2& p2)
{
// Trivial case: rectangle contains an endpoint
if (rect.Contains(p1) || rect.Contains(p2))
{
return true;
}
// Flip rectangle if necessary
ImRect flip_rect = rect;
if (flip_rect.Min.x > flip_rect.Max.x)
{
ImSwap(flip_rect.Min.x, flip_rect.Max.x);
}
if (flip_rect.Min.y > flip_rect.Max.y)
{
ImSwap(flip_rect.Min.y, flip_rect.Max.y);
}
// Trivial case: line segment lies to one particular side of rectangle
if ((p1.x < flip_rect.Min.x && p2.x < flip_rect.Min.x) ||
(p1.x > flip_rect.Max.x && p2.x > flip_rect.Max.x) ||
(p1.y < flip_rect.Min.y && p2.y < flip_rect.Min.y) ||
(p1.y > flip_rect.Max.y && p2.y > flip_rect.Max.y))
{
return false;
}
const int corner_signs[4] = {
Sign(EvalImplicitLineEq(p1, p2, flip_rect.Min)),
Sign(EvalImplicitLineEq(p1, p2, ImVec2(flip_rect.Max.x, flip_rect.Min.y))),
Sign(EvalImplicitLineEq(p1, p2, ImVec2(flip_rect.Min.x, flip_rect.Max.y))),
Sign(EvalImplicitLineEq(p1, p2, flip_rect.Max))};
int sum = 0;
int sum_abs = 0;
for (int i = 0; i < 4; ++i)
{
sum += corner_signs[i];
sum_abs += abs(corner_signs[i]);
}
// At least one corner of rectangle lies on a different side of line segment
return abs(sum) != sum_abs;
}
inline bool RectangleOverlapsBezier(const ImRect& rectangle, const CubicBezier& cubic_bezier)
{
ImVec2 current =
EvalCubicBezier(0.f, cubic_bezier.P0, cubic_bezier.P1, cubic_bezier.P2, cubic_bezier.P3);
const float dt = 1.0f / cubic_bezier.NumSegments;
for (int s = 0; s < cubic_bezier.NumSegments; ++s)
{
ImVec2 next = EvalCubicBezier(
static_cast<float>((s + 1) * dt),
cubic_bezier.P0,
cubic_bezier.P1,
cubic_bezier.P2,
cubic_bezier.P3);
if (RectangleOverlapsLineSegment(rectangle, current, next))
{
return true;
}
current = next;
}
return false;
}
inline bool RectangleOverlapsLink(
const ImRect& rectangle,
const ImVec2& start,
const ImVec2& end,
const ImNodesAttributeType start_type)
{
// First level: simple rejection test via rectangle overlap:
ImRect lrect = ImRect(start, end);
if (lrect.Min.x > lrect.Max.x)
{
ImSwap(lrect.Min.x, lrect.Max.x);
}
if (lrect.Min.y > lrect.Max.y)
{
ImSwap(lrect.Min.y, lrect.Max.y);
}
if (rectangle.Overlaps(lrect))
{
// First, check if either one or both endpoinds are trivially contained
// in the rectangle
if (rectangle.Contains(start) || rectangle.Contains(end))
{
return true;
}
// Second level of refinement: do a more expensive test against the
// link
const CubicBezier cubic_bezier =
GetCubicBezier(start, end, start_type, GImNodes->Style.LinkLineSegmentsPerLength);
return RectangleOverlapsBezier(rectangle, cubic_bezier);
}
return false;
}
// [SECTION] coordinate space conversion helpers
inline ImVec2 ScreenSpaceToGridSpace(const ImNodesEditorContext& editor, const ImVec2& v)
{
return v - GImNodes->CanvasOriginScreenSpace - editor.Panning;
}
inline ImRect ScreenSpaceToGridSpace(const ImNodesEditorContext& editor, const ImRect& r)
{
return ImRect(ScreenSpaceToGridSpace(editor, r.Min), ScreenSpaceToGridSpace(editor, r.Max));
}
inline ImVec2 GridSpaceToScreenSpace(const ImNodesEditorContext& editor, const ImVec2& v)
{
return v + GImNodes->CanvasOriginScreenSpace + editor.Panning;
}
inline ImVec2 GridSpaceToEditorSpace(const ImNodesEditorContext& editor, const ImVec2& v)
{
return v + editor.Panning;
}
inline ImVec2 EditorSpaceToGridSpace(const ImNodesEditorContext& editor, const ImVec2& v)
{
return v - editor.Panning;
}
inline ImVec2 EditorSpaceToScreenSpace(const ImVec2& v)
{
return GImNodes->CanvasOriginScreenSpace + v;
}
inline ImVec2 MiniMapSpaceToGridSpace(const ImNodesEditorContext& editor, const ImVec2& v)
{
return (v - editor.MiniMapContentScreenSpace.Min) / editor.MiniMapScaling +
editor.GridContentBounds.Min;
}
inline ImVec2 ScreenSpaceToMiniMapSpace(const ImNodesEditorContext& editor, const ImVec2& v)
{
return (ScreenSpaceToGridSpace(editor, v) - editor.GridContentBounds.Min) *
editor.MiniMapScaling +
editor.MiniMapContentScreenSpace.Min;
}
inline ImRect ScreenSpaceToMiniMapSpace(const ImNodesEditorContext& editor, const ImRect& r)
{
return ImRect(
ScreenSpaceToMiniMapSpace(editor, r.Min), ScreenSpaceToMiniMapSpace(editor, r.Max));
}
// [SECTION] draw list helper
void ImDrawListGrowChannels(ImDrawList* draw_list, const int num_channels)
{
ImDrawListSplitter& splitter = draw_list->_Splitter;
if (splitter._Count == 1)
{
splitter.Split(draw_list, num_channels + 1);
return;
}
// NOTE: this logic has been lifted from ImDrawListSplitter::Split with slight modifications
// to allow nested splits. The main modification is that we only create new ImDrawChannel
// instances after splitter._Count, instead of over the whole splitter._Channels array like
// the regular ImDrawListSplitter::Split method does.
const int old_channel_capacity = splitter._Channels.Size;
// NOTE: _Channels is not resized down, and therefore _Count <= _Channels.size()!
const int old_channel_count = splitter._Count;
const int requested_channel_count = old_channel_count + num_channels;
if (old_channel_capacity < old_channel_count + num_channels)
{
splitter._Channels.resize(requested_channel_count);
}
splitter._Count = requested_channel_count;
for (int i = old_channel_count; i < requested_channel_count; ++i)
{
ImDrawChannel& channel = splitter._Channels[i];
// If we're inside the old capacity region of the array, we need to reuse the existing
// memory of the command and index buffers.
if (i < old_channel_capacity)
{
channel._CmdBuffer.resize(0);
channel._IdxBuffer.resize(0);
}
// Else, we need to construct new draw channels.
else
{
IM_PLACEMENT_NEW(&channel) ImDrawChannel();
}
{
ImDrawCmd draw_cmd;
draw_cmd.ClipRect = draw_list->_ClipRectStack.back();
draw_cmd.TextureId = draw_list->_TextureIdStack.back();
channel._CmdBuffer.push_back(draw_cmd);
}
}
}
void ImDrawListSplitterSwapChannels(
ImDrawListSplitter& splitter,
const int lhs_idx,
const int rhs_idx)
{
if (lhs_idx == rhs_idx)
{
return;
}
IM_ASSERT(lhs_idx >= 0 && lhs_idx < splitter._Count);
IM_ASSERT(rhs_idx >= 0 && rhs_idx < splitter._Count);
ImDrawChannel& lhs_channel = splitter._Channels[lhs_idx];
ImDrawChannel& rhs_channel = splitter._Channels[rhs_idx];
lhs_channel._CmdBuffer.swap(rhs_channel._CmdBuffer);
lhs_channel._IdxBuffer.swap(rhs_channel._IdxBuffer);
const int current_channel = splitter._Current;
if (current_channel == lhs_idx)
{
splitter._Current = rhs_idx;
}
else if (current_channel == rhs_idx)
{
splitter._Current = lhs_idx;
}
}
void DrawListSet(ImDrawList* window_draw_list)
{
GImNodes->CanvasDrawList = window_draw_list;
GImNodes->NodeIdxToSubmissionIdx.Clear();
GImNodes->NodeIdxSubmissionOrder.clear();
}
// The draw list channels are structured as follows. First we have our base channel, the canvas grid
// on which we render the grid lines in BeginNodeEditor(). The base channel is the reason
// draw_list_submission_idx_to_background_channel_idx offsets the index by one. Each BeginNode()
// call appends two new draw channels, for the node background and foreground. The node foreground
// is the channel into which the node's ImGui content is rendered. Finally, in EndNodeEditor() we
// append one last draw channel for rendering the selection box and the incomplete link on top of
// everything else.
//
// +----------+----------+----------+----------+----------+----------+
// | | | | | | |
// |canvas |node |node |... |... |click |
// |grid |background|foreground| | |interaction
// | | | | | | |
// +----------+----------+----------+----------+----------+----------+
// | |
// | submission idx |
// | |
// -----------------------
void DrawListAddNode(const int node_idx)
{
GImNodes->NodeIdxToSubmissionIdx.SetInt(
static_cast<ImGuiID>(node_idx), GImNodes->NodeIdxSubmissionOrder.Size);
GImNodes->NodeIdxSubmissionOrder.push_back(node_idx);
ImDrawListGrowChannels(GImNodes->CanvasDrawList, 2);
}
void DrawListAppendClickInteractionChannel()
{
// NOTE: don't use this function outside of EndNodeEditor. Using this before all nodes have been
// added will screw up the node draw order.
ImDrawListGrowChannels(GImNodes->CanvasDrawList, 1);
}
int DrawListSubmissionIdxToBackgroundChannelIdx(const int submission_idx)
{
// NOTE: the first channel is the canvas background, i.e. the grid
return 1 + 2 * submission_idx;
}
int DrawListSubmissionIdxToForegroundChannelIdx(const int submission_idx)
{
return DrawListSubmissionIdxToBackgroundChannelIdx(submission_idx) + 1;
}
void DrawListActivateClickInteractionChannel()
{
GImNodes->CanvasDrawList->_Splitter.SetCurrentChannel(
GImNodes->CanvasDrawList, GImNodes->CanvasDrawList->_Splitter._Count - 1);
}
void DrawListActivateCurrentNodeForeground()
{
const int foreground_channel_idx =
DrawListSubmissionIdxToForegroundChannelIdx(GImNodes->NodeIdxSubmissionOrder.Size - 1);
GImNodes->CanvasDrawList->_Splitter.SetCurrentChannel(
GImNodes->CanvasDrawList, foreground_channel_idx);
}
void DrawListActivateNodeBackground(const int node_idx)
{
const int submission_idx =
GImNodes->NodeIdxToSubmissionIdx.GetInt(static_cast<ImGuiID>(node_idx), -1);
// There is a discrepancy in the submitted node count and the rendered node count! Did you call
// one of the following functions
// * EditorContextMoveToNode
// * SetNodeScreenSpacePos
// * SetNodeGridSpacePos
// * SetNodeDraggable
// after the BeginNode/EndNode function calls?
IM_ASSERT(submission_idx != -1);
const int background_channel_idx = DrawListSubmissionIdxToBackgroundChannelIdx(submission_idx);
GImNodes->CanvasDrawList->_Splitter.SetCurrentChannel(
GImNodes->CanvasDrawList, background_channel_idx);
}
void DrawListSwapSubmissionIndices(const int lhs_idx, const int rhs_idx)
{
IM_ASSERT(lhs_idx != rhs_idx);
const int lhs_foreground_channel_idx = DrawListSubmissionIdxToForegroundChannelIdx(lhs_idx);
const int lhs_background_channel_idx = DrawListSubmissionIdxToBackgroundChannelIdx(lhs_idx);
const int rhs_foreground_channel_idx = DrawListSubmissionIdxToForegroundChannelIdx(rhs_idx);
const int rhs_background_channel_idx = DrawListSubmissionIdxToBackgroundChannelIdx(rhs_idx);
ImDrawListSplitterSwapChannels(
GImNodes->CanvasDrawList->_Splitter,
lhs_background_channel_idx,
rhs_background_channel_idx);
ImDrawListSplitterSwapChannels(
GImNodes->CanvasDrawList->_Splitter,
lhs_foreground_channel_idx,
rhs_foreground_channel_idx);
}
void DrawListSortChannelsByDepth(const ImVector<int>& node_idx_depth_order)
{
if (GImNodes->NodeIdxToSubmissionIdx.Data.Size < 2)
{
return;
}
IM_ASSERT(node_idx_depth_order.Size == GImNodes->NodeIdxSubmissionOrder.Size);
int start_idx = node_idx_depth_order.Size - 1;
while (node_idx_depth_order[start_idx] == GImNodes->NodeIdxSubmissionOrder[start_idx])
{
if (--start_idx == 0)
{
// early out if submission order and depth order are the same
return;
}
}
// TODO: this is an O(N^2) algorithm. It might be worthwhile revisiting this to see if the time
// complexity can be reduced.
for (int depth_idx = start_idx; depth_idx > 0; --depth_idx)
{
const int node_idx = node_idx_depth_order[depth_idx];
// Find the current index of the node_idx in the submission order array
int submission_idx = -1;
for (int i = 0; i < GImNodes->NodeIdxSubmissionOrder.Size; ++i)
{
if (GImNodes->NodeIdxSubmissionOrder[i] == node_idx)
{
submission_idx = i;
break;
}
}
IM_ASSERT(submission_idx >= 0);
if (submission_idx == depth_idx)
{
continue;
}
for (int j = submission_idx; j < depth_idx; ++j)
{
DrawListSwapSubmissionIndices(j, j + 1);
ImSwap(GImNodes->NodeIdxSubmissionOrder[j], GImNodes->NodeIdxSubmissionOrder[j + 1]);
}
}
}
// [SECTION] ui state logic
ImVec2 GetScreenSpacePinCoordinates(
const ImRect& node_rect,
const ImRect& attribute_rect,
const ImNodesAttributeType type)
{
IM_ASSERT(type == ImNodesAttributeType_Input || type == ImNodesAttributeType_Output);
const float x = type == ImNodesAttributeType_Input
? (node_rect.Min.x - GImNodes->Style.PinOffset)
: (node_rect.Max.x + GImNodes->Style.PinOffset);
return ImVec2(x, 0.5f * (attribute_rect.Min.y + attribute_rect.Max.y));
}
ImVec2 GetScreenSpacePinCoordinates(const ImNodesEditorContext& editor, const ImPinData& pin)
{
const ImRect& parent_node_rect = editor.Nodes.Pool[pin.ParentNodeIdx].Rect;
return GetScreenSpacePinCoordinates(parent_node_rect, pin.AttributeRect, pin.Type);
}
bool MouseInCanvas()
{
// This flag should be true either when hovering or clicking something in the canvas.
const bool is_window_hovered_or_focused = ImGui::IsWindowHovered() || ImGui::IsWindowFocused();
return is_window_hovered_or_focused &&
GImNodes->CanvasRectScreenSpace.Contains(ImGui::GetMousePos());
}
void BeginNodeSelection(ImNodesEditorContext& editor, const int node_idx)
{
// Don't start selecting a node if we are e.g. already creating and dragging
// a new link! New link creation can happen when the mouse is clicked over
// a node, but within the hover radius of a pin.
if (editor.ClickInteraction.Type != ImNodesClickInteractionType_None)
{
return;
}
editor.ClickInteraction.Type = ImNodesClickInteractionType_Node;
// If the node is not already contained in the selection, then we want only
// the interaction node to be selected, effective immediately.
//
// If the multiple selection modifier is active, we want to add this node
// to the current list of selected nodes.
//
// Otherwise, we want to allow for the possibility of multiple nodes to be
// moved at once.
if (!editor.SelectedNodeIndices.contains(node_idx))
{
editor.SelectedLinkIndices.clear();
if (!GImNodes->MultipleSelectModifier)
{
editor.SelectedNodeIndices.clear();
}
editor.SelectedNodeIndices.push_back(node_idx);
// Ensure that individually selected nodes get rendered on top
ImVector<int>& depth_stack = editor.NodeDepthOrder;
const int* const elem = depth_stack.find(node_idx);
IM_ASSERT(elem != depth_stack.end());
depth_stack.erase(elem);
depth_stack.push_back(node_idx);
}
// Deselect a previously-selected node
else if (GImNodes->MultipleSelectModifier)
{
const int* const node_ptr = editor.SelectedNodeIndices.find(node_idx);
editor.SelectedNodeIndices.erase(node_ptr);
// Don't allow dragging after deselecting
editor.ClickInteraction.Type = ImNodesClickInteractionType_None;
}
// To support snapping of multiple nodes, we need to store the offset of
// each node in the selection to the origin of the dragged node.
const ImVec2 ref_origin = editor.Nodes.Pool[node_idx].Origin;
editor.PrimaryNodeOffset =
ref_origin + GImNodes->CanvasOriginScreenSpace + editor.Panning - GImNodes->MousePos;
editor.SelectedNodeOffsets.clear();
for (int idx = 0; idx < editor.SelectedNodeIndices.Size; idx++)
{
const int node = editor.SelectedNodeIndices[idx];
const ImVec2 node_origin = editor.Nodes.Pool[node].Origin - ref_origin;
editor.SelectedNodeOffsets.push_back(node_origin);
}
}
void BeginLinkSelection(ImNodesEditorContext& editor, const int link_idx)
{
editor.ClickInteraction.Type = ImNodesClickInteractionType_Link;
// When a link is selected, clear all other selections, and insert the link
// as the sole selection.
editor.SelectedNodeIndices.clear();
editor.SelectedLinkIndices.clear();
editor.SelectedLinkIndices.push_back(link_idx);
}
void BeginLinkDetach(ImNodesEditorContext& editor, const int link_idx, const int detach_pin_idx)
{
const ImLinkData& link = editor.Links.Pool[link_idx];
ImClickInteractionState& state = editor.ClickInteraction;
state.Type = ImNodesClickInteractionType_LinkCreation;
state.LinkCreation.EndPinIdx.Reset();
state.LinkCreation.StartPinIdx =
detach_pin_idx == link.StartPinIdx ? link.EndPinIdx : link.StartPinIdx;
GImNodes->DeletedLinkIdx = link_idx;
}
void BeginLinkCreation(ImNodesEditorContext& editor, const int hovered_pin_idx)
{
editor.ClickInteraction.Type = ImNodesClickInteractionType_LinkCreation;
editor.ClickInteraction.LinkCreation.StartPinIdx = hovered_pin_idx;
editor.ClickInteraction.LinkCreation.EndPinIdx.Reset();
editor.ClickInteraction.LinkCreation.Type = ImNodesLinkCreationType_Standard;
GImNodes->ImNodesUIState |= ImNodesUIState_LinkStarted;
}
void BeginLinkInteraction(
ImNodesEditorContext& editor,
const int link_idx,
const ImOptionalIndex pin_idx = ImOptionalIndex())
{
// Check if we are clicking the link with the modifier pressed.
// This will in a link detach via clicking.
const bool modifier_pressed = GImNodes->Io.LinkDetachWithModifierClick.Modifier == NULL
? false
: *GImNodes->Io.LinkDetachWithModifierClick.Modifier;
if (modifier_pressed)
{
const ImLinkData& link = editor.Links.Pool[link_idx];
const ImPinData& start_pin = editor.Pins.Pool[link.StartPinIdx];
const ImPinData& end_pin = editor.Pins.Pool[link.EndPinIdx];
const ImVec2& mouse_pos = GImNodes->MousePos;
const float dist_to_start = ImLengthSqr(start_pin.Pos - mouse_pos);
const float dist_to_end = ImLengthSqr(end_pin.Pos - mouse_pos);
const int closest_pin_idx = dist_to_start < dist_to_end ? link.StartPinIdx : link.EndPinIdx;
editor.ClickInteraction.Type = ImNodesClickInteractionType_LinkCreation;
BeginLinkDetach(editor, link_idx, closest_pin_idx);
editor.ClickInteraction.LinkCreation.Type = ImNodesLinkCreationType_FromDetach;
}
else
{
if (pin_idx.HasValue())
{
const int hovered_pin_flags = editor.Pins.Pool[pin_idx.Value()].Flags;
// Check the 'click and drag to detach' case.
if (hovered_pin_flags & ImNodesAttributeFlags_EnableLinkDetachWithDragClick)
{
BeginLinkDetach(editor, link_idx, pin_idx.Value());
editor.ClickInteraction.LinkCreation.Type = ImNodesLinkCreationType_FromDetach;
}
else
{
BeginLinkCreation(editor, pin_idx.Value());
}
}
else
{
BeginLinkSelection(editor, link_idx);
}
}
}
static inline bool IsMiniMapHovered();
void BeginCanvasInteraction(ImNodesEditorContext& editor)
{
const bool any_ui_element_hovered =
GImNodes->HoveredNodeIdx.HasValue() || GImNodes->HoveredLinkIdx.HasValue() ||
GImNodes->HoveredPinIdx.HasValue() || ImGui::IsAnyItemHovered();
const bool mouse_not_in_canvas = !MouseInCanvas();
if (editor.ClickInteraction.Type != ImNodesClickInteractionType_None ||
any_ui_element_hovered || mouse_not_in_canvas)
{
return;
}
const bool started_panning = GImNodes->AltMouseClicked;
if (started_panning)
{
editor.ClickInteraction.Type = ImNodesClickInteractionType_Panning;
}
else if (GImNodes->LeftMouseClicked)
{
editor.ClickInteraction.Type = ImNodesClickInteractionType_BoxSelection;
editor.ClickInteraction.BoxSelector.Rect.Min =
ScreenSpaceToGridSpace(editor, GImNodes->MousePos);
}
}
void BoxSelectorUpdateSelection(ImNodesEditorContext& editor, ImRect box_rect)
{
// Invert box selector coordinates as needed
if (box_rect.Min.x > box_rect.Max.x)
{
ImSwap(box_rect.Min.x, box_rect.Max.x);
}
if (box_rect.Min.y > box_rect.Max.y)
{
ImSwap(box_rect.Min.y, box_rect.Max.y);
}
// Update node selection
editor.SelectedNodeIndices.clear();
// Test for overlap against node rectangles
for (int node_idx = 0; node_idx < editor.Nodes.Pool.size(); ++node_idx)
{
if (editor.Nodes.InUse[node_idx])
{
ImNodeData& node = editor.Nodes.Pool[node_idx];
if (box_rect.Overlaps(node.Rect))
{
editor.SelectedNodeIndices.push_back(node_idx);
}
}
}
// Update link selection
editor.SelectedLinkIndices.clear();
// Test for overlap against links
for (int link_idx = 0; link_idx < editor.Links.Pool.size(); ++link_idx)
{
if (editor.Links.InUse[link_idx])
{
const ImLinkData& link = editor.Links.Pool[link_idx];
const ImPinData& pin_start = editor.Pins.Pool[link.StartPinIdx];
const ImPinData& pin_end = editor.Pins.Pool[link.EndPinIdx];
const ImRect& node_start_rect = editor.Nodes.Pool[pin_start.ParentNodeIdx].Rect;
const ImRect& node_end_rect = editor.Nodes.Pool[pin_end.ParentNodeIdx].Rect;
const ImVec2 start = GetScreenSpacePinCoordinates(
node_start_rect, pin_start.AttributeRect, pin_start.Type);
const ImVec2 end =
GetScreenSpacePinCoordinates(node_end_rect, pin_end.AttributeRect, pin_end.Type);
// Test
if (RectangleOverlapsLink(box_rect, start, end, pin_start.Type))
{
editor.SelectedLinkIndices.push_back(link_idx);
}
}
}
}
ImVec2 SnapOriginToGrid(ImVec2 origin)
{
if (GImNodes->Style.Flags & ImNodesStyleFlags_GridSnapping)
{
const float spacing = GImNodes->Style.GridSpacing;
const float spacing2 = spacing * 0.5f;
// Snap the origin to the nearest grid point in any direction
float modx = fmodf(fabsf(origin.x) + spacing2, spacing) - spacing2;
float mody = fmodf(fabsf(origin.y) + spacing2, spacing) - spacing2;
origin.x += (origin.x < 0.f) ? modx : -modx;
origin.y += (origin.y < 0.f) ? mody : -mody;
}
return origin;
}
void TranslateSelectedNodes(ImNodesEditorContext& editor)
{
if (GImNodes->LeftMouseDragging)
{
// If we have grid snap enabled, don't start moving nodes until we've moved the mouse
// slightly
const bool shouldTranslate = (GImNodes->Style.Flags & ImNodesStyleFlags_GridSnapping)
? ImGui::GetIO().MouseDragMaxDistanceSqr[0] > 5.0
: true;
const ImVec2 origin = SnapOriginToGrid(
GImNodes->MousePos - GImNodes->CanvasOriginScreenSpace - editor.Panning +
editor.PrimaryNodeOffset);
for (int i = 0; i < editor.SelectedNodeIndices.size(); ++i)
{
const ImVec2 node_rel = editor.SelectedNodeOffsets[i];
const int node_idx = editor.SelectedNodeIndices[i];
ImNodeData& node = editor.Nodes.Pool[node_idx];
if (node.Draggable && shouldTranslate)
{
node.Origin = origin + node_rel + editor.AutoPanningDelta;
}
}
}
}
struct LinkPredicate
{
bool operator()(const ImLinkData& lhs, const ImLinkData& rhs) const
{
// Do a unique compare by sorting the pins' addresses.
// This catches duplicate links, whether they are in the
// same direction or not.
// Sorting by pin index should have the uniqueness guarantees as sorting
// by id -- each unique id will get one slot in the link pool array.
int lhs_start = lhs.StartPinIdx;
int lhs_end = lhs.EndPinIdx;
int rhs_start = rhs.StartPinIdx;
int rhs_end = rhs.EndPinIdx;
if (lhs_start > lhs_end)
{
ImSwap(lhs_start, lhs_end);
}
if (rhs_start > rhs_end)
{
ImSwap(rhs_start, rhs_end);
}
return lhs_start == rhs_start && lhs_end == rhs_end;
}
};
ImOptionalIndex FindDuplicateLink(
const ImNodesEditorContext& editor,
const int start_pin_idx,
const int end_pin_idx)
{
ImLinkData test_link(0);
test_link.StartPinIdx = start_pin_idx;
test_link.EndPinIdx = end_pin_idx;
for (int link_idx = 0; link_idx < editor.Links.Pool.size(); ++link_idx)
{
const ImLinkData& link = editor.Links.Pool[link_idx];
if (LinkPredicate()(test_link, link) && editor.Links.InUse[link_idx])
{
return ImOptionalIndex(link_idx);
}
}
return ImOptionalIndex();
}
bool ShouldLinkSnapToPin(
const ImNodesEditorContext& editor,
const ImPinData& start_pin,
const int hovered_pin_idx,
const ImOptionalIndex duplicate_link)
{
const ImPinData& end_pin = editor.Pins.Pool[hovered_pin_idx];
// The end pin must be in a different node
if (start_pin.ParentNodeIdx == end_pin.ParentNodeIdx)
{
return false;
}
// The end pin must be of a different type
if (start_pin.Type == end_pin.Type)
{
return false;
}
// The link to be created must not be a duplicate, unless it is the link which was created on
// snap. In that case we want to snap, since we want it to appear visually as if the created
// link remains snapped to the pin.
if (duplicate_link.HasValue() && !(duplicate_link == GImNodes->SnapLinkIdx))
{
return false;
}
return true;
}
void ClickInteractionUpdate(ImNodesEditorContext& editor)
{
switch (editor.ClickInteraction.Type)
{
case ImNodesClickInteractionType_BoxSelection:
{
editor.ClickInteraction.BoxSelector.Rect.Max =
ScreenSpaceToGridSpace(editor, GImNodes->MousePos);
ImRect box_rect = editor.ClickInteraction.BoxSelector.Rect;
box_rect.Min = GridSpaceToScreenSpace(editor, box_rect.Min);
box_rect.Max = GridSpaceToScreenSpace(editor, box_rect.Max);
BoxSelectorUpdateSelection(editor, box_rect);
const ImU32 box_selector_color = GImNodes->Style.Colors[ImNodesCol_BoxSelector];
const ImU32 box_selector_outline = GImNodes->Style.Colors[ImNodesCol_BoxSelectorOutline];
GImNodes->CanvasDrawList->AddRectFilled(box_rect.Min, box_rect.Max, box_selector_color);
GImNodes->CanvasDrawList->AddRect(box_rect.Min, box_rect.Max, box_selector_outline);
if (GImNodes->LeftMouseReleased)
{
ImVector<int>& depth_stack = editor.NodeDepthOrder;
const ImVector<int>& selected_idxs = editor.SelectedNodeIndices;
// Bump the selected node indices, in order, to the top of the depth stack.
// NOTE: this algorithm has worst case time complexity of O(N^2), if the node selection
// is ~ N (due to selected_idxs.contains()).
if ((selected_idxs.Size > 0) && (selected_idxs.Size < depth_stack.Size))
{
int num_moved = 0; // The number of indices moved. Stop after selected_idxs.Size
for (int i = 0; i < depth_stack.Size - selected_idxs.Size; ++i)
{
for (int node_idx = depth_stack[i]; selected_idxs.contains(node_idx);
node_idx = depth_stack[i])
{
depth_stack.erase(depth_stack.begin() + static_cast<size_t>(i));
depth_stack.push_back(node_idx);
++num_moved;
}
if (num_moved == selected_idxs.Size)
{
break;
}
}
}
editor.ClickInteraction.Type = ImNodesClickInteractionType_None;
}
}
break;
case ImNodesClickInteractionType_Node:
{
TranslateSelectedNodes(editor);
if (GImNodes->LeftMouseReleased)
{
editor.ClickInteraction.Type = ImNodesClickInteractionType_None;
}
}
break;
case ImNodesClickInteractionType_Link:
{
if (GImNodes->LeftMouseReleased)
{