Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

webgl game development
PREMIUM
Số trang
418
Kích thước
5.1 MB
Định dạng
PDF
Lượt xem
760

webgl game development

Nội dung xem thử

Mô tả chi tiết

www.it-ebooks.info

WebGL Game Development

Gain insights into game development by rendering

complex 3D objects using WebGL

Sumeet Arora

BIRMINGHAM - MUMBAI

www.it-ebooks.info

WebGL Game Development

Copyright © 2014 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 expressed 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: April 2014

Production Reference: 1180414

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84969-979-2

www.packtpub.com

Cover Image by Logic Simplified ([email protected])

www.it-ebooks.info

Credits

Author

Sumeet Arora

Reviewers

Jose Dunia

Kevin M. Fitzgerald

Joseph Hocking

Maulik R. Kamdar

Hassadee Pimsuwan

Rodrigo Silveira

Acquisition Editors

Rebecca Pedley

Julian Ursell

Content Development Editors

Chalini Snega Victor

Arun Nadar

Technical Editors

Kunal Anil Gaikwad

Pramod Kumavat

Siddhi Rane

Faisal Siddiqui

Copy Editors

Sayanee Mukherjee

Deepa Nambiar

Project Coordinator

Kranti Berde

Proofreaders

Ting Baker

Simran Bhogal

Maria Gould

Paul Hindle

Indexer

Monica Ajmera Mehta

Graphics

Sheetal Aute

Ronak Dhruv

Disha Haria

Abhinash Sahu

Production Coordinator

Nilesh R. Mohite

Cover Work

Nilesh R. Mohite

www.it-ebooks.info

About the Author

Sumeet Arora is a tech entrepreneur. He founded Evon Technologies, a

consultancy for mobile and web development, and Logic Simplified, a game

development company. He holds the position of CTO at Evon and works as a

consultant for Logic Simplified. He has worked as an architect consultant for scalable

web portals for clients across the globe. His core expertise lies in 3D rendering

technologies and collaboration tools. For the past four years, he has been working

with various clients/companies on multiplatform content delivery. His own passion

towards gaming technologies has helped him help his clients in launching games on

various platforms on both web and mobile. Currently his company, Logic Simplified,

helps new gaming ideas to launch in the market.

Thanks to my family and colleagues at Evon Technologies and

Logic Simplified for assisting me with the graphics and sharing my

workload in order to complete the book.

www.it-ebooks.info

About the Reviewers

Jose Dunia is an experienced web developer with a passion for computer graphics.

He would like to see software, especially video games and simulations, being used

more within the various levels of education. Jose started developing web projects

at the age of 12 and his interest for programming lead him to pursue a B.E. in

Computer Engineering at the Universidad Simón Bolívar. He holds an M.S. degree in

Digital Arts and Sciences from the University of Florida where he studied Computer

Graphics and serious games. Currently, he is working at Shadow Health, a start-up

company that designs and develops interactive simulations for the advancement of

health education.

Kevin M. Fitzgerald is a Platform Architect of Okanjo.com. He has over 12 years

of development experience in education, medical systems, and startups and has been

tinkering with the web since dial-up modems were mainstream.

Kevin is active in the open source community and has contributed to the Mono

project and Umbraco communities. He continues to be active on GitHub, working

with the latest technologies and projects.

Kevin and his wife Luciana are celebrating their fifth year of marriage and enjoy long

walks on the beach and talking about Node.js, C#, and Bitcoin.

www.it-ebooks.info

Joseph Hocking is a software engineer living in Chicago, specializing in interactive

media development. He builds games and apps for both mobile and web using

technologies such as C#/Unity, ActionScript 3/Flash, Lua/Corona, and JavaScript/

HTML5. He works at Synapse Games as a developer of web and mobile games,

such as the recently released Tyrant Unleashed. He also teaches classes in game

development at Columbia College, Chicago. His website is www.newarteest.com.

Maulik R. Kamdar is a research scientist working at the intersection of Big Data

Visualization, Life Sciences, and Semantic Web. His primary interests revolve around

the conceptualization and development of novel, interdisciplinary approaches,

which tackle the integrative bioinformatics challenges and guide a bioscientist

towards intuitive knowledge exploration and discovery. Maulik has an M.Tech. in

Biotechnology, conferred by Indian Institute of Technology (IIT), Kharagpur, one

of the most prestigious universities in India. He qualified for the Google Summer

of Code scholarship, an annual program encouraging students across the world to

participate in open source projects, for three successive years (2010-12).

He has contributed to Drupal, a content management platform, and the Reactome

Consortium, a knowledge base of human biological pathways, on the introduction

of HTML5 canvas-based visualization modules in their frameworks. Currently, he

is employed at the Insight Center for Data Analytics, Ireland, and researches the

application of human-computer interaction principles and visualization methods to

increase the adoption and usability of semantic web technologies in the biomedical

domain. He has co-authored several scientific publications in internationally

acclaimed journals. His recent contribution, titled Fostering Serendipity through Big

Linked Data, has won the Big Data award at Semantic Web Challenge, held during

International Semantic Web Conference, Sydney, in October 2013.

www.it-ebooks.info

Hassadee Pimsuwan, currently the CEO and co-founder of Treebuild

(http://treebuild.com), a customizable 3D printing marketplace and Web3D

application. He was working with a Web3D company in Munich, Germany, in

2011 and a web design company in Singapore in 2012-2013. He has graduated in

Management Information System from Suranaree University of Technology with

first-class honors in 2012.

Rodrigo Silveira is a software engineer at Deseret Digital Media. He divides his

time there developing applications in PHP, JavaScript, and Android. Some of his

hobbies outside of work include blogging and recording educational videos about

software development, learning about new technologies, and finding ways to push

the web forward.

He received his Bachelor of Science degree in Computer Science from Brigham

Young University, Idaho, as well as an Associate's Degree in Business Management

from LDS Business College in Salt Lake City, Utah.

His fascination for game development began in his early teenage years, and his skills

grew as he discovered the power of a library subscription, a curious and willing

mind, and supportive parents and friends. Today, Rodrigo balances his time between

the three great passions of his life—his family, software development, and video

games (with the last two usually being mingled together).

I would like to thank my best friend, and the love of my life,

Lucimara, for supporting me in my many hobbies, her endless

wisdom, and her contagious love for life. I also wish to thank my

daughter Samira, who makes each day shine brighter.

www.it-ebooks.info

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 [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.

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?

• Fully searchable across every book published by Packt

• Copy and paste, print, and bookmark content

• 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.

www.it-ebooks.info

Table of Contents

Preface 1

Chapter 1: Getting Started with WebGL Game Development 7

Understanding WebGL 8

Differentiating WebGL from the game engine 8

Understanding basic 3D mathematics 8

Vectors 9

Matrices 10

Understanding transformations 10

Classifying into linear and affine transformations 10

Understanding transformations required to render 3D objects 12

Learning the basics of 3D graphics 15

Understanding mesh, polygon, and vertices 15

Using indices to save memory 17

Understanding WebGL's rendering pipeline 18

Framebuffers 20

A walkthrough of the WebGL API 20

Initializing the WebGL context 20

Vertex buffer objects – uploading data to GPU 21

Index buffer objects 23

Shaders 23

The vertex shader 24

The fragment shader 25

Shader variable qualifiers 25

Attributes 26

Uniforms 26

The varying qualifier 27

Compiling and linking shaders 28

Associating buffer objects with shader attributes 29

Drawing our primitive 30

Drawing using vertex buffer objects 33

www.it-ebooks.info

Table of Contents

[ ii ]

Drawing using index buffer objects 35

Debugging a WebGL application 36

Summary 37

Chapter 2: Colors and Shading Languages 39

Understanding colors 40

Coloring our square 40

Coloring using the vertex color 41

Learning more about colors 44

Understanding surface normals for lighting calculations 45

Different types of lights used in games 49

Understanding object materials 52

Rendering 3D objects 52

Exporting a 3D object from Blender 52

Understanding and loading the Wavefront (OBJ) format 55

Understanding the material file format (MTL) 56

Converting the OBJ file to the JSON file format 57

Loading the JSON model 65

Rendering without light 67

Understanding the illumination/reflection model 68

Lambertian reflectance/diffuse reflection 69

The Blinn-Phong model 70

Understanding shading/interpolation models 72

Flat shading 72

Gouraud shading 72

Phong shading 73

Differentiating the shading models 74

Implementing Gouraud shading on a Lambertian reflection model 75

Implementing Gouraud shading – Blinn-Phong reflection 80

Implementing Phong shading – Blinn-Phong reflection 82

Summary 84

Chapter 3: Loading the Game Scene 85

Supporting multiple objects 85

Implementing Face.js 86

Implementing Geometry.js 87

Implementing parseJSON.js 92

Implementing StageObject.js 92

Implementing Stage.js 94

Using the architectural updates 95

Understanding the main code 95

Understanding WebGL – a state machine 98

Using mvMatrix states 98

Understanding request animation frames 100

www.it-ebooks.info

Table of Contents

[ iii ]

Loading the scene 101

Understanding positional lights 103

Lighting up the scene with lamps 104

The vertex shader 105

The fragment shader 106

Understanding the main code 107

Multiple lights and shaders 108

Adding multiple lamps 109

The vertex shader 110

The fragment shader 110

Implementing Light.js 112

Applying Lights.js 113

Understanding the main code 114

Summary 116

Chapter 4: Applying Textures 117

Texturing basics 117

Understanding 2D textures and texture mapping 118

Comprehending texture filtering 120

Loading textures 121

A new data type – sampler 123

Applying a texture to the square 124

The vertex shader 125

The fragment shader 125

Texture wrapping 128

Testing the texture wrapping mode 129

The HTML 129

The event handlers 130

The redrawWithClampingMode function 130

Exporting models from Blender 131

Converting Box.obj to Box.json 134

Understanding the JSON file with UV coordinates 134

Parsing UV coordinates from the JSON file 136

The challenge and the algorithm 136

Revisiting vertices, normals, and the indices array 137

Rendering objects exported from Blender 147

Changes in our JSON parser 147

Changes in our Geometry object 148

Loading a textured object 148

Understanding mipmapping 151

Implementing mipmapping 152

Understanding the filtering methods 153

Nearest-neighbor interpolation 153

Linear interpolation 153

Nearest-neighbor with mipmapping 153

www.it-ebooks.info

Table of Contents

[ iv ]

Bilinear filtering with mipmapping 153

Trilinear filtering 154

Applying filtering modes 154

Understanding cubemaps and multi-texturing 157

Cubemap coordinates 158

Multi-texturing 158

Loading cubemaps 158

Understanding the shader code 159

Summary 161

Chapter 5: Camera and User Interaction 163

Understanding ModelView transformations 163

Applying the model transformation 164

Understanding the view transformation 165

Understanding the camera matrix 165

Comprehending the components of a camera matrix 166

Converting between the camera matrix and view matrix 167

Using the lookAt function 167

Understanding the camera rotation 169

Using quaternions 169

Understanding perspective transformations 170

Understanding the viewing frustum 171

Defining the view frustum 172

Using the basic camera 173

Implementing the basic camera 173

Understanding the free camera 176

Implementing the free camera 177

Using our free camera 182

Adding keyboard and mouse interactions 185

Handling mouse events 187

Comprehending the orbit camera 190

Implementing the orbit camera 190

Understanding the pitch function for the orbit camera 194

Understanding the yaw function for the orbit camera 196

Using an orbit camera 198

Summary 199

Chapter 6: Applying Textures and Simple Animations to

Our Scene 201

Applying textures to our scene 202

Applying a texture to the scene 204

Implementing the vertex shader code 207

Implementing the fragment shader code 208

Working with the control code 209

www.it-ebooks.info

Table of Contents

[ v ]

Understanding the animation types in 3D games 212

Understanding time-based animation 212

Understanding frame-based animation 212

Implementing time-based animation 214

Comprehending interpolation 215

Linear interpolation 215

Polynomial interpolation 215

Spline interpolation 216

A briefing on skinned animation 217

Using first-person camera 218

Adding the first-person camera 219

Improving the first-person camera code 221

Simple bullet action – linear animation 223

Reusing objects in multiple bullets 226

Using B-spline interpolation for grenade action 228

Using linear interpolation for left-hand rotation 229

Using texture animation for an explosion effect 233

Summary 238

Chapter 7: Physics and Terrains 239

Understanding a simple terrain – plane geometry 239

Rendering our plane geometry 247

Comparing JavaScript 3D physics engines 249

Ammo.js 249

Box2dweb 250

JigLibJS 250

Comprehending the physics engine concepts 251

Updating the simulation loop 252

Learning about objects in the physics system 253

Particles 254

Rigid bodies 254

Soft bodies 255

Understanding the physics shapes 255

Adding gravity and a rigid body to the game scene 256

Implementing forces, impulse, and collision detection 260

Diving deep into collision detection 261

Revisiting the grenade and bullet actions 262

Cheating in the bullet action 267

Extending our terrain with physics 269

Implementing height maps 275

Summary 276

www.it-ebooks.info

Table of Contents

[ vi ]

Chapter 8: Skinning and Animations 277

Understanding the basics of a character's skeleton 277

Comprehending the joint hierarchy 278

Understanding forward kinematics 279

Understanding the basics of skinning 281

Simple skinning 281

Smooth skinning 281

The binding matrix 282

The final vertex transformation 282

The final normal transformation 283

Loading a rigged JSON model 283

Understanding JSON file encoding 283

Loading the rigged model 285

Enhancing the StageObject class 286

Implementing the bone class 292

Implementing the RiggedMesh class 293

Loading the skinned model 299

Animating a rigged JSON model 303

JSON model – animation data 304

Loading the animation data 306

Exporting models from 3D software in JSON 315

Exporting from Blender 315

Converting FBX/Collada/3DS files to JSON 316

Loading MD5Mesh and MD5Anim files 316

Summary 317

Chapter 9: Ray Casting and Filters 319

Understanding the basic ray casting concepts 320

Learning the basics of picking 322

Picking based on an object's color 322

Picking using ray casting 324

Implementing picking using ray casting 325

Using a rigid body (collider) for each scene object 326

Calculating the screen coordinates of a click 330

Unproject the vector 332

Creating a ray segment 334

Checking for an intersection 335

Changing the color of the selected object 336

Offscreen rendering using framebuffers 338

Creating a texture object to store color information 339

Creating a renderbuffer for depth information 339

Associating a texture and a renderbuffer to framebuffers 340

Rendering to framebuffers 340

www.it-ebooks.info

Tải ngay đi em, còn do dự, trời tối mất!