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