Generating a Cube of Points using a for loop

Hi, I’m trying to draw a cube in 3D space using points rendered at each vertex. I am currently trying to figure out a system which draws them without me having to copy code and manually enter vertex positions, but I am having trouble.
The for loop I am using is:

    for(int i = 0; i < 8; i++){
        int j = i % 4;
        if(j == 0){ //then i = 0 || 4.
            int k = (i/2) - 1; // k is -1 or 1.
            mesh.addVertex(ofVec3f(-15, 0, -15 * k));
        } else if (j == 1){ //then i = 1 || 5.
            int k = ((i-1)/2) - 1; //k is -1 or 1.
            mesh.addVertex(ofVec3f(15, 0, -15 * k));
        } else if (j == 2){ //then i = 2 || 6.
            int k = ((i-2)/2) - 1; //k is -1 or 1.
            mesh.addVertex(ofVec3f(-15, -30, -15 * k));
        } else if (j == 3){ //then i = 3 || 7.
            int k = ((i-3)/2) - 1; //k is -1 or 1.
            mesh.addVertex(ofVec3f(15, -30, -15 * k));
            //this should always output 0 and 2.
            std::cout << "value: " << (i-3)/2 << endl;
        }
        mesh.addIndex(i);
    }

Effectively making a 2D square with vertices, and then using the modulo operator and k value to draw one in front and one behind. The overall cube dimensions are 30x30x30. I thought this code was correct, however only 6 vertices render in the window. Can anyone help me figure out what might be going wrong?

Hi @dvshkbm , ofMesh has some different modes. The default is OF_PRIMITIVE_TRIANGLES. Try setting the mode to OF_PRIMITIVE_POINTS instead:

    mesh.setMode(OF_PRIMITIVE_POINTS);

The modes describe what openGL is trying to draw. You can see some/all of them in the documentation:
https://openframeworks.cc//documentation/3d/ofMesh/#!show_setMode

And also with more detailed discussion in ofBook:
https://openframeworks.cc/ofBook/chapters/openGL.html
https://openframeworks.cc/ofBook/chapters/generativemesh.html#basicsworkingwithofmesh

If you want to draw the faces at some point, then the OF_PRIMITIVE_TRIANGLES mode is great, and you’ll need to set some indices (the drawing order) to draw each individual triangle in the cube. There are usually a lot more indices than vertices because any given vertex is a component of multiple different triangles (if that makes sense). The ofBook chapters have some nice detail about how to do this (especially the winding order).

The coordinates of the vertices from the loop look great though! I added some cout statements to check them. An ofEasyCam can often make 3D stuff a bit easier to view too.

Hi @TimChi, thanks for such a detailed response! Your suggestion worked, I was scratching my head about this for ages. I really appreciate the suggestions.

1 Like