Reputation: 2191
I am trying to create a MDLMesh from my own custom data that I parsed from a file. The file only contains vertices positions and triangles indexes ; I extract them into two Swift Data
objects, float3
format for vertices and uint32
format for indexes.
My problem is that my MDLMesh doesn't seem to work properly as I can't import it to SceneKit (the resulting SCNGeometry seems "empty") nor create normals from it (crashes).
Now here is the code for MDLMesh:
let mesh = MDLMesh()
mesh.vertexBuffers = [MDLMeshBufferData(type: .vertex, data: vertexData)]
mesh.vertexCount = floats.count/3
let vertexDescriptor = MDLVertexDescriptor()
let attribute = MDLVertexAttribute(name: MDLVertexAttributePosition, format: .float3, offset: 0, bufferIndex: 0)
let layout = MDLVertexBufferLayout(stride: MemoryLayout<float3>.stride)
vertexDescriptor.attributes = [attribute]
vertexDescriptor.layouts = [layout]
Then I create a sub mesh (that describes the triangles) :
let submesh = MDLSubmesh(indexBuffer: MDLMeshBufferData(type: MDLMeshBufferType.index, data: indexData),
indexCount: uint32Indexes.count-uint32Indexes.count/4,
indexType: .uint32,
geometryType: .triangles,
material: nil)
mesh.submeshes = [submesh]
Do you see anything wrong ? Or could it just be that my data isn't correct ?
Thank you
NB: Note that indexCount
and vertexCount
are both right even tough their definition seems weird without more context :)
EDIT: When trying to make normals:
mesh.addNormals(withAttributeNamed: MDLVertexAttributeNormal, creaseThreshold: 0)
Here is the error I get:
2017-08-04 09:39:24.078436+0200 MyAppName[506:70657] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndexedSubscript:]: index 1 beyond bounds [0 .. 0]'
Upvotes: 1
Views: 1535
Reputation: 818
You should remove layout from VertexDescriptor
:
these lines:
let layout = MDLVertexBufferLayout(stride: MemoryLayout<float3>.stride)
vertexDescriptor.layouts = [layout]
And add these lines at the end of setting VertexDescriptor
:
vertexDescriptor.setPackedOffsets()
vertexDescriptor.setPackedStrides()
Upvotes: 1
Reputation: 21
Apple documentation on this method states: "Calling this method on a mesh that does not contain vertex position data raises an exception.", and I believe that it is exactly the issue here: your vertexData seems to have no elements in it.
Upvotes: 0