PDA

View Full Version : Normals for cylinder



sumkang
05-10-2012, 10:28 PM
Hi i am not able to apply proper normals to my cylinder i have tried using the cross product of three vertices but it is not working for me, kindly help me

this is my code.

void normalize(float *xn, float *yn, float *zn)
{
float len = sqrt(*xn**xn+*yn**yn+*zn**zn);
*xn = *xn / len;
*yn = *yn / len;
*zn = *zn / len;
}



struct Vert v0,v1,v2,v3,vn,edge1,edge2;
float theta,theta1,x1,y1,z1,x22,y22,z22;

for(int i=0;i<32;i++)
{
theta = 2*M_PI*i/32;
x1= 1.0*cos(theta);
y1=1.0*sin(theta);
z1 = 0;

theta1 = 2*M_PI*i+1/32;
x22= 1.0*cos(theta);
y22=1.0*sin(theta);
z22 = 0;

v0.x=x1;v0.y=y1;v0.z=z1;
v1.x=x1,v1.y=y1,v1.z=z1+5.0;
v2.x=x22;v2.y=y22;v2.z=z22;

edge1.x = v1.x-v0.x;
edge1.y = v1.y-v0.y;
edge1.z = v1.z-v0.z;

edge2.x = v2.x-v0.x;
edge2.y = v2.y-v0.y;
edge2.z = v2.z-v0.z;

vn.x = edge1.y*edge2.z - edge1.z * edge2.y;
vn.y = edge1.z*edge2.x - edge1.x * edge2.z;
vn.z = edge1.x*edge2.y - edge1.y * edge2.x;

normalize(&vn.x,&vn.y,&vn.z);
//glNormal3f(vn.x,vn.y,vn.z);

glVertex3f(x1,y1,z1);
glVertex3f(x1,y1,z1+5.);


}

tonyo_au
05-10-2012, 11:36 PM
theta1 = 2*M_PI*i+1/32;
x22= 1.0*cos(theta);
y22=1.0*sin(theta);
z22 = 0;


should this be theta1

sumkang
05-11-2012, 04:09 AM
Sorry for the typing mistake,yes this should be theta1 but still i am not able to get proper normals for the cylinder

V-man
05-11-2012, 11:27 AM
Sorry for the typing mistake,yes this should be theta1 but still i am not able to get proper normals for the cylinder

Normals for a cylinder is quite simple. For the body, I would do
normal = normalize(vertex - center of cylinder); //Do that for all the body vertices

and for the top, it would be {0.0, 0.0, 1.0}
and the bottom, it would be {0.0, 0.0, -1.0}

tonyo_au
05-11-2012, 11:09 PM
very clever V-man

sumkang
05-13-2012, 10:53 PM
Thanks a lot V-man for the help but still it is not working for me all the normals are facing in top direction this is my code.

struct Vert nm1,nm2;
float theta,theta1,x1,y1,z1

for(int i=0;i<32;i++)
{

theta = 2*M_PI*i/32;
x1= 1.0*cosf(theta);
y1=1.0*sinf(theta);
z1 = 5;



// calculation normal for top vertices
nm1.x = x1-0;
nm1.y=y1-0;
nm1.z = 5.0-0;
normalize(&nm1.x,&nm1.y,&nm1.z);
glNormal3f(nm1.x,nm1.y,nm1.z);
glVertex3f(x1,y1,5.0);


// calculation normal for Bottom vertices

nm2.x = x1-0;
nm2.y = y1-0;
nm2.z = -5.0-0;
normalize(&nm2.x,&nm2.y,&nm2.z);
glNormal3f(nm2.x,nm2.y,nm2.z);
glVertex3f(x1,y1,-5.0);

sumkang
05-15-2012, 10:47 PM
Thanks V-man it is working for me now