How do I get the time in a fragment shader in the Metal shader language?

I have been reading through the metal shader language documentaiton. No luck so far.


Is there a global variable so to speak that exposes the sytem time to a fragment shader?


I want to be able to animate over time colors etc to create some visual effects applied to a 3D mesh.

Replies

None I know of, but you can easily add uniform passed to shader (kinda like global variable), which will contain system time, frame number or whatever variable you can use to animate your visual effect.


Hope that helps

Michal

Hi Michal.


Thanks for your reply.


I should have mentioned I do know about uniforms from having dabbled with GLSL some time ago. I did see some documentaiton on this page:


https://developer.apple.com/documentation/scenekit/scnshadable


There is a pre-defined uniform available to SCNShadbe in GLSL.


"u_time
float The current system time (in seconds) since SceneKit started rendering with the shader."


I will see if it works in the Metal shading language. There are so many ways to work with shaders - it is hard to know where to look in the documenation. I would really like it if there were newer code samples from Apple showing more varied uses of Metal shaders in action to avoid "faffing" about.

Metal is a much lower level API than SceneKit. As such it doesn't provide as much convenience functionality as SceneKit, but have the ability to perform more customization and achieve better performance.


That said, we're working on more sample. We've recently published a couple of Metal Fundamentalsand Advance Techniquessamples with some great docs to go with them. While none of these pass time into a shader, there are a few examples of passing uniform data from the ObjC code to Metal shaders.

In this post, Geppy Parziale outlines how he shoehorns the system time into a kernel shader in order to produce interesting effects.

Thanks for the link, I will check it out.


I have read the documentation a few times now & I do have a basic understanding of how shaderss can be authored to support both openGL and Metal at the same time.


This proejct is on hold currently while I wait to co-oridnate with the other people involved.


regards


Manjit

I have been scratching my head on this, but found a solution thanks to this gist. It contains a dump of the Metal interface containing the inputs provided by SceneKit. No more guessing!


I am absolutely stumped that this is not mentioned anywhere in Apple's documentation.


Example fragment shader:

#include <metal_stdlib>
// using namespace metal;

#pragma body
_output.color.b = sin(scn_frame.time);
// OR
_output.color.b = scn_frame.sinTime;