iOS開發 Metal Framework基礎使用

        iOS 8.0起,Apple爲了更充分地發揮GPU的潛力,引入了Metal框架,Metal基於C++設計,開發者可以用它來編寫在GPU上執行的圖形渲染邏輯代碼和通用並行計算邏輯代碼,目前的Metal框架中可以使用三種着色器——Vertex Shader、Fragment Shader以及Compute Shader。

1、先創建MTLCreateSystemDefaultDevice和CAMetalLayer

2、確定頂點數據,中心點是原點(x, y, z)和頂點緩衝區MTLBuffer

let vertexData: [Float] = [

        0.5, 0.5, 0.0,

        -0.5, 0.5, 0.0,

        -0.5, -0.5, 0.0,

        0.5, -0.5, 0.0

    ]

2.1、您需要以字節爲單位獲取頂點數據的大小。您可以通過將第一個元素的大小乘以數組中元素的計數來實現這一點

let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0])

2.2、在GPU上創建一個新的緩衝區,從CPU傳入數據。爲默認配置傳遞一個空數組

vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: [])

3、創建Metal文件

vertex float4 basic_vertex(

                           const device packed_float3* vertex_array [[ buffer(0) ]],

                           unsigned int vid [[ vertex_id ]]) {

    return float4(vertex_array[vid], 1.0);

}

fragment half4 basic_fragment() {

    return half4(1.0);              

}

3.1、按名稱查找每個着色器

        let defaultLibrary = device.makeDefaultLibrary()!

        let fragmentProgram = defaultLibrary.makeFunction(name: "basic_fragment") //片段

        let vertexProgram = defaultLibrary.makeFunction(name: "basic_vertex")

4、創建渲染管道MTLRenderPipelineState

       let pipelineStateDescriptor = MTLRenderPipelineDescriptor()

        pipelineStateDescriptor.vertexFunction = vertexProgram

        pipelineStateDescriptor.fragmentFunction = fragmentProgram;

        pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm

         pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)

5、創建MTLCommandQueue和CADisplayLink

         commandQueue = device.makeCommandQueue()

         timer = CADisplayLink.init(target: self, selector: #selector(gameloop))

        timer.add(to: RunLoop.main, forMode: .default)

在gameloop方法裏面寫相應的需求

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章