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