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