SlideShare a Scribd company logo
Introduction to OpenGL in
         Android
Agenda
•   OpenGL ES 2.0 – Brief Introduction
•   Getting started – Setting up the View
•   Drawing basic Shapes
•   Filling the shape with colors
•   Giving Life to Objects (Animation)
•   Applying texture to the shape
OpenGL ES
• OpenGL for Embedded Systems (ES)
• High performance 2D/3D Graphics for Mobile
  Devices
• Cross Platform Library
• Widely deployed Graphics Library
OpenGL ES 2.0
• Fixed Pipeline replaced by Programmable
  pipeline
• Provides more control to the programmer
Getting Started – Setting up the View
• Basics
  – GLSurfaceView
     • setRenderer()
  – GLSurfaceView.Renderer
     • onSurfaceCreated()
     • onSurfaceChanged()
     • onDrawFrame()
GLSurfaceView
/* add the following code snippet to add the OpenGL View to the layout*/



public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   // Create a GLSurfaceView instance and set it
    // as the ContentView for this Activity
   GLSurfaceView view = new GLSurfaceView(this);
   view.setRenderer(new ES2Renderer());
   setContentView(view);
}
GLSurfaceView.Renderer
public class ES2Renderer implements GLSurfaceView.Renderer {

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {

        // Set the background frame color
        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    }

    public void onDrawFrame(GL10 unused) {

        // Redraw background color
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
    }

    public void onSurfaceChanged(GL10 unused, int width, int height) {
      GLES20.glViewport(0, 0, width, height);
    }

}
Drawing Basic Shapes
Defining Shapes
• Vertex
• Edge
• Face

• Primitives
   –   GL_POINTS
   –   GL_LINE_STRIP
   –   GL_LINE_LOOP
   –   GL_LINES
   –   GL_TRIANGLES
   –   GL_TRIANGLE_STRIP
   –   GL_TRIANGLE_FAN
Defining the Shapes (Contd)
private void initShapes(){

      float squareCoords[] = {
         // X, Y, Z
                -1.0f, -1.0f, 0.0f, // Bottom Left
                1.0f, -1.0f, 0.0f, // Bottom Right
                1.0f, 1.0f, 0.0f, // Top Right
               -1.0f, 1.0f, 0.0f, // Top Left
      };

      // initialize vertex Buffer for square
      ByteBuffer vbb = ByteBuffer.allocateDirect(
           // (# of coordinate values * 4 bytes per float)
           squareCoords.length * 4);
      vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
      squareVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer
      squareVB.put(squareCoords); // add the coordinates to the FloatBuffer
      squareVB.position(0);           // set the buffer to read the first coordinate

  }
Shader Programs
• Vertex Shader
• Fragment Shader
• Loading the shader objects
• Attaching the Shader objects to Shader
  program
• Linking the program to create executable
  shader program
Shader Programs (Contd)
private final String vertexShaderCode =
     "attribute vec4 vertexPosition; n" +
     "void main(){         n" +
     " gl_Position = vertexPosition; n" +
     "}               n";

  private final String fragmentShaderCode =
    "precision mediump float; n" +
    "void main(){          n" +
    " gl_FragColor = vec4 (0.5, 0.5, 0. 5, 1.0); n" +
    "}                n";
Loading the shader
private int loadShader(int type, String shaderCode){

      // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
      // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
      int shader = GLES20.glCreateShader(type);

      // add the source code to the shader and compile it
      GLES20.glShaderSource(shader, shaderCode);
      GLES20.glCompileShader(shader);

      return shader;
  }
Compiling and Linking the Shader
                     programs
private int shaderProgram;
private int attributePositionHandle;

int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
shaderProgram = GLES20.glCreateProgram();       // create empty OpenGL Program
GLES20.glAttachShader(shaderProgram, vertexShader); // add the vertex shader to program
GLES20.glAttachShader(shaderProgram, fragmentShader); // add the fragment shader to program
GLES20.glLinkProgram(shaderProgram);          // creates OpenGL program executables

// get handle to the vertex shader's vertexPosition member
attributePositionHandle = GLES20.glGetAttribLocation(shaderProgram, "vertexPosition");
Drawing the Vertices
// Add program to OpenGL environment
GLES20.glUseProgram(shaderProgram);

// Prepare the square data
GLES20.glVertexAttribPointer(attributePositionHandle, 3, GLES20.GL_FLOAT, false, 12, squareVB);
GLES20.glEnableVertexAttribArray(attributePositionHandle);

// Draw the square
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
Making the square look like square on
              screen
       (Setting up the projection)
Setting up the projection
private int MVPMatrixHandle;
private float[] MVPMatrix = new float[16];
private float[] modelMatrix = new float[16];
private float[] viewMatrix = new float[16];
private float[] projectionMatrix = new float[16];
//--
GLES20.glViewport(0, 0, width, height);
float ratio = (float) width / height;
// this projection matrix is applied to object coodinates
// in the onDrawFrame() method
Matrix.frustumM(projectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);

//--
Matrix.setLookAtM(ViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
Applying the MVP matrix
private final String vertexShaderCode =
     // This matrix member variable provides a hook to manipulate
     // the coordinates of the objects that use this vertex shader
     "uniform mat4 MVPMatrix; n" +
     "attribute vec4 vertexPosition; n" +
     "void main(){          n" +
     // the matrix must be included as a modifier of gl_Position
     " gl_Position = MVPMatrix * vertexPosition; n" +
     "} n";

//--
MVPMatrixHandle = GLES20.glGetUniformLocation(shaderProgram, "MVPMatrix");
Applying the MVP matrix (Contd)

// Add program to OpenGL environment
GLES20.glUseProgram(shaderProgram);

// Prepare the square data
GLES20.glVertexAttribPointer(attributePositionHandle, 3, GLES20.GL_FLOAT, false,
    12, squareVB);
GLES20.glEnableVertexAttribArray(attributePositionHandle);

Matrix.multiplyMM(MVPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
GLES20.glUniformMatrix4fv(MVPMatrixHandle, 1, false, MVPMatrix, 0);

// Draw the square
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
Giving life to the objects
      (Animation)
// Add program to OpenGL environment
GLES20.glUseProgram(shaderProgram);

// Prepare the square data
GLES20.glVertexAttribPointer(attributePositionHandle, 3, GLES20.GL_FLOAT, false, 12, squareVB);
GLES20.glEnableVertexAttribArray(attributePositionHandle);

long time = SystemClock.uptimeMillis() % 4000L;
 float angle = 0.090f * ((int) time);
Matrix.setRotateM(modelMatrix, 0, angle, 0, 0, 1.0f);
Matrix.multiplyMM(MVPMatrix, 0, viewMatrix, 0, modelMatrix, 0);

Matrix.multiplyMM(MVPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
GLES20.glUniformMatrix4fv(MVPMatrixHandle, 1, false, MVPMatrix, 0);


// Draw the square
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
Applying Textures
Loading the texture
 int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureID = textures[0];
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);

InputStream is = mContext.getResources() .openRawResource(R.raw.robot);
Bitmap bitmap;
try {
   bitmap = BitmapFactory.decodeStream(is);
} finally {
   try {
      is.close();
   } catch(IOException e) {
      // Ignore.
   }
}
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
Texture coordinates
• UV Coordinates
• Mapping the texture coordinates to vertices
Mapping the texture coordinates
private final String vertexShaderCode =
      "uniform mat4 MVPMatrix; n" +
     "attribute vec4 vertexPosition; n" +
"attribute vec2 attributeTextureCoordinate;n" +
     "varying vec2 varyingTextureCoordinate;n" +
     "void main(){          n" +
" gl_Position = MVPMatrix * vertexPosition; n" +
 " varyingTextureCoord inate= attributeTextureCoordinate;n" +
     "} n";

private final String fragmentShaderCode =
     "precision mediump float;n" +
     "varying vec2 varyingTextureCoordinate;n" +
     "uniform sampler2D sTexture;n" +
     "void main() {n" +
     " gl_FragColor = texture2D(sTexture, varyingTextureCoordinate);n" +
     "}n";
Ad

Recommended

PPT
Introduction to open_gl_in_android
tamillarasan
 
PDF
OpenGL L06-Performance
Mohammad Shaker
 
PDF
OpenGL L07-Skybox and Terrian
Mohammad Shaker
 
PPTX
Trident International Graphics Workshop 2014 1/5
Takao Wada
 
PDF
OpenGL Starter L02
Mohammad Shaker
 
PDF
OpenGL Starter L01
Mohammad Shaker
 
PDF
Sceneform SDK на практиці - UA Mobile 2019
Eugene Kurko
 
PDF
Implementation of c string functions
mohamed sikander
 
PPTX
Pointer level 2
mohamed sikander
 
KEY
Exploring Canvas
Kevin Hoyt
 
PPTX
Arrays
mohamed sikander
 
PPT
C questions
mohamed sikander
 
PPTX
CSS Transitions, Transforms, Animations
Rob LaPlaca
 
PDF
Modeling Scenarios with Sequence Diagrams
Mustafa Isik
 
PDF
Pointer level 2
Mohammed Sikander
 
PDF
Implementing string
mohamed sikander
 
PDF
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Ontico
 
PDF
WebGL and three.js
Anton Narusberg
 
PPTX
WebGL and three.js - Web 3D Graphics
PSTechSerbia
 
PPT
CSS3 : Animation ,Transitions, Gradients
Jatin_23
 
PDF
Intro to Three.js
Kentucky JavaScript Users Group
 
PPTX
Introduction to three.js
yuxiang21
 
PPTX
MFC Brush
Razvan Raducanu, PhD
 
PPTX
Function basics
mohamed sikander
 
PDF
OpenGLES Android Graphics
Arvind Devaraj
 
PDF
Intro to OpenGL ES 2.0
Oleksandr Kozubets
 
PDF
Android open gl2_droidcon_2014
Droidcon Berlin
 
PPT
Open gles
sarmisthadas
 
PDF
GL Shading Language Document by OpenGL.pdf
shaikhshehzad024
 

More Related Content

What's hot (16)

PPTX
Pointer level 2
mohamed sikander
 
KEY
Exploring Canvas
Kevin Hoyt
 
PPTX
Arrays
mohamed sikander
 
PPT
C questions
mohamed sikander
 
PPTX
CSS Transitions, Transforms, Animations
Rob LaPlaca
 
PDF
Modeling Scenarios with Sequence Diagrams
Mustafa Isik
 
PDF
Pointer level 2
Mohammed Sikander
 
PDF
Implementing string
mohamed sikander
 
PDF
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Ontico
 
PDF
WebGL and three.js
Anton Narusberg
 
PPTX
WebGL and three.js - Web 3D Graphics
PSTechSerbia
 
PPT
CSS3 : Animation ,Transitions, Gradients
Jatin_23
 
PDF
Intro to Three.js
Kentucky JavaScript Users Group
 
PPTX
Introduction to three.js
yuxiang21
 
PPTX
MFC Brush
Razvan Raducanu, PhD
 
PPTX
Function basics
mohamed sikander
 
Pointer level 2
mohamed sikander
 
Exploring Canvas
Kevin Hoyt
 
C questions
mohamed sikander
 
CSS Transitions, Transforms, Animations
Rob LaPlaca
 
Modeling Scenarios with Sequence Diagrams
Mustafa Isik
 
Pointer level 2
Mohammed Sikander
 
Implementing string
mohamed sikander
 
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Ontico
 
WebGL and three.js
Anton Narusberg
 
WebGL and three.js - Web 3D Graphics
PSTechSerbia
 
CSS3 : Animation ,Transitions, Gradients
Jatin_23
 
Introduction to three.js
yuxiang21
 
Function basics
mohamed sikander
 

Similar to Introduction to open gl in android droidcon - slides (20)

PDF
OpenGLES Android Graphics
Arvind Devaraj
 
PDF
Intro to OpenGL ES 2.0
Oleksandr Kozubets
 
PDF
Android open gl2_droidcon_2014
Droidcon Berlin
 
PPT
Open gles
sarmisthadas
 
PDF
GL Shading Language Document by OpenGL.pdf
shaikhshehzad024
 
ZIP
Adobe AIR: Stage3D and AGAL
Daniel Freeman
 
PDF
XNA L11–Shaders Part 2
Mohammad Shaker
 
PPTX
Getting started with open gl es 2
matthewgalaviz
 
PDF
The fallowing program shows the simple transformation #define GLEW.pdf
arwholesalelors
 
PDF
iOS Visual F/X Using GLSL
Douglass Turner
 
PDF
WebGL - 3D in your Browser
Phil Reither
 
PDF
Hpg2011 papers kazakov
mistercteam
 
PDF
The Ring programming language version 1.7 book - Part 169 of 196
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.4 book - Part 119 of 185
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.2 book - Part 135 of 181
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.9 book - Part 177 of 210
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.4 book - Part 110 of 185
Mahmoud Samir Fayed
 
PPTX
GFX Part 6 - Introduction to Vertex and Fragment Shaders in OpenGL ES
Prabindh Sundareson
 
OpenGLES Android Graphics
Arvind Devaraj
 
Intro to OpenGL ES 2.0
Oleksandr Kozubets
 
Android open gl2_droidcon_2014
Droidcon Berlin
 
Open gles
sarmisthadas
 
GL Shading Language Document by OpenGL.pdf
shaikhshehzad024
 
Adobe AIR: Stage3D and AGAL
Daniel Freeman
 
XNA L11–Shaders Part 2
Mohammad Shaker
 
Getting started with open gl es 2
matthewgalaviz
 
The fallowing program shows the simple transformation #define GLEW.pdf
arwholesalelors
 
iOS Visual F/X Using GLSL
Douglass Turner
 
WebGL - 3D in your Browser
Phil Reither
 
Hpg2011 papers kazakov
mistercteam
 
The Ring programming language version 1.7 book - Part 169 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 119 of 185
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 135 of 181
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 177 of 210
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 110 of 185
Mahmoud Samir Fayed
 
GFX Part 6 - Introduction to Vertex and Fragment Shaders in OpenGL ES
Prabindh Sundareson
 
Ad

Recently uploaded (20)

PPTX
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
PDF
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
PDF
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
PDF
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
PDF
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
PDF
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PDF
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
PDF
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
PPTX
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
PDF
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
PDF
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
PPTX
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PDF
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Ad

Introduction to open gl in android droidcon - slides

  • 2. Agenda • OpenGL ES 2.0 – Brief Introduction • Getting started – Setting up the View • Drawing basic Shapes • Filling the shape with colors • Giving Life to Objects (Animation) • Applying texture to the shape
  • 3. OpenGL ES • OpenGL for Embedded Systems (ES) • High performance 2D/3D Graphics for Mobile Devices • Cross Platform Library • Widely deployed Graphics Library
  • 4. OpenGL ES 2.0 • Fixed Pipeline replaced by Programmable pipeline • Provides more control to the programmer
  • 5. Getting Started – Setting up the View • Basics – GLSurfaceView • setRenderer() – GLSurfaceView.Renderer • onSurfaceCreated() • onSurfaceChanged() • onDrawFrame()
  • 6. GLSurfaceView /* add the following code snippet to add the OpenGL View to the layout*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a GLSurfaceView instance and set it // as the ContentView for this Activity GLSurfaceView view = new GLSurfaceView(this); view.setRenderer(new ES2Renderer()); setContentView(view); }
  • 7. GLSurfaceView.Renderer public class ES2Renderer implements GLSurfaceView.Renderer { public void onSurfaceCreated(GL10 unused, EGLConfig config) { // Set the background frame color GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); } public void onDrawFrame(GL10 unused) { // Redraw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); } public void onSurfaceChanged(GL10 unused, int width, int height) { GLES20.glViewport(0, 0, width, height); } }
  • 9. Defining Shapes • Vertex • Edge • Face • Primitives – GL_POINTS – GL_LINE_STRIP – GL_LINE_LOOP – GL_LINES – GL_TRIANGLES – GL_TRIANGLE_STRIP – GL_TRIANGLE_FAN
  • 10. Defining the Shapes (Contd) private void initShapes(){ float squareCoords[] = { // X, Y, Z -1.0f, -1.0f, 0.0f, // Bottom Left 1.0f, -1.0f, 0.0f, // Bottom Right 1.0f, 1.0f, 0.0f, // Top Right -1.0f, 1.0f, 0.0f, // Top Left }; // initialize vertex Buffer for square ByteBuffer vbb = ByteBuffer.allocateDirect( // (# of coordinate values * 4 bytes per float) squareCoords.length * 4); vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order squareVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer squareVB.put(squareCoords); // add the coordinates to the FloatBuffer squareVB.position(0); // set the buffer to read the first coordinate }
  • 11. Shader Programs • Vertex Shader • Fragment Shader • Loading the shader objects • Attaching the Shader objects to Shader program • Linking the program to create executable shader program
  • 12. Shader Programs (Contd) private final String vertexShaderCode = "attribute vec4 vertexPosition; n" + "void main(){ n" + " gl_Position = vertexPosition; n" + "} n"; private final String fragmentShaderCode = "precision mediump float; n" + "void main(){ n" + " gl_FragColor = vec4 (0.5, 0.5, 0. 5, 1.0); n" + "} n";
  • 13. Loading the shader private int loadShader(int type, String shaderCode){ // create a vertex shader type (GLES20.GL_VERTEX_SHADER) // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER) int shader = GLES20.glCreateShader(type); // add the source code to the shader and compile it GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); return shader; }
  • 14. Compiling and Linking the Shader programs private int shaderProgram; private int attributePositionHandle; int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode); shaderProgram = GLES20.glCreateProgram(); // create empty OpenGL Program GLES20.glAttachShader(shaderProgram, vertexShader); // add the vertex shader to program GLES20.glAttachShader(shaderProgram, fragmentShader); // add the fragment shader to program GLES20.glLinkProgram(shaderProgram); // creates OpenGL program executables // get handle to the vertex shader's vertexPosition member attributePositionHandle = GLES20.glGetAttribLocation(shaderProgram, "vertexPosition");
  • 15. Drawing the Vertices // Add program to OpenGL environment GLES20.glUseProgram(shaderProgram); // Prepare the square data GLES20.glVertexAttribPointer(attributePositionHandle, 3, GLES20.GL_FLOAT, false, 12, squareVB); GLES20.glEnableVertexAttribArray(attributePositionHandle); // Draw the square GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
  • 16. Making the square look like square on screen (Setting up the projection)
  • 17. Setting up the projection private int MVPMatrixHandle; private float[] MVPMatrix = new float[16]; private float[] modelMatrix = new float[16]; private float[] viewMatrix = new float[16]; private float[] projectionMatrix = new float[16]; //-- GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // this projection matrix is applied to object coodinates // in the onDrawFrame() method Matrix.frustumM(projectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7); //-- Matrix.setLookAtM(ViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
  • 18. Applying the MVP matrix private final String vertexShaderCode = // This matrix member variable provides a hook to manipulate // the coordinates of the objects that use this vertex shader "uniform mat4 MVPMatrix; n" + "attribute vec4 vertexPosition; n" + "void main(){ n" + // the matrix must be included as a modifier of gl_Position " gl_Position = MVPMatrix * vertexPosition; n" + "} n"; //-- MVPMatrixHandle = GLES20.glGetUniformLocation(shaderProgram, "MVPMatrix");
  • 19. Applying the MVP matrix (Contd) // Add program to OpenGL environment GLES20.glUseProgram(shaderProgram); // Prepare the square data GLES20.glVertexAttribPointer(attributePositionHandle, 3, GLES20.GL_FLOAT, false, 12, squareVB); GLES20.glEnableVertexAttribArray(attributePositionHandle); Matrix.multiplyMM(MVPMatrix, 0, projectionMatrix, 0, viewMatrix, 0); GLES20.glUniformMatrix4fv(MVPMatrixHandle, 1, false, MVPMatrix, 0); // Draw the square GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
  • 20. Giving life to the objects (Animation)
  • 21. // Add program to OpenGL environment GLES20.glUseProgram(shaderProgram); // Prepare the square data GLES20.glVertexAttribPointer(attributePositionHandle, 3, GLES20.GL_FLOAT, false, 12, squareVB); GLES20.glEnableVertexAttribArray(attributePositionHandle); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); Matrix.setRotateM(modelMatrix, 0, angle, 0, 0, 1.0f); Matrix.multiplyMM(MVPMatrix, 0, viewMatrix, 0, modelMatrix, 0); Matrix.multiplyMM(MVPMatrix, 0, projectionMatrix, 0, viewMatrix, 0); GLES20.glUniformMatrix4fv(MVPMatrixHandle, 1, false, MVPMatrix, 0); // Draw the square GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
  • 23. Loading the texture int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTextureID = textures[0]; GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT); InputStream is = mContext.getResources() .openRawResource(R.raw.robot); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle();
  • 24. Texture coordinates • UV Coordinates • Mapping the texture coordinates to vertices
  • 25. Mapping the texture coordinates
  • 26. private final String vertexShaderCode = "uniform mat4 MVPMatrix; n" + "attribute vec4 vertexPosition; n" + "attribute vec2 attributeTextureCoordinate;n" + "varying vec2 varyingTextureCoordinate;n" + "void main(){ n" + " gl_Position = MVPMatrix * vertexPosition; n" + " varyingTextureCoord inate= attributeTextureCoordinate;n" + "} n"; private final String fragmentShaderCode = "precision mediump float;n" + "varying vec2 varyingTextureCoordinate;n" + "uniform sampler2D sTexture;n" + "void main() {n" + " gl_FragColor = texture2D(sTexture, varyingTextureCoordinate);n" + "}n";