You're actually making more work for yourself by trying to pull data out of the mesh and stuff it into Metal buffers "manually". Also, an MTKMeshBuffer
is not an MTLBuffer
— it contains a Metal buffer, along with info that you're likely to need when using that buffer to render with.
What you actually what to do here is have Model I/O allocate MetalKit buffers for you instead of doing it yourself, which means MetalKit allocates Metal buffers for the data so you don't have to copy it. Then use MetalKit to access the meshes and buffers. Something like this (untested):
let allocator = MTKMeshBufferAllocator(device: myMetalDevice)
let mdlMesh = MDLMesh(scnGeometry: sceneGeometry, bufferAllocator: allocator)
let mtkMesh = try! MTKMesh(mesh: mdlMesh, device: myMetalDevice)
// ~~~~ <- in real code, please handle errors
// then, at render time...
for (index, vertexBuffer) in mtkMesh.vertexBuffers.enumerated() {
// vertexBuffer is a MTKMeshBuffer, containing an MTLBuffer
renderEncoder.setVertexBuffer(vertexBuffer.buffer,
offset: vertexBuffer.offset,
at: index)
}
for submesh in mtkMesh.submeshes {
// submesh is a MTKSubmesh, containing an MTKMeshBuffer
renderEncoder.drawIndexedPrimitives(type: submesh.primitiveType,
indexCount: submesh.indexCount,
indexType: submesh.indexType,
indexBuffer: submesh.indexBuffer.buffer,
indexBufferOffset: submesh.indexBuffer.offset)
}