Chapitre -100 · Bibliothèque de fonctions mathématiques

De quoi animer des PNJ

Un fichier unique

MSLearn/ ├── Renderer/ │ └── MathFunction.hpp ← la bibliothèque (ce chapitre) └── …
/// C++ — MathFunction.hpp — update:23/10/26
#ifndef MathFunction_hpp
#define MathFunction_hpp

#endif /* MathFunction_hpp */

Cinq petits outils

wrapAngle — tourner par le plus court chemin. La personne non joueur regarde à -170°, sa cible est à 170° : la différence brute vaut 340°, le bon chemin -20°. std::remainder(a, 2π) retire le multiple de 2π le plus proche, ce qui ramène toujours dans [-π, π] : \( \text{wrap}(a) = a - \textcolor{yellow}2\pi \cdot \text{round}\left(\frac{a}{2\pi}\right) \). std::fmod garderait 340°, il arrondit vers zéro.

/// C++ — MathFunction.hpp — update:23/10/26
inline float wrapAngle(float angle)
{ // Ramène un angle dans [-π, π] : pour tourner par le chemin le plus court
  return std::remainder(angle, 2.f * (float)M_PI);
}

clampLength — borner une vitesse sans tordre sa direction : si la longueur dépasse le maximum, on multiplie tout le vecteur par \( \frac{\text{maximum}}{\text{longueur}} \).

/// C++ — MathFunction.hpp — update:23/10/26
inline simd::float3 clampLength(simd::float3 vector, float maximum)
{ // Raccourcit un vecteur s'il dépasse `maximum` (garde sa direction) :
  const float length = simd::length(vector);
  return length > maximum ? vector * (maximum / length) : vector;
} // Cela sert à borner vitesse et accélération

rotation — un quaternion (« tourner de tant autour de cet axe », en quatre nombres) converti en matrice 4×4. L'axe doit être de longueur 1.

/// C++ — MathFunction.hpp — update:23/10/26
inline simd::float4x4 rotation(float angle, simd::float3 axis)
{ // Matrice de rotation de `angle` radians autour de `axis`
  return simd_matrix4x4(simd_quaternion(angle, axis));
}

cellCenter — dans le monde en voxels, la case (3, 0, 7) va de 3 à 4 en x : ses coordonnées entières sont son coin, son centre est à +0.5.

/// C++ — MathFunction.hpp — update:23/10/26
inline simd::float3 cellCenter(simd::int3 cell)
{ // Centre d'une case de voxel (ses coordonnées entières sont son coin)
  return simd::float3{ (float)cell.x, (float)cell.y, (float)cell.z } + 0.5f;
}

transformPoint — la translation d'une matrice 4×4 n'agit que si w = 1 :

\( \begin{pmatrix} R & t \\ 0 & 1 \end{pmatrix} \begin{pmatrix} p \\ 1 \end{pmatrix} = \begin{pmatrix} Rp + t \\ 1 \end{pmatrix} \qquad \begin{pmatrix} R & t \\ 0 & 1 \end{pmatrix} \begin{pmatrix} d \\ 0 \end{pmatrix} = \begin{pmatrix} Rd \\ 0 \end{pmatrix} \)

Un point (la pointe du laser) suit le drone : w = 1. Une direction (où pointe le laser) tourne seulement : w = 0.

/// C++ — MathFunction.hpp — update:23/10/26
inline simd::float3 transformPoint(const simd::float4x4& matrix, simd::float3 point)
{ // Applique une matrice à un point
  return (matrix * simd::float4{ point.x, point.y, point.z, 1.f }).xyz;
} // w = 1 : la translation compte, contrairement à une direction