diff options
| author | Ying Wang <wangying@google.com> | 2009-12-14 16:23:32 -0800 |
|---|---|---|
| committer | Ying Wang <wangying@google.com> | 2009-12-14 16:23:32 -0800 |
| commit | dc388c565be0f539ded2bca165fef347dc7a89cc (patch) | |
| tree | a9799e5db72a0032756d1eb12bf86d999513c5dc /samples/ApiDemos/src | |
| parent | a35897da6fcddec45270324a67614deaaacbde94 (diff) | |
| parent | 5595acbed8ca1778a61881a00d7baaffecb2a64c (diff) | |
Merge commit 'goog/eclair-mr2' into play-with-monkey
Conflicts:
cmds/monkey/src/com/android/commands/monkey/Monkey.java
Diffstat (limited to 'samples/ApiDemos/src')
6 files changed, 965 insertions, 22 deletions
diff --git a/samples/ApiDemos/src/com/example/android/apis/app/TextToSpeechActivity.java b/samples/ApiDemos/src/com/example/android/apis/app/TextToSpeechActivity.java new file mode 100644 index 000000000..a693e8036 --- /dev/null +++ b/samples/ApiDemos/src/com/example/android/apis/app/TextToSpeechActivity.java @@ -0,0 +1,136 @@ + /* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.apis.app; + +import android.app.Activity; +import android.os.Bundle; +import android.speech.tts.TextToSpeech; +import android.util.Log; +import android.view.View; +import android.widget.Button; + +import com.example.android.apis.R; + +import java.util.Locale; +import java.util.Random; + +/** + * <p>Demonstrates text-to-speech (TTS). Please note the following steps:</p> + * + * <ol> + * <li>Construct the TextToSpeech object.</li> + * <li>Handle initialization callback in the onInit method. + * The activity implements TextToSpeech.OnInitListener for this purpose.</li> + * <li>Call TextToSpeech.speak to synthesize speech.</li> + * <li>Shutdown TextToSpeech in onDestroy.</li> + * </ol> + * + * <p>Documentation: + * http://developer.android.com/reference/android/speech/tts/package-summary.html + * </p> + * <ul> + */ +public class TextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener { + + private static final String TAG = "TextToSpeechDemo"; + + private TextToSpeech mTts; + private Button mAgainButton; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.text_to_speech); + + // Initialize text-to-speech. This is an asynchronous operation. + // The OnInitListener (second argument) is called after initialization completes. + mTts = new TextToSpeech(this, + this // TextToSpeech.OnInitListener + ); + + // The button is disabled in the layout. + // It will be enabled upon initialization of the TTS engine. + mAgainButton = (Button) findViewById(R.id.again_button); + + mAgainButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + sayHello(); + } + }); + } + + @Override + public void onDestroy() { + // Don't forget to shutdown! + if (mTts != null) { + mTts.stop(); + mTts.shutdown(); + } + + super.onDestroy(); + } + + // Implements TextToSpeech.OnInitListener. + public void onInit(int status) { + // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR. + if (status == TextToSpeech.SUCCESS) { + // Set preferred language to US english. + // Note that a language may not be available, and the result will indicate this. + int result = mTts.setLanguage(Locale.US); + // Try this someday for some interesting results. + // int result mTts.setLanguage(Locale.FRANCE); + if (result == TextToSpeech.LANG_MISSING_DATA || + result == TextToSpeech.LANG_NOT_SUPPORTED) { + // Lanuage data is missing or the language is not supported. + Log.e(TAG, "Language is not available."); + } else { + // Check the documentation for other possible result codes. + // For example, the language may be available for the locale, + // but not for the specified country and variant. + + // The TTS engine has been successfully initialized. + // Allow the user to press the button for the app to speak again. + mAgainButton.setEnabled(true); + // Greet the user. + sayHello(); + } + } else { + // Initialization failed. + Log.e(TAG, "Could not initialize TextToSpeech."); + } + } + + private static final Random RANDOM = new Random(); + private static final String[] HELLOS = { + "Hello", + "Salutations", + "Greetings", + "Howdy", + "What's crack-a-lackin?", + "That explains the stench!" + }; + + private void sayHello() { + // Select a random hello. + int helloLength = HELLOS.length; + String hello = HELLOS[RANDOM.nextInt(helloLength)]; + mTts.speak(hello, + TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue. + null); + } + +} diff --git a/samples/ApiDemos/src/com/example/android/apis/graphics/GLES20Activity.java b/samples/ApiDemos/src/com/example/android/apis/graphics/GLES20Activity.java new file mode 100644 index 000000000..f5573cf48 --- /dev/null +++ b/samples/ApiDemos/src/com/example/android/apis/graphics/GLES20Activity.java @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.apis.graphics; + +import android.app.Activity; +import android.app.ActivityManager; +import android.content.Context; +import android.content.pm.ConfigurationInfo; +import android.opengl.GLSurfaceView; +import android.os.Bundle; + +/** + * This sample shows how to check for OpenGL ES 2.0 support at runtime, and then + * use either OpenGL ES 1.0 or OpenGL ES 2.0, as appropriate. + */ +public class GLES20Activity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mGLSurfaceView = new GLSurfaceView(this); + if (detectOpenGLES20()) { + // Tell the surface view we want to create an OpenGL ES 2.0-compatible + // context, and set an OpenGL ES 2.0-compatible renderer. + mGLSurfaceView.setEGLContextClientVersion(2); + mGLSurfaceView.setRenderer(new GLES20TriangleRenderer(this)); + } else { + // Set an OpenGL ES 1.x-compatible renderer. In a real application + // this renderer might approximate the same output as the 2.0 renderer. + mGLSurfaceView.setRenderer(new TriangleRenderer(this)); + } + setContentView(mGLSurfaceView); + } + + private boolean detectOpenGLES20() { + ActivityManager am = + (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + ConfigurationInfo info = am.getDeviceConfigurationInfo(); + return (info.reqGlEsVersion >= 0x20000); + } + + @Override + protected void onResume() { + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus + super.onResume(); + mGLSurfaceView.onResume(); + } + + @Override + protected void onPause() { + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus + super.onPause(); + mGLSurfaceView.onPause(); + } + + private GLSurfaceView mGLSurfaceView; +} diff --git a/samples/ApiDemos/src/com/example/android/apis/graphics/GLES20TriangleRenderer.java b/samples/ApiDemos/src/com/example/android/apis/graphics/GLES20TriangleRenderer.java new file mode 100644 index 000000000..956eb6862 --- /dev/null +++ b/samples/ApiDemos/src/com/example/android/apis/graphics/GLES20TriangleRenderer.java @@ -0,0 +1,255 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.apis.graphics; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL10; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.opengl.GLES20; +import android.opengl.GLSurfaceView; +import android.opengl.GLUtils; +import android.opengl.Matrix; +import android.os.SystemClock; +import android.util.Log; + +import com.example.android.apis.R; + +class GLES20TriangleRenderer implements GLSurfaceView.Renderer { + + public GLES20TriangleRenderer(Context context) { + mContext = context; + mTriangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length + * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer(); + mTriangleVertices.put(mTriangleVerticesData).position(0); + } + + public void onDrawFrame(GL10 glUnused) { + // Ignore the passed-in GL10 interface, and use the GLES20 + // class's static methods instead. + GLES20.glClearColor(0.0f, 0.0f, 1.0f, 1.0f); + GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); + GLES20.glUseProgram(mProgram); + checkGlError("glUseProgram"); + + GLES20.glActiveTexture(GLES20.GL_TEXTURE0); + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID); + + mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET); + GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, + TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); + checkGlError("glVertexAttribPointer maPosition"); + mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET); + GLES20.glEnableVertexAttribArray(maPositionHandle); + checkGlError("glEnableVertexAttribArray maPositionHandle"); + GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, + TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); + checkGlError("glVertexAttribPointer maTextureHandle"); + GLES20.glEnableVertexAttribArray(maTextureHandle); + checkGlError("glEnableVertexAttribArray maTextureHandle"); + + long time = SystemClock.uptimeMillis() % 4000L; + float angle = 0.090f * ((int) time); + Matrix.setRotateM(mMMatrix, 0, angle, 0, 0, 1.0f); + Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0); + Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0); + + GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); + GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); + checkGlError("glDrawArrays"); + } + + public void onSurfaceChanged(GL10 glUnused, int width, int height) { + // Ignore the passed-in GL10 interface, and use the GLES20 + // class's static methods instead. + GLES20.glViewport(0, 0, width, height); + float ratio = (float) width / height; + Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7); + } + + public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { + // Ignore the passed-in GL10 interface, and use the GLES20 + // class's static methods instead. + mProgram = createProgram(mVertexShader, mFragmentShader); + if (mProgram == 0) { + return; + } + maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition"); + checkGlError("glGetAttribLocation aPosition"); + if (maPositionHandle == -1) { + throw new RuntimeException("Could not get attrib location for aPosition"); + } + maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord"); + checkGlError("glGetAttribLocation aTextureCoord"); + if (maTextureHandle == -1) { + throw new RuntimeException("Could not get attrib location for aTextureCoord"); + } + + muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); + checkGlError("glGetUniformLocation uMVPMatrix"); + if (muMVPMatrixHandle == -1) { + throw new RuntimeException("Could not get attrib location for uMVPMatrix"); + } + + /* + * Create our texture. This has to be done each time the + * surface is created. + */ + + 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(); + + Matrix.setLookAtM(mVMatrix, 0, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); + } + + private int loadShader(int shaderType, String source) { + int shader = GLES20.glCreateShader(shaderType); + if (shader != 0) { + GLES20.glShaderSource(shader, source); + GLES20.glCompileShader(shader); + int[] compiled = new int[1]; + GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0); + if (compiled[0] == 0) { + Log.e(TAG, "Could not compile shader " + shaderType + ":"); + Log.e(TAG, GLES20.glGetShaderInfoLog(shader)); + GLES20.glDeleteShader(shader); + shader = 0; + } + } + return shader; + } + + private int createProgram(String vertexSource, String fragmentSource) { + int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); + if (vertexShader == 0) { + return 0; + } + + int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); + if (pixelShader == 0) { + return 0; + } + + int program = GLES20.glCreateProgram(); + if (program != 0) { + GLES20.glAttachShader(program, vertexShader); + checkGlError("glAttachShader"); + GLES20.glAttachShader(program, pixelShader); + checkGlError("glAttachShader"); + GLES20.glLinkProgram(program); + int[] linkStatus = new int[1]; + GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); + if (linkStatus[0] != GLES20.GL_TRUE) { + Log.e(TAG, "Could not link program: "); + Log.e(TAG, GLES20.glGetProgramInfoLog(program)); + GLES20.glDeleteProgram(program); + program = 0; + } + } + return program; + } + + private void checkGlError(String op) { + int error; + while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { + Log.e(TAG, op + ": glError " + error); + throw new RuntimeException(op + ": glError " + error); + } + } + + private static final int FLOAT_SIZE_BYTES = 4; + private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES; + private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0; + private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3; + private final float[] mTriangleVerticesData = { + // X, Y, Z, U, V + -1.0f, -0.5f, 0, -0.5f, 0.0f, + 1.0f, -0.5f, 0, 1.5f, -0.0f, + 0.0f, 1.11803399f, 0, 0.5f, 1.61803399f }; + + private FloatBuffer mTriangleVertices; + + private final String mVertexShader = + "uniform mat4 uMVPMatrix;\n" + + "attribute vec4 aPosition;\n" + + "attribute vec2 aTextureCoord;\n" + + "varying vec2 vTextureCoord;\n" + + "void main() {\n" + + " gl_Position = uMVPMatrix * aPosition;\n" + + " vTextureCoord = aTextureCoord;\n" + + "}\n"; + + private final String mFragmentShader = + "precision mediump float;\n" + + "varying vec2 vTextureCoord;\n" + + "uniform sampler2D sTexture;\n" + + "void main() {\n" + + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + + "}\n"; + + private float[] mMVPMatrix = new float[16]; + private float[] mProjMatrix = new float[16]; + private float[] mMMatrix = new float[16]; + private float[] mVMatrix = new float[16]; + + private int mProgram; + private int mTextureID; + private int muMVPMatrixHandle; + private int maPositionHandle; + private int maTextureHandle; + + private Context mContext; + private static String TAG = "GLES20TriangleRenderer"; +} diff --git a/samples/ApiDemos/src/com/example/android/apis/graphics/MatrixPaletteActivity.java b/samples/ApiDemos/src/com/example/android/apis/graphics/MatrixPaletteActivity.java new file mode 100644 index 000000000..520e0e1c8 --- /dev/null +++ b/samples/ApiDemos/src/com/example/android/apis/graphics/MatrixPaletteActivity.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.apis.graphics; + +import android.app.Activity; +import android.opengl.GLSurfaceView; +import android.os.Bundle; + +/** + * This sample shows how to implement a Matrix Palette + */ +public class MatrixPaletteActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mGLSurfaceView = new GLSurfaceView(this); + mGLSurfaceView.setRenderer(new MatrixPaletteRenderer(this)); + setContentView(mGLSurfaceView); + } + + @Override + protected void onResume() { + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus + super.onResume(); + mGLSurfaceView.onResume(); + } + + @Override + protected void onPause() { + // Ideally a game should implement onResume() and onPause() + // to take appropriate action when the activity looses focus + super.onPause(); + mGLSurfaceView.onPause(); + } + + private GLSurfaceView mGLSurfaceView; +} diff --git a/samples/ApiDemos/src/com/example/android/apis/graphics/MatrixPaletteRenderer.java b/samples/ApiDemos/src/com/example/android/apis/graphics/MatrixPaletteRenderer.java new file mode 100644 index 000000000..e0e2db166 --- /dev/null +++ b/samples/ApiDemos/src/com/example/android/apis/graphics/MatrixPaletteRenderer.java @@ -0,0 +1,408 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.example.android.apis.graphics; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.FloatBuffer; + +import javax.microedition.khronos.egl.EGLConfig; +import javax.microedition.khronos.opengles.GL; +import javax.microedition.khronos.opengles.GL10; +import javax.microedition.khronos.opengles.GL11; +import javax.microedition.khronos.opengles.GL11Ext; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.opengl.GLSurfaceView; +import android.opengl.GLU; +import android.opengl.GLUtils; +import android.os.SystemClock; + +import com.example.android.apis.R; + +public class MatrixPaletteRenderer implements GLSurfaceView.Renderer{ + private Context mContext; + private Grid mGrid; + private int mTextureID; + + /** A grid is a topologically rectangular array of vertices. + * + * This grid class is customized for the vertex data required for this + * example. + * + * The vertex and index data are held in VBO objects because on most + * GPUs VBO objects are the fastest way of rendering static vertex + * and index data. + * + */ + + private static class Grid { + // Size of vertex data elements in bytes: + final static int FLOAT_SIZE = 4; + final static int CHAR_SIZE = 2; + + // Vertex structure: + // float x, y, z; + // float u, v; + // float weight0, weight1; + // byte palette0, palette1, pad0, pad1; + + final static int VERTEX_SIZE = 8 * FLOAT_SIZE; + final static int VERTEX_TEXTURE_BUFFER_INDEX_OFFSET = 3; + final static int VERTEX_WEIGHT_BUFFER_INDEX_OFFSET = 5; + final static int VERTEX_PALETTE_INDEX_OFFSET = 7 * FLOAT_SIZE; + + private int mVertexBufferObjectId; + private int mElementBufferObjectId; + + // These buffers are used to hold the vertex and index data while + // constructing the grid. Once createBufferObjects() is called + // the buffers are nulled out to save memory. + + private ByteBuffer mVertexByteBuffer; + private FloatBuffer mVertexBuffer; + private CharBuffer mIndexBuffer; + + private int mW; + private int mH; + private int mIndexCount; + + public Grid(int w, int h) { + if (w < 0 || w >= 65536) { + throw new IllegalArgumentException("w"); + } + if (h < 0 || h >= 65536) { + throw new IllegalArgumentException("h"); + } + if (w * h >= 65536) { + throw new IllegalArgumentException("w * h >= 65536"); + } + + mW = w; + mH = h; + int size = w * h; + + mVertexByteBuffer = ByteBuffer.allocateDirect(VERTEX_SIZE * size) + .order(ByteOrder.nativeOrder()); + mVertexBuffer = mVertexByteBuffer.asFloatBuffer(); + + int quadW = mW - 1; + int quadH = mH - 1; + int quadCount = quadW * quadH; + int indexCount = quadCount * 6; + mIndexCount = indexCount; + mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) + .order(ByteOrder.nativeOrder()).asCharBuffer(); + + /* + * Initialize triangle list mesh. + * + * [0]-----[ 1] ... + * | / | + * | / | + * | / | + * [w]-----[w+1] ... + * | | + * + */ + + { + int i = 0; + for (int y = 0; y < quadH; y++) { + for (int x = 0; x < quadW; x++) { + char a = (char) (y * mW + x); + char b = (char) (y * mW + x + 1); + char c = (char) ((y + 1) * mW + x); + char d = (char) ((y + 1) * mW + x + 1); + + mIndexBuffer.put(i++, a); + mIndexBuffer.put(i++, c); + mIndexBuffer.put(i++, b); + + mIndexBuffer.put(i++, b); + mIndexBuffer.put(i++, c); + mIndexBuffer.put(i++, d); + } + } + } + + } + + public void set(int i, int j, float x, float y, float z, + float u, float v, + float w0, float w1, + int p0, int p1) { + if (i < 0 || i >= mW) { + throw new IllegalArgumentException("i"); + } + if (j < 0 || j >= mH) { + throw new IllegalArgumentException("j"); + } + + if (w0 + w1 != 1.0f) { + throw new IllegalArgumentException("Weights must add up to 1.0f"); + } + + int index = mW * j + i; + + mVertexBuffer.position(index * VERTEX_SIZE / FLOAT_SIZE); + mVertexBuffer.put(x); + mVertexBuffer.put(y); + mVertexBuffer.put(z); + mVertexBuffer.put(u); + mVertexBuffer.put(v); + mVertexBuffer.put(w0); + mVertexBuffer.put(w1); + + mVertexByteBuffer.position(index * VERTEX_SIZE + VERTEX_PALETTE_INDEX_OFFSET); + mVertexByteBuffer.put((byte) p0); + mVertexByteBuffer.put((byte) p1); + } + + public void createBufferObjects(GL gl) { + // Generate a the vertex and element buffer IDs + int[] vboIds = new int[2]; + GL11 gl11 = (GL11) gl; + gl11.glGenBuffers(2, vboIds, 0); + mVertexBufferObjectId = vboIds[0]; + mElementBufferObjectId = vboIds[1]; + + // Upload the vertex data + gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertexBufferObjectId); + mVertexByteBuffer.position(0); + gl11.glBufferData(GL11.GL_ARRAY_BUFFER, mVertexByteBuffer.capacity(), mVertexByteBuffer, GL11.GL_STATIC_DRAW); + + gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mElementBufferObjectId); + mIndexBuffer.position(0); + gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer.capacity() * CHAR_SIZE, mIndexBuffer, GL11.GL_STATIC_DRAW); + + // We don't need the in-memory data any more + mVertexBuffer = null; + mVertexByteBuffer = null; + mIndexBuffer = null; + } + + public void draw(GL10 gl) { + GL11 gl11 = (GL11) gl; + GL11Ext gl11Ext = (GL11Ext) gl; + + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); + + gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertexBufferObjectId); + gl11.glVertexPointer(3, GL10.GL_FLOAT, VERTEX_SIZE, 0); + gl11.glTexCoordPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, VERTEX_TEXTURE_BUFFER_INDEX_OFFSET * FLOAT_SIZE); + + gl.glEnableClientState(GL11Ext.GL_MATRIX_INDEX_ARRAY_OES); + gl.glEnableClientState(GL11Ext.GL_WEIGHT_ARRAY_OES); + + gl11Ext.glWeightPointerOES(2, GL10.GL_FLOAT, VERTEX_SIZE, VERTEX_WEIGHT_BUFFER_INDEX_OFFSET * FLOAT_SIZE); + gl11Ext.glMatrixIndexPointerOES(2, GL10.GL_UNSIGNED_BYTE, VERTEX_SIZE, VERTEX_PALETTE_INDEX_OFFSET ); + + gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mElementBufferObjectId); + gl11.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, 0); + gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); + gl.glDisableClientState(GL11Ext.GL_MATRIX_INDEX_ARRAY_OES); + gl.glDisableClientState(GL11Ext.GL_WEIGHT_ARRAY_OES); + gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); + gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); + } + } + + public MatrixPaletteRenderer(Context context) { + mContext = context; + } + + public void onSurfaceCreated(GL10 gl, EGLConfig config) { + /* + * By default, OpenGL enables features that improve quality + * but reduce performance. One might want to tweak that + * especially on software renderer. + */ + gl.glDisable(GL10.GL_DITHER); + + /* + * Some one-time OpenGL initialization can be made here + * probably based on features of this particular context + */ + gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, + GL10.GL_FASTEST); + + gl.glClearColor(.5f, .5f, .5f, 1); + gl.glShadeModel(GL10.GL_SMOOTH); + gl.glEnable(GL10.GL_DEPTH_TEST); + gl.glEnable(GL10.GL_TEXTURE_2D); + + /* + * Create our texture. This has to be done each time the + * surface is created. + */ + + int[] textures = new int[1]; + gl.glGenTextures(1, textures, 0); + + mTextureID = textures[0]; + gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); + + gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, + GL10.GL_NEAREST); + gl.glTexParameterf(GL10.GL_TEXTURE_2D, + GL10.GL_TEXTURE_MAG_FILTER, + GL10.GL_LINEAR); + + gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, + GL10.GL_CLAMP_TO_EDGE); + gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, + GL10.GL_CLAMP_TO_EDGE); + + gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, + GL10.GL_REPLACE); + + 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(GL10.GL_TEXTURE_2D, 0, bitmap, 0); + bitmap.recycle(); + + mGrid = generateWeightedGrid(gl); + } + + public void onDrawFrame(GL10 gl) { + /* + * By default, OpenGL enables features that improve quality + * but reduce performance. One might want to tweak that + * especially on software renderer. + */ + gl.glDisable(GL10.GL_DITHER); + + gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, + GL10.GL_MODULATE); + + /* + * Usually, the first thing one might want to do is to clear + * the screen. The most efficient way of doing this is to use + * glClear(). + */ + + gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); + + gl.glEnable(GL10.GL_DEPTH_TEST); + + gl.glEnable(GL10.GL_CULL_FACE); + + /* + * Now we're ready to draw some 3D objects + */ + + gl.glMatrixMode(GL10.GL_MODELVIEW); + gl.glLoadIdentity(); + + GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); + + gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); + gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); + + gl.glActiveTexture(GL10.GL_TEXTURE0); + gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); + gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, + GL10.GL_REPEAT); + gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, + GL10.GL_REPEAT); + + long time = SystemClock.uptimeMillis() % 4000L; + + // Rock back and forth + double animationUnit = ((double) time) / 4000; + float unitAngle = (float) Math.cos(animationUnit * 2 * Math.PI); + float angle = unitAngle * 135f; + + gl.glEnable(GL11Ext.GL_MATRIX_PALETTE_OES); + gl.glMatrixMode(GL11Ext.GL_MATRIX_PALETTE_OES); + + GL11Ext gl11Ext = (GL11Ext) gl; + + // matrix 0: no transformation + gl11Ext.glCurrentPaletteMatrixOES(0); + gl11Ext.glLoadPaletteFromModelViewMatrixOES(); + + + // matrix 1: rotate by "angle" + gl.glRotatef(angle, 0, 0, 1.0f); + + gl11Ext.glCurrentPaletteMatrixOES(1); + gl11Ext.glLoadPaletteFromModelViewMatrixOES(); + + mGrid.draw(gl); + + gl.glDisable(GL11Ext.GL_MATRIX_PALETTE_OES); + } + + public void onSurfaceChanged(GL10 gl, int w, int h) { + gl.glViewport(0, 0, w, h); + + /* + * Set our projection matrix. This doesn't have to be done + * each time we draw, but usually a new projection needs to + * be set when the viewport is resized. + */ + + float ratio = (float) w / h; + gl.glMatrixMode(GL10.GL_PROJECTION); + gl.glLoadIdentity(); + gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); + } + + private Grid generateWeightedGrid(GL gl) { + final int uSteps = 20; + final int vSteps = 20; + + float radius = 0.25f; + float height = 2.0f; + Grid grid = new Grid(uSteps + 1, vSteps + 1); + + for (int j = 0; j <= vSteps; j++) { + for (int i = 0; i <= uSteps; i++) { + double angle = Math.PI * 2 * i / uSteps; + float x = radius * (float) Math.cos(angle); + float y = height * ((float) j / vSteps - 0.5f); + float z = radius * (float) Math.sin(angle); + float u = -4.0f * (float) i / uSteps; + float v = -4.0f * (float) j / vSteps; + float w0 = (float) j / vSteps; + float w1 = 1.0f - w0; + grid.set(i, j, x, y, z, u, v, w0, w1, 0, 1); + } + } + + grid.createBufferObjects(gl); + return grid; + } +} diff --git a/samples/ApiDemos/src/com/example/android/apis/view/List7.java b/samples/ApiDemos/src/com/example/android/apis/view/List7.java index d44ed5672..e773db62a 100644 --- a/samples/ApiDemos/src/com/example/android/apis/view/List7.java +++ b/samples/ApiDemos/src/com/example/android/apis/view/List7.java @@ -16,15 +16,12 @@ package com.example.android.apis.view; -// Need the following import to get access to the app resources, since this -// class is in a sub-package. import com.example.android.apis.R; - import android.app.ListActivity; import android.database.Cursor; -import android.provider.Contacts.People; import android.os.Bundle; +import android.provider.ContactsContract; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; @@ -36,46 +33,69 @@ import android.widget.TextView; * A list view example where the data comes from a cursor. */ public class List7 extends ListActivity implements OnItemSelectedListener { - private static String[] PROJECTION = new String[] { - People._ID, People.NAME, People.NUMBER + private static final String[] PROJECTION = new String[] { + ContactsContract.Contacts._ID, + ContactsContract.Contacts.DISPLAY_NAME, + ContactsContract.Contacts.HAS_PHONE_NUMBER, + ContactsContract.Contacts.LOOKUP_KEY }; + private int mIdColumnIndex; + private int mHasPhoneColumnIndex; + + private TextView mPhone; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + setContentView(R.layout.list_7); + mPhone = (TextView) findViewById(R.id.phone); getListView().setOnItemSelectedListener(this); // Get a cursor with all people - Cursor c = getContentResolver().query(People.CONTENT_URI, PROJECTION, null, null, null); - startManagingCursor(c); - mPhoneColumnIndex = c.getColumnIndex(People.NUMBER); + Cursor c = managedQuery(ContactsContract.Contacts.CONTENT_URI, + PROJECTION, null, null, null); + mIdColumnIndex = c.getColumnIndex(ContactsContract.Contacts._ID); + mHasPhoneColumnIndex = c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, // Use a template - // that displays a - // text view - c, // Give the cursor to the list adatper - new String[] {People.NAME}, // Map the NAME column in the - // people database to... - new int[] {android.R.id.text1}); // The "text1" view defined in - // the XML template + // that displays a + // text view + c, // Give the cursor to the list adapter + new String[] { ContactsContract.Contacts.DISPLAY_NAME }, // Map the NAME column in the + // people database to... + new int[] { android.R.id.text1 }); // The "text1" view defined in + // the XML template setListAdapter(adapter); } public void onItemSelected(AdapterView parent, View v, int position, long id) { if (position >= 0) { - Cursor c = (Cursor) parent.getItemAtPosition(position); - mPhone.setText(c.getString(mPhoneColumnIndex)); + final Cursor c = (Cursor) parent.getItemAtPosition(position); + if (c.getInt(mHasPhoneColumnIndex) > 0) { + final long contactId = c.getLong(mIdColumnIndex); + final Cursor phones = getContentResolver().query( + ContactsContract.CommonDataKinds.Phone.CONTENT_URI, + new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, + ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, + ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY + " DESC"); + + try { + phones.moveToFirst(); + mPhone.setText(phones.getString(0)); + } finally { + phones.close(); + } + } else { + mPhone.setText(R.string.list_7_nothing); + } } } public void onNothingSelected(AdapterView parent) { mPhone.setText(R.string.list_7_nothing); - } - - private int mPhoneColumnIndex; - private TextView mPhone; } |
