Bootstrap Android OpenGL 2.0

Wolox Engineering
Wolox
Published in
2 min readApr 14, 2016

OpenGL is a powerful API to get the juice out of your Android’s GPU in order to develop a wide variety of graphic applications, ranging from games to social apps.

However, it’s not so easy to get it up and running. Google provides some documentation and tutorials regarding OpenGL 1.0 and 2.0 here. The tutorials contain some bugs which may give you a headache if you are looking for code that “just works”.

Setting up the environment

First, you need a view to render graphic content from OpenGL. You can extend Android’s GLSurfaceView and configure the OpenGL version and sizes.

This view won’t render anything without a Renderer. Let’s implement a basic Renderer which will clear the screen and set up the camera.

Notice the GLCameraOptions class: this is just a Util class which can hold all the configuration parameters for our camera and depth range values. This way, we can pass this information to our Renderer instead of hard-coding it.

See also: AWS Lambda + SimpleDb + Mandrill

Don’t forget to add the OpenGL version to the manifest:

Now we are ready to get the party started. First, we should include a BasicGLView on our layout:

And initialize it with a renderer on our fragment:

This code should compile and render a blue screen.

Fifty Shaders of Gray

Before rendering objects into our scene, we will implement some code to compile shaders.

First, we need to have the actual shaders code somewhere. Let’s add those as constants to a Shaders class, together with a method to compile them:

Party Time

The time has come to actually render your first object. To make things easier, we will write generic code to render a model (using vertex and index buffers).

Noticed the GLHelper.checkGlError method? This method will provide us an easy way to check for errors after executing any OpenGL method:

See also: Mocking API & Server Behavior: Pros and Cons When Building a Stage Environment for QA Testing

We defined two abstract methods which we should override on our model. Let’s do that with a simple Triangle model:

Everything is set up to add some models to our scene. Let’s add some code to our basic renderer to draw models:

Now in our fragment we can simply instantiate and add some triangles:

Voilà! This will result in our black scene with some blue and green triangles. You are now ready to define more complex models.

Stay tuned! I’ll follow up with a post on shaders and textures in the near future.

Posted by Federico Ramundo, Android Technical Leader at Wolox, @FedericoRamundo, (federico.ramundo@wolox.com.ar)

www.wolox.com.ar

--

--