cube例子自带的说明文档

来源:互联网 发布:unity3d角色控制脚本 编辑:程序博客网 时间:2024/05/22 18:44


<?xml version="1.0" encoding="UTF-8"?>

Cube OpenGL ES 2.0 example

This example has been written for OpenGL ES 2.0 but it works also on desktop OpenGL because this example is simple enough and for the most parts desktop OpenGL API is same. It compiles also without OpenGL support but then it just shows a label stating that OpenGL support is required.

Screenshot of the Cube example running on N900

The example consist of two classes:

  • MainWidget extends QGLWidget and contains OpenGL ES 2.0 initialization and drawing and mouse and timer event handling
  • GeometryEngine handles polygon geometries. Transfers polygon geometry to vertex buffer objects and draws geometries from vertex buffer objects.

We'll start by initializing OpenGL ES 2.0 in MainWidget.

Initializing OpenGL ES 2.0

Since OpenGL ES 2.0 doesn't support fixed graphics pipeline anymore it has to be implemented by ourselves. This makes graphics pipeline very flexible but in the same time it becomes more difficult because user has to implement graphics pipeline to get even the simplest example running. It also makes graphics pipeline more efficient because user can decide what kind of pipeline is needed for the application.

First we have to implement vertex shader. It gets vertex data and model-view-projection matrix (MVP) as parameters. It transforms vertex position using MVP matrix to screen space and passes texture coordinate to fragment shader. Texture coordinate will be automatically interpolated on polygon faces.

[cpp] view plain copy
  1. void main()  
  2. {  
  3.     // Calculate vertex position in screen space  
  4.     gl_Position = mvp_matrix * a_position;  
  5.   
  6.     // Pass texture coordinate to fragment shader  
  7.     // Value will be automatically interpolated to fragments inside polygon faces  
  8.     v_texcoord = a_texcoord;  
  9. }  

After that we need to implement second part of the graphics pipeline - fragment shader. For this exercise we need to implement fragment shader that handles texturing. It gets interpolated texture coordinate as a parameter and looks up fragment color from the given texture.

[cpp] view plain copy
  1. void main()  
  2. {  
  3.     // Set fragment color from texture  
  4.     gl_FragColor = texture2D(texture, v_texcoord);  
  5. }  

Using QGLShaderProgram we can compile, link and bind shader code to graphics pipeline. This code uses Qt Resource files to access shader source code.

[cpp] view plain copy
  1. <span class="type">void</span> MainWidget<span class="operator">::</span>initShaders()  
  2. {  
  3.     <span class="comment">// Compile vertex shader</span>  
  4.     <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>addShaderFromSourceFile(<span class="type"><a target="_blank" href="../qtgui/qopenglshader.html">QOpenGLShader</a></span><span class="operator">::</span>Vertex<span class="operator">,</span> <span class="string">":/vshader.glsl"</span>))  
  5.         close();  
  6.   
  7.     <span class="comment">// Compile fragment shader</span>  
  8.     <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>addShaderFromSourceFile(<span class="type"><a target="_blank" href="../qtgui/qopenglshader.html">QOpenGLShader</a></span><span class="operator">::</span>Fragment<span class="operator">,</span> <span class="string">":/fshader.glsl"</span>))  
  9.         close();  
  10.   
  11.     <span class="comment">// Link shader pipeline</span>  
  12.     <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>link())  
  13.         close();  
  14.   
  15.     <span class="comment">// Bind shader pipeline for use</span>  
  16.     <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>bind())  
  17.         close();  
  18. }  

The following code enables depth buffering and back face culling.

[cpp] view plain copy
  1. <span class="comment">// Enable depth buffer</span>  
  2. glEnable(GL_DEPTH_TEST);  
  3.   
  4. <span class="comment">// Enable back face culling</span>  
  5. glEnable(GL_CULL_FACE);  

Loading Textures from Qt Resource Files

QGLWidget interface implements methods for loading textures from QImage to GL texture memory. We still need to use OpenGL provided functions for specifying the GL texture unit and configuring texture filtering options.

[cpp] view plain copy
  1. <span class="type">void</span> MainWidget<span class="operator">::</span>initTextures()  
  2. {  
  3.     <span class="comment">// Load cube.png image</span>  
  4.     texture <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a target="_blank" href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span>(<span class="type"><a target="_blank" href="../qtgui/qimage.html">QImage</a></span>(<span class="string">":/cube.png"</span>)<span class="operator">.</span>mirrored());  
  5.   
  6.     <span class="comment">// Set nearest filtering mode for texture minification</span>  
  7.     texture<span class="operator">-</span><span class="operator">></span>setMinificationFilter(<span class="type"><a target="_blank" href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span><span class="operator">::</span>Nearest);  
  8.   
  9.     <span class="comment">// Set bilinear filtering mode for texture magnification</span>  
  10.     texture<span class="operator">-</span><span class="operator">></span>setMagnificationFilter(<span class="type"><a target="_blank" href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span><span class="operator">::</span>Linear);  
  11.   
  12.     <span class="comment">// Wrap texture coordinates by repeating</span>  
  13.     <span class="comment">// f.ex. texture coordinate (1.1, 1.2) is same as (0.1, 0.2)</span>  
  14.     texture<span class="operator">-</span><span class="operator">></span>setWrapMode(<span class="type"><a target="_blank" href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span><span class="operator">::</span>Repeat);  
  15. }  

Cube Geometry

There are many ways to render polygons in OpenGL but the most efficient way is to use only triangle strip primitives and render vertices from graphics hardware memory. OpenGL has a mechanism to create buffer objects to this memory area and transfer vertex data to these buffers. In OpenGL terminology these are referred as Vertex Buffer Objects (VBO).

Cube faces and vertices

This is how cube faces break down to triangles. Vertices are ordered this way to get vertex ordering correct using triangle strips. OpenGL determines triangle front and back face based on vertex ordering. By default OpenGL uses counter-clockwise order for front faces. This information is used by back face culling which improves rendering performance by not rendering back faces of the triangles. This way graphics pipeline can omit rendering sides of the triangle that aren't facing towards screen.

Creating vertex buffer objects and transferring data to them is quite simple using QOpenGLBuffer. MainWidget makes sure the GeometryEngine instance is created and destroyed with the OpenGL context current. This way we can use OpenGL resources in the constructor and perform proper cleanup in the destructor.

[cpp] view plain copy
  1. GeometryEngine<span class="operator">::</span>GeometryEngine()  
  2.     : indexBuf(<span class="type"><a target="_blank" href="../qtgui/qopenglbuffer.html">QOpenGLBuffer</a></span><span class="operator">::</span>IndexBuffer)  
  3. {  
  4.     initializeOpenGLFunctions();  
  5.   
  6.     <span class="comment">// Generate 2 VBOs</span>  
  7.     arrayBuf<span class="operator">.</span>create();  
  8.     indexBuf<span class="operator">.</span>create();  
  9.   
  10.     <span class="comment">// Initializes cube geometry and transfers it to VBOs</span>  
  11.     initCubeGeometry();  
  12. }  
  13.   
  14. GeometryEngine<span class="operator">::</span><span class="operator">~</span>GeometryEngine()  
  15. {  
  16.     arrayBuf<span class="operator">.</span>destroy();  
  17.     indexBuf<span class="operator">.</span>destroy();  
  18. }  
  19.     <span class="comment">// Transfer vertex data to VBO 0</span>  
  20.     arrayBuf<span class="operator">.</span>bind();  
  21.     arrayBuf<span class="operator">.</span>allocate(vertices<span class="operator">,</span> <span class="number">24</span> <span class="operator">*</span> <span class="keyword">sizeof</span>(VertexData));  
  22.   
  23.     <span class="comment">// Transfer index data to VBO 1</span>  
  24.     indexBuf<span class="operator">.</span>bind();  
  25.     indexBuf<span class="operator">.</span>allocate(indices<span class="operator">,</span> <span class="number">34</span> <span class="operator">*</span> <span class="keyword">sizeof</span>(GLushort));  

Drawing primitives from VBOs and telling programmable graphics pipeline how to locate vertex data requires few steps. First we need to bind VBOs to be used. After that we bind shader program attribute names and configure what kind of data it has in the bound VBO. Finally we'll draw triangle strip primitives using indices from the other VBO.


[cpp] view plain copy
  1. <span class="type">void</span> GeometryEngine<span class="operator">::</span>drawCubeGeometry(<span class="type"><a target="_blank" href="../qtgui/qopenglshaderprogram.html">QOpenGLShaderProgram</a></span> <span class="operator">*</span>program)  
  2. {  
  3.     <span class="comment">// Tell OpenGL which VBOs to use</span>  
  4.     arrayBuf<span class="operator">.</span>bind();  
  5.     indexBuf<span class="operator">.</span>bind();  
  6.   
  7.     <span class="comment">// Offset for position</span>  
  8.     quintptr offset <span class="operator">=</span> <span class="number">0</span>;  
  9.   
  10.     <span class="comment">// Tell OpenGL programmable pipeline how to locate vertex position data</span>  
  11.     <span class="type">int</span> vertexLocation <span class="operator">=</span> program<span class="operator">-</span><span class="operator">></span>attributeLocation(<span class="string">"a_position"</span>);  
  12.     program<span class="operator">-</span><span class="operator">></span>enableAttributeArray(vertexLocation);  
  13.     program<span class="operator">-</span><span class="operator">></span>setAttributeBuffer(vertexLocation<span class="operator">,</span> GL_FLOAT<span class="operator">,</span> offset<span class="operator">,</span> <span class="number">3</span><span class="operator">,</span> <span class="keyword">sizeof</span>(VertexData));  
  14.   
  15.     <span class="comment">// Offset for texture coordinate</span>  
  16.     offset <span class="operator">+</span><span class="operator">=</span> <span class="keyword">sizeof</span>(QVector3D);  
  17.   
  18.     <span class="comment">// Tell OpenGL programmable pipeline how to locate vertex texture coordinate data</span>  
  19.     <span class="type">int</span> texcoordLocation <span class="operator">=</span> program<span class="operator">-</span><span class="operator">></span>attributeLocation(<span class="string">"a_texcoord"</span>);  
  20.     program<span class="operator">-</span><span class="operator">></span>enableAttributeArray(texcoordLocation);  
  21.     program<span class="operator">-</span><span class="operator">></span>setAttributeBuffer(texcoordLocation<span class="operator">,</span> GL_FLOAT<span class="operator">,</span> offset<span class="operator">,</span> <span class="number">2</span><span class="operator">,</span> <span class="keyword">sizeof</span>(VertexData));  
  22.   
  23.     <span class="comment">// Draw cube geometry using indices from VBO 1</span>  
  24.     glDrawElements(GL_TRIANGLE_STRIP<span class="operator">,</span> <span class="number">34</span><span class="operator">,</span> GL_UNSIGNED_SHORT<span class="operator">,</span> <span class="number">0</span>);  
  25. }  

Perspective Projection

Using QMatrix4x4 helper methods it's really easy to calculate perpective projection matrix. This matrix is used to project vertices to screen space.

[cpp] view plain copy
  1. <span class="type">void</span> MainWidget<span class="operator">::</span>resizeGL(<span class="type">int</span> w<span class="operator">,</span> <span class="type">int</span> h)  
  2. {  
  3.     <span class="comment">// Calculate aspect ratio</span>  
  4.     <span class="type"><a target="_blank" href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span> aspect <span class="operator">=</span> <span class="type"><a target="_blank" href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span>(w) <span class="operator">/</span> <span class="type"><a target="_blank" href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span>(h <span class="operator">?</span> h : <span class="number">1</span>);  
  5.   
  6.     <span class="comment">// Set near plane to 3.0, far plane to 7.0, field of view 45 degrees</span>  
  7.     <span class="keyword">const</span> <span class="type"><a target="_blank" href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span> zNear <span class="operator">=</span> <span class="number">3.0</span><span class="operator">,</span> zFar <span class="operator">=</span> <span class="number">7.0</span><span class="operator">,</span> fov <span class="operator">=</span> <span class="number">45.0</span>;  
  8.   
  9.     <span class="comment">// Reset projection</span>  
  10.     projection<span class="operator">.</span>setToIdentity();  
  11.   
  12.     <span class="comment">// Set perspective projection</span>  
  13.     projection<span class="operator">.</span>perspective(fov<span class="operator">,</span> aspect<span class="operator">,</span> zNear<span class="operator">,</span> zFar);  
  14. }  

Orientation of the 3D Object

Quaternions are handy way to represent orientation of the 3D object. Quaternions involve quite complex mathematics but fortunately all the necessary mathematics behind quaternions is implemented in QQuaternion. That allows us to store cube orientation in quaternion and rotating cube around given axis is quite simple.

The following code calculates rotation axis and angular speed based on mouse events.

[cpp] view plain copy
  1. <span class="type">void</span> MainWidget<span class="operator">::</span>mousePressEvent(<span class="type"><a target="_blank" href="../qtgui/qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e)  
  2. {  
  3.     <span class="comment">// Save mouse press position</span>  
  4.     mousePressPosition <span class="operator">=</span> QVector2D(e<span class="operator">-</span><span class="operator">></span>localPos());  
  5. }  
  6.   
  7. <span class="type">void</span> MainWidget<span class="operator">::</span>mouseReleaseEvent(<span class="type"><a target="_blank" href="../qtgui/qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e)  
  8. {  
  9.     <span class="comment">// Mouse release position - mouse press position</span>  
  10.     QVector2D diff <span class="operator">=</span> QVector2D(e<span class="operator">-</span><span class="operator">></span>localPos()) <span class="operator">-</span> mousePressPosition;  
  11.   
  12.     <span class="comment">// Rotation axis is perpendicular to the mouse position difference</span>  
  13.     <span class="comment">// vector</span>  
  14.     QVector3D n <span class="operator">=</span> QVector3D(diff<span class="operator">.</span>y()<span class="operator">,</span> diff<span class="operator">.</span>x()<span class="operator">,</span> <span class="number">0.0</span>)<span class="operator">.</span>normalized();  
  15.   
  16.     <span class="comment">// Accelerate angular speed relative to the length of the mouse sweep</span>  
  17.     <span class="type"><a target="_blank" href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span> acc <span class="operator">=</span> diff<span class="operator">.</span>length() <span class="operator">/</span> <span class="number">100.0</span>;  
  18.   
  19.     <span class="comment">// Calculate new rotation axis as weighted sum</span>  
  20.     rotationAxis <span class="operator">=</span> (rotationAxis <span class="operator">*</span> angularSpeed <span class="operator">+</span> n <span class="operator">*</span> acc)<span class="operator">.</span>normalized();  
  21.   
  22.     <span class="comment">// Increase angular speed</span>  
  23.     angularSpeed <span class="operator">+</span><span class="operator">=</span> acc;  
  24. }  

QBasicTimer is used to animate scene and update cube orientation. Rotations can be concatenated simply by multiplying quaternions.

[cpp] view plain copy
  1. <span class="type">void</span> MainWidget<span class="operator">::</span>timerEvent(<span class="type"><a target="_blank" href="../qtcore/qtimerevent.html">QTimerEvent</a></span> <span class="operator">*</span>)  
  2. {  
  3.     <span class="comment">// Decrease angular speed (friction)</span>  
  4.     angularSpeed <span class="operator">*</span><span class="operator">=</span> <span class="number">0.99</span>;  
  5.   
  6.     <span class="comment">// Stop rotation when speed goes below threshold</span>  
  7.     <span class="keyword">if</span> (angularSpeed <span class="operator"><</span> <span class="number">0.01</span>) {  
  8.         angularSpeed <span class="operator">=</span> <span class="number">0.0</span>;  
  9.     } <span class="keyword">else</span> {  
  10.         <span class="comment">// Update rotation</span>  
  11.         rotation <span class="operator">=</span> <span class="type"><a target="_blank" href="../qtgui/qquaternion.html">QQuaternion</a></span><span class="operator">::</span>fromAxisAndAngle(rotationAxis<span class="operator">,</span> angularSpeed) <span class="operator">*</span> rotation;  
  12.   
  13.         <span class="comment">// Request an update</span>  
  14.         update();  
  15.     }  
  16. }  

Model-view matrix is calculated using the quaternion and by moving world by Z axis. This matrix is multiplied with the projection matrix to get MVP matrix for shader program.

[cpp] view plain copy
  1. <span class="comment">// Calculate model view transformation</span>  
  2. QMatrix4x4 matrix;  
  3. matrix<span class="operator">.</span>translate(<span class="number">0.0</span><span class="operator">,</span> <span class="number">0.0</span><span class="operator">,</span> <span class="operator">-</span><span class="number">5.0</span>);  
  4. matrix<span class="operator">.</span>rotate(rotation);  
  5.   
  6. <span class="comment">// Set modelview-projection matrix</span>  
  7. program<span class="operator">.</span>setUniformValue(<span class="string">"mvp_matrix"</span><span class="operator">,</span> projection <span class="operator">*</span> matrix);  

Files:

  • cube/fshader.glsl
  • cube/geometryengine.cpp
  • cube/geometryengine.h
  • cube/mainwidget.cpp
  • cube/mainwidget.h
  • cube/vshader.glsl
  • cube/main.cpp
  • cube/cube.pro
  • cube/shaders.qrc
  • cube/textures.qrc


from: http://blog.csdn.net/fu851523125/article/details/51169440



0 0
原创粉丝点击