/* renderer.C: VRML to NFF conversion renderer */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "nff/renderer.H"

#include "file.H"
#include "Material.H"
#include "Viewpoint.H"
#include "PointLight.H"
#include "SpotLight.H"

namespace nff {
  using namespace xrml;  // so we can omit the xrml:: prefix

renderer::renderer(class file* file_handle, char* progname)
{
  renderer::fh = file_handle;
  renderer::progname = progname;
}

void renderer::begin_frame(class world *world)
{
  fh->printf("# converted from %s with %s\n", world->file->url, progname ? progname : "unknown program");
}

void renderer::viewpoint(Viewpoint *vp)
{
  Vec3 eye, at, up;
  Mat4 view_orientation;
  view_orientation.rotate(Vec4(vp->orientation));
  eye = Vec3(vp->position) * xf;
  at = (Vec3(0., 0., -10) * view_orientation + eye) * xf;
  up = Vec3(0., 1., 0.) * view_orientation;
  fh->printf("v\nfrom %g %g %g\nat %g %g %g\nup %g %g %g\n",
	 eye.x, eye.y, eye.z, at.x, at.y, at.z, up.x, up.y, up.z);
}

void renderer::begin_PointLight(PointLight *light)
{
  if (!light->on)
    return;
  fh->printf("l %g %g %g %g %g %g\n",
	 light->location.x, light->location.y, light->location.z,
	 light->color.r, light->color.g, light->color.b);
}

void renderer::begin_SpotLight(SpotLight *light)
{
  if (!light->on)
    return;
  fh->printf("l %g %g %g %g %g %g\n",
	 light->location.x, light->location.y, light->location.z,
	 light->color.r, light->color.g, light->color.b);
}

void renderer::begin_Material(Material *mat)
{
  fh->printf("f %g %g %g %g %g %g %g %g\n",
	 mat->diffuseColor.r, mat->diffuseColor.g, mat->diffuseColor.b, // fill color
	 1., // diffuse reflectivity
	 (mat->specularColor.r + mat->specularColor.g + mat->specularColor.b) * 0.3333,  mat->shininess * 128.,  // specular reflectivity and exponent
	 0., 1.);  // transparency and index of refraction
}

void renderer::begin_face(int /*id*/, int nrverts)
{
  fh->printf("p %d\n", nrverts);
}

void renderer::vertex_coord(int id, const SFVec3f& vert)
{
  Vec3 v = Vec3(vert) * xf;
  fh->printf("%g %g %g\n", v.x, v.y, v.z);
}

void renderer::end_face(int, int)
{
}

}  // end nff namespace
