Line clipping: Difference between revisions

Content deleted Content added
Fixed the code to appear more uniform - ignore wiki formatting in the code
Line 102:
end; {CohenSutherlandLineClipAndDraw}
</nowiki></pre>
 
C# implementation for Cohen-Sutherland algorithm
<pre><nowiki>
internal sealed class CohenSutherlandClipping : IClippingAlgorithm
{
private Vector2 _clipMin, _clipMax;
 
public IEnumerable<Vector2> GetBoundingPolygon()
{
yield return _clipMin;
yield return new Vector2(_clipMax.X, _clipMin.Y);
yield return _clipMax;
yield return new Vector2(_clipMin.X, _clipMax.Y);
}
 
public void SetBoundingRectangle(Vector2 start, Vector2 end)
{
_clipMin = start;
_clipMax = end;
}
 
public void SetBoundingPolygon(IEnumerable<Vector2> points)
{
throw new NotSupportedException("see Capabilities =)");
}
 
private int getPointCode(Vector2 point)
{
int result = 0;
 
if (point.X < _clipMin.X) ++result;
else if (point.X > _clipMax.X) result |= 2;
 
if (point.Y > _clipMax.Y) result |= 4;
else if (point.Y < _clipMin.Y) result |= 8;
 
return result;
}
 
public bool ClipLine(ref Line line)
{
Vector2 P = line.End - line.Start;
int startCode = getPointCode(line.Start);
int endCode = getPointCode(line.End);
float dxdy = 0, dydx = 0;
 
if (P.X != 0) dydx = P.Y / P.X;
if (P.Y != 0) dxdy = P.X / P.Y;
 
for (int stage = 0; stage < 4; stage++)
{
if ((startCode | endCode) == 0) return true;
else if ((startCode & endCode) != 0) return false;
 
if (startCode == 0)
{
int buf1 = startCode; startCode = endCode; endCode = buf1;
Vector2 buf2 = line.Start; line.Start = line.End; line.End = buf2;
}
 
if ((startCode & 1) == 1)
{
line.Start.Y += dydx * (_clipMin.X - line.Start.X);
line.Start.X = _clipMin.X;
}
else if ((startCode & 2) == 2)
{
line.Start.Y = line.Start.Y + dydx * (_clipMax.X - line.Start.X);
line.Start.X = _clipMax.X;
}
else if ((startCode & 4) == 4)
{
line.Start.X = line.Start.X + dxdy * (_clipMax.Y - line.Start.Y);
line.Start.Y = _clipMax.Y;
}
else if ((startCode & 8) == 8)
{
line.Start.X = line.Start.X + dxdy * (_clipMin.Y - line.Start.Y);
line.Start.Y = _clipMin.Y;
}
 
startCode = getPointCode(line.Start);
}
 
return true;
}
 
public ClippingCapabilities Capablities { get { return ClippingCapabilities.RectangleWindow; } }
 
public override string ToString()
{
return "Cohen-Sutherland algorithm";
}
}
</nowiki></pre>
 
== Liang-Barsky ==