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