Sign in to follow this  
hig

OpenGL Thinking in OpenGL

Recommended Posts

Hi folks, I'm a relatively experienced programmer and I'm trying to get my head around some opengl concepts. I have a moderate math background and I think I understand the basics of the principles at work. I'd really appreciate a short conversation with some of the opengl gurus here to clarify a few points. Briefly, I'm trying to understand how to implement relative movement. I've seen a number of tutorials that use the familiar sin and cos operations to calculate coordinates after a movement along a specified angle. However, it was my understanding that due to the way the coordinate system works, it is not necessary to do this manually in opengl. If the object is rotated around its own axes, then merely translating along the desired axis is all that is necessary. Is this correct or am I barking up the wrong tree here? I have been able to load a model, rotate on own axes and display. The problem comes when I try to move the object "forward" in the scene, followed by further rotations. 1. Rotate object to "point" a specified direction in the scene. [works] 2. Move the object "forward" [works] 3. Rotate again - this time the rotation occurs around the center of the screen and not the model space. I am thinking that somehow I have to translate to the center of the model before rotating, and the first rotations work by coincidence because before any movement: center of model == center of screen. However, regardless of the order I issue the transformations, I just can't seem to get it right. When the rotation is always around the model axes then the translation is not in the direction the model is facing and vice versa. Here's my draw function:
    //  this sets the model position for the new frame
    model->Update();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glLoadIdentity();   
    
    //  rotate the model to orientate correctly
    glRotatef(-90, 1, 0, 0);
    glRotatef(180, 0, 0, 1);

    //  rotations derived from user input
    glRotatef(model->rotation.x, 1, 0, 0);
    glRotatef(model->rotation.y, 0, 1, 0);
    glRotatef(model->rotation.z, 0, 0, 1);

    //  move the object to its current position
    glTranslatef(model->position.x, model->position.y, model->position.z);

    // draw the vertices
    model->Draw();

    glPopMatrix();
    glutSwapBuffers();


Any pointers would be greatly appreciated! FYI the model is a spacecraft and I am trying to get it to fly in the direction it is pointing.

Share this post


Link to post
Share on other sites
Try this:


// this sets the model position for the new frame
model->Update();

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glLoadIdentity();

// move the object to its current position *been moved
glTranslatef(model->position.x, model->position.y, model->position.z);

// rotate the model to orientate correctly
glRotatef(-90, 1, 0, 0);
glRotatef(180, 0, 0, 1);

// rotations derived from user input
glRotatef(model->rotation.x, 1, 0, 0);
glRotatef(model->rotation.y, 0, 1, 0);
glRotatef(model->rotation.z, 0, 0, 1);



// draw the vertices
model->Draw();

glPopMatrix();
glutSwapBuffers();







The order of matrix multiplications matter. You want to rotate on the origin first, but by translating you moved it off the origin, and then rotated it.

The matrix multiplications are associative. e.g. (a*b)*c = a(b*c) or a*(b*(c*d)) = ((a*b)*c)*d

You should look it up if you don't know what it is, as it will help you understand the multiplications.

Edit:

To fly in the direction, it would be easier to have a vector pointing the direction, and just add that to the model->position.

Also think of the lowest matrix calls acting first, e.g. rotating or translating etc.

[Edited by - andrew111 on April 30, 2010 11:10:32 AM]

Share this post


Link to post
Share on other sites
Hey thanks for such a quick reply. That is exactly what I had tried. With the translation called first, yes the model always rotates correctly on its axes - but then it always moves "down" the screen regardless of its rotation! (I guess because the translation is now relative to the world coordinate system and not the model)

I feel a "d'oh!" moment coming on. I'm sure I must be doing something stupid!

Share this post


Link to post
Share on other sites
Here are a few bits of information that might be helpful...

First of all, the problems you're talking about aren't really OpenGL-specific. It's understandable why one might think they are, but this is really just math that we're talking about, which is essentially the same regardless of what API you're using (OpenGL, Direct3D, etc.).

There are some (sort of) API-specific things that can hang people up though, and one of these is the way in which OpenGL's 'transform' functions operate. Before I continue though, let me point out that the functions you're using are actually deprecated and are more or less irrelevant in modern OpenGL code (typically, you would instead build these transforms yourself and then pass them in as shader parameters).

In any case, one of the most common causes of confusion when working with OpenGL is transform order. As I'm sure you know, matrix multiplication is not commutative, and the order in which a sequence of transforms is applied matters. For example, a rotation followed by a translation will generally have a different result than a translation followed by a rotation. Anytime someone says that they're expecting a model to rotate about its own origin but it instead appears to be rotating about some other point, you can bet that they're applying the transforms in the wrong order, and looking at the bit of code you posted, that appears to be the case here.

I think if you move the glTranslatef() call to before the calls to glRotatef(), you'll find that the behavior is correct (or at least closer to what you're expecting).

I'm sure someone's already pointed that out by now (in fact, after refreshing, I see that they have :), but I'll go ahead and elaborate a bit on this.

You may already know this, but the order in which matrices must be multiplied to yield a given effect depends on whether row or column vectors are being used. In short, when row vectors are used, the matrix product A*B applies the transforms in the order A->B, and when column vectors are used, the transforms are applied in the order B->A.

OpenGL (or the OpenGL fixed-function pipeline at least) has traditionally been thought of as using column vectors, although I don't know whether this really has any practical significance. What is significant though is that the most recent transform command issued is 'closest to' the vector to which it is to be applied, so to speak. This means that transforms are actually applied in the reverse of the order in which they appear in your code, and is why the translation actually needs to come first in your example in order to have the effect of a rotation followed by a translation.

As mentioned previously though, this really isn't the way things are done anymore. In modern OpenGL, you would typically build these transforms yourself, and then simply upload them to OpenGL as shader parameters. On your side of things, you can use whatever convention you want (e.g. row or column vectors), so long as the matrix data ends up in a form that OpenGL can understand.

Share this post


Link to post
Share on other sites
As for your follow-up post, can you post your revised rendering code, along with the code you're using to update the object's position?

Share this post


Link to post
Share on other sites
Hi thanks for the info. I'm certainly no math expert but I do understand the concepts you are raising. And I understand that the gl functions are merely helpers to construct a matrix, which is then applied to the vertices. I had read that they are now depreciated and the modern approach is to construct your own transformation matrices, however I thought it could still be a good approach to learn the basics.

I altered my drawScene function precisely as suggested by the poster above, and my code to update the model position merely increases its "position.y". The reason for that is because in the local model coordinate system, it "points" along its y axis and therefore I concluded that "forward" for the model is along the y axis. This is probably my problem, right? Although I can't quite get my head around why.

I'm assuming then that I have to do something a little more sophisticated to the model position vector?

Many thanks for the help, greatly appreciated!

Share this post


Link to post
Share on other sites
Quote:
Original post by hig
Hi thanks for the info. I'm certainly no math expert but I do understand the concepts you are raising. And I understand that the gl functions are merely helpers to construct a matrix, which is then applied to the vertices. I had read that they are now depreciated and the modern approach is to construct your own transformation matrices, however I thought it could still be a good approach to learn the basics.
Oops - well I guess that post was mostly redundant then :)
Quote:
I altered my drawScene function precisely as suggested by the poster above
I suggested that as well.
Quote:
and my code to update the model position merely increases its "position.y". The reason for that is because in the local model coordinate system, it "points" along its y axis and therefore I concluded that "forward" for the model is along the y axis. This is probably my problem, right? Although I can't quite get my head around why.

I'm assuming then that I have to do something a little more sophisticated to the model position vector?
Right, that won't do what you're expecting. Why it won't do what you're expecting is actually a little tricky to explain, but here goes.

To keep things simple, let's assume that your model transform only incorporates rotation and translation (which is fairly common, and appears to be the case here, judging from your code).

These two transforms (rotation and translation) are typically applied in the order rotation->translation. If you hold some object in your hand (e.g. a toy car, spaceship, or whatever), you can visualize this by starting at a 'default' position and orientation ('identity' in matrix terms), then rotating it to the orientation that you want, and then translating it to the position that you want.

Note that because the rotation occurs first, the translation is unaffected by the rotation. If the translation is +5 along the y axis, then the model will be first rotated to the desired orientation, and then moved 5 units along the (world) y axis.

In order to get the model positioned where you want, your position variable (model->position in your code) needs to represent the object's actual position in world space. If all you ever do is move this position vector along the y axis, then your model will always be positioned somewhere along the (world) y axis (it won't, in general, move 'forward' based on the object's orientation).

To get the kind of motion you want, you need to translate the position vector not along the y axis (or whatever), but rather along the object's current direction vector(s).

There are a few ways to get these direction vectors, but the easiest way is probably to build a transform matrix for the object and then extract the direction vectors from the first three rows or columns of the matrix. (This can be done using OpenGL functions, but it's more straightforward if you use your own math code or a third-party math library for this.)

Share this post


Link to post
Share on other sites
That helps a lot, thanks. My main misconception was that opengl inherently handles this "relative" movement internally, knowing the "local" orientation of the vertices being drawn.

Is it then analogous to the operations required in 2d space to translate at an angle? i.e sine and cosine calculations? I assume it must be, only performed directly with matrices?

Although you're right, and the discussion is moving further away from opengl and more towards independent math topics!

But I now know the specific area that I need to investigate more is the general math behind it and not specifically the opengl API.

Thanks again.

Share this post


Link to post
Share on other sites
Quote:
My main misconception was that opengl inherently handles this "relative" movement internally, knowing the "local" orientation of the vertices being drawn.
Yup, no such luck :) OpenGL neither knows nor cares about that stuff - it has no concept of 'object motion', 'local orientation', or anything of that sort. In the fixed-function pipeline, it just applies a series of transforms in matrix form to the input data (the programmable pipeline doesn't even do that much - with the PP, transforming of the input data is entirely up to you).
Quote:
Is it then analogous to the operations required in 2d space to translate at an angle? i.e sine and cosine calculations?
Yes, it can be. In 2-d, you typically see something like this (or a vector version thereof):
x += cos(angle) * speed * dt;
y += sin(angle) * speed * dt;
If you're dealing with Euler or spherical angles, you can do something similar in 3-d as well.
Quote:
I assume it must be, only performed directly with matrices?
You can use either matrices or angles in both 2-d and 3-d. In 3-d especially, using matrices is more straightforward, IMO, and is the approach I'd recommend. (What I'm referring to here is building a transform matrix for the object, and then extracting the direction vectors from the matrix. Note that once you have the transform matrix, it can be uploaded directly to OpenGL via glLoad/MultMatrix*(), allowing you to bypass convenience functions such as glRotate*() entirely.)

Share this post


Link to post
Share on other sites
Hi,

I would recommend that you use this phenomenon sparingly. In OpenGL (and as you know, if you've made games), any other graphics API, it's best to keep track of an object's position and orientation yourself.

So, while you could define an object's movement as a series of translations and rotations, it's much easier to translate to the location, and then rotate to the proper orientation.

I have, however, used this technique for simple things (e.g., cause an object to "orbit" a point with a rotation*translation*rotation, instead of a translation*rotation).

Evidently, this new OpenGL 3 thing doesn't do hardware matrices, so for learning OpenGL, I'd recommend just getting used to translating and then rotating.

Cheers,
-G

Share this post


Link to post
Share on other sites
I'm back to bend your ears again if I may. My queries really are more math related now though so perhaps a moderator might want to move this to the appropriate forum?

Anyway, I have updated my project to utilize transformation matrices manually in place of glRotate and glTranslate so I'd like to ask if I'm on the right track.

I wrote my own simple vector and matrix classes and I'm pretty sure they are correct. I know that's a bit of a leap of faith but I understand the way matrices work and that opengl matrices are column major etc... To calculate the transform matrix for my model I do this:


Matrix4 xRot = MathUtil::rotateX(rotation.x*PIdiv180);
Matrix4 yRot = MathUtil::rotateY(rotation.y*PIdiv180);
Matrix4 zRot = MathUtil::rotateZ(rotation.z*PIdiv180);
Matrix4 trans = MathUtil::translate(position.x, position.y, position.z);

transform = (yRot * zRot * xRot) * trans;



The MathUtil functions return the appropriate rotation and translation matrices.

My render function now looks like this:


glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glLoadIdentity();

// move "camera" back to view the model
glTranslatef(0,0,-600);

// this now updates the model position and calculates its transform matrix
craft->Update();

// apply the model transform matrix
glMultMatrixf(craft->transform.elements);

// draw the vertices
craft->Draw();

glPopMatrix();

glutSwapBuffers();



This results in the rotation working correctly as long as the model has not been translated. Then the vertices are just warped all over the screen. I'm kind of confused as to how the translation should work.

If forward movement is applied to the model, I increment its position.y (since it faces along its own y-axis. Then this position vector is fed into the MathUtil to obtain the translation matrix as above.

Here is how I generate the translation matrix:

Matrix4 MathUtil::translate(const float x, const float y, const float z)
{
GLfloat res[] = {
1,0,0,x, // actually *column* 1 because opengl is column major
0,1,0,y,
0,0,1,z,
0,0,0,1
};

return Matrix4(res);
}



I know its not the most elegant way, but for now my matrix class simply encapsulates an array of GLfloats and overloads the operators.

Can you see anything drastically wrong with my approach?

Cheers!

Share this post


Link to post
Share on other sites
Quote:
Can you see anything drastically wrong with my approach?
I see a few potential problems:
Quote:
To calculate the transform matrix for my model I do this:

*** Source Snippet Removed ***
This:
transform = (yRot * zRot * xRot) * trans;
Would be correct for row vectors. If you're using column vectors, the order will need to be reversed.
Quote:
This results in the rotation working correctly as long as the model has not been translated. Then the vertices are just warped all over the screen. I'm kind of confused as to how the translation should work.
I think this is probably because your matrices are set up incorrectly (see below).
Quote:
If forward movement is applied to the model, I increment its position.y (since it faces along its own y-axis. Then this position vector is fed into the MathUtil to obtain the translation matrix as above.
Moving 'forward' by incrementing the y value is incorrect (what I wrote about this earlier still applies - read my earlier posts for more info).
Quote:
Here is how I generate the translation matrix:
*** Source Snippet Removed ***
Your matrices appear to be set up incorrectly. What you've shown above would work for either a row-vector/column-major setup or a column-vector/row-major setup, but OpenGL expects either a row-vector/row-major setup or a column-vector/column-major setup (in other words, OpenGL expects the elements of a given basis vector of the matrix to be contiguous in memory).

Share this post


Link to post
Share on other sites
Ok I'm REALLY confused about the "forward" movement issue then. I thought that in model space I am always moving along the Y axis so this is the only component of the position vector that I change. But this is then converted into world coordinates via the transformation matrix - which is a translation matrix constructed based on the local position, then multiplied by the rotation matrices to produce an absolute transform matrix to be fed to opengl.

Considering your post, I know my above reasoning is wrong and I can't quite get my head around it even re-reading your previous advice. I'm against spoon feeding as much as the next person, but maybe in this case you could give me an example to help me understand the concept - if I want to move the model in the direction it is facing, how should I alter the member position vector?

My matrices are set up such that the first column is:
element[0], element[1], element[2], element[3]

and the first row is:
element[0], element[4], element[8], element[12]
and so on...

Therefore in a translation matrix, the xyz magnitude components would take the positions [3], [7], [11] respectively. Is this what you refer to when you say opengl expects column major matrices?

Your comment regarding vectors/matrices has thrown me off a little, as I don't carry out any manual vector manipulation. I simply feed the vector components into my matrix generation functions as needed, multiply the matrices to get my compound transform, then apply this via glMultMatrixf before drawing the vertices.

As I type this, I'm getting the idea that every time I update the position of the model, I don't merely increment the y component, but I must multiply the position vector by some other velocity vector... but how exactly to I construct that "other" vector... :)

Thanks a lot for your time and patience. I hope I'm not asking any completely stupid questions here! The more I ask, the more I'm feeling I'd be better moved to the beginners section!

Share this post


Link to post
Share on other sites
Quote:
My matrices are set up such that the first column is:
element[0], element[1], element[2], element[3]

and the first row is:
element[0], element[4], element[8], element[12]
and so on...

Therefore in a translation matrix, the xyz magnitude components would take the positions [3], [7], [11] respectively. Is this what you refer to when you say opengl expects column major matrices?
This setup is wrong (for the OpenGL fixed-function pipeline, at least). The translation should reside in elements 12, 13, and 14, not 3, 7, and 11.

Basically, your matrices should be the transpose of what they are currently.
Quote:
Your comment regarding vectors/matrices has thrown me off a little, as I don't carry out any manual vector manipulation. I simply feed the vector components into my matrix generation functions as needed, multiply the matrices to get my compound transform, then apply this via glMultMatrixf before drawing the vertices.
Whether or not you're performing any matrix-vector multiplications explicitly in your code, you still need to get your conventions set up in a way that makes sense.

Firstly, it doesn't matter if you use row vectors or column vectors - you can use either. The only requirement is that the 'majorness' of your matrices match the vector notation convention; that is, if you're going to use row vectors your matrices need to be row major, and if you're going to use column vectors your matrices need to be column major. (Currently your matrices are swapped around - they're either row-basis matrices with column-major ordering or vice versa, depending on how you look at it.)

Once you've settled on a vector notation convention (row or column vectors), you need to make sure that your transform matrices and matrix multiplication order reflect this convention correctly.

With row vectors, transforms should be built with basis vectors in the rows of the matrix; with column vectors, the basis vectors should be in the columns of the matrix.

Furthermore, with row vectors, the matrix product A*B applies the associated transforms in the order A->B, while with column vectors, the transforms are applied in the order B->A. Any expressions involving matrix multiplication will need to be ordered accordingly.

These topics are a frequent source of confusion for many, so don't hesitate to ask for clarification if you need it. You might also try searching the forum archives and/or internet as a whole for, say, 'row column major vector', and see what you find. Unfortunately though, confusion regarding these topics is so widespread that a good deal of what you find will be wrong anyway, so it's probably best to ask for any needed clarification here as well :)
Quote:
Ok I'm REALLY confused about the "forward" movement issue then. I thought that in model space I am always moving along the Y axis so this is the only component of the position vector that I change. But this is then converted into world coordinates via the transformation matrix - which is a translation matrix constructed based on the local position, then multiplied by the rotation matrices to produce an absolute transform matrix to be fed to opengl.
I think I understand the source of your confusion. When you build the transform for your object, the rotation and translation transforms are combined in the order rotation->translation. However, the translation transform is not modified when these two transforms are combined; in other words, it's not 'adjusted' to 'match' the rotation in any way. If the input translation is (1,2,3), then after the combined transform is built, the translation is still (1,2,3). So, the translation has to be correct and in world/parent space from the outset. Whatever you set the translation to, that is where the object will be in world space. (Sorry if I'm being a little redundant, but I'm just trying to provide a few different ways of looking at it :)
Quote:
if I want to move the model in the direction it is facing, how should I alter the member position vector?
As follows:

1. Build the rotation transform matrix for the object.

2. The rows or columns (depending on whether you're using row or column vectors) of this matrix are the direction vectors for the object. Extract the forward direction vector (which sounds like it's the y axis in your case), and store it in vector form.

3. Add this vector (most likely scaled by speed and time step) to your position vector.
Quote:
As I type this, I'm getting the idea that every time I update the position of the model, I don't merely increment the y component, but I must multiply the position vector by some other velocity vector... but how exactly to I construct that "other" vector... :)
You don't multiply the vectors, but rather add them (as described above). Here's some example pseudocode:
matrix33 m = get_rotation_matrix();
vector3 forward(m(0,1), m(1,1), m(2,1));
position += forward * speed * time_step;


[Edited by - jyk on May 4, 2010 10:42:46 PM]

Share this post


Link to post
Share on other sites
Once again thanks for a very well explained answer. I have managed to get it working (I admit through 80% understanding of what's going on and 20% trial and error) and for what it's worth it turns out my forward vector (y) ends up in matrix elements [4],[5] and [6]. As far as I can gather, this is what you would expect from a column major rotation matrix?

My next obstacle is to work out why my "pitch" is still relative to the world: if the craft is facing at right angles to the world "up", then the pitch control becomes roll, and facing -z pitch-up raises the nose whilst facing +z lowers the nose. Though yaw and forward movement is working correctly.

Interesting stuff. And thanks again, your continued help is much appreciated!

Share this post


Link to post
Share on other sites
Quote:
I have managed to get it working (I admit through 80% understanding of what's going on and 20% trial and error) and for what it's worth it turns out my forward vector (y) ends up in matrix elements [4],[5] and [6]. As far as I can gather, this is what you would expect from a column major rotation matrix?
That is what you would expect for either a column-major matrix intended for use with column vectors, or a row-major matrix intended for use with row vectors. For the other two configurations (row major/column vector and column major/row vector), the y axis would be in elements [1], [5], and [9].

But yes, [4], [5], and [6] is what you want for OpenGL.
Quote:
My next obstacle is to work out why my "pitch" is still relative to the world: if the craft is facing at right angles to the world "up", then the pitch control becomes roll, and facing -z pitch-up raises the nose whilst facing +z lowers the nose. Though yaw and forward movement is working correctly.
Not sure about that one (not without seeing the code at least), but it sounds like either a) you just have your Euler-angle order wrong, or b) you need to ditch Euler angles and store your orientation in matrix form instead (which is what you'll need to do if you're trying to implement full 6DOF motion).
Quote:
And thanks again, your continued help is much appreciated!
No problem :)

Share this post


Link to post
Share on other sites

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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628345
    • Total Posts
      2982192
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now