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 www.packtpub.com Cover Image by Duraid Fatouhi (duraidfatouhi@yahoo.com) 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 (http://code.google com/p/opencloth), which implements various cloth simulation algorithms in OpenGL His blog (http://mmmovania.blogspot.com) 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 (http://www.cae.com) 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 www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com 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 www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, 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 http://PacktLib.PacktPub.com 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 www.PacktPub.com, 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 Introduction 7 Setting up the OpenGL v3.3 core profile on Visual Studio 2010 using the GLEW and freeglut libraries 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 Chapter 3: Offscreen Rendering and Environment Mapping 81 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 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 Table of Contents Rendering a reflective object using dynamic cube mapping Implementing area filtering (sharpening/blurring/embossing) on an image using convolution Implementing the glow effect 93 98 101 Chapter 4: Lights and Shadows 107 Chapter 5: Mesh Model Formats and Particle Systems 141 Chapter 6: GPU-based Alpha Blending and Global Illumination 181 Chapter 7: GPU-based Volume Rendering Techniques 219 Introduction Implementing per-vertex and per-fragment point lighting Implementing per-fragment directional light Implementing per-fragment point light with attenuation Implementing per-fragment spot light Implementing shadow mapping with FBO Implemeting shadow mapping with percentage closer filtering (PCF) Implementing variance shadow mapping 107 108 114 117 120 122 128 132 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 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 Introduction Implementing volume rendering using 3D texture slicing Implementing volume rendering using single-pass GPU ray casting Implementing pseudo-isosurface rendering in single-pass GPU ray casting Implementing volume rendering using splatting Implementing transfer function for volume classification Implementing polygonal isosurface extraction using the Marching Tetrahedra algorithm Implementing volumetric lighting using the half-angle slicing ii 219 220 228 232 237 244 248 254 Table of Contents Chapter 8: Skeletal and Physically-based Simulation on the GPU Introduction Implementing skeletal animation using matrix palette skinning Implementing skeletal animation using dual quaternion skinning Modeling cloth using transform feedback Implementing collision detection and response on a transform feedback-based cloth model Implementing a particle system using transform feedback Index 261 261 262 273 279 290 296 307 iii Chapter How it works… The transform feedback mechanism allows us to feedback one or more attributes from the vertex shader or geometry shader back to a buffer object This feedback path could be used for implementing a physically-based simulation This recipe uses this mechanism to output the particle position after each iteration After each step, the buffers are swapped and, therefore, it can simulate the particle motion To make the particle system, we first set up three pairs of vertex buffer objects that store the per-particle attributes that we input to the vertex shader These include the particle's position, previous position, life, direction, and speed These are stored into separate buffer objects for convenience We could have stored all of these attributes into a single interleaved buffer object Since we output to the buffer object from our shader, we specify the buffer object usage as GL_DYNAMIC_COPY Similarly, we set up a separate vertex array object for rendering the particles: for(int i=0;i[...]... 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... 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. .. 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 After OpenGL v2.0, the next major version was v3.0 This version introduced two profiles for working with OpenGL; the... 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:... 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... 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"); 13 Introduction to Modern OpenGL 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... 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... project with OpenGL 3.3 core profile as shown in the first recipe The code for this recipe is in the Chapter1/SimpleTriangle directory In all of the code samples in this book, you will see a macro GL_ CHECK_ERRORS dispersed throughout This macro checks the current error bit for any error which might be raised by passing invalid arguments to an OpenGL function, or when there is some problem with the OpenGL. .. vertex shader (shaders/shader.vert) and a fragment shader (shaders/shader.frag) The first line in the shader signifies the GLSL version of the shader Starting from OpenGL v3.0, the version specifiers correspond to the OpenGL version used So for OpenGL v3.3, the GLSL version is 330 In addition, since we are interested in the core profile, we add another keyword following the version number to signify that... 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, .. .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. .. 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. .. language called OpenGL shading language (GLSL) Introduction to Modern OpenGL After OpenGL v2.0, the next major version was v3.0 This version introduced two profiles for working with OpenGL; the