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