I want to draw one cylinder using OpenGL in Visual C++. I want to make the color of the cylinder red, so I add the following code in the renderCylinder function, but it doesn't change.
glColor3f(1.0, 0.0, 0.0);
Could you help me to solve this problem?
The following codes are the full codes to make a cylinder for a test.
#include <GL/glew.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fstream>
#include <string>
#include <cstring>
#include <cmath>
#include <iostream>
int selectedObject = 1;
bool drawThatAxis = 0;
bool lightEffect = 1;
float fovy = 60.0, aspect = 1.0, zNear = 1.0, zFar = 100.0;
float depth = 8;
float phi = 0, theta = 0;
float downX, downY;
bool leftButton = false, middleButton = false;
void renderCylinder(double x1, double y1, double z1, double x2, double y2, double z2, double radius, GLUquadricObj* quadric);
void displayCallback(void);
GLdouble width, height;
int wd;
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH);
glutInitWindowSize(800,600);
wd = glutCreateWindow("3D Molecules");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glClearColor(0.0, 0.0, 0.0, 0.0);
GLuint id;
id = glGenLists(1);
printf("hi %d\n", id);
GLUquadric* myQuad;
myQuad = gluNewQuadric();
glNewList(id, GL_COMPILE);
renderCylinder(0, 0, 0, 5, 5, 5, 1.5, myQuad);
glEndList();
glutDisplayFunc(displayCallback);
glutMainLoop();
return 0;
}
void renderCylinder(double x1, double y1, double z1, double x2, double y2, double z2, double radius, GLUquadricObj* quadric)
{
double vx = x2 - x1;
double vy = y2 - y1;
double vz = z2 - z1;
double ax, rx, ry, rz;
double len = sqrt(vx * vx + vy * vy + vz * vz);
glPushMatrix();
glColor3f(1.0, 0.0, 0.0);
glTranslatef(x1, y1, z1);
if (fabs(vz) < 0.0001)
{
glRotatef(90, 0, 1, 0);
ax = 57.2957795 * -atan(vy / vx);
if (vx < 0)
{
}
rx = 1;
ry = 0;
rz = 0;
}
else
{
ax = 57.2957795 * acos(vz / len);
if (vz < 0.0)
ax = -ax;
rx = -vy * vz;
ry = vx * vz;
rz = 0;
}
glRotatef(ax, rx, ry, rz);
gluQuadricOrientation(quadric, GLU_OUTSIDE);
gluCylinder(quadric, radius, radius, len, 10, 10);
glPopMatrix();
}
void displayCallback(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(fovy, aspect, zNear, zFar);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 40, 0, 0, 0, 0, 1, 0);
glTranslatef(0.0, 0.0, -depth);
glRotatef(-theta, 1.0, 0.0, 0.0);
glRotatef(phi, 0.0, 1.0, 0.0);
if (lightEffect) {
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
}
else
{
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
}
switch (selectedObject)
{
case (1):
glCallList(1);
break;
default:
break;
}
glFlush();
}
You have lighting ON so glColor
is ignored and material & light properties are used instead...
To remedy that add this to your code near place where you enable light:
glEnable(GL_COLOR_MATERIAL);