+$#KWelcome!
        
ShaderLab 2.0
K
ShaderLab 2.0 for trueSpace 4, 5, 6 and 6.5 is an advanced tool Kfor using and building custom shaders. A major upgrade from ShaderLab 1.0, this new version includes a slew of new features, a brand new user interface, and highly tuned performance.

Installation

See the section regarding Installation.

Operation

See Getting Started (trueSpace 4) or Getting Started (trueSpace 5/6) to start using ShaderLab right away. To start writing shaders, check out Shader Basics. The ShaderLab language is described in detail in the Language Reference.

Also, please see the FAQ.

Support

The most current information regarding ShaderLab is always available here:

         http://www.primitiveitch.com/shaderlab2/

For additional support, send email to

         support@primitiveitch.com
.

An online version of this documentation is available here:

         http://www.primitiveitch.com/shaderlab2/docs


Primitive Itch

For updates and information regarding ShaderLab or other Primitive Itch products, consult our website at

         http://www.primitiveitch.com

or send email to

         info@primitiveitch.com
.




Copyright Š Primitive Itch 2003
http://www.primitiveitch.com


+$#What's New

New Interface & Presets

ShaderLab 2.0 has a brand new user interface, designed to be both efficient and user friendly. Quick access to Presets for each shader makes ShaderLab2 much easier to use day to day.

New Shader Functions

Now includes support for selecting and using image in shaders. A host of other new functions and noise types have been developed.

New Organization

ShaderLab 2.0 files are now collected into a single compressed .SLB file for each shader. For each shader, the .SLB contains the shader script, thumbnails, and presets.

All ShaderLab support files now live in a folder called ShaderLab2 which exists in the trueSpace main folder*. ShaderLab shaders are now divided into sections (sub-folders) to make it easier to manage and organize the increasingly large number of shaders that are available.

New Shader Building Tools

ShaderLab 2.0 includes a shader debugging tool, a built-in optimizer, and a new GUI builder.


* The PiShaderLab2Pro.tss
file must be placed in the trueSpace/Shaders/Material folder. See Installation for more information.



+$#Installation

The ShaderLab installer should take care of installation for you. However, the ShaderLab installation is very simple and can be repaired or managed manually if desired.

Note: the folders below named trueSpace represent your trueSpace main folder. This folder could be named differently on your system.

The ShaderLab2 shader file PiShaderLab2.tss should be installed to the trueSpace\Shaders\Material folder.

All other ShaderLab2 files should be installed to the trueSpace\ShaderLab2 folder.

When installed properly, ShaderLab2 should be structured as follows.

Folders marked with an asterisk (*) are standard trueSpace folders.

trueSpace (folder) *
         - Shaders (folder) *
                  - Materials (folder) *
                           - PiShaderLab2.tss (file)
         - ShaderLab2 (folder)
                  - Inc (folder)
                  - Shaders (folder)
                           - Main (folder)
                           - (additional shader folders)
                  - ShdrLab2.hlp (file)
                  - ShaderLab.Ico (file)



+$#Getting Started (trueSpace 4)

Left click on one of the four shader selection spheres (we'll click Color):



Select "PiShaderLab2" from the shader selection list (this list is for Color shaders):



Now right click on the same selection sphere (in this case, click Color):



The ShaderLab interface appears:



+$#Getting Started (trueSpace 5/6)

There are five steps in the basic method of accessing ShaderLab from trueSpace5.

1. Open the trueSpace material editor (ME) window.
2. Right click on the Color shader button to open the Color Shader library (you can also access this library from the Shader Library button).
3. Left click the ShaderLab icon to select ShaderLab color shader.
4. Left click the Color Button to open the Color box.
5. Finally, click the 'Expand' box to open ShaderLab2.

Note: you could instead use the Inspect tool on an object painted with ShaderLab to accomplish steps 1 and 2.










The ShaderLab interface will appear and should look something like this:



+$#Shader Panel

The main ShaderLab2 window consists of a menu bar, a set of tabs, and three main panels. The menu bar contains standard commands and is explained here.

The tabs indicate which type of trueSpace shader you are manipulating: one of Color, Alpha (Transparency), Bump (Displacement) and Reflectance. Typically, ShaderLab2 hides tabs you aren't using, so you may not always see all four tabs. There are options for changing the behavior of the tabs.

Note: the shader tabs can be confusing. You have to make sure that ShaderLab is selected in trueSpace for the shader type (Color, Alpha, etc.) you want to use. To select ShaderLab2, you can use the trueSpace Material Editor, or use the ShaderLab2 Activate Shader command.

The most important tools in ShaderLab2 are placed into three panels: Shaders, Settings, and Presets. Each panel may be collapsed or expanded by clicking its folding button (note: ShaderLab2 will only let you collapse up to two of the panels at a time).

The Shader panel shows a listing of all the Shaders for the current shader tab in the selected section. Click a shader to select it. If ShaderLab is selected in trueSpace, you will see the shader output in the Material Editor.

Shaders are divided into sections so they are easier to manage. Use the combo box at the top of the ShaderList to select different sections, or you can select All Shaders to see everything available for the shader tab.

Note: ShaderLab2 remembers the section selected for each tab. Don't be confused if the section changes when you change tabs.

Note: Right-click a Shader in the ShaderList to get a context menu containing Shader commands.



Help for the Settings and Presets panels are on the next pages.


+$#Settings Panel

The available settings for the selected shader are shown in the Settings panel.



The shader interface shows all the user controlled parameters that are available for the currently selected Shader.

Value Knobs

Values can be changed by typing into the edit boxes or dragging the knobs.

Note: If the text in an edit box is colored red, then that value hasn't been entered yet. Hit Enter or Tab to enter the value.

Note: Double-click a knob to restore it's default.

Colors

To select a color, click the color spot and using the displayed color dialog. You may also set the Red, Green, and Blue values manually using the knobs.

Right-click the color control to select Overdrive. Normally, color values are restricted to the range 0..1, but when Overdrive is checked, the R, G, and B values can be negative or greater than one.

Vectors

Vector values have three knobs, one each for the X, Y, and Z components of a vector. Some vectors are only 2-d, and therefore have only two knobs; one each for X and Y.


+$#Mapping Adjustment Panel

It is possible to adjust the way ShaderLab applies a shader to a surface using the Mapping Adjustment panel. The mapping settings are described below.

Note: Some shaders use a specific type of mapping internally, and will ignore the Mapping Adjustment setting. You can usually override such shaders by checking the 'Force Mapping' box.



Solid 3D: Shader is applied to the local surface of the object using 3D coordinates.

World 3D: Shader is applied in 3D coordinates, but in world space. When the object is moved animated, the surface pattern will changed as if the pattern were fixed in space, and the object is moving through it.

UV: Shader is applied using the 2D UV mapping on the object.

Seamless UV for stock cubes: Stock cubes (cube primitives from trueSpace) have by default an interesting unfolded UV which works very well, except that the mapping is longer than it is tall. This adjustment will equalize the ratio of the mapping so that shaders may be applied seamlessly (try with Metal Grid 2 or Color Brick to see the difference).

Compensation for stock spheres: Stock spheres (sphere primitives from trueSpace) are mapped by default with regular spaced latitudes, with the result that the latitudes near the equator of the sphere sweep much more surface area than those at the poles. This adjustment attempts to even the spacing.

More compensation for stock spheres: Even more compensation as described above.

Synthetic rounded cube: This is a 3D mapping which juggles the x, y, z coordinates of each surface point to simulate a rounded cube. You may want to try it if you have a shader that looks great in the x/y plane, but does not work as you expect in other planes.

Sky map: Creates a mapping that can be used for sky spheres or other background objects.


+$#Presets Panel

The third panel, Presets, lists all the stored shader configurations available for the selected shader. Click a preset to select it. Other preset commands are available as shown.

Preset thumbnail images are captured directly from the trueSpace material editor. Before adding a preset, make sure the trueSpace Material Editor is open, uncovered, and at it's default size (close and re-open the ME to restore the default size). You can successfully capture thumbnails in IIR mode in trueSpace5.

Note: Although each preset thumbnail displays a complete material, presets only affect the current shader. For example, you may see a Bump shader preset whose thumb is a bumpy yellow sphere. Choosing that preset will only affect the Bump channel, however, and the yellow color won't necessarily be reproduced.




+$#Menu Reference

File


New
Opens a blank ShaderLab edit window.

Edit Script
The edit button opens the currently selected shader script in a ShaderLab edit window.

Shader Properties
Open's the Properties window for the currently selected shader script..

Rename Shader
Activates the in-place editor for the name of the seected shader.

Delete Shader
Deletes the shader file from your system.

Activate Shader
Selects the current shader into the trueSpace material editor.
Import Shaders/Presets

Refresh
Refresh the list of shaders.

Edit


Copy Parameters
Copies the values of the current parameters onto the ShaderLab clipboard.

Paste Parameters
Paste the values of parameters from the ShaderLab clipboard into the current shader. Parameters are matched by comparing parameter names.

Restore Shader Defaults
Restores all parameters to their default values.

Edit Script, Shader Properties, Rename Shader, Delete Shader, Activate Shader
Simply copies of the commands in the File menu.

Options...
Opens a dialog for configuring some interface options.

View


Show All Tabs
Makes all the shader tabs visible, regardless of whether they are used in the trueSpace material editor.

Toolbar
Turns the main toolbar on and off.

Text Buttons
If checked, the toolbar buttons include text descriptions. This item is greyed out if the Toolbar is off.

Developer Mode
Adds commands to the shader context menu that are handy when developing shaders.

Always Show Tabs
If checked, all four shader tabs are always visible.

Options...
Opens a dialog for configuring some interface options.

Debug


Run Preview
Forces trueSpace to redraw the material preview (causing any selected ShaderLab shaders to execute).

Debug Is On/Off
Used to turn the debugger on or off. If the debugger is turned on, it will appear the next time a ShaderLab shader is executed.

Bypass Shaders
When checked, ShaderLab ignores shaders and uses it's default rendering only. This option provides a panic button for escaping a malfunctioning shader.

Help


ShaderLab Help
Opens the Shader Lab help file.

Shader Help
Display any documentation that exists for the current shader.





+$#Editor Window

You view and edit shader scripts using the editor window. The editor window also displays messages from the ShaderLab compiler.




Note: Pressing Ctrl-F1 displays context sensitive help: the help file will attempt to display help specific to the word or command command containing the cursor. This command is also available in the menu as Help|Topic Help. For best results, select the word or command (you can double-click to select a word) before using Topic Help.



File Menu


New
Opens a blank ShaderLab edit window.

Open
The open button displays a standard Windows open dialog that can be used to select a ShaderLab Shader file (.SHA) from anywhere on your hard drive. The selected file is then opened in a new ShaderLab edit window.

Save
Save the current script file to disk.

Save As...
Use a standard Windows save dialog to save the script file under a new name or in a new location.

Save As Binary...
Save the current script file, thumbnail bitmap, and GUI settings to a single, encrypted binary file (.SLB). The SLB file can be used in any edition of ShaderLab2, but cannot be edited.

Properties
Open's the Properties window for the currently selected shader script..

Exit
Closes the edit window.


Edit Menu


Contains a number of standard editing functions.


Compiler Menu


Compile Attempts to compile the current shader script, and displays errors, if any, in the error window.

Run Preview
Forces trueSpace to redraw the material preview (causing any selected ShaderLab shaders to execute).

Byte Code
Shows or hides the byte code panel. The byte code panel is a tool for advanced users that displays the output of the compiler. Analyzing the byte code can be helpful for understanding, debugging and optimizing shaders, as well as for compiler testing.

Debug Is On/Off
Used to turn the debugger on or off. If the debugger is turned on, it will appear the next time a ShaderLab shader is executed.


Help Menu

Contents & Index
Displays the contents/index window for the help file.

Topic Help
Displays context sensitive help: the help file will attempt to display help specific to the word or command command containing the cursor. Pressing Ctrl-F1 will have the same effect. For best results, select the word or command (you can double-click to select a word) before using Topic Help.




+$#Shader Properties - Support

Open the shader properties window from the
File menu or from the shader context menu (right-click a shader). The shader properties window is usually only needed if you are creating shaders.

Support

Use the Support tab in this window to specify which shader classes are supported by a shader script, to capture a thumbnail image or default settings, and to specify documentation for the shader.

Capture Defaults

Set the stored defaults for the shader to values from the current GUI settings.

Capture Thumb

The shader thumbnail is the image that represents the shader in the shader list. This image is screen-grabbed from the trueSpace Material Editor window. Before capturing a shader thumbnail, make sure the trueSpace Material Editor is open, uncovered, and at it's default size (close and re-open the ME to restore the default size). You can successfully capture thumbnails in IIR mode in trueSpace5.

Script Documentation

Shader documentation can be made available to the end user in .TXT, .RTF, .DOC, .HTML, .HTM, .HLP, or .CHM files. If you write documentation for your shader, put the documentation file in the same folder as the shader, and then use the Script Documentation File control to associate the file with the shader. Click the folder icon on the right side of the control to open a file selection dialog.

If this box is left blank, ShaderLab will assume the script documentation (if any) uses the default file name. The default file name will have the same file name (except extension) as the shader script itself. Use the Documentation File option to specify a documentation file for script if the documentation file has a different name than the shader script. This options is mainly for shader families that wish to share a documentation file, e.g., 'Super Color' and 'Super Reflectance' might both refer to 'Super.HLP'.




+$#Shader Properties - GUI

Open the shader properties window from the
File menu or from the shader context menu (right-click a shader). The shader properties window is usually only needed if you are creating shaders.

Use the GUI tab in this window to attach GUI controls to variables in your script. GUI stands for Graphical User Interface.

Variables used with GUI controls must be declared in the script program. Variables used with GUI controls become read-only in the script program.

Use the +Number, +Vector, and +Image buttons to add new rows to the grid. Each row corresponds to a Number, Vector and Color, or Image control on the Settings Panel.

The -Del button deletes the selected row(s).

{



Note: You can move row(s) by dragging the leftmost column.

Note: You can select multiple rows Hold the mouse on very leftmost edge of a row to get the row selection cursor. You can use the row selection cursor to select one or multiple rows.

Caption and Variable Names

For a control to be useful, it has to be linked to a variable in your script. Type the variable name into the Variable column or select it from the drop-down list. Use the Caption column to specify the name of the control as it will appear on the GUI.

Note: Make sure that the variable and the control are the same type. Make Number controls for Scalars, and Vector or Color controls for Vectors. Otherwise, your shader will not work correctly.

Information for the User

Each control has an information entry. Text entered under Information will be used as the mouse hint (tool tip) for that control.

You can also create a control that is displays it's information as a text field on the GUI. Set the Variable name to a hyphen ("-") to create a text field. Text fields do not have values and are not linked to actual variables.

Number Controls

Number controls have minimum, maximum, precision, and default values that can be entered into the grid. The precision value specifies the smalled increments are for the value. A precision of 100, means the value uses an increment of 1/100 (two decimal places). Value of 10 yields tenths (one decimal place), 50 mean increments of 1/50.

Number Controls

A checkbox control is created if the value can only be 0 or 1. Checkbox settings are min = 0, max = 1, precision = 1.

Number Speed Buttons

Below the grid is a series of buttons that can be used to quickly edit the range values for a Number control. Pressing one of these buttons will change values in the selected row.

0/1      makes a checkbox.

(1)      assigns a range from nearly zero to nearly one, by thousands. I.e. the range is min = 0.001, max = 0.999, precision = 1000

1, 10, 100, 500          sets a span from (0..max) where max is the value listed on the button

+        button sets minimum to zero. This forces the range to be always >= 0 (because the maximum is not allowed to go below the minimum).

-       button sets the minimum to the negation of maximum. That is, min = -max.

1, .1, .01, .001         buttons set the precision.

Vector and Color Controls

Vector (and Color) controls have default X, Y, Z values that can be entered.
The Special Type column specifies whether the 'Vector' control is displayed in the GUI as a Color control (Default) or as a 2D or 3D vector.

Image Controls

Image controls are always set to 'Caligari.jpg' by default.








+$#Debugger

The debugger lets you step through your code line by line and see the state of your shader.

You can turn the debugger on by changing 'Debug Is Off' to 'Debug Is On' in the Compile menu, or with buttons on the main toolbar or the editor toolbar. After turning the debugger on, the first time the Shader is used to render something, the debugger window appears and the shader is paused on it's first line.

You can use the 'Run (Preview)' command in the Compile menu or the toolbars to have trueSpace refresh the preview, which will cause the debugger to start (if it's turned on).

The green arrow and highlight show the next line of the shader that will execute if you hit the Step button. The Step button will advance through the shader one line at a time.

The Stop Debugging button will close the debugger window and turn off the debugger.

The Go Until Breakpoint button will allow the shader to run until it hits a breakpoint. You can set a breakpoint by selecting a line in the shader script and clicking the Break Point button. You can also click to the left of the line number of a line to turn a breakpoint on and off. Breakpoints are marked by red circles to the left of the line numbers.

There are two folding panels that display the values of variables in your script. The leftmost panel displays the values of the current surface variables and the rightmost show the user defined variables. There is also a panel that displays the byte code for the current script.



+$#Shader Files

There are a few different types of ShaderLab files, each with it's own file extension:

.SLB     Standard ShaderLab2 file. Each .SLB file contains a shader script, thumbnails, and presets. .SLB files are actually ZIP compatible compressed files.

.SBN     ShaderLab2 binary shader. SLB files also contain shader information, but are stored in an encrypted binary format that cannot be edited with the ShaderLab2 tools. Typically, SLB files are found in professional shader pack add-ons.

.SHA     ShaderLab1 shader script. ShaderLab2 will work with most ShaderLab1 scripts

.SHD     ShaderLab1 binary shader. These encrypted versions of ShaderLab1 shaders are also usually compatible with ShaderLab2.


+$#FAQ

Q.      
The trueSpace channel windows becomes corrupted (gray bars appear in Color, Reflectance, Bump, or Transparency windows).
A.
      This is a known bug in trueSpace 5.0. Caligari is working on it. It won't affect your work in any way.


Q.
      I see a nifty preset which is just the material I want, but when I click it, the trueSpace material doesn't match.
A.
      Remember that ShaderLab presets work on individual shader channels only. A trueSpace material is made up of Color, Reflectance, Bump, and Transparency settings. ShaderLab works on each of these channels separately. To store an entire material, use the trueSpace material library instead of ShaderLab presets.


Q.       I've used Mapping Adjustment to select UV mapping for a shader, but nothing happened.
A.
       You may need to check the Force Mapping option. Some shaders use a preferred setting internally, so you need to use Force Mapping to override the shader.



+$#Shader Basics

Once a shader is painted on an object and that object is rendered, the shader is invoked for each visible point on the object. Shaders have access to special values that describe the surface point being shaded. Shader scripts affect the appearance of the surface render by changing one or more of these values.

For example, the Co value holds the color of a surface point. A shader script can set the color of a surface point by setting Co:

Co = (1, 1, 1); // Set the color of the point to pure white

Different types of shader scripts have access to different surface values, as explained in the next section, Shader Classes
.

In this document, there are reference sections describing the surface variables
and built-in functions; but the best way to learn about shader scripts is by tinkering with the examples.








+$#Shader Classes

When an object is rendered in trueSpace, each visible point on the object is assigned an output color. A shader is a recipe for coloring each point, one by one, based on it's position, orientation to the viewer, reaction to nearby lights, etc. Shader's are written to accept the description of a single point in space (and some statistics about that point) and give back some information for that single point. trueSpace handles processing the objects, collecting the information, sending the points one by one to the shader, and finally rendering the points.

trueSpace supports four kinds, or classes, of surface shaders: Displacement, Transparency, Color, and Reflectance.

"         For each visible point on an object's surface, displacement shaders modify the surface normal (N) to simulate the appearance of bumps or grooves on the surface.

"         Then, the transparency shaders determine the opacity (Alpha) and the transparency color (or transmission, To).

"         Then, color shaders determine the RGB color (Co).

"         Finally, reflectance shaders modify the RGB color (Co) based on the surface's interaction with light.

Shaders are evaluated in the following order:

1. Displacement shaders
2. Transparency shaders
3. Color shaders (at this point the lights are evaluated)
4. Reflectance shaders




+$#Color Shaders

Color shaders are expected to put the output color into the variable Co. Co is a special ShaderLab color variable.

A color shader script might look like this:

Co.r = 1;        // Set Red to %100 in the output color
Co.g = 0.2; // Set Green to %20 in the output color
Co.b = 0.5; // Set Blue to %50 in the output color

This example can be simplified by using vector notation:

Co = (1, 0.2, 0.5);      // Co is the special ShaderLab
                                    // variable that holds the output color

This shader sets the output color to a constant value: (1, 0.2, 0.5), which is a kind of purple. Another kind of color shader might set the color of the point based on the position in space of the input point:

Co = P;  // P is the special ShaderLab variable
                  // that holds the position of the shading point

Another shader might set the red component of the color based on a sin wave:

Co = (sin(P.x), 0.2, 05);

As long as you set Co, you have a color shader.


+$#Transparency Shaders

Transparency shaders have two output values to set. The most important is Alpha, a number indicating how transparent the surface point should be. Alpha ranges from zero, totally transparent, to one, totally opaque. The other value is To, the output color for the transparent areas. To is a color variable, and setting it is optional for a transparency shader.

A simple transparency shader:

Alpha = 0.5;

This shader paints an object with 50% transparency.

Transparency shaders are more interesting if the amount of transparency is altered based on surface features:

// This shader is opaque everywhere but the right hand side of an object
// P.x goes from -1 to 1 from left to right (in default view)
Alpha = 1;
if (P.x > 0) Alpha = 1 - P.x;

As long as you set Alpha, you have a transparency shader.

You may also set To, the transmission color. This color is blended with other surface colors, and is also use to color the shadows cast by the object (in raytrace mode).

// This shader casts red shadows when raytraced
Alpha = 0.5;
To = (1, 0, 0);


+$#Reflectance Shaders

Reflectance shaders take an input color in Co, and then change the color based on the nearby light sources.

A simple Reflectance shader might look like this:

Co = Co + Ambient;       // Ambient is a built in function
                                    // that returns the ambient light
                                    // at the surface point

This shader is equivalent to setting the Ambient value on a trueSpace reflectance shader all the way to maximum (1). Probably, the shader will scale the value:

Ka = 0.5; // Contribution of ambient light (50%)
Co = Co + Ka * Ambient; // Only use Ka amount of ambient light

Often reflectance shaders also add in Diffuse and Specular light.

Ka = 0.5; // Contribution of ambient light (50%)
Kd = 0.7; // Contribution of diffuse light (70%)
Ks = 0.5; // Contribution of specular light (50%)
Roughness = 0.5; // Surface 'roughness'

Co = Co + Ka * Ambient + Kd * Diffuse + Ks * Specular(1 / Roughness);

As long as you set Co, you have a reflectance shader.


+$#Displacement Shaders

Displacement shaders change the surface normal N
to simulate bumps and grooves in a surface. Directly changing N effectively is difficult, so trueSpace provides some help. Instead of calculating the normals directly, a typical displacement shader will instead define a function which calculates the offset of each point, and then call the utility function CalculateNormal() to figure out the normal.

The variables PP and DP are special variables that are used as the input and output to the displacement function. PP is a vector that identifies the point to be processed; DP is a scalar which your function sets to the height of the displacement at point PP.

If you've changed N, you have a displacement shader.

Example for 2D:

//
// This is a function called DisplacePoint.
// The code in DisplacePoint is not executed until
// the CalculateNormal function is used.
//
// When DisplacePoint is executed, PP is the input surface point
// and DP is the output displacement height.
// For 2D displacement shaders, PP.z is 0.
//

DisplacePoint()
{
         // Displace
         DP = Sin(|PP|);
};

// Change the frequency of the bump map input value.
// It is important to do this outside of DisplacePoint.
bU = U * Frequency;
bV = V * Frequency;


// Use the CalculateNormal utility to
// calculate the new normal at point bU, bV.
N = CalculateNormal(bU, bV, DisplacePoint);

Example for 3D:

//
// This is a function called DisplacePoint.
// The code in DisplacePoint is not executed until
// the CalculateNormal function is used.
//
// When DisplacePoint is executed, PP is the input surface point
// and DP is the output displacement height.
//

DisplacePoint()
{
         // Displace
         DP = Sin(PP);
};

// Change the frequency of the bump map input value.
// It is important to do this outside of DisplacePoint.
Q = P * Frequency;

// Use the CalculateNormal utility to
// calculate the new normal at point Q.
N = CalculateNormal(Q, DisplacePoint);


+$#ShaderLab Language Overview

ShaderLab uses a simple C-like language with similarities to the Renderman shader language. The best way to familiarize yourself with the language is to examine and experiment with the example scripts.

The language reference is divided into areas on:

Syntax
The Preprocessor
Initialization
Data Types
Expressions & Operators
Statements


+$#Syntax

For the most part, the language is case sensitive. Built-in functions, however, can be referenced irrespective of case.

Example: "Random" and "RANDOM" both refer to the built-in Random function, but 'Value' and 'value' are separate variables.


User comments can be written with \\ or \* .. *\.

Example:

// Double-slash comments are in effect to the end of the line

/*
         Slash-star comments are in effect between the stars
*/


+$#The Preprocessor

ShaderLab has a simple preprocessor that can handle compiler directives of the form #directive. At this time, there is only one directive:

#include <filename>

The #include directive will insert text file <filename> into the current script before compile time. If <filename> does not specify a full path, ShaderLab will prepend the ShaderLab working folder path.

For example, given

#include /Inc/Density.slb

ShaderLab will look for

/Inc/Density.slb

and if not found will also look for:

/ts/ShaderLab2/Inc/Density.slb

where
/ts is the path to the current trueSpace folder.



+$#Initialization

If you declare a procedure called Init in a shader, it will be called exactly once when the shader is loaded. Use an Init procedure to store constants, build arrays, or do calculations that don't need to occur at each pixel.

Example:

// Init will only be called once each time the shader is loaded
Init()
{
         // Setup some colors based on the current frame number
         at = (ActiveTime mod 30) / 30;
         Colors = [ (at, 0, 0), (0, at, 0), (0, 0, at) ];
};



+$#Data Types

ShaderLab operates on two primary data types: scalars and vectors. Scalars are floating point numbers; vectors are groups of three scalars. Vectors are also used to represent colors.

// Some scalars
2.0
1
-0.3

// Some vectors
(1, -1.3, 1)
(0, 0, 0)

A variable can hold either a scalar or a vector. Once a variable is defined as a scalar or a vector, you can't change it's type.

x = 2.0;                  // x holds a scalar
y = (1, 1, 1);   // y holds a vector
y = x;            // Syntax error. y is a vector, x is a scalar

Wherever a scalar is needed, you can supply a literal, a scalar variable, or a scalar expression:

// More scalars
2.0                                 // A literal
x = 2.0;                           // x is now a scalar variable
(2.0 * 3 + x) pow 2      // a scalar expression

Wherever a vector is needed, you can supply a literal, a vector variable, or a vector expression:

// More vectors
(1, 0, 2)                          // A literal
(x, 3, 2)                          // Another literal
v = (1, 1,1 )             // v is now a vector variable
2 * v * y                          // a vector expression

To access the scalar parts of a vector, use the member notation:

v.x                        // a scalar variable that is the X component of v
v.y                        // ...Y component of v
v.z                        // ...Z component of v

other acceptable member notations:

v.r, v.g, v.b    // Red, Green, and Blue color components
v.u, v.v, v.w    // U, V, W components (homogeneous texture co-ords)
v.h, v.s, v.l    // Hue, Saturation, and Lightness color components

You may also declare a Vector array:

va = [ Vector1, Vector2, Vector3 ]; // An array of three vectors

Vector arrays are mainly for use with functions like Spline. You can access individual members of a vector array with an index:

va[0] // Is a vector variable for the first vector in array va


+$#KExpressions & Operators

Expressions


An expression is a construction that returns a value. For example,

2        // constant
6.5      // constant
x        // variable

The simplest expressions are variables and constants. More complex expressions are built from simpler ones using operators.

2 + 3   
// 2 + 3 is an expression whose value is 5.
// The plus sign is the an operator.

2 * * (y pow 5) / (z - (N.I))
// Uses the multiplication, power, division,
// subtraction, and dot product operators.


Operators


Where there is more than one operator listed, the variations may be used interchangeably (e.g. for cross product, you may use either # or CROSS ). Also, operators are not case sensitive (e.g. 'CROSS' is the same as 'cross').

+                Scalar + Scalar                                     1 + 2             simple addition
                  Vector
+ Vector                             N + P             (N.x + P.x, N.y + P.y, N.z + P.z)
                  Vector + Scalar                            
P + 1             (P.x + 1, P.y + 1, P.z + 1)

-                Scalar - Scalar                                     1 - 2             simple subtraction
                  Vector
- Vector                             N - P             (N.x - P.x, N.y - P.y, N.z - P.z)
                  Vector - Scalar                            
P - 1             (P.x - 1, P.y - 1, P.z - 1)

*                Scalar * Scalar                             3.3 * 2           simple multiplication
                  Vector
* Scalar (also Scalar * Vector)   N * 2             (N.x * 2, N.y * 2, N.z * 2)
                  Vector
* Vector                             N * P             (N.x * P.x, N.y * P.y, N.z * P.z)

/                Scalar / Scalar                             9.2 / 0.02       simple division
                  Vector
/ Scalar                                     N / 2             (N.x / 2, N.y / 2, N.z / 2)
                  Vector / Vector                             N / P             (N.x / P.x, N.y / P.y, N.z / P.z)

%, MOD  Scalar
% Scalar, Scalar mod Scalar       3 mod 5           modulus (remainder)

.                Vector . Vector                             N . I             dot product (yields a Scalar)
#, CROSS        Vector # Vector, Vector cross Vector     N # I             vector cross product (yields a Vector)

^, POW  Scalar ^ Scalar, Scalar pow Scalar       x pow y           x to the y power

( )              ( expression )                              2 * (3 + 4)      association

| |               | Vector
|                                  |N|               magnitude (length)

Relational Operators


Each of these relational operators returns a boolean (true or false) value. A boolean is a number whose value is either 0 (false) or 1 (true).

==, EQ           Scalar == Scalar         m EQ n            equality (note: there are two '=')
                  Vector == Vector         N eq P           

!=, <>, NEQ     Scalar
!= Scalar                  m NEQ n  non-equality
                  Vector
!= Vector                  N neq P          

<, LT            Scalar
< Scalar           m LT n            true (1) if m is less than n

>, GT            Scalar
> Scalar           m GT n            true (1) if m is greater than n

<=, LTE         Scalar
<= Scalar         m LTE n  true (1) if m is less than or equal to n

>=, GTE         Scalar
>= Scalar         m GTE n  true (1) if m is greater than or equal to n

&&, AND         Scalar && Scalar         m AND n  true (1) if both m and n are non-zero

||, OR           Scalar ||
Scalar                  m OR n            true (1) if either m or n are non-zero

NOT               not Scalar
                NOT m             true (1) if m is false (0), false if m is true


+$#Variables & Scope

Variables

Variables in ShaderLab are defined when they are first seen by the compiler. If ShaderLab cannot determine the type of the variable (Scalar, Vector, Array), the compiler will produce an error message.

Variable Scope

Except for procedure parameters, all variables in ShaderLab are global.

All procedure parameters are local and are passed by reference.


Tip:

If you want to define a variable, but don't care about setting it's value, you can create a procedure that defines the variable, but is never actually called. The compiler will construct the variables used in the procedure even if it is never called at runtime.

Example:

Declare() // Declare() is never called
{
i = 0; // 'i' will be defined as a Scalar variable
};


+$#Statements

A ShaderLab program is made up of a series of statements. A statement can be one of:

"         An assignment
"         An if-statement (conditional)
"         A while-loop
"         A procedure definition
"         A procedure invocation
"         A break statement (immediately terminates the current for or while loop).

Assignments

Assignments are of the form x = y, some examples are:

x = 2;
Co = (1, 1, 1);
To = (P * 2) - N;

If-Statements

If-statements, or conditionals, have one of these forms:

if <expression> then <statement or block>
if <expression> then <statement or block> else <statement or block>

A block is a group of statements surrounded by braces '{ }'. Some examples,

if (x eq 2) y = 3;

if (x eq 2) y = 3;
else y = 2;

if ((y eq 3) and (z eq 4))
{
         Co = (1, 1, 1);
}

While-Loops

While-loops look like:

while (<expression>) <statement or block>

Example:

i = 0;
while (i < 5)
{
         i = i + 1;
         d = d + di;
}

For-Loops

For-loops look like:

for (<init expression>; <condition expression>; <loop expression>) <statement or block>;

Example:

for (i = 0; i < 5; ++i) d += di;

You can use the special break statement to immediately terminate a while or for loop.


+$#Procedures

#Procedure Definitions

Procedures are self-contained statement blocks that can be called from different locations in a program.

<identifier>( ) <block>;

Note that there always must be a semi-colon to terminate the procedure definition.

Example,

SumDensity()
{
         i = 0;
         while (i < 5)
         {
                  Density = Density + Amount;
                  i = i + 5;      
         }
};

Using Procedures

To execute a defined procedure, you simply use it's name and a pair of parentheses.

<identifier>( );

Example:

Amount = 2;
SumDensity();

Procedures With Parameters

<identifier>(<parameter definition list>) <block>;

where <parameter list> is one or more elements separated by commas:
<type> parameterName1, <type> parameterName2

<type> is either Scalar or Vector.

Note that there always must be a semi-colon to terminate the procedure definition.

Example,

SumDensity(Scalar Density, Scalar Amount)
{
         i = 0;
         while (i < 5)
         {
                  Density = Density + Amount;
                  i++;    
         }
};

Using Procedures With Parameters

To execute a defined procedure, use it's name and a set of parameters inside parentheses.

<identifier>( <parameter list>);

All parameters are passed by reference, so changing the value of the parameter will change the value of the variable used in the invocation.

Example:

SumDensity(Density, 2); // Density may be changed by the procedure

Procedures That Return Values

<type> <identifier>(<parameter definition list>) <block>;

where <parameter list> is one or more elements separated by commas:
<type> parameterName1, <type> parameterName2

<type> is either Scalar or Vector.

Note that there always must be a semi-colon to terminate the procedure definition.

Example,

Scalar OmegaSum(Scalar Omega, Scalar Octaves)
{
         d = 0;
         for (i=0; i<Octaves; ++i)
         {
                  d += Omega;
                  Omega /= 2;
         }
         return d;
};

Using Procedures That Return Values

You can use a valued procedure just like any other expression or built-in function.

delta = OmegaSum(0.5, 3);


+$#BlackColor

Vector constant with value (0, 0, 0).

Example:

Co = BlackColor;

See also: WhiteColor


+$#WhiteColor

Vector constant with value (1, 1, 1).

Example:

Co = WhiteColor;

See also: BlackColor


+$#Surface Variables

Alpha
             -- Surface opacity
Ci
                -- Input color
Co
                -- Output color
dPdu
              -- Texture space derivative vector with respect to u
dPdv
              -- Texture space derivative vector with respect to v
Du
                -- Change in texture space u-coordinate
Dv
                -- Change in texture space v-coordinate
I
                 -- View direction vector of shading point
ModI
              -- Length of I vector
N                 -- Surface shading normal
Ng
                -- Surface geometric normal
P
                 -- Shading point in local coordinate system
Pw
                -- Shading point in world coordinate system
Reverse
  -- Surface reversal flag
U
                 -- Texture space u-coordinate
V
                 -- Texture space v-coordinate
Ti
                -- Input transparency
To
                -- Output transparency
UnitI
             -- Unitary version of I vector
E                 -- Camera eye from point


+$#Alpha

Type: Scalar
Usage: Output transparency for transparency shaders

Set Alpha to specify the output transparency for a transparency shader. The normal range is 0..1, with zero as completely transparent, and one as completely opaque. Negative values or values greater than one can be used for special effects.

Alpha can only be changed by Transparency shaders, but can be read by Color or Reflectance shaders.

Example:

// Set opacity to 75%
Alpha = 0.75;


+$#Ci

Type: Vector
Usage: Input color for color/reflectance shaders

Ci does not appear to have any function at this time. Please use Co instead.



+$#Co

Type: Vector
Usage: Input color for reflectance shaders, output color for color and reflectance shaders

Use Co to set the output color for a color or reflectance shader. Use Co as the input color for a reflectance shader. Color values are given as RGB triples, with each component in the range [0..1]. Pure black is (0, 0, 0), pure white is (1, 1, 1).

Example:

// Set the output color to Red
Co = (0.8, 0, 0);

Example:

// Amplify Red from the input to the output color
Co.r = Co.r * 1.5;


+$#dPdu

Type: Vector
Usage: Input to all shader classes.

Object space derivative vector with respect to U.


+$#dPdv

Type: Vector
Usage: Input to all shader classes.

Object space derivative vector with respect to V.


+$#Du

Type: Scalar
Usage: Input to all shader classes.

Change in texture space U-coordinate.


+$#Dv

Type: Scalar
Usage: Input to all shader classes.

Change in texture space V-coordinate.


+$#E

Type: Vector
Usage: Input to all shader classes.

Camera eye from point (R).


+$#I

Type: Vector
Usage: Input to all shader classes.

View direction vector of shading point.

Example:

//
// Get the angle between the surface and the view vector
//

// Get the surface normal
Nf = Normalize
(N);

// Get the view vector (normalized)
If = Normalize(I);

// Invert the surface normal so both vector are pointing the same direction
Nf = -Nf;

// Get the angle between the vectors
angle = ArcCos(Nf . If); // Get angle in Radians [0..2*Pi)


+$#ModI

Type: Scalar
Usage: Input to all shader classes.

Length of I vector.


+$#N

Type: Vector
Usage: Input to all shader classes.

Surface shading normal.

Example:

//
// Get the angle between the surface and the view vector
//

// Get the surface normal
Nf = Normalize
(N);

// Invert the surface normal so both vector are pointing the same direction
Nf = -Nf;

// Get the angle between the surface normal and the view vector
angle = ArcCos(Nf . UnitI); // Get angle in Radians [0..2*Pi)


+$#Ng

Type: Vector
Usage: Input to all shader classes.

Surface geometric normal. See N.



+$#P

Type: Vector
Usage: Input to all shader classes.

Surface shading point in local coordinate system.



+$#Pw

Type: Vector
Usage: Input to all shader classes.

Surface shading point in world coordinate system.



+$#Reverse

Type: Scalar
Usage: Input to all shader classes.

Surface reversal flag. True if the shading point is on an 'inside' face.


+$#Ti

Type: Vector
Usage: Input to transparency shaders.

Input transparency color.



+$#To

Type: Vector
Usage: Input to transparency shaders.

Output transparency color.


+$#U

Type: Scalar
Usage: Input to all shader classes.

Texture space U-coordinate.


+$#UnitI

Type: Vector
Usage: Input to all shader classes.

Normalized view direction vector of shading point. See also, I.



+$#V

Type: Scalar
Usage: Input to all shader classes.

Texture space V-coordinate.


+$#Abs

Use Abs to take the absolute value of a number, or for vectors, the absolute value of each member: Abs(N) = (abs(N.x), abs(N.y), abs(N.z))

Usage
Abs(Scalar), Abs(Vector)

Value   
Absolute value of the input.


Example:


N = (-1, -1, 2);
AN = Abs(N * 2);         // AN = (2, 2, 4)

Example:

y = -2;
x = abs(y);               // x = 2



+$#ActiveTime

ActiveTime returns the current trueSpace frame number.

Usage
ActiveTime, ActiveTime( )

Value   
Current trueSpace frame number.


Example:

N.z = N.z + ActiveTime * ZOffsetVelocity;




+$#Ambient

Calculate the color contribution of ambient light at the surface.

Usage: Ambient, or Ambient( )
Value: Vector

Returns the ambient illumination arriving at a surface, as a color.

Note: Ambient will only return a proper value in a Reflectance shader.

Example:

Co = Ka * Ambient();


+$#ArcCos

Calculates the inverse cosine of a given number.

Usage: ArcCos(Scalar)
Value: Scalar

ArcCos returns the inverse cosine. Input must be between -1 and 1. The return value is in radians; i.e. in the range [-Pi/2..Pi/2].

Example:

x = ArcCos(y * Pi);


+$#KArcSin

Calculates the inverse sine of a given number.

Usage: ArcSin(Scalar)
Value: Scalar

ArcSin returns the inverse sine. Input must be between -1 and 1. The return value is in radians; i.e. in the range [-Pi/2..Pi/2].

Example:

x = ArcSin(y * Pi);


+$#ArcTan

Calculates the arctangent of a given number.

Usage: ArcTan(Scalar)
Value: Scalar

Given a tangent, ArcTan calculates an angle (in radians).

Example:

angle_in_radians = ArcTan(y_over_x);

See also: ArcTan2


+$#KArcTan2

Calculates the arctangent of a given ratio.

Usage: ArcTan(Scalar, Scalar)
Value: Scalar

Given a tangent expressed as Y/X, ArcTan2 calculates an angle (in radians). ArcTan2 uses the signs of the input value to calculate the correct quadrant

Example:

angle_in_radians = ArcTan2(y, x);

See also: ArcTan


+$#Bias

{


Figure rendered with ShaderLab
shader Pi Func Bias


Apply a bias to a value.

Usage: Bias(Scalar, Scalar)
Value: Scalar

Bias(bias_amount, x);

Use bias to change the distribution of values on the interval [0..1] as shown in the figure.

Example:

value = Bias(bias_amount, x);


+$#CalculateNormal

Calculates a surface normal using a custom displacement function. There are two versions CalculateNormal, one for 3D input data and one for 2D.

Usage: CalculateNormal(Vector Point, Procedure CalcDisplace)
Value: Vector

Usage: CalculateNormal(Scalar U, Scalar V, Procedure CalcDisplace)
Value: Vector

See Displacement Shaders for additional information.


+$#Ceil

Rounds variables up toward positive infinity.

Usage: Ceil(Scalar)
Value: Scalar

Ceil(x);

Call Ceil to obtain the lowest integer greater than or equal to x.

Example:

Ceil(-2.8) = -2

Ceil(2.8) = 3

Ceil(-1.0) = -1


+$#KCellNoise

Synonym for NoiseCell



+$#Clamp

Clamp a value to a maximum and minimum.

Usage: Clamp(Scalar, Scalar, Scalar), Clamp(Scalar)
Value: Scalar

Clamp(x, min, max);
Clamp(y); // Same as Clamp(y, 0, 1);

Returns:
         min if x < min
         max if x > max
         otherwise x

Example:

// Make sure red_color is the range [0..1]
red_color = Clamp(red_color);
// Force blue_color to the range [0.5..1]
blue_color = Clamp(blue_color, 0.5, 1);




+$#KCos

Calculates the cosine of an angle.

Usage: Cos(Scalar), Cos(Vector)
Value: Scalar, Vector

Cos returns the cosine of the input angle. Input angles must be in radians (Pi radians = 180 degrees). For vectors, a vector is returned whose members are the Cos of each input member.

Example:

x = Cos(y * Pi);

See also: ArcCos


+$#KDiffuse

Calculate the color contribution of diffuse light at the surface.

Usage: Diffuse, or Diffuse( )
Value: Vector

Returns a color which represents the diffuse term for the illumination of the surface.

Note: Diffuse will only return a proper value in a Reflectance shader.

Example:

Co = Ka * Ambient() + Kd * Diffuse();




+$#Distance

Calculate the distance between two points

Usage: Distance(Vector, Vector)
Value: Scalar

Distance returns the distance between two vectors using the following equation:

Sqrt((x1 - x0)^2 + (y1 - y0)^2 + (z1- z0)^2)



+$#KDistanceToPlane

Calculate the distance between a point and a plane.

Usage: Distance(Vector, Vector, Vector)
Value: Scalar

Distance(Point, PlaneNormal, PointOnPlane);

Distance from Point to a plane with normal 'PlaneNormal' and containing 'PointOnPlane'. This distance is positive only if 'PnaleNormal' points towards 'Point'.


+$#KExp

Returns the exponential of X.

Usage: Exp(Scalar)
Value: Scalar

Exp(x)

Exp returns the value of e raised to the power of x, where e is the base of the natural logarithms.

See also: Ln


+$#Eye2World

Synonym for EyeToWorld


+$#KEyeToWorld


Rotate a vector from Eye space to World space.

Usage: EyeToWorld(Vector vector)
Value: Vector

Returns the input vector rotated by the trueSpace Eye2World transormation.

Example:

W = EyeToWorld(E);

See Also Eye2World, WorldToEye


+$#Faceforward

Invert vector normals for inside faces.

Usage: FaceForward (Vector, Vector)
Value: Scalar

Faceforward(N, I);

Adjust the normal so that it points towards E for inside and outside faces using:
if (N . I > 0) N = -N

Example:

//
Nf = Normalize(N);
//
// If Nf and I face the same direction,
// invert the value of Nf
//
Nf = FaceForward(Nf, I);


+$#FilterPixel

Get filtered color information from an image at a specified point.

Usage: FilterPixel(inU, inV, inFilterwidth)
Value: Vector (Color)

Parameters:

inU, inV - the normlized source location in the image of the color data
inFilterwidth - the width of the box filter that is applied

Return value: The function returns the filtered (anti-aliased) color of the pixel in the texture image at the supplied u,v position.

FilterPixel actually is part of the standard include library, not a built in function. You must include FilterPixel.slb to use this function. Also, your image variable must be called Texture.

Example:

#include FilterPixel.slb

if (filter == 0)
         Co = Pixel(Texture, repeat(st.u, 1), repeat(st.v, 1));
else
{
         Co = FilterPixel(st.u, st.v, filterwidth);
}

See Also: Pixel, Texel, FilterTexel


+$#KFilterTexel

Get filtered color information from an image.

Usage: FilterTexel(Image image)
Value: Vector (Color)

Parameters:

image - an image variable. Typically linked to a GUI control.

Return value: The function returns the filtered (anti-aliased) color of the pixel in the texture image at the current u,v position.

Example:

Co = FilterTexel(ColorTexture);

See Also: FTexel, Texel, Pixel, FilterPixel


+$#Floor

Rounds variables toward negative infinity.

Usage: Floor(Scalar)
Value: Scalar

Floor(x);

Call Floor to obtain the highest integer less than or equal to x.

Example:

Floor(-2.8) = -3

Floor(2.8) = 2

Floor(-1.0) = -1


+$#FresnelReflect

Calculate reflections using Fresnel's Law.

Usage: FresnelReflect(Vector, Vector, Vector)
Value: Vector

FresnelReflect(<reflected_direction>, <index>, <absorption>);

Calculate reflected ray direction and fractional contribution using Fresnel's Law. Value of the function is the color of the reflected vector. Direction of the reflected vector is returned in <reflected_direction>.

Example:

frColor = FresnelReflect(frDirection, index_color, absorption_color);


+$#KFTexel

Synonym for FilterTexel


+$#Gain

{


Figure rendered with ShaderLab
shader Pi Func Gain


Apply a gain to a value.

Usage: Gain(Scalar, Scalar)
Value: Scalar

Gain(gain_amount, x);

Use gain to change the distribution of values on the interval [0..1] as shown in the figure.

Example:

value = Gain(gain_amount, x);





+$#HSL2RGB

Convert a color from HSL to RGB space.

Usage: HSL2RGB(Vector color)
Value: Vector

Converts a color from representation as Hue, Saturation, and Lightness to Red, Green, Blue.

Example:

rgb = HSL2RGB(hsl);

See also: RGB2HSL.


+$#IsColor

Returns true (1) if current shader is a Color shader.

Usage: IsColor, IsColor( )
Value: Scalar

Example:

if (IsColor) Co = WhiteColor;

See also: IsReflectance, IsTransparency, IsDisplacement


+$#IsDisplacement

Returns true (1) if current shader is a Displacement shader.

Usage: IsDisplacement, IsDisplacement( )
Value: Scalar

Example:

if (IsDisplacement) N = CalculateNormal(PP, DisplaceFunc);

See also: IsColor, IsReflectance, IsTransparency


+$#IsReflectance

Returns true (1) if current shader is a Reflectance shader.

Usage: IsReflectance, IsReflectance( )
Value: Scalar

Example:

if (IsReflectance) Co = diffuse;

See also: IsColor, IsTransparency, IsDisplacement


+$#IsTransparency

Returns true (1) if current shader is a Transparency shader.

Usage: IsTransparency, IsTransparency( )
Value: Scalar

Example:

if (IsTransparency) Alpha = Random;

See also: IsColor, IsReflectance, IsDisplacement



+$#Lerp

Linearly interpolate between two numbers or vectors.

Usage: Lerp(Scalar, Scalar, Scalar), Lerp(Vector, Vector, Scalar)
Value: Scalar

Lerp(a, b, x);

Lerp linearly interpolates between it's first two parameters using the following equation:

(b - a) * x + a

Example:

// Find the value x percent between 3 and 10; x = [0..1]
value = Lerp(3, 10, x);

See also: Lerp is a synonym for Mix.


+$#Lerpstep

Calculate a value between 0 and 1 with a linear transition over a given range.

Usage: Lerpstep(Scalar, Scalar, Scalar)
Value: Scalar

This utility evaluates a linear step defined as follows:

Lerpstep( min, max, val )        = 0 ; if val < min
                                    = 1 ; if val < max
                                    = linear interpolation from min to max scaled to 0 to 1; otherwise

Example:

// Generate a value from 0 to 1 that
// rises as the input y goes from 100
// to 500. If y is below 100, value
// is always 0. If y is above 500,
// value is always 1.

value = Lerpstep(100, 500, y);

See also: Lerp is a synonym for Linearstep.


+$#Linearstep

See also: Linearstep is a synonym for Lerpstep.


+$#Ln

Returns the natural log of a number.

Usage: Ln(Scalar)
Value: Scalar

Ln(x)

Ln returns the natural logarithm (Ln(e) = 1) of the expression x.

See also: Exp


+$#Magnitude

Calculate the magnitude, or length, of a vector.

Usage: Magnitude(Vector), or |Vector|
Value: Scalar

Magnitude returns the length of a vector calculated by the following equation: Sqrt( x*x + y*y + z*z )

Magnitude can be calculated using either the function call or the vertical bars operator:

x = |N|;
x = Magnitude(N);



+$#Max

Returns the greater of two numeric values.

Usage: Max(Scalar, Scalar)
Value: Scalar

Max(x, y);

Call Max to compare two numeric values. Max returns the greater value of the two.

Example:

// Don't let x fall below smallest_x
x = Max(x, smallest_x);

See also: Min


+$#Min

Returns the lesser of two numeric values.

Usage: Min(Scalar, Scalar)
Value: Scalar

Min(x, y);

Call Min to compare two numeric values. Min returns the lesser value of the two.

Example:

// Don't let x go above largest_x
x = Min(x, largest_x);

See also: Max


+$#Mix

Linearly interpolate between two numbers or vectors.

Usage: Mix(Scalar, Scalar, Scalar), Mix(Vector, Vector, Scalar)
Value: Scalar

Mix(a, b, x);

Mix linearly interpolates between it's first two parameters using the following equation:

(b - a) * x + a

Example:

// Find the value x percent between White and Purple; x = [0..1]
value = Mix((1, 1, 1), (1, 0, 1), x);

See also: Mix is a synonym for Lerp.


+$#Noise

Calculate a value between 0 and 1 via a noise function.

Usage: Noise(Vector)
Value: Scalar

Evaluate a three-dimensional coherent noise function at the given location.

Example:

value = Noise(P);






+$#NoiseCell

Return a value between 0 and 1 from a pseudo-random integer lattice.

Usage: NoiseCell(Vector)
Value: Scalar

Evaluate a three-dimensional coherent noise function at the given location. Only evaluated for integers: all input values are truncated. Could be called box or cube noise.

Example:

value = NoiseCell(P);

Synonym for CellNoise




+$#NoiseClassic

Calculate a value between 0 and 1 via a noise function.

Usage: NoiseClassic(Vector)
Value: Scalar

Evaluate a three-dimensional coherent noise function at the given location.

Example:

value = NoiseClassic(P);





+$#NoisePerlin

Calculate a value between 0 and 1 via a Perlin noise function.

Usage: NoisePerlin(Vector)
Value: Scalar

Evaluate a three-dimensional coherent Perlin noise function at the given location.

Example:

value = NoisePerlin(P);




+$#NoiseSparseConv

Calculate a value between 0 and 1 via a sparse convolution noise function.

Usage: NoiseSparseConv(Vector)
Value: Scalar

Evaluate a three-dimensional coherent sparse convolution noise function at the given location.

Example:

value = NoiseSparseConv(P);




+$#NoiseWorley

Calculate a Worley cellular texture.

Usage: NoiseWorley(Vector)
Value: <none>

NoiseWorley starts with randomly distributed feature points in space (R3). For the input point, NoiseWorley finds the nearest feature points.

NoiseWorley does not return a value, but instead stores its results in a cache which are accessed by the WorleyN, WorleyD, and WorleyP functions.

WorleyN(F) returns the cell number for feature point F, where 0 <= F <= 3.

WorleyD(F) returns the distance from feature point F, where 0 <= F <= 4. If F==4, WorleyD returns a value equal to WorleyD(1) - WorleyD(0).

WorleyP(F) returns the position of feature point F, where 0 <= F <= 3.

Example:

// NoiseWorley function calculates Worley noise tables
NoiseWorley(PP);
// WorleyD(f) returns the distance (noise) for feature point f (0..3)
Co = color * WorleyD(0);

Example:

// NoiseWorley function calculates worley tables
NoiseWorley(PP);
// WorleyN(f) returns the cell ID for feature point #f (0..3)
// Use the cell ID to produce a random color
Seed(WorleyN(feature));
Co = (random, random, random);

Additional information: http://graphics.lcs.mit.edu/~mcm/6.838j/worley/s1.html

See Also: NoiseWorleyManhattan, WorleyN, WorleyD, WorleyP.


+$#NoiseWorleyManhattan

Calculate a Worley cellular texture using a Manhattan distance metric.

Usage: NoiseWorleyManhattan(Vector)
Value: <none>

NoiseWorleyManhattan functions exactly like NoiseWorley, except that distances are calculated using a Manhattan distance equation.

Manhattan distance between A and B is defined as Abs(A.X - B.X) + Abs(A.Y - B.Y) + Abs(A.Z - B.Z).

Example:

// Use 2d for more pleasing Manhattan effect
PP.z = 0;
// NoiseWorleyManhattan function calculates worley tables
NoiseWorleyManhattan(PP);
// WorleyN(f) returns the cell ID for feature point #f (0..3)
Seed(WorleyN(feature));
Co = (random, random, random);

Additional information: http://graphics.lcs.mit.edu/~mcm/6.838j/worley/s1.html

See Also: NoiseWorley, WorleyN, WorleyD, WorleyP.


+$#Normalize

Normalizes a vector.

Usage: Normalize(Vector)
Value: Vector

Vector is forced to be a unit vector; i.e. to have a length of 1. Performs equation nV = V / |V|, where |V| is the length (or magnitude) of V.

Example:

Co = Normalize(N);


+$#ObjectLocation

Get the location in space of the object being shaded.

Usage: ObjectLocation, ObjectLocation( )
Value: Vector

Note that the location is scaled depending on the current trueSpace setting for Object Units.

Example:

Loc = ObjectLocation;

See also: ObjectOrientation, ObjectSize


+$#ObjectOrientation

Get the orientation in space of the object being shaded.

Usage: ObjectOrientation, ObjectOrientation( )
Value: Vector

Returns the Euler angles for the object being shaded.

Example:

Rot = ObjectOrientation;

See also: ObjectLocation, ObjectSize


+$#ObjectSize

Get the size of the bounding box for the object being shaded.

Usage: ObjectSize, ObjectSize( )
Value: Vector

Note that the size values are scaled depending on the current trueSpace setting for Object Units.

Example:

Size = ObjectSize;

See also: ObjectLocation, ObjectOrientation


+$#Phong

Calculate the color contribution of light at the surface using the Phong model.

Usage: Phong(Scalar)
Value: Vector

Returns the phong term of the illumination of a surface, as a color. Scalar input is the Phong exponent.

Note: Phong will only return a proper value in a Reflectance shader.

Example:

Co = Kp * Phong(pe);




+$#Pi

Returns 3.1415926535897932385.

Usage: Pi, Pi( )
Value: Scalar

Use Pi in mathematical calculations that require pi, the ratio of a circle's circumference to its diameter. Pi is approximated as 3.1415926535897932385.

Example:

x = Sin(y * Pi);




+$#Pixel

Get color data from an image at a specified position.

Get color information from an image at a specified position.

Usage: Pixel(Image image, Scalar s, Scalar t)
Value: Vector (Color)

Parameters:

image - an image variable. Typically linked to a GUI control.

Return value: The function returns the color of the pixel in the texture image at the given s, t position.

Example:

Co = Pixel(ColorTexture, P.x, P.y);

See Also: FilterPixel, Texel, FilterTexel


+$#Pulse

Calculate a value between 0 and 1 with a smooth transition over a given range.

Usage: Pulse(Scalar, Scalar, Scalar, Scalar)
Value: Scalar

out_scalar = Pulse(min, max, fuzz, in_scalar);

A fuzzy pulse; it returns the value of smoothstep(a - fuzz, a, x) - smoothstep(b - fuzz, b, x).

See the following webpage for a discussion of Pulse:
http://www.cgrg.ohio-state.edu/~smay/RManNotes/RegularPatterns/transitions.html#pulse

Example:

// Generate a value from 0 to 1 that
// rises smoothly as the input y goes
// from 0.1 to 0.2 and then declines
// smoothly as y goes from 0.4 to 0.5
// If y is below 0.1, value will be
// equal to 0. If y is above 0.5,
// value will be equal to 1.

value = Pulse(0.2, 0.5, 0.1, y);



+$#Rand

Rand returns a pseudo-random number, 0 <= Rand < = 1

Usage: Rand, Rand( )
Value: Scalar

A random value between 0 and 1 inclusive.

Example:

Alpha = 0;
if (Rand > 0.5) Alpha = 1;

Example:

PP.x = Rand - Rand;

See also: Random, Seed



+$#KRandG

RandG returns a pseudo-random number with a Gaussian distribution, 0 <= RandG < = 1

Usage: RandG, RandG( )
Value: Scalar

A random value between 0 and 1 inclusive.

Example:

Alpha = 0;
if (RandG > 0.5) Alpha = 1;

Example:

PP.x = RandG - RandG;

See also: Rand



+$#Random

Synonym for Rand.



+$#KRandomize

Uses an internal timer to seed the random number generator.

Usage: Randomize, Randomize( )
Value: (none)

Randomize initializes the built-in random number generator with a random value (obtained from the system clock). The random number generator should be initialized by making a call to Randomize, or by calling Seed.

Example:

Randomize;

See also: Random, Seed




+$#Raytrace

Perform custom raytracing.

Usage: Raytrace(Vector, Vector, Vector, Scalar)
Value: Scalar (boolean)

RayTrace(<output_color>, <origin>, <direction>, <contribution>);

Ray tracing is supported for secondary shading phenomena, such as reflections and refractions, by the function RayTrace. The function traces a ray - a semi-infinite line - from the point specified by origin in the direction given by direction. The latter should be of unit length. The <contribution> parameter is used to indicate the maximum fractional contribution the ray will make to the current shading model, and should lie in the range zero (meaning no contribution) to one (for maximum contribution). The <contribution> parameter is used to terminate recursive computation of secondary rays when the accumulated contribution is less than a pre-specified tolerance. The color visible along the ray is returned in parameter <output_color>. The utility returns a value of 1 (true) if a ray-object intersection was found, and 0 (false) otherwise.

Example:

hit_anything = Raytrace(OutputColor, P, -I, 0.5);


+$#KReflect

Calculate simple mirror reflection

Usage: Reflect(Vector, Vector)
Value: Vector

Reflect(<vector_to_reflect>, <normal_of_reflection_plane>)

Returns a vector calculated from reflecting <vector_to_reflect> off of the plane defined by <normal_of_reflection_plane>.

Example:

reflected = Reflect(I, plane_normal);


+$#KRefract

Calculate refraction, using Snell's law

Usage: Refract(Vector result, Vector view, Vector normal, Scalar index)
Value: Scalar

Parameters:

result - The refracted vector is returned in this parameter
view - The vector to be refracted
normal - Normal of the plane on which the vector is incident
index - Refractive index of the surface

Return value: The function returns FALSE (0) if there is no transmission because of total internal reflection, and TRUE (1) otherwise

Example:

did_refract = Refract(refracted_ray, I, plane_normal, index_of_refraction);



+$#KRepeat

Converts input scalar to a value varying from [0..1) with given frequency. I.e., creates a sawtooth wave.

Usage: Repeat(Scalar in_scalar, Scalar frequency)
Value: Scalar

Repeat returns the value of (in_scalar * frequency) mod 1.

Example:

//
// Convert P.x to a value from 0..1 repeating for every 10 units of P.x
//
// for 0 < P.x < 10 => 0 <= value < 1
// for 10 < P.x < 20 => 0 <= value < 1
// and so on
//

value = Repeat(P.x, 10);



+$#RGB2HSL

Convert a color from HSL to RGB space.

Usage: RGB2HSL(Vector color)
Value: Vector

Converts a color from Red, Green, Blue representation to Hue, Saturation, and Lightness.

Example:

hsl = RGB2HSL(rgb);

See also: HSL2RGB.



+$#KRotate2D

Perform a rotation around the z-axis (in two-dimensions).

Usage: Rotate2D(Vector point, Vector center, Scalar angle_in_radians)
Value: Vector

Returns a point calculated by rotating point around center by angle_in_radians. This is a two-dimensional rotation so point.z and center.z are ignored. Return value always has z == 0.

Example:

rotated_uv = Rotate2D((U, V, 0), (0, 0, 0), Pi);


+$#Round

Input is rounded to the nearest integer

Usage: Round(Scalar), Round(Vector)
Value: Scalar, Vector

Round returns numbers rounded to the nearest integer. For vectors, it rounds each member: Round(V) = (Round(V.x), Round(V.y), Round(V.z))

Example:

x = Round(1.5); // x = 2.0

Example:

Z = (0.2, 1.6, 3.55);
Z = Round(Z); // Z = (0, 2, 4)




+$#Seed

Seed the random number generator. See Rand.

Usage: Seed(Scalar)
Value: (none)

Seed(x);

Call Seed to start a specific series of numbers from the pseudo-random number generator Rand.

Example:

id = 1513;
Seed(id);
Color = Rand; // Color will always have the same value:
                 // the first of random series #1513



+$#KShaderClass

ShaderClass returns the current shader type.

Usage: ShaderClass, ShaderClass( )
Value:
Scalar, one of: scColor, scTransparency, scReflectance, scDisplacement

Example:

if (ShaderClass EQ scColor) Co = (1, 0, 0);
else
if (ShaderClass EQ scTransparent) Alpha = 0.5;



+$#KSin

Calculates the sine of an angle.

Usage: Sin(Scalar), Sin(Vector)
Value: Scalar, Vector

Sin returns the sine of the input angle. Input angles must be in radians (Pi radians = 180 degrees). For vectors, a vector is returned whose members are the Sin of each input member.

Example:

x = Sin(y * Pi);

See also: ArcSin



+$#SmoothStep

Calculate a value between 0 and 1 with a smooth transition over a given range.

Usage: SmoothStep(Scalar, Scalar, Scalar)
Value: Scalar

This utility evaluates a smooth step defined as follows:
SmoothStep( min, max, val )      = 0 ; if val < min
                                    = 1 ; if val > max
                                    = spline interpolation from min to max scaled to 0 to 1; otherwise

Example:

// Generate a value from 0 to 1 that
// rises as the input y goes from 100
// to 500. If y is below 100, value
// is always 0. If y is above 500,
// value is always 1.

value = SmoothStep(100, 500, y);



+$#Specular

Calculate the specular color contribution of light at the surface.

Usage: Specular(Scalar)
Value: Vector

Returns a simple evaluation of the specular illumination term; no use of Fresnel filtering. Input scalar is the reciprocal of the roughness of the surface (1 / roughness).

Note: Specular will only return a proper value in a Reflectance shader.

Example:

Co = Ks * Specular(1 / r);




+$#KSpecularFresnel

Calculate the specular color contribution of light at the surface.

Usage: SpecularFresnel(Vector, Vector, Scalar)
Value: Vector

SpecularFresnel(<index>, <absorption_coefficient>, <one_over_roughness>)

Evaluate the specular reflection for a conductor using Fresnel's Law.

Example:

Co = Ks * SpecularFresnel(index_vector, absorption_vector, 1 / r);




+$#SpecularSolid

Calculate the specular color contribution of light at the surface.

Usage: SpecularSolid(Scalar, Scalar)
Value: Vector

SpecularSolid(<index>, <one_over_roughness>)

Returns the specular contribution for all non-ambient light sources from both reflected and transmitted highlights. The reciprocal of the specular roughness value is supplied in parameter <one_over_roughness>, and the index of refraction as <index>. The utility will automatically use the reciprocal of the refractive index if the view direction is leaving rather than entering the surface, based on the orientation of the surface normal.

Example:

Co = Ks * SpecularSolid(index, 1 / r);




+$#KSpecularSolidFresnel

Calculate the specular color contribution of light at the surface.

Usage: SpecularSolidFresnel(Scalar, Scalar)
Value: Vector

SpecularSolidFresnel(<index>, <one_over_roughness>)

Evaluate the specular reflection for a dielectric material using Fresnel's Law.

Example:

Co = Ks * SpecularSolidFresnel(index, 1 / r);


+$#Spline

Spline function returns a value that is interpolated through a spline curve.

Usage: Spline(Scalar, Vector Array)
Value: Vector

Spline(x, color_array); // x should range from [0..1].

Three-dimensional spline function returns a vector that is interpolated at position Scalar in the spline curve described by Vector Array.

Example:

// A spline curve from black to red+purple to black
// End points are doubled as to see more of the curve
colors = [ (0, 0, 0), (0, 0, 0), (0.5, 0, 0), (1.0, 0, 0.75), (0.5, 0, 0), (0, 0, 0), (0, 0, 0) ];

// Work in 30 frame (1 second) loops
// Note: to preview this effect, change the frame number
// and render your object or refresh the preview pane
loop_frames = 30;
t = ActiveTime mod loop_frames;

// Travel the curve from one side to the other based on animation frame
// the curve goes from position 0 to 1, so scale our position to 0 to 1
t = t / loop_frames;

// Select a color from position t in the curve
Co = Spline(t, colors);


+$#KSqr

Returns the square of a number.

Usage: Sqr(Scalar)
Value: Scalar

x_squared = Sqr(x)

Sqr returns the square of x, or x * x.



+$#Sqrt

Returns the square-root of a number.

Usage: Sqrt(Scalar)
Value: Scalar

square_root_x = Sqrt(x)

Sqrt returns the square root of x. I.e., Sqrt(x) * Sqrt(x) = x



+$#KStep

Produce a sharp transition based on a threshold.

Usage: Step(Scalar, Scalar)
Value: Scalar

x = Step(value, threshold);

This utility evaluates a step function as follows:

step(value, threshold)   = 0 ; if value < threshold
                           = 1 ; if value >= threshold

Example:

// Completely transparent (Alpha = 0) when
// angle is less than Pi

Alpha = Step(angle, Pi);




+$#KTan

Calculates the tangent of an angle.

Usage: Tan(Scalar), Tan(Vector)
Value: Scalar

Tan returns the tangent of the input angle. Input angles must be in radians (Pi radians = 180 degrees). For vectors, a vector is returned whose members are the Tan of each input member.

Example:

x = Tan(y * Pi);

See also: ArcTan


+$#Texel

Get color information from an image.

Usage: Texel(Image image)
Value: Vector (Color)

Parameters:

image - an image variable. Typically linked to a GUI control.

Return value: The function returns the color of the pixel in the texture image at the current u,v position.

Example:

Co = Texel(ColorTexture);

See Also: FilterTexel, FTexel, Pixel, FilterPixel


+$#KTrunc

Truncates a real number to an integer.

Usage: Trunc(Scalar), Trunc(Vector)
Value: Scalar, Vector

Returns the input with the decimal portion removed. For vectors, each member is truncated.

Example:

x = Trunc(1.5);  // x = 1.0



+$#Turbulence

Calculate a value between 0 and 1 via a three-dimensional fractal.

Usage: Turbulence(Vector, Scalar)
Value: Scalar

Turbulence(<Position>, <Passes>)

Turbulence calculates a three-dimensional fractal 1/f noise function at <Position>. The fractal is summed over <Passes> octaves.

Example:

value = Turbulence(P, 3);




+$#KTurbulenceClassic

Calculate a value between 0 and 1 via a three-dimensional fractal.

Usage: TurbulenceClassic(Vector, Scalar)
Value: Scalar

TurbulenceClassic(<Position>, <Passes>)

TurbulenceClassic calculates a three-dimensional fractal 1/f noise function at <Position>. The fractal is summed over <Passes> octaves.

Example:

value = TurbulenceClassic(P, 3);




+$#TurbulencePerlin

Calculate a value between 0 and 1 via a three-dimensional fractal.

Usage: TurbulencePerlin(Vector, Scalar)
Value: Scalar

TurbulencePerlin(<Position>, <Passes>)

TurbulencePerlin calculates a three-dimensional fractal 1/f noise function at <Position>. The fractal is summed over <Passes> octaves.

Example:

value = TurbulencePerlin(P, 3);


+$#KTurbulenceSparseConv

Calculate a value between 0 and 1 via a three-dimensional fractal.

Usage: TurbulenceSparseConv(Vector, Scalar)
Value: Scalar

TurbulenceSparseConv(<Position>, <Passes>)

TurbulenceSparseConv calculates a three-dimensional fractal 1/f noise function at <Position>. The fractal is summed over <Passes> octaves.

Example:

value = TurbulenceSparseConv(P, 3);


+$#KVolume

Support for simple ray-cast volume rendering.

density = Volume(Scalar depth, Scalar detail, Scalar dither, Procedure DensityProc);

Evaluates DensityProc sequentially, marching a ray from the current surface point into an imaginary density. Parameters specify the depth of the ray and the step size detail.

Dither value controls a spatial dither that can compensate for low detail and provide anti-aliasing.

DensityProc is the name of a procedure that calculates a density from a position.

Example:

Density()
{
         // Globals used for input:
         //
         // PP = point needing density calculation
         // DP = length of PP
         //
         // Function should output the density in DP
         //
         DP = DP * NoiseCell(PP * 10);
};

v = Volume(1, 20, 0.1, Density);
Alpha = Clamp(v);


+$#World2Eye

Synonym for WorldToEye


+$#WorldToEye

Rotate a vector from World space to Eye space.

Usage: WorldToEye(Vector vector)
Value: Vector

Returns the input vector rotated by the trueSpace World2Eye transformation.

Example:

// Generate a color based on the x - angle of the surface normal
// relative to the viewer.
// i.e., a screen-left to screen-right gradient.

R = WorldToEye(N);
m = Clamp((1 + R.x) / 2);
Co = mix((0, 0, 1), (1, 1, 0), m);

See Also World2Eye, EyeToWorld


+$#KWorld2Screen

Synonym for WorldToScreen


+$#KWorldToScreen

Rotate a vector from World space to Screen space.

Usage: WorldToScreen(Vector vector)
Value: Vector

Computes the (X, Y) pixel location of the input vector in the view being rendered. Returned Z value is 0.

See Also World2Screen


+$#WorleyD

Returns the distance from NoiseWorley feature point F.

Usage: WorleyD(Scalar F)
Value: Scalar

F must be 0 <= F <= 4.

If F==4, WorleyD returns a value equal to WorleyD(1) - WorleyD(0).

Can only be used after calling NoiseWorley or NoiseWorleyManhattan.

See Also: NoiseWorley, NoiseWorleyManhattan, WorleyN, WorleyP.


+$#KWorleyN

Returns the cell number for NoiseWorley feature point F.

Usage: WorleyN(Scalar F)
Value: Scalar

F must be 0 <= F <= 3.

Can only be used after calling NoiseWorley or NoiseWorleyManhattan.

See Also: NoiseWorley, NoiseWorleyManhattan, WorleyD, WorleyP.


+$#WorleyP

Returns the position of NoiseWorley feature point F.

Usage: WorleyP(Scalar F)
Value: Vector

F must be 0 <= F <= 3.

Can only be used after calling NoiseWorley or NoiseWorleyManhattan.

See Also: NoiseWorley, NoiseWorleyManhattan, WorleyN, WorleyD.