I am trying to learn Metal when all of a sudden I get hit with a syntax error. I was wondering why the person tried to add an UnsafeMutablePointer, but that is beside the point. I tried moving the stuff so it doesn't try to add an int to and UnsafeMutablePointer, but the cube just outright disappears.
This tutorial seems to have a programming syntax error and moving the cause into a different parameter or this doesn't help at all (it erases everything). (This isn't because of updates to the language).
The Gitlab to the project (I am going to keep it to one file) and the problem is at around 67. Here is what the code looks like :
memcpy(bufferPointer + MemoryLayout<Float>.size * Matrix4.numberOfElements(), projectionMatrix.raw(), MemoryLayout<Float>.size * Matrix4.numberOfElements())
Here is the Gitlab link if you want a closer look at the whole file for context:
let bufferPointer = uniformBuffer?.contents()
memcpy(bufferPointer, nodeModelMatrix.raw(), MemoryLayout<Float>.size * Matrix4.numberOfElements())
//come back to here
memcpy(bufferPointer + MemoryLayout<Float>.size * Matrix4.numberOfElements(), projectionMatrix.raw(), MemoryLayout<Float>.size * Matrix4.numberOfElements())
This is due to a subtle change in the Metal API that happened circa Swift 4 and iOS 11.
The return type of the -newBufferWithLength:options:
method changed from nonnull id<MTLBuffer>
to nullable id<MTLBuffer>
. As a result, the return type of the corresponding makeBuffer(length:options:)
method in the Swift "overlay" changed from MTLBuffer
to MTLBuffer?
Therefore, if you use optional chaining with a value returned by this API, the contents()
method returns an UnsafeMutableRawPointer?
, rather than what you want, which is an UnsafeMutableRawPointer
. If you instead use force-unwrapping to ensure that you get a non-nil buffer from the device, all of the pointer arithmetic type-checks just fine.
A couple of extra points:
Int
to an UnsafeMutableRawPointer
: it offsets into the pointer by that number of bytes, producing another UnsafeMutableRawPointer
.