Jaysen Marais Jaysen Marais - 6 months ago 35
iOS Question

Synax for functions other than vertex|fragment|kernel in metal shader file

I'm porting some basic OpenCL code to a Metal compute shader. Get stuck pretty early when attempting to convert the miscellaneous helper functions. For example, including something like the following function in a

.metal
file Xcode (7.1) gives me a "No previous prototype for function" warning



float maxComponent(float4 a) {
return fmax(a.x, fmax(a.y, fmax(a.z, a.w)));
}


What's the 'metal' way to do this?

Answer

Three ways I know of:

(I rewrote the function to be an overload, and to be more readable to me.)

Actually declare the prototype:

float fmax(float4 float4);
float fmax(float4 float4) {
   return fmax(
      fmax(float4[0], float4[1]),
      fmax(float4[2], float4[3])
   );
}

Scope it to a file with static:

static float fmax(float4 float4) {
   return fmax(
      fmax(float4[0], float4[1]),
      fmax(float4[2], float4[3])
   );
}

Wrap it in an anonymous namespace:

namespace {
   float fmax(float4 float4) {
      return metal::fmax(
         metal::fmax(float4[0], float4[1]),
         metal::fmax(float4[2], float4[3])
      );
   }
}
Comments