giorgioW
giorgioW

Reputation: 331

Triangle strip does not show properly with OpenGL

I implemented a function in C++ to generate a N segments for a triangle strip (2 x N triangles) to be printed later (as GL_TRIANGLE_STRIP) by another function. Here I show you what I've got so far:

void strip(
    std::uint32_t N,
    std::vector<glm::vec3>* vertices)
{

    vertices->clear();

    for (std::uint32_t j=0; j<=N; ++j) 
    {
        for (std::uint32_t i=1; i<=N; ++i)
        {
            float x = (float)i/(float)N;
            float y = (float)j/(float)N;
            vertices->push_back(glm::vec3(x, y, 0));
        }
    }
}

So it would be seem like the following figure (For N = 3):

    ^
    |  ----------
    |  | /| /| /|
  y |  |/ |/ |/ |
    |  ----------
    |
    |-------------->
            x

But in fact it appears like this:

My triangle strip

Any advice about it? My thoughts is that I'm not generating the points in the correct order.

Upvotes: 0

Views: 691

Answers (2)

Amadeus
Amadeus

Reputation: 10655

Your logic is not good to generate a strip of triangles. Let me try to explain mine:

    ^
    |  0--2--4--6
    |  | /| /| /|
  y |  |/ |/ |/ |
    |  1--3--5--7
    |
    |-------------->
            x

As you can, triangle 0 is composed of vertices 0, 1 and 2, while triangle 1 is composed by vertices 1, 2 and 3, and so on. So, to generate this strip, you need to generate the odd indices in a row, and the even indices in another row. Let us try with code, generating, in this case, vertices:

void strip(std::uint32_t N, std::vector<glm::vec3>* vertices)
{
    vertices->clear();

    for (std::uint32_t j=0; j < N + 1; ++j) 
    {
        float x = (float)j/(float)N;
        vertices->push_back(glm::vec3(x, 1, 0));  // even row
        vertices->push_back(glm::vec3(x, 0, 0));  // odd row
    }
}

Upvotes: 3

derhass
derhass

Reputation: 45332

A triangle strip with the vertices A,B,C,D,E,... will form the triangles ABC, BCD, CDE, and so on.

My thoughts is that I'm not generating the points in the correct order.

Yes. What you generate is

0  1  2  3
4  5  6  7
8  9 10 11

So you're getting lots of deformed triangles with no area at all, and only get some weird triangles connecting the different lines (like 2 3 4 and 3 4 5).

What you should generate is

0  2  4  6
1  3  5  7

Note that when you add an additional row, you will have to repeat the bottom vertices from the previous row as the top vertices of the new row. ALso note that you have to re-start the triangle strip for each row.

A more efficient approach could be that you generate the vertices just as you are now, and look into indexed rendering, which will allow you to just re-use the vertices between different primitives.

Upvotes: 0

Related Questions