Ported codebase to Java 1.5.

Misc OpenCL fixes and API improvements.
Changed fractal demo to use events/sync objects instead of cl/glFinish for synchronization. (untested)
This commit is contained in:
Ioannis Tsakpinis 2010-09-28 21:11:35 +00:00
parent d17e13f24b
commit a8bcb7fd25
211 changed files with 7927 additions and 6549 deletions

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -35,7 +35,8 @@ import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.openal.AL;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
/**
*
@ -46,24 +47,24 @@ import org.lwjgl.opengl.GL11;
* $Id$
*/
public class Game {
/** Game title */
public static final String GAME_TITLE = "My Game";
/** Desired frame time */
private static final int FRAMERATE = 60;
/** Exit the game */
private static boolean finished;
/** A rotating square! */
private static float angle;
/**
* No constructor needed - this class is static
*/
private Game() {}
/**
* Application init
* @param args Commandline args
@ -78,10 +79,10 @@ public class Game {
} finally {
cleanup();
}
System.exit(0);
}
/**
* Initialise the game
* @throws Exception if init fails
@ -94,25 +95,25 @@ public class Game {
// Enable vsync if we can
Display.setVSyncEnabled(true);
Display.create();
// Start up the sound system
AL.create();
// TODO: Load in your textures etc here
// Put the window into orthographic projection mode with 1:1 pixel ratio.
// We haven't used GLU here to do this to avoid an unnecessary dependency.
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0.0, Display.getDisplayMode().getWidth(), 0.0, Display.getDisplayMode().getHeight(), -1.0, 1.0);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, Display.getDisplayMode().getWidth(), 0.0, Display.getDisplayMode().getHeight(), -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
}
/**
* Runs the game (the "main loop")
*/
@ -120,7 +121,7 @@ public class Game {
while (!finished) {
// Always call Window.update(), all the time
Display.update();
if (Display.isCloseRequested()) {
// Check for O/S close requests
finished = true;
@ -144,7 +145,7 @@ public class Game {
}
}
}
/**
* Do any game-specific cleanup
*/
@ -153,11 +154,11 @@ public class Game {
// Stop the sound
AL.destroy();
// Close the window
Display.destroy();
}
/**
* Do all calculations, handle input, etc.
*/
@ -170,24 +171,24 @@ public class Game {
// TODO: all your game logic goes here.
angle += 2.0f % 360;
}
/**
* Render the current frame
*/
private static void render() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// TODO: all your rendering goes here
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glPushMatrix();
GL11.glTranslatef(Display.getDisplayMode().getWidth() / 2, Display.getDisplayMode().getHeight() / 2, 0.0f);
GL11.glRotatef(angle, 0, 0, 1.0f);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2i(-50, -50);
GL11.glVertex2i(50, -50);
GL11.glVertex2i(50, 50);
GL11.glVertex2i(-50, 50);
GL11.glEnd();
GL11.glPopMatrix();
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(Display.getDisplayMode().getWidth() / 2, Display.getDisplayMode().getHeight() / 2, 0.0f);
glRotatef(angle, 0, 0, 1.0f);
glBegin(GL_QUADS);
glVertex2i(-50, -50);
glVertex2i(50, -50);
glVertex2i(50, 50);
glVertex2i(-50, 50);
glEnd();
glPopMatrix();
}
}

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -37,13 +37,13 @@ import java.awt.Rectangle;
* An entity represents any element that appears in the game. The
* entity is responsible for resolving collisions and movement
* based on a set of properties defined either by subclass or externally.
*
*
* Note that doubles are used for positions. This may seem strange
* given that pixels locations are integers. However, using double means
* that an entity can move a partial pixel. It doesn't of course mean that
* they will be display half way through a pixel but allows us not lose
* accuracy as we move.
*
*
* @author Kevin Glass
*/
public abstract class Entity {
@ -71,12 +71,12 @@ public abstract class Entity {
/**
* Construct a entity based on a sprite image and a location.
*
* @param ref The reference to the image to be displayed for this entity
*
* @param sprite The reference to the image to be displayed for this entity
* @param x The initial x location of this entity
* @param y The initial y location of this entity
*/
public Entity(Sprite sprite, int x, int y) {
protected Entity(Sprite sprite, int x, int y) {
this.sprite = sprite;
this.x = x;
this.y = y;
@ -85,7 +85,7 @@ public abstract class Entity {
/**
* Request that this entity move itself based on a certain ammount
* of time passing.
*
*
* @param delta The ammount of time that has passed in milliseconds
*/
public void move(long delta) {
@ -96,7 +96,7 @@ public abstract class Entity {
/**
* Set the horizontal speed of this entity
*
*
* @param dx The horizontal speed of this entity (pixels/sec)
*/
public void setHorizontalMovement(float dx) {
@ -105,7 +105,7 @@ public abstract class Entity {
/**
* Set the vertical speed of this entity
*
*
* @param dy The vertical speed of this entity (pixels/sec)
*/
public void setVerticalMovement(float dy) {
@ -114,7 +114,7 @@ public abstract class Entity {
/**
* Get the horizontal speed of this entity
*
*
* @return The horizontal speed of this entity (pixels/sec)
*/
public float getHorizontalMovement() {
@ -123,7 +123,7 @@ public abstract class Entity {
/**
* Get the vertical speed of this entity
*
*
* @return The vertical speed of this entity (pixels/sec)
*/
public float getVerticalMovement() {
@ -146,7 +146,7 @@ public abstract class Entity {
/**
* Get the x location of this entity
*
*
* @return The x location of this entity
*/
public int getX() {
@ -155,7 +155,7 @@ public abstract class Entity {
/**
* Get the y location of this entity
*
*
* @return The y location of this entity
*/
public int getY() {
@ -164,7 +164,7 @@ public abstract class Entity {
/**
* Check if this entity collised with another.
*
*
* @param other The other entity to check collision against
* @return True if the entities collide with each other
*/
@ -177,7 +177,7 @@ public abstract class Entity {
/**
* Notification that this entity collided with another.
*
*
* @param other The entity with which this entity collided.
*/
public abstract void collidedWith(Entity other);

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -39,32 +39,33 @@ import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
/**
* The main hook of our game. This class with both act as a manager
* for the display and central mediator for the game logic.
*
* for the display and central mediator for the game logic.
*
* Display management will consist of a loop that cycles round all
* entities in the game asking them to move and then drawing them
* in the appropriate place. With the help of an inner class it
* will also allow the player to control the main ship.
*
*
* As a mediator it will be informed when entities within our game
* detect events (e.g. alient killed, played died) and will take
* appropriate game actions.
*
*
* <p>
* NOTE:<br>
* This game is a LWJGLized implementation of the Space Invaders game by Kevin
* Glass. The original implementation is renderer agnostic and supports other
* Glass. The original implementation is renderer agnostic and supports other
* OpenGL implementations as well as Java2D. This version has been made specific
* for LWJGL, and has added input control as well as sound (which the original doesn't,
* for LWJGL, and has added input control as well as sound (which the original doesn't,
* at the time of writing).
* You can find the original article here:<br>
* <a href="http://www.cokeandcode.com/" target="_blank">http://www.cokeandcode.com</a>
* </p>
*
*
* @author Kevin Glass
* @author Brian Matzon
*/
@ -83,10 +84,10 @@ public class Game {
private TextureLoader textureLoader;
/** The list of all the entities that exist in our game */
private ArrayList entities = new ArrayList();
private ArrayList<Entity> entities = new ArrayList<Entity>();
/** The list of entities that need to be removed from the game this loop */
private ArrayList removeList = new ArrayList();
private ArrayList<Entity> removeList = new ArrayList<Entity>();
/** The entity representing the player */
private ShipEntity ship;
@ -113,7 +114,7 @@ public class Game {
private float moveSpeed = 300;
/** The time at which last fired a shot */
private long lastFire = 0;
private long lastFire;
/** The interval between our players shot (ms) */
private long firingInterval = 500;
@ -125,16 +126,16 @@ public class Game {
private boolean waitingForKeyPress = true;
/** True if game logic needs to be applied this loop, normally as a result of a game event */
private boolean logicRequiredThisLoop = false;
private boolean logicRequiredThisLoop;
/** The time at which the last rendering looped started from the point of view of the game logic */
private long lastLoopTime = getTime();
/** True if the fire key has been released */
private boolean fireHasBeenReleased = false;
private boolean fireHasBeenReleased;
/** The time since the last record of fps */
private long lastFpsTime = 0;
private long lastFpsTime;
/** The recorded fps */
private int fps;
@ -167,15 +168,14 @@ public class Game {
/** Mouse movement on x axis */
private int mouseX;
/** Is this an application or applet */
private static boolean isApplication = false;
private static boolean isApplication;
/**
* Construct our game and set it running.
* @param fullscreen
*
* @param renderingType The type of rendering to use (should be one of the contansts from ResourceFactory)
*
*/
public Game(boolean fullscreen) {
this.fullscreen = fullscreen;
@ -184,7 +184,7 @@ public class Game {
/**
* Get the high resolution time in milliseconds
*
*
* @return The high resolution time in milliseconds
*/
public static long getTime() {
@ -196,8 +196,8 @@ public class Game {
}
/**
* Sleep for a fixed number of milliseconds.
*
* Sleep for a fixed number of milliseconds.
*
* @param duration The amount of time in milliseconds to sleep for
*/
public static void sleep(long duration) {
@ -217,25 +217,25 @@ public class Game {
Display.setTitle(WINDOW_TITLE);
Display.setFullscreen(fullscreen);
Display.create();
// grab the mouse, dont want that hideous cursor when we're playing!
if (isApplication) {
if (isApplication) {
Mouse.setGrabbed(true);
}
// enable textures since we're going to use these for our sprites
GL11.glEnable(GL11.GL_TEXTURE_2D);
glEnable(GL_TEXTURE_2D);
// disable the OpenGL depth test since we're rendering 2D graphics
GL11.glDisable(GL11.GL_DEPTH_TEST);
glDisable(GL_DEPTH_TEST);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GL11.glOrtho(0, width, height, 0, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glViewport(0, 0, width, height);
glOrtho(0, width, height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, width, height);
textureLoader = new TextureLoader();
@ -289,7 +289,7 @@ public class Game {
"height=" + height,
"freq=" + 60,
"bpp=" + org.lwjgl.opengl.Display.getDisplayMode().getBitsPerPixel()
});
});
return true;
} catch (Exception e) {
e.printStackTrace();
@ -341,7 +341,7 @@ public class Game {
/**
* Remove an entity from the game. The entity removed will
* no longer move or be drawn.
*
*
* @param entity The entity that should be removed
*/
public void removeEntity(Entity entity) {
@ -349,7 +349,7 @@ public class Game {
}
/**
* Notification that the player has died.
* Notification that the player has died.
*/
public void notifyDeath() {
if (!waitingForKeyPress) {
@ -382,10 +382,8 @@ public class Game {
// if there are still some aliens left then they all need to get faster, so
// speed up all the existing aliens
for (int i = 0; i < entities.size(); i++) {
Entity entity = (Entity) entities.get(i);
if (entity instanceof AlienEntity) {
for ( Entity entity : entities ) {
if ( entity instanceof AlienEntity ) {
// speed up by 2%
entity.setHorizontalMovement(entity.getHorizontalMovement() * 1.02f);
}
@ -396,7 +394,7 @@ public class Game {
/**
* Attempt to fire a shot from the player. Its called "try"
* since we must first check that the player can fire at this
* since we must first check that the player can fire at this
* point, i.e. has he/she waited long enough between shots
*/
public void tryToFire() {
@ -421,9 +419,9 @@ public class Game {
private void gameLoop() {
while (Game.gameRunning) {
// clear screen
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// let subsystem paint
frameRendering();
@ -431,7 +429,7 @@ public class Game {
// update window contents
Display.update();
}
// clean up
soundManager.destroy();
Display.destroy();
@ -462,25 +460,23 @@ public class Game {
// cycle round asking each entity to move itself
if (!waitingForKeyPress && !soundManager.isPlayingSound()) {
for (int i = 0; i < entities.size(); i++) {
Entity entity = (Entity) entities.get(i);
for ( Entity entity : entities ) {
entity.move(delta);
}
}
// cycle round drawing all the entities we have in the game
for (int i = 0; i < entities.size(); i++) {
Entity entity = (Entity) entities.get(i);
for ( Entity entity : entities ) {
entity.draw();
}
// brute force collisions, compare every entity against
// every other entity. If any of them collide notify
// every other entity. If any of them collide notify
// both entities that the collision has occured
for (int p = 0; p < entities.size(); p++) {
for (int s = p + 1; s < entities.size(); s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
Entity me = entities.get(p);
Entity him = entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
@ -497,21 +493,20 @@ public class Game {
// be resolved, cycle round every entity requesting that
// their personal logic should be considered.
if (logicRequiredThisLoop) {
for (int i = 0; i < entities.size(); i++) {
Entity entity = (Entity) entities.get(i);
for ( Entity entity : entities ) {
entity.doLogic();
}
logicRequiredThisLoop = false;
}
// if we're waiting for an "any key" press then draw the
// current message
// if we're waiting for an "any key" press then draw the
// current message
if (waitingForKeyPress) {
message.draw(325, 250);
}
// resolve the movemfent of the ship. First assume the ship
// resolve the movemfent of the ship. First assume the ship
// isn't moving. If either cursor key is pressed then
// update the movement appropraitely
ship.setHorizontalMovement(0);
@ -557,23 +552,23 @@ public class Game {
}
/**
* @param key_left
* @param direction
* @return
*/
private boolean hasInput(int direction) {
switch(direction) {
case Keyboard.KEY_LEFT:
return
return
Keyboard.isKeyDown(Keyboard.KEY_LEFT) ||
mouseX < 0;
case Keyboard.KEY_RIGHT:
return
return
Keyboard.isKeyDown(Keyboard.KEY_RIGHT) ||
mouseX > 0;
case Keyboard.KEY_SPACE:
return
return
Keyboard.isKeyDown(Keyboard.KEY_SPACE) ||
Mouse.isButtonDown(0);
}
@ -584,18 +579,18 @@ public class Game {
* The entry point into the game. We'll simply create an
* instance of class which will start the display and game
* loop.
*
*
* @param argv The arguments that are passed into our game
*/
public static void main(String argv[]) {
isApplication = true;
System.out.println("Use -fullscreen for fullscreen mode");
new Game((argv.length > 0 && argv[0].equalsIgnoreCase("-fullscreen"))).execute();
new Game((argv.length > 0 && "-fullscreen".equalsIgnoreCase(argv[0]))).execute();
System.exit(0);
}
/**
*
*
*/
public void execute() {
gameLoop();
@ -604,7 +599,7 @@ public class Game {
/**
* Create or get a sprite which displays the image that is pointed
* to in the classpath by "ref"
*
*
* @param ref A reference to the image to load
* @return A sprite that can be drawn onto the current graphics context.
*/

View file

@ -8,27 +8,27 @@ import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
public class GameApplet extends Applet {
/** The Canvas where the LWJGL Display is added */
Canvas display_parent;
/** Thread which runs the main game loop */
Thread gameThread;
/** The Game instance */
Game game;
/**
* Once the Canvas is created its add notify method will call this method to
* Once the Canvas is created its add notify method will call this method to
* start the LWJGL Display and game loop in another thread.
*/
public void startLWJGL() {
gameThread = new Thread() {
public void run() {
try {
Display.setParent(display_parent);
} catch (LWJGLException e) {
e.printStackTrace();
}
@ -39,8 +39,8 @@ public class GameApplet extends Applet {
};
gameThread.start();
}
/**
* Tell game loop to stop running, after which the LWJGL Display will be destoryed.
* The main thread will wait for the Display.destroy() to complete
@ -55,15 +55,15 @@ public class GameApplet extends Applet {
}
public void start() {
}
public void stop() {
}
/**
* Applet Destroy method will remove the canvas, before canvas is destroyed it will notify
* Applet Destroy method will remove the canvas, before canvas is destroyed it will notify
* stopLWJGL() to stop main game loop and to destroy the Display
*/
public void destroy() {
@ -71,21 +71,21 @@ public class GameApplet extends Applet {
super.destroy();
System.out.println("Clear up");
}
/**
* initialise applet by adding a canvas to it, this canvas will start the LWJGL Display and game loop
* in another thread. It will also stop the game loop and destroy the display on canvas removal when
* in another thread. It will also stop the game loop and destroy the display on canvas removal when
* applet is destroyed.
*/
public void init() {
setLayout(new BorderLayout());
try {
display_parent = new Canvas() {
public final void addNotify() {
public void addNotify() {
super.addNotify();
startLWJGL();
}
public final void removeNotify() {
public void removeNotify() {
stopLWJGL();
super.removeNotify();
}

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -33,7 +33,7 @@ package org.lwjgl.examples.spaceinvaders;
/**
* An entity representing a shot fired by the player's ship
*
*
* @author Kevin Glass
* @author Brian Matzon
*/
@ -49,11 +49,11 @@ public class ShotEntity extends Entity {
private Game game;
/** True if this shot has been "used", i.e. its hit something */
private boolean used = false;
private boolean used;
/**
* Create a new shot from the player
*
*
* @param game The game in which the shot has been created
* @param sprite The sprite representing this shot
* @param x The initial x location of the shot
@ -68,7 +68,7 @@ public class ShotEntity extends Entity {
/**
* Reinitializes this entity, for reuse
*
*
* @param x new x coordinate
* @param y new y coordinate
*/
@ -80,7 +80,7 @@ public class ShotEntity extends Entity {
/**
* Request that this shot moved based on time elapsed
*
*
* @param delta The time that has elapsed since last move
*/
public void move(long delta) {
@ -96,7 +96,7 @@ public class ShotEntity extends Entity {
/**
* Notification that this shot has collided with another
* entity
*
*
* @param other The other entity with which we've collided
*/
public void collidedWith(Entity other) {

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -54,22 +54,22 @@ public class SoundManager {
/** We support at most 256 buffers*/
private int[] buffers = new int[256];
/** Number of sources is limited tby user (and hardware) */
private int[] sources;
/** Our internal scratch buffer */
private IntBuffer scratchBuffer = BufferUtils.createIntBuffer(256);
/** Whether we're running in no sound mode */
private boolean soundOutput;
/** Current index in our buffers */
private int bufferIndex;
/** Current index in our source list */
private int sourceIndex;
/**
* Creates a new SoundManager
*/
@ -78,13 +78,13 @@ public class SoundManager {
/**
* Plays a sound effect
* @param buffer Buffer index to play gotten from addSound
* @param buffer Buffer index to play gotten from addSound
*/
public void playEffect(int buffer) {
if(soundOutput) {
// make sure we never choose last channel, since it is used for special sounds
int channel = sources[(sourceIndex++ % (sources.length-1))];
// link buffer and source, and play it
AL10.alSourcei(channel, AL10.AL_BUFFER, buffers[buffer]);
AL10.alSourcePlay(channel);
@ -101,7 +101,7 @@ public class SoundManager {
AL10.alSourcePlay(sources[sources.length-1]);
}
}
/**
* Whether a sound is playing on last source
* @return true if a source is playing right now on source n
@ -109,27 +109,27 @@ public class SoundManager {
public boolean isPlayingSound() {
return AL10.alGetSourcei(sources[sources.length-1], AL10.AL_SOURCE_STATE) == AL10.AL_PLAYING;
}
/**
* Initializes the SoundManager
*
* @param sources Number of sources to create
*
* @param channels Number of channels to create
*/
public void initialize(int channels) {
try {
AL.create();
// allocate sources
scratchBuffer.limit(channels);
AL10.alGenSources(scratchBuffer);
scratchBuffer.rewind();
scratchBuffer.get(sources = new int[channels]);
// could we allocate all channels?
if(AL10.alGetError() != AL10.AL_NO_ERROR) {
throw new LWJGLException("Unable to allocate " + channels + " sources");
}
// we have sound
soundOutput = true;
} catch (LWJGLException le) {
@ -137,10 +137,10 @@ public class SoundManager {
System.out.println("Sound disabled");
}
}
/**
* Adds a sound to the Sound Managers pool
*
*
* @param path Path to file to load
* @return index into SoundManagers buffer list
*/
@ -149,26 +149,26 @@ public class SoundManager {
scratchBuffer.rewind().position(0).limit(1);
AL10.alGenBuffers(scratchBuffer);
buffers[bufferIndex] = scratchBuffer.get(0);
// load wave data from buffer
WaveData wavefile = WaveData.create("spaceinvaders/" + path);
// copy to buffers
AL10.alBufferData(buffers[bufferIndex], wavefile.format, wavefile.data, wavefile.samplerate);
// unload file again
wavefile.dispose();
wavefile.dispose();
// return index for this sound
return bufferIndex++;
}
/**
* Destroy this SoundManager
*/
public void destroy() {
if(soundOutput) {
// stop playing sounds
scratchBuffer.position(0).limit(sources.length);
scratchBuffer.put(sources).flip();
@ -176,12 +176,12 @@ public class SoundManager {
// destroy sources
AL10.alDeleteSources(scratchBuffer);
// destroy buffers
scratchBuffer.position(0).limit(bufferIndex);
scratchBuffer.put(buffers, 0, bufferIndex).flip();
AL10.alDeleteBuffers(scratchBuffer);
// destory OpenAL
AL.destroy();
}

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -33,12 +33,12 @@ package org.lwjgl.examples.spaceinvaders;
import java.io.IOException;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
/**
* Implementation of sprite that uses an OpenGL quad and a texture
* to render a given image to the screen.
*
*
* @author Kevin Glass
* @author Brian Matzon
*/
@ -55,8 +55,8 @@ public class Sprite {
/**
* Create a new sprite from a specified image.
*
* @param window The window in which the sprite will be displayed
*
* @param loader the texture loader to use
* @param ref A reference to the image on which this sprite should be based
*/
public Sprite(TextureLoader loader, String ref) {
@ -72,7 +72,7 @@ public class Sprite {
/**
* Get the width of this sprite in pixels
*
*
* @return The width of this sprite in pixels
*/
public int getWidth() {
@ -81,7 +81,7 @@ public class Sprite {
/**
* Get the height of this sprite in pixels
*
*
* @return The height of this sprite in pixels
*/
public int getHeight() {
@ -90,38 +90,38 @@ public class Sprite {
/**
* Draw the sprite at the specified location
*
*
* @param x The x location at which to draw this sprite
* @param y The y location at which to draw this sprite
*/
public void draw(int x, int y) {
// store the current model matrix
GL11.glPushMatrix();
glPushMatrix();
// bind to the appropriate texture for this sprite
texture.bind();
// translate to the right location and prepare to draw
GL11.glTranslatef(x, y, 0);
glTranslatef(x, y, 0);
// draw a quad textured to match the sprite
GL11.glBegin(GL11.GL_QUADS);
glBegin(GL_QUADS);
{
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
glTexCoord2f(0, 0);
glVertex2f(0, 0);
GL11.glTexCoord2f(0, texture.getHeight());
GL11.glVertex2f(0, height);
glTexCoord2f(0, texture.getHeight());
glVertex2f(0, height);
GL11.glTexCoord2f(texture.getWidth(), texture.getHeight());
GL11.glVertex2f(width, height);
glTexCoord2f(texture.getWidth(), texture.getHeight());
glVertex2f(width, height);
GL11.glTexCoord2f(texture.getWidth(), 0);
GL11.glVertex2f(width, 0);
glTexCoord2f(texture.getWidth(), 0);
glVertex2f(width, 0);
}
GL11.glEnd();
glEnd();
// restore the model view matrix to prevent contamination
GL11.glPopMatrix();
glPopMatrix();
}
}

View file

@ -1,43 +1,43 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.examples.spaceinvaders;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
/**
* A texture to be bound within OpenGL. This object is responsible for
* A texture to be bound within OpenGL. This object is responsible for
* keeping track of a given OpenGL texture and for calculating the
* texturing mapping coordinates of the full image.
*
*
* Since textures need to be powers of 2 the actual texture may be
* considerably bigged that the source image and hence the texture
* mapping coordinates need to be adjusted to matchup drawing the
@ -75,7 +75,7 @@ public class Texture {
/**
* Create a new texture
*
* @param target The GL target
* @param target The GL target
* @param textureID The GL texture ID
*/
public Texture(int target, int textureID) {
@ -85,11 +85,9 @@ public class Texture {
/**
* Bind the specified GL context to a texture
*
* @param gl The GL context to bind to
*/
public void bind() {
GL11.glBindTexture(target, textureID);
glBindTexture(target, textureID);
}
/**
@ -121,7 +119,7 @@ public class Texture {
return height;
}
/**
/**
* Get the width of the original image
*
* @return The width of the original image
@ -149,7 +147,7 @@ public class Texture {
}
/**
* Set the height of this texture
* Set the height of this texture
*
* @param texHeight The height of the texture
*/
@ -159,7 +157,7 @@ public class Texture {
}
/**
* Set the width of this texture
* Set the width of this texture
*
* @param texWidth The width of the texture
*/

View file

@ -1,31 +1,31 @@
/*
/*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@ -53,14 +53,15 @@ import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import static org.lwjgl.opengl.GL11.*;
/**
* A utility class to load textures for OpenGL. This source is based
* on a texture that can be found in the Java Gaming (www.javagaming.org)
* Wiki. It has been simplified slightly for explicit 2D graphics use.
*
* OpenGL uses a particular image format. Since the images that are
*
* OpenGL uses a particular image format. Since the images that are
* loaded from disk may not match this format this loader introduces
* a intermediate image which the source image is copied into. In turn,
* this image is used as source for the OpenGL texture.
@ -70,21 +71,19 @@ import org.lwjgl.opengl.GL11;
*/
public class TextureLoader {
/** The table of textures that have been loaded in this loader */
private HashMap table = new HashMap();
private HashMap<String, Texture> table = new HashMap<String, Texture>();
/** The colour model including alpha for the GL image */
private ColorModel glAlphaColorModel;
/** The colour model for the GL image */
private ColorModel glColorModel;
/** Scratch buffer for texture ID's */
private IntBuffer textureIDBuffer = BufferUtils.createIntBuffer(1);
/**
private IntBuffer textureIDBuffer = BufferUtils.createIntBuffer(1);
/**
* Create a new texture loader based on the game panel
*
* @param gl The GL content in which the textures should be loaded
*/
public TextureLoader() {
glAlphaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
@ -93,7 +92,7 @@ public class TextureLoader {
false,
ComponentColorModel.TRANSLUCENT,
DataBuffer.TYPE_BYTE);
glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
new int[] {8,8,8,0},
false,
@ -101,17 +100,17 @@ public class TextureLoader {
ComponentColorModel.OPAQUE,
DataBuffer.TYPE_BYTE);
}
/**
* Create a new texture ID
* Create a new texture ID
*
* @return A new texture ID
*/
private int createTextureID() {
GL11.glGenTextures(textureIDBuffer);
glGenTextures(textureIDBuffer);
return textureIDBuffer.get(0);
}
}
/**
* Load a texture
*
@ -120,23 +119,23 @@ public class TextureLoader {
* @throws IOException Indicates a failure to access the resource
*/
public Texture getTexture(String resourceName) throws IOException {
Texture tex = (Texture) table.get(resourceName);
Texture tex = table.get(resourceName);
if (tex != null) {
return tex;
}
tex = getTexture(resourceName,
GL11.GL_TEXTURE_2D, // target
GL11.GL_RGBA, // dst pixel format
GL11.GL_LINEAR, // min filter (unused)
GL11.GL_LINEAR);
GL_TEXTURE_2D, // target
GL_RGBA, // dst pixel format
GL_LINEAR, // min filter (unused)
GL_LINEAR);
table.put(resourceName,tex);
return tex;
}
/**
* Load a texture into OpenGL from a image reference on
* disk.
@ -149,66 +148,66 @@ public class TextureLoader {
* @return The loaded texture
* @throws IOException Indicates a failure to access the resource
*/
public Texture getTexture(String resourceName,
int target,
int dstPixelFormat,
int minFilter,
int magFilter) throws IOException {
int srcPixelFormat = 0;
// create the texture ID for this texture
int textureID = createTextureID();
Texture texture = new Texture(target,textureID);
// bind this texture
GL11.glBindTexture(target, textureID);
BufferedImage bufferedImage = loadImage(resourceName);
public Texture getTexture(String resourceName,
int target,
int dstPixelFormat,
int minFilter,
int magFilter) throws IOException {
int srcPixelFormat;
// create the texture ID for this texture
int textureID = createTextureID();
Texture texture = new Texture(target,textureID);
// bind this texture
glBindTexture(target, textureID);
BufferedImage bufferedImage = loadImage(resourceName);
texture.setWidth(bufferedImage.getWidth());
texture.setHeight(bufferedImage.getHeight());
if (bufferedImage.getColorModel().hasAlpha()) {
srcPixelFormat = GL11.GL_RGBA;
srcPixelFormat = GL_RGBA;
} else {
srcPixelFormat = GL11.GL_RGB;
srcPixelFormat = GL_RGB;
}
// convert that image into a byte buffer of texture data
ByteBuffer textureBuffer = convertImageData(bufferedImage,texture);
if (target == GL_TEXTURE_2D) {
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter);
}
// convert that image into a byte buffer of texture data
ByteBuffer textureBuffer = convertImageData(bufferedImage,texture);
if (target == GL11.GL_TEXTURE_2D) {
GL11.glTexParameteri(target, GL11.GL_TEXTURE_MIN_FILTER, minFilter);
GL11.glTexParameteri(target, GL11.GL_TEXTURE_MAG_FILTER, magFilter);
}
// produce a texture from the byte buffer
GL11.glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(bufferedImage.getWidth()),
get2Fold(bufferedImage.getHeight()),
0,
srcPixelFormat,
GL11.GL_UNSIGNED_BYTE,
textureBuffer );
return texture;
}
glTexImage2D(target,
0,
dstPixelFormat,
get2Fold(bufferedImage.getWidth()),
get2Fold(bufferedImage.getHeight()),
0,
srcPixelFormat,
GL_UNSIGNED_BYTE,
textureBuffer );
return texture;
}
/**
* Get the closest greater power of 2 to the fold number
*
*
* @param fold The target number
* @return The power of 2
*/
private int get2Fold(int fold) {
private static int get2Fold(int fold) {
int ret = 2;
while (ret < fold) {
ret *= 2;
}
return ret;
}
}
/**
* Convert the buffered image to a texture
*
@ -216,14 +215,14 @@ public class TextureLoader {
* @param texture The texture to store the data into
* @return A buffer containing the data
*/
private ByteBuffer convertImageData(BufferedImage bufferedImage,Texture texture) {
ByteBuffer imageBuffer = null;
private ByteBuffer convertImageData(BufferedImage bufferedImage,Texture texture) {
ByteBuffer imageBuffer;
WritableRaster raster;
BufferedImage texImage;
int texWidth = 2;
int texHeight = 2;
// find the closest power of 2 for the width and height
// of the produced texture
while (texWidth < bufferedImage.getWidth()) {
@ -232,10 +231,10 @@ public class TextureLoader {
while (texHeight < bufferedImage.getHeight()) {
texHeight *= 2;
}
texture.setTextureHeight(texHeight);
texture.setTextureWidth(texWidth);
// create a raster that can be used by OpenGL as a source
// for a texture
if (bufferedImage.getColorModel().hasAlpha()) {
@ -245,41 +244,41 @@ public class TextureLoader {
raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,3,null);
texImage = new BufferedImage(glColorModel,raster,false,new Hashtable());
}
// copy the source image into the produced image
Graphics g = texImage.getGraphics();
g.setColor(new Color(0f,0f,0f,0f));
g.fillRect(0,0,texWidth,texHeight);
g.drawImage(bufferedImage,0,0,null);
// build a byte buffer from the temporary image
// that be used by OpenGL to produce a texture.
byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()).getData();
imageBuffer = ByteBuffer.allocateDirect(data.length);
imageBuffer.order(ByteOrder.nativeOrder());
imageBuffer.put(data, 0, data.length);
// build a byte buffer from the temporary image
// that be used by OpenGL to produce a texture.
byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()).getData();
imageBuffer = ByteBuffer.allocateDirect(data.length);
imageBuffer.order(ByteOrder.nativeOrder());
imageBuffer.put(data, 0, data.length);
imageBuffer.flip();
return imageBuffer;
}
/**
return imageBuffer;
}
/**
* Load a given resource as a buffered image
*
*
* @param ref The location of the resource to load
* @return The loaded buffered image
* @throws IOException Indicates a failure to find a resource
*/
private BufferedImage loadImage(String ref) throws IOException {
private BufferedImage loadImage(String ref) throws IOException {
URL url = TextureLoader.class.getClassLoader().getResource(ref);
if (url == null) {
throw new IOException("Cannot find: " + ref);
}
BufferedImage bufferedImage = ImageIO.read(new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(ref)));
BufferedImage bufferedImage = ImageIO.read(new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(ref)));
return bufferedImage;
}
}
}