[SESI logo]

VEX Language Reference - Version 7.0

Side Effects Software Inc. 2004

VEX Run Time Library Reference

  • Standard VEX Operations
  • Runtime Math Library
  • Runtime String Library
  • Runtime Noise/Random Functions
  • Runtime Image Access Functions
  • Runtime Geometry Functions
  • Runtime Transformation Library
  • Runtime Miscellaneous Functions

  • Operations supported in VEX

    The standard arithmetic operations are supported for most data types. Please see the order of operations for VEX. Below is a list of the currently defined operators (and their return types):

  • Addition/Subtraction
    Result LHS RHS
    matrix matrix matrix
    matrix3 matrix3 matrix3
    vector4 vector4 vector4
    vector4 vector4 vector
    vector4 vector4 float
    vector4 vector4 int
    vector vector vector4
    vector vector vector
    vector vector float
    vector vector int
    float float float
    float float int
    int int float
    int int int
  • Multiplication
    Result LHS RHS
    matrix matrix matrix
    matrix3 matrix3 matrix3
    vector4 vector4 matrix
    vector4 vector4 vector4
    vector4 vector4 vector
    vector4 vector4 float
    vector4 vector4 int
    vector vector matrix
    vector vector matrix3
    vector vector vector4
    vector vector vector
    vector vector float
    vector vector int
    float float float
    float float int
    int int float
    int int int
  • Division
    Result LHS RHS
    vector4 vector4 float
    vector4 vector4 int
    vector vector float
    vector vector int
    float float float
    float float int
    int int float
    int int int
  • Modulo
    Result LHS RHS
    vector4 vector4 float
    vector vector float
    float float float
    int int int
  • Unary Negation
    Result LHS
    vector4 vector4
    vector vector
    float float
    int int
  • Structure reference/assignment

    It is possible to reference individual elements of a vector/vector4 type using the dot operator. Vector and Point data types are not actually structures, but the dot operator is provided as a convenience. The vector/vector4 can be referenced as either a position or a color. When referencing by position, the structure elements are (.x, .y, .z, [.w]). When referencing by color, the structure elements are (.r, .g, .b, [.a]). The .w and .a components are only available for the vector4 data type.

    It is also possible to use the getcomp() and setcomp() functions.

    Note: There is currently no mechanism for extracting components from matrix types. However, it is possible to get some of the information by multiplying a vector by the matrix and extracting information from the vector. Please see Matrix Functions for further information.

  • Equality Operators.

    The equality operators (==, !=, <, <=, >, >=) are defined when the left hand of the operator is the same type as the right hand side. They are defined for string, float and integer types only. The operations result in integer types.

  • Logic Operators

    The &&, || and ! operator apply solely to integer values.

  • Bitwise Operations

    The &, |, ^ and ~ operators are defined for integers only.

  • Special functions

  • assign(float &, float &, float &, float &, vector4)
    assign(float &, float &, float &, vector)
    assign(float &, float &, float &, ..., matrix3 mat)
    assign(float &, float &, float &, ..., matrix mat)

    These two functions provide an efficient way of extracting the components of a vector, vector4, matrix3 or matrix to float variables. To assign the components from a matrix3, 9 floats are required. For a matrix type, 16 floats are required.

  • matrix set(float, float, ..., float)
    matrix3 set(float, float, ..., float)
    vector4 set(float, float, float, float)
    vector set(float, float, float)

    These two functions provide a very efficient way of creating a vector/vector4. Each component is assigned from the argument passed in. The set() function which returns a matrix type expects 16 float values, while the function returning a matrix3 expects 9 values.

  • float getcomp(vector4, int)
    float getcomp(vector, int)
    float getcomp(matrix , float, int row, int col)
    float getcomp(matrix3 , float, int row, int col)

    These functions extract a single component of a vector, vector4, matrix3 or matrix.

  • void setcomp(vector4 &, float, int)
    void setcomp(vector &, float, int)
    void setcomp(matrix &, float, int row, int col)
    void setcomp(matrix3 &, float, int row, int col)

    These functions set a single component of a vector, vector4, matrix3 or matrix.


  • Mathematical Functions in VEX

  • Basic Mathematical Functions
  • Vector Functions
  • Interpolation Functions
  • Matrix Functions
  • Geometric Functions
  • Rendering Functions
  • Color Functions

  • Basic Mathematical Functions

    vector4 abs( vector4 ), vector abs( vector ), float abs( float ), int abs( int )
    vector4 acos( vector4 ), vector acos( vector ), float acos( float )
    vector4 asin( vector4 ), vector asin( vector ), float asin( float )
    vector4 atan( vector4 ), vector atan( vector ), float atan( float )
    float atan(float x, y), atan2( float x, y)
    vector4 ceil( vector4 ), vector ceil( vector ), float ceil( float )
    vector4 cos( vector4 ), vector cos( vector ), float cos( float )
    vector4 cosh( vector4 ), vector cosh( vector ), float cosh( float )
    vector4 degrees( vector4 ), vector degrees( vector ), float degrees( float )
    vector4 exp( vector4 ), vector exp( vector ), float exp( float )
    vector4 floor( vector4 ), vector floor( vector ), float floor( float ), int floor( float )
    vector4 frac( vector4 ), vector frac( vector ), float frac( float )
    vector4 int( vector4 ), vector int( vector ), float int( float )
    vector4 log( vector4 ), vector log( vector ), float log( float )
    vector4 log10( vector4 ), vector log10( vector ), float log10( float )
    vector4 pow( vector4, float ), vector pow( vector, float ), float pow( float, float )
    vector4 radians( vector4 ), vector radians( vector ), float radians( float )
    vector4 rint( vector4 ), vector rint( vector ), float rint( float )
    vector4 sin( vector4 ), vector sin( vector ), float sin( float )
    vector4 sinh( vector4 ), vector sinh( vector ), float sinh( float )
    vector4 sqrt( vector4 ), vector sqrt( vector ), float sqrt( float )
    vector4 tan( vector4 ), vector tan( vector ), float tan( float )
    vector4 tanh( vector4 ), vector tanh( vector ), float tanh( float )

    Many of these functions are defined for vector/vector4 data types. In these cases, each element of the vector/vector4 has the operator applied to it. For example: vector4 v, v1; v1 = sin(v); Is equivalent to: vector4 v, v1; v1.x = sin(v.x); v1.y = sin(v.y); v1.z = sin(v.z); v1.w = sin(v.w); but evaluates much more efficiently.

    abs computes the absolute value of the argument.
    acos computes the arc-cosine of the argument. The return value is in the range 0 to PI.
    asin computes the arc-sine of the argument. The return value is in the range -PI/2 to PI/2.
    atan computes the arc-tangent of the argument. The return value is in the range -PI/2 to PI/2. When two floats are passed, the function behaves as atan2()
    atan2 returns the arc-tangent of y/x and has a return value in the range -PI to PI
    ceil returns the smallest integer greater than or equal to the argument
    cos computes the cosine of the argument.
    cosh computes the hyperbolic cosine of the argument.
    degrees converts the argument from radians into degrees
    exp computes the exponential function of the argument.
    floor returns the largest integer less than or equal to the argument
    frac returns the fractional component of the floating point number. This is equivalent to (x - floor(x)).
    int if the argument is negative, this returns ceil(x), otherwise it returns floor(x).
    log computes the natural logarithm of the argument
    log10 computes the logarithm (base 10) of the argument
    pow raises the first argument to the power of the second argument
    radians converts the argument from degrees into radians
    rint rounds the number to the closest integer.
    sin computes the sine of the argument
    sinh computes the hyperbolic sine of the argument
    sqrt computes the square root of the argument
    tan computes the trigonometric tangent of the argument
    tanh computes the hyperbolic tangent of the argument


    Vector Functions

    float distance( vector p1, p2),
    float distance2( vector p1, p2)
    float distance( vector4 p1, p2)
    float distance2( vector4 p1, p2)

    Returns the distance between the two 3 or 4 dimensional points passed in. distance2 returns the squared distance.

    float dot( vector4 a; vector b),
    float dot( vector a; vector4 b),
    float dot( vector a, b)

    Computes the dot product between the arguments. When 4 component vectors are specified, only the first three components are taken into consideration.

    float length( vector ),
    float length2( vector )
    float length( vector4 )
    float length2( vector4 )

    Computes the length of the vector or vector4. length2 returns the squared distance.

    vector normalize( vector )
    Returns the normalized vector

    float avg( vector )
    float max( vector )
    float min( vector )

    Returns the average of the 3 components, the maximum of the 3 components or the minimum of the 3 components of the vector.

    vector cross( vector a, b )
    Computes the cross product between the two vectors


    Interpolation Functions

    float min( float a, b, ...),
    float max( float a, b, ... )

    Returns the minimum or maximum value of the parameters. Any number of parameters may be specified

    vector4 clamp( vector4 value, min, max),
    vector clamp( vector value, min, max),
    float clamp( float value, min, max),
    int clamp( int value, min, max )

    Each component of the vector is clamped between the minimum and maximum values

    float fit( float value, omin, omax, nmin, nmax)
    vector fit( vector value, omin, omax, nmin, nmax)
    vector4 fit( vector4 value, omin, omax, nmin, nmax)

    Takes the value in the rangeo (omin, omax) and shifts it to the corresponding value in the new range (nmin, nmax). For example:

    fit(.3, 0, 1, 10, 20)
    Would return the value 13.

    vector4 lerp( vector4 value1, value2; float amount),
    vector lerp( vector value1, value2; float amount),
    float lerp( float value1, value2; float amount)

    Performs bilinear interpolation between the values. If the amount is outside the range 0 to 1, the values will be extrapolated linearly.

    float smooth( float value1, value2, amount, rolloff),
    float smooth( float value1, value2, amount)

    Computes a number between zero and one. The return code is 0 if the amount passed in is less than or equal to value1, 1 if the amount is greater than or equal to value2. If the amount is between value1 and value2, a smooth (easin/easeout) interpolation is computed. If a rolloff is specified, the inflection point of the blend will be shifted. If the rolloff is greater than 1, the shift will be to the right, if the rolloff is less than 1 (and greater than 0), the shift will be to the left.

    vector4 cspline( float t; vector4 val1, ... ),
    vector cspline( float t; vector val1, ... ),
    float cspline( float t; float val1, ... )

    Computes a Catmull-Rom (Cardinal) spline between the key points specified. The keys are uniformly spaced over the range 0 to 1. Because of the nature of the Cardinal spline, the value associated with the first and last keys will never be returned. However, these keys are used to determine the shape of the curve on entry and exit.

    vector4 lspline( float t; vector4 val1, ... ),
    vector lspline( float t; vector val1, ... ),
    float lspline( float t; float val1, ... )

    Computes a linear spline between the key points. This is equivalent to a sequence of lerp() functions.

    vector4 ckspline( float t; vector4 val1; float key1; vector4 val2; float key2, ... ),
    vector ckspline( float t; vector val1; float key1; vector val2; float key2, ... ),
    float ckspline( float t; float val1; float key1; float val2; float key2, ... )

    Computes a Catmull-Rom (Cardinal) spline between the key points specified. The values are spaced according to the keys given. The domain of the interpolant (t) should be between the second and second last key value specified. The keys should be specified in ascending order or results will be unpredictable.

    Because of the nature of the Cardinal spline, the value associated with the first and last keys will never be returned. However, these keys are used to determine the shape of the curve on entry and exit. For example:

    Cf = ckspline(s, {1,1,1}, -0.25, // First key {.5,.5,.5}, 0.0, // Second key {.5, 0,.5}, 0.25, // Third key {0,0,.8}, 1.0, // Fourth key {0,0,0}, 1.25); // Fifth key The Catmull-Rom spline defined by the above keys would be valid for interpolants in the range 0 to 1. The first and last keys are used solely to determine the slope of the curve at the second and second last keys.

    vector4 lkspline( float t; vector4 v1; float k2; vector4 v2; float k2; ... ),
    vector lkspline( float t; vector v1; float k1; vector v2; float k2; ... ),
    float lkspline( float t; float v1; float k1; float v2; float k2; ... )

    Computes a linear spline between the key points. The values are spaced according to the keys given. The keys should be specified in ascending order or the results will be unpredictable.


    Matrix Functions

    float determinant( matrix ), float determinant( matrix3 )
    matrix3 dihedral( vector a, b)
    matrix ident( void ), matrix3 ident( void )
    matrix invert( matrix ), matrix3 invert( matrix3 )
    matrix3 lookat( vector from, to, up),
    matrix3 lookat( vector from, to; float roll),
    matrix3 lookat( vector from, to)
    void rotate( matrix &; float amount; vector axis),
    void rotate( matrix3 &; float amount; vector axis)
    void scale( matrix &; vector scale_vector),
    void scale( matrix3 &; vector scale_vector)
    void translate( matrix &; vector4 amount),
    void translate( matrix &; vector amount)
    void transpose( matrix & ),
    void transpose( matrix3 & )
    matrix maketransform(int trs, xyz; vector t, r, s, p)
    matrix maketransform(int trs, xyz; vector t, r, s)
    matrix3 maketransform(vector zaxis, xaxis)
    matrix maketransform(vector zaxis, xaxis; vector translate)
    vector vtransform(vector v; matrix xform)
    vector cracktransform(int trs, xyz, c; vector p; matrix xform)


    determinant computes the determinant of the matrix
    dihedral computes the rotation matrix which rotates the vector a onto the vector b.
    ident computes identity matrices
    invert inverts the matrix. If the matrix is singular, the original matrix is returned.
    lookat computes a rotation matrix to orient the z-axis along the vector (to-from) under the transformation. If an up vector is specified, this will determine the roll.
    rotate applies a rotation to the given matrix. The angle must be given in radians and the axis must be normalized.
    scale scales the given matrix in three directions simultaneously (X, Y, Z - given by the components of the scale_vector).
    translate will apply a translation to the given matrix
    transpose will transpose the given matrix
    maketransform(int trs, xyz, ...) Builds a general 4x4 transform matrix given an order of transformations (trs), an order for rotations (xyz), a vector representing the translation (t), rotation (r), scale (s) (and optionally a pivot (p)). The specifications for the trs and xyz parameters can be found in $HFS/houdini/vex/include/math.h
    maketransform(vector zaxis, xaxis, ...) Builds either a 3x3 transform matrix or a 4x4 transform matrix. The transform matrix will be constructed so that applying the matrix will transform the z-axis to the axis specified and the x-axis to the axis specified. The version which returns a 4x4 transform will apply the translation to the 4x4 matrix. This function is very similar to the lookat function. The vectors passed in are not normalized meaning that scales should be preserved in construction of the transform.
    vtransform
    The * operator on a vector multiplied by a transform matrix assumes that the vector represents positional information. If the vector represents directional information, the vtransform function will do the correct multiplication. Basically, the translations associated with the 4x4 matrix will not be applied to the transform.
    cracktransform
    Depending on the value of c, returns the translate (c=0), rotate (c=1), or scale (c=2) component of the transform (xform). The function uses the given transform and rotation orders (trs and xyz) and the given pivot point (pivot) to calculate the return value. The specifications for the trs and xyz parameters can be found in $HFS/houdini/vex/include/math.h.

    Geometric Functions

    void clip( int &result; vector &p0, &p1; vector min, max)
    void clip( int &result, vector &p0, &p1; vector4 plane)

    The clip functions will clip the line segment between p0 and p1. The first form will clip the line segment to the bounding box specified by the min & max corner points.
    The second form will clip the line segment against an arbitrary 3D plane specified by the plane equation (plane.x*x + plane.y*y + plane.z*z + plane.w).
    If the line is entirely clipped out of the result will be set to 0. otherwise, the values p0 and p1 will be clipped to the constraints specified and the result will be 1.

    float ptlined(vector P0, P1, Q)
    This function returns the closest distance between the point Q and a finite line segment between points P0 and P1.


    Rendering Functions

    float atten( float attenuation, distance)
    Computes attenuated falloff. This is equivalent to: attenuation/(attenuation+distance).

    vector fresnel( vector i, n; float eta; float &kr, &kt)
    vector fresnel( vector i, n; float eta; float &kr, &kt; vector &R, &T)
    Computes the fresnel reflection/refraction contributions given an incoming vector, surface normal (both normalized), and an index of refraction (eta). The amount of reflected light will be returned in Kr, and the amount of transmitted light will be returned in Kt. Optionally, the reflection and transmission vectors can be returned in the R and T variables. The R & T variables will be normalized vectors on exit.

    As a note, kt is scaled by the index of refraction (eta) which can cause the value to be non-intuitive. To change this behaviour, simply divide the kt returned from the fresnel function by the index of refraction passed in.

    vector frontface( vector N, I, Nref)
    vector frontface( vector N, I)

    If dot(I, Nref) is less than zero, N will be negated. The second form (which doesn't take a reference vector) is only available in the shading contexts, where the Ng variable is used.

    vector reflect( vector direction, normal)
    Returns the vector representing the reflection of the direction against the normal.

    vector refract( vector direction, normal; float index)
    Computes the refraction ray given an incoming direction, the normalized normal and an index of refraction


    Color Functions

    vector hsvtorgb( vector ), vector hsvtorgb( float hue, sat, val)
    Convert HSV color space into RGB color space. A vector representing the RGB triple is returned. The hue should be in the range 0 to 1.

    float luminance( vector ), float luminance( float r, g, b)
    Compute the luminance of the RGB color specified by the parameters

    vector rgbtohsv( vector ), vector rgbtohsv( float h, s, v)
    Convert RGB color space to HSV color space. A vector representing the HSV color is returned. The hue will be in the range 0 to 1.


    String Functions in VEX

  • string concat(string s1, s2, ...)
    Concatenate all the strings specified to form a single string. This is equivalent (but slightly more efficient when there are more than 2 strings) to adding all the strings together.

  • int strlen(string string)
    This function computes the length of the string given.

  • int atoi(string string)
    float atof(string string)
    These functions convert a string to an integer or float value.

  • int match(string pattern, subject)
    This function returns 1 if the subject matches the pattern specified, or 0 if the subject doesn't match. The standard Houdini pattern matching is used. Multiple patterns may be separated by spaces or commas. The special characters for matching are:
  • ? Match any character
  • * Match any number of characters
  • [list] Match any of the characters specified in the list.
  • If a pattern is prefixed by a carat (^), then subjects which match this pattern will be excluded from the match. Examples:
    "a*" - Match any string beginning with a. "a*,^aardvark" - Match any string beginning with a except for aardvark. "[abc]*z" - Match any string beginning with a, b or c and ending with z. "g*,^geo*" - Match any string beginning with g, but not any string beginning with geo.

  • Noise Functions in VEX

  • Perlin Noise
  • Worley Noise
  • Voronoi Noise
  • Original Perlin Noise
  • Sparse Convolution Noise
  • Alligator Noise
  • Hscript Noise
  • Random Number Generation
  • Non-Deterministic Random Number Generation
  • The relative costs for computing noise of different types is roughly:
    Cost Noise Type
    1.0 Perlin Noise
    1.1 Original Perlin Noise
    1.8 Worley Noise
    2.1 Sparse Convolution Noise
    2.3 Alligator Noise

    Perlin Noise Functions

    There are two forms of Perlin style noise. A non-periodic noise which changes randomly throughout the N-dimensional space and a periodic form which repeats itself over a given range of the space. The periodic form can be used to generate patterns which "tile" over N-dimensional space (i.e. a noise based texture map which repeats seamlessly).

    The noise has a range of (0, 1) with a median value of 0.5. The distribution of the noise depends on the dimension, with higher dimensions approaching a Gaussian distribution of noise values.

    Dimen. Scalar Vector Periodic Scalar Periodic Vector
    1D float
    noise(float x)
    vector
    noise(float x)
    float
    pnoise(float x;
    int px)
    vector
    pnoise(float x;
    int px)
    2D float
    noise(float x, y)
    vector
    noise(float x, y)
    float
    pnoise(float x, y;
    int px, py)
    vector
    pnoise(float x, y;
    int px, py)
    3D float
    noise(vector)
    vector
    noise(vector)
    float
    pnoise(vector;
    int px, py, pz)
    float
    pnoise(vector pos, p)
    vector
    pnoise(vector;
    int px, py, pz)
    vector
    pnoise(vector pos, p)
    4D float
    noise(vector4)
    vector
    noise(vector4)
    float
    pnoise(vector4;
    int px, py,
    pz, pw)
    float
    pnoise(vector4 pos, p)
    vector
    pnoise(vector4;
    int px, py,
    pz, pw)
    vector
    pnoise(vector4 pos, p)


    Worley Noise Functions

    Worley noise works by scattering points randomly through space (according to a nice Poisson distribution). The wnoise functions return the distance to the N closest points (where N is either 2 or 4). They also return a "seed" which is associated with the first closest point. This seed is pretty much guaranteed to be unique for every point (meaning that it's unlikely that two points close by have the same seed associated with them).

    The general form of the wnoise functions is:

    void wnoise(position; int &seed; float &f1, &f2)
    void wnoise(position; int &seed; float &f1, &f2, &f3, &f4)
    where position is either a single float (1D noise), two floats (2D noise), a vector (3D noise) or a vector4 (4D noise). The seed is returned in the integer parameter, and the N closest points are returned in f1...fN (where N is 2 or 4).

    The distances returned will be sorted from closest to farthest, meaning that the following identity is true:

    f1 <= f2 <= f3 <= f4

    It is then possible to combine these distances to generate noise patterns. The noise generated tends to be very "cellular" in nature, in fact, one of the nice things is that you can determine "cell" boundaries by using the expression:

    if (f2 - f1 < tollerance) ...
    which will be true if the point in space is crossing the boundary between two cells.


    Voronoi Noise Functions

    Voronoi noise gives almost identical results to the Worley noise functions. However, the Voronoi noise functions have controls over jittering (i.e. how randomly the points are scattered through space) and also return the actual locations of the two nearest points. The Voronoi noise functions are limited to returning the two nearest points.

    The general form of the wnoise functions is:

    void vnoise(position, jitter; int &seed; float &f1, &f2; &pos1, &pos2)
    where position, jitter, pos1 and pos2 are a single float (1D noise), two floats (2D noise), a vector (3D noise) or a vector4 (4D noise). The seed is returned in the integer parameter, and the distance to pos1 and pos2 are returned in f1 and f2.

    Though this function is slightly more expensive than wnoise, the fact that the actual point posisitions are returned allows the function to overcome some of the artifacts of Worley noise. For example, to get even boundaries along the cell boundaries:

    if (f2 - f1 < tollerance * (distance(p1, p2)/(f1+f2))...
    which will "normalize" the boundary width based on the distance between the two random points in space.

    There are also periodic forms of vnoise()

    For example:

    // 1D noise float fp0, fp1, p1x, p1y, p2x, p2y; vector vp0, vp1; vnoise(s*10, 0.8, seed, f1, f2, fp0, fp1); vnoise(s*10, t*10, 0.8, 0.8, seed, f1, f2, p1x, p1y, p2x, p2y); vnoise(P*10, {.8, .8, .8}, seed, f1, f2, vp0, vp1);

    Original Perlin Noise Functions

    These functions are similar to the noise functions listed above. However, they are marginally less efficient in computation and don't have the same charactaristics.

    The bounds on the noise are roughly (-1, 1). Only 3D noise is supported. However, this noise has the ability to compute turbulence with roughness and attenuation on the noise.

  • float onoise(vector pos),
  • vector onoise(vector pos),
  • float onoise(vector pos; int turbulence; float rough, atten),
  • vector onoise(vector pos; int turbulence; float rough, atten),

    Sparse Convolution Noise Functions

    These functions are similar to the Worley noise functions listed above. The noise returned is based on the weights of all of the closest points, with each points's contribution based on a meta-ball like rolloff curve. That is, if the sample point is close to the sphere, its contribution will be greater.

    The bounds on the noise are roughly (-1.7, 1.7). Only 3D noise is supported. However, this noise has the ability to compute turbulence with roughness and attenuation on the noise.

  • float snoise(vector pos),
  • vector snoise(vector pos),
  • float snoise(vector pos; int turbulence; float rough, atten),
  • vector snoise(vector pos; int turbulence; float rough, atten),

    Alligator Noise Functions

    These functions are similar to the Worley noise functions listed above. It is currently not possible to simulate alligator noise using the Worley functions, but it's possible to get a very similar "look".

    The bounds on the noise are roughly (-1, 1). Only 3D noise is supported. However, this noise has the ability to compute turbulence with roughness and attenuation on the noise.

  • float anoise(vector pos),
  • vector anoise(vector pos),
  • float anoise(vector pos; int turbulence; float rough, atten),
  • vector anoise(vector pos; int turbulence; float rough, atten)

    Hscript Noise Functions

    These functions mimic the Houdini expression functions noise(), snoise(), turb() and sturb(). They have very similar properties to the onoise() and snoise functions, but will produce results which match the Houdini expression functions exactly.

  • float hscript_noise(vector pos),
  • float hscript_turb(vector pos; int turbulence),
  • float hscript_snoise(vector pos),
  • float hscript_sturb(vector pos; int turbulence)

    Random Number Functions in VEX

    vector4 random(vector4 position)
    vector4 random(vector position)
    vector4 random(float xpos, float ypos)
    vector4 random(float position)
    vector4 random(int xpos, int ypos)
    vector4 random(int position)
    vector random(vector4 position)
    vector random(vector position)
    vector random(float xpos, float ypos)
    vector random(float position)
    vector random(int xpos, int ypos)
    vector random(int position)
    float random(vector4 position)
    float random(vector position)
    float random(float xpos, float ypos)
    float random(float position)
    float random(int xpos, int ypos)
    float random(int position)

    float hscript_rand(float seed)

    These random functions will generate a random number based on the position in N dimensional space (where N is 1 to 4 dimensions). Unlike the noise functions which smoothly interpolate the random values between integer lattice points, the random functions do not. The random() functions are very efficient ways of doing something like: noise(floor(position)).

    The hscript_rand() function will produce the exact same results as the Houdini expression function of the same name. This function will generate different random values for every floating point seed. This is different that the random() function which converts the floating point argument to an integer seed. The hscript_rand() function may produce different results on different hardware or operating systems.


    Non-Deterministic Random Number Functions in VEX

    vector4 nrandom([string scheme])
    vector nrandom([string scheme])
    float nrandom([string scheme])

    The nrandom() functions are non-deterministic random number generators for VEX. Numbers generated will be between 0 and 1. These random generators will generate the same sequence of random numbers if called in precisely the same order. However, there is no seed involved so it is not possible to reproduce the same random number or sequence multiple times.

    An optional string argument is taken to determine the random number generation method. The string may be one of:

    default Efficient random number generation. This method is backward compatible with previous releases of Houdini.
    mersenne
    or twister
    Uses the Mersenne Twister which has some very nice properties. This code is based of the work of:
    Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
    All rights reserved.

    Image Functions in VEX

  • Color Images
  • Bump Images
  • Z-Pic Depth Images
  • 3D Image Functions
  • Point Cloud Texture Functions
  • General Notes

  • Unless otherwise specified, if the u/v coordinates are not in the range [0,1), the fractional component of the coordinate will be used to access the map. This means that uv=(0.3, 0.5) will evaluate to the same value as uv=(3.3, -5.5).

  • When area sampling an image, if a .rat file is used as a texture, the sampling will use a more efficient and higher quality algorithm for averaging the pixel samples enclosed in the area.


  • Color Image Functions

    There are various forms for looking up a color from a disk image. There are typically two forms of each function, one which returns a vector (RGB values only) and the other which returns a vector4 (RGB and Alpha values). The functions have the forms:

  • vector colormap(string filename; vector uvw; ...)
    This function will lookup a single sample of from the filename given. The first two components of the vector are used to reference the image (in 0 to 1 space). No area sampling is done, but bilinear interpolation is done on raw pixel values.

  • vector colormap(string filename; float u, v; ...)
    This function will lookup a single sample of from the filename given. The first two components of the vector are used to reference the image (in 0 to 1 space). No area sampling is done, but bilinear interpolation is done on raw pixel values.

  • vector colormap(string filename; float u0, v0, u1, v1,
    u2, v2, u3, v3; int samples; ...)
    This function will sample the area enclosed by the quadrilateral (uv0),(uv1),(uv2),(uv3). The quadrilateral will be sampled stochastically using the number of samples passed in (unless the image is a .rat file). Each sample will use bilinear interpolation on raw pixel values.

  • vector colormap(string filename; vector uv, du, dv; int samples; ...)
    This function will filter the area of the image enclosed by the quadrilateral formed by (uv)-(uv+du)-(uv+du+dv)-(uv+dv). The quadrilateral will be sampled stochastically using the number of samples specified (unless the image is a .rat file). Each sample will use bilinear interpolation on raw pixel values.

  • vector colormap(string filename; vector uv0, uv1, uv2, uv3; ...)
    This function will filter the area of the image enclosed by the quadrilateral formed by (uv0)-(uv1)-(uv2)-(uv3). The quadrilateral will be sampled stochastically using the number of samples specified (unless the image is a .rat file). Each sample will use bilinear interpolation on raw pixel values.

  • There are corresponding versions of each of the above functions which return vector4 data types (which include alpha information in the fourth component of the vector4). If an image doesn't have an alpha channel associated with it (i.e. a JPEG image), the alpha will be set to 1. For example:
    vector4 colormap(string filename; float u, v; ...)

    There are corresponding versions of each of the above functions which do not use bilinear interpolation of the raw pixel values. These function names are prefixed with "raw". For example:

    vector rawcolormap(string filename; float u, v; ...)
    vector4 rawcolormap(string filename; float u, v; ...)

    All of the colormap functions are variadic (meaning they take variable number of arguments). Additional arguments can be used to specify filtering options for the texture. These arguments must be defined at load time. That is, the arguments must be constants or parameters. The additional arguments are:

    Image Map Filter Arguments

    Keyword Values
    wrap or
    mode
    Puts constraints on how the image is evaluated when the texture coordinates are outside the range 0 to 1.
    repeat, periodic
    The image map will repeat outside the range 0 to 1. Basically, the integer component of the texture coordinate is ignored.
    clamp, edge, streak
    The texture coordinates will be clamped to the range 0 to 1. This causes evaluations outside the range to evaluate to the color at the closest edge of the image (the border pixels are streaked outside the range).
    black, decal, color
    Coordinates outside the range 0 to 1 will evaluate to the border color (rather than a color in the image). The border color is black (i.e. 0) by default.
    uwrap or
    swrap or
    smode
    Specifies the behaviour when the u coordinate is outside the range 0 to 1. The values are the same as with wrap.
    vwrap or
    twrap or
    tmode
    Specifies the behaviour when the v coordinate is outside the range 0 to 1. The values are the same as with wrap.
    border Specifies the border color when Black/Decal/Color wrapping is used. The value following this argument should be a float, vector or vector4 argument. If not specified, the border color will be black (i.e. 0) by default.
    filter Specifies the type of anti-aliasing filter to be used for evaluation. The following argument should be a string specifying one of:
    point - Point sampling (i.e. no filtering)
    box - Box filter (default)
    gauss - Gaussian filter
    bartlett - Bartlett/Triangular filter
    sinc - Sinc sharpening filter
    hanning - Hanning filter
    blackman - Blackman filter
    catrom - Catmull-Rom filter
    xfilter or
    sfilter or
    ufilter
    Specifies the filter for the x direction. The filter can be any one of those listed above.
    yfilter or
    tfilter or
    vfilter
    Specifies the filter for the y direction. The filter can be any one of those listed above.
    width Specifies the filter width in both x and y directions. The following argument should be a float value.
    swidth or
    xwidth or
    uwidth
    Specifies the filter width only in the x direction.
    twidth or
    ywidth or
    vwidth
    Specifies the filter width only in the y direction
    extrapolate
    Specifies whether derivative extrapolation should be used when computing anti-aliasing information. Extrapolation of derivatives is on by default. The argument should be either 0 or 1.
    lerp
    Specifies whether RAT files should interpolate between different MIP levels. By default, this is turned off. Turning interpolation on will help remove discontinuities when different MIP levels of a .rat file are accessed. However, the results of texture evaluation will be slightly softer (i.e. blurrier) and will take more time. The argument should be either 0 or 1.

    Examples of specifying filter parameters:
    colormap(map, u, v, "smode", "decal", "tmode", "repeat", "border", {.1,1,1}); colormap(map, u, v, "mode", "clamp", "width", 1.3); colormap(map, u, v, "filter", "gauss", "width", 1.3, "mode", "repeat");


    Bump Map Functions

  • void bumpmap( string filename; float &du, &dv; vector uvw)
  • void bumpmapR( string filename; float &du, &dv; vector uvw)
  • void bumpmapG( string filename; float &du, &dv; vector uvw)
  • void bumpmapB( string filename; float &du, &dv; vector uvw)
  • void bumpmapA( string filename; float &du, &dv; vector uvw)
  • void bumpmapL( string filename; float &du, &dv; vector uvw)

  • void bumpmap( string filename; float &du, &dv; float u, v)
  • void bumpmapA( string filename; float &du, &dv; float u, v)
  • void bumpmapB( string filename; float &du, &dv; float u, v)
  • void bumpmapG( string filename; float &du, &dv; float u, v)
  • void bumpmapL( string filename; float &du, &dv; float u, v)
  • void bumpmapR( string filename; float &du, &dv; float u, v)
  • Bump maps will return the color gradient of the image in the du/dv parameters. There are 6 different forms of the bump map function differentiated by the trailing character of the function name. The functions will compute the gradient based on:

  • Using a pre-computed bumpmap (i.e. output from ibumpmap)
  • Using the gradient in the red channel (bumpmapR)
  • Using the gradient in the green channel (bumpmapG)
  • Using the gradient in the blue channel (bumpmapB)
  • Using the gradient in the alpha channel (bumpmapA)
  • Using the gradient of the luminance (bumpmapL)
  • Bilinear interpolation is done on the raw pixel values. Though, there are versions of the above functions which do not use bilinear interpolation. These non-interpolating functions have their names prefixed with "raw". For example:
    rawbumpmapG(string filename; float &du, &dv; vector uvw);

    The du/dv parameters will be in the range (-1, 1).


    Z-Pic Depth Image Functions

    float depthmap(string filename; vector uvw)
    float depthmap(string filename; float u, v)
    float shadowmap(string filename; vector Pndc; float spread, bias, quality)

    The depthmap functions work on an image which was rendered as a z-depth image from mantra. They return the floating point distance from the camera to the pixel in question. There is no area sampling done when sampling depth values. As well, if the u/v values are not in the range 0 to 1, a value of 1E6 will be returned (indicating a "far" value).

    The shadowmap function will treat the depth map as if the image were rendered from a light source. The Pndc parameter represents the position of the point being shaded in the NDC space of the light's projection. The spread is a softness control on the shadow, while the bias controls how accurate the depth samples need to be. The quality is a general control to increase/decrease sampling. A quality of 1 is typical quality. The fractional amount of illumination which reaches the sample point will be returned. For example, if the point is fully in shadow, the return value will be 0, if it is fully illuminated, the return value will be 1.


    3D Image Functions

  • vector photonmap(string mapname; vector P, N, ...)

    The photonmap function will evaluate a photon map and return the resulting color information. The function takes optional arguments to define the behaviour of the evaluation:
    "nphotons" Specifies the number of photons to use in the filtering process. This specifies the maximum number of photons which will be filtered to produce the final color.
    The default is 50 photons.
    "type" This parameter specifies how the photons should be interpreted. There are two possibilities for the type of photon filtering:
    1. diffuse - Each photon will be scaled by the Lambertian cosine law.
    2. irradiance - The raw energy of each photon will be used (without any filtering).
    The default is "diffuse".
    "error" Specifies the "accuracy" for the lookup of photons in the photon map. This parameter determines the search radius to find photons in the map. Larger numbers will result in less accurate evaluations (i.e. smaller areas of the map will be scanned), while smaller number will result in larger areas of the map being scanned. The cost of filtering goes up as the error tolerance is decreased (meaning renders will take longer).
    The default 0.001.
    "filter" Specifies the "filter" for computing the irradiance from photons. When evaluating photon contributions, the incoming radiance is divided by the area that the photons cover (to determine the flux). The area can be computed in three different fashions:
    1. sphere - The minimum bounding sphere of all photons will be used to estimate the area. This estimator will result in soft "blobby" looking photon evaluation. It can be inaccurate near edges of primitives.
    2. convex - The convex hull of all photons is used to estimate the area. This estimator will result in slightly "sharper" edges in the photon evaluation, and can be more accurate near edges of primitives. However, since there are sharper edges, this estimator can produce very noisy evaluations.
    3. direct - When evaluating direct illumination, the projected area of each photon is used independently of all other photons. This method causes very little blending and should only be used when evaluting direct illumination from photon maps.
    The default is "sphere".
    Example: Cf = photonmap(map, P, normalize(frontface(N, I)), "nphotons", 100, "type", "diffuse", "error", 0.05, "filter", "convex);

  • float texture3d(string filename, channel; vector P, ...);
    vector texture3d(string filename, channel; vector P, ...);
    vector4 texture3d(string filename, channel; vector P, ...);

    Returns the value of the 3d image at the position specified by P. If P is outside of the bounding box of the image, the value returned will be 0. If the channel specified contains more values than the return type (i.e. a vector channel when a float return type is desired), the first component of the vector will be returned. If the channel specified contains fewer values than the return type, the missing components will be filled with the last valid channel.

    Texture files will be searched for in the path specified by the HOUDINI_TEXTURE_PATH environment variable.

    Additional arguments may be specified to control the evaluation:

    "filter" Specifies the filter for evaluation.
    "width" Specifies the filter width for evaluation.

  • vector gradient3d(string filename, channel; vector P, ...);

    Returns the gradient of a single channel texture image at the position specified by P. If P is outside of the bounding box of the image, the value returned will be 0. If the channel specified contains more values than the return type (i.e. a vector channel when a float return type is desired), the gradient of the first component of the vector will be returned. Additional arguments may be specified to control the evaluation:
    "filter" Specifies the filter for evaluation.
    "width" Specifies the filter width for evaluation.

  • int intersect3d(string filename, channel; vector &p0, p1, float density, ...);

    This function intersects a ray (with it's origin at p0 and extending to p1), against a 3d texture image. The ray will intersect the iso-surface of the texture at the density specified. If no intersection is found, then 0 is returned.

    The point p0 will be modified regardless of whether an intersection is found or not.

    Additional arguments may be specified to control the evaluation:

    "filter" Specifies the filter for evaluation.
    "width" Specifies the filter width for evaluation.

  • float integrate3d(string filename, channel; vector p0, p1, ...)
    vector integrate3d(string filename, channel; vector p0, p1, ...)
    vector4 integrate3d(string filename, channel; vector p0, p1, ...)

    This function will "integrate" the 3d image along the line specified by p0 and p1.

    Additional arguments may be specified to control the integration:

    "maxlimit" Terminate the integration if the computed sum exceeds the value specified. This option should not be used if the 3d image contains both positive and negative values as the integration my terminate prematurely.

    Caveat: The vector forms of this function don't deal with termination as precisely as the scalar form.

    "accuracy" Determine the accuracy of integration. If the accuracy is less than 1, limited filtering is done. If the accuracy is greater than 1 higher quality sampling is performed. The default value is 0. Please be cautioned that accurate filtering can be 10 times as expensive for even simple data sets.
    "iscale" Scale the value of the image by the value specified during the integration
    "filter" Specifies the filter for evaluation.
    "width" Specifies the filter width for accurate integration.

    For example: shadow_amount = integrate3d(file, "density", P, L, "maxlimit", 1, "iscale", shadow_density);
  • void texture3dBox(string filename, channel; vector &min, &max)

    This function queries the 3D texture map specified and returns the bounding box information of the file. The bounding box is returned in the vectors min and max.

  • int integrate3dClip(string filename, channel; vector &p0, p1; float limit, ...)

    The integrate3dClip function integrates along the ray described by p0 and p1 where "interesting" things start happening in a given I3D texture. It works by marching along the given ray, integrating the value of channel in the 3d texture space until the sum of the integration reaches the limit. At that point, it stops and sets the value of p0 to be the point where limit was reached and returns 1.

    If the limit is not reached during the integration, then the function will return 0 and the value of p0 will be set to the value of p1.

    Caveats:

  • If 3d textures have negative values, these will contribute to the integration.
  • When clipping against vector channels, integration is terminated when any component of the channel reaches the limit.
  • This function can be used to "skip" un-interesting parts of the 3D texture map when doing ray-marching through the map.

    Additional arguments may be specified to control the integration:

    "accuracy" Determine the accuracy of integration. If the accuracy is less than 1, limited filtering is done. If the accuracy is greater than 1 higher quality sampling is performed. The default value is 0. Please be cautioned that accurate filtering can be 10 times as expensive for even simple data sets.
    "iscale" Scale the value of the image by the value specified during the integration
    "filter" Specifies the filter for evaluation.
    "width" Specifies the filter width for accurate integration.

    For example: clipped = integrate3dClip(file, "density", eye, ps, .001); if (clipped) { // eye will be moved to the start of the "interesting" // area. raymarch(eye, ps); }


  • Point Cloud Texture Functions

    The following functions act on point cloud textures. Point cloud textures may either be specified as a tiled block file (tbf) or as a geometry file.

    A point cloud texture is simply a collection of points in space. Each point has several channels associated with the texture. For example, the texture might have a P channel to indicate the position of the point, or a temperature to indicate the temperature at the point.

    When a geometry file is used as a source for the point cloud, each point attribute is available as a read-only channel.

    It is also possible to create temporary read-write channels. These channels allow information to be stored in the point cloud and re-used by later computations. The information in these temporary channels is maintained while the texture is still referenced by any VEX function. That is, if two VEX functions reference the same texture, any temporary channels will be shared between the two functions. If the texture is flushed from the texture cache, then all temporary channels will also be flushed and information will need to be re-computed.

    Given a query point in space, the VEX functions provided allow the user to find the closest points and operate on them.

    An example of how a point cloud texture might be used is in a simple occlusion map caching shader.

    surface store_occlusion() { int handle; vector qP, qN; vector pp, nn; vector occ; float sum; qP = wo_space(P); // Transform into object space qN = wo_nspace(N); handle = pcopen(map, "P", qP, "N", qN, .5, 50); // Iterate over all of the points which don't have an "occlusion" // value stored. while (pcunshaded(handle, "occlusion")) { pcimport(handle, "P", pp); // Find the point's P value pcimport(handle, "N", nn); // Find the point's N value pp = ow_space(pp); nn = normalize(frontface(ow_nspace(nn), I)); // Compute occlusion at the map point occ = occlusion(pp, nn, "background", {1,1,1}); // Store the occlusion value in the map. pxexport(handle, "occlusion", occ); } Cf = 0; sum = 0; while (pciterate(handle)) { pcimport(handle, "occlusion", occ); Cf += occ; sum++; } Cf += 1/sum; } Another example, might be a simple image re-construction filter. This filter takes a point cloud and filters the points to re-construct an image: cop recon(string map=""; float z=0) { int handle; vector pp, clr; pp = set(X, Y, z); handle = pcopen(map, "P", pp, .1, 10); clr = pcfilter(handle, "Cd"); assign(R, G, B, clr); }
  • int pcopen(string filename, Pchannel; vector P; float radius, int maxpoints, ["prefix", channel_prefix] )
  • int pcopen(string filename, Pchannel; vector P; string Nchannel; vector N; float radius, int maxpoints, ["prefix", channel_prefix] )
    This function returns a handle to the file specified. The file may use the op: syntax to reference SOP geometry in the OP contexts. The Pchannel parameter indicates the channel in the texture which contains the position to be searched. The P parameter specifies the search query position. Only the maxpoints closest points within the sphere of the given radius will be found.

    Optionally, the Nchannel specifies a direction channel and the N parameter specifies a search direction. Only points which are pointed in the same direction (i.e. dot(N, Npoint) > 0) will be found in the search.

    The prefix parameter is used when referencing tiled block files and is used to specify the channel prefix used in the file.

    void pcclose(int &handle);
    This function closes the handle associated with a pcopen function. VEX will close handles automatically, however, it's good practice to call pcclose. When there are pcopen calls made from within a loop, VEX may consume additional memory if pcclose isn't called when the handle is no longer required.

  • float pcfarthest(int handle)
    Returns the distance to the farthest point found in the search performed by pcopen. If no points were found, the function will return a very large value (1e37)

  • float pcfilter(int handle; string channel)
    vector pcfilter(int handle; string channel)
    vector4 pcfilter(int handle; string channel)
    matrix3 pcfilter(int handle; string channel)
    matrix pcfilter(int handle; string channel)
    Filters the points found using a simple reconstruction filter. This function is roughly equivalent to: float pcfilter(int handle; string channel) { float sum, w, d; float value, result = 0; while (pciterate(handle)) { pcimport(handle, "point.distance", d); pcimport(handle, channel, value); w = 1 - smooth(0, radius, d); sum += w; result += w * value; } result /= sum; return result; }

  • int pciterate(int handle)
    This function can be used to iterate over all the points which were found in the pcopen query. The function returns 1 while there are points left in the iteration loop, or 0 when there are no further points.

    WARNINGS:

  • It is not possible to nest pcunshaded or pciterate loops for the same handle. That is, for a single pcopen call, only one pcunshaded or pciterate loop may be entered.
  • Computations involving derivatives inside pcunshaded() loops may have slightly different results. If derivatives are required for variables which aren't set by pcimport it may be better to pre-compute the derivatives before the pcunshaded loop is entered.
  • int pcunshaded(int handle; string channel)
    This function can be used to iterate over all of the points of a read-write channel which haven't had any data written to the channel yet. The function works just like the pciterate function in that 1 is returned while there are still points left unshaded.

    WARNINGS:

  • This function will not work correctly when used in multi-threaded OPs.
  • It is not possible to nest pcunshaded or pciterate loops for the same handle. That is, for a single pcopen call, only one pcunshaded or pciterate loop may be entered.
  • Computations involving derivatives inside pcunshaded() loops may have slightly different results. If derivatives are required for variables which aren't set by pcimport it may be better to pre-compute the derivatives before the pcunshaded loop is entered.
  • int pcimport(int handle; string channel; int &value)
    int pcimport(int handle; string channel; float &value)
    int pcimport(int handle; string channel; vector &value)
    int pcimport(int handle; string channel; vector4 &value)
    int pcimport(int handle; string channel; matrix3 &value)
    int pcimport(int handle; string channel; matrix &value)
    Inside either a pciterate or a pcunshaded loop, these functions can be used to import channels of the texture. The function will return 1 if the import succeeded or 0 if the import failed (this is usually due to a missing channel in the texture).

    There are two special channels which can be imported

  • point.number The number of the point being processed
  • point.distance The distance of the point being processed from the query point.
  • int pcexport(int handle; string channel; int value)
    int pcexport(int handle; string channel; float value)
    int pcexport(int handle; string channel; vector value)
    int pcexport(int handle; string channel; vector4 value)
    int pcexport(int handle; string channel; matrix3 value)
    int pcexport(int handle; string channel; matrix value)
    Inside either a pciterate or a pcunshaded loop, these functions can be used to export data into a read-write channel of the texture. The function will return 1 if the export succeeded or 0 if the export failed. The export will fail if the channel is not a read-write channel.


  • Geometry Functions in VEX

    The following functions act on the geometry stored within (filename). Allowable file formats are either geo or bgeo. The geometry specified by the filename is cached in Houdini/Mantra. The geocache command in Houdini can be used to control the caching of the geometry.
  • int getbounds( string filename; vector &min, &max )
    Returns the bounding box of the geometry specified by the filename. The point corresponding to the minimum corner of the bounding box will be returned in min, while the maximum will be in max. The function returns 1 if successful, or 0 if it wasn't possible to load the geometry.

  • int npoints( string filename )
    Returns the number of points for all primitives in the geometry file

  • int nprimitives( string filename )
    Returns the number of primitives in the geometry file

  • int intersect( string filename; vector orig, dir, &p; float &u, &v)
    This function computes the intersection of the specified ray with the geometry. The primitive number is returned or in the result of an error, has a value of -1. The world position of the intersection location is stored in (p). The corresponding parametric location of the intersection is stored in (u),(v). In the case of multiple intersections, the intersection closest to the ray origin is used.

    NOTE: When intersections are performed against metaball geometry, it is impossible to determine the primitive number of the metaball which was hit. In this case, the function returns the number of primitives in the intersection geometry.

  • float metaweight( string filename; vector p)
    Returns the metaweight of the geometry at position (p).

  • int metamarch(int &index; string filename; vector &p0, &p1; float displace_bound)
    This function will take the ray defined by p0 and p1 and partition the ray into zero or more sub-intervals. Each interval will intersect a cluster of metaballs from the file filename. The interval may not actually intersect any metaballs, but will provide fairly tight bounds on the cluster. This allows a ray-marching algorithm to "skip" uninteresting areas and only focus on marching through areas where metaballs might be found.

    The first time the function is called, the index parameter should be set to -1 and the p0 and p1 variables should be set to the end-points of the ray. If an interval was found, the function will return 1 and the p0 and p1 variables will be set to the end-points of the interval. Otherwise the function will return 0 and the p0/p1 variables will be unchanged.

    On subsequent calls to the function, the value of index will be modified by the function and any additional interesting intervals will be returned. Thus, the function can be used to ray-march through just areas of interest, skipping the dead space.

    int index; vector p0, p1; // Initialize input values index = -1; p0 = Eye; p1 = P; result = 0; while (metamarch(index, metaball_file, p0, p1, displace_bound)) { result += ray_march(metaball_file, p0, p1); }
  • int metastart(string filename; vector p)
    int metanext(int handle)

    int metaimport(int handle; string attrib; vector P; float &value)
    int metaimport(int handle; string attrib; vector P; vector &value)
    int metaimport(int handle; string attrib; vector P; vector4 &value)
    int metaimport(int handle; string attrib; vector P; matrix3 &value)
    int metaimport(int handle; string attrib; vector P; matrix &value)


    These functions allow querying of metaball geometry on a per-metaball basis. The semantics are that metastart will open a geometry file and return a "handle" to the geometry. The handle contains a list of all the metaballs of interest at the position specified in the metastart() function. The metanext function will move the handle to the next metaball for evaluation. The metaimport function provides a mechanism to query attributes of the metaball. There are currently three "special" attributes which can be queried:
    Name Meaning Data Type
    "meta:density" The density of the current metaball float
    "meta:prim" The primitive number of the current metaball float
    "meta:transform" The transform associated with the current metaball. Applying the inverse of this transform will transform a point into the "space" of the metaball. matrix
    For example, the
    metaweight function can be expressed in the following way: float metaweight(string file; vector P) { int handle; float density, tmp; density = 0; handle = metastart(file, P); while (metanext(handle)) { if (metaimport(handle, "meta:density", P, tmp)) density += tmp; } return density; } Note: The attributes evaluated are un-premultiplied by the weight of the metaball at the position and must be multipled for blending. For example, to evaluate a vector attribute (say color) on metaballs, the following function could be used: vector meta_attribute(string file, attrib_name; vector P) { int handle; vector result, tmp; float density; handle = metastart(file, P); result = 0; while (metanext(handle)) { if (metaimport(handle, "meta:density", P, density)) { if (metaimport(handle, attrib_name, P, tmp)) result += density * tmp; } } return result; } Note: In the image3d context, there is a default metaball geometry (specified by the -g option on the command line to the i3dgen program). If the filename is an empty string, the default geometry will be used.

  • vector prim_normal( string filename; int prim_number;float u, v)
    Returns the normal of the primitive (prim_number) at parametric location (u), (v).

  • int prim_attribute(string filename;int &adata; string att; int pn; float u, v)
    int prim_attribute(string filename;float &adata; string att; int pn; float u, v)
    int prim_attribute(string filename;vector &adata; string att; int pn; float u, v)
    int prim_attribute(string filename;vector4 &adata; string att; int pn; float u, v)
    int prim_attribute(string filename;matrix3 &adata; string att; int pn; float u, v)
    int prim_attribute(string filename;matrix &adata; string att; int pn; float u, v)
    Evaluates the attribute string (att) for primitive (pn) at the parametric location (u), (v). The result is stored in (adata), which can be one of several different forms. In either case, if the attribute data is of a smaller size than (adata) an error of 0 is returned. For example if attribute Cd is a vector, (adata) cannot be a matrix or any another structure which can store more than 3 values. prim_attribute returns 1 upon successful completion.


  • Transformation Functions in VEX

    The transformation functions are typically only used in the context of Rendering. When rendering, all variables are defined in "camera" space. This means that all objects are transformed so that the camera is at the origin pointing down the z-axis. Often, it is useful to get the variable in a different space. VEX supports three spaces for each rendering context: "world", "object" and "texture".

    In the SOP and POP context, all variables are in "object" space to begin with. Transforming the variables into "world" space will apply the transform of the object containing the SOP to the variables.

    There are a set of VEX functions to transform positions, direction vectors and normals into other spaces. The techniques for transforming each type of vector are subtly different, so it is important to use the correct transformation (depending on what the entity represents).

  • vector4 ow_space( vector4 )
    vector ow_space( vector )
    Transforms a position value from Object to World space.

  • vector4 wo_space( vector4 )
    vector wo_space( vector )
    Transforms a position value from World to Object space.

  • vector4 tw_space( vector4 )
    vector tw_space( vector )
    Transforms a position value from Texture to World space.

  • vector4 wt_space( vector4 )
    vector wt_space( vector )
    Transforms a position value from World to Texture space.


  • vector ow_nspace( vector )
    Transforms a normal vector from Object to World space.

  • vector wo_nspace( vector )
    Transforms a normal vector from World to Object space.

  • vector tw_nspace( vector )
    Transforms a normal vector from Texture to World space.

  • vector wt_nspace( vector )
    Transforms a normal vector from World to Texture space.


  • vector ow_vspace( vector )
    Transforms a direction vector from Object to World space.

  • vector wo_vspace( vector )
    Transforms a direction vector from World to Object space.

  • vector tw_vspace( vector )
    Transforms a direction vector from Texture to World space.

  • vector wt_vspace( vector )
    Transforms a direction vector from World to Texture space.

  • vector toNDC( vector )
    Transforms a position into normal device coordinates. This space is really only well defined for
    Displacement, Surface and Light contexts.

  • vector fromNDC( vector )
    Transforms a position from normal device coordinates to the coordinates in the appropriate space. NDC space is really only well defined for Displacement, Surface and Light contexts.


  • Miscellaneous Functions

  • void printf( string format, ...)
    string sprintf( string format, ...)

    Prints values to the starting console.

    The format string is a simpler version of the C printf format string. When a % symbol is found in the string, an argument will be printed out in a format specified by the characters following the % symbol. The conversion of the argument is specified by a single letter: g, f, s, d, x, c, p. It is possible to prefix the format option with an optional width specification. It is also possible to use an asterix (*) to cause the width option to be read from the next argument. If the specified field width begins with a 0, leading spaces will be replaced with leading zeros.

    The format characters supported are:

    %g, %p, %c Print an integer float, vector, vector4, matrix3, matrix or string in "general" form.
    %f Print a float, vector, vector4, matrix3 or matrix in floating point form.
    %s Print a string variable
    %d Print an integer variable in decimal
    %x Print an integer variable in hexidecimal
    %% Print a % symbol
    Currently there is no support for any special operators on output formatting (i.e. dash, dollar, dot, etc.)

    Examples:

    printf("P = %g, dot(N, P) = %g, %d = %x\n", P, dot(N, P), ptnum, ptnum); printf("RGB = {%g,%g,%g}\n", clr.r, clr.g, clr.b); printf("P = %20s\n", "20 chars"); Cf = texture(sprintf("/maps/map%d.rat", i)); Cf = texture(sprintf("/maps/map%04d.rat", i));
  • void sleep( int milliseconds)
    Will give up processor cycles for N milliseconds.

  • int isbound( string variable_name)
    This function will return 1 if the variable name given is bound to a geometry attribute. Parameters in VEX can be overridden by geometry attributes (if the attributes exist on the surface being rendered). If the geometry overrides the default attribute, this function will return 1. Otherwise it will return 0.

    Though this function is defined for all contexts, it is only useful in the Displacement, Surface, POP, and SOP contexts. No other contexts are currently able to bind geometry attributes to VEX variables.

    For example, in a POP function:

    pop mycolor(vector uv=0; string map="") { if (isbound("uv") && map != "") { // User has texture coordinates here, so create // velocity based on a texture map. v = colormap(map, uv); } else { // No texture coordinates, so use a random value v = random(id); } }


  • Copyright © 1999-2004 Side Effects Software Inc.
    477 Richmond Street West, Toronto, Ontario, Canada M5V 3E7