OpenGL Development Cookbook

OpenGL Development Cookbook Over 40 recipes to help you learn, understand, and implement modern OpenGL in your applications Muhammad Mobeen Movania BIRMINGHAM - MUMBAI OpenGL Development Cookbook Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: June 2013 Production Reference: 1180613 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-504-6 Cover Image by Duraid Fatouhi ( Credits Author Muhammad Mobeen Movania Reviewers Bastien Berthe Dimitrios Christopoulos Oscar Ripolles Mateu Acquisition Editor Erol Staveley Commisioning Editor Shreerang Deshpande Lead Technical Editor Madhuja Chaudhari Technical Editors Jeeten Handu Sharvari H. Baet Ankita R. Meshram Priyanka Kalekar Project Coordinator Rahul Dixit Proofreaders Stephen Silk Lauren Tobon Indexer Tejal R. Soni Graphics Abhinash Sahu Production Coordinator Aparna Bhagat Cover Work Aparna Bhagat About the Author Muhammad Mobeen Movania received his PhD degree in Advance Computer Graphics and Visualization from Nanyang Technological Unviversity (NTU), Singapore. He completed his Bachelors of Science Honors (BCS(H)) in Computer Sciences from Iqra University, Karachi with majors in Computer Graphics and Multimedia. Before joining NTU, he was a junior graphics programmer at Data Communication and Control (DCC) Pvt. Ltd., Karachi, Pakistan. He was working on DirectX and OpenGL API for producing real-time interactive tactical simulators and dynamic integrated training simulators. His research interests include GPU-based volumetric rendering techniques, GPU technologies, real-time soft body physics, real-time dynamic shadows, real-time collision detection and response, and hierarchical geometric data structures. He authored a book chapter in a recent OpenGL book (OpenGL Insights: AK Peters/CRC Press). He is also the author of the OpenCloth project ( com/p/opencloth), which implements various cloth simulation algorithms in OpenGL. His blog ( lists a lot of useful graphics tips and tricks. When not involved with computer graphics, he composes music and is an avid squash player. He is currently working at a research institute in Singapore. I would like to thank my family: my parents (Mr. and Mrs. Abdul Aziz Movania), my wife (Tanveer Taji), my brothers and sisters (Mr. Muhammad Khalid Movania, Mrs. Azra Saleem, Mrs. Sajida Shakir, and Mr. Abdul Majid Movania), my nephews/nieces, and my new born baby daughter (Muntaha Movania). About the Reviewers Bastien Berthe is a young and passionate 3D programmer. Always attracted by 3D and video games, after a few years of studying in France, he went to the Sherbrooke University in Canada and received a postgraduate degree in Computer Science, specializing in real-time systems, 3D visualization, and video games development. He is now working as a 3D Graphics Specialist Consultant at CAE (Montreal, QC) since 2012 and, more precisely, he is working on a new generation simulator's visualization system using mainly OpenSceneGraph and OpenGL. CAE ( is a global leader in modeling, simulation, and training for civil aviation, defence, healthcare, and mining. Dimitrios Christopoulos studied Computer Engineering and informatics at the University of Patras, Greece and holds a Master of Science (MSc) in Virtual Reality and Computer Graphics from the University of Hull in Great Britain. He started game programming in the '80s, and has been using OpenGL since 1997 for games, demos, European Union research projects, museum exhibits, and virtual reality productions. His research interests include virtual reality, human computer interaction, computer graphics, and games, with numerous publications in relevant conferences and journals. He coauthored the book More OpenGL Game Programming, Cengage Learning PTR and has also contributed to OpenGL Game Programming. He currently works as a virtual reality and 3D graphics software engineer producing games, educational applications, and cultural heritage productions for virtual reality installations. Oscar Ripolles received his degree in Computer Engineering in 2004 and his Ph.D. in 2009 at the Universitat Jaume I in Castellon, Spain. He has also been a researcher at the Université de Limoges, France and at the Universidad Politecnica de Valencia, Spain. He is currently working in neuroimaging at Neuroelectrics in Barcelona, Spain. His research interests include multiresolution modeling, geometry optimization, hardware programming, and medical imaging. Support files, eBooks, discount offers and more You might want to visit for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details. At, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.  Why Subscribe? ff Fully searchable across every book published by Packt ff Copy and paste, print and bookmark content ff On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: Introduction to Modern OpenGL 7 Introduction 7 Setting up the OpenGL v3.3 core profile on Visual Studio 2010 using the GLEW and freeglut libraries 8 Designing a GLSL shader class 16 Rendering a simple colored triangle using shaders 19 Doing a ripple mesh deformer using the vertex shader 28 Dynamically subdividing a plane using the geometry shader 37 Dynamically subdividing a plane using the geometry shader with instanced rendering 45 Drawing a 2D image in a window using the fragment shader and the SOIL image loading library 48 Chapter 2: 3D Viewing and Object Picking 55 Introduction 55 Implementing a vector-based camera with FPS style input support 56 Implementing the free camera 59 Implementing the target camera 63 Implementing view frustum culling 66 Implementing object picking using the depth buffer 72 Implementing object picking using color 74 Implementing object picking using scene intersection queries 76 Chapter 3: Offscreen Rendering and Environment Mapping 81 Introduction 81 Implementing the twirl filter using fragment shader 82 Rendering a skybox using the static cube mapping 85 Implementing a mirror with render-to-texture using FBO 89 ii Table of Contents Rendering a reflective object using dynamic cube mapping 93 Implementing area filtering (sharpening/blurring/embossing) on an image using convolution 98 Implementing the glow effect 101 Chapter 4: Lights and Shadows 107 Introduction 107 Implementing per-vertex and per-fragment point lighting 108 Implementing per-fragment directional light 114 Implementing per-fragment point light with attenuation 117 Implementing per-fragment spot light 120 Implementing shadow mapping with FBO 122 Implemeting shadow mapping with percentage closer filtering (PCF) 128 Implementing variance shadow mapping 132 Chapter 5: Mesh Model Formats and Particle Systems 141 Introduction 141 Implementing terrains using the height map 142 Implementing 3ds model loading using separate buffers 146 Implementing OBJ model loading using interleaved buffers 157 Implementing EZMesh model loading 163 Implementing simple particle system 171 Chapter 6: GPU-based Alpha Blending and Global Illumination 181 Introduction 181 Implementing order-independent transparency using front-to-back peeling 182 Implementing order-independent transparency using dual depth peeling 189 Implementing screen space ambient occlusion (SSAO) 195 Implementing global illumination using spherical harmonics lighting 202 Implementing GPU-based ray tracing 207 Implementing GPU-based path tracing 213 Chapter 7: GPU-based Volume Rendering Techniques 219 Introduction 219 Implementing volume rendering using 3D texture slicing 220 Implementing volume rendering using single-pass GPU ray casting 228 Implementing pseudo-isosurface rendering in single-pass GPU ray casting 232 Implementing volume rendering using splatting 237 Implementing transfer function for volume classification 244 Implementing polygonal isosurface extraction using the Marching Tetrahedra algorithm 248 Implementing volumetric lighting using the half-angle slicing 254 iii Table of Contents Chapter 8: Skeletal and Physically-based Simulation on the GPU 261 Introduction 261 Implementing skeletal animation using matrix palette skinning 262 Implementing skeletal animation using dual quaternion skinning 273 Modeling cloth using transform feedback 279 Implementing collision detection and response on a transform feedback-based cloth model 290 Implementing a particle system using transform feedback 296 Index 307 Preface This book is based on modern OpenGL v3.3 and above. It covers a myriad of topics of interest ranging from basic camera models and view frustum culling to advanced topics, such as dual quaternion skinning and GPU based simulation techniques. The book follows the cookbook format whereby a number of steps are detailed showing how to accomplish a specific task and are later dissected to show how the whole technique works. The book starts with a gentle introduction to modern OpenGL. It then elaborates how to set up a basic shader application. Following this discussion, all shader stages are introduced using practical examples so that readers may understand how the different stages of the modern GPU pipeline work. Following the introductory chapter, a vector-based camera viewing model is presented with two camera types: target and free camera. In addition, we also detail how to carry out picking in modern OpenGL using depth buffer, color buffer, and scene intersection queries. In simulation applications and games in particular, skybox is a very useful object. We will detail its implementation in a simple manner. For reflective objects, such as mirrors and dynamic reflections, render-to-texture functionality using FBO and dynamic cube mapping are detailed. In addition to graphics, image processing techniques are also presented to implement digital convolution filters using the fragment shader, and basic transformation, such as twirl is also detailed. Moreover, effects such as glow are also covered to enable rendering of glowing geometry. Seldom do we find a graphics application without light. Lights play an important role in portraying the mood of a scene. We will cover point, directional, and spot lights with attenuation and both per-vertex and per-fragment approaches. In addition, shadow mapping techniques are also covered including support of percentage closer filtering (PCF) and variance shadow mapping. Preface 2 In typical applications, more complex mesh models are used which are stored in external model files modeled in a 3D modeling package. We elaborate two techniques for loading such models by using separate and interleaved buffer objects. Concrete examples are given by parsing 3DS and OBJ model formats. These model loaders provide support for most attributes, including materials. Skeletal characters are introduced by a new skeletal animation format (the EZMesh format). We will see how to load such models with animation using both matrix palette skinning and dual quaternion skinning. Wherever possible, the recipes also detail pointers to external libraries and web addresses for more information. Fuzzy objects, such as smoke are often used to add special effects. Such objects are typically handled using a particle system. We introduce a stateless and a state-preserving particle system in detail. When a scene with a high depth complexity is presented, normal alpha blending techniques fail miserably. Hence, approaches such as depth peeling are used to render the geometry in the correct depth order with correct blending. We will take a look at the implementation of both the conventional front-to-back depth peeling as well as the more recent dual depth peeling approach. All steps needed in the process are detailed. With computer graphics, we are always pushing the limits of hardware to get a true life-like rendering. Lighting is one thing that can convincingly represent such a depiction. Unfortunately however, normal everyday lighting is impossible to simulate in real-time. The computer graphics community has developed various approximation methods for modeling of such lighting. These are grouped under global illumination techniques. The recipes elaborate two common approaches, spherical harmonics and screen space ambient occlusion, on the modern GPU. Finally, we present two additional methods for rendering scenes, namely, ray tracing and path tracing. Both of these methods have been detailed and implemented on the modern GPU. Computer graphics have influenced several different fields ranging from visual effects in movies to biomedical and engineering simulations. In the latter domain in particular, computer graphics and visualization methods have been widely adopted. Modern GPUs have tremendous horsepower, which can be utilized for advanced visualization methods, and volume rendering is one of them. We will take a look at several algorithms for volume rendering, namely view- aligned 3D texture slicing, single-pass GPU ray casting, pseudo-isosurface rendering, splatting, polygonal isosurface extraction using the Marching Tetrahedra algorithm, and half-angle slicing method for volumetric lighting. Physically-based simulations are an important class of algorithms that enable us to predict the motion of objects through approximations of the physical models. We harness the new transform feedback mechanism to carry out two physically-based simulations entirely on the GPU. We first present a model for cloth simulation (with collision detection and response) and then a model for particle system simulation on the modern GPU. In summary, this book contains a wealth of information from a wide array of topics. I had a lot of fun writing this book and I learned a lot of techniques on the way. I do hope that this book serves as a useful resource for others in the years to come. Preface 3 What this book covers Chapter 1, Introduction to Modern OpenGL, details how to set up a modern OpenGL v3.3 core profile application on Visual Studio 2010 professional version. Chapter 2, 3D Viewing and Object Picking, discusses how to implement a vector-based camera model for a viewing system. Two camera types are explained along with view frustum culling. Finally, object picking methods are also detailed. Chapter 3, Offscreen Rendering and Environment Mapping, explains how to use the framebuffer object (FBO) for offscreen rendering. Mirror and dynamic cube mapping are implemented. In addition, image processing using digital convolution and environment mapping using static cube mapping are also elaborated. Chapter 4, Lights and Shadows, discusses how to implement point, spot, and directional lights with attenuation. Moreover, methods of rendering dynamic shadows, such as shadow mapping, percentage close filtered (PCF) shadow maps, and variance shadow mapping are also covered in detail. Chapter 5, Mesh Model Formats and Particle Systems, shows how to parse standard model formats, such as 3DS and OBJ models using separate and interleaved buffer object formats. Skeletal animation format using the EZMesh model format is also detailed along with the simple particle system. Chapter 6, GPU-based Alpha Blending and Global Illumination, explains how to implement order-independent transparency with front-to-back and dual depth peeling. It also covers screen space ambient occlusion (SSAO) and the spherical harmonics method for image-based lighting and global illumination. Finally, alternate methods to render geometry, that is, GPU ray tracing and GPU path tracing are presented. Chapter 7, GPU-based Volume Rendering Techniques, discusses how to implement several volume rendering algorithms in modern OpenGL including view-aligned 3D texture slicing, single-pass GPU ray casting, splatting, pseudo-isosurface as well as polygonal isosurface rendering using Marching Tetrahedra algorithm. Volume classification and volume lighting using the half-angle slicing technique are also detailed. Chapter 8, Skeletal and Physically-based Simulation on the GPU, describes how to implement skeletal animation using matrix palette skinning and dual quaternion skinning on the modern GPU. In addition, it details how to use the transform feedback mode of the modern GPU for implementing a cloth simulation system with collision detection and response as well as particle systems entirely on the GPU. Preface 4 What you need for this book The book assumes that the reader has basic knowledge of using the OpenGL API. The example code distributed with this book contains Visual Studio 2010 Professional version project files. In order to build the source code, you will need freeglut, GLEW, GLM, and SOIL libraries. The code has been tested on a Windows 7 platform with an NVIDIA graphics card and the following versions of libraries: ff freeglut v2.8.0 (latest version available from: http://freeglut.sourceforge. net) ff GLEW v1.9.0 (latest version available from: ff GLM v0.9.4.0 (latest version available from: ff SOIL (latest version available from: We recommend using the latest version of these libraries. The code should compile and build fine with the latest libraries. Who this book is for This book is for intermediate graphics programmers who have working experience of any graphics API, but experience of OpenGL will be a definite plus. Introductory knowledge of GPU and graphics shaders will be an added advantage. The book and the accompanying code have been written with simplicity in mind. We have tried to keep it simple to understand. A wide array of topics are covered and step-by-step instructions are given on how to implement each technique. Detailed explanations are given that helps in comprehending the content of the book. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "The maximum number of color attachments supported on any GPU can be queried using the GL_MAX_COLOR_ATTACHMENTS field." A block of code is set as follows: for(int i=0;i<16;i++) { float indexA = (random(vec4(gl_FragCoord.xyx, i))*0.25); float indexB = (random(vec4(gl_FragCoord.yxy, i))*0.25); sum += textureProj(shadowMap, vShadowCoords + vec4(indexA, indexB, 0, 0)); } Preface 5 When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: void main() { vEyeSpacePosition = (MV*vec4(vVertex,1)).xyz; vEyeSpaceNormal = N*vNormal; vShadowCoords = S*(M*vec4(vVertex,1)); gl_Position = MVP*vec4(vVertex,1); } New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "by going to the Properties menu item in the Project menu". Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to, and mention the book title via the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Preface 6 Downloading the example code You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. Downloading the color images of this book We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from downloads/5046OT_ColoredImages.pdf. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it. 1 Introduction to Modern OpenGL In this chapter, we will cover: ff Setting up the OpenGL v3.3 core profile on Visual Studio 2010 using the GLEW and freeglut libraries ff Designing a GLSL shader class ff Rendering a simple colored triangle using shaders ff Doing a ripple mesh deformer using the vertex shader ff Dynamically subdividing a plane using the geometry shader ff Dynamically subdividing a plane using the geometry shader with instanced rendering ff Drawing a 2D image in a window using the fragment shader and SOIL image loading library Introduction The OpenGL API has seen various changes since its creation in 1992. With every new version, new features were added and additional functionality was exposed on supporting hardware through extensions. Until OpenGL v2.0 (which was introduced in 2004), the functionality in the graphics pipeline was fixed, that is, there were fixed set of operations hardwired in the graphics hardware and it was impossible to modify the graphics pipeline. With OpenGL v2.0, the shader objects were introduced for the first time. That enabled programmers to modify the graphics pipeline through special programs called shaders, which were written in a special language called OpenGL shading language (GLSL). Introduction to Modern OpenGL 8 After OpenGL v2.0, the next major version was v3.0. This version introduced two profiles for working with OpenGL; the core profile and the compatibility profile. The core profile basically contains all of the non-deprecated functionality whereas the compatibility profile retains deprecated functionality for backwards compatibility. As of 2012, the latest version of OpenGL available is OpenGL v4.3. Beyond OpenGL v3.0, the changes introduced in the application code are not as drastic as compared to those required for moving from OpenGL v2.0 to OpenGL v3.0 and above. In this chapter, we will introduce the three shader stages accessible in the OpenGL v3.3 core profile, that is, vertex, geometry, and fragment shaders. Note that OpenGL v4.0 introduced two additional shader stages that is tessellation control and tessellation evaluation shaders between the vertex and geometry shader. Setting up the OpenGL v3.3 core profile on Visual Studio 2010 using the GLEW and freeglut libraries We will start with a very basic example in which we will set up the modern OpenGL v3.3 core profile. This example will simply create a blank window and clear the window with red color. OpenGL or any other graphics API for that matter requires a window to display graphics in. This is carried out through platform specific codes. Previously, the GLUT library was invented to provide windowing functionality in a platform independent manner. However, this library was not maintained with each new OpenGL release. Fortunately, another independent project, freeglut, followed in the GLUT footsteps by providing similar (and in some cases better) windowing support in a platform independent way. In addition, it also helps with the creation of the OpenGL core/compatibility profile contexts. The latest version of freeglut may be downloaded from The version used in the source code accompanying this book is v2.8.0. After downloading the freeglut library, you will have to compile it to generate the libs/dlls. The extension mechanism provided by OpenGL still exists. To aid with getting the appropriate function pointers, the GLEW library is used. The latest version can be downloaded from http:// The version of GLEW used in the source code accompanying this book is v1.9.0. If the source release is downloaded, you will have to build GLEW first to generate the libs and dlls on your platform. You may also download the pre-built binaries. Prior to OpenGL v3.0, the OpenGL API provided support for matrices by providing specific matrix stacks such as the modelview, projection, and texture matrix stacks. In addition, transformation functions such as translate, rotate, and scale, as well as projection functions were also provided. Moreover, immediate mode rendering was supported, allowing application programmers to directly push the vertex information to the hardware. Chapter 1 9 In OpenGL v3.0 and above, all of these functionalities are removed from the core profile, whereas for backward compatibility they are retained in the compatibility profile. If we use the core profile (which is the recommended approach), it is our responsibility to implement all of these functionalities including all matrix handling and transformations. Fortunately, a library called glm exists that provides math related classes such as vectors and matrices. It also provides additional convenience functions and classes. For all of the demos in this book, we will use the glm library. Since this is a headers only library, there are no linker libraries for glm. The latest version of glm can be downloaded from The version used for the source code in this book is v0.9.4.0. There are several image formats available. It is not a trivial task to write an image loader for such a large number of image formats. Fortunately, there are several image loading libraries that make image loading a trivial task. In addition, they provide support for both loading as well as saving of images into various formats. One such library is the SOIL image loading library. The latest version of SOIL can be downloaded from soil.html. Once we have downloaded the SOIL library, we extract the file to a location on the hard disk. Next, we set up the include and library paths in the Visual Studio environment. The include path on my development machine is D:\Libraries\soil\Simple OpenGL Image Library\src whereas, the library path is set to D:\Libraries\soil\Simple OpenGL Image Library\lib\VC10_Debug. Of course, the path for your system will be different than mine but these are the folders that the directories should point to. These steps will help us to set up our development environment. For all of the recipes in this book, Visual Studio 2010 Professional version is used. Readers may also use the free express edition or any other version of Visual Studio (for example, Ultimate/Enterprise). Since there are a myriad of development environments, to make it easier for users on other platforms, we have provided premake script files as well. The code for this recipe is in the Chapter1/GettingStarted directory. Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub. com. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. Introduction to Modern OpenGL 10 How to do it... Let us setup the development environment using the following steps: 1. After downloading the required libraries, we set up the Visual Studio 2010 environment settings. 2. We first create a new Win32 Console Application project as shown in the preceding screenshot. We set up an empty Win32 project as shown in the following screenshot: Chapter 1 11 3. Next, we set up the include and library paths for the project by going into the Project menu and selecting project Properties. This opens a new dialog box. In the left pane, click on the Configuration Properties option and then on VC++ Directories. 4. In the right pane, in the Include Directories field, add the GLEW and freeglut subfolder paths. 5. Similarly, in the Library Directories, add the path to the lib subfolder of GLEW and freeglut libraries as shown in the following screenshot: 6. Next, we add a new .cpp file to the project and name it main.cpp. This is the main source file of our project. You may also browse through Chapter1/ GettingStarted/GettingStarted/main.cpp which does all this setup already. 7. Let us skim through the Chapter1/ GettingStarted/GettingStarted/main. cpp file piece by piece. #include #include #include These lines are the include files that we will add to all of our projects. The first is the GLEW header, the second is the freeglut header, and the final include is the standard input/output header. Introduction to Modern OpenGL 12 8. In Visual Studio, we can add the required linker libraries in two ways. The first way is through the Visual Studio environment (by going to the Properties menu item in the Project menu). This opens the project's property pages. In the configuration properties tree, we collapse the Linker subtree and click on the Input item. The first field in the right pane is Additional Dependencies. We can add the linker library in this field as shown in the following screenshot: 9. The second way is to add the glew32.lib file to the linker settings programmatically. This can be achieved by adding the following pragma: #pragma comment(lib, "glew32.lib") 10. The next line is the using directive to enable access to the functions in the std namespace. This is not mandatory but we include this here so that we do not have to prefix std:: to any standard library function from the iostream header file. using namespace std; 11. The next lines define the width and height constants which will be the screen resolution for the window. After these declarations, there are five function definitions . The OnInit() function is used for initializing any OpenGL state or object, OnShutdown() is used to delete an OpenGL object, OnResize() is used to handle the resize event, OnRender() helps to handle the paint event, and main() is the entry point of the application. We start with the definition of the main() function. const int WIDTH = 1280; const int HEIGHT = 960; Chapter 1 13 int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitContextVersion (3, 3); glutInitContextFlags (GLUT_CORE_PROFILE | GLUT_DEBUG); glutInitContextProfile(GLUT_FORWARD_COMPATIBLE); glutInitWindowSize(WIDTH, HEIGHT); 12. The first line glutInit initializes the GLUT environment. We pass the command line arguments to this function from our entry point. Next, we set up the display mode for our application. In this case, we request the GLUT framework to provide support for a depth buffer, double buffering (that is a front and a back buffer for smooth, flicker-free rendering), and the format of the frame buffer to be RGBA (that is with red, green, blue, and alpha channels). Next, we set the required OpenGL context version we desire by using the glutInitContextVersion. The first parameter is the major version of OpenGL and the second parameter is the minor version of OpenGL. For example, if we want to create an OpenGL v4.3 context, we will call glutInitContextVersion (4, 3). Next, the context flags are specified: glutInitContextFlags (GLUT_CORE_PROFILE | GLUT_DEBUG); glutInitContextProfile(GLUT_FORWARD_COMPATIBLE); In OpenGL v4.3, we can register a callback when any OpenGL related error occurs. Passing GLUT_DEBUG to the glutInitContextFlags functions creates the OpenGL context in debug mode which is needed for the debug message callback. 13. For any version of OpenGL including OpenGL v3.3 and above, there are two profiles available: the core profile (which is a pure shader based profile without support for OpenGL fixed functionality) and the compatibility profile (which supports the OpenGL fixed functionality). All of the matrix stack functionality glMatrixMode(*), glTranslate*, glRotate*, glScale*, and so on, and immediate mode calls such as glVertex*, glTexCoord*, and glNormal* of legacy OpenGL, are retained in the compatibility profile. However, they are removed from the core profile. In our case, we will request a forward compatible core profile which means that we will not have any fixed function OpenGL functionality available. 14. Next, we set the screen size and create the window: glutInitWindowSize(WIDTH, HEIGHT); glutCreateWindow("Getting started with OpenGL 3.3"); Introduction to Modern OpenGL 14 15. Next, we initialize the GLEW library. It is important to initialize the GLEW library after the OpenGL context has been created. If the function returns GLEW_OK the function succeeds, otherwise the GLEW initialization fails. glewExperimental = GL_TRUE; GLenum err = glewInit(); if (GLEW_OK != err){ cerr<<"Error: "<




需要 8 金币 [ 分享pdf获得金币 ] 2 人已下载





下载需要 8 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!