[英]C++ 2D Graphics: Flat Bottom Triangle Rasterization
我正在尝试在 Windows 控制台上构建一个简单的 2D 应用程序,使用 C++ 来显示各种图元,所以我从最基本的一个开始:三角形。 我可以正确显示三角形的轮廓和顶点,但我在填充它时遇到了问题。 我遇到了这里介绍的一些光栅化算法: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html并决定我将 Z34D1F91FB2E514B85676 第一种方法我复制了平底三角形外壳的代码,但是这在我的应用程序上似乎无法正常工作,我不知道问题的原因是什么。
我的结果:
主要的()
screen.fillFlatBottomTriangle(30,10, 10, 140/4, 256/2, 140/4, block_char, FG_CYAN);
screen.drawTriangle(30,10, 10, 140/4, 256/2, 140/4, block_char, BG_DARK_GREY);
screen.drawPixel(30,10,block_char,FG_RED);
screen.drawPixel(10,140/4,block_char,FG_GREEN);
screen.drawPixel(256/2,140/4,block_char,FG_MAGENTA);
fillFlatBottomTriangle
//http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html
void Screen::fillFlatBottomTriangle(int x1, int y1, int x2, int y2, int x3, int y3, short character, short color)
{
float invslope1 = (x2 - x1) / (y2 - y1);
float invslope2 = (x3 - x1) / (y3 - y1);
float curx1 = x1;
float curx2 = x1;
for (int scanlineY = y1; scanlineY <= y2; scanlineY++)
{
this->drawLine((int)curx1, scanlineY, (int)curx2, scanlineY, character, color);
curx1 += invslope1;
curx2 += invslope2;
}
}
画线
// https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)
void Screen::drawLine(int x1, int y1, int x2, int y2, short character, short color)
{
float delta_x = x2 - x1;
float delta_y = y2 - y1;
float step;
if (abs(delta_x) >= abs(delta_y))
step = abs(delta_x);
else
step = abs(delta_y);
delta_x = delta_x / step;
delta_y = delta_y / step;
float x = x1;
float y = y1;
for (int i = 1; i <= step; i++)
{
this->drawPixel((int)x, (int)y, character, color);
x += delta_x;
y += delta_y;
}
}
画三角形
void Screen::drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, short character, short color)
{
this->drawLine(x1,y1, x2, y2, character, color);
this->drawLine(x1,y1, x3, y3, character, color);
this->drawLine(x2,y2, x3, y3, character, color);
}
请参阅此部分: (x2 - x1) / (y2 - y1)
由于这里的所有变量都是整数,所以这是 integer 除法。 也就是说,除法的结果正在向 0 舍入。将结果分配给浮点数不会改变这一点。
要进行这种浮点除法,您应该将至少一个操作数转换为浮点数: (x2 - x1) / (float) (y2 - y1)
您当前的代码将逆斜率之一舍入为 0,从而在左侧产生垂直线。 另一侧的 x 值也没有足够快地增加,因为该部分也在下面四舍五入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.