/* PhBSphereTextureProjection.C: PhBSphereTextureProjection nodes (public source) */

#include "PhBSphereTextureProjection.H"
#include <math.h>

namespace xrml {

void PhBSphereTextureProjection::render(void)
{
  // needs to do nothing
}

Vec3 PhBSphereTextureProjection::object2surface(const Vec3& objectCoord,
						Vec3 *x,
						Vec3 *y,
						Vec3 *z)
{
  // find point on surface that is closest to the objectCoord given ( / radius)
  Vec3 p = ((Vec3)objectCoord).normalize();

  // generate (u,v) according to VRML-spec (6.43)
  // and generate axis (Z = surface-normal)
  if (x && y && z) {
    *z = p;
    if(p.y > 1-EPSILON)
      {
	*x = Vec3(0, 0, 1);
	*y = Vec3(1, 0, 0);
      }
    else if(p.y < EPSILON-1) 
      {
	*x = Vec3(0, 0, -1);
	*y = Vec3(-1, 0, 0);
      }
    else {
      *x = Vec3(p.z, 0, -p.x).normalize();
      *y = *z ^ *x;
    }
  }

  double u = .5 - atan2(-p.x, p.z) / (2 * M_PI);
  double v = acos(p.y) / M_PI;

  return Vec3(u, v, 0);
}

}  // namespace xrml
