一尘不染

离屏渲染金属

swift

 func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
        print("current drawable size:\(view.drawableSize)")
    }

    func draw(in view: MTKView) {


        guard let drawable = view.currentDrawable else { return }

        let textureDescriptor = MTLTextureDescriptor()
        textureDescriptor.textureType = MTLTextureType.type2D
        textureDescriptor.width = drawable.texture.width
        textureDescriptor.height = drawable.texture.height
        textureDescriptor.pixelFormat = .bgra8Unorm
        textureDescriptor.storageMode = .shared
        textureDescriptor.usage = .renderTarget

        let sampleTexture = device.makeTexture(descriptor: textureDescriptor)


        let renderPass = MTLRenderPassDescriptor()
        renderPass.colorAttachments[0].texture = sampleTexture
        renderPass.colorAttachments[0].loadAction = .clear
        renderPass.colorAttachments[0].clearColor =
            MTLClearColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
        renderPass.colorAttachments[0].storeAction = .store

        let commandBuffer = commandQueue.makeCommandBuffer()
        var commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: renderPass)


        let deltaTime = 1 / Float(view.preferredFramesPerSecond)


        for scene in scenes{
            scene.render(commandEncoder: commandEncoder!, deltaTime: deltaTime)
        }

        commandEncoder?.endEncoding()


        let descriptor = view.currentRenderPassDescriptor
        commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: descriptor!)



       for canvasScene in canvasScenes{
          canvasScene.updateCanvas(texture: sampleTexture!)
          canvasScene.render(commandEncoder: commandEncoder!, deltaTime: deltaTime)
       }

        commandEncoder?.endEncoding()


        commandBuffer?.present(drawable)
        commandBuffer?.commit()
    }

我是屏幕外渲染的新手。我希望我做对了。任何人都可以建议它是否正确。我首先在示例Texture中绘制它,然后将示例纹理设置为在当前drawable中绘制的quad(plane)。这是进行屏幕外渲染的优化方法。

当我仅禁用Metal API验证时,将运行此代码。否则我得到以下问题

Fragment Function(fragment_shader_texture): Shader reads texture (texture[0]) whose usage (0x04) doesn't specify MTLTextureUsageShaderRead (0x01)

建议请优化


阅读 240

收藏
2020-07-07

共1个答案

一尘不染

屏幕纹理对.renderTarget的用法,应使用[.renderTarget,.shaderRead]。

2020-07-07