
#include "poly.h"

//---- POLYGON CLASS ---------------------------------------------------------//

//---- Poly

Poly::Poly()
{
  numpoints = 0;
  p = new float[POLY_MAX_POINTS][2];
}

//---- ~Poly

Poly::~Poly()
{
  delete[] p;
}

//---- begin

void Poly::begin( )
{
  numpoints = 0;
}

//---- end

void Poly::end( )
{
}

//---- addPoint

void Poly::addPoint( float x, float y )
{
  p[ numpoints ][0] = x;
  p[ numpoints ][1] = y;
  numpoints ++;
}

//---- firstPoint

void Poly::firstPoint( )
{
  pointptr = 0;
}

//---- nextPoint

bool Poly::nextPoint( float *x, float *y )
{
  if( pointptr >= numpoints ) return false;
  *x = p[ pointptr ][0];
  *y = p[ pointptr++ ][1];
  return true;
}

//---- peekPoint

bool Poly::peekPoint( float *x, float *y )
{
  if( pointptr >= numpoints ) return false;
  *x = p[ pointptr ][0];
  *y = p[ pointptr ][1];
  return true;
}

//---- getScanline

void Poly::getScanline( Scanline *sl, int y )
{
  sl->clear();

  //- Work out which edges this scanline intersects

  for( int i=0; i<numpoints; i++ )
  {
    int ii=(i+1)%numpoints;

    if( p[i][1] <= y && p[ii][1] > y )
    {
      sl->addPoint( p[i][0] + (p[ii][0]-p[i][0]) * (y-p[i][1]) / (p[ii][1]-p[i][1]) );
    }
    else if( p[ii][1] <= y && p[i][1] > y )
    {
      sl->addPoint( p[i][0] + (p[ii][0]-p[i][0]) * (y-p[i][1]) / (p[ii][1]-p[i][1]) );
    }
  }
}

//---- getVScanline

void Poly::getVScanline( Scanline *sl, int x )
{
  sl->clear();

  //- Work out which edges this scanline intersects

  for( int i=0; i<numpoints; i++ )
  {
    int ii=(i+1)%numpoints;

    if( p[i][0] <= x && p[ii][0] > x )
    {
      sl->addPoint( p[i][1] + (p[ii][1]-p[i][1]) * (x-p[i][0]) / (p[ii][0]-p[i][0]) );
    }
    else if( p[ii][0] <= x && p[i][0] > x )
    {
      sl->addPoint( p[i][1] + (p[ii][1]-p[i][1]) * (x-p[i][0]) / (p[ii][0]-p[i][0]) );
    }
  }
}

//---- render
/*
void Poly::render( Image *im, int col )
{
  int i;

  Scanline sl;

  for( i=0; i<im->h; i++ )
  {
    getScanline( &sl, i );
    im->drawScanline( i, &sl, col );
  }
}
*/

