Jump to content
  • Advertisement
Sign in to follow this  

OpenGL Converting D3D vertex buffers to OpenGL vertex arrays...

This topic is 3963 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

Hi, Firstly, apologies if this is in the wrong forum - moderators, feel free to move it if it is, but given that it mentions Direct3D and OpenGL, I didn't know which forum to put it in, and I didn't want to cross-post. Secondly, apologies if this seems like a really obvious question. It kinda does, to me, but I couldn't find any threads which answered when I searched the forums. So, I've got a bit of code I found online which I'm playing around with, which renders stuff using DirectX 8, and I'm trying to abstract the rendering calls to a common interface so I can have the same code run on an OpenGL renderer. I'm pretty comfortable with OpenGL, not so comfortable with DirectX, although I do know a little bit. The interface has methods, which do roughly the following. This isn't the exact or complete code because I've just tried to show the interesting stuff - I can post the full source if it'll help.
void CreateVertexBuffer(UINT nLength, UINT nVertexSize, DWORD FVF, D3DPOOL Pool)
{
    // m_pD3DDevice being an IDirect3DDevice8
    m_pD3DDevice->CreateVertexBuffer(nLength*nVertexSize,
		D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY, FVF,
		Pool, &m_pVertexBuffer);

    m_pD3DDevice->SetStreamSource(0, m_pVertexBuffer, nVertexSize);
    m_pD3DDevice->SetVertexShader(FVF);
}

void LockVertexBuffer(UINT nVertices, BYTE **ppVertices)
{
    m_pVertexBuffer->Lock(0, nVertices*m_nVertexSize, ppVertices, D3DLOCK_DISCARD);
}

void UnlockVertexBuffer()
{
    m_pVertexBuffer->Unlock();
}

// ... Similar functions for the index buffers - you get the picture ...

void DrawVertexBuffer(int numVerts, int numIndeces)
{
    m_pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, numVerts, 0, numIndeces/3);
}
The program calls CreateVertexBuffer once on initialisation, and then several times a frame it calls LockVertexBuffer, fills the resulting buffer with triangle data, calls UnLockVertexBuffer then DrawVertexBuffer, then locks the buffers again to generate more vertices, and so on. So, how to port this to OpenGL? I've got CreateVertexBuffer just setting up an array of vertices, LockVertexBuffer trying to point *ppVertices at that array and calling glLockArraysEXT(0, nVertices). UnlockVertexBuffer does nothing but call glUnlockArraysEXT(), and DrawVertexBuffer sets up the client states, does a glDrawElements, and disables the client states again. This doesn't seem to work, it crashes in annoying ways which don't give me a callstack I understand or the source code for the point where the crash occurs. I suspect this is because I'm misunderstanding the differences between D3D vertex buffers and OpenGL vertex arrays. If I understand correctly, locking a vertex buffer in D3D with the D3DLOCK_DISCARD allocates memory for a new buffer to write to every time you call it (giving you a pointer to that memory), and then automagically cleaning that memory up somehow at a later date when it's not being used (or is it done in the m_pVertexBuffer->Unlock?). Whereas, my OpenGL implementation sets up one vertex array to rule them all, and just lets the program write to it, render it, write to it again, render it... I'm not sure what needs to change in my OpenGL implementation to get the same behaviour as the D3D version. What do Direct3D vertex buffers do that OpenGL vertex arrays don't? And how would I go about adding that functionality to my OpenGL implementation?

Share this post


Link to post
Share on other sites
Advertisement
Hi ElectroDruid,

I don't know much about DX so i'm shooting in the dark here. Here is how i think it should be done :

1) CreateVertexBuffer should create a VBO or allocate a chunk of system memory depending on the value of the pool variable. Also, usage (which is hard-coded in your case) can be given as a hint to the driver when creating the VBO.

2) LockVertexBuffer should map the VBO using glMapBuffer. glLockArrays() is from the GL_EXT_compiled_vertex_arrays extension which is deprecated iirc. In D3D when you lock a VB, you are requesting a pointer in order to write to it, as you described. The equivalent functionality in GL is given by glMapBuffer.

3) UnlockVertexBuffer should unmap the VBO in order to be able to use it for rendering.

4) DrawVertexBuffer should set all the glXXXPointer variables and enable all the required client state. I'm not really sure, but i suspect that in the D3D case you posted, this happens in the CreateVertexBuffer function. Maybe because the vertex format is needed to be known when locking the buffer? I'm not sure.
Finally you can safely call glDrawElements.

Hope that helps. As i said i don't know much about DX, so if anyone find any mistakes in the above descriptions, please correct me.

HellRaiZer

EDIT : I think, until now, there is no flag in GL equivalent to D3DLOCK_DISCARD, and other similar flags. I think this is because you can't specify the size of the memory you are going to modify when locking/mapping the VB. IIRC this will be added in Long Peaks. Check the latest OGL Pipeline article for more info.

Share this post


Link to post
Share on other sites
Quote:
Original post by HellRaiZer
EDIT : I think, until now, there is no flag in GL equivalent to D3DLOCK_DISCARD, and other similar flags.
You can perform a discard lock in OGL by calling BufferData with a NULL pointer.

Share this post


Link to post
Share on other sites
hey

Quote:
The program calls CreateVertexBuffer once on initialisation, and then several times a frame it calls LockVertexBuffer, fills the resulting buffer with triangle data, calls UnLockVertexBuffer then DrawVertexBuffer, then locks the buffers again to generate more vertices, and so on.


I too know very little about Direct3D. But I wonder, are you rendering static objects? and if so then why must you keep filling the Vertex Buffer several times each frame? Do you use a single Vertex Buffer to render multiple objects?

Anyhows... with Vertex Buffer Objects in OpenGL, for static objects you only need to generate the Vertex Buffer Object, and load in the Vertex Data once, which is stored in Video Memory. You then can render them very much alike regular Vertex Arrays in OpenGL.

Note, you must use a separate, and different target/type of Vertex Buffer Object for Vertex Indices (ELEMENT_ARRAY_BUFFER, rather than ARRAY_BUFFER).

You allocate/load in the Vertex Data with glBufferData(), and at this time you specify the data usage, whether it be STATIC/DYNAMIC/STREAM along with READ/COPY/DRAW flags. You can then update the data via glBufferSubData().

You can also gain direct access to data via glMapBuffer()/glUnmapBuffer(), which returns a pointer to the Vertex Data.

BTW, it's recommended that you use glDrawRangeElements(), rather than glDrawElements() when drawing Vertex Buffer Objects, which you can read about in the article I link to below.

Finally, rather than try and learn/understand from my brief explainations, I recommend you checkout THIS.

edit
To conclude, I made some pesudo code...

glGenBuffers...
glBindBuffer...
glBufferData...

I think the official OpenGL API is HERE.


// init vertex buffer object...
// note, this would be done when you load your geometry

// first you generate your vertex buffer object via...
void glGenBuffers(GLsizei n, GLuint * buffers)

// then you bind this buffer via... void glBindBuffer(GLenum target, GLuint buffer)
void glBindBuffer(GLenum target, GLuint buffer)

// then you allocate/load data into this buffer via...
// note, "GLenum target" set to GL_ARRAY_BUFFER for vertex data, and GL_ELEMENT_ARRAY_BUFFER for vertex indices
void glBufferData(GLenum target, GLsizeiptr size, const GLvoid * data, GLenum usage)

// and remember to unbind your vertex buffer object via passing 0 for "uint buffer"...
void glBindBuffer(GLenum target, GLuint buffer)

// and later on when it comes to drawing...
// you draw alike regular opengl vertex arrays, except you specify offset relative to each vertex buffer object
// note, this would obviously be done in a separate function

// enable vertex arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

// bind your vertex data VBO
void glBindBuffer(GL_ARRAY_BUFFER, GLuint buffer);

// set your vertex array pointers
// note, instead of pointer you use offset relative to origin of VBO data
glVertexPointer(3, GL_FLOAT, 0, (const GLvoid*)0);
glNormalPointer(GL_FLOAT, 0, (const GLvoid*)normalOffset);
glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid*)texCoordOffset);

// remember to unbind your VBO
glBindBuffer(GL_ARRAY_BUFFER_ARB, 0);

// now bind your vertex indices VBO
void glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, GLuint buffer)

// draw vertex array
// note, again instead of pointer you use offset relative to origin of VBO data
// note, use glDrawRangeElements() for best performance
void glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, (const GLvoid*)indexOffset);

// again, remember to unbind your VBO
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);

// disable your vertex arrays
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);






Please correct me if I have made any mistakes. I hope this helps :).

cya

[Edited by - yosh64 on July 11, 2007 10:08:29 AM]

Share this post


Link to post
Share on other sites
Wow... Okay, I have to hold my hands up and admit that I'm a bit out of my depth here. I've not used any of the advanced (read: not immediate mode) stuff in OpenGL since version 1.2 (hence the use of the deprecated extensions in my code). I don't know what's new since then and I'm kinda lost.

VBOs, glMapBuffer, glBufferData, glBufferSubData, glMapBuffer, glUnmapBuffer... All of these things are new to me. I've been working as a gameplay coder on consoles for nearly 5 years now, and haven't done any graphics programming in that time, so I'm clearly pretty out of touch with how the APIs work nowadays. This is a pet project on the PC, so I need to play catch-up.

I looked on NeHe but didn't see anything which might be of use - can someone point me to any kind of resource/tutorial/example code/whatever which demonstrates this new (to me at least) OpenGL functionality in action, so I can see what makes it tick?

Oh, and:

Quote:
But I wonder, are you rendering static objects? and if so then why must you keep filling the Vertex Buffer several times each frame? Do you use a single Vertex Buffer to render multiple objects?


You hit the nail on the head, kinda. I'm not rendering static objects, I'm rendering very dynamic ones (metaballs, specifically), so I'm needing to construct new meshes every frame. I mean meshes as a plural in the sense that I want to make sure that (for example) if two metaballs seperate, and form seperate unconnected meshes, I want to render both of them rather than have one of them suddenly vanish. I'm trying to use a single vertex buffer for everything, even though I'm aware that it's probably wrong, because that's the only way I know about how to do this kind of thing. It strikes me that the most efficient thing would be to do the maths to calculate a bunch of triangles (connected or not), and then just pipe all the triangles to get rendered at the same time. I'm aware that this might not work, and that I might need to render each mesh seperately, but right now I'm just trying to get *something* onscreen without the program crashing.

I guess what I really need (and I will thank my lucky stars if such a thing exists, although I suspect it doesn't) is something like a piece of source code (a "Rosetta Stone", if you will) which draws something very simple (a sphere, or a cube) using Direct3D vertex buffers, and can do the same thing with the same results in OpenGL using vertex arrays, or VBOs, or whatever the best equivalent is. Does such a thing exist?

Share this post


Link to post
Share on other sites
I am not sure what your OpenGL implementation looks like, but I have some comments about your original post:

If you allocate the vertex buffer in D3DPOOL_DEFAULT, Direct3D tries to put it in video memory or AGP memory (unless you're using software vertex processing, then it has to be in system memory). Either way, the memory is not directly accessible by you.

When you call Lock() on the buffer, Direct3D maps the vertex buffer to a special part of memory; when you perform a write, it doesn't go to system memory but is routed through an I/O bus and to the actual location of the buffer. When you call Unlock(), it unmaps the memory so that you no longer have direct access to it. I think that if you're getting a crash, it might be because you're keeping around this pointer.

With D3DLOCK_DISCARD, Direct3D discards the entire contents of the vertex buffer. The old vertex buffer could be floating around somewhere; your video card could be rendering from it right now. You would never know, because it's not in your control anymore. Instead, you get mapped a new vertex buffer that has nothing to do with your old buffer. This means all the data you uploaded before is gone, too.

Share this post


Link to post
Share on other sites
Quote:
Original post by ElectroDruid
I looked on NeHe but didn't see anything which might be of use - can someone point me to any kind of resource/tutorial/example code/whatever which demonstrates this new (to me at least) OpenGL functionality in action, so I can see what makes it tick?


Can't point you to any direct turotials, but whenever i'm interested in seeing whats new or getting to grips with an opengl extension i usually check out Delphi3D first and its extension list each with full spec. Although i guess its no different to opengl.org list. They canbe a bit hard to get into, but after a while they begin to make sense.

I guess you could also search on thos sites for more specific information such as tutorials.

Share this post


Link to post
Share on other sites
hey

Quote:
I'm trying to use a single vertex buffer for everything, even though I'm aware that it's probably wrong, because that's the only way I know about how to do this kind of thing.

I don't see anything wrong with doing this, and are sure it's quite possible. When loading the scene, I would just allocate one Vertex Buffer Object, large enough to hold the maximum amount of vertex data you will need.

Ohh, if you would prefer to update your vertex data in system memory, then when it comes to rendering you can just bind your VBO, and use glBufferSubData() to copy and update your Vertex Buffer Object.

Remember you will also need to update your vertex indices, or maybe just change the number of elements to draw, if I make any sense?

Finally, remember for getting started you may prefer not even to use Vertex Buffer Objects, and/or even Vertex Arrays, and go back to the basics of glBegin()/glEnd(), hehe.

Here are a couple of tutorials I goog'd on Vertex Buffer Objects, THIS, and NeHe lesson 45. But I think you may need to refer back to that original link on Vertex Buffer Objects I posted, or the OpenGL API or something.

edit
You can find an example of both Vertex Arrays, and Vertex Buffer Objects (refered to as AGP Memory) on page 5 of the OpenGL section of ultimategameprogramming.com. You can probably also find a simular example for DirectX at ultimategameprogramming.com also.

cyas

[Edited by - yosh64 on July 12, 2007 1:10:25 AM]

Share this post


Link to post
Share on other sites
Hi,

Thanks for all the replies and links, I think I'm starting to get a handle on how VBOs work now - although I'm clearly not quite there yet :) I've got code which compiles and runs without crashing, but it's not drawing anything. I've tried the usual testing stuff (setting a non-black glClearColour, disabling culling, lighting, texturing and alpha blending, triple-checking my camera position, orientation, clip planes and FOV to make sure it matches what the Direct3D renderer is doing, and drawing an immediate mode test quad to prove that I can see it), and all of that seems to work fine. The rest of the program hasn't changed, and it seems to be filling the vertex and index arrays with sensible values, and telling the renderer to draw about the number of polygons I'd expect. I just don't see any polys, and I'm at a bit of a loss as to what could be going wrong.

I've ended up trying to use glDrawArrays for the rendering, because glDrawElements was crashing, and I can't get my compiler to accept glDrawRangedElements for some reason. There's also potentially some weirdness with the way I'm using glBindBufferARB in my Lock/Unlock functions, but I'm still not 100% sure how glBindBufferARB works. If someone could take a quick look at what my code is doing, and give me an idea about what might be going wrong, that would be great.

GLuint vboVerts = 0;
GLuint vboIndeces = 0;
SVertex* mpVertexBuffer;
UINT* mpIndexBuffer;

struct SVertex
{
Vector3f v; // Vertex
Vector3f n; // Normal
Vector2f t; // Texture coordinates (currently not used)
};

void Initialize()
{
// ... Set up the window, the openGL extensions, and set some default GL states
// (lighting, texturing and backface culling turned off for testing, etc) ...

CreateVertexBuffer(MAX_VERTICES, sizeof(SVertex));
CreateIndexBuffer(MAX_INDICES);
}

void Uninitialize()
{
delete[] mpVertexBuffer;
delete[] mpIndexBuffer;

glDeleteBuffersARB(1, &vboVerts);
glDeleteBuffersARB(1, &vboIndeces);
}

void CreateVertexBuffer(UINT nLength, UINT nVertexSize)
{
mpVertexBuffer = new SVertex[nLength];
glGenBuffersARB(1, &vboVerts);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vboVerts);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, nLength * nVertexSize, mpVertexBuffer, GL_DYNAMIC_DRAW_ARB);
}

void LockVertexBuffer(UINT nVertices, BYTE **ppVertices)
{
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vboVerts); // Not sure if this should be here
(BYTE*)(*ppVertices) = (BYTE*)glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_READ_WRITE_ARB);
mpVertexBuffer = (SVertex*)(*ppVertices);
}

void UnlockVertexBuffer()
{
glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); // Not sure if this should be here
}

void CreateIndexBuffer(UINT nLength)
{
mpIndexBuffer = new UINT[nLength];
glGenBuffersARB(1, &vboIndeces);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vboIndeces);
glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, nLength * sizeof(UINT), mpIndexBuffer, GL_DYNAMIC_DRAW_ARB);
}

void LockIndexBuffer(UINT nIndices, BYTE **ppIndices)
{
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vboIndeces); // Not sure if this should be here
(BYTE*)(*ppIndices) = (BYTE*)glMapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, GL_READ_WRITE_ARB);
mpIndexBuffer = (UINT*)(*ppIndices);
}

void UnlockIndexBuffer()
{
glUnmapBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); // Not sure if this should be here
}

void DrawVertexBuffer(int numVerts, int numIndeces)
{
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vboVerts);
glNormalPointer(GL_FLOAT, sizeof(SVertex), &mpVertexBuffer[0].n);
glVertexPointer(3, GL_FLOAT, sizeof(SVertex), &mpVertexBuffer[0].v);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vboIndeces);
glIndexPointer(GL_UNSIGNED_SHORT, 0, 0);

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);

// glDrawElements(GL_TRIANGLES, numIndeces, GL_UNSIGNED_INT, mpIndexBuffer); // This crashes the program
// glDrawRangeElements(GL_TRIANGLES, 0, numIndeces, numIndeces, GL_UNSIGNED_INT, mpIndexBuffer); // I couldn't get this to compile
glDrawArrays( GL_TRIANGLES, 0, numIndeces);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}



Usage: The rest of the code is doing stuff in the following order, about half a dozen times per frame...

LockVertexBuffer();
LockIndexBuffer();
... Generate a bunch of vertex/index data ...
UnlockVertexBuffer();
UnlockIndexBuffer();
DrawVertexBuffer();

Any ideas?

Share this post


Link to post
Share on other sites
I think there are a couple of problems with the code you posted.

1) You don't have to allocate memory for passing it to the glBufferData() function. You can pass NULL in there. This way, when you Lock the VB/IB you won't overwrite the pointer value in 'mpVertexBuffer' and 'mpIndexBuffer'.

2) About your comments/questions in the Lock functions. Yes you have to bind the buffer before mapping it. OTOH there is no need to bind a zero buffer when unmapping, but that's ok if you re-bind it later for using it.

3) What's the value of 'mpVertexBuffer' when specifying glXXXPointer in DrawVertexBuffer? If it holds the last value from the Lock function, then this is wrong. If it's NULL then it should work. The point is that when using VBOs you don't specify a true pointer in memory, but an offset in the VB.

4) glIndexPointer() isn't responsible for setting the triangle indices pointer. It is related to per-vertex indexed color, which you don't need. In order for the glDrawElements to work you have to bind the index buffer (as you do) and then pass an offset in the IBO as the last parameter in the glDrawElements() call.

The DrawVertexBuffer() function should look something like this :

void DrawVertexBuffer(int numVerts, int numIndeces)
{
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vboVerts);
glNormalPointer(GL_FLOAT, sizeof(SVertex), (void*)(0 + sizeof(Vector3f)));
glVertexPointer(3, GL_FLOAT, sizeof(SVertex), (void*)(0));
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vboIndeces);

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);

glDrawElements(GL_TRIANGLES, numIndeces, GL_UNSIGNED_INT, 0);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
}



I hope i haven't done any mistakes, and the above makes sense.

HellRaiZer

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By mmmax3d
      Hi everyone,
      I would need some assistance from anyone who has a similar experience
      or a nice idea!
      I have created a skybox (as cube) and now I need to add a floor/ground.
      The skybox is created from cubemap and initially it was infinite.
      Now it is finite with a specific size. The floor is a quad in the middle
      of the skybox, like a horizon.
      I have two problems:
      When moving the skybox upwards or downwards, I need to
      sample from points even above the horizon while sampling
      from the botton at the same time.  I am trying to create a seamless blending of the texture
      at the points of the horizon, when the quad is connected
      to the skybox. However, I get skew effects. Does anybody has done sth similar?
      Is there any good practice?
      Thanks everyone!
    • By mmmax3d
      Hi everyone,
      I would need some assistance from anyone who has a similar experience
      or a nice idea!
      I have created a skybox (as cube) and now I need to add a floor/ground.
      The skybox is created from cubemap and initially it was infinite.
      Now it is finite with a specific size. The floor is a quad in the middle
      of the skybox, like a horizon.
      I have two problems:
      When moving the skybox upwards or downwards, I need to
      sample from points even above the horizon while sampling
      from the botton at the same time.  I am trying to create a seamless blending of the texture
      at the points of the horizon, when the quad is connected
      to the skybox. However, I get skew effects. Does anybody has done sth similar?
      Is there any good practice?
      Thanks everyone!
    • By iArtist93
      I'm trying to implement PBR into my simple OpenGL renderer and trying to use multiple lighting passes, I'm using one pass per light for rendering as follow:
      1- First pass = depth
      2- Second pass = ambient
      3- [3 .. n] for all the lights in the scene.
      I'm using the blending function glBlendFunc(GL_ONE, GL_ONE) for passes [3..n], and i'm doing a Gamma Correction at the end of each fragment shader.
      But i still have a problem with the output image it just looks noisy specially when i'm using texture maps.
      Is there anything wrong with those steps or is there any improvement to this process?
    • By babaliaris
      Hello Everyone!
      I'm learning openGL, and currently i'm making a simple 2D game engine to test what I've learn so far.  In order to not say to much, i made a video in which i'm showing you the behavior of the rendering.
      Video: 
       
      What i was expecting to happen, was the player moving around. When i render only the player, he moves as i would expect. When i add a second Sprite object, instead of the Player, this new sprite object is moving and finally if i add a third Sprite object the third one is moving. And the weird think is that i'm transforming the Vertices of the Player so why the transformation is being applied somewhere else?
       
      Take a look at my code:
      Sprite Class
      (You mostly need to see the Constructor, the Render Method and the Move Method)
      #include "Brain.h" #include <glm/gtc/matrix_transform.hpp> #include <vector> struct Sprite::Implementation { //Position. struct pos pos; //Tag. std::string tag; //Texture. Texture *texture; //Model matrix. glm::mat4 model; //Vertex Array Object. VertexArray *vao; //Vertex Buffer Object. VertexBuffer *vbo; //Layout. VertexBufferLayout *layout; //Index Buffer Object. IndexBuffer *ibo; //Shader. Shader *program; //Brains. std::vector<Brain *> brains; //Deconstructor. ~Implementation(); }; Sprite::Sprite(std::string image_path, std::string tag, float x, float y) { //Create Pointer To Implementaion. m_Impl = new Implementation(); //Set the Position of the Sprite object. m_Impl->pos.x = x; m_Impl->pos.y = y; //Set the tag. m_Impl->tag = tag; //Create The Texture. m_Impl->texture = new Texture(image_path); //Initialize the model Matrix. m_Impl->model = glm::mat4(1.0f); //Get the Width and the Height of the Texture. int width = m_Impl->texture->GetWidth(); int height = m_Impl->texture->GetHeight(); //Create the Verticies. float verticies[] = { //Positions //Texture Coordinates. x, y, 0.0f, 0.0f, x + width, y, 1.0f, 0.0f, x + width, y + height, 1.0f, 1.0f, x, y + height, 0.0f, 1.0f }; //Create the Indicies. unsigned int indicies[] = { 0, 1, 2, 2, 3, 0 }; //Create Vertex Array. m_Impl->vao = new VertexArray(); //Create the Vertex Buffer. m_Impl->vbo = new VertexBuffer((void *)verticies, sizeof(verticies)); //Create The Layout. m_Impl->layout = new VertexBufferLayout(); m_Impl->layout->PushFloat(2); m_Impl->layout->PushFloat(2); m_Impl->vao->AddBuffer(m_Impl->vbo, m_Impl->layout); //Create the Index Buffer. m_Impl->ibo = new IndexBuffer(indicies, 6); //Create the new shader. m_Impl->program = new Shader("Shaders/SpriteShader.shader"); } //Render. void Sprite::Render(Window * window) { //Create the projection Matrix based on the current window width and height. glm::mat4 proj = glm::ortho(0.0f, (float)window->GetWidth(), 0.0f, (float)window->GetHeight(), -1.0f, 1.0f); //Set the MVP Uniform. m_Impl->program->setUniformMat4f("u_MVP", proj * m_Impl->model); //Run All The Brains (Scripts) of this game object (sprite). for (unsigned int i = 0; i < m_Impl->brains.size(); i++) { //Get Current Brain. Brain *brain = m_Impl->brains[i]; //Call the start function only once! if (brain->GetStart()) { brain->SetStart(false); brain->Start(); } //Call the update function every frame. brain->Update(); } //Render. window->GetRenderer()->Draw(m_Impl->vao, m_Impl->ibo, m_Impl->texture, m_Impl->program); } void Sprite::Move(float speed, bool left, bool right, bool up, bool down) { if (left) { m_Impl->pos.x -= speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(-speed, 0, 0)); } if (right) { m_Impl->pos.x += speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(speed, 0, 0)); } if (up) { m_Impl->pos.y += speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(0, speed, 0)); } if (down) { m_Impl->pos.y -= speed; m_Impl->model = glm::translate(m_Impl->model, glm::vec3(0, -speed, 0)); } } void Sprite::AddBrain(Brain * brain) { //Push back the brain object. m_Impl->brains.push_back(brain); } pos *Sprite::GetPos() { return &m_Impl->pos; } std::string Sprite::GetTag() { return m_Impl->tag; } int Sprite::GetWidth() { return m_Impl->texture->GetWidth(); } int Sprite::GetHeight() { return m_Impl->texture->GetHeight(); } Sprite::~Sprite() { delete m_Impl; } //Implementation Deconstructor. Sprite::Implementation::~Implementation() { delete texture; delete vao; delete vbo; delete layout; delete ibo; delete program; }  
      Renderer Class
      #include "Renderer.h" #include "Error.h" Renderer::Renderer() { } Renderer::~Renderer() { } void Renderer::Draw(VertexArray * vao, IndexBuffer * ibo, Texture *texture, Shader * program) { vao->Bind(); ibo->Bind(); program->Bind(); if (texture != NULL) texture->Bind(); GLCall(glDrawElements(GL_TRIANGLES, ibo->GetCount(), GL_UNSIGNED_INT, NULL)); } void Renderer::Clear(float r, float g, float b) { GLCall(glClearColor(r, g, b, 1.0)); GLCall(glClear(GL_COLOR_BUFFER_BIT)); } void Renderer::Update(GLFWwindow *window) { /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); }  
      Shader Code
      #shader vertex #version 330 core layout(location = 0) in vec4 aPos; layout(location = 1) in vec2 aTexCoord; out vec2 t_TexCoord; uniform mat4 u_MVP; void main() { gl_Position = u_MVP * aPos; t_TexCoord = aTexCoord; } #shader fragment #version 330 core out vec4 aColor; in vec2 t_TexCoord; uniform sampler2D u_Texture; void main() { aColor = texture(u_Texture, t_TexCoord); } Also i'm pretty sure that every time i'm hitting the up, down, left and right arrows on the keyboard, i'm changing the model Matrix of the Player and not the others.
       
      Window Class:
      #include "Window.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Error.h" #include "Renderer.h" #include "Scene.h" #include "Input.h" //Global Variables. int screen_width, screen_height; //On Window Resize. void OnWindowResize(GLFWwindow *window, int width, int height); //Implementation Structure. struct Window::Implementation { //GLFW Window. GLFWwindow *GLFW_window; //Renderer. Renderer *renderer; //Delta Time. double delta_time; //Frames Per Second. int fps; //Scene. Scene *scnene; //Input. Input *input; //Deconstructor. ~Implementation(); }; //Window Constructor. Window::Window(std::string title, int width, int height) { //Initializing width and height. screen_width = width; screen_height = height; //Create Pointer To Implementation. m_Impl = new Implementation(); //Try initializing GLFW. if (!glfwInit()) { std::cout << "GLFW could not be initialized!" << std::endl; std::cout << "Press ENTER to exit..." << std::endl; std::cin.get(); exit(-1); } //Setting up OpenGL Version 3.3 Core Profile. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); /* Create a windowed mode window and its OpenGL context */ m_Impl->GLFW_window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL); if (!m_Impl->GLFW_window) { std::cout << "GLFW could not create a window!" << std::endl; std::cout << "Press ENTER to exit..." << std::endl; std::cin.get(); glfwTerminate(); exit(-1); } /* Make the window's context current */ glfwMakeContextCurrent(m_Impl->GLFW_window); //Initialize GLEW. if(glewInit() != GLEW_OK) { std::cout << "GLEW could not be initialized!" << std::endl; std::cout << "Press ENTER to exit..." << std::endl; std::cin.get(); glfwTerminate(); exit(-1); } //Enabling Blending. GLCall(glEnable(GL_BLEND)); GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); //Setting the ViewPort. GLCall(glViewport(0, 0, width, height)); //**********Initializing Implementation**********// m_Impl->renderer = new Renderer(); m_Impl->delta_time = 0.0; m_Impl->fps = 0; m_Impl->input = new Input(this); //**********Initializing Implementation**********// //Set Frame Buffer Size Callback. glfwSetFramebufferSizeCallback(m_Impl->GLFW_window, OnWindowResize); } //Window Deconstructor. Window::~Window() { delete m_Impl; } //Window Main Loop. void Window::MainLoop() { //Time Variables. double start_time = 0, end_time = 0, old_time = 0, total_time = 0; //Frames Counter. int frames = 0; /* Loop until the user closes the window */ while (!glfwWindowShouldClose(m_Impl->GLFW_window)) { old_time = start_time; //Total time of previous frame. start_time = glfwGetTime(); //Current frame start time. //Calculate the Delta Time. m_Impl->delta_time = start_time - old_time; //Get Frames Per Second. if (total_time >= 1) { m_Impl->fps = frames; total_time = 0; frames = 0; } //Clearing The Screen. m_Impl->renderer->Clear(0, 0, 0); //Render The Scene. if (m_Impl->scnene != NULL) m_Impl->scnene->Render(this); //Updating the Screen. m_Impl->renderer->Update(m_Impl->GLFW_window); //Increasing frames counter. frames++; //End Time. end_time = glfwGetTime(); //Total time after the frame completed. total_time += end_time - start_time; } //Terminate GLFW. glfwTerminate(); } //Load Scene. void Window::LoadScene(Scene * scene) { //Set the scene. m_Impl->scnene = scene; } //Get Delta Time. double Window::GetDeltaTime() { return m_Impl->delta_time; } //Get FPS. int Window::GetFPS() { return m_Impl->fps; } //Get Width. int Window::GetWidth() { return screen_width; } //Get Height. int Window::GetHeight() { return screen_height; } //Get Input. Input * Window::GetInput() { return m_Impl->input; } Renderer * Window::GetRenderer() { return m_Impl->renderer; } GLFWwindow * Window::GetGLFWindow() { return m_Impl->GLFW_window; } //Implementation Deconstructor. Window::Implementation::~Implementation() { delete renderer; delete input; } //OnWindowResize void OnWindowResize(GLFWwindow *window, int width, int height) { screen_width = width; screen_height = height; //Updating the ViewPort. GLCall(glViewport(0, 0, width, height)); }  
      Brain Class
      #include "Brain.h" #include "Sprite.h" #include "Window.h" struct Brain::Implementation { //Just A Flag. bool started; //Window Pointer. Window *window; //Sprite Pointer. Sprite *sprite; }; Brain::Brain(Window *window, Sprite *sprite) { //Create Pointer To Implementation. m_Impl = new Implementation(); //Initialize Implementation. m_Impl->started = true; m_Impl->window = window; m_Impl->sprite = sprite; } Brain::~Brain() { //Delete Pointer To Implementation. delete m_Impl; } void Brain::Start() { } void Brain::Update() { } Window * Brain::GetWindow() { return m_Impl->window; } Sprite * Brain::GetSprite() { return m_Impl->sprite; } bool Brain::GetStart() { return m_Impl->started; } void Brain::SetStart(bool value) { m_Impl->started = value; } Script Class (Its a Brain Subclass!!!)
      #include "Script.h" Script::Script(Window *window, Sprite *sprite) : Brain(window, sprite) { } Script::~Script() { } void Script::Start() { std::cout << "Game Started!" << std::endl; } void Script::Update() { Input *input = this->GetWindow()->GetInput(); Sprite *sp = this->GetSprite(); //Move this sprite. this->GetSprite()->Move(200 * this->GetWindow()->GetDeltaTime(), input->GetKeyDown("left"), input->GetKeyDown("right"), input->GetKeyDown("up"), input->GetKeyDown("down")); std::cout << sp->GetTag().c_str() << ".x = " << sp->GetPos()->x << ", " << sp->GetTag().c_str() << ".y = " << sp->GetPos()->y << std::endl; }  
      Main:
      #include "SpaceShooterEngine.h" #include "Script.h" int main() { Window w("title", 600,600); Scene *scene = new Scene(); Sprite *player = new Sprite("Resources/Images/player.png", "Player", 100,100); Sprite *other = new Sprite("Resources/Images/cherno.png", "Other", 400, 100); Sprite *other2 = new Sprite("Resources/Images/cherno.png", "Other", 300, 400); Brain *brain = new Script(&w, player); player->AddBrain(brain); scene->AddSprite(player); scene->AddSprite(other); scene->AddSprite(other2); w.LoadScene(scene); w.MainLoop(); return 0; }  
       
      I literally can't find what is wrong. If you need more code, ask me to post it. I will also attach all the source files.
      Brain.cpp
      Error.cpp
      IndexBuffer.cpp
      Input.cpp
      Renderer.cpp
      Scene.cpp
      Shader.cpp
      Sprite.cpp
      Texture.cpp
      VertexArray.cpp
      VertexBuffer.cpp
      VertexBufferLayout.cpp
      Window.cpp
      Brain.h
      Error.h
      IndexBuffer.h
      Input.h
      Renderer.h
      Scene.h
      Shader.h
      SpaceShooterEngine.h
      Sprite.h
      Texture.h
      VertexArray.h
      VertexBuffer.h
      VertexBufferLayout.h
      Window.h
    • By Cristian Decu
      Hello fellow programmers,
      For a couple of days now i've decided to build my own planet renderer just to see how floating point precision issues
      can be tackled. As you probably imagine, i've quickly faced FPP issues when trying to render absurdly large planets.
       
      I have used the classical quadtree LOD approach;
      I've generated my grids with 33 vertices, (x: -1 to 1, y: -1 to 1, z = 0).
      Each grid is managed by a TerrainNode class that, depending on the side it represents (top, bottom, left right, front, back),
      creates a special rotation-translation matrix that moves and rotates the grid away from the origin so that when i finally
      normalize all the vertices on my vertex shader i can get a perfect sphere.
      T = glm::translate(glm::dmat4(1.0), glm::dvec3(0.0, 0.0, 1.0)); R = glm::rotate(glm::dmat4(1.0), glm::radians(180.0), glm::dvec3(1.0, 0.0, 0.0)); sides[0] = new TerrainNode(1.0, radius, T * R, glm::dvec2(0.0, 0.0), new TerrainTile(1.0, SIDE_FRONT)); T = glm::translate(glm::dmat4(1.0), glm::dvec3(0.0, 0.0, -1.0)); R = glm::rotate(glm::dmat4(1.0), glm::radians(0.0), glm::dvec3(1.0, 0.0, 0.0)); sides[1] = new TerrainNode(1.0, radius, R * T, glm::dvec2(0.0, 0.0), new TerrainTile(1.0, SIDE_BACK)); // So on and so forth for the rest of the sides As you can see, for the front side grid, i rotate it 180 degrees to make it face the camera and push it towards the eye;
      the back side is handled almost the same way only that i don't need to rotate it but simply push it away from the eye.
      The same technique is applied for the rest of the faces (obviously, with the proper rotations / translations).
      The matrix that result from the multiplication of R and T (in that particular order) is send to my vertex shader as `r_Grid'.
      // spherify vec3 V = normalize((r_Grid * vec4(r_Vertex, 1.0)).xyz); gl_Position = r_ModelViewProjection * vec4(V, 1.0); The `r_ModelViewProjection' matrix is generated on the CPU in this manner.
      // No the most efficient way, but it works. glm::dmat4 Camera::getMatrix() { // Create the view matrix // Roll, Yaw and Pitch are all quaternions. glm::dmat4 View = glm::toMat4(Roll) * glm::toMat4(Pitch) * glm::toMat4(Yaw); // The model matrix is generated by translating in the oposite direction of the camera. glm::dmat4 Model = glm::translate(glm::dmat4(1.0), -Position); // Projection = glm::perspective(fovY, aspect, zNear, zFar); // zNear = 0.1, zFar = 1.0995116e12 return Projection * View * Model; } I managed to get rid of z-fighting by using a technique called Logarithmic Depth Buffer described in this article; it works amazingly well, no z-fighting at all, at least not visible.
      Each frame i'm rendering each node by sending the generated matrices this way.
      // set the r_ModelViewProjection uniform // Sneak in the mRadiusMatrix which is a matrix that contains the radius of my planet. Shader::setUniform(0, Camera::getInstance()->getMatrix() * mRadiusMatrix); // set the r_Grid matrix uniform i created earlier. Shader::setUniform(1, r_Grid); grid->render(); My planet's radius is around 6400000.0 units, absurdly large, but that's what i really want to achieve;
      Everything works well, the node's split and merge as you'd expect, however whenever i get close to the surface
      of the planet the rounding errors start to kick in giving me that lovely stairs effect.
      I've read that if i could render each grid relative to the camera i could get better precision on the surface, effectively
      getting rid of those rounding errors.
       
      My question is how can i achieve this relative to camera rendering in my scenario here?
      I know that i have to do most of the work on the CPU with double, and that's exactly what i'm doing.
      I only use double on the CPU side where i also do most of the matrix multiplications.
      As you can see from my vertex shader i only do the usual r_ModelViewProjection * (some vertex coords).
       
      Thank you for your suggestions!
       
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!