最近學習計算機圖形學,寫了個多邊形掃描轉換算法,貼出來分享一下;
MFC還不是太明白,主要還是使用OnDraw函數...
大家多指教...
void CPolyFillView::OnDraw(CDC* pDC)
{
CPolyFillDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
const int POINTNUM=6; //多邊形點數.
/定義結構體用於活性邊表AET和新邊表NET/
typedef struct XET
{
float x;
float dx,ymax;
XET* next;
}AET,NET;
/定義點結構體point*/
struct point
{
float x;
float y;
}polypoint[POINTNUM]={250,50,550,150,550,400,250,250,100,350,100,100};//多邊形頂點
//mypoint[POINTNUM]={100,100,200,100,200,200,100,200};//正方形
/計算最高點的y坐標(掃描到此結束)**/
int MaxY=0;
int i;
for(i=0;i<POINTNUM;i++)
if(polypoint[i].y>MaxY)
MaxY=polypoint[i].y;
/*初始化AET表/
AET *pAET=new AET;
pAET->next=NULL;
/初始化NET表*/
NET *pNET[1024];
for(i=0;i<=MaxY;i++)
{
pNET[i]=new NET;
pNET[i]->next=NULL;
}
/掃描並建立NET表*/
for(i=0;i<=MaxY;i++)
{
for(int j=0;j<POINTNUM;j++)
if(polypoint[j].y==i)
{
if(polypoint[(j-1+POINTNUM)%POINTNUM].y>polypoint[j].y)
{
NET *p=new NET;
p->x=polypoint[j].x;
p->ymax=polypoint[(j-1+POINTNUM)%POINTNUM].y;
p->dx=(polypoint[(j-1+POINTNUM)%POINTNUM].x-polypoint[j].x)/(polypoint[(j-1+POINTNUM)%POINTNUM].y-polypoint[j].y);
p->next=pNET[i]->next;
pNET[i]->next=p;
}
if(polypoint[(j+1+POINTNUM)%POINTNUM].y>polypoint[j].y)
{
NET *p=new NET;
p->x=polypoint[j].x;
p->ymax=polypoint[(j+1+POINTNUM)%POINTNUM].y;
p->dx=(polypoint[(j+1+POINTNUM)%POINTNUM].x-polypoint[j].x)/(polypoint[(j+1+POINTNUM)%POINTNUM].y-polypoint[j].y);
p->next=pNET[i]->next;
pNET[i]->next=p;
}
}
}
/建立並更新活性邊表AET/
for(i=0;i<=MaxY;i++)
{
//計算新的交點x,更新AET/
NET *p=pAET->next;
while(p)
{
p->x=p->x + p->dx;
p=p->next;
}
//更新後新AET先排序