header image
 

On Direct3D

Having already learned OpenGL, I decided to start learning some Direct3D a while back. I can see why some people like it, because it does a few things for you, like image loading, fonts, etc. If you like C++ (which I don’t, particularly), Direct3D has something for you too, being very object-oriented, whereas OpenGL is more procedural, like C. I had already seen a little Direct3D code and thought it was kind of convoluted looking like C++, but now that I’m learning it, I see it’s not too bad. I’m certainly glad I learned OpenGL first, so that I understand graphics concepts and such.

There’s a fair chunk of initialization code to start with, but that is, of course, understandable. In Direct3D, there is no primitive rendering like in OpenGL, so you have to go straight to packing vertex arrays. These arrays can be in various forms too: you specify what you’re giving it. Starting with the vector, since you can’t really have a vertex with out it, then any combination of colors, texture coordinates, etc. So you tell it what kind of vertex data you’re going to give it, create the vertex buffer, point it at the buffer:

direct3D_device->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1);
direct3D_device->CreateVertexBuffer(sizeof(aTriangle),D3DUSAGE_WRITEONLY,(D3DFVF_XYZ | D3DFVF_DIFFUSE),D3DPOOL_MANAGED,&tri_buffer,NULL);
tri_buffer->Lock(0,sizeof(pData),(void**)&pData,0);
memcpy(pData,aTriangle,sizeof(aTriangle));
tri_buffer->Unlock();
direct3D_device->SetTexture(0,testTexture);
direct3D_device->SetStreamSource(0,tri_buffer,0,sizeof(D3DVERTEX));

And then draw it:

direct3D_device->DrawPrimitive(D3DPT_TRIANGLELIST,0,2);

Whereas in OpenGL, if you’re working with vertex arrays, you’d just setup the pointers:

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer (3, GL_FLOAT, 0, vertex);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, 0, color);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer (2, GL_FLOAT, 0, texcoord);

And draw:

glDrawArrays(GL_TRIANGLES, 0, num);

Both examples are assuming the vertex arrays have already been packed, of course. The OpenGL example seems so much cleaner to me than the Direct3D. I want to say again how happy I am to have learned OpenGL first, so that I understood the graphics principles. If not, I would have gotten pretty discouraged, and probably switched to OpenGL. Now it’s just a matter of finding equivalent methods for doing common tasks in Direct3D, which has worked well so far. I’m coming right along.

~ by Entar on November 9, 2007.

Leave a Reply