Inner Workings of C++ Graphics Libraries

2019-01-26 17:57发布

问题:

As you probably know, C++ has no standard graphics library. Most games use DirectX or OpenGL.

But how do those libraries actually work? In other words, how can the third-party libraries draw graphics if there's no mechanism for it in C++? Are they just written in another language?

回答1:

Specifically DirectX and OpenGL work by calling the operating system and/or the video hardware driver. The driver, in turn, does the actual drawing by interacting with the graphical device. The exact details of interaction vary from one video card to another.

Back in the DOS days, C++ programmers could work with the hardware directly. This was accomplished in two ways. First, by writing to/reading from a special memory block ("framebuffer") where the pixels or text were stored. It was a span of memory at a known address, so to work with it you had to cast an integer constant to a pointer and work with that pointer. Purely C++ mechanism. The other way of interaction was reading from/writing to I/O ports. Now, this is a mechanism that is not directly supported by C, unless you wanna count inline assembly or compiler intrinsics. There were two library functions that would wrap these two operations (literally, wrappers around two CPU commands - INP and OUTP), but most programmers would just use a one-line inline assembly snippet instead.

Even now, most video hardware interaction boils down to these two pathways - framebuffer and I/O ports (DMA and interrupts are typically not used for graphics). But we application-level programmers don't get to see those. This is driver stuff.

One modern caveat has to do with protected mode; in protected mode, the C pointers are not the same as underlying physical addresses. Simply typecasting 0xA0000 to a pointer won't get you to a framebuffer, even in kernel mode. However, kernel-level code (i. e. a driver) can request that the memory manager give it a pointer that corresponds to a specific physical address.



回答2:

They will transfer their calls to the driver which will send them to the graphic card.



回答3:

DirectX and OpenGL opperate on a pretty low level. That is you say "draw a triangle, now draw a square". Normally programmers then wrap these calls into C++ classes that provide higher level functionality, such as "Draw a model, draw a tree". This is known as an engine.

I'd recommend taking a look at the NeHe tutorials for more info: http://nehe.gamedev.net/


So for example a call to draw a triangle in OpenGL looks like this:

GLBegin(BEGIN_POLYGONS);
GLVector3(0,0,0);
GLVector3(10,10,0);
GLVector3(-10,10,0);
GLEnd();

And like I said, see the above link to the NeHe tutorials, they are all in C/C++



标签: c++ graphics