Sign in to follow this  
Vincent_M

OpenGL Code Structure for Model Data

Recommended Posts

I've built a few model importers in the past, but I'm stuck on code structure. Should I create one Model class that can load static and dynamic (animated) geometry, and use one vertex format? I could reduce my vertex positions to GL_SHORT vectors and cache static geometry data using VBOs in OpenGL but I'd still have to use floating-point vectors for vertex positions and normals for software skinning.

What I have now is an abstract Model class that doesn't do much but manage materials (one material per mesh), then my two subclasses of my Model class will load and store data for OBJ and MD5 models. The vertex structures are different between the two, and therefore, the collection of mesh data are also different too.


Does this seem about right?

Share this post


Link to post
Share on other sites
Be more modular.

Most people write simple wrappers around OpenGL rather than calling OpenGL functions directly.
One thing they commonly do is to make an index buffer class, and that class will automatically resize to GL_INT if you add an index larger than 0xFFFF. Don’t hardcode GL_SHORT. Use GL_SHORT until it is no longer sufficient.

Next, break your model class into multiple classes.
Firstly, a “model” is a collection of meshes, so you will at least need another class to encapsulate the functionality of a mesh (this is what stores your vertex buffers etc.)

Although you don’t have to follow my system exactly, what I have done is to break the model class into its core parts.
CModel.
CAnimatedModel.
CDrawableModel.

A CModel just holds the actual model data. Bounding boxes, vertices, etc. The vertices can be removed after the graphics data has been compiled.
A CAnimatedModel adds animation functionality. It holds the bind pose and anything else related to animations. It is fairly small because it only [i]holds[/i] the animation data. Model [i]instances[/i] actually use the animation data.
A CDrawableModel is of course responsible for taking the vertices, putting them into vertex buffers, and providing a Render() function. Logically, it adds whatever functionality is needed to render the model.


This applies to the shared model data.

Next you need to make instances of this shared data.
The instances can also be layered as above, so that the CAnimatedModelInstance can update joint matrices on each tick, etc.
The CDrawableModelInstance class can perform CPU skinning (if that is what you want).


Though you don’t have to follow my system exactly, break things down into logical blocks. What parts of the model are related, or more specifically [i]unrelated[/i] to the other parts?
It is foreseeable that you would want a model that has no graphics data. Only collision data. So don’t mix core model data with graphics model data.



Additionally, don’t use only one vertex format. Skinning on the CPU will be more efficient if you store vertices in their own buffer and normals in their own buffer, and pad them to 16 bytes between elements. This allows you to exploit SIMD. And a single vertex format is simply restrictive. Build a format based on what model data exists.


L. Spiro

Share this post


Link to post
Share on other sites
@YogurtEmperor:

Do you see an advantage to having each mesh have its own vertex/index buffers rather than just having one in the model and have the meshes use that via vertex offsets, etc?


I've been recently thinking of a better structure myself and I have something similar to what YogurtEmperor has mentioned but a little simplified IMO. Here are roughly the 5 main classes that I've been thinking of:

[b]Geometry[/b]
Contains the model data (vertex streams like position, normal, uv, bone weights) and the vertex/index buffers formed from the available streams. There should be only one of these in memory for each unique model loaded from disk and therefore this data is shared between model instances.

[b]AnimationController[/b]
A higher level structure which contains a number of shared Animation resources. It is responsible for updating the animations and doing any blending trickery.

[b]Animation[/b]
Contains the key-frame data for one animation. There should be only one of these in memory for each unique animation loaded from disk and therefore this data is shared between animation controllers.

[b]Model[/b]
Represents an instance of a model and is basically a container of Mesh objects that makes up a complete model. It can either be static or animated with an AnimationController.

[b]Mesh[/b]
Represents part of a model and simply contains the offsets to the vertex/index buffers within the Geometry.

Share this post


Link to post
Share on other sites
[quote name='Shael' timestamp='1317360023' post='4867476']
@YogurtEmperor:

Do you see an advantage to having each mesh have its own vertex/index buffers rather than just having one in the model and have the meshes use that via vertex offsets, etc?[/quote]
Having multiple parts in one buffer should theoretically be faster, but I personally prefer the organization and freedom of multiple buffers. Since the different meshes that make up a model can have different vertex attributes, you won’t always be able to make just one buffer for the whole model.
One thing you would want to do though if you plan on CPU skinning is to at least keep the skinned vertices and normals separate.


L. Spiro

Share this post


Link to post
Share on other sites
I've thought about concatenating everything into one vertex buffer and one index buffer, but would that be beneficial? I'm still calling sections of it using glDrawElements() per mesh.

Here's my older setup:
[b]ModelVertex:[/b] common vertex format for all models --use to be a total buffer of unsigned chars that held data based on my model's vertex format
[b]ModelMesh:[/b] each holds a vertex and index buffer to render a mesh of the model
[b]Model:[/b] holds a collection of meshes which will be rendered
[b]Object:[/b] renderable instance of a model --holds a pointer to a valid Model with data loaded. Each "Object" holds it's own transformation matrix, can be attached to other matrices, "point" at other objects, and run along a spline among other features. Object also contains a collection of AnimationChannel instances which will process skinned animations
[b]AnimationChannel:[/b] holds current playback information such as current playback frame, playback status, and looping flag for a single animation to be blended with another animation
[b]Animation:[/b] holds animation keys to translation and scale vectors, and quaternion keys. One only instance is held.

So, I load models up once, then place instances of it in the world using Object. This is the old setup, but now I'm giving static geometry some love by supporting the OBJ format for static objects, giving them a smaller vertex format, and using static VBOs.

Doing so, I now have two subclasses of the Model and Object for OBJ and MD5:
Model: OBJModel and MD5Model
Object: OBJObject and MD5Object

This is my current setup, but I want to switch to the COLLADA format for easier loading. If I switch to this format, I'm thinking of storing all my model data in one Model/Mesh/Vertex class, and use one Object class to load it. If it's a dynamic object, I'll have pointers to animation data, and have an animation flag in the model format. All my skinning is done on the CPU right now since my target's GPU isn't ready for GPU skinning.

[color=#1C2837][size=2][/size][/color]
I agree with that, but my game is targeted for iOS platforms where I've been told that interleaved vertex are much faster. I can cram the data into an interleaved buffer of unsigned chars, then ship it to the static VBO for static models... By the way, when a VBO is created, the vertex arrays can be deleted, right?

Share this post


Link to post
Share on other sites
The way I handle data is that anything static is static, and anything animated is dynamic. This way it doesn’t matter what the source of the data is. Anything with no joint weights is static, period.
I have only one format, which is custom, but if I wanted to directly load another format, it would only require a new loading routine, not a new model class.

Again, using only one vertex buffer is a valid approach, but it may give you headaches.

Yes you can delete the source vertex buffer after you make a VBO out of it.


L. Spiro

Share this post


Link to post
Share on other sites
[quote name='YogurtEmperor' timestamp='1317518563' post='4868126']
The way I handle data is that anything static is static, and anything animated is dynamic. This way it doesn’t matter what the source of the data is. Anything with no joint weights is static, period.
I have only one format, which is custom, but if I wanted to directly load another format, it would only require a new loading routine, not a new model class.

Again, using only one vertex buffer is a valid approach, but it may give you headaches.

Yes you can delete the source vertex buffer after you make a VBO out of it.


L. Spiro
[/quote]

Do you perform your skinning on the GPU? Since I'm going for iOS devices, GPU skinning isn't a very good option from personal experience.

When I started implementing VBOs for my static geometry, it seems like I get an exception whenever I release my vertex from main memory. Here's what I'm doing:
[code]
void OBJMesh::CompileBuffers()
{
// generate the VBO
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(ModelVertex) * numVertices, (void*)vertices, GL_STATIC_DRAW);

// generate the IBO
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned long)*numIndices, (void*)indices, GL_STATIC_DRAW);
//ReleaseVertexData(); // release the vertex data (THIS CAUSES A CRASH WHEN DRAWING)

// use regular data for buffering
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

[/code]

ReleaseVertexData() is commented since it releases the vertex data that's generated during load-time. Uncommenting it will release the vertex data, but crash the game when it tries to draw something.

Here's a stripped-down version of my rendering code:
[code]
// draw each mesh in the model

OBJMesh *objMesh = NULL;

for(int i=0;i<model->GetNumMeshes();i++)

{

// make sure the mesh exists
objMesh = (OBJMesh*)model->GetMesh(i);
if(!objMesh || !objMesh->GetMaterial()) continue;
glBindBuffer(GL_ARRAY_BUFFER, objMesh->GetVBO());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, objMesh->GetIBO());

// upload the vertex data from the VBO/IBO based on
glVertexAttribPointer(GL_VERTEX_ATTRIB0, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), 0);
glVertexAttribPointer(GL_VERTEX_ATTRIB1, 2, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), (void*)12);
glVertexAttribPointer(GL_VERTEX_ATTRIB2, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), (void*)20);
glVertexAttribPointer(GL_VERTEX_ATTRIB3, 3, GL_FLOAT, GL_FALSE, sizeof(ModelVertex), (void*)32);
glDrawElements(GL_TRIANGLES, objMesh->GetNumIndices(), GL_UNSIGNED_INT, NULL);
}
[/code]

I removed some uniform and texture-setting code, but this is what I have.

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
      628353
    • Total Posts
      2982228
  • 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