Sophie

Sophie

distrib > Mageia > 7 > armv7hl > media > core-updates > by-pkgid > d5e62c01ae8d1e579463c6a871dd44bf > files > 2383

qtbase5-doc-5.12.6-2.mga7.noarch.rpm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- cube.qdoc -->
  <title>Cube OpenGL ES 2.0 example | Qt OpenGL</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td >Qt 5.12</td><td ><a href="qtopengl-index.html">Qt OpenGL</a></td><td ><a href="examples-widgets-opengl.html">OpenGL Examples from the Qt OpenGL module</a></td><td >Cube OpenGL ES 2.0 example</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right"><a href="qtopengl-index.html">Qt 5.12.6 Reference Documentation</a></td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#initializing-opengl-es-2-0">Initializing OpenGL ES 2.0</a></li>
<li class="level1"><a href="#loading-textures-from-qt-resource-files">Loading Textures from Qt Resource Files</a></li>
<li class="level1"><a href="#cube-geometry">Cube Geometry</a></li>
<li class="level1"><a href="#perspective-projection">Perspective Projection</a></li>
<li class="level1"><a href="#orientation-of-the-3d-object">Orientation of the 3D Object</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Cube OpenGL ES 2.0 example</h1>
<span class="subtitle"></span>
<!-- $$$cube-brief -->
<p>The Cube OpenGL ES 2.0 example shows how to write mouse rotateable textured 3D cube using OpenGL ES 2.0 with Qt. It shows how to handle polygon geometries efficiently and how to write simple vertex and fragment shader for programmable graphics pipeline. In addition it shows how to use quaternions for representing 3D object orientation.</p>
<!-- @@@cube -->
<!-- $$$cube-description -->
<div class="descr"> <a name="details"></a>
<p>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.</p>
<p class="centerAlign"><img src="images/cube.png" alt="Screenshot of the Cube example running on N900" /></p><p>The example consist of two classes:</p>
<ul>
<li><code>MainWidget</code> extends QGLWidget and contains OpenGL ES 2.0 initialization and drawing and mouse and timer event handling</li>
<li><code>GeometryEngine</code> handles polygon geometries. Transfers polygon geometry to vertex buffer objects and draws geometries from vertex buffer objects.</li>
</ul>
<p>We'll start by initializing OpenGL ES 2.0 in <code>MainWidget</code>.</p>
<a name="initializing-opengl-es-2-0"></a>
<h2 id="initializing-opengl-es-2-0">Initializing OpenGL ES 2.0</h2>
<p>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.</p>
<p>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.</p>
<pre class="cpp">

  void main()
  {
      // Calculate vertex position in screen space
      gl_Position = mvp_matrix * a_position;

      // Pass texture coordinate to fragment shader
      // Value will be automatically interpolated to fragments inside polygon faces
      v_texcoord = a_texcoord;
  }

</pre>
<p>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.</p>
<pre class="cpp">

  void main()
  {
      // Set fragment color from texture
      gl_FragColor = texture2D(texture, v_texcoord);
  }

</pre>
<p>Using <code>QGLShaderProgram</code> we can compile, link and bind shader code to graphics pipeline. This code uses Qt Resource files to access shader source code.</p>
<pre class="cpp">

  <span class="type">void</span> MainWidget<span class="operator">::</span>initShaders()
  {
      <span class="comment">// Compile vertex shader</span>
      <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>addShaderFromSourceFile(<span class="type"><a href="../qtgui/qopenglshader.html">QOpenGLShader</a></span><span class="operator">::</span>Vertex<span class="operator">,</span> <span class="string">&quot;:/vshader.glsl&quot;</span>))
          close();

      <span class="comment">// Compile fragment shader</span>
      <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>addShaderFromSourceFile(<span class="type"><a href="../qtgui/qopenglshader.html">QOpenGLShader</a></span><span class="operator">::</span>Fragment<span class="operator">,</span> <span class="string">&quot;:/fshader.glsl&quot;</span>))
          close();

      <span class="comment">// Link shader pipeline</span>
      <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>link())
          close();

      <span class="comment">// Bind shader pipeline for use</span>
      <span class="keyword">if</span> (<span class="operator">!</span>program<span class="operator">.</span>bind())
          close();
  }

</pre>
<p>The following code enables depth buffering and back face culling.</p>
<pre class="cpp">

      <span class="comment">// Enable depth buffer</span>
      glEnable(GL_DEPTH_TEST);

      <span class="comment">// Enable back face culling</span>
      glEnable(GL_CULL_FACE);

</pre>
<a name="loading-textures-from-qt-resource-files"></a>
<h2 id="loading-textures-from-qt-resource-files">Loading Textures from Qt Resource Files</h2>
<p><code>QGLWidget</code> interface implements methods for loading textures from <a href="../qtgui/qimage.html">QImage</a> to GL texture memory. We still need to use OpenGL provided functions for specifying the GL texture unit and configuring texture filtering options.</p>
<pre class="cpp">

  <span class="type">void</span> MainWidget<span class="operator">::</span>initTextures()
  {
      <span class="comment">// Load cube.png image</span>
      texture <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span>(<span class="type"><a href="../qtgui/qimage.html">QImage</a></span>(<span class="string">&quot;:/cube.png&quot;</span>)<span class="operator">.</span>mirrored());

      <span class="comment">// Set nearest filtering mode for texture minification</span>
      texture<span class="operator">-</span><span class="operator">&gt;</span>setMinificationFilter(<span class="type"><a href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span><span class="operator">::</span>Nearest);

      <span class="comment">// Set bilinear filtering mode for texture magnification</span>
      texture<span class="operator">-</span><span class="operator">&gt;</span>setMagnificationFilter(<span class="type"><a href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span><span class="operator">::</span>Linear);

      <span class="comment">// Wrap texture coordinates by repeating</span>
      <span class="comment">// f.ex. texture coordinate (1.1, 1.2) is same as (0.1, 0.2)</span>
      texture<span class="operator">-</span><span class="operator">&gt;</span>setWrapMode(<span class="type"><a href="../qtgui/qopengltexture.html">QOpenGLTexture</a></span><span class="operator">::</span>Repeat);
  }

</pre>
<a name="cube-geometry"></a>
<h2 id="cube-geometry">Cube Geometry</h2>
<p>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).</p>
<p class="centerAlign"><img src="images/cube_faces.png" alt="Cube faces and vertices" /></p><p>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.</p>
<p>Creating vertex buffer objects and transferring data to them is quite simple using <a href="../qtgui/qopenglbuffer.html">QOpenGLBuffer</a>. 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.</p>
<pre class="cpp">

  GeometryEngine<span class="operator">::</span>GeometryEngine()
      : indexBuf(<span class="type"><a href="../qtgui/qopenglbuffer.html">QOpenGLBuffer</a></span><span class="operator">::</span>IndexBuffer)
  {
      initializeOpenGLFunctions();

      <span class="comment">// Generate 2 VBOs</span>
      arrayBuf<span class="operator">.</span>create();
      indexBuf<span class="operator">.</span>create();

      <span class="comment">// Initializes cube geometry and transfers it to VBOs</span>
      initCubeGeometry();
  }

  GeometryEngine<span class="operator">::</span><span class="operator">~</span>GeometryEngine()
  {
      arrayBuf<span class="operator">.</span>destroy();
      indexBuf<span class="operator">.</span>destroy();
  }
      <span class="comment">// Transfer vertex data to VBO 0</span>
      arrayBuf<span class="operator">.</span>bind();
      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));

      <span class="comment">// Transfer index data to VBO 1</span>
      indexBuf<span class="operator">.</span>bind();
      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));

</pre>
<p>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.</p>
<pre class="cpp">

  <span class="type">void</span> GeometryEngine<span class="operator">::</span>drawCubeGeometry(<span class="type"><a href="../qtgui/qopenglshaderprogram.html">QOpenGLShaderProgram</a></span> <span class="operator">*</span>program)
  {
      <span class="comment">// Tell OpenGL which VBOs to use</span>
      arrayBuf<span class="operator">.</span>bind();
      indexBuf<span class="operator">.</span>bind();

      <span class="comment">// Offset for position</span>
      quintptr offset <span class="operator">=</span> <span class="number">0</span>;

      <span class="comment">// Tell OpenGL programmable pipeline how to locate vertex position data</span>
      <span class="type">int</span> vertexLocation <span class="operator">=</span> program<span class="operator">-</span><span class="operator">&gt;</span>attributeLocation(<span class="string">&quot;a_position&quot;</span>);
      program<span class="operator">-</span><span class="operator">&gt;</span>enableAttributeArray(vertexLocation);
      program<span class="operator">-</span><span class="operator">&gt;</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));

      <span class="comment">// Offset for texture coordinate</span>
      offset <span class="operator">+</span><span class="operator">=</span> <span class="keyword">sizeof</span>(QVector3D);

      <span class="comment">// Tell OpenGL programmable pipeline how to locate vertex texture coordinate data</span>
      <span class="type">int</span> texcoordLocation <span class="operator">=</span> program<span class="operator">-</span><span class="operator">&gt;</span>attributeLocation(<span class="string">&quot;a_texcoord&quot;</span>);
      program<span class="operator">-</span><span class="operator">&gt;</span>enableAttributeArray(texcoordLocation);
      program<span class="operator">-</span><span class="operator">&gt;</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));

      <span class="comment">// Draw cube geometry using indices from VBO 1</span>
      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>);
  }

</pre>
<a name="perspective-projection"></a>
<h2 id="perspective-projection">Perspective Projection</h2>
<p>Using <code>QMatrix4x4</code> helper methods it's really easy to calculate perpective projection matrix. This matrix is used to project vertices to screen space.</p>
<pre class="cpp">

  <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)
  {
      <span class="comment">// Calculate aspect ratio</span>
      <span class="type"><a href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span> aspect <span class="operator">=</span> <span class="type"><a href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span>(w) <span class="operator">/</span> <span class="type"><a href="../qtcore/qtglobal.html#qreal-typedef">qreal</a></span>(h <span class="operator">?</span> h : <span class="number">1</span>);

      <span class="comment">// Set near plane to 3.0, far plane to 7.0, field of view 45 degrees</span>
      <span class="keyword">const</span> <span class="type"><a 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>;

      <span class="comment">// Reset projection</span>
      projection<span class="operator">.</span>setToIdentity();

      <span class="comment">// Set perspective projection</span>
      projection<span class="operator">.</span>perspective(fov<span class="operator">,</span> aspect<span class="operator">,</span> zNear<span class="operator">,</span> zFar);
  }

</pre>
<a name="orientation-of-the-3d-object"></a>
<h2 id="orientation-of-the-3d-object">Orientation of the 3D Object</h2>
<p>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 <code>QQuaternion</code>. That allows us to store cube orientation in quaternion and rotating cube around given axis is quite simple.</p>
<p>The following code calculates rotation axis and angular speed based on mouse events.</p>
<pre class="cpp">

  <span class="type">void</span> MainWidget<span class="operator">::</span>mousePressEvent(<span class="type"><a href="../qtgui/qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e)
  {
      <span class="comment">// Save mouse press position</span>
      mousePressPosition <span class="operator">=</span> QVector2D(e<span class="operator">-</span><span class="operator">&gt;</span>localPos());
  }

  <span class="type">void</span> MainWidget<span class="operator">::</span>mouseReleaseEvent(<span class="type"><a href="../qtgui/qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e)
  {
      <span class="comment">// Mouse release position - mouse press position</span>
      QVector2D diff <span class="operator">=</span> QVector2D(e<span class="operator">-</span><span class="operator">&gt;</span>localPos()) <span class="operator">-</span> mousePressPosition;

      <span class="comment">// Rotation axis is perpendicular to the mouse position difference</span>
      <span class="comment">// vector</span>
      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();

      <span class="comment">// Accelerate angular speed relative to the length of the mouse sweep</span>
      <span class="type"><a 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>;

      <span class="comment">// Calculate new rotation axis as weighted sum</span>
      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();

      <span class="comment">// Increase angular speed</span>
      angularSpeed <span class="operator">+</span><span class="operator">=</span> acc;
  }

</pre>
<p><code>QBasicTimer</code> is used to animate scene and update cube orientation. Rotations can be concatenated simply by multiplying quaternions.</p>
<pre class="cpp">

  <span class="type">void</span> MainWidget<span class="operator">::</span>timerEvent(<span class="type"><a href="../qtcore/qtimerevent.html">QTimerEvent</a></span> <span class="operator">*</span>)
  {
      <span class="comment">// Decrease angular speed (friction)</span>
      angularSpeed <span class="operator">*</span><span class="operator">=</span> <span class="number">0.99</span>;

      <span class="comment">// Stop rotation when speed goes below threshold</span>
      <span class="keyword">if</span> (angularSpeed <span class="operator">&lt;</span> <span class="number">0.01</span>) {
          angularSpeed <span class="operator">=</span> <span class="number">0.0</span>;
      } <span class="keyword">else</span> {
          <span class="comment">// Update rotation</span>
          rotation <span class="operator">=</span> <span class="type"><a href="../qtgui/qquaternion.html">QQuaternion</a></span><span class="operator">::</span>fromAxisAndAngle(rotationAxis<span class="operator">,</span> angularSpeed) <span class="operator">*</span> rotation;

          <span class="comment">// Request an update</span>
          update();
      }
  }

</pre>
<p>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.</p>
<pre class="cpp">

      <span class="comment">// Calculate model view transformation</span>
      QMatrix4x4 matrix;
      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>);
      matrix<span class="operator">.</span>rotate(rotation);

      <span class="comment">// Set modelview-projection matrix</span>
      program<span class="operator">.</span>setUniformValue(<span class="string">&quot;mvp_matrix&quot;</span><span class="operator">,</span> projection <span class="operator">*</span> matrix);

</pre>
<p>Files:</p>
<ul>
<li><a href="qtopengl-cube-cube-pro.html">cube/cube.pro</a></li>
<li><a href="qtopengl-cube-fshader-glsl.html">cube/fshader.glsl</a></li>
<li><a href="qtopengl-cube-geometryengine-cpp.html">cube/geometryengine.cpp</a></li>
<li><a href="qtopengl-cube-geometryengine-h.html">cube/geometryengine.h</a></li>
<li><a href="qtopengl-cube-main-cpp.html">cube/main.cpp</a></li>
<li><a href="qtopengl-cube-mainwidget-cpp.html">cube/mainwidget.cpp</a></li>
<li><a href="qtopengl-cube-mainwidget-h.html">cube/mainwidget.h</a></li>
<li><a href="qtopengl-cube-shaders-qrc.html">cube/shaders.qrc</a></li>
<li><a href="qtopengl-cube-textures-qrc.html">cube/textures.qrc</a></li>
<li><a href="qtopengl-cube-vshader-glsl.html">cube/vshader.glsl</a></li>
</ul>
<p>Images:</p>
<ul>
<li><a href="images/used-in-examples/cube/cube.png">cube/cube.png</a></li>
</ul>
</div>
<!-- @@@cube -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2019 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br/>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br/>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>