#include "sysi2.h"

/* these are setup in main.c */
extern struct SignalSemaphore TRBMSem;  /* To protect and share TmpRasBM */
extern struct BitMap *TmpRasBM;

/* Vanilla Gadget Background */
void DrawBack(struct RastPort *RP, 
              UBYTE TopEdgePen,
              UBYTE BottomEdgePen,
              UBYTE FillPen,
              WORD X1,
              WORD Y1,
              WORD X2,
              WORD Y2)
{
  SetAPen(RP,FillPen);
  MyRectFill(RP,X1,Y1,X2,Y2);

  SetAPen(RP,BottomEdgePen);
  Move(RP,X2,Y1);
  Draw(RP,X2,Y2);
  Draw(RP,X1,Y2);
  
  SetAPen(RP,TopEdgePen);  
  Draw(RP,X1,Y1);
  Draw(RP,X2,Y1);
}


/* This is the maximum number of points FillPoly will handle.
   increase it if nessecary                                   */
#define MAX_FILLPOLYPOINTS 20

  struct Point32
  {
    LONG X,Y;
  };


void FillPoly(struct RastPort *RP,ULONG Points, ...)
{

  struct AreaInfo ai={0},*oldai;
  __aligned UBYTE ab[5*MAX_FILLPOLYPOINTS];

  struct TmpRas tr,*oldtr;

  WORD minx,maxx,miny,maxy,sx,sy;
  LONG l,points,*pntr;
  struct Point32 *p;

  pntr  = &Points;
  points= *pntr;

  if(points>MAX_FILLPOLYPOINTS)
    return;
    
  pntr++;
  p=(struct Point32 *)pntr;
  
  minx=miny= 32000;
  maxx=maxy=-32000;

  for(l=0;l<points;l++)
  {
    minx=min(minx,p[l].X);
    miny=min(miny,p[l].Y);
    maxx=max(maxx,p[l].X);
    maxy=max(maxy,p[l].Y);
  }
  sx=maxx-minx;
  sy=maxy-miny;
  
  if( sx<100 && sy<100 )
  {
    ObtainSemaphore(&TRBMSem);
    tr.RasPtr=TmpRasBM->Planes[0];
    tr.Size=TmpRasBM->BytesPerRow * TmpRasBM->Rows;
    oldtr=RP->TmpRas;
    oldai=RP->AreaInfo;
    RP->TmpRas=&tr;
    RP->AreaInfo=&ai;
    InitArea(&ai,ab,MAX_FILLPOLYPOINTS);
    AreaMove(RP,p[0].X,p[0].Y);
    for(l=1;l<points;l++)
    {
      AreaDraw(RP,p[l].X,p[l].Y);
    }
    AreaEnd(RP);
    RP->TmpRas=oldtr;
    RP->AreaInfo=oldai;
    WaitBlit();
    ReleaseSemaphore(&TRBMSem);
  }
}

void DrawPoly(struct RastPort *RP,LONG Count, ...)
{
  LONG count,*points;
  LONG l;

  points = &Count;
  count  = *points;

  points++;

  Move(RP,*points,*(points+1));
  for(l=1;l<count;l++)
  {
    points+=2;
    Draw(RP,*points,*(points+1));
  }
}

void MyRectFill(struct RastPort *RP,
                 WORD X1, WORD Y1,
                 WORD X2, WORD Y2)
{
  if(X2>=X1 && Y2>=Y1 && X1>=0 && Y1>=0)
    RectFill(RP,X1,Y1,X2,Y2);
}
