Sign in to follow this  

OpenGL D3D Vertex color format vs. OpenGL

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

IF we are to write a 3D engine that support both D3D and OpenGL and allow user of the engine specify their own vertex format using engine defined "vertex declaration", how to cope with the different in vertex color between D3D and OpenGL? Fixed function D3D only allow type DWORD (unsigned long) while OpenGL doesn't support that. On the other hand, if you use D3D shader, you can actually specify several different types, however, component types that separate the colors ( 4 floats or 4 ubyte for each color) the format is a, r, g, b. In OpenGL it is r, g, b, a. I'm having to do something like this to work around:
#ifdef	WIN32
#define	DF_RE_API_D3D9 //this is turned on or off at compile time
#endif
#ifdef	DF_RE_API_D3D9
#define	DF_RE_API	Graphics::RenderEngine::T_D3D9
#define DF_COLOR_TYPE(n)	unsigned32 n
#define	DF_COLOR( r, g, b, a )	((a << 24) + (r << 16) + (g << 8) + b)
#else
#define	DF_RE_API	Graphics::RenderEngine::T_OPENGL
#define DF_COLOR_TYPE(n)	unsigned8 n##R, n##G, n##B, n##A
#define	DF_COLOR( r, g, b, a )	r, g, b, a
#endif

struct VertexPD
	{
		Real32 X, Y, Z;
		DF_COLOR_TYPE( Diffuse );
	};
	VertexPD vertices[]	=
	{
		  0.0f, 0.0f, 0.0f, DF_COLOR( 255, 0, 0, 255 )
		, 0.0f, 1.0f, 0.0f, DF_COLOR( 0, 255, 0, 255 )
		, 1.0f, 0.0f, 0.0f, DF_COLOR( 0, 0, 255, 255 )
	};


It goes without saying that you cannot decided to use OpenGL or D3D at run-time.  Does anyone know how to deal with this?

Thanks

Share this post


Link to post
Share on other sites
Do you mean have a vertex class which would work in both APIs? Sorry, maybe its because its morning, but your actual question wasnt that clear

Share this post


Link to post
Share on other sites
In away, but the key is to allow user to define their own vertex format. The problem now is the color.

Share this post


Link to post
Share on other sites

Are you absolutely sure that you'll need to let the user define vertex formats ?

Well, for the color, you can use some sort of virtualization but I'd say that your approach isn't going to be easy.

How about:

- The engine provides the graphics API some sort of geometry objects. The graphics API creates a renderable interface from the mesh which is returned to the engine. This way, every gfx API is able to implement the best corresponding representation of the geometry and the engine itself doesn't need to worry about how the thing is actually drawn etc.

- If you need to change the vertex colors for some reason, you can do it with this approach also.

Pseudo:

RenderableInterface *pObj = GrapchisAPI->CreateRenderableInterface(pGeometry);

where pGeometry contains list of vertex positions, per vertex colors, texture coordinates, normals, tangents ... etc.

...

pObj->Draw();

I hope that I provided some useful information for your question:

Share this post


Link to post
Share on other sites
When you want to allow shaders, does it not make sense to allow custom vertex format?

For OpenGL you can have the vertex components separated and bind them in the end. However, for D3D, you'll need to have them packed into the vertex buffer. This could be very slow if you need to pack it everytime.

Share this post


Link to post
Share on other sites
I don't understand what you're trying to do. It doesn't make sense unless you're also letting the user create one shader for both OpenGL and Direct3D (say, using Cg).

If you do use Cg, I don't know what to say. But if for some reason different shaders are used for OpenGL and D3D, then you can just use swizzling in the shader to get the correct component order. Might hurt performance just a bit, but it's an easy solution.

Share this post


Link to post
Share on other sites
I understand most of the time in game development you usually define a model format and load the vertex information from a file. My goal is to develop an engine that is suitable for not only game development but also for say, scientific visualization. Vertex information usually vary a great deal depending on the application here so I would like for the developer to be able to specify their own vertex format and modify them during run time.

You can also argue to provide a fixed vertex format that has a lot of the components that a developer might need and let me decide what component they want to use from that vertex. However, that would waste some memory and transfer time.

The situation is that say you want to allow developer direct access to the "vertex buffer" so that they could provide the vertex information say through memmove or memcpy, for the most part if you don't use the color component everything is fine. However, due to the color component different mentioned with D3D vs OpenGL, you can't really use the memory operations directly. Instead, you'll have to modify indivisual vertices, pack them and then push the information to vertex buffers or buffer objects.

Share this post


Link to post
Share on other sites
Hi,

If you want to handle both OpenGL and DirectX at runtime, then you should create a layer on top of API-dependant parts.

For example :

// vertex buffer interface
class IVertexBuffer
{
protected:
IVertexBuffer(void); // protected constructor to avoid direct instantiation
virtual ~IVertexBuffer(void);

public:
// here, put all the methods that you'll need to work on vertex buffer
// for example :

bool Lock(....);
bool Unlock(....);
void SetColor(int vertexIndex, float r, float g, float b, float a);

// ...
};

// DirectX implementation
class CDXVertexBuffer : public IVertexBuffer
{
public:
CDXVertexBuffer(void);
virtual ~CDXVertexBuffer(void);

public:
bool Lock(....);
bool Unlock(....);
void SetColor(int vertexIndex, float r, float g, float b, float a);

// ...
};


// and now the vertex buffer that the engine will manipulate :
class CVertexBuffer
{
public:
CVertexBuffer(void);
~CVertexBuffer(void);

// here, you find the same methods as the ones in IVertexBuffer :
inline bool Lock(....) { m_pVertexBuffer-&gt;Lock(...); }

// ...

// the point of this class is the following method.
// eAPIType is a simple enum for OpenGL or DirectX, and in this method,
// you simply have to delete the m_pVertexBuffer and recreate a new one
// specific to the api given in parameter

bool SetAPI(eAPIType api);

private:
IVertexBuffer * m_pVertexBuffer; // this can point to a DirectX VB or and OpenGL one
}




Ok, this example might be a bit "dirty" but it's to give you the idea. Create a virtual class, make a DirectX and an OpenGL implementation, then create a layer which manipulate the interface. So in your engine, you always manipulate a CVertexBuffer without the type of buffer. And you don't need to ^^

If you want to switch from OpenGL to DirectX and vice versa, it will be a little more complicated than in my example of course. The the SetAPI(..) method can simply be used at initialization time to create the correct VB, depending on the API in use.

I hope it helped ^^

Share this post


Link to post
Share on other sites
paic,

It's not the "vertex buffer" abstraction I'm concern but the vertex data format. You example, the IVertexBuffer has the SetColor method, this assumes that the vertex has a color. So in this sense you're predefining the vertex format, which defeats the purpose of allowing user of the engine to specify their own vertex format.

Share this post


Link to post
Share on other sites
You can use any four int values for R, G, B, and A, and then arrange them however you need.

You could just make a struct like this:

struct OurColorStruct
{
int r, g, b, a;
}


Then you could just convert to whichever API you need. For DirectX you would just use

DWORD color = D3DCOLOR_RGBA(R, G, B, A)


And for OpenGL just use the values

glColor4i(R, G, B, A);

Share this post


Link to post
Share on other sites
Quote:
Original post by Simplicity
paic,

It's not the "vertex buffer" abstraction I'm concern but the vertex data format. You example, the IVertexBuffer has the SetColor method, this assumes that the vertex has a color. So in this sense you're predefining the vertex format, which defeats the purpose of allowing user of the engine to specify their own vertex format.


As it is not recommended (performances reasons) to use immediate mode anymore the vertex buffer abstraction is a good point to start. You should simply add a format abstraction too. Then the API dependent layer will convert this independent format to an dependent format. Every buffer should know both. Than you can write an loader method that takes data in the independent form and convert it to the dependent view.

We have done something very similar to store our vertex data in the best form and expand them if the GPU doesn’t support the used vertex declaration type.

Share this post


Link to post
Share on other sites
I don't really understand then. By allowing the user to choose their own vertex format, what exactly do you mean then ?

Because as I understand it, it's : does a vertex have a color, a texture coordinate set, etc. It's almost "non-sense" to allow the user to say "I want colors, but only R and G" right ?

The layer is just here to handle API specific cases. For example, if the user created the VB with a vertex color, the user will always use SetColor() with 4 floats, but in the DirectX implementation, it will be converted into a DWORD, and in the OpenGL one, into <put here the OpenGL format for color ^^>

Then, the point I forgot to mention : When you create the VB, using your layer, you can have a constructor like this :

CVertexBuffer::CVertexBuffer(unsigned int vertexFormat = 0);


#define VERTEX_FORMAT_POSITION 0
#define VERTEX_FORMAT_NORMAL 1
#define VERTEX_FORMAT_DIFFUSE_COLOR 2
#define VERTEX_FORMAT_AMBIENT_COLOR 4
#define VERTEX_FORMAT_SPECULAR_COLOR 8
// ...

So the user can create a VB with anything inside it. Just that you can't choose the format of the color, nore the normals, etc. This is left to the API implementation.

I hope I was a little clearer ^^

Share this post


Link to post
Share on other sites
I agree with you paic but your solution is so „fixed function“ like (sorry).

That was the reason why I recommend using an independent vertex structure description that contains additional information’s like a data type. Similar to the vertex declarations that D3D9 already supports. But as it is his own format he can add additional data types and custom conversion rules for every API he want to support.

Share this post


Link to post
Share on other sites
With these differences in the API though, it seems that direct memory access cannot be allowed (direct access to D3D vertex buffer or OpenGL buffer object) since we'll have to do the conversion for each vertex. Quite slow?

Share this post


Link to post
Share on other sites
In most cases direct memory accesses are evil anyway. The conversion takes some additional time but as most of your vertex buffer should be static it will happen during loading. You can improve this with a cache that store the data in the native format after it was converted one time.

Share this post


Link to post
Share on other sites
I think that if you don't use D3DDECLTYPE_D3DCOLOR in your vertex declaration you shouldn't have a problem. It's the only one that swizzles components to ARGB. D3DDECLTYPE_UBYTE4N is an equivalent format that should give RGBA as you want, and all other formats should also give RGBA. However, this will limit the target cards (only shader capable ATI card and GeForceFX and up, according to the caps list in the SDK).

Share this post


Link to post
Share on other sites

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

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

Create an account or sign in to comment

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

Create an account

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

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

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

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