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