forked from nortikin/sverchok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_structure.py
executable file
·1200 lines (972 loc) · 34.7 KB
/
data_structure.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from functools import reduce
from math import radians
import itertools
import time
import ast
import bpy
from mathutils import Vector, Matrix
global bmesh_mapping, per_cache
DEBUG_MODE = False
HEAT_MAP = False
RELOAD_EVENT = False
# this is set correctly later.
SVERCHOK_NAME = "sverchok"
#handle for object in node
temp_handle = {}
# cache node group update trees it not used, as i see
# cache_nodes = {}
# socket cache
socket_data_cache = {}
# for viewer baker node cache
cache_viewer_baker = {}
sv_Vars = {}
# note used?
#bmesh_mapping = {}
#per_cache = {}
sentinel = object()
#####################################################
################### update magic ####################
#####################################################
# is this used?
# i think no
# main update
def read_cnodes(cnode):
global cache_nodes
if cnode not in cache_nodes:
return None
return cache_nodes[cnode]
def write_cnodes(cnode, number):
global cache_nodes
if cnode in cache_nodes:
del cache_nodes[cnode]
cache_nodes[cnode] = number
def clear_cnodes(cnode='ALL'):
global cache_nodes
if cnode == 'ALL':
for i in cache_nodes.items:
del cache_nodes[i]
else:
if read_cnodes(cnode) is not None:
del cache_nodes[cnode]
def initialize_cnodes():
node_name = 'GLOBAL CNODE'
write_cnodes(node_name, 1)
write_cnodes('LOCK UPDATE CNODES', 1)
def check_update_node(node_name, write=False):
numb = read_cnodes(node_name)
etalon = read_cnodes('GLOBAL CNODE')
#print('etalon',etalon)
if numb == etalon:
return False
else:
if write:
write_cnodes(node_name, etalon)
return True
def ini_update_cnode(node_name):
if read_cnodes('LOCK UPDATE CNODES') == 1:
return False
etalon = read_cnodes('GLOBAL CNODE')
if etalon is None:
initialize_cnodes()
etalon = 1
else:
etalon += 1
write_cnodes('GLOBAL CNODE', etalon)
write_cnodes(node_name, etalon)
return True
def is_updated_cnode():
write_cnodes('LOCK UPDATE CNODES', 0)
def lock_updated_cnode():
write_cnodes('LOCK UPDATE CNODES', 1)
#####################################################
################### bmesh magic #####################
#####################################################
def read_bmm(bm_ref):
global bmesh_mapping
if bm_ref not in bmesh_mapping:
return None
return bmesh_mapping[bm_ref]
def write_bmm(bm_ref, bm):
global bmesh_mapping
if bm_ref in bmesh_mapping:
del bmesh_mapping[bm_ref]
bmesh_mapping[bm_ref] = bm
def clear_bmm(bm_ref='ALL'):
global bmesh_mapping
if bm_ref == 'ALL':
for i in bmesh_mapping.items:
del bmesh_mapping[i]
else:
if read_bmm(bm_ref) is not None:
del bmesh_mapping[bm_ref]
#####################################################
################### cache magic #####################
#####################################################
def handle_delete(handle):
if handle in temp_handle:
del temp_handle[handle]
def handle_read(handle):
if not (handle in temp_handle):
return (False, [])
return (True, temp_handle[handle]['prop'])
def handle_write(handle, prop):
handle_delete(handle)
temp_handle[handle] = {"prop" : prop}
def handle_check(handle, prop):
if handle in handle_check and \
prop == handle_check[handle]['prop']:
return True
return False
#####################################################
################ list matching magic ################
#####################################################
# creates an infinite iterator
# use with terminating input
def repeat_last(lst):
i = -1
while lst:
i += 1
if len(lst) > i:
yield lst[i]
else:
yield lst[-1]
# longest list matching [[1,2,3,4,5], [10,11]] -> [[1,2,3,4,5], [10,11,11,11,11]]
def match_long_repeat(lsts):
max_l = 0
tmp = []
for l in lsts:
max_l = max(max_l, len(l))
for l in lsts:
if len(l) == max_l:
tmp.append(l)
else:
tmp.append(repeat_last(l))
return list(map(list, zip(*zip(*tmp))))
# longest list matching, cycle [[1,2,3,4,5] ,[10,11]] -> [[1,2,3,4,5] ,[10,11,10,11,10]]
def match_long_cycle(lsts):
max_l = 0
tmp = []
for l in lsts:
max_l = max(max_l, len(l))
for l in lsts:
if len(l) == max_l:
tmp.append(l)
else:
tmp.append(itertools.cycle(l))
return list(map(list, zip(*zip(*tmp))))
# when you intent to use lenght of first list to control WHILE loop duration
# and you do not want to change the length of the first list, but you want the second list
# lenght to by not less than the length of the first
def second_as_first_cycle(F,S):
if len(F)>len(S):
return list(map(list, zip(*zip(*[F, itertools.cycle(S)]))))
else:
return [F,S]
# cross matching
# [[1,2], [5,6,7]] -> [[1,1,1,2,2,2], [5,6,7,5,6,7]]
def match_cross(lsts):
return list(map(list, zip(*itertools.product(*lsts))))
# use this one
# cross matching 2, more useful order
# [[1,2], [5,6,7]] ->[[1, 2, 1, 2, 1, 2], [5, 5, 6, 6, 7, 7]]
# but longer and less elegant expression
# performance difference is minimal since number of lists is usually small
def match_cross2(lsts):
return list(reversed(list(map(list, zip(*itertools.product(*reversed(lsts)))))))
# Shortest list decides output length [[1,2,3,4,5], [10,11]] -> [[1,2], [10, 11]]
def match_short(lsts):
return list(map(list, zip(*zip(*lsts))))
# extends list so len(l) == count
def fullList(l, count):
d = count - len(l)
if d > 0:
l.extend([l[-1] for a in range(d)])
return
def sv_zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
# like standard zip but list instead of tuple
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield result
def checking_links(process):
'''Decorator for process method of node.
This decorator does stanard checks for mandatory input and output links.
'''
def real_process(node):
# check_mandatory_links() node method should return True
# if all mandatory inputs and outputs are linked.
# If it returns False then node will just skip processing.
if hasattr(node, "check_mandatory_links"):
if not node.check_mandatory_links():
return
else:
# If check_mandatory_links() method is not defined, then node can
# define list of mandatory inputs and/or outputs.
# Node will skip processing if any of mandatory inputs is not linked.
# It will also skip processing if none of mandatory outputs is linked.
if hasattr(node, "input_descriptors"):
mandatory_inputs = [descriptor.name for descriptor in node.input_descriptors if descriptor.is_mandatory]
if not all([node.inputs[name].is_linked for name in mandatory_inputs]):
print("Node {}: skip processing: not all of mandatory inputs {} are linked.".format(node.name, mandatory_inputs))
return
if hasattr(node, "output_descriptors"):
mandatory_outputs = [descriptor.name for descriptor in node.output_descriptors if descriptor.is_mandatory]
if not any([node.outputs[name].is_linked for name in mandatory_outputs]):
print("Node {}: skip processing: none of mandatory outputs {} are linked.".format(node.name, mandatory_outputs))
return
return process(node)
real_process.__name__ = process.__name__
real_process.__doc__ = process.__doc__
return real_process
def iterate_process(method, matcher, *inputs, node=None):
'''Shortcut function for usual iteration over set of input lists.
This is shortcut for boilerplate code like
res1 = []
res2 = []
params = match_long_repeat([input1,input2])
for i1, i2 in zip(*params):
r1,r2 = self.method(i1,i2)
res1.append(r1)
res2.append(r2)
return res1, res2
'''
data = matcher(inputs)
if node is None:
results = [list(method(*d)) for d in zip(*data)]
else:
results = [list(method(node, *d)) for d in zip(*data)]
return list(zip(*results))
class Input(object):
'''Node input socket metainformation descriptor.'''
def __init__(self, socktype, name, identifier=None, is_mandatory=True, default=sentinel, deepcopy=True):
self.socktype = socktype
self.name = name
self.identifier = identifier if identifier is not None else name
self.default = default
self.deepcopy = deepcopy
self.is_mandatory = is_mandatory
def __str__(self):
return self.name
def create(self, node):
return node.inputs.new(self.socktype, self.name, self.identifier)
def get(self, node):
return node.inputs[self.name].sv_get(default=self.default, deepcopy=self.deepcopy)
class Output(object):
'''Node output socket metainformation descriptor.'''
def __init__(self, socktype, name, is_mandatory=True):
self.socktype = socktype
self.name = name
self.is_mandatory = is_mandatory
def __str__(self):
return self.name
def create(self, node):
node.outputs.new(self.socktype, self.name)
def set(self, node, value):
if node.outputs[self.name].is_linked:
node.outputs[self.name].sv_set(value)
def match_inputs(matcher, inputs, outputs):
'''Decorator for inputs/outputs boilerplate.
Usage:
@match_inputs(match_long_repeat,
inputs=[Input(...), Input(...)],
outputs=[Output(...), Output(...)])
def process(self, i1, i2):
...
return res1, res2
This is shortcut for code like
def process(self):
i1s = self.inputs['i1'].sv_get(..)
i2s = self.inputs['i2'].sv_get(..)
res1 = []
res2 = []
params = match_long_repeat([i1s, i2s])
for i1,i2 in zip(*params):
...
res1.append(r1)
res2.append(r2)
if self.outputs['r1'].is_linked:
self.outputs['r1'].sv_set(res1)
if self.outputs['r2'].is_linked:
self.outputs['r2'].sv_set(res2)
'''
def decorator(process):
def real_process(node):
inputs_data = [input_descriptor.get(node) for input_descriptor in inputs]
results = iterate_process(process, matcher, *inputs_data, node=node)
for result, output_descriptor in zip(results, outputs):
output_descriptor.set(node, result)
real_process.__name__ = process.__name__
real_process.__doc__ = process.__doc__
return real_process
return decorator
def std_links_processing(matcher):
'''Shortcut decorator for "standard" inputs/outputs sockets processing routine.
This is shortcut for combination of @checking_links and @match_inputs.
Inputs and outputs descriptors are taken from node.input_descriptors and
node.output_descriptors correspondingly.
'''
def decorator(process):
def real_process(node):
nonlocal process
process = match_inputs(matcher, node.input_descriptors, node.output_descriptors)(process)
process = checking_links(process)
return process(node)
real_process.__name__ = process.__name__
real_process.__doc__ = process.__doc__
return real_process
return decorator
#####################################################
################# list levels magic #################
#####################################################
# working with nesting levels
# define data floor
# data from nasting to standart: TO container( objects( lists( floats, ), ), )
def dataCorrect(data, nominal_dept=2):
dept = levelsOflist(data)
output = []
if not dept: # for empty lists
return []
if dept < 2:
return [dept, data]
else:
output = dataStandart(data, dept, nominal_dept)
return output
# from standart data to initial levels: to nasting lists container( objects( lists( nasty_lists( floats, ), ), ), ) это невозможно!
def dataSpoil(data, dept):
if dept:
out = []
for d in data:
out.append([dataSpoil(d, dept-1)])
else:
out = data
return out
# data from nasting to standart: TO container( objects( lists( floats, ), ), )
def dataStandart(data, dept, nominal_dept):
deptl = dept - 1
output = []
for object in data:
if deptl >= nominal_dept:
output.extend(dataStandart(object, deptl, nominal_dept))
else:
output.append(data)
return output
return output
# calc list nesting only in countainment level integer
def levelsOflist(lst):
level = 1
for n in lst:
if n and isinstance(n, (list, tuple)):
level += levelsOflist(n)
return level
return 0
#####################################################
################### matrix magic ####################
#####################################################
# tools that makes easier to convert data
# from string to matrixes, vertices,
# lists, other and vise versa
def Matrix_listing(prop):
# matrix degenerate
mat_out = []
for i, matrix in enumerate(prop):
unit = []
for k, m in enumerate(matrix):
# [Matrix0, Matrix1, ... ]
unit.append(m[:])
mat_out.append((unit))
return mat_out
def Matrix_generate(prop):
mat_out = []
for i, matrix in enumerate(prop):
unit = Matrix()
for k, m in enumerate(matrix):
# [Matrix0, Matrix1, ... ]
unit[k] = Vector(m)
mat_out.append(unit)
return mat_out
def Matrix_location(prop, list=False):
Vectors = []
for p in prop:
if list:
Vectors.append(p.translation[:])
else:
Vectors.append(p.translation)
return [Vectors]
def Matrix_scale(prop, list=False):
Vectors = []
for p in prop:
if list:
Vectors.append(p.to_scale()[:])
else:
Vectors.append(p.to_scale())
return [Vectors]
# returns (Vector, rotation) utility function for Matrix Destructor. if list is true
# the Vector is decomposed into tuple format.
def Matrix_rotation(prop, list=False):
Vectors = []
for p in prop:
q = p.to_quaternion()
if list:
vec, angle = q.to_axis_angle()
Vectors.append((vec[:], angle))
else:
Vectors.append(q.to_axis_angle())
return [Vectors]
def Vector_generate(prop):
return [[Vector(v) for v in obj] for obj in prop]
def Vector_degenerate(prop):
return [[v[0:3] for v in obj] for obj in prop]
def Edg_pol_generate(prop):
edg_pol_out = []
if len(prop[0][0]) == 2:
type = 'edg'
elif len(prop[0]) > 2:
type = 'pol'
for ob in prop:
list = []
for p in ob:
list.append(p)
edg_pol_out.append(list)
# [ [(n1,n2,n3), (n1,n7,n9), p, p, p, p...], [...],... ] n = vertexindex
return type, edg_pol_out
def matrixdef(orig, loc, scale, rot, angle, vec_angle=[[]]):
modif = []
for i, de in enumerate(orig):
ma = de.copy()
if loc[0]:
k = min(len(loc[0])-1, i)
mat_tran = de.Translation(loc[0][k])
ma *= mat_tran
if vec_angle[0] and rot[0]:
k = min(len(rot[0])-1, i)
a = min(len(vec_angle[0])-1, i)
vec_a = vec_angle[0][a].normalized()
vec_b = rot[0][k].normalized()
mat_rot = vec_b.rotation_difference(vec_a).to_matrix().to_4x4()
ma = ma * mat_rot
elif rot[0]:
k = min(len(rot[0])-1, i)
a = min(len(angle[0])-1, i)
mat_rot = de.Rotation(radians(angle[0][a]), 4, rot[0][k].normalized())
ma = ma * mat_rot
if scale[0]:
k = min(len(scale[0])-1, i)
scale2 = scale[0][k]
id_m = Matrix.Identity(4)
for j in range(3):
id_m[j][j] = scale2[j]
ma *= id_m
modif.append(ma)
return modif
#####################################################
#################### lists magic ####################
#####################################################
def create_list(x, y):
if type(y) in [list, tuple]:
return reduce(create_list, y, x)
else:
return x.append(y) or x
def enum_item(s):
s = [(i,i,"") for i in s]
return s
def preobrazovatel(list_a, levels, level2=1):
list_tmp = []
level = levels[0]
if level > level2:
if type(list_a)in [list, tuple]:
for l in list_a:
if type(l) in [list, tuple]:
tmp = preobrazovatel(l, levels, level2+1)
if type(tmp) in [list, tuple]:
list_tmp.extend(tmp)
else:
list_tmp.append(tmp)
else:
list_tmp.append(l)
elif level == level2:
if type(list_a) in [list, tuple]:
for l in list_a:
if len(levels) == 1:
tmp = preobrazovatel(l, levels, level2+1)
else:
tmp = preobrazovatel(l, levels[1:], level2+1)
list_tmp.append(tmp if tmp else l)
else:
if type(list_a) in [list, tuple]:
list_tmp = reduce(create_list, list_a, [])
return list_tmp
def myZip(list_all, level, level2=0):
if level == level2:
if type(list_all) in [list, tuple]:
list_lens = []
list_res = []
for l in list_all:
if type(l) in [list, tuple]:
list_lens.append(len(l))
else:
list_lens.append(0)
if list_lens == []:
return False
min_len = min(list_lens)
for value in range(min_len):
lt = []
for l in list_all:
lt.append(l[value])
t = list(lt)
list_res.append(t)
return list_res
else:
return False
elif level > level2:
if type(list_all) in [list, tuple]:
list_res = []
list_tr = myZip(list_all, level, level2+1)
if list_tr is False:
list_tr = list_all
t = []
for tr in list_tr:
if type(list_tr) in [list, tuple]:
list_tl = myZip(tr, level, level2+1)
if list_tl is False:
list_tl = list_tr
t.extend(list_tl)
list_res.append(list(t))
return list_res
else:
return False
#####################################################
################### update List join magic ##########
#####################################################
def myZip_2(list_all, level, level2=1):
def create_listDown(list_all, level):
def subDown(list_a, level):
list_b = []
for l2 in list_a:
if type(l2) in [list, tuple]:
list_b.extend(l2)
else:
list_b.append(l2)
if level > 1:
list_b = subDown(list_b, level-1)
return list_b
list_tmp = []
if type(list_all) in [list, tuple]:
for l in list_all:
list_b = subDown(l, level-1)
list_tmp.append(list_b)
else:
list_tmp = list_all
return list_tmp
list_tmp = list_all.copy()
for x in range(level-1):
list_tmp = create_listDown(list_tmp, level)
list_r = []
l_min = []
for el in list_tmp:
if type(el) not in [list, tuple]:
break
l_min.append(len(el))
if l_min == []:
l_min = [0]
lm = min(l_min)
for elm in range(lm):
for el in list_tmp:
list_r.append(el[elm])
list_tmp = list_r
for lev in range(level-1):
list_tmp = [list_tmp]
return list_tmp
def joiner(list_all, level, level2=1):
list_tmp = []
if level > level2:
if type(list_all) in [list, tuple]:
for list_a in list_all:
if type(list_a) in [list, tuple]:
list_tmp.extend(list_a)
else:
list_tmp.append(list_a)
else:
list_tmp = list_all
list_res = joiner(list_tmp, level, level2=level2+1)
list_tmp = [list_res]
if level == level2:
if type(list_all) in [list, tuple]:
for list_a in list_all:
if type(list_a) in [list, tuple]:
list_tmp.extend(list_a)
else:
list_tmp.append(list_a)
else:
list_tmp.append(list_all)
if level < level2:
if type(list_all) in [list, tuple]:
for l in list_all:
list_tmp.append(l)
else:
list_tmp.append(l)
return list_tmp
def wrapper_2(l_etalon, list_a, level):
def subWrap(list_a, level, count):
list_b = []
if level == 1:
if len(list_a) == count:
for l in list_a:
list_b.append([l])
else:
dc = len(list_a)//count
for l in range(count):
list_c = []
for j in range(dc):
list_c.append(list_a[l*dc+j])
list_b.append(list_c)
else:
for l in list_a:
list_b = subWrap(l, level-1, count)
return list_b
def subWrap_2(l_etalon, len_l, level):
len_r = len_l
if type(l_etalon) in [list, tuple]:
len_r = len(l_etalon) * len_l
if level > 1:
len_r = subWrap_2(l_etalon[0], len_r, level-1)
return len_r
len_l = len(l_etalon)
lens_l = subWrap_2(l_etalon, 1, level)
list_tmp = subWrap(list_a, level, lens_l)
for l in range(level-1):
list_tmp = [list_tmp]
return list_tmp
#####################################################
############### debug settings magic ################
#####################################################
def sverchok_debug(mode):
global DEBUG_MODE
DEBUG_MODE = mode
return DEBUG_MODE
def setup_init():
global DEBUG_MODE
global HEAT_MAP
global SVERCHOK_NAME
import sverchok
SVERCHOK_NAME = sverchok.__name__
addon = bpy.context.user_preferences.addons.get(SVERCHOK_NAME)
if addon:
DEBUG_MODE = addon.preferences.show_debug
HEAT_MAP = addon.preferences.heat_map
else:
print("Setup of preferences failed")
#####################################################
############### heat map system ################
#####################################################
def heat_map_state(state):
global HEAT_MAP
HEAT_MAP = state
sv_ng = [ng for ng in bpy.data.node_groups if ng.bl_idname == 'SverchCustomTreeType']
if state:
for ng in sv_ng:
color_data = {node.name: (node.color[:], node.use_custom_color) for node in ng.nodes}
if not ng.sv_user_colors:
ng.sv_user_colors = str(color_data)
else:
for ng in sv_ng:
if not ng.sv_user_colors:
print("{0} has no colors".format(ng.name))
continue
color_data = ast.literal_eval(ng.sv_user_colors)
for name, node in ng.nodes.items():
if name in color_data:
color, use = color_data[name]
setattr(node, 'color', color)
setattr(node, 'use_custom_color', use)
ng.sv_user_colors = ""
#####################################################
############### update system magic! ################
#####################################################
def updateNode(self, context):
"""
Old, use process_node instead
When a node has changed state and need to call a partial update.
For example a user exposed bpy.prop
"""
self.process_node(context)
##############################################################
##############################################################
############## changable type of socket magic ################
########### if you have separate socket solution #############
#################### wellcome to provide #####################
##############################################################
##############################################################
def changable_sockets(node, inputsocketname, outputsocketname):
'''
arguments: node, name of socket to follow, list of socket to change
'''
in_socket = node.inputs[inputsocketname]
ng = node.id_data
if in_socket.links:
in_other = get_other_socket(in_socket)
if not in_other:
return
outputs = node.outputs
s_type = in_other.bl_idname
if outputs[outputsocketname[0]].bl_idname != s_type:
node.id_data.freeze(hard=True)
to_links = {}
for n in outputsocketname:
out_socket = outputs[n]
to_links[n] = [l.to_socket for l in out_socket.links]
outputs.remove(outputs[n])
for n in outputsocketname:
new_out_socket = outputs.new(s_type, n)
for to_socket in to_links[n]:
ng.links.new(to_socket, new_out_socket)
node.id_data.unfreeze(hard=True)
def get_socket_type_full(node, inputsocketname):
socket = node.inputs[inputsocketname]
other = get_other_socket(socket)
return other.links[0].from_socket.bl_idname
def replace_socket(socket, new_type, new_name=None, new_pos=None):
'''
Replace a socket and keep links
'''
if new_name is None:
new_name = socket.name
socket.name = new_name
# quit early
#if socket.bl_idname == new_type:
# return socket
ng = socket.id_data
ng.freeze()
if socket.is_output:
to_sockets = [l.to_socket for l in socket.links]
outputs = socket.node.outputs
if new_pos is None:
for i,s in enumerate(outputs):
if s == socket:
node_pos = i
break
else:
node_pos = new_pos
outputs.remove(socket)
new_socket = outputs.new(new_type, new_name)
outputs.move(len(outputs)-1, node_pos)
for to_socket in to_sockets:
ng.links.new(new_socket, to_socket)
else:
if socket.is_linked:
from_socket = socket.links[0].from_socket
else:
from_socket = None
inputs = socket.node.inputs
if new_pos is None:
for i,s in enumerate(inputs):
if s == socket:
node_pos = i
break
else:
node_pos = new_pos
inputs.remove(socket)
new_socket = inputs.new(new_type, new_name)
inputs.move(len(inputs)-1, node_pos)
if from_socket:
ng.links.new(from_socket, new_socket)
ng.unfreeze()
return new_socket
def get_other_socket(socket):
"""
Get next real upstream socket.
This should be expanded to support wifi nodes also.
Will return None if there isn't a another socket connect
so no need to check socket.links
"""
if socket.is_linked and not socket.is_output:
other = socket.links[0].from_socket
if other.node.bl_idname == 'NodeReroute':
return get_other_socket(other.node.inputs[0])