挑战:使用 metal-cpp 绘图

Metal 是 Apple 平台上加速图形和计算功能的基础。如果您熟悉 C++,现在正是探索它的出色功能的最佳时机。针对这项挑战,我们将邀请您试用 metal-cpp,对 Xcode 中的三角形、圆形,甚至网格进行渲染。

我们也欢迎您在这一天访问图形与游戏挑战学堂,与他人协作应对这一挑战!马上来提出您的疑问,和其他开发者交流沟通,并分享您的作品吧。

Study Hall: Draw with metal-cpp

Get ready to render: We're inviting you to try out metal-cpp and render your own triangle, sphere, or even a mesh in Xcode. Visit the Graphics & Games Study Hall to collaborate on the “Draw with metal-cpp” coding challenge. Ask questions, connect with other developers, and share your creations.

View now

开始挑战

在开始前,请先观看“利用 metal-cpp 以 C++ 语言进行 Metal 编程”,并下载 LearnMetalCPP 项目,其中将包含一系列的 C++ 示例。

利用 metal-cpp 以 C++ 语言进行 Metal 编程

您的 C++ 游戏和 App 现在可以充分利用 Metal 的功能了。我们将介绍如何通过 metal-cpp 帮助您将 C++ 代码桥接到 Metal,探索它们分别如何管理对象的生命周期,并且演示有助于这些语言在您的 App...

Watch now

Download the LearnMetalCPP project

在 Xcode 中打开项目,然后选择 00-window.cpp 作为您的基础代码。要对您的图形进行渲染,您将需要在项目中进行一些设置。

首先,创建具有“MTL::RenderPipelineDescriptor”的“MTL::RenderPipelineState”对象:您将需要创建一个函数,如“buildShaders()”。在下方代码段中,我们提供了渲染单个三角形所需的着色器代码。

void Renderer::buildShaders()
{
    using NS::StringEncoding::UTF8StringEncoding;

    const char shaderSrc = R"(
        #include <metal_stdlib>
        using namespace metal;
        struct AAPLVertex
        {
            float3 position;
            half3  color;
        };
    
        // Welcome to modify the mesh as you want
        constant AAPLVertex triangles[] = {
            { float3{ -0.8f,  0.8f, 0.0f }, half3{  1.0, 0.3f, 0.2f } },
            { float3{  0.0f, -0.8f, 0.0f }, half3{  0.8f, 1.0, 0.0f } },
            { float3{ +0.8f,  0.8f, 0.0f }, half3{  0.8f, 0.0f, 1.0 } }
        };
    
        struct v2f
        {
            float4 position [[position]];
            half3 color;
        };

        v2f vertex vertexMain( uint vertexId [[vertex_id]])
        {
            v2f o;
            o.position = float4( triangles[ vertexId ].position, 1.0 );
            o.color = half3 ( triangles[ vertexId ].color );
            return o;
        }

        half4 fragment fragmentMain( v2f in [[stage_in]] )
        {
            return half4( in.color, 1.0 );
        }
    )";
    // TODO: Create a MTL::RenderPipelineDescriptor
    // TODO: Allocate a MTL::RenderPipelineState object
}

然后,通过设置 RenderPipelineState 并插入绘制调用来扩展 Renderer::draw( MTK::View pView) `MTL::函数。

void Renderer::draw(  MTK::View pView  )
{
...
    // TODO: Set MTL::RenderPipelineState
    // TODO: Draw a single triangle or more!
...
}

接下来:

  • 创建 `MTL::RenderPipelineDescriptor 对象并设置部分属性。
  • 创建 MTL::RenderPipelineState` 对象。
  • 提示:注意对象的生命周期。

想和社区分享您的 metal-cpp 作品?在 Twitter 上使用话题标签 #WWDC22Challenges 展示您的作品,或者在图形与游戏挑战学堂中分享。如果您想讨论与 metal-cpp 或其他图形与游戏相关的主题,请加入 WWDC22 一周期间举行的活动中的团队。

Explore #WWDC22Challenges on social media

Read the WWDC22 Challenges Terms and Conditions