using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
CPP_to_C_Sharp
{
class
Program
{
static
List<
int
> codeList =
new
List<
int
> { 5, 6, 7, 4, -1, 0, 3, 2, 1 };
static
int
getChainCode(
int
x1,
int
y1,
int
x2,
int
y2)
{
int
dx = x2 - x1;
int
dy = y2 - y1;
int
hashKey = 3 * dy + dx + 4;
return
codeList[hashKey];
}
static
List<
int
> generateChainCode(
List<List<
int
>> ListOfPoints)
{
List<
int
> chainCode =
new
List<
int
>();
for
(
int
i = 0; i < ListOfPoints.Count - 1; i++)
{
List<
int
> a = ListOfPoints[i];
List<
int
> b = ListOfPoints[i + 1];
chainCode.Add(getChainCode(a[0], a[1], b[0], b[1]));
}
return
chainCode;
}
static
List<List<
int
>> Bresenham2D(
int
x1,
int
y1,
int
x2,
int
y2)
{
List<List<
int
>> ListOfPoints =
new
List<List<
int
>>();
ListOfPoints.Add(
new
List<
int
> { x1, y1 });
int
xdif = x2 - x1;
int
ydif = y2 - y1;
int
dx = Math.Abs(xdif);
int
dy = Math.Abs(ydif);
int
xs;
if
(xdif > 0)
{
xs = 1;
}
else
{
xs = -1;
}
int
ys;
if
(ydif > 0)
{
ys = 1;
}
else
{
ys = -1;
}
if
(dx > dy)
{
int
p = 2 * dy - dx;
while
(x1 != x2)
{
x1 += xs;
if
(p >= 0)
{
y1 += ys;
p -= 2 * dx;
}
p += 2 * dy;
ListOfPoints.Add(
new
List<
int
> { x1, y1 });
}
}
else
{
int
p = 2 * dx - dy;
while
(y1 != y2)
{
y1 += ys;
if
(p >= 0)
{
x1 += xs;
p -= 2 * dy;
}
p += 2 * dx;
ListOfPoints.Add(
new
List<
int
> { x1, y1 });
}
}
return
ListOfPoints;
}
static
void
DriverFunction()
{
int
x1 = -9;
int
y1 = -3;
int
x2 = 10;
int
y2 = 1;
List<List<
int
>> ListOfPoints
= Bresenham2D(x1, y1, x2, y2);
List<
int
> chainCode
= generateChainCode(ListOfPoints);
string
chainCodeString =
""
;
for
(
int
i = 0; i < chainCode.Count; i++)
{
chainCodeString += chainCode[i].ToString();
}
Console.WriteLine(
"Chain code for the straight line from ("
+ x1 +
","
+ y1 +
") to ("
+ x2 +
","
+ y2 +
") is "
+ chainCodeString);
}
static
void
Main(
string
[] args)
{
DriverFunction();
}
}
}