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