ShaderType.h
#include <simd/simd.h>
typedef enum ShaderVertexInputIndex
{
ShaderVertexInputIndexVertices = 0,
ShaderVertexInputIndexViewportSize = 1,
} ShaderVertexInputIndex;
/// 纹理索引
typedef enum ShaderTextureIndex
{
ShaderTextureIndexIndexBaseColor = 0,
} ShaderTextureIndex;
typedef struct
{
vector_float2 position;
// 纹理坐标
vector_float2 textureCoordinate;
} ShaderVertex;
Shader.metal
#include <metal_stdlib>
using namespace metal;
#include "ShaderType.h"
struct RasterizerData
{
float4 position [[position]];
float2 textureCoordinate;
};
vertex RasterizerData vertexShader(const uint vertexID [[vertex_id]],
constant ShaderVertex *vertices [[buffer(ShaderVertexInputIndexVertices)]])
{
RasterizerData out;
out.position = vector_float4(vertices[vertexID].position.x, vertices[vertexID].position.y, 0.0, 1.0);
out.textureCoordinate = vertices[vertexID].textureCoordinate;
return out;
}
fragment float4 fragmentShader(RasterizerData in [[stage_in]],
texture2d<half> colorTexture [[texture(ShaderTextureIndexIndexBaseColor)]])
{
constexpr sampler textureSampler (mag_filter::linear, min_filter::linear);
const half4 colorSample = colorTexture.sample(textureSampler, in.textureCoordinate);
return float4(colorSample);
}
MetalRender
import UIKit
import MetalKit
import simd
class MetalRender: NSObject {
// 向设备传递命令的命令队列
private var commandQueue: MTLCommandQueue?
private var pipelineState: MTLRenderPipelineState?
/// 纹理
private var texture: MTLTexture?
private let triangleVertices: [ShaderVertex] = {
let vertex0 = ShaderVertex(position: vector_float2(x: -1, y: -1), textureCoordinate: vector_float2(x: 0, y: 0))
let vertex1 = ShaderVertex(position: vector_float2(-1, 1), textureCoordinate: vector_float2(0, 1))
let vertex2 = ShaderVertex(position: vector_float2(1, -1), textureCoordinate: vector_float2(1, 0))
let vertex3 = ShaderVertex(position: vector_float2(1, 1), textureCoordinate: vector_float2(1, 1))
let array: [ShaderVertex] = [vertex0, vertex1, vertex2, vertex3]
return array
}()
private override init() {
super.init()
}
convenience init(_ view: MTKView) {
self.init()
let device = view.device
let defaultLibrary = device?.makeDefaultLibrary()
let vertexFunction = defaultLibrary?.makeFunction(name: "vertexShader")
let fragmentFunction = defaultLibrary?.makeFunction(name: "fragmentShader")
let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
pipelineStateDescriptor.label = "Simple Pipeline"
pipelineStateDescriptor.vertexFunction = vertexFunction
pipelineStateDescriptor.fragmentFunction = fragmentFunction
pipelineStateDescriptor.colorAttachments[0].pixelFormat = view.colorPixelFormat
do {
pipelineState = try device?.makeRenderPipelineState(descriptor: pipelineStateDescriptor)
}catch {
print(error)
}
commandQueue = device?.makeCommandQueue()
guard let image = flipImage(UIImage(named: "02")), let cgImage = image.cgImage else { return }
let textureLoader = MTKTextureLoader(device: device!)
texture = try? textureLoader.newTexture(cgImage: cgImage, options: [MTKTextureLoader.Option.SRGB : false])
}
}
// MARK: - private
private extension MetalRender {
/// 翻转上下颠倒的图片
func flipImage(_ image: UIImage?) -> UIImage? {
guard let image = image else { return nil }
UIGraphicsBeginImageContextWithOptions(image.size, false, UIScreen.main.scale)
let ctx = UIGraphicsGetCurrentContext()
ctx?.translateBy(x: 0, y: image.size.height)
ctx?.scaleBy(x: 1, y: -1)
image.draw(in: CGRect(origin: .zero, size: image.size))
let reslut = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return reslut
}
}
// MARK: - MTKViewDelegate
extension MetalRender: MTKViewDelegate {
// 每当视图改变方向或调整大小时调用
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
}
// 当视图需要渲染帧时调
func draw(in view: MTKView) {
guard pipelineState != nil else { return }
let commandBuffer = commandQueue?.makeCommandBuffer()
commandBuffer?.label = "MyCommand"
if let renderPassDescriptor = view.currentRenderPassDescriptor {
let renderEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
renderEncoder?.label = "MyRenderEncoder"
renderEncoder?.setViewport(MTLViewport(originX: 0, originY: 0, width: Double(view.drawableSize.width), height: Double(view.drawableSize.height), znear: -1, zfar: 1))
renderEncoder?.setRenderPipelineState(pipelineState!)
renderEncoder?.setVertexBytes(triangleVertices, length: triangleVertices.count*MemoryLayout<ShaderVertex>.size, index: Int(ShaderVertexInputIndexVertices.rawValue))
renderEncoder?.setFragmentTexture(texture, index: Int(ShaderTextureIndexIndexBaseColor.rawValue))
renderEncoder?.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
renderEncoder?.endEncoding()
if let drawable = view.currentDrawable {
commandBuffer?.present(drawable)
}
}
commandBuffer?.commit()
}
}
renderEncoder?.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
使用.triangleStrip来绘制,可以少定义一些顶点。