The article first appeared on glumes.com

Getting Started with Metal-CPp

The link is here:

developer.apple.com/metal/cpp/

Apple now supports developing Metal in C++.

As we all know, OpenGL and Vulkan support C++ development when doing back-end rendering development. They can directly define C++ related interfaces and implement them according to platform characteristics.

Metal requires Objective-C support and will write.m files, but now you can write C++ rendering implementations directly.

Lead to

According to the official article, first make sure Xcode is 9.3 or later and that you use C++17 syntax.

Download the C++ header file for Metal (metal-cpp).

Developer.apple.com/metal/cpp/f…

Create a project

Create a macOS project, either App project or command line project, to verify that the environment is configured correctly.

Next, place the downloaded Metal header (metal-cpp) in the project search path, as shown below:

Then change the C++ version to STD = C++ 17.

Next we include framework dependencies:

Main is:

  • Foundation.framework

  • QuartzCore.framework

  • Metal.framework

With the above environmental dependencies out of the way, you can start code development.

Code development

The first thing you need to do is include the Metal-related header file, and since it’s just a header library, you need to generate the corresponding implementation and add some macro configuration.

The core is this piece of code,


#define NS_PRIVATE_IMPLEMENTATION

#define CA_PRIVATE_IMPLEMENTATION

#define MTL_PRIVATE_IMPLEMENTATION

#include <Foundation/Foundation.hpp>

#include <Metal/Metal.hpp>

#include <QuartzCore/QuartzCore.hpp>

Copy the code

Anywhere else you need to use Metal-related objects, just include three header files.

All three header files come together, or you can include only one header file.

In the SingleHeader folder where metal-cpp is downloaded, there is a makesingleHeader. py script to run to generate:


./SingleHeader/MakeSingleHeader.py Foundation/Foundation.hpp QuartzCore/QuartzCore.hpp Metal/Metal.hpp

Copy the code

This generates a metal.hpp file in the SingleHeader folder, which contains all the objects you’ll need to use.


#define NS_PRIVATE_IMPLEMENTATION

#define CA_PRIVATE_IMPLEMENTATION

#define MTL_PRIVATE_IMPLEMENTATION

#include <Metal/Metal.hpp>

Copy the code

The Metal header file can be successfully introduced to the development, the official also provides a Demo project, can run this project:

Developer.apple.com/documentati…

In addition, using Metal to do the development of the rendering engine is much faster than using OpenGL to write, because it itself provides a lot of encapsulation tool classes, than OpenGL to write from scratch is much less difficult, and perhaps even better performance.