Content deleted Content added
Line 38:
==Working Code in C++==
<source lang="cpp">
//Sutherland-Holdgman Polygon Clipping
#include <iostream>
#include <vector>
#include "graphics.h"
#include "Line2d.h"
#include "Coordinates2d.h"
#include "Polygon2d.h"
class ClippingPolygon2d
{
private:
Polygon2d clippingPolygon;
Polygon2d candidatePolygon;
public:
ClippingPolygon2d(){}
void SetCandidatePolygon(Polygon2d & pol)
{
candidatePolygon = pol;
}
void SetClippingPolygon(Polygon2d & pol)
{
clippingPolygon = pol;
}
public:
std::vector<Point2d> GetClippedPoints()
{
std::vector<Point2d> polygonVertices = candidatePolygon.GetVertices();
std::vector<Point2d> clipping = clippingPolygon.GetVertices();
for (size_t i = 0; i < clipping.size(); i++)
{
Line2d clippingEdge(clipping[i], clipping[(i + 1) % clipping.size()]);
std::vector<Point2d> temp;
for (size_t j = 0; j < polygonVertices.size(); j++)
{
Point2d polygonEdgeStart = polygonVertices[j];
Point2d polygonEdgeEnd = polygonVertices[(j + 1) % polygonVertices.size()];
if (clippingEdge.onLeft(polygonEdgeStart))
{
if (clippingEdge.onLeft(polygonEdgeEnd))
{
temp.push_back(polygonEdgeEnd);
}
else //Right
{
temp.push_back(clippingEdge.GetIntersectionExtended(Line2d(polygonEdgeStart, polygonEdgeEnd)));
}
}
else //Right
{
if (clippingEdge.onLeft(polygonEdgeEnd))
{
temp.push_back(clippingEdge.GetIntersectionExtended(Line2d(polygonEdgeStart, polygonEdgeEnd)));
temp.push_back(polygonEdgeEnd);
}
else //Right
{
// nothing to do: outside of the window
}
}
}
polygonVertices = temp;
}
return polygonVertices;
}
};
int main()
{
//////////////////////// Initialize ///////////////////////
Coordinates2d::ShowWindow("Sutherland-Hodgman Line Clipping");
///////////////////////////////////////////////////////////////
Polygon2d clippingPolygon;
clippingPolygon.Add(20,20);
clippingPolygon.Add(200,20);
clippingPolygon.Add(200,160);
clippingPolygon.Add(20,160);
Polygon2d candidatePolygon;
candidatePolygon.Add(Point2d(-20, 80));
candidatePolygon.Add(Point2d(10, 80));
candidatePolygon.Add(Point2d(110, 180));
candidatePolygon.Add(Point2d(210, 80));
candidatePolygon.Add(Point2d(240, 80));
candidatePolygon.Add(Point2d(110, 210));
ClippingPolygon2d clip;
clip.SetClippingPolygon(clippingPolygon);
clip.SetCandidatePolygon(candidatePolygon);
std::vector<Point2d> clippedVerticesList = clip.GetClippedPoints();
Coordinates2d::Draw(candidatePolygon, Red);
Coordinates2d::Draw(clippingPolygon, Magenta);
Polygon2d poly2(clippedVerticesList);
Coordinates2d::Draw(poly2, Yellow);
/////////////////////// Finalize /////////////////////////
Coordinates2d::Wait();
return 0;
///////////////////////////////////////////////////////////////
}
</source>
|