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