4. The Dot Product

So far we can add vectors, scale them, measure them and normalize them.
But we can't yet answer a very natural question: how much do two vectors point the same way?

The dot product answers exactly that, with a single number.
It's probably the most used operation in all of graphics programming.
Every lit pixel you have ever seen in a 3D game was computed with at least one dot product, and it also gives us angles, projections, reflections, "is it in front of me?" tests and wall sliding.
If you only remember one chapter of this series, make it this one.

4.1 The idea: how much do two arrows agree?

Imagine you are pulling a sled with a rope.
If you pull straight forward, all your effort moves the sled.
If the rope goes up at an angle, part of your effort is wasted lifting the sled instead of moving it forward.
If you pull straight up, the sled doesn't move forward at all.

Pulling a sled straight forward, at an angle and straight up, and how much of the pull moves it forward

The dot product measures this "how much of one arrow goes along the other arrow".
It is big and positive when the arrows point the same way, zero when they are at a right angle, and negative when they point in opposite directions.

4.2 What the formula is

The dot product of two vectors 𝐚 and 𝐛 is written 𝐚⋅𝐛 (read "a dot b").
The result is a single number (a scalar), not a vector.
There are two formulas, and the whole magic of this chapter is that they always give the same answer.

The algebraic formula: multiply matching components, then add everything up.

𝐚⋅𝐛=axbx+ayby+azbz

In 2D, you just leave out the z term; in general, with the sigma notation from chapter 1:

𝐚⋅𝐛=∑i=1naibi=a1b1+a2b2+⋯+anbn

The geometric formula: multiply the two lengths and the cosine of the angle θ (theta) between the arrows.

𝐚⋅𝐛=‖𝐚‖‖𝐛‖cosθ

The first formula is how a computer calculates it.
The second one is what it means.

4.3 How it works

4.3.1 Calculating it

Let 𝐚=(1,2,3) and 𝐛=(4,−5,6).

𝐚⋅𝐛=1×4+2×(−5)+3×6=4−10+18=12

Three multiplications and two additions.
That's cheap, which is one reason GPUs can do billions of them per second.

4.3.2 Properties

A few rules follow directly from the algebraic formula, because they are true for ordinary multiplication and addition of each component:

  • Commutative: 𝐚⋅𝐛=𝐛⋅𝐚. The order doesn't matter, since axbx=bxax.
  • Distributive: 𝐚⋅(𝐛+𝐜)=𝐚⋅𝐛+𝐚⋅𝐜.
  • Scalars move out: (s𝐚)⋅𝐛=s(𝐚⋅𝐛).
  • Dot with itself is the squared length: 𝐚⋅𝐚=ax2+ay2+az2=‖𝐚‖2.

The last one connects this chapter with chapter 3.
For 𝐚=(1,2,3): 𝐚⋅𝐚=1+4+9=14, and ‖𝐚‖=14.
So the squared length from chapter 3 is just dot(v, v).

4.3.3 Why the two formulas agree

This is the most important "why" in this chapter, so let's take it slowly.
We'll do it in three steps.

Step 1: the dot product only depends on lengths.
Look at ‖𝐚−𝐛‖2.
By the last property, it equals (𝐚−𝐛)⋅(𝐚−𝐛), and we can multiply it out with the distributive rule just like (x−y)2=x2−2xy+y2:

‖𝐚−𝐛‖2=𝐚⋅𝐚−𝐚⋅𝐛−𝐛⋅𝐚+𝐛⋅𝐛=‖𝐚‖2−2𝐚⋅𝐛+‖𝐛‖2

Rearranging gives:

𝐚⋅𝐛=‖𝐚‖2+‖𝐛‖2−‖𝐚−𝐛‖22

Let's check with our numbers.
‖𝐚‖2=14, ‖𝐛‖2=16+25+36=77, 𝐚−𝐛=(−3,7,−3) so ‖𝐚−𝐛‖2=9+49+9=67.
Then 14+77−672=242=12. Same as before.

Why is this useful?
Draw 𝐚 and 𝐛 as arrows starting at the origin.
Together with the arrow 𝐚−𝐛 between their tips, they form a triangle, and the formula only uses the lengths of its three sides.

Vectors a and b from the origin with the angle θ between them and the arrow a − b closing the triangle

Step 2: turning the picture doesn't change the dot product.
If you rotate the whole triangle, the side lengths stay the same.
So the dot product stays the same, too.
That means we may rotate the picture into the most convenient position: with 𝐚 lying on the positive x axis.

Step 3: calculate in the convenient position.
Now 𝐚=(‖𝐚‖,0).
And 𝐛 makes the angle θ with the x axis, so by the unit circle from chapter 1 (scaled by the length of 𝐛, see chapter 3) it is 𝐛=(‖𝐛‖cosθ,‖𝐛‖sinθ).
Apply the algebraic formula:

𝐚⋅𝐛=‖𝐚‖×‖𝐛‖cosθ+0×‖𝐛‖sinθ=‖𝐚‖‖𝐛‖cosθ

Done.
In 3D it works the same way: two arrows starting at the origin always lie in one flat plane, and we can turn that plane until it is the xy plane.

Bonus: if you substitute the geometric formula into step 1, you get ‖𝐚−𝐛‖2=‖𝐚‖2+‖𝐛‖2−2‖𝐚‖‖𝐛‖cosθ, the "law of cosines" from trigonometry. At θ=90° the cosine is 0 and it becomes Pythagoras.

4.3.4 The sign tells the direction

Lengths are never negative, so the sign of 𝐚⋅𝐛 is the sign of cosθ.
From the unit circle we know what that means:

Dot product Angle Meaning
>0 less than 90° roughly the same direction
=0 exactly 90° perpendicular
<0 more than 90° roughly opposite directions

The sign of the dot product for an acute angle, a right angle and an obtuse angle

This is why the dot product is the standard test for perpendicular vectors: if it is 0, they are at a right angle.
Example: (1,2,2)⋅(2,1,−2)=2+2−4=0, so these two vectors are perpendicular, even though that's hard to see by looking at the numbers.

4.3.5 Finding the angle

If we know both formulas give the same number, we can solve for the angle:

cosθ=𝐚⋅𝐛‖𝐚‖‖𝐛‖,θ=arccos(𝐚⋅𝐛‖𝐚‖‖𝐛‖)

Here arccos ("arc cosine", acos in code) is the inverse of the cosine: you give it a cosine value between −1 and 1, it gives you back the angle between 0 and π.

Worked example: 𝐚=(1,1,0), 𝐛=(0,1,1).

𝐚⋅𝐛=1×0+1×1+0×1=1‖𝐚‖=2,‖𝐛‖=2cosθ=122=12θ=arccos(12)=π3≈1.0472 rad=60°

Another example in 2D: (2,0) and (1,1) give cosθ=222=12≈0.7071, which is 45°.

The really useful special case: if both vectors are unit vectors, the dot product IS the cosine, because both lengths are 1:

𝐚^⋅𝐛^=cosθ

That's why graphics code normalizes everything before taking dot products: then you get the cosine for the price of three multiplications.

The clamping pitfall.
Floating-point numbers are not exact.
Two unit vectors that point in the same direction may give a dot product of 1.0000001 instead of 1.
acos is only defined for values from −1 to 1, so acos(1.0000001) returns NaN, and we already know from chapter 3 how poisonous NaN is.
Always clamp the value into [−1, 1] before calling acos.

In practice you often don't need the angle at all.
If you want to know "is the angle smaller than 30°?", compare the dot product of unit vectors with cos30°≈0.866 instead.
A bigger cosine means a smaller angle, and you have saved an expensive acos.

4.3.6 Projection: the shadow of one vector on another

Back to the sled: "how much of the pull goes forward" is called the projection of the pull onto the forward direction.
Picture a light shining straight down onto 𝐛: the shadow of 𝐚 on the line of 𝐛 is the projection.

Projection of a = 4, 2 onto b = 3, 4, giving 2.4, 3.2, and the perpendicular part 1.6, −1.2

The scalar projection is the signed length of that shadow.
It's the length of 𝐚 times cosθ, which is the dot product with the unit vector of 𝐛:

shadow length=‖𝐚‖cosθ=𝐚⋅𝐛^

The vector projection is the shadow as an arrow: that length times the direction of 𝐛:

proj𝐛𝐚=(𝐚⋅𝐛^)𝐛^=𝐚⋅𝐛𝐛⋅𝐛𝐛

The second form avoids the square root, since 𝐛⋅𝐛=‖𝐛‖2.

Worked example: project 𝐚=(4,2) onto 𝐛=(3,4).

𝐚⋅𝐛=4×3+2×4=12+8=20‖𝐛‖=5,𝐛^=(0.6,0.8)𝐚⋅𝐛^=205=4proj𝐛𝐚=4×(0.6,0.8)=(2.4,3.2)

What's left over, 𝐚−proj𝐛𝐚=(4−2.4,2−3.2)=(1.6,−1.2), should be perpendicular to 𝐛.
Check: (1.6,−1.2)⋅(3,4)=4.8−4.8=0. Yes.

So every vector can be split into a part along 𝐛 and a part perpendicular to it.
That split is the basis of the next two tricks.

4.3.7 Removing a component: wall sliding

When a character walks into a wall at an angle, we don't want them to stop dead.
We want them to slide along the wall.
In other words: keep the part of the movement that goes along the wall, throw away the part that goes into it.

The wall's direction "out of the wall" is its unit normal 𝐧^.
The part of the velocity 𝐯 that goes along 𝐧^ is the projection (𝐯⋅𝐧^)𝐧^, so we subtract it:

𝐯slide=𝐯−(𝐯⋅𝐧^)𝐧^

Top view of wall sliding: the velocity v, the wall normal and the remaining slide vector

Worked example: the player moves with 𝐯=(4,0,−3) (right and forward), and there is a wall to the right whose normal points left, 𝐧^=(−1,0,0).

𝐯⋅𝐧^=4×(−1)+0+(−3)×0=−4𝐯slide=(4,0,−3)−(−4)(−1,0,0)=(4,0,−3)−(4,0,0)=(0,0,−3)

The sideways part is gone and the player keeps walking forward along the wall.
Note the negative dot product: it tells us the player is moving into the wall.
If 𝐯⋅𝐧^≥0, the player is moving away from the wall and you should leave the velocity alone.

4.3.8 Reflection

A bouncing ball, a laser hitting a mirror, a reflection of the sky on water: we need to mirror a direction 𝐝 off a surface with unit normal 𝐧^.
Sliding removed the normal part once.
Reflecting removes it twice: once to get to the surface, and once more to come back out on the other side.

𝐫=𝐝−2(𝐝⋅𝐧^)𝐧^

The direction d = 1, −1 reflected off a floor with normal 0, 1 becomes r = 1, 1

Worked example 1: a ball moving with 𝐝=(1,−1) hits the floor, 𝐧^=(0,1).
𝐝⋅𝐧^=−1, so 𝐫=(1,−1)−2(−1)(0,1)=(1,−1)+(0,2)=(1,1).
The horizontal motion stays, the vertical motion flips. Exactly what a bounce looks like.

Worked example 2: a ray going straight down, 𝐝=(0,−1,0), hits a tilted surface with 𝐧^=(0.6,0.8,0) (which is a unit vector: 0.36+0.64=1).

𝐝⋅𝐧^=0×0.6+(−1)×0.8+0×0=−0.8𝐫=(0,−1,0)−2(−0.8)(0.6,0.8,0)=(0,−1,0)+(0.96,1.28,0)=(0.96,0.28,0)

Check: ‖𝐫‖2=0.9216+0.0784=1.
Reflection doesn't change the length, as it should be for a mirror.
The formula only works if 𝐧^ is a unit vector; with a longer normal you'd subtract too much.

GLSL, Slang and HLSL all have this built in as reflect(d, n), with exactly this formula.
The normal must be normalized, and d points towards the surface (it's the incoming direction).

4.4 Use in graphics programming

4.4.1 Lambert diffuse lighting

A matte surface (paper, clay, a wall) is brightest when the light hits it head-on and gets darker as the light comes in at a flatter angle.
Johann Heinrich Lambert described this in 1760: the brightness is proportional to cosθ, where θ is the angle between the surface normal and the direction to the light.

A light beam hitting a surface head-on and at a flatter angle, where the same beam spreads over a larger area

Why the cosine?
A beam of light of a fixed width spreads over a larger area when it hits the surface at a flat angle, so each square centimeter gets less light.
And if both vectors are unit vectors, the cosine is just a dot product.
If the light is behind the surface, the dot product is negative; negative light makes no sense, so we clamp it to 0:

diffuse=max(𝐧^⋅𝐥^,0)

Numbers: a floor with 𝐧^=(0,1,0) and light coming from 𝐥^=(0.6,0.8,0) (the direction towards the light).
𝐧^⋅𝐥^=0+0.8+0=0.8, so the floor gets 80% of the light's brightness.
If the light were below the floor, 𝐥^=(0.6,−0.8,0), the dot product would be −0.8, and max turns that into 0: completely unlit.

Here is a full, small fragment shader:

struct Scene {
  float3 lightDir;   // unit vector from the surface towards the light
  float3 lightColor;
  float3 albedo;     // surface color
};
ConstantBuffer<Scene> scene;

[shader("fragment")]
float4 fragmentMain(float3 normal : NORMAL) : SV_Target {
  float3 n = normalize(normal); // interpolation made it shorter (chapter 3)
  float diffuse = max(dot(n, scene.lightDir), 0.0);
  float3 color = scene.albedo * scene.lightColor * diffuse;
  return float4(color, 1.0);
}
#version 450

layout(location = 0) in vec3 normal;
layout(location = 0) out vec4 outColor;

layout(set = 0, binding = 0) uniform Scene {
  vec3 lightDir;   // unit vector from the surface towards the light
  vec3 lightColor;
  vec3 albedo;     // surface color
};

void main() {
  vec3 n = normalize(normal); // interpolation made it shorter (chapter 3)
  float diffuse = max(dot(n, lightDir), 0.0);
  vec3 color = albedo * lightColor * diffuse;
  outColor = vec4(color, 1.0);
}
struct Scene {
  float3 lightDir;   // unit vector from the surface towards the light
  float3 lightColor;
  float3 albedo;     // surface color
};
ConstantBuffer<Scene> scene;

float4 fragmentMain(float3 normal : NORMAL) : SV_Target {
  float3 n = normalize(normal); // interpolation made it shorter (chapter 3)
  float diffuse = max(dot(n, scene.lightDir), 0.0);
  float3 color = scene.albedo * scene.lightColor * diffuse;
  return float4(color, 1.0);
}

Two things to watch out for.
First, n and lightDir must be in the same coordinate space (usually world space or view space; chapter 11 explains the spaces).
Second, the light direction points from the surface towards the light; if your engine stores it as "the direction the light travels", negate it first, or every lit side becomes dark and the other way round.
Real renderers also add a small constant "ambient" term so that the unlit side isn't pitch black.

4.4.2 Blinn-Phong specular highlights

Shiny surfaces show a bright spot (a highlight) where the light is reflected towards the eye.
The Blinn-Phong model computes it with the half vector 𝐡^: the direction exactly halfway between the direction to the light 𝐥^ and the direction to the viewer 𝐯^:

𝐡^=𝐥^+𝐯^‖𝐥^+𝐯^‖,specular=max(𝐧^⋅𝐡^,0)s

If the surface normal points exactly along the half vector, the surface acts like a perfect mirror between light and eye, and the highlight is at full strength.
The exponent s (the "shininess") controls how fast the highlight falls off: a big s gives a small, sharp highlight (polished metal), a small s a broad one (plastic).

Worked example with 𝐧^=(0,1,0) and 𝐥^=(0.6,0.8,0):

  • Viewer at the mirror position, 𝐯^=(−0.6,0.8,0): 𝐥^+𝐯^=(0,1.6,0), so 𝐡^=(0,1,0), 𝐧^⋅𝐡^=1, specular = 1.
  • Viewer straight above, 𝐯^=(0,1,0): 𝐥^+𝐯^=(0.6,1.8,0) with length 0.36+3.24=3.6≈1.8974.
  • So 𝐡^≈(0.3162,0.9487,0) and 𝐧^⋅𝐡^=1.83.6≈0.9487, whose square is exactly 3.243.6=0.9.
  • With s=8: 0.94878=0.94=0.6561. With s=32: 0.916≈0.1853.

Same angle, but the shinier surface has already lost most of its highlight.

float blinnPhong(float3 n, float3 l, float3 v, float shininess) {
  float3 h = normalize(l + v);
  return pow(max(dot(n, h), 0.0), shininess);
}
float blinnPhong(vec3 n, vec3 l, vec3 v, float shininess) {
  vec3 h = normalize(l + v);
  return pow(max(dot(n, h), 0.0), shininess);
}
float blinnPhong(float3 n, float3 l, float3 v, float shininess) {
  float3 h = normalize(l + v);
  return pow(max(dot(n, h), 0.0), shininess);
}

4.4.3 Rim lighting

Rim lighting makes the outline of an object glow, a popular effect for characters, ghosts and force fields.
The outline is where the surface turns away from the camera, that is, where the normal is perpendicular to the view direction, so 𝐧^⋅𝐯^ is close to 0.
In the middle of the object, facing us, 𝐧^⋅𝐯^ is close to 1.
So 1−𝐧^⋅𝐯^ is 0 in the middle and 1 at the edges, which is exactly a rim mask:

float rim(float3 n, float3 v, float power) {
  return pow(1.0 - saturate(dot(n, v)), power);
}
float rim(vec3 n, vec3 v, float power) {
  return pow(1.0 - clamp(dot(n, v), 0.0, 1.0), power);
}
float rim(float3 n, float3 v, float power) {
  return pow(1.0 - saturate(dot(n, v)), power);
}

For example with 𝐯^=(0,1,0): a normal (0,1,0) facing the camera gives 1−1=0, a normal (0.6,0.8,0) gives 1−0.8=0.2, and a normal (1,0,0) at the silhouette gives 1−0=1.
The power makes the rim thinner (bigger power) or wider.

4.4.4 Facing tests: front or behind?

Because the sign of the dot product says "same side or other side", it's the standard way to ask whether something is in front of something else.

Is the enemy in front of me?
Take my forward direction 𝐟^ and the arrow from me to the enemy, 𝐞−𝐩.
If their dot product is positive, the enemy is in front of me; if negative, behind.
I don't even need to normalize anything for this, because lengths never change the sign.

Example: I stand at the origin looking down −Z, 𝐟^=(0,0,−1).
An enemy at (3,0,−4): (3,0,−4)⋅(0,0,−1)=4>0, in front.
An enemy at (1,0,2): (1,0,2)⋅(0,0,−1)=−2<0, behind.

Is the enemy inside my view cone?
A guard in a stealth game can see 45° to each side.
Now we do normalize, because we want the cosine.
Let 𝐝^ be the normalized arrow from me to the enemy.
The enemy is inside the cone if 𝐟^⋅𝐝^>cos45°≈0.7071.

For the enemy at (3,0,−4): the length is 5, so 𝐝^=(0.6,0,−0.8) and 𝐟^⋅𝐝^=0.8.
0.8>0.7071, so the guard sees the enemy (the actual angle is arccos(0.8)≈36.87°, but we never needed to compute it).
Compute cos45° once when the game starts, not every frame.

Top view of a guard with a 45° view cone on each side and an enemy at 3, 0, −4 inside it

Is this triangle facing the camera?
A surface point 𝐩 with normal 𝐧 faces a camera at 𝐜 if 𝐧⋅(𝐜−𝐩)>0.
The back sides of a closed model can never be seen, so we can skip drawing them ("backface culling").
GPUs actually decide this with the triangle's winding order on screen instead, which we'll meet in chapter 5, but the idea is the same.

4.4.5 Reflections and sliding in shaders

The reflect built-in is used for mirror-like effects: compute the direction from the camera to the surface, reflect it about the normal, and use the result to look up a sky texture (a cube map).

float3 mirrorDirection(float3 cameraPos, float3 worldPos, float3 normal) {
  float3 d = normalize(worldPos - cameraPos); // incoming: from the eye to the surface
  return reflect(d, normalize(normal));
}
vec3 mirrorDirection(vec3 cameraPos, vec3 worldPos, vec3 normal) {
  vec3 d = normalize(worldPos - cameraPos); // incoming: from the eye to the surface
  return reflect(d, normalize(normal));
}
float3 mirrorDirection(float3 cameraPos, float3 worldPos, float3 normal) {
  float3 d = normalize(worldPos - cameraPos); // incoming: from the eye to the surface
  return reflect(d, normalize(normal));
}

Wall sliding usually lives on the CPU in the physics or character controller code, but it's the same projection formula as above; you'll see it in the C++ test program below.

4.5 Other uses

The dot product is one of the most common operations in all of science and engineering.

  • Work in physics: the work done by a force 𝐅 moving an object by 𝐝 is W=𝐅⋅𝐝. Pulling the sled with 𝐅=(30,40) newtons over 𝐝=(5,0) meters gives W=150+0=150 joules. With the geometric formula: ‖𝐅‖=50, cosθ=0.6, and 50×5×0.6=150. Same answer.
  • Cosine similarity: search engines, recommendation systems and AI "embeddings" turn documents, products or sentences into long vectors and compare them with cosθ=𝐚^⋅𝐛^. Count the words "cat", "dog", "car" in three documents: 𝐚=(2,1,0), 𝐛=(4,2,0), 𝐜=(0,1,3). Then 𝐚 and 𝐛 have similarity exactly 1 (same topic, one is just longer), while 𝐚 and 𝐜 give 1510≈0.1414 (not similar).
  • Statistics: the correlation coefficient of two data series is the cosine similarity of the two series after subtracting each one's average.
  • Weighted sums: a shopping receipt is a dot product. Buying quantities (3,2,5) of items costing (120,250,80) yen costs 360+500+400=1260 yen. A final grade with weights (0.2,0.3,0.5) and scores (80,90,70) is 16+27+35=78.
  • Neural networks: a single artificial neuron computes the dot product of its weights with its inputs (plus a constant). We'll see the matrix version in chapter 7.
  • Audio: comparing a signal with a sine wave of a given frequency is a dot product. That's the core idea of the Fourier transform, which tells you which frequencies (notes) are in a sound.

4.6 Code

The dot product goes into linalg.hh, for all three vector sizes.
Put it right after the scalar multiplication from chapter 2:

// 内積 / dot product (chapter 4)
inline float dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
inline float dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
inline float dot(Vec4 a, Vec4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }

The Vec4 version will become important in chapter 6, where every row of a matrix gets dotted with a vector.

The angle, projection and reflection helpers are short enough that I define them right in the test program instead of the header.
reflect takes a unit normal, like the shader built-in.
degrees() is the helper from chapter 1.

#include "linalg.hh"
#include <cstdio>

// Angle between two vectors, in radians.
float angleBetween(Vec3 a, Vec3 b) {
  float c = dot(normalize(a), normalize(b));
  if (c > 1.0f) c = 1.0f;   // rounding can push c slightly
  if (c < -1.0f) c = -1.0f; // outside [-1, 1]; acos would return NaN
  return std::acos(c);
}

// Vector projection of a onto b (b must not be zero).
Vec3 project(Vec3 a, Vec3 b) {
  return (dot(a, b) / dot(b, b)) * b;
}

// Reflect direction d off a surface with unit normal n.
Vec3 reflect(Vec3 d, Vec3 n) {
  return d - 2.0f * dot(d, n) * n;
}

int main() {
  Vec3 a{1.0f, 2.0f, 3.0f};
  Vec3 b{4.0f, -5.0f, 6.0f};
  printf("dot(a, b)       = %g\n", dot(a, b));
  printf("dot(a, a)       = %g\n", dot(a, a));

  float angle = angleBetween({1.0f, 1.0f, 0.0f}, {0.0f, 1.0f, 1.0f});
  printf("angle           = %.4f rad = %.2f deg\n", angle, degrees(angle));

  Vec3 p = project({4.0f, 2.0f, 0.0f}, {3.0f, 4.0f, 0.0f});
  printf("projection      = (%g, %g, %g)\n", p.x, p.y, p.z);

  // Wall sliding: remove the part of v that goes into the wall
  Vec3 v{4.0f, 0.0f, -3.0f};
  Vec3 wall{-1.0f, 0.0f, 0.0f};
  Vec3 slide = v - dot(v, wall) * wall;
  printf("slide           = (%g, %g, %g)\n", slide.x, slide.y, slide.z);

  Vec3 r = reflect({0.0f, -1.0f, 0.0f}, {0.6f, 0.8f, 0.0f});
  printf("reflect         = (%.2f, %.2f, %.2f)\n", r.x, r.y, r.z);

  // Lambert: brightness = max(dot(n, l), 0)
  Vec3 n{0.0f, 1.0f, 0.0f};
  Vec3 l{0.6f, 0.8f, 0.0f};
  float diffuse = dot(n, l);
  printf("diffuse         = %g\n", diffuse > 0.0f ? diffuse : 0.0f);

  // Is the enemy in front of me, and inside a 45 degree view cone?
  Vec3 forward{0.0f, 0.0f, -1.0f};
  Vec3 toEnemy = Vec3{3.0f, 0.0f, -4.0f} - Vec3{0.0f, 0.0f, 0.0f};
  float c = dot(forward, normalize(toEnemy));
  printf("cos to enemy    = %g -> %s\n", c, c > 0.7071f ? "inside cone" : "outside cone");

  // Shopping: quantities . prices
  Vec3 quantity{3.0f, 2.0f, 5.0f};
  Vec3 price{120.0f, 250.0f, 80.0f};
  printf("total           = %g yen\n", dot(quantity, price));
  return 0;
}

Expected output:

dot(a, b)       = 12
dot(a, a)       = 14
angle           = 1.0472 rad = 60.00 deg
projection      = (2.4, 3.2, 0)
slide           = (0, 0, -3)
reflect         = (0.96, 0.28, 0.00)
diffuse         = 0.8
cos to enemy    = 0.8 -> inside cone
total           = 1260 yen

One detail in reflect: 2.0f * dot(d, n) * n is calculated from left to right, so first two floats are multiplied, and then the float * Vec3 operator from chapter 2 does the rest.

4.7 Summary

  • The dot product 𝐚⋅𝐛 multiplies matching components and adds them up. The result is a number.
  • Geometrically, 𝐚⋅𝐛=‖𝐚‖‖𝐛‖cosθ. Both formulas agree because the dot product only depends on lengths, and lengths don't change when you rotate.
  • 𝐚⋅𝐚=‖𝐚‖2.
  • Positive: same general direction. Zero: perpendicular. Negative: opposite.
  • For unit vectors, the dot product is the cosine of the angle. Clamp to [−1, 1] before acos, or better, compare cosines directly.
  • Projection: (𝐚⋅𝐛^)𝐛^. Wall sliding: 𝐯−(𝐯⋅𝐧^)𝐧^. Reflection: 𝐝−2(𝐝⋅𝐧^)𝐧^.
  • Graphics: Lambert max(dot(n, l), 0), Blinn-Phong with the half vector, rim lighting, front/behind tests and view cones.

4.8 Challenges

  1. ★ Compute (2,−1,4)⋅(3,5,1) and (1,2)⋅(−2,1). Which pair is perpendicular?
  2. ★ Find the angle between (1,0) and (1,1), and between (1,0) and (−1,1), in degrees.
  3. ★ Project (3,1) onto (0,2), then onto (1,1). In both cases check that the leftover part is perpendicular.
  4. ★ A ball moving with (3,−2,1) bounces off the floor 𝐧^=(0,1,0). What is its new direction? What would wall sliding give instead?
  5. ★★ Write float lambert(Vec3 n, Vec3 l) in C++ that normalizes both inputs and returns max(dot, 0). For n = {0, 2, 0} and l = {3, 4, 0} it should print 0.8, and for l = {3, -4, 0} it should print 0.
  6. ★★ Write bool inViewCone(Vec3 pos, Vec3 forward, Vec3 target, float halfAngle) (angle in radians). For a guard at the origin looking along {0, 0, -1} with a half angle of 30°, the targets {1, 0, -3}, {2, 0, -2} and {0, 0, 5} should give true, false, false.
  7. ★★★ Using only the dot product, explain why 𝐯−(𝐯⋅𝐧^)𝐧^ is always perpendicular to 𝐧^ (hint: take its dot product with 𝐧^ and use 𝐧^⋅𝐧^=1). Then show that the reflection 𝐫 has the same length as 𝐝.


コメント(0)

まだコメントはありません。