/////////////////////////////////////////////////////////////////////////////
// material.h - a variety of materials, local illumination functions,
//              and other utilities that can be used to construct shaders
//              that have light-reflecting properties that aren't standard
//              plastic.
//
// Much of this is adapted from Apodaca & Gritz, "Advanced RenderMan",
// Morgan-Kaufmann 1999.
//
/////////////////////////////////////////////////////////////////////////////
// Copyright 2004 NVIDIA Corporation.  All Rights Reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// 
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// (This is the Modified BSD License)
/////////////////////////////////////////////////////////////////////////////



// Compute the color of the surface using a simple plastic-like BRDF.
// Typical values are Ka=1, Kd=0.8, Ks=0.5, roughness=0.1.
//
color MaterialPlastic (normal Nf, color basecolor,
                       float Ka, float Kd, float Ks, float roughness)
{
    return basecolor * (Ka*ambient() + Kd*diffuse(Nf))
           + Ks*specular(Nf,-normalize(I),roughness);
}



// Compute the color of the surface using a simple Lambertian BRDF.
color MaterialMatte (normal Nf, color basecolor, float Ka, float Kd)
{
    return basecolor * (Ka*ambient() + Kd*diffuse(Nf));
}



// Compute the color of the surface using a simple metal-like BRDF.  To
// give a metallic appearance, both diffuse and specular components are 
// scaled by the color of the metal.  It is recommended that Kd < 0.1,
// Ks > 0.5, and roughness > 0.15 to give a believable metallic appearance.
color MaterialRoughMetal (normal Nf, color basecolor,
                          float Ka, float Kd, float Ks, float roughness)
{
    return basecolor * (Ka*ambient() + Kd*diffuse(Nf) +
                        Ks*specular(Nf,-normalize(I),roughness));
}


// Compute the color of the surface using a simple thin plastic-like BRDF.
// We call it _thin_ because it includes a transmisison component to allow 
// light from the _back_ of the surface to affect the appearance.  Typical
// values are Ka=1, Kd=0.8, Kt = 0.2, Ks=0.5, roughness=0.1.
color MaterialThinPlastic (normal Nf, vector V, color basecolor, 
                           float Ka, float Kd, float Kt,
                           float Ks, float roughness)
{
    return basecolor * (Ka*ambient() + Kd*diffuse(Nf) + Kt*diffuse(-Nf))
           + Ks*specular(Nf,V,roughness);
}




// Oren and Nayar's generalization of Lambert's reflection model.
// The roughness parameter gives the standard deviation of angle
// orientations of the presumed surface grooves.  When roughness=0,
// the model is identical to Lambertian reflection.
color
LocIllumOrenNayar (normal N, vector V, float roughness)
{
    // Surface roughness coefficients for Oren/Nayar's formula
    float sigma2 = roughness * roughness;
    float A = 1 - 0.5 * sigma2 / (sigma2 + 0.33);
    float B = 0.45 * sigma2 / (sigma2 + 0.09);
    // Useful precomputed quantities
    float  theta_r = acos (dot (V, N));        // Angle between V and N
    vector V_perp_N = normalize(V-N*dot(V,N)); // Part of V perpendicular to N

    // Accumulate incoming radiance from lights in C
    color C = 0;
    lights (P, N, M_PI_2) {
	float nondiff = 0;
	getmessage ("light", "__nondiffuse", nondiff);
	if (nondiff < 1) {
	    vector LN = normalize(L);
	    float cos_theta_i = dot(LN, N);
	    float cos_phi_diff = dot (V_perp_N, normalize(LN - N*cos_theta_i));
	    float theta_i = acos (cos_theta_i);
	    float alpha = max (theta_i, theta_r);
	    float beta = min (theta_i, theta_r);
	    C += (1-nondiff) * Cl * cos_theta_i * 
		(A + B * max(0,cos_phi_diff) * sin(alpha) * tan(beta));
	}
    }
    return C;
}



// Compute the color of the surface of a very rough, totally nonspecular
// material like clay.  Use an Oren/Nayar BRDF for the diffuse term.
color MaterialClay (normal Nf, color basecolor,
                    float Ka, float Kd, float roughness)
{
    return basecolor * (Ka*ambient() + 
			Kd*LocIllumOrenNayar(Nf,-normalize(I),roughness));
}



// Specular component for velvet, based on work by Steve Westin.
// Inputs: 
//    N - normalized surface orientation
//    V - view direction (i.e., -normalize(I))
//    sheen - color of highlight (default: (0.25, 0.25, 0.25))
//    backscatter - controls the retroreflective lobe (default: 0.1)
//    edginess - how broad the horizon scattering is (default: 10)
//    roughness - how broad the retroreflective lobe is (default: 0.1)
color LocIllumVelvet (vector N, vector V, color sheen, 
                      float backscatter, float edginess, float roughness)
{
    color C = 0;
    lights (P, N, M_PI_2) {
        vector Ln = normalize (L);
        // Retroreflective lobe
        float retro = pow (max (dot(Ln,V), 0), 1/roughness) * backscatter;
        // Horizon scattering
        float cosine = max (dot(N,V), 0);
        float sine = sqrt (1 - cosine*cosine);
        float horizon = pow (sine, edginess) * dot(Ln,N);

        C += (retro + horizon) * Cl * sheen;
    }
    return C;
}




int istexture(string envname)
{
	int status;
	gettextureinfo (envname, "exists", status);
	return status;
}




// Environment() - A does-all replacement for environment() lookups 
// (including parallax, if desired), flat reflection maps, and
// ray tracing.
//
// Inputs are:
//    envname - filename of environment map, or name of geometry set
//              for ray tracing
//    R - direction of traced ray
//    envspace - name of space environment map was made in (ignored for
//              ray tracing)
//    blur - amount of additional blur to add to environment lookup
//    samples - for ray tracing, how many ray samples to use
//    Kr - a hint to environment(), but doesn't actually multiply the results
//
// Outputs are:
//    return value - the color of incoming environment light
//
// If flat reflection mapping is desired, envspace must be "NDC" and
// envname must be an ordinary texture map that's an image made with
// the camera on "the other side" of the flat mirror.
//
// Warning - the environment call takes derivatives, causing trouble
// if called inside a loop or varying conditional!  Be cautious.
//
color Environment ( string envname, vector R,
                    string envspace,
                    float blur, float samples, float Kr)
{
    color C;
    if (envname && Kr > 0) {
        if (envspace == "NDC") {
            // envspace "NDC" signifies a flat reflection map
            point Pndc = transform ("NDC", P);
            C = texture (envname, Pndc[0], Pndc[1], "blur", blur);
        } else {
			if (istexture (envname)) {
			    // envname is a filename
                vector D = transform (envspace, R);
                C = environment (envname, R, "blur", blur);
            } else {
				// envname is a geometry set
                C = trace (P, R, "blur", blur, "samples", (int)samples,
                             "traceset", envname);
			}
        }
    }
    else C = 0;
    return C;
}



// Another Environment that takes a background map name that's used to
// substitute an env map "behind" missed rays (or alpha=0 maps).  Also,
// this version of Environment returns the hit distance in hitdist.
color Environment ( string envname, vector R,
                    string envspace,
                    float blur, float samples, float Kr,
                    string bgenvname, string bgenvspace,
                    float bgblur, output float hitdist)
{
    color C;
    float alpha = 1;
    hitdist = 1e30;
    if (envname && Kr > 0) {
        if (envspace == "NDC") {
            // envspace "NDC" signifies a flat reflection map
            point Pndc = transform ("NDC", P);
            C = texture (envname, Pndc[0], Pndc[1], "blur", blur);
        } else {
			if (istexture (envname)) {
			    // envname is a filename
                vector D = transform (envspace, R);
                C = environment (envname, D, "blur", blur);
            } else {
				// envname is a geometry set
                C = trace (P, R, "blur", blur, "samples", (int)samples,
                             "traceset", envname);
			}
        }
    }
    else C = 0;
    if (bgenvname && alpha < 1 && Kr > 0) {
        C += (1-alpha) * Environment (bgenvname, R, bgenvspace,
                                      bgblur, samples, Kr*(1-alpha));
    }
    return C;
}




// Compute the color of the surface using a simple metal-like BRDF.  To
// give a metallic appearance, both diffuse and specular components are 
// scaled by the color of the metal.  It is recommended that Kd < 0.1,
// Ks > 0.5, and roughness > 0.15 to give a believable metallic appearance.
// If twosided is nonzero, both sides are shiny, but if you know that
// the object has N facing outward, twosided==0 is a good optimization
// (especially when using ray tracing).
color MaterialShinyMetal (normal Nf, color basecolor,
                          float Ka, float Kd, float Ks, float roughness,
                          float Kr, float blur,
			              float twosided,
                          string envname, string envspace,
                          float samples)
{
    vector IN = normalize(I);
    vector R = reflect (IN, Nf);
    // kr is reflectivity, but set it to zero if we're looking at the
    // back of a surface that's "silvered" on only one side
    float kr = (twosided == 0 && dot(N,I) > 0) ? 0 : Kr;
    return basecolor * (Ka*ambient() + Kd*diffuse(Nf) +
                        Ks*specular(Nf,-IN,roughness) + 
			kr*Environment (envname, R, envspace,
                                        blur, samples, kr));
}



// Compute the color of the surface using a simple plastic-like BRDF, with
// fresnel-attenuated coherent reflections.
// If twosided is nonzero, both sides are shiny, but if you know that
// the object has N facing outward, twosided==0 is a good optimization
// (especially when using the ray server).
//
color
MaterialShinyPlastic (normal Nf, color basecolor,
                      float Ka, float Kd, float Ks,
                      float roughness, float Kr, float blur, float ior,
                      float twosided, 
                      string envname, string envspace,
                      float samples)
{
    vector IN = normalize(I);
    vector V = -IN;
    float fkr, fkt;
    vector R, T;
    fresnel (IN, Nf, 1/ior, fkr, fkt, R, T);
    fkt = 1-fkr;
    if (twosided == 0 && dot(N,I) > 0)
	fkr = 0;
    fkr *= Kr;
    return  fkt * basecolor * (Ka*ambient() + Kd*diffuse(Nf))
          + Ks * specular(Nf,V,roughness)
	  + fkr * Environment(envname, R, envspace, blur, samples, fkr);
}




// Greg Ward Larson's anisotropic specular local illumination model.
// The derivation and formulae can be found in:  Ward, Gregory J.
// "Measuring and Modeling Anisotropic Reflection," ACM Computer 
// Graphics 26(2) (Proceedings of Siggraph '92), pp. 265-272, July, 1992.
// Notice that compared to the paper, the implementation below appears
// to be missing a factor of 1/pi, and to have an extra L.N term.
// This is not an error!  It is because the paper's formula is for the
// BRDF, which is only part of the kernel of the light integral, whereas
// shaders must compute the result of the integral.
//
// Inputs:
//   N - unit surface normal
//   V - unit viewing direction (from P toward the camera)
//   xdir - a unit tangent of the surface defining the reference
//          direction for the anisotropy.
//   xroughness - the apparent roughness of the surface in xdir.
//   yroughness - the roughness for the direction of the surface 
//          tangent perpendicular to xdir.
color
LocIllumWardAnisotropic (normal N, vector V,
                         vector xdir, float xroughness, float yroughness)
{
    float sqr (float x) { return x*x; }

    float cos_theta_r = clamp (dot(N,V), 0.0001, 1);
    vector X = xdir / xroughness;
    vector Y = cross(N,xdir) / yroughness;

    color C = 0;
    lights (P, N, M_PI_2) {
	float nonspec = 0;
	getmessage ("light", "__nonspecular", nonspec);
	if (nonspec < 1) {
	    vector LN = normalize (L);
	    float cos_theta_i = dot (LN,N);
	    if (cos_theta_i > 0.0) {
		vector H = normalize (V + LN);
		float rho = exp (-2 * (sqr(dot(X,H)) +
                                       sqr(dot(Y,H))) / (1 + dot(H,N)))
		    / sqrt (cos_theta_i * cos_theta_r);
		C += Cl * ((1-nonspec) * cos_theta_i * rho);
	    }
	}
    }
    return C / (4 * xroughness * yroughness);
}



// Compute the color of the surface using an anisotropic BRDF.  To
// give a metallic appearance, both diffuse and specular components are 
// scaled by the color of the metal.  It is recommended that Kd < 0.1,
// Ks > 0.5, and roughness > 0.15 to give a believable metallic appearance.
//
color MaterialBrushedMetal (normal Nf, color basecolor,
                            float Ka, float Kd, float Ks,
                            vector xdir, float uroughness, float vroughness)
{
    color spec = LocIllumWardAnisotropic (Nf, -normalize(I), 
					  xdir, uroughness, vroughness);
    return basecolor * (Ka*ambient() + Kd*diffuse(Nf) + Ks*spec);
}



// LocIllumGlossy - a possible replacement for specular(), with a
// more uniformly bright core and a sharper falloff.  It's a nice
// specular function to use for something made of glass or liquid.
// Inputs:
//  roughness - related to the size of the highlight, larger is bigger
//  sharpness - 1 is infinitely sharp, 0 is very dull
color LocIllumGlossy ( normal N, vector V,
                       float roughness, float sharpness )
{
    color C = 0;
    float w = .18 * (1-sharpness);
    lights (P, N, M_PI_2) {
	float nonspec = 0;
	getmessage ("light", "__nonspecular", nonspec);
	if (nonspec < 1) {
	    vector H = normalize(normalize(L)+V);
	    C += Cl * ((1-nonspec) * 
		       smoothstep (.72-w, .72+w,
				   pow(max(0,dot(N,H)), 1/roughness)));
	}
    }
    return C;
}




// Compute the color of a glass-like surface with coherent reflections
// and refractions.
color MaterialGlass (normal Nf, color basecolor,
                     float Ka, float Kd, float Ks, float roughness,
                     float Kr, float reflblur, float reflsamples,
		     float Kt, float refrblur, float eta,
		     color transmitcolor,
		     float refrsamples, float twosided,
                     string envname, string envspace,
                     string bgenvname, string bgenvspace,
                     color extinction)
{
    color exp (color x) { return color (exp(x[0]), exp(x[1]), exp(x[2])); }

    vector IN = normalize (I);

    float ka = Ka, kd = Kd, ks = Ks;
    /* Compute the reflection & refraction directions and amounts */
    vector Rfldir, Rfrdir;   /* Smooth reflection/refraction directions */
    float kr, kt;
    fresnel (IN, Nf, (dot(I,N) < 0) ? 1.0/eta : eta, kr, kt, Rfldir, Rfrdir);
    kt = 1-kr;   /* Physically incorrect, but portable */
    kr *= Kr;
    kt *= Kt;

    // inside is true if we're already on the inside of the object, false
    // if we're on the outside of the object looking in.
    float inside = (dot(N,I) > 0);

    /* Speedup -- at deep ray levels, reflection is unimportant */
    float reflsamps = reflsamples;
    float refrsamps = refrsamples;
	if (raylevel() > 0) {
	if (raylevel() > 1 && kt > 2*kr)
	    kr = 0;
	reflsamps = min(1, reflsamps);
	refrsamps = min(1, refrsamps);
    }
	// Speedup for scanline -- don't shade back sides, but you HAVE to be sure
    // that normals correctly face outward.
    else if (inside && twosided == 0 && raylevel() == 0) {
	kr = kt = 0;
    }


    // Back sides shouldn't have diffuse or specular -- it's a waste
    // to run the lights
    if (twosided == 0 && inside) {
        ka = kd = ks = 0;
    }

    /* Calculate the reflection & refraction color */
    float refl_hitdist, refr_hitdist;
    color Crefl = kr * Environment (envname, normalize(Rfldir), envspace,
                                    reflblur, reflsamps, kr,
                                    bgenvname, bgenvspace, reflblur,
                                    refl_hitdist);
    color Crefr = kt * Environment (envname, normalize(Rfrdir), envspace,
                                    refrblur, refrsamps, kt,
                                    bgenvname, bgenvspace, refrblur,
                                    refr_hitdist);

    // Handle extinction
    if (extinction) {
        if (inside) {
            if (refl_hitdist < 1e30 && kr) {
                Crefl *= exp(-refl_hitdist*extinction);
            }
        } else {
            if (refr_hitdist < 1e30 && kt) {
                Crefr *= exp(-refr_hitdist*extinction);
            }
        }
    }

    color C = 0;
    if (ka > 0)
        C += basecolor * ka * ambient();
    if (kd > 0)
        C += basecolor * kd * diffuse(Nf);
    if (ks > 0)
        C += ks * specular(Nf,-IN,roughness);
    return C + Crefl + transmitcolor * Crefr;
}



// Simplified glass that doesn't have background refraction separately,
// nor extinction.  Provided mainly for back compatibility for shaders
// written before the new arguments were added to the above MaterialGlass.
color MaterialGlass (normal Nf, color basecolor,
                     float Ka, float Kd, float Ks, float roughness,
                     float Kr, float reflblur, float reflsamples,
		     float Kt, float refrblur, float eta,
		     color transmitcolor,
		     float refrsamples, float twosided,
                     string envname, string envspace)
{
    return MaterialGlass (Nf, basecolor, Ka, Kd, Ks, roughness,
                          Kr, reflblur, reflsamples, Kt, refrblur, eta,
                          transmitcolor, refrsamples, twosided, 
                          envname, envspace, "", "", color(0,0,0));
}



// MaterialGlass with a color for eta to indicate dispersive refraction
// (it's not really a color, just one float per color channel).
color MaterialGlass (normal Nf, color basecolor,
                     float Ka, float Kd, float Ks, float roughness,
                     float Kr, float reflblur, float reflsamples,
		     float Kt, float refrblur, color dispersive_eta,
		     color transmitcolor,
		     float refrsamples, float twosided,
                     string envname, string envspace,
                     string bgenvname, string bgenvspace,
                     color extinction)
{
    color C = 0;
    for (int c = 0;  c < 3;  ++c) {
        float middle = (c == 1);  // True only for middle value
        color spect = color (c==0, c==1, c==2);
        C += MaterialGlass ( Nf, basecolor,
                             Ka*middle, Kd*middle, Ks*middle, roughness,
                             Kr*middle, reflblur, reflsamples,
                             Kt, refrblur, dispersive_eta[c],
                             spect*transmitcolor,
                             refrsamples, twosided,
                             envname, envspace,
                             bgenvname, bgenvspace,
                             extinction);
    }
    return C;
}
