MetalKit框架在2015年WWDC上發(fā)布,它為Metal帶來了很多改進和新特性。Metal允許開發(fā)人員直接在GPU上執(zhí)行圖形渲染和并行計算。在Metal之前,iOS上用于圖形渲染的框架還是OpenGL ES。

image.png
- MTLDevice對象表示的GPU,通常通過MTLCreateSystemDefaultDevice()獲取。
- MTLCommandBuffer是存儲編碼命令以供GPU執(zhí)行的緩沖區(qū),MTLCommandBuffer會提供一些encoder,用于渲染的MTLRenderCommandEncoder,用于計算的MTLComputeCommandEncoder,用于緩存紋理拷貝指令的MTLBlitCommandEncoder。每一幀都會產(chǎn)生一個MTLCommandBuffer對象,用于填放指令,對于每一幀(MTLCommandBuffer)來說,只有調(diào)用encoder的操作結(jié)束,才能進行下一個encoder的創(chuàng)建,同時可以設置執(zhí)行完指令的回調(diào)。
- MTLCommandQueue是命令隊列,用于創(chuàng)建和組織MTLCommandBuffer,保證MTLCommandBuffer能有序地發(fā)送到GPU。
- MTLRenderPassDescriptor是一個輕量級的臨時對象,具有許多可配置屬性,供MTLCommandBuffer創(chuàng)建MTLRenderCommandEncoder對象用。
- MTLRenderCommandEncoder在創(chuàng)建的時候,會隱式的調(diào)用一次clear的命令。
encoder完成編碼后,commandBuffer接受兩個最終的命令:present和commit。 - MTLViewport是metal的可繪制區(qū)域,具有x和y偏移量、寬度和高度以及近平面和遠平面的3D區(qū)域。
- MTLRenderPipelineState表示渲染管道,最主要的三個過程:頂點處理、光柵化、片元處理。
獲取函數(shù)庫并創(chuàng)建管道
頂點函數(shù)
頂點函數(shù)(頂點著色器)的主要任務是處理傳入的頂點數(shù)據(jù),并將每個頂點映射到viewport中的一個位置。這樣,管道中的后續(xù)階段可以引用這個viewport位置,并將像素呈現(xiàn)到drawable中的確切位置。頂點函數(shù)通過將任意頂點坐標轉(zhuǎn)換為規(guī)范化的設備坐標(也稱為clip-space坐標)來完成此任務。

image.png
下面蘋果官方文檔的demo中的.metal文件,繪制一個五彩斑斕的三角形。
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
#import "AAPLShaderTypes.h"
typedef struct
{
float4 clipSpacePosition [[position]];
float4 color;
} RasterizerData;
vertex RasterizerData
vertexShader(uint vertexID [[vertex_id]],
constant AAPLVertex *vertices [[buffer(AAPLVertexInputIndexVertices)]],
constant vector_uint2 *viewportSizePointer [[buffer(AAPLVertexInputIndexViewportSize)]])
{
RasterizerData out;
out.clipSpacePosition = vector_float4(0.0, 0.0, 0.0, 1.0);
float2 pixelSpacePosition = vertices[vertexID].position.xy;
vector_float2 viewportSize = vector_float2(*viewportSizePointer);
out.clipSpacePosition.xy = pixelSpacePosition / (viewportSize / 2.0);
out.color = vertices[vertexID].color;
return out;
}
fragment float4 fragmentShader(RasterizerData in [[stage_in]])
{
return in.color;
}
vertexShader是頂點處理函數(shù)。ResterizerData是一個返回給片元著色器的結(jié)構(gòu)體,[[position]]修飾符表示clipSpacePosition是頂點位置。[[vertex_id]]屬性限定符是頂點函數(shù)每次執(zhí)行的頂點的索引,用于定位當前的頂點,當繪制調(diào)用這個頂點函數(shù)時,這個值從0開始,每次調(diào)用都會增加。第二個參數(shù)vertices是包含頂點(AAPLVertex類型)的數(shù)組。第三個參數(shù)viewportSizePointer表示viewport的大小。
未完待續(xù)~