Sign in to follow this  

OpenGL [c++ opengl] poligon class

This topic is 3441 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hy. I have created a poligon class this:
#include "stdafx.h"
#ifdef _WINDOWS
#include <windows.h>
#endif


#include <math.h>
#include "polygon.h"


CPolygon::CPolygon()
{
	
}

CPolygon::~CPolygon()
{
	delete m_PolyData;
}

void CPolygon::Draw()
{
	FACE* ptrFace = m_PolyData->m_faces;
	INDEX* ptrIndex = NULL;
	
	int nIndexCount = 0 ;
	int nfacesCount = m_PolyData->m_nFacesCount;
	
	while(nfacesCount -- )
	{
		ptrIndex = m_PolyData->m_faces[nfacesCount].pIndex;
		nIndexCount = m_PolyData->m_faces[nfacesCount].nCount;
			
		int pIdxNorm =m_PolyData->m_faces[nfacesCount].nFaceNormal;
		
		glBegin(GL_POLYGON);	
		glNormal3fv(m_PolyData->m_FaceNormals[pIdxNorm].val);
		while(nIndexCount--)
		{
			int pIdx =m_PolyData->m_faces[nfacesCount].pIndex[nIndexCount].nVertex;
			glVertex3fv(m_PolyData->m_vertexs[pIdx].val);
		}
		glEnd();
		//glPopMatrix();
		
	}
}			
		
		


but is very very slow comparated with draw the poly in the code. Can you give me a hint for a faseter render? Thanks.

Share this post


Link to post
Share on other sites
Rather than using GL_POLYGON, do you think you can use GL_TRIANGLES or GL_QUADS? And see if you can use a for loop rather than 2 whiles. And lastly, shouldn't #ifdef _WINDOWS be #ifdef WIN32, but if _WINDOWS works, then use it.

Share this post


Link to post
Share on other sites
Real efficiency is yielded in if you render all primitives "at once". That requires homogenized geometry. Therefore triangulate the polygons so that all faces are 3 sided, so that you need not distinct say 5-gons from 6-gons and so on. Next, go away from the immediate mode (those glBegin/glEnd stuff) but build arrays of vertex attributes and push them as VBOs to the API. As an optimization step later on, you can optimize the vertex buffers by sorting vertex indices w.r.t. the post-T-&-L cache.

I personally also have dropped pointers to topological elements where possible already in the meshes. Using indices instead have several advantages: They consume less memory (e.g. 4 bytes instead of 8 bytes on 64-bit maschines), and, perhaps more important, they allow loading (and saving) the elements in blocks without any pointer adaption.

Share this post


Link to post
Share on other sites
thanks haegarr.
Then if i use triangle I can draw more than one poly at once?
Because a line of the triangle is shared?

and im not understand this:
Quote:
but build arrays of vertex attributes and push them as VBOs to the API


what are the VBOs and the attributes?
do you have a link or a book thath explain this?
Thanks.

Share this post


Link to post
Share on other sites
Quote:
what are the VBOs and the attributes?
do you have a link or a book that explain this?


If you use glBegin/glEnd, you'll have to pass the vertex coordinates and attributes like colors to the GPU each frame. This is really inefficient. VBO's allow you to pass those once and use them every frame. Here's a pdf-file about VBO's: http://developer.nvidia.com/object/using_VBOs.html

Here's a NeHe lesson about VBO's: http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=45

Share this post


Link to post
Share on other sites
But the quad strip works equals to triangle strip?
Where is better triangle strip and where is better quad strip?
i search in google but i can't find a lot.
Do you have some link on this argument?
Thanks

[Edited by - giugio on August 14, 2008 12:50:26 PM]

Share this post


Link to post
Share on other sites
Sorry if i post again for the 3rd time,but i'm fascinated by the argument.
I read about the VBO and i have two questions about

1)if i add a new mesh to the scene ,the vertex in the GPU changes,how sincronize with the graphics card VBO's?How about the add/remove vertexes process ?

2)is the strips process of quad/triangle strips convenient(and the two think work fine boot) with VBO's or the game not worth the candle?


Thanks.

Share this post


Link to post
Share on other sites
GPUs render triangles, so drivers need to split quads into 2 triangles. Best speed is hence achieved if the faces are already ready-to-use, i.e. triangles. There are many discussion whether strips are more efficient than post-T&L cache optimized lists. AFAIK the lists are winning, but I have no personal experience (i.e. time measurements) with this topic yet.

VBOs are very versatile in the sense of usage: There are 9 usage modes, look at those DYNAMIC_... vs STATIC_... vs. STREAM_... and .._DRAW vs. ..._COPY vs ..._READ parameters when invoking glBufferData. Functions exist to map vertex data from/to GPU/CPU accessible memory (heap, VRAM, ...).

In summary VBO is a complex beast. But you have to remember that VBOs are made for fast rendering, and not for editing purposes. The more "dynamic" your mesh is, the more is it likely to be rendered less speedy. But nevertheless does it work. I personally programming an engine with integrated editing purposes. I deal with up to 5 kinds of mesh representation: A topologically full featured EditMesh that comes in 2 flavors (expanded and memory friendly), a TriMesh similar to VBOs but with multiple indices, an application accessible master copy of VBO content, and the VBOs itself. Normally only the master copy (in the case of animated meshes) and the VBOs itself are available, and the other meshes appear during editing or perhaps at load-time only.

Coming to the point of updating vertices, it often happens that large portions of vertices are updated at once, e.g. skeleton animated characters. If done on the CPU, the master copy will be computed accordingly and then pushed to the GPU. For such purposes GL_STREAM_DRAW or perhaps GL_DYNAMIC_DRAW are intended. Other ways exist as well.

However, I neither claim that the way I go is the best, nor do I invite you to do the same. The solutions I implement have some constraints that are normally not part of a game, so you may find simpler solutions for your purposes. I must admit that programming such features definitely costs its time. However, I hope that my posts give you some stimulations.

Share this post


Link to post
Share on other sites
I'm not understand the response to this question:
Quote:
Original post by giugio
2)is the strips process of triangle strips convenient(and the two think work fine boot) with VBO's or the game not worth the candle?
Thanks.

if the responce is true , can you post me some documentation?at least on the theory
sorry for my english.

[Edited by - giugio on August 15, 2008 6:07:20 AM]

Share this post


Link to post
Share on other sites
I assume you're asking whether rendering tri-strips with VBOs is fine?!

Yes, you can do so, but must be aware that using strips
(a) enforces the need to _have_ strips, e.g. to implement strip generation algorithms for non-strip models,
(b) may yield in the need of more than one invocations of glDrawElements, namely if more than a single strip is used,
(c) and/or (partly alternatively to (b)) introduce degenerated triangles.

The advantage of strips is their lesser amount of vertex indices which are to be generated and pushed into the VBO. On the other hand, if not using strips but lists (i.e. each triangle is defined by its own 3 vertex indices) you can optimize the order of indices so that the resulting timing outperforms strips. You have to implement an algorithm for that optimization, of course, but on the other hand you would also need to implement an algorithm for building strips.


But, if your question addresses whether building strips is itself a convenient process when dealing with VBOs ... I don't know, because I never implemented such an algorithm. As can be seen from my answers, I personally go the way of lists.


If you mean something else, please re-formulate your question.

Share this post


Link to post
Share on other sites
very thanks haegarr.
Quote:

if not using strips but lists (i.e. each triangle is defined by its own 3 vertex indices)

i'm not understand why strips and lists can't cooperate, why i can't use a lists of strips?
this is your answer that i'm not understand
[qute]
you can optimize the order of indices so that the resulting timing outperforms strips
[/quote]


Is useless?

Share this post


Link to post
Share on other sites
Perhaps we have a misunderstanding of the term "triangle list" here...

Triangle strips and triangle lists can co-exist, of course. But you can push either a strip or a list to the API. If you have more than 1 strip or else both a strip and a list, you need to invoke glDrawElements more than once. The declaration
glDrawElements( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices )
requires a mode as the 1st parameter. It can be (besides others) GL_TRIANGLE_STRIP or else GL_TRIANGLES (for a list). And if it is GL_TRIANGLE_STRIP then the count parameter denotes the length of 1 strip.

To make it clear: A triangle list means that a sequence of indices
{ i0, i1, i2, i0, i3, i4, i5, ... }
is interpreted as
triangle 1: vertices with indices i0, i1, i2
triangle 2: vertices with indices i0, i3, i4
...
so each triplet of vertex indices addresses the vertices of a single triangle.

To understand why this can be better than triangle strips, you must have knowledge of the cache that follows the "transformation & lighting" hardware, or for short "post-T&L cache". As its name suggest, it caches vertices that are already processed. That cache isn't very big; it has thereabout 20 to 30 entries (perhaps bigger ones exist nowadays). Now, if you can apply a sort algorithm that ensures that any vertex of the mesh is not used any more after it is once forced out of the cache, you have an optimal use case. But if you use strips, you have another force that influences your indexing scheme, and perhaps the need to introduce additional vertices (for degeneration) that seizes cache places, and all that may lead to sub-optimality.

I don't say "strips are evil". I say that triangle lists can be better. Whether or not depends on the mesh and its vertex indexing.

Share this post


Link to post
Share on other sites
Thanks.
I'm try to compile an example from the "beginning opengl game programming" , chapther 10 in which use the list,but the frame rating in my pc(from the 2000)is equal or low slower than not use it than with strips.
I repeat,is a 2000 pc, can be?.
by

[Edited by - giugio on August 15, 2008 12:07:50 PM]

Share this post


Link to post
Share on other sites

This topic is 3441 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
       
      #define NUM_LIGHTS 2
      struct Light
      {
          vec3 position;
          vec3 diffuse;
          float attenuation;
      };
      uniform Light Lights[NUM_LIGHTS];
       
       
    • By pr033r
      Hello,
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article (http://natureofcode.com/book/chapter-6-autonomous-agents/) inspirate from another code (here: https://github.com/jyanar/Boids/tree/master/src) but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch): https://github.com/pr033r/BachelorProject/tree/Optimalizing
      Exe file (if you want to look) and models folder (for those who will download the sources):
      http://leteckaposta.cz/367190436
      Thanks for any help...

    • By Andrija
      I am currently trying to implement shadow mapping into my project , but although i can render my depth map to the screen and it looks okay , when i sample it with shadowCoords there is no shadow.
      Here is my light space matrix calculation
      mat4x4 lightViewMatrix; vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0], SUN_OFFSET * the_sun->direction[1], SUN_OFFSET * the_sun->direction[2]}; mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up); mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix); I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
      the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
      player->pos is the camera position in world space
      the light projection matrix is calculated like this:
      mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR); Shadow vertex shader:
      uniform mat4 light_space_matrix; void main() { gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f); } Shadow fragment shader:
      out float fragDepth; void main() { fragDepth = gl_FragCoord.z; } I am using deferred rendering so i have all my world positions in the g_positions buffer
      My shadow calculation in the deferred fragment shader:
      float get_shadow_fac(vec4 light_space_pos) { vec3 shadow_coords = light_space_pos.xyz / light_space_pos.w; shadow_coords = shadow_coords * 0.5 + 0.5; float closest_depth = texture(shadow_map, shadow_coords.xy).r; float current_depth = shadow_coords.z; float shadow_fac = 1.0; if(closest_depth < current_depth) shadow_fac = 0.5; return shadow_fac; } I call the function like this:
      get_shadow_fac(light_space_matrix * vec4(position,1.0)); Where position is the value i got from sampling the g_position buffer
      Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
      sorry because of the compression , the black smudges are trees ... https://i.stack.imgur.com/T43aK.jpg
      EDIT: Depth texture attachment:
      glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24,fbo->width,fbo->height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo->depthTexture, 0);
  • Popular Now