La caméra et les matrices de projection
Une caméra 3D est une suite de transformations mathématiques qui convertissent les coordonnées du monde en coordonnées d'écran. Notre classe Camera encapsule ces matrices, gère un dirty flag (booléan annonçant une géométrie souillée), et expose des modes d'usage — FPS, orbite, follow, transition animée, shake.
Structure des fichiers
MSLearn/
├── MSLearn.entitlements
├── Application/ …
├── Frameworks/ …
├── Renderer/
│ ├── Renderer.cpp
│ ├── Renderer.hpp
│ ├── Math.cpp ← les helpers du chapitre précédent
│ ├── Math.hpp
│ ├── Camera.hpp
│ └── Camera.cpp
├── Shaders/ ← pas de shader pour ce chapitre, on se concentre sur C++ & les maths
├── includes/
│ ├── SharedAPP/
│ │ └── InputState.h
│ └── SharedGPU/
│ ├── Mesh_shared.h
│ └── Render_shared.h
└── Makefile
- Créer un système de coordonnées avec 3 axes unitaires perpendiculaires avec la position de la caméra comme origine
Notre objet caméra écrit dans un buffer nommés ici cameraUniforms qui sera envoyé aux shaders (dans le vertex buffer(1)) nécessitant trois dimensions minimum. Elle n'affiche rien à l'écran, ce sont des perspectives.
L’objet caméra n’est pas magique, ni fourni par l’API Metal. C’est l’ensemble de coordonnées de sommet du point de vue de la caméra, comme l'origine de la scène : la matrice de vue transforme toutes les coordonnées du monde en coordonnées de vue.
Pour définir une caméra :
Le meilleur moyen d'y parvenir est d'utiliser la méthode appelée look-at.
Une position (ou eye) dans l'espace mondial.
L’axe z de la matrice de vue doit être négatif parce que par convention (API Metal) la caméra pointe vers l'axe z positif. Droit devant toi.
simd::float3 position = { 0.0f, 0.0f, -3.0f }; // ← eye
Une direction vers laquelle elle regarde.
Soustraire le v⃗ de la cible (target, qui est le centre des axes pour commencer) du v⃗ position donne un v⃗ qui est la différence de ces deux vecteurs, le v⃗ direction :
simd::float3 target = { 0.0f, 0.0f, 0.0f }; // ← cible — centre fenêtre
simd::float3 direction = simd::normalize(target - position); // ← target - eye = forward (0, 0, +1)
0 - (-3) = 3 → normalisé → 1
Un vecteur pointant vers la droite.
L’axe x positif. Pour l’obtenir : on invente un vecteur pointant vers le haut (up) et on effectue un produit croisé (produit vectoriel) sur ce vecteur et le v⃗ de direction
simd::float3 up = { 0.0, 1.0, 0.0 }; // ← haut
simd::float3 right = simd::normalize(simd::cross(up, direction)); // ← droite
Puisque le résultat d'un produit croisé est un vecteur perpendiculaire aux deux vecteurs, nous aurons un vecteur qui pointe dans la direction de l'axe x positif :
\( \vec{up} \times \vec{direction} = \begin{pmatrix} 0.0 \\ 1.0 \\ 0.0 \end{pmatrix} \times \begin{pmatrix} 0.0 \\ 0.0 \\ 1 \end{pmatrix} = \begin{pmatrix} 1 \\ 0.0 \\ 0.0 \end{pmatrix} \)
Un vecteur pointant vers le haut.
Pour obtenir le bon \( \vec{up} \) on effectue un produit croisé du v⃗ de direction et du v⃗ de droite.
simd::float3 up = simd::normalize(simd::cross(direction, right)); // ← haut final
LookAt Matrix.
Nous savons depuis le chapitre sur les vecteurs que trois vecteurs orthogonaux \( \mathbf{right}, \mathbf{up}, \mathbf{forward} \) (avant) suffisent à décrire une orientation complète dans \( \mathbb{R}^3 \) (ensemble des 3 nombres réels), on peut encoder toute la pose de la caméra dans une seule matrice \(4 \times 4\) appelée world matrix de la caméra — c'est exactement ce que retourne notre fonction sViewMatrix (s dans le nom, pour static) :
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* + + */
/* File: Camera.cpp +++ +++ */
/* + + */
/* By: Laboitederemdal + + */
/* + + */
/* Created: 18/09/2025 18:56:40 + + + + + + */
/* Updated: 18/11/2026 */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include "Camera.hpp"
// params: position caméra, position + _direction (pas la target !), haut
static simd::float4x4 sViewMatrix(simd::float3 inEye, simd::float3 inTo, simd::float3 inUp)
{
simd::float3 z = simd::normalize(inTo - inEye); // axe forward (avant)
simd::float3 x = simd::normalize(simd::cross(inUp, z)); // axe right (droite)
simd::float3 y = simd::cross(z, x); // axe up (reortho)
// translation projetée sur chaque axe
simd::float3 t = (simd::float3){-simd::dot(x, inEye),-simd::dot(y, inEye),-simd::dot(z, inEye) };
// Matrice column-major : colonnes x, y, z, translation
return (simd::float4x4(simd::float4 { x.x, y.x, z.x, 0 },
simd::float4 { x.y, y.y, z.y, 0 },
simd::float4 { x.z, y.z, z.z, 0 },
simd::float4 { t.x, t.y, t.z, 1 }));
}
Produit vectoriel, notation mathématique :
\( LookAt = \begin{bmatrix} right_x && right_y && right_z && 0 \\ up_x && up_y && up_z && 0 \\ direction_x && direction_y && direction_z && 0 \\ 0 && 0 && 0 && 1 \end{bmatrix} \times \begin{bmatrix} 1 && 0 && 0 && -position_x \\ 0 && 1 && 0 && -position_y \\ 0 && 0 && 1 && -position_z \\ 0 && 0 && 0 && 1 \end{bmatrix} \)
\( LookAt = \begin{bmatrix} right_x && right_y && right_z && -right \cdot position \\ up_x && up_y && up_z && -up \cdot position \\ direction_x && direction_y && direction_z && -direction \cdot position \\ 0 && 0 && 0 && 1 \end{bmatrix} \)
Une matrice dont les colonnes sont \( \mathbf{right}, \mathbf{up}, \mathbf{forward} \) et la \( \mathbf{position} \), qui exprime le passage du repère caméra vers le repère monde.
La viewMatrix — le regard de la caméra
Or le shader ne veut pas ce passage-là — il veut l'inverse : transformer chaque vertex du monde vers l'espace caméra. On obtient la view matrix en inversant cette world matrix :
\[ \vec{v} = Matrix_{\text{camera}}^{-1} \]
simd::float4x4 viewMatrix = sViewMatrix(position, position + direction, up);
Et puisque \( M_{\text{camera}} \) est une matrice rigide (rotation + translation pures, sans échelle), son inverse a une forme analytique compacte — les axes en lignes, la translation projetée sur ces axes :
simd::float4x4 invViewMatrix = simd::inverse(viewMatrix);
Contrairement à OpenGL, la matrice InvLookAt et les matrices de projection ne sont pas fournies par Metal.
Notre objet — Camera.cpp
Une position initiale, la direction vers le centre du cube dessiné, le vecteur positif haut, 60° d'angle pour commencer exprimé en radians, le rapport d'aspect approximatif, un petit polygone créé par le plan de coupe, la taille du rectangle en projection orthographique, un booléan pour recalculer tout ça uniquement lorsque la caméra bouge.
→ \( \sphericalangle = \frac{\pi}{3} = 1.0471975512 \) radians
→ \( \sphericalangle = 1.0471975512 * (\frac{180}{\pi}) = 60.0\degree \)
→ \( aspectRatio = \frac{windowWidth}{windowHeight} \)
/// C++ — Camera.cpp — update:18/11/26
Camera::Camera() // Notre classe comment ici
: m_position{0, 0, -3}, m_direction{0, 0, 1}, m_up{0, 1, 0}, m_viewAngle(0.0f), m_aspectRatio(1.8),
m_nearPlane(0.1f), m_farPlane(100.0f), m_width(0), m_needRebuild(true) // valeur par défaut
{}
Camera::~Camera() {} // aucune valeur membre de la classe à détruire
// Fonction pour remplir/changer les paramètres de la classe — Init
Camera& Camera::initPerspectiveWithPosition(simd::float3 position, simd::float3 direction, simd::float3 up,
float viewAngle, float aspectRatio, float nearPlane, float farPlane)
{
m_direction = direction;
m_position = position;
m_up = up;
m_viewAngle = viewAngle;
m_aspectRatio = aspectRatio;
m_nearPlane = nearPlane;
m_farPlane = farPlane;
m_needRebuild = true;
return *this;
}
Camera& Camera::initParallelWithPosition(simd::float3 position, simd::float3 direction, simd::float3 up,
float width, float height, float nearPlane, float farPlane)
{
m_up = up;
orthogonalizeFromNewForward(direction);
m_position = position;
m_width = width;
m_viewAngle = 0;
m_aspectRatio = width / height;
m_nearPlane = nearPlane;
m_farPlane = farPlane;
m_needRebuild = true;
return *this;
}
Cela équivaut à init dans la classe : float m_width = 0; avec la priorité en supplément dans le cas où les deux sont définis !
Attention à l'initialisation pour ne pas provoquer un NaN : normalize{0, 0, 0}.
Faire/Refaire la géométrie
/// C++ — Camera.cpp — update:18/11/26
void Camera::rebuild() const
{
simd::float3 pos = m_position + m_shakeOffset;
m_cameraUniforms.viewMatrix = sViewMatrix(pos, pos + m_direction, m_up);
if (m_viewAngle != 0) // si pas d'angle → orthographique
m_cameraUniforms.projectionMatrix = math::makePerspective(m_viewAngle, m_aspectRatio, m_nearPlane, m_farPlane);
else
{
float ys = 2.0f / m_width;
float xs = ys / m_aspectRatio;
float zs = 1.0f / (m_farPlane - m_nearPlane);
m_cameraUniforms.projectionMatrix = simd::float4x4((simd::float4){xs, 0, 0, 0},
(simd::float4){ 0, ys, 0, 0},
(simd::float4){ 0, 0, zs, 0},
(simd::float4){ 0, 0, -m_nearPlane * zs , 1});
}
m_cameraUniforms.viewProjectionMatrix = m_cameraUniforms.projectionMatrix * m_cameraUniforms.viewMatrix;
m_cameraUniforms.invViewMatrix = simd::inverse(m_cameraUniforms.viewMatrix);
m_cameraUniforms.invProjectionMatrix = simd::inverse(m_cameraUniforms.projectionMatrix);
m_cameraUniforms.invViewProjectionMatrix = simd::inverse(m_cameraUniforms.viewProjectionMatrix);
m_cameraUniforms.invOrientationProjectionMatrix = simd::inverse(m_cameraUniforms.projectionMatrix *
sViewMatrix(simd::float3{0, 0, 0}, m_direction, m_up));
m_needRebuild = false;
}
C'est un pattern de cache paresseux (lazy evaluation) : on marque les données comme obsolètes quand l'état change, et on ne les recalcule qu'au moment où elles sont effectivement nécessaires.
Perspective
Une fois les vertices dans l'espace caméra, il faut simuler la perspective — le fait que les objets lointains paraissent plus petits.
C'est le rôle du field of view (FOV) : il définit l'angle d'ouverture du cône de vision. Plus \(\theta\) (angle) est grand, plus la scène paraît déformée et "fisheye" ; plus il est petit, plus l'image semble télé-objectif. À tester !
On en dérive un facteur de mise à l'échelle \( f = \frac{1}{\tan(\theta/2)} \) : quand un vertex est loin (grand \(z\)), sa coordonnée écran \( x/z \quad (\frac{width}{height}) \) diminue proportionnellement — c'est toute la mécanique de la perspective. La matrice de projection encode cette division en différant la division par \(z\) au GPU (la perspective divide) :
\[ P = \begin{bmatrix} f/\text{aspect} & 0 & 0 & 0 \\ 0 & f & 0 & 0 \\ 0 & 0 & \dfrac{\text{far}}{\text{near}-\text{far}} & \dfrac{\text{near}\cdot\text{far}}{\text{near}-\text{far}} \\ 0 & 0 & -1 & 0 \end{bmatrix} \]
La ligne \( -1 \) en bas copie \( -z_{\text{view}} \) dans \( w_{\text{clip}} \), et le GPU divise ensuite tout le vecteur clip par ce \( w \) — c'est la division perspective. Résultat : les coordonnées NDC \( (x/w,\, y/w) \) sont d'autant plus petites que l'objet est loin.
En multipliant les deux, on obtient la view-projection matrix qui condense en une seule opération le passage du monde vers l'écran :
\[ ViewProjectionMatrix = ProjectionMatrix \times ViewMatrix \]
Et parce que certains effets (ray casting, déferred shading, reconstruction de position depuis le depth buffer) ont besoin du chemin inverse — repartir d'un pixel NDC pour retrouver un point monde — on précalcule les inverses une seule fois sur le CPU plutôt que de les calculer dans chaque fragment shader :
\[ VP^{-1} = (P \times V)^{-1}, \quad V^{-1} = M_{\text{cam}}, \quad P^{-1} \]
Enfin, invOrientationProjectionMatrix est une variante où la translation de la caméra est délibérément ignorée — seule l'orientation est conservée — ce qui est exactement ce dont on a besoin pour un skybox ou un environnement infini : l'observateur tourne mais ne "déplace" jamais le fond du ciel.
\[ \mathrm{invOrientationProjectionMatrix} = \textcolor{50f17F}{\mathrm{simd::inverse}} \left( P \times \textcolor{92E846}{\mathrm{sViewMatrix}} (\mathbf{0}, \mathbf{dir}, \mathbf{up}) \right) \]
Toute la chaîne — position caméra, orientation, FOV, near/far, aspect — se retrouve ainsi compressée en quelques matrices précalculées que le vertex shader consomme en une seule multiplication par vertex.
Le polygone (view fructum) contient ce que tu vois à l'écran.
Les fonctions appartenant à notre classe
Créer d'autres setter & getter à ta guise.
/// C++ — Camera.cpp — update:18/11/26
// Retourne la copie de la structure du fichier _shared membre de notre classe Camera si besoin
CameraUniforms Camera::updateUniforms() const
{
if (m_needRebuild)
rebuild();
return m_cameraUniforms;
}
6 Getters — les membres sont toujours privés, on les récupère en toute sécurité :
/// C++ — Camera.cpp — update:18/11/26
simd::float3 Camera::getPosition() const
{
return m_position;
}
simd::float3 Camera::getForward() const
{
return m_direction;
}
simd::float3 Camera::getUp() const
{
return m_up;
}
simd::float3 Camera::getRight() const
{
return simd::normalize(simd::cross(m_up, m_direction));
}
simd::float3 Camera::getLeft() const
{
return -getRight();
}
simd::float4x4 Camera::getInvViewProjectionMatrix() const
{
return (m_cameraUniforms.invViewProjectionMatrix); // ou updateUniforms().invViewProjectionMatrix
}
6 Setters — les membres sont toujours privés, on les modifie en toute sécurité :
/// C++ — Camera.cpp — update:18/11/26
void Camera::setPosition(simd::float3 newPosition)
{
m_position = newPosition;
m_needRebuild = true;
}
void Camera::setViewAngle(float newAngle)
{
m_width = 0;
m_viewAngle = newAngle;
m_needRebuild = true;
}
void Camera::setWidth(float newWidth)
{
m_viewAngle = 0;
m_width = newWidth;
m_needRebuild = true;
}
void Camera::setUp(simd::float3 newUp)
{
orthogonalizeFromNewUp(newUp);
m_needRebuild = true;
}
void Camera::setDirection(simd::float3 newDirection)
{
orthogonalizeFromNewForward(newDirection);
m_needRebuild = true;
}
void Camera::setAspectRatio(float aspect)
{
m_aspectRatio = aspect;
m_needRebuild = true;
}
/// C++ — Renderer.cpp — update:18/11/26 — draw() ou update()
if (m_input.keyTab)
{
ViewMode currentViewMode = m_viewMode;
int nextViewMode = (static_cast<int>(currentViewMode) + 1) % static_cast<int>(ViewMode::Home); // 5 → 0 → 1 → …
setViewMode(static_cast<ViewMode>(nextViewMode));
}
Header de notre objet Caméra
/// C++ — Camera.hpp — update:18/11/26
#ifndef Camera_hpp
#define Camera_hpp
#include <functional> // std::function
#include "Math.hpp" // make projection etc …
#include "../includes/SharedGPU/Renderer_shared.h" // structure de nos matrices globales (uniforms)
// enum class : les valeurs sont préfixées par le type
enum class CameraEase {
Linear,
SmoothStep,
SmootherStep,
EaseInQuad,
EaseOutQuad,
EaseInOutQuad,
EaseInCubic,
EaseOutCubic,
EaseInOutCubic,
EaseInOutBack,
};
struct CameraSnapshot
{
simd::float3 position;
simd::float3 direction;
simd::float3 up;
float viewAngle;
float nearPlane;
float farPlane;
simd::float3 orbitTarget;
float orbitDistance;
float yaw;
float pitch;
// simd_quatf rotation = simd_quaternion(0.f, simd_make_float3(0, 1, 0));
// bool useTargetMode = true; // true = lookAt, false = quaternion
};
class Camera
{
public:
Camera();
~Camera();
Camera& initPerspectiveWithPosition(simd::float3 position, simd::float3 direction, simd::float3 up,
float viewAngle, float aspectRatio, float nearPlane, float farPlane);
Camera& initParallelWithPosition(simd::float3 position, simd::float3 direction, simd::float3 up,
float width, float height, float nearPlane, float farPlane);
// méthodes en lecture seule
CameraUniforms updateUniforms() const;
void rebuild() const;
bool isPerspective() const; // !!
bool isParallel() const; // !!
simd::float3 getLeft() const;
simd::float3 getRight() const;
simd::float3 getForward() const; // target/direction
simd::float3 getDown() const; // !!
simd::float3 backward() const; // !!
simd::float3 getUp() const;
simd::float3 getPosition() const;
simd::float4x4 getInvViewProjectionMatrix() const;
void setNearPlane(float newNearPlane);
void setFarPlane(float newFarPlane);
void setAspectRatio(float newAspectRatio);
void setViewAngle(float newAngle);
void setWidth(float newWidth);
void setPosition(simd::float3 newPosition);
void setUp(simd::float3 newUp);
void setDirection(simd::float3 newDirection);
void rotateOnAxis(simd::float3 inAxis, float inRadians);
void lookAt(simd::float3 target);
// getters
float getYaw() const { return m_yaw; }
float getPitch() const { return m_pitch; }
simd::float3 getOrbitTarget() const { return m_orbitTarget; }
float getOrbitDistance() const { return m_orbitDistance; }
bool isOrbitMode() const { return m_orbitMode; }
bool isTransitioning() const { return m_transitionActive; }
void rotateYawPitch(float deltaYaw, float deltaPitch);
void setYaw(float yaw);
void setPitch(float pitch);
void setPitchLimits(float minPitch, float maxPitch);
void followTarget(simd::float3 target, float distance, float height, float smoothing, float delta);
void setOrbitMode(bool enabled);
void setOrbitTarget(simd::float3 target);
void setOrbitDistance(float distance);
void orbit(float deltaYaw, float deltaPitch);
void zoom(float delta);
void rotateOnAxisOrbit(float yawDelta, float pitchDelta);
CameraSnapshot snapshot() const;
void applySnapshot(const CameraSnapshot& snap);
void transitionTo(const CameraSnapshot& target, float duration,
CameraEase ease = CameraEase::SmoothStep,
std::function<void()> onComplete = std::function<void()>());
void transitionTo(const Camera& other, float duration,
CameraEase ease = CameraEase::SmoothStep,
std::function<void()> onComplete = std::function<void()>());
void cancelTransition() { m_transitionActive = false; }
void updateTransition(float delta);
void applyShake(float intensity, float duration, float frequency = 25.0f);
private:
simd::float3 m_position;
simd::float3 m_direction;
simd::float3 m_right;
simd::float3 m_up;
float m_nearPlane;
float m_farPlane;
float m_aspectRatio;
float m_viewAngle;
float m_width; // carré de l'ortho, ortho only
mutable bool m_needRebuild;
mutable CameraUniforms m_cameraUniforms;
float m_yaw = 0.0f;
float m_pitch = 0.0f;
float m_pitchMin = -M_PI_2 + 0.001f; // Limite basse (-89.99°)
float m_pitchMax = M_PI_2 - 0.1f; // Limite haute (+89°)
simd::float3 m_orbitTarget = {0, 0, 0};
float m_orbitDistance = 10.0f;
bool m_orbitMode = false;
bool m_transitionActive = false;
CameraSnapshot m_transitionFrom;
CameraSnapshot m_transitionTo;
float m_transitionDuration = 0.0f;
float m_transitionElapsed = 0.0f;
CameraEase m_transitionEase = CameraEase::SmoothStep;
std::function<void()> m_transitionOnComplete = nullptr;
float m_shakeIntensity = 0.0f;
float m_shakeDuration = 0.0f;
float m_shakeElapsed = 0.0f;
float m_shakeFrequency = 25.0f;
simd::float3 m_shakeOffset = {0, 0, 0};
void orthogonalizeFromNewUp(simd::float3 newUp);
void orthogonalizeFromNewForward(simd::float3 newForward);
void updateOrbitPosition();
void updateDirectionFromYawPitch();
float applyEase(float time, CameraEase ease) const;
simd::float3 slerpDirection(simd::float3 a, simd::float3 b, float time) const;
};
#endif /* Camera_hpp */
std::function comme membre
Il permet de stocker n'importe quel callable (lambda, fonction, functor) en tant que membre. Ici il sert de callback de fin de transition — l'appelant passe ce qu'il veut exécuter quand la caméra arrive à destination.
// Appelé en fin de transition — usage lambda :
m_cameraPerspective.transitionTo(cinematicView, 2.0f, CameraEase::EaseInOutCubic,
[&]() { // Le callback peut lancer la transition suivante, ce qui donne des séquences de caméra :
m_cameraPerspective.transitionTo(m_cameraOrthographic, 15.0f, CameraEase::Linear,
[&]() {
exempleFunction(); // la paramètre de notre fonction ne stocke qu'un seul callable qui peut faire
m_audioEngine->playSoundEvent("GoodJob.m4a"); // autant d’appels de fonction que tu veux
});
});
// Dans updateTransition() — appel conditionnel :
if (t >= 1.0f)
{
_transitionActive = false;
applySnapshot(_transitionTo);
if (_transitionOnComplete) // teste si le callback est set
_transitionOnComplete(); // appel
}
Rotation
/// C++ — Camera.cpp — update:18/11/26
// formule d'Euler–Rodrigues
void Camera::rotateOnAxis(simd::float3 inAxis, float inRadians)
{
simd::float3 axis = simd::normalize(inAxis);
float ct = cosf(inRadians);
float st = sinf(inRadians);
float ci = 1 - ct;
float x = axis.x;
float y = axis.y;
float z = axis.z;
simd::float3x3 m((simd::float3){ ct + x * x * ci, y * x * ci + z * st, z * x * ci - y * st },
(simd::float3){ x * y * ci - z * st, ct + y * y * ci, z * y * ci + x * st },
(simd::float3){ x * z * ci + y * st, y * z * ci - x * st, ct + z * z * ci });
m_direction = m * m_direction;
m_up = m * m_up;
m_needRebuild = true;
}
Rotations
rotateYawPitch() reçoit des deltas : c'est elle qu'on branche sur mouseMoved().
setYaw() et setPitch() fixent un angle absolu (restaurer une vue, script de caméra).
/// C++ — Camera.cpp — update:18/11/26
void Camera::rotateYawPitch(float deltaYaw, float deltaPitch)
{
m_yaw += deltaYaw;
m_pitch += deltaPitch;
// Garde le yaw dans [-π, π] : évite que l'angle grossisse sans fin
while (m_yaw > M_PI)
m_yaw -= 2.0f * M_PI;
while (m_yaw < -M_PI)
m_yaw += 2.0f * M_PI;
m_pitch = simd::clamp(m_pitch, m_pitchMin, m_pitchMax);
if (m_orbitMode)
updateOrbitPosition();
else
updateDirectionFromYawPitch();
}
void Camera::setYaw(float yaw)
{
m_yaw = yaw;
if (m_orbitMode)
updateOrbitPosition();
else
updateDirectionFromYawPitch();
}
void Camera::setPitch(float pitch)
{
m_pitch = simd::clamp(pitch, m_pitchMin, m_pitchMax);
if (m_orbitMode)
updateOrbitPosition();
else
updateDirectionFromYawPitch();
}
void Camera::setPitchLimits(float minPitch, float maxPitch)
{
m_pitchMin = minPitch;
m_pitchMax = maxPitch;
// Limiter le pitch pour éviter le flip (gimbal lock) :
m_pitch = simd::clamp(m_pitch, m_pitchMin, m_pitchMax);
}
À ±90°, _direction devient parallèle à worldUp : leur produit vectoriel vaut zéro, normalize() renvoie NaN et l'image disparaît. setPitchLimits() te laisse resserrer les bornes, par exemple ±60° pour une caméra de véhicule.
Viser une cible et la suivre
lookAt() oriente la caméra vers un point et resynchronise yaw et pitch. Sans ça, le prochain mouvement de souris repartirait de l'ancien angle et la vue sauterait.
followTarget() place la caméra derrière une cible qui bouge (personnage, véhicule) et la rattrape en douceur. À appeler à chaque frame avec le deltaTime.
/// C++ — Camera.cpp — update:18/11/26
void Camera::lookAt(simd::float3 target)
{
simd::float3 toTarget = target - m_position; // ← forward (avant)
float distance = simd::length(toTarget);
if (distance < 0.001f) // cible sur la caméra : direction indéfinie
return;
m_direction = toTarget / distance;
// Inverse de updateDirectionFromYawPitch() : la souris repartira de ce regard
m_yaw = atan2f(m_direction.x, m_direction.z);
m_pitch = asinf(simd::clamp(m_direction.y, -1.0f, 1.0f));
simd::float3 worldUp = {0.f, 1.f, 0.f}; // ← haut hardcodé (temp)
simd::float3 right = simd::normalize(simd::cross(worldUp, m_direction)); // ← droite
m_up = simd::normalize(simd::cross(m_direction, right));
// view matrix camera rows:
// right → axe X caméra ( +1, 0, 0)
// up → axe Y caméra ( 0, +1, 0)
// direction → axe Z caméra ( 0, 0, +1)
m_needRebuild = true;
}
void Camera::followTarget(simd::float3 target, float distance, float height, float smoothing, float delta)
{ // Derrière la cible, à « distance », surélevée de « height »
simd::float3 idealPos = target - m_direction * distance + simd::float3{0, height, 0};
// smoothing = part du retard qui reste après 1 seconde (0.01 → nerveux, 0.5 → mou)
// indépendant du nombre d'images par seconde
float time = 1.0f - powf(smoothing, delta);
m_position = m_position + (idealPos - m_position) * time;
lookAt(target);
}
t = 1 - smoothingdt : après une seconde, il reste toujours la même part du retard, que le jeu tourne à 30 ou à 120 images par seconde. Un simple position += (ideal - position) * 0.1f suivrait deux fois plus vite à 120 FPS qu'à 60.
// Usage — chaque frame :
m_camera.followTarget(player.position, 6.0f, 2.0f, 0.05f, deltaTime);
Mode orbite, zoom
En orbite, yaw et pitch ne décrivent plus le regard mais la position de la caméra sur une sphère centrée sur la cible. orbit() active le mode tout seul : un clic-glisser suffit à passer de la vue FPS à l'inspection.
/// C++ — Camera.cpp — update:18/11/26
void Camera::setOrbitMode(bool enabled)
{
m_orbitMode = enabled;
if (enabled)
{
simd::float3 toTarget = m_orbitTarget - m_position;
m_orbitDistance = simd::length(toTarget);
if (m_orbitDistance > 0.001f)
{
simd::float3 direction = toTarget / m_orbitDistance;
m_yaw = atan2f(-direction.x, -direction.z);
m_pitch = -asinf(simd::clamp(direction.y, -1.0f, 1.0f));
}
}
else
{
m_yaw = atan2f(m_direction.x, m_direction.z); // la convention du regard, comme updateDirectionFromYawPitch()
m_pitch = asinf(simd::clamp(m_direction.y, -1.0f, 1.0f));
}
}
void Camera::setOrbitTarget(simd::float3 target)
{
m_orbitTarget = target;
if (m_orbitMode)
updateOrbitPosition();
}
void Camera::setOrbitDistance(float distance)
{
m_orbitDistance = simd::max(0.1f, distance);
if (m_orbitMode)
updateOrbitPosition();
}
void Camera::orbit(float deltaYaw, float deltaPitch)
{
if (!m_orbitMode)
setOrbitMode(true);
rotateYawPitch(deltaYaw, deltaPitch);
}
void Camera::zoom(float delta)
{
m_orbitDistance = simd::max(0.5f, m_orbitDistance - delta);
if (m_orbitMode)
updateOrbitPosition();
}
void Camera::rotateOnAxisOrbit(float yawDelta, float pitchDelta)
{
rotateYawPitch(yawDelta, pitchDelta);
}
En entrant en orbite, on déduit yaw et pitch de la position actuelle : la caméra ne bouge pas. En sortant, on les recalcule depuis le regard. Sans ces deux conversions, la caméra saute de l'autre côté de la cible, ou se retourne au premier mouvement de souris.
zoom() bloque à 0.5 et setOrbitDistance() à 0.1 : la caméra ne traverse jamais la cible.
Snapshots — enregistrer un point de vue
Un CameraSnapshot copie tout l'état de la caméra. Il sert à sauvegarder une vue (touches 1 à 9 d'un éditeur), à revenir en arrière, et surtout de point d'arrivée aux transitions.
/// C++ — Camera.cpp — update:18/11/26
CameraSnapshot Camera::snapshot() const
{
return { // même ordre que les membres de la structure CameraSnapshot
m_position, m_direction, m_up, m_viewAngle, m_nearPlane, m_farPlane,
m_orbitTarget, m_orbitDistance, m_yaw, m_pitch
};
}
void Camera::applySnapshot(const CameraSnapshot& snapshot)
{
m_position = snapshot.position;
m_direction = snapshot.direction;
m_up = snapshot.up;
m_viewAngle = snapshot.viewAngle;
m_nearPlane = snapshot.nearPlane;
m_farPlane = snapshot.farPlane;
m_orbitTarget = snapshot.orbitTarget;
m_orbitDistance = snapshot.orbitDistance;
m_yaw = snapshot.yaw;
m_pitch = snapshot.pitch;
m_needRebuild = true;
}
Easing et transition
La position et les valeurs scalaires sont interpolées linéairement (lerp), les directions sphériquement (slerp). La courbe d'easing ne change que la vitesse le long du trajet, pas le trajet.
/// C++ — Camera.cpp — update:18/11/26
void Camera::transitionTo(const CameraSnapshot& target, float duration, CameraEase ease, std::function<void()> onComplete)
{
m_transitionFrom = snapshot();
m_transitionTo = target;
m_transitionDuration = simd::max(0.001f, duration); // pas de division par zéro
m_transitionElapsed = 0.0f;
m_transitionEase = ease;
m_transitionActive = true;
m_transitionOnComplete = onComplete;
}
// Rejoindre le point de vue d'une autre caméra (caméra de cinématique, caméra joueur, …)
void Camera::transitionTo(const Camera& other, float duration, CameraEase ease, std::function<void()> onComplete)
{
transitionTo(other.snapshot(), duration, ease, onComplete);
}
Mise à jour de la transition
/// C++ — Camera.cpp — update:18/11/26
void Camera::updateTransition(float delta)
{
if (m_shakeDuration > 0.0f)
{
m_shakeElapsed += delta;
if (m_shakeElapsed < m_shakeDuration)
{
float decay = 1.0f - (m_shakeElapsed / m_shakeDuration);
float phase = m_shakeElapsed * m_shakeFrequency;
// Trois fréquences différentes par axe : le mouvement ne boucle pas visiblement
m_shakeOffset = {
sinf(phase) * m_shakeIntensity * decay,
cosf(phase * 1.3f) * m_shakeIntensity * decay * 0.7f,
sinf(phase * 0.7f) * m_shakeIntensity * decay * 0.3f
};
m_needRebuild = true;
}
else
{
m_shakeDuration = 0.0f;
m_shakeOffset = {0, 0, 0};
m_needRebuild = true;
}
}
if (!m_transitionActive)
return;
m_transitionElapsed += delta;
float time = simd::min(1.0f, m_transitionElapsed / m_transitionDuration);
float easedT = applyEase(time, m_transitionEase);
// Lerp position
m_position = m_transitionFrom.position + easedT * (m_transitionTo.position - m_transitionFrom.position);
// Slerp direction
m_direction = slerpDirection(m_transitionFrom.direction, m_transitionTo.direction, easedT);
// Slerp up
m_up = slerpDirection(m_transitionFrom.up, m_transitionTo.up, easedT);
// Lerp scalaires
m_viewAngle = m_transitionFrom.viewAngle + easedT * (m_transitionTo.viewAngle - m_transitionFrom.viewAngle);
m_nearPlane = m_transitionFrom.nearPlane + easedT * (m_transitionTo.nearPlane - m_transitionFrom.nearPlane);
m_farPlane = m_transitionFrom.farPlane + easedT * (m_transitionTo.farPlane - m_transitionFrom.farPlane);
// Orbit params
m_orbitTarget = m_transitionFrom.orbitTarget + easedT * (m_transitionTo.orbitTarget - m_transitionFrom.orbitTarget);
m_orbitDistance = m_transitionFrom.orbitDistance + easedT * (m_transitionTo.orbitDistance - m_transitionFrom.orbitDistance);
// chemin le plus court — de 170° à -170°, on tourne de 20°, pas de 340°
float deltaYaw = remainderf(m_transitionTo.yaw - m_transitionFrom.yaw, 2.0f * M_PI); // calcule le reste de la division flottante
m_yaw = m_transitionFrom.yaw + easedT * deltaYaw;
m_pitch = m_transitionFrom.pitch + easedT * (m_transitionTo.pitch - m_transitionFrom.pitch);
m_needRebuild = true;
if (time >= 1.0f)
{
m_transitionActive = false;
applySnapshot(m_transitionTo); // valeurs exactes, sans erreur d'arrondi
// Le callback peut relancer une transition, donc remplacer m_transitionOnComplete :
// on le sort du membre avant de l'appeler, sinon il serait détruit pendant son propre appel
std::function<void()> onComplete = std::move(m_transitionOnComplete);
m_transitionOnComplete = nullptr;
if (onComplete)
onComplete();
}
}
Le tremblement est mis à jour au même endroit que la transition : un seul appel par frame, et les deux se cumulent (une transition peut trembler).
Les transitions animent la caméra entre deux snapshots avec une courbe d'easing. La direction utilise un slerp pour éviter les raccourcis non-sphériques.
// Lancer une transition :
CameraSnapshot closeup;
closeup.position = {0, 2, -3};
closeup.direction = normalize({0, -0.3f, 1});
closeup.viewAngle = M_PI / 6.0f; // 30° FOV
m_camera.transitionTo(closeup, 1.5f, CameraEase::EaseInOutCubic, [&]() {
// callback quand la transition est terminée
startCutscene();
});
// Dans draw() — chaque frame :
m_camera.updateTransition(deltaTime);
Camera shake
applyShake() ne fait que lancer le tremblement ; le calcul se fait dans updateTransition(). Un nouvel appel remplace le tremblement en cours.
Déclenchement — explosion, impact, atterrissage :
/// C++ — Camera.cpp — update:18/11/26
void Camera::applyShake(float intensity, float duration, float frequency)
{
m_shakeIntensity = intensity; // intensité (en unités monde)
m_shakeDuration = duration; // durée en secondes
m_shakeElapsed = 0.0f;
m_shakeFrequency = frequency; // fréquence Hz
}
Impact léger : 0.05f, 0.2f, 30.0f. Explosion proche : 0.03f, 0.6f, 20.0f.
Au-delà de 0.5 unité, la scène devient illisible.
Réalise tes propres tests, comme pour les autres chapitres.
Yaw / Pitch — vue FPS
Yaw (ou lacet) = rotation autour de Y (gauche/droite).
Pitch = rotation autour de X local (haut/bas).
Roll = rotation autour de Z local ().
On les combine pour recalculer m_direction.
/// C++ — Camera.cpp — update:18/11/26
void Camera::updateDirectionFromYawPitch()
{
float cosP = cosf(m_pitch);
m_direction = simd::float3{
cosP * sinf(m_yaw), // X
sinf(m_pitch), // Y — monte/descend
cosP * cosf(m_yaw) // Z
};
m_direction = simd::normalize(m_direction);
// Re-ortho : recalculer _up depuis _direction et worldUp
simd::float3 worldUp = {0, 1, 0};
simd::float3 right = simd::normalize(simd::cross(m_direction, worldUp));
m_up = simd::cross(right, m_direction);
m_needRebuild = true;
}
Mode orbite — mettre à jour la position
En mode orbite, la caméra tourne autour d'un point fixe (m_orbitTarget) à une distance constante (m_orbitDistance). C'est le mode éditeur/inspection.
/// C++ — Camera.cpp — update:18/11/26
void Camera::updateOrbitPosition()
{
float cosP = cosf(m_pitch);
simd::float3 offset = {
cosP * sinf(m_yaw) * m_orbitDistance,
sinf(m_pitch) * m_orbitDistance,
cosP * cosf(m_yaw) * m_orbitDistance
};
m_position = m_orbitTarget + offset; // position sur la sphère
m_direction = simd::normalize(m_orbitTarget - m_position); // regarde toujours le centre
simd::float3 worldUp = {0, 1, 0};
simd::float3 right = simd::normalize(simd::cross(m_direction, worldUp));
m_up = simd::cross(right, m_direction);
m_needRebuild = true;
}
Réorthogonaliser la base
Après plusieurs rotations, les erreurs d'arrondi font que m_direction et m_up ne sont plus parfaitement perpendiculaires : l'image se déforme lentement. Ces deux fonctions reconstruisent une base propre à partir du vecteur qu'on veut garder.
/// C++ — Camera.cpp — update:18/11/26
// Nouveau « haut » imposé (roulis, gravité qui change) : on recalcule le regard
// si direction & up passés par l'appelant (setUp(), …) ne sont pas parfaitement orthogonaux
void Camera::orthogonalizeFromNewUp(simd::float3 newUp)
{ // on stocke le newUp en le normalisant, par sécurité
m_up = simd::normalize(newUp);
simd::float3 right = simd::normalize(simd::cross(m_up, m_direction)); // m_up écrasée par newUp
m_up = simd::normalize(simd::cross(m_direction, right));
}
// Nouveau regard imposé : on recalcule le haut
void Camera::orthogonalizeFromNewForward(simd::float3 newForward)
{
m_direction = simd::normalize(newForward);
simd::float3 right = simd::normalize(simd::cross(m_up, m_direction));
m_up = simd::normalize(simd::cross(m_direction, right));
}
Ease — Effet
/// C++ — Camera.cpp — update:18/11/26
float Camera::applyEase(float time, CameraEase ease) const
{
switch (ease)
{
case CameraEase::Linear:
return time;
case CameraEase::SmoothStep:
return time * time * (3.0f - 2.0f * time);
case CameraEase::SmootherStep:
return time * time * time * (time * (time * 6.0f - 15.0f) + 10.0f);
case CameraEase::EaseInQuad:
return time * time;
case CameraEase::EaseOutQuad:
return time * (2.0f - time);
case CameraEase::EaseInOutQuad:
return (time < 0.5f) ? 2.0f * time * time : -1.0f + (4.0f - 2.0f * time) * time;
case CameraEase::EaseInCubic:
return time * time * time;
case CameraEase::EaseOutCubic:
{
float f = time - 1.0f;
return f * f * f + 1.0f;
}
case CameraEase::EaseInOutCubic:
return (time < 0.5f) ? 4.0f * time * time * time
: (time - 1.0f) * (2.0f * time - 2.0f) * (2.0f * time - 2.0f) + 1.0f;
case CameraEase::EaseInOutBack:
{
const float c1 = 1.70158f;
const float c2 = c1 * 1.525f;
return (time < 0.5f)
? (std::pow(2.0f * time, 2.0f) * ((c2 + 1.0f) * 2.0f * time - c2)) / 2.0f
: (std::pow(2.0f * time - 2.0f, 2.0f) * ((c2 + 1.0f) * (time * 2.0f - 2.0f) + c2) + 2.0f) / 2.0f;
}
}
return time;
}
Les courbes d'easing
time va de 0 à 1 ; chaque courbe renvoie la progression à appliquer.
| Courbe | Formule | Effet |
|---|---|---|
| Linear | time | Vitesse constante, départ et arrivée secs. |
| SmoothStep | 3 * time² − 2 * time³ | Démarre et s'arrête en douceur. Le choix par défaut. |
| SmootherStep | 6 * time⁵ − 15 * time⁴ + 10 * time³ | Comme SmoothStep, accélération nulle aux deux bouts : aucun à-coup. |
| EaseInQuad / EaseInCubic | t² / t³ | Part lentement, arrive vite. Décollage, chute. |
| EaseOutQuad / EaseOutCubic | 1 − (1−t)² / 1 − (1−t)³ | Part vite, freine à l'arrivée. Recentrage sur un objet. |
| EaseInOutQuad / EaseInOutCubic | par morceaux | Accélère jusqu'à la moitié, puis freine. Cinématiques. |
| EaseInOutBack | par morceaux, c = 1.70158 | Recule un peu au départ et dépasse un peu à l'arrivée, puis revient. |
Slerp — interpoler une direction
Un lerp entre deux directions passe à l'intérieur de la sphère : le vecteur raccourcit, et la rotation accélère au milieu du trajet. Le slerp suit l'arc à vitesse angulaire constante.
/// C++ — Camera.cpp — update:18/11/26
simd::float3 Camera::slerpDirection(simd::float3 a, simd::float3 b, float time) const
{
a = simd::normalize(a);
b = simd::normalize(b);
float dot = simd::dot(a, b);
// Si presque parallèles, lerp simple
if (dot > 0.9995f)
return simd::normalize(a + time * (b - a));
if (dot < -0.9995f)
{
simd::float3 axis = (fabsf(a.y) < 0.99f) ? simd::float3{0, 1, 0} : simd::float3{1, 0, 0};
simd::float3 perp = simd::normalize(simd::cross(a, axis));
float theta = M_PI * time;
return a * cosf(theta) + perp * sinf(theta);
}
dot = simd::clamp(dot, -1.0f, 1.0f);
float theta = acosf(dot) * time;
simd::float3 relative = simd::normalize(b - a * dot);
return a * cosf(theta) + relative * sinf(theta);
}
enum class
Un enum class (enum fortement typé, C++11) est préférable au enum classique : les valeurs sont dans leur propre espace de noms, il n'y a pas de conversion implicite en int, et les collisions de noms sont impossibles.
/// C++ — Renderer.hpp — update:18/11/26 — généralement avant les structures
enum class ViewMode {
FreeCam, Building, DEV, ADD, FAB, Home // 0, 1, 2, 3, 4, 5
};
/// C++ — Renderer.hpp — update:18/11/26
public:
ViewMode m_viewMode = ViewMode::FreeCam;
void setViewMode(ViewMode mode);
/// C++ — Renderer.cpp — update:18/11/26
void Renderer::setViewMode(ViewMode mode)
{
m_viewMode = mode;
}
/// C++ — Renderer.hpp — update:18/11/26 — généralement avant les structures
enum class CameraMode {
FreeFly, // vol libre : ZQSD + A/E, souris pour regarder, molette = champ de vision
Orbit, // tourner autour de l'objet : souris, molette = distance, ZQSD + A/E = déplacer le centre
Follow, // suivre un point qui bouge, avec du retard (followTarget)
Cinematic, // des plans enchaînés, chacun avec une courbe d'easing différente
TopDown, // vue de dessus : orthographique ou perspective, molette = largeur visible
Count // le nombre de modes, pas un mode : sert à boucler avec ← / →
};
Intégration
Un banc d'essai pour toucher à toutes les fonctions de la caméra : chaque mode montre un morceau du chapitre. Le sujet est ton modèle Blender récupéré dans ↘ Script Python sur Blender posé en {0, 50, 0} dans le chapitre ↘ Assimp : dans tous les modes, elle reste dans le cadre.
/// C++ — Renderer.hpp — update:18/11/26
#include "Camera.hpp"
private:
static constexpr simd::float3 kCameraSubject = { 0.f, 50.f, 0.f };
Camera m_cameraPerspective;
Camera m_cameraOrthographic;
CameraMode m_cameraMode = CameraMode::Orbit;
simd::float3 m_freePosition = { 0.f, 0.f, 0.f };
float m_fov = M_PI / 1.89f;
float m_followTime = 0.f;
float m_followDistance = 12.f;
float m_followSmoothing = 0.15f;
int m_shot = 0;
int m_ease = 0;
float m_shotHold = 0.f;
simd::float3 m_topCenter = { 0.f, 0.f, 0.f };
float m_topWidth = 80.f;
bool m_topParallel = true;
void updateCamera(float delta, float speed);
void enterCameraMode(CameraMode mode);
void playNextShot();
/// C++ — Renderer.cpp — update:18/11/26 — constructeur
resizeViewWindow(width, height); // la caméra s'initialise à la première frame, la fenêtre a sa taille,
m_cameraPerspective.initPerspectiveWithPosition(kCameraSubject + simd::float3{0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 1.0f}, // et son FOV en dépend.
{0.0f, 1.0f, 0.0f},
M_PI / 1.89f,
1.0f, 2.0f, 2000.0f);
/// C++ — Renderer.cpp — update:18/11/26 — resizeViewWindow()
m_cameraPerspective.setAspectRatio((float)((float)width / (float)height));
/// C++ — Renderer.cpp — update:18/11/26 — update()
float speed = 5.0f * m_input.speedMultiplier * delta; // unités par seconde — le déplacement des chapitres suivants
updateCamera(delta, speed);
m_cameraPerspective.rotateOnAxis({0.0f, 1.0f, 0.0f}, m_input.mouseDelta.x); // rotation sur l'axe Y (up)
m_cameraPerspective.rotateOnAxis(-m_cameraPerspective.getLeft(), m_input.mouseDelta.y); // rotation sur la droite du regard de la caméra
simd::float3 position = m_cameraPerspective.getPosition();
if (m_input.keyQ)
{
m_cameraOrthographic.initParallelWithPosition({-300.0f, 89.0f, 45.0f},
{10.0f, 0.0f, 1.0f},
{0.0f, 1.0f, 0.0f},
0.f, 1.0f, 1.0f, 2500.0f);
m_cameraPerspective.transitionTo(m_cameraOrthographic, 15.0f, CameraEase::SmootherStep);
}
/// C++ — Renderer.cpp — update:18/11/26
static CameraSnapshot cameraShot(simd::float3 eye, simd::float3 target, float viewAngle)
{
const simd::float3 toTarget = target - eye;
const simd::float3 direction = simd::normalize(toTarget);
const simd::float3 right = simd::normalize(simd::cross(simd::float3{ 0.f, 1.f, 0.f }, direction));
const simd::float3 offset = -direction; // de la cible vers l'œil : la convention de l'orbite
return { eye, direction, simd::cross(direction, right), viewAngle, 0.1f, 2000.f,
target, simd::length(toTarget), atan2f(offset.x, offset.z), asinf(offset.y) };
}
/// C++ — Renderer.cpp — update:18/11/26
void Renderer::enterCameraMode(CameraMode mode)
{
m_cameraMode = mode;
m_cameraPerspective.cancelTransition(); // un plan en cours ne continue pas dans le mode suivant
m_cameraPerspective.setViewAngle(m_fov); // retour en perspective (TopDown peut l'avoir laissée en ortho)
switch (mode)
{
case CameraMode::FreeFly:
m_cameraPerspective.setOrbitMode(false);
m_freePosition = m_cameraPerspective.getPosition(); // on repart d'où l'on est
m_cameraPerspective.lookAt(kCameraSubject); // lookAt recalcule aussi yaw et pitch pour la souris
break;
case CameraMode::Orbit:
m_cameraPerspective.setOrbitTarget(kCameraSubject);
m_cameraPerspective.setOrbitMode(true);
m_cameraPerspective.setOrbitDistance(30.f);
m_cameraPerspective.setYaw(M_PI); // derrière l'objet, côté z négatif
m_cameraPerspective.setPitch(0.35f); // 20° au-dessus
break;
case CameraMode::Follow:
m_cameraPerspective.setOrbitMode(false);
m_followTime = 0.f;
break;
case CameraMode::Cinematic:
m_cameraPerspective.setOrbitMode(false);
m_shotHold = 0.f;
playNextShot();
break;
case CameraMode::TopDown:
m_cameraPerspective.setOrbitMode(false);
m_topCenter = kCameraSubject;
m_topParallel = true;
break;
case CameraMode::Count:
break;
}
}
void Renderer::playNextShot()
{
const simd::float3 s = kCameraSubject;
const CameraSnapshot shots[] = {
cameraShot(s + simd::float3{ 0.f, 8.f, -40.f }, s, M_PI / 3.f), // de face, à distance
cameraShot(s + simd::float3{ 35.f, 25.f, 0.f }, s, M_PI / 4.f), // trois quarts, en surplomb
cameraShot(s + simd::float3{ 0.f, 60.f, -1.f }, s, M_PI / 3.f), // presque à la verticale
cameraShot(s + simd::float3{ -6.f, 1.f, -6.f }, s, M_PI / 2.f), // tout près, grand angle
cameraShot(s + simd::float3{ -31.f, 12.f, -365.f }, s, M_PI / 5.f), // angle cinématique
};
const int shotCount = sizeof(shots) / sizeof(shots[0]);
const int easeCount = static_cast<int>(CameraEase::EaseInOutBack) + 1; // les 10 courbes, une par plan
const CameraEase ease = static_cast<CameraEase>(m_ease);
m_cameraPerspective.transitionTo(shots[m_shot], 3.f, ease);
m_shot = (m_shot + 1) % shotCount;
m_ease = (m_ease + 1) % easeCount;
m_shotHold = 0.f;
}
void Renderer::updateCamera(float delta, float speed)
{ // ← / → : mode précédent / suivant — un appui = un seul changement, pas un par frame
const int modeCount = static_cast<int>(CameraMode::Count);
if (m_input.keyRight && !m_prevKeyRight)
enterCameraMode(static_cast<CameraMode>((static_cast<int>(m_cameraMode) + 1) % modeCount));
if (m_input.keyLeft && !m_prevKeyLeft)
enterCameraMode(static_cast<CameraMode>((static_cast<int>(m_cameraMode) + modeCount - 1) % modeCount));
const bool action = m_input.rightMouseDown && !m_prevRightMouse; // clic droit : l'action du mode
m_prevKeyLeft = m_input.keyLeft;
m_prevKeyRight = m_input.keyRight;
m_prevRightMouse = m_input.rightMouseDown;
// Le clavier, en trois axes : Z / S avant-arrière, Q / D gauche-droite, A / E haut-bas
const float keyForward = (m_input.keyZ ? 1.f : 0.f) - (m_input.keyS ? 1.f : 0.f);
const float keyLeft = (m_input.keyQ ? 1.f : 0.f) - (m_input.keyD ? 1.f : 0.f);
const float keyUp = (m_input.keyA ? 1.f : 0.f) - (m_input.keyE ? 1.f : 0.f);
const simd::float3 forward = m_cameraPerspective.getForward();
switch (m_cameraMode)
{
case CameraMode::FreeFly:
{ // Souris vers la droite : yaw +, vers le bas : pitch − (inverse le signe si ça te paraît à l'envers)
m_cameraPerspective.rotateYawPitch(m_input.mouseDelta.x, -m_input.mouseDelta.y);
m_fov = simd::clamp(m_fov - m_input.scrollDelta * 0.05f, (float)M_PI / 9.f, (float)M_PI * 0.55f); // 20° … 100°
m_cameraPerspective.setViewAngle(m_fov);
if (action)
m_cameraPerspective.lookAt(kCameraSubject);
simd::float3 move = m_cameraPerspective.getForward() * keyForward + m_cameraPerspective.getLeft() * keyLeft
+ simd::float3{ 0.f, keyUp, 0.f };
if (simd::length_squared(move) > 0.f)
m_freePosition += simd::normalize(move) * speed;
// Notre position, réappliquée chaque frame : un autre bloc de update() qui bouge la caméra n'y change rien
m_cameraPerspective.setPosition(m_freePosition);
break;
}
case CameraMode::Orbit:
{
// Le centre se déplace à plat : avancer ne fait pas plonger quand on regarde vers le bas
const simd::float3 flatForward = simd::normalize(simd::float3{ forward.x, 0.f, forward.z });
const simd::float3 flatLeft = { -flatForward.z, 0.f, flatForward.x };
const simd::float3 pan = flatForward * keyForward + flatLeft * keyLeft + simd::float3{ 0.f, keyUp, 0.f };
if (simd::length_squared(pan) > 0.f)
m_cameraPerspective.setOrbitTarget(m_cameraPerspective.getOrbitTarget() + simd::normalize(pan) * speed);
m_cameraPerspective.orbit(m_input.mouseDelta.x, m_input.mouseDelta.y); // replace aussi la caméra sur sa sphère
m_cameraPerspective.zoom(m_input.scrollDelta);
if (m_input.keyD)
m_cameraPerspective.applyShake(0.4f, 0.6f, 30.f);
break;
}
case CameraMode::Follow:
{
// Le point suivi se balance près de l'objet : la caméra le rattrape avec du retard
m_followTime += delta;
const simd::float3 target = kCameraSubject + simd::float3{ 10.f * sinf(m_followTime * 0.5f),
3.f * sinf(m_followTime * 1.3f), 0.f };
m_followDistance = simd::clamp(m_followDistance - m_input.scrollDelta, 3.f, 60.f);
if (action)
m_followSmoothing = m_followSmoothing < 0.1f ? 0.5f : 0.01f;
m_cameraPerspective.followTarget(target, m_followDistance, 3.f, m_followSmoothing, delta);
break;
}
case CameraMode::Cinematic:
{
// Chaque plan tient 1,5 s une fois arrivé, puis le suivant part
m_shotHold = m_cameraPerspective.isTransitioning() ? 0.f : m_shotHold + delta;
if (action || m_shotHold > 1.5f)
playNextShot();
break;
}
case CameraMode::TopDown:
{
m_topWidth = simd::clamp(m_topWidth - m_input.scrollDelta * 4.f, 10.f, 400.f); // unités du monde visibles en hauteur
// Glisser la carte : à droite = +x, en haut de l'écran = +z
m_topCenter += simd::float3{ -m_input.mouseDelta.x, 0.f, m_input.mouseDelta.y } * m_topWidth;
m_topCenter += simd::float3{ -keyLeft, 0.f, keyForward } * (speed * m_topWidth / 40.f);
if (action)
m_topParallel = !m_topParallel;
// 300 unités au-dessus du centre, regard vers le bas. Le « haut » de l'écran ne peut pas être +y
// (parallèle au regard) : c'est +z
m_cameraPerspective.initPerspectiveWithPosition(m_topCenter + simd::float3{ 0.f, 300.f, 0.f },
{ 0.f, -1.f, 0.f },
{ 0.f, 0.f, 1.f },
m_fov, 1.8,
0.1f, 2000.f);
if (m_topParallel)
m_cameraPerspective.setWidth(m_topWidth); // viewAngle = 0 → rebuild() choisit la projection orthographique
break;
}
case CameraMode::Count:
break;
}
m_cameraPerspective.updateTransition(delta); // les plans (Cinematic) et la secousse (Orbit)
}
La structure CameraUniforms contiendra une data shadowCameraUniforms[3]; — une caméra par cascade de CSM (Cascaded Shadow Maps). L'implémentation fera l'objet d'un chapitre dédié au triplanar mapping.