-
Notifications
You must be signed in to change notification settings - Fork 4
/
node_helper.py
2018 lines (1602 loc) · 75.7 KB
/
node_helper.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
# -*- coding: utf-8 -*-
import c4d
import maxon
import functools
import Renderer
from typing import Union, Optional, Any
from pprint import pprint
from Renderer.constants.common_id import *
import os, sys, json
# Custom Helper for get the "Converter Port" in trick.
class ConverterPorts:
"""
data = {
"Redshift.json" : {
"com.redshift3d.redshift4c4d.nodes.core.texturesampler" : {
"Name" : "Texture"
"Input" : "None"
"Output": "com.redshift3d.redshift4c4d.nodes.core.texturesampler.outcolor"
}
"com.redshift3d.redshift4c4d.nodes.core.texturesampler" : {
"Name" : "Texture"
"Input" : "com.redshift3d.redshift4c4d.nodes.core.triplanar.imagex"
"Output": "com.redshift3d.redshift4c4d.nodes.core.triplanar.outcolor"
}
}
}
"""
def __init__(self, nodespaceId: maxon.Id) -> None:
self.nodespaceId: maxon.Id = nodespaceId
FILEPATH, f = os.path.split(__file__)
parent_dir = os.path.abspath(os.path.join(FILEPATH, os.pardir))
if self.nodespaceId == RS_NODESPACE:
self.dataPath = os.path.join(parent_dir, 'constants', "Redshift.json")
if self.nodespaceId == AR_NODESPACE:
self.dataPath = os.path.join(parent_dir, 'constants', "Arnold.json")
if not os.path.exists(self.dataPath):
raise FileExistsError(f"the Convertor data is not exsit at {self.dataPath}")
@staticmethod
def InitRedshiftData() -> dict[dict[str]]:
"""
Get the basic data, then save the date and modity it.
This should be used if the data is missing or you want to customizd
Returns:
dict[dict[str]]: teh data we want
"""
repo: maxon.AssetRepositoryRef = maxon.AssetInterface.GetUserPrefsRepository()
if repo.IsNullValue():
raise RuntimeError("Could not access the user preferences repository.")
# latest version assets
nodeTemplateDescriptions: list[maxon.AssetDescription] = repo.FindAssets(
maxon.Id("net.maxon.node.assettype.nodetemplate"), maxon.Id(), maxon.Id(),
maxon.ASSET_FIND_MODE.LATEST)
allShaders: list[str] = [
str(item.GetId()) # asset ID.
for item in nodeTemplateDescriptions
if str(item.GetId()).startswith("com.redshift3d.redshift4c4d.") # Only RS ones
]
output = {}
def _GetOutput(shader):
out_ids = ['outcolor','output','out']
for out in out_ids:
port_id = f"{str(shader.GetValue('net.maxon.node.attribute.assetid'))[1:].split(',')[0]}.{out}"
port: maxon.GraphNode = shader.GetOutputs().FindChild(port_id)
if not port.IsNullValue():
return str(port.GetId())
return ""
def _GetInput(shader):
out_ids = ['color','input','base_color',
'tex0', 'albedo', 'texture',
'input1','x', 'default', 'attribute'
]
for out in out_ids:
port_id = f"{str(shader.GetValue('net.maxon.node.attribute.assetid'))[1:].split(',')[0]}.{out}"
port: maxon.GraphNode = shader.GetInputs().FindChild(port_id)
if not port.IsNullValue():
return str(port.GetId())
return ""
rsNodeSpaceId: maxon.Id = maxon.Id(RS_NODESPACE)
if c4d.GetActiveNodeSpaceId() != rsNodeSpaceId:
raise RuntimeError("Make RS the active renderer and node space to run this script.")
material: c4d.BaseMaterial = c4d.BaseMaterial(c4d.Mmaterial)
if not material:
raise MemoryError(f"{material = }")
nodeMaterial: c4d.NodeMaterial = material.GetNodeMaterialReference()
graph: maxon.NodesGraphModelInterface = nodeMaterial.CreateDefaultGraph(rsNodeSpaceId)
with graph.BeginTransaction() as gt:
for nodeId in allShaders:
data = {}
node = graph.AddChild(maxon.Id(), nodeId)
data["input"] = str(_GetInput(node))
data["output"] = str(_GetOutput(node))
output[f"{str(node.GetValue('net.maxon.node.attribute.assetid'))[1:].split(',')[0]}"] = data
gt.Commit()
c4d.documents.GetActiveDocument().InsertMaterial(material)
c4d.EventAdd()
return output
@staticmethod
def InitArnoldData() -> dict[dict[str]]:
"""
Get the basic data, then save the date and modity it.
This should be used if the data is missing or you want to customizd
Returns:
dict[dict[str]]: teh data we want
"""
repo: maxon.AssetRepositoryRef = maxon.AssetInterface.GetUserPrefsRepository()
if repo.IsNullValue():
raise RuntimeError("Could not access the user preferences repository.")
# latest version assets
nodeTemplateDescriptions: list[maxon.AssetDescription] = repo.FindAssets(
maxon.Id("net.maxon.node.assettype.nodetemplate"), maxon.Id(), maxon.Id(),
maxon.ASSET_FIND_MODE.LATEST)
allShaders: list[str] = [
str(item.GetId()) # asset ID.
for item in nodeTemplateDescriptions
if str(item.GetId()).startswith("com.autodesk.arnold.") # Only Arnold ones
]
output = {}
def _GetOutput(shader):
out_ids = ['outcolor','output','out']
for out in out_ids:
port: maxon.GraphNode = shader.GetOutputs().FindChild(out)
if not port.IsNullValue():
return str(port.GetId())
return ""
def _GetInput(shader):
out_ids = ['color','input','base_color', 'filename',
'tex0', 'albedo', 'texture',
'input1','x', 'default', 'aov_name'
]
for out in out_ids:
port: maxon.GraphNode = shader.GetInputs().FindChild(out)
if not port.IsNullValue():
return str(port.GetId())
return ""
rsNodeSpaceId: maxon.Id = maxon.Id(AR_NODESPACE)
if c4d.GetActiveNodeSpaceId() != rsNodeSpaceId:
raise RuntimeError("Make RS the active renderer and node space to run this script.")
material: c4d.BaseMaterial = c4d.BaseMaterial(c4d.Mmaterial)
if not material:
raise MemoryError(f"{material = }")
nodeMaterial: c4d.NodeMaterial = material.GetNodeMaterialReference()
graph: maxon.NodesGraphModelInterface = nodeMaterial.CreateDefaultGraph(rsNodeSpaceId)
with graph.BeginTransaction() as gt:
for nodeId in allShaders:
data = {}
node = graph.AddChild(maxon.Id(), nodeId)
data["input"] = str(_GetInput(node))
data["output"] = str(_GetOutput(node))
output[f"{str(node.GetValue('net.maxon.node.attribute.assetid'))[1:].split(',')[0]}"] = data
gt.Commit()
c4d.documents.GetActiveDocument().InsertMaterial(material)
c4d.EventAdd()
return output
### Key methods ###
def IsGeneratorNode(self, node: maxon.GraphNode) -> bool:
"""
True if the node don't have a input data. so we call it generator.
Args:
node (maxon.GraphNode): the host node
Returns:
bool: True if the node don't have a input data.
"""
if self.GetConvertInput(node) != "":
return True
return False
def GetConvertInput(self, StrOrNode: Union[str, maxon.GraphNode]) -> str:
"""
Get the default in port of the node.
Args:
StrOrNode (Union[str, maxon.GraphNode]): the node or it's string id.
Returns:
str: the string id of the default in port, else ""
"""
if isinstance(StrOrNode, str):
assetId = StrOrNode
elif isinstance(StrOrNode, maxon.GraphNode):
if StrOrNode.GetKind() == maxon.NODE_KIND.NODE:
assetId = str(StrOrNode.GetValue("net.maxon.node.attribute.assetid"))[1:].split(",")[0]
with open(self.dataPath, 'r', encoding='UTF-8') as file:
data: dict = json.loads(file.read())
# data: dict = read_json(self.dataPath)
item: dict = data.get(assetId,"")
return item.get("input","")
def GetConvertOutput(self, StrOrNode: Union[str, maxon.GraphNode]) -> str:
"""
Get the default out port of the node.
Args:
StrOrNode (Union[str, maxon.GraphNode]): the node or it's string id.
Returns:
str: the string id of the default out port, else ""
"""
if isinstance(StrOrNode, str):
assetId = StrOrNode
elif isinstance(StrOrNode, maxon.GraphNode):
if StrOrNode.GetKind() == maxon.NODE_KIND.NODE:
assetId = str(StrOrNode.GetValue("net.maxon.node.attribute.assetid"))[1:].split(",")[0]
with open(self.dataPath, 'r', encoding='UTF-8') as file:
data: dict = json.loads(file.read())
#data: dict = read_json(self.dataPath)
item: dict = data.get(assetId,"")
return item.get("output","")
# Custom Helper for New Node Materials Graph
class NodeGraghHelper:
"""
Custom helper for NodeGragh Material in Cinema 4D Node Editor.
Warp with maxon api and add some daliy functions.
"""
#=============================================
# Basic
#=============================================
def __init__(self, material: c4d.BaseMaterial):
"""
A Custom NodeHelper for Node Material. Need a material to initalize the instance.
Args:
material (c4d.BaseMaterial): the BaseMaterial instance from the C4D document.
"""
self._support_renderers: list = [
"net.maxon.nodespace.standard",
"com.autodesk.arnold.nodespace",
"com.redshift3d.redshift4c4d.class.nodespace",
"com.chaos.class.vray_node_renderer_nodespace"
]
if not isinstance(material, c4d.BaseMaterial):
raise ValueError("The material is not a valid BaseMaterial instance.")
self.material: c4d.BaseMaterial = material
if self.material:
# get node material ref
self.nodeMaterial: c4d.NodeMaterial = self.material.GetNodeMaterialReference()
# check support node space
for nid in self._support_renderers:
if not self.nodeMaterial.HasSpace(nid):
continue
# node
self.nodespaceId: maxon.Id = c4d.GetActiveNodeSpaceId()
if self.nodespaceId is None:
raise ValueError("Cannot retrieve the NodeSpace.")
self.nimbusRef: maxon.NimbusBaseRef = self.material.GetNimbusRef(self.nodespaceId)
if self.nimbusRef is None:
raise ValueError("Cannot retrieve the nimbus reference for that NodeSpace.")
self.graph: maxon.GraphModelRef = self.nodeMaterial.GetGraph(self.nodespaceId)
if self.graph.IsNullValue():
raise ValueError("Cannot retrieve the graph of this nimbus NodeSpace.")
self.root: maxon.GraphNode = self.graph.GetRoot()
def __str__(self):
return (f"A {self.__class__.__name__} Instance with Material : {self.material.GetName()}")
# decorator 装饰器 打印函数名称和返回值
def PirntMe(func) -> None:
"""
decorator to print the function name and the return value.
**Example**
.. code-block:: python
@PirntMe
def GetAssetId(self, *args, **kwargs):
pass
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f"Function {func.__name__} return : {result = }")
return result
return wrapper
#=============================================
# Util
#=============================================
# 包装maxon数据转换,把数据强制转换为maxon数据类型
def _ConvertData(self, data: Any) -> maxon.data:
"""
Convert the data to maxon data type for safely.
Args:
data (Any): the data to convert
Returns:
maxon.data: the converted data
"""
return maxon.MaxonConvert(data, maxon.CONVERSIONMODE.TOMAXON)
# 获取资产ID 只有node有asset id ==> ok
def GetAssetId(self, node: maxon.GraphNode) -> str:
"""
Returns the asset id of the given node.
Args:
node (maxon.GraphNode): the shader node
Returns:
str: Asset id of the given node, only true node had asset id.
Example:
"com.redshift3d.redshift4c4d.nodes.core.standardmaterial"
"""
if not isinstance(node, maxon.GraphNode) and node.GetKind() != maxon.NODE_KIND.NODE:
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a true node GraphNode, got {type(node)}')
return str(node.GetValue("net.maxon.node.attribute.assetid"))[1:].split(",")[0]
# 获取ShaderID ==> ok
def GetShaderId(self, node: maxon.GraphNode) -> str:
"""
Returns the node id(No prefix) of the given node.
Args:
node (maxon.GraphNode): the shader node
Returns:
str: the node id(No prefix) of the given node
Example:
"standardmaterial"
"""
if not isinstance(node, maxon.GraphNode) and node.GetKind() != maxon.NODE_KIND.NODE:
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a true node GraphNode, got {type(node)}')
# True node
shaderId = self.GetAssetId(node).split('.')[-1]
# Group node
if not shaderId:
shaderId = str(node.GetId()).split('@')[0]
return shaderId
# NOTE:获取节点名 ==> ok
def GetName(self, node: maxon.GraphNode) -> Optional[str]:
"""
Retrieve the displayed name of a node.
Args:
node (maxon.GraphNode): the node
Returns:
Optional[str]: the name of the ndoe
"""
if not isinstance(node, maxon.GraphNode):# or node.GetKind() != maxon.NODE_KIND.NODE:
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a node GraphNode, got {type(node)}')
nodeName = node.GetValue(maxon.NODE.BASE.NAME)
# 此函数在2024.4.0中可以返回正确的值
# 在2024.2.0中返回None
if nodeName is None:
nodeName = node.GetValue(maxon.EffectiveName)
if nodeName is None:
nodeName = str(node)
return nodeName
# 设置节点名
def SetName(self, node: maxon.GraphNode, name: str) -> bool:
"""
Set the name of a node.
Args:
node (maxon.GraphNode): the node
name (str): the name of the node
Returns:
bool: True if the name has been changed.
"""
if not isinstance(node, maxon.GraphNode) and node.GetKind() != maxon.NODE_KIND.NODE:
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a true node GraphNode, got {type(node)}')
# if not isinstance(name, str):
# raise ValueError('Expected a String, got {}'.format(type(name)))
node.SetValue(maxon.NODE.BASE.NAME, self._ConvertData(str(name)))
return True
# 选择 ==> ok
def Select(self, node: maxon.GraphNode) -> maxon.GraphNode:
"""
Select a port or node.
Args:
node (maxon.GraphNode): the node to select
Returns:
maxon.GraphNode: the node self
"""
if not isinstance(node, maxon.GraphNode):
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a GraphNode, got {type(node)}')
maxon.GraphModelHelper.SelectNode(node)
return node
# 取消选择 ==> ok
def Deselect(self,node: maxon.GraphNode) -> maxon.GraphNode:
"""
Deselect a port or node.
Args:
node (maxon.GraphNode): the node to deselect
Returns:
maxon.GraphNode: the node self
"""
if not isinstance(node, maxon.GraphNode):
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a GraphNode, got {type(node)}')
maxon.GraphModelHelper.DeselectNode(node)
return node
# 获取Output Node ==> ok
def GetOutput(self) -> maxon.GraphNode:
"""
Returns the end node.
Returns:
maxon.GraphNode: the end node of this graph
"""
# Retrieve the end node of this graph
endNodePath = self.nimbusRef.GetPath(maxon.NIMBUS_PATH.MATERIALENDNODE)
endNode = self.graph.GetNode(endNodePath)
return endNode
# 获取此节点空间默认纹理节点(节点数据) ==> ok
def GetImageNodeID(self, include_portData: bool = False) -> Union[maxon.Id, tuple]:
"""
Returns the image node id (and it's port data).
Need to convert the NodePath to a string, this is a bug that is going to be fixed in 2024.2
Returns:
maxon.GraphNode: the image node id of this graph
portData
.. code-block:: python
portData = [
outColorPortId = portData[0], # The result port.
inTexturePortId = portData[1], # The URL of the input image.
inStartFramePortId = portData[2], # The index of the starting frame.
inEndFramePortId = portData[3] # The index of the ending frame.
]
"""
# Retrieve the nodespace id from the graph
spaceContext = self.root.GetValue(maxon.nodes.NODESPACE.NodeSpaceContext)
nodeSpaceId = spaceContext.Get(maxon.nodes.NODESPACE.SPACEID)
# Thanks Maxime!
# Retrieve the nodespace data, and its default picture node with the associated port Id
if c4d.GetC4DVersion() < 2024200:
# --- Temporary add NodeSpaceHelpersInterface.GetNodeSpaceData()
# This is going to be added in 2024.2 as maxon.NodeSpaceHelpersInterface.GetNodeSpaceData() --------------------------
@maxon.interface.MAXON_INTERFACE_NONVIRTUAL(maxon.consts.MAXON_REFERENCE_STATIC, "net.maxon.nodes.interface.nodespacehelpers")
class NodeSpaceHelpersInterface:
@staticmethod
@maxon.interface.MAXON_STATICMETHOD("net.maxon.nodes.interface.nodespacehelpers.GetNodeSpaceData")
def GetNodeSpaceData(spaceId):
pass
# --- End of fix -----------------------------------------------------------------------------------
spaceData = NodeSpaceHelpersInterface.GetNodeSpaceData(nodeSpaceId)
else:
spaceData = maxon.NodeSpaceHelpersInterface.GetNodeSpaceData(nodeSpaceId)
assetId = spaceData.Get(maxon.nodes.NODESPACE.IMAGENODEASSETID)
if include_portData:
portData = spaceData.Get(maxon.nodes.NODESPACE.IMAGENODEPORTS)
return (assetId, portData)
return assetId
# 切换预览 ==> ok
def FoldPreview(self, nodes: list[maxon.GraphNode] ,state: bool = False) -> bool:
"""
Toggle folding state of given nodes.
Args:
nodes (list[maxon.GraphNode]): the nodes list
state (bool, optional): the folding state, False to hide preview. Defaults to False.
Returns:
bool: True if the state has been changed.
"""
if isinstance(nodes, maxon.GraphNode):
nodes = [nodes]
for graph_node in nodes:
graph_node.SetValue(maxon.NODE.BASE.DISPLAYPREVIEW , maxon.Bool(state))
return True
# 获取属性 ==> ok
def GetShaderValue(self, node: maxon.GraphNode, paramId: Union[maxon.Id,str]=None) -> maxon.Data:
"""
Returns the value stored in the given shader parameter.
Args:
node (maxon.GraphNode): the node
paramId (Union[maxon.Id,str], optional): the port id. Defaults to None.
Returns:
maxon.Data: the value assigned to this port
"""
# standard data type
port: maxon.GraphNode = self.GetPort(node,paramId)
self.GetPortData(port)
# 设置属性 ==> ok
def SetShaderValue(self, node: maxon.GraphNode, paramId: Union[maxon.Id,str]=None, value=None) -> bool:
"""
Sets the value stored in the given shader parameter.
Args:
node (maxon.GraphNode): the node
paramId (Union[maxon.Id,str], optional): the port id. Defaults to None.
value (_type_, optional): the value to set. Defaults to None.
Returns:
bool: True if the value has been changed.
"""
port: maxon.GraphNode = self.GetPort(node,paramId)
return self.SetPortData(port, value)
# 获取端口属性 ==> ok
def GetPortData(self, port: maxon.GraphNode) -> any:
"""
Gets the value to the given port.
Args:
node (maxon.GraphNode): the node
Returns:
bool: True if the value has been changed.
"""
# standard data type
if not self.IsPortValid(port):
raise ValueError(f"Input {port} is not a valid port")
if c4d.GetC4DVersion() >= 2024400:
return port.GetPortValue()
# "effectivename" is None when a wire filled into the port
elif 2024000 <= c4d.GetC4DVersion() < 2024400:
return port.GetValue("value")
else:
try:
return port.GetValue("value")
except:
return port.GetDefaultValue()
# 设置端口属性 ==> ok
def SetPortData(self, port: maxon.GraphNode, value) -> bool:
"""
Sets the value to the given port.
Args:
node (maxon.GraphNode): the node
paramId (Union[maxon.Id,str], optional): the port id. Defaults to None.
value (_type_, optional): the value to set. Defaults to None.
Returns:
bool: True if the value has been changed.
"""
if not self.IsPortValid(port):
raise ValueError(f"Input {port} is not a valid port")
return port.SetValue("net.maxon.description.data.base.defaultvalue", self._ConvertData(value))
# if c4d.GetC4DVersion() >= 2024400:
# return port.SetPortValue(maxon_value)
# return port.SetDefaultValue(maxon_value)
# 获取所有Shader ==> ok
def GetAllShaders(self, mask: Union[str,maxon.Id] = None) -> list[maxon.GraphNode]:
"""
Get all shaders from the graph. can filter by a mask.
Args:
mask (Union[str,maxon.Id], optional): String filter to get specific nodes. Defaults to None.
Returns:
list[maxon.GraphNode]: list of nodes
"""
shaders_list: list = []
# 创建shader list
def _IterGraghNode(node, shaders_list: list):
if node.GetKind() != maxon.NODE_KIND.NODE:
return
if self.GetAssetId(node) == "net.maxon.node.group":
for node in self.root.GetChildren():
_IterGraghNode(node, shaders_list)
return
if mask:
if self.GetAssetId(node) == mask or self.GetShaderId(node) == mask:
shaders_list.append(node)
else:
shaders_list.append(node)
#root = self.graph.GetRoot()
for node in self.root.GetChildren():
_IterGraghNode(node, shaders_list)
return shaders_list
# New 节点或者端口是否被链接 ==> ok
def IsConnected(self, NodeorPort: maxon.GraphNode, port: Union[maxon.GraphNode,str] = None) -> bool:
"""Check if a node or a port is connected.
Args:
NodeorPort (maxon.GraphNode, optional): Node or port to check. Defaults to None.
port (Union[maxon.GraphNode,str], optional): Port to check. Defaults to None.
Returns:
bool: True if connected, False otherwise.
"""
# only first #arg
if isinstance(NodeorPort, maxon.GraphNode) and port is None:
if self.IsNodeConnected(NodeorPort) or self.IsPortConnected(NodeorPort):
return True
return False
# both #args filled
else:
if isinstance(NodeorPort,maxon.GraphNode) and isinstance(port,maxon.GraphNode):
# this will crash if port is None
return maxon.GraphModelHelper.IsConnected(NodeorPort,port)
return False
return False
# New 移除独立节点 ==> ok
def RemoveIsolateNodes(self, filterId: str = None) -> None:
"""
Remove all the isolate shaders(not connected to any ports or nodes),filled filter to only apply to specfic asset id.
Args:
filterId (str, optional): the asset id of the nodes to apply. Defaults to None.
"""
for node in self.GetAllShaders():
if not self.IsNodeConnected(node):
if filterId:
if self.GetAssetId(node) == filterId and self.GetShaderId(node) != "scaffold":
node.Remove()
else:
node.Remove()
# New 备注节点 ==> ok
def Scaffold(self, node_list: list[maxon.GraphNode], name: str = "Scaffold") -> maxon.GraphNode:
"""
Create a scaffold node with the given nodes.
Args:
node_list (list[maxon.GraphNode]): the list of nodes to use as inputs.
name (str, optional): the name of the scaffold node. Defaults to "Scaffold".
Returns:
maxon.GraphNode: the created scaffold node.
"""
if not isinstance(node_list, list):
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a list of true node GraphNodes, got {type(node)}')
scaffold_node = self.AddShader("net.maxon.node.scaffold")
self.SetName(scaffold_node, name)
for node in node_list:
node.SetValue("net.maxon.node.attribute.scaffoldid", scaffold_node.GetId())
return scaffold_node
# New 是否为组 ==> ok
def IsGroup(self, node: maxon.GraphNode) -> bool:
if not isinstance(node, maxon.GraphNode):
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a true node GraphNodes, got {type(node)}')
return node.GetValue("isgroup")
# New 是不是生成类节点:没有默认的输入端
def IsGeneratorNode(self, node: maxon.GraphNode) -> bool:
"""
True if the node don't have a input data. so we call it generator.
Args:
node (maxon.GraphNode): the host node
Returns:
bool: True if the node don't have a input data.
"""
return ConverterPorts(self.nodespaceId).IsGeneratorNode(node)
# New 获取默认输入端口
def GetConvertInput(self, node: maxon.GraphNode) -> Optional[str]:
"""
Get the Convert port of a node, this is a custom solution in python, only used to get "defaut" port.
Args:
node (maxon.GraphNode): the host node.
Returns:
str: the id of the port, or None
"""
res = ConverterPorts(self.nodespaceId).GetConvertInput(node)
return res if res != "" else None
# New 获取默认输出端口
def GetConvertOutput(self, node: maxon.GraphNode) -> Optional[str]:
"""
Get the Convert port of a node, this is a custom solution in python, only used to get "defaut" port.
Args:
node (maxon.GraphNode): the host node.
Returns:
str: the id of the port, or None
"""
res = ConverterPorts(self.nodespaceId).GetConvertOutput(node)
return res if res != "" else None
#=============================================
# Node
#=============================================~~
# 当前NodeSpace下所有可用的shader ==> ok
def GetAvailableShaders(self) -> list[maxon.Id]:
"""
Get all available node assets for active nodespace
----------
:return: list of all available shader node.
:rtype: maxon.GraphNode
"""
repo: maxon.AssetRepositoryRef = maxon.AssetInterface.GetUserPrefsRepository()
if repo.IsNullValue():
raise RuntimeError("Could not access the user preferences repository.")
# latest version assets
nodeTemplateDescriptions: list[maxon.AssetDescription] = repo.FindAssets(
maxon.Id("net.maxon.node.assettype.nodetemplate"), maxon.Id(), maxon.Id(),
maxon.ASSET_FIND_MODE.LATEST)
if self.nodespaceId == RS_NODESPACE:
return [
item.GetId() # asset ID.
for item in nodeTemplateDescriptions
if str(item.GetId()).startswith("com.redshift3d.redshift4c4d.") # Only RS ones
]
elif self.nodespaceId == AR_NODESPACE:
return [
item.GetId() # asset ID.
for item in nodeTemplateDescriptions
if str(item.GetId()).startswith("com.autodesk.arnold.") # Only AR ones
]
# 选择的节点 ==> ok
def GetActiveNodes(self, single_mode: bool = True, callback: callable = None) -> Union[maxon.GraphNode, list[maxon.GraphNode]]:
"""
Gets the selected nodes, return a list of them.
Args:
sigle_mode (bool): True to anble if only one node selected,return the node but not the list.
callback (callable, optional): A callback, had a ``maxon.GraphNode`` argument. Defaults to None.
Returns:
Union[maxon.GraphNode, list[maxon.GraphNode]]: the list of selected nodes.
"""
if callback:
with self.graph.BeginTransaction() as transaction:
result = maxon.GraphModelHelper.GetSelectedNodes(self.graph, maxon.NODE_KIND.NODE, callback)
transaction.Commit()
else:
result = maxon.GraphModelHelper.GetSelectedNodes(self.graph, maxon.NODE_KIND.NODE)
if single_mode:
if len(result) == 1:
return result[0]
return result
# 创建Shader ==> ok
def AddShader(self, nodeId: Union[str, maxon.Id]) -> maxon.GraphNode:
"""
Adds a new shader to the graph.
Args:
nodeId (Union[str, maxon.Id]): shader id
Returns:
maxon.GraphNode: the shader we added.
"""
return self.graph.AddChild(childId=maxon.Id(), nodeId=nodeId, args=maxon.DataDictionary())
# 创建Shader 可以提供链接 ==> ok
def AddConnectShader(self, nodeID: Union[str, maxon.Id] = None,
input_ports: list[Union[str,maxon.GraphNode]] = None, connect_inNodes: list[maxon.GraphNode] = None,
output_ports: list[Union[str,maxon.GraphNode]] = None, connect_outNodes: list[maxon.GraphNode] = None,
remove_wires: bool = True
) -> Optional[maxon.GraphNode] :
"""
Add shader and connect with given ports and nodes.
Args:
nodeID (Union[str, maxon.Id], optional): the shader id. Defaults to None.
input_ports (list[Union[str,maxon.GraphNode]], optional): the input port list. Defaults to None.
connect_inNodes (list[maxon.GraphNode], optional): the node list connect to inputs. Defaults to None.
output_ports (list[Union[str,maxon.GraphNode]], optional): the output port list. Defaults to None.
connect_outNodes (list[maxon.GraphNode], optional): the node list connect to outputs. Defaults to None.
remove_wires (bool, optional): True to remove all original wires. Defaults to True.
Returns:
Optional[maxon.GraphNode]: the node we added.
"""
shader: maxon.GraphNode = self.AddShader(nodeID)
# progress the ports data
if (isinstance(input_ports,maxon.GraphNode) or isinstance(input_ports,str)) and not isinstance(input_ports,list):
input_ports = [input_ports]
elif input_ports is None:
input_ports = []
if (isinstance(output_ports,maxon.GraphNode) or isinstance(output_ports,str)) and not isinstance(output_ports,list):
output_ports = [output_ports]
elif output_ports is None:
output_ports = []
if isinstance(connect_inNodes,maxon.GraphNode) and not isinstance(connect_inNodes,list):
connect_inNodes = [connect_inNodes]
elif connect_inNodes is None:
connect_inNodes = []
if isinstance(connect_outNodes,maxon.GraphNode) and not isinstance(connect_outNodes,list):
connect_outNodes = [connect_outNodes]
elif connect_outNodes is None:
connect_outNodes = []
# remove original wires connected to the ports
if remove_wires:
try:
# todo
ports: list[maxon.GraphNode] = input_ports + output_ports + connect_inNodes + connect_outNodes
for port in ports:
if port is not None:
self.RemoveConnection(port)
# except Exception as error:
# print(f"AddConnectShader {error = }")
finally:
pass
# connect with ports data
if input_ports is not None:
if connect_inNodes is not None:
if len(connect_inNodes) > len(input_ports):
raise ValueError(f'{sys._getframe().f_code.co_name} Error: Port nodes can not bigger than input port.')
if len(input_ports) > len(connect_inNodes):
input_ports = input_ports[:len(connect_inNodes)]
for i, input_port in enumerate(input_ports):
input: maxon.GraphNode = self.GetPort(shader,input_port)
connect_inNodes[i].Connect(input)
if output_ports is not None:
if connect_outNodes is not None:
if len(connect_outNodes) > len(output_ports):
raise ValueError(f'{sys._getframe().f_code.co_name} Error: Port nodes can not bigger than output port.')
if len(output_ports) > len(connect_outNodes):
output_ports = output_ports[:len(connect_outNodes)]
for i, output_port in enumerate(output_ports):
output: maxon.GraphNode = self.GetPort(shader,output_port)
output.Connect(connect_outNodes[i])
return shader
# 在Wire中插入Shader (New) ==> ok
def InsertShader(self, nodeID: Union[str,maxon.Id], wireData: Union[maxon.Wires, list[maxon.GraphNode]],
input_port: list[Union[str,maxon.GraphNode]],
output_port: list[Union[str,maxon.GraphNode]]) -> Optional[maxon.GraphNode]:
"""
Insert a shder into a wire, and keep connect.
Args:
nodeID (Union[str,maxon.Id]): the node id
wireData (list[maxon.GraphNode,maxon.Wires]): a wire or a data bundle with a list a ``in`` and ``out`` port
input_port (list[Union[str,maxon.GraphNode]]): the input port of the insert node
output_port (list[Union[str,maxon.GraphNode]]): the output port of the insert node
Returns:
Optional[maxon.GraphNode]: the node we added.
"""
if not wireData:
wireData: list[maxon.GraphNode,maxon.Wires] = self.GetActiveWires() # last select wire
pre_port: maxon.GraphNode = wireData[0]
if not self.IsPort(pre_port):
raise ValueError(f'{sys._getframe().f_code.co_name} wireData Error: cannot get a out-port form wireData')
next_port: maxon.GraphNode = wireData[1]
if not self.IsPort(next_port):
raise ValueError(f'{sys._getframe().f_code.co_name} wireData Error: cannot get a in-port form wireData')
# remove wire
if isinstance(pre_port, maxon.GraphNode) or isinstance(next_port, maxon.GraphNode):
self.RemoveConnection(next_port,pre_port)
# add our new shader and wires
return self.AddConnectShader(nodeID,input_port,pre_port,output_port,next_port)
# 删除Shader ==> ok
def RemoveShader(self, shader: maxon.GraphNode, keep_wire: bool = True) -> bool:
"""
Removes the given shader from the graph.
Args:
shader (maxon.GraphNode): the shader to remove
keep_wire (bool, optional): True to keep the wire across this shader. Defaults to True.
Returns:
_type_: True to keep loop
"""
if not isinstance(shader, maxon.GraphNode):
raise ValueError(f'{sys._getframe().f_code.co_name} Expected a true node GraphNode, got {type(shader)}')
if not keep_wire:
shader.Remove()
return True
else:
before = []