Path: blob/master/SLICK_HOME/src/org/newdawn/slick/opengl/SlickCallable.java
1461 views
package org.newdawn.slick.opengl;12import org.lwjgl.opengl.GL11;3import org.newdawn.slick.SlickException;4import org.newdawn.slick.opengl.renderer.Renderer;56/**7* A utility to allow performing GL operations without contaminating the8* Slick OpenGL state. Note this will not protect you from OpenGL programming errors9* like a glBegin() without a glEnd(), or glPush() without glPop() etc.10*11* Expected usage:12*13* <code>14* SlickCallable callable = new SlickCallable() {15* public performGLOperations() throws SlickException {16* GL.glTranslate(0,0,1);17* glBegin(GL.GL_POLYGONS);18* glVertex(..);19* ...20* glEnd();21* }22* }23* callable.call();24* </code>25*26* Alternatively you can use the static methods directly27*28* <code>29* SlickCallable.enterSafeBlock();30*31* GL.glTranslate(0,0,1);32* glBegin(GL.GL_POLYGONS);33* glVertex(..);34* ...35* glEnd();36*37* SlickCallable.leaveSafeBlock();38* </code>39*40* @author kevin41*/42public abstract class SlickCallable {43/** The last texture used */44private static Texture lastUsed;45/** True if we're in a safe block */46private static boolean inSafe = false;474849/**50* Enter a safe block ensuring that all the OpenGL state that slick51* uses is safe before touching the GL state directly.52*/53public static void enterSafeBlock()54{55if (inSafe) {56return;57}5859Renderer.get().flush();60lastUsed = TextureImpl.getLastBind();61TextureImpl.bindNone();62GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);63GL11.glPushClientAttrib(GL11.GL_ALL_CLIENT_ATTRIB_BITS);64GL11.glMatrixMode(GL11.GL_MODELVIEW);65GL11.glPushMatrix();66GL11.glMatrixMode(GL11.GL_PROJECTION);67GL11.glPushMatrix();68GL11.glMatrixMode(GL11.GL_MODELVIEW);6970inSafe = true;71}7273/**74* Leave a safe block ensuring that all of Slick's OpenGL state is75* restored since the last enter.76*/77public static void leaveSafeBlock()78{79if (!inSafe) {80return;81}8283GL11.glMatrixMode(GL11.GL_PROJECTION);84GL11.glPopMatrix();85GL11.glMatrixMode(GL11.GL_MODELVIEW);86GL11.glPopMatrix();87GL11.glPopClientAttrib();88GL11.glPopAttrib();8990if (lastUsed != null) {91lastUsed.bind();92} else {93TextureImpl.bindNone();94}9596inSafe = false;97}9899/**100* Cause this callable to perform it's GL operations (@see performGLOperations()). This101* method will block until the GL operations have been performed.102*103* @throws SlickException Indicates a failure while performing the GL operations or104* maintaing SlickState105*/106public final void call() throws SlickException {107enterSafeBlock();108109performGLOperations();110111leaveSafeBlock();112}113114/**115* Perform the GL operations that this callable is intended to. This operations should116* not effect the slick OpenGL state.117*118* @throws SlickException Indicates a failure of some sort. This is user exception119*/120protected abstract void performGLOperations() throws SlickException;121}122123124