63cf719d010ccc7ef4b0b13faebfc606f8d6a2f2
[blender-staging.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*, ShaderNode*> PtrNodeMap;
35 typedef pair<ShaderNode*, std::string> SocketPair;
36 typedef map<void*, SocketPair> PtrSockMap;
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::NodeSocketRGBA sock(get_node_output(b_node, name));
71         return get_float3(sock.default_value());
72 }
73
74 static float get_node_output_value(BL::Node b_node, const string& name)
75 {
76         BL::NodeSocketFloatNone sock(get_node_output(b_node, name));
77         return sock.default_value();
78 }
79
80 static ShaderSocketType convert_socket_type(BL::NodeSocket::type_enum b_type)
81 {
82         switch (b_type) {
83         case BL::NodeSocket::type_VALUE:
84                 return SHADER_SOCKET_FLOAT;
85         case BL::NodeSocket::type_INT:
86                 return SHADER_SOCKET_INT;
87         case BL::NodeSocket::type_VECTOR:
88                 return SHADER_SOCKET_VECTOR;
89         case BL::NodeSocket::type_RGBA:
90                 return SHADER_SOCKET_COLOR;
91         case BL::NodeSocket::type_SHADER:
92                 return SHADER_SOCKET_CLOSURE;
93         case BL::NodeSocket::type_STRING:
94                 return SHADER_SOCKET_STRING;
95         
96         case BL::NodeSocket::type_BOOLEAN:
97         case BL::NodeSocket::type_MESH:
98         default:
99                 return SHADER_SOCKET_FLOAT;
100         }
101 }
102
103 static void set_default_value(ShaderInput *input, BL::NodeSocket sock, BL::BlendData b_data, BL::ID b_id)
104 {
105         /* copy values for non linked inputs */
106         switch(input->type) {
107         case SHADER_SOCKET_FLOAT: {
108                 BL::NodeSocketFloatNone value_sock(sock);
109                 input->set(value_sock.default_value());
110                 break;
111         }
112         case SHADER_SOCKET_INT: {
113                 BL::NodeSocketIntNone value_sock(sock);
114                 input->set((float)value_sock.default_value());
115                 break;
116         }
117         case SHADER_SOCKET_COLOR: {
118                 BL::NodeSocketRGBA rgba_sock(sock);
119                 input->set(get_float3(rgba_sock.default_value()));
120                 break;
121         }
122         case SHADER_SOCKET_NORMAL:
123         case SHADER_SOCKET_POINT:
124         case SHADER_SOCKET_VECTOR: {
125                 BL::NodeSocketVectorNone vec_sock(sock);
126                 input->set(get_float3(vec_sock.default_value()));
127                 break;
128         }
129         case SHADER_SOCKET_STRING: {
130                 BL::NodeSocketStringNone string_sock(sock);
131                 input->set((ustring)blender_absolute_path(b_data, b_id, string_sock.default_value()));
132                 break;
133         }
134         case SHADER_SOCKET_CLOSURE:
135                 break;
136         }
137 }
138
139 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping b_mapping)
140 {
141         if(!b_mapping)
142                 return;
143
144         mapping->translation = get_float3(b_mapping.translation());
145         mapping->rotation = get_float3(b_mapping.rotation());
146         mapping->scale = get_float3(b_mapping.scale());
147
148         mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
149         mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
150         mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
151 }
152
153 static void get_tex_mapping(TextureMapping *mapping, BL::ShaderNodeMapping b_mapping)
154 {
155         if(!b_mapping)
156                 return;
157
158         mapping->translation = get_float3(b_mapping.translation());
159         mapping->rotation = get_float3(b_mapping.rotation());
160         mapping->scale = get_float3(b_mapping.scale());
161
162         mapping->use_minmax = b_mapping.use_min() || b_mapping.use_max();
163
164         if(b_mapping.use_min())
165                 mapping->min = get_float3(b_mapping.min());
166         if(b_mapping.use_max())
167                 mapping->max = get_float3(b_mapping.max());
168 }
169
170 static ShaderNode *add_node(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, BL::ShaderNode b_node)
171 {
172         ShaderNode *node = NULL;
173
174         switch(b_node.type()) {
175                 /* not supported */
176                 case BL::ShaderNode::type_CURVE_VEC: break;
177                 case BL::ShaderNode::type_GEOMETRY: break;
178                 case BL::ShaderNode::type_MATERIAL: break;
179                 case BL::ShaderNode::type_MATERIAL_EXT: break;
180                 case BL::ShaderNode::type_OUTPUT: break;
181                 case BL::ShaderNode::type_SQUEEZE: break;
182                 case BL::ShaderNode::type_TEXTURE: break;
183                 case BL::ShaderNode::type_FRAME: break;
184                 /* handled outside this function */
185                 case BL::ShaderNode::type_GROUP: break;
186                 /* existing blender nodes */
187                 case BL::ShaderNode::type_REROUTE: {
188                         BL::Node::inputs_iterator b_input;
189                         b_node.inputs.begin(b_input);
190                         BL::Node::outputs_iterator b_output;
191                         b_node.outputs.begin(b_output);
192                         ProxyNode *proxy = new ProxyNode(convert_socket_type(b_input->type()), convert_socket_type(b_output->type()));
193                         node = proxy;
194                         break;
195                 }
196                 case BL::ShaderNode::type_CURVE_RGB: {
197                         RGBCurvesNode *ramp = new RGBCurvesNode();
198                         node = ramp;
199                         break;
200                 }
201                 case BL::ShaderNode::type_VALTORGB: {
202                         RGBRampNode *ramp = new RGBRampNode();
203                         BL::ShaderNodeValToRGB b_ramp_node(b_node);
204                         colorramp_to_array(b_ramp_node.color_ramp(), ramp->ramp, RAMP_TABLE_SIZE);
205                         node = ramp;
206                         break;
207                 }
208                 case BL::ShaderNode::type_RGB: {
209                         ColorNode *color = new ColorNode();
210                         color->value = get_node_output_rgba(b_node, "Color");
211                         node = color;
212                         break;
213                 }
214                 case BL::ShaderNode::type_VALUE: {
215                         ValueNode *value = new ValueNode();
216                         value->value = get_node_output_value(b_node, "Value");
217                         node = value;
218                         break;
219                 }
220                 case BL::ShaderNode::type_CAMERA: {
221                         node = new CameraNode();
222                         break;
223                 }
224                 case BL::ShaderNode::type_INVERT: {
225                         node = new InvertNode();
226                         break;
227                 }
228                 case BL::ShaderNode::type_GAMMA: {
229                         node = new GammaNode();
230                         break;
231                 }
232                 case BL::ShaderNode::type_BRIGHTCONTRAST: {
233                         node = new BrightContrastNode();
234                         break;
235                 }
236                 case BL::ShaderNode::type_MIX_RGB: {
237                         BL::ShaderNodeMixRGB b_mix_node(b_node);
238                         MixNode *mix = new MixNode();
239                         mix->type = MixNode::type_enum[b_mix_node.blend_type()];
240                         mix->use_clamp = b_mix_node.use_clamp();
241                         node = mix;
242                         break;
243                 }
244                 case BL::ShaderNode::type_SEPRGB: {
245                         node = new SeparateRGBNode();
246                         break;
247                 }
248                 case BL::ShaderNode::type_COMBRGB: {
249                         node = new CombineRGBNode();
250                         break;
251                 }
252                 case BL::ShaderNode::type_HUE_SAT: {
253                         node = new HSVNode();
254                         break;
255                 }
256                 case BL::ShaderNode::type_RGBTOBW: {
257                         node = new ConvertNode(SHADER_SOCKET_COLOR, SHADER_SOCKET_FLOAT);
258                         break;
259                 }
260                 case BL::ShaderNode::type_MATH: {
261                         BL::ShaderNodeMath b_math_node(b_node);
262                         MathNode *math = new MathNode();
263                         math->type = MathNode::type_enum[b_math_node.operation()];
264                         math->use_clamp = b_math_node.use_clamp();
265                         node = math;
266                         break;
267                 }
268                 case BL::ShaderNode::type_VECT_MATH: {
269                         BL::ShaderNodeVectorMath b_vector_math_node(b_node);
270                         VectorMathNode *vmath = new VectorMathNode();
271                         vmath->type = VectorMathNode::type_enum[b_vector_math_node.operation()];
272                         node = vmath;
273                         break;
274                 }
275                 case BL::ShaderNode::type_NORMAL: {
276                         BL::Node::outputs_iterator out_it;
277                         b_node.outputs.begin(out_it);
278                         BL::NodeSocketVectorNone vec_sock(*out_it);
279
280                         NormalNode *norm = new NormalNode();
281                         norm->direction = get_float3(vec_sock.default_value());
282
283                         node = norm;
284                         break;
285                 }
286                 case BL::ShaderNode::type_MAPPING: {
287                         BL::ShaderNodeMapping b_mapping_node(b_node);
288                         MappingNode *mapping = new MappingNode();
289
290                         get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
291
292                         node = mapping;
293                         break;
294                 }
295
296                 /* new nodes */
297                 case BL::ShaderNode::type_OUTPUT_MATERIAL:
298                 case BL::ShaderNode::type_OUTPUT_WORLD:
299                 case BL::ShaderNode::type_OUTPUT_LAMP: {
300                         node = graph->output();
301                         break;
302                 }
303                 case BL::ShaderNode::type_FRESNEL: {
304                         node = new FresnelNode();
305                         break;
306                 }
307                 case BL::ShaderNode::type_LAYER_WEIGHT: {
308                         node = new LayerWeightNode();
309                         break;
310                 }
311                 case BL::ShaderNode::type_ADD_SHADER: {
312                         node = new AddClosureNode();
313                         break;
314                 }
315                 case BL::ShaderNode::type_MIX_SHADER: {
316                         node = new MixClosureNode();
317                         break;
318                 }
319                 case BL::ShaderNode::type_ATTRIBUTE: {
320                         BL::ShaderNodeAttribute b_attr_node(b_node);
321                         AttributeNode *attr = new AttributeNode();
322                         attr->attribute = b_attr_node.attribute_name();
323                         node = attr;
324                         break;
325                 }
326                 case BL::ShaderNode::type_BACKGROUND: {
327                         node = new BackgroundNode();
328                         break;
329                 }
330                 case BL::ShaderNode::type_HOLDOUT: {
331                         node = new HoldoutNode();
332                         break;
333                 }
334                 case BL::ShaderNode::type_BSDF_ANISOTROPIC: {
335                         node = new WardBsdfNode();
336                         break;
337                 }
338                 case BL::ShaderNode::type_BSDF_DIFFUSE: {
339                         node = new DiffuseBsdfNode();
340                         break;
341                 }
342                 case BL::ShaderNode::type_BSDF_GLOSSY: {
343                         BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
344                         GlossyBsdfNode *glossy = new GlossyBsdfNode();
345
346                         switch(b_glossy_node.distribution()) {
347                                 case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
348                                         glossy->distribution = ustring("Sharp");
349                                         break;
350                                 case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
351                                         glossy->distribution = ustring("Beckmann");
352                                         break;
353                                 case BL::ShaderNodeBsdfGlossy::distribution_GGX:
354                                         glossy->distribution = ustring("GGX");
355                                         break;
356                         }
357                         node = glossy;
358                         break;
359                 }
360                 case BL::ShaderNode::type_BSDF_GLASS: {
361                         BL::ShaderNodeBsdfGlass b_glass_node(b_node);
362                         GlassBsdfNode *glass = new GlassBsdfNode();
363                         switch(b_glass_node.distribution()) {
364                                 case BL::ShaderNodeBsdfGlass::distribution_SHARP:
365                                         glass->distribution = ustring("Sharp");
366                                         break;
367                                 case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
368                                         glass->distribution = ustring("Beckmann");
369                                         break;
370                                 case BL::ShaderNodeBsdfGlass::distribution_GGX:
371                                         glass->distribution = ustring("GGX");
372                                         break;
373                         }
374                         node = glass;
375                         break;
376                 }
377                 case BL::ShaderNode::type_BSDF_REFRACTION: {
378                         BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
379                         RefractionBsdfNode *refraction = new RefractionBsdfNode();
380                         switch(b_refraction_node.distribution()) {
381                                 case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
382                                         refraction->distribution = ustring("Sharp");
383                                         break;
384                                 case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
385                                         refraction->distribution = ustring("Beckmann");
386                                         break;
387                                 case BL::ShaderNodeBsdfRefraction::distribution_GGX:
388                                         refraction->distribution = ustring("GGX");
389                                         break;
390                         }
391                         node = refraction;
392                         break;
393                 }
394                 case BL::ShaderNode::type_BSDF_TRANSLUCENT: {
395                         node = new TranslucentBsdfNode();
396                         break;
397                 }
398                 case BL::ShaderNode::type_BSDF_TRANSPARENT: {
399                         node = new TransparentBsdfNode();
400                         break;
401                 }
402                 case BL::ShaderNode::type_BSDF_VELVET: {
403                         node = new VelvetBsdfNode();
404                         break;
405                 }
406                 case BL::ShaderNode::type_EMISSION: {
407                         node = new EmissionNode();
408                         break;
409                 }
410                 case BL::ShaderNode::type_AMBIENT_OCCLUSION: {
411                         node = new AmbientOcclusionNode();
412                         break;
413                 }
414                 case BL::ShaderNode::type_VOLUME_ISOTROPIC: {
415                         node = new IsotropicVolumeNode();
416                         break;
417                 }
418                 case BL::ShaderNode::type_VOLUME_TRANSPARENT: {
419                         node = new TransparentVolumeNode();
420                         break;
421                 }
422                 case BL::ShaderNode::type_NEW_GEOMETRY: {
423                         node = new GeometryNode();
424                         break;
425                 }
426                 case BL::ShaderNode::type_LIGHT_PATH: {
427                         node = new LightPathNode();
428                         break;
429                 }
430                 case BL::ShaderNode::type_LIGHT_FALLOFF: {
431                         node = new LightFalloffNode();
432                         break;
433                 }
434                 case BL::ShaderNode::type_OBJECT_INFO: {
435                         node = new ObjectInfoNode();
436                         break;
437                 }
438                 case BL::ShaderNode::type_PARTICLE_INFO: {
439                         node = new ParticleInfoNode();
440                         break;
441                 }
442                 case BL::ShaderNode::type_BUMP: {
443                         node = new BumpNode();
444                         break;
445                 }
446                 case BL::ShaderNode::type_SCRIPT: {
447 #ifdef WITH_OSL
448                         if(scene->params.shadingsystem != SceneParams::OSL)
449                                 break;
450
451                         /* create script node */
452                         BL::ShaderNodeScript b_script_node(b_node);
453                         OSLScriptNode *script_node = new OSLScriptNode();
454                         
455                         /* Generate inputs/outputs from node sockets
456                          *
457                          * Note: the node sockets are generated from OSL parameters,
458                          * so the names match those of the corresponding parameters exactly.
459                          *
460                          * Note 2: ShaderInput/ShaderOutput store shallow string copies only!
461                          * Socket names must be stored in the extra lists instead. */
462                         BL::Node::inputs_iterator b_input;
463
464                         for (b_script_node.inputs.begin(b_input); b_input != b_script_node.inputs.end(); ++b_input) {
465                                 script_node->input_names.push_back(ustring(b_input->name()));
466                                 ShaderInput *input = script_node->add_input(script_node->input_names.back().c_str(), convert_socket_type(b_input->type()));
467                                 set_default_value(input, *b_input, b_data, b_ntree);
468                         }
469
470                         BL::Node::outputs_iterator b_output;
471
472                         for (b_script_node.outputs.begin(b_output); b_output != b_script_node.outputs.end(); ++b_output) {
473                                 script_node->output_names.push_back(ustring(b_output->name()));
474                                 script_node->add_output(script_node->output_names.back().c_str(), convert_socket_type(b_output->type()));
475                         }
476
477                         /* load bytecode or filepath */
478                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
479                         string bytecode_hash = b_script_node.bytecode_hash();
480
481                         if(!bytecode_hash.empty()) {
482                                 /* loaded bytecode if not already done */
483                                 if(!manager->shader_test_loaded(bytecode_hash))
484                                         manager->shader_load_bytecode(bytecode_hash, b_script_node.bytecode());
485
486                                 script_node->bytecode_hash = bytecode_hash;
487                         }
488                         else {
489                                 /* set filepath */
490                                 script_node->filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
491                         }
492                         
493                         node = script_node;
494 #endif
495
496                         break;
497                 }
498                 case BL::ShaderNode::type_TEX_IMAGE: {
499                         BL::ShaderNodeTexImage b_image_node(b_node);
500                         BL::Image b_image(b_image_node.image());
501                         ImageTextureNode *image = new ImageTextureNode();
502                         /* todo: handle generated/builtin images */
503                         if(b_image && b_image.source() != BL::Image::source_MOVIE)
504                                 image->filename = image_user_file_path(b_image_node.image_user(), b_image, b_scene.frame_current());
505                         image->color_space = ImageTextureNode::color_space_enum[(int)b_image_node.color_space()];
506                         image->projection = ImageTextureNode::projection_enum[(int)b_image_node.projection()];
507                         image->projection_blend = b_image_node.projection_blend();
508                         get_tex_mapping(&image->tex_mapping, b_image_node.texture_mapping());
509                         node = image;
510                         break;
511                 }
512                 case BL::ShaderNode::type_TEX_ENVIRONMENT: {
513                         BL::ShaderNodeTexEnvironment b_env_node(b_node);
514                         BL::Image b_image(b_env_node.image());
515                         EnvironmentTextureNode *env = new EnvironmentTextureNode();
516                         if(b_image && b_image.source() != BL::Image::source_MOVIE)
517                                 env->filename = image_user_file_path(b_env_node.image_user(), b_image, b_scene.frame_current());
518                         env->color_space = EnvironmentTextureNode::color_space_enum[(int)b_env_node.color_space()];
519                         env->projection = EnvironmentTextureNode::projection_enum[(int)b_env_node.projection()];
520                         get_tex_mapping(&env->tex_mapping, b_env_node.texture_mapping());
521                         node = env;
522                         break;
523                 }
524                 case BL::ShaderNode::type_TEX_GRADIENT: {
525                         BL::ShaderNodeTexGradient b_gradient_node(b_node);
526                         GradientTextureNode *gradient = new GradientTextureNode();
527                         gradient->type = GradientTextureNode::type_enum[(int)b_gradient_node.gradient_type()];
528                         get_tex_mapping(&gradient->tex_mapping, b_gradient_node.texture_mapping());
529                         node = gradient;
530                         break;
531                 }
532                 case BL::ShaderNode::type_TEX_VORONOI: {
533                         BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
534                         VoronoiTextureNode *voronoi = new VoronoiTextureNode();
535                         voronoi->coloring = VoronoiTextureNode::coloring_enum[(int)b_voronoi_node.coloring()];
536                         get_tex_mapping(&voronoi->tex_mapping, b_voronoi_node.texture_mapping());
537                         node = voronoi;
538                         break;
539                 }
540                 case BL::ShaderNode::type_TEX_MAGIC: {
541                         BL::ShaderNodeTexMagic b_magic_node(b_node);
542                         MagicTextureNode *magic = new MagicTextureNode();
543                         magic->depth = b_magic_node.turbulence_depth();
544                         get_tex_mapping(&magic->tex_mapping, b_magic_node.texture_mapping());
545                         node = magic;
546                         break;
547                 }
548                 case BL::ShaderNode::type_TEX_WAVE: {
549                         BL::ShaderNodeTexWave b_wave_node(b_node);
550                         WaveTextureNode *wave = new WaveTextureNode();
551                         wave->type = WaveTextureNode::type_enum[(int)b_wave_node.wave_type()];
552                         get_tex_mapping(&wave->tex_mapping, b_wave_node.texture_mapping());
553                         node = wave;
554                         break;
555                 }
556                 case BL::ShaderNode::type_TEX_CHECKER: {
557                         BL::ShaderNodeTexChecker b_checker_node(b_node);
558                         CheckerTextureNode *checker = new CheckerTextureNode();
559                         get_tex_mapping(&checker->tex_mapping, b_checker_node.texture_mapping());
560                         node = checker;
561                         break;
562                 }
563                 case BL::ShaderNode::type_TEX_BRICK: {
564                         BL::ShaderNodeTexBrick b_brick_node(b_node);
565                         BrickTextureNode *brick = new BrickTextureNode();
566                         brick->offset = b_brick_node.offset();
567                         brick->offset_frequency = b_brick_node.offset_frequency();
568                         brick->squash = b_brick_node.squash();
569                         brick->squash_frequency = b_brick_node.squash_frequency();
570                         get_tex_mapping(&brick->tex_mapping, b_brick_node.texture_mapping());
571                         node = brick;
572                         break;
573                 }
574                 case BL::ShaderNode::type_TEX_NOISE: {
575                         BL::ShaderNodeTexNoise b_noise_node(b_node);
576                         NoiseTextureNode *noise = new NoiseTextureNode();
577                         get_tex_mapping(&noise->tex_mapping, b_noise_node.texture_mapping());
578                         node = noise;
579                         break;
580                 }
581                 case BL::ShaderNode::type_TEX_MUSGRAVE: {
582                         BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
583                         MusgraveTextureNode *musgrave = new MusgraveTextureNode();
584                         musgrave->type = MusgraveTextureNode::type_enum[(int)b_musgrave_node.musgrave_type()];
585                         get_tex_mapping(&musgrave->tex_mapping, b_musgrave_node.texture_mapping());
586                         node = musgrave;
587                         break;
588                 }
589                 case BL::ShaderNode::type_TEX_COORD: {
590                         BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
591                         TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
592                         tex_coord->from_dupli = b_tex_coord_node.from_dupli();
593                         node = tex_coord;
594                         break;
595                 }
596                 case BL::ShaderNode::type_TEX_SKY: {
597                         BL::ShaderNodeTexSky b_sky_node(b_node);
598                         SkyTextureNode *sky = new SkyTextureNode();
599                         sky->sun_direction = get_float3(b_sky_node.sun_direction());
600                         sky->turbidity = b_sky_node.turbidity();
601                         get_tex_mapping(&sky->tex_mapping, b_sky_node.texture_mapping());
602                         node = sky;
603                         break;
604                 }
605                 case BL::ShaderNode::type_NORMAL_MAP: {
606                         BL::ShaderNodeNormalMap b_normal_map_node(b_node);
607                         NormalMapNode *nmap = new NormalMapNode();
608                         nmap->space = NormalMapNode::space_enum[(int)b_normal_map_node.space()];
609                         nmap->attribute = b_normal_map_node.uv_map();
610                         node = nmap;
611                         break;
612                 }
613                 case BL::ShaderNode::type_TANGENT: {
614                         BL::ShaderNodeTangent b_tangent_node(b_node);
615                         TangentNode *tangent = new TangentNode();
616                         tangent->direction_type = TangentNode::direction_type_enum[(int)b_tangent_node.direction_type()];
617                         tangent->axis = TangentNode::axis_enum[(int)b_tangent_node.axis()];
618                         tangent->attribute = b_tangent_node.uv_map();
619                         node = tangent;
620                         break;
621                 }
622         }
623
624         if(node && node != graph->output())
625                 graph->add(node);
626
627         return node;
628 }
629
630 static SocketPair node_socket_map_pair(PtrNodeMap& node_map, BL::Node b_node, BL::NodeSocket b_socket)
631 {
632         BL::Node::inputs_iterator b_input;
633         BL::Node::outputs_iterator b_output;
634         string name = b_socket.name();
635         bool found = false;
636         int counter = 0, total = 0;
637
638         /* find in inputs */
639         for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
640                 if(b_input->name() == name) {
641                         if(!found)
642                                 counter++;
643                         total++;
644                 }
645
646                 if(b_input->ptr.data == b_socket.ptr.data)
647                         found = true;
648         }
649
650         if(!found) {
651                 /* find in outputs */
652                 found = false;
653                 counter = 0;
654                 total = 0;
655
656                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
657                         if(b_output->name() == name) {
658                                 if(!found)
659                                         counter++;
660                                 total++;
661                         }
662
663                         if(b_output->ptr.data == b_socket.ptr.data)
664                                 found = true;
665                 }
666         }
667
668         /* rename if needed */
669         if(name == "Shader")
670                 name = "Closure";
671
672         if(total > 1)
673                 name = string_printf("%s%d", name.c_str(), counter);
674
675         return SocketPair(node_map[b_node.ptr.data], name);
676 }
677
678 static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, PtrSockMap& sockets_map)
679 {
680         /* add nodes */
681         BL::ShaderNodeTree::nodes_iterator b_node;
682         PtrNodeMap node_map;
683         PtrSockMap proxy_map;
684
685         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
686                 if(b_node->mute()) {
687                         BL::Node::inputs_iterator b_input;
688                         BL::Node::outputs_iterator b_output;
689                         bool found_match = false;
690
691                         /* this is slightly different than blender logic, we just connect a
692                          * single pair for of input/output, but works ok for the node we have */
693                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
694                                 if(b_input->is_linked()) {
695                                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
696                                                 if(b_output->is_linked() && b_input->type() == b_output->type()) {
697                                                         ProxyNode *proxy = new ProxyNode(convert_socket_type(b_input->type()), convert_socket_type(b_output->type()));
698                                                         graph->add(proxy);
699
700                                                         proxy_map[b_input->ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
701                                                         proxy_map[b_output->ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
702                                                         found_match = true;
703
704                                                         break;
705                                                 }
706                                         }
707                                 }
708
709                                 if(found_match)
710                                         break;
711                         }
712                 }
713                 else if(b_node->is_a(&RNA_NodeGroup)) {
714                         /* add proxy converter nodes for inputs and outputs */
715                         BL::NodeGroup b_gnode(*b_node);
716                         BL::ShaderNodeTree b_group_ntree(b_gnode.node_tree());
717                         if (!b_group_ntree)
718                                 continue;
719
720                         BL::Node::inputs_iterator b_input;
721                         BL::Node::outputs_iterator b_output;
722                         
723                         PtrSockMap group_sockmap;
724                         
725                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
726                                 ShaderSocketType extern_type = convert_socket_type(b_input->type());
727                                 ShaderSocketType intern_type = convert_socket_type(b_input->group_socket().type());
728                                 ShaderNode *proxy = graph->add(new ProxyNode(extern_type, intern_type));
729                                 
730                                 /* map the external node socket to the proxy node socket */
731                                 proxy_map[b_input->ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
732                                 /* map the internal group socket to the proxy node socket */
733                                 group_sockmap[b_input->group_socket().ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
734                                 
735                                 /* default input values of the group node */
736                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_group_ntree);
737                         }
738                         
739                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
740                                 ShaderSocketType extern_type = convert_socket_type(b_output->type());
741                                 ShaderSocketType intern_type = convert_socket_type(b_output->group_socket().type());
742                                 ShaderNode *proxy = graph->add(new ProxyNode(intern_type, extern_type));
743                                 
744                                 /* map the external node socket to the proxy node socket */
745                                 proxy_map[b_output->ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
746                                 /* map the internal group socket to the proxy node socket */
747                                 group_sockmap[b_output->group_socket().ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
748                                 
749                                 /* default input values of internal, unlinked group outputs */
750                                 set_default_value(proxy->inputs[0], b_output->group_socket(), b_data, b_group_ntree);
751                         }
752                         
753                         add_nodes(scene, b_data, b_scene, graph, b_group_ntree, group_sockmap);
754                 }
755                 else {
756                         ShaderNode *node = add_node(scene, b_data, b_scene, graph, b_ntree, BL::ShaderNode(*b_node));
757                         
758                         if(node) {
759                                 BL::Node::inputs_iterator b_input;
760                                 
761                                 node_map[b_node->ptr.data] = node;
762                                 
763                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
764                                         SocketPair pair = node_socket_map_pair(node_map, *b_node, *b_input);
765                                         ShaderInput *input = pair.first->input(pair.second.c_str());
766                                         
767                                         assert(input);
768                                         
769                                         /* copy values for non linked inputs */
770                                         set_default_value(input, *b_input, b_data, b_ntree);
771                                 }
772                         }
773                 }
774         }
775
776         /* connect nodes */
777         BL::NodeTree::links_iterator b_link;
778
779         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
780                 /* get blender link data */
781                 BL::Node b_from_node = b_link->from_node();
782                 BL::Node b_to_node = b_link->to_node();
783
784                 BL::NodeSocket b_from_sock = b_link->from_socket();
785                 BL::NodeSocket b_to_sock = b_link->to_socket();
786
787                 SocketPair from_pair, to_pair;
788
789                 /* links without a node pointer are connections to group inputs/outputs */
790
791                 /* from sock */
792                 if(b_from_node) {
793                         if (b_from_node.mute() || b_from_node.is_a(&RNA_NodeGroup))
794                                 from_pair = proxy_map[b_from_sock.ptr.data];
795                         else
796                                 from_pair = node_socket_map_pair(node_map, b_from_node, b_from_sock);
797                 }
798                 else
799                         from_pair = sockets_map[b_from_sock.ptr.data];
800
801                 /* to sock */
802                 if(b_to_node) {
803                         if (b_to_node.mute() || b_to_node.is_a(&RNA_NodeGroup))
804                                 to_pair = proxy_map[b_to_sock.ptr.data];
805                         else
806                                 to_pair = node_socket_map_pair(node_map, b_to_node, b_to_sock);
807                 }
808                 else
809                         to_pair = sockets_map[b_to_sock.ptr.data];
810
811                 /* either node may be NULL when the node was not exported, typically
812                  * because the node type is not supported */
813                 if(from_pair.first && to_pair.first) {
814                         ShaderOutput *output = from_pair.first->output(from_pair.second.c_str());
815                         ShaderInput *input = to_pair.first->input(to_pair.second.c_str());
816
817                         graph->connect(output, input);
818                 }
819         }
820 }
821
822 /* Sync Materials */
823
824 void BlenderSync::sync_materials()
825 {
826         shader_map.set_default(scene->shaders[scene->default_surface]);
827
828         /* material loop */
829         BL::BlendData::materials_iterator b_mat;
830
831         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
832                 Shader *shader;
833                 
834                 /* test if we need to sync */
835                 if(shader_map.sync(&shader, *b_mat)) {
836                         ShaderGraph *graph = new ShaderGraph();
837
838                         shader->name = b_mat->name().c_str();
839                         shader->pass_id = b_mat->pass_index();
840
841                         /* create nodes */
842                         if(b_mat->use_nodes() && b_mat->node_tree()) {
843                                 PtrSockMap sock_to_node;
844                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
845
846                                 add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
847                         }
848                         else {
849                                 ShaderNode *closure, *out;
850
851                                 closure = graph->add(new DiffuseBsdfNode());
852                                 closure->input("Color")->value = get_float3(b_mat->diffuse_color());
853                                 out = graph->output();
854
855                                 graph->connect(closure->output("BSDF"), out->input("Surface"));
856                         }
857
858                         /* settings */
859                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
860                         shader->sample_as_light = get_boolean(cmat, "sample_as_light");
861                         shader->homogeneous_volume = get_boolean(cmat, "homogeneous_volume");
862
863                         shader->set_graph(graph);
864                         shader->tag_update(scene);
865                 }
866         }
867 }
868
869 /* Sync World */
870
871 void BlenderSync::sync_world()
872 {
873         Background *background = scene->background;
874         Background prevbackground = *background;
875
876         BL::World b_world = b_scene.world();
877
878         if(world_recalc || b_world.ptr.data != world_map) {
879                 Shader *shader = scene->shaders[scene->default_background];
880                 ShaderGraph *graph = new ShaderGraph();
881
882                 /* create nodes */
883                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
884                         PtrSockMap sock_to_node;
885                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
886
887                         add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
888                 }
889                 else if(b_world) {
890                         ShaderNode *closure, *out;
891
892                         closure = graph->add(new BackgroundNode());
893                         closure->input("Color")->value = get_float3(b_world.horizon_color());
894                         out = graph->output();
895
896                         graph->connect(closure->output("Background"), out->input("Surface"));
897                 }
898
899                 /* AO */
900                 if(b_world) {
901                         BL::WorldLighting b_light = b_world.light_settings();
902
903                         if(b_light.use_ambient_occlusion())
904                                 background->ao_factor = b_light.ao_factor();
905                         else
906                                 background->ao_factor = 0.0f;
907
908                         background->ao_distance = b_light.distance();
909                 }
910
911                 shader->set_graph(graph);
912                 shader->tag_update(scene);
913         }
914
915         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
916         background->transparent = get_boolean(cscene, "film_transparent");
917         background->use = render_layer.use_background;
918
919         if(background->modified(prevbackground))
920                 background->tag_update(scene);
921 }
922
923 /* Sync Lamps */
924
925 void BlenderSync::sync_lamps()
926 {
927         shader_map.set_default(scene->shaders[scene->default_light]);
928
929         /* lamp loop */
930         BL::BlendData::lamps_iterator b_lamp;
931
932         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
933                 Shader *shader;
934                 
935                 /* test if we need to sync */
936                 if(shader_map.sync(&shader, *b_lamp)) {
937                         ShaderGraph *graph = new ShaderGraph();
938
939                         /* create nodes */
940                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
941                                 shader->name = b_lamp->name().c_str();
942
943                                 PtrSockMap sock_to_node;
944                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
945
946                                 add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
947                         }
948                         else {
949                                 ShaderNode *closure, *out;
950                                 float strength = 1.0f;
951
952                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
953                                    b_lamp->type() == BL::Lamp::type_SPOT ||
954                                    b_lamp->type() == BL::Lamp::type_AREA)
955                                 {
956                                         strength = 100.0f;
957                                 }
958
959                                 closure = graph->add(new EmissionNode());
960                                 closure->input("Color")->value = get_float3(b_lamp->color());
961                                 closure->input("Strength")->value.x = strength;
962                                 out = graph->output();
963
964                                 graph->connect(closure->output("Emission"), out->input("Surface"));
965                         }
966
967                         shader->set_graph(graph);
968                         shader->tag_update(scene);
969                 }
970         }
971 }
972
973 void BlenderSync::sync_shaders()
974 {
975         shader_map.pre_sync();
976
977         sync_world();
978         sync_lamps();
979         sync_materials();
980
981         /* false = don't delete unused shaders, not supported */
982         shader_map.post_sync(false);
983 }
984
985 CCL_NAMESPACE_END
986