I'm trying to print the vertex positions of an MDLMesh
. I have the following code in a playground:
import Cocoa
import ModelIO
let boxURL = Bundle.main.url(forResource: "box", withExtension: "obj")!
let asset = MDLAsset(url: boxURL)
let mesh = asset.object(at: 0) as! MDLMesh
let vbuf = mesh.vertexBuffers[0]
let vbufmap = vbuf.map()
let layout = mesh.vertexDescriptor.layouts.firstObject as! MDLVertexBufferLayout
let stride = layout.stride
assert(vbuf.length == mesh.vertexCount*stride)
for i in 0..<mesh.vertexCount {
let v = (vbufmap.bytes+i*stride).bindMemory(to: float3.self, capacity: 1).pointee
print(v)
}
It correctly prints the first vertex, and then segfaults on the second. I suspect I'm doing something wrong with bindMemory
.
Update:
Copying out the vertices into a Data
works:
let data = Data(bytes: vbufmap.bytes, count: vbuf.length)
for i in 0..<mesh.vertexCount {
var v = float3(0)
let buffer = UnsafeMutableBufferPointer(start: &v, count: 1)
let start = i*stride
data.copyBytes(to: buffer, from: start..<start+MemoryLayout<float3>.size)
print(v)
}
But I shouldn't have to copy all the vertex data to access a vertex.