-
Notifications
You must be signed in to change notification settings - Fork 14
/
node_arranger.py
2208 lines (1554 loc) · 63.1 KB
/
node_arranger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: GPL-2.0-or-later
from collections import defaultdict
from dataclasses import dataclass, field, replace
from itertools import chain, combinations, groupby, pairwise
from operator import gt, itemgetter, lt
from statistics import fmean
import bpy
from bpy.types import NodeFrame, Operator
from bpy.props import IntVectorProperty
from bl_math import clamp
from mathutils import Vector
from mathutils.geometry import interpolate_bezier
# All credits and thanks to Leonardo-Pike-Excell
# https://github.com/Leonardo-Pike-Excell/node-arrange
# -------------------------------------------------------------------
MAX_LOC = 100_000
HIDE_OFFSET = 10
HIDDEN_NODE_FLAT_WIDTH = 116
BOTTOM_OFFSET = 14.85
TOP_OFFSET = 35
VISIBLE_PBSDF_SOCKETS = 5
SOCKET_SPACING_MULTIPLIER = 22
FRAME_PADDING = 29.8
COMPACT_HEIGHT = 450
EPS = 65
MIN_ADJ_COLS = 2
DISPERSE_MULT = 4
TARGET_NODE_TYPES = {'ShaderNodeBsdfPrincipled', 'ShaderNodeDisplacement'}
SCALE_FAC = bpy.context.preferences.system.ui_scale
# -------------------------------------------------------------------
# Parents and children
# -------------------------------------------------------------------
def get_parents(node):
if parent := node.parent:
yield parent
yield from get_parents(parent)
def get_nested_children(frame):
try:
yield from Maps.used_children[frame]
except KeyError:
return
for node in Maps.selected:
if node.bl_idname == 'NodeFrame' and node.parent == frame:
yield from get_nested_children(node)
def is_parented(a, b):
if not isinstance(a, NodeFrame) or not isinstance(b, NodeFrame):
return False
return b in get_parents(a) or a in get_parents(b)
# -------------------------------------------------------------------
# Flatten links
# -------------------------------------------------------------------
def get_predecessors(*nodes):
predecessors = []
for node in nodes:
predecessors.extend(chain(*[Maps.links[i] for i in node.inputs]))
return predecessors
def get_successors(*nodes):
successors = []
for node in nodes:
successors.extend(chain(*[Maps.links[o] for o in node.outputs]))
return successors
# -------------------------------------------------------------------
# Locations
# -------------------------------------------------------------------
def abs_loc(node):
loc = node.location.copy()
for parent in get_parents(node):
loc += parent.location
return loc
def dimensions(node):
#return node.dimensions / SCALE_FAC
if "ShaderNodeTexImage" == node.__class__.__name__:
return Vector((200, 300))
else:
return Vector((100, 150))
def get_right(node):
return abs_loc(node).x + dimensions(node).x
def get_top(node, y_loc=None):
if y_loc is None:
y_loc = abs_loc(node).y
return (y_loc + dimensions(node).y / 2) - HIDE_OFFSET if node.hide else y_loc
def get_bottom(node, y_loc=None):
if y_loc is None:
y_loc = abs_loc(node).y
dim_y = dimensions(node).y
bottom = y_loc - dim_y
return bottom + dim_y / 2 - HIDE_OFFSET if node.hide else bottom
def get_hidden_socket_y(socket):
node = socket.node
x, y = abs_loc(node)
top = get_top(node, y)
bottom = get_bottom(node, y)
cap_width = (dimensions(node).x - HIDDEN_NODE_FLAT_WIDTH) / 2
inner = x + cap_width
outer = x - cap_width / 3
raw_sockets = node.outputs if socket.is_output else node.inputs
sockets = [s for s in raw_sockets if not s.is_unavailable]
vectors = map(Vector, ((inner, top), (outer, top), (inner, bottom), (outer, bottom)))
points = interpolate_bezier(*vectors, len(sockets) + 2)[1:-1]
return points[sockets.index(socket)].y
def get_input_y(input, accurate=True):
node = input.node
if not accurate or node.bl_idname == 'NodeReroute':
return get_top(node)
if node.hide:
return get_hidden_socket_y(input)
y = get_top(node)
inputs = [i for i in node.inputs if not i.is_unavailable]
if node.bl_idname != 'ShaderNodeBsdfPrincipled':
# Start from the bottom socket to avoid any node properties
y -= dimensions(node).y - BOTTOM_OFFSET
inputs.reverse()
idx = inputs.index(input)
for i in inputs[:idx + 1]:
if i.type in {'VECTOR', 'ROTATION', 'MATRIX'} and not i.hide_value and not i.is_linked:
y += (SOCKET_SPACING_MULTIPLIER * 0.909) * len(i.default_value)
else:
y -= 56.5
idx = -inputs.index(input)
if idx < -VISIBLE_PBSDF_SOCKETS:
panels = ('Subsurface', 'Specular', 'Transmission', 'Coat', 'Sheen', 'Emission')
idx = -(VISIBLE_PBSDF_SOCKETS + 0.5 + panels.index(input.name.split()[0]))
return y + idx * SOCKET_SPACING_MULTIPLIER
def get_output_y(output, accurate=True):
node = output.node
if not accurate or node.bl_idname == 'NodeReroute':
return get_top(node)
if node.hide:
return get_hidden_socket_y(output)
y = get_top(node) - TOP_OFFSET
outputs = [o for o in node.outputs if not o.is_unavailable]
return y - outputs.index(output) * SOCKET_SPACING_MULTIPLIER
def corrected_y(node, target_y):
y = abs_loc(node).y
return target_y + (y - get_top(node)) if y != target_y else y
# -------------------------------------------------------------------
# Boxes
# -------------------------------------------------------------------
# This descriptor is meant to solve most floating point comparison issues
class Side(object):
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, val):
instance.__dict__[self.name] = round(val, 2)
@dataclass(slots=True)
class Box:
left: float = field(default=Side())
bottom: float = field(default=Side())
right: float = field(default=Side())
top: float = field(default=Side())
@property
def width(self):
return self.right - self.left
@property
def height(self):
return self.top - self.bottom
@property
def center(self):
return Vector((self.left + self.right, self.bottom + self.top)) / 2
def line_x(self):
return [self.left, self.right]
def line_y(self):
return [self.bottom, self.top]
def expand(self, x=0, y=0):
self.left -= x
self.right += x
self.bottom -= y
self.top += y
def move(self, *, x=0, y=0):
self.left += x
self.right += x
self.bottom += y
self.top += y
def overlaps(self, other, offset=0.01):
# yapf: disable
return not (
self.right - offset < other.left + offset
or self.left + offset > other.right - offset
or self.top - offset < other.bottom + offset
or self.bottom + offset > other.top - offset)
# yapf: enable
def get_leftwards(self, boxes):
try:
return next(k for k, b in reversed(boxes.items()) if b.right <= self.left)
except StopIteration:
return None
def get_rightwards(self, boxes):
try:
return next(k for k, b in boxes.items() if b.left >= self.right)
except StopIteration:
return None
def get_box(nodes):
x_vals = []
y_vals = []
for node in nodes:
x, y = abs_loc(node)
x_vals.extend((x, x + dimensions(node).x))
y_vals.extend((get_top(node, y), get_bottom(node, y)))
return Box(min(x_vals), min(y_vals), max(x_vals), max(y_vals))
def get_frame_box(frame, expand=True):
# `frame.width` and `frame.height` can't be used here: since they only
# get evaluated on UI redraw, they'll be incorrect if the rearrangement of
# the frame's children changed the frame's size.
children = tuple(get_nested_children(frame))
box = get_box(children)
box.expand(FRAME_PADDING, FRAME_PADDING)
if frame.label:
box.top -= (FRAME_PADDING / 2) - frame.label_size * 1.25
if expand:
if len(children) == 1:
box.expand(y=70)
else:
box.expand(70, 70)
return box
def get_col_boxes(columns):
subcolumns = []
for col in columns:
if len(col) == 1:
subcolumns.append(col)
continue
col.sort(key=get_top, reverse=True)
curr_idx = 0
for i, j in pairwise(range(len(col))):
if get_bottom(col[i]) - get_top(col[j]) > 70:
subcolumns.append(col[curr_idx:i + 1])
curr_idx = j
subcolumns.append(col[curr_idx:j + 1])
col_boxes = {
tuple(c): get_box(c)
for c in subcolumns
if not all(n.bl_idname == 'NodeReroute' for n in c)}
for box in col_boxes.values():
box.expand(70, 70)
return col_boxes
def sorted_boxes(boxes):
return dict(sorted(boxes.items(), key=lambda kb: kb[1].left))
def get_box_rows(boxes):
tops = {k: b.top for k, b in boxes.items()}
boxes_ascending = sorted(boxes, key=tops.get)
prev_key = boxes_ascending[0]
row = [prev_key]
rows = []
for key in boxes_ascending[1:]:
if tops[key] <= tops[prev_key] + EPS:
row.append(key)
else:
rows.append(row)
row = [key]
prev_key = key
rows.append(row)
for row in rows:
row.sort(key=lambda k: boxes[k].left)
return rows
def lines_overlap(line1, line2, offset=0.01):
b1, a1 = line1
b2, a2 = line2
a1 -= offset
b1 += offset
a2 -= offset
b2 += offset
# yapf: disable
return (
(b1 <= a2 <= a1)
or (b1 <= b2 <= a1)
or (a2 < a1 and b1 < b2)
or (a1 < a2 and b2 < b1))
# yapf: enable
# -------------------------------------------------------------------
# Update locations
# -------------------------------------------------------------------
def move(node, *, x=0, y=0):
if x == 0 and y == 0:
return
# If the (absolute) value of a node's X/Y axis exceeds 100k,
# `node.location` can't be affected directly. (This often happens with
# frames since their locations are relative.)
loc = node.location
if abs(loc.x + x) <= MAX_LOC and abs(loc.y + y) <= MAX_LOC:
loc += Vector((x, y))
return
for n in Maps.selected:
n.select = n == node
bpy.ops.transform.translate(value=[v * SCALE_FAC for v in (x, y, 0)])
for n in Maps.selected:
n.select = True
def move_to(node, *, x=None, y=None):
loc = abs_loc(node)
if x is not None and y is None:
move(node, x=x - loc.x)
elif y is not None and x is None:
move(node, y=y - loc.y)
else:
move(node, x=x - loc.x, y=y - loc.y)
def move_nodes(nodes, *, x=0, y=0):
for node in {n.parent or n for n in nodes}:
if node.bl_idname != 'NodeFrame' or not node.parent:
move(node, x=x, y=y)
# -------------------------------------------------------------------
# Generate maps
# -------------------------------------------------------------------
def get_links(ntree):
# Precompute links to:
# 1. Avoid `O(len(ntree.links))` time
# 2. Ignore invalid/hidden links
# 3. Ignore links to unused nodes
# 4. Ignore links to/from unselected nodes
links = Maps.links
sockets = Maps.sockets
for link in ntree.links:
if link.is_hidden:
continue
links[link.to_socket].append(link.from_node)
sockets[link.to_socket].append(link.from_socket)
links[link.from_socket].append(link.to_node)
sockets[link.from_socket].append(link.to_socket)
def get_columns(output_nodes):
columns = [output_nodes]
idx = 0
while columns[idx]:
columns.append(tuple(dict.fromkeys(get_predecessors(*columns[idx]))))
idx += 1
del columns[idx]
for col1 in reversed(columns):
for i, col2 in enumerate(columns):
if col1 != col2:
columns[i] = [n for n in col2 if n not in col1]
return [sc for uc in columns if (sc := [n for n in uc if n.select])]
def min_col_idx(item):
universal_columns = Maps.universal_columns
idxs = []
for col in item[1]:
idxs.append(next(i for i, c in enumerate(universal_columns) if any(n in c for n in col)))
return min(idxs)
def get_frame_columns():
frame_columns = {}
for frame, children in Maps.all_children.items():
columns = [fc for c in Maps.universal_columns if (fc := [n for n in c if n in children])]
if any(columns):
frame_columns[frame] = columns
Maps.frame_columns.update(sorted(frame_columns.items(), key=min_col_idx))
Maps.used_children.update({f: tuple(chain(*c)) for f, c in Maps.frame_columns.items()})
# -------------------------------------------------------------------
# Base arrange
# -------------------------------------------------------------------
def get_arranged(columns):
arranged = {}
for i, col in enumerate(columns):
if i != 0:
max_width = max([dimensions(n).x for n in col])
x = prev_x - (max_width + 70)
else:
x = 0
prev_x = x
y = 0
for node in col:
y = corrected_y(node, y)
arranged[node] = Vector((x, y))
y = get_bottom(node, y) - 70
return arranged
def arrange_frame_columns():
universal_arranged = get_arranged(Maps.universal_columns)
for frame, columns in Maps.frame_columns.items():
arranged = get_arranged(columns)
if frame:
virtual_x, virtual_y = zip(*[universal_arranged[n] for n in chain(*columns)])
avg_universal_loc = Vector((fmean(virtual_x), fmean(virtual_y)))
for node, vec in arranged.items():
vec += avg_universal_loc
for node, (x, y) in arranged.items():
move_to(node, x=x, y=y)
# -------------------------------------------------------------------
# Link lengths
# -------------------------------------------------------------------
def link_stretch(nodes, movement=0):
stretch = 0
for node in nodes:
x = abs_loc(node).x + movement
right = x + dimensions(node).x
for socket in chain(node.inputs, node.outputs):
for linked in Maps.links[socket]:
if linked in nodes:
continue
dist = abs_loc(linked).x - right if socket.is_output else x - get_right(linked)
if dist < 0:
stretch -= dist
return stretch
def get_input_lengths(nodes):
lengths = {}
for node in nodes:
input_x = abs_loc(node).x
for pred in get_predecessors(node):
if pred in nodes:
continue
dist = input_x - get_right(pred)
if pred not in lengths or lengths[pred] > dist:
lengths[pred] = dist
return lengths
def get_output_lengths(nodes):
lengths = {}
for node in nodes:
output_x = get_right(node)
for succ in get_successors(node):
if succ in nodes:
continue
dist = abs_loc(succ).x - output_x
if succ not in lengths or lengths[succ] > dist:
lengths[succ] = dist
return lengths
# -------------------------------------------------------------------
# Make space for stretched
# -------------------------------------------------------------------
def get_descendants(nodes, seen=None):
if seen is None:
seen = set()
for node in nodes:
if node in seen:
continue
yield node
seen.add(node)
queue = set(get_successors(node))
parent = node.parent
if parent:
queue.update(Maps.used_children[parent])
columns = Maps.frame_columns[parent]
try:
idx = next(i for i, c in enumerate(columns) if node in c)
except StopIteration:
pass
else:
queue.update(chain(*columns[:idx + 1]))
yield from get_descendants(queue, seen)
def get_ancestors(nodes, seen=None):
if seen is None:
seen = set()
for node in nodes:
if node in seen:
continue
yield node
seen.add(node)
for input in node.inputs:
yield from get_ancestors(Maps.links[input], seen)
def ideal_x_movement(nodes, line_x):
from_x = []
to_x = []
for node in nodes:
input_x = abs_loc(node).x
output_x = get_right(node)
to_x.extend([(abs_loc(n).x, output_x) for n in get_successors(node) if n not in nodes])
from_x.extend([(get_right(n), input_x) for n in get_predecessors(node) if n not in nodes])
dist_to_x = lambda io: io[0] - io[1]
dist_from_x = lambda oi: oi[1] - oi[0]
if from_x and to_x:
nright, right = min(to_x, key=dist_to_x)
nleft, left = min(from_x, key=dist_from_x)
movement = (nleft + nright - left - right) / 2
if stretch := link_stretch(nodes, movement):
try:
nleft, left = next(oi for oi in sorted(from_x, key=dist_from_x) if oi[0] < nright)
except StopIteration:
return movement
new_movement = (nleft + nright - left - right) / 2
if stretch > link_stretch(nodes, new_movement):
return new_movement
return movement
left, right = line_x
if from_x:
target_x, left = min(from_x, key=dist_from_x)
target_x += (right - left)
elif to_x:
target_x, right = min(to_x, key=dist_to_x)
target_x -= (right - left)
else:
return 0
return target_x - (left + right) / 2
def ideal_frame_x_movement(frame):
children = Maps.used_children[frame]
return ideal_x_movement(children, get_box(children).line_x())
def resolved_with_min_movement(children):
# Move the children's immediate successor rightwards, then move the
# children's frame rightwards, and see if it's resolved.
frame = children[0].parent
pred, pred_dist = min(get_input_lengths(children).items(), key=itemgetter(1))
succ, succ_dist = min(get_output_lengths(children).items(), key=itemgetter(1))
if frame in chain(get_parents(succ), get_parents(pred)):
return False
if pred_dist < 0:
pred_frame = pred.parent
predecessors = Maps.used_children[pred_frame] if pred_frame else [pred]
pred_movement = pred_dist - 70 * 2
if link_stretch(predecessors, pred_movement):
return False
if succ_dist < 0:
succ_frame = succ.parent
succ_movement = abs(succ_dist) + 70 * 2
if succ_frame:
if link_stretch(Maps.used_children[succ_frame], succ_movement):
return False
move(succ_frame, x=succ_movement)
else:
if link_stretch([succ], succ_movement):
return False
move(succ, x=succ_movement)
if pred_dist < 0:
node = succ_frame if pred_frame and succ_frame else pred
move(node, x=pred_movement)
movement = ideal_frame_x_movement(frame)
if link_stretch(children, movement):
return False
move(frame, x=movement)
return True
def make_space_for_stretched(frame):
if not frame:
return
children = Maps.used_children[frame]
to_move = set(get_descendants(get_successors(*children)))
to_move -= set(get_ancestors(get_predecessors(*children))) | set(children)
Maps.frame_descendants[frame] = to_move
move(frame, x=ideal_frame_x_movement(frame))
pred_stretch = []
succ_stretch = []
for node in children:
pred_stretch.extend([d for d in get_input_lengths([node]).values() if d < 0])
succ_stretch.extend([d for d in get_output_lengths([node]).values() if d < 0])
movement = 0
if pred_stretch:
movement += abs(min(pred_stretch)) + 70 * 2
if succ_stretch:
movement += abs(min(succ_stretch)) + 70 * 2
if movement != 0 and not resolved_with_min_movement(children):
move_nodes(to_move, x=movement)
move(frame, x=ideal_frame_x_movement(frame))
# -------------------------------------------------------------------
# Regenerate columns
# -------------------------------------------------------------------
def move_outlier(node):
try:
input_dist = min(get_input_lengths([node]).values())
output_dist = min(get_output_lengths([node]).values())
except ValueError:
return
if input_dist >= 0:
return
if output_dist < 0 or output_dist < abs(input_dist):
return
line_x = (abs_loc(node).x, get_right(node))
movement = ideal_x_movement([node], line_x)
if link_stretch([node]) >= link_stretch([node], movement):
move(node, x=movement)
def get_new_columns(frame):
sorted_nodes = sorted(Maps.used_children[frame], key=lambda n: abs_loc(n).x)
col = [sorted_nodes[0]]
columns = []
for node in sorted_nodes[1:]:
max_right = max([abs_loc(n).x + dimensions(n).x for n in col])
if abs_loc(node).x < max_right:
col.append(node)
else:
columns.append(col)
col = [node]
columns.append(col)
return columns
def align_columns(columns):
for col in columns:
col.sort(key=lambda n: dimensions(n).x, reverse=True)
for i, col in enumerate(columns):
x = abs_loc(col[0]).x
for node in col:
move_to(node, x=x)
if i == 0:
continue
prev = columns[i - 1][0]
movement = -x + get_right(prev) + 70
if movement <= 0:
continue
to_move = [f for f in Maps.frame_columns if f and get_frame_box(f, False).left > x]
to_move.extend(chain(*columns[i:]))
move_nodes(to_move, x=movement)
def line_overlap_vector(target, lines):
l1 = lines[target]
center = sum(l1) / 2
y = [sum(l2) / 2 - center for n, l2 in lines.items() if target != n and lines_overlap(l1, l2)]
if not y:
return 0
return clamp(-fmean(y), -1, 1) if any(y) else 1
def disperse_nodes_y(col):
margin = 70 / 2
lines = {n: [get_bottom(n) - margin, get_top(n) + margin] for n in col}
pairs = [(lines[n1], lines[n2]) for n1, n2 in combinations(lines, 2)]
while any(lines_overlap(l1, l2) for l1, l2 in pairs):
for node, line in lines.items():
movement = line_overlap_vector(node, lines)
line[0] += movement
line[1] += movement
for node, line in lines.items():
move_to(node, y=corrected_y(node, line[1] - margin))
def regenerate_columns(frame):
for node in Maps.used_children[frame]:
move_outlier(node)
new_columns = get_new_columns(frame)
align_columns(new_columns)
for col in new_columns:
disperse_nodes_y(col)
col.sort(key=get_top, reverse=True)
new_columns.reverse()
Maps.frame_columns[frame] = new_columns
# -------------------------------------------------------------------
# Arrange principled
# -------------------------------------------------------------------
def get_descendants_simple(nodes):
for node in nodes:
yield node
for output in node.outputs:
yield from get_descendants_simple(Maps.links[output])
def arrange_principled():
for col in Maps.universal_columns:
if target_nodes := [n for n in col if n.bl_idname in TARGET_NODE_TYPES]:
break
else:
return
all_image_nodes = [
n for n in get_ancestors(target_nodes) if n.bl_idname == 'ShaderNodeTexImage']
if not all_image_nodes:
return
groups = defaultdict(list)
for node in all_image_nodes:
groups[node.parent].append(node)
image_nodes = max(groups.values(), key=len)
leftmost = min(image_nodes, key=lambda n: abs_loc(n).x)
leftmost_row = tuple(get_descendants_simple([leftmost]))
for image_node in image_nodes:
row = tuple(get_descendants_simple([image_node]))
for node1, node2 in zip(leftmost_row, row):
movement = abs_loc(node1).x - abs_loc(node2).x
if link_stretch([node2], movement) != 0:
break
move(node2, x=movement)
col1 = next(c for c in chain(*Maps.frame_columns.values()) if node1 in c)
ranked = sorted(col1 + [node2], key=get_right, reverse=True)
if ranked[0] != node2:
continue
right = get_right(node2)
to_move = [n for n in chain(*Maps.universal_columns) if get_right(n) <= right]
move_nodes(to_move + [node2], x=get_right(ranked[1]) - right)
if any(n.bl_idname == 'ShaderNodeDisplacement' for n in row):
move(image_node, y=-1)
if frame := leftmost.parent:
regenerate_columns(frame)
# -------------------------------------------------------------------
# Move to linked Y
# -------------------------------------------------------------------
def get_real_sockets(socket):
node = socket.node
if node.bl_idname == 'NodeReroute':
new_socket = node.inputs[0] if socket.is_output else node.outputs[0]
for linked_socket in Maps.sockets[new_socket]:
yield from get_real_sockets(linked_socket)
else:
yield socket
def get_linked_y_locs(node):
y_locs = []
is_reroute = node.bl_idname == 'NodeReroute'
for socket in chain(node.inputs, node.outputs):
if not socket.is_linked or socket.is_unavailable:
continue
if socket.is_output:
get_socket_y = get_output_y
get_linked_socket_y = get_input_y
else:
get_socket_y = get_input_y
get_linked_socket_y = get_output_y
socket_y = get_socket_y(socket, not is_reroute)
for linked_socket in chain(*[get_real_sockets(s) for s in Maps.sockets[socket]]):
linked_y = get_linked_socket_y(linked_socket, is_reroute)
if linked_socket.node.bl_idname == 'NodeReroute':
linked_y += abs_loc(node).y - socket_y
y_locs.append((linked_socket.node, corrected_y(node, linked_y)))
return y_locs
def move_frames_to_linked_y():
for frame, children in Maps.used_children.items():
if not frame:
continue
linked_y_locs = [
y for c in children for n, y in get_linked_y_locs(c) if c.parent != n.parent]
if not linked_y_locs:
continue
movement = fmean(linked_y_locs) - fmean([abs_loc(n).y for n in children])
for node in children:
move(node, y=movement)
def get_ideal_y(node, divided_rows, line_y):
y = abs_loc(node).y
parent = node.parent
exclusive = node.bl_idname != 'NodeReroute' or parent
y_locs = [y for n, y in get_linked_y_locs(node) if not exclusive or n.parent == parent]
if not y_locs:
return y
rows = [r for r in divided_rows if node in r]
if rows and node not in {rows[0][0], rows[0][-1]}:
return y
if not parent:
return fmean(y_locs)
height = y - get_bottom(node)
return clamp(fmean(y_locs), line_y[0] + height, line_y[1])
def get_overlapping_lines(lines):
keys = tuple(lines)
margin = 70 / 2