Short Contents

6.4 Standard Functions

3Delight supports all the standard Shading Language (SL) built-in shadeops and constructs. The complete set of standard shadeops is listed below. Descriptions are kept brief, if any, since shadeops are already described in great details in the RenderMan specifications. Shadeops marked with (*) contain specific extensions and those marked with (**) are not part of the current standard. It is also possible to link shaders with C or C++ code to add new shadeops, see RSL Plug-ins.

3Delight supports all predefined shader variables. It doesn't follow strictly the 3.2 RenderMan Interface specification though: some shaders have access to more variables.

6.4.1 Mathematics

float radians ( float degrees )
float degrees ( float radians )
float sin ( float radians )
float asin ( float a )
float cos ( float radians )
float acos ( float a )
float tan ( float radians )
float atan ( float a )
float atan ( float y, float x )
float sqrt ( float x )

Returns the square root of x. The domain is [0..infinity]. If x<0 this shadeop will return 0.

float inversesqrt ( float x )

Returns 1.0/sqrt(x). The domain of this function is [0..infinity[. If x<0 this shadeop will return infinity(35).

float pow ( float x, y )

Returnx x**y.

float exp ( float x )

Returns pow(e, x), the natural logarithm of x.

float log ( float x [, base] )

Returns the natural logarithm of x. If the optional base is specified, returns the logarithm of x in the specified base. The domain of this function is [0..infinity[. If x<0 this shadeop will return -infinity.

float sign ( float x )

Returns:

  • -1 if x<0
  • 1 if x>=0
float mod ( float x, y )

Returns x modulus y. More formally, returns a value in the range [0..y], for which mod(x, y) = x - n*y, for some integer n.

float abs ( float x )

Returns the absolute value of x.

float floor ( float x )
float ceil ( float x )
float round ( float x )
type min ( type x, y, ... )
type max ( type x, y, ... )
type clamp ( type x, min, max )

min() and max() take two or more arguments of the same type and return the minimum and maximum values, respectively. clamp() will return min if x is smaller than min, max if x is greater than max and x otherwise. type can be a float or a 3-tuple. When running on 3-tuples, these shadeops will consider one component at a time (eg. min(point(1,2,3), point(4,3,2)) will return point(1,2,2));

float step ( float min, value )
float smoothstep ( float min, max, value )

step() returns 0 if value is less than min; otherwise it returns 1. smoothstep() returns 0 if value is less than min, 1 if value is greater than or equal to max, and returns a Hermite interpolation between 0 and 1 when value is in the range [min..max[.

type mix ( type x, y, alpha )

Returns x*(1-alpha) + y*alpha. For multi-component types (color, point, ...), the operation is performed for each component.

float filterstep ( float edge, value, ... )
float filterstep ( float edge, value1, value2, ... )

Similar to step() but the return value is filtered over the area of the micropolygon being shaded. Useful for shader anti-aliasing. Filtering kernel is selected using the "filter" optional parameter. Recognized filters are `gaussian', `box', `triangle' and `catmull-rom'. Default is `catmull-rom'. If two values are provided, return value is filtered in the range [value1..value2].

type spline ( [string basis ;] float value; type begin, p1, ..., pn, end)
type spline ( [string basis ;] float value; type p[])

Interpolates a point on a curve defined by begin, p1 to pn, and end control points. value should lie between 0 and 1, otherwise the return value will be clamped to either p1 or pn. The default basis is the `catmull-rom' spline(36). Other possible splines are `bezier', `bspline', `hermite' and `linear'. Any unknown spline is assumed to be `linear'. Any recognized spline may be prefixed by `solve', such as `solvecatmull-rom'. In such a case, the shadeop becomes a root solver and may be used as an invert function.

type Du ( type x )
type Dv ( type x )
type Deriv ( type num; float denom )

Du() and Dv() compute the parametric derivative of the given expressions with respect to the u and the v parameters of the underlying surface (37).

6.4.2 Noise and Random

type noise ( float x )
type noise ( float x, y )
type noise ( point Pt )
type noise ( point Pt; float w )

1D, 2D, 3D and 4D noise function. type can be float, color, point or vector.

type pnoise ( float x, period )
type pnoise ( float x, y, xperiod, yperiod )
type pnoise ( point Pt, Ptperiod )
type pnoise ( point Pt; float w; point Ptperiod; float wperiod )

Same as noise but has periodicity period. Maximum period is 256.

type cellnoise ( float x )
type cellnoise ( float x, y )
type cellnoise ( point Pt )
type cellnoise ( point Pt, float w )

Cellular noise functions (1D, 2D, 3D and 4D).

type random ( )

Returns a random float, color or point. Returned range is [0..1]. Can return uniform or varying values. Here is a trick to put a random color in each grid of micropolygons:

uniform float red = random();
uniform float green = random();
uniform float blue = random();

Ci = color( red, green, blue );

6.4.3 Geometry, Matrices and Colors

float xcomp ( point Pt )
float ycomp ( point Pt )
float zcomp ( point Pt )
void setxcomp ( output point Pt; float x )
void setycomp ( output point Pt; float y )
void setzcomp ( output point Pt; float z )

Gets or sets the x, y, or z component of a point (or vector).

float comp ( matrix M; float row, col )

Returns M[row,col].

void setcomp ( output matrix M; float row, col, x )

M[row,col] = x.

float comp ( color c; float i )
void setcomp ( output color c, float i, x )

Returns or sets the "ith" component of the given color.

point transform ( string [fromspace,] tospace; point Pt )
point transform ( [string fromspace;] matrix M; point Pt )
point transform ( string [fromspace,] tospace; vector V )
point transform ( [string fromspace;] matrix M; vector V )
point transform ( string [fromspace,] tospace; normal N )
point transform ( [string fromspace;] matrix M; normal N )

Transforms a point, vector or normal from a given space (fromspace) to another space (tospace). If the optional fromspace is not given, it is assumed to be the `current' space. Refer to Table 6.3 for the complete list of valid space names.

vector vtransform ( string [fromspace,] tospace; vector V )
vector vtransform ( [string fromspace;] matrix M; vector V )
normal ntransform ( string [fromspace,] tospace; normal Nr )
normal ntransform ( [string fromspace;] matrix M; normal Nr )

Same as transform() above but specifically selects a transform on normals or vectors (no polymorphism).

NOTE

One should use transform() instead since that shadeop will correctly select the appropriate transform depending on the parameter type.

color ctransform ( string [fromspace,] tospace; color src_color )

Transforms color src_color from color space fromspace to color space tospace. If the optional fromspace is not specified, it is assumed to be `rgb'. 3Delight recognizes the following color spaces: RGB, HSV, HSL, YIQ and XYZ(38). If an unknown color space is given, 3Delight returns src_color.

float distance ( point Pt1, Pt2 )
float length ( vector V )
vector normalize ( vector V )

distance() returns the distance between two points. length() returns the length (norm) of the given vector. normalize() divides the given vector by its length (making it of unit length). All three operations involve a square root.

float ptlined ( point Pt1, Pt2, Q )

Returns minimum distance between a point Q and a segment defined by Pt1 and Pt2.

point rotate ( point Q; float angle; point Pt1, Pt2 )

Rotates a point Q around the line defined by Pt1 and Pt2, by a given angle. New point position is returned. Note that angle is assumed to be in radians.

float area ( point Pt [; string strategy] )

Returns length(Du(Pt)^Dv(Pt)), which is approximately the area of one micro-polygon on the surface defined by Pt. The strategy variable can take two values:

` shading'
Compute area of the micro-polygon based on surface derivatives. This will produce smoothly varying areas if smooth derivatives are enabled (see section Other Attributes).
` dicing'
Compute area of micro-polygons using their geometry, regardless of smooth derivatives.

If no strategy is supplied, `shading' will be assumed.

vector faceforward ( vector N, I[, Nref] )

Flips N, if needed, so it faces in the direction opposite to I. Nref gives the element surface normal; if not provided, NRef is set to Ng.

vector reflect ( vector I, N )

Returns the vector which is the reflection of I around N. Note that N must be of unit length.

vector refract ( vector I, Nr; float eta )

Returns the refracted vector for the incoming vector I, surface normal Nr and index of refraction ratio eta. Nr must be of unit length.

float depth ( point Pt )

Returns the normalized z coordinate of Pt in camera space. Return value is in the range [0..1] (0=near clipping plane, 1=far clipping plane). Pt is assumed to be defined in `current' space.

normal calculatenormal ( point Pt )

Computes the normal of a surface defined by Pt. Often used after a displacement operation on Pt. Equivalent to Du(Pt)^Dv(Pt), but faster.

float determinant ( matrix M )
matrix inverse ( matrix M )
matrix translate ( matrix M; point Tr )
matrix rotate ( matrix M; float angle; vector axis )
matrix scale ( matrix M; point Sc )

Basic matrix operations. The angle parameter passed to rotate() is assumed to be in radians.

6.4.4 Lighting

color ambient ( )

Returns the contribution from ambient lights. A light is considered ambient if it does not contain an illuminate() or solar() statement. It is not available in lightsource shaders.

color diffuse ( vector Nr )

Computes the diffuse light contribution. Lights placed behind the surface element being shaded are not considered. Nr is assumed to be of unit length. Light shaders that contain a parameter named uniform float __nondiffuse are evaluated only if the parameter is set to 0. Not available in lightsource shaders (see section Predefined Shader Parameters).

color specular ( vector Nr, V; float roughness ) *

Computes the specular light contribution. Lights placed behind the object are not considered. Nr and V are assumed to be of unit length. Light shaders that contain a parameter named uniform float __nonspecular are evaluated only if the parameter is set to 0. Not available in lightsource shaders (see section Predefined Shader Parameters).

color specularbrdf ( vector L, Nr, V; float roughness )

Computes the specular light contribution. Similar to specular() but receives a L variable (incoming light vector) enabling it to run in custom illuminance() loops.

color specularstd ( normal N; vector V; float roughness)

This is the standard specular model described in all graphic books since 3Delight implements its own specular model in specular.

color specularstd( normal N; vector V; float roughness )
{
    extern point P;
    color C = 0;
    point Nn = normalize(N);
    point Vn = normalize(V);

    illuminance(P, Nn, PI/2)
    {
        extern vector L;
        extern color Cl;

        vector H = normalize(normalize(L)+Vn);
        C += Cl * pow(max(0.0, Nn.H), 1/roughness);
    }

    return C;
}
Listing 6.6: specularstd() implementation.


color phong ( vector Nr, V; float size )

Computes specular light contribution using the Phong illumination model. Nr and V are assumed to be of unit length. As in specular(), this function is also sensitive to the __nonspecular light shader parameter. Not available in lightsource shaders.

color bsdf ( vector L; normal N; ... )
color[] bsdf ( vector L; normal N; ... )

Evalutes one of the built-in BSDF available in 3Delight. L is the incoming light direction and N the surface normal. The optional parameters are the distribution-related ones from The trace Shadeop.

void fresnel ( vector I, N; float eta; output float Kr, Kt [; output vector R, T] )

Uses the Fresnel formula to compute the reflection coefficient Kr and refraction (or transmission) coefficient Kt given and incident direction I, the surface normal N and the relative index of refraction eta. Note that eta is the ratio of the index of refraction in the volume containing the incident vector to that of the volume being entered: a ray entering a water volume from a void volume would need an eta of approximately 1.0/1.3. Here is a noteworthy quotation from "The RenderMan Companion":

In most cases, a ray striking a refractive material is partly reflected and partly refracted. The function fresnel() calculates the respective fractions. It may also return the reflected and refracted direction vectors, so that is subsumes refract().

If R and T are supplied, they are set to the direction vector of the reflected and the transmitted (refracted) ray, respectively.

6.4.5 Ray Tracing

6.4.5.1 Common Parameters

All the ray tracing shadeops can receive a number of common optional parameters, these are described in Table 6.10. Specific optional parameters are described with each shadeop individually.

Name Type Default Description
"label" uniform string "" Specifies a label to attach to the ray. Refer to Ray Labels.
"subset" uniform string "" Specifies a subset of objects which are included in ray tracing computations. Refer to Trace Group Membership.
"bias" uniform float -1 Specifies a bias for ray's starting point to avoid potentially erroneous intersections with emitting surface. A value of `-1' forces 3Delight to take the default value as specified by Attribute "trace" "bias".
"hitmode" uniform string "default" Can be used to override the shading mode set on the intersected object with hitmode. Only applies when the object's visibility was set with the "diffuse" "specular" or "int transmission" visibility attributes. Refer to Primitives Visibility and Ray Tracing Attributes.
"hitsides" uniform string "default" This can be used to override which sides of surfaces a ray can hit. The default is to hit both sides of surfaces with RiSides 2 and the front side of surfaces with RiSides 1. A value of `reversed' will hit both sides of surfaces with RiSides 2 and the back side of surfaces with RiSides 1. Other possible values are `front', `back' and `both' which act the same regardless of RiSides.
"raytype" uniform string "default" Can be either `specular', `diffuse' or `transmission'. This is accepted by trace(), occlusion(), indirectdiffuse() and gather() to override the default ray type. The ray type changes which visibility attributes are considered to know if a ray can hit a given primitive.
"raypruning" uniform float 1 This option enables (enabled by default) or disables (not advised) automatic ray-pruning in the ray-tracer. Disabling ray pruning may result in catastrophic performance if shaders are not written properly.
"weight" varying color 1 This parameter can be used to adjust the importance of the rays traced by a shadeop. This eventually allows fewer rays to be traced where their impact on the image is less. As a general rule, its value should be the factor which will multiply the result of the shadeop. Proper use of this parameter can provide large gains of performance.
Table 6.10: Common optional parameters to ray tracing functions.

6.4.5.2 The trace Shadeop

color trace ( point Pt; vector R [; output float dist]; ... )
color[] trace ( point Pt; vector R [; output float dist]; ... )

The trace shadeop is a general tool for collecting incoming light at point Pt on the surface. In its simplest form, it will collect light from direction R.

If the optional output parameter dist is specified, it will contain the distance to the nearest intersection point or a very large number (> 1e30) when no intersections are found. Note that all parameters must be in "current" space. trace() accepts several optional named parameters which are explained below.

float samples
Specifies the number of samples to use. Higher sample counts will improve quality, at the cost of performance.
float maxdist
Specifies a distance after which no intersections are checked. The default value is 1e38 which in practice means that there is no maximum distance for intersections.

string distribution
This parameter specifies which BRDF trace() will use to gather light from the scene. The possible values are uniform, cosine, oren-nayar, blinn, ashikhmin-shirley, cook-torrance, ward, glass-ggx and hair. The default value is uniform. Each distribution requires some specific additional parameters listed below. See also the bsdf shadeop which allows the same distributions to be used in an illuminance loop with direct light.
float samplecone
Specifies an angle in radians which, together with Pt and R, describes a cone in which trace() will gather light. The angle specified is the cone's half angle, meaning PI/2 will sample a hemisphere. This applies to the uniform and cosine distributions. The default value is 0.
vector wo
This vector specifies the viewer direction for the oren-nayar, blinn, ashikhmin-shirley, cook-torrance, ward, glass-ggx and hair distributions. This is typically -I. Note that when this parameter is needed, the R parameter is expected to be the surface normal, except for the hair distribution where it is a vector pointing toward the tip of the fiber.
vector horizon
This optional vector specifies the normal of a horizon plane which cuts off the requested distribution. This would usually be the geometric normal when it is different from the shading normal.
float roughness
Specifies the roughness of the surface for the oren-nayar, blinn, ashikhmin-shirley, cook-torrance, ward and glass-ggx distributions. The valid range is between 0 and 1, except for oren-nayar which has no upper limit (in practice, there is little difference above PI/2). For the blinn and ashikhmin-shirley distributions, roughness is converted to an exponent using this formula: pow( roughness, -3.5 ) - 1
float roughnessv
Specifies the roughness in the second axis for the anisotropic ashikhmin-shirley , glass-ggx and ward distributions.
vector udir
Specifies the orientation of the u direction for the anisotropic ashikhmin-shirley, glass-ggx and ward distributions. This is the directon where roughness applies. roughnessv is applied in a perpendicular direction on the surface. The udir vector does not need to be strictly tangent to the surface as 3Delight will project it on the surface itself. With the hair brdf, this parameter is used to specify hair fiber orientation and eccentricity. See Using the hair BSDF.
color[] eta
Specifies an index of refraction to compute a fresnel effect for the blinn, ashikhmin-shirley and cook-torrance distributions. This is optional and not specifying it is equivalent to using 0, providing full reflection. If a color is provided, the fresnel equations are computed separately for each channel. If an array of two colors is provided, the second value is taken to be the extinction coefficient for conductors (metals). Note that giving a float or color value can be done without using an array. For the glass-ggx distribution, this is the index of refraction of the glass, with a default value of 1.5. For the hair distribution, this is the index of refraction of the hair fiber and the default value is 1.55.
color absorption
Specifies the absorption coefficient of the hair fiber for the hair distribution. This affects the color and intensity of all lobes but the first one.
float[] lobeparameters
Specifies per lobe BRDF parameters for the hair distribution. Each lobe requires 4 parameters and up to 4 lobes are supported. See Using the hair BSDF. For the glass-ggx distribution, this specifies reflection and refraction weights which allow adjusting the relative contribution of each part.
uniform string environmentmap
Specifies an environment map to use as incoming light in directions where there is no geometry.
uniform string environmentspace
Specifies a coordinate system to orient the environment map.
color environmenttint
Specifies a multiplicative factor for the content of the environment map.

output varying color transmission
Returns the transmission in the traced direction. This takes into account both coverage (if sampling a cone) and the opacity of the surfaces hit by rays. It is not influenced by the specified environment map. There is no speed penalty to get the transmission from trace()
IMPORTANT

The returned value is exactly the same as what would have been returned by the transmission shadeop with the important difference that transmission() defaults to intersecting objects visible to transmission rays while trace() uses specular rays.

output varying color environmentcontribution
Returns the contribution of the environment map to the output of trace.
output varying color unshadowedenvironment
Returns the contribution that the environment map would have to the output of trace if no regular geometry was hit in any direction. If area lights area being sampled, they will still block the environment map contribution to this output.
uniform float samplearealights
Setting this to 1 means this trace() call will sample area lights which are set to the "trace" sampling strategy (see The light samplingstrategy attribute). The default is 0 which means area lights are not seen by the trace shadeop.
output varying color arealightcontribution
Returns the contribution of area lights to the output of trace. Note that using only this output of trace can be faster as 3Delight will know that some surfaces do not need to be shaded. Tracing rays can also be skipped entirely if there are no area lights in the scene.
output varying color unshadowedarealight
Returns the contribution that area lights would have to the output of trace if no regular geometry was blocking any of them.

The second version of trace which returns an array of colors can be used with some distributions to get separate results for their components. In that case, arrays of colors are also output by the environmentcontribution, unshadowedenvironment, arealightcontribution and unshadowedarealight output parameters. This is supported by the following distributions:

glass-ggx
The array must be of length two. There is one value for reflected rays and one for refracted rays.
hair
The array must be one fourth the length of the lobeparameters parameter array.

EXAMPLE

/* Trace a ray, only considering intersections closer than 10 units. 
   Intersection distance is stored in ``dist'' and intersection
   color in ``c''. If no intersection, dist will be very large. */
float dist; 
color c = trace( P, Nf, dist, "maxdist", 10 );

Using the hair BSDF

The hair BSDF is a fairly complex function which simulates several effects observed on real hair fibers. It supports a variable number of major lobes, usually named R, TT, TRT, etc which are numbered according to the number of times the light crosses the hair fiber. Here is an example which retrieves the contribution of each lobe separately:

float lobeparams[12] =
{
    1, tilt, roughness[0], roughness_azimuthal[0],
    1, tilt, roughness[1], roughness_azimuthal[1],
    1, tilt, roughness[2], roughness_azimuthal[2]
};

vector orient = eccentricity * rotate(
	normalize(dPdu), random_hair_orient * 2 * PI, 0, point(dPdv) );

color lobes[3];
lobes = trace(
    P, dPdv,
    "distribution", "hair",
    "wo", normalize(-I),
    "samplearealights", 1,
    "samples", 300,
    "eta", 1.55,
    "udir", orient,
    "absorption", absorption,
    "lobeparameters", lobeparams );

Ci = lobes[0] + lobes[1] + lobes[2];

The lobeparameters array contains 4 values for each lobe to be computed. They are, in order:

weight
This scales the contribution of each lobe. Note that with values greater than 1, internal normalization might be done in order to avoid energy amplification by the bsdf. This means changing these weights can change the look of the hair but will generally not make it brighter overall.
scales tilt
The angle of the scales which form the surface of the hair fiber, in radians. It affects the position of the highlight. This will typically be in the range of -0.05 to -0.1 radians for human hair (negative to tilt towards the root). Note that the final position is computed from this angle differently for each lobe so using the same value for all lobes will produce distinct highlights.
longitudinal roughness
This will change the size of the lobe along the length of the hair. It behaves just like roughness for other bsdfs.
azimuthal roughness
This will change the size of the lobe across the hair fiber. As the simulated hair is cylindrical, this parameter has little effect on the R and TT lobes. Its effect is most visible on the sharpness of the TRT lobe (glints).

6.4.5.3 Other Ray Tracing Shadeops

float trace ( point Pt; vector R )

This is an obsolete form which returns the distance to the nearest intersection, when looking from Pt in the direction specified by the unit vector R. Pt and R must lie in `current' space. This function intersects objects that are visible to transmission rays and is strictly equivalent to:

float distance;
trace( P, dir, distance, "type", "tranmission" );

color transmission ( point Pt1, Pt2, ... )

Determines the visibility between Pt1 and Pt2 using ray tracing. Returns color 1 if un-occluded and color 0 if totally occluded. In-between values indicate the presence of a translucent surface between Pt1 and Pt2. Only objects tagged as visible to transmission rays are considered during the operation (using Attribute "visibility" "transmission", Attributes). Pt1 and Pt2 must lie in `current' space. When tracing area light shadows, it is usually better for performance to trace from the surface to the light. In addition to standard ray tracing optional parameters (see Table 6.10), this shadeop also accepts:

varying float samplecone
Same as for the trace shadeop.
uniform float samples
Same as for the trace shadeop.

float occlusion ( point Pt; vector R; [float samples;] ... ) *

Computes the amount of occlusion, using ray tracing, as seen from Pt in direction R and solid angle 2*PI (hemisphere). Returns 1.0 if all rays hit some geometry (totally occluded) and 0.0 if there are no hits (totally un-occluded).

  • Pt and R must lie in `current' space and R must be of unit length.
  • The optional samples parameter specifies the number of rays to trace to compute occlusion; if absent or set to 0, the value is taken from Attribute "irradiance" "nsamples" (see section Attributes).
  • This shadeop accepts many optional token/value pairs. These are explained in Table 6.11.
  • More on ambient occlusion in Ambient Occlusion and Point-Based Occlusion and Color Bleeding.

EXAMPLE

/* Returns the amount of occlusion using default number of
   samples */
float hemi_occ = occlusion( P, Ng );

/* Returns the amount of occlusion for the hemisphere surrounding P,
   uses a rough approximation with 8 samples */
hemi_occ = occlusion( P, Ng, 8 );

/* Same as above, but only consider objects closer than 10 units and
   in a solid angle of Pi/4 */
hemi_occ = occlusion( P, Ng, 8, "maxdist", 10, "coneangle", PI/4 );

/* Same as above, but only consider light coming from a hemisphere
   oriented toward (0,1,0) */
uniform vector sky = vector (0, 1, 0);
hemi_occ =
    occlusion( P, Ng, 8, "maxdist", 10, "coneangle", PI/2, "axis", sky );

color indirectdiffuse ( point Pt; vector R; [float samples;] ... ) *

Computes diffuse illumination due to diffuse-to-diffuse indirect light transport by sampling a hemisphere around a point Pt and direction R. Use this shadeop to render color bleeding effects.

  • Pt and R must lie in `current' space and R must be of unit length.
  • This function makes it possible to lookup into an HDR image when sampled rays do not hit any geometry; the map is specified using the "environmentmap" parameter as shown in Table 6.11.
  • Computing the occlusion while calling this function is also possible (through the occlusion parameter), with the following restriction: indirectdiffuse() only sees geometry tagged as visible to reflections, as opposed to occlusion() which sees geometry visible to shadows. For more informations about visibility attributes refer to Attributes.
Note

This shadeop will automatically perform "final gathering" if there is a photon map attached to geometry. Using photon maps will speed up global illumination computations tremendously using this shadeop, more about photons maps and final gathering in Photon Mapping and Final Gathering.

color indirectdiffuse ( string envmap; vector dir ) *

Returns the irradiance coming from an environment and a given direction (dir must be of unit length). The environment can be either an environment map or a light probe. Environment maps have to be generated by tdlmake with the `-envcube' or `-envlatl' parameter. All other textures are interpreted as light probes. Probe images generated by software such as HDRShop and stored in other formats (such as Radiance files with an `.hdr' extension) must be converted by tdlmake to a normal TIFF texture. It is perfectly correct (and recommended) to provide high dynamic range images to this shadeop. Refer to Image Based Lighting for more information.

Name Type Description
"coneangle" uniform float Controls the solid angle considered. Default covers the entire hemisphere. Default is PI/2.
"axis" uniform vector If specified, and different from vector 0, indicates the direction of the light casting hemisphere. Rays that are not directed toward this axis are not considered. This is useful for specifying skylights.
"samplebase" uniform float Scales the amount of jittering of the start position of rays. The default is to jitter over the area of one micropolygon. Default is 1.0 .
"maxdist" uniform float Only consider intersections closer than this distance. Default is 1e38.
"environmentmap" uniform string Specifies an environment map to probe when a ray doesn't hit any geometry.
"environmentspace" uniform string Specifies the coordinate system to use when accessing the provided environment map. Default is "world".
"distribution" uniform string or vector[] Specifies what distribution to use when tracing rays. `uniform' and `cosine' distributions are recognized. One can also specify an environment map file that describes the distribution to use (an HDRI of the environment is most appropriate for this). Finally, an array of vectors can be given to specify an arbitrary, user generated distribution. Default is "cosine". Not supported in point-based occlusion.
"environmentcolor" output varying color If specified, it is set to the color resulting from environment map lookups on unnoccluded samples. If no environment map is provided, this variable is set to black.
"environmentdir" output varying vector If specified, it is set to the average un-occluded direction, which is the average of all sampled directions that do not hit any geometry. Note that this vector is defined in `current' space, so it is necessary to transform it to `world' space if an environment() lookup is intended.
"occlusion" output varying float [indirectdiffuse() only] If specified, it is set to the fraction of the sampled cone which was occluded by geometry.
"adaptive" uniform float Enables or disables adaptive sampling. Default is 1 (enable). Doesn't affect point-based algorithm.
"minsamples" uniform float Specifies the minimum number of samples for adaptive sampling. Defaults to samples if it is less than 64 and samples/4 otherwise.
"falloffmode" "uniform float" Specifies the falloff curve to use. 0 is exponential (default) and 1 is polynomial.
"falloff" "uniform float" This shapes the falloff curve. In the exponential case the curve is exp( -falloff * hitdist ) and in the polynomial case it is pow(1-hitdist/maxdist, falloff)(39). The default value is 0 for no falloff.
Table 6.11: occlusion() and indirectdiffuse() optional parameters.

Additionally, for point-cloud based occlusion and color bleeding, the following parameters are recognized:

Name Type Description
"pointbased" uniform float This has to be set to 1 if point-based occlusion and color bleeding are to be used. Default is 0.
"filename" uniform string Specifies the name of a point cloud file to be used to compute the occlusion and color bleeding.
"filenames" uniform string[] Like "filename" but allows several point cloud files to be used together.
"hitsides" uniform string Specifies which side(s) of the point cloud's samples will produce occlusion. Can take values of "front", "back" or "both". Default is "front".
"maxsolidangle" uniform float This is a quality vs speed control when a point cloud is used. Default is 0.1 .
"clamp" uniform float If set to 1, attempts to reduce the excessive occlusion caused by the point-based algorithm, at the cost of speed. Default is 0.
"sortbleeding" uniform float If set to 1 and "clamp" is also set to 1, this forces the color bleeding computations to take the ordering of surfaces into account. It is recommanded to set this parameter to 1. Default is 0.
"coordsystem" uniform string The coordinate system where the point cloud data was stored. Default is "world".
"areachannel" uniform string Specifies the name of the channel to be used as area of the points. Defaults is "_area".
"radiositychannel" uniform string Specifies the name of the channel to be used as radiosity of the points. Default is "_radiosity" or the first color channel if the one specified is not found. The channel may be either a single float or a color.
"opacitychannel" uniform string Specifies the name of the channel to be used as opacity of the points. Default is "_opacity". The channel may be a single float or a color.
"distance" output varying float If specified, it is set to the average distance of surfaces which contribute to the effect.
"shadingrate" uniform float Controls the shading rate for this specific shadeop and overrides the corresponding irradiance attribute (see section Global Illumination Attributes).
"maxerror" uniform float Controls the maximum error for this specific shadeop and overrides the corresponding irradiance attribute (see section Global Illumination Attributes).
Table 6.12: Parameters controlling point-based occlusion and color bleeding.

float gather ( string category; point P; vector dir; float angle; float samples, ... ) statement [else statement ]

gather is considered as a language construct and is detailed in The Gather Construct.

color subsurface ( point Pt; ... )

Returns subsurface lighting at the given point Pt. Subsurface light transport is automatically computed in a separate pass. More about subsurface scattering in Subsurface Scattering.

Name Description
"uniform srting type" Specifies the algorithm to use for subsurface scattering. This can be either "pointlcoud" or "raytrace".
"float samples" For raytracing algorithm, specifies the number of rays to trace.
"uniform string groupname" Allows lookups of arbitrary subsurface groups in the scene. Not supported by the ray tracing algorithm.
"uniform string filename" Specifies the name of the point-cloud file to use. This tells the renderer to operate in point-cloud mode. Refer to Two Pass Point-Based Subsurface Scattering.
"uniform string filenames[]" Like "filename" but allows several point-cloud files to be used together.
"uniform string coordsystem" Specifies the coordinate system where the points in the point-cloud are to be interpreted. The default is "world" and this has no effect if "filename" is not used.
"color scattering" Specifies the reduced scattering coefficient when operating in point-cloud mode.
"color absorption" Specifies the absorption coefficient when operating in point-cloud mode.
"color diffusemeanfreepath" Specifies the diffuse mean free path when operating in point-cloud mode.
"color albedo" Specifies albedo (reflectance) when operating in point-cloud mode.
"float ior" Specifies the index of refraction when operating in point-cloud mode.
"float unitlength"(40) Specifies the object scale when operating in point-cloud mode.
"uniform float smooth" May enable smoother results when the point density is too low for the amount of desired scattering. 0 disables the smoothing and 1 enables it. Values smaller or greater than 1 may also be used to control the amount of smoothing.
"uniform float followtopology"(41) The subsurface approximation assumes that the surface topology is that of a flat surface. Very different geometry can give incorrect results. Setting this parameter to 1 will enable an attempt to correct for this. In the ray-tracing case this parameter will generate much more noise and higher samples are required.
"uniform string areachannel" Specifies which channel of the point cloud is used as the area of samples. Default is "_area".
"uniform string radiancechannel" Specifies which channel of the point cloud is used as the radiance of samples. Default is "_radiance_t" or the first color channel if the one specified is not found.
"float singlescatter" Specifies the weighting of single scattering when using the ray traced version of the shadeop. A value of 0 disables single scattering and a value of 1 gives the normal contribtion.
"output color singlescattercontribution" Contains the contribution of single scattering only, without the multiple scattering component. Works only with the ray traced version of the shadeop.
"color irradiance" Specifies the irradiance entering the surface at this point. This is an optional parameter that is used by the renderer to compute fast approximations in certain contexts. The renderer will issue warning R5063 when this parameter is needed but not provided (usually when combining subsurface scattering and global illumination). A good approximation to this value is the diffuse illumination at the surface point.
"uniform string subset" Specifies the subset of objects to consider for raytraced subsurface. See Trace Group Membership.
"uniform string label" Specifies a label to attach to the rays. See Ray Labels.
Table 6.13: subsurface() optional parameters.

float photonmap ( string mapname; point P; vector N; ...)

This shadeop performs a lookup in the photonmap specified by mapname at the surface location described by (P, N). This shadeop accepts the following additional parameters:

"float estimator"
An integer specifying the number of photons to use for the lookup. More photons will give smoother results. The default is 50.
"string lookuptype"
Can take one of the following values:
` irradiance'
Returns the irradiance at the specified location.
` radiance'
Returns the radiance at the specified location. Note that 3DELIGHT stores a coarse estimation of the radiance which is not meant for direct visualization. It is mainly useful for the indirectdiffuse() shadeop when performing final gathering as explained in Final Gathering.
"float mindepth"
When performing irradiance lookups, specifies the minimum number of bounces for a photon to be considered in irradiance computation. For example, setting a mindepth of `1' will avoid photons that come directly from the light sources (meaning that the call will return only indirect light contribution).

EXAMPLE

/* Perform an irradiance lookup using 100 photons */
color res = photonmap( "gloabal.map", P, Nf, "estimator", 100 );

Refer to Photon Mapping for more details about photon maps.

float caustic ( point P; vector N )

This shadeop performs a lookup in the caustic photon map that belongs to the surface being shaded at the surface location described by (P, N). This shadeop can be written using the photonmap() shadeop:

color caustic( point P, normal N )
{
    uniform float estimator = 50;
    uniform string causticmap = "";

    attribute( "photon:causticmap", causticmap );
    attribute( "photon:estimator", estimator );

    color c = 0;

    if( causticmap!="" )
    { 
        c = photonmap(
                causticmap, P, N,
                "lookuptype", "irradiance",
                "estimator", estimator );
    }

    return c;
}
Table 6.14: caustic() shadeop implementation using the photonmap() shadeop.

6.4.6 Texture Mapping

type texture ( string texturename[float channel]; ... )
type texture ( string texturename[float channel]; float s, t; ... )
type texture ( string texturename[float channel]; float s1, t1, s2, t2, s3, t3, s4, t4; ... )

Returns a filtered texture value, at the specified texture coordinates. type can be either a float or a color. If no texture coordinates are provided, s and t are used. An optional channel can be specified to select a starting channel in the texture. This can be useful when a texture contains more than three channels. Use tdlmake to prepare textures for improved performance and memory usage (see section Using the Texture Optimizer - tdlmake). texture() accepts a list of optional parameters as summarized in Table 6.16. EXAMPLE

/* Sharper result (width<1) */
color c = texture( "grid.tdl", s, t, "width", 0.8 );

/* Returns the green component */
float green = texture( "grid.tdl"[1] );

/* Returns the alpha channel, or 1.0 (opaque) if no
   alpha channel is present */
float alpha = texture( "grid.tdl"[3], "fill", 1.0 );

/* Returns an _unfiltered_ color from the texture */
color unfiltered = texture( "grid.tdl", s, t, s, t, s, t, s, t );

Note that this shadeop will return proper linear-space colors if the texture has a gamma specification. Refer to Texture Mapping in Linear Space for details.

The texture() shadeop also includes support for MARI's UDIM tile mapping. Simply provide a file name with the string UDIM in it and that will be replaced by the 4 digit tile number before looking for the texture.

type ptexture ( string texturename; uniform float channel; float faceindex; ... )
type ptexture ( string texturename; uniform float channel; float faceindex; float s, t; ... )
type ptexture ( string texturename; uniform float channel; float faceindex; float s1, t1, s2, t2, s3, t3, s4, t4; ... )

Same as texture but acts on "ptextures". ptexture() accepts a list of optional parameters as summerized in Table 6.15.

Name Type Default Description
"blur" float 0 Refer to Table 6.16
"width" float 1.0 Refer to Table 6.16
"lerp" uniform float 0 If set to 1, lookups will be interpolated between the two closest mipmaps. This usually achieves higher quality.
"fill" uniform color 0 Refer to Table 6.16
"filter" uniform string "gaussian" Specifies the reconstruction filter to use when accessing the ptexture map. Supported filters are: `gaussian', `point', `bilinear', `bspline', `catmull-rom', `box' and `mitchell'. The default is `mitchell'.
"expand" uniform float 0 Refer to Table 6.16
Table 6.15: ptexture() optional parameters.

type environment ( string texturename[channel]; vector V; ... )
type environment ( string texturename[channel]; vector V1, V2, V3, V4; ... )

Returns a filtered texture value from an environment map, for a specified direction. As in texture(), an optional channel can be specified to select a starting channel when performing texture lookups. Use tdlmake to prepare cubic and long-lat envmaps. If an unprepared TIFF is given to environment(), it is considered as a lat-long environment map. environement() recognizes the same list of optional parameters as texture(). If the given file name is "raytrace", environment uses ray tracing instead of texture lookups, which of course is more expensive. Only geometry tagged as visible to "trace" rays is considered (Attribute "visibility" "trace" 1 ). Optional parameters accepted by this shadeop are listed in Table 6.16. When using ray tracing, this environment() also accepts the same optional parameters as trace (see trace shadeop). EXAMPLE

/* Do an env lookup */
vector Nf = faceforward( N, I );
color c = environment( "env.tdl", vtransform("world", Nf) );

/* Only fetch the alpha channel, if no alpha present, returns 1 */
float red_comp = environment( "env.tdl"[3], Nf, "fill", 1 );

Note that this shadeop will return proper linear-space colors if the texture has a gamma specification. Refer to Texture Mapping in Linear Space for details.

Name Type Default Description
"blur" varying float 0 Specifies an additional length to be added to texture lookup region in both s and t, expressed in units of texture coordinates (range = [0..1]). A value of 1.0 would request that the entire texture be blurred in the result. In ray tracing, specifies the half angle of the blur cone, in radians.
"sblur" varying float 0.0 Specifies "blur" in s only.
"tblur" varying float 0.0 Specifies "blur" in t only.
"width" uniform float 1.0 Multiplies the width of the filtered area in both s and t.
"swidth" uniform float 1.0 Specifies "width" in s only.
"twidth" uniform float 1.0 Specifies "width" in t only.
"samples" uniform float 16/4 Specifies the number of samples to use for shadow() and environment() lookups. This influences the antialias quality. A value of 16 is recommended for shadow maps and 4 is recommended for both DSM and environment() lookups. texture() only uses this value with the `box' filter. In ray tracing mode, specifies the number of rays to trace.
"fill" uniform color 0 If a channel is not present in the texture, use this value.
"filter" uniform string "gaussian" Specifies the reconstruction filter to use when accessing the texture map. Supported filters are: `gaussian', `triangle' and `box'.
"bias" uniform float 0.225 Used to prevent self-shadowing in shadow(). If set to 0, the global bias is used, as specified by Option "shadow" "bias" (see section Options);
"usedmipmap" output varying float - texture() only. Returns the mipmap level used for the lookup.
"alpha" output varying float - texture() only. Outputs the alpha channel of the texture or 1 if there is none. 3Delight considers as an alpha the last channel of 2 or 4 channel textures.
"expand" uniform float 0 If this is set to 1, textures with only one or two channels have their first channel duplicated to all channels when doing a color lookup. 0 leaves the default behavior of setting the missing channels to the value provided by "fill".
"lerp" uniform float 0 If set to 1, lookups will be interpolated between the two closest mipmaps (doesn't apply to shadow map lookups). This usually achieves higher quality.
Table 6.16: texture() shadow() and environment() optional parameters.


type shadow ( string shadowmap[float channel]; point Pt; ... ) *
type shadow ( string shadowmap[float channel]; point Pt1, Pt2, Pt3, Pt4; ... ) *

Computes occlusion at a point in space using a shadow map or a deep shadow map. Shadow lookups are automatically anti-aliased. When using deep shadow maps, colored shadows and motion blur are correctly computed. If the file name passed to shadow() is "raytrace" then ray tracing is used to compute shadows. Note that if ray tracing is used, only objects tagged as visible to shadows are considered (using Attribute "visibility" "transmission"). Optional parameters to shadow() are described in Table 6.16. Additional information for both shadow maps and deep shadow maps are found in Shadows.

void bake ( string bakefile; float s, t; type value )

This shadeop writes the given value (of type float, point or color) to a file named bakefile. This file can then be converted to a texture map using tdlmake (see section Using the Texture Optimizer - tdlmake) or a call to RiMakeTexture. We recommend using the `.bake' extension for files containing such "baked" data.

By defaul, data is saved in a human-readable ASCII format for easy inspection but saving in binary format is also possible. To do so one can concatenate the "&binary" string to the file name, as shown in Listing 6.7.

surface bake2d(
    string bakefile = "";
    float binary = 0; )
{
      Ci = noise(s*32, t*16);	

      if( binary == 1 )
          bake( concat(bakefile,"&binary"), s, t, Ci );
      else
          bake( bakefile, s, t, Ci );
}
Listing 6.7: Baking into a binary file.

Note that baking in 2D space is only appropriate when the underlying surface has a well-behaved 2D parametrisation (which is often the case in most models that had undergone some UV unwrapping). More about baking in Baking.

float bake3d ( string bakefile; string channels; point P, normal N, ... )

This shadeops records a set of values to the file bakefile for the given position and normal. Values to record are supplied as named parameter pairs. For example:

float occlusion = occlusion( P, N, samples, "maxdist", 3 );
bake3d( texturename, "", P, N, "surface_color", Ci, "occlusion", occlusion );

Note that the channels parameter is ignored in the current implementation. The files created by the bake3d() are unfiltered point clouds which can be used directly or converted to brick maps as explained in Brick Maps; in both cases data is directly accessible through texture3d() (see texture3d shadeop). bake3d() returns 1 if the write is successful and 0 otherwise. It takes various optional parameters listed in Table 6.17.

Name Type Default Description
"coordsystem" string "world" Specifies the coordinate system into which the values are written.
"radius" varying float based on grid Specifies the radius of the disk (or sphere if N is 0) covered by each baked sample.
"radiusscale" float 1.0 Allows scaling of the radius value without overriding it. In point cloud files, the size of a disk affects the importance of its orientation for lookups with texture3d. Larger disks are less likely to be picked if the normals do not match. They are more strongly oriented.
"interpolate" float 0.0 When set to 1.0, saves the centers of the micro-polygons instead of its corners. This is primarily useful for point-based occlusion and color bleeding (see section Point-Based Imaging Pipeline).
Table 6.17: bake3d() optional parameters.


Additionally, there is two channel names that are reserved for use with point-based occlusion and color bleeding (see section Point-Based Occlusion and Color Bleeding):

` float _area'
Specifies the area of the given point. It is not necessary to specify this channel if it is not different from the actual micro-polygon area.
` color _radiosity'
Specifies the radiosity at the given point. This is used for point-based color bleeding.

float texture3d ( string bakefile; point P, normal N, ... )

This shadeop is used to perform lookups in files created by bake3d() (see bake3d shadeop). Its syntax is indeed very similar to bake3d():

float occlusion;
texture3d( texturename, P, N, "surface_color", Ci, "occlusion", occlusion );

texture3d() returns 1 if the lookup was successful and 0 otherwise. It takes various optional parameters listed in Table 6.18.

Name Type Default Description
"coordsystem" string "world" Specifies the coordinate system from which the values are written.
"filterradius" float - Specifies the radius of the lookup filter. If none is given, the renderer computes one that is faithful to the shaded element derivatives.
"filterscale" float 1 A multiplier on the radius of the lookup filter. It is not necessary to specify `filterradius' to use this parameter.
"maxdepth" float - Sets a maximum depth for lookups. If not specified, maximum depth is used. Works for both point clouds and brick maps.
Table 6.18: texture3d() optional parameters.

6.4.7 String Manipulation

string concat ( string str1, ..., strn )

Concatenates one or more strings into one string.

string format ( string pattern; val1, ..., valn ) *

Similar to the C sprintf function. pattern is a string containing conversion characters. Recognized conversion characters are:

%f
Formats a float using the style [-]ddd.ddd. Number of fractional digits depends on the precision used (see example).
%e
Formats a float using the style [-]d.ddde dd (that is, exponential notation). This is the recommended conversion for floats when precision matters.
%g
The floating point is converted to style %f or %e. If a precision specifier is used, %f is applied. Otherwise, the format which uses the least characters to represent the number is used.
%d
Equivalent to %.0f, useful to format integers.
%p
Formats a point-like type (point, vector, normal) using the style [%f %f %f].
%c
Same as %p, but for colors.
%m
Formats a matrix using the style [%f %f %f %f, %f %f %f %f, %f %f %f %f, %f %f %f %f] if a precision specifier is used. Otherwise, each element is formatted to full precision as with %g.
%s
Formats a string.
%h
Formats a shader handle. Light shaders and co-shaders will use the handle of their declaration. The null shader object is output as <null>. Surface, Displacement, etc become <surface>, <displacement>, etc.

Note that all conversion characters recognize the precision specifier.

EXAMPLE

/* Formats a float using exponential notation */
string expo = format( "%e", sqrt(27) );

/* Formats a float, with 5 decimals in the fractional part */ 
point p = sqrt(5);
string precision5 = format( "p = %.5p", p );

/* Aligns text */
string aligned = format( "%20s", "align me please" ); 
void printf ( string pattern; val1, ..., valn ) *

Same as format() but prints the formatted string to `stdout' instead of returning a string.

float match ( string pattern, subject )

Does a string pattern match on subject. Returns 1 if pattern exists anywhere within subject, 0 otherwise. The pattern can be any standard regex(42) expression.

float stringhash ( string str )
color stringhash ( string str )

Takes a string as input and returns a hash in form of a float or a color. Provided to output such AOVs as object and material identifiers for further masking and compositing.

6.4.8 Message Passing and Information

float textureinfo ( string texturename, fieldname; output uniform type variable )

Returns information about a particular texture, environment or shadow map. fieldname specifies the name of the information as listed in Table 6.19. If fieldname is known, and variable is of the correct type, textureinfo() returns 1.0. Otherwise, 0.0 is returned.

EXAMPLE

/* mapres[0] gets map resolution in x,
   mapres[1] gets map resolution in y */

uniform float mapres[2];
textureinfo( "grid.tdl", "resolution", mapres );

/* Get current to camera matrix used to create the shadow map */

uniform matrix Nl;
if( textureinfo( "main-spot.tdl", "viewingmatrix", Nl )!= 1.0 )
{
    Nl = 1;
}

Additionally, a special call to textureinfo() is provided to test texture existence:

color C;
if( textureinfo(texturename, "exists", 0) )
    C = texture(texturename);
else
    C = errorcolor;

The existence check also checks for validity so if the file exists on disk but is not a valid texture, this function will return 0. An error message will only be output if the file is present but invalid.

Field Type Description
"resolution" uniform float[2] Returns texture map resolution.
"type" uniform string Returns type of texture map. Can be one of the following: "texture", "shadow", "environment", "ptexture", "pointcloud", "brickmap", "photonmap".
"channels" uniform float Returns the total number of channels in the map.
"viewingmatrix" uniform matrix Returns a matrix representing the transform from "current" space to "camera" space in which the map was created.
"projectionmatrix" uniform matrix Returns a matrix representing the transform from "current" space to map's raster space(43).
"bitsperchannel" uniform float Returns the number of bits used to represent each channel of the texture. This is typically 8, 16 or 32.
"pixelaspectratio" uniform float Returns the aspect ratio of the pixels in the texture.
"min" uniform float[] Returns the minimum value of each channel over the entire texture.
"max" uniform float[] Returns the maximum value of each channel over the entire texture.
"fileformat" uniform string Returns the file format for textures. Can be one of: "tiff", "openexr" or "deepshadow".
Table 6.19: textureinfo() field names.


float atmosphere ( string paramname; output type variable )
float displacement ( string paramname; output type variable )
float incident ( string paramname; output type variable )
float opposite ( string paramname; output type variable )
float lightsource ( string paramname; output type variable )
float surface ( string paramname; output type variable )

Functions to access a parameter in one of the shaders attached to the geometric primitive being shaded. The operation succeeds if the shader exists, the parameter is present and the type is compatible, in which case 1.0 is returned. Otherwise, 0.0 is returned and variable is unchanged. Note that assigning a varying shader parameter to a uniform variable fails. Also, lightsource() is only available inside an illuminance() block and refers to the light source being examined.

float attribute ( string dataname; output type variable )

Returns the value of the data that is part of the primitive's attribute state. The operation succeeds if dataname is known and the type is correct, in which case 1.0 is returned. Otherwise, 0.0 is returned and variable is unchanged. The supported data names are listed in Table 6.20. User defined attributes are also accessible as in:

uniform float self_illuminated = 0;
attribute( "user:self_illuminated", self_illuminated );
if( self_illuminated == 1 ) {
 .. do some magic here ...
}

It is possible to query the attributes of a light source from a surface shader. To do so, use the attribute() shadeop inside an illuminance loop and prefix the attribute name with "light:".

illuminance( P )
{
    string name;
    if( 1 == attribute( "light:identifier:name", name ) )
        printf( "light name: %s\n", name );
}

The list of recognized uniform attributes is are listed in Table 6.20.

"Ri:ShadingRate" "Ri:Sides"
"Ri:Color" "Ri:Opacity"
"Ri:Matte" "Ri:DetailRange"
"Ri:TextureCoordinates" "Ri:Orientation"
"Ri:Transformation" "Ri:CoordinateSystem:space"
"GeometricApproximation:motionfactor" "displacementbound:sphere"
"displacementbound:coordinatesystem" "shaderdisplacementbound:sphere"
"shaderdisplacementbound:coordinatesystem" "geometry:backfacing"
"geometry:frontfacing" "geometry:geometricnormal"
"grouping:membership" "identifier:name"
"trace:bias" "trace:displacements"
"trace:maxspeculardepth" "trace:maxdiffusedepth"
"photon:shadingmodel" "photon:causticmap"
"photon:globalmap" "photon:estimator"
"sides:doubleshaded" "visibility:camera"
"visibility:diffuse" "visibility:specular"
"visibility:trace" "visibility:transmission"
"visibility:photon" "dice:hair"
"dice:rasterorient" "cull:backfacing"
"cull:hidden" "derivatives:smooth"
"derivatives:centered" "subsurface:groupname"
"subsurface:scale" "subsurface:refractionindex"
"subsurface:shadingrate" "subsurface:absorption"
"subsurface:scattering" "subsurface:meanfreepath"
"subsurface:reflectance" "subsurface:samples"
"attribute:light:samples" "attribute:light:samplingstrategy"
"attribute:light:emitphotons" "irradiance:shadingrate",
"irradiance:nsamples" "hider:composite"
"user:attributename"
Table 6.20: attribute() field names.

The type of each attribute is directly related to its declaration when declating the corresponding attribute in the Ri stream (with the exception of integer attributes becoming floating point values in the shader since there is no integer type in SL).

Two entries in the table require slightly more information:

shaderdisplacementbound:sphere
This returns the displacement bound as specified by the __displacementbound_sphere shader parameter. If both displacement and surface shader has such parameters, their will simply be added together meaning that they should be declared in the same space. Refer to shader declared displacementbound.
shaderdisplacementbound:coordinatesystem
Will return the __displacementbound_coordinatesystem. Surface shader parameter will be returned if displacement shader has no such parameter. Again, it is imperative to have the same space in both shaders.

float option ( string dataname; output type variable )

Returns the data that is part of the renderer's global option state. The operation succeeds if dataname is known and the type is correct, in which case 1.0 is returned. Otherwise, 0.0 is returned and variable is unchanged. The supported data names are listed in Table 6.21. User defined options (as specified by RiOption, see User Options) are also accessible:

EXAMPLE

uniform float shadow_pass = 0;
option( "user:shadow_pass", shadow_pass );
if( shadow_pass == 1 ) {
 ...
}

Name Type Description
"Format" uniform float[3] Returns [ x resolution, y resolution, aspect ratio ].
"FrameAspectRatio" uniform float Frame aspect ratio.
"CropWindow" uniform float[4] Crop window coordinates as specified by RiCropWindow.
"DepthOfField" uniform float[3] Returns [ fstop, focal length, focal distance ]; as specified by RiDepthOfField.
"Shutter" uniform float[2] Returns [ shutter open, shutter close ]; as specified by RiShutter.
"Clipping" uniform float[2] Returns [near, far]; as specified by RiClipping.
"Ri:FrameBegin" uniform float Returns the frame number given to RiFrameBegin.
"FieldOfView" uniform float Returns the camera's field of view, in degrees.
"Hider" uniform string Current hider.
"Hider:progressive" uniform float Returns the "progressive" Hider parameter.
"Hider:editable" uniform float Returns the "editable" Hider parameter.
"Ri:PixelSamples" uniform float[2] Returns the RiPixelSamples option.
"trace:maxdepth" uniform float Option "trace" "maxdepth"
"trace:specularthreshold" uniform float Option "trace" "specularthreshold"
"shutter:offset" uniform float Option "shutter" "offset"
"limits:bucketsize" uniform float[2] Option "limits" "bucketsize"
"limits:gridsize" uniform float Option "limits" "gridsize"
"limits:texturememory" uniform float Option "limits" "texturememory"
"render:nthreads" uniform float The number of rendering threads.
"searchpath:shader" uniform string shader searchpath
"searchpath:texture" uniform string texture searchpath
"searchpath:display" uniform string display searchpath
"searchpath:resource" uniform string resource searchpath
"searchpath:archive" uniform string archive searchpath
"searchpath:procedural" uniform string procedural searchpath
"user:useroption" any type A user defined option.
Table 6.21: option() field names.


Name Type Description
"renderer" uniform string Returns "3Delight".
"version" uniform float[4] Returns [Major, Minor, release, 0] (e.g. [1,0,6,0] ).
"versionstring" uniform string Version expressed as a string, (e.g., "1.0.6.0").
Table 6.22: rendererinfo() field names.


uniform float rendererinfo ( string dataname; output type result )

Returns information about the renderer. The operation succeeds if dataname is known and the type is correct, in which case 1.0 is returned. Otherwise, 0.0 is returned and result is unchanged. The supported data names are listed in Table 6.22.

float rayinfo ( uniform string keyword; output type result )

Provides informations about the current ray. Returns 1.0 if keyword is known and result is of the correct type. Returns 0.0 on failure.

EXAMPLE

/* Choose the number of rays to trace depending on current ray depth. */
uniform float ray_depth;
rayinfo( "depth", ray_depth )

samples = max(1, samples / pow(2, ray_depth) );

trace_color = trace( P, Nr, "samples", samples );

Name Type Description
"speculardepth" uniform float Returns the specular depth of the current ray.
"diffusedepth" uniform float Returns the diffuse depth of the current ray.
"hairdepth" uniform float Returns the hair depth of the current ray.
"shadowdepth" uniform float Returns 1.0 if the current ray is a transmission ray, 0 otherwise.
"depth" uniform float Returns the total depth of the current ray: speculardepth+diffusedepth+hairdepth+shadowdepth.
"type" uniform string Returns one of the following: `camera', `light' (for photons), `specular', `diffuse', `subsurface', `hair' or `transmission'.
"label" uniform string Returns the label attached to this ray, if any.
"displaceonly" uniform float Returns 1.0 if the current ray is run for geometric displacement only (normal is not needed), otherwise 0.0.
Table 6.23: rayinfo() field names.


float raylevel ( )
float isindirectray ( )
float isshadowray ( )

Deprecated functions. Their functionalities can be reproduced using the rayinfo() shadeop. See rayinfo shadeop.

float arraylength ( var )

Returns the number of elements in the array var or -1 if var is a scalar.

float isoutput ( var )

Returns 1 if var is output to a display driver. This is true if:

  1. The variable is declared as output in shaders' parameters.
  2. The variable is specified in at least one display driver.

This function is useful to optimize shaders that have to calculate many AOVs: it is wasteful to compute an AOV if there is no display driver that uses it.

surface shader1( output varying float noisy = 0 )
{
    if( isoutput( noisy ) )
    {
        noisy = noise( P );
    }
}
float isoutput ( string varname )

Returns 1 if the variable with the given name is output to a display driver. This is the same function as the other form above but by name instead of directly giving the variable to test. This form can also query individual array components:

surface shader1( output varying float outputs[3] = {} )
{
    if( isoutput( "outputs[1]" ) )
    {
        outputs[1] = foo();
    }
}
void outputchannel ( uniform string channelname; value )

This function allows output variables to be dynamically added to a shader. For example, these two shaders would produce equivalent behavior:

surface shader1(
    output varying color myoutput = 0 )
{
    myoutput = Cs;
}

surface shader2();
{
    outputchannel( "myoutput", Cs );
}

If the variable channelname already exists, it is simply assigned to. If there is some incompatibility in the type of detail of the existing variable then nothing is done. value may be of any type except string. Output variables should still be declared whenever possible as it is more efficient.

Note that if outputchannel() is called from a light shader or a coshader, the output is added to the main shader by default (usually the surface) so it will be visible to the display system. To override this behavior, prefix the variable name with "light:" or "local:".

void gridmin ( varying float value )
void gridmax ( varying float value )

These special functions take a varying floating point parameter as input and find out the minimum and maximum values over the entire grid (in REYES) or shading point set (ray-tracing). These functions are useful to take decisions for an entire set of shading samples. For example, if it is known that some parameter is less than X for the entire grid then one might skip some particular code branch. Not to be confused with min and max shadeops.

6.4.9 Co-Shader Access

shader getshader ( shader shader_name )

Get the shader with the specified name and active in the current attribute scope.

shader[] getshaders ( ["category"; string category_name] )

Get all co-shaders declared in the current attribute scope, filtering them using an optional category name.

shader getlight ( string light_handle )

Returns the co-shader for the light source with handle light_handle.

shader[] getlights ( ["category"; string category_name] )

Returns all active lights in the current attribute scope, filtering them using an optional category name. This method can be used to build custom illuminance loops. For example,

vector L;
color Cl, C=0;
shader lights[] = getlights( "category", "diffuse" );
uniform float num_lights = arraylength( lights ), i;
for (i = 0; i < num_lights; i += 1)
{
    lights[i]->light( L, Cl );
    C += Cl * (Nn . normalize(-L));
}

Note that the L vector is automatically inverted by illumiance() but in this case one has the responsibility to invert it manually. Refer to The Illuminance Construct for a more explanation about the mechanics of illuminance() and refer to Light Categories and Predefined Shader Parameters for more about light categories.

float getvar ( shader coshader, string name, [output type variable] )

A function to access member variables in a specified co-shaders (see section Co-Shaders). Another use of this function is giving it the null shader handle to make it search for the variable directly on the geometric primitive, bypassing all shaders. This is likely to be slower to compute than getting a similar variable from another shader.

6.4.10 Operations on Arrays

void resize ( output type A[], uniform float length )

Resizes the array to the specified length.

  • Increase array length will leave the new elements uninitialized.
  • length is always uniform.
  • If length is set to 0, the memory held by the array is released
void reserve ( output type A[], uniform float length )

Increase array's capacity if necessary without affecting it's length.

void push ( output type A[], type value )

Increase the array length by one and initializes the last element to value.

type pop ( output type A[] )

Returns the last element of A and decreases array's length by one. The capacity of the array is not decreased.

3Delight 10.0. Copyright 2000-2011 The 3Delight Team. All Rights Reserved.