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