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