34,79 €
WebGL is a new web technology that brings hardware-accelerated 3D graphics to the browser without installing additional software. As WebGL is based on OpenGL and brings in a new concept of 3D graphics programming to web development, it may seem unfamiliar to even experienced Web developers.Packed with many examples, this book shows how WebGL can be easy to learn despite its unfriendly appearance. Each chapter addresses one of the important aspects of 3D graphics programming and presents different alternatives for its implementation. The topics are always associated with exercises that will allow the reader to put the concepts to the test in an immediate manner.WebGL Beginner's Guide presents a clear road map to learning WebGL. Each chapter starts with a summary of the learning goals for the chapter, followed by a detailed description of each topic. The book offers example-rich, up-to-date introductions to a wide range of essential WebGL topics, including drawing, color, texture, transformations, framebuffers, light, surfaces, geometry, and more. With each chapter, you will "level up"ù your 3D graphics programming skills. This book will become your trustworthy companion filled with the information required to develop cool-looking 3D web applications with WebGL and JavaScript.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 425
Veröffentlichungsjahr: 2012
Copyright © 2012 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 authors, 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 2012
Production Reference: 1070612
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-172-7
www.packtpub.com
Cover Image by Diego Cantor (<[email protected]>)
Authors
Diego Cantor
Brandon Jones
Reviewers
Paul Brunt
Dan Ginsburg
Andor Salga
Giles Thomas
Acquisition Editor
Wilson D'Souza
Lead Technical Editor
Azharuddin Sheikh
Technical Editors
Manasi Poonthottam
Manali Mehta
Rati Pillai
Ankita Shashi
Manmeet Singh Vasir
Copy Editor
Leonard D'Silva
Project Coordinator
Joel Goveya
Proofreader
Lesley Harrison
Indexer
Monica Ajmera Mehta
Graphics
Valentina D'silva
Manu Joseph
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
Diego Hernando Cantor Rivera is a Software Engineer born in 1980 in Bogota, Colombia. Diego completed his undergraduate studies in 2002 with the development of a computer vision system that tracked the human gaze as a mechanism to interact with computers.
Later on, in 2005, he finished his master's degree in Computer Engineering with emphasis in Software Architecture and Medical Imaging Processing. During his master's studies, Diego worked as an intern at the imaging processing laboratory CREATIS in Lyon, France and later on at the Australian E-Health Research Centre in Brisbane, Australia.
Diego is currently pursuing a PhD in Biomedical Engineering at Western University in London, Canada, where he is involved in the development augmented reality systems for neurosurgery.
When Diego is not writing code, he enjoys singing, cooking, travelling, watching a good play, or bodybuilding.
Diego speaks Spanish, English, and French.
I would like to thank all the people that in one way or in another have been involved with this project:
My partner Jose, thank you for your love and infinite patience.
My family Cecy, Fredy, and Jonathan.
My mentors Dr. Terry Peters and Dr. Robert Bartha for allowing me to work on this project. Thank you for your support and encouragement.
My friends and collegues Danielle Pace and Chris Russ. Guys your work ethic, professionalism, and dedication are inspiring. Thank you for supporting me during the development of this project.
Brandon Jones, my co-author for the awesome glMatrix library! This is a great contribution to the WebGL world! Also, thank you for your contributions on chapters 7 and 10. Without you this book would not had been a reality.
The technical reviewers who taught me a lot and gave me great feedback during the development of this book: Dan Ginsburg, Giles Thomas, Andor Salga, and Paul Brunt. You guys rock!
The tireless PACKT team: Joel Goveya, Wilson D'souza, Maitreya Bhakal, Meeta Rajani, Azharuddin Sheikh, Manasi Poonthottam, Manali Mehta, Manmeet Singh Vasir, Archana Manjrekar, Duane Moraes, and all the other people that somehow contributed to this project at PACKT publishing.
Brandon Jones has been developing WebGL demos since the technology first began appearing in browsers in early 2010. He finds that it's the perfect combination of two aspects of programming that he loves, allowing him to combine eight years of web development experience and a life-long passion for real-time graphics.
Brandon currently works with cutting-edge HTML5 development at Motorola Mobility.
I'd like to thank my wife, Emily, and my dog, Cooper, for being very patient with me while writing this book, and Zach for convincing me that I should do it in the first place.
Paul Brunt has over 10 years of web development experience, initially working on e-commerce systems. However, with a strong programming background and a good grasp of mathematics, the emergence of HTML5 presented him with the opportunity to work with richer media technologies with particular focus on using these web technologies in the creation of games. He was working with JavaScript early on in the emergence of HTML5 to create some early games and applications that made extensive use of SVG, canvas, and a new generation of fast JavaScript engines. This work included a proof of concept platform game demonstration called Berts Breakdown.
With a keen interest in computer art and an extensive knowledge of Blender, combined with knowledge of real-time graphics, the introduction of WebGL was the catalyst for the creation of GLGE. He began working on GLGE in 2009 when WebGL was still in its infancy, gearing it heavily towards the development of online games.
Apart from GLGE he has also contributed to other WebGL frameworks and projects as well as porting the JigLib physics library to JavaScript in 2010, demoing 3D physics within a browser for the first time.
Dan Ginsburg is the founder of Upsample Software, LLC, a software company offering consulting services with a specialization in 3D graphics and GPU computing. Dan has co-authored several books including the OpenGL ES 2.0 Programming Guide and OpenCL Programming Guide. He holds a B.Sc in Computer Science from Worcester Polytechnic Institute and an MBA from Bentley University.
Andor Salga graduated from Seneca College with a bachelor's degree in software development. He worked as a research assistant and technical lead in Seneca's open source research lab (CDOT) for four years, developing WebGL libraries such as Processing.js, C3DL, and XB PointStream. He has presented his work at SIGGRAPH, MIT, and Seneca's open source symposium.
I'd like to thank my family and my wife Marina.
Giles Thomas has been coding happily since he first encountered an ICL DRS 20 at the age of seven. Never short on ambition, he wrote his first programming language at 12 and his first operating system at 14. Undaunted by their complete lack of success, and thinking that the third time is a charm, he is currently trying to reinvent cloud computing with a startup called PythonAnywhere. In his copious spare time, he runs a blog at http://learningwebgl.com/
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 <[email protected]> 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.
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.
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.
WebGL is a new web technology that brings hardware-accelerated 3D graphics to the browser without requiring the user to install additional software. As WebGL is based on OpenGL and brings in a new concept of 3D graphics programming to web development, it may seem unfamiliar to even experienced web developers.
Packed with many examples, this book shows how WebGL can be easy to learn despite its unfriendly appearance. Each chapter addresses one of the important aspects of 3D graphics programming and presents different alternatives for its implementation. The topics are always associated with exercises that will allow the reader to put the concepts to the test in an immediate manner.
WebGL Beginner's Guide presents a clear road map to learning WebGL. Each chapter starts with a summary of the learning goals for the chapter, followed by a detailed description of each topic. The book offers example-rich, up-to-date introductions to a wide range of essential WebGL topics, including drawing, color, texture, transformations, framebuffers, light, surfaces, geometry, and more. Each chapter is packed with useful and practical examples that demonstrate the implementation of these topics in a WebGL scene. With each chapter, you will "level up" your 3D graphics programming skills. This book will become your trustworthy companion filled with the information required to develop cool-looking 3D web applications with WebGL and JavaScript.
Chapter 1, Getting Started with WebGL, introduces the HTML5 canvas element and describes how to obtain a WebGL context for it. After that, it discusses the basic structure of a WebGL application. The virtual car showroom application is presented as a demo of the capabilities of WebGL. This application also showcases the different components of a WebGL application.
Chapter 2, Rendering Geometry, presents the WebGL API to define, process, and render objects. Also, this chapter shows how to perform asynchronous geometry loading using AJAX and JSON.
Chapter 3, Lights!, introduces ESSL the shading language for WebGL. This chapter shows how to implement a lighting strategy for the WebGL scene using ESSL shaders. The theory behind shading and reflective lighting models is covered and it is put into practice through several examples.
Chapter 4, Camera, illustrates the use of matrix algebra to create and operate cameras in WebGL. The Perspective and Normal matrices that are used in a WebGL scene are also described here. The chapter also shows how to pass these matrices to ESSL shaders so they can be applied to every vertex. The chapter contains several examples that show how to set up a camera in WebGL.
Chapter 5, Action, extends the use of matrices to perform geometrical transformations (move, rotate, scale) on scene elements. In this chapter the concept of matrix stacks is discussed. It is shown how to maintain isolated transformations for every object in the scene using matrix stacks. Also, the chapter describes several animation techniques using matrix stacks and JavaScript timers. Each technique is exemplified through a practical demo.
Chapter 6, Colors, Depth Testing, and Alpha Blending, goes in depth about the use of colors in ESSL shaders. This chapter shows how to define and operate with more than one light source in a WebGL scene. It also explains the concepts of Depth Testing and Alpha Blending, and it shows how these features can be used to create translucent objects. The chapter contains several practical exercises that put into practice these concepts.
Chapter 7, Textures, shows how to create, manage, and map textures in a WebGL scene. The concepts of texture coordinates and texture mapping are presented here. This chapter discusses different mapping techniques that are presented through practical examples. The chapter also shows how to use multiple textures and cube maps.
Chapter 8, Picking, describes a simple implementation of picking which is the technical term that describes the selection and interaction of the user with objects in the scene. The method described in this chapter calculates mouse-click coordinates and determines if the user is clicking on any of the objects being rendered in the canvas. The architecture of the solution is presented with several callback hooks that can be used to implement logic-specific application. A couple of examples of picking are given.
Chapter 9, Putting It All Together, ties in the concepts discussed throughout the book. In this chapter the architecture of the demos is reviewed and the virtual car showroom application outlined in Chapter 1, Getting Started with WebGL, is revisited and expanded. Using the virtual car showroom as the case study, this chapter shows how to import Blender models into WebGL scenes and how to create ESSL shaders that support the materials used in Blender.
Chapter 10, Advanced Techniques, shows a sample of some advanced techniques such as post-processing effects, point sprites, normal mapping, and ray tracing. Each technique is provided with a practical example. After reading this WebGL Beginner's Guide you will be able to take on more advanced techniques on your own.
http://www.khronos.org/webgl/wiki/Getting_a_WebGL_Implementation
A source code editor that recognizes and highlights JavaScript syntax.You may need a web server such as Apache or Lighttpd to load remote geometry if you want to do so (as shown in Chapter 2, Rendering Geometry). This is optional.This book is written for JavaScript developers who are interested in 3D web development. A basic understanding of the DOM object model, the JQuery library, AJAX, and JSON is ideal but not required. No prior WebGL knowledge is expected.
A basic understanding of linear algebra operations is assumed.
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
Instructions often need some extra explanation so that they make sense, so they are followed with:
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:
These set practical challenges and give you ideas for experimenting with what you have learned.
You will also 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: "Open the file ch1_Canvas.html using one of the supported browsers."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
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: "Now switch to camera coordinates by clicking on the Camera button."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 <[email protected]>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.
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 www.packtpub.com/authors.
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.
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 http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
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 http://www.packtpub.com/sites/default/files/downloads/1727_images.pdf
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 http://www.packtpub.com/support, 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.packtpub.com/support.
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 <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
In 2007, Vladimir Vukicevic, an American-Serbian software engineer, began working on an OpenGL prototype for the then upcoming HTML <canvas> element which he called Canvas 3D. In March, 2011, his work would lead Kronos Group, the nonprofit organization behind OpenGL, to create WebGL: a specification to grant Internet browsers access to Graphic Processing Units (GPUs) on those computers where they were used.
WebGL was originally based on OpenGL ES 2.0 (ES standing for Embedded Systems), the OpenGL specification version for devices such as Apple's iPhone and iPad. But as the specification evolved, it became independent with the goal of providing portability across various operating systems and devices. The idea of web-based, real-time rendering opened a new universe of possibilities for web-based 3D environments such as videogames, scientific visualization, and medical imaging. Additionally, due to the pervasiveness of web browsers, these and other kinds of 3D applications could be taken to mobile devices such as smart phones and tablets. Whether you want to create your first web-based videogame, a 3D art project for a virtual gallery, visualize the data from your experiments, or any other 3D application you could have in mind, the first step will be always to make sure that your environment is ready.
In this chapter, you will:
WebGL is a web-based 3D Graphics API. As such there is no installation needed. At the time this book was written, you will automatically have access to it as long as you have one of the following Internet web browsers:
To get an updated list of the Internet web browsers where WebGL is supported, please check on the Khronos Group web page following this link:
http://www.khronos.org/webgl/wiki/Getting_a_WebGL_Implementation
You also need to make sure that your computer has a graphics card.
If you want to quickly check if your current configuration supports WebGL, please visit this link:
http://get.webgl.org/
WebGL is a 3D graphics library that enables modern Internet browsers to render 3D scenes in a standard and efficient manner. According to Wikipedia, rendering is the process of generating an image from a model by means of computer programs. As this is a process executed in a computer, there are different ways to produce such images.
The first distinction we need to make is whether we are using any special graphics hardware or not. We can talk of software-based rendering, for those cases where all the calculations required to render 3D scenes are performed using the computer's main processor, its CPU; on the other hand we use the term hardware-based rendering for those scenarios where there is a Graphics Processing Unit (GPU) performing 3D graphics computations in real time. From a technical point of view, hardware-based rendering is much more efficient than software-based rendering because there is dedicated hardware taking care of the operations. Contrastingly, a software-based rendering solution can be more pervasive due to the lack of hardware dependencies.
A second distinction we can make is whether or not the rendering process is happening locally or remotely. When the image that needs to be rendered is too complex, the render most likely will occur remotely. This is the case for 3D animated movies where dedicated servers with lots of hardware resources allow rendering intricate scenes. We called this server-based rendering. The opposite of this is when rendering occurs locally. We called this client-based rendering.
WebGL has a client-based rendering approach: the elements that make part of the 3D scene are usually downloaded from a server. However, all the processing required to obtain an image is performed locally using the client's graphics hardware.
In comparison with other technologies (such as Java 3D, Flash, and The Unity Web Player Plugin), WebGL presents several advantages:
As in any 3D graphics library, in WebGL, you need certain components to be present to create a 3D scene. These fundamental elements will be covered in the first four chapters of the book. Starting from Chapter 5, Action, we will cover elements that are not required to have a working 3D scene such as colors and textures and then later on we will move to more advanced topics.
The components we are referring to are as follows:
This chapter will cover the first element of our list—the canvas. We will see in the coming sections how to create a canvas and how to set up a WebGL context.
Let's create a web page and add an HTML5 canvas. A canvas is a rectangular element in your web page where your 3D scene will be rendered.
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 http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We have just created a simple web page with a canvas in it. This canvas will contain our 3D application. Let's go very quickly to some relevant elements presented in this example.
This is the piece of code that determines the canvas style:
As you can imagine, this code is not fundamental to build a WebGL application. However, a blue-dotted border is a good way to verify where the canvas is located, given that the canvas will be initially empty.
There are three attributes in our previous example:
If you see the message on your screen: Your browser does not support HTML5 (Which was the message we put between <canvas> and </canvas>) then you need to make sure that you are using one of the supported Internet browsers.
If you are using Firefox and you still see the HTML5 not supported message. You might want to be sure that WebGL is enabled (it is by default). To do so, go to Firefox and type about:config in the address bar, then look for the property webgl.disabled. If is set to true, then go ahead and change it. When you restart Firefox and load ch1_Canvas.html, you should be able to see the dotted border of the canvas, meaning everything is ok.
In the remote case where you still do not see the canvas, it could be due to the fact that Firefox has blacklisted some graphic card drivers. In that case, there is not much you can do other than use a different computer.
A WebGL context is a handle (more strictly a JavaScript object) through which we can access all the WebGL functions and attributes. These constitute WebGL's Application Program Interface (API).
We are going to create a JavaScript function that will check whether a WebGL context can be obtained for the canvas or not. Unlike other JavaScript libraries that need to be downloaded and included in your projects to work, WebGL is already in your browser. In other words, if you are using one of the supported browsers, you don't need to install or include any library.
A WebGL context can be understood as a state machine: once you modify any of its attributes, that modification is permanent until you modify that attribute again. At any point you can query the state of these attributes and so you can determine the current state of your WebGL context. Let's analyze this behavior with an example.
So far we have seen how to set up a canvas and how to obtain a WebGL context; the next step is to discuss objects, lights, and cameras. However, why should we wait to see what WebGL can do? In this section, we will have a glance at what a WebGL scene look like.
Through the book, we will develop a virtual car showroom application using WebGL. At this point, we will load one simple scene in the canvas. This scene will contain a car, some lights, and a camera.
Once you finish reading the book you will be able to create scenes like the one we are going to play with next. This scene shows one of the cars from the book's virtual car showroom.
We have loaded a simple scene in an Internet web browser using WebGL.
This scene consists of:
There are other elements that are not covered in this example such as textures, colors, and special light effects (specularity). Do not panic! Each element will be explained later in the book. The point here is to identify that the four basic elements we discussed previously are present in the scene.
In this chapter, we have looked at the four basic elements that are always present in any WebGL application: canvas, objects, lights, and camera.
We have learned how to add an HTML5 canvas to our web page and how to set its ID, width, and height. After that, we have included the code to create a WebGL context. We have seen that WebGL works as a state machine and as such, we can query any of its variables using the getParameter function.
In the next chapter we will learn how to define, load, and render 3D objects into a WebGL scene.
WebGL renders objects following a "divide and conquer" approach. Complex polygons are decomposed into triangles, lines, and point primitives. Then, each geometric primitive is processed in parallel by the GPU through a series of steps, known as the rendering pipeline, in order to create the final scene that is displayed on the canvas.
