Skip to content

Instantly share code, notes, and snippets.

@fkaa
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save fkaa/0465d17781b1d7926ae6 to your computer and use it in GitHub Desktop.

Select an option

Save fkaa/0465d17781b1d7926ae6 to your computer and use it in GitHub Desktop.
package cojo.game.render;
import static org.lwjgl.opengl.GL11.*;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
import cojo.game.CojoGame;
public class RenderUtils {
/**
* Binds a texture from the texture map if it exists. If it does not exist, it adds it to the map, then binds it.
* @param name Name the image is mapped to
*/
public static void bindTexture(String name) {
try {
if (!CojoGame.textureMap.containsKey(name))
CojoGame.textureMap.put(name, TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(String.format("images/%s.png", name))));
CojoGame.textureMap.get(name).bind();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Draws a rectangle using quads
* @param x x coordinate
* @param y y coordinate
* @param w width of the rect
* @param h height of the rect
*/
public static void drawTexturedRect(float x, float y, float w, float h) {
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glTexCoord2f(1, 1);
glVertex2f(x + w, y);
glTexCoord2f(1, 0);
glVertex2f(x + w, y + h);
glTexCoord2f(0, 0);
glVertex2f(x, y + h);
glTexCoord2f(0, 1);
glVertex2f(x, y);
glEnd();
glDisable(GL_TEXTURE_2D);
}
/**
* Draws a rectangle using quads
* @param x x coordinate
* @param y y coordinate
* @param w width of the rect
* @param h height of the rect
* @param textureWidth width of the texture being drawn
* @param textureHeight height of the texture being drawn
*/
public static void drawTexturedRectUV(float x, float y, float w, float h, float textureWidth, float textureHeight) {
float mx = x*w;
float my = y*h;
float u1 = mx / 512;
float v1 = my / 256;
float u2 = (mx + w) / 512;
float v2 = (my + h) / 256;
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glTexCoord2f(u1, v1); glVertex2f(0, 0);
glTexCoord2f(u1, v2); glVertex2f(0, h);
glTexCoord2f(u2, v2); glVertex2f(w, h);
glTexCoord2f(u2, v1); glVertex2f(w, 0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment