These code examples were ranked by Codota’s semantic indexing as the best open source examples for GL10 glColorPointer method.
// USAGE: call once before calling draw() multiple times for this buffer. // A: [none] // R: [none] public void bind() { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // Enable Position in Vertices vertices.position(0); // Set Vertex Buffer to Position gl.glVertexPointer(positionCnt, GL10.GL_FLOAT, vertexSize, vertices); // Set Vertex Pointer if (hasColor) { // IF Vertices Have Color gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Enable Color in Vertices vertices.position(positionCnt); // Set Vertex Buffer to Color gl.glColorPointer(COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Color Pointer } if (hasTexCoords) { // IF Vertices Have Texture Coords gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable Texture Coords in Vertices vertices.position(positionCnt + (hasColor ? COLOR_CNT : 0)); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified) gl.glTexCoordPointer(TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Texture Coords Pointer }
// USAGE: call once before calling draw() multiple times for this buffer. // A: [none] // R: [none] public void bind() { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // Enable Position in Vertices vertices.position(0); // Set Vertex Buffer to Position gl.glVertexPointer(positionCnt, GL10.GL_FLOAT, vertexSize, vertices); // Set Vertex Pointer if (hasColor) { // IF Vertices Have Color gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Enable Color in Vertices vertices.position(positionCnt); // Set Vertex Buffer to Color gl.glColorPointer(COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Color Pointer } if (hasTexCoords) { // IF Vertices Have Texture Coords gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable Texture Coords in Vertices vertices.position(positionCnt + (hasColor ? COLOR_CNT : 0)); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified) gl.glTexCoordPointer(TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Texture Coords Pointer } if (hasNormals) { gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); // Enable Normals in Vertices vertices.position(positionCnt + (hasColor ? COLOR_CNT : 0) + (hasTexCoords ? TEXCOORD_CNT : 0)); // Set Vertex Buffer to Normals (NOTE: position based on whether color/texcoords is also specified) gl.glNormalPointer(GL10.GL_FLOAT, vertexSize, vertices); // Set Normals Pointer } } //--Draw--// // D: draw the currently bound vertices in the vertex/index buffers
} } public void draw(GL11 gl) { if (useVBO) { gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexVbo); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, 0); gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, colorVbo); gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, 0); gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N*N); gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vertexElementVbo); gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, 0); gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } else { gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuf); gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, colorBuf);
} } public void draw(GL11 gl) { if (useVBO) { gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexVbo); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, 0); gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, colorVbo); gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, 0); gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N*N); gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vertexElementVbo); gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, 0); gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } else { gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuf); gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, colorBuf); gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, verticeIdx); } final int N2 = n * n; gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N2); gl.glDrawArrays(GL10.GL_LINES, N2, polygonsⁿ - N2); } public boolean isUseHighQuality3d() { return useHighQuality3d;
public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); } }
public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); } } public void draw(int primitiveType, int offset, int numVertices) { GL10 gl = glGraphics.getGL();
public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); } }
public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); } } public void draw(int primitiveType, int offset, int numVertices) { GL10 gl = glGraphics.getGL();
mIndexBuffer.put(indices); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glEnable(GL10.GL_CULL_FACE); gl.glFrontFace(GL10.GL_CW); gl.glShadeModel(GL10.GL_SMOOTH); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer); gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer); } } public void onAccuracyChanged(Sensor sensor, int accuracy) { } } }
mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CW); gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer); gl.glDrawElements(GL10.GL_TRIANGLES, 36, GL10.GL_UNSIGNED_BYTE, mIndexBuffer); } private IntBuffer mVertexBuffer; private IntBuffer mColorBuffer; private ByteBuffer mIndexBuffer; }
private FloatBuffer mColorBuffer; public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.i(TAG_RENDER, "onSurfaceCreated"); // preparation gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); mTriangleBuffer = createFloatBuffer(triangle); mColorBuffer = createFloatBuffer(colors); gl.glClearColor (0.0f, 0.0f, 0.0f, 0.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleBuffer); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glShadeModel(GL10.GL_FLAT); }
private FloatBuffer mColorBuffer; public void onSurfaceCreated(GL10 gl, EGLConfig config) { Log.i(TAG_RENDER, "onSurfaceCreated"); // preparation gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); mTriangleBuffer = createFloatBuffer(triangle); mColorBuffer = createFloatBuffer(colors); gl.glClearColor (0.0f, 0.0f, 0.0f, 0.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleBuffer); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glShadeModel(GL10.GL_FLAT); } public void onSurfaceChanged(GL10 gl, int width, int height) { Log.i(TAG_RENDER, "onSurfaceChanged");
} public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); }
} public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); } } public void draw(int primitiveType, int offset, int numVertices) { GL10 gl = glGraphics.getGL();
} public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); }
} public void bind() { GL10 gl = glGraphics.getGL(); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); vertices.position(0); gl.glVertexPointer(2, GL10.GL_FLOAT, vertexSize, vertices); if(hasColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); vertices.position(2); gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices); } if(hasTexCoords) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); vertices.position(hasColor?6:2); gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices); } } public void draw(int primitiveType, int offset, int numVertices) { GL10 gl = glGraphics.getGL();
* called by renderer drawframe * * @param gl */ public void draw(GL10 gl) { gl.glFrontFace(GL11.GL_CW); // tell opengl to order their faces // stride to between two gl data so system can skip bwteen the gl data // so the system can skip over it to the next bit gl.glVertexPointer(2, GL11.GL_FLOAT, 0, mFVertexBuffer); gl.glColorPointer(4, GL11.GL_UNSIGNED_BYTE, 0, mColorBuffer); gl.glDrawElements(GL11.GL_TRIANGLES, 6, GL11.GL_UNSIGNED_BYTE, mIndexBuffer);//set triangles with gl.glFrontFace(GL11.GL_CCW); // reset front face ordering back to GL_CCW } private FloatBuffer mFVertexBuffer; private ByteBuffer mColorBuffer; private ByteBuffer mIndexBuffer; }
57: gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
58: vertices.position(3);
59: gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices);
60: }
61:
maybe this will help you i used it to import an .obj file and it worked with a texture and everything, you will have to pick it apart to whats relevant to your project its tied into all these other classes, like the instance of GLGame and GLGraphics are used for file input and getting an instance of GL10, good luck, hope this helps
object loader
public class ObjLoader {
public static Vertices3 load(GLGame game, String file) {
InputStream in = null;
try {
in = game.getFileIO().readAsset(file);
List<String> lines = readLines(in);
float[] vertices = new float[lines.size() * 3];
float[] normals = new float[lines.size() * 3];
float[] uv = new float[lines.size() * 2];
int numVertices = 0;
int numNormals = 0;
int numUV = 0;
int numFaces = 0;
int[] facesVerts = new int[lines.size() * 3];
int[] facesNormals = new int[lines.size() * 3];
int[] facesUV = new int[lines.size() * 3];
int vertexIndex = 0;
int normalIndex = 0;
int uvIndex = 0;
int faceIndex = 0;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line.startsWith("v ")) {
String[] tokens = line.split("[ ]+");
vertices[vertexIndex] = Float.parseFloat(tokens[1]);
vertices[vertexIndex + 1] = Float.parseFloat(tokens[2]);
vertices[vertexIndex + 2] = Float.parseFloat(tokens[3]);
vertexIndex += 3;
numVertices++;
continue;
}
if (line.startsWith("vn ")) {
String[] tokens = line.split("[ ]+");
normals[normalIndex] = Float.parseFloat(tokens[1]);
normals[normalIndex + 1] = Float.parseFloat(tokens[2]);
normals[normalIndex + 2] = Float.parseFloat(tokens[3]);
normalIndex += 3;
numNormals++;
continue;
}
if (line.startsWith("vt")) {
String[] tokens = line.split("[ ]+");
uv[uvIndex] = Float.parseFloat(tokens[1]);
uv[uvIndex + 1] = Float.parseFloat(tokens[2]);
uvIndex += 2;
numUV++;
continue;
}
if (line.startsWith("f ")) {
String[] tokens = line.split("[ ]+");
String[] parts = tokens[1].split("/");
facesVerts[faceIndex] = getIndex(parts[0], numVertices);
if (parts.length > 2)
facesNormals[faceIndex] = getIndex(parts[2], numNormals);
if (parts.length > 1)
facesUV[faceIndex] = getIndex(parts[1], numUV);
faceIndex++;
parts = tokens[2].split("/");
facesVerts[faceIndex] = getIndex(parts[0], numVertices);
if (parts.length > 2)
facesNormals[faceIndex] = getIndex(parts[2], numNormals);
if (parts.length > 1)
facesUV[faceIndex] = getIndex(parts[1], numUV);
faceIndex++;
parts = tokens[3].split("/");
facesVerts[faceIndex] = getIndex(parts[0], numVertices);
if (parts.length > 2)
facesNormals[faceIndex] = getIndex(parts[2], numNormals);
if (parts.length > 1)
facesUV[faceIndex] = getIndex(parts[1], numUV);
faceIndex++;
numFaces++;
continue;
}
}
float[] verts = new float[(numFaces * 3)
* (3 + (numNormals > 0 ? 3 : 0) + (numUV > 0 ? 2 : 0))];
for (int i = 0, vi = 0; i < numFaces * 3; i++) {
int vertexIdx = facesVerts[i] * 3;
verts[vi++] = vertices[vertexIdx];
verts[vi++] = vertices[vertexIdx + 1];
verts[vi++] = vertices[vertexIdx + 2];
if (numUV > 0) {
int uvIdx = facesUV[i] * 2;
verts[vi++] = uv[uvIdx];
verts[vi++] = 1 - uv[uvIdx + 1];
}
if (numNormals > 0) {
int normalIdx = facesNormals[i] * 3;
verts[vi++] = normals[normalIdx];
verts[vi++] = normals[normalIdx + 1];
verts[vi++] = normals[normalIdx + 2];
}
}
Vertices3 model = new Vertices3(game.getGLGraphics(), numFaces * 3,
0, false, numUV > 0, numNormals > 0);
model.setVertices(verts, 0, verts.length);
return model;
} catch (Exception ex) {
throw new RuntimeException("couldn't load '" + file + "'", ex);
} finally {
if (in != null)
try {
in.close();
} catch (Exception ex) {
}
}
}
static int getIndex(String index, int size) {
int idx = Integer.parseInt(index);
if (idx < 0)
return size + idx;
else
return idx - 1;
}
static List<String> readLines(InputStream in) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null)
lines.add(line);
return lines;
}
}
vertices3
public class Vertices3 {
final GLGraphics glGraphics;
final boolean hasColor;
final boolean hasTexCoords;
final boolean hasNormals;
final int vertexSize;
final IntBuffer vertices;
final int[] tmpBuffer;
final ShortBuffer indices;
public Vertices3(GLGraphics glGraphics, int maxVertices, int maxIndices,
boolean hasColor, boolean hasTexCoords, boolean hasNormals) {
this.glGraphics = glGraphics;
this.hasColor = hasColor;
this.hasTexCoords = hasTexCoords;
this.hasNormals = hasNormals;
this.vertexSize = (3 + (hasColor ? 4 : 0) + (hasTexCoords ? 2 : 0) + (hasNormals ? 3
: 0)) * 4;
this.tmpBuffer = new int[maxVertices * vertexSize / 4];
ByteBuffer buffer = ByteBuffer.allocateDirect(maxVertices * vertexSize);
buffer.order(ByteOrder.nativeOrder());
vertices = buffer.asIntBuffer();
if (maxIndices > 0) {
buffer = ByteBuffer.allocateDirect(maxIndices * Short.SIZE / 8);
buffer.order(ByteOrder.nativeOrder());
indices = buffer.asShortBuffer();
} else {
indices = null;
}
}
public void setVertices(float[] vertices, int offset, int length) {
this.vertices.clear();
int len = offset + length;
for (int i = offset, j = 0; i < len; i++, j++)
tmpBuffer[j] = Float.floatToRawIntBits(vertices[i]);
this.vertices.put(tmpBuffer, 0, length);
this.vertices.flip();
}
public void setIndices(short[] indices, int offset, int length) {
this.indices.clear();
this.indices.put(indices, offset, length);
this.indices.flip();
}
public void bind() {
GL10 gl = glGraphics.getGL();
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
vertices.position(0);
gl.glVertexPointer(3, GL10.GL_FLOAT, vertexSize, vertices);
if (hasColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
vertices.position(3);
gl.glColorPointer(4, GL10.GL_FLOAT, vertexSize, vertices);
}
if (hasTexCoords) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
vertices.position(hasColor ? 7 : 3);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, vertexSize, vertices);
}
if (hasNormals) {
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
int offset = 3;
if (hasColor)
offset += 4;
if (hasTexCoords)
offset += 2;
vertices.position(offset);
gl.glNormalPointer(GL10.GL_FLOAT, vertexSize, vertices);
}
}
public void draw(int primitiveType, int offset, int numVertices) {
GL10 gl = glGraphics.getGL();
if (indices != null) {
indices.position(offset);
gl.glDrawElements(primitiveType, numVertices,
GL10.GL_UNSIGNED_SHORT, indices);
} else {
gl.glDrawArrays(primitiveType, offset, numVertices);
}
}
public void unbind() {
GL10 gl = glGraphics.getGL();
if (hasTexCoords)
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
if (hasColor)
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if (hasNormals)
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
}
public int getNumIndices() {
return indices.limit();
}
public int getNumVertices() {
return vertices.limit() / (vertexSize / 4);
}
}
33: {
34: gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
35: gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
36: }
37:
I finally got it to work, for the most part. I wasn't keeping the related data for each vertex together well enough so by the time it needed to be rendered, it was all out of order. The parser as of now supports vertices, normals and texture coordinates, although with mildly detailed meshes it hits the maximum heap size and gets stuck in a very long garbage collection loop. I created the suzanne monkey head in Blender, subdivided it once with smoothing and exported that as an OBJ. It did load, but it took about 20 minutes.
Here is the source, I'm sure it will help someone as I could not manage to find code that read an OBJ file and sent it to the graphics card in the form of VBOs, WITH normals and texture coordinates working:
public class OBJToolkit {
private static ArrayList<String> parseOBJ(String modelLocation) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(new File(modelLocation)));
ArrayList<String> lines = new ArrayList<String>();
while(reader.ready())
{
lines.add(reader.readLine());
}
reader.close();
reader = null;
return lines;
}
public static Mesh loadOBJ(String modelLocation) throws FileNotFoundException, IOException
{
Log.d("OBJToolkit", "Location searched for model: " + modelLocation);
ArrayList<Vector3f> allVertices = new ArrayList<Vector3f>();
ArrayList<Vector2f> allTextureCoords = new ArrayList<Vector2f>();
ArrayList<Vector3f> allNormals = new ArrayList<Vector3f>();
ArrayList<Face> faces = new ArrayList<Face>();
Mesh mesh = new Mesh();
ArrayList<String> lines = parseOBJ(modelLocation);
Log.d("OBJToolkit", "About to read the contents of the model");
for (String line : lines)
{
if (line == null)
break;
if (line.startsWith("v "))
{
allVertices.add(new Vector3f(Float.valueOf(line.split(" ")[1]), Float.valueOf(line.split(" ")[2]), Float.valueOf(line.split(" ")[3])));
}
if (line.startsWith("vt "))
{
allTextureCoords.add(new Vector2f(Float.valueOf(line.split(" ")[1]),Float.valueOf(line.split(" ")[2])));
}
if (line.startsWith("vn "))
{
allNormals.add(new Vector3f(Float.valueOf(line.split(" ")[1]), Float.valueOf(line.split(" ")[2]), Float.valueOf(line.split(" ")[3])));
}
if (line.startsWith("f "))
{
//Log.d("OBJToolkit", line);
Face f = new Face();
String[] faceVertexArray = line.split(" ");
for (int index = 1; index < faceVertexArray.length; index++)
{
String[] valueArray = faceVertexArray[index].split("/");
if (allTextureCoords.size() > 0)
f.addVertex(new Vertex(allVertices.get(Integer.valueOf(valueArray[0]) - 1), allNormals.get(Integer.valueOf(valueArray[2]) - 1), allTextureCoords.get(Integer.valueOf(valueArray[1]) - 1)));
else
f.addVertex(new Vertex(allVertices.get(Integer.valueOf(valueArray[0]) - 1), allNormals.get(Integer.valueOf(valueArray[2]) - 1), new Vector2f(0, 0)));
}
faces.add(f);
}
}
Log.d("OBJToolkit", "Number of vertices: " + allVertices.size());
Log.d("OBJToolkit", "Number of normals: " + allNormals.size());
Log.d("OBJToolkit", "Number of texture coords: " + allTextureCoords.size());
lines = null;
allVertices = null;
allNormals = null;
allTextureCoords = null;
ArrayList<Vector3f> VBOVertices = new ArrayList<Vector3f>();
ArrayList<Vector2f> VBOTextureCoords = new ArrayList<Vector2f>();
ArrayList<Vector3f> VBONormals = new ArrayList<Vector3f>();
ArrayList<Integer> VBOIndices = new ArrayList<Integer>();
Log.d("OBJToolkit", "About to reorganize each point of data");
int counter = 0;
for (Face f : faces)
{
for (Vertex v : f.vertices)
{
VBOVertices.add(v.position);
VBONormals.add(v.normal);
VBOTextureCoords.add(v.textureCoord);
VBOIndices.add(counter);
counter++;
}
}
faces = null;
mesh.createBuffers(vector3fListToFloatArray(VBOVertices), integerListToShortArray(VBOIndices), null, vector2fListToFloatArray(VBOTextureCoords), vector3fListToFloatArray(VBONormals));
VBOVertices = null;
VBONormals = null;
VBOTextureCoords = null;
VBOIndices = null;
return mesh;
}
public static void printFloatArrayList(ArrayList<Float> list)
{
String strToPrint = "";
for (float value : list)
{
strToPrint += (value + ", ");
}
Log.d("OBJToolkit", strToPrint);
}
public static String floatArrayToString(ArrayList<Float> list)
{
String strToPrint = "";
for (float value : list)
{
strToPrint += (value + ", ");
}
return strToPrint;
}
public static String vector3fArrayToString(ArrayList<Vector3f> list)
{
String strToPrint = "";
for (Vector3f v : list)
{
strToPrint += v.x + ", ";
strToPrint += v.y + ", ";
strToPrint += v.z + ", ";
}
return strToPrint;
}
public static void printStringArray(String[] list)
{
String strToPrint = "";
for (String s : list)
{
strToPrint += s + ",";
}
Log.d("OBJToolkit", strToPrint);
}
public static void printIntegerArrayList(ArrayList<Integer> list)
{
String strToPrint = "";
for (float value : list)
{
strToPrint += (value + ", ");
}
Log.d("OBJToolkit", strToPrint);
}
public static float[] floatListToFloatArray(ArrayList<Float> list)
{
Log.d("OBJToolkit", "Converting ArrayList Float");
float[] returnArray = new float[list.size()];
int counter = 0;
for (Float i : list)
{
returnArray[counter] = i.floatValue();
counter++;
}
return returnArray;
}
public static short[] integerListToShortArray(ArrayList<Integer> list)
{
Log.d("OBJToolkit", "Converting ArrayList Integer");
short[] returnArray = new short[list.size()];
int counter = 0;
for (int i : list)
{
returnArray[counter] = (short)i;
counter++;
}
return returnArray;
}
public static float[] vector3fListToFloatArray(ArrayList<Vector3f> list)
{
Log.d("OBJToolkit", "Converting ArrayList Vector3f");
float[] returnArray = new float[list.size() * 3];
int counter = 0;
for (Vector3f v : list)
{
returnArray[counter] = v.x;
counter++;
returnArray[counter] = v.y;
counter++;
returnArray[counter] = v.z;
counter++;
}
return returnArray;
}
public static float[] vector2fListToFloatArray(ArrayList<Vector2f> list)
{
Log.d("OBJToolkit", "Converting ArrayList Vector2f");
float[] returnArray = new float[list.size() * 2];
int counter = 0;
for (Vector2f v : list)
{
returnArray[counter] = v.x;
counter++;
returnArray[counter] = v.y;
counter++;
}
return returnArray;
}
Vector3f:
public class Vector3f {
public float x, y, z;
public Vector3f()
{
setTo(0, 0, 0);
}
public Vector3f(float x, float y, float z)
{
setTo(x, y, z);
}
public void setTo(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public float lengthSquared()
{
return x*x + y*y + z*z;
}
public float length()
{
return (float) Math.sqrt(lengthSquared());
}
public Vector3f add(Vector3f v)
{
return new Vector3f(x + v.x, y + v.y, z + v.z);
}
public Vector3f addAndSet(Vector3f v)
{
x += v.x;
y += v.y;
z += v.z;
return this;
}
public Vector3f crossProduct(Vector3f v)
{
return new Vector3f(y * v.z - z * v.y,
z * v.x - x * z,
x * v.y - y * v.x
);
}
public Vector3f negate()
{
x *= -1;
y *= -1;
z *= -1;
return this;
}
public Vector3f normalize()
{
float l = length();
return new Vector3f(x / l, y / l, z / l);
}
public float dotProduct(Vector3f v)
{
return x * v.x + y * v.y + z * v.z;
}
public float angleBetween(Vector3f v)
{
float dls = dotProduct(v) / (length() * v.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
public Vector3f scale(float scale)
{
return new Vector3f(x * scale, y * scale, z * scale);
}
public Vector3f scaleAndSet(float scale)
{
x *= scale;
y *= scale;
z *= scale;
return this;
}
}
Vector2f:
public class Vector2f {
public float x, y;
public Vector2f()
{
setTo(0, 0);
}
public Vector2f(float x, float y)
{
setTo(x, y);
}
public void setTo(float x, float y)
{
this.x = x;
this.y = y;
}
public float lengthSquared()
{
return x * x + y * y;
}
public float length()
{
return (float) Math.sqrt(lengthSquared());
}
public Vector2f add(float x, float y)
{
return new Vector2f(this.x + x, this.y + y);
}
public Vector2f addAndSet(float x, float y)
{
this.x += x;
this.y += y;
return this;
}
public Vector2f negate()
{
x *= -1;
y *= -1;
return this;
}
public Vector2f normalize()
{
float l = length();
return new Vector2f(x / l, y / l);
}
public float dotProduct(Vector2f v)
{
return x * v.x + y * v.y;
}
public float angleBetween(Vector2f v)
{
float dls = dotProduct(v) / (length() * v.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
public Vector2f scale(float scale)
{
return new Vector2f(x * scale, y * scale);
}
public Vector2f scaleAndSet(float scale)
{
x *= scale;
y *= scale;
return this;
}
}
Mesh:
public class Mesh {
Bitmap bitmap = null;
private FloatBuffer verticesBuffer;
private ShortBuffer indicesBuffer;
private FloatBuffer normalsBuffer;
private int numOfIndices = -1;
private float[] rgba = new float[] {1.0f, 1.0f, 1.0f, 1.0f};
private FloatBuffer colorBuffer;
private FloatBuffer mTextureBuffer;
private int mTextureId = -1;
private Bitmap mBitmap;
private boolean mShouldLoadTexture = false;
public float x = 0, y = 0, z = 0, rx = 0, ry = 0, rz = 0;
public Mesh() {
}
public void draw(GL10 gl)
{
//Log.d("Mesh", "About to render mesh");
gl.glFrontFace(GL10.GL_CCW);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glCullFace(GL10.GL_BACK);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, verticesBuffer);
gl.glNormalPointer(GL10.GL_FLOAT, 0, normalsBuffer);
gl.glColor4f(rgba[0], rgba[1], rgba[2], rgba[3]);
if (colorBuffer != null)
{
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
}
if (mShouldLoadTexture)
{
loadGLTexture(gl);
mShouldLoadTexture = false;
}
if (mTextureId != -1 && mTextureBuffer != null)
{
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureId);
}
gl.glTranslatef(x, y, z);
gl.glRotatef(rx, 1, 0, 0);
gl.glRotatef(ry, 0, 1, 0);
gl.glRotatef(rz, 0, 0, 1);
gl.glDrawElements(GL10.GL_TRIANGLES, numOfIndices, GL10.GL_UNSIGNED_SHORT, indicesBuffer);
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
if (mTextureId != -1 && mTextureBuffer != null)
{
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
gl.glDisable(GL10.GL_CULL_FACE);
}
public void setTexture(Bitmap bitmap) {
this.bitmap = bitmap;
}
public void createBuffers(float[] vertices, short[] indices, float[] colors, float[] textureCoords, float[] normals)
{
Log.d("MeshCreateBuffers", "Vertices: " + floatArrayToString(vertices));
setVertices(vertices);
Log.d("MeshCreateBuffers", "Indices: " + shortArrayToString(indices));
setIndices(indices);
if (colors != null)
setColors(colors);
if (textureCoords != null)
setTextureCoordinates(textureCoords);
if (normals != null)
setNormals(normals);
Log.d("MeshCreateBuffers", "Texture Coors: " + floatArrayToString(textureCoords));
}
public String floatArrayToString(float[] array)
{
String returnString = "";
for (int i = 0; i < array.length; i++)
{
returnString += ", " + array[i];
}
if (returnString.length() > 2)
return returnString.substring(2);
else
return returnString;
}
public String shortArrayToString(short[] array)
{
String returnString = "";
for (int i = 0; i < array.length; i++)
{
returnString += ", " + array[i];
}
if (returnString.length() > 2)
return returnString.substring(2);
else
return returnString;
}
protected void setVertices(float[] vertices)
{
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
verticesBuffer = vbb.asFloatBuffer();
verticesBuffer.put(vertices);
verticesBuffer.position(0);
}
protected void setIndices(short[] indices)
{
ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
ibb.order(ByteOrder.nativeOrder());
indicesBuffer = ibb.asShortBuffer();
indicesBuffer.put(indices);
indicesBuffer.position(0);
numOfIndices = indices.length;
}
protected void setColor(float red, float green, float blue, float alpha)
{
rgba[0] = red;
rgba[1] = green;
rgba[2] = blue;
rgba[3] = alpha;
}
protected void setColors(float[] colors)
{
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
cbb.order(ByteOrder.nativeOrder());
colorBuffer = cbb.asFloatBuffer();
colorBuffer.put(colors);
colorBuffer.position(0);
}
protected void setTextureCoordinates(float[] textureCoords)
{
ByteBuffer byteBuf = ByteBuffer.allocateDirect(textureCoords.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
mTextureBuffer = byteBuf.asFloatBuffer();
mTextureBuffer.put(textureCoords);
mTextureBuffer.position(0);
}
protected void setNormals(float[] normals)
{
ByteBuffer byteBuf = ByteBuffer.allocateDirect(normals.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
normalsBuffer = byteBuf.asFloatBuffer();
normalsBuffer.put(normals);
normalsBuffer.position(0);
}
public void loadBitmap(Bitmap bitmap)
{
this.mBitmap = bitmap;
mShouldLoadTexture = true;
}
private void loadGLTexture(GL10 gl)
{
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_LINEAR);
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_REPEAT);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
}
}
Face:
public class Face {
ArrayList<Vertex> vertices = new ArrayList<Vertex>();
public Face()
{
}
public void addVertex(Vertex vertex)
{
vertices.add(vertex);
}
}
Vertex:
public class Vertex {
public Vector3f position, normal;
public Vector2f textureCoord;
public Vertex(Vector3f pos, Vector3f norm, Vector2f textCoord)
{
position = pos;
normal = norm;
textureCoord = textCoord;
}
}
MainActivity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
MyGLSurfaceView view = new MyGLSurfaceView(this);
OpenGLRenderer renderer = new OpenGLRenderer();
view.renderer = renderer;
//renderer.plane.loadBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
view.setRenderer(renderer);
setContentView(view);
}
}
class MyGLSurfaceView extends GLSurfaceView implements OnGestureListener, OnTouchListener
{
OpenGLRenderer renderer;
GestureDetector detector;
float lastX = 0, lastY = 0;
float onDown = 0, onUp = 0;
public MyGLSurfaceView(Context context) {
super(context);
detector = new GestureDetector(this);
setOnTouchListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent me)
{
detector.onTouchEvent(me);
//Log.d("OBJToolkit", "X: " + me.getX());
//Log.d("OBJToolkit", "Y: " + me.getY());
return super.onTouchEvent(me);
}
@Override
public boolean onTouch(View v, MotionEvent me)
{
Log.d("OBJToolkit", "Registered onTouch event");
Log.d("OBJToolkit", "X: " + me.getX());
Log.d("OBJToolkit", "Y: " + me.getY());
if (me.getAction() == MotionEvent.ACTION_DOWN)
{
lastY = me.getY();
}
else if (me.getAction() == MotionEvent.ACTION_MOVE)
{
renderer.moveMesh(me.getY() - lastY);
}
/*
if (lastX == 0)
{
lastX = me.getX();
}
if (lastY == 0)
{
lastY = me.getY();
}
Log.d("OBJToolkit", String.valueOf((me.getY() - lastY) * 0.1f));
renderer.moveMesh(me.getY() - lastY);
*/
lastY = me.getY();
return true;
}
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
//Log.d("OBJToolkit", "Registered onDown Event");
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
//Log.d("OBJToolkit", "Registered onFling Event");
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
//Log.d("OBJToolkit", "Registered onLongPress Event");
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
//Log.d("OBJToolkit", "Registered onScroll Event");
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
//Log.d("OBJToolkit", "Registered onShowPress Event");
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
//Log.d("OBJToolkit", "Registered onSIngleTapUp Event");
return false;
}
}
OpenGLRenderer:
public class OpenGLRenderer implements Renderer
{
//SmoothColoredSquare smoothSquare = new SmoothColoredSquare();
//Cube cube = new Cube(1, 1, 1);
public Mesh plane;
public float meshMoveSpeed = .05f, planePosition = 0f;
float zNear = 0.01f, zFar = 1000.0f, fieldOfView = 45.0f, size;
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.d(getClass().getName(), "About to attempt to load model");
try {
plane = OBJToolkit.loadOBJ(Environment.getExternalStorageDirectory().getPath() + "/testModel.obj");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.d("FNF", "testModel.obj not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("IOE", "testModel.obj not found IOE");
e.printStackTrace();
}
//.z = -7.7f;
//plane.rx = -10;
gl.glEnable(GL11.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
gl.glMatrixMode(GL11.GL_MODELVIEW);
gl.glShadeModel(GL11.GL_SMOOTH);
gl.glClearDepthf(1.0f);
gl.glEnable(GL11.GL_LIGHTING);
gl.glEnable(GL11.GL_LIGHT0);
float ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f};
float diffuseColor[] = {0.2f, 0.2f, 0.2f, 1.0f};
float lightPosition[] = {-2f, 5f, -2f, 1f};
gl.glLightfv(GL11.GL_LIGHT0, GL11.GL_AMBIENT, ambientColor, 0);
gl.glLightfv(GL11.GL_LIGHT0, GL11.GL_DIFFUSE, diffuseColor, 0);
gl.glLightfv(GL11.GL_LIGHT0, GL11.GL_POSITION, lightPosition, 0);
gl.glLoadIdentity();
gl.glClearColor(0.8f, 0.8f, 0.8f, 1.0f);
gl.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//Reset viewport
gl.glViewport(0, 0, width, height);
//Select projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
size = (float) (zNear * Math.tan((fieldOfView / 180.0f) * Math.PI) / 2.0f);
gl.glFrustumf(-size, size, -size / (width / height), size / (width / height), zNear, zFar);
gl.glViewport(0, 0, width, height);
//Reset projection matrix
gl.glLoadIdentity();
//Calculate aspect ratio of window
GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f);
//GLU.gluLookAt(gl, -5f, 2f, 0f, 0f, 0f, 0f, 0f, 1f, 0f);
//Select modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
//Reset modelview matrix
gl.glLoadIdentity();
}
@Override
public void onDrawFrame(GL10 gl) {
//Clear the screen before drawing
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
//plane.ry += 2f;
//plane.rz += 2f;
plane.x += meshMoveSpeed;
plane.z = planePosition;
if (plane.x > 3f)
{
meshMoveSpeed *= -1;
}
else if(plane.x < -3f)
{
meshMoveSpeed *= -1;
}
//Reset the current position held by OpenGL, otherwise the
//camera will be pushed farther and farther back every frame
gl.glLoadIdentity();
//Move the camera backwards in order to actually see the face
gl.glTranslatef(0, 0f, -15f);
plane.draw(gl);
}
public void moveMesh(float distance)
{
planePosition += distance * 0.05f;
}
}
56: gl.glVertexPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, vertices);
57: vertices.position(2);
58: gl.glColorPointer(4, GL10.GL_FLOAT, VERTEX_SIZE, vertices);
59:
60: gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
Oh. I have fixed whole my solutions, and below is my full code. I posted here for whom try to read my long post (^^) and need a real solution :) Thanks to SteveL has suggested me :)
In my solution, I have some change:
first. Performance: I put code read texture in onSurfaceCreate
.
second. As SteveL say. I'm missing gl.glEnable
and I have reseted again gl.glBindTexture
.
Thinks again, I see that those error really silly. Just because I'm a newbie of OpenGL :(
package com.test;
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.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
public class ColorTriangleTest extends Activity{
GLSurfaceView glView;
ByteBuffer byteBuffer;
FloatBuffer vertices;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
int VERTEX_SIZE = (2+4)*4;
byteBuffer = ByteBuffer.allocateDirect(3*VERTEX_SIZE);
byteBuffer.order(ByteOrder.nativeOrder());
vertices = byteBuffer.asFloatBuffer();
vertices.put(new float[] { 0.0f, 0.0f, 1, 0, 0, 1,
319.0f, 0.0f, 1, 1, 0, 1,
160.0f, 479.0f, 1, 0, 1, 1 });
vertices.flip();
glView = new GLSurfaceView(this);
glView.setRenderer(new Render());
setContentView(glView);
}
class Render implements Renderer {
@Override
public void onDrawFrame(GL10 gl) {
int VERTEX_SIZE = (2+4)*4;
gl.glViewport(0, 0, glView.getWidth(), glView.getHeight());
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, 320, 0, 480, 10, -10);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
vertices.position(0);
gl.glVertexPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, vertices);
vertices.position(2);
gl.glColorPointer(4, GL10.GL_FLOAT, VERTEX_SIZE, vertices);
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// TODO Auto-generated method stub
}
}
}
65: // set the color of our element
66: //gl.glColor4f(0.5f, 0f, 0f, 0.5f);
67: gl.glColorPointer(4, GL10.GL_FLOAT, 0, _colorBuffer);
68:
69: // define the vertices we want to draw
here my triangle code from a project which works. Looks like your indices and colour arrays are different
package com.martynhaigh.Vortex;
import android.view.animation.Transformation;
import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
public class Triangle {
private ShortBuffer _indexBuffer;
private FloatBuffer _vertexBuffer;
private FloatBuffer _colorBuffer;
static float _xAngle, _yAngle;
private int _nrOfVertices;
Triangle() {
float[] coords = {
-0.5f, -0.5f, 0f, // (x1, y1, z1)
0.5f, -0.5f, 0f, // (x2, y2, z2)
0f, 0.5f, 0f // (x3, y3, z3)
}; // 9
_nrOfVertices = coords.length / 3;
float[] colors = {
1f, 0f, 0f, 1f, // point 1
0f, 1f, 0f, 1f, // point 2
0f, 0f, 1f, 1f // point 3
}; // 12
short[] indices = {0, 1, 2}; // 3
// float has 4 bytes, coordinate * 4 bytes
ByteBuffer vbb = ByteBuffer.allocateDirect(coords.length * 4); //36
vbb.order(ByteOrder.nativeOrder());
_vertexBuffer = vbb.asFloatBuffer();
// short has 2 bytes, indices * 2 bytes
ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2); // 6
ibb.order(ByteOrder.nativeOrder());
_indexBuffer = ibb.asShortBuffer();
// float has 4 bytes, colors (RGBA) * 4 bytes
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4); // 48
cbb.order(ByteOrder.nativeOrder());
_colorBuffer = cbb.asFloatBuffer();
_vertexBuffer.put(coords);
_indexBuffer.put(indices);
_colorBuffer.put(colors);
_vertexBuffer.position(0);
_indexBuffer.position(0);
_colorBuffer.position(0);
}
public void onDraw(GL10 gl) {
// set rotation
gl.glRotatef(_xAngle, 1f, 0f, 0f);
gl.glRotatef(_yAngle, 0f, 1f, 0f);
// set the color of our element
//gl.glColor4f(0.5f, 0f, 0f, 0.5f);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, _colorBuffer);
// define the vertices we want to draw
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _vertexBuffer);
// finally draw the vertices
gl.glDrawElements(GL10.GL_TRIANGLES, _nrOfVertices, GL10.GL_UNSIGNED_SHORT, _indexBuffer);
}
public void setXAngle(float angle) {
_xAngle = angle;
}
public float getXAngle() {
return _xAngle;
}
public void setYAngle(float angle) {
_yAngle = angle;
}
public float getYAngle() {
return _yAngle;
}
}
47: gl.glFrontFace(gl.GL_CW);
48: gl.glVertexPointer(3, gl.GL_FIXED, 0, mVertexBuffer);
49: gl.glColorPointer(4, gl.GL_FIXED, 0, mColorBuffer);
50: gl.glDrawElements(gl.GL_TRIANGLES, 36, gl.GL_UNSIGNED_BYTE, mIndexBuffer); }
51:
Well here's how I did it ... I hope somebody finds it useful though the Qualcomm AR stuff is out.. it might be obselete.. oh and basically what this does is -- generate two funky cubes from that Android Example, additional functionality introduced are the touch events, though the rotational vectors are off by a lot-- just for a demonstration purpose anyway and ofcourse the cubes overlaid on top of the camera preview which can be moved on a screen..
public class TakeRecieptPicture extends Activity implements Callback {
private Camera camera;
private SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
private TouchSurfaceView mGLSurfaceView;
ShutterCallback shutter = new ShutterCallback(){
@Override
public void onShutter() {
// TODO Auto-generated method stub
// No action to be perfomed on the Shutter callback.
}
};
PictureCallback raw = new PictureCallback(){
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
// No action taken on the raw data. Only action taken on jpeg data.
}
};
PictureCallback jpeg = new PictureCallback(){
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try{
outStream = new FileOutputStream("/sdcard/test.jpg");
outStream.write(data);
outStream.close();
}catch(FileNotFoundException e){
Log.d("Camera", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("Camera", e.getMessage());
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mGLSurfaceView = new TouchSurfaceView(this);
addContentView(mGLSurfaceView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
mSurfaceView = new SurfaceView(this);
addContentView(mSurfaceView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT|LayoutParams.FLAG_BLUR_BEHIND);
}
private void takePicture() {
// TODO Auto-generated method stub
camera.takePicture(shutter, raw, jpeg);
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(arg2, arg3);
try {
camera.setPreviewDisplay(arg0);
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
}
}
The TouchSurfaceView is defined below:
class TouchSurfaceView extends GLSurfaceView {
public TouchSurfaceView(Context context) {
super(context);
cr = new CubeRenderer(true);
this.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
this.setRenderer(cr);
this.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
this.getHolder().setFormat(PixelFormat.TRANSPARENT);
}
public boolean onTrackballEvent(MotionEvent e) {
cr.mAngleX += e.getX() * TRACKBALL_SCALE_FACTOR;
cr.mAngleY += e.getY() * TRACKBALL_SCALE_FACTOR;
requestRender();
return true; }
@Override
public boolean onTouchEvent(MotionEvent e) {
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dx = x - mPreviousX;
float dy = y - mPreviousY;
cr.mAngleX += dx * TOUCH_SCALE_FACTOR;
cr.mAngleY += dy * TOUCH_SCALE_FACTOR;
requestRender();
}
mPreviousX = x;
mPreviousY = y;
return true;
}
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private final float TRACKBALL_SCALE_FACTOR = 36.0f;
public CubeRenderer cr ;
private float mPreviousX;
private float mPreviousY;
}
And the CubeRenderer is given by:
class CubeRenderer implements GLSurfaceView.Renderer {
public CubeRenderer(boolean useTranslucentBackground) {
mTranslucentBackground = useTranslucentBackground;
mCube = new Cube();
}
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -5.0f);
gl.glRotatef(mAngle, 0, 1, 0);
gl.glRotatef(mAngle*0.25f, 1, 0, 0);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
mCube.draw(gl);
gl.glRotatef(mAngle*2.0f, 0, 1, 1);
gl.glTranslatef(0.5f, 0.5f, 0.5f);
mCube.draw(gl);
mAngle += 1.2f;
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
if (mTranslucentBackground) {
gl.glClearColor(0,0,0,0);
} else {
gl.glClearColor(1,1,1,1);
}
gl.glEnable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
}
public void setAngle(float _angle){
}
private boolean mTranslucentBackground;
private Cube mCube;
private float mAngle;
public float mAngleX;
public float mAngleY;
}
And finally the Cube itself is given by:
class Cube{
public Cube()
{ int one = 0x10000;
int vertices[] = {
-one, -one, -one,
one, -one, -one,
one, one, -one,
-one, one, -one,
-one, -one, one,
one, -one, one,
one, one, one,
-one, one, one, };
float[] colors = {
0f, 0f, 0f, 0.5f,
1f , 0f, 0f, 0.1f,
1f,1f,0f,0.5f,
0f, 1f, 0f, 0.1f,
0f, 0f, 1f, 0.1f,
1f, 0f, 1f, 0.2f,
1f, 1f, 1f, 0.1f,
0f, 1f, 1f, 0.1f, };
byte indices[] = {
0, 4, 5, 0, 5, 1,
1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3,
3, 7, 4, 3, 4, 0,
4, 7, 6, 4, 6, 5,
3, 0, 1, 3, 1, 2 };
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asIntBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
cbb.order(ByteOrder.nativeOrder());
mColorBuffer = cbb.asFloatBuffer();
mColorBuffer.put(colors);
mColorBuffer.position(0);
mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
mIndexBuffer.put(indices);
mIndexBuffer.position(0); }
public void draw(GL10 gl) {
gl.glFrontFace(gl.GL_CW);
gl.glVertexPointer(3, gl.GL_FIXED, 0, mVertexBuffer);
gl.glColorPointer(4, gl.GL_FIXED, 0, mColorBuffer);
gl.glDrawElements(gl.GL_TRIANGLES, 36, gl.GL_UNSIGNED_BYTE, mIndexBuffer); }
private IntBuffer mVertexBuffer;
private FloatBuffer mColorBuffer;
private ByteBuffer mIndexBuffer;
}
Well hope somebody finds this useful...