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 DSO Shadeops.

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 time point (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.

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

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 transmission 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.
Table 6.10: Common optional parameters to ray tracing functions.

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

Returns the color of light arriving to Pt from direction R. This is accomplished by tracing a ray from Pt in the direction specified by R. Only objects tagged as visible to reflection rays are considered during the operation. 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 Pt and R must lie in `current' space. Optional parameters to trace() are summarized in below.

uniform float maxdist
Specifies a distance after which no intersections are checked. The default value is 1e38 which means that there is nothing
varying float samplecone
Specifies an angle in radians that, together with trace()'s starting point Pt, describes a cone in which rays will be sampled. Larger cones means softer results. This is the same angle as specified to the transmission shadeop. The default value is 0.
uniform float samples
Specifies the number of samples to use to. Higher sample counts are needed if:

  1. Anti-aliasing is to be performed. Even if `samplecone' is set to 0.
  2. `samplecone' is greater than 0 and more samples are needed to achieve a smoother result.
output varying color transmission
Returns the transmission in the traced direction. If returned transmission is equal to (1, 1, 1) then no objects have been intersected, if it is (0,0,0) then no lights is coming from direction R. Intermediate values describe a varying degree of coverage. The resulting transmission will correctly accounts for translucent objects and can be used to composite the result returned by trace with an environment map as shown in Listing 7.2. 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() intersects objects that are visible to transmission rays while trace() honors reflection rays.

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 left at 
   1e36  */
float dist = 1e36; 
color c = trace( P, Nf, dist, "maxdist", 10 );
float trace ( point Pt; vector R )

Returns the distance to the nearest intersection, when looking from Pt in the direction specified by the unit vector R. This function may be substantially faster than the color version of trace() since it might avoid costly shading operations. Pt and R must lie in `current' space. This function intersects objects that are visible to reflection rays.


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 described in three different formats:

  1. A cube environment map.
  2. A latitude/longitude environment map.
  3. A light probe.

Environment maps have to be generated by tdlmake with the `-envcube' or `-latlong' parameter. Probes are images generated by software such as HDRShop and are usually stored as Radiance files (with an `.hdr' extension). These 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 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). 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).
"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).
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.
"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".
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 Type Default Description
"groupname" uniform string "" Allows lookups of arbitrary subsurface groups in the scene.
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.15. 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.

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.15. 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 float 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);
Table 6.15: 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.15. 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.16.

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 primarly usefule for point-based occlusion and color bleeding (see section Point-Based Imaging Pipeline).
Table 6.16: 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.17.

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.17: 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.

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(40) expression.

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.18. 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 still be output if the texture doesn't exist.

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" or "environment".
"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(41).
"bitsperchannel" uniform float Returns the number of bits used to represent each channel of the texture. This is typically 8, 16 or 32.
Table 6.18: 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.19. User defined attributes are also accessible.

EXAMPLE

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:".

EXAMPLE

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

Name Type
"ShadingRate" uniform float
"Sides" uniform float
"Matte" uniform float
"Ri:Orientation" uniform string
"GeometricApproximation:motionfactor" uniform float
"displacementbound:sphere" uniform float
"displacementbound:coordinatesystem" uniform string
"geometry:backfacing" uniform float
"geometry:geometricnormal" uniform float
"grouping:membership" uniform string
"identifier:name" uniform string
"trace:bias" uniform float
"trace:displacements" uniform float
"photon:shadingmodel" uniform string
"photon:causticmap" uniform string
"photon:globalmap" uniform string
"photon:estimator" uniform float
"sides:doubleshaded" uniform float
"visibility:camera" uniform float
"visibility:diffuse" uniform float
"visibility:specular" uniform float
"visibility:trace" uniform float
"visibility:transmission" uniform float or uniform string
"visibility:photon" uniform float
"dice:hair" uniform float
"dice:rasterorient" uniform float
"cull:backfacing" uniform float
"cull:hidden" uniform float
"derivatives:smooth" uniform float
"derivatives:centered" uniform float
"user:attributename" any type
Table 6.19: attribute() field names.


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.20. 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] Uses this format: [ 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] Uses this format: [ fstop, focal length, focal distance ]; as specified by RiDepthOfField.
"Shutter" uniform float[2] Uses this format: [ shutter open, shutter close ]; as specified by RiShutter.
"Clipping" uniform float[2] Uses this format: [near, far]; as specified by RiClipping.
"trace:maxdepth" uniform float Option "trace" "maxdepth"
"trace:specularthreshold" uniform float Option "trace" "specularthreshold"
"shutter:offset" uniform float Option "shutter" "offset"
"user:useroption" any type A user defined option.
Table 6.20: option() field names.


Name Type Description
"renderer" uniform string Returns "3Delight".
"version" uniform float[4] Uses this format: [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.21: 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.21.

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.
"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+shadowdepth.
"type" uniform string Returns one of the following: `camera', `specular', `diffuse', `subsurface', or `transmission'.
"label" uniform string Returns the label attached to this ray, if any.
Table 6.22: 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 true 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.

IMPORTANT

This shadeop doesn't work with compiled shaders (shaders compiled with the `-dso' option).

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 ()

Get all co-shaders declared in the current attribute scope.

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. Refer to Co-Shaders for more detail.

3Delight 8.5. Copyright 2000-2009 The 3Delight Team. All Rights Reserved.