我正在尝试进入金属。我已经做了一些 OpenGL,但已经有好几年了,所以我想不出合适的方法来做到这一点。我一直在使用 Ray Wenderlich 的 Metal 教程介绍(http://www.raywenderlich.com/81399/ios-8-metal-tutorial-swift-moving-to-3d)
我有一个顶点结构:
struct Vertex
{
var x, y, z: Float
var r, g, b, a: Float
func floatBuffer() -> Array<Float>
{
return [x, y, z, r, g, b, a]
}
}
和一个顶点缓冲区类:
class VertexBuffer
{
var vertexData = Array<Float>()
init(vertices: Array<Vertex>)
{
var vertexData = Array<Float>()
for vertex in vertices
{
vertexData += vertex.floatBuffer()
}
self.vertexData = vertexData
}
func updateColorOfVertexAtIndex(index: Int, newRed: CGFloat, newGreen: CGFloat, newBlue: CGFloat, newAlpha: CGFloat)
{
let vertexDataIndex = index * 7
if (vertexDataIndex < self.vertexData.count)
{
self.vertexData[vertexDataIndex + 3] = Float(newRed)
self.vertexData[vertexDataIndex + 4] = Float(newGreen)
self.vertexData[vertexDataIndex + 5] = Float(newBlue)
self.vertexData[vertexDataIndex + 6] = Float(newAlpha)
}
}
func updateColorOfVertexAtIndex(index: Int, newColor: UIColor)
{
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
newColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
self.updateColorOfVertexAtIndex(index, newRed: red, newGreen: green, newBlue: blue, newAlpha: alpha)
}
}
基于其他一些应用程序的状态,我想更新一个或多个顶点的 RGBA。使用这些VertexBuffer.updateColor...
方法,我正在更新VertexBuffer.vertexData
. 我有一个 CADisplayLink 连接到以下功能:
func diffusionLoop()
{
self.updateVertexData()
var vertexData = self.inkVertexBuffer.vertexData
let dataSize = vertexData.count * sizeofValue(vertexData[0])
let vertexBuffer = self.device.newBufferWithBytes(vertexData, length: dataSize, options: nil)
autoreleasepool { () -> () in
self.renderColorsWithVertexBuffer(vertexBuffer)
}
}
func renderColorsWithVertexBuffer(vertexBuffer: MTLBuffer)
{
let renderPassDescriptor = MTLRenderPassDescriptor()
let drawable = self.metalLayer.nextDrawable()
renderPassDescriptor.colorAttachments[0].texture = drawable.texture
renderPassDescriptor.colorAttachments[0].loadAction = .Clear
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(1.0, 1.0, 1.0, 0.0)
renderPassDescriptor.colorAttachments[0].storeAction = .Store
let commandBuffer = self.commandQueue.commandBuffer()
if let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor) {
renderEncoder.setRenderPipelineState(self.pipelineState)
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, atIndex: 0)
renderEncoder.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: self.vertexCount, instanceCount: self.triangleCount)
renderEncoder.endEncoding()
}
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
}
问题是,我不知道这是否是正确的方法。我的目标是经常更新某些顶点的颜色,但是每次修改顶点数据并从中创建一个 MTLBuffer 的答案是什么?或者是其他东西?
任何帮助将不胜感激!