/************************************************************************
 * displace.h - Routines for displacing
 *
 * Entropy and BMRT are:
 * (c) Copyright 2001 Exluna, Inc.  Portions (c) 1990-2000 Larry Gritz.
 * All rights reserved.
 *
 * $Revision: 1.6 $    $Date: 2001/08/08 22:47:49 $
 *
 ************************************************************************/



#ifndef DISPLACE_H
#define DISPLACE_H 1




/* Displace along N by amp units (measured in the coordinate system
 * given by space.  As a side effect, reset N to the new normal (but
 * not necessarily normalized).  Be careful to handle the case where
 * the geometry is a polymesh with smoothed normals.  
 */
normal Displace (string space; float amp)
{
    extern point P;
    extern normal N;
    vector dir = normalize(N);
    vector Nresid = dir - normalize(calculatenormal(P));
    float spacescale = length(vtransform(space, dir));
    vector Ndisp = dir * (amp / max(spacescale,1e-6));
    P += /* truedisp * */ Ndisp;
    N = Nresid + normalize (calculatenormal (P));
    return N;
}



/* Bump along N by amp units (measured in the coordinate system given
 * by space.  As a side effect, reset N to the new normal (but not
 * necessarily normalized).  Be careful to handle the case where the
 * geometry is a polymesh with smoothed normals.  This routine does not
 * actually move P, it just bump maps.  
 */
normal Bump (string space; float amp)
{
    extern point P;
    extern normal N;
    vector dir = normalize(N);
    vector Nresid = dir - normalize(calculatenormal(P));
    float spacescale = length(vtransform(space, dir));
    vector Ndisp = dir * (amp / max(spacescale,1e-6));
    N = Nresid + normalize (calculatenormal (P + Ndisp));
    return N;
}



/* Combine displacement and bump mapping, with units relative to a
 * particular space, in any direction (not necessarily the normal).
 * When truedisp != 0, this function modifies P as a side effect.
 * This function does not account for shading "N" being different
 * from the true normal, and may have artifacts on faceted geometry.
 *
 * Inputs:
 *    dir       direction in which to push the surface, assumed to
 *                 already be in "current" space and normalized.
 *    amp       amplitude of the actual displacement or bumping.
 *    space     the name of the coordinate system against which the
 *                 amplitude is measured.
 *    truedisp  when 1, truly displace; when 0, just bump.
 * Return value: the normal of the displaced and bumped surface,
 *                in "current" space, normalized.
 * 
 */
normal Displace (vector dir;  string space;
                 float amp; float truedisp;)
{
    extern point P;
    float spacescale = length(vtransform(space, dir));
    vector Ndisp = dir * (amp / max(spacescale,1e-6));
    P += truedisp * Ndisp;
    return normalize (calculatenormal (P + (1-truedisp)*Ndisp));
}



#endif /* DISPLACE_H */
