/*------------------------------------------------------------------------
 * glassbal - solid glass sphere shader (turns everything upside-down
 *	and backwards). Also works fairly well for other "sort of spherical"
 *	objects (like teapots).
 *
 * Ka, Ks, Kd, roughness, specularcolor - the usual
 * eta - index of refraction of air/glass
 * envname - environment map file name
 *----------------------------------------------------------------------*/

#include "material.h"

surface
glassbal( float Ka=0, float Ks=.6, float roughness=.2, float Kd=0, float eta=.6,
	color specularcolor=1, string envname="" )
{
    float Kr, Kt, Ktr, Ktt;
    vector Rray, Tray, R, T;
    normal Nf;
    vector V;
    normal N2;

    /* N and I are not automatically normalized in this implementation. */
    Nf = faceforward( normalize(N), I);
    V = -normalize(I) ;

    /* find direction of refracted ray */
    fresnel(-V, Nf, eta, Kr, Kt, Rray, T);
    T = normalize(T);
    N2 = reflect(Nf, -T);
    fresnel(T, N2, 1/eta, Ktr, Ktt, R, Tray);
    Rray = transform("world", Rray);
    Tray = transform("world", Tray);

    /* calculate color */
	color Cs = C;
    C = Cs*(Ka*ambient() + Kd*diffuse(Nf)) +
   		specularcolor*Ks*specular(Nf,V,roughness);
    if (envname != "") {
	    C += Kr * Environment(envname,Rray, "", 0, 1, Kr)
		+ min(Kt*Ktt, 1) * Cs * Environment(envname,Tray, "", 0, 1, min(Kt*Ktt, 1));
    }
    C *= opacity;
}
