-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathredshift_node.py
More file actions
858 lines (741 loc) · 29.2 KB
/
redshift_node.py
File metadata and controls
858 lines (741 loc) · 29.2 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
# Last Update 2023 06 25
#
# Custom Redshift API
#
# Cinema 4D build R2023 @Redshift 3.5.16
#
# Author: DunHou
# Updated by: HerzogVonWiesel (Jérôme Stephan)
#
# Only For Redshift Node Materials
#
# To be Continued
#
#=============================================
# Updates
#=============================================
"""
22/07/... : 功能实现 测试
22/08/16 :
适配注释 VS Code ==> Better Comments插件
22/08/16 :
引用redshift_ID包 常用ID在VsCode中自动补全。
替换原始字符串定义方式
22/08/20 :
精简删除 {未完成} 或 {未测试完成} 的函数 ==> 等待补充
"""
#=============================================
# Libs
#=============================================
import c4d
import maxon
import maxon.frameworks.nodespace
import maxon.frameworks.nodes
import maxon.frameworks.graph
import redshift_ID as rsID # Commonly Used IDs for Redshift
#=============================================
# ID
#=============================================
StandardMaterialAssetID = rsID.ShaderID.StandardMaterial # maxon.Id("com.redshift3d.redshift4c4d.nodes.core.standardmaterial") # standard surface node
StandardOutputPortID = rsID.PortID.standard_outcolor # maxon.Id("com.redshift3d.redshift4c4d.nodes.core.standardmaterial.outcolor") # standard surface output
OutputMaterialAssetID = rsID.ShaderID.Output # maxon.Id("com.redshift3d.redshift4c4d.node.output") # Output node
OutputSurfacePortID = rsID.PortID.Output_Surface # maxon.Id("com.redshift3d.redshift4c4d.node.output.surface") # Output node surface
OutDisplacementPortID = rsID.PortID.Output_Displacement # maxon.Id("com.redshift3d.redshift4c4d.node.output.displacement") # Output node displacement
ImageNodeID = rsID.StrtoMaxonID(rsID.StrNodeID("texturesampler")) # maxon.Id("com.redshift3d.redshift4c4d.nodes.core.texturesampler") # texture node
ColorCorrectionNodeID = rsID.StrtoMaxonID(rsID.StrNodeID("rscolorcorrection")) # maxon.Id("com.redshift3d.redshift4c4d.nodes.core.rscolorcorrection") # color correct
RS_NODESPACE = "com.redshift3d.redshift4c4d.class.nodespace" # node space
RS_MATERIAL_END_NODE = "com.autodesk.Redshift.material" # old mat
RS_SHADER_PREFIX = "com.redshift3d.redshift4c4d.nodes.core." # prefix
RS_NODESPACE = "com.redshift3d.redshift4c4d.class.nodespace" # node space
RS_MATERIAL_END_NODE = "com.autodesk.Redshift.material"
RS_SHADER_PREFIX = "com.redshift3d.redshift4c4d.nodes.core."
ID_PREFERENCES_NODE = 465001632 # Prefs ID
ID_REDSHIFT = 1036219 # Redshift
doc = c4d.documents.GetActiveDocument()
#=============================================
# Common Functions
#=============================================
# 确认当前渲染器是Redshift
# 且首选项设置为Node材质
def RedshiftNodeBased():
"""
1.Check current Render Engine is Redshift
2.Preference Redshift material type is Node
Returns:
bool
"""
RenderEngine = doc.GetActiveRenderData()[c4d.RDATA_RENDERENGINE]
prefs = c4d.plugins.FindPlugin(ID_PREFERENCES_NODE)
if not isinstance(prefs, c4d.BaseList2D):
raise RuntimeError("Could not access preferences node.")
# Redshift Node
if RenderEngine == ID_REDSHIFT:
descIdSettings = c4d.DescID(
c4d.DescLevel(1036220, 1, 465001632), # pref ID Redshift
c4d.DescLevel(888, 133, 465001632)
)
# Set
prefsset = prefs[descIdSettings]
if prefsset[c4d.PREFS_REDSHIFT_USE_NODE_MATERIALS] == False: # Legacy
#isNode = False
return False
elif prefsset[c4d.PREFS_REDSHIFT_USE_NODE_MATERIALS] == True: # Node
#isNode = True
return True
def GetActiveGraphModelRef() -> maxon.NodesGraphModelRef:
"""Returns the Nodes graph of the active document.
"""
# Get the scene nodes scene hook.
sceneNodesHook = doc.FindSceneHook(c4d.SCENENODES_IDS_SCENEHOOK_ID)
if not sceneNodesHook:
raise RuntimeError("Could not retrieve Scene Nodes scene hook.")
# Get the scene nodes graph from the hook.
sceneNodesHook.Message(maxon.neutron.MSG_CREATE_IF_REQUIRED)
sceneNodes = sceneNodesHook.GetNimbusRef(maxon.neutron.NODESPACE)
if not sceneNodes:
raise RuntimeError("Could not retrieve Scene Nodes graph model.")
graph = sceneNodes.GetGraph()
if graph.IsReadOnly():
raise RuntimeError("Scene Nodes graph is read only.")
return graph
def GetActiveNodeGraph(dispaly=False):
mat = doc.GetActiveMaterial()
if mat is None:
raise ValueError("Cannot get a Material")
# Retrieve the reference of the material as a node Material.
nodeMaterial = mat.GetNodeMaterialReference()
if nodeMaterial is None:
raise ValueError("Cannot retrieve nodeMaterial reference")
nimbusRef = mat.GetNimbusRef(RS_NODESPACE)
# print("nimbusRef " + str(nimbusRef))
if nimbusRef is None:
raise ValueError("Cannot retrieve the nimbus ref for that node space")
# Retrieve the graph corresponding to that node space.
graph = nimbusRef.GetGraph()
if dispaly == True:
print("graph " + str(graph))
if graph is None:
raise ValueError("Cannot retrieve the graph of this nimbus ref")
return graph
# 创建Standard Surface
def CreateStandardSurface(name):
"""
Creates a new Redshift Starndard Surface Material with a NAME.
Args:
name (str): Name of the Material
Returns:
Material: Redshift Material instance
"""
standardMaterial = RedshiftNodeMaterial.Create(name)
if standardMaterial is None or standardMaterial.material is None:
raise Exception("Failed to create Redshift Standard Surface Material")
with RSMaterialTransaction(standardMaterial) as transaction:
oldrs = standardMaterial.GetRootBRDF()
output = standardMaterial.GetRSOutput()
standardMaterial.RemoveShader(oldrs)
standard_surface = standardMaterial.AddShader("standardmaterial")
standardMaterial.AddConnection(standard_surface,rsID.PortStr.standard_outcolor, output, rsID.PortStr.Output_Surface)
return standardMaterial
#=============================================
# Redshift Node Material
#=============================================
class RedshiftNodeMaterial:
# 初始化 ==> OK
def __init__(self, material):
self.material = material
self.graph = None
self.nimbusRef = self.material.GetNimbusRef(RS_NODESPACE)
#self.node = maxon.GraphNode # Type of 5 :[true node, input port, output port, input port list, output port list]
if self.material is not None:
nodeMaterial = self.material.GetNodeMaterialReference()
self.graph = nodeMaterial.GetGraph(RS_NODESPACE)
if self.graph is None:
print("[WARNING] Node space is not found in Node Material: %s" % self.material.GetName())
# ===== Add ===== #
# 创建材质 ==> OK
def Create(name):
"""
Creates a new Redshift Node Material with a NAME.
Parameters
----------
name : str
The Material entry name.
"""
# Retrieve the selected baseMaterial
material = c4d.BaseMaterial(c4d.Mmaterial)
if material is None:
raise ValueError("Cannot create a BaseMaterial")
material.SetName(name)
# Retrieve the reference of the material as a node Material.
nodeMaterial = material.GetNodeMaterialReference()
if nodeMaterial is None:
raise ValueError("Cannot retrieve nodeMaterial reference")
# Add a graph for the redshift node space
nodeMaterial.AddGraph(RS_NODESPACE)
# Return a redshift node material
return RedshiftNodeMaterial(material)
# 创建Shader ==> OK
def AddShader(self, nodeId, useStr=True):
"""
Adds a new shader to the graph.
Parameters
----------
nodeId : str
The Redshift node entry name.
useStr : bool
True : only inpput node name
False: inpput full node id
"""
if self.graph is None:
return None
if useStr == True:
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
else:
shader = self.graph.AddChild("", nodeId, maxon.DataDictionary())
return shader
# 创建color correct ==> OK
def AddColorCorrect(self):
"""
Adds a new color correct shader to the graph.
"""
if self.graph is None:
return None
nodeId = "rscolorcorrection"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
return shader
# 创建ramp ==> OK
def AddRamp(self):
"""
Adds a new ramp shader to the graph.
"""
if self.graph is None:
return None
nodeId = "rsramp"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
return shader
# 创建scalar ramp ==> OK
def AddScalarRamp(self):
"""
Adds a new scalar ramp shader to the graph.
"""
if self.graph is None:
return None
nodeId = "rsscalarramp"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
return shader
# 创建maxon noise ==> OK
def AddMaxonNoise(self):
"""
Adds a new maxonnoise shader to the graph.
"""
if self.graph is None:
return None
nodeId = "maxonnoise"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
return shader
# 创建displacement ==> OK
def AddDisplacement(self):
"""
Adds a new displacement shader to the graph.
"""
if self.graph is None:
return None
nodeId = "displacement"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
return shader
# todo AddTexture ==> 设置贴图ok 名称ok 贴图路径ok raw\sRGB ok
# todo 待完成 判断贴图并连接到指定端口 ==> 判断rough贴图到rough接口 并且设置名称和raw
def AddTexture(self, shadername, filepath, colorspace: str='RS_INPUT_COLORSPACE_RAW'): # Use '' as colorspace to choose Auto
"""
Adds a new texture shader to the graph.
"""
if self.graph is None:
return None
nodeId = "texturesampler"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
texPort = shader.GetInputs().FindChild("com.redshift3d.redshift4c4d.nodes.core.texturesampler.tex0")
texFilenamePort = texPort.FindChild('path')
colorspacePort = texPort.FindChild("colorspace")
texFilenamePort.SetDefaultValue(filepath)
colorspacePort.SetDefaultValue(colorspace)
self.SetShaderName(shader,shadername)
return shader
def AddSprite(self, filepath, colorspace: str='RS_INPUT_COLORSPACE_RAW'):
"""
Adds a new sprite shader to the graph.
"""
if self.graph is None:
return None
nodeId = "sprite"
shader = self.graph.AddChild("", "com.redshift3d.redshift4c4d.nodes.core." + nodeId, maxon.DataDictionary())
texPort = shader.GetInputs().FindChild("com.redshift3d.redshift4c4d.nodes.core.sprite.tex0")
texFilenamePort = texPort.FindChild('path')
colorspacePort = texPort.FindChild("colorspace")
texFilenamePort.SetDefaultValue(filepath)
colorspacePort.SetDefaultValue(colorspace)
return shader
# ===== Add To ===== #
# 创建Shader并连接到指定节点的指定端口 ==> OK
def AddShaderTo(self, shader_Id, shader_port, target_shader, target_port):
"""
Adds a new shader to the given port of given node.
Parameters
----------
shader_Id : str
The Redshift node entry name.
shader_port : str
the shader output port id
target_node : str
target shader to connect
target_port : str
target shader input port to connect
"""
source_node = self.AddShader(shader_Id)
self.AddConnection(source_node, shader_port, target_shader, target_port)
return source_node
# 创建color correct并且链接到指定节点的指定端口 ==> OK
def AddColorCorrectTo(self, target_shader, target_port):
"""
Adds a new color correct shader to the given port of given node.
Parameters
----------
targret_shader : str
target shader to connect
target_port : str
target shader input port to connect
"""
node = self.AddColorCorrect()
outPort = rsID.StrPortID("rscolorcorrection", "outcolor") # "com.redshift3d.redshift4c4d.nodes.core.rscolorcorrection.outcolor"
return node,self.AddConnection(node, outPort, target_shader, target_port) is not None
# ===== Add Tree ===== #
# todo 创建Texture节点组 ==> to check
# todo 创建color correct Texture节点组 ==> TO DO
# todo 创建bump节点组 bump node链接到brdf的置换端口 ==> to check
# todo 创建texture 并通过displacement node链接到output的置换端口 ==> to check
# ===== Get ===== #
# 获取节点上端口
def GetPort(self,shader, port_name):
"""
Get a port from a Shader node.
Parameters
----------
shader : shader node
The shader.
port_name : str
The shader port.
"""
if self.graph is None:
return None
if not shader:
return None
port = shader.GetInputs().FindChild(port_name)
return port
# 端口合法 ==> OK
def IsPortValid(self, port):
"""
Checks if the FieldOutputBlock instance allocations and sizes are valid.
"""
try:
return port.IsValid()
except Exception as e:
return False
# 获取名称 :
def GetNodeName(self, node, display=False):
"""
Retrieve the displayed name of a node.
Parameters
----------
Args:
node: (maxon.GraphNode): The node to retrieve the name from.
display: print info when display is True
Returns:
Optional[str]: The node name, or None if the Node name can't be retrieved.
"""
if node is None:
return None
nodeName = node.GetValue(maxon.NODE.BASE.NAME)
if nodeName is None:
nodeName = node.GetValue(maxon.EffectiveName)
if nodeName is None:
nodeName = str(node)
if display ==True :
print(nodeName)
return nodeName
# 获取资产ID ==> OK tip:只有node有asset id
def GetAssetId(self, shader, display=False):
"""
Returns the asset id of the given shader.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
display: print info when display is True
"""
res = shader.GetValue("net.maxon.node.attribute.assetid")
assetId = ("%r"%res)[1:].split(",")[0]
if display == True:
print("AssetID = " + ("%r"%res)[1:].split(",")[0])
return assetId
# 获取ShaderID ==> OK
def GetShaderId(self, shader):
"""
Returns the node id of the given shader.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
"""
if shader is None:
return None
assetId = self.GetAssetId(shader,False)
if assetId.startswith(RS_SHADER_PREFIX):
return assetId[len(RS_SHADER_PREFIX):]
return ""
# 获取port数据类型 ==> OK
def GetParamDataType(self, shader, paramId, display=False):
"""
Returns the data type id of the given port.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
paramId : int
Id of the parameter.
display: print info when display is True
"""
if shader is None or paramId is None:
return None
port = shader.GetInputs().FindChild(paramId)
if not self.IsPortValid(port):
return None
if display == True:
print(port.GetDefaultValue().GetType().GetId())
return port.GetDefaultValue().GetType().GetId()
# 获取属性 ==> OK
def GetShaderValue(self, shader, paramId, display=False):
"""
Returns the value stored in the given shader parameter.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
paramId : int
Id of the parameter.
display: bool
print info when display is True
"""
if shader is None or paramId is None:
return None
# standard data type
port = shader.GetInputs().FindChild(paramId)
if not self.IsPortValid(port):
print("[Error] Input port '%s' is not found on shader '%r'" % (paramId, shader))
return None
if display == True:
print(port.GetDefaultValue())
return port.GetDefaultValue()
# 获取Output Node==> OK
def GetRSOutput(self):
"""
Returns the Redshift Output node.
"""
if self.graph is None:
return None
try:
endNodePath = self.nimbusRef.GetPath(maxon.NIMBUS_PATH.MATERIALENDNODE)
shader = self.graph.GetNode(endNodePath)
return shader
finally:
for shader in self.GetShaders(False):
if self.GetAssetId(shader) == OutputMaterialAssetID:
return shader
return None
# 获取Root BRDF ==> OK BRDF:standard surface / rs material
def GetRootBRDF(self):
"""
Returns the shader connect to redshift output (maxon.frameworks.graph.GraphNode)
"""
if self.graph is None:
return None
endNode = self.GetRSOutput()
if endNode is None:
print("[Error] End node is not found in Node Material: %s" % self.material.GetName())
return None
predecessor = list()
maxon.GraphModelHelper.GetDirectPredecessors(endNode, maxon.NODE_KIND.NODE, predecessor)
rootshader = predecessor[0]
if rootshader is None and not rootshader.IsValid() :
raise ValueError("Cannot retrieve the inputs list of the bsdfNode node")
#print(rootshader)
return rootshader
def GetInputPortNames(self, shader, display=False):
"""
Returns the list of input ports of the given shader.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
display: print info when display is True
"""
if shader is None:
return None
inputPorts = shader.GetInputs().GetChildren()
portNames = [element.ToString().split('.')[-1] for element in inputPorts]
if display == True:
print(portNames)
return portNames
def GetOutputPortNames(self, shader, display=False):
"""
Returns the list of output ports of the given shader.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
display: print info when display is True
"""
if shader is None:
return None
outputPorts = shader.GetOutputs().GetChildren()
portNames = [element.ToString().split('.')[-1] for element in outputPorts]
if display == True:
print(portNames)
return portNames
# todo 获取Shader贴图路径 ==> to check
# todo 获取选择node的子集 ==> to check
# ===== Set ===== #
# 设置节点名 ==> OK
def SetShaderName(self,shader,name):
"""
Set the name of the shader.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
name : name str
"""
if shader is None:
return None
shadername = maxon.String(name)
shader.SetValue(maxon.NODE.BASE.NAME, shadername)
shader.SetValue(maxon.EffectiveName, shadername)
# 设置属性 ==> OK 注意数据类型 : maxon.Float64(0.2) / maxon.Color64(1,0,0)
def SetShaderValue(self, shader, paramId, value):
"""
Sets the value stored in the given shader parameter.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
paramId : int
Id of the parameter.
value : [depends on the parameter]
Parameter value.
"""
if shader is None or paramId is None:
return None
# standard data type
port = shader.GetInputs().FindChild(paramId)
if not self.IsPortValid(port):
print("[WARNING] Input port '%s' is not found on shader '%r'" % (paramId, shader))
return None
port.SetDefaultValue(value)
# ===== Modify ===== #
# [private]
# 创建shader list
def _CollectShaders(self, node, shaders):
"""
Private function to collect shaders from the graph.
Parameters
----------
node : maxon.frameworks.graph.GraphNode
Graph node.
shaders : list
List of shaders.
"""
if node.GetKind() != maxon.frameworks.graph.NODE_KIND.NODE:
return
if self.GetAssetId(node) == "net.maxon.node.group":
for node in root.GetChildren():
self._CollectShaders(node, shaders)
return
shaders.append(node)
# 遍历shader ==> OK
def GetShaders(self,display=False):
"""
Get all shaders from the graph.
Parameters
----------
display: print shaders number when display is True
"""
if self.graph is None:
return []
shaders = []
root = self.graph.GetRoot()
for node in root.GetChildren():
self._CollectShaders(node, shaders)
if display == True:
print("Shaders Num : " + str(len(shaders)-2))
return shaders
# 删除Shader ==> OK
def RemoveShader(self, shader):
"""
Removes the given shader from the graph.
Parameters
----------
shader : maxon.frameworks.graph.GraphNode
The shader node.
"""
if self.graph is None:
return
if shader is None:
return
shader.Remove()
# todo 隐藏节点预览 ==> TO DO
# todo 暴露接口 ==> TO DO
# ===== Connections ===== #
# 获取所有连接线 ==> OK
def GetConnections(self):
"""
Returns the list of connections within this shader graph.
A connection is a tuple of:
source shader node : maxon.frameworks.graph.GraphNode
source shader output port id : str
target shader node : maxon.frameworks.graph.GraphNode
target shader input port id : str
"""
if self.graph is None:
return []
connections = []
for shader in self.GetShaders():
for inPort in shader.GetInputs().GetChildren():
for c in inPort.GetConnections(maxon.frameworks.misc.PORT_DIR.INPUT):
outPort = c[0]
src = outPort.GetAncestor(maxon.frameworks.graph.NODE_KIND.NODE)
connections.append((src, outPort, shader, inPort))
return connections
# todo 获取当前node连接线
# todo 获取当前port连接线
# 添加连接线 ==> OK
def AddConnection(self, source_node, outPort, target_node, inPort, removeExisting=True):
"""
Connects the given shaders with given port.
Parameters
----------
source_node : maxon.frameworks.graph.GraphNode
The source shader node.
outPort : str
Output port id of the source shader node.
target_node : maxon.frameworks.graph.GraphNode
The target shader node.
inPort : str
Input port id of the target shader node.
"""
if self.graph is None:
return None
if source_node is None or target_node is None:
return None
if outPort is None or outPort == "":
outPort = "output"
if isinstance(outPort, str):
outPort_name = outPort
outPort = source_node.GetOutputs().FindChild(outPort_name)
if not self.IsPortValid(outPort):
print("[WARNING] Output port '%s' is not found on shader '%r'" % (outPort_name, source_node))
outPort = None
if isinstance(inPort, str):
inPort_name = inPort
inPort = target_node.GetInputs().FindChild(inPort_name)
if not self.IsPortValid(inPort):
print("[WARNING] Input port '%s' is not found on shader '%r'" % (inPort_name, target_node))
inPort = None
if outPort is None or inPort is None:
return None
if removeExisting:
self.RemoveConnection(target_node, inPort)
outPort.Connect(inPort)
return (source_node, outPort, target_node, inPort)
# 删除连接线
def RemoveConnection(self, target_node, inPort):
"""
Disconnects the given shader input.
Parameters
----------
target_node : maxon.frameworks.graph.GraphNode
The target shader node.
inPort : str
Input port id of the target shader node.
"""
if self.graph is None:
return None
if target_node is None:
return None
if isinstance(inPort, str):
inPort_name = inPort
inPort = target_node.GetInputs().FindChild(inPort_name)
if not self.IsPortValid(inPort):
print("[Error] Input port '%s' is not found on shader '%r'" % (inPort_name, target_node))
inPort = None
if inPort is None:
return None
mask = maxon.frameworks.graph.Wires(maxon.frameworks.graph.WIRE_MODE.NORMAL)
inPort.RemoveConnections(maxon.frameworks.misc.PORT_DIR.INPUT, mask)
# todo 禁用连接线
# 连接到Output Surface接口
def AddtoOutput(self, source_node, outPort):
"""
Connects the given shader to RS Output Surface port.
Parameters
----------
source_node : maxon.frameworks.graph.GraphNode
The source shader node.
outPort : str
Output port id of the source shader node.
"""
endNode = self.GetRSOutput()
return self.AddConnection(source_node, outPort, endNode, rsID.PortStr.Output_Surface) is not None
# 连接到Output置换接口
def AddtoDisplacement(self, source_node, outPort):
"""
Connects the given shader to RS Output Displacement port.
Parameters
----------
source_node : maxon.frameworks.graph.GraphNode
The source shader node.
outPort : str
Output port id of the source shader node.
"""
rsoutput = self.GetRSOutput()
return self.AddConnection(source_node, outPort, rsoutput, rsID.PortStr.Output_Displacement) is not None
# ===== Material itself ===== #
def GetMaterialName(self):
"""
Returns the name of the material.
"""
return self.material.GetName()
def ArrangeNodes(self):
"""
Arranges the nodes in the graph.
"""
if self.graph is None:
return
# Can be derived from Extensions -> Script log
c4d.CallCommand(465002363) # Arrange All Nodes
#=============================================
# Redshift Transaction
#=============================================
# Transaction
class RSMaterialTransaction:
"""
A class used to represent a transaction in an Redshift Node Material.
Use it in a `with` statement.
"""
def __init__(self, redshiftMaterial):
self.redshiftMaterial = redshiftMaterial
self.transaction = None
def __enter__(self):
if self.redshiftMaterial is not None and self.redshiftMaterial.graph is not None:
self.transaction = self.redshiftMaterial.graph.BeginTransaction()
return self
def __exit__(self, type, value, traceback):
if self.transaction is not None:
self.transaction.Commit()