Shaders In Opengl

来源:互联网 发布:ipad无法加入网络 编辑:程序博客网 时间:2024/05/17 22:14

Shaders are the essence of programmable graphics; they give you full control of your final rendered scene using GLSL (OpenGL Shading Language) programming.

Here’s a quick refresher on vertex and fragment shaders, taken from the tutorialOpenGL ES 2.0 for iPhone:

  • Vertex shaders are programs that get called once per vertex in your scene. So if you are rendering a simple scene with a single rectangle, with one vertex at each corner, this would be calledat least four times. (The actual number can vary for implementation-dependent reasons. It could be as high as six.) Its job is to perform some calculations such as lighting, geometry transforms, etc., figure out the final position of the vertex, and also pass on some data to the fragment shader.
  • Fragment shaders are programs that get called once per pixel (sort of) in your scene. So if you’re rendering the same simple scene with a single rectangle, it will be called at least once for each pixel that the rectangle covers. Fragment shaders can also perform lighting calculations, etc., but their most important job is to set the final color for the pixel.

For the sake of completeness, here’s a quick explanation on the difference between fragments and pixels:

  • A pixel is simply the smallest measured unit of an image or screen.
  • The graphics pipeline produces fragments which are then converted (or not) to actual pixels, depending on their visibility, depth, stencil, colour, etc.

Note: It’s important to realize that fragment shaders are called many times when rendering a scene. Imagine a single rectangle with 4 vertices. If the rectangle was very small, say about 32×32 pixels, the vertex shader would be called roughly 4 times. However, the fragment shader would be called 1024 times — once for each pixel in the rectangle.

Now imagine rendering the pixels of a 3D view that covers the entire screen. On an iPhone 5, that’s 1136 x 640 pixels, resulting in 727,040separate calls to the fragment shader. And shaders are called for…Every. Single. Frame. Plus, if there are transparent objects in your view, some shaders will need to run more than once per frame.

The moral of this story? Be careful when writing shaders, because inefficient shaders are a fast track to a slow app!


In general, all shader programs have the following characteristics:

  • They are very short programs written in GLSL, which is quite similar to C. Why so short? Recall that they are called with every single frame change.
  • They have special variable prefixes that determine the type and source of data the shader will receive from the main program:
    • Attributes typically change per-vertex (variable θ). Due to their per-vertex nature, they are exclusive to the vertex shader.
    • Uniforms typically change per-frame or per-object (constant k). They are accessible to both vertex and fragment shaders.

原创粉丝点击