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