c9a7f2756b713b76449e52cf4d0218bc1561f458
[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_texture.h"
26 #include "blender_sync.h"
27 #include "blender_util.h"
28
29 #include "util_debug.h"
30
31 CCL_NAMESPACE_BEGIN
32
33 typedef map<void*, ShaderInput*> PtrInputMap;
34 typedef map<void*, ShaderOutput*> PtrOutputMap;
35 typedef map<std::string, ProxyNode*> ProxyMap;
36
37 /* Find */
38
39 void BlenderSync::find_shader(BL::ID& id,
40                               vector<uint>& used_shaders,
41                               int default_shader)
42 {
43         Shader *shader = (id)? shader_map.find(id): scene->shaders[default_shader];
44
45         for(size_t i = 0; i < scene->shaders.size(); i++) {
46                 if(scene->shaders[i] == shader) {
47                         used_shaders.push_back(i);
48                         scene->shaders[i]->tag_used(scene);
49                         break;
50                 }
51         }
52 }
53
54 /* Graph */
55
56 static BL::NodeSocket get_node_output(BL::Node& b_node, const string& name)
57 {
58         BL::Node::outputs_iterator b_out;
59
60         for(b_node.outputs.begin(b_out); b_out != b_node.outputs.end(); ++b_out)
61                 if(b_out->name() == name)
62                         return *b_out;
63
64         assert(0);
65
66         return *b_out;
67 }
68
69 static float3 get_node_output_rgba(BL::Node& b_node, const string& name)
70 {
71         BL::NodeSocket b_sock = get_node_output(b_node, name);
72         float value[4];
73         RNA_float_get_array(&b_sock.ptr, "default_value", value);
74         return make_float3(value[0], value[1], value[2]);
75 }
76
77 static float get_node_output_value(BL::Node& b_node, const string& name)
78 {
79         BL::NodeSocket b_sock = get_node_output(b_node, name);
80         return RNA_float_get(&b_sock.ptr, "default_value");
81 }
82
83 static float3 get_node_output_vector(BL::Node& b_node, const string& name)
84 {
85         BL::NodeSocket b_sock = get_node_output(b_node, name);
86         float value[3];
87         RNA_float_get_array(&b_sock.ptr, "default_value", value);
88         return make_float3(value[0], value[1], value[2]);
89 }
90
91 static ShaderSocketType convert_socket_type(BL::NodeSocket& b_socket)
92 {
93         switch(b_socket.type()) {
94                 case BL::NodeSocket::type_VALUE:
95                         return SHADER_SOCKET_FLOAT;
96                 case BL::NodeSocket::type_INT:
97                         return SHADER_SOCKET_INT;
98                 case BL::NodeSocket::type_VECTOR:
99                         return SHADER_SOCKET_VECTOR;
100                 case BL::NodeSocket::type_RGBA:
101                         return SHADER_SOCKET_COLOR;
102                 case BL::NodeSocket::type_STRING:
103                         return SHADER_SOCKET_STRING;
104                 case BL::NodeSocket::type_SHADER:
105                         return SHADER_SOCKET_CLOSURE;
106                 
107                 default:
108                         return SHADER_SOCKET_UNDEFINED;
109         }
110 }
111
112 #ifdef WITH_OSL
113 static ShaderSocketType convert_osl_socket_type(OSL::OSLQuery& query,
114                                                 BL::NodeSocket& b_socket)
115 {
116         ShaderSocketType socket_type = convert_socket_type(b_socket);
117 #if OSL_LIBRARY_VERSION_CODE < 10701
118         (void) query;
119 #else
120         if(socket_type == SHADER_SOCKET_VECTOR) {
121                 /* TODO(sergey): Do we need compatible_name() here? */
122                 const OSL::OSLQuery::Parameter *param = query.getparam(b_socket.name());
123                 assert(param != NULL);
124                 if(param != NULL) {
125                         if(param->type.vecsemantics == TypeDesc::POINT) {
126                                 socket_type = SHADER_SOCKET_POINT;
127                         }
128                         else if(param->type.vecsemantics == TypeDesc::NORMAL) {
129                                 socket_type = SHADER_SOCKET_NORMAL;
130                         }
131                 }
132         }
133 #endif
134         return socket_type;
135 }
136 #endif  /* WITH_OSL */
137
138 static void set_default_value(ShaderInput *input,
139                               BL::NodeSocket& b_sock,
140                               BL::BlendData& b_data,
141                               BL::ID& b_id)
142 {
143         /* copy values for non linked inputs */
144         switch(input->type) {
145                 case SHADER_SOCKET_FLOAT: {
146                         input->set(get_float(b_sock.ptr, "default_value"));
147                         break;
148                 }
149                 case SHADER_SOCKET_INT: {
150                         input->set((float)get_int(b_sock.ptr, "default_value"));
151                         break;
152                 }
153                 case SHADER_SOCKET_COLOR: {
154                         input->set(float4_to_float3(get_float4(b_sock.ptr, "default_value")));
155                         break;
156                 }
157                 case SHADER_SOCKET_NORMAL:
158                 case SHADER_SOCKET_POINT:
159                 case SHADER_SOCKET_VECTOR: {
160                         input->set(get_float3(b_sock.ptr, "default_value"));
161                         break;
162                 }
163                 case SHADER_SOCKET_STRING: {
164                         input->set((ustring)blender_absolute_path(b_data, b_id, get_string(b_sock.ptr, "default_value")));
165                         break;
166                 }
167
168                 case SHADER_SOCKET_CLOSURE:
169                 case SHADER_SOCKET_UNDEFINED:
170                         break;
171         }
172 }
173
174 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping& b_mapping)
175 {
176         if(!b_mapping)
177                 return;
178
179         mapping->translation = get_float3(b_mapping.translation());
180         mapping->rotation = get_float3(b_mapping.rotation());
181         mapping->scale = get_float3(b_mapping.scale());
182         mapping->type = (TextureMapping::Type)b_mapping.vector_type();
183
184         mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
185         mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
186         mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
187 }
188
189 static void get_tex_mapping(TextureMapping *mapping,
190                             BL::ShaderNodeMapping& b_mapping)
191 {
192         if(!b_mapping)
193                 return;
194
195         mapping->translation = get_float3(b_mapping.translation());
196         mapping->rotation = get_float3(b_mapping.rotation());
197         mapping->scale = get_float3(b_mapping.scale());
198         mapping->type = (TextureMapping::Type)b_mapping.vector_type();
199
200         mapping->use_minmax = b_mapping.use_min() || b_mapping.use_max();
201
202         if(b_mapping.use_min())
203                 mapping->min = get_float3(b_mapping.min());
204         if(b_mapping.use_max())
205                 mapping->max = get_float3(b_mapping.max());
206 }
207
208 static bool is_output_node(BL::Node& b_node)
209 {
210         return (b_node.is_a(&RNA_ShaderNodeOutputMaterial)
211                     || b_node.is_a(&RNA_ShaderNodeOutputWorld)
212                     || b_node.is_a(&RNA_ShaderNodeOutputLamp));
213 }
214
215 static ShaderNode *add_node(Scene *scene,
216                             BL::RenderEngine& b_engine,
217                             BL::BlendData& b_data,
218                             BL::Scene& b_scene,
219                             const bool background,
220                             ShaderGraph *graph,
221                             BL::ShaderNodeTree& b_ntree,
222                             BL::ShaderNode& b_node)
223 {
224         ShaderNode *node = NULL;
225
226         /* existing blender nodes */
227         if(b_node.is_a(&RNA_ShaderNodeRGBCurve)) {
228                 BL::ShaderNodeRGBCurve b_curve_node(b_node);
229                 BL::CurveMapping mapping(b_curve_node.mapping());
230                 RGBCurvesNode *curves = new RGBCurvesNode();
231                 curvemapping_color_to_array(mapping,
232                                             curves->curves,
233                                             RAMP_TABLE_SIZE,
234                                             true);
235                 curvemapping_minmax(mapping, true, &curves->min_x, &curves->max_x);
236                 node = curves;
237         }
238         if(b_node.is_a(&RNA_ShaderNodeVectorCurve)) {
239                 BL::ShaderNodeVectorCurve b_curve_node(b_node);
240                 BL::CurveMapping mapping(b_curve_node.mapping());
241                 VectorCurvesNode *curves = new VectorCurvesNode();
242                 curvemapping_color_to_array(mapping,
243                                             curves->curves,
244                                             RAMP_TABLE_SIZE,
245                                             false);
246                 curvemapping_minmax(mapping, false, &curves->min_x, &curves->max_x);
247                 node = curves;
248         }
249         else if(b_node.is_a(&RNA_ShaderNodeValToRGB)) {
250                 RGBRampNode *ramp = new RGBRampNode();
251                 BL::ShaderNodeValToRGB b_ramp_node(b_node);
252                 BL::ColorRamp b_color_ramp(b_ramp_node.color_ramp());
253                 colorramp_to_array(b_color_ramp, ramp->ramp, RAMP_TABLE_SIZE);
254                 ramp->interpolate = b_color_ramp.interpolation() != BL::ColorRamp::interpolation_CONSTANT;
255                 node = ramp;
256         }
257         else if(b_node.is_a(&RNA_ShaderNodeRGB)) {
258                 ColorNode *color = new ColorNode();
259                 color->value = get_node_output_rgba(b_node, "Color");
260                 node = color;
261         }
262         else if(b_node.is_a(&RNA_ShaderNodeValue)) {
263                 ValueNode *value = new ValueNode();
264                 value->value = get_node_output_value(b_node, "Value");
265                 node = value;
266         }
267         else if(b_node.is_a(&RNA_ShaderNodeCameraData)) {
268                 node = new CameraNode();
269         }
270         else if(b_node.is_a(&RNA_ShaderNodeInvert)) {
271                 node = new InvertNode();
272         }
273         else if(b_node.is_a(&RNA_ShaderNodeGamma)) {
274                 node = new GammaNode();
275         }
276         else if(b_node.is_a(&RNA_ShaderNodeBrightContrast)) {
277                 node = new BrightContrastNode();
278         }
279         else if(b_node.is_a(&RNA_ShaderNodeMixRGB)) {
280                 BL::ShaderNodeMixRGB b_mix_node(b_node);
281                 MixNode *mix = new MixNode();
282                 mix->type = MixNode::type_enum[b_mix_node.blend_type()];
283                 /* Tag if it's Mix */
284                 if(b_mix_node.blend_type() == 0) 
285                         mix->special_type = SHADER_SPECIAL_TYPE_MIX_RGB;
286
287                 mix->use_clamp = b_mix_node.use_clamp();
288                 node = mix;
289         }
290         else if(b_node.is_a(&RNA_ShaderNodeSeparateRGB)) {
291                 node = new SeparateRGBNode();
292         }
293         else if(b_node.is_a(&RNA_ShaderNodeCombineRGB)) {
294                 node = new CombineRGBNode();
295         }
296         else if(b_node.is_a(&RNA_ShaderNodeSeparateHSV)) {
297                 node = new SeparateHSVNode();
298         }
299         else if(b_node.is_a(&RNA_ShaderNodeCombineHSV)) {
300                 node = new CombineHSVNode();
301         }
302         else if(b_node.is_a(&RNA_ShaderNodeSeparateXYZ)) {
303                 node = new SeparateXYZNode();
304         }
305         else if(b_node.is_a(&RNA_ShaderNodeCombineXYZ)) {
306                 node = new CombineXYZNode();
307         }
308         else if(b_node.is_a(&RNA_ShaderNodeHueSaturation)) {
309                 node = new HSVNode();
310         }
311         else if(b_node.is_a(&RNA_ShaderNodeRGBToBW)) {
312                 node = new ConvertNode(SHADER_SOCKET_COLOR, SHADER_SOCKET_FLOAT);
313         }
314         else if(b_node.is_a(&RNA_ShaderNodeMath)) {
315                 BL::ShaderNodeMath b_math_node(b_node);
316                 MathNode *math = new MathNode();
317                 math->type = MathNode::type_enum[b_math_node.operation()];
318                 math->use_clamp = b_math_node.use_clamp();
319                 node = math;
320         }
321         else if(b_node.is_a(&RNA_ShaderNodeVectorMath)) {
322                 BL::ShaderNodeVectorMath b_vector_math_node(b_node);
323                 VectorMathNode *vmath = new VectorMathNode();
324                 vmath->type = VectorMathNode::type_enum[b_vector_math_node.operation()];
325                 node = vmath;
326         }
327         else if(b_node.is_a(&RNA_ShaderNodeVectorTransform)) {
328                 BL::ShaderNodeVectorTransform b_vector_transform_node(b_node);
329                 VectorTransformNode *vtransform = new VectorTransformNode();
330                 vtransform->type = VectorTransformNode::type_enum[b_vector_transform_node.vector_type()];
331                 vtransform->convert_from = VectorTransformNode::convert_space_enum[b_vector_transform_node.convert_from()];
332                 vtransform->convert_to = VectorTransformNode::convert_space_enum[b_vector_transform_node.convert_to()];
333                 node = vtransform;
334         }
335         else if(b_node.is_a(&RNA_ShaderNodeNormal)) {
336                 BL::Node::outputs_iterator out_it;
337                 b_node.outputs.begin(out_it);
338
339                 NormalNode *norm = new NormalNode();
340                 norm->direction = get_node_output_vector(b_node, "Normal");
341                 node = norm;
342         }
343         else if(b_node.is_a(&RNA_ShaderNodeMapping)) {
344                 BL::ShaderNodeMapping b_mapping_node(b_node);
345                 MappingNode *mapping = new MappingNode();
346
347                 get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
348
349                 node = mapping;
350         }
351         else if(b_node.is_a(&RNA_ShaderNodeFresnel)) {
352                 node = new FresnelNode();
353         }
354         else if(b_node.is_a(&RNA_ShaderNodeLayerWeight)) {
355                 node = new LayerWeightNode();
356         }
357         else if(b_node.is_a(&RNA_ShaderNodeAddShader)) {
358                 node = new AddClosureNode();
359         }
360         else if(b_node.is_a(&RNA_ShaderNodeMixShader)) {
361                 node = new MixClosureNode();
362         }
363         else if(b_node.is_a(&RNA_ShaderNodeAttribute)) {
364                 BL::ShaderNodeAttribute b_attr_node(b_node);
365                 AttributeNode *attr = new AttributeNode();
366                 attr->attribute = b_attr_node.attribute_name();
367                 node = attr;
368         }
369         else if(b_node.is_a(&RNA_ShaderNodeBackground)) {
370                 node = new BackgroundNode();
371         }
372         else if(b_node.is_a(&RNA_ShaderNodeHoldout)) {
373                 node = new HoldoutNode();
374         }
375         else if(b_node.is_a(&RNA_ShaderNodeBsdfAnisotropic)) {
376                 BL::ShaderNodeBsdfAnisotropic b_aniso_node(b_node);
377                 AnisotropicBsdfNode *aniso = new AnisotropicBsdfNode();
378
379                 switch(b_aniso_node.distribution()) {
380                         case BL::ShaderNodeBsdfAnisotropic::distribution_BECKMANN:
381                                 aniso->distribution = ustring("Beckmann");
382                                 break;
383                         case BL::ShaderNodeBsdfAnisotropic::distribution_GGX:
384                                 aniso->distribution = ustring("GGX");
385                                 break;
386                         case BL::ShaderNodeBsdfAnisotropic::distribution_ASHIKHMIN_SHIRLEY:
387                                 aniso->distribution = ustring("Ashikhmin-Shirley");
388                                 break;
389                 }
390
391                 node = aniso;
392         }
393         else if(b_node.is_a(&RNA_ShaderNodeBsdfDiffuse)) {
394                 node = new DiffuseBsdfNode();
395         }
396         else if(b_node.is_a(&RNA_ShaderNodeSubsurfaceScattering)) {
397                 BL::ShaderNodeSubsurfaceScattering b_subsurface_node(b_node);
398
399                 SubsurfaceScatteringNode *subsurface = new SubsurfaceScatteringNode();
400
401                 switch(b_subsurface_node.falloff()) {
402                         case BL::ShaderNodeSubsurfaceScattering::falloff_CUBIC:
403                                 subsurface->closure = CLOSURE_BSSRDF_CUBIC_ID;
404                                 break;
405                         case BL::ShaderNodeSubsurfaceScattering::falloff_GAUSSIAN:
406                                 subsurface->closure = CLOSURE_BSSRDF_GAUSSIAN_ID;
407                                 break;
408                         case BL::ShaderNodeSubsurfaceScattering::falloff_BURLEY:
409                                 subsurface->closure = CLOSURE_BSSRDF_BURLEY_ID;
410                                 break;
411                 }
412
413                 node = subsurface;
414         }
415         else if(b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) {
416                 BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
417                 GlossyBsdfNode *glossy = new GlossyBsdfNode();
418                 
419                 switch(b_glossy_node.distribution()) {
420                         case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
421                                 glossy->distribution = ustring("Sharp");
422                                 break;
423                         case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
424                                 glossy->distribution = ustring("Beckmann");
425                                 break;
426                         case BL::ShaderNodeBsdfGlossy::distribution_GGX:
427                                 glossy->distribution = ustring("GGX");
428                                 break;
429                         case BL::ShaderNodeBsdfGlossy::distribution_ASHIKHMIN_SHIRLEY:
430                                 glossy->distribution = ustring("Ashikhmin-Shirley");
431                                 break;
432                 }
433                 node = glossy;
434         }
435         else if(b_node.is_a(&RNA_ShaderNodeBsdfGlass)) {
436                 BL::ShaderNodeBsdfGlass b_glass_node(b_node);
437                 GlassBsdfNode *glass = new GlassBsdfNode();
438                 switch(b_glass_node.distribution()) {
439                         case BL::ShaderNodeBsdfGlass::distribution_SHARP:
440                                 glass->distribution = ustring("Sharp");
441                                 break;
442                         case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
443                                 glass->distribution = ustring("Beckmann");
444                                 break;
445                         case BL::ShaderNodeBsdfGlass::distribution_GGX:
446                                 glass->distribution = ustring("GGX");
447                                 break;
448                 }
449                 node = glass;
450         }
451         else if(b_node.is_a(&RNA_ShaderNodeBsdfRefraction)) {
452                 BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
453                 RefractionBsdfNode *refraction = new RefractionBsdfNode();
454                 switch(b_refraction_node.distribution()) {
455                         case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
456                                 refraction->distribution = ustring("Sharp");
457                                 break;
458                         case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
459                                 refraction->distribution = ustring("Beckmann");
460                                 break;
461                         case BL::ShaderNodeBsdfRefraction::distribution_GGX:
462                                 refraction->distribution = ustring("GGX");
463                                 break;
464                 }
465                 node = refraction;
466         }
467         else if(b_node.is_a(&RNA_ShaderNodeBsdfToon)) {
468                 BL::ShaderNodeBsdfToon b_toon_node(b_node);
469                 ToonBsdfNode *toon = new ToonBsdfNode();
470                 switch(b_toon_node.component()) {
471                         case BL::ShaderNodeBsdfToon::component_DIFFUSE:
472                                 toon->component = ustring("Diffuse");
473                                 break;
474                         case BL::ShaderNodeBsdfToon::component_GLOSSY:
475                                 toon->component = ustring("Glossy");
476                                 break;
477                 }
478                 node = toon;
479         }
480         else if(b_node.is_a(&RNA_ShaderNodeBsdfHair)) {
481                 BL::ShaderNodeBsdfHair b_hair_node(b_node);
482                 HairBsdfNode *hair = new HairBsdfNode();
483                 switch(b_hair_node.component()) {
484                         case BL::ShaderNodeBsdfHair::component_Reflection:
485                                 hair->component = ustring("Reflection");
486                                 break;
487                         case BL::ShaderNodeBsdfHair::component_Transmission:
488                                 hair->component = ustring("Transmission");
489                                 break;
490                 }
491                 node = hair;
492         }
493         else if(b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
494                 node = new TranslucentBsdfNode();
495         }
496         else if(b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
497                 node = new TransparentBsdfNode();
498         }
499         else if(b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
500                 node = new VelvetBsdfNode();
501         }
502         else if(b_node.is_a(&RNA_ShaderNodeEmission)) {
503                 node = new EmissionNode();
504         }
505         else if(b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
506                 node = new AmbientOcclusionNode();
507         }
508         else if(b_node.is_a(&RNA_ShaderNodeVolumeScatter)) {
509                 node = new ScatterVolumeNode();
510         }
511         else if(b_node.is_a(&RNA_ShaderNodeVolumeAbsorption)) {
512                 node = new AbsorptionVolumeNode();
513         }
514         else if(b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
515                 node = new GeometryNode();
516         }
517         else if(b_node.is_a(&RNA_ShaderNodeWireframe)) {
518                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
519                 WireframeNode *wire = new WireframeNode();
520                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
521                 node = wire;
522         }
523         else if(b_node.is_a(&RNA_ShaderNodeWavelength)) {
524                 node = new WavelengthNode();
525         }
526         else if(b_node.is_a(&RNA_ShaderNodeBlackbody)) {
527                 node = new BlackbodyNode();
528         }
529         else if(b_node.is_a(&RNA_ShaderNodeLightPath)) {
530                 node = new LightPathNode();
531         }
532         else if(b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
533                 node = new LightFalloffNode();
534         }
535         else if(b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
536                 node = new ObjectInfoNode();
537         }
538         else if(b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
539                 node = new ParticleInfoNode();
540         }
541         else if(b_node.is_a(&RNA_ShaderNodeHairInfo)) {
542                 node = new HairInfoNode();
543         }
544         else if(b_node.is_a(&RNA_ShaderNodeBump)) {
545                 BL::ShaderNodeBump b_bump_node(b_node);
546                 BumpNode *bump = new BumpNode();
547                 bump->invert = b_bump_node.invert();
548                 node = bump;
549         }
550         else if(b_node.is_a(&RNA_ShaderNodeScript)) {
551 #ifdef WITH_OSL
552                 if(scene->shader_manager->use_osl()) {
553                         /* create script node */
554                         BL::ShaderNodeScript b_script_node(b_node);
555                         OSLScriptNode *script_node = new OSLScriptNode();
556
557                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
558                         string bytecode_hash = b_script_node.bytecode_hash();
559
560                         /* Gather additional information from the shader, such as
561                          * input/output type info needed for proper node construction.
562                          */
563                         OSL::OSLQuery query;
564 #if OSL_LIBRARY_VERSION_CODE >= 10701
565                         if(!bytecode_hash.empty()) {
566                                 query.open_bytecode(b_script_node.bytecode());
567                         }
568                         else {
569                                 !OSLShaderManager::osl_query(query, b_script_node.filepath());
570                         }
571                         /* TODO(sergey): Add proper query info error parsing. */
572 #endif
573
574                         /* Generate inputs/outputs from node sockets
575                          *
576                          * Note: the node sockets are generated from OSL parameters,
577                          * so the names match those of the corresponding parameters exactly.
578                          *
579                          * Note 2: ShaderInput/ShaderOutput store shallow string copies only!
580                          * Socket names must be stored in the extra lists instead. */
581                         BL::Node::inputs_iterator b_input;
582
583                         for(b_script_node.inputs.begin(b_input); b_input != b_script_node.inputs.end(); ++b_input) {
584                                 script_node->input_names.push_back(ustring(b_input->name()));
585                                 ShaderInput *input = script_node->add_input(script_node->input_names.back().c_str(),
586                                                                             convert_osl_socket_type(query, *b_input));
587                                 set_default_value(input, *b_input, b_data, b_ntree);
588                         }
589
590                         BL::Node::outputs_iterator b_output;
591
592                         for(b_script_node.outputs.begin(b_output); b_output != b_script_node.outputs.end(); ++b_output) {
593                                 script_node->output_names.push_back(ustring(b_output->name()));
594                                 script_node->add_output(script_node->output_names.back().c_str(),
595                                                         convert_osl_socket_type(query, *b_output));
596                         }
597
598                         /* load bytecode or filepath */
599                         if(!bytecode_hash.empty()) {
600                                 /* loaded bytecode if not already done */
601                                 if(!manager->shader_test_loaded(bytecode_hash))
602                                         manager->shader_load_bytecode(bytecode_hash, b_script_node.bytecode());
603
604                                 script_node->bytecode_hash = bytecode_hash;
605                         }
606                         else {
607                                 /* set filepath */
608                                 script_node->filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
609                         }
610
611                         node = script_node;
612                 }
613 #else
614                 (void)b_data;
615                 (void)b_ntree;
616 #endif
617         }
618         else if(b_node.is_a(&RNA_ShaderNodeTexImage)) {
619                 BL::ShaderNodeTexImage b_image_node(b_node);
620                 BL::Image b_image(b_image_node.image());
621                 BL::ImageUser b_image_user(b_image_node.image_user());
622                 ImageTextureNode *image = new ImageTextureNode();
623                 if(b_image) {
624                         /* builtin images will use callback-based reading because
625                          * they could only be loaded correct from blender side
626                          */
627                         bool is_builtin = b_image.packed_file() ||
628                                           b_image.source() == BL::Image::source_GENERATED ||
629                                           b_image.source() == BL::Image::source_MOVIE ||
630                                           b_engine.is_preview();
631
632                         if(is_builtin) {
633                                 /* for builtin images we're using image datablock name to find an image to
634                                  * read pixels from later
635                                  *
636                                  * also store frame number as well, so there's no differences in handling
637                                  * builtin names for packed images and movies
638                                  */
639                                 int scene_frame = b_scene.frame_current();
640                                 int image_frame = image_user_frame_number(b_image_user,
641                                                                           scene_frame);
642                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
643                                 image->builtin_data = b_image.ptr.data;
644                         }
645                         else {
646                                 image->filename = image_user_file_path(b_image_user,
647                                                                        b_image,
648                                                                        b_scene.frame_current());
649                                 image->builtin_data = NULL;
650                         }
651
652                         image->animated = b_image_node.image_user().use_auto_refresh();
653                         image->use_alpha = b_image.use_alpha();
654
655                         /* TODO(sergey): Does not work properly when we change builtin type. */
656                         if(b_image.is_updated()) {
657                                 scene->image_manager->tag_reload_image(
658                                         image->filename,
659                                         image->builtin_data,
660                                         (InterpolationType)b_image_node.interpolation(),
661                                         (ExtensionType)b_image_node.extension());
662                         }
663                 }
664                 image->color_space = ImageTextureNode::color_space_enum[(int)b_image_node.color_space()];
665                 image->projection = ImageTextureNode::projection_enum[(int)b_image_node.projection()];
666                 image->interpolation = (InterpolationType)b_image_node.interpolation();
667                 image->extension = (ExtensionType)b_image_node.extension();
668                 image->projection_blend = b_image_node.projection_blend();
669                 BL::TexMapping b_texture_mapping(b_image_node.texture_mapping());
670                 get_tex_mapping(&image->tex_mapping, b_texture_mapping);
671                 node = image;
672         }
673         else if(b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
674                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
675                 BL::Image b_image(b_env_node.image());
676                 BL::ImageUser b_image_user(b_env_node.image_user());
677                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
678                 if(b_image) {
679                         bool is_builtin = b_image.packed_file() ||
680                                           b_image.source() == BL::Image::source_GENERATED ||
681                                           b_image.source() == BL::Image::source_MOVIE ||
682                                           b_engine.is_preview();
683
684                         if(is_builtin) {
685                                 int scene_frame = b_scene.frame_current();
686                                 int image_frame = image_user_frame_number(b_image_user,
687                                                                           scene_frame);
688                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
689                                 env->builtin_data = b_image.ptr.data;
690                         }
691                         else {
692                                 env->filename = image_user_file_path(b_image_user,
693                                                                      b_image,
694                                                                      b_scene.frame_current());
695                                 env->animated = b_env_node.image_user().use_auto_refresh();
696                                 env->builtin_data = NULL;
697                         }
698
699                         env->use_alpha = b_image.use_alpha();
700
701                         /* TODO(sergey): Does not work properly when we change builtin type. */
702                         if(b_image.is_updated()) {
703                                 scene->image_manager->tag_reload_image(env->filename,
704                                                                        env->builtin_data,
705                                                                        (InterpolationType)b_env_node.interpolation(),
706                                                                        EXTENSION_REPEAT);
707                         }
708                 }
709                 env->color_space = EnvironmentTextureNode::color_space_enum[(int)b_env_node.color_space()];
710                 env->interpolation = (InterpolationType)b_env_node.interpolation();
711                 env->projection = EnvironmentTextureNode::projection_enum[(int)b_env_node.projection()];
712                 BL::TexMapping b_texture_mapping(b_env_node.texture_mapping());
713                 get_tex_mapping(&env->tex_mapping, b_texture_mapping);
714                 node = env;
715         }
716         else if(b_node.is_a(&RNA_ShaderNodeTexGradient)) {
717                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
718                 GradientTextureNode *gradient = new GradientTextureNode();
719                 gradient->type = GradientTextureNode::type_enum[(int)b_gradient_node.gradient_type()];
720                 BL::TexMapping b_texture_mapping(b_gradient_node.texture_mapping());
721                 get_tex_mapping(&gradient->tex_mapping, b_texture_mapping);
722                 node = gradient;
723         }
724         else if(b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
725                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
726                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
727                 voronoi->coloring = VoronoiTextureNode::coloring_enum[(int)b_voronoi_node.coloring()];
728                 BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping());
729                 get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping);
730                 node = voronoi;
731         }
732         else if(b_node.is_a(&RNA_ShaderNodeTexMagic)) {
733                 BL::ShaderNodeTexMagic b_magic_node(b_node);
734                 MagicTextureNode *magic = new MagicTextureNode();
735                 magic->depth = b_magic_node.turbulence_depth();
736                 BL::TexMapping b_texture_mapping(b_magic_node.texture_mapping());
737                 get_tex_mapping(&magic->tex_mapping, b_texture_mapping);
738                 node = magic;
739         }
740         else if(b_node.is_a(&RNA_ShaderNodeTexWave)) {
741                 BL::ShaderNodeTexWave b_wave_node(b_node);
742                 WaveTextureNode *wave = new WaveTextureNode();
743                 wave->type = WaveTextureNode::type_enum[(int)b_wave_node.wave_type()];
744                 wave->profile = WaveTextureNode::profile_enum[(int)b_wave_node.wave_profile()];
745                 BL::TexMapping b_texture_mapping(b_wave_node.texture_mapping());
746                 get_tex_mapping(&wave->tex_mapping, b_texture_mapping);
747                 node = wave;
748         }
749         else if(b_node.is_a(&RNA_ShaderNodeTexChecker)) {
750                 BL::ShaderNodeTexChecker b_checker_node(b_node);
751                 CheckerTextureNode *checker = new CheckerTextureNode();
752                 BL::TexMapping b_texture_mapping(b_checker_node.texture_mapping());
753                 get_tex_mapping(&checker->tex_mapping, b_texture_mapping);
754                 node = checker;
755         }
756         else if(b_node.is_a(&RNA_ShaderNodeTexBrick)) {
757                 BL::ShaderNodeTexBrick b_brick_node(b_node);
758                 BrickTextureNode *brick = new BrickTextureNode();
759                 brick->offset = b_brick_node.offset();
760                 brick->offset_frequency = b_brick_node.offset_frequency();
761                 brick->squash = b_brick_node.squash();
762                 brick->squash_frequency = b_brick_node.squash_frequency();
763                 BL::TexMapping b_texture_mapping(b_brick_node.texture_mapping());
764                 get_tex_mapping(&brick->tex_mapping, b_texture_mapping);
765                 node = brick;
766         }
767         else if(b_node.is_a(&RNA_ShaderNodeTexNoise)) {
768                 BL::ShaderNodeTexNoise b_noise_node(b_node);
769                 NoiseTextureNode *noise = new NoiseTextureNode();
770                 BL::TexMapping b_texture_mapping(b_noise_node.texture_mapping());
771                 get_tex_mapping(&noise->tex_mapping, b_texture_mapping);
772                 node = noise;
773         }
774         else if(b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
775                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
776                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
777                 musgrave->type = MusgraveTextureNode::type_enum[(int)b_musgrave_node.musgrave_type()];
778                 BL::TexMapping b_texture_mapping(b_musgrave_node.texture_mapping());
779                 get_tex_mapping(&musgrave->tex_mapping, b_texture_mapping);
780                 node = musgrave;
781         }
782         else if(b_node.is_a(&RNA_ShaderNodeTexCoord)) {
783                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
784                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
785                 tex_coord->from_dupli = b_tex_coord_node.from_dupli();
786                 if(b_tex_coord_node.object()) {
787                         tex_coord->use_transform = true;
788                         tex_coord->ob_tfm = get_transform(b_tex_coord_node.object().matrix_world());
789                 }
790                 node = tex_coord;
791         }
792         else if(b_node.is_a(&RNA_ShaderNodeTexSky)) {
793                 BL::ShaderNodeTexSky b_sky_node(b_node);
794                 SkyTextureNode *sky = new SkyTextureNode();
795                 sky->type = SkyTextureNode::type_enum[(int)b_sky_node.sky_type()];
796                 sky->sun_direction = normalize(get_float3(b_sky_node.sun_direction()));
797                 sky->turbidity = b_sky_node.turbidity();
798                 sky->ground_albedo = b_sky_node.ground_albedo();
799                 BL::TexMapping b_texture_mapping(b_sky_node.texture_mapping());
800                 get_tex_mapping(&sky->tex_mapping, b_texture_mapping);
801                 node = sky;
802         }
803         else if(b_node.is_a(&RNA_ShaderNodeNormalMap)) {
804                 BL::ShaderNodeNormalMap b_normal_map_node(b_node);
805                 NormalMapNode *nmap = new NormalMapNode();
806                 nmap->space = NormalMapNode::space_enum[(int)b_normal_map_node.space()];
807                 nmap->attribute = b_normal_map_node.uv_map();
808                 node = nmap;
809         }
810         else if(b_node.is_a(&RNA_ShaderNodeTangent)) {
811                 BL::ShaderNodeTangent b_tangent_node(b_node);
812                 TangentNode *tangent = new TangentNode();
813                 tangent->direction_type = TangentNode::direction_type_enum[(int)b_tangent_node.direction_type()];
814                 tangent->axis = TangentNode::axis_enum[(int)b_tangent_node.axis()];
815                 tangent->attribute = b_tangent_node.uv_map();
816                 node = tangent;
817         }
818         else if(b_node.is_a(&RNA_ShaderNodeUVMap)) {
819                 BL::ShaderNodeUVMap b_uvmap_node(b_node);
820                 UVMapNode *uvm = new UVMapNode();
821                 uvm->attribute = b_uvmap_node.uv_map();
822                 uvm->from_dupli = b_uvmap_node.from_dupli();
823                 node = uvm;
824         }
825         else if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
826                 BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
827                 PointDensityTextureNode *point_density = new PointDensityTextureNode();
828                 point_density->filename = b_point_density_node.name();
829                 point_density->space =
830                         PointDensityTextureNode::space_enum[(int)b_point_density_node.space()];
831                 point_density->interpolation =
832                         (InterpolationType)b_point_density_node.interpolation();
833                 point_density->builtin_data = b_point_density_node.ptr.data;
834
835                 /* 1 - render settings, 0 - vewport settings. */
836                 int settings = background ? 1 : 0;
837
838                 /* TODO(sergey): Use more proper update flag. */
839                 if(true) {
840                         b_point_density_node.cache_point_density(b_scene, settings);
841                         scene->image_manager->tag_reload_image(
842                                 point_density->filename,
843                                 point_density->builtin_data,
844                                 point_density->interpolation,
845                                 EXTENSION_CLIP);
846                 }
847                 node = point_density;
848
849                 /* Transformation form world space to texture space.
850                  *
851                  * NOTE: Do this after the texture is cached, this is because getting
852                  * min/max will need to access this cache.
853                  */
854                 BL::Object b_ob(b_point_density_node.object());
855                 if(b_ob) {
856                         float3 loc, size;
857                         point_density_texture_space(b_scene,
858                                                     b_point_density_node,
859                                                     settings,
860                                                     loc,
861                                                     size);
862                         point_density->tfm =
863                                 transform_translate(-loc) * transform_scale(size) *
864                                 transform_inverse(get_transform(b_ob.matrix_world()));
865                 }
866         }
867
868         if(node)
869                 graph->add(node);
870
871         return node;
872 }
873
874 static bool node_use_modified_socket_name(ShaderNode *node)
875 {
876         if(node->special_type == SHADER_SPECIAL_TYPE_SCRIPT)
877                 return false;
878
879         return true;
880 }
881
882 static ShaderInput *node_find_input_by_name(ShaderNode *node,
883                                             BL::Node& b_node,
884                                             BL::NodeSocket& b_socket)
885 {
886         string name = b_socket.name();
887         
888         if(node_use_modified_socket_name(node)) {
889                 BL::Node::inputs_iterator b_input;
890                 bool found = false;
891                 int counter = 0, total = 0;
892
893                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
894                         if(b_input->name() == name) {
895                                 if(!found)
896                                         counter++;
897                                 total++;
898                         }
899
900                         if(b_input->ptr.data == b_socket.ptr.data)
901                                 found = true;
902                 }
903
904                 /* rename if needed */
905                 if(name == "Shader")
906                         name = "Closure";
907
908                 if(total > 1)
909                         name = string_printf("%s%d", name.c_str(), counter);
910         }
911
912         return node->input(name.c_str());
913 }
914
915 static ShaderOutput *node_find_output_by_name(ShaderNode *node,
916                                               BL::Node& b_node,
917                                               BL::NodeSocket& b_socket)
918 {
919         string name = b_socket.name();
920
921         if(node_use_modified_socket_name(node)) {
922                 BL::Node::outputs_iterator b_output;
923                 bool found = false;
924                 int counter = 0, total = 0;
925
926                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
927                         if(b_output->name() == name) {
928                                 if(!found)
929                                         counter++;
930                                 total++;
931                         }
932
933                         if(b_output->ptr.data == b_socket.ptr.data)
934                                 found = true;
935                 }
936
937                 /* rename if needed */
938                 if(name == "Shader")
939                         name = "Closure";
940
941                 if(total > 1)
942                         name = string_printf("%s%d", name.c_str(), counter);
943         }
944
945         return node->output(name.c_str());
946 }
947
948 static void add_nodes(Scene *scene,
949                       BL::RenderEngine& b_engine,
950                       BL::BlendData& b_data,
951                       BL::Scene& b_scene,
952                       const bool background,
953                       ShaderGraph *graph,
954                       BL::ShaderNodeTree& b_ntree,
955                       const ProxyMap &proxy_input_map,
956                       const ProxyMap &proxy_output_map)
957 {
958         /* add nodes */
959         BL::ShaderNodeTree::nodes_iterator b_node;
960         PtrInputMap input_map;
961         PtrOutputMap output_map;
962
963         BL::Node::inputs_iterator b_input;
964         BL::Node::outputs_iterator b_output;
965
966         /* find the node to use for output if there are multiple */
967         bool found_active_output = false;
968         BL::ShaderNode output_node(PointerRNA_NULL);
969
970         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
971                 if(is_output_node(*b_node)) {
972                         BL::ShaderNodeOutputMaterial b_output_node(*b_node);
973
974                         if(b_output_node.is_active_output()) {
975                                 output_node = b_output_node;
976                                 found_active_output = true;
977                                 break;
978                         }
979                         else if(!output_node.ptr.data && !found_active_output) {
980                                 output_node = b_output_node;
981                         }
982                 }
983         }
984
985         /* add nodes */
986         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
987                 if(b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
988                         /* replace muted node with internal links */
989                         BL::Node::internal_links_iterator b_link;
990                         for(b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
991                                 BL::NodeSocket to_socket(b_link->to_socket());
992                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(to_socket));
993
994                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
995                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
996
997                                 graph->add(proxy);
998                         }
999                 }
1000                 else if(b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) {
1001                         
1002                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
1003                         if(b_node->is_a(&RNA_ShaderNodeGroup))
1004                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
1005                         else
1006                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
1007                         ProxyMap group_proxy_input_map, group_proxy_output_map;
1008
1009                         /* Add a proxy node for each socket
1010                          * Do this even if the node group has no internal tree,
1011                          * so that links have something to connect to and assert won't fail.
1012                          */
1013                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1014                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(*b_input));
1015                                 graph->add(proxy);
1016
1017                                 /* register the proxy node for internal binding */
1018                                 group_proxy_input_map[b_input->identifier()] = proxy;
1019
1020                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1021
1022                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1023                         }
1024                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1025                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(*b_output));
1026                                 graph->add(proxy);
1027
1028                                 /* register the proxy node for internal binding */
1029                                 group_proxy_output_map[b_output->identifier()] = proxy;
1030
1031                                 output_map[b_output->ptr.data] = proxy->outputs[0];
1032                         }
1033                         
1034                         if(b_group_ntree) {
1035                                 add_nodes(scene,
1036                                           b_engine,
1037                                           b_data,
1038                                           b_scene,
1039                                           background,
1040                                           graph,
1041                                           b_group_ntree,
1042                                           group_proxy_input_map,
1043                                           group_proxy_output_map);
1044                         }
1045                 }
1046                 else if(b_node->is_a(&RNA_NodeGroupInput)) {
1047                         /* map each socket to a proxy node */
1048                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1049                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
1050                                 if(proxy_it != proxy_input_map.end()) {
1051                                         ProxyNode *proxy = proxy_it->second;
1052
1053                                         output_map[b_output->ptr.data] = proxy->outputs[0];
1054                                 }
1055                         }
1056                 }
1057                 else if(b_node->is_a(&RNA_NodeGroupOutput)) {
1058                         BL::NodeGroupOutput b_output_node(*b_node);
1059                         /* only the active group output is used */
1060                         if(b_output_node.is_active_output()) {
1061                                 /* map each socket to a proxy node */
1062                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1063                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
1064                                         if(proxy_it != proxy_output_map.end()) {
1065                                                 ProxyNode *proxy = proxy_it->second;
1066
1067                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1068
1069                                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1070                                         }
1071                                 }
1072                         }
1073                 }
1074                 else {
1075                         ShaderNode *node = NULL;
1076
1077                         if(is_output_node(*b_node)) {
1078                                 if(b_node->ptr.data == output_node.ptr.data) {
1079                                         node = graph->output();
1080                                 }
1081                         }
1082                         else {
1083                                 BL::ShaderNode b_shader_node(*b_node);
1084                                 node = add_node(scene,
1085                                                 b_engine,
1086                                                 b_data,
1087                                                 b_scene,
1088                                                 background,
1089                                                 graph,
1090                                                 b_ntree,
1091                                                 b_shader_node);
1092                         }
1093
1094                         if(node) {
1095                                 /* map node sockets for linking */
1096                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1097                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
1098                                         if(!input) {
1099                                                 /* XXX should not happen, report error? */
1100                                                 continue;
1101                                         }
1102                                         input_map[b_input->ptr.data] = input;
1103
1104                                         set_default_value(input, *b_input, b_data, b_ntree);
1105                                 }
1106                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1107                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
1108                                         if(!output) {
1109                                                 /* XXX should not happen, report error? */
1110                                                 continue;
1111                                         }
1112                                         output_map[b_output->ptr.data] = output;
1113                                 }
1114                         }
1115                 }
1116         }
1117
1118         /* connect nodes */
1119         BL::NodeTree::links_iterator b_link;
1120
1121         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
1122                 /* Ignore invalid links to avoid unwanted cycles created in graph. */
1123                 if(!b_link->is_valid()) {
1124                         continue;
1125                 }
1126                 /* get blender link data */
1127                 BL::NodeSocket b_from_sock = b_link->from_socket();
1128                 BL::NodeSocket b_to_sock = b_link->to_socket();
1129
1130                 ShaderOutput *output = 0;
1131                 ShaderInput *input = 0;
1132
1133                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
1134                 if(output_it != output_map.end())
1135                         output = output_it->second;
1136                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
1137                 if(input_it != input_map.end())
1138                         input = input_it->second;
1139
1140                 /* either node may be NULL when the node was not exported, typically
1141                  * because the node type is not supported */
1142                 if(output && input)
1143                         graph->connect(output, input);
1144         }
1145 }
1146
1147 static void add_nodes(Scene *scene,
1148                       BL::RenderEngine& b_engine,
1149                       BL::BlendData& b_data,
1150                       BL::Scene& b_scene,
1151                       const bool background,
1152                       ShaderGraph *graph,
1153                       BL::ShaderNodeTree& b_ntree)
1154 {
1155         static const ProxyMap empty_proxy_map;
1156         add_nodes(scene,
1157                   b_engine,
1158                   b_data,
1159                   b_scene,
1160                   background,
1161                   graph,
1162                   b_ntree,
1163                   empty_proxy_map,
1164                   empty_proxy_map);
1165 }
1166
1167 /* Sync Materials */
1168
1169 void BlenderSync::sync_materials(bool update_all)
1170 {
1171         shader_map.set_default(scene->shaders[scene->default_surface]);
1172
1173         /* material loop */
1174         BL::BlendData::materials_iterator b_mat;
1175
1176         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
1177                 Shader *shader;
1178
1179                 /* test if we need to sync */
1180                 if(shader_map.sync(&shader, *b_mat) || update_all) {
1181                         ShaderGraph *graph = new ShaderGraph();
1182
1183                         shader->name = b_mat->name().c_str();
1184                         shader->pass_id = b_mat->pass_index();
1185
1186                         /* create nodes */
1187                         if(b_mat->use_nodes() && b_mat->node_tree()) {
1188                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
1189
1190                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1191                         }
1192                         else {
1193                                 ShaderNode *closure, *out;
1194
1195                                 closure = graph->add(new DiffuseBsdfNode());
1196                                 closure->input("Color")->value = get_float3(b_mat->diffuse_color());
1197                                 out = graph->output();
1198
1199                                 graph->connect(closure->output("BSDF"), out->input("Surface"));
1200                         }
1201
1202                         /* settings */
1203                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
1204                         shader->use_mis = get_boolean(cmat, "sample_as_light");
1205                         shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
1206                         shader->heterogeneous_volume = !get_boolean(cmat, "homogeneous_volume");
1207                         shader->volume_sampling_method = (VolumeSampling)get_enum(cmat, "volume_sampling");
1208                         shader->volume_interpolation_method = (VolumeInterpolation)get_enum(cmat, "volume_interpolation");
1209
1210                         shader->set_graph(graph);
1211                         shader->tag_update(scene);
1212                 }
1213         }
1214 }
1215
1216 /* Sync World */
1217
1218 void BlenderSync::sync_world(bool update_all)
1219 {
1220         Background *background = scene->background;
1221         Background prevbackground = *background;
1222
1223         BL::World b_world = b_scene.world();
1224
1225         if(world_recalc || update_all || b_world.ptr.data != world_map) {
1226                 Shader *shader = scene->shaders[scene->default_background];
1227                 ShaderGraph *graph = new ShaderGraph();
1228
1229                 /* create nodes */
1230                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
1231                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
1232
1233                         add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1234
1235                         /* volume */
1236                         PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
1237                         shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
1238                         shader->volume_sampling_method = (VolumeSampling)get_enum(cworld, "volume_sampling");
1239                         shader->volume_interpolation_method = (VolumeInterpolation)get_enum(cworld, "volume_interpolation");
1240                 }
1241                 else if(b_world) {
1242                         ShaderNode *closure, *out;
1243
1244                         closure = graph->add(new BackgroundNode());
1245                         closure->input("Color")->value = get_float3(b_world.horizon_color());
1246                         out = graph->output();
1247
1248                         graph->connect(closure->output("Background"), out->input("Surface"));
1249                 }
1250
1251                 if(b_world) {
1252                         /* AO */
1253                         BL::WorldLighting b_light = b_world.light_settings();
1254
1255                         if(b_light.use_ambient_occlusion())
1256                                 background->ao_factor = b_light.ao_factor();
1257                         else
1258                                 background->ao_factor = 0.0f;
1259
1260                         background->ao_distance = b_light.distance();
1261
1262                         /* visibility */
1263                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
1264                         uint visibility = 0;
1265
1266                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
1267                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
1268                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
1269                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
1270                         visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0;
1271
1272                         background->visibility = visibility;
1273                 }
1274                 else {
1275                         background->ao_factor = 0.0f;
1276                         background->ao_distance = FLT_MAX;
1277                 }
1278
1279                 shader->set_graph(graph);
1280                 shader->tag_update(scene);
1281                 background->tag_update(scene);
1282         }
1283
1284         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
1285
1286         /* when doing preview render check for BI's transparency settings,
1287          * this is so because Blender's preview render routines are not able
1288          * to tweak all cycles's settings depending on different circumstances
1289          */
1290         if(b_engine.is_preview() == false)
1291                 background->transparent = get_boolean(cscene, "film_transparent");
1292         else
1293                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
1294
1295         background->use_shader = render_layer.use_background_shader;
1296         background->use_ao = render_layer.use_background_ao;
1297
1298         if(background->modified(prevbackground))
1299                 background->tag_update(scene);
1300 }
1301
1302 /* Sync Lamps */
1303
1304 void BlenderSync::sync_lamps(bool update_all)
1305 {
1306         shader_map.set_default(scene->shaders[scene->default_light]);
1307
1308         /* lamp loop */
1309         BL::BlendData::lamps_iterator b_lamp;
1310
1311         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
1312                 Shader *shader;
1313
1314                 /* test if we need to sync */
1315                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
1316                         ShaderGraph *graph = new ShaderGraph();
1317
1318                         /* create nodes */
1319                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
1320                                 shader->name = b_lamp->name().c_str();
1321
1322                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
1323
1324                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1325                         }
1326                         else {
1327                                 ShaderNode *closure, *out;
1328                                 float strength = 1.0f;
1329
1330                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
1331                                    b_lamp->type() == BL::Lamp::type_SPOT ||
1332                                    b_lamp->type() == BL::Lamp::type_AREA)
1333                                 {
1334                                         strength = 100.0f;
1335                                 }
1336
1337                                 closure = graph->add(new EmissionNode());
1338                                 closure->input("Color")->value = get_float3(b_lamp->color());
1339                                 closure->input("Strength")->value.x = strength;
1340                                 out = graph->output();
1341
1342                                 graph->connect(closure->output("Emission"), out->input("Surface"));
1343                         }
1344
1345                         shader->set_graph(graph);
1346                         shader->tag_update(scene);
1347                 }
1348         }
1349 }
1350
1351 void BlenderSync::sync_shaders()
1352 {
1353         /* for auto refresh images */
1354         bool auto_refresh_update = false;
1355
1356         if(preview) {
1357                 ImageManager *image_manager = scene->image_manager;
1358                 int frame = b_scene.frame_current();
1359                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1360         }
1361
1362         shader_map.pre_sync();
1363
1364         sync_world(auto_refresh_update);
1365         sync_lamps(auto_refresh_update);
1366         sync_materials(auto_refresh_update);
1367
1368         /* false = don't delete unused shaders, not supported */
1369         shader_map.post_sync(false);
1370 }
1371
1372 CCL_NAMESPACE_END
1373