Chapitre -125 · Le pont entreThe Bridge Between
De brug tussen
C++ & Objective-C

Tout ce dont tu as besoinEverything you need
Alles wat je nodig hebt
pourto
om
ouvrir une MTKViewopen an MTKView
een MTKView te openen
et peut-êtreand maybe
en misschien
lancer ta première applicationlaunch your first application
je eerste applicatie te starten

À partir de ce chapitre, nous ajouterons du code petit à petit au même projet,From this chapter onward, we will add code little by little to the same project,
Vanaf dit hoofdstuk voegen we beetje bij beetje code toe aan hetzelfde project,
sur des dizaines de chapitres.across dozens of chapters.
over tientallen hoofdstukken heen.

Objectif de ce chapitreWhat you’ll learn
Wat je leert
  • Le quartz pour l'animationYour first run
    Je eerste run
  • Ton premier run
⏱ ~10 min
PrérequisPrerequisites
Vereisten

Ton fichier main :Your main file:
Je main-bestand:
ton programme débute son exécution iciwhere your program starts executing
hier begint je programma te lopen

Ci-dessous se trouveBelow is
Hieronder staat
le seul et unique fichier écrit en Objective-C du projet.the one and only file written in Objective-C in the whole project.
het enige bestand van het project dat in Objective-C geschreven is.

Grâce à lui, tu peux lancer une application macOS;you can launch a macOS application;
Dankzij dit bestand kun je een macOS-applicatie starten;

On s'occupera un peu plus tard du rendu sur l'environnement iOS, iPadOS, etc …Rendering on iOS, iPadOS and friends comes later.
Het renderen op iOS, iPadOS en co komt later.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // bloc de commentaire
/*                                        +       +          */ // comment block
/*      File: main.m            +++     +++                  */ // commentaarblok
/*                                        +       +          */ // pour personnaliser le tien :
/*      By: Laboitederemdal                +       +         */ // to customize your own:
/*                                       +           +       */ // om die van jou aan te passen:
/*      Created: 16/04/2026 04:01:42      + + + + + +        */ // ↘ Configuration ZSH .zshrc
/*      Updated: 15/10/2026                                  */ // ↘ ZSH configuration .zshrc
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ // ↘ ZSH-configuratie  .zshrc

#import <Cocoa/Cocoa.h>

#import "AppViewController.h"

int main(int argc, const char* argv[])
{
  NSApplication* application = [NSApplication sharedApplication];

  ApplicationController* applicationController = [[ApplicationController alloc] init];

  application.delegate = applicationController;

  return (NSApplicationMain(argc, argv));
}

À partir de ce fichier tu peux déjàFrom this file you can already
Met dit bestand kun je
Créer et personnaliser le menu de ton application à droite du menu PommeCreate and customize your application's menu, to the right of the Apple menu,
Het menu van je app rechts van het Apple-menu al aanmaken en aanpassen
Grâce à NSMenu, NSMenuItem, NSSlider, …Using NSMenu, NSMenuItem, NSSlider, …
Met behulp van NSMenu, NSMenuItem, NSSlider, …

main.m — les autres tu les appelles comme tu veuxname the others however you like
de andere noem je zoals je wilt

Il n'existe pas de fichier header pour le fichier main.There is no header file for a main file.
Er is geen header-bestand voor het bestand main.
Peu importe le langage utilisé.It doesn’t matter what language is used.
Het maakt niet uit welke taal wordt gebruikt.
Aucun autre fichier n'en a besoin.No other file needs one.
Geen enkel ander bestand heeft dit nodig.

La fenêtre, la vue Metal et notamment les entrées claviers/souris passent parThe window, the Metal view, and in particular keyboard and mouse input go through
Het venster, de Metal-view en vooral de toetsenbord- en muisinvoer verlopen via
AppKit — le framework UI de macOS, écrit en Objective-C.— the macOS UI framework, written in Objective-C.
— het UI-framework van macOS, geschreven in Objective-C.
On ne peut pas y échapper.There is no escaping it.
Daar kun je niet omheen.

Mais on limite le contact aux fichiers .mm qui font le pont entre l'Obj-C et notre code C++ pur.But we confine it to the .mm files, which bridge Obj-C and our pure C++ code.
Maar we beperken het contact tot de .mm-bestanden, die de brug slaan tussen Obj-C en onze pure C++-code.

Le principe du pontHow the bridge works:
Het principe van de brug
Objective-C ↔ C++

AppViewController.mm gère uniquement la fenêtre et les callbacks système.AppViewController.mm handles only the window and the system callbacks.
AppViewController.mm beheert alleen het venster en de systeemcallbacks.

Il instancie notre rendu C++ et lui passe le pointeur vers notre GPU MTL::Device.It instantiates our C++ renderer and hands it the pointer to our GPU, MTL::Device.
Het maakt onze C++-renderer aan en geeft hem de pointer naar onze GPU, MTL::Device.

Un point rapide sur les éléments utiles à notre projet ;A quick look at the pieces our project needs:
Even de onderdelen overlopen die ons project nodig heeft:

  1. Cocoa.h → framework Cocoa (sans wrapper C++)the Cocoa framework (no C++ wrapper)
    het Cocoa-framework (zonder C++-wrapper)
    → il prend directement le code en Obj-C de ton OS,it pulls in your OS's Obj-C code directly
    het haalt rechtstreeks de Obj-C-code van je OS binnen

    et permet notamment d'utiliser l'objet/classe NSApplicationand lets you use the NSApplication object/class
    en laat je onder meer het object/de klasse NSApplication gebruiken
    avec toutes ses propriétés, toutes ses méthodes et tous ses protocoles.with all its properties, methods, and protocols.
    met al zijn eigenschappen, methoden en protocollen.
  2. NSApplication → gère la boucle d'événement principale de toute applicationruns the main event loop of every application
    beheert de hoofd-eventloop van elke applicatie
    et conserve une liste de tous les objets NSWindowand keeps a list of all NSWindow objects
    en houdt een lijst bij van alle NSWindow-objecten

    pour distribuer les événements aux objets NSResponder appropriésto dispatch events to the right NSResponder objects
    om events naar de juiste NSResponder-objecten te sturen
    sauf si la touche Commande est enfoncée lorsqu'un événement de frappe se produit.except when the Command key is held down during a key event.
    behalve als de Command-toets ingedrukt is tijdens een toetsaanslag.
  3. sharedApplication → méthode (fonction associée à une classe) NSApplicationan NSApplication method (a function tied to a class)
    een methode van NSApplication (een functie die bij een klasse hoort)
    qui initialise l'environnement d'affichage et connecte notre programme au serveur de fenêtres.that sets up the display environment and connects our program to the window server.
    die de weergaveomgeving initialiseert en ons programma met de windowserver verbindt.

    Elle crée l'instance unique au premier appel, puis renvoie toujours la même :It creates the single instance on the first call, then always returns that same one:
    Ze maakt de enige instantie aan bij de eerste aanroep en geeft daarna altijd dezelfde terug:
    on récupère ici un pointeur vers l'application, que l'on nomme application.here we get a pointer to the application, which we name application.
    hier krijgen we een pointer naar de applicatie, die we application noemen.
  4. ApplicationController → alloue (allocate) de la mémoire pour ton objet Objective-C++ et l'initialise.allocates memory for your Objective-C++ object and initializes it.
    reserveert (allocate) geheugen voor je Objective-C++-object en initialiseert het.
    C'est notre classe écrite en Objective-C++.It is our class, written in Objective-C++.
    Het is onze klasse, geschreven in Objective-C++.
  5. .delegate = …; → propriété de NSApplicationan NSApplication property
    een eigenschap van NSApplication
    → notre objet devient le délégué de la boucle/de l'application. (setter).our object becomes the delegate of the loop/application (setter).
    ons object wordt de delegate van de loop/applicatie (setter).

    De cette manière, notre application reçoit directement les NSNotification et nous pouvons les gérer dans notre classeThis way, our application receives NSNotifications directly and we can handle them in our class
    Zo ontvangt onze applicatie de NSNotifications rechtstreeks en kunnen we ze in onze klasse afhandelen

    — et comme elle est écrite en Obj-C++, elle nous ouvre la porte du— and since it is written in Obj-C++, it opens the door to
    — en omdat ze in Obj-C++ geschreven is, opent ze de deur naar
    C++ !.
    Attention : NSApplication.delegate est une référence weak.Careful: NSApplication.delegate is a weak reference.
    Opgelet: NSApplication.delegate is een weak referentie.

    C'est la variable locale applicationController qui maintient l'objet en vieThe local variable applicationController is what keeps the object alive
    De lokale variabele applicationController houdt het object in leven
    — ce qui suffit ici, puisque la fonction ne se termine jamais.— which is enough here, since the function never returns.
    — wat hier volstaat, want de functie eindigt nooit.
  6. NSApplicationMain → fonction main() de l'application, elle démarre la boucle,the application's main() function: it starts the loop,
    de main()-functie van de applicatie: ze start de loop,
    un peu comme ton système d'exploitation pour afficher constamment à l'écran, c'est là que la magie opèrea bit like your operating system keeping the screen drawn — this is where the magic happens
    een beetje zoals je besturingssysteem dat het scherm voortdurend tekent — hier gebeurt de magie

    - On passe de rien à une application fonctionnelle,- We go from nothing to a working application,
    - We gaan van niets naar een werkende applicatie,
    on va pouvoir interagir avec l'ordinateur autrement que par le terminal,able to interact with the computer other than through the terminal.
    waarmee we anders dan via de terminal met de computer werken.

    contrairement au C & C++, cette fonction ne renvoie rien, elle s'arrête lorsque l'on interrompt la boucle.Unlike in C & C++, this function never returns: it stops when the loop is interrupted.
    Anders dan in C & C++ geeft deze functie niets terug: ze stopt wanneer de loop onderbroken wordt.
    Tout comme ton système d'exploitation (en partie).Just like your operating system (in part).
    Net zoals je besturingssysteem (gedeeltelijk).
  7. argc / argv → identique au C et autres,same as in C and other languages;
    hetzelfde als in C en andere talen;
    pour notre part, l'application se lancera sans prendre d'entrée (fichier image, argument texte, …) et affichera nos rendus.in our case, the application launches without any input (image file, text argument, …) and displays our renders.
    bij ons start de applicatie zonder invoer (afbeelding, tekstargument, …) en toont ze onze renders.

    (argument count = 1) : le chemin de l'exécutable est toujours passé en premier argument.(argument count = 1): the executable's path is always passed as the first argument.
    (argument count = 1): het pad van het uitvoerbare bestand wordt altijd als eerste argument doorgegeven.
    Aperçu dans le chapitre concernant la vitamine-C.A preview in the vitamin-C chapter.
    Een voorproefje in het hoofdstuk over vitamine C.
Command Directory ou directement dans tes WrappersCommand Directory, or straight in your wrappers
Command Directory, of rechtstreeks in je wrappers

Où explorer les fonctionnalités existantes de chaque objet des frameworks AppleWhere to explore what each Apple framework object can do
Waar je ontdekt wat elk object uit de Apple-frameworks kan

- directement dans les headers Obj-C (souvent commentés par Apple)- directly in the Obj-C headers (often commented by Apple)
- rechtstreeks in de Obj-C-headers (vaak door Apple becommentarieerd)

- ou click-droit dans Xcode sur l’élément.- or right-click the element in Xcode.
- of klik in Xcode met de rechtermuisknop op het element.

C'est ici que ton include #import <Cocoa/Cocoa.h> va chercher le code Obj-C :This is where your #import <Cocoa/Cocoa.h> include fetches the Obj-C code:
Hier haalt je include #import <Cocoa/Cocoa.h> de Obj-C-code op:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks

Structure des fichiersFile structure
Bestandsstructuur

Une fois sur le projet, tu peux le réorganiser de cette manière :Once in the project, you can reorganize it like this:
Eenmaal in het project kun je het zo herschikken:

MSLearn/ ├── Frameworks/ # headers officiels Apple │ ├── metal-cpp/ │ └── metal-cpp-extensions/ ├── MSLearn.entitlements # optionnel ├── Application/ # sources Objective-C / Objective-C++ │ ├── main.m │ ├── AppViewController.h │ ├── AppViewController.mm │ └── macOS/ │ └── macOSInfo.plist ├── Renderer/ # logique de rendu + headers .hpp │ ├── Renderer.cpp │ └── Renderer.hpp ├── Shaders/ # shaders │ └── Fullscreen.metal # fichier MSL ├── includes/ # headers .h (C++ / MSL) │ └── SharedGPU/ # des fichiers partagés entre les langages C++ & MSL │ └── Renderer_shared.h ├── .gitignore # du chapitre précédent, fichier caché └── Makefile

En suivant la même structure, tu ne rencontreras aucun problème d'includes.Follow the same structure and you won't run into any include problems.
Volg dezelfde structuur en je krijgt geen problemen met includes.

Xcode voit tous les fichiers, Makefile doit indiquer où ils se trouvent.Xcode sees every file; the Makefile has to say where they are.
Xcode ziet alle bestanden; de Makefile moet aangeven waar ze staan.

Fichier .entitlementsThe .entitlements file
Het .entitlements-bestand

Paires clé-valeur (en XML, comme le .plist)Key-value pairs (in XML, like the .plist)
Sleutel-waardeparen (in XML, net als de .plist)

qui accordent à ton exécutable le droit d'utiliser un service ou une technologie protégée par le système :that grant your executable the right to use a service or technology protected by the system:
die je uitvoerbare bestand het recht geven een door het systeem beschermde dienst of technologie te gebruiken:

iCloud, notifications push, Game Center, réseau, accès aux fichiers, etc.iCloud, push notifications, Game Center, networking, file access, and so on.
iCloud, pushmeldingen, Game Center, netwerk, bestandstoegang, enz.

La différence : le .plist décrit ton application (nom, version, icône, …),The difference: the .plist describes your application (name, version, icon, …);
Het verschil: de .plist beschrijft je applicatie (naam, versie, icoon, …),
le .entitlements lui donne des permissions.the .entitlements grants it permissions.
de .entitlements geeft haar rechten.

Il n'est pas copié tel quel dans le bundle : il est gravé dans la signature de l'exécutable par codesign.It is not copied as-is into the bundle: codesign embeds it in the signature of the executable.
Het wordt niet zomaar in de bundel gekopieerd: codesign brandt het in de handtekening van het uitvoerbare bestand.

Résultat, impossible de le modifier après coup sans casser la signature,As a result, you can't change it afterwards without breaking the signature,
Gevolg: je kunt het achteraf niet wijzigen zonder de handtekening te breken,
et c'est le système (le noyau) qui le vérifie au lancement.and the system (the kernel) checks it at launch.
en het systeem (de kernel) controleert het bij het opstarten.

Quand entre-t-il en jeu ? Dès la signature.When does it come into play? As soon as you sign.
Wanneer speelt het een rol? Vanaf het ondertekenen.
Il devient indispensable dès que :It becomes essential as soon as:
Het wordt onmisbaar zodra:

— tu publies sur le Mac App Store :you publish on the Mac App Store:
je publiceert in de Mac App Store:
l'App Sandbox (com.apple.security.app-sandbox) y est obligatoire.the App Sandbox (com.apple.security.app-sandbox) is mandatory there.
de App Sandbox (com.apple.security.app-sandbox) is daar verplicht.

— ton application est sandboxée et doit sortir de sa « boîte » (réseau, dossiers de l'utilisateur, caméra, …).your application is sandboxed and needs to reach outside its “box” (network, user folders, camera, …).
je applicatie gesandboxed is en buiten haar “doos” moet (netwerk, gebruikersmappen, camera, …).

— tu utilises un service Apple (iCloud/CloudKit, push, Game Center, App Groups).you use an Apple service (iCloud/CloudKit, push, Game Center, App Groups).
je een Apple-dienst gebruikt (iCloud/CloudKit, push, Game Center, App Groups).

Ces droits-là doivent aussi être autorisés par ton provisioning profile,Those rights must also be allowed by your provisioning profile,
Die rechten moeten ook door je provisioning profile toegestaan zijn,
sinon le système refuse de lancer l'application.otherwise the system refuses to launch the application.
anders weigert het systeem de applicatie te starten.

— tu distribues hors App Store avec le Hardened Runtime (nécessaire pour la notarisation)you distribute outside the App Store with the Hardened Runtime (required for notarization)
je buiten de App Store verspreidt met de Hardened Runtime (nodig voor notarisatie)

et qu'il te faut une exception (ex. com.apple.security.cs.allow-jit).and you need an exception (e.g. com.apple.security.cs.allow-jit).
en je een uitzondering nodig hebt (bv. com.apple.security.cs.allow-jit).

Pour notre application Metal, qui tourne en local sans service ni sandbox, il est donc optionnel.For our Metal application, which runs locally with no service and no sandbox, it is therefore optional.
Voor onze Metal-applicatie, die lokaal draait zonder diensten of sandbox, is het dus optioneel.

Exemple tiré deAn example from
Een voorbeeld uit
GlossDev, notre application Swift qui utilise plusieurs services :, our Swift application that uses several services:
, onze Swift-applicatie die verschillende diensten gebruikt:

<dict>
  <key>aps-environment</key>                       <!-- notifications push -->
  <string>development</string>                     <!-- "production" une fois distribuée -->
  <key>com.apple.developer.game-center</key>       <!-- Game Center -->
  <true/>
  <key>com.apple.developer.icloud-services</key>   <!-- iCloud via CloudKit -->
  <array>
    <string>CloudKit</string>
  </array>
  <key>com.apple.security.application-groups</key> <!-- données partagées avec un widget -->
  <array>                                                              <!-- ou une extension -->
    <string>group.dev.learnmsl.glossdev</string>
  </array>
</dict>

Avec Xcode, l'onglet Signing & Capabilities remplit ce fichier pour toi.With Xcode, the Signing & Capabilities tab fills in this file for you.
Met Xcode vult het tabblad Signing & Capabilities dit bestand voor je in.

Avec un Makefile, tu le passes à la signature :With a Makefile, you pass it at signing time:
Met een Makefile geef je het mee bij het ondertekenen:
codesign --force --options runtime --entitlements MSLearn.entitlements --sign "Developer ID Application: …" MSLearn.app, et tu vérifies le résultat avec, and you check the result with
, en je controleert het resultaat met
codesign -d --entitlements - MSLearn.app.
Les règles make sign, make notarize et make appstore duThe make sign, make notarize, and make appstore rules in the
De regels make sign, make notarize en make appstore uit de
↘ Makefile enchaînent tout ça pour toi.chain all of that for you.
doen dat allemaal na elkaar voor je.

Cependant, c'est la seule chose que notre Makefile ne contient pas,However, it is the only thing our Makefile doesn't contain:
Toch is dit het enige wat onze Makefile niet bevat:

il est beaucoup plus facile de créer ton archive via Xcode avant de l'envoyer pour vérification.it is much easier to create your archive through Xcode before sending it for review.
het is veel makkelijker om je archief via Xcode te maken voordat je het ter controle opstuurt.

La migration de la méthode utilisant Make jusqu'à Xcode est relativement simple.Migrating from the Make approach to Xcode is fairly simple.
De overstap van de Make-aanpak naar Xcode is vrij eenvoudig.

Un fichier exemple de fichier macOSInfo.plistAn example macOSInfo.plist file
Een voorbeeldbestand macOSInfo.plist

→ Tu as peut-être dû supprimer le fichier Storyboard généré par Xcode ainsi que l'appel de celui-ci.→ You may have had to delete the Storyboard file generated by Xcode, along with its reference.
→ Misschien moest je het door Xcode gegenereerde Storyboard-bestand en de verwijzing ernaar verwijderen.

Cette liste (voir photo) correspond au fichier .plist que nous allons rédiger manuellement,This list (see picture) matches the .plist file we are going to write by hand,
Deze lijst (zie foto) komt overeen met het .plist-bestand dat we met de hand schrijven,
écrit en XML (langage de balisage).in XML (a markup language).
in XML (een opmaaktaal).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleDevelopmentRegion</key>
  <string>$(DEVELOPMENT_LANGUAGE)</string>
  <key>CFBundleExecutable</key>
  <string>$(EXECUTABLE_NAME)</string>
  <key>CFBundleIdentifier</key>
  <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
  <key>CFBundleInfoDictionaryVersion</key>
  <string>6.0</string>
  <key>CFBundleName</key>
  <string>$(PRODUCT_NAME)</string>
  <key>CFBundleShortVersionString</key>
  <string>$(MARKETING_VERSION)</string>
  <key>CFBundleSupportedPlatforms</key>
  <array>
      <string>MacOSX</string>
  </array>
  <key>CFBundleVersion</key>
  <string>$(CURRENT_PROJECT_VERSION)</string>
  <key>GCSupportsControllerUserInteraction</key>
  <true/>
  <key>LSApplicationCategoryType</key>
  <string>public.app-category.graphics-design</string>
  <key>LSMinimumSystemVersion</key>
  <string>27.2</string>
  <key>MetalCaptureEnabled</key>
  <true/>
  <key>NSHumanReadableCopyright</key>
  <string>Copyright © 2026 Rémy Gralinger. All rights reserved.</string>
  <key>CFBundleIconFile</key>
  <string>AppIcon.icns</string>
  <key>NSPrincipalClass</key>
  <string>NSApplication</string>
  <key>CFBundlePackageType</key>
  <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
  <key>CFBundleDisplayName</key>
  <string>MSLearn</string>
</dict>
</plist>
NSPrincipalClass est obligatoireis mandatory
is verplicht

Sans storyboard ni nib principal, c'est cette clé qui indique à macOS quelle classe instancier au lancement.Without a storyboard or main nib, this key tells macOS which class to instantiate at launch.
Zonder storyboard of hoofd-nib vertelt deze sleutel macOS welke klasse het bij het opstarten moet aanmaken.

Si tu l'oublies, l'application se lance sans jamais afficher de fenêtre.If you forget it, the application launches without ever showing a window.
Vergeet je ze, dan start de applicatie zonder ooit een venster te tonen.

Si tu utilises le Makefile, les variables $() du .plist ne sont pas connues par celui-ci,If you use the Makefile, it doesn't know the .plist's $() variables:
Gebruik je de Makefile, dan kent die de $()-variabelen van de .plist niet:

remplace simplement les valeurs par une chaîne de caractères comme suit :simply replace the values with a string, as follows:
vervang de waarden gewoon door een tekenreeks, zoals hieronder:

XML
<key>CFBundleExecutable</key>
<string>MSLearn</string>
Autres fichiersOther files
Andere bestanden

Pour l'instant nous n'utiliserons pas de Storyboard (.storyboard)For now we won't use a Storyboard (.storyboard)
Voorlopig gebruiken we geen Storyboard (.storyboard)

Le fichier .entitlements, tu peux le garder.You can keep the .entitlements file.
Het .entitlements-bestand mag je houden.

Configuration de l'applicationConfiguring the Application
De applicatie configureren

Celle-ci est actuellement vide, on déclare alors ce dont on a besoin et ce qui est nécessaire.It is currently empty, so we declare what we need.
Ze is momenteel leeg, dus we declareren wat we nodig hebben.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                        +       +          */
/*      File: AppViewController.h            +++     +++     */
/*                                        +       +          */
/*      By: Laboitederemdal                +       +         */
/*                                       +           +       */
/*      Created: 16/04/2026 04:59:56      + + + + + +        */
/*      Updated: 12/10/2026                                  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#import <MetalKit/MetalKit.h> // MTKView / MTKViewDelegate

@interface ApplicationController : NSObject <NSApplicationDelegate, NSWindowDelegate, MTKViewDelegate>

@property (nonatomic, strong, readonly) MTKView* _Nonnull mtkView;
// se terminera
- (void)applicationWillTerminate:(NSNotification* _Nonnull)notification;
// a terminé son lancement
- (void)applicationDidFinishLaunching:(NSNotification* _Nonnull)notification;
// doit se terminer après la fermeture de la dernière fenêtre
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication* _Nonnull)sender;

- (void)drawInMTKView:(MTKView* _Nonnull)view;

- (void)mtkView:(MTKView* _Nonnull)view drawableSizeWillChange:(CGSize)size;

@end

Un nouveau point rapide :Another quick look:
Nog een snel overzicht:

  1. NSApplicationDelegate / NSWindowDelegate → protocole (signatures de méthodes publiques).protocol (public method signatures).
    protocol (publieke methodesignaturen).

    Il s'agit donc d'un ensemble de méthodes accessibles depuis l'extérieur d'une classe,In other words, a set of methods reachable from outside a class,
    Het is dus een verzameling methoden die van buiten een klasse bereikbaar zijn,
    par lesquelles on peut agir sur un objet, ou plus généralement communiquer avec lui.through which you can act on an object or, more generally, communicate with it.
    waarmee je op een object inwerkt of, algemener, ermee communiceert.
  2. NSNotification → classe appartenant à Foundationa Foundation class
    een klasse uit Foundation
    → communication entre l'OS et notre app.communication between the OS and our app.
    communicatie tussen het OS en onze app.
  3. NSObject → classe racine de la plupart des hiérarchies Objective-C,the root class of most Objective-C hierarchies,
    de basisklasse van de meeste Objective-C-hiërarchieën,

    à partir de laquelle les sous-classes héritent d'une interface de base au système d'exécutionfrom which subclasses inherit a basic interface to the runtime system
    waarvan subklassen een basisinterface naar het runtimesysteem erven
    et de la capacité de se comporter comme des objets Objective-C.and the ability to behave as Objective-C objects.
    en het vermogen om zich als Objective-C-objecten te gedragen.
  4. Prototypes des méthodesPrototypes of the
    Prototypes van de methoden
    application…
    → méthodes de cycle de vie AppKit.AppKit lifecycle methods.
    levenscyclusmethoden van AppKit.

    Les redéclarer ici n'est pas obligatoire (les protocoles les fournissent déjà),Redeclaring them here isn't required (the protocols already provide them),
    Ze hier opnieuw declareren is niet verplicht (de protocollen leveren ze al),
    mais ça rend le contrat public de ApplicationController explicite :but it makes ApplicationController's public contract explicit:
    maar het maakt het publieke contract van ApplicationController expliciet:

    main.m importe ce header et en crée une instance.main.m imports this header and creates an instance.
    main.m importeert deze header en maakt er een instantie van.
    Le compilateur vérifie que tu respectes ce contrat et les protocoles adoptés.The compiler checks that you honor this contract and the adopted protocols.
    De compiler controleert of je dit contract en de gekozen protocollen naleeft.
  5. draw() → "ton terrain de jeu", on va dessiner ici après avoir nous aussi créé des fonctions et shaders."your playground": this is where we'll draw, once we've written our own functions and shaders.
    "je speeltuin": hier tekenen we, zodra we zelf functies en shaders geschreven hebben.
  6. drawableSizeWillChange → appelée à chaque fois que la taille du drawable change.called every time the drawable's size changes.
    aangeroepen telkens de grootte van de drawable verandert.
  7. MTKViewDelegate → protocole qui fournit drawInMTKView & drawableSizeWillChange pour une MTKViewprotocol that provides drawInMTKView & drawableSizeWillChange for an MTKView
    protocol dat drawInMTKView & drawableSizeWillChange levert voor een MTKView
    (MTK::View côté C++).(MTK::View on the C++ side).
    (MTK::View aan de C++-kant).

Sur ce site, tu verras également comment mettre en place l'autre manière d'utiliser MetalOn this site, you will also see how to set up the other way of using Metal
Op deze site zie je ook hoe je Metal op de andere manier gebruikt
— via un CAMetalLayer (Core Animation Layer) — qui demande davantage de configuration.— through a CAMetalLayer (Core Animation Layer) — which takes more configuration.
— via een CAMetalLayer (Core Animation Layer) — wat meer configuratie vraagt.

La principale différence entre Cocoa et AppKit tient au fait queThe main difference between Cocoa and AppKit is that
Het grootste verschil tussen Cocoa en AppKit is dat
Cocoa est un framework d'application complet (un parapluie),Cocoa is a complete application framework (an umbrella),
Cocoa een volledig applicatieframework is (een paraplu),

tandis qu'AppKit en est la sous-partie spécialisée dans l'interface utilisateur sur macOS.while AppKit is its part dedicated to the user interface on macOS.
terwijl AppKit het deel is dat zich op de gebruikersinterface van macOS richt.

MetalKit.h importe AppKit en entier ;MetalKit.h imports all of AppKit;
MetalKit.h importeert AppKit volledig;
MetalKit.hpp importe AppKit.hpp.MetalKit.hpp imports AppKit.hpp.
MetalKit.hpp importeert AppKit.hpp.

Le préfixe NS vient de NeXTSTEP :The NS prefix comes from NeXTSTEP:
Het voorvoegsel NS komt van NeXTSTEP:

on le retrouve aussi bien dans Foundation (NSString, NSArray, NSNotification)you find it in Foundation (NSString, NSArray, NSNotification)
je vindt het zowel in Foundation (NSString, NSArray, NSNotification)
que dans AppKit (NSWindow, NSView, NSApplication).as well as in AppKit (NSWindow, NSView, NSApplication).
als in AppKit (NSWindow, NSView, NSApplication).

Ce n'est donc pas un marqueur de framework.So it doesn't tell you which framework a class belongs to.
Het zegt dus niet tot welk framework iets behoort.

AppKit.hpp n'expose qu'une petite fraction de AppKit.h :AppKit.hpp exposes only a small fraction of AppKit.h:
AppKit.hpp stelt maar een klein deel van AppKit.h beschikbaar:
le strict nécessaire pour créer une fenêtre et une vue.just what it takes to create a window and a view.
het strikt nodige om een venster en een view te maken.

Ce n'est pas une limitation — ce qui manque, on l'écrit dans notre fichier .mm.It isn't a limitation — whatever is missing, we write in our .mm file.
Dat is geen beperking — wat ontbreekt, schrijven we in ons .mm-bestand.

L'implémentationThe Implementation
De implementatie

Il a été décidé de créer une fonction pour créer la fenêtre et une autre pour créer la vueWe chose to write one function to create the window and another to create the view,
We kozen voor één functie om het venster te maken en een andere voor de view,

en supplément des fonctionnalités fournies par l'API et l'OS.on top of the features provided by the API and the OS.
bovenop de functies die de API en het OS leveren.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                        +       +          */
/*      File: AppViewController.mm            +++     +++    */
/*                                        +       +          */
/*      By: Laboitederemdal                +       +         */
/*                                       +           +       */
/*      Created: 16/04/2026 05:43:06      + + + + + +        */
/*      Updated: 12/10/2026                                  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#import "../Renderer/Renderer.hpp"

#import "AppViewController.h"

#pragma mark - RenderWindow                                 // Ignoré par le compilateur
#pragma region RenderWindow {                               // indication visuelle

@interface RenderWindow : NSWindow                          // Déclaration de notre classe Obj-C

@property (weak) ApplicationController* appCoordinator;     // Un pointeur vers notre classe Obj-C++
                                                            // observe son propriétaire → weak
@end

@implementation RenderWindow                                // Implémentation de notre classe Obj-C
{
}

- (instancetype)initWithContentRect:(NSRect)rect
                          styleMask:(NSWindowStyleMask)mask // Paramètres de la fonction (NSRect inclus)
                            backing:(NSBackingStoreType)backing
                              defer:(BOOL)flag
                             screen:(NSScreen*)screen
{
  self = [super initWithContentRect:rect styleMask:mask backing:backing defer:flag screen:screen];
  return self;
}

@end

#pragma endregion RenderWindow }

#pragma mark - ApplicationController
#pragma region ApplicationController {

@implementation ApplicationController
{
  RenderWindow*             _window;      // possède RenderWindow → strong
  std::unique_ptr<Renderer> m_renderer;    // Notre classe C++
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender
{
  return (YES);
}

- (void)applicationDidFinishLaunching:(NSNotification*)notification
{
  [self createWindow];                      // des fonctions à nous, qui sont appelées
  [self createView];
}

- (void)applicationWillTerminate:(NSNotification*)notification
{
  m_renderer.reset();                        // Détruit (release) "std::unique_ptr"
}

- (void)createWindow
{
  NSWindowStyleMask mask = NSWindowStyleMaskClosable | NSWindowStyleMaskTitled |
                              NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
  NSRect contentRect = NSMakeRect(0, 0, 1280, 720);
  NSScreen* screen = [NSScreen mainScreen];
  contentRect.origin.x = 0;
  contentRect.origin.y = (screen.frame.size.height / 2) - (contentRect.size.height / 2);
  _window = [[RenderWindow alloc] initWithContentRect:contentRect styleMask:mask
                                              backing:NSBackingStoreBuffered defer:NO screen:screen];
  _window.releasedWhenClosed = NO;
  _window.minSize = NSMakeSize(640, 360);
  _window.delegate = self;
  _window.appCoordinator = self;
  screen = _window.screen;
  NSString* title = [NSString stringWithFormat:@"LearnMSL.dev : MSL x C++ (%@ @ %ldHz, EDR max: %.2f)",
                     screen.localizedName, (long)screen.maximumFramesPerSecond,
                     screen.maximumPotentialExtendedDynamicRangeColorComponentValue];
  _window.title = title;
  [_window makeKeyAndOrderFront:_window];
  [_window setIsVisible:YES];
  [_window makeMainWindow];
}

- (void)createView
{
  id<MTLDevice> device = MTLCreateSystemDefaultDevice();
  _mtkView = [[MTKView alloc] initWithFrame:_window.contentLayoutRect device:device];
  _mtkView.preferredFramesPerSecond = 120;
  _mtkView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
  _mtkView.colorPixelFormat = MTLPixelFormatRGBA16Float;
  _mtkView.depthStencilPixelFormat = MTLPixelFormatDepth32Float;
  _mtkView.colorspace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearDisplayP3);
  _mtkView.framebufferOnly = YES;
  _mtkView.paused = NO;
  _mtkView.delegate = self;
  _mtkView.enableSetNeedsDisplay = NO;
  NSTrackingArea* trackingArea = [[NSTrackingArea alloc]
                                  initWithRect:_mtkView.bounds
                                  options:(NSTrackingMouseMoved | NSTrackingActiveInKeyWindow |
                                           NSTrackingInVisibleRect | NSTrackingActiveAlways)
                                  owner:self userInfo:nil];
  [_mtkView addTrackingArea:trackingArea];
  NSScreen* screen = _window.screen ?: [NSScreen mainScreen];
  CGFloat scale = screen.backingScaleFactor ?: 1.0;
  CGSize sizePts = _mtkView.bounds.size;
  _mtkView.drawableSize = CGSizeMake(sizePts.width * scale, sizePts.height * scale);
  _window.contentView = _mtkView;
  m_renderer = std::make_unique<Renderer>((__bridge MTL::Device *)_mtkView.device,
                                         NSBundle.mainBundle.resourcePath.UTF8String,
                                         (NS::UInteger)_mtkView.drawableSize.width,
                                         (NS::UInteger)_mtkView.drawableSize.height,
                                         (MTL::PixelFormat)_mtkView.colorPixelFormat,
                                         (MTL::PixelFormat)_mtkView.depthStencilPixelFormat);
}

- (void)drawInMTKView:(nonnull MTKView *)view
{
  m_renderer->draw((__bridge MTK::View *)view, CACurrentMediaTime());
}

- (void)mouseMoved:(NSEvent *)event
{
}

- (void)mtkView:(MTKView *)view drawableSizeWillChange:(CGSize)size
{
  m_renderer->resizeViewWindow((NS::UInteger)size.width, (NS::UInteger)size.height);
}

@end

#pragma endregion ApplicationController }

Pour mieux comprendre les fonctions "obligatoires" de chaque protocole à mettre en placeTo better understand each protocol's "required" functions
Om de "verplichte" functies van elk protocol beter te begrijpen
↘ Objective-C++ vs C++ : syntaxe & documentation.
(Tu y arriveras dans quelques chapitres.)(You'll get there in a few chapters.)
(Daar kom je binnen een paar hoofdstukken.)

Un nouveau point rapide :Another quick look:
Nog een snel overzicht:

  1. applicationShouldTerminateAfterLastWindowClosed → le protocole qui renvoie si oui (YES) ou non (NO) l'application doit être fermée.the protocol method that returns whether (YES) or not (NO) the application should quit.
    de protocolmethode die teruggeeft of de applicatie moet stoppen (YES) of niet (NO).
  2. applicationDidFinishLaunching → méthode de délégué appelée une fois le lancement terminé.delegate method called once launching is done.
    delegatemethode die aangeroepen wordt zodra het opstarten klaar is.
    C'est le bon endroit pour créer la fenêtre et la vue.It's the right place to create the window and the view.
    Dit is de juiste plek om het venster en de view te maken.
  3. applicationWillTerminate → appelée juste avant la fermeture.called right before quitting.
    aangeroepen vlak voor het afsluiten.
    On y libère le renderer, avant que le processus ne disparaisse.We release the renderer there, before the process goes away.
    Hier geven we de renderer vrij, voordat het proces verdwijnt.
  4. MTLCreateSystemDefaultDevice() → fonction (pas un protocole) qui renvoie le GPU par défaut du système.a function (not a protocol) that returns the system's default GPU.
    een functie (geen protocol) die de standaard-GPU van het systeem teruggeeft.

    Sur les anciens Macs Intel à double GPU, l'appel provoquait le basculement vers le GPU haute performance ;On older dual-GPU Intel Macs, the call switched to the high-performance GPU;
    Op oudere Intel-Macs met twee GPU's schakelde de aanroep over naar de krachtige GPU;

    sur Apple Silicon il n'y a qu'un seul GPU, donc pas d'ambiguïté.on Apple Silicon there is only one GPU, so there is no ambiguity.
    op Apple Silicon is er maar één GPU, dus geen twijfel.
  5. __bridge → (~cast) liaison de pointeurs entre objets Objective-C et objets Core Foundation (toll-free bridging),(~cast) links pointers between Objective-C objects and Core Foundation objects (toll-free bridging),
    (~cast) koppelt pointers tussen Objective-C-objecten en Core Foundation-objecten (toll-free bridging),

    sans transfert de propriété : le compilateur ne touche pas au compteur de références.without transferring ownership: the compiler leaves the reference count alone.
    zonder eigendom over te dragen: de compiler raakt de reference count niet aan.

    C'est exactement ce qu'il nous faut pour passer une MTKView ou un MTLDevice à metal-cpp.It's exactly what we need to hand an MTKView or an MTLDevice to metal-cpp.
    Precies wat we nodig hebben om een MTKView of een MTLDevice aan metal-cpp door te geven.
  6. mouseMoved() → puisque NSTrackingMouseMoved est activé,since NSTrackingMouseMoved is enabled,
    omdat NSTrackingMouseMoved ingeschakeld is,
    la méthode doit exister dans notre classe pour éviter une erreur de selector à l'exécution.the method must exist in our class to avoid a selector error at runtime.
    moet de methode in onze klasse bestaan, anders krijg je bij het uitvoeren een selector-fout.
  7. NSTrackingArea → les options « actives » sont exclusives : on en choisit une seule (NSTrackingActiveInKeyWindow ici).the “active” options are mutually exclusive: pick only one (NSTrackingActiveInKeyWindow here).
    de “actieve” opties sluiten elkaar uit: je kiest er maar één (NSTrackingActiveInKeyWindow hier).

    Passer NSTrackingActiveAlways en plus est contradictoire.Adding NSTrackingActiveAlways on top is contradictory.
    Daarbovenop NSTrackingActiveAlways meegeven is tegenstrijdig.

Cycle de vieLifecycle
Levenscyclus

macOS · AppKit
           main.m ----- NSApplication → boucle d'events macOS
Objective-C · pont             | delegate
      ------------- ApplicationController → cycle de vie, resize
      | strong       |         |         | delegate
      |             |          |      MTKView → surface de dessin - EDR - 120 images par secondes
      |            | weak      |
RenderWindow - - -             | unique_pointeur
→ inputs                       |
C++ · Metal                    |
                            Renderer → draw - commandQueue
                               |
                          GPU · Metal → commandBuffer - drawable

Nous aurons besoin d'un pont Objective-C (le langage très utilisé par Apple et obligatoire pour notre projet)We will need an Objective-C bridge (the language Apple uses widely, and mandatory for our project)
We hebben een Objective-C-brug nodig (de taal die Apple veel gebruikt en die verplicht is voor ons project)

afin de gérer l'audio, les manettes de jeu, l'écran tactile, …to handle audio, game controllers, the touchscreen, …
om audio, gamecontrollers, het aanraakscherm, … af te handelen

N'hésite pas à personnaliser ta fenêtre.Feel free to customize your window.
Pas je venster gerust aan.
Par exemple, une ligne suffit pour la centrer :For example, one line is enough to center it:
Eén regel volstaat bijvoorbeeld om het te centreren:

// dans notre fonction createWindow() après l'allocation
[_window center];

Tu pourrais également lancer l'application en plein écran par défaut.You could also launch the application in full screen by default.
Je kunt de applicatie ook standaard in volledig scherm starten.

Nous l’avons placée au milieu à gauche.We placed it on the middle left.
We hebben het links in het midden gezet.
Quasiment tout est là pour configurer la fenêtre, ce qui n'est pas expliqué ici le sera après.Almost everything needed to configure the window is here; what isn't explained now will be later.
Bijna alles om het venster te configureren staat hier; wat nu niet uitgelegd wordt, komt later.

De cette manière tu peux déjà ouvrir une fenêtre — une application !This way you can already open a window — an application!
Zo kun je al een venster openen — een applicatie!

La classe RenderWindow (classe privée), définie entièrement dans AppViewController.mmThe RenderWindow class (a private class), defined entirely in AppViewController.mm,
De klasse RenderWindow (een private klasse), volledig gedefinieerd in AppViewController.mm,
n'a pas de header du tout, personne d'autre n'en a besoin.has no header at all: nobody else needs it.
heeft helemaal geen header: niemand anders heeft ze nodig.

Les méthodes d'input → pas de prototype ?Input methods → no prototype?
Invoermethoden → geen prototype?

Ce sont des overrides de NSResponder — elles existent déjà dans la superclasse NSWindow.They are NSResponder overrides — they already exist in the NSWindow superclass.
Het zijn overrides van NSResponder — ze bestaan al in de superklasse NSWindow.

Tu ne crées pas une nouvelle interface, tu écrases un comportement existant.You aren't creating a new interface, you are overriding existing behavior.
Je maakt geen nieuwe interface, je overschrijft bestaand gedrag.
Le compilateur n'a pas besoin qu'on lui redéclare ce qu'il connaît déjà.The compiler doesn't need you to redeclare what it already knows.
De compiler hoeft niet opnieuw te horen wat hij al kent.

Si tu compares avec les Wrappers C++, le principe est le même.Compared with the C++ wrappers, the principle is the same.
Vergeleken met de C++-wrappers is het principe hetzelfde.

Automatic Reference Counting

Code de gestion mémoire injecté par le compilateur à la compilation (retain/release),Memory-management code the compiler inserts at compile time (retain/release),
Geheugenbeheercode die de compiler bij het compileren invoegt (retain/release),
que tu aurais écrit à la main en MRC (Manual Reference Counting).which you would have written by hand with MRC (Manual Reference Counting).
die je met MRC (Manual Reference Counting) met de hand zou schrijven.

ApplicationController* controller = [[ApplicationController alloc] init];

// Ce que le compilateur ARC ajoute — alloc/init renvoie déjà +1,
// ARC n'ajoute donc pas de retain, seulement le release de fin de portée
ApplicationController* controller = [[ApplicationController alloc] init];  // +1
[controller retain];
…
[controller release];   // inséré automatiquement

Chaque objet Obj-C a un retain count interne :Every Obj-C object has an internal retain count:
Elk Obj-C-object heeft een interne retain count:

strong      +1 au retain count                  Propriétaire
weak        0, mis à nil si l'objet meurt       Delegate, référence inverse
assign      0, pas mis à nil (dangereux)        Types primitifs uniquement
copy        +1 sur une copie                    NSString, blocs

Nous verrons retain() qui compte automatiquement dans notre C++ (notamment le pointeur vers MTLDevice)We will see retain(), which counts automatically in our C++ (notably the pointer to MTLDevice)
We zien later retain(), dat in onze C++ automatisch telt (onder meer de pointer naar MTLDevice)

Retain cycle
A ──strong──▶ B     retain count A = 1 (tenu par B)
▲              │    retain count B = 1 (tenu par A)
└───strong─────┘    → jamais libérés, même si plus personne d'autre ne les référence

ApplicationController  ──strong───▶ RenderWindow
          ▲                              │
          └────────────────weak──────────┘

ARC ne concerne que le code Obj-C, ne t'en inquiète pas trop.ARC only concerns Obj-C code, so don't worry about it too much.
ARC gaat alleen over Obj-C-code, maak je er niet te veel zorgen over.

En MSL & C++ on gère manuellement la mémoire,In MSL & C++ we manage memory by hand,
In MSL & C++ beheren we het geheugen met de hand,
nous avons tout de même un RAII maison qui simule ARC.but we do have a home-made RAII that mimics ARC.
maar we hebben wel een zelfgemaakte RAII die ARC nabootst.

RAII

Resource Acquisition Is Initialization ou « l'acquisition de ressource est une initialisation » est un idiome de programmation, principalement utilisé en C++,Resource Acquisition Is Initialization is a programming idiom, mainly used in C++,
Resource Acquisition Is Initialization of “het verwerven van een resource is een initialisatie” is een programmeeridioom, vooral gebruikt in C++,

liant la gestion des ressources (mémoire, fichiers, mutex) à la durée de vie d'un objet.that ties resource management (memory, files, mutexes) to an object's lifetime.
dat het beheer van resources (geheugen, bestanden, mutexen) aan de levensduur van een object koppelt.

La ressource est acquise au constructeur et libérée automatiquement dans le destructeur, garantissant une libération sûre.The resource is acquired in the constructor and released automatically in the destructor, which guarantees a safe release.
De resource wordt in de constructor verworven en in de destructor automatisch vrijgegeven, wat een veilige vrijgave garandeert.

Le minimum en C++The Bare Minimum in C++
Het minimum in C++

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                        +       +          */
/*      File: Renderer.hpp            +++     +++            */
/*                                        +       +          */
/*      By: Laboitederemdal                +       +         */
/*                                       +           +       */
/*      Created: 16/04/2026 10:33:22      + + + + + +        */
/*      Updated: 12/10/2026                                  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#ifndef RENDERER_HPP
#define RENDERER_HPP

#include <string>                     // std::string (utilisé dans le constructeur)
#include <simd/simd.h>                // all simd
#include <iostream>                // pour afficher dans la console / DEBUG

#include <MetalKit/MetalKit.hpp>      // fichier C++ → wrapper C++

#include "FrameClock.hpp"

class Renderer
{
public:
  Renderer(MTL::Device* device,     // constructeur
           const std::string& resourcePath,
           NS::UInteger width, NS::UInteger height,
           MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat);
  ~Renderer();                      // destructeur

  void draw(MTK::View* view, double quartz); // heure Quartz (CACurrentMediaTime)
  void resizeViewWindow(NS::UInteger width, NS::UInteger height);

private:
  void update(const FrameTime& time);

  MTL::Device*                m_device;
  MTL::Library*               m_shaderLibrary;
  MTL::CommandQueue*          m_commandQueue;
  MTL::PixelFormat            m_pixelFormat;
  MTL::PixelFormat            m_depthPixelFormat;

  FrameClock m_clock; // le tempo commun : un seul delta
};

#endif /* RENDERER_HPP */

C'est presque terminé :Almost done:
Bijna klaar:

  1. Construction de notre classe principaleConstruction of our main class
    Constructie van onze hoofdklasse
    → elle reçoit la taille de la fenêtre, le chemin du dossier des assets externes,it receives the window size, the path to the external assets folder,
    ze krijgt de venstergrootte, het pad naar de map met externe assets,

    les formats de pixels dont on a besoin et le pointeur vers notre GPU.the pixel formats we need, and the pointer to our GPU.
    de pixelformaten die we nodig hebben en de pointer naar onze GPU.
  2. Library → les shaders compilés, dans le fichier .metallib.the compiled shaders, in the .metallib file.
    de gecompileerde shaders, in het .metallib-bestand.
  3. GPU → il alloue la mémoire sur la puce (un M2 Pro dans mon cas),it allocates memory on the chip (an M2 Pro in my case),
    het reserveert geheugen op de chip (een M2 Pro in mijn geval),

    lit les fonctions de vertex et de fragment shader écrites en MSL, détient la file de commandes, …reads the vertex and fragment shader functions written in MSL, owns the command queue, …
    leest de vertex- en fragmentshaderfuncties in MSL, bezit de command queue, …
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                        +       +          */
/*      File: Renderer.cpp            +++     +++            */
/*                                        +       +          */
/*      By: Laboitederemdal                +       +         */
/*                                       +           +       */
/*      Created: 16/04/2026 10:33:18      + + + + + +        */
/*      Updated: 12/10/2026                                  */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#define NS_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#define MTK_PRIVATE_IMPLEMENTATION

#include "Renderer.hpp"

Renderer::Renderer(MTL::Device* device,
                   const std::string& resourcePath,
                   NS::UInteger width, NS::UInteger height,
                   MTL::PixelFormat colorPixelFormat, MTL::PixelFormat depthPixelFormat)
: m_device(device->retain()),
m_shaderLibrary(m_device->newDefaultLibrary()),
m_commandQueue(m_device->newCommandQueue()),
m_pixelFormat(colorPixelFormat), m_depthPixelFormat(depthPixelFormat)
{
}

Renderer::~Renderer()
{ // Pointeurs, on libère les cases mémoire allouées.
  m_commandQueue->release();
  m_shaderLibrary->release();
  m_device->release();
}

void Renderer::update(const FrameTime& time)
{
  const float delta = time.delta; // le même pour tout le monde cette frame
}

void Renderer::draw(MTK::View* view, double quartz)
{
  NS::AutoreleasePool* autoreleasePool = NS::AutoreleasePool::alloc()->init();
  update(m_clock.tick(quartz)); // le seul endroit où le temps avance
  MTL::CommandBuffer* commandBuffer = m_commandQueue->commandBuffer();

  MTL::RenderPassDescriptor* renderPassDescriptor = view->currentRenderPassDescriptor();
  {
    MTL::RenderCommandEncoder* renderCommandEncoder = commandBuffer->renderCommandEncoder(renderPassDescriptor);

    renderCommandEncoder->endEncoding();
  }

  commandBuffer->presentDrawable(view->currentDrawable());
  commandBuffer->commit();
  commandBuffer->waitUntilCompleted();

  autoreleasePool->release();
}

void Renderer::resizeViewWindow(NS::UInteger width, NS::UInteger height)
{
}
Deux pièges dans ce premier RendererTwo pitfalls in this first Renderer
Twee valkuilen in deze eerste Renderer

newDefaultLibrary() renvoie nullptr tant qu'aucun .metallib n'est embarqué dans le bundlereturns nullptr as long as no .metallib is embedded in the bundle
geeft nullptr terug zolang er geen .metallib in de bundel zit

— c'est le cas si tu n'as pas encore de fichier .metal.— which is the case if you don't have a .metal file yet.
— wat het geval is als je nog geen .metal-bestand hebt.

D'où les tests dans le destructeur : appeler release() sur un pointeur nul plante.Hence the checks in the destructor: calling release() on a null pointer crashes.
Vandaar de tests in de destructor: release() aanroepen op een null-pointer crasht.

waitUntilCompleted() bloque le CPU jusqu'à la fin du travail GPU.blocks the CPU until the GPU work is done.
blokkeert de CPU tot het GPU-werk klaar is.

C'est pratique pour valider un premier rendu et pour déboguer, mais ça sérialise CPU et GPU.It's handy to validate a first render and to debug, but it serializes the CPU and the GPU.
Handig om een eerste render te valideren en te debuggen, maar het laat CPU en GPU na elkaar werken.

On l'enlèvera dans le chapitre consacré à la synchronisation.We'll remove it in the chapter on synchronization.
We halen het weg in het hoofdstuk over synchronisatie.

Pour terminer, un point sur les fonctionnalités et classes proposées par MetalTo finish, a look at the features and classes Metal provides
Tot slot een overzicht van de functies en klassen die Metal biedt

  1. newDefaultLibrary() → charge le .metallib compilé depuis les shaders du projet.loads the .metallib compiled from the project's shaders.
    laadt de .metallib die uit de shaders van het project gecompileerd is.
  2. newCommandQueue() → crée la file de commandes GPU.creates the GPU command queue.
    maakt de GPU-command queue aan.
    C'est par elle que tous les commandBuffer seront soumis au GPU.Every commandBuffer is submitted to the GPU through it.
    Elke commandBuffer wordt via deze queue naar de GPU gestuurd.
  3. NS::AutoreleasePool → zone mémoire temporaire qui libère automatiquement les objets autoreleased à la fin de chaque frame.a temporary memory zone that automatically releases autoreleased objects at the end of each frame.
    een tijdelijke geheugenzone die autoreleased objecten aan het einde van elke frame automatisch vrijgeeft.

    Indispensable dans la boucle de rendu metal-cpp.Essential in the metal-cpp render loop.
    Onmisbaar in de metal-cpp-renderloop.
  4. MTL::CommandBuffer → enregistre une séquence de commandes GPU pour une seule frame (une seule image).records a sequence of GPU commands for a single frame (a single image).
    neemt een reeks GPU-commando's op voor één frame (één beeld).
    Soumis au GPU via commit().Submitted to the GPU with commit().
    Naar de GPU gestuurd met commit().
  5. MTL::RenderPassDescriptor → décrit les attachements de rendudescribes the render attachments
    beschrijft de render-attachments
    (color, depth) d'un pass.of a pass.
    van een pass.

    Fourni par la MTKView via currentRenderPassDescriptor().Provided by the MTKView through currentRenderPassDescriptor().
    Geleverd door de MTKView via currentRenderPassDescriptor().
  6. MTL::RenderCommandEncoder → encode les draw calls, les états du pipeline, les buffers et les textures d'un render pass.encodes a render pass's draw calls, pipeline states, buffers, and textures.
    encodeert de draw calls, pipelinestates, buffers en texturen van een render pass.
ÉvidemmentOf course
Uiteraard

Tu peux juste copier-coller le code et changer à ta façon, c'est relativement intuitif.You can just copy-paste the code and adapt it your way; it's fairly intuitive.
Je kunt de code gewoon kopiëren en naar eigen smaak aanpassen; het is vrij intuïtief.

Le tempo du rendu

Une seule horloge, avancée une fois par frame à partir de l'heure Quartz (CACurrentMediaTime). De cette manière, tous les systèmes lisent le même FrameTime : même delta, même temps écoulé.

/// C++ — FrameClock.hpp — update:22/10/26
#ifndef FrameClock_hpp
#define FrameClock_hpp

#include <algorithm>
#include <cstdint>

struct FrameTime
{
  double   now     = 0.0; // heure Quartz de la frame, en secondes (monotone, depuis le boot)
  float    delta   = 0.f; // durée de la frame, bornée : après une pause, pas de téléportation
  float    elapsed = 0.f; // somme des delta : le temps de jeu (n'avance pas pendant les gros à-coups)
  uint64_t index   = 0;   // numéro de frame
};

class FrameClock
{
public:
  static constexpr float kMaxDelta = 0.1f;

  const FrameTime& tick(double now)
  { // Première frame : pas de delta (rien à rattraper)
    const double raw = m_started ? now - m_time.now : 0.0;
    m_started      = true;
    m_time.now     = now;
    m_time.delta   = std::clamp((float)raw, 0.f, kMaxDelta); // delta time — cappé à 100ms pour éviter les sauts après suspend
    m_time.elapsed += m_time.delta;
    m_time.index   += 1;
    return m_time;
  }

  const FrameTime& time() const { return m_time; }

private:
  FrameTime m_time;
  bool      m_started = false;
};

#endif /* FrameClock_hpp */

Un point rapide sur le fichier :A quick look at the file:
Even het bestand overlopen:

  1. CACurrentMediaTime() → l'heure Quartz de Core Animation : des secondes depuis le démarrage du Mac, en double.Core Animation's Quartz time: seconds since the Mac booted, as a double.
    de Quartz-tijd van Core Animation: seconden sinds het opstarten van de Mac, als double.

    Elle est monotone : elle ne recule jamais, même si l'heure du système change.It's monotonic: it never goes backwards, even if the system clock changes.
    Ze is monotoon: ze gaat nooit terug, ook niet als de systeemklok verandert.

    AppViewController la lit à chaque frame et la passe à draw().AppViewController reads it every frame and passes it to draw().
    AppViewController leest ze elke frame en geeft ze door aan draw().
  2. FrameTime → ce que tous les systèmes lisent pendant une frame : now (l'heure Quartz), delta (la durée de la frame), elapsed (le temps de jeu) et index (le numéro de frame).what every system reads during a frame: now (Quartz time), delta (the frame's duration), elapsed (game time) and index (the frame number).
    wat elk systeem tijdens een frame leest: now (de Quartz-tijd), delta (de duur van de frame), elapsed (de speltijd) en index (het framenummer).
  3. tick(now) → appelée une seule fois par frame, au début de draw() : le delta est l'écart avec l'heure de la frame précédente.called once per frame, at the start of draw(): the delta is the gap with the previous frame's time.
    één keer per frame aangeroepen, aan het begin van draw(): de delta is het verschil met de tijd van de vorige frame.

    À la première frame, il n'y a pas de frame précédente : le delta vaut 0.On the first frame there is no previous frame, so the delta is 0.
    Bij de eerste frame is er geen vorige frame: de delta is 0.
  4. kMaxDelta + std::clamp → le delta est borné à 0.1 s.the delta is capped at 0.1 s.
    de delta wordt begrensd op 0.1 s.

    Après un point d'arrêt du débogueur ou une mise en veille, il vaudrait plusieurs secondes, et tout ce qui bouge avec vitesse × delta se téléporterait.After a debugger breakpoint or a sleep, it would be several seconds, and everything that moves by speed × delta would teleport.
    Na een breakpoint in de debugger of een slaapstand zou hij meerdere seconden zijn, en alles wat beweegt met snelheid × delta zou teleporteren.
  5. elapsed → la somme des delta bornés : le temps de jeu. Pendant un gros à-coup, il avance d'au plus 0.1 s, alors que l'heure Quartz, elle, continue.the sum of the capped deltas: game time. During a big hitch it moves by at most 0.1 s, while Quartz time keeps going.
    de som van de begrensde delta's: de speltijd. Bij een grote hapering gaat hij hooguit 0.1 s vooruit, terwijl de Quartz-tijd gewoon doorloopt.
  6. index → le numéro de frame, pratique pour faire quelque chose toutes les N frames (time.index % 5000).the frame number, handy to do something every N frames (time.index % 5000).
    het framenummer, handig om elke N frames iets te doen (time.index % 5000).
  7. time() const → relit le FrameTime courant sans faire avancer l'horloge.reads the current FrameTime without advancing the clock.
    leest de huidige FrameTime zonder de klok vooruit te zetten.
Pourquoi une seule horloge ?Why a single clock?
Waarom maar één klok?

Si chaque système appelait CACurrentMediaTime() de son côté, chacun aurait un delta légèrement différent dans la même frame, et ils se désynchroniseraient.If every system called CACurrentMediaTime() on its own, each would get a slightly different delta within the same frame, and they would drift apart.
Als elk systeem zelf CACurrentMediaTime() aanriep, kreeg elk een iets andere delta binnen dezelfde frame, en zouden ze uit de pas lopen.

Ici, draw() est le seul endroit où le temps avance : update(m_clock.tick(quartz)).Here, draw() is the only place where time moves forward: update(m_clock.tick(quartz)).
Hier is draw() de enige plek waar de tijd vooruitgaat: update(m_clock.tick(quartz)).

⬡CheckPoint Compilation — Tu peux effectuer ta première compilation !You can run your first build!
Je kunt je eerste build uitvoeren!

Tu auras une fenêtre noire à l'exécution parce que la texture du pass est vide (00000 …).You should get a black window when you run it, because the pass texture is empty (00000 …).
Normaal krijg je bij het uitvoeren een zwart venster, omdat de textuur van de pass leeg is (00000 …).
Pour la changer :To change it:
Om dat te veranderen:

/// C++ — Renderer.cpp — update:18/05/26
MTL::RenderPassDescriptor* renderPassDescriptor = view->currentRenderPassDescriptor();
renderPassDescriptor->colorAttachments()->object(0)->setClearColor(MTL::ClearColor(1.0, 0.3725, 0.1216, 1.0));
{ // l'orange de la marque · the brand's orange · de oranje kleur van het merk
  MTL::RenderCommandEncoder* renderCommandEncoder = commandBuffer->renderCommandEncoder(renderPassDescriptor);
⬡CheckPoint Compilation — Un fond de la couleur de la marque

Il y a quelques exemples de couleurs dans le chapitreThere are a few color examples in the … chapter
Er staan enkele kleurvoorbeelden in het hoofdstuk …
↘ Couleurs

Le menu macOS de l'application

Inutilisé dans ce cours, il permet de créer le menu à côté de la pomme en haut à droite de chaque application.

/// Objective-C — main.m — update:23/10/26 — avant : main
#import <Cocoa/Cocoa.h>

#import "AppViewController.h"

static void makeSliderSubmenu(NSMenu* parentMenu, NSString* title, SEL action, double minValue, double maxValue, double defaultValue, NSInteger tickmarks)
{
  NSMenu* submenu = [[NSMenu alloc] initWithTitle:title];
  NSMenuItem* sliderHostItem = [parentMenu addItemWithTitle:title action:nil keyEquivalent:@""];
  sliderHostItem.submenu = submenu;

  NSSlider* slider = [NSSlider sliderWithTarget:nil action:action];
  slider.frame = NSMakeRect(0, 0, 160, 16);
  NSMenuItem* sliderItem = [submenu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  sliderItem.view = slider;
  slider.numberOfTickMarks = tickmarks;
  slider.minValue = minValue;
  slider.maxValue = maxValue;
  slider.intValue = defaultValue;
  slider.allowsTickMarkValuesOnly = tickmarks ? YES : NO;
  slider.autoresizingMask = NSViewMinXMargin|NSViewWidthSizable|NSViewMaxXMargin|NSViewMinYMargin|NSViewMaxYMargin|NSViewHeightSizable;
  [slider sizeToFit];
}

static void createApplicationMenu(NSApplication* app)
{
  app.mainMenu = [[NSMenu alloc] init];
  NSString* bundleName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
  NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@""];
  NSMenuItem* appMenuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];

  [appMenu addItemWithTitle:[@"About " stringByAppendingString:bundleName]
                     action:@selector(orderFrontStandardAboutPanel:)
              keyEquivalent:@""];

  [appMenu addItem:[NSMenuItem separatorItem]];

  [appMenu addItemWithTitle:[@"Hide " stringByAppendingString:bundleName]
                     action:@selector(hide:)
              keyEquivalent:@"h"];

  NSMenuItem* hide_other_item = [appMenu addItemWithTitle:@"Hide Others"
                                                   action:@selector(hideOtherApplications:)
                                            keyEquivalent:@"h"];
  hide_other_item.keyEquivalentModifierMask = NSEventModifierFlagOption | NSEventModifierFlagCommand;

  [appMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];

  [appMenu addItem:[NSMenuItem separatorItem]];

  [appMenu addItemWithTitle:[@"Quit " stringByAppendingString:bundleName]
                     action:@selector(terminate:)
              keyEquivalent:@"q"];

  appMenuItem.submenu = appMenu;

  [app.mainMenu addItem:appMenuItem];

  NSMenu* graphicsMenu = [[NSMenu alloc] initWithTitle:@"Graphics"];
  NSMenuItem* graphicsMenuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
  graphicsMenuItem.submenu = graphicsMenu;

  // On pourra régler ces paramètres sur un shader
  makeSliderSubmenu(graphicsMenu, @"Brightness", @selector(setBrightness:), 1, 10, 5, 9);
  makeSliderSubmenu(graphicsMenu, @"EDR Demo",   @selector(setEDRBias:),    0,  1, 0, 0);

  [app.mainMenu addItem:graphicsMenuItem];

  NSMenu* windowsMenu = [[NSMenu alloc] initWithTitle:@"Window"];
  NSMenuItem* windowsMenuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];

  [windowsMenu addItemWithTitle:NSLocalizedString(@"Minimize", @"")
                         action:@selector(performMiniaturize:)
                  keyEquivalent:@"m"];
  windowsMenuItem.submenu = windowsMenu;
  [app.mainMenu addItem:windowsMenuItem];

  app.windowsMenu = windowsMenu;
}

int main(int argc, const char* argv[])
{
  NSApplication* application = [NSApplication sharedApplication];

  createApplicationMenu(application); // Appelle ton menu

  ApplicationController* applicationController = [[ApplicationController alloc] init];
  application.delegate = applicationController;

  return (NSApplicationMain(argc, argv));
}