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