iosxcodeopengl-es

Which is the best way to handle OpenGLES shaders as part of an API for iOS?


Working on an API for iOS, I wrote a couple of shaders that are very important for the API. These shaders are in the form of vsh and fsh files. Now, working on real projects with the API , I discovered that when we add the folder with the API source to an Xcode iOS project, we have to do an additional step, consisting in adding the file to "Copy Bundle Resources" in the Build Phases tab of the project configuration. So, we are thinking in a best way to handle this issue (and with "best" I meant that step shouldn't exist at all!) since the shaders are loaded as strings to the GPU, so, what will be the best way to handle these shaders in the API?


Solution

  • One way to avoid having to bundle the shader files with your framework or static library is to embed them as string constants. I do this in this project using the following macros:

    #define STRINGIZE(x) #x
    #define STRINGIZE2(x) STRINGIZE(x)
    #define SHADER_STRING(text) @ STRINGIZE2(text)
    

    This lets me then do something like the following:

    NSString *const kGPUImagePassthroughFragmentShaderString = SHADER_STRING
    (
     varying highp vec2 textureCoordinate;
    
     uniform sampler2D inputImageTexture;
    
     void main()
     {
         gl_FragColor = texture2D(inputImageTexture, textureCoordinate);
     }
    );
    

    and use that NSString constant to provide the shader for my programs where needed. Shader files are then not needed, which simplifies the distribution process.

    You don't get as specific of syntax highlighting in Xcode as you do for dedicated vertex and fragment shader files, but you do get basic C coloring.