Objectif de ce chapitreWhat you’ll learn
Wat je leert
  • Debug avec précision tes rendusScissor de l'API Metal
⏱ ~25 min
/// C++ — Menu_shared.h — update:21/11/26
#ifndef MENU_SHARED_H
#define MENU_SHARED_H

#include <simd/simd.h>

/* Un widget = un ou plusieurs de ces rectangles. Panneau, bouton, rail de
   slider, poignée, case à cocher : tout est un rectangle arrondi.
   48 octets, aucun pointeur, aucune texture. */
struct UIRect
{ // simd_float4 en C++, float4 en MSL, même taille et même alignement.
  simd_float4 bounds;      /* x, y, largeur, hauteur — PIXELS, origine haut-gauche */
  simd_float4 color;       /* rgba, alpha NON prémultipliée                        */
  float       radius;      /* rayon des coins en pixels (0 = angles vifs)          */
  float       borderWidth; /* 0 = rempli ; > 0 = contour de cette épaisseur        */
  float       softness;    /* 0.7 = antialiasing d'un pixel ; plus = halo/ombre    */
};

struct UIViewport
{
  simd_float2 size;
};

#endif /* MENU_SHARED_H */
/// C++ — Menu.hpp — update:21/11/26
#ifndef MENU_HPP
#define MENU_HPP

#include <Metal/Metal.hpp>

#include <cstdint>
#include <functional>
#include <string>
#include <vector>

#include "../includes/SharedGPU/Menu_shared.h"
#include "NonCopyable.hpp"

/* Les flags de debug voyagent jusqu'au GPU dans un seul uint : une branche
 uniforme dans le fragment (tous les threads prennent le même chemin, donc
 aucune divergence). À copier dans GlobalUniforms avant de dessiner. */
enum DebugFlag : uint32_t
{
  DebugNone         = 0u,
  DebugNormals      = 1u << 0,
  DebugDepth        = 1u << 1,
  DebugChunkBorders = 1u << 2,
  DebugUVs          = 1u << 3,
  DebugLightOnly    = 1u << 4,
};

struct UISettings
{
  float    fovDegrees       = 60.0f;
  float    exposure         = 1.0f; /* multiplicateur LINÉAIRE, pas un offset */
  float    mouseSensitivity = 1.0f;
  float    sunSpeed         = 1.0f;
  float    moveSpeed        = 3.0f;
  bool     wireframe        = false;
  bool     showStats        = true;
  uint32_t debugFlags       = DebugNone;

  // Format texte "clé = valeur", une par ligne. Charge AVANT de construire
  // la Camera, sinon la première frame utilise le FOV par défaut.
  bool load(const std::string& path);
  bool save(const std::string& path) const;
};

class UIMenu : NonCopyable
{
public:
  static constexpr uint32_t kMaxRects       = 512;
  static constexpr uint32_t kFramesInFlight = 3;

  UIMenu(MTL::Device*, MTL::Library*,
         MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat);
  ~UIMenu();

  // Le menu ne connaît pas ton système de texte : tu lui donnes une lambda.
  // x, y = coin HAUT-GAUCHE du texte, en pixels écran.
  using TextFn = std::function<void(const char* text, float x, float y,
                                    float size, simd::float4 color)>;

  void setTextCallback(TextFn callback) { m_drawText = std::move(callback); }

  void getToggle()        { m_open = !m_open; }
  void setOpen(bool open) { m_open = open; }
  bool isOpen() const     { return m_open; }

  // true = la souris appartient au menu. La caméra NE DOIT PAS tourner
  // pendant ce temps, sinon la vue part en vrille dès qu'on tire un slider.
  bool wantCaptureMouse() const { return m_open && (m_mouseInPanel || m_active != 0); }

  // mousePixel : origine HAUT-GAUCHE. Si ton InputState est en bas-gauche
  // (convention AppKit), passe { mouse.x, windowSize.y - mouse.y }. */
  void begin(simd::float2 mousePixel, bool mouseDown, simd::float2 windowSize);
  void end();

  void label(const char* text);
  void separator(const char* title = nullptr);
  bool button(const char* text);
  bool checkbox(const char* text, bool* value);
  bool flag(const char* text, uint32_t* bits, uint32_t mask);
  bool sliderFloat(const char* text, float* value,
                   float minValue, float maxValue, const char* format = "%.2f");

  void draw(MTL::RenderCommandEncoder* encoder);

private:
  void         buildPipeline(MTL::Device*, MTL::Library* shaderLibrary,
                             MTL::PixelFormat, MTL::PixelFormat);

  void         pushRect(simd::float2 position, simd::float2 size, simd::float4 color,
                        float radius = 0.0f, float borderWidth = 0.0f, float softness = 0.7f);
  bool         hitRect(simd::float2 position, simd::float2 size) const;
  simd::float2 nextRow(float height);
  void         drawText(const char* text, float x, float y, float size, simd::float4 color);
  bool         beginWidget(const char* text, uint32_t& outID, simd::float2& outOrigin);
  static uint32_t hashID(const char* text);

  NS::SharedPtr<MTL::RenderPipelineState> m_pipeline;
  NS::SharedPtr<MTL::DepthStencilState>   m_depthState;
  NS::SharedPtr<MTL::Buffer>              m_instanceBuffer;

  TextFn              m_drawText;
  std::vector<UIRect> m_rects;

  simd::float2 m_mouse         { 0.0f, 0.0f };
  simd::float2 m_windowSize    { 1.0f, 1.0f };
  simd::float2 m_cursor        { 0.0f, 0.0f };
  bool         m_mouseDown     = false;
  bool         m_mousePressed  = false; /* front montant  */
  bool         m_mouseReleased = false; /* front descendant */
  bool         m_mouseInPanel  = false;
  bool         m_open          = false;

  // Tout le mode immédiat tient dans ces deux entiers.
  // hot    : recalculé chaque frame, widget sous le curseur.
  // active : PERSISTE entre les frames, widget qui a capturé la souris.
  // C'est active qui fait qu'un slider continue de suivre le curseur
  // quand on sort du rail en tirant.
  uint32_t m_hot    = 0;
  uint32_t m_active = 0;

  uint64_t m_frame = 0;
};

#endif /* MENU_HPP */

Depth

Le depth test est neutralisé, pas désactivé : l'attachement depth reste branché (le pipeline doit rester compatible avec la passe), on se contente de toujours passer et de ne rien écrire.

/// C++ — Menu.cpp — update:21/11/26
#include "Menu.hpp"

#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>

static const simd::float4 kPanelBg     = { 0.055f, 0.062f, 0.075f, 0.94f };
static const simd::float4 kPanelBorder = { 1.000f, 1.000f, 1.000f, 0.10f };
static const simd::float4 kWidgetBg    = { 1.000f, 1.000f, 1.000f, 0.08f };
static const simd::float4 kRowHover    = { 1.000f, 1.000f, 1.000f, 0.06f };
static const simd::float4 kAccent      = { 1.000f, 0.373f, 0.122f, 1.00f }; /* orange LearnMSL */
static const simd::float4 kAccentDim   = { 1.000f, 0.373f, 0.122f, 0.55f };
static const simd::float4 kText        = { 0.900f, 0.910f, 0.930f, 1.00f };
static const simd::float4 kTextDim     = { 0.560f, 0.580f, 0.620f, 1.00f };

static constexpr float kPanelX     = 24.0f;
static constexpr float kPanelY     = 24.0f;
static constexpr float kPanelWidth = 330.0f;
static constexpr float kPadding    = 14.0f;
static constexpr float kRowHeight  = 26.0f;
static constexpr float kRowGap     = 4.0f;
static constexpr float kTextSize   = 15.0f;
static constexpr float kRadius     = 5.0f;

static inline float innerWidth() { return kPanelWidth - 2.0f * kPadding; }

UIMenu::UIMenu(MTL::Device* device, MTL::Library* shaderLibrary,
               MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat)
{
  buildPipeline(device, shaderLibrary, colorPixelFormat, depthPixelFormat);

  auto depthDescriptor = NS::TransferPtr(MTL::DepthStencilDescriptor::alloc()->init());
  depthDescriptor->setDepthCompareFunction(MTL::CompareFunctionAlways);
  depthDescriptor->setDepthWriteEnabled(false);
  m_depthState = NS::TransferPtr(device->newDepthStencilState(depthDescriptor.get()));

  // Un seul buffer, kFramesInFlight tranches. On écrit dans la tranche du
  // frame courant : le GPU peut encore lire celle d'avant.
  const NS::UInteger bytes = (NS::UInteger)kMaxRects * kFramesInFlight * sizeof(UIRect);
  m_instanceBuffer = NS::TransferPtr(device->newBuffer(bytes, MTL::ResourceStorageModeShared));

  m_rects.reserve(kMaxRects);
}

UIMenu::~UIMenu()
{}

void UIMenu::buildPipeline(MTL::Device* device, MTL::Library* shaderLibrary,
                         MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat)
{
  auto vertexFn   = NS::TransferPtr(shaderLibrary->newFunction(MTLSTR("vertex_ui")));
  auto fragmentFn = NS::TransferPtr(shaderLibrary->newFunction(MTLSTR("fragment_ui")));
  assert(vertexFn.get() && fragmentFn.get() && "shaders ui absents");

  auto descriptor = NS::TransferPtr(MTL::RenderPipelineDescriptor::alloc()->init());
  descriptor->setVertexFunction(vertexFn.get());
  descriptor->setFragmentFunction(fragmentFn.get());
  descriptor->setDepthAttachmentPixelFormat(depthPixelFormat);

  // Alpha blending classique (alpha non prémultipliée) : sans ça le menu
  // est un bloc opaque et les coins arrondis deviennent des carrés noirs.
  MTL::RenderPipelineColorAttachmentDescriptor* attachment =
  descriptor->colorAttachments()->object(0);
  attachment->setPixelFormat(colorPixelFormat);
  attachment->setBlendingEnabled(true);
  attachment->setRgbBlendOperation(MTL::BlendOperationAdd);
  attachment->setAlphaBlendOperation(MTL::BlendOperationAdd);
  attachment->setSourceRGBBlendFactor(MTL::BlendFactorSourceAlpha);
  attachment->setSourceAlphaBlendFactor(MTL::BlendFactorSourceAlpha);
  attachment->setDestinationRGBBlendFactor(MTL::BlendFactorOneMinusSourceAlpha);
  attachment->setDestinationAlphaBlendFactor(MTL::BlendFactorOneMinusSourceAlpha);

  NS::Error* error = nullptr;
  m_pipeline = NS::TransferPtr(device->newRenderPipelineState(descriptor.get(), &error));
  assert(!error && "Render pipeline ui KO");
}

#pragma mark - Outils internes

// FNV-1a 32 bits. Un compteur incrémental casserait dès qu'un widget apparaît sous condition :
// tous les suivants changeraient d'ID et perdraient leur état de drag en plein milieu d'un glissement.
uint32_t UIMenu::hashID(const char* text)
{
  uint32_t hash = 2166136261u;
  for (const char* p = text; p && *p; ++p)
  {
    hash ^= (uint32_t)(unsigned char)*p;
    hash *= 16777619u;
  }
  return hash ? hash : 1u; /* 0 est réservé à "aucun widget" */
}

void UIMenu::pushRect(simd::float2 position, simd::float2 size, simd::float4 color,
                    float radius, float borderWidth, float softness)
{
  if (m_rects.size() >= kMaxRects)
    return; /* on jette plutôt que de déborder */

  UIRect rect {};
  rect.bounds      = simd_make_float4(position.x, position.y, size.x, size.y);
  rect.color       = color;
  rect.radius      = radius;
  rect.borderWidth = borderWidth;
  rect.softness    = softness;
  m_rects.push_back(rect);
}

bool UIMenu::hitRect(simd::float2 position, simd::float2 size) const
{
  return m_mouse.x >= position.x && m_mouse.x < position.x + size.x
  && m_mouse.y >= position.y && m_mouse.y < position.y + size.y;
}

simd::float2 UIMenu::nextRow(float height)
{
  const simd::float2 origin { kPanelX + kPadding, m_cursor.y };
  m_cursor.y += height + kRowGap;
  return origin;
}

void UIMenu::drawText(const char* text, float x, float y, float size, simd::float4 color)
{
  if (m_drawText)
    m_drawText(text, x, y, size, color);
}

// Préambule commun à tous les widgets interactifs : ID, ligne, hot/active.
// Retourne false quand le menu est fermé — chaque widget devient alors un
// no-op, et le code appelant n'a aucun if à écrire.
bool UIMenu::beginWidget(const char* text, uint32_t& outID, simd::float2& outOrigin)
{
  if (!m_open || text == nullptr)
    return false;

  outID     = hashID(text);
  outOrigin = nextRow(kRowHeight);

  const bool over = hitRect(outOrigin, { innerWidth(), kRowHeight });

  // On ne devient hot que si aucun autre widget n'a capturé la souris :
  // sinon, en tirant un slider, tous les widgets survolés au passage s'allumeraient.
  if (over && (m_active == 0 || m_active == outID))
    m_hot = outID;

  if (over && m_mousePressed)
    m_active = outID;

  return true;
}

#pragma mark - Frame

void UIMenu::begin(simd::float2 mousePixel, bool mouseDown, simd::float2 windowSize)
{
  ++m_frame;
  m_windowSize = windowSize;
  m_rects.clear();
  m_hot = 0;

  // Fronts : c'est le press qui capture, le release qui valide. Tester
  // seulement "bouton enfoncé" déclencherait le clic 60 fois par seconde. */
  m_mousePressed  = mouseDown && !m_mouseDown;
  m_mouseReleased = !mouseDown && m_mouseDown;
  m_mouseDown     = mouseDown;
  m_mouse         = mousePixel;

  if (!m_open)
  {
    m_mouseInPanel = false;
    m_active       = 0;
    return;
  }

  m_cursor = { kPanelX + kPadding, kPanelY + kPadding };

  /* Emplacement réservé : la hauteur du panneau n'est connue qu'à end(),
   mais le fond doit être dessiné EN PREMIER pour passer derrière. */
  m_rects.push_back(UIRect {});
}

void UIMenu::end()
{
  if (!m_open)
    return;

  const float height = m_cursor.y - kPanelY + kPadding - kRowGap;
  const simd::float2 panelPos  { kPanelX, kPanelY };
  const simd::float2 panelSize { kPanelWidth, height };

  /* On remplit après coup l'emplacement réservé à begin(). */
  UIRect& panel   = m_rects[0];
  panel.bounds      = simd_make_float4(panelPos.x, panelPos.y, panelSize.x, panelSize.y);
  panel.color       = kPanelBg;
  panel.radius      = 10.0f;
  panel.borderWidth = 0.0f;
  panel.softness    = 0.7f;

  /* Le contour passe par-dessus tout : on l'ajoute en dernier. */
  pushRect(panelPos, panelSize, kPanelBorder, 10.0f, 1.0f);

  m_mouseInPanel = hitRect(panelPos, panelSize);

  // Relâchement : le widget rend la souris. Après les widgets, jamais avant,
  // sinon aucun d'eux ne verrait jamais son propre release. */
  if (!m_mouseDown)
    m_active = 0;
}

#pragma mark - Widgets

void UIMenu::label(const char* text)
{
  if (!m_open || text == nullptr)
    return;

  const simd::float2 origin = nextRow(kRowHeight * 0.8f);
  drawText(text, origin.x, origin.y + 3.0f, kTextSize, kTextDim);
}

void UIMenu::separator(const char* title)
{
  if (!m_open)
    return;

  if (title != nullptr)
  {
    const simd::float2 titlePos = nextRow(kRowHeight * 0.9f);
    drawText(title, titlePos.x, titlePos.y + 3.0f, kTextSize * 0.86f, kAccent);
  }

  const simd::float2 origin = nextRow(5.0f);
  pushRect({ origin.x, origin.y }, { innerWidth(), 1.0f }, kPanelBorder, 0.0f);
}

bool UIMenu::button(const char* text)
{
  uint32_t     id;
  simd::float2 origin;
  if (!beginWidget(text, id, origin))
    return false;

  const bool over    = (m_hot == id);
  const bool pressed = (m_active == id);

  /* Le clic ne se déclenche que si on relâche SUR le widget qu'on avait
   pressé : presser puis glisser dehors doit annuler. */
  const bool clicked = pressed && m_mouseReleased && over;

  const simd::float4 background = pressed ? kAccent : (over ? kAccentDim : kWidgetBg);
  pushRect(origin, { innerWidth(), kRowHeight }, background, kRadius);
  drawText(text, origin.x + 10.0f, origin.y + 6.0f, kTextSize, kText);

  return clicked;
}

bool UIMenu::checkbox(const char* text, bool* value)
{
  uint32_t     id;
  simd::float2 origin;
  if (value == nullptr || !beginWidget(text, id, origin))
    return false;

  const bool over    = (m_hot == id);
  const bool changed = (m_active == id) && m_mouseReleased && over;
  if (changed)
    *value = !*value;

  if (over)
    pushRect(origin, { innerWidth(), kRowHeight }, kRowHover, kRadius);

  const simd::float2 boxSize { 18.0f, 18.0f };
  const simd::float2 boxPos  { origin.x + innerWidth() - boxSize.x, origin.y + 4.0f };

  pushRect(boxPos, boxSize, *value ? kAccent : kWidgetBg, kRadius);
  if (*value)
    pushRect({ boxPos.x + 5.0f, boxPos.y + 5.0f }, { 8.0f, 8.0f }, kPanelBg, 2.0f);

  drawText(text, origin.x, origin.y + 6.0f, kTextSize, kText);
  return changed;
}

bool UIMenu::flag(const char* text, uint32_t* bits, uint32_t mask)
{
  if (bits == nullptr)
    return false;

  bool enabled = (*bits & mask) != 0u;
  if (!checkbox(text, &enabled))
    return false;

  if (enabled) *bits |=  mask;
  else         *bits &= ~mask;
  return true;
}

bool UIMenu::sliderFloat(const char* text, float* value,
                         float minValue, float maxValue, const char* format)
{
  uint32_t     id;
  simd::float2 origin;
  if (value == nullptr || maxValue <= minValue || !beginWidget(text, id, origin))
    return false;

  const float        railWidth = innerWidth() * 0.44f;
  const simd::float2 railPos  { origin.x + innerWidth() - railWidth,
    origin.y + kRowHeight * 0.5f - 3.0f };
  const simd::float2 railSize { railWidth, 6.0f };

  bool changed = false;

  /* LE point du slider : tant qu'on est actif, on suit la souris même
   quand elle est sortie du rail, de la ligne, ou du panneau. Sans cette
   capture, le curseur décroche dès qu'il dépasse d'un pixel. */
  if (m_active == id)
  {
    const float t        = std::clamp((m_mouse.x - railPos.x) / railWidth, 0.0f, 1.0f);
    const float newValue = minValue + t * (maxValue - minValue);
    if (newValue != *value)
    {
      *value  = newValue;
      changed = true;
    }
  }

  *value = std::clamp(*value, minValue, maxValue);
  const float ratio = (*value - minValue) / (maxValue - minValue);

  if (m_hot == id || m_active == id)
    pushRect(origin, { innerWidth(), kRowHeight }, kRowHover, kRadius);

  pushRect(railPos, railSize, kWidgetBg, 3.0f);
  pushRect(railPos, { railSize.x * ratio, railSize.y },
           (m_active == id) ? kAccent : kAccentDim, 3.0f);

  const simd::float2 handleSize { 12.0f, 16.0f };
  pushRect({ railPos.x + railSize.x * ratio - handleSize.x * 0.5f,
    railPos.y + railSize.y * 0.5f - handleSize.y * 0.5f },
           handleSize, kAccent, 3.0f);

  char buffer[64];
  std::snprintf(buffer, sizeof(buffer), format, *value);
  drawText(text,   origin.x, origin.y + 6.0f, kTextSize, kText);
  drawText(buffer, railPos.x - 58.0f, origin.y + 6.0f, kTextSize * 0.9f, kTextDim);

  return changed;
}

void UIMenu::draw(MTL::RenderCommandEncoder* encoder)
{
  if (!m_open || m_rects.empty())
    return;

  const NS::UInteger count  = (NS::UInteger)std::min<size_t>(m_rects.size(), kMaxRects);
  const NS::UInteger slot   = (NS::UInteger)(m_frame % kFramesInFlight);
  const NS::UInteger offset = slot * kMaxRects * sizeof(UIRect);

  std::memcpy(static_cast<char*>(m_instanceBuffer->contents()) + offset,
              m_rects.data(), count * sizeof(UIRect));

  UIViewport viewport {};
  viewport.size = simd_make_float2(m_windowSize.x, m_windowSize.y);

  /* L'état de l'encoder est sticky : on repose tout ce dont on dépend.
   Le menu dessine en dernier, donc on ne casse rien après. */
  encoder->setRenderPipelineState(m_pipeline.get());
  encoder->setDepthStencilState(m_depthState.get());
  encoder->setCullMode(MTL::CullModeNone);
  encoder->setTriangleFillMode(MTL::TriangleFillModeFill);

  encoder->setVertexBuffer(m_instanceBuffer.get(), offset, 0);
  encoder->setVertexBytes(&viewport, sizeof(viewport), 1);

  /* UNE draw call pour tout le menu : 4 sommets, N instances. */
  encoder->drawPrimitives(MTL::PrimitiveTypeTriangleStrip,
                          NS::UInteger(0), NS::UInteger(4), count);
}

bool UISettings::save(const std::string& path) const
{
  std::ofstream file(path, std::ios::trunc);
  if (!file)
    return false;

  file << "version = 1\n"
  << "fovDegrees = "       << fovDegrees       << '\n'
  << "exposure = "         << exposure         << '\n'
  << "mouseSensitivity = " << mouseSensitivity << '\n'
  << "sunSpeed = "         << sunSpeed         << '\n'
  << "moveSpeed = "        << moveSpeed        << '\n'
  << "wireframe = "        << (wireframe ? 1 : 0) << '\n'
  << "showStats = "        << (showStats ? 1 : 0) << '\n'
  << "debugFlags = "       << debugFlags       << '\n';
  return file.good();
}

bool UISettings::load(const std::string& path)
{
  std::ifstream file(path);
  if (!file)
    return false; /* pas de fichier = valeurs par défaut */

  std::string line;
  while (std::getline(file, line))
  {
    const size_t equals = line.find('=');
    if (equals == std::string::npos || line.empty() || line[0] == '#')
      continue;

    std::string key   = line.substr(0, equals);
    std::string value = line.substr(equals + 1);
    key.erase(key.find_last_not_of(" \t\r") + 1);
    value.erase(0, value.find_first_not_of(" \t"));

    std::istringstream stream(value);
    if      (key == "fovDegrees")       stream >> fovDegrees;
    else if (key == "exposure")         stream >> exposure;
    else if (key == "mouseSensitivity") stream >> mouseSensitivity;
    else if (key == "sunSpeed")         stream >> sunSpeed;
    else if (key == "moveSpeed")        stream >> moveSpeed;
    else if (key == "debugFlags")       stream >> debugFlags;
    else if (key == "wireframe")      { int v = 0; stream >> v; wireframe = (v != 0); }
    else if (key == "showStats")      { int v = 0; stream >> v; showStats = (v != 0); }
    // clé inconnue = version plus ancienne ou plus récente : on ignore, on ne casse pas.
  }

  /* Un fichier édité à la main peut contenir n'importe quoi. */
  fovDegrees = std::clamp(fovDegrees, 40.0f, 120.0f);
  exposure   = std::clamp(exposure,    0.1f,   8.0f);
  return true;
}
/// MSL — Menu.metal — update:21/11/26
#include <metal_stdlib>

#include "../includes/SharedGPU/Menu_shared.h"

using namespace metal;

/* [[flat]] : ces valeurs sont constantes sur tout le rectangle. Le dire
 évite trois interpolations par fragment et supprime toute dérive
 numérique sur les grands panneaux. */
struct UIRasterizerData
{
  float4 position [[position]];
  float2 local;                       /* pixels, relatif au CENTRE du rect */
  float2 halfSize [[flat]];
  float4 color    [[flat]];
  float  radius   [[flat]];
  float  border   [[flat]];
  float  softness [[flat]];
};

vertex UIRasterizerData vertex_ui(uint                 vertexID   [[vertex_id]],
                                  uint                 instanceID [[instance_id]],
                                  device const UIRect* rects      [[buffer(0)]],
                                  constant UIViewport& viewport   [[buffer(1)]])
{
  const UIRect r = rects[instanceID];
  
  /* Aucun vertex buffer de géométrie : les 4 coins d'un triangle strip
   sortent directement de l'ID -> (0,0) (1,0) (0,1) (1,1). */
  const float2 corner = float2(float(vertexID & 1u), float((vertexID >> 1u) & 1u));
  
  /* On dilate le quad de quelques pixels : le SDF a besoin de marge à
   l'extérieur du bord pour y étaler son antialiasing. Sans ça, les coins
   arrondis sont coupés net. */
  const float  pad      = r.softness + 1.0f;
  const float2 halfSize = r.bounds.zw * 0.5f;
  const float2 center   = r.bounds.xy + halfSize;
  const float2 local    = (corner * 2.0f - 1.0f) * (halfSize + pad);
  const float2 pixel    = center + local;
  
  UIRasterizerData out;
  /* Pixels (origine haut-gauche) -> NDC. Le Y s'inverse ici, et NULLE PART
   ailleurs : tout le C++ raisonne en pixels écran. */
  out.position = float4(pixel.x / viewport.size.x * 2.0f - 1.0f,
                        1.0f - pixel.y / viewport.size.y * 2.0f,
                        0.0f, 1.0f);
  out.local    = local;
  out.halfSize = halfSize;
  out.color    = r.color;
  out.radius   = min(r.radius, min(halfSize.x, halfSize.y));  /* jamais > la moitié */
  out.border   = r.borderWidth;
  out.softness = max(r.softness, 0.0001f);
  return out;
}

/* Distance signée à un rectangle arrondi, EN PIXELS.
 Négative dedans, nulle sur le bord, positive dehors.
 max(q, 0) traite les coins, min(max(q.x, q.y), 0) traite l'intérieur. */
static inline float sdRoundedBox(float2 p, float2 halfSize, float radius)
{
  const float2 q = abs(p) - halfSize + radius;
  return length(max(q, 0.0f)) + min(max(q.x, q.y), 0.0f) - radius;
}

fragment float4 fragment_ui(UIRasterizerData in [[stage_in]])
{
  float distance = sdRoundedBox(in.local, in.halfSize, in.radius);
  
  /* Contour : on ne garde que l'anneau [-border, 0] le long du bord.
   Le remplissage et le contour sortent du MÊME champ de distance —
   c'est tout l'intérêt du SDF. */
  if (in.border > 0.0f)
  {
    const float halfBorder = in.border * 0.5f;
    distance = abs(distance + halfBorder) - halfBorder;
  }
  
  /* Couverture antialiasée : une transition d'un pixel de part et d'autre
   du bord. Aucune texture, aucune résolution figée. */
  const float coverage = 1.0f - smoothstep(-in.softness, in.softness, distance);
  if (coverage <= 0.0f)
    discard_fragment();             /* évite le blend sur la marge */
  
  float3 rgb = in.color.rgb;
  
  rgb = pow(rgb, 2.2f);
  
  return float4(rgb, in.color.a * coverage);
}
/// C++ — Renderer.hpp — update:21/11/26
#include "Menu.hpp"

public:
  UIMenu uiMenu;
  UISettings uiSettings;
/// C++ — Renderer.cpp — update:21/11/26 — constructeur
uiMenu(m_device, m_shaderLibrary, m_pixelFormat, m_depthPixelFormat),
/// C++ — Renderer.cpp — update:21/11/26 — draw()
uiMenu.draw(renderCommandEncoder);
/// C++ — Renderer.cpp — update:21/11/26 — update()
uiMenu.wantCaptureMouse();
uiMenu.setOpen(true);

if (m_input.keyTab)
  uiMenu.getToggle();