Cycles: support loading images from arbitrary OpenColorIO color space
[blender.git] / intern / cycles / render / nodes.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/colorspace.h"
18 #include "render/film.h"
19 #include "render/image.h"
20 #include "render/integrator.h"
21 #include "render/light.h"
22 #include "render/nodes.h"
23 #include "render/scene.h"
24 #include "render/svm.h"
25 #include "kernel/svm/svm_color_util.h"
26 #include "kernel/svm/svm_ramp_util.h"
27 #include "kernel/svm/svm_math_util.h"
28 #include "render/osl.h"
29 #include "render/constant_fold.h"
30
31 #include "util/util_sky_model.h"
32 #include "util/util_foreach.h"
33 #include "util/util_logging.h"
34 #include "util/util_transform.h"
35
36 CCL_NAMESPACE_BEGIN
37
38 /* Texture Mapping */
39
40 #define TEXTURE_MAPPING_DEFINE(TextureNode) \
41   SOCKET_POINT(tex_mapping.translation, "Translation", make_float3(0.0f, 0.0f, 0.0f)); \
42   SOCKET_VECTOR(tex_mapping.rotation, "Rotation", make_float3(0.0f, 0.0f, 0.0f)); \
43   SOCKET_VECTOR(tex_mapping.scale, "Scale", make_float3(1.0f, 1.0f, 1.0f)); \
44 \
45   SOCKET_VECTOR(tex_mapping.min, "Min", make_float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); \
46   SOCKET_VECTOR(tex_mapping.max, "Max", make_float3(FLT_MAX, FLT_MAX, FLT_MAX)); \
47   SOCKET_BOOLEAN(tex_mapping.use_minmax, "Use Min Max", false); \
48 \
49   static NodeEnum mapping_axis_enum; \
50   mapping_axis_enum.insert("none", TextureMapping::NONE); \
51   mapping_axis_enum.insert("x", TextureMapping::X); \
52   mapping_axis_enum.insert("y", TextureMapping::Y); \
53   mapping_axis_enum.insert("z", TextureMapping::Z); \
54   SOCKET_ENUM(tex_mapping.x_mapping, "x_mapping", mapping_axis_enum, TextureMapping::X); \
55   SOCKET_ENUM(tex_mapping.y_mapping, "y_mapping", mapping_axis_enum, TextureMapping::Y); \
56   SOCKET_ENUM(tex_mapping.z_mapping, "z_mapping", mapping_axis_enum, TextureMapping::Z); \
57 \
58   static NodeEnum mapping_type_enum; \
59   mapping_type_enum.insert("point", TextureMapping::POINT); \
60   mapping_type_enum.insert("texture", TextureMapping::TEXTURE); \
61   mapping_type_enum.insert("vector", TextureMapping::VECTOR); \
62   mapping_type_enum.insert("normal", TextureMapping::NORMAL); \
63   SOCKET_ENUM(tex_mapping.type, "Type", mapping_type_enum, TextureMapping::TEXTURE); \
64 \
65   static NodeEnum mapping_projection_enum; \
66   mapping_projection_enum.insert("flat", TextureMapping::FLAT); \
67   mapping_projection_enum.insert("cube", TextureMapping::CUBE); \
68   mapping_projection_enum.insert("tube", TextureMapping::TUBE); \
69   mapping_projection_enum.insert("sphere", TextureMapping::SPHERE); \
70   SOCKET_ENUM(tex_mapping.projection, "Projection", mapping_projection_enum, TextureMapping::FLAT);
71
72 TextureMapping::TextureMapping()
73 {
74 }
75
76 Transform TextureMapping::compute_transform()
77 {
78   Transform mmat = transform_scale(make_float3(0.0f, 0.0f, 0.0f));
79
80   if (x_mapping != NONE)
81     mmat[0][x_mapping - 1] = 1.0f;
82   if (y_mapping != NONE)
83     mmat[1][y_mapping - 1] = 1.0f;
84   if (z_mapping != NONE)
85     mmat[2][z_mapping - 1] = 1.0f;
86
87   float3 scale_clamped = scale;
88
89   if (type == TEXTURE || type == NORMAL) {
90     /* keep matrix invertible */
91     if (fabsf(scale.x) < 1e-5f)
92       scale_clamped.x = signf(scale.x) * 1e-5f;
93     if (fabsf(scale.y) < 1e-5f)
94       scale_clamped.y = signf(scale.y) * 1e-5f;
95     if (fabsf(scale.z) < 1e-5f)
96       scale_clamped.z = signf(scale.z) * 1e-5f;
97   }
98
99   Transform smat = transform_scale(scale_clamped);
100   Transform rmat = transform_euler(rotation);
101   Transform tmat = transform_translate(translation);
102
103   Transform mat;
104
105   switch (type) {
106     case TEXTURE:
107       /* inverse transform on texture coordinate gives
108        * forward transform on texture */
109       mat = tmat * rmat * smat;
110       mat = transform_inverse(mat);
111       break;
112     case POINT:
113       /* full transform */
114       mat = tmat * rmat * smat;
115       break;
116     case VECTOR:
117       /* no translation for vectors */
118       mat = rmat * smat;
119       break;
120     case NORMAL:
121       /* no translation for normals, and inverse transpose */
122       mat = rmat * smat;
123       mat = transform_transposed_inverse(mat);
124       break;
125   }
126
127   /* projection last */
128   mat = mat * mmat;
129
130   return mat;
131 }
132
133 bool TextureMapping::skip()
134 {
135   if (translation != make_float3(0.0f, 0.0f, 0.0f))
136     return false;
137   if (rotation != make_float3(0.0f, 0.0f, 0.0f))
138     return false;
139   if (scale != make_float3(1.0f, 1.0f, 1.0f))
140     return false;
141
142   if (x_mapping != X || y_mapping != Y || z_mapping != Z)
143     return false;
144   if (use_minmax)
145     return false;
146
147   return true;
148 }
149
150 void TextureMapping::compile(SVMCompiler &compiler, int offset_in, int offset_out)
151 {
152   compiler.add_node(NODE_MAPPING, offset_in, offset_out);
153
154   Transform tfm = compute_transform();
155   compiler.add_node(tfm.x);
156   compiler.add_node(tfm.y);
157   compiler.add_node(tfm.z);
158
159   if (use_minmax) {
160     compiler.add_node(NODE_MIN_MAX, offset_out, offset_out);
161     compiler.add_node(float3_to_float4(min));
162     compiler.add_node(float3_to_float4(max));
163   }
164
165   if (type == NORMAL) {
166     compiler.add_node(NODE_VECTOR_MATH, NODE_VECTOR_MATH_NORMALIZE, offset_out, offset_out);
167     compiler.add_node(NODE_VECTOR_MATH, SVM_STACK_INVALID, offset_out);
168   }
169 }
170
171 /* Convenience function for texture nodes, allocating stack space to output
172  * a modified vector and returning its offset */
173 int TextureMapping::compile_begin(SVMCompiler &compiler, ShaderInput *vector_in)
174 {
175   if (!skip()) {
176     int offset_in = compiler.stack_assign(vector_in);
177     int offset_out = compiler.stack_find_offset(SocketType::VECTOR);
178
179     compile(compiler, offset_in, offset_out);
180
181     return offset_out;
182   }
183
184   return compiler.stack_assign(vector_in);
185 }
186
187 void TextureMapping::compile_end(SVMCompiler &compiler, ShaderInput *vector_in, int vector_offset)
188 {
189   if (!skip()) {
190     compiler.stack_clear_offset(vector_in->type(), vector_offset);
191   }
192 }
193
194 void TextureMapping::compile(OSLCompiler &compiler)
195 {
196   if (!skip()) {
197     compiler.parameter("mapping", compute_transform());
198     compiler.parameter("use_mapping", 1);
199   }
200 }
201
202 /* Image Texture */
203
204 NODE_DEFINE(ImageTextureNode)
205 {
206   NodeType *type = NodeType::add("image_texture", create, NodeType::SHADER);
207
208   TEXTURE_MAPPING_DEFINE(ImageTextureNode);
209
210   SOCKET_STRING(filename, "Filename", ustring());
211   SOCKET_STRING(colorspace, "Colorspace", u_colorspace_auto);
212
213   SOCKET_BOOLEAN(use_alpha, "Use Alpha", true);
214
215   static NodeEnum interpolation_enum;
216   interpolation_enum.insert("closest", INTERPOLATION_CLOSEST);
217   interpolation_enum.insert("linear", INTERPOLATION_LINEAR);
218   interpolation_enum.insert("cubic", INTERPOLATION_CUBIC);
219   interpolation_enum.insert("smart", INTERPOLATION_SMART);
220   SOCKET_ENUM(interpolation, "Interpolation", interpolation_enum, INTERPOLATION_LINEAR);
221
222   static NodeEnum extension_enum;
223   extension_enum.insert("periodic", EXTENSION_REPEAT);
224   extension_enum.insert("clamp", EXTENSION_EXTEND);
225   extension_enum.insert("black", EXTENSION_CLIP);
226   SOCKET_ENUM(extension, "Extension", extension_enum, EXTENSION_REPEAT);
227
228   static NodeEnum projection_enum;
229   projection_enum.insert("flat", NODE_IMAGE_PROJ_FLAT);
230   projection_enum.insert("box", NODE_IMAGE_PROJ_BOX);
231   projection_enum.insert("sphere", NODE_IMAGE_PROJ_SPHERE);
232   projection_enum.insert("tube", NODE_IMAGE_PROJ_TUBE);
233   SOCKET_ENUM(projection, "Projection", projection_enum, NODE_IMAGE_PROJ_FLAT);
234
235   SOCKET_FLOAT(projection_blend, "Projection Blend", 0.0f);
236
237   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_UV);
238
239   SOCKET_OUT_COLOR(color, "Color");
240   SOCKET_OUT_FLOAT(alpha, "Alpha");
241
242   return type;
243 }
244
245 ImageTextureNode::ImageTextureNode() : ImageSlotTextureNode(node_type)
246 {
247   image_manager = NULL;
248   slot = -1;
249   is_float = -1;
250   compress_as_srgb = false;
251   colorspace = u_colorspace_raw;
252   builtin_data = NULL;
253   animated = false;
254 }
255
256 ImageTextureNode::~ImageTextureNode()
257 {
258   if (image_manager) {
259     image_manager->remove_image(
260         filename.string(), builtin_data, interpolation, extension, use_alpha, colorspace);
261   }
262 }
263
264 ShaderNode *ImageTextureNode::clone() const
265 {
266   ImageTextureNode *node = new ImageTextureNode(*this);
267   node->image_manager = NULL;
268   node->slot = -1;
269   node->is_float = -1;
270   node->compress_as_srgb = false;
271   node->colorspace = u_colorspace_raw;
272   return node;
273 }
274
275 void ImageTextureNode::attributes(Shader *shader, AttributeRequestSet *attributes)
276 {
277 #ifdef WITH_PTEX
278   /* todo: avoid loading other texture coordinates when using ptex,
279    * and hide texture coordinate socket in the UI */
280   if (shader->has_surface && string_endswith(filename, ".ptx")) {
281     /* ptex */
282     attributes->add(ATTR_STD_PTEX_FACE_ID);
283     attributes->add(ATTR_STD_PTEX_UV);
284   }
285 #endif
286
287   ShaderNode::attributes(shader, attributes);
288 }
289
290 void ImageTextureNode::compile(SVMCompiler &compiler)
291 {
292   ShaderInput *vector_in = input("Vector");
293   ShaderOutput *color_out = output("Color");
294   ShaderOutput *alpha_out = output("Alpha");
295
296   image_manager = compiler.image_manager;
297   if (is_float == -1) {
298     ImageMetaData metadata;
299     slot = image_manager->add_image(filename.string(),
300                                     builtin_data,
301                                     animated,
302                                     0,
303                                     interpolation,
304                                     extension,
305                                     use_alpha,
306                                     colorspace,
307                                     metadata);
308     is_float = metadata.is_float;
309     compress_as_srgb = metadata.compress_as_srgb;
310     colorspace = metadata.colorspace;
311   }
312
313   if (slot != -1) {
314     int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
315
316     if (projection != NODE_IMAGE_PROJ_BOX) {
317       compiler.add_node(NODE_TEX_IMAGE,
318                         slot,
319                         compiler.encode_uchar4(vector_offset,
320                                                compiler.stack_assign_if_linked(color_out),
321                                                compiler.stack_assign_if_linked(alpha_out),
322                                                compress_as_srgb),
323                         projection);
324     }
325     else {
326       compiler.add_node(NODE_TEX_IMAGE_BOX,
327                         slot,
328                         compiler.encode_uchar4(vector_offset,
329                                                compiler.stack_assign_if_linked(color_out),
330                                                compiler.stack_assign_if_linked(alpha_out),
331                                                compress_as_srgb),
332                         __float_as_int(projection_blend));
333     }
334
335     tex_mapping.compile_end(compiler, vector_in, vector_offset);
336   }
337   else {
338     /* image not found */
339     if (!color_out->links.empty()) {
340       compiler.add_node(NODE_VALUE_V, compiler.stack_assign(color_out));
341       compiler.add_node(
342           NODE_VALUE_V,
343           make_float3(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B));
344     }
345     if (!alpha_out->links.empty())
346       compiler.add_node(
347           NODE_VALUE_F, __float_as_int(TEX_IMAGE_MISSING_A), compiler.stack_assign(alpha_out));
348   }
349 }
350
351 void ImageTextureNode::compile(OSLCompiler &compiler)
352 {
353   ShaderOutput *alpha_out = output("Alpha");
354
355   tex_mapping.compile(compiler);
356
357   image_manager = compiler.image_manager;
358   if (is_float == -1) {
359     ImageMetaData metadata;
360     if (builtin_data == NULL) {
361       image_manager->get_image_metadata(filename.string(), NULL, colorspace, metadata);
362     }
363     else {
364       slot = image_manager->add_image(filename.string(),
365                                       builtin_data,
366                                       animated,
367                                       0,
368                                       interpolation,
369                                       extension,
370                                       use_alpha,
371                                       colorspace,
372                                       metadata);
373     }
374     is_float = metadata.is_float;
375     compress_as_srgb = metadata.compress_as_srgb;
376     colorspace = metadata.colorspace;
377   }
378
379   if (slot == -1) {
380     compiler.parameter_texture("filename", filename, colorspace);
381   }
382   else {
383     compiler.parameter_texture("filename", slot);
384   }
385
386   compiler.parameter("color_space", (compress_as_srgb) ? "sRGB" : "linear");
387   compiler.parameter(this, "projection");
388   compiler.parameter(this, "projection_blend");
389   compiler.parameter("is_float", is_float);
390   compiler.parameter("use_alpha", !alpha_out->links.empty());
391   compiler.parameter(this, "interpolation");
392   compiler.parameter(this, "extension");
393
394   compiler.add(this, "node_image_texture");
395 }
396
397 /* Environment Texture */
398
399 NODE_DEFINE(EnvironmentTextureNode)
400 {
401   NodeType *type = NodeType::add("environment_texture", create, NodeType::SHADER);
402
403   TEXTURE_MAPPING_DEFINE(EnvironmentTextureNode);
404
405   SOCKET_STRING(filename, "Filename", ustring());
406   SOCKET_STRING(colorspace, "Colorspace", u_colorspace_auto);
407
408   SOCKET_BOOLEAN(use_alpha, "Use Alpha", true);
409
410   static NodeEnum interpolation_enum;
411   interpolation_enum.insert("closest", INTERPOLATION_CLOSEST);
412   interpolation_enum.insert("linear", INTERPOLATION_LINEAR);
413   interpolation_enum.insert("cubic", INTERPOLATION_CUBIC);
414   interpolation_enum.insert("smart", INTERPOLATION_SMART);
415   SOCKET_ENUM(interpolation, "Interpolation", interpolation_enum, INTERPOLATION_LINEAR);
416
417   static NodeEnum projection_enum;
418   projection_enum.insert("equirectangular", NODE_ENVIRONMENT_EQUIRECTANGULAR);
419   projection_enum.insert("mirror_ball", NODE_ENVIRONMENT_MIRROR_BALL);
420   SOCKET_ENUM(projection, "Projection", projection_enum, NODE_ENVIRONMENT_EQUIRECTANGULAR);
421
422   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_POSITION);
423
424   SOCKET_OUT_COLOR(color, "Color");
425   SOCKET_OUT_FLOAT(alpha, "Alpha");
426
427   return type;
428 }
429
430 EnvironmentTextureNode::EnvironmentTextureNode() : ImageSlotTextureNode(node_type)
431 {
432   image_manager = NULL;
433   slot = -1;
434   is_float = -1;
435   compress_as_srgb = false;
436   colorspace = u_colorspace_raw;
437   builtin_data = NULL;
438   animated = false;
439 }
440
441 EnvironmentTextureNode::~EnvironmentTextureNode()
442 {
443   if (image_manager) {
444     image_manager->remove_image(
445         filename.string(), builtin_data, interpolation, EXTENSION_REPEAT, use_alpha, colorspace);
446   }
447 }
448
449 ShaderNode *EnvironmentTextureNode::clone() const
450 {
451   EnvironmentTextureNode *node = new EnvironmentTextureNode(*this);
452   node->image_manager = NULL;
453   node->slot = -1;
454   node->is_float = -1;
455   node->compress_as_srgb = false;
456   node->colorspace = u_colorspace_raw;
457   return node;
458 }
459
460 void EnvironmentTextureNode::attributes(Shader *shader, AttributeRequestSet *attributes)
461 {
462 #ifdef WITH_PTEX
463   if (shader->has_surface && string_endswith(filename, ".ptx")) {
464     /* ptex */
465     attributes->add(ATTR_STD_PTEX_FACE_ID);
466     attributes->add(ATTR_STD_PTEX_UV);
467   }
468 #endif
469
470   ShaderNode::attributes(shader, attributes);
471 }
472
473 void EnvironmentTextureNode::compile(SVMCompiler &compiler)
474 {
475   ShaderInput *vector_in = input("Vector");
476   ShaderOutput *color_out = output("Color");
477   ShaderOutput *alpha_out = output("Alpha");
478
479   image_manager = compiler.image_manager;
480   if (slot == -1) {
481     ImageMetaData metadata;
482     slot = image_manager->add_image(filename.string(),
483                                     builtin_data,
484                                     animated,
485                                     0,
486                                     interpolation,
487                                     EXTENSION_REPEAT,
488                                     use_alpha,
489                                     colorspace,
490                                     metadata);
491     is_float = metadata.is_float;
492     compress_as_srgb = metadata.compress_as_srgb;
493     colorspace = metadata.colorspace;
494   }
495
496   if (slot != -1) {
497     int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
498
499     compiler.add_node(NODE_TEX_ENVIRONMENT,
500                       slot,
501                       compiler.encode_uchar4(vector_offset,
502                                              compiler.stack_assign_if_linked(color_out),
503                                              compiler.stack_assign_if_linked(alpha_out),
504                                              compress_as_srgb),
505                       projection);
506
507     tex_mapping.compile_end(compiler, vector_in, vector_offset);
508   }
509   else {
510     /* image not found */
511     if (!color_out->links.empty()) {
512       compiler.add_node(NODE_VALUE_V, compiler.stack_assign(color_out));
513       compiler.add_node(
514           NODE_VALUE_V,
515           make_float3(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B));
516     }
517     if (!alpha_out->links.empty())
518       compiler.add_node(
519           NODE_VALUE_F, __float_as_int(TEX_IMAGE_MISSING_A), compiler.stack_assign(alpha_out));
520   }
521 }
522
523 void EnvironmentTextureNode::compile(OSLCompiler &compiler)
524 {
525   ShaderOutput *alpha_out = output("Alpha");
526
527   tex_mapping.compile(compiler);
528
529   /* See comments in ImageTextureNode::compile about support
530    * of builtin images.
531    */
532   image_manager = compiler.image_manager;
533   if (is_float == -1) {
534     ImageMetaData metadata;
535     if (builtin_data == NULL) {
536       image_manager->get_image_metadata(filename.string(), NULL, colorspace, metadata);
537     }
538     else {
539       slot = image_manager->add_image(filename.string(),
540                                       builtin_data,
541                                       animated,
542                                       0,
543                                       interpolation,
544                                       EXTENSION_REPEAT,
545                                       use_alpha,
546                                       colorspace,
547                                       metadata);
548     }
549     is_float = metadata.is_float;
550     compress_as_srgb = metadata.compress_as_srgb;
551     colorspace = metadata.colorspace;
552   }
553
554   if (slot == -1) {
555     compiler.parameter_texture("filename", filename, colorspace);
556   }
557   else {
558     compiler.parameter_texture("filename", slot);
559   }
560
561   compiler.parameter(this, "projection");
562   compiler.parameter("color_space", (compress_as_srgb) ? "sRGB" : "linear");
563   compiler.parameter(this, "interpolation");
564   compiler.parameter("is_float", is_float);
565   compiler.parameter("use_alpha", !alpha_out->links.empty());
566   compiler.add(this, "node_environment_texture");
567 }
568
569 /* Sky Texture */
570
571 static float2 sky_spherical_coordinates(float3 dir)
572 {
573   return make_float2(acosf(dir.z), atan2f(dir.x, dir.y));
574 }
575
576 typedef struct SunSky {
577   /* sun direction in spherical and cartesian */
578   float theta, phi;
579
580   /* Parameter */
581   float radiance_x, radiance_y, radiance_z;
582   float config_x[9], config_y[9], config_z[9];
583 } SunSky;
584
585 /* Preetham model */
586 static float sky_perez_function(float lam[6], float theta, float gamma)
587 {
588   return (1.0f + lam[0] * expf(lam[1] / cosf(theta))) *
589          (1.0f + lam[2] * expf(lam[3] * gamma) + lam[4] * cosf(gamma) * cosf(gamma));
590 }
591
592 static void sky_texture_precompute_old(SunSky *sunsky, float3 dir, float turbidity)
593 {
594   /*
595    * We re-use the SunSky struct of the new model, to avoid extra variables
596    * zenith_Y/x/y is now radiance_x/y/z
597    * perez_Y/x/y is now config_x/y/z
598    */
599
600   float2 spherical = sky_spherical_coordinates(dir);
601   float theta = spherical.x;
602   float phi = spherical.y;
603
604   sunsky->theta = theta;
605   sunsky->phi = phi;
606
607   float theta2 = theta * theta;
608   float theta3 = theta2 * theta;
609   float T = turbidity;
610   float T2 = T * T;
611
612   float chi = (4.0f / 9.0f - T / 120.0f) * (M_PI_F - 2.0f * theta);
613   sunsky->radiance_x = (4.0453f * T - 4.9710f) * tanf(chi) - 0.2155f * T + 2.4192f;
614   sunsky->radiance_x *= 0.06f;
615
616   sunsky->radiance_y = (0.00166f * theta3 - 0.00375f * theta2 + 0.00209f * theta) * T2 +
617                        (-0.02903f * theta3 + 0.06377f * theta2 - 0.03202f * theta + 0.00394f) * T +
618                        (0.11693f * theta3 - 0.21196f * theta2 + 0.06052f * theta + 0.25886f);
619
620   sunsky->radiance_z = (0.00275f * theta3 - 0.00610f * theta2 + 0.00317f * theta) * T2 +
621                        (-0.04214f * theta3 + 0.08970f * theta2 - 0.04153f * theta + 0.00516f) * T +
622                        (0.15346f * theta3 - 0.26756f * theta2 + 0.06670f * theta + 0.26688f);
623
624   sunsky->config_x[0] = (0.1787f * T - 1.4630f);
625   sunsky->config_x[1] = (-0.3554f * T + 0.4275f);
626   sunsky->config_x[2] = (-0.0227f * T + 5.3251f);
627   sunsky->config_x[3] = (0.1206f * T - 2.5771f);
628   sunsky->config_x[4] = (-0.0670f * T + 0.3703f);
629
630   sunsky->config_y[0] = (-0.0193f * T - 0.2592f);
631   sunsky->config_y[1] = (-0.0665f * T + 0.0008f);
632   sunsky->config_y[2] = (-0.0004f * T + 0.2125f);
633   sunsky->config_y[3] = (-0.0641f * T - 0.8989f);
634   sunsky->config_y[4] = (-0.0033f * T + 0.0452f);
635
636   sunsky->config_z[0] = (-0.0167f * T - 0.2608f);
637   sunsky->config_z[1] = (-0.0950f * T + 0.0092f);
638   sunsky->config_z[2] = (-0.0079f * T + 0.2102f);
639   sunsky->config_z[3] = (-0.0441f * T - 1.6537f);
640   sunsky->config_z[4] = (-0.0109f * T + 0.0529f);
641
642   /* unused for old sky model */
643   for (int i = 5; i < 9; i++) {
644     sunsky->config_x[i] = 0.0f;
645     sunsky->config_y[i] = 0.0f;
646     sunsky->config_z[i] = 0.0f;
647   }
648
649   sunsky->radiance_x /= sky_perez_function(sunsky->config_x, 0, theta);
650   sunsky->radiance_y /= sky_perez_function(sunsky->config_y, 0, theta);
651   sunsky->radiance_z /= sky_perez_function(sunsky->config_z, 0, theta);
652 }
653
654 /* Hosek / Wilkie */
655 static void sky_texture_precompute_new(SunSky *sunsky,
656                                        float3 dir,
657                                        float turbidity,
658                                        float ground_albedo)
659 {
660   /* Calculate Sun Direction and save coordinates */
661   float2 spherical = sky_spherical_coordinates(dir);
662   float theta = spherical.x;
663   float phi = spherical.y;
664
665   /* Clamp Turbidity */
666   turbidity = clamp(turbidity, 0.0f, 10.0f);
667
668   /* Clamp to Horizon */
669   theta = clamp(theta, 0.0f, M_PI_2_F);
670
671   sunsky->theta = theta;
672   sunsky->phi = phi;
673
674   float solarElevation = M_PI_2_F - theta;
675
676   /* Initialize Sky Model */
677   ArHosekSkyModelState *sky_state;
678   sky_state = arhosek_xyz_skymodelstate_alloc_init(
679       (double)turbidity, (double)ground_albedo, (double)solarElevation);
680
681   /* Copy values from sky_state to SunSky */
682   for (int i = 0; i < 9; ++i) {
683     sunsky->config_x[i] = (float)sky_state->configs[0][i];
684     sunsky->config_y[i] = (float)sky_state->configs[1][i];
685     sunsky->config_z[i] = (float)sky_state->configs[2][i];
686   }
687   sunsky->radiance_x = (float)sky_state->radiances[0];
688   sunsky->radiance_y = (float)sky_state->radiances[1];
689   sunsky->radiance_z = (float)sky_state->radiances[2];
690
691   /* Free sky_state */
692   arhosekskymodelstate_free(sky_state);
693 }
694
695 NODE_DEFINE(SkyTextureNode)
696 {
697   NodeType *type = NodeType::add("sky_texture", create, NodeType::SHADER);
698
699   TEXTURE_MAPPING_DEFINE(SkyTextureNode);
700
701   static NodeEnum type_enum;
702   type_enum.insert("preetham", NODE_SKY_OLD);
703   type_enum.insert("hosek_wilkie", NODE_SKY_NEW);
704   SOCKET_ENUM(type, "Type", type_enum, NODE_SKY_NEW);
705
706   SOCKET_VECTOR(sun_direction, "Sun Direction", make_float3(0.0f, 0.0f, 1.0f));
707   SOCKET_FLOAT(turbidity, "Turbidity", 2.2f);
708   SOCKET_FLOAT(ground_albedo, "Ground Albedo", 0.3f);
709
710   SOCKET_IN_POINT(
711       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
712
713   SOCKET_OUT_COLOR(color, "Color");
714
715   return type;
716 }
717
718 SkyTextureNode::SkyTextureNode() : TextureNode(node_type)
719 {
720 }
721
722 void SkyTextureNode::compile(SVMCompiler &compiler)
723 {
724   ShaderInput *vector_in = input("Vector");
725   ShaderOutput *color_out = output("Color");
726
727   SunSky sunsky;
728   if (type == NODE_SKY_OLD)
729     sky_texture_precompute_old(&sunsky, sun_direction, turbidity);
730   else if (type == NODE_SKY_NEW)
731     sky_texture_precompute_new(&sunsky, sun_direction, turbidity, ground_albedo);
732   else
733     assert(false);
734
735   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
736
737   compiler.stack_assign(color_out);
738   compiler.add_node(NODE_TEX_SKY, vector_offset, compiler.stack_assign(color_out), type);
739   compiler.add_node(__float_as_uint(sunsky.phi),
740                     __float_as_uint(sunsky.theta),
741                     __float_as_uint(sunsky.radiance_x),
742                     __float_as_uint(sunsky.radiance_y));
743   compiler.add_node(__float_as_uint(sunsky.radiance_z),
744                     __float_as_uint(sunsky.config_x[0]),
745                     __float_as_uint(sunsky.config_x[1]),
746                     __float_as_uint(sunsky.config_x[2]));
747   compiler.add_node(__float_as_uint(sunsky.config_x[3]),
748                     __float_as_uint(sunsky.config_x[4]),
749                     __float_as_uint(sunsky.config_x[5]),
750                     __float_as_uint(sunsky.config_x[6]));
751   compiler.add_node(__float_as_uint(sunsky.config_x[7]),
752                     __float_as_uint(sunsky.config_x[8]),
753                     __float_as_uint(sunsky.config_y[0]),
754                     __float_as_uint(sunsky.config_y[1]));
755   compiler.add_node(__float_as_uint(sunsky.config_y[2]),
756                     __float_as_uint(sunsky.config_y[3]),
757                     __float_as_uint(sunsky.config_y[4]),
758                     __float_as_uint(sunsky.config_y[5]));
759   compiler.add_node(__float_as_uint(sunsky.config_y[6]),
760                     __float_as_uint(sunsky.config_y[7]),
761                     __float_as_uint(sunsky.config_y[8]),
762                     __float_as_uint(sunsky.config_z[0]));
763   compiler.add_node(__float_as_uint(sunsky.config_z[1]),
764                     __float_as_uint(sunsky.config_z[2]),
765                     __float_as_uint(sunsky.config_z[3]),
766                     __float_as_uint(sunsky.config_z[4]));
767   compiler.add_node(__float_as_uint(sunsky.config_z[5]),
768                     __float_as_uint(sunsky.config_z[6]),
769                     __float_as_uint(sunsky.config_z[7]),
770                     __float_as_uint(sunsky.config_z[8]));
771
772   tex_mapping.compile_end(compiler, vector_in, vector_offset);
773 }
774
775 void SkyTextureNode::compile(OSLCompiler &compiler)
776 {
777   tex_mapping.compile(compiler);
778
779   SunSky sunsky;
780   if (type == NODE_SKY_OLD)
781     sky_texture_precompute_old(&sunsky, sun_direction, turbidity);
782   else if (type == NODE_SKY_NEW)
783     sky_texture_precompute_new(&sunsky, sun_direction, turbidity, ground_albedo);
784   else
785     assert(false);
786
787   compiler.parameter(this, "type");
788   compiler.parameter("theta", sunsky.theta);
789   compiler.parameter("phi", sunsky.phi);
790   compiler.parameter_color("radiance",
791                            make_float3(sunsky.radiance_x, sunsky.radiance_y, sunsky.radiance_z));
792   compiler.parameter_array("config_x", sunsky.config_x, 9);
793   compiler.parameter_array("config_y", sunsky.config_y, 9);
794   compiler.parameter_array("config_z", sunsky.config_z, 9);
795   compiler.add(this, "node_sky_texture");
796 }
797
798 /* Gradient Texture */
799
800 NODE_DEFINE(GradientTextureNode)
801 {
802   NodeType *type = NodeType::add("gradient_texture", create, NodeType::SHADER);
803
804   TEXTURE_MAPPING_DEFINE(GradientTextureNode);
805
806   static NodeEnum type_enum;
807   type_enum.insert("linear", NODE_BLEND_LINEAR);
808   type_enum.insert("quadratic", NODE_BLEND_QUADRATIC);
809   type_enum.insert("easing", NODE_BLEND_EASING);
810   type_enum.insert("diagonal", NODE_BLEND_DIAGONAL);
811   type_enum.insert("radial", NODE_BLEND_RADIAL);
812   type_enum.insert("quadratic_sphere", NODE_BLEND_QUADRATIC_SPHERE);
813   type_enum.insert("spherical", NODE_BLEND_SPHERICAL);
814   SOCKET_ENUM(type, "Type", type_enum, NODE_BLEND_LINEAR);
815
816   SOCKET_IN_POINT(
817       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
818
819   SOCKET_OUT_COLOR(color, "Color");
820   SOCKET_OUT_FLOAT(fac, "Fac");
821
822   return type;
823 }
824
825 GradientTextureNode::GradientTextureNode() : TextureNode(node_type)
826 {
827 }
828
829 void GradientTextureNode::compile(SVMCompiler &compiler)
830 {
831   ShaderInput *vector_in = input("Vector");
832   ShaderOutput *color_out = output("Color");
833   ShaderOutput *fac_out = output("Fac");
834
835   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
836
837   compiler.add_node(NODE_TEX_GRADIENT,
838                     compiler.encode_uchar4(type,
839                                            vector_offset,
840                                            compiler.stack_assign_if_linked(fac_out),
841                                            compiler.stack_assign_if_linked(color_out)));
842
843   tex_mapping.compile_end(compiler, vector_in, vector_offset);
844 }
845
846 void GradientTextureNode::compile(OSLCompiler &compiler)
847 {
848   tex_mapping.compile(compiler);
849
850   compiler.parameter(this, "type");
851   compiler.add(this, "node_gradient_texture");
852 }
853
854 /* Noise Texture */
855
856 NODE_DEFINE(NoiseTextureNode)
857 {
858   NodeType *type = NodeType::add("noise_texture", create, NodeType::SHADER);
859
860   TEXTURE_MAPPING_DEFINE(NoiseTextureNode);
861
862   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
863   SOCKET_IN_FLOAT(detail, "Detail", 2.0f);
864   SOCKET_IN_FLOAT(distortion, "Distortion", 0.0f);
865   SOCKET_IN_POINT(
866       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
867
868   SOCKET_OUT_COLOR(color, "Color");
869   SOCKET_OUT_FLOAT(fac, "Fac");
870
871   return type;
872 }
873
874 NoiseTextureNode::NoiseTextureNode() : TextureNode(node_type)
875 {
876 }
877
878 void NoiseTextureNode::compile(SVMCompiler &compiler)
879 {
880   ShaderInput *distortion_in = input("Distortion");
881   ShaderInput *detail_in = input("Detail");
882   ShaderInput *scale_in = input("Scale");
883   ShaderInput *vector_in = input("Vector");
884   ShaderOutput *color_out = output("Color");
885   ShaderOutput *fac_out = output("Fac");
886
887   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
888
889   compiler.add_node(NODE_TEX_NOISE,
890                     compiler.encode_uchar4(vector_offset,
891                                            compiler.stack_assign_if_linked(scale_in),
892                                            compiler.stack_assign_if_linked(detail_in),
893                                            compiler.stack_assign_if_linked(distortion_in)),
894                     compiler.encode_uchar4(compiler.stack_assign_if_linked(color_out),
895                                            compiler.stack_assign_if_linked(fac_out)));
896   compiler.add_node(__float_as_int(scale), __float_as_int(detail), __float_as_int(distortion));
897
898   tex_mapping.compile_end(compiler, vector_in, vector_offset);
899 }
900
901 void NoiseTextureNode::compile(OSLCompiler &compiler)
902 {
903   tex_mapping.compile(compiler);
904
905   compiler.add(this, "node_noise_texture");
906 }
907
908 /* Voronoi Texture */
909
910 NODE_DEFINE(VoronoiTextureNode)
911 {
912   NodeType *type = NodeType::add("voronoi_texture", create, NodeType::SHADER);
913
914   TEXTURE_MAPPING_DEFINE(VoronoiTextureNode);
915
916   static NodeEnum coloring_enum;
917   coloring_enum.insert("intensity", NODE_VORONOI_INTENSITY);
918   coloring_enum.insert("cells", NODE_VORONOI_CELLS);
919   SOCKET_ENUM(coloring, "Coloring", coloring_enum, NODE_VORONOI_INTENSITY);
920
921   static NodeEnum metric;
922   metric.insert("distance", NODE_VORONOI_DISTANCE);
923   metric.insert("manhattan", NODE_VORONOI_MANHATTAN);
924   metric.insert("chebychev", NODE_VORONOI_CHEBYCHEV);
925   metric.insert("minkowski", NODE_VORONOI_MINKOWSKI);
926   SOCKET_ENUM(metric, "Distance Metric", metric, NODE_VORONOI_INTENSITY);
927
928   static NodeEnum feature_enum;
929   feature_enum.insert("F1", NODE_VORONOI_F1);
930   feature_enum.insert("F2", NODE_VORONOI_F2);
931   feature_enum.insert("F3", NODE_VORONOI_F3);
932   feature_enum.insert("F4", NODE_VORONOI_F4);
933   feature_enum.insert("F2F1", NODE_VORONOI_F2F1);
934   SOCKET_ENUM(feature, "Feature", feature_enum, NODE_VORONOI_INTENSITY);
935
936   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
937   SOCKET_IN_FLOAT(exponent, "Exponent", 0.5f);
938   SOCKET_IN_POINT(
939       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
940
941   SOCKET_OUT_COLOR(color, "Color");
942   SOCKET_OUT_FLOAT(fac, "Fac");
943
944   return type;
945 }
946
947 VoronoiTextureNode::VoronoiTextureNode() : TextureNode(node_type)
948 {
949 }
950
951 void VoronoiTextureNode::compile(SVMCompiler &compiler)
952 {
953   ShaderInput *scale_in = input("Scale");
954   ShaderInput *vector_in = input("Vector");
955   ShaderInput *exponent_in = input("Exponent");
956   ShaderOutput *color_out = output("Color");
957   ShaderOutput *fac_out = output("Fac");
958
959   if (vector_in->link)
960     compiler.stack_assign(vector_in);
961   if (scale_in->link)
962     compiler.stack_assign(scale_in);
963   if (exponent_in->link)
964     compiler.stack_assign(exponent_in);
965
966   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
967
968   compiler.add_node(NODE_TEX_VORONOI,
969                     compiler.encode_uchar4(vector_offset, coloring, metric, feature),
970                     compiler.encode_uchar4(compiler.stack_assign_if_linked(scale_in),
971                                            compiler.stack_assign_if_linked(exponent_in),
972                                            compiler.stack_assign(fac_out),
973                                            compiler.stack_assign(color_out)));
974   compiler.add_node(__float_as_int(scale), __float_as_int(exponent));
975
976   tex_mapping.compile_end(compiler, vector_in, vector_offset);
977 }
978
979 void VoronoiTextureNode::compile(OSLCompiler &compiler)
980 {
981   tex_mapping.compile(compiler);
982
983   compiler.parameter(this, "coloring");
984   compiler.parameter(this, "metric");
985   compiler.parameter(this, "feature");
986   compiler.add(this, "node_voronoi_texture");
987 }
988
989 /* IES Light */
990
991 NODE_DEFINE(IESLightNode)
992 {
993   NodeType *type = NodeType::add("ies_light", create, NodeType::SHADER);
994
995   TEXTURE_MAPPING_DEFINE(IESLightNode);
996
997   SOCKET_STRING(ies, "IES", ustring());
998   SOCKET_STRING(filename, "File Name", ustring());
999
1000   SOCKET_IN_FLOAT(strength, "Strength", 1.0f);
1001   SOCKET_IN_POINT(
1002       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_NORMAL);
1003
1004   SOCKET_OUT_FLOAT(fac, "Fac");
1005
1006   return type;
1007 }
1008
1009 IESLightNode::IESLightNode() : TextureNode(node_type)
1010 {
1011   light_manager = NULL;
1012   slot = -1;
1013 }
1014
1015 ShaderNode *IESLightNode::clone() const
1016 {
1017   IESLightNode *node = new IESLightNode(*this);
1018
1019   node->light_manager = NULL;
1020   node->slot = -1;
1021
1022   return node;
1023 }
1024
1025 IESLightNode::~IESLightNode()
1026 {
1027   if (light_manager) {
1028     light_manager->remove_ies(slot);
1029   }
1030 }
1031
1032 void IESLightNode::get_slot()
1033 {
1034   assert(light_manager);
1035
1036   if (slot == -1) {
1037     if (ies.empty()) {
1038       slot = light_manager->add_ies_from_file(filename);
1039     }
1040     else {
1041       slot = light_manager->add_ies(ies);
1042     }
1043   }
1044 }
1045
1046 void IESLightNode::compile(SVMCompiler &compiler)
1047 {
1048   light_manager = compiler.light_manager;
1049   get_slot();
1050
1051   ShaderInput *strength_in = input("Strength");
1052   ShaderInput *vector_in = input("Vector");
1053   ShaderOutput *fac_out = output("Fac");
1054
1055   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1056
1057   compiler.add_node(NODE_IES,
1058                     compiler.encode_uchar4(compiler.stack_assign_if_linked(strength_in),
1059                                            vector_offset,
1060                                            compiler.stack_assign(fac_out),
1061                                            0),
1062                     slot,
1063                     __float_as_int(strength));
1064
1065   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1066 }
1067
1068 void IESLightNode::compile(OSLCompiler &compiler)
1069 {
1070   light_manager = compiler.light_manager;
1071   get_slot();
1072
1073   tex_mapping.compile(compiler);
1074
1075   compiler.parameter_texture_ies("filename", slot);
1076   compiler.add(this, "node_ies_light");
1077 }
1078
1079 /* Musgrave Texture */
1080
1081 NODE_DEFINE(MusgraveTextureNode)
1082 {
1083   NodeType *type = NodeType::add("musgrave_texture", create, NodeType::SHADER);
1084
1085   TEXTURE_MAPPING_DEFINE(MusgraveTextureNode);
1086
1087   static NodeEnum type_enum;
1088   type_enum.insert("multifractal", NODE_MUSGRAVE_MULTIFRACTAL);
1089   type_enum.insert("fBM", NODE_MUSGRAVE_FBM);
1090   type_enum.insert("hybrid_multifractal", NODE_MUSGRAVE_HYBRID_MULTIFRACTAL);
1091   type_enum.insert("ridged_multifractal", NODE_MUSGRAVE_RIDGED_MULTIFRACTAL);
1092   type_enum.insert("hetero_terrain", NODE_MUSGRAVE_HETERO_TERRAIN);
1093   SOCKET_ENUM(type, "Type", type_enum, NODE_MUSGRAVE_FBM);
1094
1095   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
1096   SOCKET_IN_FLOAT(detail, "Detail", 2.0f);
1097   SOCKET_IN_FLOAT(dimension, "Dimension", 2.0f);
1098   SOCKET_IN_FLOAT(lacunarity, "Lacunarity", 1.0f);
1099   SOCKET_IN_FLOAT(offset, "Offset", 0.0f);
1100   SOCKET_IN_FLOAT(gain, "Gain", 1.0f);
1101   SOCKET_IN_POINT(
1102       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1103
1104   SOCKET_OUT_COLOR(color, "Color");
1105   SOCKET_OUT_FLOAT(fac, "Fac");
1106
1107   return type;
1108 }
1109
1110 MusgraveTextureNode::MusgraveTextureNode() : TextureNode(node_type)
1111 {
1112 }
1113
1114 void MusgraveTextureNode::compile(SVMCompiler &compiler)
1115 {
1116   ShaderInput *vector_in = input("Vector");
1117   ShaderInput *scale_in = input("Scale");
1118   ShaderInput *dimension_in = input("Dimension");
1119   ShaderInput *lacunarity_in = input("Lacunarity");
1120   ShaderInput *detail_in = input("Detail");
1121   ShaderInput *offset_in = input("Offset");
1122   ShaderInput *gain_in = input("Gain");
1123   ShaderOutput *fac_out = output("Fac");
1124   ShaderOutput *color_out = output("Color");
1125
1126   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1127
1128   compiler.add_node(NODE_TEX_MUSGRAVE,
1129                     compiler.encode_uchar4(type,
1130                                            vector_offset,
1131                                            compiler.stack_assign_if_linked(color_out),
1132                                            compiler.stack_assign_if_linked(fac_out)),
1133                     compiler.encode_uchar4(compiler.stack_assign_if_linked(dimension_in),
1134                                            compiler.stack_assign_if_linked(lacunarity_in),
1135                                            compiler.stack_assign_if_linked(detail_in),
1136                                            compiler.stack_assign_if_linked(offset_in)),
1137                     compiler.encode_uchar4(compiler.stack_assign_if_linked(gain_in),
1138                                            compiler.stack_assign_if_linked(scale_in)));
1139   compiler.add_node(__float_as_int(dimension),
1140                     __float_as_int(lacunarity),
1141                     __float_as_int(detail),
1142                     __float_as_int(offset));
1143   compiler.add_node(__float_as_int(gain), __float_as_int(scale));
1144
1145   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1146 }
1147
1148 void MusgraveTextureNode::compile(OSLCompiler &compiler)
1149 {
1150   tex_mapping.compile(compiler);
1151
1152   compiler.parameter(this, "type");
1153   compiler.add(this, "node_musgrave_texture");
1154 }
1155
1156 /* Wave Texture */
1157
1158 NODE_DEFINE(WaveTextureNode)
1159 {
1160   NodeType *type = NodeType::add("wave_texture", create, NodeType::SHADER);
1161
1162   TEXTURE_MAPPING_DEFINE(WaveTextureNode);
1163
1164   static NodeEnum type_enum;
1165   type_enum.insert("bands", NODE_WAVE_BANDS);
1166   type_enum.insert("rings", NODE_WAVE_RINGS);
1167   SOCKET_ENUM(type, "Type", type_enum, NODE_WAVE_BANDS);
1168
1169   static NodeEnum profile_enum;
1170   profile_enum.insert("sine", NODE_WAVE_PROFILE_SIN);
1171   profile_enum.insert("saw", NODE_WAVE_PROFILE_SAW);
1172   SOCKET_ENUM(profile, "Profile", profile_enum, NODE_WAVE_PROFILE_SIN);
1173
1174   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
1175   SOCKET_IN_FLOAT(distortion, "Distortion", 0.0f);
1176   SOCKET_IN_FLOAT(detail, "Detail", 2.0f);
1177   SOCKET_IN_FLOAT(detail_scale, "Detail Scale", 0.0f);
1178   SOCKET_IN_POINT(
1179       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1180
1181   SOCKET_OUT_COLOR(color, "Color");
1182   SOCKET_OUT_FLOAT(fac, "Fac");
1183
1184   return type;
1185 }
1186
1187 WaveTextureNode::WaveTextureNode() : TextureNode(node_type)
1188 {
1189 }
1190
1191 void WaveTextureNode::compile(SVMCompiler &compiler)
1192 {
1193   ShaderInput *scale_in = input("Scale");
1194   ShaderInput *distortion_in = input("Distortion");
1195   ShaderInput *dscale_in = input("Detail Scale");
1196   ShaderInput *detail_in = input("Detail");
1197   ShaderInput *vector_in = input("Vector");
1198   ShaderOutput *fac_out = output("Fac");
1199   ShaderOutput *color_out = output("Color");
1200
1201   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1202
1203   compiler.add_node(NODE_TEX_WAVE,
1204                     compiler.encode_uchar4(type,
1205                                            compiler.stack_assign_if_linked(color_out),
1206                                            compiler.stack_assign_if_linked(fac_out),
1207                                            compiler.stack_assign_if_linked(dscale_in)),
1208                     compiler.encode_uchar4(vector_offset,
1209                                            compiler.stack_assign_if_linked(scale_in),
1210                                            compiler.stack_assign_if_linked(detail_in),
1211                                            compiler.stack_assign_if_linked(distortion_in)),
1212                     profile);
1213
1214   compiler.add_node(__float_as_int(scale),
1215                     __float_as_int(detail),
1216                     __float_as_int(distortion),
1217                     __float_as_int(detail_scale));
1218
1219   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1220 }
1221
1222 void WaveTextureNode::compile(OSLCompiler &compiler)
1223 {
1224   tex_mapping.compile(compiler);
1225
1226   compiler.parameter(this, "type");
1227   compiler.parameter(this, "profile");
1228
1229   compiler.add(this, "node_wave_texture");
1230 }
1231
1232 /* Magic Texture */
1233
1234 NODE_DEFINE(MagicTextureNode)
1235 {
1236   NodeType *type = NodeType::add("magic_texture", create, NodeType::SHADER);
1237
1238   TEXTURE_MAPPING_DEFINE(MagicTextureNode);
1239
1240   SOCKET_INT(depth, "Depth", 2);
1241
1242   SOCKET_IN_POINT(
1243       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1244   SOCKET_IN_FLOAT(scale, "Scale", 5.0f);
1245   SOCKET_IN_FLOAT(distortion, "Distortion", 1.0f);
1246
1247   SOCKET_OUT_COLOR(color, "Color");
1248   SOCKET_OUT_FLOAT(fac, "Fac");
1249
1250   return type;
1251 }
1252
1253 MagicTextureNode::MagicTextureNode() : TextureNode(node_type)
1254 {
1255 }
1256
1257 void MagicTextureNode::compile(SVMCompiler &compiler)
1258 {
1259   ShaderInput *vector_in = input("Vector");
1260   ShaderInput *scale_in = input("Scale");
1261   ShaderInput *distortion_in = input("Distortion");
1262   ShaderOutput *color_out = output("Color");
1263   ShaderOutput *fac_out = output("Fac");
1264
1265   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1266
1267   compiler.add_node(NODE_TEX_MAGIC,
1268                     compiler.encode_uchar4(depth,
1269                                            compiler.stack_assign_if_linked(color_out),
1270                                            compiler.stack_assign_if_linked(fac_out)),
1271                     compiler.encode_uchar4(vector_offset,
1272                                            compiler.stack_assign_if_linked(scale_in),
1273                                            compiler.stack_assign_if_linked(distortion_in)));
1274   compiler.add_node(__float_as_int(scale), __float_as_int(distortion));
1275
1276   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1277 }
1278
1279 void MagicTextureNode::compile(OSLCompiler &compiler)
1280 {
1281   tex_mapping.compile(compiler);
1282
1283   compiler.parameter(this, "depth");
1284   compiler.add(this, "node_magic_texture");
1285 }
1286
1287 /* Checker Texture */
1288
1289 NODE_DEFINE(CheckerTextureNode)
1290 {
1291   NodeType *type = NodeType::add("checker_texture", create, NodeType::SHADER);
1292
1293   TEXTURE_MAPPING_DEFINE(CheckerTextureNode);
1294
1295   SOCKET_IN_POINT(
1296       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1297   SOCKET_IN_COLOR(color1, "Color1", make_float3(0.0f, 0.0f, 0.0f));
1298   SOCKET_IN_COLOR(color2, "Color2", make_float3(0.0f, 0.0f, 0.0f));
1299   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
1300
1301   SOCKET_OUT_COLOR(color, "Color");
1302   SOCKET_OUT_FLOAT(fac, "Fac");
1303
1304   return type;
1305 }
1306
1307 CheckerTextureNode::CheckerTextureNode() : TextureNode(node_type)
1308 {
1309 }
1310
1311 void CheckerTextureNode::compile(SVMCompiler &compiler)
1312 {
1313   ShaderInput *vector_in = input("Vector");
1314   ShaderInput *color1_in = input("Color1");
1315   ShaderInput *color2_in = input("Color2");
1316   ShaderInput *scale_in = input("Scale");
1317
1318   ShaderOutput *color_out = output("Color");
1319   ShaderOutput *fac_out = output("Fac");
1320
1321   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1322
1323   compiler.add_node(NODE_TEX_CHECKER,
1324                     compiler.encode_uchar4(vector_offset,
1325                                            compiler.stack_assign(color1_in),
1326                                            compiler.stack_assign(color2_in),
1327                                            compiler.stack_assign_if_linked(scale_in)),
1328                     compiler.encode_uchar4(compiler.stack_assign_if_linked(color_out),
1329                                            compiler.stack_assign_if_linked(fac_out)),
1330                     __float_as_int(scale));
1331
1332   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1333 }
1334
1335 void CheckerTextureNode::compile(OSLCompiler &compiler)
1336 {
1337   tex_mapping.compile(compiler);
1338
1339   compiler.add(this, "node_checker_texture");
1340 }
1341
1342 /* Brick Texture */
1343
1344 NODE_DEFINE(BrickTextureNode)
1345 {
1346   NodeType *type = NodeType::add("brick_texture", create, NodeType::SHADER);
1347
1348   TEXTURE_MAPPING_DEFINE(BrickTextureNode);
1349
1350   SOCKET_FLOAT(offset, "Offset", 0.5f);
1351   SOCKET_INT(offset_frequency, "Offset Frequency", 2);
1352   SOCKET_FLOAT(squash, "Squash", 1.0f);
1353   SOCKET_INT(squash_frequency, "Squash Frequency", 2);
1354
1355   SOCKET_IN_POINT(
1356       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1357
1358   SOCKET_IN_COLOR(color1, "Color1", make_float3(0.0f, 0.0f, 0.0f));
1359   SOCKET_IN_COLOR(color2, "Color2", make_float3(0.0f, 0.0f, 0.0f));
1360   SOCKET_IN_COLOR(mortar, "Mortar", make_float3(0.0f, 0.0f, 0.0f));
1361   SOCKET_IN_FLOAT(scale, "Scale", 5.0f);
1362   SOCKET_IN_FLOAT(mortar_size, "Mortar Size", 0.02f);
1363   SOCKET_IN_FLOAT(mortar_smooth, "Mortar Smooth", 0.0f);
1364   SOCKET_IN_FLOAT(bias, "Bias", 0.0f);
1365   SOCKET_IN_FLOAT(brick_width, "Brick Width", 0.5f);
1366   SOCKET_IN_FLOAT(row_height, "Row Height", 0.25f);
1367
1368   SOCKET_OUT_COLOR(color, "Color");
1369   SOCKET_OUT_FLOAT(fac, "Fac");
1370
1371   return type;
1372 }
1373
1374 BrickTextureNode::BrickTextureNode() : TextureNode(node_type)
1375 {
1376 }
1377
1378 void BrickTextureNode::compile(SVMCompiler &compiler)
1379 {
1380   ShaderInput *vector_in = input("Vector");
1381   ShaderInput *color1_in = input("Color1");
1382   ShaderInput *color2_in = input("Color2");
1383   ShaderInput *mortar_in = input("Mortar");
1384   ShaderInput *scale_in = input("Scale");
1385   ShaderInput *mortar_size_in = input("Mortar Size");
1386   ShaderInput *mortar_smooth_in = input("Mortar Smooth");
1387   ShaderInput *bias_in = input("Bias");
1388   ShaderInput *brick_width_in = input("Brick Width");
1389   ShaderInput *row_height_in = input("Row Height");
1390
1391   ShaderOutput *color_out = output("Color");
1392   ShaderOutput *fac_out = output("Fac");
1393
1394   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1395
1396   compiler.add_node(NODE_TEX_BRICK,
1397                     compiler.encode_uchar4(vector_offset,
1398                                            compiler.stack_assign(color1_in),
1399                                            compiler.stack_assign(color2_in),
1400                                            compiler.stack_assign(mortar_in)),
1401                     compiler.encode_uchar4(compiler.stack_assign_if_linked(scale_in),
1402                                            compiler.stack_assign_if_linked(mortar_size_in),
1403                                            compiler.stack_assign_if_linked(bias_in),
1404                                            compiler.stack_assign_if_linked(brick_width_in)),
1405                     compiler.encode_uchar4(compiler.stack_assign_if_linked(row_height_in),
1406                                            compiler.stack_assign_if_linked(color_out),
1407                                            compiler.stack_assign_if_linked(fac_out),
1408                                            compiler.stack_assign_if_linked(mortar_smooth_in)));
1409
1410   compiler.add_node(compiler.encode_uchar4(offset_frequency, squash_frequency),
1411                     __float_as_int(scale),
1412                     __float_as_int(mortar_size),
1413                     __float_as_int(bias));
1414
1415   compiler.add_node(__float_as_int(brick_width),
1416                     __float_as_int(row_height),
1417                     __float_as_int(offset),
1418                     __float_as_int(squash));
1419
1420   compiler.add_node(
1421       __float_as_int(mortar_smooth), SVM_STACK_INVALID, SVM_STACK_INVALID, SVM_STACK_INVALID);
1422
1423   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1424 }
1425
1426 void BrickTextureNode::compile(OSLCompiler &compiler)
1427 {
1428   tex_mapping.compile(compiler);
1429
1430   compiler.parameter(this, "offset");
1431   compiler.parameter(this, "offset_frequency");
1432   compiler.parameter(this, "squash");
1433   compiler.parameter(this, "squash_frequency");
1434   compiler.add(this, "node_brick_texture");
1435 }
1436
1437 /* Point Density Texture */
1438
1439 NODE_DEFINE(PointDensityTextureNode)
1440 {
1441   NodeType *type = NodeType::add("point_density_texture", create, NodeType::SHADER);
1442
1443   SOCKET_STRING(filename, "Filename", ustring());
1444
1445   static NodeEnum space_enum;
1446   space_enum.insert("object", NODE_TEX_VOXEL_SPACE_OBJECT);
1447   space_enum.insert("world", NODE_TEX_VOXEL_SPACE_WORLD);
1448   SOCKET_ENUM(space, "Space", space_enum, NODE_TEX_VOXEL_SPACE_OBJECT);
1449
1450   static NodeEnum interpolation_enum;
1451   interpolation_enum.insert("closest", INTERPOLATION_CLOSEST);
1452   interpolation_enum.insert("linear", INTERPOLATION_LINEAR);
1453   interpolation_enum.insert("cubic", INTERPOLATION_CUBIC);
1454   interpolation_enum.insert("smart", INTERPOLATION_SMART);
1455   SOCKET_ENUM(interpolation, "Interpolation", interpolation_enum, INTERPOLATION_LINEAR);
1456
1457   SOCKET_TRANSFORM(tfm, "Transform", transform_identity());
1458
1459   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_POSITION);
1460
1461   SOCKET_OUT_FLOAT(density, "Density");
1462   SOCKET_OUT_COLOR(color, "Color");
1463
1464   return type;
1465 }
1466
1467 PointDensityTextureNode::PointDensityTextureNode() : ShaderNode(node_type)
1468 {
1469   image_manager = NULL;
1470   slot = -1;
1471   builtin_data = NULL;
1472 }
1473
1474 PointDensityTextureNode::~PointDensityTextureNode()
1475 {
1476   if (image_manager) {
1477     image_manager->remove_image(
1478         filename.string(), builtin_data, interpolation, EXTENSION_CLIP, true, ustring());
1479   }
1480 }
1481
1482 ShaderNode *PointDensityTextureNode::clone() const
1483 {
1484   PointDensityTextureNode *node = new PointDensityTextureNode(*this);
1485   node->image_manager = NULL;
1486   node->slot = -1;
1487   return node;
1488 }
1489
1490 void PointDensityTextureNode::attributes(Shader *shader, AttributeRequestSet *attributes)
1491 {
1492   if (shader->has_volume)
1493     attributes->add(ATTR_STD_GENERATED_TRANSFORM);
1494
1495   ShaderNode::attributes(shader, attributes);
1496 }
1497
1498 void PointDensityTextureNode::add_image()
1499 {
1500   if (slot == -1) {
1501     ImageMetaData metadata;
1502     slot = image_manager->add_image(filename.string(),
1503                                     builtin_data,
1504                                     false,
1505                                     0,
1506                                     interpolation,
1507                                     EXTENSION_CLIP,
1508                                     true,
1509                                     u_colorspace_raw,
1510                                     metadata);
1511   }
1512 }
1513
1514 void PointDensityTextureNode::compile(SVMCompiler &compiler)
1515 {
1516   ShaderInput *vector_in = input("Vector");
1517   ShaderOutput *density_out = output("Density");
1518   ShaderOutput *color_out = output("Color");
1519
1520   const bool use_density = !density_out->links.empty();
1521   const bool use_color = !color_out->links.empty();
1522
1523   image_manager = compiler.image_manager;
1524
1525   if (use_density || use_color) {
1526     add_image();
1527
1528     if (slot != -1) {
1529       compiler.stack_assign(vector_in);
1530       compiler.add_node(NODE_TEX_VOXEL,
1531                         slot,
1532                         compiler.encode_uchar4(compiler.stack_assign(vector_in),
1533                                                compiler.stack_assign_if_linked(density_out),
1534                                                compiler.stack_assign_if_linked(color_out),
1535                                                space));
1536       if (space == NODE_TEX_VOXEL_SPACE_WORLD) {
1537         compiler.add_node(tfm.x);
1538         compiler.add_node(tfm.y);
1539         compiler.add_node(tfm.z);
1540       }
1541     }
1542     else {
1543       if (use_density) {
1544         compiler.add_node(NODE_VALUE_F, __float_as_int(0.0f), compiler.stack_assign(density_out));
1545       }
1546       if (use_color) {
1547         compiler.add_node(NODE_VALUE_V, compiler.stack_assign(color_out));
1548         compiler.add_node(
1549             NODE_VALUE_V,
1550             make_float3(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B));
1551       }
1552     }
1553   }
1554 }
1555
1556 void PointDensityTextureNode::compile(OSLCompiler &compiler)
1557 {
1558   ShaderOutput *density_out = output("Density");
1559   ShaderOutput *color_out = output("Color");
1560
1561   const bool use_density = !density_out->links.empty();
1562   const bool use_color = !color_out->links.empty();
1563
1564   image_manager = compiler.image_manager;
1565
1566   if (use_density || use_color) {
1567     add_image();
1568
1569     compiler.parameter_texture("filename", slot);
1570     if (space == NODE_TEX_VOXEL_SPACE_WORLD) {
1571       compiler.parameter("mapping", tfm);
1572       compiler.parameter("use_mapping", 1);
1573     }
1574     compiler.parameter(this, "interpolation");
1575     compiler.add(this, "node_voxel_texture");
1576   }
1577 }
1578
1579 /* Normal */
1580
1581 NODE_DEFINE(NormalNode)
1582 {
1583   NodeType *type = NodeType::add("normal", create, NodeType::SHADER);
1584
1585   SOCKET_VECTOR(direction, "direction", make_float3(0.0f, 0.0f, 0.0f));
1586
1587   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f));
1588
1589   SOCKET_OUT_NORMAL(normal, "Normal");
1590   SOCKET_OUT_FLOAT(dot, "Dot");
1591
1592   return type;
1593 }
1594
1595 NormalNode::NormalNode() : ShaderNode(node_type)
1596 {
1597 }
1598
1599 void NormalNode::compile(SVMCompiler &compiler)
1600 {
1601   ShaderInput *normal_in = input("Normal");
1602   ShaderOutput *normal_out = output("Normal");
1603   ShaderOutput *dot_out = output("Dot");
1604
1605   compiler.add_node(NODE_NORMAL,
1606                     compiler.stack_assign(normal_in),
1607                     compiler.stack_assign(normal_out),
1608                     compiler.stack_assign(dot_out));
1609   compiler.add_node(
1610       __float_as_int(direction.x), __float_as_int(direction.y), __float_as_int(direction.z));
1611 }
1612
1613 void NormalNode::compile(OSLCompiler &compiler)
1614 {
1615   compiler.parameter(this, "direction");
1616   compiler.add(this, "node_normal");
1617 }
1618
1619 /* Mapping */
1620
1621 NODE_DEFINE(MappingNode)
1622 {
1623   NodeType *type = NodeType::add("mapping", create, NodeType::SHADER);
1624
1625   TEXTURE_MAPPING_DEFINE(MappingNode);
1626
1627   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f));
1628   SOCKET_OUT_POINT(vector, "Vector");
1629
1630   return type;
1631 }
1632
1633 MappingNode::MappingNode() : ShaderNode(node_type)
1634 {
1635 }
1636
1637 void MappingNode::compile(SVMCompiler &compiler)
1638 {
1639   ShaderInput *vector_in = input("Vector");
1640   ShaderOutput *vector_out = output("Vector");
1641
1642   tex_mapping.compile(
1643       compiler, compiler.stack_assign(vector_in), compiler.stack_assign(vector_out));
1644 }
1645
1646 void MappingNode::compile(OSLCompiler &compiler)
1647 {
1648   compiler.parameter("Matrix", tex_mapping.compute_transform());
1649   compiler.parameter_point("mapping_min", tex_mapping.min);
1650   compiler.parameter_point("mapping_max", tex_mapping.max);
1651   compiler.parameter("use_minmax", tex_mapping.use_minmax);
1652
1653   compiler.add(this, "node_mapping");
1654 }
1655
1656 /* RGBToBW */
1657
1658 NODE_DEFINE(RGBToBWNode)
1659 {
1660   NodeType *type = NodeType::add("rgb_to_bw", create, NodeType::SHADER);
1661
1662   SOCKET_IN_COLOR(color, "Color", make_float3(0.0f, 0.0f, 0.0f));
1663   SOCKET_OUT_FLOAT(val, "Val");
1664
1665   return type;
1666 }
1667
1668 RGBToBWNode::RGBToBWNode() : ShaderNode(node_type)
1669 {
1670 }
1671
1672 void RGBToBWNode::constant_fold(const ConstantFolder &folder)
1673 {
1674   if (folder.all_inputs_constant()) {
1675     float val = folder.scene->shader_manager->linear_rgb_to_gray(color);
1676     folder.make_constant(val);
1677   }
1678 }
1679
1680 void RGBToBWNode::compile(SVMCompiler &compiler)
1681 {
1682   compiler.add_node(NODE_CONVERT,
1683                     NODE_CONVERT_CF,
1684                     compiler.stack_assign(inputs[0]),
1685                     compiler.stack_assign(outputs[0]));
1686 }
1687
1688 void RGBToBWNode::compile(OSLCompiler &compiler)
1689 {
1690   compiler.add(this, "node_rgb_to_bw");
1691 }
1692
1693 /* Convert */
1694
1695 const NodeType *ConvertNode::node_types[ConvertNode::MAX_TYPE][ConvertNode::MAX_TYPE];
1696 bool ConvertNode::initialized = ConvertNode::register_types();
1697
1698 Node *ConvertNode::create(const NodeType *type)
1699 {
1700   return new ConvertNode(type->inputs[0].type, type->outputs[0].type);
1701 }
1702
1703 bool ConvertNode::register_types()
1704 {
1705   const int num_types = 8;
1706   SocketType::Type types[num_types] = {SocketType::FLOAT,
1707                                        SocketType::INT,
1708                                        SocketType::COLOR,
1709                                        SocketType::VECTOR,
1710                                        SocketType::POINT,
1711                                        SocketType::NORMAL,
1712                                        SocketType::STRING,
1713                                        SocketType::CLOSURE};
1714
1715   for (size_t i = 0; i < num_types; i++) {
1716     SocketType::Type from = types[i];
1717     ustring from_name(SocketType::type_name(from));
1718     ustring from_value_name("value_" + from_name.string());
1719
1720     for (size_t j = 0; j < num_types; j++) {
1721       SocketType::Type to = types[j];
1722       ustring to_name(SocketType::type_name(to));
1723       ustring to_value_name("value_" + to_name.string());
1724
1725       string node_name = "convert_" + from_name.string() + "_to_" + to_name.string();
1726       NodeType *type = NodeType::add(node_name.c_str(), create, NodeType::SHADER);
1727
1728       type->register_input(from_value_name,
1729                            from_value_name,
1730                            from,
1731                            SOCKET_OFFSETOF(ConvertNode, value_float),
1732                            SocketType::zero_default_value(),
1733                            NULL,
1734                            NULL,
1735                            SocketType::LINKABLE);
1736       type->register_output(to_value_name, to_value_name, to);
1737
1738       assert(from < MAX_TYPE);
1739       assert(to < MAX_TYPE);
1740
1741       node_types[from][to] = type;
1742     }
1743   }
1744
1745   return true;
1746 }
1747
1748 ConvertNode::ConvertNode(SocketType::Type from_, SocketType::Type to_, bool autoconvert)
1749     : ShaderNode(node_types[from_][to_])
1750 {
1751   from = from_;
1752   to = to_;
1753
1754   if (from == to)
1755     special_type = SHADER_SPECIAL_TYPE_PROXY;
1756   else if (autoconvert)
1757     special_type = SHADER_SPECIAL_TYPE_AUTOCONVERT;
1758 }
1759
1760 void ConvertNode::constant_fold(const ConstantFolder &folder)
1761 {
1762   /* proxy nodes should have been removed at this point */
1763   assert(special_type != SHADER_SPECIAL_TYPE_PROXY);
1764
1765   /* TODO(DingTo): conversion from/to int is not supported yet, don't fold in that case */
1766
1767   if (folder.all_inputs_constant()) {
1768     if (from == SocketType::FLOAT) {
1769       if (SocketType::is_float3(to)) {
1770         folder.make_constant(make_float3(value_float, value_float, value_float));
1771       }
1772     }
1773     else if (SocketType::is_float3(from)) {
1774       if (to == SocketType::FLOAT) {
1775         if (from == SocketType::COLOR) {
1776           /* color to float */
1777           float val = folder.scene->shader_manager->linear_rgb_to_gray(value_color);
1778           folder.make_constant(val);
1779         }
1780         else {
1781           /* vector/point/normal to float */
1782           folder.make_constant(average(value_vector));
1783         }
1784       }
1785       else if (SocketType::is_float3(to)) {
1786         folder.make_constant(value_color);
1787       }
1788     }
1789   }
1790   else {
1791     ShaderInput *in = inputs[0];
1792     ShaderNode *prev = in->link->parent;
1793
1794     /* no-op conversion of A to B to A */
1795     if (prev->type == node_types[to][from]) {
1796       ShaderInput *prev_in = prev->inputs[0];
1797
1798       if (SocketType::is_float3(from) && (to == SocketType::FLOAT || SocketType::is_float3(to)) &&
1799           prev_in->link) {
1800         folder.bypass(prev_in->link);
1801       }
1802     }
1803   }
1804 }
1805
1806 void ConvertNode::compile(SVMCompiler &compiler)
1807 {
1808   /* proxy nodes should have been removed at this point */
1809   assert(special_type != SHADER_SPECIAL_TYPE_PROXY);
1810
1811   ShaderInput *in = inputs[0];
1812   ShaderOutput *out = outputs[0];
1813
1814   if (from == SocketType::FLOAT) {
1815     if (to == SocketType::INT)
1816       /* float to int */
1817       compiler.add_node(
1818           NODE_CONVERT, NODE_CONVERT_FI, compiler.stack_assign(in), compiler.stack_assign(out));
1819     else
1820       /* float to float3 */
1821       compiler.add_node(
1822           NODE_CONVERT, NODE_CONVERT_FV, compiler.stack_assign(in), compiler.stack_assign(out));
1823   }
1824   else if (from == SocketType::INT) {
1825     if (to == SocketType::FLOAT)
1826       /* int to float */
1827       compiler.add_node(
1828           NODE_CONVERT, NODE_CONVERT_IF, compiler.stack_assign(in), compiler.stack_assign(out));
1829     else
1830       /* int to vector/point/normal */
1831       compiler.add_node(
1832           NODE_CONVERT, NODE_CONVERT_IV, compiler.stack_assign(in), compiler.stack_assign(out));
1833   }
1834   else if (to == SocketType::FLOAT) {
1835     if (from == SocketType::COLOR)
1836       /* color to float */
1837       compiler.add_node(
1838           NODE_CONVERT, NODE_CONVERT_CF, compiler.stack_assign(in), compiler.stack_assign(out));
1839     else
1840       /* vector/point/normal to float */
1841       compiler.add_node(
1842           NODE_CONVERT, NODE_CONVERT_VF, compiler.stack_assign(in), compiler.stack_assign(out));
1843   }
1844   else if (to == SocketType::INT) {
1845     if (from == SocketType::COLOR)
1846       /* color to int */
1847       compiler.add_node(
1848           NODE_CONVERT, NODE_CONVERT_CI, compiler.stack_assign(in), compiler.stack_assign(out));
1849     else
1850       /* vector/point/normal to int */
1851       compiler.add_node(
1852           NODE_CONVERT, NODE_CONVERT_VI, compiler.stack_assign(in), compiler.stack_assign(out));
1853   }
1854   else {
1855     /* float3 to float3 */
1856     if (in->link) {
1857       /* no op in SVM */
1858       compiler.stack_link(in, out);
1859     }
1860     else {
1861       /* set 0,0,0 value */
1862       compiler.add_node(NODE_VALUE_V, compiler.stack_assign(out));
1863       compiler.add_node(NODE_VALUE_V, value_color);
1864     }
1865   }
1866 }
1867
1868 void ConvertNode::compile(OSLCompiler &compiler)
1869 {
1870   /* proxy nodes should have been removed at this point */
1871   assert(special_type != SHADER_SPECIAL_TYPE_PROXY);
1872
1873   if (from == SocketType::FLOAT)
1874     compiler.add(this, "node_convert_from_float");
1875   else if (from == SocketType::INT)
1876     compiler.add(this, "node_convert_from_int");
1877   else if (from == SocketType::COLOR)
1878     compiler.add(this, "node_convert_from_color");
1879   else if (from == SocketType::VECTOR)
1880     compiler.add(this, "node_convert_from_vector");
1881   else if (from == SocketType::POINT)
1882     compiler.add(this, "node_convert_from_point");
1883   else if (from == SocketType::NORMAL)
1884     compiler.add(this, "node_convert_from_normal");
1885   else
1886     assert(0);
1887 }
1888
1889 /* Base type for all closure-type nodes */
1890
1891 BsdfBaseNode::BsdfBaseNode(const NodeType *node_type) : ShaderNode(node_type)
1892 {
1893   special_type = SHADER_SPECIAL_TYPE_CLOSURE;
1894 }
1895
1896 bool BsdfBaseNode::has_bump()
1897 {
1898   /* detect if anything is plugged into the normal input besides the default */
1899   ShaderInput *normal_in = input("Normal");
1900   return (normal_in && normal_in->link &&
1901           normal_in->link->parent->special_type != SHADER_SPECIAL_TYPE_GEOMETRY);
1902 }
1903
1904 /* BSDF Closure */
1905
1906 BsdfNode::BsdfNode(const NodeType *node_type) : BsdfBaseNode(node_type)
1907 {
1908 }
1909
1910 void BsdfNode::compile(SVMCompiler &compiler,
1911                        ShaderInput *param1,
1912                        ShaderInput *param2,
1913                        ShaderInput *param3,
1914                        ShaderInput *param4)
1915 {
1916   ShaderInput *color_in = input("Color");
1917   ShaderInput *normal_in = input("Normal");
1918   ShaderInput *tangent_in = input("Tangent");
1919
1920   if (color_in->link)
1921     compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in));
1922   else
1923     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color);
1924
1925   int normal_offset = (normal_in) ? compiler.stack_assign_if_linked(normal_in) : SVM_STACK_INVALID;
1926   int tangent_offset = (tangent_in) ? compiler.stack_assign_if_linked(tangent_in) :
1927                                       SVM_STACK_INVALID;
1928   int param3_offset = (param3) ? compiler.stack_assign(param3) : SVM_STACK_INVALID;
1929   int param4_offset = (param4) ? compiler.stack_assign(param4) : SVM_STACK_INVALID;
1930
1931   compiler.add_node(
1932       NODE_CLOSURE_BSDF,
1933       compiler.encode_uchar4(closure,
1934                              (param1) ? compiler.stack_assign(param1) : SVM_STACK_INVALID,
1935                              (param2) ? compiler.stack_assign(param2) : SVM_STACK_INVALID,
1936                              compiler.closure_mix_weight_offset()),
1937       __float_as_int((param1) ? get_float(param1->socket_type) : 0.0f),
1938       __float_as_int((param2) ? get_float(param2->socket_type) : 0.0f));
1939
1940   compiler.add_node(normal_offset, tangent_offset, param3_offset, param4_offset);
1941 }
1942
1943 void BsdfNode::compile(SVMCompiler &compiler)
1944 {
1945   compile(compiler, NULL, NULL);
1946 }
1947
1948 void BsdfNode::compile(OSLCompiler & /*compiler*/)
1949 {
1950   assert(0);
1951 }
1952
1953 /* Anisotropic BSDF Closure */
1954
1955 NODE_DEFINE(AnisotropicBsdfNode)
1956 {
1957   NodeType *type = NodeType::add("anisotropic_bsdf", create, NodeType::SHADER);
1958
1959   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
1960   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
1961   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
1962
1963   static NodeEnum distribution_enum;
1964   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_ANISO_ID);
1965   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID);
1966   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_ANISO_ID);
1967   distribution_enum.insert("ashikhmin_shirley", CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ANISO_ID);
1968   SOCKET_ENUM(
1969       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID);
1970
1971   SOCKET_IN_VECTOR(tangent, "Tangent", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TANGENT);
1972
1973   SOCKET_IN_FLOAT(roughness, "Roughness", 0.5f);
1974   SOCKET_IN_FLOAT(anisotropy, "Anisotropy", 0.5f);
1975   SOCKET_IN_FLOAT(rotation, "Rotation", 0.0f);
1976
1977   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
1978
1979   return type;
1980 }
1981
1982 AnisotropicBsdfNode::AnisotropicBsdfNode() : BsdfNode(node_type)
1983 {
1984   closure = CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID;
1985 }
1986
1987 void AnisotropicBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes)
1988 {
1989   if (shader->has_surface) {
1990     ShaderInput *tangent_in = input("Tangent");
1991
1992     if (!tangent_in->link)
1993       attributes->add(ATTR_STD_GENERATED);
1994   }
1995
1996   ShaderNode::attributes(shader, attributes);
1997 }
1998
1999 void AnisotropicBsdfNode::compile(SVMCompiler &compiler)
2000 {
2001   closure = distribution;
2002
2003   if (closure == CLOSURE_BSDF_MICROFACET_MULTI_GGX_ANISO_ID)
2004     BsdfNode::compile(
2005         compiler, input("Roughness"), input("Anisotropy"), input("Rotation"), input("Color"));
2006   else
2007     BsdfNode::compile(compiler, input("Roughness"), input("Anisotropy"), input("Rotation"));
2008 }
2009
2010 void AnisotropicBsdfNode::compile(OSLCompiler &compiler)
2011 {
2012   compiler.parameter(this, "distribution");
2013   compiler.add(this, "node_anisotropic_bsdf");
2014 }
2015
2016 /* Glossy BSDF Closure */
2017
2018 NODE_DEFINE(GlossyBsdfNode)
2019 {
2020   NodeType *type = NodeType::add("glossy_bsdf", create, NodeType::SHADER);
2021
2022   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2023   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2024   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2025
2026   static NodeEnum distribution_enum;
2027   distribution_enum.insert("sharp", CLOSURE_BSDF_REFLECTION_ID);
2028   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_ID);
2029   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_ID);
2030   distribution_enum.insert("ashikhmin_shirley", CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID);
2031   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID);
2032   SOCKET_ENUM(distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_ID);
2033   SOCKET_IN_FLOAT(roughness, "Roughness", 0.5f);
2034
2035   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2036
2037   return type;
2038 }
2039
2040 GlossyBsdfNode::GlossyBsdfNode() : BsdfNode(node_type)
2041 {
2042   closure = CLOSURE_BSDF_MICROFACET_GGX_ID;
2043   distribution_orig = NBUILTIN_CLOSURES;
2044 }
2045
2046 void GlossyBsdfNode::simplify_settings(Scene *scene)
2047 {
2048   if (distribution_orig == NBUILTIN_CLOSURES) {
2049     roughness_orig = roughness;
2050     distribution_orig = distribution;
2051   }
2052   else {
2053     /* By default we use original values, so we don't worry about restoring
2054      * defaults later one and can only do override when needed.
2055      */
2056     roughness = roughness_orig;
2057     distribution = distribution_orig;
2058   }
2059   Integrator *integrator = scene->integrator;
2060   ShaderInput *roughness_input = input("Roughness");
2061   if (integrator->filter_glossy == 0.0f) {
2062     /* Fallback to Sharp closure for Roughness close to 0.
2063      * Note: Keep the epsilon in sync with kernel!
2064      */
2065     if (!roughness_input->link && roughness <= 1e-4f) {
2066       VLOG(1) << "Using sharp glossy BSDF.";
2067       distribution = CLOSURE_BSDF_REFLECTION_ID;
2068     }
2069   }
2070   else {
2071     /* If filter glossy is used we replace Sharp glossy with GGX so we can
2072      * benefit from closure blur to remove unwanted noise.
2073      */
2074     if (roughness_input->link == NULL && distribution == CLOSURE_BSDF_REFLECTION_ID) {
2075       VLOG(1) << "Using GGX glossy with filter glossy.";
2076       distribution = CLOSURE_BSDF_MICROFACET_GGX_ID;
2077       roughness = 0.0f;
2078     }
2079   }
2080   closure = distribution;
2081 }
2082
2083 bool GlossyBsdfNode::has_integrator_dependency()
2084 {
2085   ShaderInput *roughness_input = input("Roughness");
2086   return !roughness_input->link &&
2087          (distribution == CLOSURE_BSDF_REFLECTION_ID || roughness <= 1e-4f);
2088 }
2089
2090 void GlossyBsdfNode::compile(SVMCompiler &compiler)
2091 {
2092   closure = distribution;
2093
2094   if (closure == CLOSURE_BSDF_REFLECTION_ID)
2095     BsdfNode::compile(compiler, NULL, NULL);
2096   else if (closure == CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID)
2097     BsdfNode::compile(compiler, input("Roughness"), NULL, input("Color"));
2098   else
2099     BsdfNode::compile(compiler, input("Roughness"), NULL);
2100 }
2101
2102 void GlossyBsdfNode::compile(OSLCompiler &compiler)
2103 {
2104   compiler.parameter(this, "distribution");
2105   compiler.add(this, "node_glossy_bsdf");
2106 }
2107
2108 /* Glass BSDF Closure */
2109
2110 NODE_DEFINE(GlassBsdfNode)
2111 {
2112   NodeType *type = NodeType::add("glass_bsdf", create, NodeType::SHADER);
2113
2114   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2115   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2116   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2117
2118   static NodeEnum distribution_enum;
2119   distribution_enum.insert("sharp", CLOSURE_BSDF_SHARP_GLASS_ID);
2120   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID);
2121   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
2122   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
2123   SOCKET_ENUM(
2124       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
2125   SOCKET_IN_FLOAT(roughness, "Roughness", 0.0f);
2126   SOCKET_IN_FLOAT(IOR, "IOR", 0.3f);
2127
2128   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2129
2130   return type;
2131 }
2132
2133 GlassBsdfNode::GlassBsdfNode() : BsdfNode(node_type)
2134 {
2135   closure = CLOSURE_BSDF_SHARP_GLASS_ID;
2136   distribution_orig = NBUILTIN_CLOSURES;
2137 }
2138
2139 void GlassBsdfNode::simplify_settings(Scene *scene)
2140 {
2141   if (distribution_orig == NBUILTIN_CLOSURES) {
2142     roughness_orig = roughness;
2143     distribution_orig = distribution;
2144   }
2145   else {
2146     /* By default we use original values, so we don't worry about restoring
2147      * defaults later one and can only do override when needed.
2148      */
2149     roughness = roughness_orig;
2150     distribution = distribution_orig;
2151   }
2152   Integrator *integrator = scene->integrator;
2153   ShaderInput *roughness_input = input("Roughness");
2154   if (integrator->filter_glossy == 0.0f) {
2155     /* Fallback to Sharp closure for Roughness close to 0.
2156      * Note: Keep the epsilon in sync with kernel!
2157      */
2158     if (!roughness_input->link && roughness <= 1e-4f) {
2159       VLOG(1) << "Using sharp glass BSDF.";
2160       distribution = CLOSURE_BSDF_SHARP_GLASS_ID;
2161     }
2162   }
2163   else {
2164     /* If filter glossy is used we replace Sharp glossy with GGX so we can
2165      * benefit from closure blur to remove unwanted noise.
2166      */
2167     if (roughness_input->link == NULL && distribution == CLOSURE_BSDF_SHARP_GLASS_ID) {
2168       VLOG(1) << "Using GGX glass with filter glossy.";
2169       distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
2170       roughness = 0.0f;
2171     }
2172   }
2173   closure = distribution;
2174 }
2175
2176 bool GlassBsdfNode::has_integrator_dependency()
2177 {
2178   ShaderInput *roughness_input = input("Roughness");
2179   return !roughness_input->link &&
2180          (distribution == CLOSURE_BSDF_SHARP_GLASS_ID || roughness <= 1e-4f);
2181 }
2182
2183 void GlassBsdfNode::compile(SVMCompiler &compiler)
2184 {
2185   closure = distribution;
2186
2187   if (closure == CLOSURE_BSDF_SHARP_GLASS_ID)
2188     BsdfNode::compile(compiler, NULL, input("IOR"));
2189   else if (closure == CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID)
2190     BsdfNode::compile(compiler, input("Roughness"), input("IOR"), input("Color"));
2191   else
2192     BsdfNode::compile(compiler, input("Roughness"), input("IOR"));
2193 }
2194
2195 void GlassBsdfNode::compile(OSLCompiler &compiler)
2196 {
2197   compiler.parameter(this, "distribution");
2198   compiler.add(this, "node_glass_bsdf");
2199 }
2200
2201 /* Refraction BSDF Closure */
2202
2203 NODE_DEFINE(RefractionBsdfNode)
2204 {
2205   NodeType *type = NodeType::add("refraction_bsdf", create, NodeType::SHADER);
2206
2207   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2208   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2209   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2210
2211   static NodeEnum distribution_enum;
2212   distribution_enum.insert("sharp", CLOSURE_BSDF_REFRACTION_ID);
2213   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID);
2214   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID);
2215   SOCKET_ENUM(
2216       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID);
2217
2218   SOCKET_IN_FLOAT(roughness, "Roughness", 0.0f);
2219   SOCKET_IN_FLOAT(IOR, "IOR", 0.3f);
2220
2221   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2222
2223   return type;
2224 }
2225
2226 RefractionBsdfNode::RefractionBsdfNode() : BsdfNode(node_type)
2227 {
2228   closure = CLOSURE_BSDF_REFRACTION_ID;
2229   distribution_orig = NBUILTIN_CLOSURES;
2230 }
2231
2232 void RefractionBsdfNode::simplify_settings(Scene *scene)
2233 {
2234   if (distribution_orig == NBUILTIN_CLOSURES) {
2235     roughness_orig = roughness;
2236     distribution_orig = distribution;
2237   }
2238   else {
2239     /* By default we use original values, so we don't worry about restoring
2240      * defaults later one and can only do override when needed.
2241      */
2242     roughness = roughness_orig;
2243     distribution = distribution_orig;
2244   }
2245   Integrator *integrator = scene->integrator;
2246   ShaderInput *roughness_input = input("Roughness");
2247   if (integrator->filter_glossy == 0.0f) {
2248     /* Fallback to Sharp closure for Roughness close to 0.
2249      * Note: Keep the epsilon in sync with kernel!
2250      */
2251     if (!roughness_input->link && roughness <= 1e-4f) {
2252       VLOG(1) << "Using sharp refraction BSDF.";
2253       distribution = CLOSURE_BSDF_REFRACTION_ID;
2254     }
2255   }
2256   else {
2257     /* If filter glossy is used we replace Sharp glossy with GGX so we can
2258      * benefit from closure blur to remove unwanted noise.
2259      */
2260     if (roughness_input->link == NULL && distribution == CLOSURE_BSDF_REFRACTION_ID) {
2261       VLOG(1) << "Using GGX refraction with filter glossy.";
2262       distribution = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
2263       roughness = 0.0f;
2264     }
2265   }
2266   closure = distribution;
2267 }
2268
2269 bool RefractionBsdfNode::has_integrator_dependency()
2270 {
2271   ShaderInput *roughness_input = input("Roughness");
2272   return !roughness_input->link &&
2273          (distribution == CLOSURE_BSDF_REFRACTION_ID || roughness <= 1e-4f);
2274 }
2275
2276 void RefractionBsdfNode::compile(SVMCompiler &compiler)
2277 {
2278   closure = distribution;
2279
2280   if (closure == CLOSURE_BSDF_REFRACTION_ID)
2281     BsdfNode::compile(compiler, NULL, input("IOR"));
2282   else
2283     BsdfNode::compile(compiler, input("Roughness"), input("IOR"));
2284 }
2285
2286 void RefractionBsdfNode::compile(OSLCompiler &compiler)
2287 {
2288   compiler.parameter(this, "distribution");
2289   compiler.add(this, "node_refraction_bsdf");
2290 }
2291
2292 /* Toon BSDF Closure */
2293
2294 NODE_DEFINE(ToonBsdfNode)
2295 {
2296   NodeType *type = NodeType::add("toon_bsdf", create, NodeType::SHADER);
2297
2298   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2299   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2300   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2301
2302   static NodeEnum component_enum;
2303   component_enum.insert("diffuse", CLOSURE_BSDF_DIFFUSE_TOON_ID);
2304   component_enum.insert("glossy", CLOSURE_BSDF_GLOSSY_TOON_ID);
2305   SOCKET_ENUM(component, "Component", component_enum, CLOSURE_BSDF_DIFFUSE_TOON_ID);
2306   SOCKET_IN_FLOAT(size, "Size", 0.5f);
2307   SOCKET_IN_FLOAT(smooth, "Smooth", 0.0f);
2308
2309   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2310
2311   return type;
2312 }
2313
2314 ToonBsdfNode::ToonBsdfNode() : BsdfNode(node_type)
2315 {
2316   closure = CLOSURE_BSDF_DIFFUSE_TOON_ID;
2317 }
2318
2319 void ToonBsdfNode::compile(SVMCompiler &compiler)
2320 {
2321   closure = component;
2322
2323   BsdfNode::compile(compiler, input("Size"), input("Smooth"));
2324 }
2325
2326 void ToonBsdfNode::compile(OSLCompiler &compiler)
2327 {
2328   compiler.parameter(this, "component");
2329   compiler.add(this, "node_toon_bsdf");
2330 }
2331
2332 /* Velvet BSDF Closure */
2333
2334 NODE_DEFINE(VelvetBsdfNode)
2335 {
2336   NodeType *type = NodeType::add("velvet_bsdf", create, NodeType::SHADER);
2337
2338   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2339   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2340   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2341   SOCKET_IN_FLOAT(sigma, "Sigma", 1.0f);
2342
2343   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2344
2345   return type;
2346 }
2347
2348 VelvetBsdfNode::VelvetBsdfNode() : BsdfNode(node_type)
2349 {
2350   closure = CLOSURE_BSDF_ASHIKHMIN_VELVET_ID;
2351 }
2352
2353 void VelvetBsdfNode::compile(SVMCompiler &compiler)
2354 {
2355   BsdfNode::compile(compiler, input("Sigma"), NULL);
2356 }
2357
2358 void VelvetBsdfNode::compile(OSLCompiler &compiler)
2359 {
2360   compiler.add(this, "node_velvet_bsdf");
2361 }
2362
2363 /* Diffuse BSDF Closure */
2364
2365 NODE_DEFINE(DiffuseBsdfNode)
2366 {
2367   NodeType *type = NodeType::add("diffuse_bsdf", create, NodeType::SHADER);
2368
2369   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2370   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2371   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2372   SOCKET_IN_FLOAT(roughness, "Roughness", 0.0f);
2373
2374   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2375
2376   return type;
2377 }
2378
2379 DiffuseBsdfNode::DiffuseBsdfNode() : BsdfNode(node_type)
2380 {
2381   closure = CLOSURE_BSDF_DIFFUSE_ID;
2382 }
2383
2384 void DiffuseBsdfNode::compile(SVMCompiler &compiler)
2385 {
2386   BsdfNode::compile(compiler, input("Roughness"), NULL);
2387 }
2388
2389 void DiffuseBsdfNode::compile(OSLCompiler &compiler)
2390 {
2391   compiler.add(this, "node_diffuse_bsdf");
2392 }
2393
2394 /* Disney principled BSDF Closure */
2395 NODE_DEFINE(PrincipledBsdfNode)
2396 {
2397   NodeType *type = NodeType::add("principled_bsdf", create, NodeType::SHADER);
2398
2399   static NodeEnum distribution_enum;
2400   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
2401   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
2402   SOCKET_ENUM(
2403       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
2404
2405   static NodeEnum subsurface_method_enum;
2406   subsurface_method_enum.insert("burley", CLOSURE_BSSRDF_PRINCIPLED_ID);
2407   subsurface_method_enum.insert("random_walk", CLOSURE_BSSRDF_PRINCIPLED_RANDOM_WALK_ID);
2408   SOCKET_ENUM(subsurface_method,
2409               "Subsurface Method",
2410               subsurface_method_enum,
2411               CLOSURE_BSSRDF_PRINCIPLED_ID);
2412
2413   SOCKET_IN_COLOR(base_color, "Base Color", make_float3(0.8f, 0.8f, 0.8f));
2414   SOCKET_IN_COLOR(subsurface_color, "Subsurface Color", make_float3(0.8f, 0.8f, 0.8f));
2415   SOCKET_IN_FLOAT(metallic, "Metallic", 0.0f);
2416   SOCKET_IN_FLOAT(subsurface, "Subsurface", 0.0f);
2417   SOCKET_IN_VECTOR(subsurface_radius, "Subsurface Radius", make_float3(0.1f, 0.1f, 0.1f));
2418   SOCKET_IN_FLOAT(specular, "Specular", 0.0f);
2419   SOCKET_IN_FLOAT(roughness, "Roughness", 0.5f);
2420   SOCKET_IN_FLOAT(specular_tint, "Specular Tint", 0.0f);
2421   SOCKET_IN_FLOAT(anisotropic, "Anisotropic", 0.0f);
2422   SOCKET_IN_FLOAT(sheen, "Sheen", 0.0f);
2423   SOCKET_IN_FLOAT(sheen_tint, "Sheen Tint", 0.0f);
2424   SOCKET_IN_FLOAT(clearcoat, "Clearcoat", 0.0f);
2425   SOCKET_IN_FLOAT(clearcoat_roughness, "Clearcoat Roughness", 0.03f);
2426   SOCKET_IN_FLOAT(ior, "IOR", 0.0f);
2427   SOCKET_IN_FLOAT(transmission, "Transmission", 0.0f);
2428   SOCKET_IN_FLOAT(transmission_roughness, "Transmission Roughness", 0.0f);
2429   SOCKET_IN_FLOAT(anisotropic_rotation, "Anisotropic Rotation", 0.0f);
2430   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2431   SOCKET_IN_NORMAL(clearcoat_normal,
2432                    "Clearcoat Normal",
2433                    make_float3(0.0f, 0.0f, 0.0f),
2434                    SocketType::LINK_NORMAL);
2435   SOCKET_IN_NORMAL(tangent, "Tangent", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TANGENT);
2436   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2437
2438   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2439
2440   return type;
2441 }
2442
2443 PrincipledBsdfNode::PrincipledBsdfNode() : BsdfBaseNode(node_type)
2444 {
2445   closure = CLOSURE_BSDF_PRINCIPLED_ID;
2446   distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
2447   distribution_orig = NBUILTIN_CLOSURES;
2448 }
2449
2450 bool PrincipledBsdfNode::has_surface_bssrdf()
2451 {
2452   ShaderInput *subsurface_in = input("Subsurface");
2453   return (subsurface_in->link != NULL || subsurface > CLOSURE_WEIGHT_CUTOFF);
2454 }
2455
2456 void PrincipledBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes)
2457 {
2458   if (shader->has_surface) {
2459     ShaderInput *tangent_in = input("Tangent");
2460
2461     if (!tangent_in->link)
2462       attributes->add(ATTR_STD_GENERATED);
2463   }
2464
2465   ShaderNode::attributes(shader, attributes);
2466 }
2467
2468 void PrincipledBsdfNode::compile(SVMCompiler &compiler,
2469                                  ShaderInput *p_metallic,
2470                                  ShaderInput *p_subsurface,
2471                                  ShaderInput *p_subsurface_radius,
2472                                  ShaderInput *p_specular,
2473                                  ShaderInput *p_roughness,
2474                                  ShaderInput *p_specular_tint,
2475                                  ShaderInput *p_anisotropic,
2476                                  ShaderInput *p_sheen,
2477                                  ShaderInput *p_sheen_tint,
2478                                  ShaderInput *p_clearcoat,
2479                                  ShaderInput *p_clearcoat_roughness,
2480                                  ShaderInput *p_ior,
2481                                  ShaderInput *p_transmission,
2482                                  ShaderInput *p_anisotropic_rotation,
2483                                  ShaderInput *p_transmission_roughness)
2484 {
2485   ShaderInput *base_color_in = input("Base Color");
2486   ShaderInput *subsurface_color_in = input("Subsurface Color");
2487   ShaderInput *normal_in = input("Normal");
2488   ShaderInput *clearcoat_normal_in = input("Clearcoat Normal");
2489   ShaderInput *tangent_in = input("Tangent");
2490
2491   float3 weight = make_float3(1.0f, 1.0f, 1.0f);
2492
2493   compiler.add_node(NODE_CLOSURE_SET_WEIGHT, weight);
2494
2495   int normal_offset = compiler.stack_assign_if_linked(normal_in);
2496   int clearcoat_normal_offset = compiler.stack_assign_if_linked(clearcoat_normal_in);
2497   int tangent_offset = compiler.stack_assign_if_linked(tangent_in);
2498   int specular_offset = compiler.stack_assign(p_specular);
2499   int roughness_offset = compiler.stack_assign(p_roughness);
2500   int specular_tint_offset = compiler.stack_assign(p_specular_tint);
2501   int anisotropic_offset = compiler.stack_assign(p_anisotropic);
2502   int sheen_offset = compiler.stack_assign(p_sheen);
2503   int sheen_tint_offset = compiler.stack_assign(p_sheen_tint);
2504   int clearcoat_offset = compiler.stack_assign(p_clearcoat);
2505   int clearcoat_roughness_offset = compiler.stack_assign(p_clearcoat_roughness);
2506   int ior_offset = compiler.stack_assign(p_ior);
2507   int transmission_offset = compiler.stack_assign(p_transmission);
2508   int transmission_roughness_offset = compiler.stack_assign(p_transmission_roughness);
2509   int anisotropic_rotation_offset = compiler.stack_assign(p_anisotropic_rotation);
2510   int subsurface_radius_offset = compiler.stack_assign(p_subsurface_radius);
2511
2512   compiler.add_node(NODE_CLOSURE_BSDF,
2513                     compiler.encode_uchar4(closure,
2514                                            compiler.stack_assign(p_metallic),
2515                                            compiler.stack_assign(p_subsurface),
2516                                            compiler.closure_mix_weight_offset()),
2517                     __float_as_int((p_metallic) ? get_float(p_metallic->socket_type) : 0.0f),
2518                     __float_as_int((p_subsurface) ? get_float(p_subsurface->socket_type) : 0.0f));
2519
2520   compiler.add_node(
2521       normal_offset,
2522       tangent_offset,
2523       compiler.encode_uchar4(
2524           specular_offset, roughness_offset, specular_tint_offset, anisotropic_offset),
2525       compiler.encode_uchar4(
2526           sheen_offset, sheen_tint_offset, clearcoat_offset, clearcoat_roughness_offset));
2527
2528   compiler.add_node(compiler.encode_uchar4(ior_offset,
2529                                            transmission_offset,
2530                                            anisotropic_rotation_offset,
2531                                            transmission_roughness_offset),
2532                     distribution,
2533                     subsurface_method,
2534                     SVM_STACK_INVALID);
2535
2536   float3 bc_default = get_float3(base_color_in->socket_type);
2537
2538   compiler.add_node(
2539       ((base_color_in->link) ? compiler.stack_assign(base_color_in) : SVM_STACK_INVALID),
2540       __float_as_int(bc_default.x),
2541       __float_as_int(bc_default.y),
2542       __float_as_int(bc_default.z));
2543
2544   compiler.add_node(
2545       clearcoat_normal_offset, subsurface_radius_offset, SVM_STACK_INVALID, SVM_STACK_INVALID);
2546
2547   float3 ss_default = get_float3(subsurface_color_in->socket_type);
2548
2549   compiler.add_node(((subsurface_color_in->link) ? compiler.stack_assign(subsurface_color_in) :
2550                                                    SVM_STACK_INVALID),
2551                     __float_as_int(ss_default.x),
2552                     __float_as_int(ss_default.y),
2553                     __float_as_int(ss_default.z));
2554 }
2555
2556 bool PrincipledBsdfNode::has_integrator_dependency()
2557 {
2558   ShaderInput *roughness_input = input("Roughness");
2559   return !roughness_input->link && roughness <= 1e-4f;
2560 }
2561
2562 void PrincipledBsdfNode::compile(SVMCompiler &compiler)
2563 {
2564   compile(compiler,
2565           input("Metallic"),
2566           input("Subsurface"),
2567           input("Subsurface Radius"),
2568           input("Specular"),
2569           input("Roughness"),
2570           input("Specular Tint"),
2571           input("Anisotropic"),
2572           input("Sheen"),
2573           input("Sheen Tint"),
2574           input("Clearcoat"),
2575           input("Clearcoat Roughness"),
2576           input("IOR"),
2577           input("Transmission"),
2578           input("Anisotropic Rotation"),
2579           input("Transmission Roughness"));
2580 }
2581
2582 void PrincipledBsdfNode::compile(OSLCompiler &compiler)
2583 {
2584   compiler.parameter(this, "distribution");
2585   compiler.parameter(this, "subsurface_method");
2586   compiler.add(this, "node_principled_bsdf");
2587 }
2588
2589 bool PrincipledBsdfNode::has_bssrdf_bump()
2590 {
2591   return has_surface_bssrdf() && has_bump();
2592 }
2593
2594 /* Translucent BSDF Closure */
2595
2596 NODE_DEFINE(TranslucentBsdfNode)
2597 {
2598   NodeType *type = NodeType::add("translucent_bsdf", create, NodeType::SHADER);
2599
2600   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2601   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2602   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2603
2604   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2605
2606   return type;
2607 }
2608
2609 TranslucentBsdfNode::TranslucentBsdfNode() : BsdfNode(node_type)
2610 {
2611   closure = CLOSURE_BSDF_TRANSLUCENT_ID;
2612 }
2613
2614 void TranslucentBsdfNode::compile(SVMCompiler &compiler)
2615 {
2616   BsdfNode::compile(compiler, NULL, NULL);
2617 }
2618
2619 void TranslucentBsdfNode::compile(OSLCompiler &compiler)
2620 {
2621   compiler.add(this, "node_translucent_bsdf");
2622 }
2623
2624 /* Transparent BSDF Closure */
2625
2626 NODE_DEFINE(TransparentBsdfNode)
2627 {
2628   NodeType *type = NodeType::add("transparent_bsdf", create, NodeType::SHADER);
2629
2630   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2631   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2632
2633   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2634
2635   return type;
2636 }
2637
2638 TransparentBsdfNode::TransparentBsdfNode() : BsdfNode(node_type)
2639 {
2640   closure = CLOSURE_BSDF_TRANSPARENT_ID;
2641 }
2642
2643 void TransparentBsdfNode::compile(SVMCompiler &compiler)
2644 {
2645   BsdfNode::compile(compiler, NULL, NULL);
2646 }
2647
2648 void TransparentBsdfNode::compile(OSLCompiler &compiler)
2649 {
2650   compiler.add(this, "node_transparent_bsdf");
2651 }
2652
2653 /* Subsurface Scattering Closure */
2654
2655 NODE_DEFINE(SubsurfaceScatteringNode)
2656 {
2657   NodeType *type = NodeType::add("subsurface_scattering", create, NodeType::SHADER);
2658
2659   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2660   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2661   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2662
2663   static NodeEnum falloff_enum;
2664   falloff_enum.insert("cubic", CLOSURE_BSSRDF_CUBIC_ID);
2665   falloff_enum.insert("gaussian", CLOSURE_BSSRDF_GAUSSIAN_ID);
2666   falloff_enum.insert("burley", CLOSURE_BSSRDF_BURLEY_ID);
2667   falloff_enum.insert("random_walk", CLOSURE_BSSRDF_RANDOM_WALK_ID);
2668   SOCKET_ENUM(falloff, "Falloff", falloff_enum, CLOSURE_BSSRDF_BURLEY_ID);
2669   SOCKET_IN_FLOAT(scale, "Scale", 0.01f);
2670   SOCKET_IN_VECTOR(radius, "Radius", make_float3(0.1f, 0.1f, 0.1f));
2671   SOCKET_IN_FLOAT(sharpness, "Sharpness", 0.0f);
2672   SOCKET_IN_FLOAT(texture_blur, "Texture Blur", 1.0f);
2673
2674   SOCKET_OUT_CLOSURE(BSSRDF, "BSSRDF");
2675
2676   return type;
2677 }
2678
2679 SubsurfaceScatteringNode::SubsurfaceScatteringNode() : BsdfNode(node_type)
2680 {
2681   closure = falloff;
2682 }
2683
2684 void SubsurfaceScatteringNode::compile(SVMCompiler &compiler)
2685 {
2686   closure = falloff;
2687   BsdfNode::compile(
2688       compiler, input("Scale"), input("Texture Blur"), input("Radius"), input("Sharpness"));
2689 }
2690
2691 void SubsurfaceScatteringNode::compile(OSLCompiler &compiler)
2692 {
2693   closure = falloff;
2694   compiler.parameter(this, "falloff");
2695   compiler.add(this, "node_subsurface_scattering");
2696 }
2697
2698 bool SubsurfaceScatteringNode::has_bssrdf_bump()
2699 {
2700   /* detect if anything is plugged into the normal input besides the default */
2701   ShaderInput *normal_in = input("Normal");
2702   return (normal_in->link &&
2703           normal_in->link->parent->special_type != SHADER_SPECIAL_TYPE_GEOMETRY);
2704 }
2705
2706 /* Emissive Closure */
2707
2708 NODE_DEFINE(EmissionNode)
2709 {
2710   NodeType *type = NodeType::add("emission", create, NodeType::SHADER);
2711
2712   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2713   SOCKET_IN_FLOAT(strength, "Strength", 10.0f);
2714   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2715
2716   SOCKET_OUT_CLOSURE(emission, "Emission");
2717
2718   return type;
2719 }
2720
2721 EmissionNode::EmissionNode() : ShaderNode(node_type)
2722 {
2723 }
2724
2725 void EmissionNode::compile(SVMCompiler &compiler)
2726 {
2727   ShaderInput *color_in = input("Color");
2728   ShaderInput *strength_in = input("Strength");
2729
2730   if (color_in->link || strength_in->link) {
2731     compiler.add_node(
2732         NODE_EMISSION_WEIGHT, compiler.stack_assign(color_in), compiler.stack_assign(strength_in));
2733   }
2734   else
2735     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color * strength);
2736
2737   compiler.add_node(NODE_CLOSURE_EMISSION, compiler.closure_mix_weight_offset());
2738 }
2739
2740 void EmissionNode::compile(OSLCompiler &compiler)
2741 {
2742   compiler.add(this, "node_emission");
2743 }
2744
2745 void EmissionNode::constant_fold(const ConstantFolder &folder)
2746 {
2747   ShaderInput *color_in = input("Color");
2748   ShaderInput *strength_in = input("Strength");
2749
2750   if ((!color_in->link && color == make_float3(0.0f, 0.0f, 0.0f)) ||
2751       (!strength_in->link && strength == 0.0f)) {
2752     folder.discard();
2753   }
2754 }
2755
2756 /* Background Closure */
2757
2758 NODE_DEFINE(BackgroundNode)
2759 {
2760   NodeType *type = NodeType::add("background_shader", create, NodeType::SHADER);
2761
2762   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2763   SOCKET_IN_FLOAT(strength, "Strength", 1.0f);
2764   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2765
2766   SOCKET_OUT_CLOSURE(background, "Background");
2767
2768   return type;
2769 }
2770
2771 BackgroundNode::BackgroundNode() : ShaderNode(node_type)
2772 {
2773 }
2774
2775 void BackgroundNode::compile(SVMCompiler &compiler)
2776 {
2777   ShaderInput *color_in = input("Color");
2778   ShaderInput *strength_in = input("Strength");
2779
2780   if (color_in->link || strength_in->link) {
2781     compiler.add_node(
2782         NODE_EMISSION_WEIGHT, compiler.stack_assign(color_in), compiler.stack_assign(strength_in));
2783   }
2784   else
2785     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color * strength);
2786
2787   compiler.add_node(NODE_CLOSURE_BACKGROUND, compiler.closure_mix_weight_offset());
2788 }
2789
2790 void BackgroundNode::compile(OSLCompiler &compiler)
2791 {
2792   compiler.add(this, "node_background");
2793 }
2794
2795 void BackgroundNode::constant_fold(const ConstantFolder &folder)
2796 {
2797   ShaderInput *color_in = input("Color");
2798   ShaderInput *strength_in = input("Strength");
2799
2800   if ((!color_in->link && color == make_float3(0.0f, 0.0f, 0.0f)) ||
2801       (!strength_in->link && strength == 0.0f)) {
2802     folder.discard();
2803   }
2804 }
2805
2806 /* Holdout Closure */
2807
2808 NODE_DEFINE(HoldoutNode)
2809 {
2810   NodeType *type = NodeType::add("holdout", create, NodeType::SHADER);
2811
2812   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2813   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2814
2815   SOCKET_OUT_CLOSURE(holdout, "Holdout");
2816
2817   return type;
2818 }
2819
2820 HoldoutNode::HoldoutNode() : ShaderNode(node_type)
2821 {
2822 }
2823
2824 void HoldoutNode::compile(SVMCompiler &compiler)
2825 {
2826   float3 value = make_float3(1.0f, 1.0f, 1.0f);
2827
2828   compiler.add_node(NODE_CLOSURE_SET_WEIGHT, value);
2829   compiler.add_node(NODE_CLOSURE_HOLDOUT, compiler.closure_mix_weight_offset());
2830 }
2831
2832 void HoldoutNode::compile(OSLCompiler &compiler)
2833 {
2834   compiler.add(this, "node_holdout");
2835 }
2836
2837 /* Ambient Occlusion */
2838
2839 NODE_DEFINE(AmbientOcclusionNode)
2840 {
2841   NodeType *type = NodeType::add("ambient_occlusion", create, NodeType::SHADER);
2842
2843   SOCKET_INT(samples, "Samples", 16);
2844
2845   SOCKET_IN_COLOR(color, "Color", make_float3(1.0f, 1.0f, 1.0f));
2846   SOCKET_IN_FLOAT(distance, "Distance", 1.0f);
2847   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2848
2849   SOCKET_BOOLEAN(inside, "Inside", false);
2850   SOCKET_BOOLEAN(only_local, "Only Local", false);
2851
2852   SOCKET_OUT_COLOR(color, "Color");
2853   SOCKET_OUT_FLOAT(ao, "AO");
2854
2855   return type;
2856 }
2857
2858 AmbientOcclusionNode::AmbientOcclusionNode() : ShaderNode(node_type)
2859 {
2860 }
2861
2862 void AmbientOcclusionNode::compile(SVMCompiler &compiler)
2863 {
2864   ShaderInput *color_in = input("Color");
2865   ShaderInput *distance_in = input("Distance");
2866   ShaderInput *normal_in = input("Normal");
2867   ShaderOutput *color_out = output("Color");
2868   ShaderOutput *ao_out = output("AO");
2869
2870   int flags = (inside ? NODE_AO_INSIDE : 0) | (only_local ? NODE_AO_ONLY_LOCAL : 0);
2871
2872   if (!distance_in->link && distance == 0.0f) {
2873     flags |= NODE_AO_GLOBAL_RADIUS;
2874   }
2875
2876   compiler.add_node(NODE_AMBIENT_OCCLUSION,
2877                     compiler.encode_uchar4(flags,
2878                                            compiler.stack_assign_if_linked(distance_in),
2879                                            compiler.stack_assign_if_linked(normal_in),
2880                                            compiler.stack_assign(ao_out)),
2881                     compiler.encode_uchar4(compiler.stack_assign(color_in),
2882                                            compiler.stack_assign(color_out),
2883                                            samples),
2884                     __float_as_uint(distance));
2885 }
2886
2887 void AmbientOcclusionNode::compile(OSLCompiler &compiler)
2888 {
2889   compiler.parameter(this, "samples");
2890   compiler.parameter(this, "inside");
2891   compiler.parameter(this, "only_local");
2892   compiler.add(this, "node_ambient_occlusion");
2893 }
2894
2895 /* Volume Closure */
2896
2897 VolumeNode::VolumeNode(const NodeType *node_type) : ShaderNode(node_type)
2898 {
2899   closure = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID;
2900 }
2901
2902 void VolumeNode::compile(SVMCompiler &compiler, ShaderInput *param1, ShaderInput *param2)
2903 {
2904   ShaderInput *color_in = input("Color");
2905
2906   if (color_in->link)
2907     compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in));
2908   else
2909     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color);
2910
2911   compiler.add_node(
2912       NODE_CLOSURE_VOLUME,
2913       compiler.encode_uchar4(closure,
2914                              (param1) ? compiler.stack_assign(param1) : SVM_STACK_INVALID,
2915                              (param2) ? compiler.stack_assign(param2) : SVM_STACK_INVALID,
2916                              compiler.closure_mix_weight_offset()),
2917       __float_as_int((param1) ? get_float(param1->socket_type) : 0.0f),
2918       __float_as_int((param2) ? get_float(param2->socket_type) : 0.0f));
2919 }
2920
2921 void VolumeNode::compile(SVMCompiler &compiler)
2922 {
2923   compile(compiler, NULL, NULL);
2924 }
2925
2926 void VolumeNode::compile(OSLCompiler & /*compiler*/)
2927 {
2928   assert(0);
2929 }
2930
2931 /* Absorption Volume Closure */
2932
2933 NODE_DEFINE(AbsorptionVolumeNode)
2934 {
2935   NodeType *type = NodeType::add("absorption_volume", create, NodeType::SHADER);
2936
2937   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2938   SOCKET_IN_FLOAT(density, "Density", 1.0f);
2939   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2940
2941   SOCKET_OUT_CLOSURE(volume, "Volume");
2942
2943   return type;
2944 }
2945
2946 AbsorptionVolumeNode::AbsorptionVolumeNode() : VolumeNode(node_type)
2947 {
2948   closure = CLOSURE_VOLUME_ABSORPTION_ID;
2949 }
2950
2951 void AbsorptionVolumeNode::compile(SVMCompiler &compiler)
2952 {
2953   VolumeNode::compile(compiler, input("Density"), NULL);
2954 }
2955
2956 void AbsorptionVolumeNode::compile(OSLCompiler &compiler)
2957 {
2958   compiler.add(this, "node_absorption_volume");
2959 }
2960
2961 /* Scatter Volume Closure */
2962
2963 NODE_DEFINE(ScatterVolumeNode)
2964 {
2965   NodeType *type = NodeType::add("scatter_volume", create, NodeType::SHADER);
2966
2967   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2968   SOCKET_IN_FLOAT(density, "Density", 1.0f);
2969   SOCKET_IN_FLOAT(anisotropy, "Anisotropy", 0.0f);
2970   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2971
2972   SOCKET_OUT_CLOSURE(volume, "Volume");
2973
2974   return type;
2975 }
2976
2977 ScatterVolumeNode::ScatterVolumeNode() : VolumeNode(node_type)
2978 {
2979   closure = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID;
2980 }
2981
2982 void ScatterVolumeNode::compile(SVMCompiler &compiler)
2983 {
2984   VolumeNode::compile(compiler, input("Density"), input("Anisotropy"));
2985 }
2986
2987 void ScatterVolumeNode::compile(OSLCompiler &compiler)
2988 {
2989   compiler.add(this, "node_scatter_volume");
2990 }
2991
2992 /* Principled Volume Closure */
2993
2994 NODE_DEFINE(PrincipledVolumeNode)
2995 {
2996   NodeType *type = NodeType::add("principled_volume", create, NodeType::SHADER);
2997
2998   SOCKET_IN_STRING(density_attribute, "Density Attribute", ustring());
2999   SOCKET_IN_STRING(color_attribute, "Color Attribute", ustring());
3000   SOCKET_IN_STRING(temperature_attribute, "Temperature Attribute", ustring());
3001
3002   SOCKET_IN_COLOR(color, "Color", make_float3(0.5f, 0.5f, 0.5f));
3003   SOCKET_IN_FLOAT(density, "Density", 1.0f);
3004   SOCKET_IN_FLOAT(anisotropy, "Anisotropy", 0.0f);
3005   SOCKET_IN_COLOR(absorption_color, "Absorption Color", make_float3(0.0f, 0.0f, 0.0f));
3006   SOCKET_IN_FLOAT(emission_strength, "Emission Strength", 0.0f);
3007   SOCKET_IN_COLOR(emission_color, "Emission Color", make_float3(1.0f, 1.0f, 1.0f));
3008   SOCKET_IN_FLOAT(blackbody_intensity, "Blackbody Intensity", 0.0f);
3009   SOCKET_IN_COLOR(blackbody_tint, "Blackbody Tint", make_float3(1.0f, 1.0f, 1.0f));
3010   SOCKET_IN_FLOAT(temperature, "Temperature", 1500.0f);
3011   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
3012
3013   SOCKET_OUT_CLOSURE(volume, "Volume");
3014
3015   return type;
3016 }
3017
3018 PrincipledVolumeNode::PrincipledVolumeNode() : VolumeNode(node_type)
3019 {
3020   closure = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID;
3021 }
3022
3023 void PrincipledVolumeNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3024 {
3025   if (shader->has_volume) {
3026     ShaderInput *density_in = input("Density");
3027     ShaderInput *blackbody_in = input("Blackbody Intensity");
3028
3029     if (density_in->link || density > 0.0f) {
3030       attributes->add_standard(density_attribute);
3031       attributes->add_standard(color_attribute);
3032     }
3033
3034     if (blackbody_in->link || blackbody_intensity > 0.0f) {
3035       attributes->add_standard(temperature_attribute);
3036     }
3037
3038     attributes->add(ATTR_STD_GENERATED_TRANSFORM);
3039   }
3040
3041   ShaderNode::attributes(shader, attributes);
3042 }
3043
3044 void PrincipledVolumeNode::compile(SVMCompiler &compiler)
3045 {
3046   ShaderInput *color_in = input("Color");
3047   ShaderInput *density_in = input("Density");
3048   ShaderInput *anisotropy_in = input("Anisotropy");
3049   ShaderInput *absorption_color_in = input("Absorption Color");
3050   ShaderInput *emission_in = input("Emission Strength");
3051   ShaderInput *emission_color_in = input("Emission Color");
3052   ShaderInput *blackbody_in = input("Blackbody Intensity");
3053   ShaderInput *blackbody_tint_in = input("Blackbody Tint");
3054   ShaderInput *temperature_in = input("Temperature");
3055
3056   if (color_in->link)
3057     compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in));
3058   else
3059     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color);
3060
3061   compiler.add_node(NODE_PRINCIPLED_VOLUME,
3062                     compiler.encode_uchar4(compiler.stack_assign_if_linked(density_in),
3063                                            compiler.stack_assign_if_linked(anisotropy_in),
3064                                            compiler.stack_assign(absorption_color_in),
3065                                            compiler.closure_mix_weight_offset()),
3066                     compiler.encode_uchar4(compiler.stack_assign_if_linked(emission_in),
3067                                            compiler.stack_assign(emission_color_in),
3068                                            compiler.stack_assign_if_linked(blackbody_in),
3069                                            compiler.stack_assign(temperature_in)),
3070                     compiler.stack_assign(blackbody_tint_in));
3071
3072   int attr_density = compiler.attribute_standard(density_attribute);
3073   int attr_color = compiler.attribute_standard(color_attribute);
3074   int attr_temperature = compiler.attribute_standard(temperature_attribute);
3075
3076   compiler.add_node(__float_as_int(density),
3077                     __float_as_int(anisotropy),
3078                     __float_as_int(emission_strength),
3079                     __float_as_int(blackbody_intensity));
3080
3081   compiler.add_node(attr_density, attr_color, attr_temperature);
3082 }
3083
3084 void PrincipledVolumeNode::compile(OSLCompiler &compiler)
3085 {
3086   if (Attribute::name_standard(density_attribute.c_str())) {
3087     density_attribute = ustring("geom:" + density_attribute.string());
3088   }
3089   if (Attribute::name_standard(color_attribute.c_str())) {
3090     color_attribute = ustring("geom:" + color_attribute.string());
3091   }
3092   if (Attribute::name_standard(temperature_attribute.c_str())) {
3093     temperature_attribute = ustring("geom:" + temperature_attribute.string());
3094   }
3095
3096   compiler.add(this, "node_principled_volume");
3097 }
3098
3099 /* Principled Hair BSDF Closure */
3100
3101 NODE_DEFINE(PrincipledHairBsdfNode)
3102 {
3103   NodeType *type = NodeType::add("principled_hair_bsdf", create, NodeType::SHADER);
3104
3105   /* Color parametrization specified as enum. */
3106   static NodeEnum parametrization_enum;
3107   parametrization_enum.insert("Direct coloring", NODE_PRINCIPLED_HAIR_REFLECTANCE);
3108   parametrization_enum.insert("Melanin concentration", NODE_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION);
3109   parametrization_enum.insert("Absorption coefficient", NODE_PRINCIPLED_HAIR_DIRECT_ABSORPTION);
3110   SOCKET_ENUM(
3111       parametrization, "Parametrization", parametrization_enum, NODE_PRINCIPLED_HAIR_REFLECTANCE);
3112
3113   /* Initialize sockets to their default values. */
3114   SOCKET_IN_COLOR(color, "Color", make_float3(0.017513f, 0.005763f, 0.002059f));
3115   SOCKET_IN_FLOAT(melanin, "Melanin", 0.8f);
3116   SOCKET_IN_FLOAT(melanin_redness, "Melanin Redness", 1.0f);
3117   SOCKET_IN_COLOR(tint, "Tint", make_float3(1.f, 1.f, 1.f));
3118   SOCKET_IN_VECTOR(absorption_coefficient,
3119                    "Absorption Coefficient",
3120                    make_float3(0.245531f, 0.52f, 1.365f),
3121                    SocketType::VECTOR);
3122
3123   SOCKET_IN_FLOAT(offset, "Offset", 2.f * M_PI_F / 180.f);
3124   SOCKET_IN_FLOAT(roughness, "Roughness", 0.3f);
3125   SOCKET_IN_FLOAT(radial_roughness, "Radial Roughness", 0.3f);
3126   SOCKET_IN_FLOAT(coat, "Coat", 0.0f);
3127   SOCKET_IN_FLOAT(ior, "IOR", 1.55f);
3128
3129   SOCKET_IN_FLOAT(random_roughness, "Random Roughness", 0.0f);
3130   SOCKET_IN_FLOAT(random_color, "Random Color", 0.0f);
3131   SOCKET_IN_FLOAT(random, "Random", 0.0f);
3132
3133   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
3134   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
3135
3136   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
3137
3138   return type;
3139 }
3140
3141 PrincipledHairBsdfNode::PrincipledHairBsdfNode() : BsdfBaseNode(node_type)
3142 {
3143   closure = CLOSURE_BSDF_HAIR_PRINCIPLED_ID;
3144 }
3145
3146 /* Enable retrieving Hair Info -> Random if Random isn't linked. */
3147 void PrincipledHairBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3148 {
3149   if (!input("Random")->link) {
3150     attributes->add(ATTR_STD_CURVE_RANDOM);
3151   }
3152   ShaderNode::attributes(shader, attributes);
3153 }
3154
3155 /* Prepares the input data for the SVM shader. */
3156 void PrincipledHairBsdfNode::compile(SVMCompiler &compiler)
3157 {
3158   compiler.add_node(NODE_CLOSURE_SET_WEIGHT, make_float3(1.0f, 1.0f, 1.0f));
3159
3160   ShaderInput *roughness_in = input("Roughness");
3161   ShaderInput *radial_roughness_in = input("Radial Roughness");
3162   ShaderInput *random_roughness_in = input("Random Roughness");
3163   ShaderInput *offset_in = input("Offset");
3164   ShaderInput *coat_in = input("Coat");
3165   ShaderInput *ior_in = input("IOR");
3166   ShaderInput *melanin_in = input("Melanin");
3167   ShaderInput *melanin_redness_in = input("Melanin Redness");
3168   ShaderInput *random_color_in = input("Random Color");
3169
3170   int color_ofs = compiler.stack_assign(input("Color"));
3171   int tint_ofs = compiler.stack_assign(input("Tint"));
3172   int absorption_coefficient_ofs = compiler.stack_assign(input("Absorption Coefficient"));
3173
3174   ShaderInput *random_in = input("Random");
3175   int attr_random = random_in->link ? SVM_STACK_INVALID :
3176                                       compiler.attribute(ATTR_STD_CURVE_RANDOM);
3177
3178   /* Encode all parameters into data nodes. */
3179   compiler.add_node(NODE_CLOSURE_BSDF,
3180                     /* Socket IDs can be packed 4 at a time into a single data packet */
3181                     compiler.encode_uchar4(closure,
3182                                            compiler.stack_assign_if_linked(roughness_in),
3183                                            compiler.stack_assign_if_linked(radial_roughness_in),
3184                                            compiler.closure_mix_weight_offset()),
3185                     /* The rest are stored as unsigned integers */
3186                     __float_as_uint(roughness),
3187                     __float_as_uint(radial_roughness));
3188
3189   compiler.add_node(compiler.stack_assign_if_linked(input("Normal")),
3190                     compiler.encode_uchar4(compiler.stack_assign_if_linked(offset_in),
3191                                            compiler.stack_assign_if_linked(ior_in),
3192                                            color_ofs,
3193                                            parametrization),
3194                     __float_as_uint(offset),
3195                     __float_as_uint(ior));
3196
3197   compiler.add_node(compiler.encode_uchar4(compiler.stack_assign_if_linked(coat_in),
3198                                            compiler.stack_assign_if_linked(melanin_in),
3199                                            compiler.stack_assign_if_linked(melanin_redness_in),
3200                                            absorption_coefficient_ofs),
3201                     __float_as_uint(coat),
3202                     __float_as_uint(melanin),
3203                     __float_as_uint(melanin_redness));
3204
3205   compiler.add_node(compiler.encode_uchar4(tint_ofs,
3206                                            compiler.stack_assign_if_linked(random_in),
3207                                            compiler.stack_assign_if_linked(random_color_in),
3208                                            compiler.stack_assign_if_linked(random_roughness_in)),
3209                     __float_as_uint(random),
3210                     __float_as_uint(random_color),
3211                     __float_as_uint(random_roughness));
3212
3213   compiler.add_node(
3214       compiler.encode_uchar4(
3215           SVM_STACK_INVALID, SVM_STACK_INVALID, SVM_STACK_INVALID, SVM_STACK_INVALID),
3216       attr_random,
3217       SVM_STACK_INVALID,
3218       SVM_STACK_INVALID);
3219 }
3220
3221 /* Prepares the input data for the OSL shader. */
3222 void PrincipledHairBsdfNode::compile(OSLCompiler &compiler)
3223 {
3224   compiler.parameter(this, "parametrization");
3225   compiler.add(this, "node_principled_hair_bsdf");
3226 }
3227
3228 /* Hair BSDF Closure */
3229
3230 NODE_DEFINE(HairBsdfNode)
3231 {
3232   NodeType *type = NodeType::add("hair_bsdf", create, NodeType::SHADER);
3233
3234   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
3235   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
3236   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
3237
3238   static NodeEnum component_enum;
3239   component_enum.insert("reflection", CLOSURE_BSDF_HAIR_REFLECTION_ID);
3240   component_enum.insert("transmission", CLOSURE_BSDF_HAIR_TRANSMISSION_ID);
3241   SOCKET_ENUM(component, "Component", component_enum, CLOSURE_BSDF_HAIR_REFLECTION_ID);
3242   SOCKET_IN_FLOAT(offset, "Offset", 0.0f);
3243   SOCKET_IN_FLOAT(roughness_u, "RoughnessU", 0.2f);
3244   SOCKET_IN_FLOAT(roughness_v, "RoughnessV", 0.2f);
3245   SOCKET_IN_VECTOR(tangent, "Tangent", make_float3(0.0f, 0.0f, 0.0f));
3246
3247   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
3248
3249   return type;
3250 }
3251
3252 HairBsdfNode::HairBsdfNode() : BsdfNode(node_type)
3253 {
3254   closure = CLOSURE_BSDF_HAIR_REFLECTION_ID;
3255 }
3256
3257 void HairBsdfNode::compile(SVMCompiler &compiler)
3258 {
3259   closure = component;
3260
3261   BsdfNode::compile(compiler, input("RoughnessU"), input("RoughnessV"), input("Offset"));
3262 }
3263
3264 void HairBsdfNode::compile(OSLCompiler &compiler)
3265 {
3266   compiler.parameter(this, "component");
3267   compiler.add(this, "node_hair_bsdf");
3268 }
3269
3270 /* Geometry */
3271
3272 NODE_DEFINE(GeometryNode)
3273 {
3274   NodeType *type = NodeType::add("geometry", create, NodeType::SHADER);
3275
3276   SOCKET_IN_NORMAL(normal_osl,
3277                    "NormalIn",
3278                    make_float3(0.0f, 0.0f, 0.0f),
3279                    SocketType::LINK_NORMAL | SocketType::OSL_INTERNAL);
3280
3281   SOCKET_OUT_POINT(position, "Position");
3282   SOCKET_OUT_NORMAL(normal, "Normal");
3283   SOCKET_OUT_NORMAL(tangent, "Tangent");
3284   SOCKET_OUT_NORMAL(true_normal, "True Normal");
3285   SOCKET_OUT_VECTOR(incoming, "Incoming");
3286   SOCKET_OUT_POINT(parametric, "Parametric");
3287   SOCKET_OUT_FLOAT(backfacing, "Backfacing");
3288   SOCKET_OUT_FLOAT(pointiness, "Pointiness");
3289
3290   return type;
3291 }
3292
3293 GeometryNode::GeometryNode() : ShaderNode(node_type)
3294 {
3295   special_type = SHADER_SPECIAL_TYPE_GEOMETRY;
3296 }
3297
3298 void GeometryNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3299 {
3300   if (shader->has_surface) {
3301     if (!output("Tangent")->links.empty()) {
3302       attributes->add(ATTR_STD_GENERATED);
3303     }
3304     if (!output("Pointiness")->links.empty()) {
3305       attributes->add(ATTR_STD_POINTINESS);
3306     }
3307   }
3308
3309   ShaderNode::attributes(shader, attributes);
3310 }
3311
3312 void GeometryNode::compile(SVMCompiler &compiler)
3313 {
3314   ShaderOutput *out;
3315   ShaderNodeType geom_node = NODE_GEOMETRY;
3316   ShaderNodeType attr_node = NODE_ATTR;
3317
3318   if (bump == SHADER_BUMP_DX) {
3319     geom_node = NODE_GEOMETRY_BUMP_DX;
3320     attr_node = NODE_ATTR_BUMP_DX;
3321   }
3322   else if (bump == SHADER_BUMP_DY) {
3323     geom_node = NODE_GEOMETRY_BUMP_DY;
3324     attr_node = NODE_ATTR_BUMP_DY;
3325   }
3326
3327   out = output("Position");
3328   if (!out->links.empty()) {
3329     compiler.add_node(geom_node, NODE_GEOM_P, compiler.stack_assign(out));
3330   }
3331
3332   out = output("Normal");
3333   if (!out->links.empty()) {
3334     compiler.add_node(geom_node, NODE_GEOM_N, compiler.stack_assign(out));
3335   }
3336
3337   out = output("Tangent");
3338   if (!out->links.empty()) {
3339     compiler.add_node(geom_node, NODE_GEOM_T, compiler.stack_assign(out));
3340   }
3341
3342   out = output("True Normal");
3343   if (!out->links.empty()) {
3344     compiler.add_node(geom_node, NODE_GEOM_Ng, compiler.stack_assign(out));
3345   }
3346
3347   out = output("Incoming");
3348   if (!out->links.empty()) {
3349     compiler.add_node(geom_node, NODE_GEOM_I, compiler.stack_assign(out));
3350   }
3351
3352   out = output("Parametric");
3353   if (!out->links.empty()) {
3354     compiler.add_node(geom_node, NODE_GEOM_uv, compiler.stack_assign(out));
3355   }
3356
3357   out = output("Backfacing");
3358   if (!out->links.empty()) {
3359     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_backfacing, compiler.stack_assign(out));
3360   }
3361
3362   out = output("Pointiness");
3363   if (!out->links.empty()) {
3364     if (compiler.output_type() != SHADER_TYPE_VOLUME) {
3365       compiler.add_node(
3366           attr_node, ATTR_STD_POINTINESS, compiler.stack_assign(out), NODE_ATTR_FLOAT);
3367     }
3368     else {
3369       compiler.add_node(NODE_VALUE_F, __float_as_int(0.0f), compiler.stack_assign(out));
3370     }
3371   }
3372 }
3373
3374 void GeometryNode::compile(OSLCompiler &compiler)
3375 {
3376   if (bump == SHADER_BUMP_DX)
3377     compiler.parameter("bump_offset", "dx");
3378   else if (bump == SHADER_BUMP_DY)
3379     compiler.parameter("bump_offset", "dy");
3380   else
3381     compiler.parameter("bump_offset", "center");
3382
3383   compiler.add(this, "node_geometry");
3384 }
3385
3386 int GeometryNode::get_group()
3387 {
3388   ShaderOutput *out;
3389   int result = ShaderNode::get_group();
3390
3391   /* Backfacing uses NODE_LIGHT_PATH */
3392   out = output("Backfacing");
3393   if (!out->links.empty()) {
3394     result = max(result, NODE_GROUP_LEVEL_1);
3395   }
3396
3397   return result;
3398 }
3399
3400 /* TextureCoordinate */
3401
3402 NODE_DEFINE(TextureCoordinateNode)
3403 {
3404   NodeType *type = NodeType::add("texture_coordinate", create, NodeType::SHADER);
3405
3406   SOCKET_BOOLEAN(from_dupli, "From Dupli", false);
3407   SOCKET_BOOLEAN(use_transform, "Use Transform", false);
3408   SOCKET_TRANSFORM(ob_tfm, "Object Transform", transform_identity());
3409
3410   SOCKET_IN_NORMAL(normal_osl,
3411                    "NormalIn",
3412                    make_float3(0.0f, 0.0f, 0.0f),
3413                    SocketType::LINK_NORMAL | SocketType::OSL_INTERNAL);
3414
3415   SOCKET_OUT_POINT(generated, "Generated");
3416   SOCKET_OUT_NORMAL(normal, "Normal");
3417   SOCKET_OUT_POINT(UV, "UV");
3418   SOCKET_OUT_POINT(object, "Object");
3419   SOCKET_OUT_POINT(camera, "Camera");
3420   SOCKET_OUT_POINT(window, "Window");
3421   SOCKET_OUT_NORMAL(reflection, "Reflection");
3422
3423   return type;
3424 }
3425
3426 TextureCoordinateNode::TextureCoordinateNode() : ShaderNode(node_type)
3427 {
3428 }
3429
3430 void TextureCoordinateNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3431 {
3432   if (shader->has_surface) {
3433     if (!from_dupli) {
3434       if (!output("Generated")->links.empty())
3435         attributes->add(ATTR_STD_GENERATED);
3436       if (!output("UV")->links.empty())
3437         attributes->add(ATTR_STD_UV);
3438     }
3439   }
3440
3441   if (shader->has_volume) {
3442     if (!from_dupli) {
3443       if (!output("Generated")->links.empty()) {
3444         attributes->add(ATTR_STD_GENERATED_TRANSFORM);
3445       }
3446     }
3447   }
3448
3449   ShaderNode::attributes(shader, attributes);
3450 }
3451
3452 void TextureCoordinateNode::compile(SVMCompiler &compiler)
3453 {
3454   ShaderOutput *out;
3455   ShaderNodeType texco_node = NODE_TEX_COORD;
3456   ShaderNodeType attr_node = NODE_ATTR;
3457   ShaderNodeType geom_node = NODE_GEOMETRY;
3458
3459   if (bump == SHADER_BUMP_DX) {
3460     texco_node = NODE_TEX_COORD_BUMP_DX;
3461     attr_node = NODE_ATTR_BUMP_DX;
3462     geom_node = NODE_GEOMETRY_BUMP_DX;
3463   }
3464   else if (bump == SHADER_BUMP_DY) {
3465     texco_node = NODE_TEX_COORD_BUMP_DY;
3466     attr_node = NODE_ATTR_BUMP_DY;
3467     geom_node = NODE_GEOMETRY_BUMP_DY;
3468   }
3469
3470   out = output("Generated");
3471   if (!out->links.empty()) {
3472     if (compiler.background) {
3473       compiler.add_node(geom_node, NODE_GEOM_P, compiler.stack_assign(out));
3474     }
3475     else {
3476       if (from_dupli) {
3477         compiler.add_node(texco_node, NODE_TEXCO_DUPLI_GENERATED, compiler.stack_assign(out));
3478       }
3479       else if (compiler.output_type() == SHADER_TYPE_VOLUME) {
3480         compiler.add_node(texco_node, NODE_TEXCO_VOLUME_GENERATED, compiler.stack_assign(out));
3481       }
3482       else {
3483         int attr = compiler.attribute(ATTR_STD_GENERATED);
3484         compiler.add_node(attr_node, attr, compiler.stack_assign(out), NODE_ATTR_FLOAT3);
3485       }
3486     }
3487   }
3488
3489   out = output("Normal");
3490   if (!out->links.empty()) {
3491     compiler.add_node(texco_node, NODE_TEXCO_NORMAL, compiler.stack_assign(out));
3492   }
3493
3494   out = output("UV");
3495   if (!out->links.empty()) {
3496     if (from_dupli) {
3497       compiler.add_node(texco_node, NODE_TEXCO_DUPLI_UV, compiler.stack_assign(out));
3498     }
3499     else {
3500       int attr = compiler.attribute(ATTR_STD_UV);
3501       compiler.add_node(attr_node, attr, compiler.stack_assign(out), NODE_ATTR_FLOAT3);
3502     }
3503   }
3504
3505   out = output("Object");
3506   if (!out->links.empty()) {
3507     compiler.add_node(texco_node, NODE_TEXCO_OBJECT, compiler.stack_assign(out), use_transform);
3508     if (use_transform) {
3509       Transform ob_itfm = transform_inverse(ob_tfm);
3510       compiler.add_node(ob_itfm.x);
3511       compiler.add_node(ob_itfm.y);
3512       compiler.add_node(ob_itfm.z);
3513     }
3514   }
3515
3516   out = output("Camera");
3517   if (!out->links.empty()) {
3518     compiler.add_node(texco_node, NODE_TEXCO_CAMERA, compiler.stack_assign(out));
3519   }
3520
3521   out = output("Window");
3522   if (!out->links.empty()) {
3523     compiler.add_node(texco_node, NODE_TEXCO_WINDOW, compiler.stack_assign(out));
3524   }
3525
3526   out = output("Reflection");
3527   if (!out->links.empty()) {
3528     if (compiler.background) {
3529       compiler.add_node(geom_node, NODE_GEOM_I, compiler.stack_assign(out));
3530     }
3531     else {
3532       compiler.add_node(texco_node, NODE_TEXCO_REFLECTION, compiler.stack_assign(out));
3533     }
3534   }
3535 }
3536
3537 void TextureCoordinateNode::compile(OSLCompiler &compiler)
3538 {
3539   if (bump == SHADER_BUMP_DX)
3540     compiler.parameter("bump_offset", "dx");
3541   else if (bump == SHADER_BUMP_DY)
3542     compiler.parameter("bump_offset", "dy");
3543   else
3544     compiler.parameter("bump_offset", "center");
3545
3546   if (compiler.background)
3547     compiler.parameter("is_background", true);
3548   if (compiler.output_type() == SHADER_TYPE_VOLUME)
3549     compiler.parameter("is_volume", true);
3550   compiler.parameter(this, "use_transform");
3551   Transform ob_itfm = transform_inverse(ob_tfm);
3552   compiler.parameter("object_itfm", ob_itfm);
3553
3554   compiler.parameter(this, "from_dupli");
3555
3556   compiler.add(this, "node_texture_coordinate");
3557 }
3558
3559 /* UV Map */
3560
3561 NODE_DEFINE(UVMapNode)
3562 {
3563   NodeType *type = NodeType::add("uvmap", create, NodeType::SHADER);
3564
3565   SOCKET_STRING(attribute, "attribute", ustring());
3566   SOCKET_IN_BOOLEAN(from_dupli, "from dupli", false);
3567
3568   SOCKET_OUT_POINT(UV, "UV");
3569
3570   return type;
3571 }
3572
3573 UVMapNode::UVMapNode() : ShaderNode(node_type)
3574 {
3575 }
3576
3577 void UVMapNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3578 {
3579   if (shader->has_surface) {
3580     if (!from_dupli) {
3581       if (!output("UV")->links.empty()) {
3582         if (attribute != "")
3583           attributes->add(attribute);
3584         else
3585           attributes->add(ATTR_STD_UV);
3586       }
3587     }
3588   }
3589
3590   ShaderNode::attributes(shader, attributes);
3591 }
3592
3593 void UVMapNode::compile(SVMCompiler &compiler)
3594 {
3595   ShaderOutput *out = output("UV");
3596   ShaderNodeType texco_node = NODE_TEX_COORD;
3597   ShaderNodeType attr_node = NODE_ATTR;
3598   int attr;
3599
3600   if (bump == SHADER_BUMP_DX) {
3601     texco_node = NODE_TEX_COORD_BUMP_DX;
3602     attr_node = NODE_ATTR_BUMP_DX;
3603   }
3604   else if (bump == SHADER_BUMP_DY) {
3605     texco_node = NODE_TEX_COORD_BUMP_DY;
3606     attr_node = NODE_ATTR_BUMP_DY;
3607   }
3608
3609   if (!out->links.empty()) {
3610     if (from_dupli) {
3611       compiler.add_node(texco_node, NODE_TEXCO_DUPLI_UV, compiler.stack_assign(out));
3612     }
3613     else {
3614       if (attribute != "")
3615         attr = compiler.attribute(attribute);
3616       else
3617         attr = compiler.attribute(ATTR_STD_UV);
3618
3619       compiler.add_node(attr_node, attr, compiler.stack_assign(out), NODE_ATTR_FLOAT3);
3620     }
3621   }
3622 }
3623
3624 void UVMapNode::compile(OSLCompiler &compiler)
3625 {
3626   if (bump == SHADER_BUMP_DX)
3627     compiler.parameter("bump_offset", "dx");
3628   else if (bump == SHADER_BUMP_DY)
3629     compiler.parameter("bump_offset", "dy");
3630   else
3631     compiler.parameter("bump_offset", "center");
3632
3633   compiler.parameter(this, "from_dupli");
3634   compiler.parameter(this, "attribute");
3635   compiler.add(this, "node_uv_map");
3636 }
3637
3638 /* Light Path */
3639
3640 NODE_DEFINE(LightPathNode)
3641 {
3642   NodeType *type = NodeType::add("light_path", create, NodeType::SHADER);
3643
3644   SOCKET_OUT_FLOAT(is_camera_ray, "Is Camera Ray");
3645   SOCKET_OUT_FLOAT(is_shadow_ray, "Is Shadow Ray");
3646   SOCKET_OUT_FLOAT(is_diffuse_ray, "Is Diffuse Ray");
3647   SOCKET_OUT_FLOAT(is_glossy_ray, "Is Glossy Ray");
3648   SOCKET_OUT_FLOAT(is_singular_ray, "Is Singular Ray");
3649   SOCKET_OUT_FLOAT(is_reflection_ray, "Is Reflection Ray");
3650   SOCKET_OUT_FLOAT(is_transmission_ray, "Is Transmission Ray");
3651   SOCKET_OUT_FLOAT(is_volume_scatter_ray, "Is Volume Scatter Ray");
3652   SOCKET_OUT_FLOAT(ray_length, "Ray Length");
3653   SOCKET_OUT_FLOAT(ray_depth, "Ray Depth");
3654   SOCKET_OUT_FLOAT(diffuse_depth, "Diffuse Depth");
3655   SOCKET_OUT_FLOAT(glossy_depth, "Glossy Depth");
3656   SOCKET_OUT_FLOAT(transparent_depth, "Transparent Depth");
3657   SOCKET_OUT_FLOAT(transmission_depth, "Transmission Depth");
3658
3659   return type;
3660 }
3661
3662 LightPathNode::LightPathNode() : ShaderNode(node_type)
3663 {
3664 }
3665
3666 void LightPathNode::compile(SVMCompiler &compiler)
3667 {
3668   ShaderOutput *out;
3669
3670   out = output("Is Camera Ray");
3671   if (!out->links.empty()) {
3672     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_camera, compiler.stack_assign(out));
3673   }
3674
3675   out = output("Is Shadow Ray");
3676   if (!out->links.empty()) {
3677     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_shadow, compiler.stack_assign(out));
3678   }
3679
3680   out = output("Is Diffuse Ray");
3681   if (!out->links.empty()) {
3682     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_diffuse, compiler.stack_assign(out));
3683   }
3684
3685   out = output("Is Glossy Ray");
3686   if (!out->links.empty()) {
3687     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_glossy, compiler.stack_assign(out));
3688   }
3689
3690   out = output("Is Singular Ray");
3691   if (!out->links.empty()) {
3692     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_singular, compiler.stack_assign(out));
3693   }
3694
3695   out = output("Is Reflection Ray");
3696   if (!out->links.empty()) {
3697     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_reflection, compiler.stack_assign(out));
3698   }
3699
3700   out = output("Is Transmission Ray");
3701   if (!out->links.empty()) {
3702     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_transmission, compiler.stack_assign(out));
3703   }
3704
3705   out = output("Is Volume Scatter Ray");
3706   if (!out->links.empty()) {
3707     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_volume_scatter, compiler.stack_assign(out));
3708   }
3709
3710   out = output("Ray Length");
3711   if (!out->links.empty()) {
3712     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_length, compiler.stack_assign(out));
3713   }
3714
3715   out = output("Ray Depth");
3716   if (!out->links.empty()) {
3717     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_depth, compiler.stack_assign(out));
3718   }
3719
3720   out = output("Diffuse Depth");
3721   if (!out->links.empty()) {
3722     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_diffuse, compiler.stack_assign(out));
3723   }
3724
3725   out = output("Glossy Depth");
3726   if (!out->links.empty()) {
3727     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_glossy, compiler.stack_assign(out));
3728   }
3729
3730   out = output("Transparent Depth");
3731   if (!out->links.empty()) {
3732     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_transparent, compiler.stack_assign(out));
3733   }
3734
3735   out = output("Transmission Depth");
3736   if (!out->links.empty()) {
3737     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_transmission, compiler.stack_assign(out));
3738   }
3739 }
3740
3741 void LightPathNode::compile(OSLCompiler &compiler)
3742 {
3743   compiler.add(this, "node_light_path");
3744 }
3745
3746 /* Light Falloff */
3747
3748 NODE_DEFINE(LightFalloffNode)
3749 {
3750   NodeType *type = NodeType::add("light_falloff", create, NodeType::SHADER);
3751
3752   SOCKET_IN_FLOAT(strength, "Strength", 100.0f);
3753   SOCKET_IN_FLOAT(smooth, "Smooth", 0.0f);
3754
3755   SOCKET_OUT_FLOAT(quadratic, "Quadratic");
3756   SOCKET_OUT_FLOAT(linear, "Linear");
3757   SOCKET_OUT_FLOAT(constant, "Constant");
3758
3759   return type;
3760 }
3761
3762 LightFalloffNode::LightFalloffNode() : ShaderNode(node_type)
3763 {
3764 }
3765
3766 void LightFalloffNode::compile(SVMCompiler &compiler)
3767 {
3768   ShaderInput *strength_in = input("Strength");
3769   ShaderInput *smooth_in = input("Smooth");
3770
3771   ShaderOutput *out = output("Quadratic");
3772   if (!out->links.empty()) {
3773     compiler.add_node(NODE_LIGHT_FALLOFF,
3774                       NODE_LIGHT_FALLOFF_QUADRATIC,
3775                       compiler.encode_uchar4(compiler.stack_assign(strength_in),
3776                                              compiler.stack_assign(smooth_in),
3777                                              compiler.stack_assign(out)));
3778   }
3779
3780   out = output("Linear");
3781   if (!out->links.empty()) {
3782     compiler.add_node(NODE_LIGHT_FALLOFF,
3783                       NODE_LIGHT_FALLOFF_LINEAR,
3784                       compiler.encode_uchar4(compiler.stack_assign(strength_in),
3785                                              compiler.stack_assign(smooth_in),
3786                                              compiler.stack_assign(out)));
3787   }
3788
3789   out = output("Constant");
3790   if (!out->links.empty()) {
3791     compiler.add_node(NODE_LIGHT_FALLOFF,
3792                       NODE_LIGHT_FALLOFF_CONSTANT,
3793                       compiler.encode_uchar4(compiler.stack_assign(strength_in),
3794                                              compiler.stack_assign(smooth_in),
3795                                              compiler.stack_assign(out)));
3796   }
3797 }
3798
3799 void LightFalloffNode::compile(OSLCompiler &compiler)
3800 {
3801   compiler.add(this, "node_light_falloff");
3802 }
3803
3804 /* Object Info */
3805
3806 NODE_DEFINE(ObjectInfoNode)
3807 {
3808   NodeType *type = NodeType::add("object_info", create, NodeType::SHADER);
3809
3810   SOCKET_OUT_VECTOR(location, "Location");
3811   SOCKET_OUT_FLOAT(object_index, "Object Index");
3812   SOCKET_OUT_FLOAT(material_index, "Material Index");
3813   SOCKET_OUT_FLOAT(random, "Random");
3814
3815   return type;
3816 }
3817
3818 ObjectInfoNode::ObjectInfoNode() : ShaderNode(node_type)
3819 {
3820 }
3821
3822 void ObjectInfoNode::compile(SVMCompiler &compiler)
3823 {
3824   ShaderOutput *out = output("Location");
3825   if (!out->links.empty()) {
3826     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_OB_LOCATION, compiler.stack_assign(out));
3827   }
3828
3829   out = output("Object Index");
3830   if (!out->links.empty()) {
3831     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_OB_INDEX, compiler.stack_assign(out));
3832   }
3833
3834   out = output("Material Index");
3835   if (!out->links.empty()) {
3836     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_MAT_INDEX, compiler.stack_assign(out));
3837   }
3838
3839   out = output("Random");
3840   if (!out->links.empty()) {
3841     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_OB_RANDOM, compiler.stack_assign(out));
3842   }
3843 }
3844
3845 void ObjectInfoNode::compile(OSLCompiler &compiler)
3846 {
3847   compiler.add(this, "node_object_info");
3848 }
3849
3850 /* Particle Info */
3851
3852 NODE_DEFINE(ParticleInfoNode)
3853 {
3854   NodeType *type = NodeType::add("particle_info", create, NodeType::SHADER);
3855
3856   SOCKET_OUT_FLOAT(index, "Index");
3857   SOCKET_OUT_FLOAT(random, "Random");
3858   SOCKET_OUT_FLOAT(age, "Age");
3859   SOCKET_OUT_FLOAT(lifetime, "Lifetime");
3860   SOCKET_OUT_POINT(location, "Location");
3861 #if 0 /* not yet supported */
3862   SOCKET_OUT_QUATERNION(rotation, "Rotation");
3863 #endif
3864   SOCKET_OUT_FLOAT(size, "Size");
3865   SOCKET_OUT_VECTOR(velocity, "Velocity");
3866   SOCKET_OUT_VECTOR(angular_velocity, "Angular Velocity");
3867
3868   return type;
3869 }
3870
3871 ParticleInfoNode::ParticleInfoNode() : ShaderNode(node_type)
3872 {
3873 }
3874
3875 void ParticleInfoNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3876 {
3877   if (!output("Index")->links.empty())
3878     attributes->add(ATTR_STD_PARTICLE);
3879   if (!output("Random")->links.empty())
3880     attributes->add(ATTR_STD_PARTICLE);
3881   if (!output("Age")->links.empty())
3882     attributes->add(ATTR_STD_PARTICLE);
3883   if (!output("Lifetime")->links.empty())
3884     attributes->add(ATTR_STD_PARTICLE);
3885   if (!output("Location")->links.empty())
3886     attributes->add(ATTR_STD_PARTICLE);
3887 #if 0 /* not yet supported */
3888   if (!output("Rotation")->links.empty())
3889     attributes->add(ATTR_STD_PARTICLE);
3890 #endif
3891   if (!output("Size")->links.empty())
3892     attributes->add(ATTR_STD_PARTICLE);
3893   if (!output("Velocity")->links.empty())
3894     attributes->add(ATTR_STD_PARTICLE);
3895   if (!output("Angular Velocity")->links.empty())
3896     attributes->add(ATTR_STD_PARTICLE);
3897
3898   ShaderNode::attributes(shader, attributes);