From 41cd6c47b23975098cd155517790e018670785e7 Mon Sep 17 00:00:00 2001 From: Kenneth Russel Date: Mon, 15 Jun 2009 23:12:27 +0000 Subject: Copied JOGL_2_SANDBOX r350 on to trunk; JOGL_2_SANDBOX branch is now closed git-svn-id: file:///usr/local/projects/SUN/JOGL/git-svn/../svn-server-sync/jogl-demos/trunk@352 3298f667-5e0e-4b4a-8ed4-a3559d26a5f4 --- src/demos/util/Bunny.java | 141 +++++++ src/demos/util/Cubemap.java | 83 ++++ src/demos/util/DurationTimer.java | 68 ++++ src/demos/util/DxTex.java | 376 ++++++++++++++++++ src/demos/util/FPSCounter.java | 228 +++++++++++ src/demos/util/FileUtils.java | 68 ++++ src/demos/util/FloatList.java | 100 +++++ src/demos/util/IntList.java | 100 +++++ src/demos/util/MD2.java | 702 ++++++++++++++++++++++++++++++++++ src/demos/util/ObjReader.java | 368 ++++++++++++++++++ src/demos/util/ScreenResSelector.java | 241 ++++++++++++ src/demos/util/SystemTime.java | 110 ++++++ src/demos/util/Time.java | 52 +++ src/demos/util/Triceratops.java | 144 +++++++ 14 files changed, 2781 insertions(+) create mode 100644 src/demos/util/Bunny.java create mode 100755 src/demos/util/Cubemap.java create mode 100644 src/demos/util/DurationTimer.java create mode 100644 src/demos/util/DxTex.java create mode 100755 src/demos/util/FPSCounter.java create mode 100755 src/demos/util/FileUtils.java create mode 100644 src/demos/util/FloatList.java create mode 100644 src/demos/util/IntList.java create mode 100644 src/demos/util/MD2.java create mode 100644 src/demos/util/ObjReader.java create mode 100755 src/demos/util/ScreenResSelector.java create mode 100644 src/demos/util/SystemTime.java create mode 100644 src/demos/util/Time.java create mode 100644 src/demos/util/Triceratops.java (limited to 'src/demos/util') diff --git a/src/demos/util/Bunny.java b/src/demos/util/Bunny.java new file mode 100644 index 0000000..c4afd0c --- /dev/null +++ b/src/demos/util/Bunny.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +import java.io.*; + +import javax.media.opengl.*; + +/** Renders a bunny. + +

This file was produced by 3D Exploration Plugin: CPP Export filter. + +

3D Exploration + +

Copyright (c) 1999-2000 X Dimension Software + +

WWW http://www.xdsoft.com/explorer/
+ eMail info@xdsoft.com +*/ +public class Bunny { + + /** Generates and returns a display list for the bunny model. */ + public static int gen3DObjectList(GL2 gl) throws IOException { + StreamTokenizer tok = new StreamTokenizer(new BufferedReader(new InputStreamReader( + Bunny.class.getClassLoader().getResourceAsStream("demos/data/models/bunny.txt")))); + // Reset tokenizer's syntax so numbers are not parsed + tok.resetSyntax(); + tok.wordChars('a', 'z'); + tok.wordChars('A', 'Z'); + tok.wordChars('0', '9'); + tok.wordChars('-', '-'); + tok.wordChars('.', '.'); + tok.wordChars(128 + 32, 255); + tok.whitespaceChars(0, ' '); + tok.whitespaceChars(',', ','); + tok.whitespaceChars('{', '{'); + tok.whitespaceChars('}', '}'); + tok.commentChar('/'); + tok.quoteChar('"'); + tok.quoteChar('\''); + tok.slashSlashComments(true); + tok.slashStarComments(true); + + // Read in file + int numFaceIndices = nextInt(tok, "number of face indices"); + short[] faceIndices = new short[numFaceIndices * 6]; + for (int i = 0; i < numFaceIndices * 6; i++) { + faceIndices[i] = (short) nextInt(tok, "face index"); + } + int numVertices = nextInt(tok, "number of vertices"); + float[] vertices = new float[numVertices * 3]; + for (int i = 0; i < numVertices * 3; i++) { + vertices[i] = nextFloat(tok, "vertex"); + } + int numNormals = nextInt(tok, "number of normals"); + float[] normals = new float[numNormals * 3]; + for (int i = 0; i < numNormals * 3; i++) { + normals[i] = nextFloat(tok, "normal"); + } + + int lid = gl.glGenLists(1); + gl.glNewList(lid, GL2.GL_COMPILE); + + gl.glBegin(GL.GL_TRIANGLES); + for (int i = 0; i < faceIndices.length; i += 6) { + for (int j = 0; j < 3; j++) { + int vi = faceIndices[i + j]; + int ni = faceIndices[i + j + 3]; + gl.glNormal3f(normals[3 * ni], + normals[3 * ni + 1], + normals[3 * ni + 2]); + gl.glVertex3f(vertices[3 * vi], + vertices[3 * vi + 1], + vertices[3 * vi + 2]); + } + } + gl.glEnd(); + + gl.glEndList(); + return lid; + } + + private static int nextInt(StreamTokenizer tok, String error) throws IOException { + if (tok.nextToken() != StreamTokenizer.TT_WORD) { + throw new IOException("Parse error reading " + error + " at line " + tok.lineno()); + } + try { + return Integer.parseInt(tok.sval); + } catch (NumberFormatException e) { + throw new IOException("Parse error reading " + error + " at line " + tok.lineno()); + } + } + + private static float nextFloat(StreamTokenizer tok, String error) throws IOException { + if (tok.nextToken() != StreamTokenizer.TT_WORD) { + throw new IOException("Parse error reading " + error + " at line " + tok.lineno()); + } + try { + return Float.parseFloat(tok.sval); + } catch (NumberFormatException e) { + throw new IOException("Parse error reading " + error + " at line " + tok.lineno()); + } + } +} diff --git a/src/demos/util/Cubemap.java b/src/demos/util/Cubemap.java new file mode 100755 index 0000000..405fc38 --- /dev/null +++ b/src/demos/util/Cubemap.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +import com.sun.opengl.util.FileUtil; +import com.sun.opengl.util.texture.Texture; +import com.sun.opengl.util.texture.TextureData; +import com.sun.opengl.util.texture.TextureIO; +import java.io.IOException; +import javax.media.opengl.GL; +import javax.media.opengl.GLException; + + + +/** Helper class for loading cubemaps from a set of textures. */ + +public class Cubemap { + + private static final String[] suffixes = { "posx", "negx", "posy", "negy", "posz", "negz" }; + private static final int[] targets = { GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X, + GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, + GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, + GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, + GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, + GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }; + + public static Texture loadFromStreams(ClassLoader scope, + String basename, + String suffix, + boolean mipmapped) throws IOException, GLException { + Texture cubemap = TextureIO.newTexture(GL.GL_TEXTURE_CUBE_MAP); + + for (int i = 0; i < suffixes.length; i++) { + String resourceName = basename + suffixes[i] + "." + suffix; + TextureData data = TextureIO.newTextureData(scope.getResourceAsStream(resourceName), + mipmapped, + FileUtil.getFileSuffix(resourceName)); + if (data == null) { + throw new IOException("Unable to load texture " + resourceName); + } + cubemap.updateImage(data, targets[i]); + } + + return cubemap; + } +} diff --git a/src/demos/util/DurationTimer.java b/src/demos/util/DurationTimer.java new file mode 100644 index 0000000..c0f88e7 --- /dev/null +++ b/src/demos/util/DurationTimer.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +/** Simple class for helping measure frames-per-second. */ + +public class DurationTimer { + private long startTime; + private long accumulatedTime; + + public void reset() { + accumulatedTime = 0; + } + + public void start() { + startTime = System.currentTimeMillis(); + } + + public void stop() { + long curTime = System.currentTimeMillis(); + accumulatedTime += (curTime - startTime); + } + + public long getDuration() { + return accumulatedTime; + } + + public float getDurationAsSeconds() { + return (float) accumulatedTime / 1000.0f; + } +} diff --git a/src/demos/util/DxTex.java b/src/demos/util/DxTex.java new file mode 100644 index 0000000..fbe1963 --- /dev/null +++ b/src/demos/util/DxTex.java @@ -0,0 +1,376 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +import java.io.*; +import java.nio.*; +import java.awt.image.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.filechooser.*; + +import com.sun.opengl.util.texture.spi.*; + +/** Simplified clone of DxTex tool from the DirectX SDK, written in + Java using the DDSImage; tests fetching of texture data */ + +public class DxTex { + private InternalFrameListener frameListener; + private File defaultDirectory; + private JDesktopPane desktop; + private static String endl = System.getProperty("line.separator"); + private JMenu mipMapMenu; + + public static void main(String[] args) { + new DxTex().run(args); + } + + private void run(String[] args) { + defaultDirectory = new File(System.getProperty("user.dir")); + JFrame frame = new JFrame("DirectX Texture Tool"); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + JMenuBar menuBar = new JMenuBar(); + JMenu menu = createMenu("File", 'F', 0); + JMenuItem item = + createMenuItem("Open...", + new ActionListener() { + public void actionPerformed(ActionEvent e) { + openFile(); + } + }, + KeyEvent.VK_O, InputEvent.CTRL_MASK, + 'O', 0); + menu.add(item); + item = + createMenuItem("Exit", + new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }, + KeyEvent.VK_Q, InputEvent.CTRL_MASK, + 'x', 1); + menu.add(item); + menuBar.add(menu); + + menu = createMenu("MipMap", 'M', 0); + menu.setEnabled(false); + mipMapMenu = menu; + menuBar.add(menu); + + frame.setJMenuBar(menuBar); + + desktop = new JDesktopPane(); + frame.getContentPane().add(desktop); + frame.setSize(640, 480); + frame.setVisible(true); + + frameListener = new InternalFrameAdapter() { + public void internalFrameActivated(InternalFrameEvent e) { + JInternalFrame ifr = e.getInternalFrame(); + if (ifr instanceof ImageFrame) { + // Recompute entries in mip map menu + final ImageFrame frame = (ImageFrame) ifr; + if (frame.getNumMipMaps() > 0) { + mipMapMenu.removeAll(); + // Add entries + for (int i = 0; i < frame.getNumMipMaps(); i++) { + final int map = i; + JMenuItem item; + String title = "Level " + (i + 1); + ActionListener listener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + frame.setMipMapLevel(map); + } + }); + } + }; + if (i < 9) { + char c = (char) ('0' + i + 1); + item = createMenuItem(title, listener, c, 6); + } else { + item = createMenuItem(title, listener); + } + mipMapMenu.add(item); + } + mipMapMenu.setEnabled(true); + } else { + mipMapMenu.setEnabled(false); + } + } else { + mipMapMenu.setEnabled(false); + } + } + + public void internalFrameClosing(InternalFrameEvent e) { + desktop.remove(e.getInternalFrame()); + desktop.invalidate(); + desktop.validate(); + desktop.repaint(); + // THIS SHOULD NOT BE NECESSARY + desktop.requestFocus(); + } + + public void internalFrameClosed(InternalFrameEvent e) { + JInternalFrame ifr = e.getInternalFrame(); + if (ifr instanceof ImageFrame) { + ((ImageFrame) ifr).close(); + } + } + }; + + for (int i = 0; i < args.length; i++) { + final File file = new File(args[i]); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + openFile(file); + } + }); + } + } + + //---------------------------------------------------------------------- + // Actions + // + + private void openFile() { + JFileChooser chooser = new JFileChooser(defaultDirectory); + chooser.setMultiSelectionEnabled(false); + chooser.addChoosableFileFilter(new javax.swing.filechooser.FileFilter() { + public boolean accept(File f) { + return (f.isDirectory() || + f.getName().endsWith(".dds")); + } + + public String getDescription() { + return "Texture files (*.dds)"; + } + }); + + int res = chooser.showOpenDialog(null); + if (res == JFileChooser.APPROVE_OPTION) { + final File file = chooser.getSelectedFile(); + defaultDirectory = file.getParentFile(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + openFile(file); + } + }); + } + } + + private void openFile(File file) { + try { + DDSImage image = DDSImage.read(file); + showImage(file.getName(), image, 0); + } catch (IOException e) { + showMessageDialog("Error while opening file:" + endl + + exceptionToString(e), + "Error opening file", + JOptionPane.WARNING_MESSAGE); + } + } + + //---------------------------------------------------------------------- + // Image display + // + + private void showImage(String filename, DDSImage image, int mipMapLevel) { + try { + ImageFrame fr = new ImageFrame(filename, image, mipMapLevel); + desktop.add(fr); + fr.setVisible(true); + } catch (Exception e) { + showMessageDialog("Error while loading file:" + endl + + exceptionToString(e), + "Error loading file", + JOptionPane.WARNING_MESSAGE); + } + } + + class ImageFrame extends JInternalFrame { + private String filename; + private DDSImage image; + private int mipMapLevel; + private int curWidth; + private int curHeight; + private JLabel label; + + ImageFrame(String filename, DDSImage image, int mipMapLevel) { + super(); + this.filename = filename; + this.image = image; + + addInternalFrameListener(frameListener); + label = new JLabel(); + JScrollPane scroller = new JScrollPane(label); + getContentPane().add(scroller); + setSize(400, 400); + setResizable(true); + setIconifiable(true); + setClosable(true); + setMipMapLevel(mipMapLevel); + } + + int getNumMipMaps() { + return image.getNumMipMaps(); + } + + void setMipMapLevel(int level) { + mipMapLevel = level; + computeImage(); + resetTitle(); + } + + void close() { + System.err.println("Closing files"); + image.close(); + } + + private void computeImage() { + // Get image data + image.getNumMipMaps(); + DDSImage.ImageInfo info = image.getMipMap(mipMapLevel); + int width = info.getWidth(); + int height = info.getHeight(); + curWidth = width; + curHeight = height; + ByteBuffer data = info.getData(); + + // Build ImageIcon out of image data + BufferedImage img = new BufferedImage(width, height, + BufferedImage.TYPE_3BYTE_BGR); + WritableRaster dst = img.getRaster(); + + int skipSize; + if (image.getPixelFormat() == DDSImage.D3DFMT_A8R8G8B8) { + skipSize = 4; + } else if (image.getPixelFormat() == DDSImage.D3DFMT_R8G8B8) { + skipSize = 3; + } else { + image.close(); + throw new RuntimeException("Unsupported pixel format " + image.getPixelFormat()); + } + + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + // NOTE: highly suspicious that A comes fourth in + // A8R8G8B8...not really ARGB, but RGBA (like OpenGL) + dst.setSample(x, y, 0, data.get(skipSize * (width * y + x) + 2) & 0xFF); + dst.setSample(x, y, 1, data.get(skipSize * (width * y + x) + 1) & 0xFF); + dst.setSample(x, y, 2, data.get(skipSize * (width * y + x) + 0) & 0xFF); + } + } + + label.setIcon(new ImageIcon(img)); + } + + private void resetTitle() { + setTitle(filename + " (" + curWidth + "x" + curHeight + + ", mipmap " + (1 + mipMapLevel) + " of " + + image.getNumMipMaps() + ")"); + } + } + + + //---------------------------------------------------------------------- + // Menu and menu item creation + // + + private static JMenu createMenu(String name, char mnemonic, int mnemonicPos) { + JMenu menu = new JMenu(name); + menu.setMnemonic(mnemonic); + menu.setDisplayedMnemonicIndex(mnemonicPos); + return menu; + } + + private static JMenuItem createMenuItem(String name, ActionListener l) { + JMenuItem item = new JMenuItem(name); + item.addActionListener(l); + return item; + } + + private static JMenuItem createMenuItemInternal(String name, ActionListener l, int accelerator, int modifiers) { + JMenuItem item = createMenuItem(name, l); + item.setAccelerator(KeyStroke.getKeyStroke(accelerator, modifiers)); + return item; + } + + private static JMenuItem createMenuItem(String name, ActionListener l, int accelerator) { + return createMenuItemInternal(name, l, accelerator, 0); + } + + private static JMenuItem createMenuItem(String name, ActionListener l, char mnemonic, int mnemonicPos) { + JMenuItem item = createMenuItem(name, l); + item.setMnemonic(mnemonic); + item.setDisplayedMnemonicIndex(mnemonicPos); + return item; + } + + private static JMenuItem createMenuItem(String name, + ActionListener l, + int accelerator, + int acceleratorMods, + char mnemonic, + int mnemonicPos) { + JMenuItem item = createMenuItemInternal(name, l, accelerator, acceleratorMods); + item.setMnemonic(mnemonic); + item.setDisplayedMnemonicIndex(mnemonicPos); + return item; + } + + private void showMessageDialog(final String message, final String title, final int jOptionPaneKind) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + JOptionPane.showInternalMessageDialog(desktop, message, title, jOptionPaneKind); + } + }); + } + + private static String exceptionToString(Exception e) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + PrintStream s = new PrintStream(bos); + e.printStackTrace(s); + return bos.toString(); + } +} diff --git a/src/demos/util/FPSCounter.java b/src/demos/util/FPSCounter.java new file mode 100755 index 0000000..79ea38b --- /dev/null +++ b/src/demos/util/FPSCounter.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +import com.sun.opengl.util.awt.TextRenderer; +import com.sun.opengl.util.texture.Texture; +import java.awt.Font; +import java.awt.geom.Rectangle2D; +import java.text.DecimalFormat; +import javax.media.opengl.GLDrawable; +import javax.media.opengl.GLException; + + + +/** A simple class which uses the TextRenderer to provide an FPS + counter overlaid on top of the scene. */ + +public class FPSCounter { + // Placement constants + public static final int UPPER_LEFT = 1; + public static final int UPPER_RIGHT = 2; + public static final int LOWER_LEFT = 3; + public static final int LOWER_RIGHT = 4; + + private int textLocation = LOWER_RIGHT; + private GLDrawable drawable; + private TextRenderer renderer; + private DecimalFormat format = new DecimalFormat("####.00"); + private int frameCount; + private long startTime; + private String fpsText; + private int fpsMagnitude; + private int fpsWidth; + private int fpsHeight; + private int fpsOffset; + + /** Creates a new FPSCounter with the given font size. An OpenGL + context must be current at the time the constructor is called. + + @param drawable the drawable to render the text to + @param textSize the point size of the font to use + @throws GLException if an OpenGL context is not current when the constructor is called + */ + public FPSCounter(GLDrawable drawable, int textSize) throws GLException { + this(drawable, new Font("SansSerif", Font.BOLD, textSize)); + } + + /** Creates a new FPSCounter with the given font. An OpenGL context + must be current at the time the constructor is called. + + @param drawable the drawable to render the text to + @param font the font to use + @throws GLException if an OpenGL context is not current when the constructor is called + */ + public FPSCounter(GLDrawable drawable, Font font) throws GLException { + this(drawable, font, true, true); + } + + /** Creates a new FPSCounter with the given font and rendering + attributes. An OpenGL context must be current at the time the + constructor is called. + + @param drawable the drawable to render the text to + @param font the font to use + @param antialiased whether to use antialiased fonts + @param useFractionalMetrics whether to use fractional font + @throws GLException if an OpenGL context is not current when the constructor is called + */ + public FPSCounter(GLDrawable drawable, + Font font, + boolean antialiased, + boolean useFractionalMetrics) throws GLException { + this.drawable = drawable; + renderer = new TextRenderer(font, antialiased, useFractionalMetrics); + } + + /** Gets the relative location where the text of this FPSCounter + will be drawn: one of UPPER_LEFT, UPPER_RIGHT, LOWER_LEFT, or + LOWER_RIGHT. Defaults to LOWER_RIGHT. */ + public int getTextLocation() { + return textLocation; + } + + /** Sets the relative location where the text of this FPSCounter + will be drawn: one of UPPER_LEFT, UPPER_RIGHT, LOWER_LEFT, or + LOWER_RIGHT. Defaults to LOWER_RIGHT. */ + public void setTextLocation(int textLocation) { + if (textLocation < UPPER_LEFT || textLocation > LOWER_RIGHT) { + throw new IllegalArgumentException("textLocation"); + } + this.textLocation = textLocation; + } + + /** Changes the current color of this TextRenderer to the supplied + one, where each component ranges from 0.0f - 1.0f. The alpha + component, if used, does not need to be premultiplied into the + color channels as described in the documentation for {@link + Texture Texture}, although premultiplied colors are used + internally. The default color is opaque white. + + @param r the red component of the new color + @param g the green component of the new color + @param b the blue component of the new color + @param alpha the alpha component of the new color, 0.0f = + completely transparent, 1.0f = completely opaque + @throws GLException If an OpenGL context is not current when this method is called + */ + public void setColor(float r, float g, float b, float a) throws GLException { + renderer.setColor(r, g, b, a); + } + + /** Updates the FPSCounter's internal timer and counter and draws + the computed FPS. It is assumed this method will be called only + once per frame. + */ + public void draw() { + if (startTime == 0) { + startTime = System.currentTimeMillis(); + } + + if (++frameCount >= 100) { + long endTime = System.currentTimeMillis(); + float fps = 100.0f / (float) (endTime - startTime) * 1000; + recomputeFPSSize(fps); + frameCount = 0; + startTime = System.currentTimeMillis(); + + fpsText = "FPS: " + format.format(fps); + } + + if (fpsText != null) { + renderer.beginRendering(drawable.getWidth(), drawable.getHeight()); + // Figure out the location at which to draw the text + int x = 0; + int y = 0; + switch (textLocation) { + case UPPER_LEFT: + x = fpsOffset; + y = drawable.getHeight() - fpsHeight - fpsOffset; + break; + + case UPPER_RIGHT: + x = drawable.getWidth() - fpsWidth - fpsOffset; + y = drawable.getHeight() - fpsHeight - fpsOffset; + break; + + case LOWER_LEFT: + x = fpsOffset; + y = fpsOffset; + break; + + case LOWER_RIGHT: + x = drawable.getWidth() - fpsWidth - fpsOffset; + y = fpsOffset; + break; + } + + renderer.draw(fpsText, x, y); + renderer.endRendering(); + } + } + + private void recomputeFPSSize(float fps) { + String fpsText; + int fpsMagnitude; + if (fps >= 10000) { + fpsText = "10000.00"; + fpsMagnitude = 5; + } else if (fps >= 1000) { + fpsText = "1000.00"; + fpsMagnitude = 4; + } else if (fps >= 100) { + fpsText = "100.00"; + fpsMagnitude = 3; + } else if (fps >= 10) { + fpsText = "10.00"; + fpsMagnitude = 2; + } else { + fpsText = "9.00"; + fpsMagnitude = 1; + } + + if (fpsMagnitude > this.fpsMagnitude) { + Rectangle2D bounds = renderer.getBounds("FPS: " + fpsText); + fpsWidth = (int) bounds.getWidth(); + fpsHeight = (int) bounds.getHeight(); + fpsOffset = (int) (fpsHeight * 0.5f); + this.fpsMagnitude = fpsMagnitude; + } + } +} diff --git a/src/demos/util/FileUtils.java b/src/demos/util/FileUtils.java new file mode 100755 index 0000000..442485d --- /dev/null +++ b/src/demos/util/FileUtils.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +import java.io.*; + +public class FileUtils { + public static String loadStreamIntoString(InputStream stream) throws IOException { + if (stream == null) { + throw new java.io.IOException("null stream"); + } + stream = new java.io.BufferedInputStream(stream); + int avail = stream.available(); + byte[] data = new byte[avail]; + int numRead = 0; + int pos = 0; + do { + if (pos + avail > data.length) { + byte[] newData = new byte[pos + avail]; + System.arraycopy(data, 0, newData, 0, pos); + data = newData; + } + numRead = stream.read(data, pos, avail); + if (numRead >= 0) { + pos += numRead; + } + avail = stream.available(); + } while (avail > 0 && numRead >= 0); + return new String(data, 0, pos, "US-ASCII"); + } +} diff --git a/src/demos/util/FloatList.java b/src/demos/util/FloatList.java new file mode 100644 index 0000000..fe06e2e --- /dev/null +++ b/src/demos/util/FloatList.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +/** Growable array of floats. */ + +public class FloatList { + private static final int DEFAULT_SIZE = 10; + + private float[] data = new float[DEFAULT_SIZE]; + private int numElements; + + public void add(float f) { + if (numElements == data.length) { + resize(1 + numElements); + } + data[numElements++] = f; + assert numElements <= data.length; + } + + public int size() { + return numElements; + } + + public float get(int index) { + if (index >= numElements) { + throw new ArrayIndexOutOfBoundsException(index); + } + return data[index]; + } + + public void put(int index, float val) { + if (index >= numElements) { + throw new ArrayIndexOutOfBoundsException(index); + } + data[index] = val; + } + + public void trim() { + if (data.length > numElements) { + float[] newData = new float[numElements]; + System.arraycopy(data, 0, newData, 0, numElements); + data = newData; + } + } + + public float[] getData() { + return data; + } + + private void resize(int minCapacity) { + int newCapacity = 2 * data.length; + if (newCapacity == 0) { + newCapacity = DEFAULT_SIZE; + } + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + float[] newData = new float[newCapacity]; + System.arraycopy(data, 0, newData, 0, data.length); + data = newData; + } +} diff --git a/src/demos/util/IntList.java b/src/demos/util/IntList.java new file mode 100644 index 0000000..54a4745 --- /dev/null +++ b/src/demos/util/IntList.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +/** Growable array of ints. */ + +public class IntList { + private static final int DEFAULT_SIZE = 10; + + private int[] data = new int[DEFAULT_SIZE]; + private int numElements; + + public void add(int f) { + if (numElements == data.length) { + resize(1 + numElements); + } + data[numElements++] = f; + assert numElements <= data.length; + } + + public int size() { + return numElements; + } + + public int get(int index) { + if (index >= numElements) { + throw new ArrayIndexOutOfBoundsException(index); + } + return data[index]; + } + + public void put(int index, int val) { + if (index >= numElements) { + throw new ArrayIndexOutOfBoundsException(index); + } + data[index] = val; + } + + public void trim() { + if (data.length > numElements) { + int[] newData = new int[numElements]; + System.arraycopy(data, 0, newData, 0, numElements); + data = newData; + } + } + + public int[] getData() { + return data; + } + + private void resize(int minCapacity) { + int newCapacity = 2 * data.length; + if (newCapacity == 0) { + newCapacity = DEFAULT_SIZE; + } + if (newCapacity < minCapacity) { + newCapacity = minCapacity; + } + int[] newData = new int[newCapacity]; + System.arraycopy(data, 0, newData, 0, data.length); + data = newData; + } +} diff --git a/src/demos/util/MD2.java b/src/demos/util/MD2.java new file mode 100644 index 0000000..8e43c79 --- /dev/null +++ b/src/demos/util/MD2.java @@ -0,0 +1,702 @@ +/* + * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * - Redistribution of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution 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 Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN + * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR + * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR + * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF + * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that this software is not designed or intended for use + * in the design, construction, operation or maintenance of any nuclear + * facility. + * + * Sun gratefully acknowledges that this software was originally authored + * and developed by Kenneth Bradley Russell and Christopher John Kline. + */ + +package demos.util; + +import java.io.*; +import java.nio.*; +import java.nio.channels.*; +import java.util.*; + +/** Reader for MD2 models, used by Quake II. */ + +public class MD2 { + public static Model loadMD2(String filename) throws IOException { + List/*