To generate more powerful graphic effect, OpenGL ES(OpenGL for Embeded System) provides modern graphic processing api.
I will make a simple GLSurfaceView(pre-defined view class to use opengl in android) and Renderer to visualize effect only using fragment shader. Once I build this successfully, I can refer some interesting glsl codes in online like glsl sandbox or shader frog.
1. Manifest Setting
I will use gles 3.1 version. Way to checking of supported version is in developer docs.
<uses-feature android:glEsVersion="0x00030001" android:required="true" />
<application ... />
2. Custom GLSurfaceView Class
private lateinit var renderer:MyRenderer
override fun setRenderer(renderer: Renderer) {
super.setRenderer(renderer)
this.renderer = renderer as MyRenderer
}
}
3. Custom Renderer
Most of Renderer's codes are boilerplate code. Shader compile and attach processes are explained in dev docs. I will add tiny additional code.
...
private var hMouse = 0
private var hTime = 0
private var hResolution = 0
private var width = 0
private var height = 0
var mouseX : Float = 0f
var mouseY : Float = 0f
...
override fun onDrawFrame(gl: GL10?) {
...
GLES31.glClear(GLES31.GL_DEPTH_BUFFER_BIT or GLES31.GL_COLOR_BUFFER_BIT)
val time = SystemClock.uptimeMillis() % 10000L
GLES31.glUniform1f(hTime,(time/1000f))
GLES31.glUniform2f(hResolution,this.width.toFloat(),this.height.toFloat())
GLES31.glUniform2f(hMouse,-1f+(2*this.mouseX/this.width),1f-(2*this.mouseY/this.height))
GLES31.glUniformMatrix4fv(hScale,1,false, mScale,0)
...
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
...
this.width = width
this.height = height
...
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
...
hTime = GLES31.glGetUniformLocation(hProgram,"time")
hResolution = GLES31.glGetUniformLocation(hProgram,"resolution")
hMouse = GLES31.glGetUniformLocation(hProgram,"mouse")
...
}
Almost done. Override onTouchEvent in view class to pass the mouse location to renderer(mouseX,mouseY variables at above code).
this.renderer.mouseX = event.x
this.renderer.mouseY = event.y
return super.onTouchEvent(event)
}
4. etc
For vertex Shader, Any shape is possible. To see the fragment shader code's effect fully, use Square Shape.
And find some code in online, test and make own code.