我正在渲染一个在 metalkit 中有一些半透明区域(alpha < 1)的几何体MTKView
。如果isBlendingEnabled
在渲染管道状态的描述符中保留为 false,则所有内容都按应有的方式显示(尽管使用所有纯色)。
我知道渲染半透明对象取决于绘制顺序。目前,我只想测试 alpha 混合看起来像半透明区域与渲染缓冲区中已有的混合,即使它只是混合到背景(此时仍然只是清晰的颜色)。
但是,当我尝试启用混合时,makeRenderPipelineState
失败并出现以下错误:
编译器无法构建请求错误域=编译器错误代码=1“片段着色器未写入渲染目标颜色(0),混合所需的索引(1)”
这是尝试在 MTKView 的委托中构建管道状态的代码。它从 MTKView 继承属性的地方,我已将这些属性的值放在注释中
do {
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = vertex
descriptor.fragmentFunction = fragment
descriptor.sampleCount = view.sampleCount // 4
descriptor.depthAttachmentPixelFormat = view.depthStencilPixelFormat //.depth32Float
let renderAttachment = descriptor.colorAttachments[0]
renderAttachment?.pixelFormat = view.colorPixelFormat //.bgra8Unorm
// following 7 lines cause makeRenderPipelineState to fail
renderAttachment?.isBlendingEnabled = true
renderAttachment?.alphaBlendOperation = .add
renderAttachment?.rgbBlendOperation = .add
renderAttachment?.sourceRGBBlendFactor = .sourceAlpha
renderAttachment?.sourceAlphaBlendFactor = .sourceAlpha
renderAttachment?.destinationRGBBlendFactor = .oneMinusSourceAlpha
renderAttachment?.destinationAlphaBlendFactor = .oneMinusSource1Alpha
computePipelineState = try device.makeComputePipelineState(function: kernel)
renderPipelineState = try device.makeRenderPipelineState(descriptor: descriptor)
} catch {
print(error)
}
鉴于错误抱怨color(0)
,我将color[0]
绑定添加到片段着色器的输出中:
constant float3 directionalLight = float3(-50, -30, 80);
struct FragOut {
float4 solidColor [[ color(0) ]];
};
fragment FragOut passThroughFragment(Vertex fragIn [[ stage_in ]]) {
FragOut fragOut;
fragOut.solidColor = fragIn.color;
fragOut.solidColor.rgb *= max(0.4, dot(fragIn.normal, normalize(directionalLight)));
return fragOut;
};
最后,绘制代码:
if let renderPassDescriptor = view.currentRenderPassDescriptor,
let drawable = view.currentDrawable {
let commandBuffer = queue.makeCommandBuffer()
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.8, green: 0.8, blue: 1, alpha: 1)
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
renderEncoder.setDepthStencilState(depthStencilState)
renderEncoder.setRenderPipelineState(renderPipelineState)
//renderEncoder.setTriangleFillMode(.lines)
renderEncoder.setVertexBuffer(sceneBuffer, offset: 0, at: 0)
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, at: 1)
renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: Int(vertexCount) )
renderEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
我没有在片段着色器中明确设置任何纹理。这是否意味着 currentDrawable 隐含地是索引 0 处的颜色附件?为什么要color(0)
在索引 1 处看到错误消息?混合是否需要两个颜色附件?(它不能只是添加到已经渲染的东西上吗?)
谢谢。