I'm starting with OpenGL ES2.0 on Android (5.0.1), API Level 19. Where should I store the shader code? The first example encodes the shader directly as a string.
I'd like to have the shader code in a separate file for better usability. What's the best practice for storing and loading the vertex and fragment shaders?
Shader is the base class for objects that return horizontal spans of colors during drawing. A subclass of Shader is installed in a Paint calling paint. setShader(shader). After that any object (other than a bitmap) that is drawn with that paint will get its color(s) from the shader.
A function in GLSL must be declared before it can be used, a bit like defining a variable. This feature is the same as in C and was deemed unnecessary with the development of Java. Note unlike C or Java a function in GLSL cannot be called recursively. This is the code within a function cannot call the same function.
There are two main options:
Store them as text files in the assets
folder of your project. To load the shader:
AssetManager
with the getAssets()
method of the context.open()
on the AssetManager
, passing in the file name of the shader. This gives you an InputStream
.InputStream
, and store it in a String
.close()
on the InputStream
.Store them in the res/raw
folder of your project. To load the shader:
Resources
with the getResources()
method of the context.openRawResource()
on the Resources
, passing in the resource id (R.raw.<name>
). This gives you an InputStream
.I don't believe there's a big reason to prefer one over the other. The main difference is that you use the file name to access assets, while you use the automatically assigned resource id for resources. It's a matter of preference which one you like better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With