Giving different texture to each face in a pyramid - java

I am beginner in openGL.
i am created a prism ( each face is equilateral triangle ) in android using openGL library and i am able to rotate the prism successfully.
but my requirment is to put three different images in each face of the prism and i am not able to put the images. when i am putting the image it is scaling and mapping to all faces.
MyRenderer Class
public class MyRenderer implements Renderer {
/** Cube instance */
/* Rotation values for all axis */
private float xrot; //X Rotation ( NEW )
private float yrot; //Y Rotation ( NEW )
private float zrot; //Z Rotation ( NEW )
/** The Activity Context ( NEW ) */
private Context context;
private Pyramid pyramid;
/**
* Instance the Cube object and set
* the Activity Context handed over
*/
public MyRenderer(Context context) {
this.context = context;
pyramid = new Pyramid(this.context);
}
/**
* The Surface is created/init()
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//Load the texture for the cube once during Surface creation
gl.glEnable(GL10.GL_TEXTURE_2D); //Enable Texture Mapping ( NEW )
gl.glShadeModel(GL10.GL_SMOOTH); //Enable Smooth Shading
gl.glClearColor(1.0f, 1.0f, 1.0f, 0.5f); //Black Background
gl.glClearDepthf(1.0f); //Depth Buffer Setup
gl.glEnable(GL10.GL_DEPTH_TEST); //Enables Depth Testing
gl.glDepthFunc(GL10.GL_LEQUAL); //The Type Of Depth Testing To Do
//Really Nice Perspective Calculations
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}
/**
* Here we do our drawing
*/
public void onDrawFrame(GL10 gl) {
//Clear Screen And Depth Buffer
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity(); //Reset The Current Modelview Matrix
//Drawing
gl.glTranslatef(0.0f, -1.0f, -5.0f); //Move 5 units into the screen
gl.glScalef(1.0f, 1.0f, 1.0f); //Scale the Cube to 80 percent, otherwise it would be too large for the screen
//Rotate around the axis based on the rotation matrix (rotation, x, y, z)
gl.glRotatef(yrot, 0.0f, 1.65f, 0.0f); //X
pyramid.draw(gl, context);
yrot += 1.0f;
}
/**
* If the surface changes, reset the view
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
if(height == 0) { //Prevent A Divide By Zero By
height = 1; //Making Height Equal One
}
gl.glViewport(0, 0, width, height); //Reset The Current Viewport
gl.glMatrixMode(GL10.GL_PROJECTION); //Select The Projection Matrix
gl.glLoadIdentity(); //Reset The Projection Matrix
//Calculate The Aspect Ratio Of The Window
GLU.gluPerspective(gl, 45.0f, (float)width / (float)height, 0.1f, 100.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW); //Select The Modelview Matrix
gl.glLoadIdentity(); //Reset The Modelview Matrix
}
}
MyPyramid class
public class Pyramid {
/** The buffer holding the vertices */
private FloatBuffer vertexBuffer;
/** The buffer holding the color values */
private FloatBuffer colorBuffer;
private ByteBuffer indexBuffer;
private FloatBuffer textureBuffer;
private int noOfFaces = 3;
private int[] texturesID = new int[3];
private float PyramidVertices [] = {
0.0f, 1.65f, 0.0f,
-1.3f, 0.0f, 1.0f,
1.3f, 0.0f, 1.0f,
0.0f, 0.0f, -1.65f,
};
private float textures[] = {
//Mapping coordinates for the vertices
0.0f, 1.65f,
0.0f, 1.65f,
-1.3f, 0.0f,
1.3f, 0.0f,
};
private float colors[] = {
1.0f, 0.0f, 0.0f, 1.0f, //Red
0.0f, 1.0f, 0.0f, 1.0f, //Green
0.0f, 0.0f, 1.0f, 1.0f, //Blue
1.0f, 0.0f, 0.0f, 1.0f, //Red
};
private byte indices [] = { 0, 2, 1,
0, 2, 3,
0, 1, 3,
};
/**
* The Pyramid constructor.
*
* Initiate the buffers.
*/
public Pyramid( Context context) {
//
ByteBuffer byteBuf = ByteBuffer.allocateDirect(PyramidVertices.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuf.asFloatBuffer();
vertexBuffer.put(PyramidVertices);
vertexBuffer.position(0);
byteBuf = ByteBuffer.allocateDirect(colors.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
colorBuffer = byteBuf.asFloatBuffer();
colorBuffer.put(colors);
colorBuffer.position(0);
indexBuffer = ByteBuffer.allocateDirect(indices.length);
indexBuffer.put(indices);
indexBuffer.position(0);
byteBuf = ByteBuffer.allocateDirect(textures.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
textureBuffer = byteBuf.asFloatBuffer();
textureBuffer.put(textures);
textureBuffer.position(0);
}
/**
* The object own drawing function.
* Called from the renderer to redraw this instance
* with possible changes in values.
*
* #param gl - The GL Context
*/
public void draw(GL10 gl, Context context) {
//Set the face rotation
// gl.glFrontFace(GL10.GL_CW);
gl.glCullFace(GL10.GL_CCW);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
// gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
loadTexture(gl, context);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
// Enable the texture state
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Point to our buffers
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_BYTE, indexBuffer);
//Disable the client state before leaving
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
public void loadTexture(GL10 gl, Context context) {
Bitmap bitmap;
gl.glGenTextures(3, texturesID, 0); // Generate texture-ID array for 6 IDs
gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesID[2]);
InputStream is = context.getResources().openRawResource(R.drawable.forward);
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {
}
}
// Generate OpenGL texture images
// Create Nearest Filtered Texture
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);
// Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
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);
// Build Texture from loaded bitmap for the currently-bind texture ID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
}
and i took the help from
http://www3.ntu.edu.sg/home/ehchua/programming/android/Android_3D.html
http://nehe.gamedev.net/
How to give different images on each face?

There are few ways of doing this but here are the simplest two for you to try:
Modify object to your needs
It's quite tricky to use few textures at a time and select them per-face, but the simple solution is to divide your pyramid into few objects. Then, you can assign different texture for each of your objects as you like.
Modify texture to your needs
You can use a technique known as Texture Atlas. In this solution you can take few textures and stitch them together into one, bigger bitmap. Then you use this bitmap as your main texture. You also need to modify your vertices UVs, so one of your triangles uses some part of your bigger texture, while another triangle uses different part of your texture. Using this technique you can get an appearance that different triangles use totally different images as their texture (even that there's just one real texture during rendering).
Let us know if you need more details about it.

Thanks for response.
I found the solution for my problem. I created a equilateral triangle and then by giving the proper rotation angle i am able to rotate it as well as i put the different texture in each face.
MyPyramid class
public class PyramidNew {
int []texturesID = new int[3];
Bitmap []bitmap = new Bitmap[3];
private FloatBuffer textureBuffer;
private FloatBuffer vertexBuffer; // Buffer for vertex-array
private float[][] colors = { // Colors of the 6 faces
{1.0f, 0.5f, 0.0f, 1.0f}, // 0. orange
{1.0f, 0.0f, 1.0f, 1.0f}, // 1. violet
{0.0f, 1.0f, 0.0f, 1.0f}, // 2. green
{0.0f, 0.0f, 1.0f, 1.0f}, // 3. blue
{1.0f, 0.0f, 0.0f, 1.0f}, // 4. red
{1.0f, 1.0f, 0.0f, 1.0f} // 5. yellow
};
/* private float[] vertices = { // Vertices for the front face
-1.5f, 0.0f, 0.86f, // 0. left-bottom-front
1.5f, 0.0f, 0.86f, // 1. right-bottom-front
0.0f, 1.86f, 0.0f, // 2. left-top-front
// 3. right-top-front
};*/
private float[] vertices = { // Vertices for the front face
-1.0f, 0.0f, 0.86f, // 0. left-bottom-front
1.0f, 0.0f, 0.86f, // 1. right-bottom-front
0.0f, 1.86f, 0.0f, // 2. left-top-front
// 3. right-top-front
};
private float textures[] = {
//Mapping coordinates for the vertices
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
};
// Constructor - Set up the buffers
public PyramidNew( Context context) {
// Setup vertex-array buffer. Vertices in float. An float has 4 bytes
System.out.println("calling Pyramid:::::::::");
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder()); // Use native byte order
vertexBuffer = vbb.asFloatBuffer(); // Convert from byte to float
vertexBuffer.put(vertices); // Copy data into buffer
vertexBuffer.position(0); // Rewind
ByteBuffer byteBuf = ByteBuffer.allocateDirect(textures.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
textureBuffer = byteBuf.asFloatBuffer();
textureBuffer.put(textures);
textureBuffer.position(0);
InputStream stream1 = context.getResources().openRawResource(R.drawable.splash_screen);
InputStream stream2 = context.getResources().openRawResource(R.drawable.bg);
InputStream stream3 = context.getResources().openRawResource(R.drawable.bg1);
try {
//BitmapFactory is an Android graphics utility for images
bitmap[0] = BitmapFactory.decodeStream(stream1);
bitmap[1] = BitmapFactory.decodeStream(stream2);
bitmap[2] = BitmapFactory.decodeStream(stream3);
} finally {
//Always clear and close
try {
stream1.close();
stream2.close();
stream3.close();
stream1 = stream2 = stream3 = null;
} catch (IOException e) {
}
}
}
// Draw the color cube
public void draw(GL10 gl, Context context) {
gl.glFrontFace(GL10.GL_CCW); // Front face in counter-clockwise orientation
gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
gl.glCullFace(GL10.GL_BACK); // Cull the back face (don't display)
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
//loading the first texture in first face
loadTexture(gl, context, 0);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 3);
// rotating the face and puting the second texture in face
gl.glRotatef(120.0f, 0.0f, 1.0f, 0.0f);
//gl.glColor4f(colors[1][0], colors[1][1], colors[1][2], colors[1][3]);
loadTexture(gl, context, 1);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 3);
// Back - Rotate another 120 degree about y-axis and then put different texture
gl.glRotatef(120.0f, 0.0f, 1.0f, 0.0f);
//gl.glColor4f(colors[2][0], colors[2][1], colors[2][2], colors[2][3]);
loadTexture(gl, context, 2);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 3);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisable(GL10.GL_CULL_FACE);
}
public void loadTexture(GL10 gl, Context context, int currentImage) {
// Bitmap []bitmap = new Bitmap[3];
gl.glGenTextures(3, texturesID, 0); // Generate texture-ID array for 6 IDs
gl.glBindTexture(GL10.GL_TEXTURE_2D, texturesID[currentImage]);
// Generate OpenGL texture images
// Create Nearest Filtered Texture
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);
// Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
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);
// Build Texture from loaded bitmap for the currently-bind texture ID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap[currentImage], 0);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
// Enable the texture state
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Point to our buffers
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
}
}

Related

Depth not being render but instead is displaying overlay

I have an issue in my project where I am trying to draw a pyramid on screen but the depth is not being displayed.
public void create(float[] vertices, int[] indices, int numberOfVertices, int numberOfIndices) {
indexCount = numberOfIndices;
vao = gl.genVertexArrays();
gl.bindVertexArray(vao);
IntBuffer indicesBuffer = factory.create(indices);
ibo = gl.genBuffers();
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
gl.bufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW);
FloatBuffer verticesBuffer = factory.create(vertices);
vbo = gl.genBuffers();
gl.bindBuffer(GL_ARRAY_BUFFER, vbo);
gl.bufferData(GL_ARRAY_BUFFER, verticesBuffer, GL_STATIC_DRAW);
gl.vertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
gl.enableVertexAttribArray(0);
gl.bindBuffer(GL_ARRAY_BUFFER, 0);
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
gl.bindVertexArray(0);
}
I create my mesh object with following code where Vertices and Indices are defined as :
private void createTriangles() {
float[] vertices = new float[] {
//x y z
-1.0f, -1.0f, 0.0f, //0
0.0f, 0.0f, 1.0f, //1
1.0f, -1.0f, 0.0f, //2
0.0f, 1.0f, 0.0f //3
};
int[] indices = new int[] {
0, 3, 1,
1, 3, 2,
2, 3, 0,
0, 1, 2
};
mesh.create(vertices, indices, 12, 12);
}
In order to display them to screen I call my render function from my game loop which is defined as.
public void render() {
gl.bindVertexArray(vao);
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
gl.drawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
gl.bindVertexArray(0);
}
To create my FloatBuffer and IntBuffer I have a factory class defined as.
public class BufferFactory {
public IntBuffer create(int[] indices) {
IntBuffer buffer = BufferUtils.createIntBuffer(indices.length);
buffer.put(indices);
buffer.flip();
return buffer;
}
public FloatBuffer create(float[] vertices) {
FloatBuffer buffer = BufferUtils.createFloatBuffer(vertices.length);
buffer.put(vertices);
buffer.flip();
return buffer;
}
}
So the issue i'm getting is that it should have drawn four triangles to screen to form a pyramid, however my output looks like this.
I have rotated the image to try and see the depth but it is a flat object.
I have tried to identify where the issue may be coming from by attempting to draw each triangle individually by changing my render method to gl.drawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0); So that it only draws one triangle. I have tried to draw all four faces individually and all are drawn to screen.
I found the issue. I was originally scaling the triangle such that
model.scale(new Vector3f(0.2f, 0.2f, 0.0f));
As a result the z axis was being multiplied by 0. Silly mistake, hope this helps someone in the future.

Texture being rendered as black quad

I have been trying to follow the code as specified in this tutorial on OpenGL3+ textures, but my result ends up black instead of the texture.
I am using stbimage to load the image the texture uses into a direct ByteBuffer and can guarantee the RGB data in the buffer is, at least, not uniform - so it can't be that.
I usually do not like to dump code, but I don't see much else I can do at this point. Here's my java code and shaders:
GL is an interface pointing to all the GL## functionality in LWJGL31.
ShaderProgram wraps all the shader specific stuff into a nice blackbox that generates a shaderprogram from the attached shaders on the first call of use(GL) and subsequently reuses that program. This works just fine for rendering a coloured triangle, so I rule out any errors in there.
Util.checkError(GL, boolean); does check for any OpenGL errors that have accumulated since its last execution and throws a runtime exception if the boolean is not set (silently writes to the log instead, if set).
The rendering code, update(GL, long) is run once every frame
private static final ResourceAPI res = API.get(ResourceAPI.class);
Image lwjgl32;
ShaderProgram prog = new ShaderProgram();
int vbo, vao, ebo;
int texture;
#Override
public void init(GL gl) {
try {
prog.attach(res.get("shaders/texDemo.vert", ShaderSource.class));
prog.attach(res.get("shaders/texDemo.frag", ShaderSource.class));
lwjgl32 = res.get("textures/lwjgl32.png", Image.class);
} catch(ResourceException e) {
throw new RuntimeException(e);
}
float[] vertices = {
// positions // colors // texture coords
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // top left
};
int[] indices = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
vao = gl.glGenVertexArrays();
vbo = gl.glGenBuffers();
ebo = gl.glGenBuffers();
gl.glBindVertexArray(vao);
gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo);
gl.glBufferData(GL.GL_ARRAY_BUFFER, vertices, GL.GL_STATIC_DRAW);
gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, ebo);
gl.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indices, GL.GL_STATIC_DRAW);
gl.glVertexAttribPointer(0, 3, GL.GL_FLOAT, false, 8 * Float.BYTES, 0);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(1, 3, GL.GL_FLOAT, false, 8 * Float.BYTES, 3 * Float.BYTES);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(2, 2, GL.GL_FLOAT, false, 8 * Float.BYTES, 6 * Float.BYTES);
gl.glEnableVertexAttribArray(0);
texture = gl.glGenTextures();
gl.glBindTexture(GL.GL_TEXTURE_2D, texture);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, lwjgl32.getWidth(), lwjgl32.getHeight(), 0, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, lwjgl32.getImageData());
gl.glGenerateMipmap(GL.GL_TEXTURE_2D);
prog.use(gl);
gl.glUniform1i(gl.glGetUniformLocation(prog.getId(gl), "texture"), 0);
Util.checkError(gl, false);
}
#Override
protected void update(GL gl, long deltaFrame) {
gl.glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glActiveTexture(GL.GL_TEXTURE0);
gl.glBindTexture(GL.GL_TEXTURE_2D, texture);
prog.use(gl);
gl.glBindVertexArray(vao);
gl.glDrawElements(GL.GL_TRIANGLES, 6, GL.GL_UNSIGNED_INT, 0);
}
#Override
public void clean(GL gl) {
gl.glDeleteVertexArrays(vao);
gl.glDeleteBuffers(vbo);
gl.glDeleteBuffers(ebo);
ShaderProgram.clearUse(gl);
prog.dispose(gl);
}
Vertex shader
#version 330 core
layout (location = 0) in vec3 in_position;
layout (location = 1) in vec3 in_color;
layout (location = 2) in vec2 in_texCoord;
out vec3 color;
out vec2 texCoord;
void main() {
gl_Position = vec4(in_position, 1.0);
color = in_color;
texCoord = vec2(in_texCoord.x, in_texCoord.y);
}
Fragment shader
#version 330 core
out vec4 frag_colour;
in vec3 color;
in vec2 texCoord;
uniform sampler2D texture;
void main() {
frag_colour = texture(texture, texCoord) * vec4(color, 1.0);
}
1I wrapped LWJGL3's GL## static classes into a single interface and implementation so I can have a bunch of stateful methods that do things such as identifying the context that is being rendered to, etc. I also did my best to remove non-core functionality from the interface so I don't even get tempted to use deprecated stuff
You only enable the vertex attribute with index 0, but this 3 times.
Adapt your code like this:
gl.glVertexAttribPointer(0, 3, GL.GL_FLOAT, false, 8 * Float.BYTES, 0);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(1, 3, GL.GL_FLOAT, false, 8 * Float.BYTES, 3 * Float.BYTES);
gl.glEnableVertexAttribArray(1); // <-------
gl.glVertexAttribPointer(2, 2, GL.GL_FLOAT, false, 8 * Float.BYTES, 6 * Float.BYTES);
gl.glEnableVertexAttribArray(2); // <------
It's hard to tell from just looking at the code but a black quad means that this row in your fragment shader:
frag_colour = texture(texture, texCoord) * vec4(color, 1.0);
evaluates to 0. Which means either the texture is'nt read/bound properly, your texture coordinates are off or color is a zero vector. Make sure your texture image is properly loaded (file exists, has a width and height etc) and has the correct format. What I usually do to debug the shader is to set each parameter as a color to give a hint if it has the correct value:
frag_colour = vec4(color, 1.0); //Makes sure the color is right
or
frag_colour = texture(texture, texCoord); //Makes sure the texture is loaded and bound
And if that doesn't give enough information, even more detail:
frag_colour = vec4(color.x, color.x, color.x, 1.0);
or
frag_colour = vec4(texCoord.x, texCoord.x, texCoord.x, 1.0);

OpenGL Change Width Height Of Bitmap Image

I can't figure out how to increase the size of the image, I know how to rotate, but how would I adjust the size? Also, I would like to know how to prevent the bitmap from looking squished. Right now when I load it on screen it looks like the sides are being squished.
#Override
public void onDrawFrame(GL10 gl) {
// clear Screen and Depth Buffer
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// Reset the Modelview Matrix
gl.glLoadIdentity();
// Drawing
gl.glTranslatef(0.0f, 0.0f, -5.0f); // move 5 units INTO the screen
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glRotatef(mAngle, 0, 1, 0);
gl.glRotatef(mAngle*0.25f, 1, 0, 0);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glRotatef(mAngle*2.0f, 0, 1, 1);
gl.glTranslatef(0.5f, 0.5f, 0.5f);
mAngle += 1.2f;
bitmap_image.draw(gl);
}
In another class I'm loading the bitmap with:
private FloatBuffer vertexBuffer; // buffer holding the vertices
private float vertices[] = {
-1.0f, -1.0f, 0.0f, // V1 - bottom left
-1.0f, 1.0f, 0.0f, // V2 - top left
1.0f, -1.0f, 0.0f, // V3 - bottom right
1.0f, 1.0f, 0.0f // V4 - top right
};
private FloatBuffer textureBuffer; // buffer holding the texture coordinates
private float texture[] = {
// Mapping coordinates for the vertices
0.0f, 1.0f, // top left (V2)
0.0f, 0.0f, // bottom left (V1)
1.0f, 1.0f, // top right (V4)
1.0f, 0.0f // bottom right (V3)
};
/** The texture pointer */
private int[] textures = new int[1];
public ImageLoader() {
// a float has 4 bytes so we allocate for each coordinate 4 bytes
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
// allocates the memory from the byte buffer
vertexBuffer = byteBuffer.asFloatBuffer();
// fill the vertexBuffer with the vertices
vertexBuffer.put(vertices);
// set the cursor position to the beginning of the buffer
vertexBuffer.position(0);
byteBuffer = ByteBuffer.allocateDirect(texture.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
textureBuffer = byteBuffer.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);
}

OpenGL function refusing to render triangle

This has probably something to do with my transformations, but right now I can't figure this out and this is driving me instane. I have wrapped the draw code so that I can easily define new triangles. However, when I put this into a function, it just shows a grey screen. Te function code is as follows:
public void Draw(float[] mViewMatrix, float[] mModelMatrix, float[] mProjectionMatrix, int mPositionHandle, int mColorHandle, int mMVPMatrixHandle)
{
long time = SystemClock.uptimeMillis() % 10000L;
float angleInDegrees = (360.0f / 10000.0f) * ((int) time);
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.rotateM(mModelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);
aBuffer = ByteBuffer.allocateDirect(verts.length * mBytesPerFloat)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
//aBuffer.position(mPositionOffset);
GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,
mStrideBytes, aBuffer);
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Pass in the color information
aBuffer.position(mColorOffset);
GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize, GLES20.GL_FLOAT, false,
mStrideBytes, aBuffer);
GLES20.glEnableVertexAttribArray(mColorHandle);
// This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
// (which currently contains model * view).
Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
// This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
// (which now contains model * view * projection).
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
}
The code which IS working is:
public void onDrawFrame(GL10 glUnused)
{
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
// Do a complete rotation every 10 seconds.
long time = SystemClock.uptimeMillis() % 10000L;
float angleInDegrees = (360.0f / 10000.0f) * ((int) time);
// Draw the triangle facing straight on.
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.rotateM(mModelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);
drawTriangle(mTriangle1Vertices);
// Draw one translated a bit down and rotated to be flat on the ground.
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.translateM(mModelMatrix, 0, 0.0f, -1.0f, 0.0f);
Matrix.rotateM(mModelMatrix, 0, 90.0f, 1.0f, 0.0f, 0.0f);
Matrix.rotateM(mModelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);
drawTriangle(mTriangle2Vertices);
// Draw one translated a bit to the right and rotated to be facing to the left.
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.translateM(mModelMatrix, 0, 1.0f, 0.0f, 0.0f);
Matrix.rotateM(mModelMatrix, 0, 90.0f, 0.0f, 1.0f, 0.0f);
Matrix.rotateM(mModelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);
drawTriangle(mTriangle3Vertices);
*/
/*
for (int x = 0; x < staticHolder.objectList.size(); x++)
{
staticHolder.objectList.get(x).Draw(mViewMatrix, mModelMatrix, mProjectionMatrix, mPositionHandle, mColorHandle, mMVPMatrixHandle);
}
*/
}
/**
* Draws a triangle from the given vertex data.
*
* #param aTriangleBuffer The buffer containing the vertex data.
*/
private void drawTriangle(final FloatBuffer aTriangleBuffer)
{
// Pass in the position information
aTriangleBuffer.position(mPositionOffset);
GLES20.glVertexAttribPointer(mPositionHandle, mPositionDataSize, GLES20.GL_FLOAT, false,
mStrideBytes, aTriangleBuffer);
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Pass in the color information
aTriangleBuffer.position(mColorOffset);
GLES20.glVertexAttribPointer(mColorHandle, mColorDataSize, GLES20.GL_FLOAT, false,
mStrideBytes, aTriangleBuffer);
GLES20.glEnableVertexAttribArray(mColorHandle);
// This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
// (which currently contains model * view).
Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
// This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
// (which now contains model * view * projection).
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
}
I am passing in the same variables and the final variables used here are initialized the same. There is some other work that happens in the function for encapsulation. Any idea why it is refusing to render in the function?
The following code loads the objects in the list:
final float[] triangle1VerticesData = {
// X, Y, Z,
// R, G, B, A
-0.5f, -0.25f, 0.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.25f, 0.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.559016994f, 0.0f,
0.0f, 1.0f, 0.0f, 1.0f};
final float[] triangle2VerticesData = {
// X, Y, Z,
// R, G, B, A
-0.5f, -0.25f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f,
0.5f, -0.25f, 0.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 0.559016994f, 0.0f,
1.0f, 0.0f, 1.0f, 1.0f};
// This triangle is white, gray, and black.
final float[] triangle3VerticesData = {
// X, Y, Z,
// R, G, B, A
-0.5f, -0.25f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
0.5f, -0.25f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f,
0.0f, 0.559016994f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f};
staticHolder.objectList.add(new Triangle(triangle1VerticesData));
staticHolder.objectList.add(new Triangle(triangle2VerticesData));
staticHolder.objectList.add(new Triangle(triangle3VerticesData));
The receiving class is:
public class Triangle extends shape
{
public Triangle(float[] data)
{
verts = data;
}
}
After the following bit of code:
aBuffer = ByteBuffer.allocateDirect(verts.length * mBytesPerFloat).order(ByteOrder.nativeOrder()).asFloatBuffer();
You must put the vertices into the buffer (otherwise, it's blank!):
aBuffer.put(verts);
The reason this isn't in the bit of code that works, is because those three sets of vertices' buffers are pre-allocated, and the vertices are put into it then (at initialization). They are simply passed to the method each time, so they don't have to be put() in again.
On that note, you will want to avoid allocations in your Draw method, as it's called many times per frame and could lead to slow rendering. Allocate aBuffer once, and put new vertices into it each time.

OpenGL: Drawing text in a 2d fashion on a 3d scene?

When I try to display text on my 3d scene it doesn't display the rest of the scene. What do I have to do to fix this? I tried the answer here: Opengl drawing a 2d overlay on a 3d scene problem but it didn't work for me. Here is my code:
public class GunCraft {
private boolean done = false;
Texture texture;
Camera cam;
private float yspeed;
float legAngle;
float playerX = 0;
float playerZ = 0;
float playerSpeed = 0.01f;
float enemyX = 0;
float enemyZ = 0;
private TrueTypeFont font2;
public static void main(String args[]) {
GunCraft gc = new GunCraft();
gc.run();
}
public void run() {
try {
init();
while (!done) {
mainloop();
render();
Display.update();
}
cleanup();
}
catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
/**
* Very basic for first lesson. Just check for escape key or user
* clicking to close the window.
*/
private void mainloop() {
if(Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { // Exit if Escape is pressed
done = true;
}
if(Display.isCloseRequested()) { // Exit if window is closed
done = true;
}
}
/**
* For rendering all objects to the screen
* #return boolean for success or not
*/
private void render() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
font2.drawString(100, 100, "NICE LOOKING FONTS!", Color.green);
loadIdentity();
//GL11.glRotatef(yspeed,0.0f,1.0f,0.0f);
drawRect(texture, 1f, 1f, 1f);
}
public void loadIdentity(){
GL11.glLoadIdentity();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
float camAngle = (float) Math.atan2(playerX, playerZ);
float radius = 5;
GLU.gluLookAt(playerX + (float)(Math.sin(camAngle) * radius), 0, playerZ + (float)(Math.cos(camAngle) * radius), 0, 0, 0, 0, 1, 0);
//GL11.glGetMatrix();
}
public void drawRect(Texture texture, float width, float height, float depth){
texture.bind();
GL11.glBegin(GL11.GL_QUADS); // Start Drawing Quads
// Front Face
GL11.glNormal3f( 0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer
GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f(-width, -height, depth); // Point 1 (Front)
GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f( width, -height, depth); // Point 2 (Front)
GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f( width, height, depth); // Point 3 (Front)
GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f(-width, height, depth); // Point 4 (Front)
// Back Face
GL11.glNormal3f( 0.0f, 0.0f,-1.0f); // Normal Pointing Away From Viewer
GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f(-width, -height, -depth); // Point 1 (Back)
GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f(-width, height, -depth); // Point 2 (Back)
GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f( width, height, -depth); // Point 3 (Back)
GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f( width, -height, -depth); // Point 4 (Back)
// Top Face
GL11.glNormal3f( 0.0f, 1.0f, 0.0f); // Normal Pointing Up
GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f(-width, height, -depth); // Point 1 (Top)
GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f(-width, height, depth); // Point 2 (Top)
GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f( width, height, depth); // Point 3 (Top)
GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f( width, height, -depth); // Point 4 (Top)
// Bottom Face
GL11.glNormal3f( 0.0f,-1.0f, 0.0f); // Normal Pointing Down
GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f(-width, -height, -depth); // Point 1 (Bottom)
GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f( width, -height, -depth); // Point 2 (Bottom)
GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f( width, -height, depth); // Point 3 (Bottom)
GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f(-width, -height, depth); // Point 4 (Bottom)
// Right face
GL11.glNormal3f( 1.0f, 0.0f, 0.0f); // Normal Pointing Right
GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f( width, -height, -depth); // Point 1 (Right)
GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f( width, height, -depth); // Point 2 (Right)
GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f( width, height, depth); // Point 3 (Right)
GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f( width, -height, depth); // Point 4 (Right)
// Left Face
GL11.glNormal3f(-1.0f, 0.0f, 0.0f); // Normal Pointing Left
GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f(-width, -height, -depth); // Point 1 (Left)
GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f(-width, -height, depth); // Point 2 (Left)
GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f(-width, height, depth); // Point 3 (Left)
GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f(-width, height, -depth); // Point 4 (Left)
GL11.glEnd(); // Done Drawing The Quad
}
/**
* Create a window for all display
* #throws Exception
*/
private void createWindow() throws Exception {
Display.setFullscreen(false);
Display.setDisplayMode(new DisplayMode(640, 480));
Display.setTitle("GunCraft - By William Starkovich");
Display.create();
}
/**
* Initialize the environment
* #throws Exception
*/
private void init() throws Exception {
createWindow();
try{
FileInputStream fis;
fis = new FileInputStream(new File("font.ttf"));
Font awtFont2 = Font.createFont(Font.TRUETYPE_FONT, fis);
awtFont2 = awtFont2.deriveFont(24f); // set font size
font2 = new TrueTypeFont(awtFont2, false);
} catch (Exception e) {
e.printStackTrace();
}
initGL(640,480);
}
/**
* Initialize OpenGL
*
*/
private void initGL(int width, int height) {
GL11.glEnable(GL11.GL_TEXTURE_2D); // Enable Texture Mapping
GL11.glShadeModel(GL11.GL_SMOOTH); // Enable Smooth Shading
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background
GL11.glClearDepth(1.0); // Depth Buffer Setup
GL11.glEnable(GL11.GL_DEPTH_TEST); // Enables Depth Testing
GL11.glDepthFunc(GL11.GL_LEQUAL); // The Type Of Depth Testing To Do
GL11.glMatrixMode(GL11.GL_PROJECTION); // Select The Projection Matrix
GL11.glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
GLU.gluPerspective(
45.0f,
(float) Display.getDisplayMode().getWidth() / (float) Display.getDisplayMode().getHeight(),
0.1f,
100.0f);
//GLU.gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz)
GL11.glMatrixMode(GL11.GL_MODELVIEW); // Select The Modelview Matrix
// Really Nice Perspective Calculations
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, width, height, 0, -1000, 1000);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glDisable(GL11.GL_CULL_FACE);
try {
texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("tex.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Cleanup all the resources.
*
*/
private void cleanup() {
Display.destroy();
}
}
You should really review how OpenGL work you have a bunch of truncated statements in your code that get overwritten a few lines later. You have to get what "OpenGL is a state machine" means. If you don't want to deal with that you should find a more abstract game engine that handles all the draw-calls.
I just copypastad your render() and loadIdentity() methods into something working but this is not the real solution. (Recreating the Projection matrices each frame instead of saving/loading them is not smart). Also OpenGL 1.1 is terribly deprecated and using immediate mode is strongly discouraged.
private void render() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
loadIdentity();
GL11.glRotatef(yspeed++,0.0f,1.0f,0.0f);
drawRect(texture, 1f, 1f, 1f);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0, 640, 480, 0, -1000, 1000);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
font2.drawString(100, 100, "NICE LOOKING FONTS!", Color.green);
}
public void loadIdentity(){
GL11.glMatrixMode(GL11.GL_PROJECTION); // Select The Projection Matrix
GL11.glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
GLU.gluPerspective(
45.0f,
(float) Display.getDisplayMode().getWidth() / (float) Display.getDisplayMode().getHeight(),
0.1f,
100.0f);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
float camAngle = (float) Math.atan2(playerX, playerZ);
float radius = 5;
GLU.gluLookAt(playerX + (float)(Math.sin(camAngle) * radius), 0, playerZ + (float)(Math.cos(camAngle) * radius), 0, 0, 0, 0, 1, 0);
//GL11.glGetMatrix();
}

Categories