Drawing Sphere with Metal

Turns out it’s quite easy to calculate normals: mesh - Programmatically generating vertex normals - Computer Graphics Stack Exchange

This is your code returning the normal from the fragment shader.

It rotates the sphere using timer.

It also has a depth stencil state so that the sphere renders correctly.

The major change is in Sphere.swift where the normals are calculated:

Sphere-Normals.zip (138.0 KB)

Screen Shot 2021-07-19 at 8.37.19 am

Thank you so much Caroline.

Is there a easy code for drawing contours in metal?

How do you mean contours? Do you mean wireframe drawing instead of filling the triangles?

renderEncoder.setTriangleFillMode(.lines)

No actually means
image
This lines on surface comes from taking derivatives or plotting slopes. Contours are closes curve on the surface

That’s a bit tricky. If you have a look at Chapter 23, it describes fwidth, which gives you the changes in slope in a fragment function.

"dfdx() and dfdy() return the horizontal and vertical changes in slope, and fwidth() gives you the absolute derivative of the combined dfdx() and dfdy() ."

But I don’t know how you’d get from that to drawing contour lines

Thank you. I will check

Chapter 23 is debugging and profiling … I am looking in the right place?

Thanks

I believe it is chapter 22 Integrating SpriteKit.

Yes, that’s the one. Sorry!

Just thinking out loud here - The Sobel filter also gives you slopes.

It’s an edge detection filter though, not contour.

The tessellation chapter has an example of running a texture through a Metal Performance Shader and returning a Sobel texture.

I did wonder if you could run the depth texture through a Sobel filter, as they are here:

but I’ve never done that.

This looks an interesting read: