Android OpenGL ES Application (i)

Source: Internet
Author: User


OpenGL has become a 3D "standard" because it can cross the platform, the interface is also rich, almost the majority of mobile 3D games are related to OpenGL.

And, of course, Microsoft has direct X but it can only be used on Microsoft platforms.

OpenGL Bottom is a C + + implementation, and Java is used in a packaged class library. Android offers the following interface packs that can be used, basically to meet the requirements of 3D technology.

The Android platform uses a subset of OpenGL ES to process images, and now OpenGL ES is basically 2.0, rarely used for 1.0, and 3.0 is not yet popular.


First write to determine if the Android device supports OpenGL 2.0.

Glhelper.java adds a code method that determines whether the 2.0 version is supported.

public static Boolean enableOpenGL2 (Activity Act) {final Activitymanager mg = (Activitymanager) act.getsystemservice ( Context.activity_service); Configurationinfo configuration = Mg.getdeviceconfigurationinfo (); Boolean B = Configuration.reqglesversion >= 0x20000); return b;}

We need to expand Android.opengl.GLSurfaceView this class, let the image drawn on the surfaceview above, see the source code found this class is actually extended Surfaceview did write encapsulation.


public class Myopenglview extends Glsurfaceview {//This class is first empty, this time there is not much code public Myopenglview (context context) {Super ( context);} Public Myopenglview (context context, AttributeSet Attrs) {Super (context, attrs);}}


We encapsulate the various methods of processing.

public class Gldata {public Gldata () {}public static float[] Singeltriangles = {//defines 2 triangles, forming a square because OpenGL ES can only be points, lines, and triangles -0.3f, -0.3f,  0.3f, 0.3f, -0.3f, 0.3f, -0.3f, -0.3f, 0.3f, -0.3f,  0.3f, 0.3f};}

OpenGL es within the range of the Android coordinate system is [ -1,1]




Write 2 simple vertex shaders and fragment color shaders.


public class Glscript {public Glscript () {}public static final String vertex1 = "attribute vec4 mposition;\n" + "void Main ( \ n "+" {\ n "+" gl_position=mposition;\n "+"}\n ";p ublic static final String fragment1 =" Precision mediump float;\n "+" unif ORM VEC4 mcolor;\n "+" void Main () {gl_fragcolor=mcolor;\n} ";}

VEC4 Mposition This representation defines a 4-component (X,Y,Z,W) vertex, which is then paid to the gl_position built-in variable, and OpenGL compiles and processes automatically.
VEC4 Mcolor This expression defines a color component Rgba, and the last one is transparency, which is red-green-blue.

The scripting language is the core of OpenGL ES, and many of the rendering effects require script processing.

Glhelper.java Add a code method for compiling the script.

public static int Compilescript (int type, String script) {int ObjID  = Gles20.glcreateshader (type);//Create a Shader object, The type represents the vertex shader and fragment shader if (ObjID = = 0) {//0 indicates an error    return 0;} Gles20.glshadersource (ObjID, script); Pass the script code to the OpenGL engine Gles20.glcompileshader (ObjID); Start compiling int[] status = new Int[1]; Gles20.glgetshaderiv (ObjID, Gles20.gl_compile_status, STATUS, 0); See if the compilation results have errors. LOG.D ("OPENGL", "Compilescript status info:" + gles20.glgetshaderinfolog (ObjID)); if (status[0] = = 0) { Gles20.gldeleteshader (ObjID);//Error we delete this object. LOG.E ("OPENGL", "Error Compile script:" + script); return 0;} return ObjID;}


If the compilation succeeds we begin to correlate OpenGL ES programs.


public static int Linkgl () {int programid = Gles20.glcreateprogram ();//Create a program if (ProgramID = = 0) {   log.e ("OPENGL", "Er ROR Create Link Program ");   return 0;} return programid;} public static int Linkattach (int vertexsharder,int fragmentsharder) {int programid = LINKGL (); Gles20.glattachshader (ProgramID, Vertexsharder); And shaders are associated with Gles20.glattachshader (ProgramID, Fragmentsharder);//and shaders are associated gles20.gllinkprogram (PROGRAMID); Link program int status[] = new INT[1]; GLES20.GLGETPROGRAMIV (ProgramID, Gles20.gl_link_status, STATUS, 0); This place is the same as checking for errors to occur. LOG.D ("OpenGL", "Linkattach link status is" + Gles20.glgetprograminfolog (ProgramID)), if (status[0] = = 0) {log.e ("OpenGL" , "link status is error."); Gles20.gldeleteprogram (programid); return 0;} return programid;}


Finally we verify that the program has errors

public static Boolean checkprogram (int programid) {gles20.glvalidateprogram (programid); int status[] = new INT[1]; GLES20.GLGETPROGRAMIV (Programid,gles20.gl_validate_status, status,0), if (status[0] = = 0) {log.e ("OPENGL", "program is Error "); return false;} return true;}

The above code is written in Glhelper.java,

We add the code to the rendering class renderer


Rendering class

public class Myopenglrenderer implements Renderer {public static floatbuffer verdatabuffer;int colorlocation; int Positio Nlocation;p ublic myopenglrenderer () {//Request direct memory space and use native byte sequence Verdatabuffer = Bytebuffer.allocatedirect (4 * GLData.singelTriangles.length). Order (Byteorder.nativeorder ()). Asfloatbuffer (); Verdatabuffer.put (  Gldata.singeltriangles); This is a square, and so will post code. } @Overridepublic void Ondrawframe (GL10 arg0) {//This method will continually redraw gles20.glclear (gles20.gl_color_buffer_bit); gles20.gluniform4f (Colorlocation, 0f, 0f, 0F, 0f); Here is black, color will pass to <span style= "font-family:arial, Helvetica, Sans-serif;" >colorlocation</span>gles20.gldrawarrays (gles20.gl_triangles, 0, 6);//Draw a triangle with 6 vertices so start with 0, 6}@ overridepublic void onsurfacechanged (GL10 arg0, int w, int h) {gles20.glviewport (0, 0, W, h);} @Overridepublic void onsurfacecreated (GL10 arg0, EGLConfig arg1) {gles20.glclearcolor (1F, 1F, 1F, 0.0F);// The following code is organized with the Glhelper class we have written. int vertexsharder = Glhelper.compilescript (Gles20.gl_vertex_shader, GLSCRIPT.VERTEX1); int fragmentsharder = Glhelper.compilescript (Gles20.gl_fragment_shader, glscript.fragment1); int programId = Glhelper.linkattach (Vertexsharder, Fragmentsharder); Boolean IsOK = Glhelper.checkprogram (ProgramID); if (IsOK) {LOG.D ("", "start draw ......"); Gles20.gluseprogram (ProgramID); We started using this program colorlocation = gles20.glgetuniformlocation (ProgramID, "Mcolor");//Get variable position, can be understood as memory address, OpenGL will fetch data in this address Positionlocation = Gles20.glgetattriblocation (ProgramID, "mposition"); Verdatabuffer.position (0);//Data Start-read Gles20.glvertexattribpointer (positionlocation, 2, Gles20.gl_float, False, 0, Verdatabuffer);//This place associates the vertex data with the variable Gles20.glenablevertexattribarray (positionlocation);//This place makes it possible to use the vertex array}}}

The last activity part of the code.

Private Myopenglview Glview;private boolean openglenable, @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (Savedinstancestate), if (GLHELPER.ENABLEOPENGL2 (this)) {openglenable = true;} LOG.D ("", "OpenGL is Enable:" + openglenable); Glview = new Myopenglview (this); Glview.seteglcontextclientversion (2);// OpenGL ES 2.0glview.setrenderer (New Myopenglrenderer ()) can be used; Setcontentview (Glview);}




The result of the operation is simply a square in the middle.

The OpenGL ES entry is relatively complex, because the function calls the Java when it is used, and the C + + library is not the same

3D Complex is more than just a coordinate z, there are a lot of rendering techniques.


Engineering Structure:




Android OpenGL ES Application (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.