Fix use of uninitialized value in Cycles, probably did not cause a bug.
[blender.git] / intern / cycles / render / 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 "render/background.h"
18 #include "render/camera.h"
19 #include "device/device.h"
20 #include "render/graph.h"
21 #include "render/integrator.h"
22 #include "render/light.h"
23 #include "render/mesh.h"
24 #include "render/nodes.h"
25 #include "render/object.h"
26 #include "render/osl.h"
27 #include "render/scene.h"
28 #include "render/shader.h"
29 #include "render/svm.h"
30 #include "render/tables.h"
31
32 #include "util/util_foreach.h"
33
34 CCL_NAMESPACE_BEGIN
35
36 vector<float> ShaderManager::beckmann_table;
37
38 /* Beckmann sampling precomputed table, see bsdf_microfacet.h */
39
40 /* 2D slope distribution (alpha = 1.0) */
41 static float beckmann_table_P22(const float slope_x, const float slope_y)
42 {
43         return expf(-(slope_x*slope_x + slope_y*slope_y));
44 }
45
46 /* maximal slope amplitude (range that contains 99.99% of the distribution) */
47 static float beckmann_table_slope_max()
48 {
49         return 6.0;
50 }
51
52
53 /* MSVC 2015 needs this ugly hack to prevent a codegen bug on x86
54  * see T50176 for details
55  */
56 #if defined(_MSC_VER) && (_MSC_VER == 1900)
57 #  define MSVC_VOLATILE volatile
58 #else
59 #  define MSVC_VOLATILE
60 #endif
61
62 /* Paper used: Importance Sampling Microfacet-Based BSDFs with the
63  * Distribution of Visible Normals. Supplemental Material 2/2.
64  *
65  * http://hal.inria.fr/docs/01/00/66/20/ANNEX/supplemental2.pdf
66  */
67 static void beckmann_table_rows(float *table, int row_from, int row_to)
68 {
69         /* allocate temporary data */
70         const int DATA_TMP_SIZE = 512;
71         vector<double> slope_x(DATA_TMP_SIZE);
72         vector<double> CDF_P22_omega_i(DATA_TMP_SIZE);
73
74         /* loop over incident directions */
75         for(int index_theta = row_from; index_theta < row_to; index_theta++) {
76                 /* incident vector */
77                 const float cos_theta = index_theta / (BECKMANN_TABLE_SIZE - 1.0f);
78                 const float sin_theta = safe_sqrtf(1.0f - cos_theta*cos_theta);
79
80                 /* for a given incident vector
81                  * integrate P22_{omega_i}(x_slope, 1, 1), Eq. (10) */
82                 slope_x[0] = (double)-beckmann_table_slope_max();
83                 CDF_P22_omega_i[0] = 0;
84
85                 for(MSVC_VOLATILE int index_slope_x = 1; index_slope_x < DATA_TMP_SIZE; ++index_slope_x) {
86                         /* slope_x */
87                         slope_x[index_slope_x] = (double)(-beckmann_table_slope_max() + 2.0f * beckmann_table_slope_max() * index_slope_x/(DATA_TMP_SIZE - 1.0f));
88
89                         /* dot product with incident vector */
90                         float dot_product = fmaxf(0.0f, -(float)slope_x[index_slope_x]*sin_theta + cos_theta);
91                         /* marginalize P22_{omega_i}(x_slope, 1, 1), Eq. (10) */
92                         float P22_omega_i = 0.0f;
93
94                         for(int j = 0; j < 100; ++j) {
95                                 float slope_y = -beckmann_table_slope_max() + 2.0f * beckmann_table_slope_max() * j * (1.0f/99.0f);
96                                 P22_omega_i += dot_product * beckmann_table_P22((float)slope_x[index_slope_x], slope_y);
97                         }
98
99                         /* CDF of P22_{omega_i}(x_slope, 1, 1), Eq. (10) */
100                         CDF_P22_omega_i[index_slope_x] = CDF_P22_omega_i[index_slope_x - 1] + (double)P22_omega_i;
101                 }
102
103                 /* renormalize CDF_P22_omega_i */
104                 for(int index_slope_x = 1; index_slope_x < DATA_TMP_SIZE; ++index_slope_x)
105                         CDF_P22_omega_i[index_slope_x] /= CDF_P22_omega_i[DATA_TMP_SIZE - 1];
106
107                 /* loop over random number U1 */
108                 int index_slope_x = 0;
109
110                 for(int index_U = 0; index_U < BECKMANN_TABLE_SIZE; ++index_U) {
111                         const double U = 0.0000001 + 0.9999998 * index_U / (double)(BECKMANN_TABLE_SIZE - 1);
112
113                         /* inverse CDF_P22_omega_i, solve Eq.(11) */
114                         while(CDF_P22_omega_i[index_slope_x] <= U)
115                                 ++index_slope_x;
116
117                         const double interp =
118                                 (CDF_P22_omega_i[index_slope_x] - U) /
119                                 (CDF_P22_omega_i[index_slope_x] - CDF_P22_omega_i[index_slope_x - 1]);
120
121                         /* store value */
122                         table[index_U + index_theta*BECKMANN_TABLE_SIZE] = (float)(
123                                 interp * slope_x[index_slope_x - 1] +
124                                     (1.0 - interp) * slope_x[index_slope_x]);
125                 }
126         }
127 }
128
129 #undef MSVC_VOLATILE
130
131 static void beckmann_table_build(vector<float>& table)
132 {
133         table.resize(BECKMANN_TABLE_SIZE*BECKMANN_TABLE_SIZE);
134
135         /* multithreaded build */
136         TaskPool pool;
137
138         for(int i = 0; i < BECKMANN_TABLE_SIZE; i+=8)
139                 pool.push(function_bind(&beckmann_table_rows, &table[0], i, i+8));
140
141         pool.wait_work();
142 }
143
144 /* Shader */
145
146 NODE_DEFINE(Shader)
147 {
148         NodeType* type = NodeType::add("shader", create);
149
150         SOCKET_BOOLEAN(use_mis, "Use MIS", true);
151         SOCKET_BOOLEAN(use_transparent_shadow, "Use Transparent Shadow", true);
152         SOCKET_BOOLEAN(heterogeneous_volume, "Heterogeneous Volume", true);
153
154         static NodeEnum volume_sampling_method_enum;
155         volume_sampling_method_enum.insert("distance", VOLUME_SAMPLING_DISTANCE);
156         volume_sampling_method_enum.insert("equiangular", VOLUME_SAMPLING_EQUIANGULAR);
157         volume_sampling_method_enum.insert("multiple_importance", VOLUME_SAMPLING_MULTIPLE_IMPORTANCE);
158         SOCKET_ENUM(volume_sampling_method, "Volume Sampling Method", volume_sampling_method_enum, VOLUME_SAMPLING_DISTANCE);
159
160         static NodeEnum volume_interpolation_method_enum;
161         volume_interpolation_method_enum.insert("linear", VOLUME_INTERPOLATION_LINEAR);
162         volume_interpolation_method_enum.insert("cubic", VOLUME_INTERPOLATION_CUBIC);
163         SOCKET_ENUM(volume_interpolation_method, "Volume Interpolation Method", volume_interpolation_method_enum, VOLUME_INTERPOLATION_LINEAR);
164
165         static NodeEnum displacement_method_enum;
166         displacement_method_enum.insert("bump", DISPLACE_BUMP);
167         displacement_method_enum.insert("true", DISPLACE_TRUE);
168         displacement_method_enum.insert("both", DISPLACE_BOTH);
169         SOCKET_ENUM(displacement_method, "Displacement Method", displacement_method_enum, DISPLACE_BUMP);
170
171         return type;
172 }
173
174 Shader::Shader()
175 : Node(node_type)
176 {
177         pass_id = 0;
178
179         graph = NULL;
180         graph_bump = NULL;
181
182         has_surface = false;
183         has_surface_transparent = false;
184         has_surface_emission = false;
185         has_surface_bssrdf = false;
186         has_volume = false;
187         has_displacement = false;
188         has_bssrdf_bump = false;
189         has_surface_spatial_varying = false;
190         has_volume_spatial_varying = false;
191         has_object_dependency = false;
192         has_integrator_dependency = false;
193         has_volume_connected = false;
194
195         displacement_method = DISPLACE_BUMP;
196
197         id = -1;
198         used = false;
199
200         need_update = true;
201         need_update_attributes = true;
202 }
203
204 Shader::~Shader()
205 {
206         delete graph;
207         delete graph_bump;
208 }
209
210 bool Shader::is_constant_emission(float3 *emission)
211 {
212         ShaderInput *surf = graph->output()->input("Surface");
213
214         if(!surf->link || surf->link->parent->type != EmissionNode::node_type) {
215                 return false;
216         }
217
218         EmissionNode *node = (EmissionNode*) surf->link->parent;
219
220         assert(node->input("Color"));
221         assert(node->input("Strength"));
222
223         if(node->input("Color")->link || node->input("Strength")->link) {
224                 return false;
225         }
226
227         *emission = node->color*node->strength;
228
229         return true;
230 }
231
232 void Shader::set_graph(ShaderGraph *graph_)
233 {
234         /* do this here already so that we can detect if mesh or object attributes
235          * are needed, since the node attribute callbacks check if their sockets
236          * are connected but proxy nodes should not count */
237         if(graph_)
238                 graph_->remove_proxy_nodes();
239
240         /* assign graph */
241         delete graph;
242         delete graph_bump;
243         graph = graph_;
244         graph_bump = NULL;
245
246         /* Store info here before graph optimization to make sure that
247          * nodes that get optimized away still count. */
248         has_volume_connected = (graph->output()->input("Volume")->link != NULL);
249 }
250
251 void Shader::tag_update(Scene *scene)
252 {
253         /* update tag */
254         need_update = true;
255         scene->shader_manager->need_update = true;
256
257         /* if the shader previously was emissive, update light distribution,
258          * if the new shader is emissive, a light manager update tag will be
259          * done in the shader manager device update. */
260         if(use_mis && has_surface_emission)
261                 scene->light_manager->need_update = true;
262
263         /* Special handle of background MIS light for now: for some reason it
264          * has use_mis set to false. We are quite close to release now, so
265          * better to be safe.
266          */
267         if(this == scene->default_background &&
268            scene->light_manager->has_background_light(scene))
269         {
270                 scene->light_manager->need_update = true;
271         }
272
273         /* quick detection of which kind of shaders we have to avoid loading
274          * e.g. surface attributes when there is only a volume shader. this could
275          * be more fine grained but it's better than nothing */
276         OutputNode *output = graph->output();
277         bool prev_has_volume = has_volume;
278         has_surface = has_surface || output->input("Surface")->link;
279         has_volume = has_volume || output->input("Volume")->link;
280         has_displacement = has_displacement || output->input("Displacement")->link;
281
282         /* get requested attributes. this could be optimized by pruning unused
283          * nodes here already, but that's the job of the shader manager currently,
284          * and may not be so great for interactive rendering where you temporarily
285          * disconnect a node */
286
287         AttributeRequestSet prev_attributes = attributes;
288
289         attributes.clear();
290         foreach(ShaderNode *node, graph->nodes)
291                 node->attributes(this, &attributes);
292
293         if(has_displacement && displacement_method == DISPLACE_BOTH) {
294                 attributes.add(ATTR_STD_POSITION_UNDISPLACED);
295         }
296         
297         /* compare if the attributes changed, mesh manager will check
298          * need_update_attributes, update the relevant meshes and clear it. */
299         if(attributes.modified(prev_attributes)) {
300                 need_update_attributes = true;
301                 scene->mesh_manager->need_update = true;
302         }
303
304         if(has_volume != prev_has_volume) {
305                 scene->mesh_manager->need_flags_update = true;
306                 scene->object_manager->need_flags_update = true;
307         }
308 }
309
310 void Shader::tag_used(Scene *scene)
311 {
312         /* if an unused shader suddenly gets used somewhere, it needs to be
313          * recompiled because it was skipped for compilation before */
314         if(!used) {
315                 need_update = true;
316                 scene->shader_manager->need_update = true;
317         }
318 }
319
320 /* Shader Manager */
321
322 ShaderManager::ShaderManager()
323 {
324         need_update = true;
325         beckmann_table_offset = TABLE_OFFSET_INVALID;
326 }
327
328 ShaderManager::~ShaderManager()
329 {
330 }
331
332 ShaderManager *ShaderManager::create(Scene *scene, int shadingsystem)
333 {
334         ShaderManager *manager;
335
336         (void)shadingsystem;  /* Ignored when built without OSL. */
337
338 #ifdef WITH_OSL
339         if(shadingsystem == SHADINGSYSTEM_OSL) {
340                 manager = new OSLShaderManager();
341         }
342         else
343 #endif
344         {
345                 manager = new SVMShaderManager();
346         }
347         
348         add_default(scene);
349
350         return manager;
351 }
352
353 uint ShaderManager::get_attribute_id(ustring name)
354 {
355         thread_scoped_spin_lock lock(attribute_lock_);
356
357         /* get a unique id for each name, for SVM attribute lookup */
358         AttributeIDMap::iterator it = unique_attribute_id.find(name);
359
360         if(it != unique_attribute_id.end())
361                 return it->second;
362         
363         uint id = (uint)ATTR_STD_NUM + unique_attribute_id.size();
364         unique_attribute_id[name] = id;
365         return id;
366 }
367
368 uint ShaderManager::get_attribute_id(AttributeStandard std)
369 {
370         return (uint)std;
371 }
372
373 int ShaderManager::get_shader_id(Shader *shader, bool smooth)
374 {
375         /* get a shader id to pass to the kernel */
376         int id = shader->id;
377
378         /* smooth flag */
379         if(smooth)
380                 id |= SHADER_SMOOTH_NORMAL;
381         
382         /* default flags */
383         id |= SHADER_CAST_SHADOW|SHADER_AREA_LIGHT;
384         
385         return id;
386 }
387
388 void ShaderManager::device_update_shaders_used(Scene *scene)
389 {
390         /* figure out which shaders are in use, so SVM/OSL can skip compiling them
391          * for speed and avoid loading image textures into memory */
392         uint id = 0;
393         foreach(Shader *shader, scene->shaders) {
394                 shader->used = false;
395                 shader->id = id++;
396         }
397
398         scene->default_surface->used = true;
399         scene->default_light->used = true;
400         scene->default_background->used = true;
401         scene->default_empty->used = true;
402
403         if(scene->background->shader)
404                 scene->background->shader->used = true;
405
406         foreach(Mesh *mesh, scene->meshes)
407                 foreach(Shader *shader, mesh->used_shaders)
408                         shader->used = true;
409
410         foreach(Light *light, scene->lights)
411                 if(light->shader)
412                         light->shader->used = true;
413 }
414
415 void ShaderManager::device_update_common(Device *device,
416                                          DeviceScene *dscene,
417                                          Scene *scene,
418                                          Progress& /*progress*/)
419 {
420         device->tex_free(dscene->shader_flag);
421         dscene->shader_flag.clear();
422
423         if(scene->shaders.size() == 0)
424                 return;
425
426         uint shader_flag_size = scene->shaders.size()*SHADER_SIZE;
427         uint *shader_flag = dscene->shader_flag.resize(shader_flag_size);
428         uint i = 0;
429         bool has_volumes = false;
430         bool has_transparent_shadow = false;
431
432         foreach(Shader *shader, scene->shaders) {
433                 uint flag = 0;
434
435                 if(shader->use_mis)
436                         flag |= SD_USE_MIS;
437                 if(shader->has_surface_transparent && shader->use_transparent_shadow)
438                         flag |= SD_HAS_TRANSPARENT_SHADOW;
439                 if(shader->has_volume) {
440                         flag |= SD_HAS_VOLUME;
441                         has_volumes = true;
442
443                         /* todo: this could check more fine grained, to skip useless volumes
444                          * enclosed inside an opaque bsdf.
445                          */
446                         flag |= SD_HAS_TRANSPARENT_SHADOW;
447                 }
448                 /* in this case we can assume transparent surface */
449                 if(shader->has_volume_connected && !shader->has_surface)
450                         flag |= SD_HAS_ONLY_VOLUME;
451                 if(shader->heterogeneous_volume && shader->has_volume_spatial_varying)
452                         flag |= SD_HETEROGENEOUS_VOLUME;
453                 if(shader->has_bssrdf_bump)
454                         flag |= SD_HAS_BSSRDF_BUMP;
455                 if(shader->volume_sampling_method == VOLUME_SAMPLING_EQUIANGULAR)
456                         flag |= SD_VOLUME_EQUIANGULAR;
457                 if(shader->volume_sampling_method == VOLUME_SAMPLING_MULTIPLE_IMPORTANCE)
458                         flag |= SD_VOLUME_MIS;
459                 if(shader->volume_interpolation_method == VOLUME_INTERPOLATION_CUBIC)
460                         flag |= SD_VOLUME_CUBIC;
461                 if(shader->graph_bump)
462                         flag |= SD_HAS_BUMP;
463                 if(shader->displacement_method != DISPLACE_BUMP)
464                         flag |= SD_HAS_DISPLACEMENT;
465
466                 /* shader with bump mapping */
467                 if(shader->displacement_method != DISPLACE_TRUE && shader->graph_bump)
468                         flag |= SD_HAS_BSSRDF_BUMP;
469
470                 /* constant emission check */
471                 float3 constant_emission = make_float3(0.0f, 0.0f, 0.0f);
472                 if(shader->is_constant_emission(&constant_emission))
473                         flag |= SD_HAS_CONSTANT_EMISSION;
474
475                 /* regular shader */
476                 shader_flag[i++] = flag;
477                 shader_flag[i++] = shader->pass_id;
478                 shader_flag[i++] = __float_as_int(constant_emission.x);
479                 shader_flag[i++] = __float_as_int(constant_emission.y);
480                 shader_flag[i++] = __float_as_int(constant_emission.z);
481
482                 has_transparent_shadow |= (flag & SD_HAS_TRANSPARENT_SHADOW) != 0;
483         }
484
485         device->tex_alloc("__shader_flag", dscene->shader_flag);
486
487         /* lookup tables */
488         KernelTables *ktables = &dscene->data.tables;
489
490         /* beckmann lookup table */
491         if(beckmann_table_offset == TABLE_OFFSET_INVALID) {
492                 if(beckmann_table.size() == 0) {
493                         thread_scoped_lock lock(lookup_table_mutex);
494                         if(beckmann_table.size() == 0) {
495                                 beckmann_table_build(beckmann_table);
496                         }
497                 }
498                 beckmann_table_offset = scene->lookup_tables->add_table(dscene, beckmann_table);
499         }
500         ktables->beckmann_offset = (int)beckmann_table_offset;
501
502         /* integrator */
503         KernelIntegrator *kintegrator = &dscene->data.integrator;
504         kintegrator->use_volumes = has_volumes;
505         /* TODO(sergey): De-duplicate with flags set in integrator.cpp. */
506         if(scene->integrator->transparent_shadows) {
507                 kintegrator->transparent_shadows = has_transparent_shadow;
508         }
509 }
510
511 void ShaderManager::device_free_common(Device *device, DeviceScene *dscene, Scene *scene)
512 {
513         scene->lookup_tables->remove_table(&beckmann_table_offset);
514
515         device->tex_free(dscene->shader_flag);
516         dscene->shader_flag.clear();
517 }
518
519 void ShaderManager::add_default(Scene *scene)
520 {
521         /* default surface */
522         {
523                 ShaderGraph *graph = new ShaderGraph();
524
525                 DiffuseBsdfNode *diffuse = new DiffuseBsdfNode();
526                 diffuse->color = make_float3(0.8f, 0.8f, 0.8f);
527                 graph->add(diffuse);
528
529                 graph->connect(diffuse->output("BSDF"), graph->output()->input("Surface"));
530
531                 Shader *shader = new Shader();
532                 shader->name = "default_surface";
533                 shader->graph = graph;
534                 scene->shaders.push_back(shader);
535                 scene->default_surface = shader;
536         }
537
538         /* default light */
539         {
540                 ShaderGraph *graph = new ShaderGraph();
541
542                 EmissionNode *emission = new EmissionNode();
543                 emission->color = make_float3(0.8f, 0.8f, 0.8f);
544                 emission->strength = 0.0f;
545                 graph->add(emission);
546
547                 graph->connect(emission->output("Emission"), graph->output()->input("Surface"));
548
549                 Shader *shader = new Shader();
550                 shader->name = "default_light";
551                 shader->graph = graph;
552                 scene->shaders.push_back(shader);
553                 scene->default_light = shader;
554         }
555
556         /* default background */
557         {
558                 ShaderGraph *graph = new ShaderGraph();
559
560                 Shader *shader = new Shader();
561                 shader->name = "default_background";
562                 shader->graph = graph;
563                 scene->shaders.push_back(shader);
564                 scene->default_background = shader;
565         }
566
567         /* default empty */
568         {
569                 ShaderGraph *graph = new ShaderGraph();
570
571                 Shader *shader = new Shader();
572                 shader->name = "default_empty";
573                 shader->graph = graph;
574                 scene->shaders.push_back(shader);
575                 scene->default_empty = shader;
576         }
577 }
578
579 void ShaderManager::get_requested_graph_features(ShaderGraph *graph,
580                                                  DeviceRequestedFeatures *requested_features)
581 {
582         foreach(ShaderNode *node, graph->nodes) {
583                 requested_features->max_nodes_group = max(requested_features->max_nodes_group,
584                                                           node->get_group());
585                 requested_features->nodes_features |= node->get_feature();
586                 if(node->special_type == SHADER_SPECIAL_TYPE_CLOSURE) {
587                         BsdfNode *bsdf_node = static_cast<BsdfNode*>(node);
588                         if(CLOSURE_IS_VOLUME(bsdf_node->closure)) {
589                                 requested_features->nodes_features |= NODE_FEATURE_VOLUME;
590                         }
591                         else if(CLOSURE_IS_PRINCIPLED(bsdf_node->closure)) {
592                                 requested_features->use_principled = true;
593                         }
594                 }
595                 if(node->has_surface_bssrdf()) {
596                         requested_features->use_subsurface = true;
597                 }
598                 if(node->has_surface_transparent()) {
599                         requested_features->use_transparent = true;
600                 }
601         }
602 }
603
604 void ShaderManager::get_requested_features(Scene *scene,
605                                            DeviceRequestedFeatures *requested_features)
606 {
607         requested_features->max_nodes_group = NODE_GROUP_LEVEL_0;
608         requested_features->nodes_features = 0;
609         for(int i = 0; i < scene->shaders.size(); i++) {
610                 Shader *shader = scene->shaders[i];
611                 /* Gather requested features from all the nodes from the graph nodes. */
612                 get_requested_graph_features(shader->graph, requested_features);
613                 /* Gather requested features from the graph itself. */
614                 if(shader->graph_bump) {
615                         get_requested_graph_features(shader->graph_bump,
616                                                      requested_features);
617                 }
618                 ShaderNode *output_node = shader->graph->output();
619                 if(output_node->input("Displacement")->link != NULL) {
620                         requested_features->nodes_features |= NODE_FEATURE_BUMP;
621                         if(shader->displacement_method == DISPLACE_BOTH && requested_features->experimental) {
622                                 requested_features->nodes_features |= NODE_FEATURE_BUMP_STATE;
623                         }
624                 }
625                 /* On top of volume nodes, also check if we need volume sampling because
626                  * e.g. an Emission node would slip through the NODE_FEATURE_VOLUME check */
627                 if(shader->has_volume)
628                         requested_features->use_volume |= true;
629         }
630 }
631
632 void ShaderManager::free_memory()
633 {
634         beckmann_table.free_memory();
635 }
636
637 CCL_NAMESPACE_END
638