forked from prman-pixar/RenderManForBlender
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnodes.py
1622 lines (1329 loc) · 63.5 KB
/
nodes.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 MIT LICENSE BLOCK #####
#
# Copyright (c) 2015 - 2017 Pixar
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#
# ##### END MIT LICENSE BLOCK #####
import bpy
import _cycles
from bpy.app.handlers import persistent
import xml.etree.ElementTree as ET
import tempfile
import nodeitems_utils
import shutil
import subprocess
from bpy.props import *
from nodeitems_utils import NodeCategory, NodeItem
from .shader_parameters import class_generate_properties
from .shader_parameters import node_add_inputs
from .shader_parameters import node_add_outputs
from .shader_parameters import socket_map
from .shader_parameters import update_conditional_visops
from .util import args_files_in_path
from .util import get_path_list
from .util import rib
from .util import debug
from .util import user_path
from .util import get_real_path
from .util import readOSO
from .cycles_convert import *
from .rman_utils import texture_utils
from .rman_utils import filepath_utils
from .rman_utils import prefs_utils
from .rfb_logger import rfb_log
from .rman_bl_nodes import rman_bl_nodes_shaders
from operator import attrgetter, itemgetter
import os.path
from time import sleep
import traceback
NODE_LAYOUT_SPLIT = 0.5
# Generate dynamic types
def set_rix_param(params, param_type, param_name, val, is_reference=False):
if is_reference:
if param_type == "float":
params.ReferenceFloat(param_name, val)
elif param_type == "int":
params.ReferenceInteger(param_name, val)
elif param_type == "color":
params.ReferenceColor(param_name, val)
elif param_type == "point":
params.ReferencePoint(param_name, val)
elif param_type == "vector":
params.ReferenceVector(param_name, val)
elif param_type == "normal":
params.ReferenceNormal(param_name, val)
else:
if param_type == "float":
params.SetFloat(param_name, val)
elif param_type == "int":
params.SetInteger(param_name, val)
elif param_type == "color":
params.SetColor(param_name, val)
elif param_type == "string":
params.SetString(param_name, val)
elif param_type == "point":
params.SetPoint(param_name, val)
elif param_type == "vector":
params.SetVector(param_name, val)
elif param_type == "normal":
params.SetNormal(param_name, val)
def generate_node_type(prefs, name, args):
''' Dynamically generate a node type from pattern '''
nodeType = args.find("shaderType/tag").attrib['value']
typename = '%s%sNode' % (name, nodeType.capitalize())
nodeDict = {'bxdf': rman_bl_nodes_shaders.RendermanBxdfNode,
'pattern': rman_bl_nodes_shaders.RendermanPatternNode,
'displacement': rman_bl_nodes_shaders.RendermanDisplacementNode,
'light': rman_bl_nodes_shaders.RendermanLightNode}
if nodeType not in nodeDict.keys():
return
ntype = type(typename, (nodeDict[nodeType],), {})
ntype.bl_label = name
ntype.typename = typename
inputs = [p for p in args.findall('./param')] + \
[p for p in args.findall('./page')]
outputs = [p for p in args.findall('.//output')]
def init(self, context):
if self.renderman_node_type == 'bxdf':
self.outputs.new('RendermanShaderSocket', "Bxdf").type = 'SHADER'
#socket_template = self.socket_templates.new(identifier='Bxdf', name='Bxdf', type='SHADER')
node_add_inputs(self, name, self.prop_names)
node_add_outputs(self)
# if this is PxrLayerSurface set the diffusegain to 0. The default
# of 1 is unintuitive
if self.plugin_name == 'PxrLayerSurface':
self.diffuseGain = 0
elif self.renderman_node_type == 'light':
# only make a few sockets connectable
node_add_inputs(self, name, self.prop_names)
self.outputs.new('RendermanShaderSocket', "Light")
elif self.renderman_node_type == 'displacement':
# only make the color connectable
self.outputs.new('RendermanShaderSocket', "Displacement")
node_add_inputs(self, name, self.prop_names)
# else pattern
elif name == "PxrOSL":
self.outputs.clear()
else:
node_add_inputs(self, name, self.prop_names)
node_add_outputs(self)
if name == "PxrRamp":
node_group = bpy.data.node_groups.new(
'PxrRamp_nodegroup', 'ShaderNodeTree')
node_group.nodes.new('ShaderNodeValToRGB')
node_group.use_fake_user = True
self.node_group = node_group.name
update_conditional_visops(self)
def free(self):
if name == "PxrRamp":
bpy.data.node_groups.remove(bpy.data.node_groups[self.node_group])
ntype.init = init
ntype.free = free
if "__annotations__" not in ntype.__dict__:
setattr(ntype, "__annotations__", {})
if name == 'PxrRamp':
ntype.__annotations__['node_group'] = StringProperty('color_ramp', default='')
ntype.__annotations__['plugin_name'] = StringProperty(name='Plugin Name',
default=name, options={'HIDDEN'})
# lights cant connect to a node tree in 20.0
class_generate_properties(ntype, name, inputs + outputs)
if nodeType == 'light':
ntype.__annotations__['light_shading_rate'] = FloatProperty(
name="Light Shading Rate",
description="Shading Rate for this light. \
Leave this high unless detail is missing",
default=100.0)
ntype.__annotations__['light_primary_visibility'] = BoolProperty(
name="Light Primary Visibility",
description="Camera visibility for this light",
default=True)
bpy.utils.register_class(ntype)
return typename, ntype
# UI
def find_node_input(node, name):
for input in node.inputs:
if input.name == name:
return input
return None
def find_node(material, nodetype):
if material and material.node_tree:
ntree = material.node_tree
active_output_node = None
for node in ntree.nodes:
if getattr(node, "bl_idname", None) == nodetype:
if getattr(node, "is_active_output", True):
return node
if not active_output_node:
active_output_node = node
return active_output_node
return None
def find_node_input(node, name):
for input in node.inputs:
if input.name == name:
return input
return None
def panel_node_draw(layout, context, id_data, output_type, input_name):
ntree = id_data.node_tree
node = find_node(id_data, output_type)
if not node:
layout.label(text="No output node")
else:
input = find_node_input(node, input_name)
#layout.template_node_view(ntree, node, input)
draw_nodes_properties_ui(layout, context, ntree)
return True
def is_renderman_nodetree(material):
return find_node(material, 'RendermanOutputNode')
def draw_nodes_properties_ui(layout, context, nt, input_name='Bxdf',
output_node_type="output"):
output_node = next((n for n in nt.nodes
if hasattr(n, 'renderman_node_type') and n.renderman_node_type == output_node_type), None)
if output_node is None:
return
socket = output_node.inputs[input_name]
node = socket_node_input(nt, socket)
layout.context_pointer_set("nodetree", nt)
layout.context_pointer_set("node", output_node)
layout.context_pointer_set("socket", socket)
split = layout.split(factor=0.35)
split.label(text=socket.name + ':')
if socket.is_linked:
# for lights draw the shading rate ui.
split.operator_menu_enum("node.add_%s" % input_name.lower(),
"node_type", text=node.bl_label)
else:
split.operator_menu_enum("node.add_%s" % input_name.lower(),
"node_type", text='None')
if node is not None:
draw_node_properties_recursive(layout, context, nt, node)
def socket_node_input(nt, socket):
return next((l.from_node for l in nt.links if l.to_socket == socket), None)
def socket_socket_input(nt, socket):
return next((l.from_socket for l in nt.links if l.to_socket == socket and socket.is_linked),
None)
def linked_sockets(sockets):
if sockets is None:
return []
return [i for i in sockets if i.is_linked]
def draw_node_properties_recursive(layout, context, nt, node, level=0):
def indented_label(layout, label, level):
for i in range(level):
layout.label(text='', icon='BLANK1')
if label:
layout.label(text=label)
layout.context_pointer_set("node", node)
layout.context_pointer_set("nodetree", nt)
def draw_props(prop_names, layout, level):
for prop_name in prop_names:
# skip showing the shape for PxrStdAreaLight
if prop_name in ["lightGroup", "rman__Shape", "coneAngle", "penumbraAngle"]:
continue
if prop_name == "codetypeswitch":
row = layout.row()
if node.codetypeswitch == 'INT':
row.prop_search(node, "internalSearch",
bpy.data, "texts", text="")
elif node.codetypeswitch == 'EXT':
row.prop(node, "shadercode")
elif prop_name == "internalSearch" or prop_name == "shadercode" or prop_name == "expression":
pass
else:
prop_meta = node.prop_meta[prop_name]
prop = getattr(node, prop_name)
if 'widget' in prop_meta and prop_meta['widget'] == 'null' or \
'hidden' in prop_meta and prop_meta['hidden']:
continue
# else check if the socket with this name is connected
socket = node.inputs[prop_name] if prop_name in node.inputs \
else None
layout.context_pointer_set("socket", socket)
if socket and socket.is_linked:
input_node = socket_node_input(nt, socket)
icon = 'DISCLOSURE_TRI_DOWN' if socket.ui_open \
else 'DISCLOSURE_TRI_RIGHT'
split = layout.split(factor=NODE_LAYOUT_SPLIT)
row = split.row()
indented_label(row, None, level)
row.prop(socket, "ui_open", icon=icon, text='',
icon_only=True, emboss=False)
label = prop_meta.get('label', prop_name)
row.label(text=label + ':')
if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial':
split.operator_menu_enum("node.add_layer", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
elif prop_meta['renderman_type'] == 'struct':
split.operator_menu_enum("node.add_manifold", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
elif prop_meta['renderman_type'] == 'normal':
split.operator_menu_enum("node.add_bump", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
else:
split.operator_menu_enum("node.add_pattern", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
if socket.ui_open:
draw_node_properties_recursive(layout, context, nt,
input_node, level=level + 1)
else:
row = layout.row(align=True)
if prop_meta['renderman_type'] == 'page':
ui_prop = prop_name + "_uio"
ui_open = getattr(node, ui_prop)
icon = 'DISCLOSURE_TRI_DOWN' if ui_open \
else 'DISCLOSURE_TRI_RIGHT'
split = layout.split(factor=NODE_LAYOUT_SPLIT)
row = split.row()
for i in range(level):
row.label(text='', icon='BLANK1')
row.prop(node, ui_prop, icon=icon, text='',
icon_only=True, emboss=False)
sub_prop_names = list(prop)
if node.bl_idname in {"PxrSurfaceBxdfNode", "PxrLayerPatternNode"}:
for pn in sub_prop_names:
if pn.startswith('enable'):
row.prop(node, pn, text='')
sub_prop_names.remove(pn)
break
row.label(text=prop_name.split('.')[-1] + ':')
if ui_open:
draw_props(sub_prop_names, layout, level + 1)
else:
indented_label(row, None, level)
# indented_label(row, socket.name+':')
# don't draw prop for struct type
if "Subset" in prop_name and prop_meta['type'] == 'string':
row.prop_search(node, prop_name, bpy.data.scenes[0].renderman,
"object_groups")
else:
if prop_meta['renderman_type'] != 'struct':
row.prop(node, prop_name, slider=True)
else:
row.label(text=prop_meta['label'])
if prop_name in node.inputs:
if ('type' in prop_meta and prop_meta['type'] == 'vstruct') or prop_name == 'inputMaterial':
row.operator_menu_enum("node.add_layer", "node_type",
text='', icon="LAYER_USED")
elif prop_meta['renderman_type'] == 'struct':
row.operator_menu_enum("node.add_manifold", "node_type",
text='', icon="LAYER_USED")
elif prop_meta['renderman_type'] == 'normal':
row.operator_menu_enum("node.add_bump", "node_type",
text='', icon="LAYER_USED")
else:
row.operator_menu_enum("node.add_pattern", "node_type",
text='', icon="LAYER_USED")
# if this is a cycles node do something different
if not hasattr(node, 'plugin_name') or node.bl_idname == 'PxrOSLPatternNode':
node.draw_buttons(context, layout)
for input in node.inputs:
if input.is_linked:
input_node = socket_node_input(nt, input)
icon = 'DISCLOSURE_TRI_DOWN' if input.show_expanded \
else 'DISCLOSURE_TRI_RIGHT'
split = layout.split(factor=NODE_LAYOUT_SPLIT)
row = split.row()
indented_label(row, None, level)
row.prop(input, "show_expanded", icon=icon, text='',
icon_only=True, emboss=False)
row.label(text=input.name + ':')
split.operator_menu_enum("node.add_pattern", "node_type",
text=input_node.bl_label, icon="LAYER_USED")
if input.show_expanded:
draw_node_properties_recursive(layout, context, nt,
input_node, level=level + 1)
else:
row = layout.row(align=True)
indented_label(row, None, level)
# indented_label(row, socket.name+':')
# don't draw prop for struct type
if input.hide_value:
row.label(text=input.name)
else:
row.prop(input, 'default_value',
slider=True, text=input.name)
row.operator_menu_enum("node.add_pattern", "node_type",
text='', icon="LAYER_USED")
else:
if node.plugin_name == 'PxrRamp':
dummy_nt = bpy.data.node_groups[node.node_group]
if dummy_nt:
layout.template_color_ramp(
dummy_nt.nodes['ColorRamp'], 'color_ramp')
draw_props(node.prop_names, layout, level)
layout.separator()
# Operators
# connect the pattern nodes in some sensible manner (color output to color input etc)
# TODO more robust
def link_node(nt, from_node, in_socket):
out_socket = None
# first look for resultF/resultRGB
if type(in_socket).__name__ in ['RendermanNodeSocketColor',
'RendermanNodeSocketVector']:
out_socket = from_node.outputs.get('resultRGB',
next((s for s in from_node.outputs
if type(s).__name__ == 'RendermanNodeSocketColor'), None))
elif type(in_socket).__name__ == 'RendermanNodeSocketStruct':
out_socket = from_node.outputs.get('pxrMaterialOut', None)
if not out_socket:
out_socket = from_node.outputs.get('result', None)
else:
out_socket = from_node.outputs.get('resultF',
next((s for s in from_node.outputs
if type(s).__name__ == 'RendermanNodeSocketFloat'), None))
if out_socket:
nt.links.new(out_socket, in_socket)
# return if this param has a vstuct connection or linked independently
def is_vstruct_or_linked(node, param):
meta = node.prop_meta[param]
if 'vstructmember' not in meta.keys():
return node.inputs[param].is_linked
elif param in node.inputs and node.inputs[param].is_linked:
return True
else:
vstruct_name, vstruct_member = meta['vstructmember'].split('.')
if node.inputs[vstruct_name].is_linked:
from_socket = node.inputs[vstruct_name].links[0].from_socket
vstruct_from_param = "%s_%s" % (
from_socket.identifier, vstruct_member)
return vstruct_conditional(from_socket.node, vstruct_from_param)
else:
return False
# tells if this param has a vstuct connection that is linked and
# conditional met
def is_vstruct_and_linked(node, param):
meta = node.prop_meta[param]
if 'vstructmember' not in meta.keys():
return False
else:
vstruct_name, vstruct_member = meta['vstructmember'].split('.')
if node.inputs[vstruct_name].is_linked:
from_socket = node.inputs[vstruct_name].links[0].from_socket
# if coming from a shader group hookup across that
if from_socket.node.bl_idname == 'ShaderNodeGroup':
ng = from_socket.node.node_tree
group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'),
None)
if group_output is None:
return False
in_sock = group_output.inputs[from_socket.name]
if len(in_sock.links):
from_socket = in_sock.links[0].from_socket
vstruct_from_param = "%s_%s" % (
from_socket.identifier, vstruct_member)
return vstruct_conditional(from_socket.node, vstruct_from_param)
else:
return False
# gets the value for a node walking up the vstruct chain
def get_val_vstruct(node, param):
if param in node.inputs and node.inputs[param].is_linked:
from_socket = node.inputs[param].links[0].from_socket
return get_val_vstruct(from_socket.node, from_socket.identifier)
elif is_vstruct_and_linked(node, param):
return True
else:
return getattr(node, param)
# parse a vstruct conditional string and return true or false if should link
def vstruct_conditional(node, param):
if not hasattr(node, 'shader_meta') and not hasattr(node, 'output_meta'):
return False
meta = getattr(
node, 'shader_meta') if node.bl_idname == "PxrOSLPatternNode" else node.output_meta
if param not in meta:
return False
meta = meta[param]
if 'vstructConditionalExpr' not in meta.keys():
return True
expr = meta['vstructConditionalExpr']
expr = expr.replace('connect if ', '')
set_zero = False
if ' else set 0' in expr:
expr = expr.replace(' else set 0', '')
set_zero = True
tokens = expr.split()
new_tokens = []
i = 0
num_tokens = len(tokens)
while i < num_tokens:
token = tokens[i]
prepend, append = '', ''
while token[0] == '(':
token = token[1:]
prepend += '('
while token[-1] == ')':
token = token[:-1]
append += ')'
if token == 'set':
i += 1
continue
# is connected change this to node.inputs.is_linked
if i < num_tokens - 2 and tokens[i + 1] == 'is'\
and 'connected' in tokens[i + 2]:
token = "is_vstruct_or_linked(node, '%s')" % token
last_token = tokens[i + 2]
while last_token[-1] == ')':
last_token = last_token[:-1]
append += ')'
i += 3
else:
i += 1
if hasattr(node, token):
token = "get_val_vstruct(node, '%s')" % token
new_tokens.append(prepend + token + append)
if 'if' in new_tokens and 'else' not in new_tokens:
new_tokens.extend(['else', 'False'])
return eval(" ".join(new_tokens))
# Rib export
gains_to_enable = {
'diffuseGain': 'enableDiffuse',
'specularFaceColor': 'enablePrimarySpecular',
'specularEdgeColor': 'enablePrimarySpecular',
'roughSpecularFaceColor': 'enableRoughSpecular',
'roughSpecularEdgeColor': 'enableRoughSpecular',
'clearcoatFaceColor': 'enableClearCoat',
'clearcoatEdgeColor': 'enableClearCoat',
'iridescenceFaceGain': 'enableIridescence',
'iridescenceEdgeGain': 'enableIridescence',
'fuzzGain': 'enableFuzz',
'subsurfaceGain': 'enableSubsurface',
'singlescatterGain': 'enableSingleScatter',
'singlescatterDirectGain': 'enableSingleScatter',
'refractionGain': 'enableGlass',
'reflectionGain': 'enableGlass',
'glowGain': 'enableGlow',
}
# generate param list
# generate rixparam list
def gen_rixparams(node, params, mat_name=None):
# If node is OSL node get properties from dynamic location.
if node.bl_idname == "PxrOSLPatternNode":
if getattr(node, "codetypeswitch") == "EXT":
prefs = bpy.context.preferences.addons[__package__].preferences
osl_path = user_path(getattr(node, 'shadercode'))
FileName = os.path.basename(osl_path)
FileNameNoEXT,ext = os.path.splitext(FileName)
out_file = os.path.join(
user_path(prefs.env_vars.out), "shaders", FileName)
if ext == ".oso":
if not os.path.exists(out_file) or not os.path.samefile(osl_path, out_file):
if not os.path.exists(os.path.join(user_path(prefs.env_vars.out), "shaders")):
os.mkdir(os.path.join(user_path(prefs.env_vars.out), "shaders"))
shutil.copy(osl_path, out_file)
for input_name, input in node.inputs.items():
prop_type = input.renderman_type
if input.is_linked:
to_socket = input
from_socket = input.links[0].from_socket
param_type = prop_type
param_name = input_name
val = get_output_param_str(from_socket.node, mat_name, from_socket, to_socket)
set_rix_param(params, param_type, param_name, val, is_reference=True)
elif type(input) != RendermanNodeSocketStruct:
param_type = prop_type
param_name = input_name
val = rib(input.default_value, type_hint=prop_type)
set_rix_param(params, param_type, param_name, val, is_reference=False)
# Special case for SeExpr Nodes. Assume that the code will be in a file so
# that needs to be extracted.
elif node.bl_idname == "PxrSeExprPatternNode":
fileInputType = node.codetypeswitch
for prop_name, meta in node.prop_meta.items():
if prop_name in ["codetypeswitch", 'filename']:
pass
elif prop_name == "internalSearch" and fileInputType == 'INT':
if node.internalSearch != "":
script = bpy.data.texts[node.internalSearch]
params.SetString("expression", script.as_string() )
elif prop_name == "shadercode" and fileInputType == "NODE":
params.SetString("expression", node.expression)
else:
prop = getattr(node, prop_name)
# if input socket is linked reference that
if prop_name in node.inputs and \
node.inputs[prop_name].is_linked:
to_socket = node.inputs[prop_name]
from_socket = to_socket.links[0].from_socket
from_node = to_socket.links[0].from_node
param_type = meta['renderman_type']
param_name = meta['renderman_name']
val = get_output_param_str(
from_socket.node, mat_name, from_socket, to_socket)
set_rix_param(params, param_type, param_name, val, is_reference=True)
else:
param_type = meta['renderman_type']
param_name = meta['renderman_name']
val = rib(prop, type_hint=meta['renderman_type'])
set_rix_param(params, param_type, param_name, val, is_reference=False)
else:
for prop_name, meta in node.prop_meta.items():
if node.plugin_name == 'PxrRamp' and prop_name in ['colors', 'positions']:
pass
elif(prop_name in ['sblur', 'tblur', 'notes']):
pass
else:
prop = getattr(node, prop_name)
# if property group recurse
if meta['renderman_type'] == 'page':
continue
elif prop_name == 'inputMaterial' or \
('type' in meta and meta['type'] == 'vstruct'):
continue
# if input socket is linked reference that
elif hasattr(node, 'inputs') and prop_name in node.inputs and \
node.inputs[prop_name].is_linked:
to_socket = node.inputs[prop_name]
from_socket = to_socket.links[0].from_socket
from_node = to_socket.links[0].from_node
param_type = meta['renderman_type']
param_name = meta['renderman_name']
if 'arraySize' in meta:
pass
else:
val = get_output_param_str(
from_node, mat_name, from_socket, to_socket)
set_rix_param(params, param_type, param_name, val, is_reference=True)
# see if vstruct linked
elif is_vstruct_and_linked(node, prop_name):
vstruct_name, vstruct_member = meta[
'vstructmember'].split('.')
from_socket = node.inputs[
vstruct_name].links[0].from_socket
temp_mat_name = mat_name
if from_socket.node.bl_idname == 'ShaderNodeGroup':
ng = from_socket.node.node_tree
group_output = next((n for n in ng.nodes if n.bl_idname == 'NodeGroupOutput'),
None)
if group_output is None:
return False
in_sock = group_output.inputs[from_socket.name]
if len(in_sock.links):
from_socket = in_sock.links[0].from_socket
temp_mat_name = mat_name + '.' + from_socket.node.name
vstruct_from_param = "%s_%s" % (
from_socket.identifier, vstruct_member)
if vstruct_from_param in from_socket.node.output_meta:
actual_socket = from_socket.node.output_meta[
vstruct_from_param]
param_type = meta['renderman_type']
param_name = meta['renderman_name']
node_meta = getattr(
node, 'shader_meta') if node.bl_idname == "PxrOSLPatternNode" else node.output_meta
node_meta = node_meta.get(vstruct_from_param)
is_reference = True
val = get_output_param_str(
from_socket.node, temp_mat_name, actual_socket)
if node_meta:
expr = node_meta.get('vstructConditionalExpr')
# check if we should connect or just set a value
if expr:
if expr.split(' ')[0] == 'set':
val = 1
is_reference = False
set_rix_param(params, param_type, param_name, val, is_reference=is_reference)
else:
print('Warning! %s not found on %s' %
(vstruct_from_param, from_socket.node.name))
# else output rib
else:
# if struct is not linked continue
if meta['renderman_type'] in ['struct', 'enum']:
continue
param_type = meta['renderman_type']
param_name = meta['renderman_name']
val = None
isArray = False
arrayLen = 0
# if this is a gain on PxrSurface and the lobe isn't
# enabled
if node.bl_idname == 'PxrSurfaceBxdfNode' and \
prop_name in gains_to_enable and \
not getattr(node, gains_to_enable[prop_name]):
val = [0, 0, 0] if meta[
'renderman_type'] == 'color' else 0
#params['%s %s' % (meta['renderman_type'],
# meta['renderman_name'])] = val
elif 'options' in meta and meta['options'] == 'texture' \
and node.bl_idname != "PxrPtexturePatternNode" or \
('widget' in meta and meta['widget'] == 'assetIdInput' and prop_name != 'iesProfile'):
val = rib(texture_utils.get_tex_file_name(prop), type_hint=meta['renderman_type'])
elif 'arraySize' in meta:
isArray = True
if type(prop) == int:
prop = [prop]
val = rib(prop)
arrayLen = len(prop)
else:
val = rib(prop, type_hint=meta['renderman_type'])
if isArray:
pass
else:
set_rix_param(params, param_type, param_name, val, is_reference=False)
if node.plugin_name == 'PxrRamp':
nt = bpy.data.node_groups[node.node_group]
if nt:
dummy_ramp = nt.nodes['ColorRamp']
colors = []
positions = []
# double the start and end points
positions.append(float(dummy_ramp.color_ramp.elements[0].position))
colors.extend(dummy_ramp.color_ramp.elements[0].color[:3])
for e in dummy_ramp.color_ramp.elements:
positions.append(float(e.position))
colors.extend(e.color[:3])
positions.append(
float(dummy_ramp.color_ramp.elements[-1].position))
colors.extend(dummy_ramp.color_ramp.elements[-1].color[:3])
params.SetFloatArray("colorRamp_Knots", positions, len(positions))
params.SetColorArray("colorRamp_Colors", colors, len(positions))
rman_interp_map = { 'LINEAR': 'linear', 'CONSTANT': 'constant'}
interp = rman_interp_map.get(dummy_ramp.color_ramp.interpolation,'catmull-rom')
params.SetString("colorRamp_Interpolation", interp )
return params
def create_rman_surface(nt, parent_node, input_index, node_type="PxrSurfaceBxdfNode"):
layer = nt.nodes.new(node_type)
nt.links.new(layer.outputs[0], parent_node.inputs[input_index])
setattr(layer, 'enableDiffuse', False)
layer.location = parent_node.location
layer.diffuseGain = 0
layer.location[0] -= 300
return layer
combine_nodes = ['ShaderNodeAddShader', 'ShaderNodeMixShader']
# rman_parent could be PxrSurface or PxrMixer
def convert_cycles_bsdf(nt, rman_parent, node, input_index):
# if mix or add pass both to parent
if node.bl_idname in combine_nodes:
i = 0 if node.bl_idname == 'ShaderNodeAddShader' else 1
node1 = node.inputs[
0 + i].links[0].from_node if node.inputs[0 + i].is_linked else None
node2 = node.inputs[
1 + i].links[0].from_node if node.inputs[1 + i].is_linked else None
if not node1 and not node2:
return
elif not node1:
convert_cycles_bsdf(nt, rman_parent, node2, input_index)
elif not node2:
convert_cycles_bsdf(nt, rman_parent, node1, input_index)
# if ones a combiner or they're of the same type and not glossy we need
# to make a mixer
elif node.bl_idname == 'ShaderNodeMixShader' or node1.bl_idname in combine_nodes \
or node2.bl_idname in combine_nodes or \
node1.bl_idname == 'ShaderNodeGroup' or node2.bl_idname == 'ShaderNodeGroup' \
or (bsdf_map[node1.bl_idname][0] == bsdf_map[node2.bl_idname][0]):
mixer = nt.nodes.new('PxrLayerMixerPatternNode')
# if parent is output make a pxr surface first
nt.links.new(mixer.outputs["pxrMaterialOut"],
rman_parent.inputs[input_index])
offset_node_location(rman_parent, mixer, node)
# set the layer masks
if node.bl_idname == 'ShaderNodeAddShader':
mixer.layer1Mask = .5
else:
convert_cycles_input(
nt, node.inputs['Fac'], mixer, 'layer1Mask')
# make a new node for each
convert_cycles_bsdf(nt, mixer, node1, 0)
convert_cycles_bsdf(nt, mixer, node2, 1)
# this is a heterogenous mix of add
else:
if rman_parent.plugin_name == 'PxrLayerMixer':
old_parent = rman_parent
rman_parent = create_rman_surface(nt, rman_parent, input_index,
'PxrLayerPatternNode')
offset_node_location(old_parent, rman_parent, node)
convert_cycles_bsdf(nt, rman_parent, node1, 0)
convert_cycles_bsdf(nt, rman_parent, node2, 1)
# else set lobe on parent
elif 'Bsdf' in node.bl_idname or node.bl_idname == 'ShaderNodeSubsurfaceScattering':
if rman_parent.plugin_name == 'PxrLayerMixer':
old_parent = rman_parent
rman_parent = create_rman_surface(nt, rman_parent, input_index,
'PxrLayerPatternNode')
offset_node_location(old_parent, rman_parent, node)
node_type = node.bl_idname
bsdf_map[node_type][1](nt, node, rman_parent)
# if we find an emission node, naively make it a meshlight
# note this will only make the last emission node the light
elif node.bl_idname == 'ShaderNodeEmission':
output = next((n for n in nt.nodes if hasattr(n, 'renderman_node_type') and
n.renderman_node_type == 'output'),
None)
meshlight = nt.nodes.new("PxrMeshLightLightNode")
nt.links.new(meshlight.outputs[0], output.inputs["Light"])
meshlight.location = output.location
meshlight.location[0] -= 300
convert_cycles_input(
nt, node.inputs['Strength'], meshlight, "intensity")
if node.inputs['Color'].is_linked:
convert_cycles_input(
nt, node.inputs['Color'], meshlight, "textureColor")
else:
setattr(meshlight, 'lightColor', node.inputs[
'Color'].default_value[:3])
else:
rman_node = convert_cycles_node(nt, node)
nt.links.new(rman_node.outputs[0], rman_parent.inputs[input_index])
def convert_cycles_displacement(nt, surface_node, displace_socket):
# for now just do bump
if displace_socket.is_linked:
bump = nt.nodes.new("PxrBumpPatternNode")
nt.links.new(bump.outputs[0], surface_node.inputs['bumpNormal'])
bump.location = surface_node.location
bump.location[0] -= 200
bump.location[1] -= 100
convert_cycles_input(nt, displace_socket, bump, "inputBump")
# return
# if displace_socket.is_linked:
# displace = nt.nodes.new("PxrDisplaceDisplacementNode")
# nt.links.new(displace.outputs[0], output_node.inputs['Displacement'])
# displace.location = output_node.location
# displace.location[0] -= 200
# displace.location[1] -= 100
# setattr(displace, 'dispAmount', .01)
# convert_cycles_input(nt, displace_socket, displace, "dispScalar")
# could make this more robust to shift the entire nodetree to below the
# bounds of the cycles nodetree
def set_ouput_node_location(nt, output_node, cycles_output):
output_node.location = cycles_output.location
output_node.location[1] -= 500
def offset_node_location(rman_parent, rman_node, cycles_node):
linked_socket = next((sock for sock in cycles_node.outputs if sock.is_linked),
None)
rman_node.location = rman_parent.location
if linked_socket:
rman_node.location += (cycles_node.location -
linked_socket.links[0].to_node.location)
def convert_cycles_nodetree(id, output_node, reporter):
# find base node
from . import cycles_convert
cycles_convert.converted_nodes = {}
nt = id.node_tree
reporter({'INFO'}, 'Converting material ' + id.name + ' to RenderMan')
cycles_output_node = find_node(id, 'ShaderNodeOutputMaterial')
if not cycles_output_node:
reporter({'WARNING'}, 'No Cycles output found ' + id.name)
return False