1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "render/background.h"
18 #include "render/colorspace.h"
19 #include "render/graph.h"
20 #include "render/light.h"
21 #include "render/nodes.h"
22 #include "render/osl.h"
23 #include "render/scene.h"
24 #include "render/shader.h"
25 
26 #include "blender/blender_image.h"
27 #include "blender/blender_sync.h"
28 #include "blender/blender_texture.h"
29 #include "blender/blender_util.h"
30 
31 #include "util/util_debug.h"
32 #include "util/util_foreach.h"
33 #include "util/util_set.h"
34 #include "util/util_string.h"
35 #include "util/util_task.h"
36 
37 CCL_NAMESPACE_BEGIN
38 
39 typedef map<void *, ShaderInput *> PtrInputMap;
40 typedef map<void *, ShaderOutput *> PtrOutputMap;
41 typedef map<string, ConvertNode *> ProxyMap;
42 
43 /* Find */
44 
find_shader(BL::ID & id,vector<Shader * > & used_shaders,Shader * default_shader)45 void BlenderSync::find_shader(BL::ID &id, vector<Shader *> &used_shaders, Shader *default_shader)
46 {
47   Shader *shader = (id) ? shader_map.find(id) : default_shader;
48 
49   used_shaders.push_back(shader);
50   shader->tag_used(scene);
51 }
52 
53 /* RNA translation utilities */
54 
get_volume_sampling(PointerRNA & ptr)55 static VolumeSampling get_volume_sampling(PointerRNA &ptr)
56 {
57   return (VolumeSampling)get_enum(
58       ptr, "volume_sampling", VOLUME_NUM_SAMPLING, VOLUME_SAMPLING_DISTANCE);
59 }
60 
get_volume_interpolation(PointerRNA & ptr)61 static VolumeInterpolation get_volume_interpolation(PointerRNA &ptr)
62 {
63   return (VolumeInterpolation)get_enum(
64       ptr, "volume_interpolation", VOLUME_NUM_INTERPOLATION, VOLUME_INTERPOLATION_LINEAR);
65 }
66 
get_displacement_method(PointerRNA & ptr)67 static DisplacementMethod get_displacement_method(PointerRNA &ptr)
68 {
69   return (DisplacementMethod)get_enum(
70       ptr, "displacement_method", DISPLACE_NUM_METHODS, DISPLACE_BUMP);
71 }
72 
validate_enum_value(int value,int num_values,int default_value)73 static int validate_enum_value(int value, int num_values, int default_value)
74 {
75   if (value >= num_values) {
76     return default_value;
77   }
78   return value;
79 }
80 
get_image_interpolation(NodeType & b_node)81 template<typename NodeType> static InterpolationType get_image_interpolation(NodeType &b_node)
82 {
83   int value = b_node.interpolation();
84   return (InterpolationType)validate_enum_value(
85       value, INTERPOLATION_NUM_TYPES, INTERPOLATION_LINEAR);
86 }
87 
get_image_extension(NodeType & b_node)88 template<typename NodeType> static ExtensionType get_image_extension(NodeType &b_node)
89 {
90   int value = b_node.extension();
91   return (ExtensionType)validate_enum_value(value, EXTENSION_NUM_TYPES, EXTENSION_REPEAT);
92 }
93 
get_image_alpha_type(BL::Image & b_image)94 static ImageAlphaType get_image_alpha_type(BL::Image &b_image)
95 {
96   int value = b_image.alpha_mode();
97   return (ImageAlphaType)validate_enum_value(value, IMAGE_ALPHA_NUM_TYPES, IMAGE_ALPHA_AUTO);
98 }
99 
100 /* Graph */
101 
get_node_output(BL::Node & b_node,const string & name)102 static BL::NodeSocket get_node_output(BL::Node &b_node, const string &name)
103 {
104   BL::Node::outputs_iterator b_out;
105 
106   for (b_node.outputs.begin(b_out); b_out != b_node.outputs.end(); ++b_out)
107     if (b_out->name() == name)
108       return *b_out;
109 
110   assert(0);
111 
112   return *b_out;
113 }
114 
get_node_output_rgba(BL::Node & b_node,const string & name)115 static float3 get_node_output_rgba(BL::Node &b_node, const string &name)
116 {
117   BL::NodeSocket b_sock = get_node_output(b_node, name);
118   float value[4];
119   RNA_float_get_array(&b_sock.ptr, "default_value", value);
120   return make_float3(value[0], value[1], value[2]);
121 }
122 
get_node_output_value(BL::Node & b_node,const string & name)123 static float get_node_output_value(BL::Node &b_node, const string &name)
124 {
125   BL::NodeSocket b_sock = get_node_output(b_node, name);
126   return RNA_float_get(&b_sock.ptr, "default_value");
127 }
128 
get_node_output_vector(BL::Node & b_node,const string & name)129 static float3 get_node_output_vector(BL::Node &b_node, const string &name)
130 {
131   BL::NodeSocket b_sock = get_node_output(b_node, name);
132   float value[3];
133   RNA_float_get_array(&b_sock.ptr, "default_value", value);
134   return make_float3(value[0], value[1], value[2]);
135 }
136 
convert_socket_type(BL::NodeSocket & b_socket)137 static SocketType::Type convert_socket_type(BL::NodeSocket &b_socket)
138 {
139   switch (b_socket.type()) {
140     case BL::NodeSocket::type_VALUE:
141       return SocketType::FLOAT;
142     case BL::NodeSocket::type_INT:
143       return SocketType::INT;
144     case BL::NodeSocket::type_VECTOR:
145       return SocketType::VECTOR;
146     case BL::NodeSocket::type_RGBA:
147       return SocketType::COLOR;
148     case BL::NodeSocket::type_STRING:
149       return SocketType::STRING;
150     case BL::NodeSocket::type_SHADER:
151       return SocketType::CLOSURE;
152 
153     default:
154       return SocketType::UNDEFINED;
155   }
156 }
157 
set_default_value(ShaderInput * input,BL::NodeSocket & b_sock,BL::BlendData & b_data,BL::ID & b_id)158 static void set_default_value(ShaderInput *input,
159                               BL::NodeSocket &b_sock,
160                               BL::BlendData &b_data,
161                               BL::ID &b_id)
162 {
163   Node *node = input->parent;
164   const SocketType &socket = input->socket_type;
165 
166   /* copy values for non linked inputs */
167   switch (input->type()) {
168     case SocketType::FLOAT: {
169       node->set(socket, get_float(b_sock.ptr, "default_value"));
170       break;
171     }
172     case SocketType::INT: {
173       node->set(socket, get_int(b_sock.ptr, "default_value"));
174       break;
175     }
176     case SocketType::COLOR: {
177       node->set(socket, float4_to_float3(get_float4(b_sock.ptr, "default_value")));
178       break;
179     }
180     case SocketType::NORMAL:
181     case SocketType::POINT:
182     case SocketType::VECTOR: {
183       node->set(socket, get_float3(b_sock.ptr, "default_value"));
184       break;
185     }
186     case SocketType::STRING: {
187       node->set(
188           socket,
189           (ustring)blender_absolute_path(b_data, b_id, get_string(b_sock.ptr, "default_value")));
190       break;
191     }
192     default:
193       break;
194   }
195 }
196 
get_tex_mapping(TextureMapping * mapping,BL::TexMapping & b_mapping)197 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping &b_mapping)
198 {
199   if (!b_mapping)
200     return;
201 
202   mapping->translation = get_float3(b_mapping.translation());
203   mapping->rotation = get_float3(b_mapping.rotation());
204   mapping->scale = get_float3(b_mapping.scale());
205   mapping->type = (TextureMapping::Type)b_mapping.vector_type();
206 
207   mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
208   mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
209   mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
210 }
211 
add_node(Scene * scene,BL::RenderEngine & b_engine,BL::BlendData & b_data,BL::Depsgraph & b_depsgraph,BL::Scene & b_scene,ShaderGraph * graph,BL::ShaderNodeTree & b_ntree,BL::ShaderNode & b_node)212 static ShaderNode *add_node(Scene *scene,
213                             BL::RenderEngine &b_engine,
214                             BL::BlendData &b_data,
215                             BL::Depsgraph &b_depsgraph,
216                             BL::Scene &b_scene,
217                             ShaderGraph *graph,
218                             BL::ShaderNodeTree &b_ntree,
219                             BL::ShaderNode &b_node)
220 {
221   ShaderNode *node = NULL;
222 
223   /* existing blender nodes */
224   if (b_node.is_a(&RNA_ShaderNodeRGBCurve)) {
225     BL::ShaderNodeRGBCurve b_curve_node(b_node);
226     BL::CurveMapping mapping(b_curve_node.mapping());
227     RGBCurvesNode *curves = graph->create_node<RGBCurvesNode>();
228     curvemapping_color_to_array(mapping, curves->curves, RAMP_TABLE_SIZE, true);
229     curvemapping_minmax(mapping, true, &curves->min_x, &curves->max_x);
230     node = curves;
231   }
232   if (b_node.is_a(&RNA_ShaderNodeVectorCurve)) {
233     BL::ShaderNodeVectorCurve b_curve_node(b_node);
234     BL::CurveMapping mapping(b_curve_node.mapping());
235     VectorCurvesNode *curves = graph->create_node<VectorCurvesNode>();
236     curvemapping_color_to_array(mapping, curves->curves, RAMP_TABLE_SIZE, false);
237     curvemapping_minmax(mapping, false, &curves->min_x, &curves->max_x);
238     node = curves;
239   }
240   else if (b_node.is_a(&RNA_ShaderNodeValToRGB)) {
241     RGBRampNode *ramp = graph->create_node<RGBRampNode>();
242     BL::ShaderNodeValToRGB b_ramp_node(b_node);
243     BL::ColorRamp b_color_ramp(b_ramp_node.color_ramp());
244     colorramp_to_array(b_color_ramp, ramp->ramp, ramp->ramp_alpha, RAMP_TABLE_SIZE);
245     ramp->interpolate = b_color_ramp.interpolation() != BL::ColorRamp::interpolation_CONSTANT;
246     node = ramp;
247   }
248   else if (b_node.is_a(&RNA_ShaderNodeRGB)) {
249     ColorNode *color = graph->create_node<ColorNode>();
250     color->value = get_node_output_rgba(b_node, "Color");
251     node = color;
252   }
253   else if (b_node.is_a(&RNA_ShaderNodeValue)) {
254     ValueNode *value = graph->create_node<ValueNode>();
255     value->value = get_node_output_value(b_node, "Value");
256     node = value;
257   }
258   else if (b_node.is_a(&RNA_ShaderNodeCameraData)) {
259     node = graph->create_node<CameraNode>();
260   }
261   else if (b_node.is_a(&RNA_ShaderNodeInvert)) {
262     node = graph->create_node<InvertNode>();
263   }
264   else if (b_node.is_a(&RNA_ShaderNodeGamma)) {
265     node = graph->create_node<GammaNode>();
266   }
267   else if (b_node.is_a(&RNA_ShaderNodeBrightContrast)) {
268     node = graph->create_node<BrightContrastNode>();
269   }
270   else if (b_node.is_a(&RNA_ShaderNodeMixRGB)) {
271     BL::ShaderNodeMixRGB b_mix_node(b_node);
272     MixNode *mix = graph->create_node<MixNode>();
273     mix->type = (NodeMix)b_mix_node.blend_type();
274     mix->use_clamp = b_mix_node.use_clamp();
275     node = mix;
276   }
277   else if (b_node.is_a(&RNA_ShaderNodeSeparateRGB)) {
278     node = graph->create_node<SeparateRGBNode>();
279   }
280   else if (b_node.is_a(&RNA_ShaderNodeCombineRGB)) {
281     node = graph->create_node<CombineRGBNode>();
282   }
283   else if (b_node.is_a(&RNA_ShaderNodeSeparateHSV)) {
284     node = graph->create_node<SeparateHSVNode>();
285   }
286   else if (b_node.is_a(&RNA_ShaderNodeCombineHSV)) {
287     node = graph->create_node<CombineHSVNode>();
288   }
289   else if (b_node.is_a(&RNA_ShaderNodeSeparateXYZ)) {
290     node = graph->create_node<SeparateXYZNode>();
291   }
292   else if (b_node.is_a(&RNA_ShaderNodeCombineXYZ)) {
293     node = graph->create_node<CombineXYZNode>();
294   }
295   else if (b_node.is_a(&RNA_ShaderNodeHueSaturation)) {
296     node = graph->create_node<HSVNode>();
297   }
298   else if (b_node.is_a(&RNA_ShaderNodeRGBToBW)) {
299     node = graph->create_node<RGBToBWNode>();
300   }
301   else if (b_node.is_a(&RNA_ShaderNodeMapRange)) {
302     BL::ShaderNodeMapRange b_map_range_node(b_node);
303     MapRangeNode *map_range_node = graph->create_node<MapRangeNode>();
304     map_range_node->clamp = b_map_range_node.clamp();
305     map_range_node->type = (NodeMapRangeType)b_map_range_node.interpolation_type();
306     node = map_range_node;
307   }
308   else if (b_node.is_a(&RNA_ShaderNodeClamp)) {
309     BL::ShaderNodeClamp b_clamp_node(b_node);
310     ClampNode *clamp_node = graph->create_node<ClampNode>();
311     clamp_node->type = (NodeClampType)b_clamp_node.clamp_type();
312     node = clamp_node;
313   }
314   else if (b_node.is_a(&RNA_ShaderNodeMath)) {
315     BL::ShaderNodeMath b_math_node(b_node);
316     MathNode *math_node = graph->create_node<MathNode>();
317     math_node->type = (NodeMathType)b_math_node.operation();
318     math_node->use_clamp = b_math_node.use_clamp();
319     node = math_node;
320   }
321   else if (b_node.is_a(&RNA_ShaderNodeVectorMath)) {
322     BL::ShaderNodeVectorMath b_vector_math_node(b_node);
323     VectorMathNode *vector_math_node = graph->create_node<VectorMathNode>();
324     vector_math_node->type = (NodeVectorMathType)b_vector_math_node.operation();
325     node = vector_math_node;
326   }
327   else if (b_node.is_a(&RNA_ShaderNodeVectorRotate)) {
328     BL::ShaderNodeVectorRotate b_vector_rotate_node(b_node);
329     VectorRotateNode *vector_rotate_node = graph->create_node<VectorRotateNode>();
330     vector_rotate_node->type = (NodeVectorRotateType)b_vector_rotate_node.rotation_type();
331     vector_rotate_node->invert = b_vector_rotate_node.invert();
332     node = vector_rotate_node;
333   }
334   else if (b_node.is_a(&RNA_ShaderNodeVectorTransform)) {
335     BL::ShaderNodeVectorTransform b_vector_transform_node(b_node);
336     VectorTransformNode *vtransform = graph->create_node<VectorTransformNode>();
337     vtransform->type = (NodeVectorTransformType)b_vector_transform_node.vector_type();
338     vtransform->convert_from = (NodeVectorTransformConvertSpace)
339                                    b_vector_transform_node.convert_from();
340     vtransform->convert_to = (NodeVectorTransformConvertSpace)b_vector_transform_node.convert_to();
341     node = vtransform;
342   }
343   else if (b_node.is_a(&RNA_ShaderNodeNormal)) {
344     BL::Node::outputs_iterator out_it;
345     b_node.outputs.begin(out_it);
346 
347     NormalNode *norm = graph->create_node<NormalNode>();
348     norm->direction = get_node_output_vector(b_node, "Normal");
349     node = norm;
350   }
351   else if (b_node.is_a(&RNA_ShaderNodeMapping)) {
352     BL::ShaderNodeMapping b_mapping_node(b_node);
353     MappingNode *mapping = graph->create_node<MappingNode>();
354     mapping->type = (NodeMappingType)b_mapping_node.vector_type();
355     node = mapping;
356   }
357   else if (b_node.is_a(&RNA_ShaderNodeFresnel)) {
358     node = graph->create_node<FresnelNode>();
359   }
360   else if (b_node.is_a(&RNA_ShaderNodeLayerWeight)) {
361     node = graph->create_node<LayerWeightNode>();
362   }
363   else if (b_node.is_a(&RNA_ShaderNodeAddShader)) {
364     node = graph->create_node<AddClosureNode>();
365   }
366   else if (b_node.is_a(&RNA_ShaderNodeMixShader)) {
367     node = graph->create_node<MixClosureNode>();
368   }
369   else if (b_node.is_a(&RNA_ShaderNodeAttribute)) {
370     BL::ShaderNodeAttribute b_attr_node(b_node);
371     AttributeNode *attr = graph->create_node<AttributeNode>();
372     attr->attribute = b_attr_node.attribute_name();
373     node = attr;
374   }
375   else if (b_node.is_a(&RNA_ShaderNodeBackground)) {
376     node = graph->create_node<BackgroundNode>();
377   }
378   else if (b_node.is_a(&RNA_ShaderNodeHoldout)) {
379     node = graph->create_node<HoldoutNode>();
380   }
381   else if (b_node.is_a(&RNA_ShaderNodeBsdfAnisotropic)) {
382     BL::ShaderNodeBsdfAnisotropic b_aniso_node(b_node);
383     AnisotropicBsdfNode *aniso = graph->create_node<AnisotropicBsdfNode>();
384 
385     switch (b_aniso_node.distribution()) {
386       case BL::ShaderNodeBsdfAnisotropic::distribution_BECKMANN:
387         aniso->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_ID;
388         break;
389       case BL::ShaderNodeBsdfAnisotropic::distribution_GGX:
390         aniso->distribution = CLOSURE_BSDF_MICROFACET_GGX_ID;
391         break;
392       case BL::ShaderNodeBsdfAnisotropic::distribution_MULTI_GGX:
393         aniso->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID;
394         break;
395       case BL::ShaderNodeBsdfAnisotropic::distribution_ASHIKHMIN_SHIRLEY:
396         aniso->distribution = CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID;
397         break;
398     }
399 
400     node = aniso;
401   }
402   else if (b_node.is_a(&RNA_ShaderNodeBsdfDiffuse)) {
403     node = graph->create_node<DiffuseBsdfNode>();
404   }
405   else if (b_node.is_a(&RNA_ShaderNodeSubsurfaceScattering)) {
406     BL::ShaderNodeSubsurfaceScattering b_subsurface_node(b_node);
407 
408     SubsurfaceScatteringNode *subsurface = graph->create_node<SubsurfaceScatteringNode>();
409 
410     switch (b_subsurface_node.falloff()) {
411       case BL::ShaderNodeSubsurfaceScattering::falloff_CUBIC:
412         subsurface->falloff = CLOSURE_BSSRDF_CUBIC_ID;
413         break;
414       case BL::ShaderNodeSubsurfaceScattering::falloff_GAUSSIAN:
415         subsurface->falloff = CLOSURE_BSSRDF_GAUSSIAN_ID;
416         break;
417       case BL::ShaderNodeSubsurfaceScattering::falloff_BURLEY:
418         subsurface->falloff = CLOSURE_BSSRDF_BURLEY_ID;
419         break;
420       case BL::ShaderNodeSubsurfaceScattering::falloff_RANDOM_WALK:
421         subsurface->falloff = CLOSURE_BSSRDF_RANDOM_WALK_ID;
422         break;
423     }
424 
425     node = subsurface;
426   }
427   else if (b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) {
428     BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
429     GlossyBsdfNode *glossy = graph->create_node<GlossyBsdfNode>();
430 
431     switch (b_glossy_node.distribution()) {
432       case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
433         glossy->distribution = CLOSURE_BSDF_REFLECTION_ID;
434         break;
435       case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
436         glossy->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_ID;
437         break;
438       case BL::ShaderNodeBsdfGlossy::distribution_GGX:
439         glossy->distribution = CLOSURE_BSDF_MICROFACET_GGX_ID;
440         break;
441       case BL::ShaderNodeBsdfGlossy::distribution_ASHIKHMIN_SHIRLEY:
442         glossy->distribution = CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID;
443         break;
444       case BL::ShaderNodeBsdfGlossy::distribution_MULTI_GGX:
445         glossy->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID;
446         break;
447     }
448     node = glossy;
449   }
450   else if (b_node.is_a(&RNA_ShaderNodeBsdfGlass)) {
451     BL::ShaderNodeBsdfGlass b_glass_node(b_node);
452     GlassBsdfNode *glass = graph->create_node<GlassBsdfNode>();
453     switch (b_glass_node.distribution()) {
454       case BL::ShaderNodeBsdfGlass::distribution_SHARP:
455         glass->distribution = CLOSURE_BSDF_SHARP_GLASS_ID;
456         break;
457       case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
458         glass->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID;
459         break;
460       case BL::ShaderNodeBsdfGlass::distribution_GGX:
461         glass->distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
462         break;
463       case BL::ShaderNodeBsdfGlass::distribution_MULTI_GGX:
464         glass->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
465         break;
466     }
467     node = glass;
468   }
469   else if (b_node.is_a(&RNA_ShaderNodeBsdfRefraction)) {
470     BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
471     RefractionBsdfNode *refraction = graph->create_node<RefractionBsdfNode>();
472     switch (b_refraction_node.distribution()) {
473       case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
474         refraction->distribution = CLOSURE_BSDF_REFRACTION_ID;
475         break;
476       case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
477         refraction->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
478         break;
479       case BL::ShaderNodeBsdfRefraction::distribution_GGX:
480         refraction->distribution = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
481         break;
482     }
483     node = refraction;
484   }
485   else if (b_node.is_a(&RNA_ShaderNodeBsdfToon)) {
486     BL::ShaderNodeBsdfToon b_toon_node(b_node);
487     ToonBsdfNode *toon = graph->create_node<ToonBsdfNode>();
488     switch (b_toon_node.component()) {
489       case BL::ShaderNodeBsdfToon::component_DIFFUSE:
490         toon->component = CLOSURE_BSDF_DIFFUSE_TOON_ID;
491         break;
492       case BL::ShaderNodeBsdfToon::component_GLOSSY:
493         toon->component = CLOSURE_BSDF_GLOSSY_TOON_ID;
494         break;
495     }
496     node = toon;
497   }
498   else if (b_node.is_a(&RNA_ShaderNodeBsdfHair)) {
499     BL::ShaderNodeBsdfHair b_hair_node(b_node);
500     HairBsdfNode *hair = graph->create_node<HairBsdfNode>();
501     switch (b_hair_node.component()) {
502       case BL::ShaderNodeBsdfHair::component_Reflection:
503         hair->component = CLOSURE_BSDF_HAIR_REFLECTION_ID;
504         break;
505       case BL::ShaderNodeBsdfHair::component_Transmission:
506         hair->component = CLOSURE_BSDF_HAIR_TRANSMISSION_ID;
507         break;
508     }
509     node = hair;
510   }
511   else if (b_node.is_a(&RNA_ShaderNodeBsdfHairPrincipled)) {
512     BL::ShaderNodeBsdfHairPrincipled b_principled_hair_node(b_node);
513     PrincipledHairBsdfNode *principled_hair = graph->create_node<PrincipledHairBsdfNode>();
514     principled_hair->parametrization = (NodePrincipledHairParametrization)get_enum(
515         b_principled_hair_node.ptr,
516         "parametrization",
517         NODE_PRINCIPLED_HAIR_NUM,
518         NODE_PRINCIPLED_HAIR_REFLECTANCE);
519     node = principled_hair;
520   }
521   else if (b_node.is_a(&RNA_ShaderNodeBsdfPrincipled)) {
522     BL::ShaderNodeBsdfPrincipled b_principled_node(b_node);
523     PrincipledBsdfNode *principled = graph->create_node<PrincipledBsdfNode>();
524     switch (b_principled_node.distribution()) {
525       case BL::ShaderNodeBsdfPrincipled::distribution_GGX:
526         principled->distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
527         break;
528       case BL::ShaderNodeBsdfPrincipled::distribution_MULTI_GGX:
529         principled->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
530         break;
531     }
532     switch (b_principled_node.subsurface_method()) {
533       case BL::ShaderNodeBsdfPrincipled::subsurface_method_BURLEY:
534         principled->subsurface_method = CLOSURE_BSSRDF_PRINCIPLED_ID;
535         break;
536       case BL::ShaderNodeBsdfPrincipled::subsurface_method_RANDOM_WALK:
537         principled->subsurface_method = CLOSURE_BSSRDF_PRINCIPLED_RANDOM_WALK_ID;
538         break;
539     }
540     node = principled;
541   }
542   else if (b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
543     node = graph->create_node<TranslucentBsdfNode>();
544   }
545   else if (b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
546     node = graph->create_node<TransparentBsdfNode>();
547   }
548   else if (b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
549     node = graph->create_node<VelvetBsdfNode>();
550   }
551   else if (b_node.is_a(&RNA_ShaderNodeEmission)) {
552     node = graph->create_node<EmissionNode>();
553   }
554   else if (b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
555     BL::ShaderNodeAmbientOcclusion b_ao_node(b_node);
556     AmbientOcclusionNode *ao = graph->create_node<AmbientOcclusionNode>();
557     ao->samples = b_ao_node.samples();
558     ao->inside = b_ao_node.inside();
559     ao->only_local = b_ao_node.only_local();
560     node = ao;
561   }
562   else if (b_node.is_a(&RNA_ShaderNodeVolumeScatter)) {
563     node = graph->create_node<ScatterVolumeNode>();
564   }
565   else if (b_node.is_a(&RNA_ShaderNodeVolumeAbsorption)) {
566     node = graph->create_node<AbsorptionVolumeNode>();
567   }
568   else if (b_node.is_a(&RNA_ShaderNodeVolumePrincipled)) {
569     PrincipledVolumeNode *principled = graph->create_node<PrincipledVolumeNode>();
570     node = principled;
571   }
572   else if (b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
573     node = graph->create_node<GeometryNode>();
574   }
575   else if (b_node.is_a(&RNA_ShaderNodeWireframe)) {
576     BL::ShaderNodeWireframe b_wireframe_node(b_node);
577     WireframeNode *wire = graph->create_node<WireframeNode>();
578     wire->use_pixel_size = b_wireframe_node.use_pixel_size();
579     node = wire;
580   }
581   else if (b_node.is_a(&RNA_ShaderNodeWavelength)) {
582     node = graph->create_node<WavelengthNode>();
583   }
584   else if (b_node.is_a(&RNA_ShaderNodeBlackbody)) {
585     node = graph->create_node<BlackbodyNode>();
586   }
587   else if (b_node.is_a(&RNA_ShaderNodeLightPath)) {
588     node = graph->create_node<LightPathNode>();
589   }
590   else if (b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
591     node = graph->create_node<LightFalloffNode>();
592   }
593   else if (b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
594     node = graph->create_node<ObjectInfoNode>();
595   }
596   else if (b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
597     node = graph->create_node<ParticleInfoNode>();
598   }
599   else if (b_node.is_a(&RNA_ShaderNodeHairInfo)) {
600     node = graph->create_node<HairInfoNode>();
601   }
602   else if (b_node.is_a(&RNA_ShaderNodeVolumeInfo)) {
603     node = graph->create_node<VolumeInfoNode>();
604   }
605   else if (b_node.is_a(&RNA_ShaderNodeVertexColor)) {
606     BL::ShaderNodeVertexColor b_vertex_color_node(b_node);
607     VertexColorNode *vertex_color_node = graph->create_node<VertexColorNode>();
608     vertex_color_node->layer_name = b_vertex_color_node.layer_name();
609     node = vertex_color_node;
610   }
611   else if (b_node.is_a(&RNA_ShaderNodeBump)) {
612     BL::ShaderNodeBump b_bump_node(b_node);
613     BumpNode *bump = graph->create_node<BumpNode>();
614     bump->invert = b_bump_node.invert();
615     node = bump;
616   }
617   else if (b_node.is_a(&RNA_ShaderNodeScript)) {
618 #ifdef WITH_OSL
619     if (scene->shader_manager->use_osl()) {
620       /* create script node */
621       BL::ShaderNodeScript b_script_node(b_node);
622 
623       ShaderManager *manager = scene->shader_manager;
624       string bytecode_hash = b_script_node.bytecode_hash();
625 
626       if (!bytecode_hash.empty()) {
627         node = OSLShaderManager::osl_node(
628             graph, manager, "", bytecode_hash, b_script_node.bytecode());
629       }
630       else {
631         string absolute_filepath = blender_absolute_path(
632             b_data, b_ntree, b_script_node.filepath());
633         node = OSLShaderManager::osl_node(graph, manager, absolute_filepath, "");
634       }
635     }
636 #else
637     (void)b_data;
638     (void)b_ntree;
639 #endif
640   }
641   else if (b_node.is_a(&RNA_ShaderNodeTexImage)) {
642     BL::ShaderNodeTexImage b_image_node(b_node);
643     BL::Image b_image(b_image_node.image());
644     BL::ImageUser b_image_user(b_image_node.image_user());
645     ImageTextureNode *image = graph->create_node<ImageTextureNode>();
646 
647     image->interpolation = get_image_interpolation(b_image_node);
648     image->extension = get_image_extension(b_image_node);
649     image->projection = (NodeImageProjection)b_image_node.projection();
650     image->projection_blend = b_image_node.projection_blend();
651     BL::TexMapping b_texture_mapping(b_image_node.texture_mapping());
652     get_tex_mapping(&image->tex_mapping, b_texture_mapping);
653 
654     if (b_image) {
655       PointerRNA colorspace_ptr = b_image.colorspace_settings().ptr;
656       image->colorspace = get_enum_identifier(colorspace_ptr, "name");
657 
658       image->animated = b_image_node.image_user().use_auto_refresh();
659       image->alpha_type = get_image_alpha_type(b_image);
660 
661       image->tiles.clear();
662       BL::Image::tiles_iterator b_iter;
663       for (b_image.tiles.begin(b_iter); b_iter != b_image.tiles.end(); ++b_iter) {
664         image->tiles.push_back(b_iter->number());
665       }
666 
667       /* builtin images will use callback-based reading because
668        * they could only be loaded correct from blender side
669        */
670       bool is_builtin = b_image.packed_file() || b_image.source() == BL::Image::source_GENERATED ||
671                         b_image.source() == BL::Image::source_MOVIE ||
672                         (b_engine.is_preview() && b_image.source() != BL::Image::source_SEQUENCE);
673 
674       if (is_builtin) {
675         /* for builtin images we're using image datablock name to find an image to
676          * read pixels from later
677          *
678          * also store frame number as well, so there's no differences in handling
679          * builtin names for packed images and movies
680          */
681         int scene_frame = b_scene.frame_current();
682         int image_frame = image_user_frame_number(b_image_user, b_image, scene_frame);
683         image->handle = scene->image_manager->add_image(
684             new BlenderImageLoader(b_image, image_frame), image->image_params());
685       }
686       else {
687         image->filename = image_user_file_path(
688             b_image_user, b_image, b_scene.frame_current(), true);
689       }
690     }
691     node = image;
692   }
693   else if (b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
694     BL::ShaderNodeTexEnvironment b_env_node(b_node);
695     BL::Image b_image(b_env_node.image());
696     BL::ImageUser b_image_user(b_env_node.image_user());
697     EnvironmentTextureNode *env = graph->create_node<EnvironmentTextureNode>();
698 
699     env->interpolation = get_image_interpolation(b_env_node);
700     env->projection = (NodeEnvironmentProjection)b_env_node.projection();
701     BL::TexMapping b_texture_mapping(b_env_node.texture_mapping());
702     get_tex_mapping(&env->tex_mapping, b_texture_mapping);
703 
704     if (b_image) {
705       PointerRNA colorspace_ptr = b_image.colorspace_settings().ptr;
706       env->colorspace = get_enum_identifier(colorspace_ptr, "name");
707 
708       env->animated = b_env_node.image_user().use_auto_refresh();
709       env->alpha_type = get_image_alpha_type(b_image);
710 
711       bool is_builtin = b_image.packed_file() || b_image.source() == BL::Image::source_GENERATED ||
712                         b_image.source() == BL::Image::source_MOVIE ||
713                         (b_engine.is_preview() && b_image.source() != BL::Image::source_SEQUENCE);
714 
715       if (is_builtin) {
716         int scene_frame = b_scene.frame_current();
717         int image_frame = image_user_frame_number(b_image_user, b_image, scene_frame);
718         env->handle = scene->image_manager->add_image(new BlenderImageLoader(b_image, image_frame),
719                                                       env->image_params());
720       }
721       else {
722         env->filename = image_user_file_path(
723             b_image_user, b_image, b_scene.frame_current(), false);
724       }
725     }
726     node = env;
727   }
728   else if (b_node.is_a(&RNA_ShaderNodeTexGradient)) {
729     BL::ShaderNodeTexGradient b_gradient_node(b_node);
730     GradientTextureNode *gradient = graph->create_node<GradientTextureNode>();
731     gradient->type = (NodeGradientType)b_gradient_node.gradient_type();
732     BL::TexMapping b_texture_mapping(b_gradient_node.texture_mapping());
733     get_tex_mapping(&gradient->tex_mapping, b_texture_mapping);
734     node = gradient;
735   }
736   else if (b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
737     BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
738     VoronoiTextureNode *voronoi = graph->create_node<VoronoiTextureNode>();
739     voronoi->dimensions = b_voronoi_node.voronoi_dimensions();
740     voronoi->feature = (NodeVoronoiFeature)b_voronoi_node.feature();
741     voronoi->metric = (NodeVoronoiDistanceMetric)b_voronoi_node.distance();
742     BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping());
743     get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping);
744     node = voronoi;
745   }
746   else if (b_node.is_a(&RNA_ShaderNodeTexMagic)) {
747     BL::ShaderNodeTexMagic b_magic_node(b_node);
748     MagicTextureNode *magic = graph->create_node<MagicTextureNode>();
749     magic->depth = b_magic_node.turbulence_depth();
750     BL::TexMapping b_texture_mapping(b_magic_node.texture_mapping());
751     get_tex_mapping(&magic->tex_mapping, b_texture_mapping);
752     node = magic;
753   }
754   else if (b_node.is_a(&RNA_ShaderNodeTexWave)) {
755     BL::ShaderNodeTexWave b_wave_node(b_node);
756     WaveTextureNode *wave = graph->create_node<WaveTextureNode>();
757     wave->type = (NodeWaveType)b_wave_node.wave_type();
758     wave->bands_direction = (NodeWaveBandsDirection)b_wave_node.bands_direction();
759     wave->rings_direction = (NodeWaveRingsDirection)b_wave_node.rings_direction();
760     wave->profile = (NodeWaveProfile)b_wave_node.wave_profile();
761     BL::TexMapping b_texture_mapping(b_wave_node.texture_mapping());
762     get_tex_mapping(&wave->tex_mapping, b_texture_mapping);
763     node = wave;
764   }
765   else if (b_node.is_a(&RNA_ShaderNodeTexChecker)) {
766     BL::ShaderNodeTexChecker b_checker_node(b_node);
767     CheckerTextureNode *checker = graph->create_node<CheckerTextureNode>();
768     BL::TexMapping b_texture_mapping(b_checker_node.texture_mapping());
769     get_tex_mapping(&checker->tex_mapping, b_texture_mapping);
770     node = checker;
771   }
772   else if (b_node.is_a(&RNA_ShaderNodeTexBrick)) {
773     BL::ShaderNodeTexBrick b_brick_node(b_node);
774     BrickTextureNode *brick = graph->create_node<BrickTextureNode>();
775     brick->offset = b_brick_node.offset();
776     brick->offset_frequency = b_brick_node.offset_frequency();
777     brick->squash = b_brick_node.squash();
778     brick->squash_frequency = b_brick_node.squash_frequency();
779     BL::TexMapping b_texture_mapping(b_brick_node.texture_mapping());
780     get_tex_mapping(&brick->tex_mapping, b_texture_mapping);
781     node = brick;
782   }
783   else if (b_node.is_a(&RNA_ShaderNodeTexNoise)) {
784     BL::ShaderNodeTexNoise b_noise_node(b_node);
785     NoiseTextureNode *noise = graph->create_node<NoiseTextureNode>();
786     noise->dimensions = b_noise_node.noise_dimensions();
787     BL::TexMapping b_texture_mapping(b_noise_node.texture_mapping());
788     get_tex_mapping(&noise->tex_mapping, b_texture_mapping);
789     node = noise;
790   }
791   else if (b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
792     BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
793     MusgraveTextureNode *musgrave_node = graph->create_node<MusgraveTextureNode>();
794     musgrave_node->type = (NodeMusgraveType)b_musgrave_node.musgrave_type();
795     musgrave_node->dimensions = b_musgrave_node.musgrave_dimensions();
796     BL::TexMapping b_texture_mapping(b_musgrave_node.texture_mapping());
797     get_tex_mapping(&musgrave_node->tex_mapping, b_texture_mapping);
798     node = musgrave_node;
799   }
800   else if (b_node.is_a(&RNA_ShaderNodeTexCoord)) {
801     BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
802     TextureCoordinateNode *tex_coord = graph->create_node<TextureCoordinateNode>();
803     tex_coord->from_dupli = b_tex_coord_node.from_instancer();
804     if (b_tex_coord_node.object()) {
805       tex_coord->use_transform = true;
806       tex_coord->ob_tfm = get_transform(b_tex_coord_node.object().matrix_world());
807     }
808     node = tex_coord;
809   }
810   else if (b_node.is_a(&RNA_ShaderNodeTexSky)) {
811     BL::ShaderNodeTexSky b_sky_node(b_node);
812     SkyTextureNode *sky = graph->create_node<SkyTextureNode>();
813     sky->type = (NodeSkyType)b_sky_node.sky_type();
814     sky->sun_direction = normalize(get_float3(b_sky_node.sun_direction()));
815     sky->turbidity = b_sky_node.turbidity();
816     sky->ground_albedo = b_sky_node.ground_albedo();
817     sky->sun_disc = b_sky_node.sun_disc();
818     sky->sun_size = b_sky_node.sun_size();
819     sky->sun_intensity = b_sky_node.sun_intensity();
820     sky->sun_elevation = b_sky_node.sun_elevation();
821     sky->sun_rotation = b_sky_node.sun_rotation();
822     sky->altitude = 1000.0f * b_sky_node.altitude();
823     sky->air_density = b_sky_node.air_density();
824     sky->dust_density = b_sky_node.dust_density();
825     sky->ozone_density = b_sky_node.ozone_density();
826     BL::TexMapping b_texture_mapping(b_sky_node.texture_mapping());
827     get_tex_mapping(&sky->tex_mapping, b_texture_mapping);
828     node = sky;
829   }
830   else if (b_node.is_a(&RNA_ShaderNodeTexIES)) {
831     BL::ShaderNodeTexIES b_ies_node(b_node);
832     IESLightNode *ies = graph->create_node<IESLightNode>();
833     switch (b_ies_node.mode()) {
834       case BL::ShaderNodeTexIES::mode_EXTERNAL:
835         ies->filename = blender_absolute_path(b_data, b_ntree, b_ies_node.filepath());
836         break;
837       case BL::ShaderNodeTexIES::mode_INTERNAL:
838         ies->ies = get_text_datablock_content(b_ies_node.ies().ptr);
839         if (ies->ies.empty()) {
840           ies->ies = "\n";
841         }
842         break;
843     }
844     node = ies;
845   }
846   else if (b_node.is_a(&RNA_ShaderNodeTexWhiteNoise)) {
847     BL::ShaderNodeTexWhiteNoise b_tex_white_noise_node(b_node);
848     WhiteNoiseTextureNode *white_noise_node = graph->create_node<WhiteNoiseTextureNode>();
849     white_noise_node->dimensions = b_tex_white_noise_node.noise_dimensions();
850     node = white_noise_node;
851   }
852   else if (b_node.is_a(&RNA_ShaderNodeNormalMap)) {
853     BL::ShaderNodeNormalMap b_normal_map_node(b_node);
854     NormalMapNode *nmap = graph->create_node<NormalMapNode>();
855     nmap->space = (NodeNormalMapSpace)b_normal_map_node.space();
856     nmap->attribute = b_normal_map_node.uv_map();
857     node = nmap;
858   }
859   else if (b_node.is_a(&RNA_ShaderNodeTangent)) {
860     BL::ShaderNodeTangent b_tangent_node(b_node);
861     TangentNode *tangent = graph->create_node<TangentNode>();
862     tangent->direction_type = (NodeTangentDirectionType)b_tangent_node.direction_type();
863     tangent->axis = (NodeTangentAxis)b_tangent_node.axis();
864     tangent->attribute = b_tangent_node.uv_map();
865     node = tangent;
866   }
867   else if (b_node.is_a(&RNA_ShaderNodeUVMap)) {
868     BL::ShaderNodeUVMap b_uvmap_node(b_node);
869     UVMapNode *uvm = graph->create_node<UVMapNode>();
870     uvm->attribute = b_uvmap_node.uv_map();
871     uvm->from_dupli = b_uvmap_node.from_instancer();
872     node = uvm;
873   }
874   else if (b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
875     BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
876     PointDensityTextureNode *point_density = graph->create_node<PointDensityTextureNode>();
877     point_density->space = (NodeTexVoxelSpace)b_point_density_node.space();
878     point_density->interpolation = get_image_interpolation(b_point_density_node);
879     point_density->handle = scene->image_manager->add_image(
880         new BlenderPointDensityLoader(b_depsgraph, b_point_density_node),
881         point_density->image_params());
882 
883     b_point_density_node.cache_point_density(b_depsgraph);
884     node = point_density;
885 
886     /* Transformation form world space to texture space.
887      *
888      * NOTE: Do this after the texture is cached, this is because getting
889      * min/max will need to access this cache.
890      */
891     BL::Object b_ob(b_point_density_node.object());
892     if (b_ob) {
893       float3 loc, size;
894       point_density_texture_space(b_depsgraph, b_point_density_node, loc, size);
895       point_density->tfm = transform_translate(-loc) * transform_scale(size) *
896                            transform_inverse(get_transform(b_ob.matrix_world()));
897     }
898   }
899   else if (b_node.is_a(&RNA_ShaderNodeBevel)) {
900     BL::ShaderNodeBevel b_bevel_node(b_node);
901     BevelNode *bevel = graph->create_node<BevelNode>();
902     bevel->samples = b_bevel_node.samples();
903     node = bevel;
904   }
905   else if (b_node.is_a(&RNA_ShaderNodeDisplacement)) {
906     BL::ShaderNodeDisplacement b_disp_node(b_node);
907     DisplacementNode *disp = graph->create_node<DisplacementNode>();
908     disp->space = (NodeNormalMapSpace)b_disp_node.space();
909     node = disp;
910   }
911   else if (b_node.is_a(&RNA_ShaderNodeVectorDisplacement)) {
912     BL::ShaderNodeVectorDisplacement b_disp_node(b_node);
913     VectorDisplacementNode *disp = graph->create_node<VectorDisplacementNode>();
914     disp->space = (NodeNormalMapSpace)b_disp_node.space();
915     disp->attribute = "";
916     node = disp;
917   }
918   else if (b_node.is_a(&RNA_ShaderNodeOutputAOV)) {
919     BL::ShaderNodeOutputAOV b_aov_node(b_node);
920     OutputAOVNode *aov = graph->create_node<OutputAOVNode>();
921     aov->name = b_aov_node.name();
922     node = aov;
923   }
924 
925   if (node) {
926     node->name = b_node.name();
927     graph->add(node);
928   }
929 
930   return node;
931 }
932 
node_use_modified_socket_name(ShaderNode * node)933 static bool node_use_modified_socket_name(ShaderNode *node)
934 {
935   if (node->special_type == SHADER_SPECIAL_TYPE_OSL)
936     return false;
937 
938   return true;
939 }
940 
node_find_input_by_name(ShaderNode * node,BL::Node & b_node,BL::NodeSocket & b_socket)941 static ShaderInput *node_find_input_by_name(ShaderNode *node,
942                                             BL::Node &b_node,
943                                             BL::NodeSocket &b_socket)
944 {
945   string name = b_socket.name();
946 
947   if (node_use_modified_socket_name(node)) {
948     BL::Node::inputs_iterator b_input;
949     bool found = false;
950     int counter = 0, total = 0;
951 
952     for (b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
953       if (b_input->name() == name) {
954         if (!found)
955           counter++;
956         total++;
957       }
958 
959       if (b_input->ptr.data == b_socket.ptr.data)
960         found = true;
961     }
962 
963     /* rename if needed */
964     if (name == "Shader")
965       name = "Closure";
966 
967     if (total > 1)
968       name = string_printf("%s%d", name.c_str(), counter);
969   }
970 
971   return node->input(name.c_str());
972 }
973 
node_find_output_by_name(ShaderNode * node,BL::Node & b_node,BL::NodeSocket & b_socket)974 static ShaderOutput *node_find_output_by_name(ShaderNode *node,
975                                               BL::Node &b_node,
976                                               BL::NodeSocket &b_socket)
977 {
978   string name = b_socket.name();
979 
980   if (node_use_modified_socket_name(node)) {
981     BL::Node::outputs_iterator b_output;
982     bool found = false;
983     int counter = 0, total = 0;
984 
985     for (b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
986       if (b_output->name() == name) {
987         if (!found)
988           counter++;
989         total++;
990       }
991 
992       if (b_output->ptr.data == b_socket.ptr.data)
993         found = true;
994     }
995 
996     /* rename if needed */
997     if (name == "Shader")
998       name = "Closure";
999 
1000     if (total > 1)
1001       name = string_printf("%s%d", name.c_str(), counter);
1002   }
1003 
1004   return node->output(name.c_str());
1005 }
1006 
add_nodes(Scene * scene,BL::RenderEngine & b_engine,BL::BlendData & b_data,BL::Depsgraph & b_depsgraph,BL::Scene & b_scene,ShaderGraph * graph,BL::ShaderNodeTree & b_ntree,const ProxyMap & proxy_input_map,const ProxyMap & proxy_output_map)1007 static void add_nodes(Scene *scene,
1008                       BL::RenderEngine &b_engine,
1009                       BL::BlendData &b_data,
1010                       BL::Depsgraph &b_depsgraph,
1011                       BL::Scene &b_scene,
1012                       ShaderGraph *graph,
1013                       BL::ShaderNodeTree &b_ntree,
1014                       const ProxyMap &proxy_input_map,
1015                       const ProxyMap &proxy_output_map)
1016 {
1017   /* add nodes */
1018   BL::ShaderNodeTree::nodes_iterator b_node;
1019   PtrInputMap input_map;
1020   PtrOutputMap output_map;
1021 
1022   BL::Node::inputs_iterator b_input;
1023   BL::Node::outputs_iterator b_output;
1024 
1025   /* find the node to use for output if there are multiple */
1026   BL::ShaderNode output_node = b_ntree.get_output_node(
1027       BL::ShaderNodeOutputMaterial::target_CYCLES);
1028 
1029   /* add nodes */
1030   for (b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
1031     if (b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
1032       /* replace muted node with internal links */
1033       BL::Node::internal_links_iterator b_link;
1034       for (b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end();
1035            ++b_link) {
1036         BL::NodeSocket to_socket(b_link->to_socket());
1037         SocketType::Type to_socket_type = convert_socket_type(to_socket);
1038         if (to_socket_type == SocketType::UNDEFINED) {
1039           continue;
1040         }
1041 
1042         ConvertNode *proxy = graph->create_node<ConvertNode>(to_socket_type, to_socket_type, true);
1043 
1044         input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
1045         output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
1046 
1047         graph->add(proxy);
1048       }
1049     }
1050     else if (b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup) ||
1051              b_node->is_a(&RNA_ShaderNodeCustomGroup)) {
1052 
1053       BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
1054       if (b_node->is_a(&RNA_ShaderNodeGroup))
1055         b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
1056       else if (b_node->is_a(&RNA_NodeCustomGroup))
1057         b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
1058       else
1059         b_group_ntree = BL::ShaderNodeTree(((BL::ShaderNodeCustomGroup)(*b_node)).node_tree());
1060 
1061       ProxyMap group_proxy_input_map, group_proxy_output_map;
1062 
1063       /* Add a proxy node for each socket
1064        * Do this even if the node group has no internal tree,
1065        * so that links have something to connect to and assert won't fail.
1066        */
1067       for (b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1068         SocketType::Type input_type = convert_socket_type(*b_input);
1069         if (input_type == SocketType::UNDEFINED) {
1070           continue;
1071         }
1072 
1073         ConvertNode *proxy = graph->create_node<ConvertNode>(input_type, input_type, true);
1074         graph->add(proxy);
1075 
1076         /* register the proxy node for internal binding */
1077         group_proxy_input_map[b_input->identifier()] = proxy;
1078 
1079         input_map[b_input->ptr.data] = proxy->inputs[0];
1080 
1081         set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1082       }
1083       for (b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1084         SocketType::Type output_type = convert_socket_type(*b_output);
1085         if (output_type == SocketType::UNDEFINED) {
1086           continue;
1087         }
1088 
1089         ConvertNode *proxy = graph->create_node<ConvertNode>(output_type, output_type, true);
1090         graph->add(proxy);
1091 
1092         /* register the proxy node for internal binding */
1093         group_proxy_output_map[b_output->identifier()] = proxy;
1094 
1095         output_map[b_output->ptr.data] = proxy->outputs[0];
1096       }
1097 
1098       if (b_group_ntree) {
1099         add_nodes(scene,
1100                   b_engine,
1101                   b_data,
1102                   b_depsgraph,
1103                   b_scene,
1104                   graph,
1105                   b_group_ntree,
1106                   group_proxy_input_map,
1107                   group_proxy_output_map);
1108       }
1109     }
1110     else if (b_node->is_a(&RNA_NodeGroupInput)) {
1111       /* map each socket to a proxy node */
1112       for (b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1113         ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
1114         if (proxy_it != proxy_input_map.end()) {
1115           ConvertNode *proxy = proxy_it->second;
1116 
1117           output_map[b_output->ptr.data] = proxy->outputs[0];
1118         }
1119       }
1120     }
1121     else if (b_node->is_a(&RNA_NodeGroupOutput)) {
1122       BL::NodeGroupOutput b_output_node(*b_node);
1123       /* only the active group output is used */
1124       if (b_output_node.is_active_output()) {
1125         /* map each socket to a proxy node */
1126         for (b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1127           ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
1128           if (proxy_it != proxy_output_map.end()) {
1129             ConvertNode *proxy = proxy_it->second;
1130 
1131             input_map[b_input->ptr.data] = proxy->inputs[0];
1132 
1133             set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1134           }
1135         }
1136       }
1137     }
1138     else {
1139       ShaderNode *node = NULL;
1140 
1141       if (b_node->ptr.data == output_node.ptr.data) {
1142         node = graph->output();
1143       }
1144       else {
1145         BL::ShaderNode b_shader_node(*b_node);
1146         node = add_node(
1147             scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree, b_shader_node);
1148       }
1149 
1150       if (node) {
1151         /* map node sockets for linking */
1152         for (b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1153           ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
1154           if (!input) {
1155             /* XXX should not happen, report error? */
1156             continue;
1157           }
1158           input_map[b_input->ptr.data] = input;
1159 
1160           set_default_value(input, *b_input, b_data, b_ntree);
1161         }
1162         for (b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1163           ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
1164           if (!output) {
1165             /* XXX should not happen, report error? */
1166             continue;
1167           }
1168           output_map[b_output->ptr.data] = output;
1169         }
1170       }
1171     }
1172   }
1173 
1174   /* connect nodes */
1175   BL::NodeTree::links_iterator b_link;
1176 
1177   for (b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
1178     /* Ignore invalid links to avoid unwanted cycles created in graph.
1179      * Also ignore links with unavailable sockets. */
1180     if (!(b_link->is_valid() && b_link->from_socket().enabled() &&
1181           b_link->to_socket().enabled())) {
1182       continue;
1183     }
1184     /* get blender link data */
1185     BL::NodeSocket b_from_sock = b_link->from_socket();
1186     BL::NodeSocket b_to_sock = b_link->to_socket();
1187 
1188     ShaderOutput *output = 0;
1189     ShaderInput *input = 0;
1190 
1191     PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
1192     if (output_it != output_map.end())
1193       output = output_it->second;
1194     PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
1195     if (input_it != input_map.end())
1196       input = input_it->second;
1197 
1198     /* either node may be NULL when the node was not exported, typically
1199      * because the node type is not supported */
1200     if (output && input)
1201       graph->connect(output, input);
1202   }
1203 }
1204 
add_nodes(Scene * scene,BL::RenderEngine & b_engine,BL::BlendData & b_data,BL::Depsgraph & b_depsgraph,BL::Scene & b_scene,ShaderGraph * graph,BL::ShaderNodeTree & b_ntree)1205 static void add_nodes(Scene *scene,
1206                       BL::RenderEngine &b_engine,
1207                       BL::BlendData &b_data,
1208                       BL::Depsgraph &b_depsgraph,
1209                       BL::Scene &b_scene,
1210                       ShaderGraph *graph,
1211                       BL::ShaderNodeTree &b_ntree)
1212 {
1213   static const ProxyMap empty_proxy_map;
1214   add_nodes(scene,
1215             b_engine,
1216             b_data,
1217             b_depsgraph,
1218             b_scene,
1219             graph,
1220             b_ntree,
1221             empty_proxy_map,
1222             empty_proxy_map);
1223 }
1224 
1225 /* Sync Materials */
1226 
sync_materials(BL::Depsgraph & b_depsgraph,bool update_all)1227 void BlenderSync::sync_materials(BL::Depsgraph &b_depsgraph, bool update_all)
1228 {
1229   shader_map.set_default(scene->default_surface);
1230 
1231   TaskPool pool;
1232   set<Shader *> updated_shaders;
1233 
1234   BL::Depsgraph::ids_iterator b_id;
1235   for (b_depsgraph.ids.begin(b_id); b_id != b_depsgraph.ids.end(); ++b_id) {
1236     if (!b_id->is_a(&RNA_Material)) {
1237       continue;
1238     }
1239 
1240     BL::Material b_mat(*b_id);
1241     Shader *shader;
1242 
1243     /* test if we need to sync */
1244     if (shader_map.add_or_update(&shader, b_mat) || update_all) {
1245       ShaderGraph *graph = new ShaderGraph();
1246 
1247       shader->name = b_mat.name().c_str();
1248       shader->pass_id = b_mat.pass_index();
1249 
1250       /* create nodes */
1251       if (b_mat.use_nodes() && b_mat.node_tree()) {
1252         BL::ShaderNodeTree b_ntree(b_mat.node_tree());
1253 
1254         add_nodes(scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree);
1255       }
1256       else {
1257         DiffuseBsdfNode *diffuse = graph->create_node<DiffuseBsdfNode>();
1258         diffuse->color = get_float3(b_mat.diffuse_color());
1259         graph->add(diffuse);
1260 
1261         ShaderNode *out = graph->output();
1262         graph->connect(diffuse->output("BSDF"), out->input("Surface"));
1263       }
1264 
1265       /* settings */
1266       PointerRNA cmat = RNA_pointer_get(&b_mat.ptr, "cycles");
1267       shader->use_mis = get_boolean(cmat, "sample_as_light");
1268       shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
1269       shader->heterogeneous_volume = !get_boolean(cmat, "homogeneous_volume");
1270       shader->volume_sampling_method = get_volume_sampling(cmat);
1271       shader->volume_interpolation_method = get_volume_interpolation(cmat);
1272       shader->volume_step_rate = get_float(cmat, "volume_step_rate");
1273       shader->displacement_method = get_displacement_method(cmat);
1274 
1275       shader->set_graph(graph);
1276 
1277       /* By simplifying the shader graph as soon as possible, some
1278        * redundant shader nodes might be removed which prevents loading
1279        * unnecessary attributes later.
1280        *
1281        * However, since graph simplification also accounts for e.g. mix
1282        * weight, this would cause frequent expensive resyncs in interactive
1283        * sessions, so for those sessions optimization is only performed
1284        * right before compiling.
1285        */
1286       if (!preview) {
1287         pool.push(function_bind(&ShaderGraph::simplify, graph, scene));
1288         /* NOTE: Update shaders out of the threads since those routines
1289          * are accessing and writing to a global context.
1290          */
1291         updated_shaders.insert(shader);
1292       }
1293       else {
1294         /* NOTE: Update tagging can access links which are being
1295          * optimized out.
1296          */
1297         shader->tag_update(scene);
1298       }
1299     }
1300   }
1301 
1302   pool.wait_work();
1303 
1304   foreach (Shader *shader, updated_shaders) {
1305     shader->tag_update(scene);
1306   }
1307 }
1308 
1309 /* Sync World */
1310 
sync_world(BL::Depsgraph & b_depsgraph,BL::SpaceView3D & b_v3d,bool update_all)1311 void BlenderSync::sync_world(BL::Depsgraph &b_depsgraph, BL::SpaceView3D &b_v3d, bool update_all)
1312 {
1313   Background *background = scene->background;
1314   Background prevbackground = *background;
1315 
1316   BL::World b_world = b_scene.world();
1317 
1318   BlenderViewportParameters new_viewport_parameters(b_v3d);
1319 
1320   if (world_recalc || update_all || b_world.ptr.data != world_map ||
1321       viewport_parameters.modified(new_viewport_parameters)) {
1322     Shader *shader = scene->default_background;
1323     ShaderGraph *graph = new ShaderGraph();
1324 
1325     /* create nodes */
1326     if (new_viewport_parameters.use_scene_world && b_world && b_world.use_nodes() &&
1327         b_world.node_tree()) {
1328       BL::ShaderNodeTree b_ntree(b_world.node_tree());
1329 
1330       add_nodes(scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree);
1331 
1332       /* volume */
1333       PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
1334       shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
1335       shader->volume_sampling_method = get_volume_sampling(cworld);
1336       shader->volume_interpolation_method = get_volume_interpolation(cworld);
1337       shader->volume_step_rate = get_float(cworld, "volume_step_size");
1338     }
1339     else if (new_viewport_parameters.use_scene_world && b_world) {
1340       BackgroundNode *background = graph->create_node<BackgroundNode>();
1341       background->color = get_float3(b_world.color());
1342       graph->add(background);
1343 
1344       ShaderNode *out = graph->output();
1345       graph->connect(background->output("Background"), out->input("Surface"));
1346     }
1347     else if (!new_viewport_parameters.use_scene_world) {
1348       float3 world_color;
1349       if (b_world) {
1350         world_color = get_float3(b_world.color());
1351       }
1352       else {
1353         world_color = make_float3(0.0f, 0.0f, 0.0f);
1354       }
1355 
1356       BackgroundNode *background = graph->create_node<BackgroundNode>();
1357       graph->add(background);
1358 
1359       LightPathNode *light_path = graph->create_node<LightPathNode>();
1360       graph->add(light_path);
1361 
1362       MixNode *mix_scene_with_background = graph->create_node<MixNode>();
1363       mix_scene_with_background->color2 = world_color;
1364       graph->add(mix_scene_with_background);
1365 
1366       EnvironmentTextureNode *texture_environment = graph->create_node<EnvironmentTextureNode>();
1367       texture_environment->tex_mapping.type = TextureMapping::VECTOR;
1368       texture_environment->tex_mapping.rotation[2] = new_viewport_parameters.studiolight_rotate_z;
1369       texture_environment->filename = new_viewport_parameters.studiolight_path;
1370       graph->add(texture_environment);
1371 
1372       MixNode *mix_intensity = graph->create_node<MixNode>();
1373       mix_intensity->type = NODE_MIX_MUL;
1374       mix_intensity->fac = 1.0f;
1375       mix_intensity->color2 = make_float3(new_viewport_parameters.studiolight_intensity,
1376                                           new_viewport_parameters.studiolight_intensity,
1377                                           new_viewport_parameters.studiolight_intensity);
1378       graph->add(mix_intensity);
1379 
1380       TextureCoordinateNode *texture_coordinate = graph->create_node<TextureCoordinateNode>();
1381       graph->add(texture_coordinate);
1382 
1383       MixNode *mix_background_with_environment = graph->create_node<MixNode>();
1384       mix_background_with_environment->fac = new_viewport_parameters.studiolight_background_alpha;
1385       mix_background_with_environment->color1 = world_color;
1386       graph->add(mix_background_with_environment);
1387 
1388       ShaderNode *out = graph->output();
1389 
1390       graph->connect(texture_coordinate->output("Generated"),
1391                      texture_environment->input("Vector"));
1392       graph->connect(texture_environment->output("Color"), mix_intensity->input("Color1"));
1393       graph->connect(light_path->output("Is Camera Ray"), mix_scene_with_background->input("Fac"));
1394       graph->connect(mix_intensity->output("Color"), mix_scene_with_background->input("Color1"));
1395       graph->connect(mix_intensity->output("Color"),
1396                      mix_background_with_environment->input("Color2"));
1397       graph->connect(mix_background_with_environment->output("Color"),
1398                      mix_scene_with_background->input("Color2"));
1399       graph->connect(mix_scene_with_background->output("Color"), background->input("Color"));
1400       graph->connect(background->output("Background"), out->input("Surface"));
1401     }
1402 
1403     if (b_world) {
1404       /* AO */
1405       BL::WorldLighting b_light = b_world.light_settings();
1406 
1407       background->use_ao = b_light.use_ambient_occlusion();
1408       background->ao_factor = b_light.ao_factor();
1409       background->ao_distance = b_light.distance();
1410 
1411       /* visibility */
1412       PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
1413       uint visibility = 0;
1414 
1415       visibility |= get_boolean(cvisibility, "camera") ? PATH_RAY_CAMERA : 0;
1416       visibility |= get_boolean(cvisibility, "diffuse") ? PATH_RAY_DIFFUSE : 0;
1417       visibility |= get_boolean(cvisibility, "glossy") ? PATH_RAY_GLOSSY : 0;
1418       visibility |= get_boolean(cvisibility, "transmission") ? PATH_RAY_TRANSMIT : 0;
1419       visibility |= get_boolean(cvisibility, "scatter") ? PATH_RAY_VOLUME_SCATTER : 0;
1420 
1421       background->visibility = visibility;
1422     }
1423     else {
1424       background->use_ao = false;
1425       background->ao_factor = 0.0f;
1426       background->ao_distance = FLT_MAX;
1427     }
1428 
1429     shader->set_graph(graph);
1430     shader->tag_update(scene);
1431     background->tag_update(scene);
1432   }
1433 
1434   PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
1435   background->transparent = b_scene.render().film_transparent();
1436 
1437   if (background->transparent) {
1438     background->transparent_glass = get_boolean(cscene, "film_transparent_glass");
1439     background->transparent_roughness_threshold = get_float(cscene, "film_transparent_roughness");
1440   }
1441   else {
1442     background->transparent_glass = false;
1443     background->transparent_roughness_threshold = 0.0f;
1444   }
1445 
1446   background->use_shader = view_layer.use_background_shader |
1447                            viewport_parameters.custom_viewport_parameters();
1448   background->use_ao = background->use_ao && view_layer.use_background_ao;
1449 
1450   if (background->modified(prevbackground))
1451     background->tag_update(scene);
1452 }
1453 
1454 /* Sync Lights */
1455 
sync_lights(BL::Depsgraph & b_depsgraph,bool update_all)1456 void BlenderSync::sync_lights(BL::Depsgraph &b_depsgraph, bool update_all)
1457 {
1458   shader_map.set_default(scene->default_light);
1459 
1460   BL::Depsgraph::ids_iterator b_id;
1461   for (b_depsgraph.ids.begin(b_id); b_id != b_depsgraph.ids.end(); ++b_id) {
1462     if (!b_id->is_a(&RNA_Light)) {
1463       continue;
1464     }
1465 
1466     BL::Light b_light(*b_id);
1467     Shader *shader;
1468 
1469     /* test if we need to sync */
1470     if (shader_map.add_or_update(&shader, b_light) || update_all) {
1471       ShaderGraph *graph = new ShaderGraph();
1472 
1473       /* create nodes */
1474       if (b_light.use_nodes() && b_light.node_tree()) {
1475         shader->name = b_light.name().c_str();
1476 
1477         BL::ShaderNodeTree b_ntree(b_light.node_tree());
1478 
1479         add_nodes(scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree);
1480       }
1481       else {
1482         EmissionNode *emission = graph->create_node<EmissionNode>();
1483         emission->color = make_float3(1.0f, 1.0f, 1.0f);
1484         emission->strength = 1.0f;
1485         graph->add(emission);
1486 
1487         ShaderNode *out = graph->output();
1488         graph->connect(emission->output("Emission"), out->input("Surface"));
1489       }
1490 
1491       shader->set_graph(graph);
1492       shader->tag_update(scene);
1493     }
1494   }
1495 }
1496 
sync_shaders(BL::Depsgraph & b_depsgraph,BL::SpaceView3D & b_v3d)1497 void BlenderSync::sync_shaders(BL::Depsgraph &b_depsgraph, BL::SpaceView3D &b_v3d)
1498 {
1499   /* for auto refresh images */
1500   bool auto_refresh_update = false;
1501 
1502   if (preview) {
1503     ImageManager *image_manager = scene->image_manager;
1504     int frame = b_scene.frame_current();
1505     auto_refresh_update = image_manager->set_animation_frame_update(frame);
1506   }
1507 
1508   shader_map.pre_sync();
1509 
1510   sync_world(b_depsgraph, b_v3d, auto_refresh_update);
1511   sync_lights(b_depsgraph, auto_refresh_update);
1512   sync_materials(b_depsgraph, auto_refresh_update);
1513 }
1514 
1515 CCL_NAMESPACE_END
1516