• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# OpenGL OpenGL Lighting problems

## Recommended Posts

Can somebody tell me how to specify the normal for each vertex? The book I have tells me how to get just the one normal (giving me flat shaded polygons. :<) Also, anybody know how to gourand shade polygons using materials? Please keep in mind that I''m real new to OpenGL... Thanks.

##### Share on other sites
Specifing a normal for each vertex is easy - just call glNormalxxx() before each glVertexxxx(). Later, when you get better with using OpenGL, you''ll start using vertex arrays, but for learning purposes, you''ll probably eventually wrap every vertex with:
glNormal();
glTexCoords();
glVertex();

##### Share on other sites
Uhh, I''m not trying to be ungrateful but...

How do I "get" the normal for each vertex...that OpenGL book I got only shows how to get the one normal and then it cheats on the rest of the examples and uses aux functions and therefor not telling me how to get them...

##### Share on other sites
Well, you calculate it based on the object you''re trying to render.

If it''s a sphere, the normal is a vector pointing directly away from the center of the sphere.

If it''s a terrain or flatish polygonal model, people generally average the face normals of all the faces which share the vertex.

If you''re drawing some kind of mathematically defined surface, you can figure out the normal based on the derivative of the surface''s equation.

##### Share on other sites

It accepts one of 2 parameters:

At initialization, gl has glShadeModel set to GL_SMOOTH, so as long as you didn't call glShadeMode(), specifying a normal per vertex will give you smooth shading, so long as each normal is the normal to the surface, and not the polygon. Here is an example of the difference between a normal to the surface and the normals to the polygons apporximating the surface.

Edited by - succinct on November 2, 2001 3:15:28 PM

##### Share on other sites
A sphere is definitely the easiest, because, as cheesegrater said, the normal for any point on a sphere is the line from the line from the center of the sphere to the point, normalized.

For an arbitrary mesh of polygons, you keep track of what polygons use what vertices and for each vertex computer the average of all the polygon normals that use that vertex. The necessary data structures for figuring this out are somewhat tricky, because each polygon must reference it's composing vertices, and each vertex must reference all of the polygons that reference it. It becomes a "chicken or the egg" type of problem, but you can solve it.

And, to my knowledge, the only other type of surface is a mathematically defined one. If you can define a surface parametrically, such that it is in terms of two variables, usually u and v, you can find the normal using a little calculus. For a given ( u,v ) on the surface, the surface normal is the unit tangent of the u curve crossed with the unit tangent of the v curve.

Basically, seperate the equation into it's f( u ) and g( v ) parts, expressed as vector functions. Find f'( u ) and g'( v ). Normalize them. Cross them. This is your unit normal vector.

Here is a visual explanation for the normals for a parametric torus.

The torus is just a circle (g(v)) swept around another curve (f(u)). The normal at any given point is the unit gradient of the sweeping curve crossed by the unit gradient of the swept curve.

For a circle defined as
x = r*cos( t )
y = r*sin( t )

x' = r*-sin( t )
y' = r*cos( t )

just like you learn in highschool (and hopefully you've been to highschool and have had calculus!)

For further explanation, the picture generated used the following function.

  void gl::RenderTorus( int Majors, // number of major subdivisions (along the greater circle) int Minors, // number of minor subdivisions (along the lesser circle) float MrX, // major x radius float MrY, // major y radius float mrX, // minor x radius float mrZ, // minor z radius float Msa, // major start angle float Mea, // major end angle float msa, // minor start angle float mea, // minor end angle bool InvertNormals){ // the vector class uses the operator ^ as a cross product // the member function .Unit() normalizes the vector. int NumMajorVertices = Majors + 1; int NumMinorVertices = Minors + 1; if( NumMajorVertices <= 2 ) NumMajorVertices = 3; if( NumMinorVertices <= 2 ) NumMinorVertices = 3; // calc angle deltas float MajorAngleDelta = (Mea - Msa)*M_PI/(180*(NumMajorVertices - 1)); float MinorAngleDelta = (mea - msa)*M_PI/(180*(NumMinorVertices - 1)); float MajorAngle1 = Msa*M_PI/180; float MajorAngle2 = MajorAngle1 + MajorAngleDelta; for( int i = 0; i < NumMajorVertices - 1; ++i ) { // calc major coordinates and normals float uS1x = cos( MajorAngle1 ); float uS1y = sin( MajorAngle1 ); float uS2x = cos( MajorAngle2 ); float uS2y = sin( MajorAngle2 ); Vector uS1 = Vector( MrX*uS1x,MrY*uS1y,0 ); Vector uN1 = Vector( -MrX*uS1y,MrY*uS1x,0 ).Unit() ^ Vector( 0,0,1 ); Vector uS2 = Vector( MrX*uS2x,MrY*uS2y,0 ); Vector uN2 = Vector( -MrX*uS2y,MrY*uS2x,0 ).Unit() ^ Vector( 0,0,1 ); // calc rotation angles for minor ellipse (so it lines up with major normal) float RotationAngle1 = acos( uN1.x ); if( ((-M_PI < MajorAngle1) && (MajorAngle1 < 0 )) || ((2*M_PI > MajorAngle1) && (MajorAngle1 > M_PI)) ) RotationAngle1 = -RotationAngle1; float RotationAngle2 = acos( uN2.x ); if( ((-M_PI < MajorAngle2) && (MajorAngle2 < 0 )) || ((2*M_PI > MajorAngle2) && (MajorAngle2 > M_PI)) ) RotationAngle2 = -RotationAngle2; // cache rotation coefficients float ct1 = cos( RotationAngle1 ); float st1 = sin( RotationAngle1 ); float ct2 = cos( RotationAngle2 ); float st2 = sin( RotationAngle2 ); glBegin( GL_QUAD_STRIP ); float MinorAngle = msa*M_PI/180; for( int j = 0; j < NumMinorVertices; ++j ) { // v == minor param float vSx = cos( MinorAngle ); float vSz = sin( MinorAngle ); // rotate minor ellipse so it is aligned with the normal of the major ellipse at this point Vector vS = Vector( mrX* vSx,0,mrZ*vSz ); Vector vT = Vector( mrX*-vSz,0,mrZ*vSx ); Vector vS1r = Vector( ct1*vS.x,st1*vS.x,vS.z ); Vector vT1r = Vector( ct1*vT.x,st1*vT.x,vT.z ); Vector vS2r = Vector( ct2*vS.x,st2*vS.x,vS.z ); Vector vT2r = Vector( ct2*vT.x,st2*vT.x,vT.z ); Vector vN1 = ((vT1r ^ vS1r).Unit() ^ vT1r).Unit(); Vector vN2 = ((vT2r ^ vS2r).Unit() ^ vT2r).Unit(); if( InvertNormals ) { vN1 = -vN1; vN2 = -vN2; } glNormal3fv( vN1 ); glVertex3fv( uS1 + vS1r ); glNormal3fv( vN2 ); glVertex3fv( uS2 + vS2r ); MinorAngle += MinorAngleDelta; } glEnd(); MajorAngle1 += MajorAngleDelta; MajorAngle2 += MajorAngleDelta; }}

I hope that helps,
-- Succinct

Edited by - succinct on November 2, 2001 5:14:11 PM

##### Share on other sites
Uhh, hmm.

Ok, you guys are really being nice and putting lots of time into this but, all this info is really confusing...how do I "smooth shade" a cube? I thought you had to give a "normal" for each vertex...

>just like you learn in highschool (and hopefully you''ve been to >highschool and have had calculus!)
Hmm, uhh... In highschool.

##### Share on other sites
If you have the object in a .3ds file you can use
a software named 3DExploration (search with www.google.com)
and this software give you a file (see "Save as..") with
all information about texturing normals vertex position...
as .cpp file for OpenGL.
That''s all

##### Share on other sites
Hi,

When you have already the normal for a polygon it is
not difficult to find the vertex-normals.
take a vertex, go through your polygons, take the Face(polygon)-Normal from all the polygons who share that vertex,
add them and normalize it, so can get the vertex-normals.

Try a Cube, becaue a cube only has eight corners, vertices

##### Share on other sites
Etwinox:

After you figure out the vertex issues, to gourand shade a polygon you can do the following:

//----------------------------------------

//define light and material properties
float ambientLight[] = {0.5f,0.5f,0.5f,1.0f}; // ambient light
float specularLight[]= {1.0f,1.0f,1.0f,1.0f }; //specular light

//material reacting to ambient light
float matAmbient[] = {1.0f, 1.0f, 1.0f, 1.0f};

glEnable (GL_LIGHTING); // Enable lighting
glEnable (GL_COLOR_MATERIAL); //enable materials
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

//Set the lighting materials
glMaterialfv(GL_FRONT, GL_AMBIENT, matAmbient);
glMaterialfv(GL_FRONT, GL_SPECULAR, specularLight);
glMateriali (GL_FRONT, GL_SHININESS, 128); //strong shiny effect

//Setup LIGHT0
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight); //ambient light
glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);//specular light
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);//light position

glEnable (GL_LIGHT0); //enable light0

/---------------------------------/

Hope it helps

##### Share on other sites
quote:
Original post by Etwinox
Uhh, hmm.

Ok, you guys are really being nice and putting lots of time into this but, all this info is really confusing...how do I "smooth shade" a cube? I thought you had to give a "normal" for each vertex...

Smooth shading works fine with face normals. With a cube, specify the same normal for each vertex in a face. The ''smoothness'' of smooth shading will come from the changing angle to the light source at the different vertexes (which is computed by openGL for you) rather than from differing normals.

##### Share on other sites
Why would you smooth shade a cube? All of the normals on a particular face share the same normal. Even worse, if you''re only using 8 vertices for the cube, because each vertex is used more than once (4 vertices per face, each vertex shares 3 faces), there is not a particular "vertex normal" or "surface normal" that relates to each vertex in a 1 to 1 manner. Each vertex will use 3 different normals, one for each face it''s rendering. This is because each vertex lies on a sharp edge.

If you were to use a single "surface" normal for each vertex, the cube would not look like a cube, but like a sphere that is very under tesselated, like it doesn''t use enough polygons to approximate the surface of the sphere.

Now, if you were talking about using more than 8 vertices, like having vertices internal to a particular plane (face), then each vertex on a particular face shares the same normal.

If you''re looking to explore smooth shading, try a different primitive that doesn''t have sharp edges, such as a sphere, cone, or cylinder. I learned how to describe these shapes in 11th grade trig class - it''s all sines and cosines.

If you''re interested in some code for them post here about it and I can send you some or post some here. My advice, though, is to "borrow" some of the math books you use in high school trig and calculus, and get your hands on some college level texts, if you can. I still have my high school trig book, two different high school calc books, and all of my college math books. Every once in a while, I still have to go and double check something from that high school trig book!

##### Share on other sites
Aww...
I didn''t think of it that way. I thought you "had" to smooth shade an object...how do games get a "spotlight" effect then if
the surface consists of only one normal? I didn''t think it would
work considering the lighting is only a brightness level when its one normal (or so it seems).

Course, now I know why my attempts at smooth shading a cube were
not exactly correct looking.

P.S.
Thank god, I thought I would of been stuck on chapter five of that book forever. ^_^

Oh, almost forgot, I would be happy to see that source code you were talking about if you have the free time, but its upto you.

##### Share on other sites
By a ''spotlight'' effect I''m going to assume that you''re talking about a specular reflection. (The white patch you see when looking at an apple or a shiny ball.)

The specular reflection occurs when the vector of light ''mirroring'' off of the object happens to line up well with the vector to the eye. Think of the light bouncing off of the surface at the same angle it hit. If the bounce points right at your eye or camera, you get a specular hightlight. This happens at some points of a flat surface but not others, since the reflected light rays won''t match up when reflected from various points, even if they are reflected at nearly the same angle.

OpenGL''s shading model (gourand shading) won''t do specular highlighting within a face. To get this you need to tesselate your flat surfaces into larger groups of triangles. However, with a flat surface these tesselated faces will still all have the same normal.

If you want this to happen on one big quad, you need phong shading, which isn''t built into OpenGL.

##### Share on other sites
If you want a normal for a triangle, this is the code:

struct GLVECTOR
{
float x,y,z;
}

GLVECTOR triangle[3];
glVECTOR normal;
GLVECTOR temp[2];

//move the triangle temporarily to the origin.
temp[0] = triangle[1] - triangle[0];
temp[1] = triangle[2] - triangle[0];
//No real code, i know, but you know how to do that.

normal.x = triangle[1].y*triangle[2].z - triangle[2].y*triangle[1].z;
normal.y = triangle[1].z*triangle[2].x - triangle[2].z*triangle[1].x;
normal.z = triangle[1].x*triangle[2].y - triangle[2].x*triangle[1].y;

Now you got a good normal. (Needs to be normalized, though, but you can use glEnable(GL_NORMALIZE), i think..)

• ### Forum Statistics

• Total Topics
627735
• Total Posts
2978854
• ### Similar Content

• Hello! As an exercise for delving into modern OpenGL, I'm creating a simple .obj renderer. I want to support things like varying degrees of specularity, geometry opacity, things like that, on a per-material basis. Different materials can also have different textures. Basic .obj necessities. I've done this in old school OpenGL, but modern OpenGL has its own thing going on, and I'd like to conform as closely to the standards as possible so as to keep the program running correctly, and I'm hoping to avoid picking up bad habits this early on.
Reading around on the OpenGL Wiki, one tip in particular really stands out to me on this page:
For something like a renderer for .obj files, this sort of thing seems almost ideal, but according to the wiki, it's a bad idea. Interesting to note!
So, here's what the plan is so far as far as loading goes:
Set up a type for materials so that materials can be created and destroyed. They will contain things like diffuse color, diffuse texture, geometry opacity, and so on, for each material in the .mtl file. Since .obj files are conveniently split up by material, I can load different groups of vertices/normals/UVs and triangles into different blocks of data for different models. When it comes to the rendering, I get a bit lost. I can either:
Between drawing triangle groups, call glUseProgram to use a different shader for that particular geometry (so a unique shader just for the material that is shared by this triangle group). or
Between drawing triangle groups, call glUniform a few times to adjust different parameters within the "master shader", such as specularity, diffuse color, and geometry opacity. In both cases, I still have to call glBindTexture between drawing triangle groups in order to bind the diffuse texture used by the material, so there doesn't seem to be a way around having the CPU do *something* during the rendering process instead of letting the GPU do everything all at once.
The second option here seems less cluttered, however. There are less shaders to keep up with while one "master shader" handles it all. I don't have to duplicate any code or compile multiple shaders. Arguably, I could always have the shader program for each material be embedded in the material itself, and be auto-generated upon loading the material from the .mtl file. But this still leads to constantly calling glUseProgram, much more than is probably necessary in order to properly render the .obj. There seem to be a number of differing opinions on if it's okay to use hundreds of shaders or if it's best to just use tens of shaders.
So, ultimately, what is the "right" way to do this? Does using a "master shader" (or a few variants of one) bog down the system compared to using hundreds of shader programs each dedicated to their own corresponding materials? Keeping in mind that the "master shaders" would have to track these additional uniforms and potentially have numerous branches of ifs, it may be possible that the ifs will lead to additional and unnecessary processing. But would that more expensive than constantly calling glUseProgram to switch shaders, or storing the shaders to begin with?
With all these angles to consider, it's difficult to come to a conclusion. Both possible methods work, and both seem rather convenient for their own reasons, but which is the most performant? Please help this beginner/dummy understand. Thank you!

• I want to make professional java 3d game with server program and database,packet handling for multiplayer and client-server communicating,maps rendering,models,and stuffs Which aspect of java can I learn and where can I learn java Lwjgl OpenGL rendering Like minecraft and world of tanks

• A friend of mine and I are making a 2D game engine as a learning experience and to hopefully build upon the experience in the long run.

-What I'm using:
C++;. Since im learning this language while in college and its one of the popular language to make games with why not.     Visual Studios; Im using a windows so yea.     SDL or GLFW; was thinking about SDL since i do some research on it where it is catching my interest but i hear SDL is a huge package compared to GLFW, so i may do GLFW to start with as learning since i may get overwhelmed with SDL.
-Questions
Knowing what we want in the engine what should our main focus be in terms of learning. File managements, with headers, functions ect. How can i properly manage files with out confusing myself and my friend when sharing code. Alternative to Visual studios: My friend has a mac and cant properly use Vis studios, is there another alternative to it?

• Both functions are available since 3.0, and I'm currently using glMapBuffer(), which works fine.
But, I was wondering if anyone has experienced advantage in using glMapBufferRange(), which allows to specify the range of the mapped buffer. Could this be only a safety measure or does it improve performance?
Note: I'm not asking about glBufferSubData()/glBufferData. Those two are irrelevant in this case.
• By xhcao
Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness.

• 10
• 10
• 21
• 14
• 12