SlideShare una empresa de Scribd logo
1 de 26
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";

Más contenido relacionado

La actualidad más candente

Exploring Canvas
Exploring CanvasExploring Canvas
Exploring CanvasKevin Hoyt
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations Rob LaPlaca
 
Modeling Scenarios with Sequence Diagrams
Modeling Scenarios with Sequence DiagramsModeling Scenarios with Sequence Diagrams
Modeling Scenarios with Sequence DiagramsMustafa Isik
 
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...Ontico
 
WebGL and three.js - Web 3D Graphics
WebGL and three.js - Web 3D Graphics WebGL and three.js - Web 3D Graphics
WebGL and three.js - Web 3D Graphics PSTechSerbia
 
CSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, GradientsCSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, GradientsJatin_23
 
Introduction to three.js
Introduction to three.jsIntroduction to three.js
Introduction to three.jsyuxiang21
 

La actualidad más candente (16)

Pointer level 2
Pointer   level 2Pointer   level 2
Pointer level 2
 
Exploring Canvas
Exploring CanvasExploring Canvas
Exploring Canvas
 
Arrays
ArraysArrays
Arrays
 
C questions
C questionsC questions
C questions
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations
 
Modeling Scenarios with Sequence Diagrams
Modeling Scenarios with Sequence DiagramsModeling Scenarios with Sequence Diagrams
Modeling Scenarios with Sequence Diagrams
 
Pointer level 2
Pointer   level 2Pointer   level 2
Pointer level 2
 
Implementing string
Implementing stringImplementing string
Implementing string
 
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
Портируем существующее Web-приложение в виртуальную реальность / Денис Радин ...
 
WebGL and three.js
WebGL and three.jsWebGL and three.js
WebGL and three.js
 
WebGL and three.js - Web 3D Graphics
WebGL and three.js - Web 3D Graphics WebGL and three.js - Web 3D Graphics
WebGL and three.js - Web 3D Graphics
 
CSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, GradientsCSS3 : Animation ,Transitions, Gradients
CSS3 : Animation ,Transitions, Gradients
 
Intro to Three.js
Intro to Three.jsIntro to Three.js
Intro to Three.js
 
Introduction to three.js
Introduction to three.jsIntroduction to three.js
Introduction to three.js
 
MFC Brush
MFC BrushMFC Brush
MFC Brush
 
Function basics
Function basicsFunction basics
Function basics
 

Similar a Introduction to open gl in android droidcon - slides

GL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfGL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfshaikhshehzad024
 
Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScriptersgerbille
 
How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?Flutter Agency
 
Bs webgl소모임004
Bs webgl소모임004Bs webgl소모임004
Bs webgl소모임004Seonki Paik
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3Droxlu
 
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeksBeginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeksJinTaek Seo
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLgerbille
 
Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5firenze-gtug
 
Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Korhan Bircan
 
Deep dive into deeplearn.js
Deep dive into deeplearn.jsDeep dive into deeplearn.js
Deep dive into deeplearn.jsKai Sasaki
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL roxlu
 
Richard Salter: Using the Titanium OpenGL Module
Richard Salter: Using the Titanium OpenGL ModuleRichard Salter: Using the Titanium OpenGL Module
Richard Salter: Using the Titanium OpenGL ModuleAxway Appcelerator
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScriptJungsoo Nam
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsNaman Dwivedi
 
Getting Started with WebGL
Getting Started with WebGLGetting Started with WebGL
Getting Started with WebGLChihoon Byun
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-CNissan Tsafrir
 

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

GL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdfGL Shading Language Document by OpenGL.pdf
GL Shading Language Document by OpenGL.pdf
 
Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScripters
 
How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?How to Create Custom Shaders in Flutter?
How to Create Custom Shaders in Flutter?
 
Bs webgl소모임004
Bs webgl소모임004Bs webgl소모임004
Bs webgl소모임004
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
COLLADA & WebGL
COLLADA & WebGLCOLLADA & WebGL
COLLADA & WebGL
 
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeksBeginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
 
Leaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGLLeaving Flatland: getting started with WebGL
Leaving Flatland: getting started with WebGL
 
Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5Unconventional webapps with gwt:elemental & html5
Unconventional webapps with gwt:elemental & html5
 
Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
 
Deep dive into deeplearn.js
Deep dive into deeplearn.jsDeep dive into deeplearn.js
Deep dive into deeplearn.js
 
openFrameworks 007 - GL
openFrameworks 007 - GL openFrameworks 007 - GL
openFrameworks 007 - GL
 
Richard Salter: Using the Titanium OpenGL Module
Richard Salter: Using the Titanium OpenGL ModuleRichard Salter: Using the Titanium OpenGL Module
Richard Salter: Using the Titanium OpenGL Module
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Games 3 dl4-example
Games 3 dl4-exampleGames 3 dl4-example
Games 3 dl4-example
 
Android RenderScript
Android RenderScriptAndroid RenderScript
Android RenderScript
 
Enhancing UI/UX using Java animations
Enhancing UI/UX using Java animationsEnhancing UI/UX using Java animations
Enhancing UI/UX using Java animations
 
Getting Started with WebGL
Getting Started with WebGLGetting Started with WebGL
Getting Started with WebGL
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 

Último

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

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";