用三角形制作OpenGL平面的问题



我试图使用OpenGL制作飞机,在某种程度上代码工作,但我在一些指标上得到奇怪的结果。我将尽我所能解释我的代码,它是我的代码和我在网上找到的东西的混合物。

主:

所有设置都在主程序中进行,因此函数将知道所需的所有值

float zoom = 6.0f;
float vertical = 1.2f;
float horizontal = 1.2f;
const int planeWidth = 4;  //columns
const int planeHeight = 2; //rows
const int totalVertices = (planeWidth + 1) * (planeHeight + 1);
//GLfloat* vertices = new GLfloat[totalVertices];
GLfloat vertices[totalVertices] = { 0.0 };
const int indPerRow = planeWidth * 2 + 2;
const int indDegenReq = (planeHeight - 1) * 2;
const int totalIndices = indPerRow * planeWidth + indDegenReq;
//GLuint* indices = new GLuint[totalIndices];
GLuint indices[totalIndices] = { 0 };
GLfloat texCoords[totalVertices] = { 0 };
makePlane(planeWidth, planeHeight, vertices, indices, texCoords);
函数:

第一个for循环创建顶点,第二个创建索引

void makePlane(int width, int height, GLfloat *vertices, GLuint *indices)
{
width++;  //columns
height++; //rows
int size = sizeof(GLfloat);
for (int y = 0; y < height; y++)
{
    int base = y * width;
    for (int x = 0; x < width; x++)
    {
        int index = (base + x) * 2;
        vertices[index]    = (float)x;
        vertices[index +1] = (float)y;
    }
}
int i = 0;
height--;
for (int y = 0; y < height; y++)
{
    int base = y * width;
    for (int x = 0; x < width; x++)
    {
        indices[i++] = base + x;
        indices[i++] = base + width + x; 
    }
    if (y < height - 1)
    {
        indices[i++] = ((y + 1) * width + (width - 1));
        indices[i++] = ((y + 1) * width);
    }   
}
}
结果:

4 × 2

指数0、5、1、6、2、7、3、8、4、9、9日5、5、10、6、11、7、12、8、13日,9日,14日,0,0,0,0,0,0,…} unsigned int[42]

正确处理22个值,其余为0。

知道为什么吗?

我认为你的循环需要看起来像这样(小心未经测试:)。基本上可以把它看作是在四边形上循环并输出三角形对的下标。

for (int y = 0; y < height; y++)
{
    unsigned int base = y * width;
    unsigned int top = base + width;
    for (int x = 0; x < (width-1); x++)
    {
        indices[i++] = base + x;
        indices[i++] = top + x; 
        indices[i++] = top + x + 1; 
        indices[i++] = top + x + 1;
        indices[i++] = base + x + 1; 
        indices[i++] = base + x; 
    }
}

我意识到顶点是从下到上创建的,索引是从上到下创建三角形的。所以我改变了for循环的顶点创建。

int index = 0;
for (int y = height; y >= 0; y--)
{
    for (int x = 0; x <= width; x++)
    {
        vertices[index] = ((float)x/4)-0.5;
        vertices[index +1] = ((float)y/4)-0.5;
        vertices[index + 2] = 0.0f;
        index += 3;
    }
}

从左上到右下创建顶点。索引的循环保持不变:

int i = 0;
++width;
GLuint indices2[170] = { 0 };
for (int y = 0; y < height; y++)
{
    int base = y * width;
    for (int x = 0; x < width; x++)
    {
        indices[i++] = base + x;
        indices[i++] = base + width + x;
    }
    if (y < height - 1)
    {
        indices[i++] = ((y + 1) * width + (width - 1));
        indices[i++] = ((y + 1) * width);
    }
}

相关内容

  • 没有找到相关文章

最新更新