3D Graphics with Metal · Set Up Metal in Swift | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1258241-3d-graphics-with-metal/lessons/3

When we write pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm, what does the “[0]” signifies? Why do we set pixelFormat to only first element of this array? How do we know which array element to use, i.e., how do we know we have to set value for 0th element?

[0] is the default color attachment. This holds a default render texture. When you write to a fragment, you’re writing to this render texture.

A render pass descriptor can hold multiple colour attachments. You can set up textures for each attachment and then write to each texture in the fragment shader. You might do this for deferred lighting, where you save the colour for a fragment, but also the world position of the object that occupies the space at that fragment. That position would be a float, so that colour attachment [1] would be a float texture format.
You can then send those two textures as inputs to the next render pass which would do some further calculation and output the final texture for rendering.

An MTKView has a default render descriptor automatically set up

If you’re interested in deferred lighting, Apple has a great sample: Apple Developer Documentation

When i try to compile and run the app, I have this error: MetalRenderer/Renderer.swift:46: Fatal error: Unexpectedly found nil while unwrapping an Optional value

It is in this line: Renderer.library = device.makeDefaultLibrary()!

How can I fix this?

I’m using Xcode 13.1

Hi @javi_aranda, and welcome to the forums :slightly_smiling_face:.

You can’t create a library when you have no Metal shaders for the library to compile. That’s why the library here is nil. The end result of this video is not intended to be run - continue to the next video, and you’ll create the shaders so everything works.

1 Like