Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store shader code in Android app

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?

like image 351
anhoppe Avatar asked Dec 19 '14 21:12

anhoppe


People also ask

What is shaders in files on an android?

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.

How do you create a function in GLSL?

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.


1 Answers

There are two main options:

  • Store them as text files in the assets folder of your project. To load the shader:

    1. Get the AssetManager with the getAssets() method of the context.
    2. Call open() on the AssetManager, passing in the file name of the shader. This gives you an InputStream.
    3. Read the shader code from the InputStream, and store it in a String.
    4. Call close() on the InputStream.
  • Store them in the res/raw folder of your project. To load the shader:

    1. Get the Resources with the getResources() method of the context.
    2. Call openRawResource() on the Resources, passing in the resource id (R.raw.<name>). This gives you an InputStream.
    3. (same as above)
    4. (same as above)

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.

like image 197
Reto Koradi Avatar answered Dec 06 '22 23:12

Reto Koradi