注册

iOS - Metal的认识

一.Metal 简介

        在 WWDC 2014 上,Apple为游戏开发者推出了新的平台技术 Metal,该技术能够为 3D 图像提高 10 倍的渲染性能,并支持大家熟悉的游戏引擎及公司。

        Metal 是一种低层次的渲染应用程序编程接口,提供了软件所需的最低层,保证软件可以运行在不同的图形芯片上。Metal 提升了 A7 与 A8 处理器效能,让其性能完全发挥。

        Metal,充分利用GPU的运算能力,在现阶段,AVFoundation ⼈脸识别/.... 等大量需要显示计算的时候,苹果采用了硬件加速器驱动GPU工作,在音视频方面,⾳频编码/解码 / 视频编码/解码 ->压缩任务 ->都与硬件加速器分不开,苹果提供的Metal,能发挥GPU/CPu的最大性能,并且管理我们的资源。

二.Metal的渲染流程

        Metal的渲染流程借鉴了OpenGLES的流程,它通过控制顶点着色器/片元着色器(Metal里面叫顶点函数/片元函数),交给帧缓冲区,最后显示到屏幕上


c688ee775d25006f273bb1da70c9cdc8.png


值得注意的是,在OpenGlES中,图元装配有9中,在Metal中,图元装配只有五种,他们分别是:

                 MTLPrimitiveTypePoint = 0, 点

                 MTLPrimitiveTypeLine = 1, 线段

                 MTLPrimitiveTypeLineStrip = 2, 线环

                 MTLPrimitiveTypeTriangle = 3,  三角形

                 MTLPrimitiveTypeTriangleStrip = 4, 三角型扇

三.Metal的初级准备工作

3.1Metal的注意事项

        在讲Metal的初级使用之前,我们先来看看苹果爸爸给我们的建议,首先,苹果建议我们Separate Your Rendering Loop,即分离我们渲染,Metal给我们提供了一个View,叫MTKView,它继承自UiView,它主要的渲染是通过MTKViewDelegate协议回调实现,两个重要的协议方法是:

        1)当MTKView视图发生大小改变时调用

        /*!

         @method mtkView:drawableSizeWillChange:

         @abstract Called whenever the drawableSize of the view will change

         @discussion Delegate can recompute view and projection matricies or regenerate any buffers to be compatible with the new view size or resolution

         @paramviewMTKView which called this method

         @paramsizeNew drawable size in pixels

         */

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

        2)每当视图需要渲染时调用

        /*!

         @method drawInMTKView:

         @abstract Called on the delegate when it is asked to render into the view

         @discussion Called on the delegate when it is asked to render into the view

         */

        - (void)drawInMTKView:(nonnullMTKView*)view;

    3.2  Metal是如何驱动GPU工作的?

7c0dd1f3d02f0a60663bf1adbe7f762f.png


相关对应代码:在ViewController中,我们把当前的View变成MTKView,当然你也可以用self.view添加一个子视图View,CCRenderer是自定义的一个类,主要是分离MTview的渲染,

         _view.device = MTLCreateSystemDefaultDevice();一个MTLDevice 对象就代表这着一个GPU,通常我们可以调用方法MTLCreateSystemDefaultDevice()来获取代表默认的GPU单个对象.

        在CCRenderer中的初始化方法中- (id)initWithMetalKitView:(MTKView *)mtkView我们拿到device,创建newCommandQueue队列:

                _commandQueue = [_device newCommandQueue];

        所有应用程序需要与GPU交互的第一个对象是一个对象->MTLCommandQueue. 你使用MTLCommandQueue 去创建对象,并且加入MTLCommandBuffer 对象中.确保它们能够按照正确顺序发送到GPU.对于每一帧,一个新的MTLCommandBuffer 对象创建并且填满了由GPU执行的命令.

        在CCRenderer中,我们实现了MTKView的协议代理方法,在- (void)drawInMTKView:(nonnullMTKView*)view中,我们通过创建好的队列再创建命令缓冲区并且加入到MTCommandBuffer对象中去:

                id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];

        值得注意的是,在创建好命令缓冲区后,Metal提出了一个概念叫渲染描述符:(个人理解这个渲染描述符是给每个命令打上一个标记,GPU在工作的时候通过这个渲染描述符取出相应的命令,如果说的不对,请大神指点)从视图绘制中,获得渲染描述符:

                MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor;

通过渲染描述符renderPassDescriptor创建MTLRenderCommandEncoder                

                id<MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];

        最后 [renderEncoderendEncoding];

当编码器结束之后,命令缓存区就会接受到2个命令.

         1) present

         2) commit

         因为GPU是不会直接绘制到屏幕上,因此你不给出去指令.是不会有任何内容渲染到屏幕上.

        [commandBuffer presentDrawable:view.currentDrawable];

        [commandBuffercommit];

        至此,Metal的准备工作已经完成

四.用Metal渲染一个简单的三角形

在做好上面的准备的准备工作后:

500371cf64980233e40064b3522a0d33.png

//初始化MTKView

- (nonnull instancetype)initWithMetalKitView:(nonnull MTKView *)mtkView

{

    self= [superinit];

    if(self)

    {

        NSError*error =NULL;


        //1.获取GPU 设备

        _device= mtkView.device;

        //2.在项目中加载所有的(.metal)着色器文件

        // 从bundle中获取.metal文件

        id defaultLibrary = [_devicenewDefaultLibrary];

        //从库中加载顶点函数

        id vertexFunction = [defaultLibrarynewFunctionWithName:@"vertexShader"];

        //从库中加载片元函数

        id fragmentFunction = [defaultLibrarynewFunctionWithName:@"fragmentShader"];

        //3.配置用于创建管道状态的管道

        MTLRenderPipelineDescriptor *pipelineStateDescriptor = [[MTLRenderPipelineDescriptor alloc] init];

        //管道名称

        pipelineStateDescriptor.label=@"Simple Pipeline";

        //可编程函数,用于处理渲染过程中的各个顶点

        pipelineStateDescriptor.vertexFunction= vertexFunction;

        //可编程函数,用于处理渲染过程中各个片段/片元

        pipelineStateDescriptor.fragmentFunction= fragmentFunction;

        //一组存储颜色数据的组件

        pipelineStateDescriptor.colorAttachments[0].pixelFormat= mtkView.colorPixelFormat;


        //4.同步创建并返回渲染管线状态对象

        _pipelineState= [_devicenewRenderPipelineStateWithDescriptor:pipelineStateDescriptorerror:&error];

        //判断是否返回了管线状态对象

        if (!_pipelineState)

        {


            //如果我们没有正确设置管道描述符,则管道状态创建可能失败

            NSLog(@"Failed to created pipeline state, error %@", error);

            returnnil;

        }

        //5.创建命令队列

        _commandQueue = [_device newCommandQueue];

    }

    return self;

}

//每当视图需要渲染帧时调用

- (void)drawInMTKView:(nonnullMTKView*)view

{

    //1. 顶点数据/颜色数据

    staticconstCCVertextriangleVertices[] =

    {

        //顶点,    RGBA 颜色值

        { {  0.5, -0.25,0.0,1.0}, {1,0,0,1} },

        { { -0.5, -0.25,0.0,1.0}, {0,1,0,1} },

        { { -0.0f,0.25,0.0,1.0}, {0,0,1,1} },

    };

    //2.为当前渲染的每个渲染传递创建一个新的命令缓冲区

    id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];

    //指定缓存区名称

    commandBuffer.label=@"MyCommand";


    //3.

    // MTLRenderPassDescriptor:一组渲染目标,用作渲染通道生成的像素的输出目标。

    MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor;

    //判断渲染目标是否为空

    if(renderPassDescriptor !=nil)

    {

        //4.创建渲染命令编码器,这样我们才可以渲染到something

        id renderEncoder =[commandBufferrenderCommandEncoderWithDescriptor:renderPassDescriptor];

        //渲染器名称

        renderEncoder.label=@"MyRenderEncoder";

        //5.设置我们绘制的可绘制区域

        /*

        typedef struct {

            double originX, originY, width, height, znear, zfar;

        } MTLViewport;

         */

        //视口指定Metal渲染内容的drawable区域。 视口是具有x和y偏移,宽度和高度以及近和远平面的3D区域

        //为管道分配自定义视口需要通过调用setViewport:方法将MTLViewport结构编码为渲染命令编码器。 如果未指定视口,Metal会设置一个默认视口,其大小与用于创建渲染命令编码器的drawable相同。

        MTLViewportviewPort = {

            0.0,0.0,_viewportSize.x,_viewportSize.y,-1.0,1.0

        };

        [renderEncodersetViewport:viewPort];

        //[renderEncoder setViewport:(MTLViewport){0.0, 0.0, _viewportSize.x, _viewportSize.y, -1.0, 1.0 }];


        //6.设置当前渲染管道状态对象

        [renderEncodersetRenderPipelineState:_pipelineState];



        //7.从应用程序OC 代码 中发送数据给Metal 顶点着色器 函数

        //顶点数据+颜色数据

        //  1) 指向要传递给着色器的内存的指针

        //  2) 我们想要传递的数据的内存大小

        //  3)一个整数索引,它对应于我们的“vertexShader”函数中的缓冲区属性限定符的索引。

        [renderEncodersetVertexBytes:triangleVertices

                               length:sizeof(triangleVertices)

                              atIndex:CCVertexInputIndexVertices];

        //viewPortSize 数据

        //1) 发送到顶点着色函数中,视图大小

        //2) 视图大小内存空间大小

        //3) 对应的索引

        [renderEncodersetVertexBytes:&_viewportSize

                               length:sizeof(_viewportSize)

                              atIndex:CCVertexInputIndexViewportSize];



        //8.画出三角形的3个顶点

        // @method drawPrimitives:vertexStart:vertexCount:

        //@brief 在不使用索引列表的情况下,绘制图元

        //@param 绘制图形组装的基元类型

        //@param 从哪个位置数据开始绘制,一般为0

        //@param 每个图元的顶点个数,绘制的图型顶点数量

        /*

         MTLPrimitiveTypePoint = 0, 点

         MTLPrimitiveTypeLine = 1, 线段

         MTLPrimitiveTypeLineStrip = 2, 线环

         MTLPrimitiveTypeTriangle = 3,  三角形

         MTLPrimitiveTypeTriangleStrip = 4, 三角型扇

         */


        [renderEncoderdrawPrimitives:MTLPrimitiveTypeTriangle

                          vertexStart:0

                          vertexCount:3];

        //9.表示已该编码器生成的命令都已完成,并且从NTLCommandBuffer中分离

        [renderEncoderendEncoding];

        //10.一旦框架缓冲区完成,使用当前可绘制的进度表

        [commandBufferpresentDrawable:view.currentDrawable];

    }

    //11.最后,在这里完成渲染并将命令缓冲区推送到GPU

    [commandBuffercommit];

}


f2a12fcc7d07182148bb8a7838b4e729.png

 

Metal文件:(语法下篇介绍)

#include 

//使用命名空间 Metal

using namespace metal;

// 导入Metal shader 代码和执行Metal API命令的C代码之间共享的头

#import "CCShaderTypes.h"

// 顶点着色器输出和片段着色器输入

//结构体

typedef struct

{

    //处理空间的顶点信息

    float4clipSpacePosition [[position]];

    //颜色

    float4color;

} RasterizerData;

//顶点着色函数

vertex RasterizerData

vertexShader(uintvertexID [[vertex_id]],

             constantCCVertex*vertices [[buffer(CCVertexInputIndexVertices)]],

             constantvector_uint2*viewportSizePointer [[buffer(CCVertexInputIndexViewportSize)]])

{

    /*

     处理顶点数据:

        1) 执行坐标系转换,将生成的顶点剪辑空间写入到返回值中.

        2) 将顶点颜色值传递给返回值

     */


    //定义out

    RasterizerDataout; 

//    //初始化输出剪辑空间位置

//    out.clipSpacePosition = vector_float4(0.0, 0.0, 0.0, 1.0);

//

//    // 索引到我们的数组位置以获得当前顶点

//    // 我们的位置是在像素维度中指定的.

//    float2 pixelSpacePosition = vertices[vertexID].position.xy;

//

//    //将vierportSizePointer 从verctor_uint2 转换为vector_float2 类型

//    vector_float2 viewportSize = vector_float2(*viewportSizePointer);

//

//    //每个顶点着色器的输出位置在剪辑空间中(也称为归一化设备坐标空间,NDC),剪辑空间中的(-1,-1)表示视口的左下角,而(1,1)表示视口的右上角.

//    //计算和写入 XY值到我们的剪辑空间的位置.为了从像素空间中的位置转换到剪辑空间的位置,我们将像素坐标除以视口的大小的一半.

//    out.clipSpacePosition.xy = pixelSpacePosition / (viewportSize / 2.0);

    out.clipSpacePosition= vertices[vertexID].position;

    //把我们输入的颜色直接赋值给输出颜色. 这个值将于构成三角形的顶点的其他颜色值插值,从而为我们片段着色器中的每个片段生成颜色值.

    out.color= vertices[vertexID].color;

    //完成! 将结构体传递到管道中下一个阶段:

    returnout;

}

//当顶点函数执行3次,三角形的每个顶点执行一次后,则执行管道中的下一个阶段.栅格化/光栅化.

// 片元函数

//[[stage_in]],片元着色函数使用的单个片元输入数据是由顶点着色函数输出.然后经过光栅化生成的.单个片元输入函数数据可以使用"[[stage_in]]"属性修饰符.

//一个顶点着色函数可以读取单个顶点的输入数据,这些输入数据存储于参数传递的缓存中,使用顶点和实例ID在这些缓存中寻址.读取到单个顶点的数据.另外,单个顶点输入数据也可以通过使用"[[stage_in]]"属性修饰符的产生传递给顶点着色函数.

//被stage_in 修饰的结构体的成员不能是如下这些.Packed vectors 紧密填充类型向量,matrices 矩阵,structs 结构体,references or pointers to type 某类型的引用或指针. arrays,vectors,matrices 标量,向量,矩阵数组.

fragmentfloat4fragmentShader(RasterizerDatain [[stage_in]])

{

    //返回输入的片元颜色

    returnin.color;

}

用于OC和Metal桥接的文件:

/*

 介绍:

 头文件包含了 Metal shaders 与C/OBJC 源之间共享的类型和枚举常数

*/

#ifndef CCShaderTypes_h

#define CCShaderTypes_h

// 缓存区索引值 共享与 shader 和 C 代码 为了确保Metal Shader缓存区索引能够匹配 Metal API Buffer 设置的集合调用

typedef enum CCVertexInputIndex

{

    //顶点

    CCVertexInputIndexVertices    =0,

    //视图大小

    CCVertexInputIndexViewportSize =1,

} CCVertexInputIndex;

//结构体: 顶点/颜色值

typedef struct

{

    // 像素空间的位置

    // 像素中心点(100,100)

    vector_float4 position;

    // RGBA颜色

    vector_float4 color;

} CCVertex;

#endif


作者:枫紫
链接:https://www.jianshu.com/p/a6f3c90d6ba5





0 个评论

要回复文章请先登录注册