文章

Apple Metal 如何清屏

Metal 中清屏的核心代码是通过设置渲染通道描述符(MTLRenderPassDescriptor)中的colorAttachments 的 loadAction 为MTLLoadActionClear,并设置清屏颜色clearColor,然后通过命令编码器执行清屏操作。

具体流程如下: 1. 从CAMetalLayer获取当前绘制的drawable和texture 2. 创建MTLRenderPassDescriptor,设置colorAttachments.texture为上述texture 3. 将colorAttachments.loadAction设置为MTLLoadActionClear,表示每次渲染开始时清除颜色缓冲 4. 设置colorAttachments.storeAction为MTLStoreActionStore,表示渲染结束后保存绘制结果 5. 设置colorAttachments.clearColor为需要的清屏颜色(例如红色(1,0,0,1)) 6. 创建命令队列和命令缓冲区,使用该渲染描述符创建渲染命令编码器 7. 结束编码并提交命令缓冲区,显示drawable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
guard let drawable = metalLayer.nextDrawable() else { return }
let texture = drawable.texture

let passDescriptor = MTLRenderPassDescriptor()
passDescriptor.colorAttachments[0].texture = texture
passDescriptor.colorAttachments[0].loadAction = .clear
passDescriptor.colorAttachments[0].storeAction = .store
passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(1, 0, 0, 1) // 红色清屏

let commandBuffer = commandQueue.makeCommandBuffer()!
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor)!
encoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()

对于离屏渲染直接清理 your_texture 纹理即可:

1
2
3
4
5
6
7
8
9
10
let passDescriptor = MTLRenderPassDescriptor()
passDescriptor.colorAttachments[0].texture = your_texture
passDescriptor.colorAttachments[0].loadAction = .clear
passDescriptor.colorAttachments[0].storeAction = .store
passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(1, 0, 0, 1) // 红色清屏

let commandBuffer = commandQueue.makeCommandBuffer()!
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: passDescriptor)!
encoder.endEncoding()
commandBuffer.commit()

可以看出清屏时,不需要定点和片源着色器,当然也不需要定点数据和纹理,因为清理的是目标纹理。

本文由作者按照 CC BY 4.0 进行授权