I'm trying to render a quad with a texture, but it's not working.
Here is my code:
//Init Code
GL11.glViewport(0, 0, WIDTH, HEIGHT);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GLU.gluPerspective(45.0f, ((float) WIDTH / (float) HEIGHT), 0.1f, 100.0f);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GL11.glClearDepth(1.0f);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthFunc(GL11.GL_LEQUAL);
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
GL11.glEnable(GL11.GL_TEXTURE_2D);
//Render Code
BufferedImage textures = null;
try {
textures = ImageIO.read(BlockWorldComponent.class.getResource("/textures.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedImage img = textures;
int w = img.getWidth();
int h = img.getHeight();
int imgInt[] = new int[w * h];
byte imgByte[] = new byte[w * h * 4];
img.getRGB(0, 0, w, h, imgInt, 0, w);
for (int i = 0; i < imgInt.length; i++) {
int a = imgInt[i] >> 24 & 0xFF;
int r = imgInt[i] >> 16 & 0xFF;
int g = imgInt[i] >> 8 & 0xFF;
int b = imgInt[i] & 0xFF;
imgByte[i * 4 + 0] = (byte) r;
imgByte[i * 4 + 1] = (byte) g;
imgByte[i * 4 + 2] = (byte) b;
imgByte[i * 4 + 3] = (byte) a;
}
ByteBuffer imageData = ByteBuffer.allocateDirect(imgByte.length);
imageData.order(ByteOrder.nativeOrder());
imageData.clear();
imageData.put(imgByte, 0, imgByte.length);
imageData.flip();
int[] tex = new int[1];
tex[0] = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex[0]);
System.out.println(tex[0]);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, w, h, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, imageData);
GL11.glScalef(0.25f, 0.25f, 0.25f);
//GL11.glColor3f(0.0f,1.0f,0.0f);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex[0]);
GL11.glBegin(GL11.GL_QUADS);
//Top Left
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f(1.0f, 1.0f, -1.0f);
//Top Right
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f(1.0f, 1.0f, 1.0f);
//Bottom Left
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f(-1.0f, 1.0f, 1.0f);
//Bottom Right
GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f(-1.0f, 1.0f, -1.0f);
GL11.glEnd();
I see a couple problems here. First, you don't seem to have a texture bound when you call glTexImage2D. You will need to call glBindTexture(GL_TEXTURE_2D, tex[0]); prior to calling it in order for the texture to be properly set up by OpenGL. And, of course, you will need to have populated tex[0] by means of a call to glGenTextures prior to that.
Secondly, you cannot call glBindTexture between calls to glBegin and glEnd. As a result, the first bind you call in your drawing section, GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); will take effect, but not the second, since the second one is after your call to glBegin. As such, no texture will be used in rendering.
Have you enabled texturing in your project?
glEnable(GL_TEXTURE_2D);
Or perhaps in your case:
GL11.glEnable(GL_11.GL_TEXTURE_2D);
Related
I'm trying to create some code for loading and drawing 2D textures in LWJGL. Here is my code for drawing:
glfwShowWindow(window);
GL.createCapabilities();
loadTextures();
glClearColor(1f, 1f, 1f, 1f);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//draw
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glTranslatef(100, 100, 0);
glBindTexture(GL_TEXTURE_2D, testTexture);
glBegin(GL_QUADS);
{
glTexCoord2f(0, 0);
glVertex2f(0, 0);
glTexCoord2f(1, 0);
glVertex2f(TEXTURE_WIDTH, 0);
glTexCoord2f(1, 1);
glVertex2f(TEXTURE_WIDTH, TEXTURE_HEIGHT);
glTexCoord2f(0, 1);
glVertex2f(0, TEXTURE_HEIGHT);
}
glEnd();
glPopMatrix();
//end draw
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwFreeCallbacks(window);
glfwDestroyWindow(window);
glfwTerminate();
glfwSetErrorCallback(null).free();
And this is my texture loading code:
try
{
BufferedImage image = ImageIO.read(file);
/*
if (image.getType() != BufferedImage.TYPE_INT_ARGB)
{
throw new TextureException("Invalid image!");
}
*/
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
ByteBuffer byteBuffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
for (int x = 0; x < image.getWidth(); x++)
{
for (int y = 0; y < image.getHeight(); y++)
{
int pixel = pixels[y * image.getWidth() + x];
byteBuffer.put((byte)((pixel >> 16) & 0xFF));
byteBuffer.put((byte)((pixel >> 8) & 0xFF));
byteBuffer.put((byte)(pixel & 0xFF));
byteBuffer.put((byte)((pixel >> 24) & 0xFF));
}
}
byteBuffer.flip();
int textureID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, textureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, byteBuffer);
return textureID;
}
catch (Exception e)
{
e.printStackTrace();
throw new TextureException("Failed to load image!");
}
However, when I run this code all I get is a white screen. I checked the value of testTexture and it was set to 1, so I assume that's the texture's ID which makes me believe that worked, but I think there's something going wrong when drawing.
Two-dimensional texturing has to be enabled by glEnable and can be disabled by glDisable:
glEnable(GL_TEXTURE_2D);
If texturing is enables then the texture wich is currently bound is applied, when the geometry is drawn by the glBegin/glEnd sequences.
If you want to draw the geometry in window (pixel) coordinates, then you've to set an orthographic projection with. The orthographic projection can be set by glOrtho.
If you dont set the orthographic projection, the vertex coordinates would have to be in normalized device space in range [-1.0, 1.0].
In the following windowWidth an windowHeight is assumed to be the width and height of the window:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, windowWidth, windowHeight, 0.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// [...]
}
I've got some code that's supposed to render text to a texture so that I don't have to render each character each draw step, and can instead use the rendered texture. However, my code does not as it's supposed to, and the texture is left blank. After a few hours of trying different things, I cannot figure it out, and so I bring the question to you.
I'm fairly certain the problem is somewhere in this code chunk below, but if you think it's not, I'll gladly post whatever other samples of code you would like. I just really want to get this done already. The exact problem is that the created texture is blank, and never is rendered to (it seems like). I've tried just drawing one massive quad on it, and that didn't seem to work either.
Edit: After flipping the buffer, I can get some color to be rendered to the texture, but it's all just one color (which makes me think it's only sampling one pixel), and I can't figure out how to get the actual image I want to render to show on it.
public Text(String text, int x, int y, Font font, float size, GUIComponent parent, Binding binding) {
super(null, x, y, font.getStringWidth(size, text), font.getStringHeight(size), parent, binding, false);
this.text = text;
this.font = font;
this.width = font.getStringWidth(size, text);
this.height = font.getStringHeight(size);
int fbo = glGenFramebuffers();
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
int tex = glGenTextures();
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex, 0);
IntBuffer intBuffer = BufferUtils.createIntBuffer(1);
intBuffer.put(GL_COLOR_ATTACHMENT0);
intBuffer.flip();
glDrawBuffers(intBuffer);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
throw new RuntimeException("Something really bad happened");
}
//RENDER
RenderUtil.recalibrate(width, height, 1.0f); //Does glViewport(width, height), and some matrix stuff
Camera.updateShader("textshader", "projection", false); //Update projection matrix
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
int width = 0;
float f = this.width / 1.0f;
int charWidth = 0;
for (char c : text.toCharArray()) {
font.bind(0, c % 256); // calls glBindTexture, this works, have tested
//ResourceManager.getTexture("grassroadedger1").bind(0, 0);
charWidth = font.getCharWidth(size, c);
//float[] verts = new float[] { -1f, 1f, 1f, 1f, 1f, -1f, -1f, -1f };
float[] verts = new float[] { -1.0f + (width / f), 1.0f, 1.0f + ((width + charWidth) / f), 1.0f, 1.0f + ((width + charWidth) / f), -1.0f, -1.0f + (width / f), -1.0f };
width += charWidth;
glBindBuffer(GL_ARRAY_BUFFER, vertexPointer);
glBufferSubData(GL_ARRAY_BUFFER, 0, RenderUtil.createBuffer(verts));
glVertexAttribPointer(0, 2, GL_FLOAT, false, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, RenderUtil.getIndicesPointer());
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
//END
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
RenderUtil.recalibrate(Window.getWidth(), Window.getHeight(), LuminaEngine.getGlobalImageScale());
this.setTexture(new Texture(tex, "text_"+size+"_"+text));
}
FragmentShader
#version 330 core
in vec2 uv;
layout(location = 0) out vec4 color;
uniform sampler2D sampler;
void main(){
color = texture2D( sampler, uv );
}
Vertex Shader
#version 330 core
layout(location = 0) in vec3 vertices;
layout(location = 1) in vec2 textures;
out vec2 uv;
uniform mat4 projection;
void main(){
gl_Position = projection * vec4(vertices,1);
uv = textures;
}
Edit: After flipping the intBuffer for drawBuffers, I can get some things to appear, mostly just a big blue square. Progress nonetheless
You never defined an array of generic vertex attribute data for the texture coordinates (in vec2 textures;).
Add something like this to your code:
int texCoordBuffer;
glGenBuffers(1, texCoordBuffer);
float[] texCoord = new float[] { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f };
glBindBuffer(GL_ARRAY_BUFFER, texCoordBuffer);
glBufferData(GL_ARRAY_BUFFER, RenderUtil.createBuffer(texCoord), GL_STATIC_DRAW);
int tax_attr_i = 1; // layout(location = 1) in vec2 textures;
glVertexAttribPointer(tax_attr_i, 2, GL_FLOAT, false, 0, 0);
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);
}
The Original Problem:
I'm making a 2d game in OpenGL that uses tiles to draw a map. At the moment, each tile is drawn individually on a quad. The code for the tile rendering is:
#Override
public void render() {
if (parentTileSet.getTexture() == null)
return;
float alpha = parentLayer.getOpacity();
if (alpha < 0)
alpha = 0;
glColor4f(1.0f, 1.0f, 1.0f, alpha); //Set alpha to parent layer's alpha
parentTileSet.getTexture().bind(); //Bind texture
float bx = parentTileSet.getTileWidth() / 2; //Half the width
float by = parentTileSet.getTileHeight() / 2; //Half the height
float x = getX(), y = getY();
float z = 0f;
glPushMatrix(); //Save the current view matrix
glTranslatef(x, y, 0f); //Translate to the tile's position
glRotatef(rotate, 0f, 0f, 1f); //Rotate the tile if it has a rotation
if ((flipType & 1) > 0) //Are we flipping horizontally?
glScalef(-1f, 1f, 1f);
if ((flipType & 2) > 0) //Are we flipping vertically?
glScalef(1f, -1f, 1f);
//Draw the tile
glBegin(GL_QUADS);
glTexCoord2f(tex_cords.bottom_left.x, tex_cords.bottom_left.y); //bottom left
glVertex3f(-bx, -by, z);
glTexCoord2f(tex_cords.bottom_right.x, tex_cords.bottom_right.y); //bottom right
glVertex3f(bx, -by, z);
glTexCoord2f(tex_cords.top_right.x, tex_cords.top_right.y); //top right
glVertex3f(bx, by, z);
glTexCoord2f(tex_cords.top_left.x, tex_cords.top_left.y); //top left
glVertex3f(-bx, by, z);
glEnd();
glPopMatrix(); //Reload the view matrix to original state
parentTileSet.getTexture().unbind(); //Unbind the texture
}
And the result looks like the following:
http://i.stack.imgur.com/maIXk.jpg
Which is good. However, the FPS could be better, and this especially becomes an issue when the maps become more detailed. (The FPS drops to about 20).
My Ideal Solution:
Since the tiles will never change position or animate, if I render all the tiles to a texture once, and just draw that texture, then performance will increase!
So, I made a framebuffer using the following class:
public class Framebuffer implements Drawable {
private int fID, tID;
protected int width, height;
public Framebuffer(int width, int height) {
this.width = width;
this.height = height;
}
public void generate() {
fID = glGenFramebuffers();
tID = glGenTextures();
glBindFramebuffer(GL_FRAMEBUFFER, fID);
glBindTexture(GL_TEXTURE_2D, tID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_INT, (ByteBuffer) null);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tID, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw new RuntimeException("Framebuffer configuration error.");
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
public void begin() {
glPushMatrix();
glPushAttrib(GL_VIEWPORT_BIT);
glBindFramebuffer(GL_FRAMEBUFFER, fID);
glViewport(0, 0, width, height);
}
public void end() {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glPopMatrix();
glPopAttrib();
}
#Override
public void render() {
float x = 0f;
float y = 0f;
float z = 0f;
float bx = (this.width)/2f;
float by = (this.height)/2f;
glPushMatrix();
glBindTexture(GL_TEXTURE_2D, tID);
glBegin(GL_QUADS);
glTexCoord2f(0f, 0f); //bottom left
glVertex3f(x - bx, y - by, z);
glTexCoord2f(1f, 0f); //bottom right
glVertex3f(x + bx, y - by, z);
glTexCoord2f(1f, 1f); //top right
glVertex3f(x + bx, y + by, z);
glTexCoord2f(0f, 1f); //top left
glVertex3f(x - bx, y + by, z);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
And then use the following code to generate the framebuffer, and render the tiles to the texture:
System.out.println("Attempting to generate frame buffer..");
try {
Framebuffer frame = new Framebuffer(tiledData.getPixelWidth(), tiledData.getPixelHeight());
frame.generate();
frame.begin();
glScalef(0.5f, 0.5f, 1f); //The game is scaled up by 2, so I'm just unscalling here.
Iterator<Drawable> drawableIterator = getSortedDrawables();
while (drawableIterator.hasNext()) {
Drawable d = drawableIterator.next();
if (d instanceof TileObject) {
TileObject t = (TileObject)d;
if (t.isGroundLayer() && !t.isParallaxLayer() && !t.isAnimated()) {
t.render(); //This render method is the one from above
drawableIterator.remove();
}
}
}
frame.end();
System.out.println("Success!");
addDrawable(frame);
} catch (RuntimeException e) {
System.out.println("Framebuffers are not supported!");
}
However, the output is this:
http://puu.sh/8Eemy.jpg
Which is not what I expected to happen. I tried scaling it, moving it, and all sorts of things but I can never get it exactly right.
My Question
What am I doing wrong? Is there another way to go about this? Am I missing something?
UPDATE
Thanks to the comments, I've got it to render correctly!
I changed the framebuffer class to be the following:
private int fID, tID;
protected int width, height;
public Framebuffer(int width, int height) {
this.width = width;
this.height = height;
}
public void generate() {
fID = glGenFramebuffers();
tID = glGenTextures();
glBindFramebuffer(GL_FRAMEBUFFER, fID);
glBindTexture(GL_TEXTURE_2D, tID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_INT, (ByteBuffer) null);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tID, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw new RuntimeException("Framebuffer configuration error.");
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
public void begin() {
glBindFramebuffer(GL_FRAMEBUFFER, fID);
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
public void end() {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
#Override
public void render() {
float x = this.width / 2f;
float y = this.height / 2f;
float z = 0f;
float bx = (this.width)/2f;
float by = (this.height)/2f;
glPushMatrix();
glBindTexture(GL_TEXTURE_2D, tID);
glBegin(GL_QUADS);
glTexCoord2f(0f, 0f); //bottom left
glVertex3f(x - bx, y - by, z);
glTexCoord2f(1f, 0f); //bottom right
glVertex3f(x + bx, y - by, z);
glTexCoord2f(1f, 1f); //top right
glVertex3f(x + bx, y + by, z);
glTexCoord2f(0f, 1f); //top left
glVertex3f(x - bx, y + by, z);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
glPopMatrix();
}
The points of interest here is the begin() and end() method, where I setup a new projection matrix and save the old one, then restore it in the end() method.
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();
}