c program to draw 3d triangle

I assume that y'all have some cognition of OpenGL. Otherwise, read "Introduction to OpenGL with 2D Graphics".

Example 1: 3D Shapes (OGL01Shape3D.cpp)

This case is taken from Nehe OpenGL Tutorial Lesson # 5 (@ http://nehe.gamedev.net/), which displays a 3D color-cube and a pyramid. The cube is made of of 6 quads, each having unlike colors. The hallow pyramid is made upward of four triangle, with dissimilar colors on each of the vertices.

1 two iii four 5 6 7 eight 9 10 11 12 xiii 14 15 16 17 eighteen nineteen 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 twoscore 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 threescore 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 fourscore 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
                    #include <windows.h>   #include <GL/glut.h>      char title[] = "3D Shapes";    void initGL() {    glClearColor(0.0f, 0.0f, 0.0f, one.0f);     glClearDepth(1.0f);                       glEnable(GL_DEPTH_TEST);       glDepthFunc(GL_LEQUAL);        glShadeModel(GL_SMOOTH);       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);   }    void display() {    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     glMatrixMode(GL_MODELVIEW);               glLoadIdentity();                     glTranslatef(1.5f, 0.0f, -7.0f);        glBegin(GL_QUADS);                                     glColor3f(0.0f, one.0f, 0.0f);            glVertex3f( 1.0f, one.0f, -1.0f);       glVertex3f(-1.0f, 1.0f, -i.0f);       glVertex3f(-i.0f, 1.0f,  ane.0f);       glVertex3f( 1.0f, 1.0f,  one.0f);                glColor3f(ane.0f, 0.5f, 0.0f);            glVertex3f( 1.0f, -1.0f,  1.0f);       glVertex3f(-i.0f, -one.0f,  i.0f);       glVertex3f(-1.0f, -ane.0f, -1.0f);       glVertex3f( ane.0f, -1.0f, -1.0f);                glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f( ane.0f,  one.0f, 1.0f);       glVertex3f(-1.0f,  ane.0f, i.0f);       glVertex3f(-i.0f, -1.0f, one.0f);       glVertex3f( i.0f, -1.0f, 1.0f);                glColor3f(one.0f, 1.0f, 0.0f);            glVertex3f( i.0f, -1.0f, -i.0f);       glVertex3f(-1.0f, -1.0f, -1.0f);       glVertex3f(-1.0f,  ane.0f, -one.0f);       glVertex3f( one.0f,  ane.0f, -1.0f);                glColor3f(0.0f, 0.0f, ane.0f);            glVertex3f(-1.0f,  1.0f,  1.0f);       glVertex3f(-1.0f,  1.0f, -i.0f);       glVertex3f(-1.0f, -one.0f, -1.0f);       glVertex3f(-i.0f, -1.0f,  1.0f);                glColor3f(1.0f, 0.0f, ane.0f);            glVertex3f(1.0f,  1.0f, -1.0f);       glVertex3f(one.0f,  1.0f,  1.0f);       glVertex3f(1.0f, -one.0f,  i.0f);       glVertex3f(ane.0f, -1.0f, -1.0f);    glEnd();            glLoadIdentity();                      glTranslatef(-1.5f, 0.0f, -half dozen.0f);        glBegin(GL_TRIANGLES);                         glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f( 0.0f, 1.0f, 0.0f);       glColor3f(0.0f, 1.0f, 0.0f);            glVertex3f(-1.0f, -1.0f, one.0f);       glColor3f(0.0f, 0.0f, one.0f);            glVertex3f(i.0f, -1.0f, 1.0f);                glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f(0.0f, one.0f, 0.0f);       glColor3f(0.0f, 0.0f, 1.0f);            glVertex3f(1.0f, -1.0f, one.0f);       glColor3f(0.0f, 1.0f, 0.0f);            glVertex3f(1.0f, -1.0f, -1.0f);                glColor3f(one.0f, 0.0f, 0.0f);            glVertex3f(0.0f, 1.0f, 0.0f);       glColor3f(0.0f, one.0f, 0.0f);            glVertex3f(ane.0f, -1.0f, -1.0f);       glColor3f(0.0f, 0.0f, 1.0f);            glVertex3f(-1.0f, -1.0f, -i.0f);                glColor3f(1.0f,0.0f,0.0f);              glVertex3f( 0.0f, 1.0f, 0.0f);       glColor3f(0.0f,0.0f,1.0f);              glVertex3f(-1.0f,-1.0f,-1.0f);       glColor3f(0.0f,1.0f,0.0f);              glVertex3f(-i.0f,-1.0f, 1.0f);    glEnd();         glutSwapBuffers();   }    void reshape(GLsizei width, GLsizei height) {          if (pinnacle == 0) summit = 1;                    GLfloat aspect = (GLfloat)width / (GLfloat)superlative;          glViewport(0, 0, width, elevation);          glMatrixMode(GL_PROJECTION);      glLoadIdentity();                     gluPerspective(45.0f, aspect, 0.1f, 100.0f); }    int main(int argc, char** argv) {    glutInit(&argc, argv);                glutInitDisplayMode(GLUT_DOUBLE);     glutInitWindowSize(640, 480);       glutInitWindowPosition(50, 50);     glutCreateWindow(title);              glutDisplayFunc(display);           glutReshapeFunc(reshape);           initGL();                           glutMainLoop();                     return 0; }

Overabundance Setup - main()

The programme contains a initGL(), display() and reshape() functions.

The principal() program:

  1. glutInit(&argc, argv);
    Initializes the GLUT.
  2. glutInitWindowSize(640, 480);
    glutInitWindowPosition(50, 50);
    glutCreateWindow(championship);

    Creates a window with a title, initial width and pinnacle positioned at initial peak-left corner.
  3. glutDisplayFunc(brandish);
    Registers brandish() as the re-paint event handler. That is, the graphics sub-organization calls dorsum display() when the window offset appears and whenever there is a re-paint request.
  4. glutReshapeFunc(reshape);
    Registers reshape() every bit the re-sized consequence handler. That is, the graphics sub-organisation calls back reshape() when the window first appears and whenever the window is re-sized.
  5. glutInitDisplayMode(GLUT_DOUBLE);
    Enables double buffering. In display(), nosotros utilize glutSwapBuffers() to bespeak to the GPU to swap the front-buffer and back-buffer during the next VSync (Vertical Synchronization).
  6. initGL();
    Invokes the initGL() once to perform all i-fourth dimension initialization tasks.
  7. glutMainLoop();
    Finally, enters the event-processing loop.
One-Fourth dimension Initialization Operations - initGL()

The initGL() part performs the one-time initialization tasks. It is invoked from main() once (and only once).

glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(i.0f);

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

Fix the immigration (groundwork) color to blackness (R=0, G=0, B=0) and opaque (A=1), and the immigration (background) depth to the farthest (Z=1). In display(), nosotros invoke glClear() to clear the color and depth buffer, with the immigration color and depth, before rendering the graphics. (Too the color buffer and depth buffer, OpenGL also maintains an aggregating buffer and a stencil buffer which shall be discussed afterwards.)

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);

We need to enable depth-test to remove the hidden surface, and prepare the function used for the depth test.

glShadeModel(GL_SMOOTH);
We enable smoothen shading in color transition. The alternative is GL_FLAT. Try information technology out and see the difference.

glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
In graphics rendering, there is frequently a trade-off betwixt processing speed and visual quality. We can use glHint() to make up one's mind on the merchandise-off. In this case, nosotros ask for the all-time perspective correction, which may involve more processing. The default is GL_DONT_CARE.

Defining the Color-cube and Pyramid

OpenGL's object is fabricated up of primitives (such as triangle, quad, polygon, signal and line). A archaic is defined via i or more vertices. The color-cube is made up of 6 quads. Each quad is made up of 4 vertices, defined in counter-clockwise (CCW) order, such equally the normal vector is pointing out, indicating the front face. All the 4 vertices have the aforementioned color. The colour-cube is divers in its local space (chosen model space) with origin at the center of the cube with sides of ii units.

Similarly, the pyramid is made up of 4 triangles (without the base). Each triangle is fabricated up of iii vertices, defined in CCW order. The 5 vertices of the pyramid are assigned different colors. The color of the triangles are interpolated (and alloy smoothly) from its iii vertices. Over again, the pyramid is defined in its local infinite with origin at the middle of the pyramid.

Model Transform

The objects are divers in their local spaces (model spaces). We need to transform them to the common globe space, known as model transform.

To perform model transform, we need to operate on the so-called model-view matrix (OpenGL has a few transformation matrices), by setting the electric current matrix mode to model-view matrix:

glMatrixMode(GL_MODELVIEW);

Nosotros perform translations on cube and pyramid, respectively, to position them on the world space:


glLoadIdentity();
glTranslatef(1.5f, 0.0f, -seven.0f);

glLoadIdentity();
glTranslatef(-one.5f, 0.0f, -6.0f);

View Transform

The default camera position is:

gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -100.0, 0.0, 1.0, 0.0)

That is, Centre=(0,0,0) at the origin, AT=(0,0,-100) pointing at negative-z axis (into the screen), and UP=(0,1,0) corresponds to y-centrality.

OpenGL graphics rendering pipeline performs then-called view transform to bring the world space to camera's view space. In the case of the default camera position, no transform is needed.

Viewport Transform

void reshape(GLsizei width, GLsizei pinnacle) {
glViewport(0, 0, width, elevation);

The graphics sub-organization calls back reshape() when the window first appears and whenever the window is resized, given the new window'due south width and height, in pixels. We fix our application viewport to cover the entire window, meridian-left corner at (0, 0) of width and height, with default minZ of 0 and maxZ of one. We likewise use the same aspect ratio of the viewport for the projection view frustum to prevent distortion. In the viewport, a pixel has (x, y) value also as z-value for depth processing.

Projection Transform

GLfloat attribute = (GLfloat)width / (GLfloat)height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, aspect, 0.1f, 100.0f);
A camera has express field of view. The projection models the view captured by the camera. There are ii types of projection: perspective projection and orthographic projection. In perspective projection, object further to the photographic camera appears smaller compared with object of the same size nearer to the camera. In orthographic projection, the objects announced the same regardless of the z-value. Orthographic project is a special example of perspective projection where the photographic camera is placed very far away. We shall discuss the orthographic projection in the afterwards case.

To set the projection, nosotros demand to operate on the projection matrix. (Recall that we operated on the model-view matrix in model transform.)

We set the matrix way to projection matrix and reset the matrix. Nosotros use the gluPerspective() to enable perspective projection, and gear up the fovy (view bending from the bottom-plane to the elevation-aeroplane), aspect ratio (width/top), zNear and zFar of the View Frustum (truncated pyramid). In this example, we gear up the fovy to 45°. We use the same attribute ratio every bit the viewport to avoid distortion. Nosotros set the zNear to 0.one and zFar to 100 (z=-100). Take that annotation the color-cube (1.5, 0, -7) and the pyramid (-ane.5, 0, -half-dozen) are contained within the View Frustum.

The projection transform transforms the view frustum to a 2x2x1 cuboid clipping-book centered on the near plane (z=0). The subsequent viewport transform transforms the clipping-volume to the viewport in screen space. The viewport is set earlier via the glViewport() function.

Instance 2: 3D Shape with Animation (OGL02Animation.cpp)

Permit's change the previous example to conduct out blitheness (rotating the cube and pyramid).

1 2 3 4 5 6 vii 8 9 10 11 12 13 fourteen 15 16 17 xviii 19 xx 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 twoscore 41 42 43 44 45 46 47 48 49 fifty 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 lxxx 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
                    #include <windows.h>   #include <GL/glut.h>      char title[] = "3D Shapes with animation";                  GLfloat anglePyramid = 0.0f;   GLfloat angleCube = 0.0f;      int refreshMills = 15;                                     void initGL() {    glClearColor(0.0f, 0.0f, 0.0f, one.0f);     glClearDepth(i.0f);                       glEnable(GL_DEPTH_TEST);       glDepthFunc(GL_LEQUAL);        glShadeModel(GL_SMOOTH);       glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);   }    void display() {    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     glMatrixMode(GL_MODELVIEW);               glLoadIdentity();                     glTranslatef(1.5f, 0.0f, -vii.0f);                    glRotatef(angleCube, one.0f, 1.0f, 1.0f);                                    glBegin(GL_QUADS);                                     glColor3f(0.0f, 1.0f, 0.0f);            glVertex3f( 1.0f, ane.0f, -1.0f);       glVertex3f(-1.0f, i.0f, -ane.0f);       glVertex3f(-1.0f, i.0f,  1.0f);       glVertex3f( 1.0f, 1.0f,  1.0f);                glColor3f(ane.0f, 0.5f, 0.0f);            glVertex3f( 1.0f, -one.0f,  1.0f);       glVertex3f(-1.0f, -i.0f,  ane.0f);       glVertex3f(-ane.0f, -1.0f, -i.0f);       glVertex3f( 1.0f, -one.0f, -ane.0f);                glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f( i.0f,  ane.0f, 1.0f);       glVertex3f(-1.0f,  1.0f, 1.0f);       glVertex3f(-1.0f, -i.0f, 1.0f);       glVertex3f( ane.0f, -ane.0f, 1.0f);                glColor3f(1.0f, i.0f, 0.0f);            glVertex3f( ane.0f, -1.0f, -1.0f);       glVertex3f(-1.0f, -1.0f, -ane.0f);       glVertex3f(-1.0f,  i.0f, -1.0f);       glVertex3f( i.0f,  1.0f, -i.0f);                glColor3f(0.0f, 0.0f, ane.0f);            glVertex3f(-1.0f,  1.0f,  one.0f);       glVertex3f(-1.0f,  1.0f, -1.0f);       glVertex3f(-1.0f, -1.0f, -1.0f);       glVertex3f(-ane.0f, -1.0f,  ane.0f);                glColor3f(ane.0f, 0.0f, 1.0f);            glVertex3f(1.0f,  one.0f, -ane.0f);       glVertex3f(1.0f,  1.0f,  1.0f);       glVertex3f(one.0f, -1.0f,  1.0f);       glVertex3f(ane.0f, -ane.0f, -1.0f);    glEnd();            glLoadIdentity();                      glTranslatef(-1.5f, 0.0f, -vi.0f);                    glRotatef(anglePyramid, 1.0f, 1.0f, 0.0f);                                    glBegin(GL_TRIANGLES);                         glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f( 0.0f, one.0f, 0.0f);       glColor3f(0.0f, one.0f, 0.0f);            glVertex3f(-one.0f, -1.0f, 1.0f);       glColor3f(0.0f, 0.0f, i.0f);            glVertex3f(1.0f, -one.0f, ane.0f);                glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f(0.0f, 1.0f, 0.0f);       glColor3f(0.0f, 0.0f, ane.0f);            glVertex3f(1.0f, -1.0f, 1.0f);       glColor3f(0.0f, 1.0f, 0.0f);            glVertex3f(1.0f, -1.0f, -1.0f);                glColor3f(1.0f, 0.0f, 0.0f);            glVertex3f(0.0f, 1.0f, 0.0f);       glColor3f(0.0f, 1.0f, 0.0f);            glVertex3f(ane.0f, -ane.0f, -1.0f);       glColor3f(0.0f, 0.0f, 1.0f);            glVertex3f(-1.0f, -ane.0f, -1.0f);                glColor3f(1.0f,0.0f,0.0f);              glVertex3f( 0.0f, one.0f, 0.0f);       glColor3f(0.0f,0.0f,1.0f);              glVertex3f(-1.0f,-one.0f,-ane.0f);       glColor3f(0.0f,one.0f,0.0f);              glVertex3f(-1.0f,-1.0f, 1.0f);    glEnd();         glutSwapBuffers();                                        anglePyramid += 0.2f;    angleCube -= 0.15f;                  }                                      void timer(int value) {    glutPostRedisplay();          glutTimerFunc(refreshMills, timer, 0);  }                   void reshape(GLsizei width, GLsizei top) {          if (height == 0) height = i;                    GLfloat aspect = (GLfloat)width / (GLfloat)tiptop;          glViewport(0, 0, width, height);          glMatrixMode(GL_PROJECTION);      glLoadIdentity();                     gluPerspective(45.0f, aspect, 0.1f, 100.0f); }    int primary(int argc, char** argv) {    glutInit(&argc, argv);                glutInitDisplayMode(GLUT_DOUBLE);     glutInitWindowSize(640, 480);       glutInitWindowPosition(50, l);     glutCreateWindow(title);              glutDisplayFunc(display);           glutReshapeFunc(reshape);           initGL();                                         glutTimerFunc(0, timer, 0);                                    glutMainLoop();                     return 0; }

The new codes are:

GLfloat anglePyramid = 0.0f;
GLfloat angleCube = 0.0f;
int refreshMills = fifteen;
We define 2 global variables to keep track of the current rotational angles of the cube and pyramid. We also define the refresh period as 15 msec (66 frames per second).

void timer(int value) {
glutPostRedisplay();
glutTimerFunc(refreshMills, timer, 0); //
}

To perform animation, we ascertain a function called timer(), which posts a re-paint request to activate brandish() when the timer expired, and then run the timer over again. In main(), we perform the first timer() call via glutTimerFunc(0, timer, 0).

glRotatef(angleCube, 1.0f, 1.0f, i.0f);
......
glRotatef(anglePyramid, 1.0f, 1.0f, 0.0f);
......
anglePyramid += 0.2f;
angleCube -= 0.15f;
In display(), we rotate the cube and pyramid based on their rotational angles, and update the angles after each refresh.

Instance 3: Orthographic Projection (OGL03Orthographic.cpp)

As mentioned, OpenGL support two blazon of projections: perspective and orthographic. In orthographic project, an object appears to be the same size regardless of the depth. Orthographic is a special case of perspective project, where the photographic camera is placed very far away.

To use orthographic project, change the reshape() function to invoke glOrtho().

void reshape(GLsizei width, GLsizei height) {          if (summit == 0) tiptop = 1;                    GLfloat attribute = (GLfloat)width / (GLfloat)height;          glViewport(0, 0, width, peak);          glMatrixMode(GL_PROJECTION);      glLoadIdentity();                                   if (width >= height) {             glOrtho(-3.0 * aspect, 3.0 * attribute, -3.0, iii.0, 0.1, 100);    } else {             glOrtho(-3.0, 3.0, -3.0 / aspect, 3.0 / aspect, 0.1, 100);    }          }

In this case, we gear up the cantankerous-section of view-volume co-ordinate to the aspect ratio of the viewport, and depth from 0.1 to 100, corresponding to z=-0.1 to z=-100. Take note that the cube and pyramid are independent inside the view-volume.

Case 4: Vertex Array

In the before example, cartoon a cube requires at least 24 glVertex functions and a pair of glBegin and glEnd. Role calls may involve high overhead and hinder the performance. Furthermore, each vertex is specified and processed three times.

Link to OpenGL/Estimator Graphics References and Resources

crosbystold1998.blogspot.com

Source: https://www3.ntu.edu.sg/home/ehchua/programming/opengl/CG_Examples.html

0 Response to "c program to draw 3d triangle"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel