Cycles / Blackbody to RGB node:
[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_ShaderNodeNormal)) {
254                 BL::Node::outputs_iterator out_it;
255                 b_node.outputs.begin(out_it);
256                 
257                 NormalNode *norm = new NormalNode();
258                 norm->direction = get_node_output_vector(b_node, "Normal");
259                 node = norm;
260         }
261         else if (b_node.is_a(&RNA_ShaderNodeMapping)) {
262                 BL::ShaderNodeMapping b_mapping_node(b_node);
263                 MappingNode *mapping = new MappingNode();
264                 
265                 get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
266                 
267                 node = mapping;
268         }
269         /* new nodes */
270         else if (b_node.is_a(&RNA_ShaderNodeOutputMaterial)
271               || b_node.is_a(&RNA_ShaderNodeOutputWorld)
272               || b_node.is_a(&RNA_ShaderNodeOutputLamp)) {
273                 node = graph->output();
274         }
275         else if (b_node.is_a(&RNA_ShaderNodeFresnel)) {
276                 node = new FresnelNode();
277         }
278         else if (b_node.is_a(&RNA_ShaderNodeLayerWeight)) {
279                 node = new LayerWeightNode();
280         }
281         else if (b_node.is_a(&RNA_ShaderNodeAddShader)) {
282                 node = new AddClosureNode();
283         }
284         else if (b_node.is_a(&RNA_ShaderNodeMixShader)) {
285                 node = new MixClosureNode();
286         }
287         else if (b_node.is_a(&RNA_ShaderNodeAttribute)) {
288                 BL::ShaderNodeAttribute b_attr_node(b_node);
289                 AttributeNode *attr = new AttributeNode();
290                 attr->attribute = b_attr_node.attribute_name();
291                 node = attr;
292         }
293         else if (b_node.is_a(&RNA_ShaderNodeBackground)) {
294                 node = new BackgroundNode();
295         }
296         else if (b_node.is_a(&RNA_ShaderNodeHoldout)) {
297                 node = new HoldoutNode();
298         }
299         else if (b_node.is_a(&RNA_ShaderNodeBsdfAnisotropic)) {
300                 node = new WardBsdfNode();
301         }
302         else if (b_node.is_a(&RNA_ShaderNodeBsdfDiffuse)) {
303                 node = new DiffuseBsdfNode();
304         }
305         else if (b_node.is_a(&RNA_ShaderNodeSubsurfaceScattering)) {
306                 node = new SubsurfaceScatteringNode();
307         }
308         else if (b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) {
309                 BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
310                 GlossyBsdfNode *glossy = new GlossyBsdfNode();
311                 
312                 switch(b_glossy_node.distribution()) {
313                 case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
314                         glossy->distribution = ustring("Sharp");
315                         break;
316                 case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
317                         glossy->distribution = ustring("Beckmann");
318                         break;
319                 case BL::ShaderNodeBsdfGlossy::distribution_GGX:
320                         glossy->distribution = ustring("GGX");
321                         break;
322                 }
323                 node = glossy;
324         }
325         else if (b_node.is_a(&RNA_ShaderNodeBsdfGlass)) {
326                 BL::ShaderNodeBsdfGlass b_glass_node(b_node);
327                 GlassBsdfNode *glass = new GlassBsdfNode();
328                 switch(b_glass_node.distribution()) {
329                 case BL::ShaderNodeBsdfGlass::distribution_SHARP:
330                         glass->distribution = ustring("Sharp");
331                         break;
332                 case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
333                         glass->distribution = ustring("Beckmann");
334                         break;
335                 case BL::ShaderNodeBsdfGlass::distribution_GGX:
336                         glass->distribution = ustring("GGX");
337                         break;
338                 }
339                 node = glass;
340         }
341         else if (b_node.is_a(&RNA_ShaderNodeBsdfRefraction)) {
342                 BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
343                 RefractionBsdfNode *refraction = new RefractionBsdfNode();
344                 switch(b_refraction_node.distribution()) {
345                         case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
346                                 refraction->distribution = ustring("Sharp");
347                                 break;
348                         case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
349                                 refraction->distribution = ustring("Beckmann");
350                                 break;
351                         case BL::ShaderNodeBsdfRefraction::distribution_GGX:
352                                 refraction->distribution = ustring("GGX");
353                                 break;
354                 }
355                 node = refraction;
356         }
357         else if (b_node.is_a(&RNA_ShaderNodeBsdfToon)) {
358                 BL::ShaderNodeBsdfToon b_toon_node(b_node);
359                 ToonBsdfNode *toon = new ToonBsdfNode();
360                 switch(b_toon_node.component()) {
361                         case BL::ShaderNodeBsdfToon::component_DIFFUSE:
362                                 toon->component = ustring("Diffuse");
363                                 break;
364                         case BL::ShaderNodeBsdfToon::component_GLOSSY:
365                                 toon->component = ustring("Glossy");
366                                 break;
367                 }
368                 node = toon;
369         }
370         else if (b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
371                 node = new TranslucentBsdfNode();
372         }
373         else if (b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
374                 node = new TransparentBsdfNode();
375         }
376         else if (b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
377                 node = new VelvetBsdfNode();
378         }
379         else if (b_node.is_a(&RNA_ShaderNodeEmission)) {
380                 node = new EmissionNode();
381         }
382         else if (b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
383                 node = new AmbientOcclusionNode();
384         }
385         else if (b_node.is_a(&RNA_ShaderNodeVolumeIsotropic)) {
386                 node = new IsotropicVolumeNode();
387         }
388         else if (b_node.is_a(&RNA_ShaderNodeVolumeTransparent)) {
389                 node = new TransparentVolumeNode();
390         }
391         else if (b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
392                 node = new GeometryNode();
393         }
394         else if (b_node.is_a(&RNA_ShaderNodeWireframe)) {
395                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
396                 WireframeNode *wire = new WireframeNode();
397                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
398                 node = wire;
399         }
400         else if (b_node.is_a(&RNA_ShaderNodeWavelength)) {
401                 node = new WavelengthNode();
402         }
403         else if (b_node.is_a(&RNA_ShaderNodeBlackbody)) {
404                 node = new BlackbodyNode();
405         }
406         else if (b_node.is_a(&RNA_ShaderNodeLightPath)) {
407                 node = new LightPathNode();
408         }
409         else if (b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
410                 node = new LightFalloffNode();
411         }
412         else if (b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
413                 node = new ObjectInfoNode();
414         }
415         else if (b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
416                 node = new ParticleInfoNode();
417         }
418         else if (b_node.is_a(&RNA_ShaderNodeHairInfo)) {
419                 node = new HairInfoNode();
420         }
421         else if (b_node.is_a(&RNA_ShaderNodeBump)) {
422                 BL::ShaderNodeBump b_bump_node(b_node);
423                 BumpNode *bump = new BumpNode();
424                 bump->invert = b_bump_node.invert();
425                 node = bump;
426         }
427         else if (b_node.is_a(&RNA_ShaderNodeScript)) {
428 #ifdef WITH_OSL
429                 if(scene->shader_manager->use_osl()) {
430                         /* create script node */
431                         BL::ShaderNodeScript b_script_node(b_node);
432                         OSLScriptNode *script_node = new OSLScriptNode();
433                         
434                         /* Generate inputs/outputs from node sockets
435                          *
436                          * Note: the node sockets are generated from OSL parameters,
437                          * so the names match those of the corresponding parameters exactly.
438                          *
439                          * Note 2: ShaderInput/ShaderOutput store shallow string copies only!
440                          * Socket names must be stored in the extra lists instead. */
441                         BL::Node::inputs_iterator b_input;
442                         
443                         for (b_script_node.inputs.begin(b_input); b_input != b_script_node.inputs.end(); ++b_input) {
444                                 script_node->input_names.push_back(ustring(b_input->name()));
445                                 ShaderInput *input = script_node->add_input(script_node->input_names.back().c_str(),
446                                                                             convert_socket_type(*b_input));
447                                 set_default_value(input, b_node, *b_input, b_data, b_ntree);
448                         }
449                         
450                         BL::Node::outputs_iterator b_output;
451                         
452                         for (b_script_node.outputs.begin(b_output); b_output != b_script_node.outputs.end(); ++b_output) {
453                                 script_node->output_names.push_back(ustring(b_output->name()));
454                                 script_node->add_output(script_node->output_names.back().c_str(),
455                                                         convert_socket_type(*b_output));
456                         }
457                         
458                         /* load bytecode or filepath */
459                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
460                         string bytecode_hash = b_script_node.bytecode_hash();
461                         
462                         if(!bytecode_hash.empty()) {
463                                 /* loaded bytecode if not already done */
464                                 if(!manager->shader_test_loaded(bytecode_hash))
465                                         manager->shader_load_bytecode(bytecode_hash, b_script_node.bytecode());
466                                 
467                                 script_node->bytecode_hash = bytecode_hash;
468                         }
469                         else {
470                                 /* set filepath */
471                                 script_node->filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
472                         }
473                         
474                         node = script_node;
475                 }
476 #endif
477         }
478         else if (b_node.is_a(&RNA_ShaderNodeTexImage)) {
479                 BL::ShaderNodeTexImage b_image_node(b_node);
480                 BL::Image b_image(b_image_node.image());
481                 ImageTextureNode *image = new ImageTextureNode();
482                 if(b_image) {
483                         /* builtin images will use callback-based reading because
484                          * they could only be loaded correct from blender side
485                          */
486                         bool is_builtin = b_image.packed_file() ||
487                                           b_image.source() == BL::Image::source_GENERATED ||
488                                           b_image.source() == BL::Image::source_MOVIE;
489
490                         if(is_builtin) {
491                                 /* for builtin images we're using image datablock name to find an image to
492                                  * read pixels from later
493                                  *
494                                  * also store frame number as well, so there's no differences in handling
495                                  * builtin names for packed images and movies
496                                  */
497                                 int scene_frame = b_scene.frame_current();
498                                 int image_frame = image_user_frame_number(b_image_node.image_user(), scene_frame);
499                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
500                                 image->builtin_data = b_image.ptr.data;
501                         }
502                         else {
503                                 image->filename = image_user_file_path(b_image_node.image_user(), b_image, b_scene.frame_current());
504                                 image->builtin_data = NULL;
505                         }
506
507                         image->animated = b_image_node.image_user().use_auto_refresh();
508                 }
509                 image->color_space = ImageTextureNode::color_space_enum[(int)b_image_node.color_space()];
510                 image->projection = ImageTextureNode::projection_enum[(int)b_image_node.projection()];
511                 image->projection_blend = b_image_node.projection_blend();
512                 get_tex_mapping(&image->tex_mapping, b_image_node.texture_mapping());
513                 node = image;
514         }
515         else if (b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
516                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
517                 BL::Image b_image(b_env_node.image());
518                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
519                 if(b_image) {
520                         bool is_builtin = b_image.packed_file() ||
521                                           b_image.source() == BL::Image::source_GENERATED ||
522                                           b_image.source() == BL::Image::source_MOVIE;
523
524                         if(is_builtin) {
525                                 int scene_frame = b_scene.frame_current();
526                                 int image_frame = image_user_frame_number(b_env_node.image_user(), scene_frame);
527                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
528                                 env->builtin_data = b_image.ptr.data;
529                         }
530                         else {
531                                 env->filename = image_user_file_path(b_env_node.image_user(), b_image, b_scene.frame_current());
532                                 env->animated = b_env_node.image_user().use_auto_refresh();
533                                 env->builtin_data = NULL;
534                         }
535                 }
536                 env->color_space = EnvironmentTextureNode::color_space_enum[(int)b_env_node.color_space()];
537                 env->projection = EnvironmentTextureNode::projection_enum[(int)b_env_node.projection()];
538                 get_tex_mapping(&env->tex_mapping, b_env_node.texture_mapping());
539                 node = env;
540         }
541         else if (b_node.is_a(&RNA_ShaderNodeTexGradient)) {
542                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
543                 GradientTextureNode *gradient = new GradientTextureNode();
544                 gradient->type = GradientTextureNode::type_enum[(int)b_gradient_node.gradient_type()];
545                 get_tex_mapping(&gradient->tex_mapping, b_gradient_node.texture_mapping());
546                 node = gradient;
547         }
548         else if (b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
549                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
550                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
551                 voronoi->coloring = VoronoiTextureNode::coloring_enum[(int)b_voronoi_node.coloring()];
552                 get_tex_mapping(&voronoi->tex_mapping, b_voronoi_node.texture_mapping());
553                 node = voronoi;
554         }
555         else if (b_node.is_a(&RNA_ShaderNodeTexMagic)) {
556                 BL::ShaderNodeTexMagic b_magic_node(b_node);
557                 MagicTextureNode *magic = new MagicTextureNode();
558                 magic->depth = b_magic_node.turbulence_depth();
559                 get_tex_mapping(&magic->tex_mapping, b_magic_node.texture_mapping());
560                 node = magic;
561         }
562         else if (b_node.is_a(&RNA_ShaderNodeTexWave)) {
563                 BL::ShaderNodeTexWave b_wave_node(b_node);
564                 WaveTextureNode *wave = new WaveTextureNode();
565                 wave->type = WaveTextureNode::type_enum[(int)b_wave_node.wave_type()];
566                 get_tex_mapping(&wave->tex_mapping, b_wave_node.texture_mapping());
567                 node = wave;
568         }
569         else if (b_node.is_a(&RNA_ShaderNodeTexChecker)) {
570                 BL::ShaderNodeTexChecker b_checker_node(b_node);
571                 CheckerTextureNode *checker = new CheckerTextureNode();
572                 get_tex_mapping(&checker->tex_mapping, b_checker_node.texture_mapping());
573                 node = checker;
574         }
575         else if (b_node.is_a(&RNA_ShaderNodeTexBrick)) {
576                 BL::ShaderNodeTexBrick b_brick_node(b_node);
577                 BrickTextureNode *brick = new BrickTextureNode();
578                 brick->offset = b_brick_node.offset();
579                 brick->offset_frequency = b_brick_node.offset_frequency();
580                 brick->squash = b_brick_node.squash();
581                 brick->squash_frequency = b_brick_node.squash_frequency();
582                 get_tex_mapping(&brick->tex_mapping, b_brick_node.texture_mapping());
583                 node = brick;
584         }
585         else if (b_node.is_a(&RNA_ShaderNodeTexNoise)) {
586                 BL::ShaderNodeTexNoise b_noise_node(b_node);
587                 NoiseTextureNode *noise = new NoiseTextureNode();
588                 get_tex_mapping(&noise->tex_mapping, b_noise_node.texture_mapping());
589                 node = noise;
590         }
591         else if (b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
592                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
593                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
594                 musgrave->type = MusgraveTextureNode::type_enum[(int)b_musgrave_node.musgrave_type()];
595                 get_tex_mapping(&musgrave->tex_mapping, b_musgrave_node.texture_mapping());
596                 node = musgrave;
597         }
598         else if (b_node.is_a(&RNA_ShaderNodeTexCoord)) {
599                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
600                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
601                 tex_coord->from_dupli = b_tex_coord_node.from_dupli();
602                 node = tex_coord;
603         }
604         else if (b_node.is_a(&RNA_ShaderNodeTexSky)) {
605                 BL::ShaderNodeTexSky b_sky_node(b_node);
606                 SkyTextureNode *sky = new SkyTextureNode();
607                 sky->sun_direction = get_float3(b_sky_node.sun_direction());
608                 sky->turbidity = b_sky_node.turbidity();
609                 get_tex_mapping(&sky->tex_mapping, b_sky_node.texture_mapping());
610                 node = sky;
611         }
612         else if (b_node.is_a(&RNA_ShaderNodeNormalMap)) {
613                 BL::ShaderNodeNormalMap b_normal_map_node(b_node);
614                 NormalMapNode *nmap = new NormalMapNode();
615                 nmap->space = NormalMapNode::space_enum[(int)b_normal_map_node.space()];
616                 nmap->attribute = b_normal_map_node.uv_map();
617                 node = nmap;
618         }
619         else if (b_node.is_a(&RNA_ShaderNodeTangent)) {
620                 BL::ShaderNodeTangent b_tangent_node(b_node);
621                 TangentNode *tangent = new TangentNode();
622                 tangent->direction_type = TangentNode::direction_type_enum[(int)b_tangent_node.direction_type()];
623                 tangent->axis = TangentNode::axis_enum[(int)b_tangent_node.axis()];
624                 tangent->attribute = b_tangent_node.uv_map();
625                 node = tangent;
626         }
627
628         if(node && node != graph->output())
629                 graph->add(node);
630
631         return node;
632 }
633
634 static ShaderInput *node_find_input_by_name(ShaderNode *node, BL::Node b_node, BL::NodeSocket b_socket)
635 {
636         BL::Node::inputs_iterator b_input;
637         string name = b_socket.name();
638         bool found = false;
639         int counter = 0, total = 0;
640         
641         for (b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
642                 if (b_input->name() == name) {
643                         if (!found)
644                                 counter++;
645                         total++;
646                 }
647
648                 if(b_input->ptr.data == b_socket.ptr.data)
649                         found = true;
650         }
651         
652         /* rename if needed */
653         if (name == "Shader")
654                 name = "Closure";
655         
656         if (total > 1)
657                 name = string_printf("%s%d", name.c_str(), counter);
658         
659         return node->input(name.c_str());
660 }
661
662 static ShaderOutput *node_find_output_by_name(ShaderNode *node, BL::Node b_node, BL::NodeSocket b_socket)
663 {
664         BL::Node::outputs_iterator b_output;
665         string name = b_socket.name();
666         bool found = false;
667         int counter = 0, total = 0;
668         
669         for (b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
670                 if (b_output->name() == name) {
671                         if (!found)
672                                 counter++;
673                         total++;
674                 }
675
676                 if(b_output->ptr.data == b_socket.ptr.data)
677                         found = true;
678         }
679         
680         /* rename if needed */
681         if (name == "Shader")
682                 name = "Closure";
683         
684         if (total > 1)
685                 name = string_printf("%s%d", name.c_str(), counter);
686         
687         return node->output(name.c_str());
688 }
689
690 static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree,
691                       const ProxyMap &proxy_input_map, const ProxyMap &proxy_output_map)
692 {
693         /* add nodes */
694         BL::ShaderNodeTree::nodes_iterator b_node;
695         PtrInputMap input_map;
696         PtrOutputMap output_map;
697         
698         BL::Node::inputs_iterator b_input;
699         BL::Node::outputs_iterator b_output;
700
701         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
702                 if (b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
703                         /* replace muted node with internal links */
704                         BL::Node::internal_links_iterator b_link;
705                         for (b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
706                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(b_link->to_socket()));
707                                 
708                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
709                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
710                                 
711                                 graph->add(proxy);
712                         }
713                 }
714                 else if (b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) {
715                         
716                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
717                         if (b_node->is_a(&RNA_ShaderNodeGroup))
718                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
719                         else
720                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
721                         ProxyMap group_proxy_input_map, group_proxy_output_map;
722                         
723                         /* Add a proxy node for each socket
724                          * Do this even if the node group has no internal tree,
725                          * so that links have something to connect to and assert won't fail.
726                          */
727                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
728                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(*b_input));
729                                 graph->add(proxy);
730                                 
731                                 /* register the proxy node for internal binding */
732                                 group_proxy_input_map[b_input->identifier()] = proxy;
733                                 
734                                 input_map[b_input->ptr.data] = proxy->inputs[0];
735                                 
736                                 set_default_value(proxy->inputs[0], *b_node, *b_input, b_data, b_ntree);
737                         }
738                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
739                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(*b_output));
740                                 graph->add(proxy);
741                                 
742                                 /* register the proxy node for internal binding */
743                                 group_proxy_output_map[b_output->identifier()] = proxy;
744                                 
745                                 output_map[b_output->ptr.data] = proxy->outputs[0];
746                         }
747                         
748                         if (b_group_ntree)
749                                 add_nodes(scene, b_data, b_scene, graph, b_group_ntree, group_proxy_input_map, group_proxy_output_map);
750                 }
751                 else if (b_node->is_a(&RNA_NodeGroupInput)) {
752                         /* map each socket to a proxy node */
753                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
754                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
755                                 if (proxy_it != proxy_input_map.end()) {
756                                         ProxyNode *proxy = proxy_it->second;
757                                         
758                                         output_map[b_output->ptr.data] = proxy->outputs[0];
759                                 }
760                         }
761                 }
762                 else if (b_node->is_a(&RNA_NodeGroupOutput)) {
763                         BL::NodeGroupOutput b_output_node(*b_node);
764                         /* only the active group output is used */
765                         if (b_output_node.is_active_output()) {
766                                 /* map each socket to a proxy node */
767                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
768                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
769                                         if (proxy_it != proxy_output_map.end()) {
770                                                 ProxyNode *proxy = proxy_it->second;
771                                                 
772                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
773                                                 
774                                                 set_default_value(proxy->inputs[0], *b_node, *b_input, b_data, b_ntree);
775                                         }
776                                 }
777                         }
778                 }
779                 else {
780                         ShaderNode *node = add_node(scene, b_data, b_scene, graph, b_ntree, BL::ShaderNode(*b_node));
781                         
782                         if(node) {
783                                 /* map node sockets for linking */
784                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
785                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
786                                         input_map[b_input->ptr.data] = input;
787                                         
788                                         set_default_value(input, *b_node, *b_input, b_data, b_ntree);
789                                 }
790                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
791                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
792                                         output_map[b_output->ptr.data] = output;
793                                 }
794                         }
795                 }
796         }
797
798         /* connect nodes */
799         BL::NodeTree::links_iterator b_link;
800
801         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
802                 /* get blender link data */
803                 BL::NodeSocket b_from_sock = b_link->from_socket();
804                 BL::NodeSocket b_to_sock = b_link->to_socket();
805
806                 ShaderOutput *output = 0;
807                 ShaderInput *input = 0;
808                 
809                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
810                 if (output_it != output_map.end())
811                         output = output_it->second;
812                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
813                 if (input_it != input_map.end())
814                         input = input_it->second;
815
816                 /* either node may be NULL when the node was not exported, typically
817                  * because the node type is not supported */
818                 if(output && input)
819                         graph->connect(output, input);
820         }
821 }
822
823 static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree)
824 {
825         static const ProxyMap empty_proxy_map;
826         add_nodes(scene, b_data, b_scene, graph, b_ntree, empty_proxy_map, empty_proxy_map);
827 }
828
829 /* Sync Materials */
830
831 void BlenderSync::sync_materials(bool update_all)
832 {
833         shader_map.set_default(scene->shaders[scene->default_surface]);
834
835         /* material loop */
836         BL::BlendData::materials_iterator b_mat;
837
838         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
839                 Shader *shader;
840                 
841                 /* test if we need to sync */
842                 if(shader_map.sync(&shader, *b_mat) || update_all) {
843                         ShaderGraph *graph = new ShaderGraph();
844
845                         shader->name = b_mat->name().c_str();
846                         shader->pass_id = b_mat->pass_index();
847
848                         /* create nodes */
849                         if(b_mat->use_nodes() && b_mat->node_tree()) {
850                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
851
852                                 add_nodes(scene, b_data, b_scene, graph, b_ntree);
853                         }
854                         else {
855                                 ShaderNode *closure, *out;
856
857                                 closure = graph->add(new DiffuseBsdfNode());
858                                 closure->input("Color")->value = get_float3(b_mat->diffuse_color());
859                                 out = graph->output();
860
861                                 graph->connect(closure->output("BSDF"), out->input("Surface"));
862                         }
863
864                         /* settings */
865                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
866                         shader->use_mis = get_boolean(cmat, "sample_as_light");
867                         shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
868                         shader->homogeneous_volume = get_boolean(cmat, "homogeneous_volume");
869
870                         shader->set_graph(graph);
871                         shader->tag_update(scene);
872                 }
873         }
874 }
875
876 /* Sync World */
877
878 void BlenderSync::sync_world(bool update_all)
879 {
880         Background *background = scene->background;
881         Background prevbackground = *background;
882
883         BL::World b_world = b_scene.world();
884
885         if(world_recalc || update_all || b_world.ptr.data != world_map) {
886                 Shader *shader = scene->shaders[scene->default_background];
887                 ShaderGraph *graph = new ShaderGraph();
888
889                 /* create nodes */
890                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
891                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
892
893                         add_nodes(scene, b_data, b_scene, graph, b_ntree);
894                 }
895                 else if(b_world) {
896                         ShaderNode *closure, *out;
897
898                         closure = graph->add(new BackgroundNode());
899                         closure->input("Color")->value = get_float3(b_world.horizon_color());
900                         out = graph->output();
901
902                         graph->connect(closure->output("Background"), out->input("Surface"));
903                 }
904
905                 if(b_world) {
906                         /* AO */
907                         BL::WorldLighting b_light = b_world.light_settings();
908
909                         if(b_light.use_ambient_occlusion())
910                                 background->ao_factor = b_light.ao_factor();
911                         else
912                                 background->ao_factor = 0.0f;
913
914                         background->ao_distance = b_light.distance();
915
916                         /* visibility */
917                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
918                         uint visibility = 0;
919
920                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
921                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
922                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
923                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
924
925                         background->visibility = visibility;
926                 }
927
928                 shader->set_graph(graph);
929                 shader->tag_update(scene);
930         }
931
932         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
933
934         /* when doing preview render check for BI's transparency settings,
935          * this is so because bledner's preview render routines are not able
936          * to tweak all cycles's settings depending on different circumstances
937          */
938         if(b_engine.is_preview() == false)
939                 background->transparent = get_boolean(cscene, "film_transparent");
940         else
941                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
942
943         background->use = render_layer.use_background;
944
945         if(background->modified(prevbackground))
946                 background->tag_update(scene);
947 }
948
949 /* Sync Lamps */
950
951 void BlenderSync::sync_lamps(bool update_all)
952 {
953         shader_map.set_default(scene->shaders[scene->default_light]);
954
955         /* lamp loop */
956         BL::BlendData::lamps_iterator b_lamp;
957
958         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
959                 Shader *shader;
960                 
961                 /* test if we need to sync */
962                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
963                         ShaderGraph *graph = new ShaderGraph();
964
965                         /* create nodes */
966                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
967                                 shader->name = b_lamp->name().c_str();
968
969                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
970
971                                 add_nodes(scene, b_data, b_scene, graph, b_ntree);
972                         }
973                         else {
974                                 ShaderNode *closure, *out;
975                                 float strength = 1.0f;
976
977                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
978                                    b_lamp->type() == BL::Lamp::type_SPOT ||
979                                    b_lamp->type() == BL::Lamp::type_AREA)
980                                 {
981                                         strength = 100.0f;
982                                 }
983
984                                 closure = graph->add(new EmissionNode());
985                                 closure->input("Color")->value = get_float3(b_lamp->color());
986                                 closure->input("Strength")->value.x = strength;
987                                 out = graph->output();
988
989                                 graph->connect(closure->output("Emission"), out->input("Surface"));
990                         }
991
992                         shader->set_graph(graph);
993                         shader->tag_update(scene);
994                 }
995         }
996 }
997
998 void BlenderSync::sync_shaders()
999 {
1000         /* for auto refresh images */
1001         bool auto_refresh_update = false;
1002
1003         if(preview) {
1004                 ImageManager *image_manager = scene->image_manager;
1005                 int frame = b_scene.frame_current();
1006                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1007         }
1008
1009         shader_map.pre_sync();
1010
1011         sync_world(auto_refresh_update);
1012         sync_lamps(auto_refresh_update);
1013         sync_materials(auto_refresh_update);
1014
1015         /* false = don't delete unused shaders, not supported */
1016         shader_map.post_sync(false);
1017 }
1018
1019 CCL_NAMESPACE_END
1020