Sunday, July 12, 2009

OpenGL: First Test - 2D Example

I'm not a Computer Graphics fan, but I've spent my the last year working on Report Engine, and User Interfaces... drawLine, drawRect.. setLocation... (I don't know.. I'm a malloc/memset boy).

But I need to learn more about Computer Graphics for the future, and today I've started playing with OpenGL... No more 2D points!!! :D
Below you can see a couple of lines of code that draws the example above...



static void drawTriangle (void) {
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_TRIANGLES);

glVertex3f( 0.0f,  0.6f, 0.0f);
glVertex3f(-0.2f, -0.3f, 0.0f);
glVertex3f( 0.2f, -0.3f, 0.0f);

glEnd();
}

static void drawSquare (void) {
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_TRIANGLE_FAN);

glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(0.5f, 0.0f, 0.0f);
glVertex3f(0.5f, 0.5f, 0.0f);
glVertex3f(0.0f, 0.5f, 0.0f);

glEnd();
}

static void drawSquareMode2 (void) {
const GLfloat squareVertices[] = {
-0.2,  0.2, 0.2, 
-0.2, -0.2, 0.2,
0.2, -0.2, 0.2, 
0.2,  0.2, 0.2 
};

glColor3f(0.0f, 1.0f, 0.0f);
glVertexPointer(3, GL_FLOAT, 0, squareVertices);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}


I've used NSOpenGLView to display the GL, so the drawing code is inside a drawRect method.
- (void)drawRect:(NSRect)bounds {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);

glTranslatef(-0.2f, 0.0f, 0.0f);
drawTriangle();

glTranslatef(0.2f, 0.0f, 0.0f);
drawSquare();
drawSquareMode2();

glFlush();
}

No comments:

Post a Comment