1 page.title=OpenGL ES 1.0 2 parent.title=Tutorials 3 parent.link=../../browser.html?tag=tutorial 4 @jd:body 5 6 7 <div id="qv-wrapper"> 8 <div id="qv"> 9 <h2>In this document</h2> 10 11 <ol> 12 <li><a href="#creating">Create an Activity with GLSurfaceView</a></li> 13 <li> 14 <a href="#drawing">Draw a Shape on GLSurfaceView</a> 15 <ol> 16 <li><a href="#define-triangle">Define a Triangle</a></li> 17 <li><a href="#draw-triangle">Draw the Triangle</a></li> 18 </ol> 19 </li> 20 <li><a href="#projection-and-views">Apply Projection and Camera Views</a></li> 21 <li><a href="#motion">Add Motion</a></li> 22 <li><a href="#touch">Respond to Touch Events</a></li> 23 </ol> 24 <h2 id="code-samples-list">Related Samples</h2> 25 <ol> 26 <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ 27 index.html">API Demos - graphics</a></li> 28 <li><a 29 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ 30 GLSurfaceViewActivity.html">OpenGL ES 1.0 Sample</a></li> 31 <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ 32 TouchRotateActivity.html">TouchRotateActivity</a></li> 33 </ol> 34 <h2>See also</h2> 35 <ol> 36 <li><a href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a></li> 37 <li><a href="{@docRoot}resources/tutorials/opengl/opengl-es20.html">OpenGL 38 ES 2.0</a></li> 39 </ol> 40 </div> 41 </div> 42 43 <p>This tutorial shows you how to create a simple Android application that uses the OpenGL ES 1.0 44 API to perform some basic graphics operations. You'll learn how to:</p> 45 46 <ul> 47 <li>Create an activity using {@link android.opengl.GLSurfaceView} and {@link 48 android.opengl.GLSurfaceView.Renderer}</li> 49 <li>Create and draw a graphic object</li> 50 <li>Define a projection to correct for screen geometry</li> 51 <li>Define a camera view</li> 52 <li>Rotate a graphic object</li> 53 <li>Make graphics touch-interactive</li> 54 </ul> 55 56 <p>The Android framework supports both the OpenGL ES 1.0/1.1 and OpenGL ES 2.0 APIs. You should 57 carefully consider which version of the OpenGL ES API (1.0/1.1 or 2.0) is most appropriate for your 58 needs. For more information, see 59 <a href="{@docRoot}guide/topics/graphics/opengl.html#choosing-version">Choosing an OpenGL API 60 Version</a>. If you would prefer to use OpenGL ES 2.0, see the <a 61 href="{@docRoot}resources/tutorials/opengl/opengl-es20.jd">OpenGL ES 2.0 tutorial</a>.</p> 62 63 <p>Before you start, you should understand how to create a basic Android application. If you do not 64 know how to create an app, follow the <a href="{@docRoot}resources/tutorials/hello-world.html">Hello 65 World Tutorial</a> to familiarize yourself with the process.</p> 66 67 <h2 id="creating">Create an Activity with GLSurfaceView</h2> 68 69 <p>To get started using OpenGL, you must implement both a {@link android.opengl.GLSurfaceView} and a 70 {@link android.opengl.GLSurfaceView.Renderer}. The {@link android.opengl.GLSurfaceView} is the main 71 view type for applications that use OpenGL and the {@link android.opengl.GLSurfaceView.Renderer} 72 controls what is drawn within that view. (For more information about these classes, see the <a 73 href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document.)</p> 74 75 <p>To create an activity using {@code GLSurfaceView}:</p> 76 77 <ol> 78 <li>Start a new Android project that targets Android 1.6 (API Level 4) or higher. 79 </li> 80 <li>Name the project <strong>HelloOpenGLES10</strong> and make sure it includes an activity called 81 {@code HelloOpenGLES10}. 82 </li> 83 <li>Modify the {@code HelloOpenGLES10} class as follows: 84 <pre> 85 package com.example.android.apis.graphics; 86 87 import android.app.Activity; 88 import android.content.Context; 89 import android.opengl.GLSurfaceView; 90 import android.os.Bundle; 91 92 public class HelloOpenGLES10 extends Activity { 93 94 private GLSurfaceView mGLView; 95 96 @Override 97 public void onCreate(Bundle savedInstanceState) { 98 super.onCreate(savedInstanceState); 99 100 // Create a GLSurfaceView instance and set it 101 // as the ContentView for this Activity. 102 mGLView = new HelloOpenGLES10SurfaceView(this); 103 setContentView(mGLView); 104 } 105 106 @Override 107 protected void onPause() { 108 super.onPause(); 109 // The following call pauses the rendering thread. 110 // If your OpenGL application is memory intensive, 111 // you should consider de-allocating objects that 112 // consume significant memory here. 113 mGLView.onPause(); 114 } 115 116 @Override 117 protected void onResume() { 118 super.onResume(); 119 // The following call resumes a paused rendering thread. 120 // If you de-allocated graphic objects for onPause() 121 // this is a good place to re-allocate them. 122 mGLView.onResume(); 123 } 124 } 125 126 class HelloOpenGLES10SurfaceView extends GLSurfaceView { 127 128 public HelloOpenGLES10SurfaceView(Context context){ 129 super(context); 130 131 // Set the Renderer for drawing on the GLSurfaceView 132 setRenderer(new HelloOpenGLES10Renderer()); 133 } 134 } 135 </pre> 136 <p class="note"><strong>Note:</strong> You will get a compile error for the {@code 137 HelloOpenGLES10Renderer} class reference. That's expected; you will fix this error in the next step. 138 </p> 139 140 <p>As shown above, this activity uses a single {@link android.opengl.GLSurfaceView} for its 141 view. Notice that this activity implements crucial lifecycle callbacks for pausing and resuming its 142 work.</p> 143 144 <p>The {@code HelloOpenGLES10SurfaceView} class in this example code above is just a thin wrapper 145 for an instance of {@link android.opengl.GLSurfaceView} and is not strictly necessary for this 146 example. However, if you want your application to monitor and respond to touch screen 147 events—and we are guessing you do—you must extend {@link android.opengl.GLSurfaceView} 148 to add touch event listeners, which you will learn how to do in the <a href="#touch">Reponding to 149 Touch Events</a> section.</p> 150 151 <p>In order to draw graphics in the {@link android.opengl.GLSurfaceView}, you must define an 152 implementation of {@link android.opengl.GLSurfaceView.Renderer}. In the next step, you create 153 a renderer class to complete this OpenGL application.</p> 154 </li> 155 156 <li>Create a new file for the following class {@code HelloOpenGLES10Renderer}, which implements 157 the {@link android.opengl.GLSurfaceView.Renderer} interface: 158 159 <pre> 160 package com.example.android.apis.graphics; 161 162 import javax.microedition.khronos.egl.EGLConfig; 163 import javax.microedition.khronos.opengles.GL10; 164 165 import android.opengl.GLSurfaceView; 166 167 public class HelloOpenGLES10Renderer implements GLSurfaceView.Renderer { 168 169 public void onSurfaceCreated(GL10 gl, EGLConfig config) { 170 // Set the background frame color 171 gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); 172 } 173 174 public void onDrawFrame(GL10 gl) { 175 // Redraw background color 176 gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); 177 } 178 179 public void onSurfaceChanged(GL10 gl, int width, int height) { 180 gl.glViewport(0, 0, width, height); 181 } 182 183 } 184 </pre> 185 <p>This minimal implementation of {@link android.opengl.GLSurfaceView.Renderer} provides the 186 code structure needed to use OpenGL drawing methods: 187 <ul> 188 <li>{@link 189 android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, 190 javax.microedition.khronos.egl.EGLConfig) onSurfaceCreated()} is called once to set up the 191 {@link android.opengl.GLSurfaceView} 192 environment.</li> 193 <li>{@link 194 android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.khronos.opengles.GL10) 195 onDrawFrame()} is called for each redraw of the {@link 196 android.opengl.GLSurfaceView}.</li> 197 <li>{@link 198 android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition.khronos.opengles.GL10, 199 int, int) onSurfaceChanged()} is called if the geometry of the {@link 200 android.opengl.GLSurfaceView} changes, for example when the device's screen orientation 201 changes.</li> 202 </ul> 203 </p> 204 <p>For more information about these methods, see the <a 205 href="{@docRoot}guide/topics/graphics/opengl.html">3D with OpenGL</a> document. 206 </p> 207 </li> 208 </ol> 209 210 <p>The code example above creates a simple Android application that displays a grey screen using 211 OpenGL ES 1.0 calls. While this application does not do anything very interesting, by creating these 212 classes, you have layed the foundation needed to start drawing graphic elements with OpenGL ES 213 1.0.</p> 214 215 <p>If you are familiar with the OpenGL ES APIs, these classes should give you enough information 216 to use the OpenGL ES 1.0 API and create graphics. However, if you need a bit more help getting 217 started with OpenGL, head on to the next sections for a few more hints.</p> 218 219 <h2 id="drawing">Draw a Shape on GLSurfaceView</h2> 220 221 <p>Once you have implemented a {@link android.opengl.GLSurfaceView.Renderer}, the next step is to 222 draw something with it. This section shows you how to define and draw a triangle.</p> 223 224 <h3 id="define-triangle">Define a Triangle</h3> 225 226 <p>OpenGL allows you to define objects using coordinates in three-dimensional space. So, before you 227 can draw a triangle, you must define its coordinates. In OpenGL, the typical way to do this is to 228 define a vertex array for the coordinates.</p> 229 230 <p>By default, OpenGL ES assumes a coordinate system where [0,0,0] (X,Y,Z) specifies the center of 231 the {@link android.opengl.GLSurfaceView} frame, [1,1,0] is the top right corner of the frame and 232 [-1,-1,0] is bottom left corner of the frame.</p> 233 234 <p>To define a vertex array for a triangle:</p> 235 236 <ol> 237 <li>In your {@code HelloOpenGLES10Renderer} class, add new member variable to contain the 238 vertices of a triangle shape: 239 <pre> 240 private FloatBuffer triangleVB; 241 </pre> 242 </li> 243 244 <li>Create a method, {@code initShapes()} which populates this member variable: 245 <pre> 246 private void initShapes(){ 247 248 float triangleCoords[] = { 249 // X, Y, Z 250 -0.5f, -0.25f, 0, 251 0.5f, -0.25f, 0, 252 0.0f, 0.559016994f, 0 253 }; 254 255 // initialize vertex Buffer for triangle 256 ByteBuffer vbb = ByteBuffer.allocateDirect( 257 // (# of coordinate values * 4 bytes per float) 258 triangleCoords.length * 4); 259 vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order 260 triangleVB = vbb.asFloatBuffer(); // create a floating point buffer from the ByteBuffer 261 triangleVB.put(triangleCoords); // add the coordinates to the FloatBuffer 262 triangleVB.position(0); // set the buffer to read the first coordinate 263 264 } 265 </pre> 266 <p>This method defines a two-dimensional triangle with three equal sides.</p> 267 </li> 268 <li>Modify your {@code onSurfaceCreated()} method to initialize your triangle: 269 <pre> 270 public void onSurfaceCreated(GL10 gl, EGLConfig config) { 271 272 // Set the background frame color 273 gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); 274 275 // initialize the triangle vertex array 276 initShapes(); 277 } 278 </pre> 279 <p class="caution"><strong>Caution:</strong> Shapes and other static objects should be initialized 280 once in your {@code onSurfaceCreated()} method for best performance. Avoid initializing the 281 new objects in {@code onDrawFrame()}, as this causes the system to re-create the objects 282 for every frame redraw and slows down your application. 283 </p> 284 </li> 285 286 </ol> 287 288 <p>You have now defined a triangle shape, but if you run the application, nothing appears. What?! 289 You also have to tell OpenGL to draw the triangle, which you'll do in the next section. 290 </p> 291 292 293 <h3 id="draw-triangle">Draw the Triangle</h3> 294 295 <p>Before you can draw your triangle, you must tell OpenGL that you are using vertex arrays. After 296 that setup step, you can call the drawing APIs to display the triangle.</p> 297 298 <p>To draw the triangle:</p> 299 300 <ol> 301 <li>Add the {@code glEnableClientState()} method to the end of {@code onSurfaceCreated()} to 302 enable vertex arrays. 303 <pre> 304 // Enable use of vertex arrays 305 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); 306 </pre> 307 <p>At this point, you are ready to draw the triangle object in the OpenGL view.</p> 308 </li> 309 310 <li>Add the following code to the end of your {@code onDrawFrame()} method to draw the triangle. 311 <pre> 312 // Draw the triangle 313 gl.glColor4f(0.63671875f, 0.76953125f, 0.22265625f, 0.0f); 314 gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVB); 315 gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3); 316 </pre> 317 </li> 318 <li id="squashed-triangle">Run the app! Your application should look something like this: 319 </li> 320 </ol> 321 322 <img src="{@docRoot}images/opengl/helloopengl-es10-1.png"> 323 <p class="img-caption"> 324 <strong>Figure 1.</strong> Triangle drawn without a projection or camera view. 325 </p> 326 327 <p>There are a few problems with this example. First of all, it is not going to impress your 328 friends. Secondly, the triangle is a bit squashed and changes shape when you change the screen 329 orientation of the device. The reason the shape is skewed is due to the fact that the object is 330 being rendered in a frame which is not perfectly square. You'll fix that problem using a projection 331 and camera view in the next section.</p> 332 333 <p>Lastly, because the triangle is stationary, the system is redrawing the object repeatedly in 334 exactly the same place, which is not the most efficient use of the OpenGL graphics pipeline. In the 335 <a href="#motion">Add Motion</a> section, you'll make this shape rotate and justify 336 this use of processing power.</p> 337 338 <h2 id="projection-and-views">Apply Projection and Camera View</h2> 339 340 <p>One of the basic problems in displaying graphics is that Android device displays are typically 341 not square and, by default, OpenGL happily maps a perfectly square, uniform coordinate 342 system onto your typically non-square screen. To solve this problem, you can apply an OpenGL 343 projection mode and camera view (eye point) to transform the coordinates of your graphic objects 344 so they have the correct proportions on any display. For more information about OpenGL coordinate 345 mapping, see <a href="{@docRoot}guide/topics/graphics/opengl.html#coordinate-mapping">Mapping 346 Coordinates for Drawn Objects</a>.</p> 347 348 <p>To apply projection and camera view transformations to your triangle: 349 </p> 350 <ol> 351 <li>Modify your {@code onSurfaceChanged()} method to enable {@link 352 javax.microedition.khronos.opengles.GL10#GL_PROJECTION GL10.GL_PROJECTION} mode, calculate the 353 screen ratio and apply the ratio as a transformation of the object coordinates. 354 <pre> 355 public void onSurfaceChanged(GL10 gl, int width, int height) { 356 gl.glViewport(0, 0, width, height); 357 358 // make adjustments for screen ratio 359 float ratio = (float) width / height; 360 gl.glMatrixMode(GL10.GL_PROJECTION); // set matrix to projection mode 361 gl.glLoadIdentity(); // reset the matrix to its default state 362 gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); // apply the projection matrix 363 } 364 </pre> 365 </li> 366 367 <li>Next, modify your {@code onDrawFrame()} method to apply the {@link 368 javax.microedition.khronos.opengles.GL10#GL_MODELVIEW GL_MODELVIEW} mode and set 369 a view point using {@link android.opengl.GLU#gluLookAt(javax.microedition.khronos.opengles.GL10, 370 float, float, float, float, float, float, float, float, float) GLU.gluLookAt()}. 371 <pre> 372 public void onDrawFrame(GL10 gl) { 373 // Redraw background color 374 gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); 375 376 // Set GL_MODELVIEW transformation mode 377 gl.glMatrixMode(GL10.GL_MODELVIEW); 378 gl.glLoadIdentity(); // reset the matrix to its default state 379 380 // When using GL_MODELVIEW, you must set the view point 381 GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); 382 383 // Draw the triangle 384 ... 385 } 386 </pre> 387 </li> 388 <li>Run the updated application and you should see something like this:</li> 389 </ol> 390 391 <img src="{@docRoot}images/opengl/helloopengl-es10-2.png"> 392 <p class="img-caption"> 393 <strong>Figure 2.</strong> Triangle drawn with a projection and camera view applied. 394 </p> 395 396 <p>Now that you have applied this transformation, the triangle has three equal sides, instead of the 397 <a href="#squashed-triangle">squashed triangle</a> in the earlier version.</p> 398 399 <h2 id="motion">Add Motion</h2> 400 401 <p>While it may be an interesting exercise to create static graphic objects with OpenGL ES, chances 402 are you want at least <em>some</em> of your objects to move. In this section, you'll add motion to 403 your triangle by rotating it.</p> 404 405 <p>To add rotation to your triangle:</p> 406 <ol> 407 <li>Modify your {@code onDrawFrame()} method to rotate the triangle object: 408 <pre> 409 public void onDrawFrame(GL10 gl) { 410 ... 411 // When using GL_MODELVIEW, you must set the view point 412 GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); 413 414 // Create a rotation for the triangle 415 long time = SystemClock.uptimeMillis() % 4000L; 416 float angle = 0.090f * ((int) time); 417 gl.glRotatef(angle, 0.0f, 0.0f, 1.0f); 418 419 // Draw the triangle 420 ... 421 } 422 </pre> 423 </li> 424 <li>Run the application and your triangle should rotate around its center.</li> 425 </ol> 426 427 428 <h2 id="touch">Respond to Touch Events</h2> 429 <p>Making objects move according to a preset program like the rotating triangle is useful for 430 getting some attention, but what if you want to have users interact with your OpenGL graphics? In 431 this section, you'll learn how listen for touch events to let users interact with objects in your 432 {@code HelloOpenGLES10SurfaceView}.</p> 433 434 <p>The key to making your OpenGL application touch interactive is expanding your implementation of 435 {@link android.opengl.GLSurfaceView} to override the {@link 436 android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} to listen for touch events. 437 Before you do that, however, you'll modify the renderer class to expose the rotation angle of the 438 triangle. Afterwards, you'll modify the {@code HelloOpenGLES10SurfaceView} to process touch events 439 and pass that data to your renderer.</p> 440 441 <p>To make your triangle rotate in response to touch events:</p> 442 443 <ol> 444 <li>Modify your {@code HelloOpenGLES10Renderer} class to include a new, public member so that 445 your {@code HelloOpenGLES10SurfaceView} class is able to pass new rotation values your renderer: 446 <pre> 447 public float mAngle; 448 </pre> 449 </li> 450 <li>In your {@code onDrawFrame()} method, comment out the code that generates an angle and 451 replace the {@code angle} variable with {@code mAngle}. 452 <pre> 453 // Create a rotation for the triangle (Boring! Comment this out:) 454 // long time = SystemClock.uptimeMillis() % 4000L; 455 // float angle = 0.090f * ((int) time); 456 457 // Use the mAngle member as the rotation value 458 gl.glRotatef(mAngle, 0.0f, 0.0f, 1.0f); 459 </pre> 460 </li> 461 <li>In your {@code HelloOpenGLES10SurfaceView} class, add the following member variables. 462 <pre> 463 private final float TOUCH_SCALE_FACTOR = 180.0f / 320; 464 private HelloOpenGLES10Renderer mRenderer; 465 private float mPreviousX; 466 private float mPreviousY; 467 </pre> 468 </li> 469 <li>In the constructor method for {@code HelloOpenGLES10SurfaceView}, set the {@code mRenderer} 470 member so you have a handle to pass in rotation input and set the render mode to {@link 471 android.opengl.GLSurfaceView#RENDERMODE_WHEN_DIRTY}. 472 <pre> 473 public HelloOpenGLES10SurfaceView(Context context){ 474 super(context); 475 // set the mRenderer member 476 mRenderer = new HelloOpenGLES10Renderer(); 477 setRenderer(mRenderer); 478 479 // Render the view only when there is a change 480 setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); 481 } 482 </pre> 483 </li> 484 <li>In your {@code HelloOpenGLES10SurfaceView} class, override the {@link 485 android.view.View#onTouchEvent(android.view.MotionEvent) onTouchEvent()} method to listen for touch 486 events and pass them to your renderer. 487 <pre> 488 @Override 489 public boolean onTouchEvent(MotionEvent e) { 490 // MotionEvent reports input details from the touch screen 491 // and other input controls. In this case, you are only 492 // interested in events where the touch position changed. 493 494 float x = e.getX(); 495 float y = e.getY(); 496 497 switch (e.getAction()) { 498 case MotionEvent.ACTION_MOVE: 499 500 float dx = x - mPreviousX; 501 float dy = y - mPreviousY; 502 503 // reverse direction of rotation above the mid-line 504 if (y > getHeight() / 2) { 505 dx = dx * -1 ; 506 } 507 508 // reverse direction of rotation to left of the mid-line 509 if (x < getWidth() / 2) { 510 dy = dy * -1 ; 511 } 512 513 mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR; 514 requestRender(); 515 } 516 517 mPreviousX = x; 518 mPreviousY = y; 519 return true; 520 } 521 </pre> 522 <p class="note"><strong>Note:</strong> Touch events return pixel coordinates which <em>are not the 523 same</em> as OpenGL coordinates. Touch coordinate [0,0] is the bottom-left of the screen and the 524 highest value [max_X, max_Y] is the top-right corner of the screen. To match touch events to OpenGL 525 graphic objects, you must translate touch coordinates into OpenGL coordinates.</p> 526 </li> 527 <li>Run the application and drag your finger or cursor around the screen to rotate the 528 triangle.</li> 529 </ol> 530 <p>For another example of OpenGL touch event functionality, see <a 531 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/graphics/ 532 TouchRotateActivity.html">TouchRotateActivity</a>.</p>