forked from intel/gvk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.cpp
More file actions
1514 lines (1275 loc) · 59.5 KB
/
Copy pathnodes.cpp
File metadata and controls
1514 lines (1275 loc) · 59.5 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 "nodes.h"
#include "TileCache.h"
#include "GPURenderer.h"
#include "Debug.h"
#include <algorithm>
#include <unordered_map>
#include <chrono>
namespace ImGui
{
// Pre-linearize a color for the RGB565 tiles. The old tile format (GL_SRGB8_ALPHA8) converted
// sRGB->linear when sampled during compositing, which darkens mid-tones; RGB565 stores linear and
// does NO conversion, so baked colors read brighter/flatter. Baking pow(c, 2.2) into the color
// values reproduces that darkening so tile content looks ~like it did before. Whites/blacks are
// unchanged (only mid-tones move); alpha is left alone. Approximate (2.2 gamma vs true sRGB curve)
// and does not affect RGB565's separate 5-6 bit banding. Apply ONLY to tile-baked colors - overlay
// colors draw to the sRGB-ish default framebuffer and never shifted.
static inline ImVec4 LinearizeForTile(const ImVec4& c) {
return ImVec4(powf(c.x, 2.2f), powf(c.y, 2.2f), powf(c.z, 2.2f), c.w);
}
template<int n>
struct BezierWeights
{
constexpr BezierWeights() : x_(), y_(), z_(), w_()
{
for (int i = 1; i <= n; ++i)
{
float t = (float)i / (float)(n + 1);
float u = 1.0f - t;
x_[i - 1] = u * u * u;
y_[i - 1] = 3 * u * u * t;
z_[i - 1] = 3 * u * t * t;
w_[i - 1] = t * t * t;
}
}
float x_[n];
float y_[n];
float z_[n];
float w_[n];
};
static constexpr auto bezier_weights_ = BezierWeights<16>();
float ImVec2Dot(const ImVec2& S1, const ImVec2& S2)
{
return (S1.x * S2.x + S1.y * S2.y);
}
float GetSquaredDistancePointSegment(const ImVec2& P, const ImVec2& S1, const ImVec2& S2)
{
const float l2 = (S1.x - S2.x) * (S1.x - S2.x) + (S1.y - S2.y) * (S1.y - S2.y);
if (l2 < 1.0f)
{
return (P.x - S2.x) * (P.x - S2.x) + (P.y - S2.y) * (P.y - S2.y);
}
ImVec2 PS1(P.x - S1.x, P.y - S1.y);
ImVec2 T(S2.x - S1.x, S2.y - S2.y);
const float tf = ImVec2Dot(PS1, T) / l2;
const float minTf = 1.0f < tf ? 1.0f : tf;
const float t = 0.0f > minTf ? 0.0f : minTf;
T.x = S1.x + T.x * t;
T.y = S1.y + T.y * t;
return (P.x - T.x) * (P.x - T.x) + (P.y - T.y) * (P.y - T.y);
}
float GetSquaredDistanceToBezierCurve(const ImVec2& point, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4)
{
float minSquaredDistance = FLT_MAX;
float tmp;
ImVec2 L = p1;
ImVec2 temp;
for (int i = 1; i < 16 - 1; ++i)
{
const ImVec4& W = ImVec4(bezier_weights_.x_[i], bezier_weights_.y_[i], bezier_weights_.z_[i], bezier_weights_.w_[i]);
temp.x = W.x * p1.x + W.y * p2.x + W.z * p3.x + W.w * p4.x;
temp.y = W.x * p1.y + W.y * p2.y + W.z * p3.y + W.w * p4.y;
tmp = GetSquaredDistancePointSegment(point, L, temp);
if (minSquaredDistance > tmp)
{
minSquaredDistance = tmp;
}
L = temp;
}
tmp = GetSquaredDistancePointSegment(point, L, p4);
if (minSquaredDistance > tmp)
{
minSquaredDistance = tmp;
}
return minSquaredDistance;
}
NodeView* GraphView::CreateNodeFromDesc(NodeViewDesc* desc, ImVec2 pos)
{
NodeView* node = new NodeView(desc->name_, desc->type_);
ImVec2 inputs;
ImVec2 outputs;
////////////////////////////////////////////////////////////////////////////////
for (int input_idx = 0; input_idx < ImGuiNodesConnectionsMaxNumber; ++input_idx)
{
if (desc->inputs_[input_idx].type_ == ImGuiNodesConnectorType_None)
break;
NodesInput* input = new NodesInput(desc->inputs_[input_idx].name_, desc->inputs_[input_idx].type_);
inputs.x = ImMax(inputs.x, input->area_input_.GetWidth());
inputs.y += input->area_input_.GetHeight();
node->inputs_.push_back(input);
}
for (int output_idx = 0; output_idx < ImGuiNodesConnectionsMaxNumber; ++output_idx)
{
if (desc->outputs_[output_idx].type_ == ImGuiNodesConnectorType_None)
break;
NodesOutput* output = new NodesOutput(desc->outputs_[output_idx].name_, desc->outputs_[output_idx].type_);
outputs.x = ImMax(outputs.x, output->area_output_.GetWidth());
outputs.y += output->area_output_.GetHeight();
node->outputs_.push_back(output);
}
////////////////////////////////////////////////////////////////////////////////
node->BuildNodeGeometry(inputs, outputs);
node->TranslateNode(pos); //
node->state_ |= NodeStateFlag_Visible | NodeStateFlag_Hovered;
return node;
}
// Retrieves cached NodeView for the given nodeID, or creates and caches it if not found
NodeView* GraphView::GetNodeView(const GraphData::Node& dataNode, ImVec2 position) {
auto it = ImGui::GraphView::nodeViewCache_.find(dataNode.id);
if (it != nodeViewCache_.end()) {
// Update hierarchy state even for cached nodes (expand state may have changed)
it->second->isExpandable = dataNode.isExpandable;
it->second->isExpanded = layoutEngine->IsExpanded(dataNode.id);
// Update position from LayoutEngine (source of truth for both layout and drag)
if (layoutEngine->HasNodePosition(dataNode.id)) {
ImVec2 layoutPos = layoutEngine->GetNodePosition(dataNode.id);
ImVec2 delta = layoutPos - it->second->area_node_.Min;
if (delta.x != 0.0f || delta.y != 0.0f) {
it->second->TranslateNode(delta);
}
}
return it->second; // Return cached object
}
// Create new NodeView from relevant dataNode data
NodeViewDesc desc = {};
strncpy(desc.name_, dataNode.name.c_str(), ImGuiNodesNamesMaxLen - 1);
desc.name_[ImGuiNodesNamesMaxLen - 1] = '\0';
//desc.type_ = NodeType_Generic; //When we introduce node types, use this
// Map inputs
for (size_t i = 0; i < dataNode.inputs.size() && i < ImGuiNodesConnectionsMaxNumber; i++) {
strncpy(desc.inputs_[i].name_, dataNode.inputs[i].name.c_str(), 31);
desc.inputs_[i].name_[31] = '\0';
desc.inputs_[i].type_ = MapPortTypeToConnectorType(dataNode.inputs[i].type);
}
// Map outputs
for (size_t i = 0; i < dataNode.outputs.size() && i < ImGuiNodesConnectionsMaxNumber; i++) {
strncpy(desc.outputs_[i].name_, dataNode.outputs[i].name.c_str(), 31);
desc.outputs_[i].name_[31] = '\0';
desc.outputs_[i].type_ = MapPortTypeToConnectorType(dataNode.outputs[i].type);
}
NodeView* viewNode = CreateNodeFromDesc(&desc, position);
// Note: viewNode->name_ already set by CreateNodeFromDesc (points to desc.name_)
// Do NOT reassign here to dataNode.name.c_str() - that would create a dangling pointer!
viewNode->nodeId = dataNode.id;
// Copy hierarchy state for expand/collapse indicator
viewNode->isExpandable = dataNode.isExpandable;
viewNode->isExpanded = layoutEngine->IsExpanded(dataNode.id);
// Apply dynamic size from LayoutEngine by rebuilding geometry
ImVec2 calculatedSize = layoutEngine->GetNodeSize(dataNode.id);
// Calculate current input/output sizes
ImVec2 inputsSize(0, 0);
ImVec2 outputsSize(0, 0);
for (const auto* input : viewNode->inputs_) {
inputsSize.x = ImMax(inputsSize.x, input->area_input_.GetWidth());
inputsSize.y += input->area_input_.GetHeight();
}
for (const auto* output : viewNode->outputs_) {
outputsSize.x = ImMax(outputsSize.x, output->area_output_.GetWidth());
outputsSize.y += output->area_output_.GetHeight();
}
// Force the node to be EXACTLY the width LayoutEngine calculated
// BuildNodeGeometry calculates: width = inputsSize.x + outputsSize.x + separator
// We need: finalWidth = desiredWidth
// So: inputsSize.x + outputsSize.x = desiredWidth - separator
float separator = ImGuiNodesHSeparation * viewNode->area_name_.GetHeight();
float desiredWidth = calculatedSize.x;
float desiredIOWidth = desiredWidth - separator;
// Scale inputs and outputs proportionally to fill desired width
float currentIOWidth = inputsSize.x + outputsSize.x;
if (currentIOWidth > 0) {
float scale = desiredIOWidth / currentIOWidth;
inputsSize.x *= scale;
outputsSize.x *= scale;
} else {
// No inputs/outputs - split width evenly
inputsSize.x = desiredIOWidth * 0.5f;
outputsSize.x = desiredIOWidth * 0.5f;
}
// Reset area_name_ to origin before rebuilding (BuildNodeGeometry uses relative Translate)
ImVec2 nameSize = viewNode->area_name_.GetSize();
viewNode->area_name_.Min = ImVec2(0.0f, 0.0f);
viewNode->area_name_.Max = nameSize;
// Rebuild geometry with adjusted dimensions
viewNode->BuildNodeGeometry(inputsSize, outputsSize);
viewNode->TranslateNode(position);
nodeViewCache_[dataNode.id] = viewNode;
return viewNode;
}
// Helper to map DataModel PortType to ImGui ConnectorType
ImGuiNodesConnectorType GraphView::MapPortTypeToConnectorType(GraphData::PortType portType) {
switch (portType) {
case GraphData::PortType::INT: return ImGuiNodesConnectorType_Int;
case GraphData::PortType::FLOAT: return ImGuiNodesConnectorType_Float;
case GraphData::PortType::BOOL: return ImGuiNodesConnectorType_Bool;
default: return ImGuiNodesConnectorType_Generic;
}
}
// Builds connection cache from DataModel to avoid 2M map lookups per frame
// Includes connection substitution for expanded nodes (port mapping)
void GraphView::BuildConnectionCache() {
nodes_connections_.clear();
connection_lookup_.clear();
// Build cached connections from DataModel with substitution
for (const auto& conn : dataModel->GetConnections()) {
int actualSrcNodeId = conn.sourceNodeId;
int actualSrcPort = conn.sourcePortIndex;
int actualDstNodeId = conn.targetNodeId;
int actualDstPort = conn.targetPortIndex;
// Substitute source if parent is expanded
if (layoutEngine->IsExpanded(conn.sourceNodeId)) {
const GraphData::Node* child = dataModel->FindChildProvidingOutputPort(
conn.sourceNodeId, conn.sourcePortIndex);
if (!child) continue; // No child provides this port = hidden connection
actualSrcNodeId = child->id;
actualSrcPort = dataModel->FindChildPortIndex(child->parentOutputPortMap, conn.sourcePortIndex);
if (actualSrcPort < 0) continue; // Port mapping failed
}
// Substitute target if parent is expanded
if (layoutEngine->IsExpanded(conn.targetNodeId)) {
const GraphData::Node* child = dataModel->FindChildAcceptingInputPort(
conn.targetNodeId, conn.targetPortIndex);
if (!child) continue; // No child accepts this port = hidden connection
actualDstNodeId = child->id;
actualDstPort = dataModel->FindChildPortIndex(child->parentInputPortMap, conn.targetPortIndex);
if (actualDstPort < 0) continue; // Port mapping failed
}
// Look up cached NodeView objects for actual (substituted) nodes
auto srcIt = nodeViewCache_.find(actualSrcNodeId);
auto dstIt = nodeViewCache_.find(actualDstNodeId);
// Skip if either node not in cache (not active)
if (srcIt == nodeViewCache_.end() || dstIt == nodeViewCache_.end())
continue;
NodeView* srcView = srcIt->second;
NodeView* dstView = dstIt->second;
// Validate port indices
if (actualSrcPort >= srcView->outputs_.size() ||
actualDstPort >= dstView->inputs_.size())
continue;
// Build connection pair with cached pointers
NodesConnectionPair connPair;
connPair.output_node = srcView;
connPair.output = srcView->outputs_[actualSrcPort];
connPair.input_node = dstView;
connPair.input = dstView->inputs_[actualDstPort];
connPair.state = ImGuiNodesConnectionStateFlag_Default;
nodes_connections_.push_back(connPair);
connection_lookup_[{connPair.input, connPair.output}] =
&nodes_connections_.back();
}
}
// Resolve every edge to its final world-space GPUConnectionData ONCE. This is the tile-invariant
// half of the old per-tile edge loop (expand/collapse substitution, GetEdgeRoutePoints, port-position
// lookups, control-point packing). Tiles then only run the cheap per-tile bbox cull over the result,
// so a 200k-node bake stops re-resolving ~1M edges for each of ~75 tiles. Requires nodeViewCache_ to
// be populated (connector positions come from it), which RenderToTile guarantees before calling this.
// Recompute one cached edge's polyline + bbox from the CURRENT node/connector positions. Uses the
// resolved ids/ports already stored on `ce` (set during the full build), so it does NO substitution -
// just routing + endpoint snap + control-point packing. This is the per-edge unit both the full build
// and the incremental drag refresh share.
void GraphView::ResolveEdgeGeometry(CachedEdge& ce) {
std::vector<ImVec2> routePoints = layoutEngine->GetEdgeRoutePoints(ce.srcNodeId, ce.dstNodeId);
if (routePoints.size() < 2) { ce.numPoints = 0; return; }
// Snap endpoints to the real port connectors (read straight from the NodeViews - no map).
auto srcIt = nodeViewCache_.find(ce.srcNodeId);
if (srcIt != nodeViewCache_.end() && srcIt->second &&
ce.srcPort >= 0 && ce.srcPort < srcIt->second->outputs_.size() &&
srcIt->second->outputs_[ce.srcPort])
routePoints[0] = srcIt->second->outputs_[ce.srcPort]->pos_;
auto dstIt = nodeViewCache_.find(ce.dstNodeId);
if (dstIt != nodeViewCache_.end() && dstIt->second &&
ce.dstPort >= 0 && ce.dstPort < dstIt->second->inputs_.size() &&
dstIt->second->inputs_[ce.dstPort])
routePoints.back() = dstIt->second->inputs_[ce.dstPort]->pos_;
// World-space route bbox, padded for the GPU control-point bow (±50px). Precomputed so the
// per-tile cull is a single ImRect overlap test instead of a re-scan of the polyline.
ImVec2 bbMin = routePoints[0], bbMax = routePoints[0];
for (const ImVec2& p : routePoints) {
bbMin.x = ImMin(bbMin.x, p.x); bbMin.y = ImMin(bbMin.y, p.y);
bbMax.x = ImMax(bbMax.x, p.x); bbMax.y = ImMax(bbMax.y, p.y);
}
const float kEdgeCullMargin = 64.0f;
ce.bbMin = ImVec2(bbMin.x - kEdgeCullMargin, bbMin.y - kEdgeCullMargin);
ce.bbMax = ImVec2(bbMax.x + kEdgeCullMargin, bbMax.y + kEdgeCullMargin);
// Store the polyline in the shared pool. An edge keeps its slot across re-resolves (a drag moves
// points but can't change the route's point COUNT, since that's set by the layers it crosses), so
// the incremental drag path writes in place and the pool never grows during a drag. Only a first
// resolve, or the rare count change, appends - the stale slot is then abandoned, which BuildEdge-
// RenderCache's full rebuild reclaims.
if (ce.numPoints != (uint32_t)routePoints.size()) {
ce.pointOffset = (uint32_t)edgePointPool_.size();
ce.numPoints = (uint32_t)routePoints.size();
edgePointPool_.resize(ce.pointOffset + ce.numPoints);
}
for (uint32_t i = 0; i < ce.numPoints; i++)
edgePointPool_[ce.pointOffset + i] = routePoints[i];
ce.color = ImGui::ColorConvertFloat4ToU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
ce.thickness = 2.0f; // world-space width; the shader scales by zoom
}
// Copy a cached polyline into the fixed-size struct the shaders read. A deep edge accrues one dummy
// waypoint per crossed layer and can exceed the cap; never truncate (that strands the far endpoint) -
// keep the exact endpoints and evenly subsample the interior.
void GraphView::FillGPUConnection(const CachedEdge& ce, GPUConnectionData& out) const {
out = GPUConnectionData{};
const ImVec2* pts = &edgePointPool_[ce.pointOffset];
if (ce.numPoints <= (uint32_t)MAX_EDGE_POINTS) {
for (uint32_t i = 0; i < ce.numPoints; i++)
out.controlPoints[i] = pts[i];
out.numPoints = ce.numPoints;
} else {
const size_t last = ce.numPoints - 1;
out.controlPoints[0] = pts[0];
out.controlPoints[MAX_EDGE_POINTS - 1] = pts[last];
for (int i = 1; i < MAX_EDGE_POINTS - 1; i++) {
float t = (float)i / (float)(MAX_EDGE_POINTS - 1);
size_t srcIdx = (size_t)(t * (float)last + 0.5f);
if (srcIdx == 0) srcIdx = 1;
if (srcIdx >= last) srcIdx = last - 1;
out.controlPoints[i] = pts[srcIdx];
}
out.numPoints = MAX_EDGE_POINTS;
}
out.color = ce.color;
out.thickness = ce.thickness;
}
void GraphView::BuildEdgeRenderCache() {
edgeRenderCache_.clear();
edgeIndexByNode_.clear();
edgeRenderCache_.reserve(dataModel->GetConnections().size());
// Reclaims any slots abandoned by point-count changes since the last full build.
edgePointPool_.clear();
// Most edges are straight (2 points); deeper routes just grow the pool from here.
edgePointPool_.reserve(dataModel->GetConnections().size() * 2);
for (const auto& conn : dataModel->GetConnections()) {
int srcNodeId = conn.sourceNodeId;
int dstNodeId = conn.targetNodeId;
int srcPort = conn.sourcePortIndex;
int dstPort = conn.targetPortIndex;
// Expand/collapse port substitution (mirrors BuildConnectionCache). Done ONCE here; the
// incremental drag refresh reuses the resolved ids/ports and skips this.
if (layoutEngine->IsExpanded(srcNodeId)) {
const GraphData::Node* child = dataModel->FindChildProvidingOutputPort(srcNodeId, conn.sourcePortIndex);
if (child) {
srcNodeId = child->id;
srcPort = dataModel->FindChildPortIndex(child->parentOutputPortMap, conn.sourcePortIndex);
} else continue;
}
if (layoutEngine->IsExpanded(dstNodeId)) {
const GraphData::Node* child = dataModel->FindChildAcceptingInputPort(dstNodeId, conn.targetPortIndex);
if (child) {
dstNodeId = child->id;
dstPort = dataModel->FindChildPortIndex(child->parentInputPortMap, conn.targetPortIndex);
} else continue;
}
CachedEdge ce;
ce.srcNodeId = srcNodeId; ce.dstNodeId = dstNodeId;
ce.srcPort = srcPort; ce.dstPort = dstPort;
ResolveEdgeGeometry(ce);
if (ce.numPoints < 2) continue; // unroutable (missing endpoints) - drop it
int idx = (int)edgeRenderCache_.size();
edgeRenderCache_.push_back(ce);
edgeIndexByNode_[srcNodeId].push_back(idx);
if (dstNodeId != srcNodeId) edgeIndexByNode_[dstNodeId].push_back(idx);
}
}
void GraphView::TileRangeForRect(const ImVec2& mn, const ImVec2& mx,
int& x0, int& y0, int& x1, int& y1) {
const int TS = TileCache::TILE_SIZE;
// Integer division truncates toward zero, so negative coords would fold onto tile 0 and put
// off-world geometry in the origin tile's bucket. Clamp instead - TileCache's grid starts at 0.
x0 = mn.x < 0.0f ? 0 : (int)(mn.x / TS);
y0 = mn.y < 0.0f ? 0 : (int)(mn.y / TS);
x1 = mx.x < 0.0f ? 0 : (int)(mx.x / TS);
y1 = mx.y < 0.0f ? 0 : (int)(mx.y / TS);
}
// Bucket every visible node into the tiles its rect overlaps. Runs once per bake instead of the
// old whole-graph scan per tile (see nodeIdsByTile_).
void GraphView::BuildNodeBuckets() {
nodeIdsByTile_.clear();
for (const auto& pair : nodeViewCache_) {
const NodeView* node = pair.second;
if (!(node->state_ & NodeStateFlag_Visible))
continue; // same filter the per-tile rect loop used
int x0, y0, x1, y1;
TileRangeForRect(node->area_node_.Min, node->area_node_.Max, x0, y0, x1, y1);
for (int ty = y0; ty <= y1; ++ty)
for (int tx = x0; tx <= x1; ++tx)
nodeIdsByTile_[std::make_pair(tx, ty)].push_back(pair.first);
}
}
// Bucket every cached edge into the tiles its (already padded) route bbox overlaps.
void GraphView::MarkBucketOverride(const std::vector<int>& movedNodeIds) {
for (int nodeId : movedNodeIds) {
bucketOverrideNodeIds_.insert(nodeId);
auto it = edgeIndexByNode_.find(nodeId);
if (it == edgeIndexByNode_.end()) continue;
for (int idx : it->second) {
if (std::find(bucketOverrideEdgeIdxs_.begin(), bucketOverrideEdgeIdxs_.end(), idx)
== bucketOverrideEdgeIdxs_.end())
bucketOverrideEdgeIdxs_.push_back(idx);
}
}
}
void GraphView::BuildEdgeBuckets() {
edgeIdxByTile_.clear();
// A full rebuild re-buckets from current positions, so the drag overrides are absorbed.
bucketOverrideNodeIds_.clear();
bucketOverrideEdgeIdxs_.clear();
for (int i = 0; i < (int)edgeRenderCache_.size(); ++i) {
const CachedEdge& ce = edgeRenderCache_[i];
int x0, y0, x1, y1;
TileRangeForRect(ce.bbMin, ce.bbMax, x0, y0, x1, y1);
for (int ty = y0; ty <= y1; ++ty)
for (int tx = x0; tx <= x1; ++tx)
edgeIdxByTile_[std::make_pair(tx, ty)].push_back(i);
}
}
void GraphView::RefreshEdgeGeometryForNodes(const std::vector<int>& movedNodeIds) {
if (!edgeRenderCacheValid_ || edgeRenderCache_.empty()) return; // nothing built yet -> full build will run
for (int nodeId : movedNodeIds) {
auto it = edgeIndexByNode_.find(nodeId);
if (it == edgeIndexByNode_.end()) continue;
for (int idx : it->second)
ResolveEdgeGeometry(edgeRenderCache_[idx]);
}
}
void GraphView::ProcessNodes()
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ImVec2 offset = pos_ + world_shift_;
////////////////////////////////////////////////////////////////////////////////
ImGui::SetWindowFontScale(scale_);
// Check if culling is enabled (culling_rect_ has non-zero area)
bool use_culling = (culling_rect_.GetWidth() > 0.0f && culling_rect_.GetHeight() > 0.0f);
int nodes_culled = 0;
int nodes_rendered = 0;
// Track expanded parent nodes to draw boundaries
std::vector<int> expandedParentIds;
// First pass: Render active nodes (root + expanded children)
std::vector<const GraphData::Node*> activeNodes = layoutEngine->GetActiveNodes(*dataModel);
for (const GraphData::Node* dataNode : activeNodes)
{
// Get position + size from LayoutEngine
ImVec2 pos = layoutEngine->GetNodePosition(dataNode->id);
NodeView* viewNode = GetNodeView(*dataNode, pos);
// Track if this node's parent is expanded (to draw boundary later)
if (dataNode->parentId != -1 && layoutEngine->IsExpanded(dataNode->parentId)) {
// Check if we've already added this parent
if (std::find(expandedParentIds.begin(), expandedParentIds.end(), dataNode->parentId) == expandedParentIds.end()) {
expandedParentIds.push_back(dataNode->parentId);
}
}
// culling world space nodes out if outside of tile space
if (use_culling && !culling_rect_.Overlaps(viewNode->area_node_)) {
nodes_culled++;
continue;
}
nodes_rendered++;
viewNode->DrawNode(draw_list, offset, scale_);
}
// Draw subgraph boundaries for expanded parents (found in first pass)
for (int parentId : expandedParentIds) {
const GraphData::Node* parent = dataModel->GetNode(parentId);
if (!parent) continue;
// Calculate bounding box of all children
ImVec2 min(FLT_MAX, FLT_MAX);
ImVec2 max(-FLT_MAX, -FLT_MAX);
for (int childId : parent->childNodeIds) {
ImRect childBounds = layoutEngine->GetNodeBounds(childId);
if (childBounds.GetWidth() > 0) { // Valid bounds
min.x = ImMin(min.x, childBounds.Min.x);
min.y = ImMin(min.y, childBounds.Min.y);
max.x = ImMax(max.x, childBounds.Max.x);
max.y = ImMax(max.y, childBounds.Max.y);
}
}
// Add padding around subgraph
float padding = 20.0f;
min.x -= padding;
min.y -= padding;
max.x += padding;
max.y += padding;
// Transform to screen space
ImVec2 screenMin = (min * scale_) + offset;
ImVec2 screenMax = (max * scale_) + offset;
// Draw dark blue boundary with some transparency
draw_list->AddRect(screenMin, screenMax,
ImColor(0.2f, 0.3f, 0.8f, 0.6f), 0.0f, 0, 3.0f * scale_);
// Draw filled rect with low alpha for visual grouping
draw_list->AddRectFilled(screenMin, screenMax,
ImColor(0.2f, 0.3f, 0.8f, 0.1f));
}
// Second pass: Render connections (now that all NodeViews exist)
// Build connection cache if needed (avoids 2M map lookups per frame)
if (!connectionCacheValid_) {
BuildConnectionCache();
connectionCacheValid_ = true;
}
// Render connections from cached array (fast!)
for (const auto& conn : nodes_connections_)
{
// Calculate Bezier control points in world space (before transform)
ImVec2 p1_world = conn.input->pos_;
ImVec2 p2_world = p1_world + ImVec2(-50.0f, 0.0f);
ImVec2 p4_world = conn.output->pos_;
ImVec2 p3_world = p4_world + ImVec2(+50.0f, 0.0f);
// Cull connections: check if edge bounding box overlaps culling rect
if (use_culling)
{
// Calculate bounding box of all 4 Bezier control points
ImVec2 edgeMin(ImMin(ImMin(p1_world.x, p2_world.x), ImMin(p3_world.x, p4_world.x)),
ImMin(ImMin(p1_world.y, p2_world.y), ImMin(p3_world.y, p4_world.y)));
ImVec2 edgeMax(ImMax(ImMax(p1_world.x, p2_world.x), ImMax(p3_world.x, p4_world.x)),
ImMax(ImMax(p1_world.y, p2_world.y), ImMax(p3_world.y, p4_world.y)));
ImRect edgeBounds(edgeMin, edgeMax);
// Skip if edge bounding box doesn't overlap culling rect
if (!culling_rect_.Overlaps(edgeBounds))
continue;
}
// Transform to screen space
ImVec2 p1 = offset + (p1_world * scale_);
ImVec2 p2 = offset + (p2_world * scale_);
ImVec2 p3 = offset + (p3_world * scale_);
ImVec2 p4 = offset + (p4_world * scale_);
// Draw connection with state-based color
if (conn.state == ImGuiNodesConnectionStateFlag_Hovered)
draw_list->AddBezierCubic(p1, p2, p3, p4, ImColor(1.0f, 0.7f, 0.0f, 1.0f), 2.0f * scale_);
else
draw_list->AddBezierCubic(p1, p2, p3, p4, ImColor(1.0f, 1.0f, 1.0f, 1.0f), 2.0f * scale_);
}
//DELETE ME
//for (int node_idx = 0; node_idx < nodes_.size(); ++node_idx)
//{
// NodeView* node = nodes_[node_idx];
//
// // Cull nodes: skip if node is outside the culling rect
// if (use_culling && !culling_rect_.Overlaps(node->area_node_))
// {
// nodes_culled++;
// continue;
// }
//
// node->DrawNode(draw_list, offset, scale_);
//}
if (gDebugEnabled && use_culling && nodes_culled > 0)
{
// Debug: print culling stats (only first time to avoid spam)
static int debug_count = 0;
if (debug_count++ < 10)
{
printf(" Culling: rendered %d nodes, culled %d nodes (culling rect: %.0f,%.0f-%.0f,%.0f)\n",
nodes_rendered, nodes_culled,
culling_rect_.Min.x, culling_rect_.Min.y,
culling_rect_.Max.x, culling_rect_.Max.y);
}
}
ImGui::SetWindowFontScale(1.0f);
////////////////////////////////////////////////////////////////////////////////
if (state_ == ImGuiNodesState_Selecting)
{
//Optimization: Cache verts instead of sending every frame
//Send all vect comps to the gpu
draw_list->AddRectFilled(area_.Min, area_.Max, ImColor(1.0f, 1.0f, 0.0f, 0.1f));
draw_list->AddRect(area_.Min, area_.Max, ImColor(1.0f, 1.0f, 0.0f, 0.5f));
}
////////////////////////////////////////////////////////////////////////////////
ImGui::SetCursorPos(ImVec2(0.0f, 0.0f));
ImGui::NewLine();
switch (state_)
{
case ImGuiNodesState_Default: ImGui::Text("ImGuiNodesState_Default"); break;
case ImGuiNodesState_HoveringNode: ImGui::Text("ImGuiNodesState_HoveringNode"); break;
case ImGuiNodesState_HoveringInput: ImGui::Text("ImGuiNodesState_HoveringInput"); break;
case ImGuiNodesState_HoveringOutput: ImGui::Text("ImGuiNodesState_HoveringOutput"); break;
case ImGuiNodesState_Dragging: ImGui::Text("ImGuiNodesState_Dragging"); break;
case ImGuiNodesState_DraggingInput: ImGui::Text("ImGuiNodesState_DraggingInput"); break;
case ImGuiNodesState_DraggingOutput: ImGui::Text("ImGuiNodesState_DraggingOutput"); break;
case ImGuiNodesState_Selecting: ImGui::Text("ImGuiNodesState_Selecting"); break;
case ImGuiNodesState_HoveringConnection: ImGui::Text("ImGuiNodesState_HoveringConnection"); break;
default: ImGui::Text("UNKNOWN"); break;
}
ImGui::NewLine();
ImGui::Text("Position: %.2f, %.2f", pos_.x, pos_.y);
ImGui::Text("Size: %.2f, %.2f", size_.x, size_.y);
ImGui::Text("Mouse: %.2f, %.2f", mouse_.x, mouse_.y);
ImGui::Text("Scroll: %.2f, %.2f", world_shift_.x, world_shift_.y);
ImGui::Text("Scale: %.2f", scale_);
ImGui::NewLine();
if (element_node_)
ImGui::Text("Element_node: %s", element_node_->name_);
if (element_input_)
ImGui::Text("Element_input: %s", element_input_->name_);
if (element_output_)
ImGui::Text("Element_output: %s", element_output_->name_);
////////////////////////////////////////////////////////////////////////////////
}
void GraphView::ProcessContextMenu()
{
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8));
if (ImGui::BeginPopup("NodesContextMenu"))
{
for (int node_idx = 0; node_idx < nodes_desc_.size(); ++node_idx)
if (ImGui::MenuItem(nodes_desc_[node_idx].name_))
{
//New way to add nodes (will have no connections!): (layout engine decides pos)
// GraphData::Node newNode(nextId, "NewNode");
//dataModel->AddNode(newNode);
//Old way to make nodes:
//NodeView* node = CreateNodeFromDesc(&nodes_desc_[node_idx], (mouse_ - world_shift_ - pos_) / scale_);
//nodes_.push_back(node);
}
ImGui::EndPopup();
}
ImGui::PopStyleVar();
}
ImVec2 GraphView::GetRenderedNodeSize(const GraphData::Node& dataNode, ImVec2 pos)
{
NodeView* view = GetNodeView(dataNode, pos); // creates + caches if missing
if (!view) return ImVec2(150.0f, 50.0f);
return view->area_node_.GetSize();
}
void GraphView::BuildOverlayNodeText(int nodeId, ImVec2 livePos, uint32_t color,
std::vector<GPUCharData>& out) const
{
if (!gpuRenderer_) return;
auto it = nodeViewCache_.find(nodeId);
if (it == nodeViewCache_.end()) return;
const NodeView* node = it->second;
const GraphData::Node* dataNode = dataModel ? dataModel->GetNode(nodeId) : nullptr;
if (!dataNode) return;
// The cached connector geometry is relative to the node's BAKED top-left. Offset by how far
// the node has moved (livePos - bakedTopLeft) so labels track the live position.
ImVec2 off = ImVec2(livePos.x - node->area_node_.Min.x,
livePos.y - node->area_node_.Min.y);
// Title
gpuRenderer_->BuildTextChars(dataNode->name.c_str(),
ImVec2(livePos.x + 8.0f, livePos.y + 4.0f), color, out);
// "+" symbol for expandable (collapsed) parent nodes - matches the tile path (nodes.cpp text loop).
// Positioned at the right of the title bar; livePos is the live top-left, so offset by node width.
if (!dataNode->childNodeIds.empty() && layoutEngine && !layoutEngine->IsExpanded(nodeId)) {
float plusX = livePos.x + node->area_node_.GetWidth() - 20.0f; // 20px from right edge
float plusY = livePos.y + 4.0f; // same Y as title
gpuRenderer_->BuildTextChars("+", ImVec2(plusX, plusY), color, out);
}
// Input connector labels
for (int i = 0; i < node->inputs_.size(); ++i) {
const NodesInput* input = node->inputs_[i];
if (input->type_ == ImGuiNodesConnectorType_Invisible) continue;
ImVec2 p = ImVec2(input->area_name_.Min.x + off.x, input->area_name_.Min.y + off.y);
gpuRenderer_->BuildTextChars(input->name_, p, color, out);
}
// Output connector labels
for (int i = 0; i < node->outputs_.size(); ++i) {
const NodesOutput* output = node->outputs_[i];
if (output->type_ == ImGuiNodesConnectorType_Invisible) continue;
ImVec2 p = ImVec2(output->area_name_.Min.x + off.x, output->area_name_.Min.y + off.y);
gpuRenderer_->BuildTextChars(output->name_, p, color, out);
}
}
void GraphView::BuildOverlayEdges(const std::function<ImVec2(int)>& livePos,
std::vector<GPUConnectionData>& out) const
{
if (!dataModel || !layoutEngine) return;
// Per-node world offset from baked top-left to live position (0 for non-animated nodes).
auto liveOffset = [&](int nodeId) -> ImVec2 {
auto it = nodeViewCache_.find(nodeId);
if (it == nodeViewCache_.end()) return ImVec2(0.0f, 0.0f);
ImVec2 baked = it->second->area_node_.Min;
ImVec2 lp = livePos(nodeId);
return ImVec2(lp.x - baked.x, lp.y - baked.y);
};
for (const auto& conn : dataModel->GetConnections()) {
int srcNodeId = conn.sourceNodeId, dstNodeId = conn.targetNodeId;
int srcPort = conn.sourcePortIndex, dstPort = conn.targetPortIndex;
// Same expand/collapse substitution as the tile path.
if (layoutEngine->IsExpanded(srcNodeId)) {
const GraphData::Node* c = dataModel->FindChildProvidingOutputPort(srcNodeId, conn.sourcePortIndex);
if (c) { srcNodeId = c->id; srcPort = dataModel->FindChildPortIndex(c->parentOutputPortMap, conn.sourcePortIndex); }
else continue;
}
if (layoutEngine->IsExpanded(dstNodeId)) {
const GraphData::Node* c = dataModel->FindChildAcceptingInputPort(dstNodeId, conn.targetPortIndex);
if (c) { dstNodeId = c->id; dstPort = dataModel->FindChildPortIndex(c->parentInputPortMap, conn.targetPortIndex); }
else continue;
}
// ONLY edges touching an animated node (the inverse of the tile path's hole-punch).
if (!IsAnimated(srcNodeId) && !IsAnimated(dstNodeId)) continue;
std::vector<ImVec2> routePoints = layoutEngine->GetEdgeRoutePoints(srcNodeId, dstNodeId);
// Freshly-expanded children aren't in layoutEngine->nodePositions_ yet (only committed
// on settle), so GetEdgeRoutePoints returns empty for them. Fall back to a direct 2-point
// route; the endpoints are overwritten with live port positions just below anyway.
if (routePoints.size() < 2) {
routePoints.clear();
routePoints.push_back(ImVec2(0.0f, 0.0f)); // placeholder src (set below)
routePoints.push_back(ImVec2(0.0f, 0.0f)); // placeholder dst (set below)
}
// Endpoints: use cached port positions offset to the live node position. (Dummy
// waypoints in the middle stay at their baked positions - fine, endpoints dominate.)
ImVec2 srcOff = liveOffset(srcNodeId);
ImVec2 dstOff = liveOffset(dstNodeId);
auto sit = nodeViewCache_.find(srcNodeId);
if (sit != nodeViewCache_.end() && srcPort >= 0 && srcPort < (int)sit->second->outputs_.size()) {
ImVec2 pp = sit->second->outputs_[srcPort]->pos_;
routePoints[0] = ImVec2(pp.x + srcOff.x, pp.y + srcOff.y);
}
auto dit = nodeViewCache_.find(dstNodeId);
if (dit != nodeViewCache_.end() && dstPort >= 0 && dstPort < (int)dit->second->inputs_.size()) {
ImVec2 pp = dit->second->inputs_[dstPort]->pos_;
routePoints.back() = ImVec2(pp.x + dstOff.x, pp.y + dstOff.y);
}
GPUConnectionData gpuConn = {};
size_t n = routePoints.size() <= (size_t)MAX_EDGE_POINTS ? routePoints.size() : (size_t)MAX_EDGE_POINTS;
if (n < 2) continue;
if (routePoints.size() <= (size_t)MAX_EDGE_POINTS) {
for (size_t i = 0; i < n; i++) gpuConn.controlPoints[i] = routePoints[i];
} else {
const size_t last = routePoints.size() - 1;
gpuConn.controlPoints[0] = routePoints[0];
gpuConn.controlPoints[MAX_EDGE_POINTS - 1] = routePoints[last];
for (int i = 1; i < MAX_EDGE_POINTS - 1; i++) {
float t = (float)i / (float)(MAX_EDGE_POINTS - 1);
size_t si = (size_t)(t * (float)last + 0.5f);
if (si == 0) si = 1; if (si >= last) si = last - 1;
gpuConn.controlPoints[i] = routePoints[si];
}
}
gpuConn.numPoints = (uint32_t)n;
gpuConn.color = ImGui::ColorConvertFloat4ToU32(ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
gpuConn.thickness = 2.0f;
out.push_back(gpuConn);
}
}
////////////////////////////////////////////////////////////////////////////////
// High-level rendering methods
////////////////////////////////////////////////////////////////////////////////
// Sync nodeViewCache_ (and the expanded-parent list) from the DataModel + LayoutEngine for every
// active node. Tile-invariant, so the bake loop calls this ONCE and then renders all dirty tiles;
// RenderToTile() calls it too so single-tile/interactive callers stay correct (it's idempotent).
// Guarded by nodeViewsSynced_ to collapse the repeats within one bake.
void GraphView::SyncNodeViews()
{
if (nodeViewsSynced_)
return;
std::vector<const GraphData::Node*> activeNodes = layoutEngine->GetActiveNodes(*dataModel);
expandedParentIds_.clear();
for (const GraphData::Node* dataNode : activeNodes) {
ImVec2 pos = layoutEngine->GetNodePosition(dataNode->id);
GetNodeView(*dataNode, pos); // Populates nodeViewCache_
// Track if this node's parent is expanded (to draw boundary later)
if (dataNode->parentId != -1 && layoutEngine->IsExpanded(dataNode->parentId)) {
if (std::find(expandedParentIds_.begin(), expandedParentIds_.end(), dataNode->parentId) == expandedParentIds_.end()) {
expandedParentIds_.push_back(dataNode->parentId);
}
}
}
// Expand order (least-recent first) is the boundary-box z-order; also tile-invariant.
std::sort(expandedParentIds_.begin(), expandedParentIds_.end(),
[this](int a, int b) {
return layoutEngine->GetExpandOrder(a) < layoutEngine->GetExpandOrder(b);
});
nodeViewsSynced_ = true;
spatialBucketsValid_ = false; // nodeViewCache_ just changed -> node buckets are stale
}
void GraphView::RenderToTile(Tile* tile)
{
// Set up tile rendering context
pos_ = ImVec2(0, 0);
world_shift_ = -tile->worldBounds.Min;
scale_ = 1.0f;
culling_rect_ = tile->worldBounds;
// Node-view sync is TILE-INVARIANT and hoisted to SyncNodeViews(), called once per bake by the
// render loop. It walks every active node (GetActiveNodes + 3 std::map lookups each), so doing it
// per tile cost O(nodes x tiles) - ~400M tree traversals at 650k nodes x 200 tiles, which dominated
// bake time. Correctness is unchanged: it still runs fully BEFORE any tile renders, which is what
// BuildEdgeRenderCache and the subgraph-boundary box require (they read positions for nodes outside
// the current tile, so a per-tile cull here would drop edges and half-draw seam-straddling nodes).
SyncNodeViews();
const std::vector<int>& expandedParentIds = expandedParentIds_;
// Choose rendering path: GPU or CPU
if (useGPURendering_ && gpuRenderer_ && gpuRenderer_->IsSupported()) {
// GPU rendering path (OpenGL 4.3+ compute shaders)
// Rebuild connection cache if needed (same as CPU path). Topology change -> also stale geometry.
if (!connectionCacheValid_) {
BuildConnectionCache();
connectionCacheValid_ = true;
edgeRenderCacheValid_ = false; // topology changed -> geometry must be re-resolved too
}
// Re-resolve world-space edge geometry when stale (topology change). A node drag does NOT flip
// this flag - it calls RefreshEdgeGeometryForNodes to patch just the moved edges incrementally.
if (!edgeRenderCacheValid_) {
BuildEdgeRenderCache(); // resolve every edge's world geometry ONCE; tiles just cull it below
edgeRenderCacheValid_ = true;
spatialBucketsValid_ = false; // edge indices moved -> edge buckets are stale
}
// Spatial buckets: also tile-invariant, so build once per bake. This is what turns the bake from
// O(nodes x tiles) into O(nodes + tiles) - the loops below iterate this tile's bucket instead of
// re-scanning the whole graph and culling.
if (!spatialBucketsValid_) {
BuildNodeBuckets();
BuildEdgeBuckets();
spatialBucketsValid_ = true;
}
// This tile's buckets. Absent key = nothing here; use a shared empty list so the loops below
// don't need a null check.
static const std::vector<int> kNoIds;
std::pair<int,int> tileKey(
(int)(tile->worldBounds.Min.x / TileCache::TILE_SIZE),
(int)(tile->worldBounds.Min.y / TileCache::TILE_SIZE));
auto nodeBucketIt = nodeIdsByTile_.find(tileKey);
auto edgeBucketIt = edgeIdxByTile_.find(tileKey);
const std::vector<int>& tileNodeIds = (nodeBucketIt != nodeIdsByTile_.end()) ? nodeBucketIt->second : kNoIds;
const std::vector<int>& tileEdgeIdxs = (edgeBucketIt != edgeIdxByTile_.end()) ? edgeBucketIt->second : kNoIds;
// Drag overrides as a vector so the node loops can iterate bucket and overrides uniformly.
const std::vector<int> overrideNodeIdList(bucketOverrideNodeIds_.begin(), bucketOverrideNodeIds_.end());
// GPU BUILD APPROACH: per-tile we now do ONLY the cheap work - reject edges whose (precomputed)
// world bbox doesn't touch this tile, hole-punch animated edges, then upload. All the heavy
// resolution (substitution, routing, port lookup, control-point packing) already happened once
// in BuildEdgeRenderCache(), instead of repeating for every tile.
// Reuse the persistent staging buffer (see tileConnScratch_): clear keeps the capacity earlier
// tiles grew, so this stops re-reserving the whole graph's edge count for every tile.
std::vector<GPUConnectionData>& gpuConnections = tileConnScratch_;
gpuConnections.clear();
bool use_culling = (culling_rect_.GetWidth() > 0.0f && culling_rect_.GetHeight() > 0.0f);
// Only the edges bucketed into THIS tile, plus any drag overrides - no whole-graph scan.
auto EmitEdge = [&](int edgeIdx) {
const CachedEdge& ce = edgeRenderCache_[edgeIdx];
// Hole-punch: skip edges touching an animated node - they're redrawn live from the overlay.
if (IsAnimated(ce.srcNodeId) || IsAnimated(ce.dstNodeId))
return;
// The bucket is tile-granular (whole 8192^2 cells) while culling_rect_ can be a sub-rect,
// so keep the exact bbox test. It now runs on a handful of edges instead of all ~3M.
if (use_culling && !culling_rect_.Overlaps(ImRect(ce.bbMin, ce.bbMax)))