Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Hands-On C++ Game Animation Programming
Hands-On C++ Game Animation Programming

Hands-On C++ Game Animation Programming: Learn modern animation techniques from theory to implementation with C++ and OpenGL

By Gabor Szauer
Free Trial
Book Jun 2020 368 pages 1st Edition
eBook
S$42.99
Print
S$52.99
Subscription
Free Trial
eBook
S$42.99
Print
S$52.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Hands-On C++ Game Animation Programming

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 vectors
  • Creating a vector
  • Understanding component-wise operations
  • Understanding non-component-wise operations
  • Interpolating vectors
  • Comparing vectors
  • Exploring 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...

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

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;
        };
      &...

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 addition
  • Vector subtraction
  • Vector scaling
  • Multiplying vectors
  • Dot 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...

Understanding non-component-wise operations

Not all vector operations are component-wise; some operations require more math. In this section, you are going to learn how to implement common vector operations that are not component-based. These operations are as follows:

  • How to find the length of a vector
  • What a normal vector is
  • How to normalize a vector
  • How to find the angle between two vectors
  • How to project vectors and what rejection is
  • How to reflect vectors
  • What the cross product is and how to implement it

Let's take a look at each one in more detail.

Vector length

Vectors represent a direction and a magnitude; the magnitude of a vector is its length. The formula for finding the length of a vector comes from trigonometry. In the following figure, a two-dimensional vector is broken down into parallel and perpendicular components. Notice how this forms a right triangle, with the vector being the hypotenuse:

Figure...

Interpolating vectors

Two vectors can be interpolated linearly by scaling the difference between the two vectors and adding the result back to the original vector. This linear interpolation is often abbreviated to lerp. The amount to lerp by is a normalized value between 0 and 1; this normalized value is often represented by the letter t. The following figure shows lerp between two vectors with several values for t:

Figure 2.13: Linear interpolation

When t = 0, the interpolated vector is the same as the starting vector. When t = 1, the interpolated vector is the same as the end vector.

Implement the lerp function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

vec3 lerp(const vec3 &s, const vec3 &e, float t) {
    return vec3(
        s.x + (e.x - s.x) * t,
        s.y + (e.y - s.y) * t,
     ...

Comparing vectors

The last operation that needs to be implemented is vector comparison. Comparison is a component-wise operation; each element must be compared using an epsilon. Another way to measure whether two vectors are the same is to subtract them. If they were equal, subtracting them would yield a vector with no length.

Overload the == and != operators in vec3.cpp. Don't forget to add the function declarations to vec3.h:

bool operator==(const vec3 &l, const vec3 &r) {
    vec3 diff(l - r);
    return lenSq(diff) < VEC3_EPSILON;
}
bool operator!=(const vec3 &l, const vec3 &r) {
    return !(l == r);
}

Important note:

Finding the right epsilon value to use for comparison operations is difficult. In this chapter, you declared 0.000001f as the epsilon. This value is the result of some trial and error. To learn more about comparing floating point values, check out https://bitbashing.io...

Exploring more vectors

At some point later on in this book, you will need to utilize two- and four-component vectors as well. The two- and four-component vectors don't need any mathematical functions defined as they will be used exclusively as containers used to pass data to the GPU.

Unlike the three-component vector you have implemented, the two- and four-component vectors need to exist as both integer and floating point vectors. To avoid duplicating code, both structures will be implemented using a template:

  1. Create a new file, vec2.h, and add the definition of the vec2 struct. All the vec2 constructors are inline; there is no need for a cpp file. The TVec2 struct is templated and typedef is used to declare vec2 and ivec2:
    template<typename T>
    struct TVec2 {
        union {
            struct {
                T x;
           ...

Summary

In this chapter, you have learned the vector math required to create a robust animation system. Animation is a math-heavy topic; the skills you have learned in this chapter are required to complete the rest of this book. You implemented all the common vector operations for three-component vectors. The vec2 and vec4 structures don't have a full implementation like vec3, but they are only used to send data to the GPU.

In the next chapter, you will continue to learn more about game-related math by learning about matrices.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build a functional and production-ready modern animation system with complete features using C++
  • Learn basic, advanced, and skinned animation programming with this step-by-step guide
  • Discover the math required to implement cutting edge animation techniques such as inverse kinematics and dual quaternions

Description

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.

What you will learn

Get the hang of 3D vectors, matrices, and transforms, and their use in game development Discover various techniques to smoothly blend animations Get to grips with GLTF file format and its design decisions and data structures Design an animation system by using animation tracks and implementing skinning Optimize various aspects of animation systems such as skinned meshes, clip sampling, and pose palettes Implement the IK technique for your game characters using CCD and FABRIK solvers Understand dual quaternion skinning and how to render large instanced crowds

Product Details

Country selected

Publication date : Jun 12, 2020
Length 368 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781800208087
Category :
Languages :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : Jun 12, 2020
Length 368 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781800208087
Category :
Languages :
Concepts :

Table of Contents

17 Chapters
Preface Chevron down icon Chevron up icon
1. Chapter 1: Creating a Game Window Chevron down icon Chevron up icon
2. Chapter 2: Implementing Vectors Chevron down icon Chevron up icon
3. Chapter 3: Implementing Matrices Chevron down icon Chevron up icon
4. Chapter 4: Implementing Quaternions Chevron down icon Chevron up icon
5. Chapter 5: Implementing Transforms Chevron down icon Chevron up icon
6. Chapter 6: Building an Abstract Renderer Chevron down icon Chevron up icon
7. Chapter 7: Exploring the glTF File Format Chevron down icon Chevron up icon
8. Chapter 8: Creating Curves, Frames, and Tracks Chevron down icon Chevron up icon
9. Chapter 9: Implementing Animation Clips Chevron down icon Chevron up icon
10. Chapter 10: Mesh Skinning Chevron down icon Chevron up icon
11. Chapter 11: Optimizing the Animation Pipeline Chevron down icon Chevron up icon
12. Chapter 12: Blending between Animations Chevron down icon Chevron up icon
13. Chapter 13: Implementing Inverse Kinematics Chevron down icon Chevron up icon
14. Chapter 14: Using Dual Quaternions for Skinning Chevron down icon Chevron up icon
15. Chapter 15: Rendering Instanced Crowds Chevron down icon Chevron up icon
16. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.