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