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