Hands-On C++ Game Animation Programming - Gabor Szauer - E-Book

Hands-On C++ Game Animation Programming E-Book

Gabor Szauer

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Animation is one of the most important parts of any game. Modern animation systems work directly with track-driven animation and provide support for advanced techniques such as inverse kinematics (IK), blend trees, and dual quaternion skinning.
This book will walk you through everything you need to get an optimized, production-ready animation system up and running, and contains all the code required to build the animation system. You’ll start by learning the basic principles, and then delve into the core topics of animation programming by building a curve-based skinned animation system. You’ll implement different skinning techniques and explore advanced animation topics such as IK, animation blending, dual quaternion skinning, and crowd rendering. The animation system you will build following this book can be easily integrated into your next game development project. The book is intended to be read from start to finish, although each chapter is self-contained and can be read independently as well.
By the end of this book, you’ll have implemented a modern animation system and got to grips with optimization concepts and advanced animation techniques.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 412

Veröffentlichungsjahr: 2020

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Hands-On C++ Game Animation Programming

Learn modern animation techniques from theory to implementation with C++ and OpenGL

Gabor Szauer

BIRMINGHAM—MUMBAI

Hands-On C++ Game Animation Programming

Copyright © 2020 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

Commissioning Editor: Pavan Ramchandani

Acquisition Editor: Ashwin Nair

Senior Editor: Hayden Edwards

Content Development Editor: Akhil Nair, Aamir Ahmed

Technical Editor: Deepesh Patel

Copy Editor: Safis Editing

Project Coordinator: Kinjal Bari

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Jyoti Chauhan

First published: June 2020

Production reference: 1110620

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80020-808-7

www.packt.com

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionalsImprove your learning with Skill Plans built especially for youGet a free eBook or video every monthFully searchable for easy access to vital informationCopy and paste, print, and bookmark content

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

Contributors

About the author

Gabor Szauer has been making games since 2010. He graduated from Full Sail University in 2010 with a bachelor's degree in game development. Gabor maintains an active Twitter presence, @gszauer, and maintains a programming-oriented game development blog: gabormakesgames.com. Gabor's previously published books are Game Physics Programming Cookbook and Lua Quick Start Guide, both published by Packt.

About the reviewer

Pedro Sousa is your typical software engineer by day, but at night he goes by the name SketchPunk as he develops various open source projects – basically whatever tickles his fancy at any given moment. Being self-taught in many areas of software development and having a pure love of art has given him a good amount of success in his career since he's able to balance writing good software with splashing a beautiful coat of paint over it.

In the last 3 years, Pedro has spent a great deal of time developing a game engine from scratch and, along the way, creating YouTube tutorials of all the nuts and bolts so that others can learn and follow in his footsteps. He has a strong belief that knowledge should be free and shared with all who want to learn.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Preface

Chapter 1: Creating a Game Window

Technical requirements14

Creating an empty project14

Creating the application class16

Adding an OpenGL loader17

Getting glad18

Adding glad to the project18

Creating a window19

Global variables22

Opening a window22

Creating the event handler28

Exploring the samples30

Summary32

Chapter 2: Implementing Vectors

Introducing vectors34

Creating a vector34

Epsilon35

Understanding component-wise operations36

Vector addition36

Vector subtraction37

Scaling vectors38

Multiplying vectors38

Dot product39

Understanding non-component-wise operations40

Vector length40

Normalizing vectors41

The angle between vectors42

Vector projection and rejection43

Vector reflection45

Cross product46

Interpolating vectors47

Comparing vectors49

Exploring more vectors50

Summary52

Chapter 3: Implementing Matrices

Technical requirements54

What is a matrix?54

Matrix storage55

Creating a matrix56

Common matrix operations59

Comparing matrices59

Adding matrices60

Scaling a matrix60

Matrix multiplication61

Transforming vectors and points63

Inverting a matrix65

Transpose65

Determinant and minors of lower-order matrices66

Creating camera matrices71

Frustum71

Perspective72

Orthographic72

Look at73

Summary74

Chapter 4: Implementing Quaternions

Creating quaternions76

Angle axis77

Creating rotations from one vector to another78

Retrieving quaternion data80

Common quaternion operations80

Comparison operations81

Dot product82

Length and squared length82

Unit quaternions83

Conjugate and inverse84

Multiplying quaternions85

Transforming vectors88

Interpolating quaternions89

Neighborhood89

Understanding the mix function90

Understanding the nlerp function90

Introduction to slerp91

Power91

Implementing slerp92

Look rotation92

Converting between quaternions and matrices94

Summary95

Chapter 5: Implementing Transforms

Creating the transform98

Combining transforms99

Inverting transforms100

Mixing transforms100

Converting transforms to matrices101

Converting matrices into transforms102

Transforming points and vectors104

Summary105

Chapter 6: Building an Abstract Renderer

Technical requirements108

Working with shaders108

The Shader class declaration108

Implementing the Shader class110

Working with buffers (attributes)117

The Attribute class declaration118

Implementing the Attribute class119

Working with uniforms122

The Uniform class declaration122

Implementing the Uniform class 123

Working with index buffers125

The IndexBuffer class declaration125

Implementing the IndexBuffer class126

Rendering geometry127

Working with textures129

Adding stb_image130

The Texture class declaration130

Implementing the Texture class131

Simple shaders133

The vertex shader133

The fragment shader134

Summary135

Chapter 7: Exploring the glTF File Format

Technical requirements138

Exploring how glTF files are stored 138

glTF files store a scene, not a model139

Exploring the glTF format139

The parts you need for animation140

The parts you don't need for animation141

Accessing data141

Exploring cgltf143

Integrating cgltf144

Exploring the sample assets146

Exporting from Blender146

Summary147

Chapter 8: Creating Curves, Frames, and Tracks

Understanding cubic Bézier splines150

Understanding cubic Hermite splines156

Interpolation types157

Creating the Frame struct159

Creating the Track class160

Declaring the Track class161

Implementing the Track class163

Creating the TransformTrack class174

Declaring the TransformTrack class174

Implementing the TransformTrack class176

Summary179

Chapter 9: Implementing Animation Clips

Implementing poses182

Declaring the Pose class183

Implementing the Pose class184

Implementing clips188

Declaring the Clip class188

Implementing the Clip class190

glTF – loading the rest pose194

glTF – loading joint names196

glTF – loading animation clips197

Summary201

Chapter 10: Mesh Skinning

Exploring meshes204

Understanding skinning205

Exploring rigid skinning207

The rigid skinning pipeline209

Exploring smooth skinning210

Implementing skeletons212

The Skeleton class declaration212

The Skeleton class implementation214

glTF – loading the bind pose216

glTF – loading a skeleton218

Implementing meshes218

The Mesh class declaration218

The Mesh class implementation221

glTF – loading meshes229

Implementing GPU skinning235

Summary237

Chapter 11: Optimizing the Animation Pipeline

Pre-generating the skin matrix240

Generating the skin matrix240

CPU skinning241

GPU skinning243

Storing the skin palette in a texture244

Faster sampling245

Optimizing the Track class245

Converting tracks250

Creating FastTransformTrack251

Creating FastClip253

The Pose palette generation254

Changing the GetMatrixPalette function255

Reordering joints256

Reordering clips259

Reordering meshes260

Exploring Pose::GetGlobalTransform261

Summary261

Chapter 12: Blending between Animations

Pose blending264

Declaring the Blend function264

Implementing the Blend function265

Crossfading animations266

Creating helper classes266

Declaring the cross-fade controller267

Implementing the cross-fade controller268

Additive blending271

Declaring additive animations272

Implementing additive animations272

Summary274

Chapter 13: Implementing Inverse Kinematics

Creating a CCD solver276

Declaring the CCD solver277

Implementing the CCD solver278

Creating a FABRIK solver282

Declaring the FABRIK solver283

Implementing the FABRIK solver285

Implementing constraints290

Ball-and-socket constraint292

Hinge constraint293

Using IK to align a character's feet to the ground294

Finding the foot goals295

Interpolating the foot goals296

Vertical character placement297

IK pass297

Foot alignment298

Summary299

Further reading299

Chapter 14: Using Dual Quaternions for Skinning

Introducing dual quaternions302

Implementing dual quaternions303

Implementing dual quaternion operations304

Measuring, normalizing, and inverting dual quaternions305

Converting transforms and dual quaternions307

Transforming vectors and points309

Skinning with dual quaternions310

Modifying the pose class311

Modifying the skeleton class312

Creating new uniform types313

Creating a dual quaternion shader314

Understanding how to use dual quaternion skinning318

Summary320

Chapter 15: Rendering Instanced Crowds

Storing data in textures322

Reading data from textures323

Encoding animation data323

Exploring per-instance data324

Creating an animation texture324

Declaring the AnimTexture class325

Implementing the AnimTexture class326

Animation baker331

Creating a crowd shader333

Creating the Crowd utility class337

Implementing the Crowd class339

Using the Crowd class344

Blending animations345

Exploring texture formats346

Combining animation textures346

Optimizing texel fetches347

Limiting influences347

Limiting animated components348

Not interpolating348

Combining these optimizations349

Summary349

Other Books You May Enjoy

Leave a review - let other readers know what you think353

Preface

Modern game animation is a bit of a black art. There are not many resources available that detail how to build a track-driven animation system, or advanced topics such as dual quaternion skinning. That is the void this book aims to fill. The goal of this book is to shed some light on the black art of animation programming and make the topic approachable for everyone.

This book takes a "theory to implementation" approach, where you will learn the theory of each topic discussed first. Once you understand the theory, you will implement it to get hands-on experience.

This book makes it a point to focus on the concepts and implementation details of animation programming, not the language or graphics API being used. By focusing on these fundamental concepts, you will be able to implement an animation system regardless of language or graphics API.

Who this book is for

This book is for programmers who want to learn how to build a modern animation system. The only requirement for following along with this book is some familiarity with C++. Other than that, everything is covered, from how to open a new window, to creating an OpenGL context, rendering an animated model, and advanced animation techniques.

What this book covers

Chapter 1, Creating a Game Window, explains how to create a new visual studio project, create a Win32 window, set up an OpenGL 3.3 render context, and enable vsynch. The code samples for this book are compiled against OpenGL 3.3. All the OpenGL code is compatible with the latest version of OpenGL and OpenGL 4.6.

Chapter 2, Implementing Vectors, covers vector math for game animation programming.

Chapter 3, Implementing Matrices, discusses matrix math for game animation programming.

Chapter 4, Implementing Quaternions, explains how to use quaternion math for game animation programming.

Chapter 5, Implementing Transforms, explains how to combine position, rotation, and scale into a transform object. These transform objects can be arranged in a hierarchy.

Chapter 6, Building an Abstract Renderer, shows you how to create an abstraction layer on top of OpenGL 3.3. The rest of this book will use this abstraction for rendering. By using an abstraction, we can focus on the core concepts of animation programming instead of the API being used to implement it. The abstraction layer targets OpenGL 3.3, but the code is valid with OpenGL 4.6 as well.

Chapter 7, Understanding the glTF File Format, introduces the glTF file format. glTF is a standard open file format that is supported by most 3D content creation tools. Being able to load a common format will let you load animation authored in almost any creation tool.

Chapter 8 Creating Curves, Frames, and Tracks, covers how to interpolate curves and how cruces can be used to animate transforms stored in a hierarchy.

Chapter 9, Implementing Animation Clips, explains how to implement animation clips. Animation clips modify a transform hierarchy over time.

Chapter 10, Mesh Skinning, covers how to deform a mesh so that it matches the pose generated by sampling an animation clip.

Chapter 11, Optimizing the Animation Pipeline, shows you how to optimize parts of the animation pipeline to make it faster and more production-ready.

Chapter 12, Blending between Animations, explains how to blend two animated poses together. This technique can be used to switch between two animations smoothly, without any visual popping.

Chapter 13, Implementing Inverse Kinematics, covers how to use inverse kinematics to make animations interact with the environment. For example, you'll learn how to make an animated character's foot not penetrate the ground on uneven terrain.

Chapter 14, Using Dual Quaternions for Skinning, covers dual quaternion math for game animation. Dual quaternions can be used to avoid pinching at animated joints.

Chapter 15, Rendering Instanced Crowds, shows how to encode animation data to a texture and move pose generation into a vertex shader. You will use this technique to render a large crowd using instancing.

To get the most out of this book

To get the most out of this book, some experience with C++ is expected. You don’t have to be a hardened C++ master, but you should be able to debug simple C++ problems. Having some experience with OpenGL is a plus, but not required. No advanced C++ features are used. The provided code compiles against C++ 11 or the most recent version.

The code in this book is written against OpenGL 3.3 Core. The OpenGL code presented in this book is forward compatible; the highest compatible version of OpenGL at the time of publishing is 4.6. In Chapter 6, Building an Abstract Renderer, you will implement a thin abstraction layer on top of OpenGL. Throughout the rest of the book, you will be coding against this abstraction layer, rather than OpenGL directly.

The code presented should compile and run on just about any laptop running Windows 10 or a more recent version. The only hardware requirement to follow along with this book is access to a computer that can run Visual Studio 2019 or a more recent version.

The minimum hardware requirements for Visual Studio 2019 are:

Windows 10, version 1703 or higher1.8 Ghz or a faster processor2GB of RAM

These requirements can be found online at: https://docs.microsoft.com/en-us/visualstudio/releases/2019/system-requirements

Download the example code files

You can download the example code files for this book from your account at http://www.packt.com. If you purchased this book elsewhere, you can visit http://www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at http://www.packt.com.Select the SUPPORT tab.Click on Code Downloads & Errata.Enter the name of the book in the Search box and follow the on-screen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for WindowsZipeg/iZip / UnRarX for Mac7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Game-Animation-Programming. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

public:

    Pose();

    Pose(const Pose& p);

    Pose& operator=(const Pose& p);

    Pose(unsigned int numJoints);

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample

     /etc/asterisk/cdr_mysql.conf

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: "Select System info from the Administration panel."

Note

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Get in touch with the author: The best way to get in touch with Gabor, the book's author, is on Twitter: @gszauer.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit, http://www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Chapter 2: Implementing Vectors

In this chapter, you will learn the basics of vector math. Much of what you will code throughout the rest of this book relies on having a strong understanding of vectors. Vectors will be used to represent displacement and direction.

By the end of this chapter, you will have implemented a robust vector library and will be able to perform a variety of vector operations, including component-wise and non-component-wise operations.

We will cover the following topics in this chapter:

Introducing vectorsCreating a vectorUnderstanding component-wise operationsUnderstanding non-component-wise operationsInterpolating vectorsComparing vectorsExploring more vectors

Important information:

In this chapter, you will learn how to implement vectors in an intuitive, visual way that relies on code more than math formulas. If you are interested in math formulas or want some interactive examples to try out, go to https://gabormakesgames.com/vectors.html.

Introducing vectors

What is a vector? A vector is an n-tuple of numbers. It represents a displacement measured as a magnitude and a direction. Each element of a vector is usually expressed as a subscript, such as (V0, V1, V2, … VN). In the context of games, vectors usually have two, three, or four components.

For example, a three-dimensional vector measures displacement on three unique axes: x, y, and z. Elements of vectors are often subscripted with the axis they represent, rather than an index. (VX, VY, VZ) and (V0, V1, V2) are used interchangeably.

When visualizing vectors, they are often drawn as arrows. The position of the base of an arrow does not matter because vectors measure displacement, not a position. The end of the arrow follows the displacement of the arrow on each axis.

For example, all of the arrows in the following figure represent the same vector:

Figure 2.1: Vector (2, 5) drawn in multiple locations

Each arrow has the same length and points in the same direction, regardless of where it is positioned. In the next section, you will start to implement the vector structure that will be used throughout the rest of this book.

Creating a vector

Vectors will be implemented as structures, not classes. The vector struct will contain an anonymous union that allows the vector's components to be accessed as an array or as individual elements.

To declare the vec3 structure and the function headers, create a new file, vec3.h. Declare the new vec3 structure in this file. The vec3 struct needs three constructors—a default constructor, one that takes each component as an element, and one that takes a pointer to a float array:

#ifndef _H_VEC3_

#define _H_VEC3_

struct vec3 {

    union {

        struct  {

            float x;

            float y;

            float z;

        };

        float v[3];

    };

    inline vec3() : x(0.0f), y(0.0f), z(0.0f) { }

    inline vec3(float _x, float _y, float _z) :

        x(_x), y(_y), z(_z) { }

    inline vec3(float *fv) :

        x(fv[0]), y(fv[1]), z(fv[2]) { }

};

#endif

The anonymous union in the vec3 struct allows data to be accessed using .x, .y, and .z notation, or as a contiguous array using .v. Before moving on to implementing functions that work on the vec3 struct, you need to consider comparing floating point numbers and whether or not to use an epsilon value.

Epsilon

Comparing floating point numbers is difficult. Instead of comparing two floating point numbers directly, you need to compare them using an epsilon. An epsilon is an arbitrarily small positive number that is the minimum difference two numbers need to have to be considered different numbers. Declare an epsilon constant in vec3.h:

#define VEC3_EPSILON 0.000001f

Important note:

You can learn more about floating point comparison at https://bitbashing.io/comparing-floats.html

With the vec3 structure created and the vec3 epsilon defined, you are ready to start implementing some common vector operations. In the next section, you're going to start by learning and implementing several component-wise operations.

Understanding component-wise operations

Several vector operations are just component-wise operations. A component-wise operation is one that you perform on each component of a vector or on like components of two vectors. Like components are components that have the same subscript. The component-wise operations that you will implement are as follows:

Vector additionVector subtractionVector scalingMultiplying vectorsDot product

Let's look at each of these in more detail.

Vector addition

Adding two vectors together yields a third vector, which has the combined displacement of both input vectors. Vector addition is a component-wise operation; to perform it, you need to add like components.

To visualize the addition of two vectors, draw the base of the second vector at the tip of the first vector. Next, draw an arrow from the base of the first vector to the tip of the second vector. This arrow represents the vector that is the result of the addition:

Figure 2.2: Vector addition

To implement vector addition in code, add like components of the input vectors. Create a new file, vec3.cpp. This is where you will define functions related to the vec3 struct. Don't forget to include vec3.h. Overload the + operator to perform vector addition. Don't forget to add the function signature to vec3.h:

vec3 operator+(const vec3 &l, const vec3 &r) {

    return vec3(l.x + r.x, l.y + r.y, l.z + r.z);

}

When thinking about vector addition, remember that a vector represents a displacement. When adding two vectors, the result is the combined displacement of both input vectors.

Vector subtraction

As with adding vectors, subtracting vectors is also a component-wise operation. You can think of subtracting vectors as adding the negative of the second vector to the first vector. When visualized as an arrow, subtraction points from the tip of the second vector to the tip of the first one.

To visually subtract vectors, place both vectors so they share the same origin. Draw a vector from the tip of the second arrow to the tip of the first one. The resulting arrow is the subtraction result vector:

Figure 2.3: Vector subtraction

To implement vector subtraction, subtract like components. Implement the subtraction function by overloading the - operator in vec3.cpp. Don't forget to add the function declaration to vec3.h:

vec3 operator-(const vec3 &l, const vec3 &r) {

    return vec3(l.x - r.x, l.y - r.y, l.z - r.z);

}

The steps and logic are very similar to vector addition. It might help to think of vector subtraction as adding a negative vector.

Scaling vectors

When a vector is scaled, it only changes in magnitude, not direction. As with addition and subtraction, scaling is a component-wise operation. Unlike addition and subtraction, a vector is scaled by a scalar, not another vector.

Visually, a scaled vector points in the same direction as the original vector, but it has a different length. The following figure shows two vectors: (2, 1) and (2, 4). Both vectors share the same direction, but the magnitude of the second vector is longer:

Figure 2.4: Vector scaling

To implement vector scaling, multiply every component of the vector by the given scalar value.

Implement the scale function by overloading the * operator in vec3.cpp. Don't forget to add the function declaration to vec3.h:

vec3 operator*(const vec3 &v, float f) {

    return vec3(v.x * f, v.y * f, v.z * f);

}

Negating a vector can be done by scaling the vector by -1. When negating a vector, the vector maintains its magnitude but changes its direction.

Multiplying vectors

Vector multiplication can be considered a